libc: Sync asctime.c and localtime.c with tzcode2010a from elsie.
[dragonfly.git] / lib / libc / stdtime / localtime.c
blob8ce97495410850c5201a0b175de8e189f98216a4
1 /*
2 ** This file is in the public domain, so clarified as of
3 ** 1996-06-05 by Arthur David Olson.
4 **
5 ** @(#)localtime.c 8.10
6 ** $FreeBSD: src/lib/libc/stdtime/localtime.c,v 1.25.2.2 2002/08/13 16:08:07 bmilekic Exp $
7 */
9 /*
10 ** Leap second handling from Bradley White.
11 ** POSIX-style TZ environment variable handling from Guy Harris.
14 /*LINTLIBRARY*/
16 #include "namespace.h"
17 #include <sys/types.h>
18 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <float.h> /* for FLT_MAX and DBL_MAX */
22 #include <time.h>
23 #include <pthread.h>
24 #include "private.h"
25 #include <un-namespace.h>
27 #include "tzfile.h"
29 #include "libc_private.h"
31 #define _MUTEX_LOCK(x) if (__isthreaded) _pthread_mutex_lock(x)
32 #define _MUTEX_UNLOCK(x) if (__isthreaded) _pthread_mutex_unlock(x)
34 #define _RWLOCK_RDLOCK(x) \
35 do { \
36 if (__isthreaded) _pthread_rwlock_rdlock(x); \
37 } while (0)
39 #define _RWLOCK_WRLOCK(x) \
40 do { \
41 if (__isthreaded) _pthread_rwlock_wrlock(x); \
42 } while (0)
44 #define _RWLOCK_UNLOCK(x) \
45 do { \
46 if (__isthreaded) _pthread_rwlock_unlock(x); \
47 } while (0)
49 #ifndef TZ_ABBR_MAX_LEN
50 #define TZ_ABBR_MAX_LEN 16
51 #endif /* !defined TZ_ABBR_MAX_LEN */
53 #ifndef TZ_ABBR_CHAR_SET
54 #define TZ_ABBR_CHAR_SET \
55 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
56 #endif /* !defined TZ_ABBR_CHAR_SET */
58 #ifndef TZ_ABBR_ERR_CHAR
59 #define TZ_ABBR_ERR_CHAR '_'
60 #endif /* !defined TZ_ABBR_ERR_CHAR */
63 ** Someone might make incorrect use of a time zone abbreviation:
64 ** 1. They might reference tzname[0] before calling tzset (explicitly
65 ** or implicitly).
66 ** 2. They might reference tzname[1] before calling tzset (explicitly
67 ** or implicitly).
68 ** 3. They might reference tzname[1] after setting to a time zone
69 ** in which Daylight Saving Time is never observed.
70 ** 4. They might reference tzname[0] after setting to a time zone
71 ** in which Standard Time is never observed.
72 ** 5. They might reference tm.TM_ZONE after calling offtime.
73 ** What's best to do in the above cases is open to debate;
74 ** for now, we just set things up so that in any of the five cases
75 ** WILDABBR is used. Another possibility: initialize tzname[0] to the
76 ** string "tzname[0] used before set", and similarly for the other cases.
77 ** And another: initialize tzname[0] to "ERA", with an explanation in the
78 ** manual page of what this "time zone abbreviation" means (doing this so
79 ** that tzname[0] has the "normal" length of three characters).
81 #define WILDABBR " "
83 static char wildabbr[] = WILDABBR;
85 static const char gmt[] = "UTC";
88 ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
89 ** We default to US rules as of 1999-08-17.
90 ** POSIX 1003.1 section 8.1.1 says that the default DST rules are
91 ** implementation dependent; for historical reasons, US rules are a
92 ** common default.
94 #ifndef TZDEFRULESTRING
95 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
96 #endif /* !defined TZDEFDST */
98 struct ttinfo { /* time type information */
99 long tt_gmtoff; /* UTC offset in seconds */
100 int tt_isdst; /* used to set tm_isdst */
101 int tt_abbrind; /* abbreviation list index */
102 int tt_ttisstd; /* TRUE if transition is std time */
103 int tt_ttisgmt; /* TRUE if transition is UTC */
106 struct lsinfo { /* leap second information */
107 time_t ls_trans; /* transition time */
108 long ls_corr; /* correction to apply */
111 #define BIGGEST(a, b) (((a) > (b)) ? (a) : (b))
113 #ifdef TZNAME_MAX
114 #define MY_TZNAME_MAX TZNAME_MAX
115 #endif /* defined TZNAME_MAX */
116 #ifndef TZNAME_MAX
117 #define MY_TZNAME_MAX 255
118 #endif /* !defined TZNAME_MAX */
120 struct state {
121 int leapcnt;
122 int timecnt;
123 int typecnt;
124 int charcnt;
125 int goback;
126 int goahead;
127 time_t ats[TZ_MAX_TIMES];
128 unsigned char types[TZ_MAX_TIMES];
129 struct ttinfo ttis[TZ_MAX_TYPES];
130 char chars[BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
131 (2 * (MY_TZNAME_MAX + 1)))];
132 struct lsinfo lsis[TZ_MAX_LEAPS];
135 struct rule {
136 int r_type; /* type of rule--see below */
137 int r_day; /* day number of rule */
138 int r_week; /* week number of rule */
139 int r_mon; /* month number of rule */
140 long r_time; /* transition time of rule */
143 #define JULIAN_DAY 0 /* Jn - Julian day */
144 #define DAY_OF_YEAR 1 /* n - day of year */
145 #define MONTH_NTH_DAY_OF_WEEK 2 /* Mm.n.d - month, week, day of week */
148 ** Prototypes for static functions.
151 static long detzcode(const char * codep);
152 static time_t detzcode64(const char * codep);
153 static int differ_by_repeat(time_t t1, time_t t0);
154 static const char * getzname(const char * strp);
155 static const char * getqzname(const char * strp, const int delim);
156 static const char * getnum(const char * strp, int * nump, int min,
157 int max);
158 static const char * getsecs(const char * strp, long * secsp);
159 static const char * getoffset(const char * strp, long * offsetp);
160 static const char * getrule(const char * strp, struct rule * rulep);
161 static void gmtload(struct state * sp);
162 static struct tm * gmtsub(const time_t * timep, long offset,
163 struct tm * tmp);
164 static struct tm * localsub(const time_t * timep, long offset,
165 struct tm * tmp);
166 static int increment_overflow(int * number, int delta);
167 static int leaps_thru_end_of(int y);
168 static int long_increment_overflow(long * number, int delta);
169 static int long_normalize_overflow(long * tensptr,
170 int * unitsptr, int base);
171 static int normalize_overflow(int * tensptr, int * unitsptr,
172 int base);
173 static void settzname(void);
174 static time_t time1(struct tm * tmp,
175 struct tm * (*funcp)(const time_t *,
176 long, struct tm *),
177 long offset);
178 static time_t time2(struct tm *tmp,
179 struct tm * (*funcp)(const time_t *,
180 long, struct tm*),
181 long offset, int * okayp);
182 static time_t time2sub(struct tm *tmp,
183 struct tm * (*funcp)(const time_t *,
184 long, struct tm*),
185 long offset, int * okayp, int do_norm_secs);
186 static struct tm * timesub(const time_t * timep, long offset,
187 const struct state * sp, struct tm * tmp);
188 static int tmcomp(const struct tm * atmp,
189 const struct tm * btmp);
190 static time_t transtime(time_t janfirst, int year,
191 const struct rule * rulep, long offset);
192 static int typesequiv(const struct state * sp, int a, int b);
193 static int tzload(const char * name, struct state * sp,
194 int doextend);
195 static int tzparse(const char * name, struct state * sp,
196 int lastditch);
198 static struct state lclmem;
199 static struct state gmtmem;
200 #define lclptr (&lclmem)
201 #define gmtptr (&gmtmem)
203 #ifndef TZ_STRLEN_MAX
204 #define TZ_STRLEN_MAX 255
205 #endif /* !defined TZ_STRLEN_MAX */
207 static char lcl_TZname[TZ_STRLEN_MAX + 1];
208 static int lcl_is_set;
209 static int gmt_is_set;
210 static pthread_rwlock_t lcl_rwlock = PTHREAD_RWLOCK_INITIALIZER;
211 static pthread_mutex_t gmt_mutex = PTHREAD_MUTEX_INITIALIZER;
213 char * tzname[2] = {
214 wildabbr,
215 wildabbr
219 ** Section 4.12.3 of X3.159-1989 requires that
220 ** Except for the strftime function, these functions [asctime,
221 ** ctime, gmtime, localtime] return values in one of two static
222 ** objects: a broken-down time structure and an array of char.
223 ** Thanks to Paul Eggert for noting this.
226 static struct tm tm;
228 time_t timezone = 0;
229 int daylight = 0;
231 static long
232 detzcode(const char * const codep)
234 long result;
235 int i;
237 result = (codep[0] & 0x80) ? ~0L : 0;
238 for (i = 0; i < 4; ++i)
239 result = (result << 8) | (codep[i] & 0xff);
240 return result;
243 static time_t
244 detzcode64(const char * const codep)
246 time_t result;
247 int i;
249 result = (codep[0] & 0x80) ? (~(int_fast64_t) 0) : 0;
250 for (i = 0; i < 8; ++i)
251 result = result * 256 + (codep[i] & 0xff);
252 return result;
255 static void
256 settzname(void)
258 struct state * const sp = lclptr;
259 int i;
261 tzname[0] = wildabbr;
262 tzname[1] = wildabbr;
263 daylight = 0;
264 timezone = 0;
266 for (i = 0; i < sp->typecnt; ++i) {
267 const struct ttinfo * const ttisp = &sp->ttis[i];
269 tzname[ttisp->tt_isdst] =
270 &sp->chars[ttisp->tt_abbrind];
271 if (ttisp->tt_isdst)
272 daylight = 1;
273 if (i == 0 || !ttisp->tt_isdst)
274 timezone = -(ttisp->tt_gmtoff);
277 ** And to get the latest zone names into tzname. . .
279 for (i = 0; i < sp->timecnt; ++i) {
280 const struct ttinfo * const ttisp =
281 &sp->ttis[
282 sp->types[i]];
284 tzname[ttisp->tt_isdst] =
285 &sp->chars[ttisp->tt_abbrind];
288 ** Finally, scrub the abbreviations.
289 ** First, replace bogus characters.
291 for (i = 0; i < sp->charcnt; ++i)
292 if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
293 sp->chars[i] = TZ_ABBR_ERR_CHAR;
295 ** Second, truncate long abbreviations.
297 for (i = 0; i < sp->typecnt; ++i) {
298 const struct ttinfo * const ttisp = &sp->ttis[i];
299 char * cp = &sp->chars[ttisp->tt_abbrind];
301 if (strlen(cp) > TZ_ABBR_MAX_LEN &&
302 strcmp(cp, GRANDPARENTED) != 0)
303 *(cp + TZ_ABBR_MAX_LEN) = '\0';
307 static int
308 differ_by_repeat(const time_t t1, const time_t t0)
310 int_fast64_t _t0 = t0;
311 int_fast64_t _t1 = t1;
313 if (TYPE_INTEGRAL(time_t) &&
314 TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
315 return 0;
316 return _t1 - _t0 == SECSPERREPEAT;
319 static int
320 tzload(const char *name, struct state * const sp, const int doextend)
322 const char * p;
323 int i;
324 int fid;
325 int stored;
326 int nread;
327 union {
328 struct tzhead tzhead;
329 char buf[2 * sizeof(struct tzhead) +
330 2 * sizeof *sp +
331 4 * TZ_MAX_TIMES];
332 } u;
334 /* XXX The following is from OpenBSD, and I'm not sure it is correct */
335 if (name != NULL && issetugid() != 0)
336 if ((name[0] == ':' && name[1] == '/') ||
337 name[0] == '/' || strchr(name, '.'))
338 name = NULL;
339 if (name == NULL && (name = TZDEFAULT) == NULL)
340 return -1;
342 int doaccess;
343 struct stat stab;
345 ** Section 4.9.1 of the C standard says that
346 ** "FILENAME_MAX expands to an integral constant expression
347 ** that is the size needed for an array of char large enough
348 ** to hold the longest file name string that the implementation
349 ** guarantees can be opened."
351 char fullname[FILENAME_MAX + 1];
353 if (name[0] == ':')
354 ++name;
355 doaccess = name[0] == '/';
356 if (!doaccess) {
357 if ((p = TZDIR) == NULL)
358 return -1;
359 if ((strlen(p) + 1 + strlen(name) + 1) >= sizeof fullname)
360 return -1;
361 strcpy(fullname, p);
362 strcat(fullname, "/");
363 strcat(fullname, name);
365 ** Set doaccess if '.' (as in "../") shows up in name.
367 if (strchr(name, '.') != NULL)
368 doaccess = TRUE;
369 name = fullname;
371 if (doaccess && access(name, R_OK) != 0)
372 return -1;
373 if ((fid = _open(name, O_RDONLY)) == -1)
374 return -1;
375 if ((_fstat(fid, &stab) < 0) || !S_ISREG(stab.st_mode)) {
376 _close(fid);
377 return -1;
380 nread = read(fid, u.buf, sizeof u.buf);
381 if (close(fid) < 0 || nread <= 0)
382 return -1;
383 for (stored = 4; stored <= 8; stored *= 2) {
384 int ttisstdcnt;
385 int ttisgmtcnt;
387 ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
388 ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
389 sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
390 sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
391 sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
392 sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
393 p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
394 if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
395 sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
396 sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
397 sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
398 (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
399 (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
400 return -1;
401 if (nread - (p - u.buf) <
402 sp->timecnt * stored + /* ats */
403 sp->timecnt + /* types */
404 sp->typecnt * 6 + /* ttinfos */
405 sp->charcnt + /* chars */
406 sp->leapcnt * (stored + 4) + /* lsinfos */
407 ttisstdcnt + /* ttisstds */
408 ttisgmtcnt) /* ttisgmts */
409 return -1;
410 for (i = 0; i < sp->timecnt; ++i) {
411 sp->ats[i] = (stored == 4) ?
412 detzcode(p) : detzcode64(p);
413 p += stored;
415 for (i = 0; i < sp->timecnt; ++i) {
416 sp->types[i] = (unsigned char) *p++;
417 if (sp->types[i] >= sp->typecnt)
418 return -1;
420 for (i = 0; i < sp->typecnt; ++i) {
421 struct ttinfo * ttisp;
423 ttisp = &sp->ttis[i];
424 ttisp->tt_gmtoff = detzcode(p);
425 p += 4;
426 ttisp->tt_isdst = (unsigned char) *p++;
427 if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
428 return -1;
429 ttisp->tt_abbrind = (unsigned char) *p++;
430 if (ttisp->tt_abbrind < 0 ||
431 ttisp->tt_abbrind > sp->charcnt)
432 return -1;
434 for (i = 0; i < sp->charcnt; ++i)
435 sp->chars[i] = *p++;
436 sp->chars[i] = '\0'; /* ensure '\0' at end */
437 for (i = 0; i < sp->leapcnt; ++i) {
438 struct lsinfo * lsisp;
440 lsisp = &sp->lsis[i];
441 lsisp->ls_trans = (stored == 4) ?
442 detzcode(p) : detzcode64(p);
443 p += stored;
444 lsisp->ls_corr = detzcode(p);
445 p += 4;
447 for (i = 0; i < sp->typecnt; ++i) {
448 struct ttinfo * ttisp;
450 ttisp = &sp->ttis[i];
451 if (ttisstdcnt == 0)
452 ttisp->tt_ttisstd = FALSE;
453 else {
454 ttisp->tt_ttisstd = *p++;
455 if (ttisp->tt_ttisstd != TRUE &&
456 ttisp->tt_ttisstd != FALSE)
457 return -1;
460 for (i = 0; i < sp->typecnt; ++i) {
461 struct ttinfo * ttisp;
463 ttisp = &sp->ttis[i];
464 if (ttisgmtcnt == 0)
465 ttisp->tt_ttisgmt = FALSE;
466 else {
467 ttisp->tt_ttisgmt = *p++;
468 if (ttisp->tt_ttisgmt != TRUE &&
469 ttisp->tt_ttisgmt != FALSE)
470 return -1;
474 ** Out-of-sort ats should mean we're running on a
475 ** signed time_t system but using a data file with
476 ** unsigned values (or vice versa).
478 for (i = 0; i < sp->timecnt - 2; ++i)
479 if (sp->ats[i] > sp->ats[i + 1]) {
480 ++i;
481 if (TYPE_SIGNED(time_t)) {
483 ** Ignore the end (easy).
485 sp->timecnt = i;
486 } else {
488 ** Ignore the beginning (harder).
490 int j;
492 for (j = 0; j + i < sp->timecnt; ++j) {
493 sp->ats[j] = sp->ats[j + i];
494 sp->types[j] = sp->types[j + i];
496 sp->timecnt = j;
498 break;
501 ** If this is an old file, we're done.
503 if (u.tzhead.tzh_version[0] == '\0')
504 break;
505 nread -= p - u.buf;
506 for (i = 0; i < nread; ++i)
507 u.buf[i] = p[i];
509 ** If this is a narrow integer time_t system, we're done.
511 if (stored >= (int) sizeof(time_t) && TYPE_INTEGRAL(time_t))
512 break;
514 if (doextend && nread > 2 &&
515 u.buf[0] == '\n' && u.buf[nread - 1] == '\n' &&
516 sp->typecnt + 2 <= TZ_MAX_TYPES) {
517 struct state ts;
518 int result;
520 u.buf[nread - 1] = '\0';
521 result = tzparse(&u.buf[1], &ts, FALSE);
522 if (result == 0 && ts.typecnt == 2 &&
523 sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
524 for (i = 0; i < 2; ++i)
525 ts.ttis[i].tt_abbrind +=
526 sp->charcnt;
527 for (i = 0; i < ts.charcnt; ++i)
528 sp->chars[sp->charcnt++] =
529 ts.chars[i];
530 i = 0;
531 while (i < ts.timecnt &&
532 ts.ats[i] <=
533 sp->ats[sp->timecnt - 1])
534 ++i;
535 while (i < ts.timecnt &&
536 sp->timecnt < TZ_MAX_TIMES) {
537 sp->ats[sp->timecnt] =
538 ts.ats[i];
539 sp->types[sp->timecnt] =
540 sp->typecnt +
541 ts.types[i];
542 ++sp->timecnt;
543 ++i;
545 sp->ttis[sp->typecnt++] = ts.ttis[0];
546 sp->ttis[sp->typecnt++] = ts.ttis[1];
549 sp->goback = sp->goahead = FALSE;
550 if (sp->timecnt > 1) {
551 for (i = 1; i < sp->timecnt; ++i)
552 if (typesequiv(sp, sp->types[i], sp->types[0]) &&
553 differ_by_repeat(sp->ats[i], sp->ats[0])) {
554 sp->goback = TRUE;
555 break;
557 for (i = sp->timecnt - 2; i >= 0; --i)
558 if (typesequiv(sp, sp->types[sp->timecnt - 1],
559 sp->types[i]) &&
560 differ_by_repeat(sp->ats[sp->timecnt - 1],
561 sp->ats[i])) {
562 sp->goahead = TRUE;
563 break;
566 return 0;
569 static int
570 typesequiv(const struct state * const sp, const int a, const int b)
572 int result;
574 if (sp == NULL ||
575 a < 0 || a >= sp->typecnt ||
576 b < 0 || b >= sp->typecnt)
577 result = FALSE;
578 else {
579 const struct ttinfo * ap = &sp->ttis[a];
580 const struct ttinfo * bp = &sp->ttis[b];
581 result = ap->tt_gmtoff == bp->tt_gmtoff &&
582 ap->tt_isdst == bp->tt_isdst &&
583 ap->tt_ttisstd == bp->tt_ttisstd &&
584 ap->tt_ttisgmt == bp->tt_ttisgmt &&
585 strcmp(&sp->chars[ap->tt_abbrind],
586 &sp->chars[bp->tt_abbrind]) == 0;
588 return result;
591 static const int mon_lengths[2][MONSPERYEAR] = {
592 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
593 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
596 static const int year_lengths[2] = {
597 DAYSPERNYEAR, DAYSPERLYEAR
601 ** Given a pointer into a time zone string, scan until a character that is not
602 ** a valid character in a zone name is found. Return a pointer to that
603 ** character.
606 static const char *
607 getzname(const char *strp)
609 char c;
611 while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
612 c != '+')
613 ++strp;
614 return strp;
618 ** Given a pointer into an extended time zone string, scan until the ending
619 ** delimiter of the zone name is located. Return a pointer to the delimiter.
621 ** As with getzname above, the legal character set is actually quite
622 ** restricted, with other characters producing undefined results.
623 ** We don't do any checking here; checking is done later in common-case code.
626 static const char *
627 getqzname(const char *strp, const int delim)
629 int c;
631 while ((c = *strp) != '\0' && c != delim)
632 ++strp;
633 return strp;
637 ** Given a pointer into a time zone string, extract a number from that string.
638 ** Check that the number is within a specified range; if it is not, return
639 ** NULL.
640 ** Otherwise, return a pointer to the first character not part of the number.
643 static const char *
644 getnum(const char *strp, int * const nump, const int min, const int max)
646 char c;
647 int num;
649 if (strp == NULL || !is_digit(c = *strp))
650 return NULL;
651 num = 0;
652 do {
653 num = num * 10 + (c - '0');
654 if (num > max)
655 return NULL; /* illegal value */
656 c = *++strp;
657 } while (is_digit(c));
658 if (num < min)
659 return NULL; /* illegal value */
660 *nump = num;
661 return strp;
665 ** Given a pointer into a time zone string, extract a number of seconds,
666 ** in hh[:mm[:ss]] form, from the string.
667 ** If any error occurs, return NULL.
668 ** Otherwise, return a pointer to the first character not part of the number
669 ** of seconds.
672 static const char *
673 getsecs(const char *strp, long * const secsp)
675 int num;
678 ** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
679 ** "M10.4.6/26", which does not conform to Posix,
680 ** but which specifies the equivalent of
681 ** ``02:00 on the first Sunday on or after 23 Oct''.
683 strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
684 if (strp == NULL)
685 return NULL;
686 *secsp = num * (long) SECSPERHOUR;
687 if (*strp == ':') {
688 ++strp;
689 strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
690 if (strp == NULL)
691 return NULL;
692 *secsp += num * SECSPERMIN;
693 if (*strp == ':') {
694 ++strp;
695 /* `SECSPERMIN' allows for leap seconds. */
696 strp = getnum(strp, &num, 0, SECSPERMIN);
697 if (strp == NULL)
698 return NULL;
699 *secsp += num;
702 return strp;
706 ** Given a pointer into a time zone string, extract an offset, in
707 ** [+-]hh[:mm[:ss]] form, from the string.
708 ** If any error occurs, return NULL.
709 ** Otherwise, return a pointer to the first character not part of the time.
712 static const char *
713 getoffset(const char *strp, long * const offsetp)
715 int neg = 0;
717 if (*strp == '-') {
718 neg = 1;
719 ++strp;
720 } else if (*strp == '+')
721 ++strp;
722 strp = getsecs(strp, offsetp);
723 if (strp == NULL)
724 return NULL; /* illegal time */
725 if (neg)
726 *offsetp = -*offsetp;
727 return strp;
731 ** Given a pointer into a time zone string, extract a rule in the form
732 ** date[/time]. See POSIX section 8 for the format of "date" and "time".
733 ** If a valid rule is not found, return NULL.
734 ** Otherwise, return a pointer to the first character not part of the rule.
737 static const char *
738 getrule(const char *strp, struct rule * const rulep)
740 if (*strp == 'J') {
742 ** Julian day.
744 rulep->r_type = JULIAN_DAY;
745 ++strp;
746 strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
747 } else if (*strp == 'M') {
749 ** Month, week, day.
751 rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
752 ++strp;
753 strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
754 if (strp == NULL)
755 return NULL;
756 if (*strp++ != '.')
757 return NULL;
758 strp = getnum(strp, &rulep->r_week, 1, 5);
759 if (strp == NULL)
760 return NULL;
761 if (*strp++ != '.')
762 return NULL;
763 strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
764 } else if (is_digit(*strp)) {
766 ** Day of year.
768 rulep->r_type = DAY_OF_YEAR;
769 strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
770 } else return NULL; /* invalid format */
771 if (strp == NULL)
772 return NULL;
773 if (*strp == '/') {
775 ** Time specified.
777 ++strp;
778 strp = getsecs(strp, &rulep->r_time);
779 } else rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
780 return strp;
784 ** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
785 ** year, a rule, and the offset from UTC at the time that rule takes effect,
786 ** calculate the Epoch-relative time that rule takes effect.
789 static time_t
790 transtime(const time_t janfirst, const int year,
791 const struct rule * const rulep, const long offset)
793 int leapyear;
794 time_t value;
795 int i;
796 int d, m1, yy0, yy1, yy2, dow;
798 INITIALIZE(value);
799 leapyear = isleap(year);
800 switch (rulep->r_type) {
802 case JULIAN_DAY:
804 ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
805 ** years.
806 ** In non-leap years, or if the day number is 59 or less, just
807 ** add SECSPERDAY times the day number-1 to the time of
808 ** January 1, midnight, to get the day.
810 value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
811 if (leapyear && rulep->r_day >= 60)
812 value += SECSPERDAY;
813 break;
815 case DAY_OF_YEAR:
817 ** n - day of year.
818 ** Just add SECSPERDAY times the day number to the time of
819 ** January 1, midnight, to get the day.
821 value = janfirst + rulep->r_day * SECSPERDAY;
822 break;
824 case MONTH_NTH_DAY_OF_WEEK:
826 ** Mm.n.d - nth "dth day" of month m.
828 value = janfirst;
829 for (i = 0; i < rulep->r_mon - 1; ++i)
830 value += mon_lengths[leapyear][i] * SECSPERDAY;
833 ** Use Zeller's Congruence to get day-of-week of first day of
834 ** month.
836 m1 = (rulep->r_mon + 9) % 12 + 1;
837 yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
838 yy1 = yy0 / 100;
839 yy2 = yy0 % 100;
840 dow = ((26 * m1 - 2) / 10 +
841 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
842 if (dow < 0)
843 dow += DAYSPERWEEK;
846 ** "dow" is the day-of-week of the first day of the month. Get
847 ** the day-of-month (zero-origin) of the first "dow" day of the
848 ** month.
850 d = rulep->r_day - dow;
851 if (d < 0)
852 d += DAYSPERWEEK;
853 for (i = 1; i < rulep->r_week; ++i) {
854 if (d + DAYSPERWEEK >=
855 mon_lengths[leapyear][rulep->r_mon - 1])
856 break;
857 d += DAYSPERWEEK;
861 ** "d" is the day-of-month (zero-origin) of the day we want.
863 value += d * SECSPERDAY;
864 break;
868 ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
869 ** question. To get the Epoch-relative time of the specified local
870 ** time on that day, add the transition time and the current offset
871 ** from UTC.
873 return value + rulep->r_time + offset;
877 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
878 ** appropriate.
881 static int
882 tzparse(const char *name, struct state * const sp, const int lastditch)
884 const char * stdname;
885 const char * dstname;
886 size_t stdlen;
887 size_t dstlen;
888 long stdoffset;
889 long dstoffset;
890 time_t * atp;
891 unsigned char * typep;
892 char * cp;
893 int load_result;
895 INITIALIZE(dstname);
896 stdname = name;
897 if (lastditch) {
898 stdlen = strlen(name); /* length of standard zone name */
899 name += stdlen;
900 if (stdlen >= sizeof sp->chars)
901 stdlen = (sizeof sp->chars) - 1;
902 stdoffset = 0;
903 } else {
904 if (*name == '<') {
905 name++;
906 stdname = name;
907 name = getqzname(name, '>');
908 if (*name != '>')
909 return (-1);
910 stdlen = name - stdname;
911 name++;
912 } else {
913 name = getzname(name);
914 stdlen = name - stdname;
916 if (*name == '\0')
917 return -1;
918 name = getoffset(name, &stdoffset);
919 if (name == NULL)
920 return -1;
922 load_result = tzload(TZDEFRULES, sp, FALSE);
923 if (load_result != 0)
924 sp->leapcnt = 0; /* so, we're off a little */
925 if (*name != '\0') {
926 if (*name == '<') {
927 dstname = ++name;
928 name = getqzname(name, '>');
929 if (*name != '>')
930 return -1;
931 dstlen = name - dstname;
932 name++;
933 } else {
934 dstname = name;
935 name = getzname(name);
936 dstlen = name - dstname; /* length of DST zone name */
938 if (*name != '\0' && *name != ',' && *name != ';') {
939 name = getoffset(name, &dstoffset);
940 if (name == NULL)
941 return -1;
942 } else dstoffset = stdoffset - SECSPERHOUR;
943 if (*name == '\0' && load_result != 0)
944 name = TZDEFRULESTRING;
945 if (*name == ',' || *name == ';') {
946 struct rule start;
947 struct rule end;
948 int year;
949 time_t janfirst;
950 time_t starttime;
951 time_t endtime;
953 ++name;
954 if ((name = getrule(name, &start)) == NULL)
955 return -1;
956 if (*name++ != ',')
957 return -1;
958 if ((name = getrule(name, &end)) == NULL)
959 return -1;
960 if (*name != '\0')
961 return -1;
962 sp->typecnt = 2; /* standard time and DST */
964 ** Two transitions per year, from EPOCH_YEAR forward.
966 sp->ttis[0].tt_gmtoff = -dstoffset;
967 sp->ttis[0].tt_isdst = 1;
968 sp->ttis[0].tt_abbrind = stdlen + 1;
969 sp->ttis[1].tt_gmtoff = -stdoffset;
970 sp->ttis[1].tt_isdst = 0;
971 sp->ttis[1].tt_abbrind = 0;
972 atp = sp->ats;
973 typep = sp->types;
974 janfirst = 0;
975 sp->timecnt = 0;
976 for (year = EPOCH_YEAR;
977 sp->timecnt + 2 <= TZ_MAX_TIMES;
978 ++year) {
979 time_t newfirst;
981 starttime = transtime(janfirst, year, &start,
982 stdoffset);
983 endtime = transtime(janfirst, year, &end,
984 dstoffset);
985 if (starttime > endtime) {
986 *atp++ = endtime;
987 *typep++ = 1; /* DST ends */
988 *atp++ = starttime;
989 *typep++ = 0; /* DST begins */
990 } else {
991 *atp++ = starttime;
992 *typep++ = 0; /* DST begins */
993 *atp++ = endtime;
994 *typep++ = 1; /* DST ends */
996 sp->timecnt += 2;
997 newfirst = janfirst;
998 newfirst += year_lengths[isleap(year)] *
999 SECSPERDAY;
1000 if (newfirst <= janfirst)
1001 break;
1002 janfirst = newfirst;
1004 } else {
1005 long theirstdoffset;
1006 long theirdstoffset;
1007 long theiroffset;
1008 int isdst;
1009 int i;
1010 int j;
1012 if (*name != '\0')
1013 return -1;
1015 ** Initial values of theirstdoffset and theirdstoffset.
1017 theirstdoffset = 0;
1018 for (i = 0; i < sp->timecnt; ++i) {
1019 j = sp->types[i];
1020 if (!sp->ttis[j].tt_isdst) {
1021 theirstdoffset =
1022 -sp->ttis[j].tt_gmtoff;
1023 break;
1026 theirdstoffset = 0;
1027 for (i = 0; i < sp->timecnt; ++i) {
1028 j = sp->types[i];
1029 if (sp->ttis[j].tt_isdst) {
1030 theirdstoffset =
1031 -sp->ttis[j].tt_gmtoff;
1032 break;
1036 ** Initially we're assumed to be in standard time.
1038 isdst = FALSE;
1039 theiroffset = theirstdoffset;
1041 ** Now juggle transition times and types
1042 ** tracking offsets as you do.
1044 for (i = 0; i < sp->timecnt; ++i) {
1045 j = sp->types[i];
1046 sp->types[i] = sp->ttis[j].tt_isdst;
1047 if (sp->ttis[j].tt_ttisgmt) {
1048 /* No adjustment to transition time */
1049 } else {
1051 ** If summer time is in effect, and the
1052 ** transition time was not specified as
1053 ** standard time, add the summer time
1054 ** offset to the transition time;
1055 ** otherwise, add the standard time
1056 ** offset to the transition time.
1059 ** Transitions from DST to DDST
1060 ** will effectively disappear since
1061 ** POSIX provides for only one DST
1062 ** offset.
1064 if (isdst && !sp->ttis[j].tt_ttisstd) {
1065 sp->ats[i] += dstoffset -
1066 theirdstoffset;
1067 } else {
1068 sp->ats[i] += stdoffset -
1069 theirstdoffset;
1072 theiroffset = -sp->ttis[j].tt_gmtoff;
1073 if (sp->ttis[j].tt_isdst)
1074 theirdstoffset = theiroffset;
1075 else theirstdoffset = theiroffset;
1078 ** Finally, fill in ttis.
1079 ** ttisstd and ttisgmt need not be handled.
1081 sp->ttis[0].tt_gmtoff = -stdoffset;
1082 sp->ttis[0].tt_isdst = FALSE;
1083 sp->ttis[0].tt_abbrind = 0;
1084 sp->ttis[1].tt_gmtoff = -dstoffset;
1085 sp->ttis[1].tt_isdst = TRUE;
1086 sp->ttis[1].tt_abbrind = stdlen + 1;
1087 sp->typecnt = 2;
1089 } else {
1090 dstlen = 0;
1091 sp->typecnt = 1; /* only standard time */
1092 sp->timecnt = 0;
1093 sp->ttis[0].tt_gmtoff = -stdoffset;
1094 sp->ttis[0].tt_isdst = 0;
1095 sp->ttis[0].tt_abbrind = 0;
1097 sp->charcnt = stdlen + 1;
1098 if (dstlen != 0)
1099 sp->charcnt += dstlen + 1;
1100 if ((size_t) sp->charcnt > sizeof sp->chars)
1101 return -1;
1102 cp = sp->chars;
1103 strncpy(cp, stdname, stdlen);
1104 cp += stdlen;
1105 *cp++ = '\0';
1106 if (dstlen != 0) {
1107 strncpy(cp, dstname, dstlen);
1108 *(cp + dstlen) = '\0';
1110 return 0;
1113 static void
1114 gmtload(struct state * const sp)
1116 if (tzload(gmt, sp, TRUE) != 0)
1117 tzparse(gmt, sp, TRUE);
1120 static void
1121 tzsetwall_basic(int rdlocked)
1123 if (!rdlocked)
1124 _RWLOCK_RDLOCK(&lcl_rwlock);
1125 if (lcl_is_set < 0) {
1126 if (!rdlocked)
1127 _RWLOCK_UNLOCK(&lcl_rwlock);
1128 return;
1130 _RWLOCK_UNLOCK(&lcl_rwlock);
1132 _RWLOCK_WRLOCK(&lcl_rwlock);
1133 lcl_is_set = -1;
1135 if (tzload(NULL, lclptr, TRUE) != 0)
1136 gmtload(lclptr);
1137 settzname();
1138 _RWLOCK_UNLOCK(&lcl_rwlock);
1140 if (rdlocked)
1141 _RWLOCK_RDLOCK(&lcl_rwlock);
1144 void
1145 tzsetwall(void)
1147 tzsetwall_basic(0);
1150 static void
1151 tzset_basic(int rdlocked)
1153 const char * name;
1155 name = getenv("TZ");
1156 if (name == NULL) {
1157 tzsetwall_basic(rdlocked);
1158 return;
1161 if (!rdlocked)
1162 _RWLOCK_RDLOCK(&lcl_rwlock);
1163 if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0) {
1164 if (!rdlocked)
1165 _RWLOCK_UNLOCK(&lcl_rwlock);
1166 return;
1168 _RWLOCK_UNLOCK(&lcl_rwlock);
1170 _RWLOCK_WRLOCK(&lcl_rwlock);
1171 lcl_is_set = strlen(name) < sizeof lcl_TZname;
1172 if (lcl_is_set)
1173 strcpy(lcl_TZname, name);
1175 if (*name == '\0') {
1177 ** User wants it fast rather than right.
1179 lclptr->leapcnt = 0; /* so, we're off a little */
1180 lclptr->timecnt = 0;
1181 lclptr->typecnt = 0;
1182 lclptr->ttis[0].tt_isdst = 0;
1183 lclptr->ttis[0].tt_gmtoff = 0;
1184 lclptr->ttis[0].tt_abbrind = 0;
1185 strcpy(lclptr->chars, gmt);
1186 } else if (tzload(name, lclptr, TRUE) != 0)
1187 if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
1188 gmtload(lclptr);
1189 settzname();
1190 _RWLOCK_UNLOCK(&lcl_rwlock);
1192 if (rdlocked)
1193 _RWLOCK_RDLOCK(&lcl_rwlock);
1196 void
1197 tzset(void)
1199 tzset_basic(0);
1203 ** The easy way to behave "as if no library function calls" localtime
1204 ** is to not call it--so we drop its guts into "localsub", which can be
1205 ** freely called. (And no, the PANS doesn't require the above behavior--
1206 ** but it *is* desirable.)
1208 ** The unused offset argument is for the benefit of mktime variants.
1211 /*ARGSUSED*/
1212 static struct tm *
1213 localsub(const time_t * const timep, const long offset __unused,
1214 struct tm * const tmp)
1216 struct state * sp;
1217 const struct ttinfo * ttisp;
1218 int i;
1219 struct tm * result;
1220 const time_t t = *timep;
1222 sp = lclptr;
1224 if ((sp->goback && t < sp->ats[0]) ||
1225 (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1226 time_t newt = t;
1227 time_t seconds;
1228 time_t tcycles;
1229 int_fast64_t icycles;
1231 if (t < sp->ats[0])
1232 seconds = sp->ats[0] - t;
1233 else seconds = t - sp->ats[sp->timecnt - 1];
1234 --seconds;
1235 tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1236 ++tcycles;
1237 icycles = tcycles;
1238 if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1239 return NULL;
1240 seconds = icycles;
1241 seconds *= YEARSPERREPEAT;
1242 seconds *= AVGSECSPERYEAR;
1243 if (t < sp->ats[0])
1244 newt += seconds;
1245 else newt -= seconds;
1246 if (newt < sp->ats[0] ||
1247 newt > sp->ats[sp->timecnt - 1])
1248 return NULL; /* "cannot happen" */
1249 result = localsub(&newt, offset, tmp);
1250 if (result == tmp) {
1251 time_t newy;
1253 newy = tmp->tm_year;
1254 if (t < sp->ats[0])
1255 newy -= icycles * YEARSPERREPEAT;
1256 else newy += icycles * YEARSPERREPEAT;
1257 tmp->tm_year = newy;
1258 if (tmp->tm_year != newy)
1259 return NULL;
1261 return result;
1263 if (sp->timecnt == 0 || t < sp->ats[0]) {
1264 i = 0;
1265 while (sp->ttis[i].tt_isdst)
1266 if (++i >= sp->typecnt) {
1267 i = 0;
1268 break;
1270 } else {
1271 int lo = 1;
1272 int hi = sp->timecnt;
1274 while (lo < hi) {
1275 int mid = (lo + hi) >> 1;
1277 if (t < sp->ats[mid])
1278 hi = mid;
1279 else lo = mid + 1;
1281 i = (int) sp->types[lo - 1];
1283 ttisp = &sp->ttis[i];
1285 ** To get (wrong) behavior that's compatible with System V Release 2.0
1286 ** you'd replace the statement below with
1287 ** t += ttisp->tt_gmtoff;
1288 ** timesub(&t, 0L, sp, tmp);
1290 result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1291 tmp->tm_isdst = ttisp->tt_isdst;
1292 tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1293 #ifdef TM_ZONE
1294 tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1295 #endif /* defined TM_ZONE */
1296 return result;
1299 struct tm *
1300 localtime_r(const time_t * const timep, struct tm *p_tm)
1302 _RWLOCK_RDLOCK(&lcl_rwlock);
1303 tzset_basic(1);
1304 localsub(timep, 0L, p_tm);
1305 _RWLOCK_UNLOCK(&lcl_rwlock);
1306 return(p_tm);
1309 struct tm *
1310 localtime(const time_t * const timep)
1312 static pthread_mutex_t localtime_mutex = PTHREAD_MUTEX_INITIALIZER;
1313 static pthread_key_t localtime_key = -1;
1314 struct tm *p_tm;
1316 if (__isthreaded != 0) {
1317 if (localtime_key < 0) {
1318 _pthread_mutex_lock(&localtime_mutex);
1319 if (localtime_key < 0) {
1320 if (_pthread_key_create(&localtime_key, free) < 0) {
1321 _pthread_mutex_unlock(&localtime_mutex);
1322 return(NULL);
1325 _pthread_mutex_unlock(&localtime_mutex);
1327 p_tm = _pthread_getspecific(localtime_key);
1328 if (p_tm == NULL) {
1329 if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1330 == NULL)
1331 return(NULL);
1332 _pthread_setspecific(localtime_key, p_tm);
1334 _RWLOCK_RDLOCK(&lcl_rwlock);
1335 tzset_basic(1);
1336 localsub(timep, 0L, p_tm);
1337 _RWLOCK_UNLOCK(&lcl_rwlock);
1338 return(p_tm);
1339 } else {
1340 tzset_basic(0);
1341 localsub(timep, 0L, &tm);
1342 return(&tm);
1347 ** gmtsub is to gmtime as localsub is to localtime.
1350 static struct tm *
1351 gmtsub(const time_t * const timep, const long offset, struct tm * const tmp)
1353 struct tm * result;
1355 if (!gmt_is_set) {
1356 _MUTEX_LOCK(&gmt_mutex);
1357 if (!gmt_is_set) {
1358 gmtload(gmtptr);
1359 gmt_is_set = TRUE;
1361 _MUTEX_UNLOCK(&gmt_mutex);
1363 result = timesub(timep, offset, gmtptr, tmp);
1364 #ifdef TM_ZONE
1366 ** Could get fancy here and deliver something such as
1367 ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1368 ** but this is no time for a treasure hunt.
1370 if (offset != 0)
1371 tmp->TM_ZONE = wildabbr;
1372 else
1373 tmp->TM_ZONE = gmtptr->chars;
1374 #endif /* defined TM_ZONE */
1375 return result;
1378 struct tm *
1379 gmtime(const time_t * const timep)
1381 static pthread_mutex_t gmtime_mutex = PTHREAD_MUTEX_INITIALIZER;
1382 static pthread_key_t gmtime_key = -1;
1383 struct tm *p_tm;
1385 if (__isthreaded != 0) {
1386 if (gmtime_key < 0) {
1387 _pthread_mutex_lock(&gmtime_mutex);
1388 if (gmtime_key < 0) {
1389 if (_pthread_key_create(&gmtime_key, free) < 0) {
1390 _pthread_mutex_unlock(&gmtime_mutex);
1391 return(NULL);
1394 _pthread_mutex_unlock(&gmtime_mutex);
1397 * Changed to follow POSIX.1 threads standard, which
1398 * is what BSD currently has.
1400 if ((p_tm = _pthread_getspecific(gmtime_key)) == NULL) {
1401 if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1402 == NULL) {
1403 return(NULL);
1405 _pthread_setspecific(gmtime_key, p_tm);
1407 return gmtsub(timep, 0L, p_tm);
1408 } else {
1409 return gmtsub(timep, 0L, &tm);
1413 struct tm *
1414 gmtime_r(const time_t * timep, struct tm * tmp)
1416 return gmtsub(timep, 0L, tmp);
1419 struct tm *
1420 offtime(const time_t * const timep, const long offset)
1422 return gmtsub(timep, offset, &tm);
1426 ** Return the number of leap years through the end of the given year
1427 ** where, to make the math easy, the answer for year zero is defined as zero.
1430 static int
1431 leaps_thru_end_of(const int y)
1433 return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1434 -(leaps_thru_end_of(-(y + 1)) + 1);
1437 static struct tm *
1438 timesub(const time_t * const timep, const long offset,
1439 const struct state * const sp, struct tm * const tmp)
1441 const struct lsinfo * lp;
1442 time_t tdays;
1443 int idays; /* unsigned would be so 2003 */
1444 long rem;
1445 int y;
1446 int yleap;
1447 const int * ip;
1448 long corr;
1449 int hit;
1450 int i;
1452 corr = 0;
1453 hit = 0;
1454 i = sp->leapcnt;
1456 while (--i >= 0) {
1457 lp = &sp->lsis[i];
1458 if (*timep >= lp->ls_trans) {
1459 if (*timep == lp->ls_trans) {
1460 hit = ((i == 0 && lp->ls_corr > 0) ||
1461 lp->ls_corr > sp->lsis[i - 1].ls_corr);
1462 if (hit)
1463 while (i > 0 &&
1464 sp->lsis[i].ls_trans ==
1465 sp->lsis[i - 1].ls_trans + 1 &&
1466 sp->lsis[i].ls_corr ==
1467 sp->lsis[i - 1].ls_corr + 1) {
1468 ++hit;
1469 --i;
1472 corr = lp->ls_corr;
1473 break;
1476 y = EPOCH_YEAR;
1477 tdays = *timep / SECSPERDAY;
1478 rem = *timep - tdays * SECSPERDAY;
1479 while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
1480 int newy;
1481 time_t tdelta;
1482 int idelta;
1483 int leapdays;
1485 tdelta = tdays / DAYSPERLYEAR;
1486 idelta = tdelta;
1487 if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
1488 return NULL;
1489 if (idelta == 0)
1490 idelta = (tdays < 0) ? -1 : 1;
1491 newy = y;
1492 if (increment_overflow(&newy, idelta))
1493 return NULL;
1494 leapdays = leaps_thru_end_of(newy - 1) -
1495 leaps_thru_end_of(y - 1);
1496 tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
1497 tdays -= leapdays;
1498 y = newy;
1501 long seconds;
1503 seconds = tdays * SECSPERDAY + 0.5;
1504 tdays = seconds / SECSPERDAY;
1505 rem += seconds - tdays * SECSPERDAY;
1508 ** Given the range, we can now fearlessly cast...
1510 idays = tdays;
1511 rem += offset - corr;
1512 while (rem < 0) {
1513 rem += SECSPERDAY;
1514 --idays;
1516 while (rem >= SECSPERDAY) {
1517 rem -= SECSPERDAY;
1518 ++idays;
1520 while (idays < 0) {
1521 if (increment_overflow(&y, -1))
1522 return NULL;
1523 idays += year_lengths[isleap(y)];
1525 while (idays >= year_lengths[isleap(y)]) {
1526 idays -= year_lengths[isleap(y)];
1527 if (increment_overflow(&y, 1))
1528 return NULL;
1530 tmp->tm_year = y;
1531 if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
1532 return NULL;
1533 tmp->tm_yday = idays;
1535 ** The "extra" mods below avoid overflow problems.
1537 tmp->tm_wday = EPOCH_WDAY +
1538 ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1539 (DAYSPERNYEAR % DAYSPERWEEK) +
1540 leaps_thru_end_of(y - 1) -
1541 leaps_thru_end_of(EPOCH_YEAR - 1) +
1542 idays;
1543 tmp->tm_wday %= DAYSPERWEEK;
1544 if (tmp->tm_wday < 0)
1545 tmp->tm_wday += DAYSPERWEEK;
1546 tmp->tm_hour = (int) (rem / SECSPERHOUR);
1547 rem %= SECSPERHOUR;
1548 tmp->tm_min = (int) (rem / SECSPERMIN);
1550 ** A positive leap second requires a special
1551 ** representation. This uses "... ??:59:60" et seq.
1553 tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1554 ip = mon_lengths[isleap(y)];
1555 for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1556 idays -= ip[tmp->tm_mon];
1557 tmp->tm_mday = (int) (idays + 1);
1558 tmp->tm_isdst = 0;
1559 #ifdef TM_GMTOFF
1560 tmp->TM_GMTOFF = offset;
1561 #endif /* defined TM_GMTOFF */
1562 return tmp;
1565 char *
1566 ctime(const time_t * const timep)
1569 ** Section 4.12.3.2 of X3.159-1989 requires that
1570 ** The ctime function converts the calendar time pointed to by timer
1571 ** to local time in the form of a string. It is equivalent to
1572 ** asctime(localtime(timer))
1574 return asctime(localtime(timep));
1577 char *
1578 ctime_r(const time_t * const timep, char *buf)
1580 struct tm mytm;
1581 return asctime_r(localtime_r(timep, &mytm), buf);
1585 ** Adapted from code provided by Robert Elz, who writes:
1586 ** The "best" way to do mktime I think is based on an idea of Bob
1587 ** Kridle's (so its said...) from a long time ago.
1588 ** It does a binary search of the time_t space. Since time_t's are
1589 ** just 32 bits, its a max of 32 iterations (even at 64 bits it
1590 ** would still be very reasonable).
1593 #ifndef WRONG
1594 #define WRONG (-1)
1595 #endif /* !defined WRONG */
1598 ** Simplified normalize logic courtesy Paul Eggert.
1601 static int
1602 increment_overflow(int *number, int delta)
1604 int number0;
1606 number0 = *number;
1607 *number += delta;
1608 return (*number < number0) != (delta < 0);
1611 static int
1612 long_increment_overflow(long *number, int delta)
1614 long number0;
1616 number0 = *number;
1617 *number += delta;
1618 return (*number < number0) != (delta < 0);
1621 static int
1622 normalize_overflow(int * const tensptr, int * const unitsptr, const int base)
1624 int tensdelta;
1626 tensdelta = (*unitsptr >= 0) ?
1627 (*unitsptr / base) :
1628 (-1 - (-1 - *unitsptr) / base);
1629 *unitsptr -= tensdelta * base;
1630 return increment_overflow(tensptr, tensdelta);
1633 static int
1634 long_normalize_overflow(long * const tensptr, int * const unitsptr,
1635 const int base)
1637 int tensdelta;
1639 tensdelta = (*unitsptr >= 0) ?
1640 (*unitsptr / base) :
1641 (-1 - (-1 - *unitsptr) / base);
1642 *unitsptr -= tensdelta * base;
1643 return long_increment_overflow(tensptr, tensdelta);
1646 static int
1647 tmcomp(const struct tm * const atmp, const struct tm * const btmp)
1649 int result;
1651 if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1652 (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1653 (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1654 (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1655 (result = (atmp->tm_min - btmp->tm_min)) == 0)
1656 result = atmp->tm_sec - btmp->tm_sec;
1657 return result;
1660 static time_t
1661 time2sub(struct tm * const tmp,
1662 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1663 const long offset, int * const okayp, const int do_norm_secs)
1665 const struct state * sp;
1666 int dir;
1667 int i, j;
1668 int saved_seconds;
1669 long li;
1670 time_t lo;
1671 time_t hi;
1672 long y;
1673 time_t newt;
1674 time_t t;
1675 struct tm yourtm, mytm;
1677 *okayp = FALSE;
1678 yourtm = *tmp;
1679 if (do_norm_secs) {
1680 if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1681 SECSPERMIN))
1682 return WRONG;
1684 if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1685 return WRONG;
1686 if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1687 return WRONG;
1688 y = yourtm.tm_year;
1689 if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
1690 return WRONG;
1692 ** Turn y into an actual year number for now.
1693 ** It is converted back to an offset from TM_YEAR_BASE later.
1695 if (long_increment_overflow(&y, TM_YEAR_BASE))
1696 return WRONG;
1697 while (yourtm.tm_mday <= 0) {
1698 if (long_increment_overflow(&y, -1))
1699 return WRONG;
1700 li = y + (1 < yourtm.tm_mon);
1701 yourtm.tm_mday += year_lengths[isleap(li)];
1703 while (yourtm.tm_mday > DAYSPERLYEAR) {
1704 li = y + (1 < yourtm.tm_mon);
1705 yourtm.tm_mday -= year_lengths[isleap(li)];
1706 if (long_increment_overflow(&y, 1))
1707 return WRONG;
1709 for ( ; ; ) {
1710 i = mon_lengths[isleap(y)][yourtm.tm_mon];
1711 if (yourtm.tm_mday <= i)
1712 break;
1713 yourtm.tm_mday -= i;
1714 if (++yourtm.tm_mon >= MONSPERYEAR) {
1715 yourtm.tm_mon = 0;
1716 if (long_increment_overflow(&y, 1))
1717 return WRONG;
1720 if (long_increment_overflow(&y, -TM_YEAR_BASE))
1721 return WRONG;
1722 yourtm.tm_year = y;
1723 if (yourtm.tm_year != y)
1724 return WRONG;
1725 if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1726 saved_seconds = 0;
1727 else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
1729 ** We can't set tm_sec to 0, because that might push the
1730 ** time below the minimum representable time.
1731 ** Set tm_sec to 59 instead.
1732 ** This assumes that the minimum representable time is
1733 ** not in the same minute that a leap second was deleted from,
1734 ** which is a safer assumption than using 58 would be.
1736 if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1737 return WRONG;
1738 saved_seconds = yourtm.tm_sec;
1739 yourtm.tm_sec = SECSPERMIN - 1;
1740 } else {
1741 saved_seconds = yourtm.tm_sec;
1742 yourtm.tm_sec = 0;
1745 ** Do a binary search (this works whatever time_t's type is).
1747 if (!TYPE_SIGNED(time_t)) {
1748 lo = 0;
1749 hi = lo - 1;
1750 } else if (!TYPE_INTEGRAL(time_t)) {
1751 if (sizeof(time_t) > sizeof(float))
1752 hi = (time_t) DBL_MAX;
1753 else hi = (time_t) FLT_MAX;
1754 lo = -hi;
1755 } else {
1756 lo = 1;
1757 for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
1758 lo *= 2;
1759 hi = -(lo + 1);
1761 for ( ; ; ) {
1762 t = lo / 2 + hi / 2;
1763 if (t < lo)
1764 t = lo;
1765 else if (t > hi)
1766 t = hi;
1767 if ((*funcp)(&t, offset, &mytm) == NULL) {
1769 ** Assume that t is too extreme to be represented in
1770 ** a struct tm; arrange things so that it is less
1771 ** extreme on the next pass.
1773 dir = (t > 0) ? 1 : -1;
1774 } else dir = tmcomp(&mytm, &yourtm);
1775 if (dir != 0) {
1776 if (t == lo) {
1777 ++t;
1778 if (t <= lo)
1779 return WRONG;
1780 ++lo;
1781 } else if (t == hi) {
1782 --t;
1783 if (t >= hi)
1784 return WRONG;
1785 --hi;
1787 if (lo > hi)
1788 return WRONG;
1789 if (dir > 0)
1790 hi = t;
1791 else lo = t;
1792 continue;
1794 if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1795 break;
1797 ** Right time, wrong type.
1798 ** Hunt for right time, right type.
1799 ** It's okay to guess wrong since the guess
1800 ** gets checked.
1802 sp = (const struct state *)
1803 ((funcp == localsub) ? lclptr : gmtptr);
1805 for (i = sp->typecnt - 1; i >= 0; --i) {
1806 if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1807 continue;
1808 for (j = sp->typecnt - 1; j >= 0; --j) {
1809 if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1810 continue;
1811 newt = t + sp->ttis[j].tt_gmtoff -
1812 sp->ttis[i].tt_gmtoff;
1813 if ((*funcp)(&newt, offset, &mytm) == NULL)
1814 continue;
1815 if (tmcomp(&mytm, &yourtm) != 0)
1816 continue;
1817 if (mytm.tm_isdst != yourtm.tm_isdst)
1818 continue;
1820 ** We have a match.
1822 t = newt;
1823 goto label;
1826 return WRONG;
1828 label:
1829 newt = t + saved_seconds;
1830 if ((newt < t) != (saved_seconds < 0))
1831 return WRONG;
1832 t = newt;
1833 if ((*funcp)(&t, offset, tmp))
1834 *okayp = TRUE;
1835 return t;
1838 static time_t
1839 time2(struct tm * const tmp,
1840 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1841 const long offset, int * const okayp)
1843 time_t t;
1846 ** First try without normalization of seconds
1847 ** (in case tm_sec contains a value associated with a leap second).
1848 ** If that fails, try with normalization of seconds.
1850 t = time2sub(tmp, funcp, offset, okayp, FALSE);
1851 return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE);
1854 static time_t
1855 time1(struct tm * const tmp,
1856 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1857 const long offset)
1859 time_t t;
1860 const struct state * sp;
1861 int samei, otheri;
1862 int sameind, otherind;
1863 int i;
1864 int nseen;
1865 int seen[TZ_MAX_TYPES];
1866 int types[TZ_MAX_TYPES];
1867 int okay;
1869 if (tmp == NULL) {
1870 errno = EINVAL;
1871 return WRONG;
1873 if (tmp->tm_isdst > 1)
1874 tmp->tm_isdst = 1;
1875 t = time2(tmp, funcp, offset, &okay);
1878 ** PCTS code courtesy Grant Sullivan.
1880 if (okay)
1881 return t;
1882 if (tmp->tm_isdst < 0)
1883 tmp->tm_isdst = 0; /* reset to std and try again */
1886 ** We're supposed to assume that somebody took a time of one type
1887 ** and did some math on it that yielded a "struct tm" that's bad.
1888 ** We try to divine the type they started from and adjust to the
1889 ** type they need.
1891 sp = (const struct state *) ((funcp == localsub) ? lclptr : gmtptr);
1893 for (i = 0; i < sp->typecnt; ++i)
1894 seen[i] = FALSE;
1895 nseen = 0;
1896 for (i = sp->timecnt - 1; i >= 0; --i)
1897 if (!seen[sp->types[i]]) {
1898 seen[sp->types[i]] = TRUE;
1899 types[nseen++] = sp->types[i];
1901 for (sameind = 0; sameind < nseen; ++sameind) {
1902 samei = types[sameind];
1903 if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1904 continue;
1905 for (otherind = 0; otherind < nseen; ++otherind) {
1906 otheri = types[otherind];
1907 if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1908 continue;
1909 tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1910 sp->ttis[samei].tt_gmtoff;
1911 tmp->tm_isdst = !tmp->tm_isdst;
1912 t = time2(tmp, funcp, offset, &okay);
1913 if (okay)
1914 return t;
1915 tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1916 sp->ttis[samei].tt_gmtoff;
1917 tmp->tm_isdst = !tmp->tm_isdst;
1920 return WRONG;
1923 time_t
1924 mktime(struct tm * const tmp)
1926 time_t mktime_return_value;
1927 _RWLOCK_RDLOCK(&lcl_rwlock);
1928 tzset_basic(1);
1929 mktime_return_value = time1(tmp, localsub, 0L);
1930 _RWLOCK_UNLOCK(&lcl_rwlock);
1931 return(mktime_return_value);
1934 time_t
1935 timelocal(struct tm * const tmp)
1937 if (tmp != NULL)
1938 tmp->tm_isdst = -1; /* in case it wasn't initialized */
1939 return mktime(tmp);
1942 time_t
1943 timegm(struct tm * const tmp)
1945 if (tmp != NULL)
1946 tmp->tm_isdst = 0;
1947 return time1(tmp, gmtsub, 0L);
1950 time_t
1951 timeoff(struct tm * const tmp, const long offset)
1953 if (tmp != NULL)
1954 tmp->tm_isdst = 0;
1955 return time1(tmp, gmtsub, offset);
1958 #ifdef CMUCS
1961 ** The following is supplied for compatibility with
1962 ** previous versions of the CMUCS runtime library.
1965 long
1966 gtime(struct tm * const tmp)
1968 const time_t t = mktime(tmp);
1970 if (t == WRONG)
1971 return -1;
1972 return t;
1975 #endif /* defined CMUCS */
1978 ** XXX--is the below the right way to conditionalize??
1982 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
1983 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
1984 ** is not the case if we are accounting for leap seconds.
1985 ** So, we provide the following conversion routines for use
1986 ** when exchanging timestamps with POSIX conforming systems.
1989 static long
1990 leapcorr(time_t *timep)
1992 struct state * sp;
1993 struct lsinfo * lp;
1994 int i;
1996 sp = lclptr;
1997 i = sp->leapcnt;
1998 while (--i >= 0) {
1999 lp = &sp->lsis[i];
2000 if (*timep >= lp->ls_trans)
2001 return lp->ls_corr;
2003 return 0;
2006 time_t
2007 time2posix(time_t t)
2009 tzset();
2010 return t - leapcorr(&t);
2013 time_t
2014 posix2time(time_t t)
2016 time_t x;
2017 time_t y;
2019 tzset();
2021 ** For a positive leap second hit, the result
2022 ** is not unique. For a negative leap second
2023 ** hit, the corresponding time doesn't exist,
2024 ** so we return an adjacent second.
2026 x = t + leapcorr(&t);
2027 y = x - leapcorr(&x);
2028 if (y < t) {
2029 do {
2030 x++;
2031 y = x - leapcorr(&x);
2032 } while (y < t);
2033 if (t != y)
2034 return x - 1;
2035 } else if (y > t) {
2036 do {
2037 --x;
2038 y = x - leapcorr(&x);
2039 } while (y > t);
2040 if (t != y)
2041 return x + 1;
2043 return x;