localtime.c revision 1.84 1 /* $NetBSD: localtime.c,v 1.84 2014/08/15 13:20:29 martin Exp $ */
2
3 /*
4 ** This file is in the public domain, so clarified as of
5 ** 1996-06-05 by Arthur David Olson.
6 */
7
8 #include <sys/cdefs.h>
9 #if defined(LIBC_SCCS) && !defined(lint)
10 #if 0
11 static char elsieid[] = "@(#)localtime.c 8.17";
12 #else
13 __RCSID("$NetBSD: localtime.c,v 1.84 2014/08/15 13:20:29 martin Exp $");
14 #endif
15 #endif /* LIBC_SCCS and not lint */
16
17 /*
18 ** Leap second handling from Bradley White.
19 ** POSIX-style TZ environment variable handling from Guy Harris.
20 */
21
22 /*LINTLIBRARY*/
23
24 #include "namespace.h"
25 #include <assert.h>
26 #include "private.h"
27 #include "tzfile.h"
28 #include "fcntl.h"
29 #include "reentrant.h"
30
31 #if defined(__weak_alias)
32 __weak_alias(daylight,_daylight)
33 __weak_alias(tzname,_tzname)
34 #endif
35
36 #ifndef TZ_ABBR_MAX_LEN
37 #define TZ_ABBR_MAX_LEN 16
38 #endif /* !defined TZ_ABBR_MAX_LEN */
39
40 #ifndef TZ_ABBR_CHAR_SET
41 #define TZ_ABBR_CHAR_SET \
42 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
43 #endif /* !defined TZ_ABBR_CHAR_SET */
44
45 #ifndef TZ_ABBR_ERR_CHAR
46 #define TZ_ABBR_ERR_CHAR '_'
47 #endif /* !defined TZ_ABBR_ERR_CHAR */
48
49 /* The minimum and maximum finite time values. */
50 static time_t const time_t_min =
51 (TYPE_SIGNED(time_t)
52 ? (time_t) -1 << (int)(CHAR_BIT * sizeof (time_t) - 1)
53 : 0);
54 static time_t const time_t_max =
55 (TYPE_SIGNED(time_t)
56 ? - (~ 0 < 0) - ((time_t) -1 << (int)(CHAR_BIT * sizeof (time_t) - 1))
57 : -1);
58
59 /*
60 ** SunOS 4.1.1 headers lack O_BINARY.
61 */
62
63 #ifdef O_BINARY
64 #define OPEN_MODE (O_RDONLY | O_BINARY)
65 #endif /* defined O_BINARY */
66 #ifndef O_BINARY
67 #define OPEN_MODE O_RDONLY
68 #endif /* !defined O_BINARY */
69
70 #ifndef WILDABBR
71 /*
72 ** Someone might make incorrect use of a time zone abbreviation:
73 ** 1. They might reference tzname[0] before calling tzset (explicitly
74 ** or implicitly).
75 ** 2. They might reference tzname[1] before calling tzset (explicitly
76 ** or implicitly).
77 ** 3. They might reference tzname[1] after setting to a time zone
78 ** in which Daylight Saving Time is never observed.
79 ** 4. They might reference tzname[0] after setting to a time zone
80 ** in which Standard Time is never observed.
81 ** 5. They might reference tm.TM_ZONE after calling offtime.
82 ** What's best to do in the above cases is open to debate;
83 ** for now, we just set things up so that in any of the five cases
84 ** WILDABBR is used. Another possibility: initialize tzname[0] to the
85 ** string "tzname[0] used before set", and similarly for the other cases.
86 ** And another: initialize tzname[0] to "ERA", with an explanation in the
87 ** manual page of what this "time zone abbreviation" means (doing this so
88 ** that tzname[0] has the "normal" length of three characters).
89 */
90 #define WILDABBR " "
91 #endif /* !defined WILDABBR */
92
93 static const char wildabbr[] = WILDABBR;
94
95 static const char gmt[] = "GMT";
96
97 /*
98 ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
99 ** We default to US rules as of 1999-08-17.
100 ** POSIX 1003.1 section 8.1.1 says that the default DST rules are
101 ** implementation dependent; for historical reasons, US rules are a
102 ** common default.
103 */
104 #ifndef TZDEFRULESTRING
105 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
106 #endif /* !defined TZDEFDST */
107
108 struct ttinfo { /* time type information */
109 int_fast32_t tt_gmtoff; /* UT offset in seconds */
110 int tt_isdst; /* used to set tm_isdst */
111 int tt_abbrind; /* abbreviation list index */
112 int tt_ttisstd; /* TRUE if transition is std time */
113 int tt_ttisgmt; /* TRUE if transition is UT */
114 };
115
116 struct lsinfo { /* leap second information */
117 time_t ls_trans; /* transition time */
118 int_fast64_t ls_corr; /* correction to apply */
119 };
120
121 #define BIGGEST(a, b) (((a) > (b)) ? (a) : (b))
122
123 #ifdef TZNAME_MAX
124 #define MY_TZNAME_MAX TZNAME_MAX
125 #endif /* defined TZNAME_MAX */
126 #ifndef TZNAME_MAX
127 #define MY_TZNAME_MAX 255
128 #endif /* !defined TZNAME_MAX */
129
130 struct __state {
131 int leapcnt;
132 int timecnt;
133 int typecnt;
134 int charcnt;
135 int goback;
136 int goahead;
137 time_t ats[TZ_MAX_TIMES];
138 unsigned char types[TZ_MAX_TIMES];
139 struct ttinfo ttis[TZ_MAX_TYPES];
140 char chars[/*CONSTCOND*/BIGGEST(BIGGEST(TZ_MAX_CHARS + 1,
141 sizeof gmt), (2 * (MY_TZNAME_MAX + 1)))];
142 struct lsinfo lsis[TZ_MAX_LEAPS];
143 int defaulttype; /* for early times or if no transitions */
144 };
145
146 struct rule {
147 int r_type; /* type of rule; see below */
148 int r_day; /* day number of rule */
149 int r_week; /* week number of rule */
150 int r_mon; /* month number of rule */
151 int_fast32_t r_time; /* transition time of rule */
152 };
153
154 #define JULIAN_DAY 0 /* Jn = Julian day */
155 #define DAY_OF_YEAR 1 /* n = day of year */
156 #define MONTH_NTH_DAY_OF_WEEK 2 /* Mm.n.d = month, week, day of week */
157
158 typedef struct tm *(*subfun_t)(const timezone_t sp, const time_t *timep,
159 const int_fast32_t offset, struct tm *tmp);
160
161 /*
162 ** Prototypes for static functions.
163 */
164
165 static int_fast32_t detzcode(const char * codep);
166 static int_fast64_t detzcode64(const char * codep);
167 static int differ_by_repeat(time_t t1, time_t t0);
168 static const char * getzname(const char * strp) ATTRIBUTE_PURE;
169 static const char * getqzname(const char * strp, const int delim) ATTRIBUTE_PURE;
170 static const char * getnum(const char * strp, int * nump, int min,
171 int max);
172 static const char * getsecs(const char * strp, int_fast32_t * secsp);
173 static const char * getoffset(const char * strp, int_fast32_t * offsetp);
174 static const char * getrule(const char * strp, struct rule * rulep);
175 static void gmtload(timezone_t sp);
176 static struct tm * gmtsub(const timezone_t sp, const time_t *timep,
177 const int_fast32_t offset, struct tm * tmp);
178 static struct tm * localsub(const timezone_t sp, const time_t *timep,
179 const int_fast32_t offset, struct tm *tmp);
180 static int increment_overflow(int * number, int delta);
181 static int increment_overflow32(int_fast32_t * number, int delta);
182 static int increment_overflow_time(time_t *t, int_fast32_t delta);
183 static int leaps_thru_end_of(int y) ATTRIBUTE_PURE;
184 static int normalize_overflow(int * tensptr, int * unitsptr,
185 int base);
186 static int normalize_overflow32(int_fast32_t * tensptr,
187 int * unitsptr, int base);
188 static void settzname(void);
189 static time_t time1(const timezone_t sp, struct tm * const tmp,
190 subfun_t funcp, const int_fast32_t offset);
191 static time_t time2(const timezone_t sp, struct tm * const tmp,
192 subfun_t funcp,
193 const int_fast32_t offset, int *const okayp);
194 static time_t time2sub(const timezone_t sp, struct tm * const tmp,
195 subfun_t funcp, const int_fast32_t offset,
196 int *const okayp, const int do_norm_secs);
197 static struct tm * timesub(const timezone_t sp, const time_t * timep,
198 const int_fast32_t offset, struct tm * tmp);
199 static int tmcomp(const struct tm * atmp,
200 const struct tm * btmp);
201 static int_fast32_t transtime(int year, const struct rule * rulep,
202 int_fast32_t offset)
203 ATTRIBUTE_PURE;
204 static int typesequiv(const timezone_t sp, int a, int b);
205 static int tzload(timezone_t sp, const char * name,
206 int doextend);
207 static int tzparse(timezone_t sp, const char * name,
208 int lastditch);
209 static void tzset_unlocked(void);
210 static void tzsetwall_unlocked(void);
211 static int_fast64_t leapcorr(const timezone_t sp, time_t * timep);
212
213 static timezone_t lclptr;
214 static timezone_t gmtptr;
215
216 #ifndef TZ_STRLEN_MAX
217 #define TZ_STRLEN_MAX 255
218 #endif /* !defined TZ_STRLEN_MAX */
219
220 static char lcl_TZname[TZ_STRLEN_MAX + 1];
221 static int lcl_is_set;
222 static int gmt_is_set;
223
224 #if !defined(__LIBC12_SOURCE__)
225
226 __aconst char * tzname[2] = {
227 (__aconst char *)__UNCONST(wildabbr),
228 (__aconst char *)__UNCONST(wildabbr)
229 };
230
231 #else
232
233 extern __aconst char * tzname[2];
234
235 #endif
236
237 #ifdef _REENTRANT
238 static rwlock_t lcl_lock = RWLOCK_INITIALIZER;
239 #endif
240
241 /*
242 ** Section 4.12.3 of X3.159-1989 requires that
243 ** Except for the strftime function, these functions [asctime,
244 ** ctime, gmtime, localtime] return values in one of two static
245 ** objects: a broken-down time structure and an array of char.
246 ** Thanks to Paul Eggert for noting this.
247 */
248
249 static struct tm tm;
250
251 #ifdef USG_COMPAT
252 #if !defined(__LIBC12_SOURCE__)
253 long timezone = 0;
254 int daylight = 0;
255 #else
256 extern int daylight;
257 extern long timezone __RENAME(__timezone13);
258 #endif
259 #endif /* defined USG_COMPAT */
260
261 #ifdef ALTZONE
262 long altzone = 0;
263 #endif /* defined ALTZONE */
264
265 static int_fast32_t
266 detzcode(const char *const codep)
267 {
268 int_fast32_t result;
269 int i;
270
271 result = (codep[0] & 0x80) ? -1 : 0;
272 for (i = 0; i < 4; ++i)
273 result = (result << 8) | (codep[i] & 0xff);
274 return result;
275 }
276
277 static int_fast64_t
278 detzcode64(const char *const codep)
279 {
280 int_fast64_t result;
281 int i;
282
283 result = (codep[0] & 0x80) ? -1 : 0;
284 for (i = 0; i < 8; ++i)
285 result = (result << 8) | (codep[i] & 0xff);
286 return result;
287 }
288
289 const char *
290 tzgetname(const timezone_t sp, int isdst)
291 {
292 int i;
293 for (i = 0; i < sp->timecnt; ++i) {
294 const struct ttinfo *const ttisp = &sp->ttis[sp->types[i]];
295
296 if (ttisp->tt_isdst == isdst)
297 return &sp->chars[ttisp->tt_abbrind];
298 }
299 return NULL;
300 }
301
302 static void
303 settzname_z(timezone_t sp)
304 {
305 int i;
306
307 /*
308 ** Scrub the abbreviations.
309 ** First, replace bogus characters.
310 */
311 for (i = 0; i < sp->charcnt; ++i)
312 if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
313 sp->chars[i] = TZ_ABBR_ERR_CHAR;
314 /*
315 ** Second, truncate long abbreviations.
316 */
317 for (i = 0; i < sp->typecnt; ++i) {
318 const struct ttinfo * const ttisp = &sp->ttis[i];
319 char * cp = &sp->chars[ttisp->tt_abbrind];
320
321 if (strlen(cp) > TZ_ABBR_MAX_LEN &&
322 strcmp(cp, GRANDPARENTED) != 0)
323 *(cp + TZ_ABBR_MAX_LEN) = '\0';
324 }
325 }
326
327 static void
328 settzname(void)
329 {
330 timezone_t const sp = lclptr;
331 int i;
332
333 tzname[0] = (__aconst char *)__UNCONST(wildabbr);
334 tzname[1] = (__aconst char *)__UNCONST(wildabbr);
335 #ifdef USG_COMPAT
336 daylight = 0;
337 timezone = 0;
338 #endif /* defined USG_COMPAT */
339 #ifdef ALTZONE
340 altzone = 0;
341 #endif /* defined ALTZONE */
342 if (sp == NULL) {
343 tzname[0] = tzname[1] = (__aconst char *)__UNCONST(gmt);
344 return;
345 }
346 /*
347 ** And to get the latest zone names into tzname. . .
348 */
349 for (i = 0; i < sp->typecnt; ++i) {
350 const struct ttinfo * const ttisp = &sp->ttis[i];
351
352 tzname[ttisp->tt_isdst] = &sp->chars[ttisp->tt_abbrind];
353 #ifdef USG_COMPAT
354 if (ttisp->tt_isdst)
355 daylight = 1;
356 if (!ttisp->tt_isdst)
357 timezone = -(ttisp->tt_gmtoff);
358 #endif /* defined USG_COMPAT */
359 #ifdef ALTZONE
360 if (ttisp->tt_isdst)
361 altzone = -(ttisp->tt_gmtoff);
362 #endif /* defined ALTZONE */
363 }
364 settzname_z(sp);
365 }
366
367 static int
368 differ_by_repeat(const time_t t1, const time_t t0)
369 {
370 if (TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
371 return 0;
372 return (int_fast64_t)t1 - (int_fast64_t)t0 == SECSPERREPEAT;
373 }
374
375 static int
376 tzload(timezone_t sp, const char *name, const int doextend)
377 {
378 const char * p;
379 int i;
380 int fid;
381 int stored;
382 ssize_t nread;
383 typedef union {
384 struct tzhead tzhead;
385 char buf[2 * sizeof(struct tzhead) +
386 2 * sizeof *sp +
387 4 * TZ_MAX_TIMES];
388 } u_t;
389 union local_storage {
390 /*
391 ** Section 4.9.1 of the C standard says that
392 ** "FILENAME_MAX expands to an integral constant expression
393 ** that is the size needed for an array of char large enough
394 ** to hold the longest file name string that the implementation
395 ** guarantees can be opened."
396 */
397 char fullname[FILENAME_MAX + 1];
398
399 /* The main part of the storage for this function. */
400 struct {
401 u_t u;
402 struct __state st;
403 } u;
404 };
405 char *fullname;
406 u_t *up;
407 int doaccess;
408 union local_storage *lsp;
409 lsp = malloc(sizeof *lsp);
410 if (!lsp)
411 return -1;
412 fullname = lsp->fullname;
413 up = &lsp->u.u;
414
415 sp->goback = sp->goahead = FALSE;
416
417 if (! name) {
418 name = TZDEFAULT;
419 if (! name)
420 goto oops;
421 }
422
423 if (name[0] == ':')
424 ++name;
425 doaccess = name[0] == '/';
426 if (!doaccess) {
427 p = TZDIR;
428 if (! p || sizeof lsp->fullname - 1 <= strlen(p) + strlen(name))
429 goto oops;
430 strcpy(fullname, p);
431 strcat(fullname, "/");
432 strcat(fullname, name);
433 /* Set doaccess if '.' (as in "../") shows up in name. */
434 if (strchr(name, '.'))
435 doaccess = TRUE;
436 name = fullname;
437 }
438 if (doaccess && access(name, R_OK) != 0)
439 goto oops;
440
441 fid = open(name, OPEN_MODE);
442 if (fid < 0)
443 goto oops;
444 nread = read(fid, up->buf, sizeof up->buf);
445 if (close(fid) < 0 || nread <= 0)
446 goto oops;
447 for (stored = 4; stored <= 8; stored *= 2) {
448 int ttisstdcnt;
449 int ttisgmtcnt;
450 int timecnt;
451
452 ttisstdcnt = (int) detzcode(up->tzhead.tzh_ttisstdcnt);
453 ttisgmtcnt = (int) detzcode(up->tzhead.tzh_ttisgmtcnt);
454 sp->leapcnt = (int) detzcode(up->tzhead.tzh_leapcnt);
455 sp->timecnt = (int) detzcode(up->tzhead.tzh_timecnt);
456 sp->typecnt = (int) detzcode(up->tzhead.tzh_typecnt);
457 sp->charcnt = (int) detzcode(up->tzhead.tzh_charcnt);
458 p = up->tzhead.tzh_charcnt + sizeof up->tzhead.tzh_charcnt;
459 if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
460 sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
461 sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
462 sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
463 (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
464 (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
465 goto oops;
466 if (nread - (p - up->buf) <
467 sp->timecnt * stored + /* ats */
468 sp->timecnt + /* types */
469 sp->typecnt * 6 + /* ttinfos */
470 sp->charcnt + /* chars */
471 sp->leapcnt * (stored + 4) + /* lsinfos */
472 ttisstdcnt + /* ttisstds */
473 ttisgmtcnt) /* ttisgmts */
474 goto oops;
475 timecnt = 0;
476 for (i = 0; i < sp->timecnt; ++i) {
477 int_fast64_t at
478 = stored == 4 ? detzcode(p) : detzcode64(p);
479 sp->types[i] = ((TYPE_SIGNED(time_t)
480 ? time_t_min <= at
481 : 0 <= at)
482 && at <= time_t_max);
483 if (sp->types[i]) {
484 if (i && !timecnt && at != time_t_min) {
485 /*
486 ** Keep the earlier record, but tweak
487 ** it so that it starts with the
488 ** minimum time_t value.
489 */
490 sp->types[i - 1] = 1;
491 sp->ats[timecnt++] = time_t_min;
492 }
493 _DIAGASSERT(__type_fit(time_t, at));
494 sp->ats[timecnt++] = (time_t)at;
495 }
496 p += stored;
497 }
498 timecnt = 0;
499 for (i = 0; i < sp->timecnt; ++i) {
500 unsigned char typ = *p++;
501 if (sp->typecnt <= typ)
502 goto oops;
503 if (sp->types[i])
504 sp->types[timecnt++] = typ;
505 }
506 for (i = 0; i < sp->typecnt; ++i) {
507 struct ttinfo * ttisp;
508
509 ttisp = &sp->ttis[i];
510 ttisp->tt_gmtoff = detzcode(p);
511 p += 4;
512 ttisp->tt_isdst = (unsigned char) *p++;
513 if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
514 goto oops;
515 ttisp->tt_abbrind = (unsigned char) *p++;
516 if (ttisp->tt_abbrind < 0 ||
517 ttisp->tt_abbrind > sp->charcnt)
518 goto oops;
519 }
520 for (i = 0; i < sp->charcnt; ++i)
521 sp->chars[i] = *p++;
522 sp->chars[i] = '\0'; /* ensure '\0' at end */
523 for (i = 0; i < sp->leapcnt; ++i) {
524 struct lsinfo * lsisp;
525
526 lsisp = &sp->lsis[i];
527 lsisp->ls_trans = (time_t)((stored == 4) ?
528 detzcode(p) : detzcode64(p));
529 p += stored;
530 lsisp->ls_corr = detzcode(p);
531 p += 4;
532 }
533 for (i = 0; i < sp->typecnt; ++i) {
534 struct ttinfo * ttisp;
535
536 ttisp = &sp->ttis[i];
537 if (ttisstdcnt == 0)
538 ttisp->tt_ttisstd = FALSE;
539 else {
540 ttisp->tt_ttisstd = *p++;
541 if (ttisp->tt_ttisstd != TRUE &&
542 ttisp->tt_ttisstd != FALSE)
543 goto oops;
544 }
545 }
546 for (i = 0; i < sp->typecnt; ++i) {
547 struct ttinfo * ttisp;
548
549 ttisp = &sp->ttis[i];
550 if (ttisgmtcnt == 0)
551 ttisp->tt_ttisgmt = FALSE;
552 else {
553 ttisp->tt_ttisgmt = *p++;
554 if (ttisp->tt_ttisgmt != TRUE &&
555 ttisp->tt_ttisgmt != FALSE)
556 goto oops;
557 }
558 }
559 /*
560 ** If this is an old file, we're done.
561 */
562 if (up->tzhead.tzh_version[0] == '\0')
563 break;
564 nread -= p - up->buf;
565 for (i = 0; i < nread; ++i)
566 up->buf[i] = p[i];
567 /*
568 ** If this is a signed narrow time_t system, we're done.
569 */
570 if (TYPE_SIGNED(time_t) && stored >= (int) sizeof(time_t))
571 break;
572 }
573 if (doextend && nread > 2 &&
574 up->buf[0] == '\n' && up->buf[nread - 1] == '\n' &&
575 sp->typecnt + 2 <= TZ_MAX_TYPES) {
576 struct __state *ts = &lsp->u.st;
577 int result;
578
579 up->buf[nread - 1] = '\0';
580 result = tzparse(ts, &up->buf[1], FALSE);
581 if (result == 0 && ts->typecnt == 2 &&
582 sp->charcnt + ts->charcnt <= TZ_MAX_CHARS) {
583 for (i = 0; i < 2; ++i)
584 ts->ttis[i].tt_abbrind +=
585 sp->charcnt;
586 for (i = 0; i < ts->charcnt; ++i)
587 sp->chars[sp->charcnt++] =
588 ts->chars[i];
589 i = 0;
590 while (i < ts->timecnt &&
591 ts->ats[i] <=
592 sp->ats[sp->timecnt - 1])
593 ++i;
594 while (i < ts->timecnt &&
595 sp->timecnt < TZ_MAX_TIMES) {
596 sp->ats[sp->timecnt] =
597 ts->ats[i];
598 sp->types[sp->timecnt] =
599 sp->typecnt +
600 ts->types[i];
601 ++sp->timecnt;
602 ++i;
603 }
604 sp->ttis[sp->typecnt++] = ts->ttis[0];
605 sp->ttis[sp->typecnt++] = ts->ttis[1];
606 }
607 }
608 if (sp->timecnt > 1) {
609 for (i = 1; i < sp->timecnt; ++i)
610 if (typesequiv(sp, sp->types[i], sp->types[0]) &&
611 differ_by_repeat(sp->ats[i], sp->ats[0])) {
612 sp->goback = TRUE;
613 break;
614 }
615 for (i = sp->timecnt - 2; i >= 0; --i)
616 if (typesequiv(sp, sp->types[sp->timecnt - 1],
617 sp->types[i]) &&
618 differ_by_repeat(sp->ats[sp->timecnt - 1],
619 sp->ats[i])) {
620 sp->goahead = TRUE;
621 break;
622 }
623 }
624 /*
625 ** If type 0 is is unused in transitions,
626 ** it's the type to use for early times.
627 */
628 for (i = 0; i < sp->typecnt; ++i)
629 if (sp->types[i] == 0)
630 break;
631 i = (i >= sp->typecnt) ? 0 : -1;
632 /*
633 ** Absent the above,
634 ** if there are transition times
635 ** and the first transition is to a daylight time
636 ** find the standard type less than and closest to
637 ** the type of the first transition.
638 */
639 if (i < 0 && sp->timecnt > 0 && sp->ttis[sp->types[0]].tt_isdst) {
640 i = sp->types[0];
641 while (--i >= 0)
642 if (!sp->ttis[i].tt_isdst)
643 break;
644 }
645 /*
646 ** If no result yet, find the first standard type.
647 ** If there is none, punt to type zero.
648 */
649 if (i < 0) {
650 i = 0;
651 while (sp->ttis[i].tt_isdst)
652 if (++i >= sp->typecnt) {
653 i = 0;
654 break;
655 }
656 }
657 sp->defaulttype = i;
658 free(up);
659 return 0;
660 oops:
661 free(up);
662 return -1;
663 }
664
665 static int
666 typesequiv(const timezone_t sp, const int a, const int b)
667 {
668 int result;
669
670 if (sp == NULL ||
671 a < 0 || a >= sp->typecnt ||
672 b < 0 || b >= sp->typecnt)
673 result = FALSE;
674 else {
675 const struct ttinfo * ap = &sp->ttis[a];
676 const struct ttinfo * bp = &sp->ttis[b];
677 result = ap->tt_gmtoff == bp->tt_gmtoff &&
678 ap->tt_isdst == bp->tt_isdst &&
679 ap->tt_ttisstd == bp->tt_ttisstd &&
680 ap->tt_ttisgmt == bp->tt_ttisgmt &&
681 strcmp(&sp->chars[ap->tt_abbrind],
682 &sp->chars[bp->tt_abbrind]) == 0;
683 }
684 return result;
685 }
686
687 static const int mon_lengths[2][MONSPERYEAR] = {
688 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
689 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
690 };
691
692 static const int year_lengths[2] = {
693 DAYSPERNYEAR, DAYSPERLYEAR
694 };
695
696 /*
697 ** Given a pointer into a time zone string, scan until a character that is not
698 ** a valid character in a zone name is found. Return a pointer to that
699 ** character.
700 */
701
702 static const char *
703 getzname(const char *strp)
704 {
705 char c;
706
707 while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
708 c != '+')
709 ++strp;
710 return strp;
711 }
712
713 /*
714 ** Given a pointer into an extended time zone string, scan until the ending
715 ** delimiter of the zone name is located. Return a pointer to the delimiter.
716 **
717 ** As with getzname above, the legal character set is actually quite
718 ** restricted, with other characters producing undefined results.
719 ** We don't do any checking here; checking is done later in common-case code.
720 */
721
722 static const char *
723 getqzname(const char *strp, const int delim)
724 {
725 int c;
726
727 while ((c = *strp) != '\0' && c != delim)
728 ++strp;
729 return strp;
730 }
731
732 /*
733 ** Given a pointer into a time zone string, extract a number from that string.
734 ** Check that the number is within a specified range; if it is not, return
735 ** NULL.
736 ** Otherwise, return a pointer to the first character not part of the number.
737 */
738
739 static const char *
740 getnum(const char *strp, int *const nump, const int min, const int max)
741 {
742 char c;
743 int num;
744
745 if (strp == NULL || !is_digit(c = *strp)) {
746 errno = EINVAL;
747 return NULL;
748 }
749 num = 0;
750 do {
751 num = num * 10 + (c - '0');
752 if (num > max) {
753 errno = EOVERFLOW;
754 return NULL; /* illegal value */
755 }
756 c = *++strp;
757 } while (is_digit(c));
758 if (num < min) {
759 errno = EINVAL;
760 return NULL; /* illegal value */
761 }
762 *nump = num;
763 return strp;
764 }
765
766 /*
767 ** Given a pointer into a time zone string, extract a number of seconds,
768 ** in hh[:mm[:ss]] form, from the string.
769 ** If any error occurs, return NULL.
770 ** Otherwise, return a pointer to the first character not part of the number
771 ** of seconds.
772 */
773
774 static const char *
775 getsecs(const char *strp, int_fast32_t *const secsp)
776 {
777 int num;
778
779 /*
780 ** 'HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
781 ** "M10.4.6/26", which does not conform to Posix,
782 ** but which specifies the equivalent of
783 ** "02:00 on the first Sunday on or after 23 Oct".
784 */
785 strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
786 if (strp == NULL)
787 return NULL;
788 *secsp = num * (int_fast32_t) SECSPERHOUR;
789 if (*strp == ':') {
790 ++strp;
791 strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
792 if (strp == NULL)
793 return NULL;
794 *secsp += num * SECSPERMIN;
795 if (*strp == ':') {
796 ++strp;
797 /* 'SECSPERMIN' allows for leap seconds. */
798 strp = getnum(strp, &num, 0, SECSPERMIN);
799 if (strp == NULL)
800 return NULL;
801 *secsp += num;
802 }
803 }
804 return strp;
805 }
806
807 /*
808 ** Given a pointer into a time zone string, extract an offset, in
809 ** [+-]hh[:mm[:ss]] form, from the string.
810 ** If any error occurs, return NULL.
811 ** Otherwise, return a pointer to the first character not part of the time.
812 */
813
814 static const char *
815 getoffset(const char *strp, int_fast32_t *const offsetp)
816 {
817 int neg = 0;
818
819 if (*strp == '-') {
820 neg = 1;
821 ++strp;
822 } else if (*strp == '+')
823 ++strp;
824 strp = getsecs(strp, offsetp);
825 if (strp == NULL)
826 return NULL; /* illegal time */
827 if (neg)
828 *offsetp = -*offsetp;
829 return strp;
830 }
831
832 /*
833 ** Given a pointer into a time zone string, extract a rule in the form
834 ** date[/time]. See POSIX section 8 for the format of "date" and "time".
835 ** If a valid rule is not found, return NULL.
836 ** Otherwise, return a pointer to the first character not part of the rule.
837 */
838
839 static const char *
840 getrule(const char *strp, struct rule *const rulep)
841 {
842 if (*strp == 'J') {
843 /*
844 ** Julian day.
845 */
846 rulep->r_type = JULIAN_DAY;
847 ++strp;
848 strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
849 } else if (*strp == 'M') {
850 /*
851 ** Month, week, day.
852 */
853 rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
854 ++strp;
855 strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
856 if (strp == NULL)
857 return NULL;
858 if (*strp++ != '.')
859 return NULL;
860 strp = getnum(strp, &rulep->r_week, 1, 5);
861 if (strp == NULL)
862 return NULL;
863 if (*strp++ != '.')
864 return NULL;
865 strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
866 } else if (is_digit(*strp)) {
867 /*
868 ** Day of year.
869 */
870 rulep->r_type = DAY_OF_YEAR;
871 strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
872 } else return NULL; /* invalid format */
873 if (strp == NULL)
874 return NULL;
875 if (*strp == '/') {
876 /*
877 ** Time specified.
878 */
879 ++strp;
880 strp = getoffset(strp, &rulep->r_time);
881 } else rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
882 return strp;
883 }
884
885 /*
886 ** Given a year, a rule, and the offset from UT at the time that rule takes
887 ** effect, calculate the year-relative time that rule takes effect.
888 */
889
890 static int_fast32_t
891 transtime(const int year, const struct rule *const rulep,
892 const int_fast32_t offset)
893 {
894 int leapyear;
895 int_fast32_t value;
896 int i;
897 int d, m1, yy0, yy1, yy2, dow;
898
899 INITIALIZE(value);
900 leapyear = isleap(year);
901 switch (rulep->r_type) {
902
903 case JULIAN_DAY:
904 /*
905 ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
906 ** years.
907 ** In non-leap years, or if the day number is 59 or less, just
908 ** add SECSPERDAY times the day number-1 to the time of
909 ** January 1, midnight, to get the day.
910 */
911 value = (rulep->r_day - 1) * SECSPERDAY;
912 if (leapyear && rulep->r_day >= 60)
913 value += SECSPERDAY;
914 break;
915
916 case DAY_OF_YEAR:
917 /*
918 ** n - day of year.
919 ** Just add SECSPERDAY times the day number to the time of
920 ** January 1, midnight, to get the day.
921 */
922 value = rulep->r_day * SECSPERDAY;
923 break;
924
925 case MONTH_NTH_DAY_OF_WEEK:
926 /*
927 ** Mm.n.d - nth "dth day" of month m.
928 */
929
930 /*
931 ** Use Zeller's Congruence to get day-of-week of first day of
932 ** month.
933 */
934 m1 = (rulep->r_mon + 9) % 12 + 1;
935 yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
936 yy1 = yy0 / 100;
937 yy2 = yy0 % 100;
938 dow = ((26 * m1 - 2) / 10 +
939 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
940 if (dow < 0)
941 dow += DAYSPERWEEK;
942
943 /*
944 ** "dow" is the day-of-week of the first day of the month. Get
945 ** the day-of-month (zero-origin) of the first "dow" day of the
946 ** month.
947 */
948 d = rulep->r_day - dow;
949 if (d < 0)
950 d += DAYSPERWEEK;
951 for (i = 1; i < rulep->r_week; ++i) {
952 if (d + DAYSPERWEEK >=
953 mon_lengths[leapyear][rulep->r_mon - 1])
954 break;
955 d += DAYSPERWEEK;
956 }
957
958 /*
959 ** "d" is the day-of-month (zero-origin) of the day we want.
960 */
961 value = d * SECSPERDAY;
962 for (i = 0; i < rulep->r_mon - 1; ++i)
963 value += mon_lengths[leapyear][i] * SECSPERDAY;
964 break;
965 default:
966 _DIAGASSERT(
967 rulep->r_type == JULIAN_DAY ||
968 rulep->r_type == DAY_OF_YEAR ||
969 rulep->r_type == MONTH_NTH_DAY_OF_WEEK);
970 value = 0;
971 break;
972 }
973
974 /*
975 ** "value" is the year-relative time of 00:00:00 UT on the day in
976 ** question. To get the year-relative time of the specified local
977 ** time on that day, add the transition time and the current offset
978 ** from UT.
979 */
980 return value + rulep->r_time + offset;
981 }
982
983 /*
984 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
985 ** appropriate.
986 */
987
988 static int
989 tzparse(timezone_t sp, const char *name, const int lastditch)
990 {
991 const char * stdname;
992 const char * dstname;
993 size_t stdlen;
994 size_t dstlen;
995 int_fast32_t stdoffset;
996 int_fast32_t dstoffset;
997 char * cp;
998 int load_result;
999
1000 dstname = NULL; /* XXX gcc */
1001 stdname = name;
1002 if (lastditch) {
1003 stdlen = strlen(name); /* length of standard zone name */
1004 name += stdlen;
1005 if (stdlen >= sizeof sp->chars)
1006 stdlen = (sizeof sp->chars) - 1;
1007 stdoffset = 0;
1008 } else {
1009 if (*name == '<') {
1010 name++;
1011 stdname = name;
1012 name = getqzname(name, '>');
1013 if (*name != '>')
1014 return (-1);
1015 stdlen = name - stdname;
1016 name++;
1017 } else {
1018 name = getzname(name);
1019 stdlen = name - stdname;
1020 }
1021 if (*name == '\0')
1022 return -1;
1023 name = getoffset(name, &stdoffset);
1024 if (name == NULL)
1025 return -1;
1026 }
1027 load_result = tzload(sp, TZDEFRULES, FALSE);
1028 if (load_result != 0)
1029 sp->leapcnt = 0; /* so, we're off a little */
1030 if (*name != '\0') {
1031 if (*name == '<') {
1032 dstname = ++name;
1033 name = getqzname(name, '>');
1034 if (*name != '>')
1035 return -1;
1036 dstlen = name - dstname;
1037 name++;
1038 } else {
1039 dstname = name;
1040 name = getzname(name);
1041 dstlen = name - dstname; /* length of DST zone name */
1042 }
1043 if (*name != '\0' && *name != ',' && *name != ';') {
1044 name = getoffset(name, &dstoffset);
1045 if (name == NULL)
1046 return -1;
1047 } else dstoffset = stdoffset - SECSPERHOUR;
1048 if (*name == '\0' && load_result != 0)
1049 name = TZDEFRULESTRING;
1050 if (*name == ',' || *name == ';') {
1051 struct rule start;
1052 struct rule end;
1053 int year;
1054 int yearlim;
1055 int timecnt;
1056 time_t janfirst;
1057
1058 ++name;
1059 if ((name = getrule(name, &start)) == NULL)
1060 return -1;
1061 if (*name++ != ',')
1062 return -1;
1063 if ((name = getrule(name, &end)) == NULL)
1064 return -1;
1065 if (*name != '\0')
1066 return -1;
1067 sp->typecnt = 2; /* standard time and DST */
1068 /*
1069 ** Two transitions per year, from EPOCH_YEAR forward.
1070 */
1071 memset(sp->ttis, 0, sizeof(sp->ttis));
1072 sp->ttis[0].tt_gmtoff = -dstoffset;
1073 sp->ttis[0].tt_isdst = 1;
1074 sp->ttis[0].tt_abbrind = (int)(stdlen + 1);
1075 sp->ttis[1].tt_gmtoff = -stdoffset;
1076 sp->ttis[1].tt_isdst = 0;
1077 sp->ttis[1].tt_abbrind = 0;
1078 sp->defaulttype = 0;
1079 timecnt = 0;
1080 janfirst = 0;
1081 sp->timecnt = 0;
1082 yearlim = EPOCH_YEAR + YEARSPERREPEAT;
1083 for (year = EPOCH_YEAR; year < yearlim; year++) {
1084 int_fast32_t
1085 starttime = transtime(year, &start, stdoffset),
1086 endtime = transtime(year, &end, dstoffset);
1087 int_fast32_t
1088 yearsecs = (year_lengths[isleap(year)]
1089 * SECSPERDAY);
1090 int reversed = endtime < starttime;
1091 if (reversed) {
1092 int_fast32_t swap = starttime;
1093 starttime = endtime;
1094 endtime = swap;
1095 }
1096 if (reversed
1097 || (starttime < endtime
1098 && (endtime - starttime
1099 < (yearsecs
1100 + (stdoffset - dstoffset))))) {
1101 if (TZ_MAX_TIMES - 2 < timecnt)
1102 break;
1103 yearlim = year + YEARSPERREPEAT + 1;
1104 sp->ats[timecnt] = janfirst;
1105 if (increment_overflow_time
1106 (&sp->ats[timecnt], starttime))
1107 break;
1108 sp->types[timecnt++] = reversed;
1109 sp->ats[timecnt] = janfirst;
1110 if (increment_overflow_time
1111 (&sp->ats[timecnt], endtime))
1112 break;
1113 sp->types[timecnt++] = !reversed;
1114 }
1115 if (increment_overflow_time(&janfirst, yearsecs))
1116 break;
1117 }
1118 sp->timecnt = timecnt;
1119 if (!timecnt)
1120 sp->typecnt = 1; /* Perpetual DST. */
1121 } else {
1122 int_fast32_t theirstdoffset;
1123 int_fast32_t theirdstoffset;
1124 int_fast32_t theiroffset;
1125 int isdst;
1126 int i;
1127 int j;
1128
1129 if (*name != '\0')
1130 return -1;
1131 /*
1132 ** Initial values of theirstdoffset and theirdstoffset.
1133 */
1134 theirstdoffset = 0;
1135 for (i = 0; i < sp->timecnt; ++i) {
1136 j = sp->types[i];
1137 if (!sp->ttis[j].tt_isdst) {
1138 theirstdoffset =
1139 -sp->ttis[j].tt_gmtoff;
1140 break;
1141 }
1142 }
1143 theirdstoffset = 0;
1144 for (i = 0; i < sp->timecnt; ++i) {
1145 j = sp->types[i];
1146 if (sp->ttis[j].tt_isdst) {
1147 theirdstoffset =
1148 -sp->ttis[j].tt_gmtoff;
1149 break;
1150 }
1151 }
1152 /*
1153 ** Initially we're assumed to be in standard time.
1154 */
1155 isdst = FALSE;
1156 theiroffset = theirstdoffset;
1157 /*
1158 ** Now juggle transition times and types
1159 ** tracking offsets as you do.
1160 */
1161 for (i = 0; i < sp->timecnt; ++i) {
1162 j = sp->types[i];
1163 sp->types[i] = sp->ttis[j].tt_isdst;
1164 if (sp->ttis[j].tt_ttisgmt) {
1165 /* No adjustment to transition time */
1166 } else {
1167 /*
1168 ** If summer time is in effect, and the
1169 ** transition time was not specified as
1170 ** standard time, add the summer time
1171 ** offset to the transition time;
1172 ** otherwise, add the standard time
1173 ** offset to the transition time.
1174 */
1175 /*
1176 ** Transitions from DST to DDST
1177 ** will effectively disappear since
1178 ** POSIX provides for only one DST
1179 ** offset.
1180 */
1181 if (isdst && !sp->ttis[j].tt_ttisstd) {
1182 sp->ats[i] += (time_t)
1183 (dstoffset - theirdstoffset);
1184 } else {
1185 sp->ats[i] += (time_t)
1186 (stdoffset - theirstdoffset);
1187 }
1188 }
1189 theiroffset = -sp->ttis[j].tt_gmtoff;
1190 if (!sp->ttis[j].tt_isdst)
1191 theirstdoffset = theiroffset;
1192 else theirdstoffset = theiroffset;
1193 }
1194 /*
1195 ** Finally, fill in ttis.
1196 ** ttisstd and ttisgmt need not be handled
1197 */
1198 memset(sp->ttis, 0, sizeof(sp->ttis));
1199 sp->ttis[0].tt_gmtoff = -stdoffset;
1200 sp->ttis[0].tt_isdst = FALSE;
1201 sp->ttis[0].tt_abbrind = 0;
1202 sp->ttis[1].tt_gmtoff = -dstoffset;
1203 sp->ttis[1].tt_isdst = TRUE;
1204 sp->ttis[1].tt_abbrind = (int)(stdlen + 1);
1205 sp->typecnt = 2;
1206 sp->defaulttype = 0;
1207 }
1208 } else {
1209 dstlen = 0;
1210 sp->typecnt = 1; /* only standard time */
1211 sp->timecnt = 0;
1212 memset(sp->ttis, 0, sizeof(sp->ttis));
1213 sp->ttis[0].tt_gmtoff = -stdoffset;
1214 sp->ttis[0].tt_isdst = 0;
1215 sp->ttis[0].tt_abbrind = 0;
1216 sp->defaulttype = 0;
1217 }
1218 sp->charcnt = (int)(stdlen + 1);
1219 if (dstlen != 0)
1220 sp->charcnt += (int)(dstlen + 1);
1221 if ((size_t) sp->charcnt > sizeof sp->chars)
1222 return -1;
1223 cp = sp->chars;
1224 (void) strncpy(cp, stdname, stdlen);
1225 cp += stdlen;
1226 *cp++ = '\0';
1227 if (dstlen != 0) {
1228 (void) strncpy(cp, dstname, dstlen);
1229 *(cp + dstlen) = '\0';
1230 }
1231 return 0;
1232 }
1233
1234 static void
1235 gmtload(timezone_t sp)
1236 {
1237 if (tzload(sp, gmt, TRUE) != 0)
1238 (void) tzparse(sp, gmt, TRUE);
1239 }
1240
1241 timezone_t
1242 tzalloc(const char *name)
1243 {
1244 timezone_t sp = malloc(sizeof *sp);
1245 if (sp == NULL)
1246 return NULL;
1247 if (tzload(sp, name, TRUE) != 0) {
1248 free(sp);
1249 return NULL;
1250 }
1251 settzname_z(sp);
1252 return sp;
1253 }
1254
1255 void
1256 tzfree(const timezone_t sp)
1257 {
1258 free(sp);
1259 }
1260
1261 static void
1262 tzsetwall_unlocked(void)
1263 {
1264 if (lcl_is_set < 0)
1265 return;
1266 lcl_is_set = -1;
1267
1268 if (lclptr == NULL) {
1269 int saveerrno = errno;
1270 lclptr = malloc(sizeof *lclptr);
1271 errno = saveerrno;
1272 if (lclptr == NULL) {
1273 settzname(); /* all we can do */
1274 return;
1275 }
1276 }
1277 if (tzload(lclptr, NULL, TRUE) != 0)
1278 gmtload(lclptr);
1279 settzname();
1280 }
1281
1282 #ifndef STD_INSPIRED
1283 /*
1284 ** A non-static declaration of tzsetwall in a system header file
1285 ** may cause a warning about this upcoming static declaration...
1286 */
1287 static
1288 #endif /* !defined STD_INSPIRED */
1289 void
1290 tzsetwall(void)
1291 {
1292 rwlock_wrlock(&lcl_lock);
1293 tzsetwall_unlocked();
1294 rwlock_unlock(&lcl_lock);
1295 }
1296
1297 #ifndef STD_INSPIRED
1298 /*
1299 ** A non-static declaration of tzsetwall in a system header file
1300 ** may cause a warning about this upcoming static declaration...
1301 */
1302 static
1303 #endif /* !defined STD_INSPIRED */
1304 void
1305 tzset_unlocked(void)
1306 {
1307 const char * name;
1308
1309 name = getenv("TZ");
1310 if (name == NULL) {
1311 tzsetwall_unlocked();
1312 return;
1313 }
1314
1315 if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
1316 return;
1317 lcl_is_set = strlen(name) < sizeof lcl_TZname;
1318 if (lcl_is_set)
1319 (void)strlcpy(lcl_TZname, name, sizeof(lcl_TZname));
1320
1321 if (lclptr == NULL) {
1322 int saveerrno = errno;
1323 lclptr = malloc(sizeof *lclptr);
1324 errno = saveerrno;
1325 if (lclptr == NULL) {
1326 settzname(); /* all we can do */
1327 return;
1328 }
1329 }
1330 if (*name == '\0') {
1331 /*
1332 ** User wants it fast rather than right.
1333 */
1334 lclptr->leapcnt = 0; /* so, we're off a little */
1335 lclptr->timecnt = 0;
1336 lclptr->typecnt = 0;
1337 lclptr->ttis[0].tt_isdst = 0;
1338 lclptr->ttis[0].tt_gmtoff = 0;
1339 lclptr->ttis[0].tt_abbrind = 0;
1340 (void) strlcpy(lclptr->chars, gmt, sizeof(lclptr->chars));
1341 } else if (tzload(lclptr, name, TRUE) != 0)
1342 if (name[0] == ':' || tzparse(lclptr, name, FALSE) != 0)
1343 (void) gmtload(lclptr);
1344 settzname();
1345 }
1346
1347 void
1348 tzset(void)
1349 {
1350 rwlock_wrlock(&lcl_lock);
1351 tzset_unlocked();
1352 rwlock_unlock(&lcl_lock);
1353 }
1354
1355 /*
1356 ** The easy way to behave "as if no library function calls" localtime
1357 ** is to not call it, so we drop its guts into "localsub", which can be
1358 ** freely called. (And no, the PANS doesn't require the above behavior,
1359 ** but it *is* desirable.)
1360 **
1361 ** The unused offset argument is for the benefit of mktime variants.
1362 */
1363
1364 /*ARGSUSED*/
1365 static struct tm *
1366 localsub(const timezone_t sp, const time_t * const timep, const int_fast32_t offset,
1367 struct tm *const tmp)
1368 {
1369 const struct ttinfo * ttisp;
1370 int i;
1371 struct tm * result;
1372 const time_t t = *timep;
1373
1374 if ((sp->goback && t < sp->ats[0]) ||
1375 (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1376 time_t newt = t;
1377 time_t seconds;
1378 time_t years;
1379
1380 if (t < sp->ats[0])
1381 seconds = sp->ats[0] - t;
1382 else seconds = t - sp->ats[sp->timecnt - 1];
1383 --seconds;
1384 years = (time_t)((seconds / SECSPERREPEAT + 1) * YEARSPERREPEAT);
1385 seconds = (time_t)(years * AVGSECSPERYEAR);
1386 if (t < sp->ats[0])
1387 newt += seconds;
1388 else newt -= seconds;
1389 if (newt < sp->ats[0] ||
1390 newt > sp->ats[sp->timecnt - 1])
1391 return NULL; /* "cannot happen" */
1392 result = localsub(sp, &newt, offset, tmp);
1393 if (result == tmp) {
1394 time_t newy;
1395
1396 newy = tmp->tm_year;
1397 if (t < sp->ats[0])
1398 newy -= years;
1399 else newy += years;
1400 tmp->tm_year = (int)newy;
1401 if (tmp->tm_year != newy)
1402 return NULL;
1403 }
1404 return result;
1405 }
1406 if (sp->timecnt == 0 || t < sp->ats[0]) {
1407 i = sp->defaulttype;
1408 } else {
1409 int lo = 1;
1410 int hi = sp->timecnt;
1411
1412 while (lo < hi) {
1413 int mid = (lo + hi) / 2;
1414
1415 if (t < sp->ats[mid])
1416 hi = mid;
1417 else lo = mid + 1;
1418 }
1419 i = (int) sp->types[lo - 1];
1420 }
1421 ttisp = &sp->ttis[i];
1422 /*
1423 ** To get (wrong) behavior that's compatible with System V Release 2.0
1424 ** you'd replace the statement below with
1425 ** t += ttisp->tt_gmtoff;
1426 ** timesub(&t, 0L, sp, tmp);
1427 */
1428 result = timesub(sp, &t, ttisp->tt_gmtoff, tmp);
1429 tmp->tm_isdst = ttisp->tt_isdst;
1430 if (sp == lclptr)
1431 tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1432 #ifdef TM_ZONE
1433 tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1434 #endif /* defined TM_ZONE */
1435 return result;
1436 }
1437
1438 /*
1439 ** Re-entrant version of localtime.
1440 */
1441
1442 struct tm *
1443 localtime_r(const time_t * __restrict timep, struct tm *tmp)
1444 {
1445 rwlock_rdlock(&lcl_lock);
1446 tzset_unlocked();
1447 tmp = localtime_rz(lclptr, timep, tmp);
1448 rwlock_unlock(&lcl_lock);
1449 return tmp;
1450 }
1451
1452 struct tm *
1453 localtime(const time_t *const timep)
1454 {
1455 return localtime_r(timep, &tm);
1456 }
1457
1458 struct tm *
1459 localtime_rz(const timezone_t sp, const time_t * __restrict timep, struct tm *tmp)
1460 {
1461 if (sp == NULL)
1462 tmp = gmtsub(NULL, timep, 0, tmp);
1463 else
1464 tmp = localsub(sp, timep, 0, tmp);
1465 if (tmp == NULL)
1466 errno = EOVERFLOW;
1467 return tmp;
1468 }
1469
1470 /*
1471 ** gmtsub is to gmtime as localsub is to localtime.
1472 */
1473
1474 static struct tm *
1475 gmtsub(const timezone_t sp, const time_t *const timep,
1476 const int_fast32_t offset, struct tm *const tmp)
1477 {
1478 struct tm * result;
1479 #ifdef _REENTRANT
1480 static mutex_t gmt_mutex = MUTEX_INITIALIZER;
1481 #endif
1482
1483 mutex_lock(&gmt_mutex);
1484 if (!gmt_is_set) {
1485 int saveerrno;
1486 gmt_is_set = TRUE;
1487 saveerrno = errno;
1488 gmtptr = malloc(sizeof *gmtptr);
1489 gmt_is_set = gmtptr != NULL;
1490 errno = saveerrno;
1491 if (gmt_is_set)
1492 gmtload(gmtptr);
1493 }
1494 mutex_unlock(&gmt_mutex);
1495 result = timesub(gmtptr, timep, offset, tmp);
1496 #ifdef TM_ZONE
1497 /*
1498 ** Could get fancy here and deliver something such as
1499 ** "UT+xxxx" or "UT-xxxx" if offset is non-zero,
1500 ** but this is no time for a treasure hunt.
1501 */
1502 tmp->TM_ZONE = offset ? __UNCONST(wildabbr) : gmtptr ? gmtptr->chars :
1503 __UNCONST(gmt);
1504 #endif /* defined TM_ZONE */
1505 return result;
1506 }
1507
1508 struct tm *
1509 gmtime(const time_t *const timep)
1510 {
1511 struct tm *tmp = gmtsub(NULL, timep, 0, &tm);
1512
1513 if (tmp == NULL)
1514 errno = EOVERFLOW;
1515
1516 return tmp;
1517 }
1518
1519 /*
1520 ** Re-entrant version of gmtime.
1521 */
1522
1523 struct tm *
1524 gmtime_r(const time_t * const timep, struct tm *tmp)
1525 {
1526 tmp = gmtsub(NULL, timep, 0, tmp);
1527
1528 if (tmp == NULL)
1529 errno = EOVERFLOW;
1530
1531 return tmp;
1532 }
1533
1534 #ifdef STD_INSPIRED
1535
1536 struct tm *
1537 offtime(const time_t *const timep, long offset)
1538 {
1539 struct tm *tmp;
1540
1541 if ((offset > 0 && offset > INT_FAST32_MAX) ||
1542 (offset < 0 && offset < INT_FAST32_MIN)) {
1543 errno = EOVERFLOW;
1544 return NULL;
1545 }
1546 tmp = gmtsub(NULL, timep, (int_fast32_t)offset, &tm);
1547
1548 if (tmp == NULL)
1549 errno = EOVERFLOW;
1550
1551 return tmp;
1552 }
1553
1554 struct tm *
1555 offtime_r(const time_t *timep, long offset, struct tm *tmp)
1556 {
1557 if ((offset > 0 && offset > INT_FAST32_MAX) ||
1558 (offset < 0 && offset < INT_FAST32_MIN)) {
1559 errno = EOVERFLOW;
1560 return NULL;
1561 }
1562 tmp = gmtsub(NULL, timep, (int_fast32_t)offset, tmp);
1563
1564 if (tmp == NULL)
1565 errno = EOVERFLOW;
1566
1567 return tmp;
1568 }
1569
1570 #endif /* defined STD_INSPIRED */
1571
1572 /*
1573 ** Return the number of leap years through the end of the given year
1574 ** where, to make the math easy, the answer for year zero is defined as zero.
1575 */
1576
1577 static int
1578 leaps_thru_end_of(const int y)
1579 {
1580 return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1581 -(leaps_thru_end_of(-(y + 1)) + 1);
1582 }
1583
1584 static struct tm *
1585 timesub(const timezone_t sp, const time_t *const timep,
1586 const int_fast32_t offset, struct tm *const tmp)
1587 {
1588 const struct lsinfo * lp;
1589 time_t tdays;
1590 int idays; /* unsigned would be so 2003 */
1591 int_fast64_t rem;
1592 int y;
1593 const int * ip;
1594 int_fast64_t corr;
1595 int hit;
1596 int i;
1597
1598 corr = 0;
1599 hit = 0;
1600 i = (sp == NULL) ? 0 : sp->leapcnt;
1601 while (--i >= 0) {
1602 lp = &sp->lsis[i];
1603 if (*timep >= lp->ls_trans) {
1604 if (*timep == lp->ls_trans) {
1605 hit = ((i == 0 && lp->ls_corr > 0) ||
1606 lp->ls_corr > sp->lsis[i - 1].ls_corr);
1607 if (hit)
1608 while (i > 0 &&
1609 sp->lsis[i].ls_trans ==
1610 sp->lsis[i - 1].ls_trans + 1 &&
1611 sp->lsis[i].ls_corr ==
1612 sp->lsis[i - 1].ls_corr + 1) {
1613 ++hit;
1614 --i;
1615 }
1616 }
1617 corr = lp->ls_corr;
1618 break;
1619 }
1620 }
1621 y = EPOCH_YEAR;
1622 tdays = (time_t)(*timep / SECSPERDAY);
1623 rem = (int_fast64_t) (*timep - tdays * SECSPERDAY);
1624 while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
1625 int newy;
1626 time_t tdelta;
1627 int idelta;
1628 int leapdays;
1629
1630 tdelta = tdays / DAYSPERLYEAR;
1631 if (! ((! TYPE_SIGNED(time_t) || INT_MIN <= tdelta)
1632 && tdelta <= INT_MAX))
1633 return NULL;
1634 _DIAGASSERT(__type_fit(int, tdelta));
1635 idelta = (int)tdelta;
1636 if (idelta == 0)
1637 idelta = (tdays < 0) ? -1 : 1;
1638 newy = y;
1639 if (increment_overflow(&newy, idelta))
1640 return NULL;
1641 leapdays = leaps_thru_end_of(newy - 1) -
1642 leaps_thru_end_of(y - 1);
1643 tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
1644 tdays -= leapdays;
1645 y = newy;
1646 }
1647 {
1648 int_fast32_t seconds;
1649
1650 seconds = (int_fast32_t)(tdays * SECSPERDAY);
1651 tdays = (time_t)(seconds / SECSPERDAY);
1652 rem += (int_fast64_t)(seconds - tdays * SECSPERDAY);
1653 }
1654 /*
1655 ** Given the range, we can now fearlessly cast...
1656 */
1657 idays = (int) tdays;
1658 rem += offset - corr;
1659 while (rem < 0) {
1660 rem += SECSPERDAY;
1661 --idays;
1662 }
1663 while (rem >= SECSPERDAY) {
1664 rem -= SECSPERDAY;
1665 ++idays;
1666 }
1667 while (idays < 0) {
1668 if (increment_overflow(&y, -1))
1669 return NULL;
1670 idays += year_lengths[isleap(y)];
1671 }
1672 while (idays >= year_lengths[isleap(y)]) {
1673 idays -= year_lengths[isleap(y)];
1674 if (increment_overflow(&y, 1))
1675 return NULL;
1676 }
1677 tmp->tm_year = y;
1678 if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
1679 return NULL;
1680 tmp->tm_yday = idays;
1681 /*
1682 ** The "extra" mods below avoid overflow problems.
1683 */
1684 tmp->tm_wday = EPOCH_WDAY +
1685 ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1686 (DAYSPERNYEAR % DAYSPERWEEK) +
1687 leaps_thru_end_of(y - 1) -
1688 leaps_thru_end_of(EPOCH_YEAR - 1) +
1689 idays;
1690 tmp->tm_wday %= DAYSPERWEEK;
1691 if (tmp->tm_wday < 0)
1692 tmp->tm_wday += DAYSPERWEEK;
1693 tmp->tm_hour = (int) (rem / SECSPERHOUR);
1694 rem %= SECSPERHOUR;
1695 tmp->tm_min = (int) (rem / SECSPERMIN);
1696 /*
1697 ** A positive leap second requires a special
1698 ** representation. This uses "... ??:59:60" et seq.
1699 */
1700 tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1701 ip = mon_lengths[isleap(y)];
1702 for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1703 idays -= ip[tmp->tm_mon];
1704 tmp->tm_mday = (int) (idays + 1);
1705 tmp->tm_isdst = 0;
1706 #ifdef TM_GMTOFF
1707 tmp->TM_GMTOFF = offset;
1708 #endif /* defined TM_GMTOFF */
1709 return tmp;
1710 }
1711
1712 char *
1713 ctime(const time_t *const timep)
1714 {
1715 /*
1716 ** Section 4.12.3.2 of X3.159-1989 requires that
1717 ** The ctime function converts the calendar time pointed to by timer
1718 ** to local time in the form of a string. It is equivalent to
1719 ** asctime(localtime(timer))
1720 */
1721 struct tm *rtm = localtime(timep);
1722 if (rtm == NULL)
1723 return NULL;
1724 return asctime(rtm);
1725 }
1726
1727 char *
1728 ctime_r(const time_t *const timep, char *buf)
1729 {
1730 struct tm mytm, *rtm;
1731
1732 rtm = localtime_r(timep, &mytm);
1733 if (rtm == NULL)
1734 return NULL;
1735 return asctime_r(rtm, buf);
1736 }
1737
1738 char *
1739 ctime_rz(const timezone_t sp, const time_t * timep, char *buf)
1740 {
1741 struct tm mytm, *rtm;
1742
1743 rtm = localtime_rz(sp, timep, &mytm);
1744 if (rtm == NULL)
1745 return NULL;
1746 return asctime_r(rtm, buf);
1747 }
1748
1749 /*
1750 ** Adapted from code provided by Robert Elz, who writes:
1751 ** The "best" way to do mktime I think is based on an idea of Bob
1752 ** Kridle's (so its said...) from a long time ago.
1753 ** It does a binary search of the time_t space. Since time_t's are
1754 ** just 32 bits, its a max of 32 iterations (even at 64 bits it
1755 ** would still be very reasonable).
1756 */
1757
1758 #ifndef WRONG
1759 #define WRONG ((time_t)-1)
1760 #endif /* !defined WRONG */
1761
1762 /*
1763 ** Simplified normalize logic courtesy Paul Eggert.
1764 */
1765
1766 static int
1767 increment_overflow(int *const ip, int j)
1768 {
1769 int i = *ip;
1770
1771 /*
1772 ** If i >= 0 there can only be overflow if i + j > INT_MAX
1773 ** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
1774 ** If i < 0 there can only be overflow if i + j < INT_MIN
1775 ** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
1776 */
1777 if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
1778 return TRUE;
1779 *ip += j;
1780 return FALSE;
1781 }
1782
1783 static int
1784 increment_overflow32(int_fast32_t *const lp, int const m)
1785 {
1786 int_fast32_t l = *lp;
1787
1788 if ((l >= 0) ? (m > INT_FAST32_MAX - l) : (m < INT_FAST32_MIN - l))
1789 return TRUE;
1790 *lp += m;
1791 return FALSE;
1792 }
1793
1794 static int
1795 increment_overflow_time(time_t *tp, int_fast32_t j)
1796 {
1797 /*
1798 ** This is like
1799 ** 'if (! (time_t_min <= *tp + j && *tp + j <= time_t_max)) ...',
1800 ** except that it does the right thing even if *tp + j would overflow.
1801 */
1802 if (! (j < 0
1803 ? (TYPE_SIGNED(time_t) ? time_t_min - j <= *tp : -1 - j < *tp)
1804 : *tp <= time_t_max - j))
1805 return TRUE;
1806 *tp += j;
1807 return FALSE;
1808 }
1809
1810 static int
1811 normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
1812 {
1813 int tensdelta;
1814
1815 tensdelta = (*unitsptr >= 0) ?
1816 (*unitsptr / base) :
1817 (-1 - (-1 - *unitsptr) / base);
1818 *unitsptr -= tensdelta * base;
1819 return increment_overflow(tensptr, tensdelta);
1820 }
1821
1822 static int
1823 normalize_overflow32(int_fast32_t *const tensptr, int *const unitsptr,
1824 const int base)
1825 {
1826 int tensdelta;
1827
1828 tensdelta = (*unitsptr >= 0) ?
1829 (*unitsptr / base) :
1830 (-1 - (-1 - *unitsptr) / base);
1831 *unitsptr -= tensdelta * base;
1832 return increment_overflow32(tensptr, tensdelta);
1833 }
1834
1835 static int
1836 tmcomp(const struct tm *const atmp, const struct tm *const btmp)
1837 {
1838 int result;
1839
1840 if (atmp->tm_year != btmp->tm_year)
1841 return atmp->tm_year < btmp->tm_year ? -1 : 1;
1842 if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1843 (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1844 (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1845 (result = (atmp->tm_min - btmp->tm_min)) == 0)
1846 result = atmp->tm_sec - btmp->tm_sec;
1847 return result;
1848 }
1849
1850 static time_t
1851 time2sub(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
1852 const int_fast32_t offset, int *const okayp, const int do_norm_secs)
1853 {
1854 int dir;
1855 int i, j;
1856 int saved_seconds;
1857 int_fast32_t li;
1858 time_t lo;
1859 time_t hi;
1860 #ifdef NO_ERROR_IN_DST_GAP
1861 time_t ilo;
1862 #endif
1863 int_fast32_t y;
1864 time_t newt;
1865 time_t t;
1866 struct tm yourtm, mytm;
1867
1868 *okayp = FALSE;
1869 yourtm = *tmp;
1870 #ifdef NO_ERROR_IN_DST_GAP
1871 again:
1872 #endif
1873 if (do_norm_secs) {
1874 if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1875 SECSPERMIN))
1876 goto overflow;
1877 }
1878 if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1879 goto overflow;
1880 if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1881 goto overflow;
1882 y = yourtm.tm_year;
1883 if (normalize_overflow32(&y, &yourtm.tm_mon, MONSPERYEAR))
1884 goto overflow;
1885 /*
1886 ** Turn y into an actual year number for now.
1887 ** It is converted back to an offset from TM_YEAR_BASE later.
1888 */
1889 if (increment_overflow32(&y, TM_YEAR_BASE))
1890 goto overflow;
1891 while (yourtm.tm_mday <= 0) {
1892 if (increment_overflow32(&y, -1))
1893 goto overflow;
1894 li = y + (1 < yourtm.tm_mon);
1895 yourtm.tm_mday += year_lengths[isleap(li)];
1896 }
1897 while (yourtm.tm_mday > DAYSPERLYEAR) {
1898 li = y + (1 < yourtm.tm_mon);
1899 yourtm.tm_mday -= year_lengths[isleap(li)];
1900 if (increment_overflow32(&y, 1))
1901 goto overflow;
1902 }
1903 for ( ; ; ) {
1904 i = mon_lengths[isleap(y)][yourtm.tm_mon];
1905 if (yourtm.tm_mday <= i)
1906 break;
1907 yourtm.tm_mday -= i;
1908 if (++yourtm.tm_mon >= MONSPERYEAR) {
1909 yourtm.tm_mon = 0;
1910 if (increment_overflow32(&y, 1))
1911 goto overflow;
1912 }
1913 }
1914 if (increment_overflow32(&y, -TM_YEAR_BASE))
1915 goto overflow;
1916 yourtm.tm_year = (int)y;
1917 if (yourtm.tm_year != y)
1918 goto overflow;
1919 if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1920 saved_seconds = 0;
1921 else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
1922 /*
1923 ** We can't set tm_sec to 0, because that might push the
1924 ** time below the minimum representable time.
1925 ** Set tm_sec to 59 instead.
1926 ** This assumes that the minimum representable time is
1927 ** not in the same minute that a leap second was deleted from,
1928 ** which is a safer assumption than using 58 would be.
1929 */
1930 if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1931 goto overflow;
1932 saved_seconds = yourtm.tm_sec;
1933 yourtm.tm_sec = SECSPERMIN - 1;
1934 } else {
1935 saved_seconds = yourtm.tm_sec;
1936 yourtm.tm_sec = 0;
1937 }
1938 /*
1939 ** Do a binary search (this works whatever time_t's type is).
1940 */
1941 /* LINTED const not */
1942 if (!TYPE_SIGNED(time_t)) {
1943 lo = 0;
1944 hi = lo - 1;
1945 } else {
1946 lo = 1;
1947 for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
1948 lo *= 2;
1949 hi = -(lo + 1);
1950 }
1951 #ifdef NO_ERROR_IN_DST_GAP
1952 ilo = lo;
1953 #endif
1954 for ( ; ; ) {
1955 t = lo / 2 + hi / 2;
1956 if (t < lo)
1957 t = lo;
1958 else if (t > hi)
1959 t = hi;
1960 if ((*funcp)(sp, &t, offset, &mytm) == NULL) {
1961 /*
1962 ** Assume that t is too extreme to be represented in
1963 ** a struct tm; arrange things so that it is less
1964 ** extreme on the next pass.
1965 */
1966 dir = (t > 0) ? 1 : -1;
1967 } else dir = tmcomp(&mytm, &yourtm);
1968 if (dir != 0) {
1969 if (t == lo) {
1970 if (t == time_t_max)
1971 goto overflow;
1972 ++t;
1973 ++lo;
1974 } else if (t == hi) {
1975 if (t == time_t_min)
1976 goto overflow;
1977 --t;
1978 --hi;
1979 }
1980 #ifdef NO_ERROR_IN_DST_GAP
1981 if (ilo != lo && lo - 1 == hi && yourtm.tm_isdst < 0 &&
1982 do_norm_secs) {
1983 for (i = sp->typecnt - 1; i >= 0; --i) {
1984 for (j = sp->typecnt - 1; j >= 0; --j) {
1985 time_t off;
1986 if (sp->ttis[j].tt_isdst ==
1987 sp->ttis[i].tt_isdst)
1988 continue;
1989 off = sp->ttis[j].tt_gmtoff -
1990 sp->ttis[i].tt_gmtoff;
1991 yourtm.tm_sec += off < 0 ?
1992 -off : off;
1993 goto again;
1994 }
1995 }
1996 }
1997 #endif
1998 if (lo > hi)
1999 goto invalid;
2000 if (dir > 0)
2001 hi = t;
2002 else lo = t;
2003 continue;
2004 }
2005 if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
2006 break;
2007 /*
2008 ** Right time, wrong type.
2009 ** Hunt for right time, right type.
2010 ** It's okay to guess wrong since the guess
2011 ** gets checked.
2012 */
2013 if (sp == NULL)
2014 goto invalid;
2015 for (i = sp->typecnt - 1; i >= 0; --i) {
2016 if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
2017 continue;
2018 for (j = sp->typecnt - 1; j >= 0; --j) {
2019 if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
2020 continue;
2021 newt = (time_t)(t + sp->ttis[j].tt_gmtoff -
2022 sp->ttis[i].tt_gmtoff);
2023 if ((*funcp)(sp, &newt, offset, &mytm) == NULL)
2024 continue;
2025 if (tmcomp(&mytm, &yourtm) != 0)
2026 continue;
2027 if (mytm.tm_isdst != yourtm.tm_isdst)
2028 continue;
2029 /*
2030 ** We have a match.
2031 */
2032 t = newt;
2033 goto label;
2034 }
2035 }
2036 goto invalid;
2037 }
2038 label:
2039 newt = t + saved_seconds;
2040 if ((newt < t) != (saved_seconds < 0))
2041 goto overflow;
2042 t = newt;
2043 if ((*funcp)(sp, &t, offset, tmp)) {
2044 *okayp = TRUE;
2045 return t;
2046 }
2047 overflow:
2048 errno = EOVERFLOW;
2049 return WRONG;
2050 invalid:
2051 errno = EINVAL;
2052 return WRONG;
2053 }
2054
2055 static time_t
2056 time2(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
2057 const int_fast32_t offset, int *const okayp)
2058 {
2059 time_t t;
2060
2061 /*
2062 ** First try without normalization of seconds
2063 ** (in case tm_sec contains a value associated with a leap second).
2064 ** If that fails, try with normalization of seconds.
2065 */
2066 t = time2sub(sp, tmp, funcp, offset, okayp, FALSE);
2067 return *okayp ? t : time2sub(sp, tmp, funcp, offset, okayp, TRUE);
2068 }
2069
2070 static time_t
2071 time1(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
2072 const int_fast32_t offset)
2073 {
2074 time_t t;
2075 int samei, otheri;
2076 int sameind, otherind;
2077 int i;
2078 int nseen;
2079 char seen[TZ_MAX_TYPES];
2080 unsigned char types[TZ_MAX_TYPES];
2081 int okay;
2082
2083 if (tmp == NULL) {
2084 errno = EINVAL;
2085 return WRONG;
2086 }
2087 if (tmp->tm_isdst > 1)
2088 tmp->tm_isdst = 1;
2089 t = time2(sp, tmp, funcp, offset, &okay);
2090 if (okay)
2091 return t;
2092 if (tmp->tm_isdst < 0)
2093 #ifdef PCTS
2094 /*
2095 ** POSIX Conformance Test Suite code courtesy Grant Sullivan.
2096 */
2097 tmp->tm_isdst = 0; /* reset to std and try again */
2098 #else
2099 return t;
2100 #endif /* !defined PCTS */
2101 /*
2102 ** We're supposed to assume that somebody took a time of one type
2103 ** and did some math on it that yielded a "struct tm" that's bad.
2104 ** We try to divine the type they started from and adjust to the
2105 ** type they need.
2106 */
2107 if (sp == NULL) {
2108 errno = EINVAL;
2109 return WRONG;
2110 }
2111 for (i = 0; i < sp->typecnt; ++i)
2112 seen[i] = FALSE;
2113 nseen = 0;
2114 for (i = sp->timecnt - 1; i >= 0; --i)
2115 if (!seen[sp->types[i]]) {
2116 seen[sp->types[i]] = TRUE;
2117 types[nseen++] = sp->types[i];
2118 }
2119 for (sameind = 0; sameind < nseen; ++sameind) {
2120 samei = types[sameind];
2121 if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
2122 continue;
2123 for (otherind = 0; otherind < nseen; ++otherind) {
2124 otheri = types[otherind];
2125 if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
2126 continue;
2127 tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
2128 sp->ttis[samei].tt_gmtoff);
2129 tmp->tm_isdst = !tmp->tm_isdst;
2130 t = time2(sp, tmp, funcp, offset, &okay);
2131 if (okay)
2132 return t;
2133 tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
2134 sp->ttis[samei].tt_gmtoff);
2135 tmp->tm_isdst = !tmp->tm_isdst;
2136 }
2137 }
2138 errno = EOVERFLOW;
2139 return WRONG;
2140 }
2141
2142 time_t
2143 mktime_z(const timezone_t sp, struct tm *const tmp)
2144 {
2145 time_t t;
2146 if (sp == NULL)
2147 t = time1(NULL, tmp, gmtsub, 0);
2148 else
2149 t = time1(sp, tmp, localsub, 0);
2150 return t;
2151 }
2152
2153 time_t
2154 mktime(struct tm *const tmp)
2155 {
2156 time_t result;
2157
2158 rwlock_wrlock(&lcl_lock);
2159 tzset_unlocked();
2160 result = mktime_z(lclptr, tmp);
2161 rwlock_unlock(&lcl_lock);
2162 return result;
2163 }
2164
2165 #ifdef STD_INSPIRED
2166
2167 time_t
2168 timelocal_z(const timezone_t sp, struct tm *const tmp)
2169 {
2170 if (tmp != NULL)
2171 tmp->tm_isdst = -1; /* in case it wasn't initialized */
2172 return mktime_z(sp, tmp);
2173 }
2174
2175 time_t
2176 timelocal(struct tm *const tmp)
2177 {
2178 if (tmp != NULL)
2179 tmp->tm_isdst = -1; /* in case it wasn't initialized */
2180 return mktime(tmp);
2181 }
2182
2183 time_t
2184 timegm(struct tm *const tmp)
2185 {
2186 time_t t;
2187
2188 if (tmp != NULL)
2189 tmp->tm_isdst = 0;
2190 t = time1(gmtptr, tmp, gmtsub, 0);
2191 return t;
2192 }
2193
2194 time_t
2195 timeoff(struct tm *const tmp, long offset)
2196 {
2197 time_t t;
2198
2199 if ((offset > 0 && offset > INT_FAST32_MAX) ||
2200 (offset < 0 && offset < INT_FAST32_MIN)) {
2201 errno = EOVERFLOW;
2202 return -1;
2203 }
2204 if (tmp != NULL)
2205 tmp->tm_isdst = 0;
2206 t = time1(gmtptr, tmp, gmtsub, (int_fast32_t)offset);
2207 return t;
2208 }
2209
2210 #endif /* defined STD_INSPIRED */
2211
2212 #ifdef CMUCS
2213
2214 /*
2215 ** The following is supplied for compatibility with
2216 ** previous versions of the CMUCS runtime library.
2217 */
2218
2219 long
2220 gtime(struct tm *const tmp)
2221 {
2222 const time_t t = mktime(tmp);
2223
2224 if (t == WRONG)
2225 return -1;
2226 return t;
2227 }
2228
2229 #endif /* defined CMUCS */
2230
2231 /*
2232 ** XXX--is the below the right way to conditionalize??
2233 */
2234
2235 #ifdef STD_INSPIRED
2236
2237 /*
2238 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
2239 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
2240 ** is not the case if we are accounting for leap seconds.
2241 ** So, we provide the following conversion routines for use
2242 ** when exchanging timestamps with POSIX conforming systems.
2243 */
2244
2245 static int_fast64_t
2246 leapcorr(const timezone_t sp, time_t *timep)
2247 {
2248 struct lsinfo * lp;
2249 int i;
2250
2251 i = sp->leapcnt;
2252 while (--i >= 0) {
2253 lp = &sp->lsis[i];
2254 if (*timep >= lp->ls_trans)
2255 return lp->ls_corr;
2256 }
2257 return 0;
2258 }
2259
2260 time_t
2261 time2posix_z(const timezone_t sp, time_t t)
2262 {
2263 return (time_t)(t - leapcorr(sp, &t));
2264 }
2265
2266 time_t
2267 time2posix(time_t t)
2268 {
2269 time_t result;
2270 rwlock_wrlock(&lcl_lock);
2271 tzset_unlocked();
2272 result = (time_t)(t - leapcorr(lclptr, &t));
2273 rwlock_unlock(&lcl_lock);
2274 return (result);
2275 }
2276
2277 time_t
2278 posix2time_z(const timezone_t sp, time_t t)
2279 {
2280 time_t x;
2281 time_t y;
2282
2283 /*
2284 ** For a positive leap second hit, the result
2285 ** is not unique. For a negative leap second
2286 ** hit, the corresponding time doesn't exist,
2287 ** so we return an adjacent second.
2288 */
2289 x = (time_t)(t + leapcorr(sp, &t));
2290 y = (time_t)(x - leapcorr(sp, &x));
2291 if (y < t) {
2292 do {
2293 x++;
2294 y = (time_t)(x - leapcorr(sp, &x));
2295 } while (y < t);
2296 if (t != y) {
2297 return x - 1;
2298 }
2299 } else if (y > t) {
2300 do {
2301 --x;
2302 y = (time_t)(x - leapcorr(sp, &x));
2303 } while (y > t);
2304 if (t != y) {
2305 return x + 1;
2306 }
2307 }
2308 return x;
2309 }
2310
2311
2312
2313 time_t
2314 posix2time(time_t t)
2315 {
2316 time_t result;
2317
2318 rwlock_wrlock(&lcl_lock);
2319 tzset_unlocked();
2320 result = posix2time_z(lclptr, t);
2321 rwlock_unlock(&lcl_lock);
2322 return result;
2323 }
2324
2325 #endif /* defined STD_INSPIRED */
2326