Don't depend on lcl_mutex being a recursive mutex.
[dragonfly.git] / lib / libc / stdtime / localtime.c
blobb698f0869acf67d99c82340f26f593716b6d3e6b
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.9
6 ** $FreeBSD: src/lib/libc/stdtime/localtime.c,v 1.25.2.2 2002/08/13 16:08:07 bmilekic Exp $
7 ** $DragonFly: src/lib/libc/stdtime/localtime.c,v 1.7 2008/10/19 20:15:58 swildner Exp $
8 */
11 ** Leap second handling from Bradley White.
12 ** POSIX-style TZ environment variable handling from Guy Harris.
15 /*LINTLIBRARY*/
17 #include "namespace.h"
18 #include <sys/types.h>
19 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <float.h> /* for FLT_MAX and DBL_MAX */
23 #include <time.h>
24 #include <pthread.h>
25 #include "private.h"
26 #include <un-namespace.h>
28 #include "tzfile.h"
30 #include "libc_private.h"
32 #define _MUTEX_LOCK(x) if (__isthreaded) _pthread_mutex_lock(x)
33 #define _MUTEX_UNLOCK(x) if (__isthreaded) _pthread_mutex_unlock(x)
35 #ifndef TZ_ABBR_MAX_LEN
36 #define TZ_ABBR_MAX_LEN 16
37 #endif /* !defined TZ_ABBR_MAX_LEN */
39 #ifndef TZ_ABBR_CHAR_SET
40 #define TZ_ABBR_CHAR_SET \
41 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
42 #endif /* !defined TZ_ABBR_CHAR_SET */
44 #ifndef TZ_ABBR_ERR_CHAR
45 #define TZ_ABBR_ERR_CHAR '_'
46 #endif /* !defined TZ_ABBR_ERR_CHAR */
49 ** Someone might make incorrect use of a time zone abbreviation:
50 ** 1. They might reference tzname[0] before calling tzset (explicitly
51 ** or implicitly).
52 ** 2. They might reference tzname[1] before calling tzset (explicitly
53 ** or implicitly).
54 ** 3. They might reference tzname[1] after setting to a time zone
55 ** in which Daylight Saving Time is never observed.
56 ** 4. They might reference tzname[0] after setting to a time zone
57 ** in which Standard Time is never observed.
58 ** 5. They might reference tm.TM_ZONE after calling offtime.
59 ** What's best to do in the above cases is open to debate;
60 ** for now, we just set things up so that in any of the five cases
61 ** WILDABBR is used. Another possibility: initialize tzname[0] to the
62 ** string "tzname[0] used before set", and similarly for the other cases.
63 ** And another: initialize tzname[0] to "ERA", with an explanation in the
64 ** manual page of what this "time zone abbreviation" means (doing this so
65 ** that tzname[0] has the "normal" length of three characters).
67 #define WILDABBR " "
69 static char wildabbr[] = WILDABBR;
71 static const char gmt[] = "UTC";
74 ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
75 ** We default to US rules as of 1999-08-17.
76 ** POSIX 1003.1 section 8.1.1 says that the default DST rules are
77 ** implementation dependent; for historical reasons, US rules are a
78 ** common default.
80 #ifndef TZDEFRULESTRING
81 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
82 #endif /* !defined TZDEFDST */
84 struct ttinfo { /* time type information */
85 long tt_gmtoff; /* UTC offset in seconds */
86 int tt_isdst; /* used to set tm_isdst */
87 int tt_abbrind; /* abbreviation list index */
88 int tt_ttisstd; /* TRUE if transition is std time */
89 int tt_ttisgmt; /* TRUE if transition is UTC */
92 struct lsinfo { /* leap second information */
93 time_t ls_trans; /* transition time */
94 long ls_corr; /* correction to apply */
97 #define BIGGEST(a, b) (((a) > (b)) ? (a) : (b))
99 #ifdef TZNAME_MAX
100 #define MY_TZNAME_MAX TZNAME_MAX
101 #endif /* defined TZNAME_MAX */
102 #ifndef TZNAME_MAX
103 #define MY_TZNAME_MAX 255
104 #endif /* !defined TZNAME_MAX */
106 struct state {
107 int leapcnt;
108 int timecnt;
109 int typecnt;
110 int charcnt;
111 int goback;
112 int goahead;
113 time_t ats[TZ_MAX_TIMES];
114 unsigned char types[TZ_MAX_TIMES];
115 struct ttinfo ttis[TZ_MAX_TYPES];
116 char chars[BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
117 (2 * (MY_TZNAME_MAX + 1)))];
118 struct lsinfo lsis[TZ_MAX_LEAPS];
121 struct rule {
122 int r_type; /* type of rule--see below */
123 int r_day; /* day number of rule */
124 int r_week; /* week number of rule */
125 int r_mon; /* month number of rule */
126 long r_time; /* transition time of rule */
129 #define JULIAN_DAY 0 /* Jn - Julian day */
130 #define DAY_OF_YEAR 1 /* n - day of year */
131 #define MONTH_NTH_DAY_OF_WEEK 2 /* Mm.n.d - month, week, day of week */
134 ** Prototypes for static functions.
137 static long detzcode(const char * codep);
138 static time_t detzcode64(const char * codep);
139 static int differ_by_repeat(time_t t1, time_t t0);
140 static const char * getzname(const char * strp);
141 static const char * getqzname(const char * strp, const int delim);
142 static const char * getnum(const char * strp, int * nump, int min,
143 int max);
144 static const char * getsecs(const char * strp, long * secsp);
145 static const char * getoffset(const char * strp, long * offsetp);
146 static const char * getrule(const char * strp, struct rule * rulep);
147 static void gmtload(struct state * sp);
148 static struct tm * gmtsub(const time_t * timep, long offset,
149 struct tm * tmp);
150 static struct tm * localsub(const time_t * timep, long offset,
151 struct tm * tmp);
152 static int increment_overflow(int * number, int delta);
153 static int leaps_thru_end_of(int y);
154 static int long_increment_overflow(long * number, int delta);
155 static int long_normalize_overflow(long * tensptr,
156 int * unitsptr, int base);
157 static int normalize_overflow(int * tensptr, int * unitsptr,
158 int base);
159 static void settzname(void);
160 static time_t time1(struct tm * tmp,
161 struct tm * (*funcp)(const time_t *,
162 long, struct tm *),
163 long offset);
164 static time_t time2(struct tm *tmp,
165 struct tm * (*funcp)(const time_t *,
166 long, struct tm*),
167 long offset, int * okayp);
168 static time_t time2sub(struct tm *tmp,
169 struct tm * (*funcp)(const time_t *,
170 long, struct tm*),
171 long offset, int * okayp, int do_norm_secs);
172 static struct tm * timesub(const time_t * timep, long offset,
173 const struct state * sp, struct tm * tmp);
174 static int tmcomp(const struct tm * atmp,
175 const struct tm * btmp);
176 static time_t transtime(time_t janfirst, int year,
177 const struct rule * rulep, long offset);
178 static int typesequiv(const struct state * sp, int a, int b);
179 static int tzload(const char * name, struct state * sp,
180 int doextend);
181 static int tzparse(const char * name, struct state * sp,
182 int lastditch);
184 static struct state lclmem;
185 static struct state gmtmem;
186 #define lclptr (&lclmem)
187 #define gmtptr (&gmtmem)
189 #ifndef TZ_STRLEN_MAX
190 #define TZ_STRLEN_MAX 255
191 #endif /* !defined TZ_STRLEN_MAX */
193 static char lcl_TZname[TZ_STRLEN_MAX + 1];
194 static int lcl_is_set;
195 static int gmt_is_set;
196 static pthread_mutex_t lcl_mutex = PTHREAD_MUTEX_INITIALIZER;
197 static pthread_mutex_t gmt_mutex = PTHREAD_MUTEX_INITIALIZER;
199 char * tzname[2] = {
200 wildabbr,
201 wildabbr
205 ** Section 4.12.3 of X3.159-1989 requires that
206 ** Except for the strftime function, these functions [asctime,
207 ** ctime, gmtime, localtime] return values in one of two static
208 ** objects: a broken-down time structure and an array of char.
209 ** Thanks to Paul Eggert for noting this.
212 static struct tm tm;
214 static long
215 detzcode(const char * const codep)
217 long result;
218 int i;
220 result = (codep[0] & 0x80) ? ~0L : 0;
221 for (i = 0; i < 4; ++i)
222 result = (result << 8) | (codep[i] & 0xff);
223 return result;
226 static time_t
227 detzcode64(const char * const codep)
229 time_t result;
230 int i;
232 result = (codep[0] & 0x80) ? (~(int_fast64_t) 0) : 0;
233 for (i = 0; i < 8; ++i)
234 result = result * 256 + (codep[i] & 0xff);
235 return result;
238 static void
239 settzname(void)
241 struct state * const sp = lclptr;
242 int i;
244 tzname[0] = wildabbr;
245 tzname[1] = wildabbr;
247 for (i = 0; i < sp->typecnt; ++i) {
248 const struct ttinfo * const ttisp = &sp->ttis[i];
250 tzname[ttisp->tt_isdst] =
251 &sp->chars[ttisp->tt_abbrind];
254 ** And to get the latest zone names into tzname. . .
256 for (i = 0; i < sp->timecnt; ++i) {
257 const struct ttinfo * const ttisp =
258 &sp->ttis[
259 sp->types[i]];
261 tzname[ttisp->tt_isdst] =
262 &sp->chars[ttisp->tt_abbrind];
265 ** Finally, scrub the abbreviations.
266 ** First, replace bogus characters.
268 for (i = 0; i < sp->charcnt; ++i)
269 if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
270 sp->chars[i] = TZ_ABBR_ERR_CHAR;
272 ** Second, truncate long abbreviations.
274 for (i = 0; i < sp->typecnt; ++i) {
275 const struct ttinfo * const ttisp = &sp->ttis[i];
276 char * cp = &sp->chars[ttisp->tt_abbrind];
278 if (strlen(cp) > TZ_ABBR_MAX_LEN &&
279 strcmp(cp, GRANDPARENTED) != 0)
280 *(cp + TZ_ABBR_MAX_LEN) = '\0';
284 static int
285 differ_by_repeat(const time_t t1, const time_t t0)
287 if (TYPE_INTEGRAL(time_t) &&
288 TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
289 return 0;
290 return t1 - t0 == SECSPERREPEAT;
293 static int
294 tzload(const char *name, struct state * const sp, const int doextend)
296 const char * p;
297 int i;
298 int fid;
299 int stored;
300 int nread;
301 union {
302 struct tzhead tzhead;
303 char buf[2 * sizeof(struct tzhead) +
304 2 * sizeof *sp +
305 4 * TZ_MAX_TIMES];
306 } u;
308 /* XXX The following is from OpenBSD, and I'm not sure it is correct */
309 if (name != NULL && issetugid() != 0)
310 if ((name[0] == ':' && name[1] == '/') ||
311 name[0] == '/' || strchr(name, '.'))
312 name = NULL;
313 if (name == NULL && (name = TZDEFAULT) == NULL)
314 return -1;
316 int doaccess;
317 struct stat stab;
319 ** Section 4.9.1 of the C standard says that
320 ** "FILENAME_MAX expands to an integral constant expression
321 ** that is the size needed for an array of char large enough
322 ** to hold the longest file name string that the implementation
323 ** guarantees can be opened."
325 char fullname[FILENAME_MAX + 1];
327 if (name[0] == ':')
328 ++name;
329 doaccess = name[0] == '/';
330 if (!doaccess) {
331 if ((p = TZDIR) == NULL)
332 return -1;
333 if ((strlen(p) + 1 + strlen(name) + 1) >= sizeof fullname)
334 return -1;
335 strcpy(fullname, p);
336 strcat(fullname, "/");
337 strcat(fullname, name);
339 ** Set doaccess if '.' (as in "../") shows up in name.
341 if (strchr(name, '.') != NULL)
342 doaccess = TRUE;
343 name = fullname;
345 if (doaccess && access(name, R_OK) != 0)
346 return -1;
347 if ((fid = _open(name, O_RDONLY)) == -1)
348 return -1;
349 if ((_fstat(fid, &stab) < 0) || !S_ISREG(stab.st_mode)) {
350 _close(fid);
351 return -1;
354 nread = read(fid, u.buf, sizeof u.buf);
355 if (close(fid) < 0 || nread <= 0)
356 return -1;
357 for (stored = 4; stored <= 8; stored *= 2) {
358 int ttisstdcnt;
359 int ttisgmtcnt;
361 ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
362 ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
363 sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
364 sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
365 sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
366 sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
367 p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
368 if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
369 sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
370 sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
371 sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
372 (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
373 (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
374 return -1;
375 if (nread - (p - u.buf) <
376 sp->timecnt * stored + /* ats */
377 sp->timecnt + /* types */
378 sp->typecnt * 6 + /* ttinfos */
379 sp->charcnt + /* chars */
380 sp->leapcnt * (stored + 4) + /* lsinfos */
381 ttisstdcnt + /* ttisstds */
382 ttisgmtcnt) /* ttisgmts */
383 return -1;
384 for (i = 0; i < sp->timecnt; ++i) {
385 sp->ats[i] = (stored == 4) ?
386 detzcode(p) : detzcode64(p);
387 p += stored;
389 for (i = 0; i < sp->timecnt; ++i) {
390 sp->types[i] = (unsigned char) *p++;
391 if (sp->types[i] >= sp->typecnt)
392 return -1;
394 for (i = 0; i < sp->typecnt; ++i) {
395 struct ttinfo * ttisp;
397 ttisp = &sp->ttis[i];
398 ttisp->tt_gmtoff = detzcode(p);
399 p += 4;
400 ttisp->tt_isdst = (unsigned char) *p++;
401 if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
402 return -1;
403 ttisp->tt_abbrind = (unsigned char) *p++;
404 if (ttisp->tt_abbrind < 0 ||
405 ttisp->tt_abbrind > sp->charcnt)
406 return -1;
408 for (i = 0; i < sp->charcnt; ++i)
409 sp->chars[i] = *p++;
410 sp->chars[i] = '\0'; /* ensure '\0' at end */
411 for (i = 0; i < sp->leapcnt; ++i) {
412 struct lsinfo * lsisp;
414 lsisp = &sp->lsis[i];
415 lsisp->ls_trans = (stored == 4) ?
416 detzcode(p) : detzcode64(p);
417 p += stored;
418 lsisp->ls_corr = detzcode(p);
419 p += 4;
421 for (i = 0; i < sp->typecnt; ++i) {
422 struct ttinfo * ttisp;
424 ttisp = &sp->ttis[i];
425 if (ttisstdcnt == 0)
426 ttisp->tt_ttisstd = FALSE;
427 else {
428 ttisp->tt_ttisstd = *p++;
429 if (ttisp->tt_ttisstd != TRUE &&
430 ttisp->tt_ttisstd != FALSE)
431 return -1;
434 for (i = 0; i < sp->typecnt; ++i) {
435 struct ttinfo * ttisp;
437 ttisp = &sp->ttis[i];
438 if (ttisgmtcnt == 0)
439 ttisp->tt_ttisgmt = FALSE;
440 else {
441 ttisp->tt_ttisgmt = *p++;
442 if (ttisp->tt_ttisgmt != TRUE &&
443 ttisp->tt_ttisgmt != FALSE)
444 return -1;
448 ** Out-of-sort ats should mean we're running on a
449 ** signed time_t system but using a data file with
450 ** unsigned values (or vice versa).
452 for (i = 0; i < sp->timecnt - 2; ++i)
453 if (sp->ats[i] > sp->ats[i + 1]) {
454 ++i;
455 if (TYPE_SIGNED(time_t)) {
457 ** Ignore the end (easy).
459 sp->timecnt = i;
460 } else {
462 ** Ignore the beginning (harder).
464 int j;
466 for (j = 0; j + i < sp->timecnt; ++j) {
467 sp->ats[j] = sp->ats[j + i];
468 sp->types[j] = sp->types[j + i];
470 sp->timecnt = j;
472 break;
475 ** If this is an old file, we're done.
477 if (u.tzhead.tzh_version[0] == '\0')
478 break;
479 nread -= p - u.buf;
480 for (i = 0; i < nread; ++i)
481 u.buf[i] = p[i];
483 ** If this is a narrow integer time_t system, we're done.
485 if (stored >= (int) sizeof(time_t) && TYPE_INTEGRAL(time_t))
486 break;
488 if (doextend && nread > 2 &&
489 u.buf[0] == '\n' && u.buf[nread - 1] == '\n' &&
490 sp->typecnt + 2 <= TZ_MAX_TYPES) {
491 struct state ts;
492 int result;
494 u.buf[nread - 1] = '\0';
495 result = tzparse(&u.buf[1], &ts, FALSE);
496 if (result == 0 && ts.typecnt == 2 &&
497 sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
498 for (i = 0; i < 2; ++i)
499 ts.ttis[i].tt_abbrind +=
500 sp->charcnt;
501 for (i = 0; i < ts.charcnt; ++i)
502 sp->chars[sp->charcnt++] =
503 ts.chars[i];
504 i = 0;
505 while (i < ts.timecnt &&
506 ts.ats[i] <=
507 sp->ats[sp->timecnt - 1])
508 ++i;
509 while (i < ts.timecnt &&
510 sp->timecnt < TZ_MAX_TIMES) {
511 sp->ats[sp->timecnt] =
512 ts.ats[i];
513 sp->types[sp->timecnt] =
514 sp->typecnt +
515 ts.types[i];
516 ++sp->timecnt;
517 ++i;
519 sp->ttis[sp->typecnt++] = ts.ttis[0];
520 sp->ttis[sp->typecnt++] = ts.ttis[1];
523 sp->goback = sp->goahead = FALSE;
524 if (sp->timecnt > 1) {
525 for (i = 1; i < sp->timecnt; ++i)
526 if (typesequiv(sp, sp->types[i], sp->types[0]) &&
527 differ_by_repeat(sp->ats[i], sp->ats[0])) {
528 sp->goback = TRUE;
529 break;
531 for (i = sp->timecnt - 2; i >= 0; --i)
532 if (typesequiv(sp, sp->types[sp->timecnt - 1],
533 sp->types[i]) &&
534 differ_by_repeat(sp->ats[sp->timecnt - 1],
535 sp->ats[i])) {
536 sp->goahead = TRUE;
537 break;
540 return 0;
543 static int
544 typesequiv(const struct state * const sp, const int a, const int b)
546 int result;
548 if (sp == NULL ||
549 a < 0 || a >= sp->typecnt ||
550 b < 0 || b >= sp->typecnt)
551 result = FALSE;
552 else {
553 const struct ttinfo * ap = &sp->ttis[a];
554 const struct ttinfo * bp = &sp->ttis[b];
555 result = ap->tt_gmtoff == bp->tt_gmtoff &&
556 ap->tt_isdst == bp->tt_isdst &&
557 ap->tt_ttisstd == bp->tt_ttisstd &&
558 ap->tt_ttisgmt == bp->tt_ttisgmt &&
559 strcmp(&sp->chars[ap->tt_abbrind],
560 &sp->chars[bp->tt_abbrind]) == 0;
562 return result;
565 static const int mon_lengths[2][MONSPERYEAR] = {
566 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
567 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
570 static const int year_lengths[2] = {
571 DAYSPERNYEAR, DAYSPERLYEAR
575 ** Given a pointer into a time zone string, scan until a character that is not
576 ** a valid character in a zone name is found. Return a pointer to that
577 ** character.
580 static const char *
581 getzname(const char *strp)
583 char c;
585 while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
586 c != '+')
587 ++strp;
588 return strp;
592 ** Given a pointer into an extended time zone string, scan until the ending
593 ** delimiter of the zone name is located. Return a pointer to the delimiter.
595 ** As with getzname above, the legal character set is actually quite
596 ** restricted, with other characters producing undefined results.
597 ** We don't do any checking here; checking is done later in common-case code.
600 static const char *
601 getqzname(const char *strp, const int delim)
603 int c;
605 while ((c = *strp) != '\0' && c != delim)
606 ++strp;
607 return strp;
611 ** Given a pointer into a time zone string, extract a number from that string.
612 ** Check that the number is within a specified range; if it is not, return
613 ** NULL.
614 ** Otherwise, return a pointer to the first character not part of the number.
617 static const char *
618 getnum(const char *strp, int * const nump, const int min, const int max)
620 char c;
621 int num;
623 if (strp == NULL || !is_digit(c = *strp))
624 return NULL;
625 num = 0;
626 do {
627 num = num * 10 + (c - '0');
628 if (num > max)
629 return NULL; /* illegal value */
630 c = *++strp;
631 } while (is_digit(c));
632 if (num < min)
633 return NULL; /* illegal value */
634 *nump = num;
635 return strp;
639 ** Given a pointer into a time zone string, extract a number of seconds,
640 ** in hh[:mm[:ss]] form, from the string.
641 ** If any error occurs, return NULL.
642 ** Otherwise, return a pointer to the first character not part of the number
643 ** of seconds.
646 static const char *
647 getsecs(const char *strp, long * const secsp)
649 int num;
652 ** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
653 ** "M10.4.6/26", which does not conform to Posix,
654 ** but which specifies the equivalent of
655 ** ``02:00 on the first Sunday on or after 23 Oct''.
657 strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
658 if (strp == NULL)
659 return NULL;
660 *secsp = num * (long) SECSPERHOUR;
661 if (*strp == ':') {
662 ++strp;
663 strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
664 if (strp == NULL)
665 return NULL;
666 *secsp += num * SECSPERMIN;
667 if (*strp == ':') {
668 ++strp;
669 /* `SECSPERMIN' allows for leap seconds. */
670 strp = getnum(strp, &num, 0, SECSPERMIN);
671 if (strp == NULL)
672 return NULL;
673 *secsp += num;
676 return strp;
680 ** Given a pointer into a time zone string, extract an offset, in
681 ** [+-]hh[:mm[:ss]] form, from the string.
682 ** If any error occurs, return NULL.
683 ** Otherwise, return a pointer to the first character not part of the time.
686 static const char *
687 getoffset(const char *strp, long * const offsetp)
689 int neg = 0;
691 if (*strp == '-') {
692 neg = 1;
693 ++strp;
694 } else if (*strp == '+')
695 ++strp;
696 strp = getsecs(strp, offsetp);
697 if (strp == NULL)
698 return NULL; /* illegal time */
699 if (neg)
700 *offsetp = -*offsetp;
701 return strp;
705 ** Given a pointer into a time zone string, extract a rule in the form
706 ** date[/time]. See POSIX section 8 for the format of "date" and "time".
707 ** If a valid rule is not found, return NULL.
708 ** Otherwise, return a pointer to the first character not part of the rule.
711 static const char *
712 getrule(const char *strp, struct rule * const rulep)
714 if (*strp == 'J') {
716 ** Julian day.
718 rulep->r_type = JULIAN_DAY;
719 ++strp;
720 strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
721 } else if (*strp == 'M') {
723 ** Month, week, day.
725 rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
726 ++strp;
727 strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
728 if (strp == NULL)
729 return NULL;
730 if (*strp++ != '.')
731 return NULL;
732 strp = getnum(strp, &rulep->r_week, 1, 5);
733 if (strp == NULL)
734 return NULL;
735 if (*strp++ != '.')
736 return NULL;
737 strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
738 } else if (is_digit(*strp)) {
740 ** Day of year.
742 rulep->r_type = DAY_OF_YEAR;
743 strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
744 } else return NULL; /* invalid format */
745 if (strp == NULL)
746 return NULL;
747 if (*strp == '/') {
749 ** Time specified.
751 ++strp;
752 strp = getsecs(strp, &rulep->r_time);
753 } else rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
754 return strp;
758 ** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
759 ** year, a rule, and the offset from UTC at the time that rule takes effect,
760 ** calculate the Epoch-relative time that rule takes effect.
763 static time_t
764 transtime(const time_t janfirst, const int year,
765 const struct rule * const rulep, const long offset)
767 int leapyear;
768 time_t value;
769 int i;
770 int d, m1, yy0, yy1, yy2, dow;
772 INITIALIZE(value);
773 leapyear = isleap(year);
774 switch (rulep->r_type) {
776 case JULIAN_DAY:
778 ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
779 ** years.
780 ** In non-leap years, or if the day number is 59 or less, just
781 ** add SECSPERDAY times the day number-1 to the time of
782 ** January 1, midnight, to get the day.
784 value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
785 if (leapyear && rulep->r_day >= 60)
786 value += SECSPERDAY;
787 break;
789 case DAY_OF_YEAR:
791 ** n - day of year.
792 ** Just add SECSPERDAY times the day number to the time of
793 ** January 1, midnight, to get the day.
795 value = janfirst + rulep->r_day * SECSPERDAY;
796 break;
798 case MONTH_NTH_DAY_OF_WEEK:
800 ** Mm.n.d - nth "dth day" of month m.
802 value = janfirst;
803 for (i = 0; i < rulep->r_mon - 1; ++i)
804 value += mon_lengths[leapyear][i] * SECSPERDAY;
807 ** Use Zeller's Congruence to get day-of-week of first day of
808 ** month.
810 m1 = (rulep->r_mon + 9) % 12 + 1;
811 yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
812 yy1 = yy0 / 100;
813 yy2 = yy0 % 100;
814 dow = ((26 * m1 - 2) / 10 +
815 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
816 if (dow < 0)
817 dow += DAYSPERWEEK;
820 ** "dow" is the day-of-week of the first day of the month. Get
821 ** the day-of-month (zero-origin) of the first "dow" day of the
822 ** month.
824 d = rulep->r_day - dow;
825 if (d < 0)
826 d += DAYSPERWEEK;
827 for (i = 1; i < rulep->r_week; ++i) {
828 if (d + DAYSPERWEEK >=
829 mon_lengths[leapyear][rulep->r_mon - 1])
830 break;
831 d += DAYSPERWEEK;
835 ** "d" is the day-of-month (zero-origin) of the day we want.
837 value += d * SECSPERDAY;
838 break;
842 ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
843 ** question. To get the Epoch-relative time of the specified local
844 ** time on that day, add the transition time and the current offset
845 ** from UTC.
847 return value + rulep->r_time + offset;
851 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
852 ** appropriate.
855 static int
856 tzparse(const char *name, struct state * const sp, const int lastditch)
858 const char * stdname;
859 const char * dstname;
860 size_t stdlen;
861 size_t dstlen;
862 long stdoffset;
863 long dstoffset;
864 time_t * atp;
865 unsigned char * typep;
866 char * cp;
867 int load_result;
869 INITIALIZE(dstname);
870 stdname = name;
871 if (lastditch) {
872 stdlen = strlen(name); /* length of standard zone name */
873 name += stdlen;
874 if (stdlen >= sizeof sp->chars)
875 stdlen = (sizeof sp->chars) - 1;
876 stdoffset = 0;
877 } else {
878 if (*name == '<') {
879 name++;
880 stdname = name;
881 name = getqzname(name, '>');
882 if (*name != '>')
883 return (-1);
884 stdlen = name - stdname;
885 name++;
886 } else {
887 name = getzname(name);
888 stdlen = name - stdname;
890 if (*name == '\0')
891 return -1;
892 name = getoffset(name, &stdoffset);
893 if (name == NULL)
894 return -1;
896 load_result = tzload(TZDEFRULES, sp, FALSE);
897 if (load_result != 0)
898 sp->leapcnt = 0; /* so, we're off a little */
899 if (*name != '\0') {
900 if (*name == '<') {
901 dstname = ++name;
902 name = getqzname(name, '>');
903 if (*name != '>')
904 return -1;
905 dstlen = name - dstname;
906 name++;
907 } else {
908 dstname = name;
909 name = getzname(name);
910 dstlen = name - dstname; /* length of DST zone name */
912 if (*name != '\0' && *name != ',' && *name != ';') {
913 name = getoffset(name, &dstoffset);
914 if (name == NULL)
915 return -1;
916 } else dstoffset = stdoffset - SECSPERHOUR;
917 if (*name == '\0' && load_result != 0)
918 name = TZDEFRULESTRING;
919 if (*name == ',' || *name == ';') {
920 struct rule start;
921 struct rule end;
922 int year;
923 time_t janfirst;
924 time_t starttime;
925 time_t endtime;
927 ++name;
928 if ((name = getrule(name, &start)) == NULL)
929 return -1;
930 if (*name++ != ',')
931 return -1;
932 if ((name = getrule(name, &end)) == NULL)
933 return -1;
934 if (*name != '\0')
935 return -1;
936 sp->typecnt = 2; /* standard time and DST */
938 ** Two transitions per year, from EPOCH_YEAR forward.
940 sp->ttis[0].tt_gmtoff = -dstoffset;
941 sp->ttis[0].tt_isdst = 1;
942 sp->ttis[0].tt_abbrind = stdlen + 1;
943 sp->ttis[1].tt_gmtoff = -stdoffset;
944 sp->ttis[1].tt_isdst = 0;
945 sp->ttis[1].tt_abbrind = 0;
946 atp = sp->ats;
947 typep = sp->types;
948 janfirst = 0;
949 sp->timecnt = 0;
950 for (year = EPOCH_YEAR;
951 sp->timecnt + 2 <= TZ_MAX_TIMES;
952 ++year) {
953 time_t newfirst;
955 starttime = transtime(janfirst, year, &start,
956 stdoffset);
957 endtime = transtime(janfirst, year, &end,
958 dstoffset);
959 if (starttime > endtime) {
960 *atp++ = endtime;
961 *typep++ = 1; /* DST ends */
962 *atp++ = starttime;
963 *typep++ = 0; /* DST begins */
964 } else {
965 *atp++ = starttime;
966 *typep++ = 0; /* DST begins */
967 *atp++ = endtime;
968 *typep++ = 1; /* DST ends */
970 sp->timecnt += 2;
971 newfirst = janfirst;
972 newfirst += year_lengths[isleap(year)] *
973 SECSPERDAY;
974 if (newfirst <= janfirst)
975 break;
976 janfirst = newfirst;
978 } else {
979 long theirstdoffset;
980 long theirdstoffset;
981 long theiroffset;
982 int isdst;
983 int i;
984 int j;
986 if (*name != '\0')
987 return -1;
989 ** Initial values of theirstdoffset and theirdstoffset.
991 theirstdoffset = 0;
992 for (i = 0; i < sp->timecnt; ++i) {
993 j = sp->types[i];
994 if (!sp->ttis[j].tt_isdst) {
995 theirstdoffset =
996 -sp->ttis[j].tt_gmtoff;
997 break;
1000 theirdstoffset = 0;
1001 for (i = 0; i < sp->timecnt; ++i) {
1002 j = sp->types[i];
1003 if (sp->ttis[j].tt_isdst) {
1004 theirdstoffset =
1005 -sp->ttis[j].tt_gmtoff;
1006 break;
1010 ** Initially we're assumed to be in standard time.
1012 isdst = FALSE;
1013 theiroffset = theirstdoffset;
1015 ** Now juggle transition times and types
1016 ** tracking offsets as you do.
1018 for (i = 0; i < sp->timecnt; ++i) {
1019 j = sp->types[i];
1020 sp->types[i] = sp->ttis[j].tt_isdst;
1021 if (sp->ttis[j].tt_ttisgmt) {
1022 /* No adjustment to transition time */
1023 } else {
1025 ** If summer time is in effect, and the
1026 ** transition time was not specified as
1027 ** standard time, add the summer time
1028 ** offset to the transition time;
1029 ** otherwise, add the standard time
1030 ** offset to the transition time.
1033 ** Transitions from DST to DDST
1034 ** will effectively disappear since
1035 ** POSIX provides for only one DST
1036 ** offset.
1038 if (isdst && !sp->ttis[j].tt_ttisstd) {
1039 sp->ats[i] += dstoffset -
1040 theirdstoffset;
1041 } else {
1042 sp->ats[i] += stdoffset -
1043 theirstdoffset;
1046 theiroffset = -sp->ttis[j].tt_gmtoff;
1047 if (sp->ttis[j].tt_isdst)
1048 theirdstoffset = theiroffset;
1049 else theirstdoffset = theiroffset;
1052 ** Finally, fill in ttis.
1053 ** ttisstd and ttisgmt need not be handled.
1055 sp->ttis[0].tt_gmtoff = -stdoffset;
1056 sp->ttis[0].tt_isdst = FALSE;
1057 sp->ttis[0].tt_abbrind = 0;
1058 sp->ttis[1].tt_gmtoff = -dstoffset;
1059 sp->ttis[1].tt_isdst = TRUE;
1060 sp->ttis[1].tt_abbrind = stdlen + 1;
1061 sp->typecnt = 2;
1063 } else {
1064 dstlen = 0;
1065 sp->typecnt = 1; /* only standard time */
1066 sp->timecnt = 0;
1067 sp->ttis[0].tt_gmtoff = -stdoffset;
1068 sp->ttis[0].tt_isdst = 0;
1069 sp->ttis[0].tt_abbrind = 0;
1071 sp->charcnt = stdlen + 1;
1072 if (dstlen != 0)
1073 sp->charcnt += dstlen + 1;
1074 if ((size_t) sp->charcnt > sizeof sp->chars)
1075 return -1;
1076 cp = sp->chars;
1077 strncpy(cp, stdname, stdlen);
1078 cp += stdlen;
1079 *cp++ = '\0';
1080 if (dstlen != 0) {
1081 strncpy(cp, dstname, dstlen);
1082 *(cp + dstlen) = '\0';
1084 return 0;
1087 static void
1088 gmtload(struct state * const sp)
1090 if (tzload(gmt, sp, TRUE) != 0)
1091 tzparse(gmt, sp, TRUE);
1094 static void
1095 tzsetwall_basic(void)
1097 if (lcl_is_set < 0)
1098 return;
1099 lcl_is_set = -1;
1101 if (tzload((char *) NULL, lclptr, TRUE) != 0)
1102 gmtload(lclptr);
1103 settzname();
1106 void
1107 tzsetwall(void)
1109 _MUTEX_LOCK(&lcl_mutex);
1110 tzsetwall_basic();
1111 _MUTEX_UNLOCK(&lcl_mutex);
1114 static void
1115 tzset_basic(void)
1117 const char * name;
1119 name = getenv("TZ");
1120 if (name == NULL) {
1121 tzsetwall_basic();
1122 return;
1125 if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
1126 return;
1127 lcl_is_set = strlen(name) < sizeof lcl_TZname;
1128 if (lcl_is_set)
1129 strcpy(lcl_TZname, name);
1131 if (*name == '\0') {
1133 ** User wants it fast rather than right.
1135 lclptr->leapcnt = 0; /* so, we're off a little */
1136 lclptr->timecnt = 0;
1137 lclptr->typecnt = 0;
1138 lclptr->ttis[0].tt_isdst = 0;
1139 lclptr->ttis[0].tt_gmtoff = 0;
1140 lclptr->ttis[0].tt_abbrind = 0;
1141 strcpy(lclptr->chars, gmt);
1142 } else if (tzload(name, lclptr, TRUE) != 0)
1143 if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
1144 gmtload(lclptr);
1145 settzname();
1148 void
1149 tzset(void)
1151 _MUTEX_LOCK(&lcl_mutex);
1152 tzset_basic();
1153 _MUTEX_UNLOCK(&lcl_mutex);
1157 ** The easy way to behave "as if no library function calls" localtime
1158 ** is to not call it--so we drop its guts into "localsub", which can be
1159 ** freely called. (And no, the PANS doesn't require the above behavior--
1160 ** but it *is* desirable.)
1162 ** The unused offset argument is for the benefit of mktime variants.
1165 /*ARGSUSED*/
1166 static struct tm *
1167 localsub(const time_t * const timep, const long offset __unused,
1168 struct tm * const tmp)
1170 struct state * sp;
1171 const struct ttinfo * ttisp;
1172 int i;
1173 struct tm * result;
1174 const time_t t = *timep;
1176 sp = lclptr;
1178 if ((sp->goback && t < sp->ats[0]) ||
1179 (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1180 time_t newt = t;
1181 time_t seconds;
1182 time_t tcycles;
1183 int_fast64_t icycles;
1185 if (t < sp->ats[0])
1186 seconds = sp->ats[0] - t;
1187 else seconds = t - sp->ats[sp->timecnt - 1];
1188 --seconds;
1189 tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1190 ++tcycles;
1191 icycles = tcycles;
1192 if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1193 return NULL;
1194 seconds = icycles;
1195 seconds *= YEARSPERREPEAT;
1196 seconds *= AVGSECSPERYEAR;
1197 if (t < sp->ats[0])
1198 newt += seconds;
1199 else newt -= seconds;
1200 if (newt < sp->ats[0] ||
1201 newt > sp->ats[sp->timecnt - 1])
1202 return NULL; /* "cannot happen" */
1203 result = localsub(&newt, offset, tmp);
1204 if (result == tmp) {
1205 time_t newy;
1207 newy = tmp->tm_year;
1208 if (t < sp->ats[0])
1209 newy -= icycles * YEARSPERREPEAT;
1210 else newy += icycles * YEARSPERREPEAT;
1211 tmp->tm_year = newy;
1212 if (tmp->tm_year != newy)
1213 return NULL;
1215 return result;
1217 if (sp->timecnt == 0 || t < sp->ats[0]) {
1218 i = 0;
1219 while (sp->ttis[i].tt_isdst)
1220 if (++i >= sp->typecnt) {
1221 i = 0;
1222 break;
1224 } else {
1225 int lo = 1;
1226 int hi = sp->timecnt;
1228 while (lo < hi) {
1229 int mid = (lo + hi) >> 1;
1231 if (t < sp->ats[mid])
1232 hi = mid;
1233 else lo = mid + 1;
1235 i = (int) sp->types[lo - 1];
1237 ttisp = &sp->ttis[i];
1239 ** To get (wrong) behavior that's compatible with System V Release 2.0
1240 ** you'd replace the statement below with
1241 ** t += ttisp->tt_gmtoff;
1242 ** timesub(&t, 0L, sp, tmp);
1244 result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1245 tmp->tm_isdst = ttisp->tt_isdst;
1246 tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1247 #ifdef TM_ZONE
1248 tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1249 #endif /* defined TM_ZONE */
1250 return result;
1253 struct tm *
1254 localtime_r(const time_t * const timep, struct tm *p_tm)
1256 _MUTEX_LOCK(&lcl_mutex);
1257 tzset_basic();
1258 localsub(timep, 0L, p_tm);
1259 _MUTEX_UNLOCK(&lcl_mutex);
1260 return(p_tm);
1263 struct tm *
1264 localtime(const time_t * const timep)
1266 static pthread_mutex_t localtime_mutex = PTHREAD_MUTEX_INITIALIZER;
1267 static pthread_key_t localtime_key = -1;
1268 struct tm *p_tm;
1270 if (__isthreaded != 0) {
1271 _pthread_mutex_lock(&localtime_mutex);
1272 if (localtime_key < 0) {
1273 if (_pthread_key_create(&localtime_key, free) < 0) {
1274 _pthread_mutex_unlock(&localtime_mutex);
1275 return(NULL);
1278 _pthread_mutex_unlock(&localtime_mutex);
1279 p_tm = _pthread_getspecific(localtime_key);
1280 if (p_tm == NULL) {
1281 if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1282 == NULL)
1283 return(NULL);
1284 _pthread_setspecific(localtime_key, p_tm);
1286 _pthread_mutex_lock(&lcl_mutex);
1287 tzset_basic();
1288 localsub(timep, 0L, p_tm);
1289 _pthread_mutex_unlock(&lcl_mutex);
1290 return(p_tm);
1291 } else {
1292 tzset_basic();
1293 localsub(timep, 0L, &tm);
1294 return(&tm);
1299 ** gmtsub is to gmtime as localsub is to localtime.
1302 static struct tm *
1303 gmtsub(const time_t * const timep, const long offset, struct tm * const tmp)
1305 struct tm * result;
1307 _MUTEX_LOCK(&gmt_mutex);
1308 if (!gmt_is_set) {
1309 gmt_is_set = TRUE;
1310 gmtload(gmtptr);
1312 _MUTEX_UNLOCK(&gmt_mutex);
1313 result = timesub(timep, offset, gmtptr, tmp);
1314 #ifdef TM_ZONE
1316 ** Could get fancy here and deliver something such as
1317 ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1318 ** but this is no time for a treasure hunt.
1320 if (offset != 0)
1321 tmp->TM_ZONE = wildabbr;
1322 else
1323 tmp->TM_ZONE = gmtptr->chars;
1324 #endif /* defined TM_ZONE */
1325 return result;
1328 struct tm *
1329 gmtime(const time_t * const timep)
1331 static pthread_mutex_t gmtime_mutex = PTHREAD_MUTEX_INITIALIZER;
1332 static pthread_key_t gmtime_key = -1;
1333 struct tm *p_tm;
1335 if (__isthreaded != 0) {
1336 _pthread_mutex_lock(&gmtime_mutex);
1337 if (gmtime_key < 0) {
1338 if (_pthread_key_create(&gmtime_key, free) < 0) {
1339 _pthread_mutex_unlock(&gmtime_mutex);
1340 return(NULL);
1343 _pthread_mutex_unlock(&gmtime_mutex);
1345 * Changed to follow POSIX.1 threads standard, which
1346 * is what BSD currently has.
1348 if ((p_tm = _pthread_getspecific(gmtime_key)) == NULL) {
1349 if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1350 == NULL) {
1351 return(NULL);
1353 _pthread_setspecific(gmtime_key, p_tm);
1355 return gmtsub(timep, 0L, p_tm);
1356 } else {
1357 return gmtsub(timep, 0L, &tm);
1361 struct tm *
1362 gmtime_r(const time_t * timep, struct tm * tmp)
1364 return gmtsub(timep, 0L, tmp);
1367 struct tm *
1368 offtime(const time_t * const timep, const long offset)
1370 return gmtsub(timep, offset, &tm);
1374 ** Return the number of leap years through the end of the given year
1375 ** where, to make the math easy, the answer for year zero is defined as zero.
1378 static int
1379 leaps_thru_end_of(const int y)
1381 return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1382 -(leaps_thru_end_of(-(y + 1)) + 1);
1385 static struct tm *
1386 timesub(const time_t * const timep, const long offset,
1387 const struct state * const sp, struct tm * const tmp)
1389 const struct lsinfo * lp;
1390 time_t tdays;
1391 int idays; /* unsigned would be so 2003 */
1392 long rem;
1393 int y;
1394 int yleap;
1395 const int * ip;
1396 long corr;
1397 int hit;
1398 int i;
1400 corr = 0;
1401 hit = 0;
1402 i = sp->leapcnt;
1404 while (--i >= 0) {
1405 lp = &sp->lsis[i];
1406 if (*timep >= lp->ls_trans) {
1407 if (*timep == lp->ls_trans) {
1408 hit = ((i == 0 && lp->ls_corr > 0) ||
1409 lp->ls_corr > sp->lsis[i - 1].ls_corr);
1410 if (hit)
1411 while (i > 0 &&
1412 sp->lsis[i].ls_trans ==
1413 sp->lsis[i - 1].ls_trans + 1 &&
1414 sp->lsis[i].ls_corr ==
1415 sp->lsis[i - 1].ls_corr + 1) {
1416 ++hit;
1417 --i;
1420 corr = lp->ls_corr;
1421 break;
1424 y = EPOCH_YEAR;
1425 tdays = *timep / SECSPERDAY;
1426 rem = *timep - tdays * SECSPERDAY;
1427 while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
1428 int newy;
1429 time_t tdelta;
1430 int idelta;
1431 int leapdays;
1433 tdelta = tdays / DAYSPERLYEAR;
1434 idelta = tdelta;
1435 if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
1436 return NULL;
1437 if (idelta == 0)
1438 idelta = (tdays < 0) ? -1 : 1;
1439 newy = y;
1440 if (increment_overflow(&newy, idelta))
1441 return NULL;
1442 leapdays = leaps_thru_end_of(newy - 1) -
1443 leaps_thru_end_of(y - 1);
1444 tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
1445 tdays -= leapdays;
1446 y = newy;
1449 long seconds;
1451 seconds = tdays * SECSPERDAY + 0.5;
1452 tdays = seconds / SECSPERDAY;
1453 rem += seconds - tdays * SECSPERDAY;
1456 ** Given the range, we can now fearlessly cast...
1458 idays = tdays;
1459 rem += offset - corr;
1460 while (rem < 0) {
1461 rem += SECSPERDAY;
1462 --idays;
1464 while (rem >= SECSPERDAY) {
1465 rem -= SECSPERDAY;
1466 ++idays;
1468 while (idays < 0) {
1469 if (increment_overflow(&y, -1))
1470 return NULL;
1471 idays += year_lengths[isleap(y)];
1473 while (idays >= year_lengths[isleap(y)]) {
1474 idays -= year_lengths[isleap(y)];
1475 if (increment_overflow(&y, 1))
1476 return NULL;
1478 tmp->tm_year = y;
1479 if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
1480 return NULL;
1481 tmp->tm_yday = idays;
1483 ** The "extra" mods below avoid overflow problems.
1485 tmp->tm_wday = EPOCH_WDAY +
1486 ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1487 (DAYSPERNYEAR % DAYSPERWEEK) +
1488 leaps_thru_end_of(y - 1) -
1489 leaps_thru_end_of(EPOCH_YEAR - 1) +
1490 idays;
1491 tmp->tm_wday %= DAYSPERWEEK;
1492 if (tmp->tm_wday < 0)
1493 tmp->tm_wday += DAYSPERWEEK;
1494 tmp->tm_hour = (int) (rem / SECSPERHOUR);
1495 rem %= SECSPERHOUR;
1496 tmp->tm_min = (int) (rem / SECSPERMIN);
1498 ** A positive leap second requires a special
1499 ** representation. This uses "... ??:59:60" et seq.
1501 tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1502 ip = mon_lengths[isleap(y)];
1503 for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1504 idays -= ip[tmp->tm_mon];
1505 tmp->tm_mday = (int) (idays + 1);
1506 tmp->tm_isdst = 0;
1507 #ifdef TM_GMTOFF
1508 tmp->TM_GMTOFF = offset;
1509 #endif /* defined TM_GMTOFF */
1510 return tmp;
1513 char *
1514 ctime(const time_t * const timep)
1517 ** Section 4.12.3.2 of X3.159-1989 requires that
1518 ** The ctime function converts the calendar time pointed to by timer
1519 ** to local time in the form of a string. It is equivalent to
1520 ** asctime(localtime(timer))
1522 return asctime(localtime(timep));
1525 char *
1526 ctime_r(const time_t * const timep, char *buf)
1528 struct tm mytm;
1529 return asctime_r(localtime_r(timep, &mytm), buf);
1533 ** Adapted from code provided by Robert Elz, who writes:
1534 ** The "best" way to do mktime I think is based on an idea of Bob
1535 ** Kridle's (so its said...) from a long time ago.
1536 ** It does a binary search of the time_t space. Since time_t's are
1537 ** just 32 bits, its a max of 32 iterations (even at 64 bits it
1538 ** would still be very reasonable).
1541 #ifndef WRONG
1542 #define WRONG (-1)
1543 #endif /* !defined WRONG */
1546 ** Simplified normalize logic courtesy Paul Eggert.
1549 static int
1550 increment_overflow(int *number, int delta)
1552 int number0;
1554 number0 = *number;
1555 *number += delta;
1556 return (*number < number0) != (delta < 0);
1559 static int
1560 long_increment_overflow(long *number, int delta)
1562 long number0;
1564 number0 = *number;
1565 *number += delta;
1566 return (*number < number0) != (delta < 0);
1569 static int
1570 normalize_overflow(int * const tensptr, int * const unitsptr, const int base)
1572 int tensdelta;
1574 tensdelta = (*unitsptr >= 0) ?
1575 (*unitsptr / base) :
1576 (-1 - (-1 - *unitsptr) / base);
1577 *unitsptr -= tensdelta * base;
1578 return increment_overflow(tensptr, tensdelta);
1581 static int
1582 long_normalize_overflow(long * const tensptr, int * const unitsptr,
1583 const int base)
1585 int tensdelta;
1587 tensdelta = (*unitsptr >= 0) ?
1588 (*unitsptr / base) :
1589 (-1 - (-1 - *unitsptr) / base);
1590 *unitsptr -= tensdelta * base;
1591 return long_increment_overflow(tensptr, tensdelta);
1594 static int
1595 tmcomp(const struct tm * const atmp, const struct tm * const btmp)
1597 int result;
1599 if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1600 (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1601 (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1602 (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1603 (result = (atmp->tm_min - btmp->tm_min)) == 0)
1604 result = atmp->tm_sec - btmp->tm_sec;
1605 return result;
1608 static time_t
1609 time2sub(struct tm * const tmp,
1610 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1611 const long offset, int * const okayp, const int do_norm_secs)
1613 const struct state * sp;
1614 int dir;
1615 int i, j;
1616 int saved_seconds;
1617 long li;
1618 time_t lo;
1619 time_t hi;
1620 long y;
1621 time_t newt;
1622 time_t t;
1623 struct tm yourtm, mytm;
1625 *okayp = FALSE;
1626 yourtm = *tmp;
1627 if (do_norm_secs) {
1628 if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1629 SECSPERMIN))
1630 return WRONG;
1632 if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1633 return WRONG;
1634 if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1635 return WRONG;
1636 y = yourtm.tm_year;
1637 if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
1638 return WRONG;
1640 ** Turn y into an actual year number for now.
1641 ** It is converted back to an offset from TM_YEAR_BASE later.
1643 if (long_increment_overflow(&y, TM_YEAR_BASE))
1644 return WRONG;
1645 while (yourtm.tm_mday <= 0) {
1646 if (long_increment_overflow(&y, -1))
1647 return WRONG;
1648 li = y + (1 < yourtm.tm_mon);
1649 yourtm.tm_mday += year_lengths[isleap(li)];
1651 while (yourtm.tm_mday > DAYSPERLYEAR) {
1652 li = y + (1 < yourtm.tm_mon);
1653 yourtm.tm_mday -= year_lengths[isleap(li)];
1654 if (long_increment_overflow(&y, 1))
1655 return WRONG;
1657 for ( ; ; ) {
1658 i = mon_lengths[isleap(y)][yourtm.tm_mon];
1659 if (yourtm.tm_mday <= i)
1660 break;
1661 yourtm.tm_mday -= i;
1662 if (++yourtm.tm_mon >= MONSPERYEAR) {
1663 yourtm.tm_mon = 0;
1664 if (long_increment_overflow(&y, 1))
1665 return WRONG;
1668 if (long_increment_overflow(&y, -TM_YEAR_BASE))
1669 return WRONG;
1670 yourtm.tm_year = y;
1671 if (yourtm.tm_year != y)
1672 return WRONG;
1673 if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1674 saved_seconds = 0;
1675 else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
1677 ** We can't set tm_sec to 0, because that might push the
1678 ** time below the minimum representable time.
1679 ** Set tm_sec to 59 instead.
1680 ** This assumes that the minimum representable time is
1681 ** not in the same minute that a leap second was deleted from,
1682 ** which is a safer assumption than using 58 would be.
1684 if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1685 return WRONG;
1686 saved_seconds = yourtm.tm_sec;
1687 yourtm.tm_sec = SECSPERMIN - 1;
1688 } else {
1689 saved_seconds = yourtm.tm_sec;
1690 yourtm.tm_sec = 0;
1693 ** Do a binary search (this works whatever time_t's type is).
1695 if (!TYPE_SIGNED(time_t)) {
1696 lo = 0;
1697 hi = lo - 1;
1698 } else if (!TYPE_INTEGRAL(time_t)) {
1699 if (sizeof(time_t) > sizeof(float))
1700 hi = (time_t) DBL_MAX;
1701 else hi = (time_t) FLT_MAX;
1702 lo = -hi;
1703 } else {
1704 lo = 1;
1705 for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
1706 lo *= 2;
1707 hi = -(lo + 1);
1709 for ( ; ; ) {
1710 t = lo / 2 + hi / 2;
1711 if (t < lo)
1712 t = lo;
1713 else if (t > hi)
1714 t = hi;
1715 if ((*funcp)(&t, offset, &mytm) == NULL) {
1717 ** Assume that t is too extreme to be represented in
1718 ** a struct tm; arrange things so that it is less
1719 ** extreme on the next pass.
1721 dir = (t > 0) ? 1 : -1;
1722 } else dir = tmcomp(&mytm, &yourtm);
1723 if (dir != 0) {
1724 if (t == lo) {
1725 ++t;
1726 if (t <= lo)
1727 return WRONG;
1728 ++lo;
1729 } else if (t == hi) {
1730 --t;
1731 if (t >= hi)
1732 return WRONG;
1733 --hi;
1735 if (lo > hi)
1736 return WRONG;
1737 if (dir > 0)
1738 hi = t;
1739 else lo = t;
1740 continue;
1742 if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1743 break;
1745 ** Right time, wrong type.
1746 ** Hunt for right time, right type.
1747 ** It's okay to guess wrong since the guess
1748 ** gets checked.
1750 sp = (const struct state *)
1751 ((funcp == localsub) ? lclptr : gmtptr);
1753 for (i = sp->typecnt - 1; i >= 0; --i) {
1754 if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1755 continue;
1756 for (j = sp->typecnt - 1; j >= 0; --j) {
1757 if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1758 continue;
1759 newt = t + sp->ttis[j].tt_gmtoff -
1760 sp->ttis[i].tt_gmtoff;
1761 if ((*funcp)(&newt, offset, &mytm) == NULL)
1762 continue;
1763 if (tmcomp(&mytm, &yourtm) != 0)
1764 continue;
1765 if (mytm.tm_isdst != yourtm.tm_isdst)
1766 continue;
1768 ** We have a match.
1770 t = newt;
1771 goto label;
1774 return WRONG;
1776 label:
1777 newt = t + saved_seconds;
1778 if ((newt < t) != (saved_seconds < 0))
1779 return WRONG;
1780 t = newt;
1781 if ((*funcp)(&t, offset, tmp))
1782 *okayp = TRUE;
1783 return t;
1786 static time_t
1787 time2(struct tm * const tmp,
1788 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1789 const long offset, int * const okayp)
1791 time_t t;
1794 ** First try without normalization of seconds
1795 ** (in case tm_sec contains a value associated with a leap second).
1796 ** If that fails, try with normalization of seconds.
1798 t = time2sub(tmp, funcp, offset, okayp, FALSE);
1799 return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE);
1802 static time_t
1803 time1(struct tm * const tmp,
1804 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1805 const long offset)
1807 time_t t;
1808 const struct state * sp;
1809 int samei, otheri;
1810 int sameind, otherind;
1811 int i;
1812 int nseen;
1813 int seen[TZ_MAX_TYPES];
1814 int types[TZ_MAX_TYPES];
1815 int okay;
1817 if (tmp->tm_isdst > 1)
1818 tmp->tm_isdst = 1;
1819 t = time2(tmp, funcp, offset, &okay);
1822 ** PCTS code courtesy Grant Sullivan.
1824 if (okay)
1825 return t;
1826 if (tmp->tm_isdst < 0)
1827 tmp->tm_isdst = 0; /* reset to std and try again */
1830 ** We're supposed to assume that somebody took a time of one type
1831 ** and did some math on it that yielded a "struct tm" that's bad.
1832 ** We try to divine the type they started from and adjust to the
1833 ** type they need.
1835 sp = (const struct state *) ((funcp == localsub) ? lclptr : gmtptr);
1837 for (i = 0; i < sp->typecnt; ++i)
1838 seen[i] = FALSE;
1839 nseen = 0;
1840 for (i = sp->timecnt - 1; i >= 0; --i)
1841 if (!seen[sp->types[i]]) {
1842 seen[sp->types[i]] = TRUE;
1843 types[nseen++] = sp->types[i];
1845 for (sameind = 0; sameind < nseen; ++sameind) {
1846 samei = types[sameind];
1847 if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1848 continue;
1849 for (otherind = 0; otherind < nseen; ++otherind) {
1850 otheri = types[otherind];
1851 if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1852 continue;
1853 tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1854 sp->ttis[samei].tt_gmtoff;
1855 tmp->tm_isdst = !tmp->tm_isdst;
1856 t = time2(tmp, funcp, offset, &okay);
1857 if (okay)
1858 return t;
1859 tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1860 sp->ttis[samei].tt_gmtoff;
1861 tmp->tm_isdst = !tmp->tm_isdst;
1864 return WRONG;
1867 time_t
1868 mktime(struct tm * const tmp)
1870 time_t mktime_return_value;
1871 _MUTEX_LOCK(&lcl_mutex);
1872 tzset_basic();
1873 mktime_return_value = time1(tmp, localsub, 0L);
1874 _MUTEX_UNLOCK(&lcl_mutex);
1875 return(mktime_return_value);
1878 time_t
1879 timelocal(struct tm * const tmp)
1881 tmp->tm_isdst = -1; /* in case it wasn't initialized */
1882 return mktime(tmp);
1885 time_t
1886 timegm(struct tm * const tmp)
1888 tmp->tm_isdst = 0;
1889 return time1(tmp, gmtsub, 0L);
1892 time_t
1893 timeoff(struct tm * const tmp, const long offset)
1895 tmp->tm_isdst = 0;
1896 return time1(tmp, gmtsub, offset);
1899 #ifdef CMUCS
1902 ** The following is supplied for compatibility with
1903 ** previous versions of the CMUCS runtime library.
1906 long
1907 gtime(struct tm * const tmp)
1909 const time_t t = mktime(tmp);
1911 if (t == WRONG)
1912 return -1;
1913 return t;
1916 #endif /* defined CMUCS */
1919 ** XXX--is the below the right way to conditionalize??
1923 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
1924 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
1925 ** is not the case if we are accounting for leap seconds.
1926 ** So, we provide the following conversion routines for use
1927 ** when exchanging timestamps with POSIX conforming systems.
1930 static long
1931 leapcorr(time_t *timep)
1933 struct state * sp;
1934 struct lsinfo * lp;
1935 int i;
1937 sp = lclptr;
1938 i = sp->leapcnt;
1939 while (--i >= 0) {
1940 lp = &sp->lsis[i];
1941 if (*timep >= lp->ls_trans)
1942 return lp->ls_corr;
1944 return 0;
1947 time_t
1948 time2posix(time_t t)
1950 tzset();
1951 return t - leapcorr(&t);
1954 time_t
1955 posix2time(time_t t)
1957 time_t x;
1958 time_t y;
1960 tzset();
1962 ** For a positive leap second hit, the result
1963 ** is not unique. For a negative leap second
1964 ** hit, the corresponding time doesn't exist,
1965 ** so we return an adjacent second.
1967 x = t + leapcorr(&t);
1968 y = x - leapcorr(&x);
1969 if (y < t) {
1970 do {
1971 x++;
1972 y = x - leapcorr(&x);
1973 } while (y < t);
1974 if (t != y)
1975 return x - 1;
1976 } else if (y > t) {
1977 do {
1978 --x;
1979 y = x - leapcorr(&x);
1980 } while (y > t);
1981 if (t != y)
1982 return x + 1;
1984 return x;