xref: /freebsd/contrib/tzcode/localtime.c (revision af23369a6deaaeb612ab266eb88b8bb8d560c322)
1 /* Convert timestamp from time_t to struct tm.  */
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 /*
9 ** Leap second handling from Bradley White.
10 ** POSIX-style TZ environment variable handling from Guy Harris.
11 */
12 
13 /*LINTLIBRARY*/
14 
15 #define LOCALTIME_IMPLEMENTATION
16 #include "namespace.h"
17 #ifdef DETECT_TZ_CHANGES
18 #ifndef DETECT_TZ_CHANGES_INTERVAL
19 #define DETECT_TZ_CHANGES_INTERVAL 61
20 #endif
21 #include <sys/stat.h>
22 #endif
23 #include <fcntl.h>
24 #if THREAD_SAFE
25 #include <pthread.h>
26 #endif
27 #include "private.h"
28 #include "un-namespace.h"
29 
30 #include "tzfile.h"
31 
32 #include "libc_private.h"
33 
34 #if defined THREAD_SAFE && THREAD_SAFE
35 static pthread_mutex_t locallock = PTHREAD_MUTEX_INITIALIZER;
36 static int lock(void) {
37 	if (__isthreaded)
38 		return _pthread_mutex_lock(&locallock);
39 	return 0;
40 }
41 static void unlock(void) {
42 	if (__isthreaded)
43 		_pthread_mutex_unlock(&locallock);
44 }
45 #else
46 static int lock(void) { return 0; }
47 static void unlock(void) { }
48 #endif
49 
50 #ifndef TZ_ABBR_MAX_LEN
51 # define TZ_ABBR_MAX_LEN 16
52 #endif /* !defined TZ_ABBR_MAX_LEN */
53 
54 #ifndef TZ_ABBR_CHAR_SET
55 # define TZ_ABBR_CHAR_SET \
56 	"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
57 #endif /* !defined TZ_ABBR_CHAR_SET */
58 
59 #ifndef TZ_ABBR_ERR_CHAR
60 # define TZ_ABBR_ERR_CHAR '_'
61 #endif /* !defined TZ_ABBR_ERR_CHAR */
62 
63 /*
64 ** Support non-POSIX platforms that distinguish between text and binary files.
65 */
66 
67 #ifndef O_BINARY
68 # define O_BINARY 0
69 #endif
70 
71 #ifndef WILDABBR
72 /*
73 ** Someone might make incorrect use of a time zone abbreviation:
74 **	1.	They might reference tzname[0] before calling tzset (explicitly
75 **		or implicitly).
76 **	2.	They might reference tzname[1] before calling tzset (explicitly
77 **		or implicitly).
78 **	3.	They might reference tzname[1] after setting to a time zone
79 **		in which Daylight Saving Time is never observed.
80 **	4.	They might reference tzname[0] after setting to a time zone
81 **		in which Standard Time is never observed.
82 **	5.	They might reference tm.TM_ZONE after calling offtime.
83 ** What's best to do in the above cases is open to debate;
84 ** for now, we just set things up so that in any of the five cases
85 ** WILDABBR is used. Another possibility: initialize tzname[0] to the
86 ** string "tzname[0] used before set", and similarly for the other cases.
87 ** And another: initialize tzname[0] to "ERA", with an explanation in the
88 ** manual page of what this "time zone abbreviation" means (doing this so
89 ** that tzname[0] has the "normal" length of three characters).
90 */
91 # define WILDABBR "   "
92 #endif /* !defined WILDABBR */
93 
94 static const char	wildabbr[] = WILDABBR;
95 
96 static char const etc_utc[] = "Etc/UTC";
97 static char const *utc = etc_utc + sizeof "Etc/" - 1;
98 
99 /*
100 ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
101 ** Default to US rules as of 2017-05-07.
102 ** POSIX does not specify the default DST rules;
103 ** for historical reasons, US rules are a common default.
104 */
105 #ifndef TZDEFRULESTRING
106 # define TZDEFRULESTRING ",M3.2.0,M11.1.0"
107 #endif
108 
109 struct ttinfo {				/* time type information */
110 	int_fast32_t	tt_utoff;	/* UT offset in seconds */
111 	bool		tt_isdst;	/* used to set tm_isdst */
112 	int		tt_desigidx;	/* abbreviation list index */
113 	bool		tt_ttisstd;	/* transition is std time */
114 	bool		tt_ttisut;	/* transition is UT */
115 };
116 
117 struct lsinfo {				/* leap second information */
118 	time_t		ls_trans;	/* transition time */
119 	int_fast32_t	ls_corr;	/* correction to apply */
120 };
121 
122 /* This abbreviation means local time is unspecified.  */
123 static char const UNSPEC[] = "-00";
124 
125 /* How many extra bytes are needed at the end of struct state's chars array.
126    This needs to be at least 1 for null termination in case the input
127    data isn't properly terminated, and it also needs to be big enough
128    for ttunspecified to work without crashing.  */
129 enum { CHARS_EXTRA = max(sizeof UNSPEC, 2) - 1 };
130 
131 #ifdef TZNAME_MAX
132 # define MY_TZNAME_MAX TZNAME_MAX
133 #endif /* defined TZNAME_MAX */
134 #ifndef TZNAME_MAX
135 # define MY_TZNAME_MAX 255
136 #endif /* !defined TZNAME_MAX */
137 
138 struct state {
139 	int		leapcnt;
140 	int		timecnt;
141 	int		typecnt;
142 	int		charcnt;
143 	bool		goback;
144 	bool		goahead;
145 	time_t		ats[TZ_MAX_TIMES];
146 	unsigned char	types[TZ_MAX_TIMES];
147 	struct ttinfo	ttis[TZ_MAX_TYPES];
148 	char chars[max(max(TZ_MAX_CHARS + CHARS_EXTRA, sizeof "UTC"),
149 		       2 * (MY_TZNAME_MAX + 1))];
150 	struct lsinfo	lsis[TZ_MAX_LEAPS];
151 
152 	/* The time type to use for early times or if no transitions.
153 	   It is always zero for recent tzdb releases.
154 	   It might be nonzero for data from tzdb 2018e or earlier.  */
155 	int defaulttype;
156 };
157 
158 enum r_type {
159   JULIAN_DAY,		/* Jn = Julian day */
160   DAY_OF_YEAR,		/* n = day of year */
161   MONTH_NTH_DAY_OF_WEEK	/* Mm.n.d = month, week, day of week */
162 };
163 
164 struct rule {
165 	enum r_type	r_type;		/* type of rule */
166 	int		r_day;		/* day number of rule */
167 	int		r_week;		/* week number of rule */
168 	int		r_mon;		/* month number of rule */
169 	int_fast32_t	r_time;		/* transition time of rule */
170 };
171 
172 static struct tm *gmtsub(struct state const *, time_t const *, int_fast32_t,
173 			 struct tm *);
174 static bool increment_overflow(int *, int);
175 static bool increment_overflow_time(time_t *, int_fast32_t);
176 static int_fast32_t leapcorr(struct state const *, time_t);
177 static bool normalize_overflow32(int_fast32_t *, int *, int);
178 static struct tm *timesub(time_t const *, int_fast32_t, struct state const *,
179 			  struct tm *);
180 static bool typesequiv(struct state const *, int, int);
181 static bool tzparse(char const *, struct state *, struct state *);
182 
183 #ifdef ALL_STATE
184 static struct state *	lclptr;
185 static struct state *	gmtptr;
186 #endif /* defined ALL_STATE */
187 
188 #ifndef ALL_STATE
189 static struct state	lclmem;
190 static struct state	gmtmem;
191 static struct state *const lclptr = &lclmem;
192 static struct state *const gmtptr = &gmtmem;
193 #endif /* State Farm */
194 
195 #ifndef TZ_STRLEN_MAX
196 # define TZ_STRLEN_MAX 255
197 #endif /* !defined TZ_STRLEN_MAX */
198 
199 static char		lcl_TZname[TZ_STRLEN_MAX + 1];
200 static int		lcl_is_set;
201 
202 static pthread_once_t	gmt_once = PTHREAD_ONCE_INIT;
203 static pthread_once_t	gmtime_once = PTHREAD_ONCE_INIT;
204 static pthread_key_t	gmtime_key;
205 static int		gmtime_key_error;
206 static pthread_once_t	localtime_once = PTHREAD_ONCE_INIT;
207 static pthread_key_t	localtime_key;
208 static int		localtime_key_error;
209 
210 /*
211 ** Section 4.12.3 of X3.159-1989 requires that
212 **	Except for the strftime function, these functions [asctime,
213 **	ctime, gmtime, localtime] return values in one of two static
214 **	objects: a broken-down time structure and an array of char.
215 ** Thanks to Paul Eggert for noting this.
216 */
217 
218 static struct tm	tm;
219 
220 #if 2 <= HAVE_TZNAME + TZ_TIME_T
221 char *			tzname[2] = {
222 	(char *) wildabbr,
223 	(char *) wildabbr
224 };
225 #endif
226 #if 2 <= USG_COMPAT + TZ_TIME_T
227 long			timezone;
228 int			daylight;
229 #endif
230 #if 2 <= ALTZONE + TZ_TIME_T
231 long			altzone;
232 #endif
233 
234 /* Initialize *S to a value based on UTOFF, ISDST, and DESIGIDX.  */
235 static void
236 init_ttinfo(struct ttinfo *s, int_fast32_t utoff, bool isdst, int desigidx)
237 {
238   s->tt_utoff = utoff;
239   s->tt_isdst = isdst;
240   s->tt_desigidx = desigidx;
241   s->tt_ttisstd = false;
242   s->tt_ttisut = false;
243 }
244 
245 /* Return true if SP's time type I does not specify local time.  */
246 static bool
247 ttunspecified(struct state const *sp, int i)
248 {
249   char const *abbr = &sp->chars[sp->ttis[i].tt_desigidx];
250   /* memcmp is likely faster than strcmp, and is safe due to CHARS_EXTRA.  */
251   return memcmp(abbr, UNSPEC, sizeof UNSPEC) == 0;
252 }
253 
254 static int_fast32_t
255 detzcode(const char *const codep)
256 {
257 	register int_fast32_t	result;
258 	register int		i;
259 	int_fast32_t one = 1;
260 	int_fast32_t halfmaxval = one << (32 - 2);
261 	int_fast32_t maxval = halfmaxval - 1 + halfmaxval;
262 	int_fast32_t minval = -1 - maxval;
263 
264 	result = codep[0] & 0x7f;
265 	for (i = 1; i < 4; ++i)
266 		result = (result << 8) | (codep[i] & 0xff);
267 
268 	if (codep[0] & 0x80) {
269 	  /* Do two's-complement negation even on non-two's-complement machines.
270 	     If the result would be minval - 1, return minval.  */
271 	  result -= !TWOS_COMPLEMENT(int_fast32_t) && result != 0;
272 	  result += minval;
273 	}
274 	return result;
275 }
276 
277 static int_fast64_t
278 detzcode64(const char *const codep)
279 {
280 	register int_fast64_t result;
281 	register int	i;
282 	int_fast64_t one = 1;
283 	int_fast64_t halfmaxval = one << (64 - 2);
284 	int_fast64_t maxval = halfmaxval - 1 + halfmaxval;
285 	int_fast64_t minval = -TWOS_COMPLEMENT(int_fast64_t) - maxval;
286 
287 	result = codep[0] & 0x7f;
288 	for (i = 1; i < 8; ++i)
289 		result = (result << 8) | (codep[i] & 0xff);
290 
291 	if (codep[0] & 0x80) {
292 	  /* Do two's-complement negation even on non-two's-complement machines.
293 	     If the result would be minval - 1, return minval.  */
294 	  result -= !TWOS_COMPLEMENT(int_fast64_t) && result != 0;
295 	  result += minval;
296 	}
297 	return result;
298 }
299 
300 static void
301 update_tzname_etc(struct state const *sp, struct ttinfo const *ttisp)
302 {
303 #if HAVE_TZNAME
304   tzname[ttisp->tt_isdst] = (char *) &sp->chars[ttisp->tt_desigidx];
305 #endif
306 #if USG_COMPAT
307   if (!ttisp->tt_isdst)
308     timezone = - ttisp->tt_utoff;
309 #endif
310 #if ALTZONE
311   if (ttisp->tt_isdst)
312     altzone = - ttisp->tt_utoff;
313 #endif
314 }
315 
316 /* If STDDST_MASK indicates that SP's TYPE provides useful info,
317    update tzname, timezone, and/or altzone and return STDDST_MASK,
318    diminished by the provided info if it is a specified local time.
319    Otherwise, return STDDST_MASK.  See settzname for STDDST_MASK.  */
320 static int
321 may_update_tzname_etc(int stddst_mask, struct state *sp, int type)
322 {
323   struct ttinfo *ttisp = &sp->ttis[type];
324   int this_bit = 1 << ttisp->tt_isdst;
325   if (stddst_mask & this_bit) {
326     update_tzname_etc(sp, ttisp);
327     if (!ttunspecified(sp, type))
328       return stddst_mask & ~this_bit;
329   }
330   return stddst_mask;
331 }
332 
333 static void
334 settzname(void)
335 {
336 	register struct state * const	sp = lclptr;
337 	register int			i;
338 
339 	/* If STDDST_MASK & 1 we need info about a standard time.
340 	   If STDDST_MASK & 2 we need info about a daylight saving time.
341 	   When STDDST_MASK becomes zero we can stop looking.  */
342 	int stddst_mask = 0;
343 
344 #if HAVE_TZNAME
345 	tzname[0] = tzname[1] = (char *) (sp ? wildabbr : utc);
346 	stddst_mask = 3;
347 #endif
348 #if USG_COMPAT
349 	timezone = 0;
350 	stddst_mask = 3;
351 #endif
352 #if ALTZONE
353 	altzone = 0;
354 	stddst_mask |= 2;
355 #endif
356 	/*
357 	** And to get the latest time zone abbreviations into tzname. . .
358 	*/
359 	if (sp) {
360 	  for (i = sp->timecnt - 1; stddst_mask && 0 <= i; i--)
361 	    stddst_mask = may_update_tzname_etc(stddst_mask, sp, sp->types[i]);
362 	  for (i = sp->typecnt - 1; stddst_mask && 0 <= i; i--)
363 	    stddst_mask = may_update_tzname_etc(stddst_mask, sp, i);
364 	}
365 #if USG_COMPAT
366 	daylight = stddst_mask >> 1 ^ 1;
367 #endif
368 }
369 
370 static void
371 scrub_abbrs(struct state *sp)
372 {
373 	int i;
374 	/*
375 	** First, replace bogus characters.
376 	*/
377 	for (i = 0; i < sp->charcnt; ++i)
378 		if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
379 			sp->chars[i] = TZ_ABBR_ERR_CHAR;
380 	/*
381 	** Second, truncate long abbreviations.
382 	*/
383 	for (i = 0; i < sp->typecnt; ++i) {
384 		register const struct ttinfo * const	ttisp = &sp->ttis[i];
385 		char *cp = &sp->chars[ttisp->tt_desigidx];
386 
387 		if (strlen(cp) > TZ_ABBR_MAX_LEN &&
388 			strcmp(cp, GRANDPARENTED) != 0)
389 				*(cp + TZ_ABBR_MAX_LEN) = '\0';
390 	}
391 }
392 
393 #ifdef DETECT_TZ_CHANGES
394 /*
395  * Determine if there's a change in the timezone since the last time we checked.
396  * Returns: -1 on error
397  * 	     0 if the timezone has not changed
398  *	     1 if the timezone has changed
399  */
400 static int
401 change_in_tz(const char *name)
402 {
403 	static char old_name[PATH_MAX];
404 	static struct stat old_sb;
405 	struct stat sb;
406 	int error;
407 
408 	error = stat(name, &sb);
409 	if (error != 0)
410 		return -1;
411 
412 	if (strcmp(name, old_name) != 0) {
413 		strlcpy(old_name, name, sizeof(old_name));
414 		old_sb = sb;
415 		return 1;
416 	}
417 
418 	if (sb.st_dev != old_sb.st_dev ||
419 	    sb.st_ino != old_sb.st_ino ||
420 	    sb.st_ctime != old_sb.st_ctime ||
421 	    sb.st_mtime != old_sb.st_mtime) {
422 		old_sb = sb;
423 		return 1;
424 	}
425 
426 	return 0;
427 }
428 #else /* !DETECT_TZ_CHANGES */
429 #define	change_in_tz(X)	1
430 #endif /* !DETECT_TZ_CHANGES */
431 
432 /* Input buffer for data read from a compiled tz file.  */
433 union input_buffer {
434   /* The first part of the buffer, interpreted as a header.  */
435   struct tzhead tzhead;
436 
437   /* The entire buffer.  */
438   char buf[2 * sizeof(struct tzhead) + 2 * sizeof(struct state)
439 	   + 4 * TZ_MAX_TIMES];
440 };
441 
442 /* TZDIR with a trailing '/' rather than a trailing '\0'.  */
443 static char const tzdirslash[sizeof TZDIR] = TZDIR "/";
444 
445 /* Local storage needed for 'tzloadbody'.  */
446 union local_storage {
447   /* The results of analyzing the file's contents after it is opened.  */
448   struct file_analysis {
449     /* The input buffer.  */
450     union input_buffer u;
451 
452     /* A temporary state used for parsing a TZ string in the file.  */
453     struct state st;
454   } u;
455 
456   /* The file name to be opened.  */
457   char fullname[max(sizeof(struct file_analysis), sizeof tzdirslash + 1024)];
458 };
459 
460 /* Load tz data from the file named NAME into *SP.  Read extended
461    format if DOEXTEND.  Use *LSP for temporary storage.  Return 0 on
462    success, an errno value on failure.  */
463 static int
464 tzloadbody(char const *name, struct state *sp, bool doextend,
465 	   union local_storage *lsp)
466 {
467 	register int			i;
468 	register int			fid;
469 	register int			stored;
470 	register ssize_t		nread;
471 	register union input_buffer *up = &lsp->u.u;
472 	register int tzheadsize = sizeof(struct tzhead);
473 
474 	sp->goback = sp->goahead = false;
475 
476 	if (! name) {
477 		name = TZDEFAULT;
478 		if (! name)
479 		  return EINVAL;
480 	}
481 
482 	if (name[0] == ':')
483 		++name;
484 	if (name[0] != '/') {
485 		if (sizeof lsp->fullname - sizeof tzdirslash <= strlen(name))
486 		  return ENAMETOOLONG;
487 
488 		/* Create a string "TZDIR/NAME".  Using sprintf here
489 		   would pull in stdio (and would fail if the
490 		   resulting string length exceeded INT_MAX!).  */
491 		memcpy(lsp->fullname, tzdirslash, sizeof tzdirslash);
492 		strcpy(lsp->fullname + sizeof tzdirslash, name);
493 
494 		name = lsp->fullname;
495 	}
496 	if (doextend) {
497 		/*
498 		 * Detect if the timezone file has changed.  Check
499 		 * 'doextend' to ignore TZDEFRULES; the change_in_tz()
500 		 * function can only keep state for a single file.
501 		 */
502 		int ret = change_in_tz(name);
503 		if (ret <= 0) {
504 			/*
505 			 * Returns an errno value if there was an error,
506 			 * and 0 if the timezone had not changed.
507 			 */
508 			return errno;
509 		}
510 	}
511 	fid = _open(name, O_RDONLY | O_BINARY);
512 	if (fid < 0)
513 	  return errno;
514 
515 	nread = _read(fid, up->buf, sizeof up->buf);
516 	if (nread < tzheadsize) {
517 	  int err = nread < 0 ? errno : EINVAL;
518 	  _close(fid);
519 	  return err;
520 	}
521 	if (_close(fid) < 0)
522 	  return errno;
523 	for (stored = 4; stored <= 8; stored *= 2) {
524 	    char version = up->tzhead.tzh_version[0];
525 	    bool skip_datablock = stored == 4 && version;
526 	    int_fast32_t datablock_size;
527 	    int_fast32_t ttisstdcnt = detzcode(up->tzhead.tzh_ttisstdcnt);
528 	    int_fast32_t ttisutcnt = detzcode(up->tzhead.tzh_ttisutcnt);
529 	    int_fast64_t prevtr = -1;
530 	    int_fast32_t prevcorr;
531 	    int_fast32_t leapcnt = detzcode(up->tzhead.tzh_leapcnt);
532 	    int_fast32_t timecnt = detzcode(up->tzhead.tzh_timecnt);
533 	    int_fast32_t typecnt = detzcode(up->tzhead.tzh_typecnt);
534 	    int_fast32_t charcnt = detzcode(up->tzhead.tzh_charcnt);
535 	    char const *p = up->buf + tzheadsize;
536 	    /* Although tzfile(5) currently requires typecnt to be nonzero,
537 	       support future formats that may allow zero typecnt
538 	       in files that have a TZ string and no transitions.  */
539 	    if (! (0 <= leapcnt && leapcnt < TZ_MAX_LEAPS
540 		   && 0 <= typecnt && typecnt < TZ_MAX_TYPES
541 		   && 0 <= timecnt && timecnt < TZ_MAX_TIMES
542 		   && 0 <= charcnt && charcnt < TZ_MAX_CHARS
543 		   && 0 <= ttisstdcnt && ttisstdcnt < TZ_MAX_TYPES
544 		   && 0 <= ttisutcnt && ttisutcnt < TZ_MAX_TYPES))
545 	      return EINVAL;
546 	    datablock_size
547 		    = (timecnt * stored		/* ats */
548 		       + timecnt		/* types */
549 		       + typecnt * 6		/* ttinfos */
550 		       + charcnt		/* chars */
551 		       + leapcnt * (stored + 4)	/* lsinfos */
552 		       + ttisstdcnt		/* ttisstds */
553 		       + ttisutcnt);		/* ttisuts */
554 	    if (nread < tzheadsize + datablock_size)
555 	      return EINVAL;
556 	    if (skip_datablock)
557 		p += datablock_size;
558 	    else {
559 		if (! ((ttisstdcnt == typecnt || ttisstdcnt == 0)
560 		       && (ttisutcnt == typecnt || ttisutcnt == 0)))
561 		  return EINVAL;
562 
563 		sp->leapcnt = leapcnt;
564 		sp->timecnt = timecnt;
565 		sp->typecnt = typecnt;
566 		sp->charcnt = charcnt;
567 
568 		/* Read transitions, discarding those out of time_t range.
569 		   But pretend the last transition before TIME_T_MIN
570 		   occurred at TIME_T_MIN.  */
571 		timecnt = 0;
572 		for (i = 0; i < sp->timecnt; ++i) {
573 			int_fast64_t at
574 			  = stored == 4 ? detzcode(p) : detzcode64(p);
575 			sp->types[i] = at <= TIME_T_MAX;
576 			if (sp->types[i]) {
577 			  time_t attime
578 			    = ((TYPE_SIGNED(time_t) ? at < TIME_T_MIN : at < 0)
579 			       ? TIME_T_MIN : at);
580 			  if (timecnt && attime <= sp->ats[timecnt - 1]) {
581 			    if (attime < sp->ats[timecnt - 1])
582 			      return EINVAL;
583 			    sp->types[i - 1] = 0;
584 			    timecnt--;
585 			  }
586 			  sp->ats[timecnt++] = attime;
587 			}
588 			p += stored;
589 		}
590 
591 		timecnt = 0;
592 		for (i = 0; i < sp->timecnt; ++i) {
593 			unsigned char typ = *p++;
594 			if (sp->typecnt <= typ)
595 			  return EINVAL;
596 			if (sp->types[i])
597 				sp->types[timecnt++] = typ;
598 		}
599 		sp->timecnt = timecnt;
600 		for (i = 0; i < sp->typecnt; ++i) {
601 			register struct ttinfo *	ttisp;
602 			unsigned char isdst, desigidx;
603 
604 			ttisp = &sp->ttis[i];
605 			ttisp->tt_utoff = detzcode(p);
606 			p += 4;
607 			isdst = *p++;
608 			if (! (isdst < 2))
609 			  return EINVAL;
610 			ttisp->tt_isdst = isdst;
611 			desigidx = *p++;
612 			if (! (desigidx < sp->charcnt))
613 			  return EINVAL;
614 			ttisp->tt_desigidx = desigidx;
615 		}
616 		for (i = 0; i < sp->charcnt; ++i)
617 			sp->chars[i] = *p++;
618 		/* Ensure '\0'-terminated, and make it safe to call
619 		   ttunspecified later.  */
620 		memset(&sp->chars[i], 0, CHARS_EXTRA);
621 
622 		/* Read leap seconds, discarding those out of time_t range.  */
623 		leapcnt = 0;
624 		for (i = 0; i < sp->leapcnt; ++i) {
625 		  int_fast64_t tr = stored == 4 ? detzcode(p) : detzcode64(p);
626 		  int_fast32_t corr = detzcode(p + stored);
627 		  p += stored + 4;
628 
629 		  /* Leap seconds cannot occur before the Epoch,
630 		     or out of order.  */
631 		  if (tr <= prevtr)
632 		    return EINVAL;
633 
634 		  /* To avoid other botches in this code, each leap second's
635 		     correction must differ from the previous one's by 1
636 		     second or less, except that the first correction can be
637 		     any value; these requirements are more generous than
638 		     RFC 8536, to allow future RFC extensions.  */
639 		  if (! (i == 0
640 			 || (prevcorr < corr
641 			     ? corr == prevcorr + 1
642 			     : (corr == prevcorr
643 				|| corr == prevcorr - 1))))
644 		    return EINVAL;
645 		  prevtr = tr;
646 		  prevcorr = corr;
647 
648 		  if (tr <= TIME_T_MAX) {
649 		    sp->lsis[leapcnt].ls_trans = tr;
650 		    sp->lsis[leapcnt].ls_corr = corr;
651 		    leapcnt++;
652 		  }
653 		}
654 		sp->leapcnt = leapcnt;
655 
656 		for (i = 0; i < sp->typecnt; ++i) {
657 			register struct ttinfo *	ttisp;
658 
659 			ttisp = &sp->ttis[i];
660 			if (ttisstdcnt == 0)
661 				ttisp->tt_ttisstd = false;
662 			else {
663 				if (*p != true && *p != false)
664 				  return EINVAL;
665 				ttisp->tt_ttisstd = *p++;
666 			}
667 		}
668 		for (i = 0; i < sp->typecnt; ++i) {
669 			register struct ttinfo *	ttisp;
670 
671 			ttisp = &sp->ttis[i];
672 			if (ttisutcnt == 0)
673 				ttisp->tt_ttisut = false;
674 			else {
675 				if (*p != true && *p != false)
676 						return EINVAL;
677 				ttisp->tt_ttisut = *p++;
678 			}
679 		}
680 	    }
681 
682 	    nread -= p - up->buf;
683 	    memmove(up->buf, p, nread);
684 
685 	    /* If this is an old file, we're done.  */
686 	    if (!version)
687 	      break;
688 	}
689 	if (doextend && nread > 2 &&
690 		up->buf[0] == '\n' && up->buf[nread - 1] == '\n' &&
691 		sp->typecnt + 2 <= TZ_MAX_TYPES) {
692 			struct state	*ts = &lsp->u.st;
693 
694 			up->buf[nread - 1] = '\0';
695 			if (tzparse(&up->buf[1], ts, sp)) {
696 
697 			  /* Attempt to reuse existing abbreviations.
698 			     Without this, America/Anchorage would be right on
699 			     the edge after 2037 when TZ_MAX_CHARS is 50, as
700 			     sp->charcnt equals 40 (for LMT AST AWT APT AHST
701 			     AHDT YST AKDT AKST) and ts->charcnt equals 10
702 			     (for AKST AKDT).  Reusing means sp->charcnt can
703 			     stay 40 in this example.  */
704 			  int gotabbr = 0;
705 			  int charcnt = sp->charcnt;
706 			  for (i = 0; i < ts->typecnt; i++) {
707 			    char *tsabbr = ts->chars + ts->ttis[i].tt_desigidx;
708 			    int j;
709 			    for (j = 0; j < charcnt; j++)
710 			      if (strcmp(sp->chars + j, tsabbr) == 0) {
711 				ts->ttis[i].tt_desigidx = j;
712 				gotabbr++;
713 				break;
714 			      }
715 			    if (! (j < charcnt)) {
716 			      int tsabbrlen = strlen(tsabbr);
717 			      if (j + tsabbrlen < TZ_MAX_CHARS) {
718 				strcpy(sp->chars + j, tsabbr);
719 				charcnt = j + tsabbrlen + 1;
720 				ts->ttis[i].tt_desigidx = j;
721 				gotabbr++;
722 			      }
723 			    }
724 			  }
725 			  if (gotabbr == ts->typecnt) {
726 			    sp->charcnt = charcnt;
727 
728 			    /* Ignore any trailing, no-op transitions generated
729 			       by zic as they don't help here and can run afoul
730 			       of bugs in zic 2016j or earlier.  */
731 			    while (1 < sp->timecnt
732 				   && (sp->types[sp->timecnt - 1]
733 				       == sp->types[sp->timecnt - 2]))
734 			      sp->timecnt--;
735 
736 			    for (i = 0;
737 				 i < ts->timecnt && sp->timecnt < TZ_MAX_TIMES;
738 				 i++) {
739 			      time_t t = ts->ats[i];
740 			      if (increment_overflow_time(&t, leapcorr(sp, t))
741 				  || (0 < sp->timecnt
742 				      && t <= sp->ats[sp->timecnt - 1]))
743 				continue;
744 			      sp->ats[sp->timecnt] = t;
745 			      sp->types[sp->timecnt] = (sp->typecnt
746 							+ ts->types[i]);
747 			      sp->timecnt++;
748 			    }
749 			    for (i = 0; i < ts->typecnt; i++)
750 			      sp->ttis[sp->typecnt++] = ts->ttis[i];
751 			  }
752 			}
753 	}
754 	if (sp->typecnt == 0)
755 	  return EINVAL;
756 	if (sp->timecnt > 1) {
757 	    if (sp->ats[0] <= TIME_T_MAX - SECSPERREPEAT) {
758 		time_t repeatat = sp->ats[0] + SECSPERREPEAT;
759 		int repeattype = sp->types[0];
760 		for (i = 1; i < sp->timecnt; ++i)
761 		  if (sp->ats[i] == repeatat
762 		      && typesequiv(sp, sp->types[i], repeattype)) {
763 					sp->goback = true;
764 					break;
765 		  }
766 	    }
767 	    if (TIME_T_MIN + SECSPERREPEAT <= sp->ats[sp->timecnt - 1]) {
768 		time_t repeatat = sp->ats[sp->timecnt - 1] - SECSPERREPEAT;
769 		int repeattype = sp->types[sp->timecnt - 1];
770 		for (i = sp->timecnt - 2; i >= 0; --i)
771 		  if (sp->ats[i] == repeatat
772 		      && typesequiv(sp, sp->types[i], repeattype)) {
773 					sp->goahead = true;
774 					break;
775 		  }
776 	    }
777 	}
778 
779 	/* Infer sp->defaulttype from the data.  Although this default
780 	   type is always zero for data from recent tzdb releases,
781 	   things are trickier for data from tzdb 2018e or earlier.
782 
783 	   The first set of heuristics work around bugs in 32-bit data
784 	   generated by tzdb 2013c or earlier.  The workaround is for
785 	   zones like Australia/Macquarie where timestamps before the
786 	   first transition have a time type that is not the earliest
787 	   standard-time type.  See:
788 	   https://mm.icann.org/pipermail/tz/2013-May/019368.html */
789 	/*
790 	** If type 0 does not specify local time, or is unused in transitions,
791 	** it's the type to use for early times.
792 	*/
793 	for (i = 0; i < sp->timecnt; ++i)
794 		if (sp->types[i] == 0)
795 			break;
796 	i = i < sp->timecnt && ! ttunspecified(sp, 0) ? -1 : 0;
797 	/*
798 	** Absent the above,
799 	** if there are transition times
800 	** and the first transition is to a daylight time
801 	** find the standard type less than and closest to
802 	** the type of the first transition.
803 	*/
804 	if (i < 0 && sp->timecnt > 0 && sp->ttis[sp->types[0]].tt_isdst) {
805 		i = sp->types[0];
806 		while (--i >= 0)
807 			if (!sp->ttis[i].tt_isdst)
808 				break;
809 	}
810 	/* The next heuristics are for data generated by tzdb 2018e or
811 	   earlier, for zones like EST5EDT where the first transition
812 	   is to DST.  */
813 	/*
814 	** If no result yet, find the first standard type.
815 	** If there is none, punt to type zero.
816 	*/
817 	if (i < 0) {
818 		i = 0;
819 		while (sp->ttis[i].tt_isdst)
820 			if (++i >= sp->typecnt) {
821 				i = 0;
822 				break;
823 			}
824 	}
825 	/* A simple 'sp->defaulttype = 0;' would suffice here if we
826 	   didn't have to worry about 2018e-or-earlier data.  Even
827 	   simpler would be to remove the defaulttype member and just
828 	   use 0 in its place.  */
829 	sp->defaulttype = i;
830 
831 	return 0;
832 }
833 
834 /* Load tz data from the file named NAME into *SP.  Read extended
835    format if DOEXTEND.  Return 0 on success, an errno value on failure.  */
836 static int
837 tzload(char const *name, struct state *sp, bool doextend)
838 {
839 #ifdef ALL_STATE
840   union local_storage *lsp = malloc(sizeof *lsp);
841   if (!lsp) {
842     return HAVE_MALLOC_ERRNO ? errno : ENOMEM;
843   } else {
844     int err = tzloadbody(name, sp, doextend, lsp);
845     free(lsp);
846     return err;
847   }
848 #else
849   union local_storage ls;
850   return tzloadbody(name, sp, doextend, &ls);
851 #endif
852 }
853 
854 static bool
855 typesequiv(const struct state *sp, int a, int b)
856 {
857 	register bool result;
858 
859 	if (sp == NULL ||
860 		a < 0 || a >= sp->typecnt ||
861 		b < 0 || b >= sp->typecnt)
862 			result = false;
863 	else {
864 		/* Compare the relevant members of *AP and *BP.
865 		   Ignore tt_ttisstd and tt_ttisut, as they are
866 		   irrelevant now and counting them could cause
867 		   sp->goahead to mistakenly remain false.  */
868 		register const struct ttinfo *	ap = &sp->ttis[a];
869 		register const struct ttinfo *	bp = &sp->ttis[b];
870 		result = (ap->tt_utoff == bp->tt_utoff
871 			  && ap->tt_isdst == bp->tt_isdst
872 			  && (strcmp(&sp->chars[ap->tt_desigidx],
873 				     &sp->chars[bp->tt_desigidx])
874 			      == 0));
875 	}
876 	return result;
877 }
878 
879 static const int	mon_lengths[2][MONSPERYEAR] = {
880 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
881 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
882 };
883 
884 static const int	year_lengths[2] = {
885 	DAYSPERNYEAR, DAYSPERLYEAR
886 };
887 
888 /* Is C an ASCII digit?  */
889 static bool
890 is_digit(char c)
891 {
892   return '0' <= c && c <= '9';
893 }
894 
895 /*
896 ** Given a pointer into a timezone string, scan until a character that is not
897 ** a valid character in a time zone abbreviation is found.
898 ** Return a pointer to that character.
899 */
900 
901 static ATTRIBUTE_REPRODUCIBLE const char *
902 getzname(register const char *strp)
903 {
904 	register char	c;
905 
906 	while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
907 		c != '+')
908 			++strp;
909 	return strp;
910 }
911 
912 /*
913 ** Given a pointer into an extended timezone string, scan until the ending
914 ** delimiter of the time zone abbreviation is located.
915 ** Return a pointer to the delimiter.
916 **
917 ** As with getzname above, the legal character set is actually quite
918 ** restricted, with other characters producing undefined results.
919 ** We don't do any checking here; checking is done later in common-case code.
920 */
921 
922 static ATTRIBUTE_REPRODUCIBLE const char *
923 getqzname(register const char *strp, const int delim)
924 {
925 	register int	c;
926 
927 	while ((c = *strp) != '\0' && c != delim)
928 		++strp;
929 	return strp;
930 }
931 
932 /*
933 ** Given a pointer into a timezone string, extract a number from that string.
934 ** Check that the number is within a specified range; if it is not, return
935 ** NULL.
936 ** Otherwise, return a pointer to the first character not part of the number.
937 */
938 
939 static const char *
940 getnum(register const char *strp, int *const nump, const int min, const int max)
941 {
942 	register char	c;
943 	register int	num;
944 
945 	if (strp == NULL || !is_digit(c = *strp))
946 		return NULL;
947 	num = 0;
948 	do {
949 		num = num * 10 + (c - '0');
950 		if (num > max)
951 			return NULL;	/* illegal value */
952 		c = *++strp;
953 	} while (is_digit(c));
954 	if (num < min)
955 		return NULL;		/* illegal value */
956 	*nump = num;
957 	return strp;
958 }
959 
960 /*
961 ** Given a pointer into a timezone string, extract a number of seconds,
962 ** in hh[:mm[:ss]] form, from the string.
963 ** If any error occurs, return NULL.
964 ** Otherwise, return a pointer to the first character not part of the number
965 ** of seconds.
966 */
967 
968 static const char *
969 getsecs(register const char *strp, int_fast32_t *const secsp)
970 {
971 	int	num;
972 	int_fast32_t secsperhour = SECSPERHOUR;
973 
974 	/*
975 	** 'HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
976 	** "M10.4.6/26", which does not conform to Posix,
977 	** but which specifies the equivalent of
978 	** "02:00 on the first Sunday on or after 23 Oct".
979 	*/
980 	strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
981 	if (strp == NULL)
982 		return NULL;
983 	*secsp = num * secsperhour;
984 	if (*strp == ':') {
985 		++strp;
986 		strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
987 		if (strp == NULL)
988 			return NULL;
989 		*secsp += num * SECSPERMIN;
990 		if (*strp == ':') {
991 			++strp;
992 			/* 'SECSPERMIN' allows for leap seconds.  */
993 			strp = getnum(strp, &num, 0, SECSPERMIN);
994 			if (strp == NULL)
995 				return NULL;
996 			*secsp += num;
997 		}
998 	}
999 	return strp;
1000 }
1001 
1002 /*
1003 ** Given a pointer into a timezone string, extract an offset, in
1004 ** [+-]hh[:mm[:ss]] form, from the string.
1005 ** If any error occurs, return NULL.
1006 ** Otherwise, return a pointer to the first character not part of the time.
1007 */
1008 
1009 static const char *
1010 getoffset(register const char *strp, int_fast32_t *const offsetp)
1011 {
1012 	register bool neg = false;
1013 
1014 	if (*strp == '-') {
1015 		neg = true;
1016 		++strp;
1017 	} else if (*strp == '+')
1018 		++strp;
1019 	strp = getsecs(strp, offsetp);
1020 	if (strp == NULL)
1021 		return NULL;		/* illegal time */
1022 	if (neg)
1023 		*offsetp = -*offsetp;
1024 	return strp;
1025 }
1026 
1027 /*
1028 ** Given a pointer into a timezone string, extract a rule in the form
1029 ** date[/time]. See POSIX section 8 for the format of "date" and "time".
1030 ** If a valid rule is not found, return NULL.
1031 ** Otherwise, return a pointer to the first character not part of the rule.
1032 */
1033 
1034 static const char *
1035 getrule(const char *strp, register struct rule *const rulep)
1036 {
1037 	if (*strp == 'J') {
1038 		/*
1039 		** Julian day.
1040 		*/
1041 		rulep->r_type = JULIAN_DAY;
1042 		++strp;
1043 		strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
1044 	} else if (*strp == 'M') {
1045 		/*
1046 		** Month, week, day.
1047 		*/
1048 		rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
1049 		++strp;
1050 		strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
1051 		if (strp == NULL)
1052 			return NULL;
1053 		if (*strp++ != '.')
1054 			return NULL;
1055 		strp = getnum(strp, &rulep->r_week, 1, 5);
1056 		if (strp == NULL)
1057 			return NULL;
1058 		if (*strp++ != '.')
1059 			return NULL;
1060 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
1061 	} else if (is_digit(*strp)) {
1062 		/*
1063 		** Day of year.
1064 		*/
1065 		rulep->r_type = DAY_OF_YEAR;
1066 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
1067 	} else	return NULL;		/* invalid format */
1068 	if (strp == NULL)
1069 		return NULL;
1070 	if (*strp == '/') {
1071 		/*
1072 		** Time specified.
1073 		*/
1074 		++strp;
1075 		strp = getoffset(strp, &rulep->r_time);
1076 	} else	rulep->r_time = 2 * SECSPERHOUR;	/* default = 2:00:00 */
1077 	return strp;
1078 }
1079 
1080 /*
1081 ** Given a year, a rule, and the offset from UT at the time that rule takes
1082 ** effect, calculate the year-relative time that rule takes effect.
1083 */
1084 
1085 static int_fast32_t
1086 transtime(const int year, register const struct rule *const rulep,
1087 	  const int_fast32_t offset)
1088 {
1089 	register bool	leapyear;
1090 	register int_fast32_t value;
1091 	register int	i;
1092 	int		d, m1, yy0, yy1, yy2, dow;
1093 
1094 	leapyear = isleap(year);
1095 	switch (rulep->r_type) {
1096 
1097 	case JULIAN_DAY:
1098 		/*
1099 		** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
1100 		** years.
1101 		** In non-leap years, or if the day number is 59 or less, just
1102 		** add SECSPERDAY times the day number-1 to the time of
1103 		** January 1, midnight, to get the day.
1104 		*/
1105 		value = (rulep->r_day - 1) * SECSPERDAY;
1106 		if (leapyear && rulep->r_day >= 60)
1107 			value += SECSPERDAY;
1108 		break;
1109 
1110 	case DAY_OF_YEAR:
1111 		/*
1112 		** n - day of year.
1113 		** Just add SECSPERDAY times the day number to the time of
1114 		** January 1, midnight, to get the day.
1115 		*/
1116 		value = rulep->r_day * SECSPERDAY;
1117 		break;
1118 
1119 	case MONTH_NTH_DAY_OF_WEEK:
1120 		/*
1121 		** Mm.n.d - nth "dth day" of month m.
1122 		*/
1123 
1124 		/*
1125 		** Use Zeller's Congruence to get day-of-week of first day of
1126 		** month.
1127 		*/
1128 		m1 = (rulep->r_mon + 9) % 12 + 1;
1129 		yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
1130 		yy1 = yy0 / 100;
1131 		yy2 = yy0 % 100;
1132 		dow = ((26 * m1 - 2) / 10 +
1133 			1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
1134 		if (dow < 0)
1135 			dow += DAYSPERWEEK;
1136 
1137 		/*
1138 		** "dow" is the day-of-week of the first day of the month. Get
1139 		** the day-of-month (zero-origin) of the first "dow" day of the
1140 		** month.
1141 		*/
1142 		d = rulep->r_day - dow;
1143 		if (d < 0)
1144 			d += DAYSPERWEEK;
1145 		for (i = 1; i < rulep->r_week; ++i) {
1146 			if (d + DAYSPERWEEK >=
1147 				mon_lengths[leapyear][rulep->r_mon - 1])
1148 					break;
1149 			d += DAYSPERWEEK;
1150 		}
1151 
1152 		/*
1153 		** "d" is the day-of-month (zero-origin) of the day we want.
1154 		*/
1155 		value = d * SECSPERDAY;
1156 		for (i = 0; i < rulep->r_mon - 1; ++i)
1157 			value += mon_lengths[leapyear][i] * SECSPERDAY;
1158 		break;
1159 
1160 	default: unreachable();
1161 	}
1162 
1163 	/*
1164 	** "value" is the year-relative time of 00:00:00 UT on the day in
1165 	** question. To get the year-relative time of the specified local
1166 	** time on that day, add the transition time and the current offset
1167 	** from UT.
1168 	*/
1169 	return value + rulep->r_time + offset;
1170 }
1171 
1172 /*
1173 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
1174 ** appropriate.
1175 */
1176 
1177 static bool
1178 tzparse(const char *name, struct state *sp, struct state *basep)
1179 {
1180 	const char *			stdname;
1181 	const char *			dstname;
1182 	int_fast32_t			stdoffset;
1183 	int_fast32_t			dstoffset;
1184 	register char *			cp;
1185 	register bool			load_ok;
1186 	ptrdiff_t stdlen, dstlen, charcnt;
1187 	time_t atlo = TIME_T_MIN, leaplo = TIME_T_MIN;
1188 
1189 	stdname = name;
1190 	if (*name == '<') {
1191 	  name++;
1192 	  stdname = name;
1193 	  name = getqzname(name, '>');
1194 	  if (*name != '>')
1195 	    return false;
1196 	  stdlen = name - stdname;
1197 	  name++;
1198 	} else {
1199 	  name = getzname(name);
1200 	  stdlen = name - stdname;
1201 	}
1202 	if (!stdlen)
1203 	  return false;
1204 	name = getoffset(name, &stdoffset);
1205 	if (name == NULL)
1206 	  return false;
1207 	charcnt = stdlen + 1;
1208 	if (sizeof sp->chars < charcnt)
1209 	  return false;
1210 	if (basep) {
1211 	  if (0 < basep->timecnt)
1212 	    atlo = basep->ats[basep->timecnt - 1];
1213 	  load_ok = false;
1214 	  sp->leapcnt = basep->leapcnt;
1215 	  memcpy(sp->lsis, basep->lsis, sp->leapcnt * sizeof *sp->lsis);
1216 	} else {
1217 	  load_ok = tzload(TZDEFRULES, sp, false) == 0;
1218 	  if (!load_ok)
1219 	    sp->leapcnt = 0;	/* So, we're off a little.  */
1220 	}
1221 	if (0 < sp->leapcnt)
1222 	  leaplo = sp->lsis[sp->leapcnt - 1].ls_trans;
1223 	if (*name != '\0') {
1224 		if (*name == '<') {
1225 			dstname = ++name;
1226 			name = getqzname(name, '>');
1227 			if (*name != '>')
1228 			  return false;
1229 			dstlen = name - dstname;
1230 			name++;
1231 		} else {
1232 			dstname = name;
1233 			name = getzname(name);
1234 			dstlen = name - dstname; /* length of DST abbr. */
1235 		}
1236 		if (!dstlen)
1237 		  return false;
1238 		charcnt += dstlen + 1;
1239 		if (sizeof sp->chars < charcnt)
1240 		  return false;
1241 		if (*name != '\0' && *name != ',' && *name != ';') {
1242 			name = getoffset(name, &dstoffset);
1243 			if (name == NULL)
1244 			  return false;
1245 		} else	dstoffset = stdoffset - SECSPERHOUR;
1246 		if (*name == '\0' && !load_ok)
1247 			name = TZDEFRULESTRING;
1248 		if (*name == ',' || *name == ';') {
1249 			struct rule	start;
1250 			struct rule	end;
1251 			register int	year;
1252 			register int	timecnt;
1253 			time_t		janfirst;
1254 			int_fast32_t janoffset = 0;
1255 			int yearbeg, yearlim;
1256 
1257 			++name;
1258 			if ((name = getrule(name, &start)) == NULL)
1259 			  return false;
1260 			if (*name++ != ',')
1261 			  return false;
1262 			if ((name = getrule(name, &end)) == NULL)
1263 			  return false;
1264 			if (*name != '\0')
1265 			  return false;
1266 			sp->typecnt = 2;	/* standard time and DST */
1267 			/*
1268 			** Two transitions per year, from EPOCH_YEAR forward.
1269 			*/
1270 			init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
1271 			init_ttinfo(&sp->ttis[1], -dstoffset, true, stdlen + 1);
1272 			sp->defaulttype = 0;
1273 			timecnt = 0;
1274 			janfirst = 0;
1275 			yearbeg = EPOCH_YEAR;
1276 
1277 			do {
1278 			  int_fast32_t yearsecs
1279 			    = year_lengths[isleap(yearbeg - 1)] * SECSPERDAY;
1280 			  yearbeg--;
1281 			  if (increment_overflow_time(&janfirst, -yearsecs)) {
1282 			    janoffset = -yearsecs;
1283 			    break;
1284 			  }
1285 			} while (atlo < janfirst
1286 				 && EPOCH_YEAR - YEARSPERREPEAT / 2 < yearbeg);
1287 
1288 			while (true) {
1289 			  int_fast32_t yearsecs
1290 			    = year_lengths[isleap(yearbeg)] * SECSPERDAY;
1291 			  int yearbeg1 = yearbeg;
1292 			  time_t janfirst1 = janfirst;
1293 			  if (increment_overflow_time(&janfirst1, yearsecs)
1294 			      || increment_overflow(&yearbeg1, 1)
1295 			      || atlo <= janfirst1)
1296 			    break;
1297 			  yearbeg = yearbeg1;
1298 			  janfirst = janfirst1;
1299 			}
1300 
1301 			yearlim = yearbeg;
1302 			if (increment_overflow(&yearlim, YEARSPERREPEAT + 1))
1303 			  yearlim = INT_MAX;
1304 			for (year = yearbeg; year < yearlim; year++) {
1305 				int_fast32_t
1306 				  starttime = transtime(year, &start, stdoffset),
1307 				  endtime = transtime(year, &end, dstoffset);
1308 				int_fast32_t
1309 				  yearsecs = (year_lengths[isleap(year)]
1310 					      * SECSPERDAY);
1311 				bool reversed = endtime < starttime;
1312 				if (reversed) {
1313 					int_fast32_t swap = starttime;
1314 					starttime = endtime;
1315 					endtime = swap;
1316 				}
1317 				if (reversed
1318 				    || (starttime < endtime
1319 					&& endtime - starttime < yearsecs)) {
1320 					if (TZ_MAX_TIMES - 2 < timecnt)
1321 						break;
1322 					sp->ats[timecnt] = janfirst;
1323 					if (! increment_overflow_time
1324 					    (&sp->ats[timecnt],
1325 					     janoffset + starttime)
1326 					    && atlo <= sp->ats[timecnt])
1327 					  sp->types[timecnt++] = !reversed;
1328 					sp->ats[timecnt] = janfirst;
1329 					if (! increment_overflow_time
1330 					    (&sp->ats[timecnt],
1331 					     janoffset + endtime)
1332 					    && atlo <= sp->ats[timecnt]) {
1333 					  sp->types[timecnt++] = reversed;
1334 					}
1335 				}
1336 				if (endtime < leaplo) {
1337 				  yearlim = year;
1338 				  if (increment_overflow(&yearlim,
1339 							 YEARSPERREPEAT + 1))
1340 				    yearlim = INT_MAX;
1341 				}
1342 				if (increment_overflow_time
1343 				    (&janfirst, janoffset + yearsecs))
1344 					break;
1345 				janoffset = 0;
1346 			}
1347 			sp->timecnt = timecnt;
1348 			if (! timecnt) {
1349 				sp->ttis[0] = sp->ttis[1];
1350 				sp->typecnt = 1;	/* Perpetual DST.  */
1351 			} else if (YEARSPERREPEAT < year - yearbeg)
1352 				sp->goback = sp->goahead = true;
1353 		} else {
1354 			register int_fast32_t	theirstdoffset;
1355 			register int_fast32_t	theirdstoffset;
1356 			register int_fast32_t	theiroffset;
1357 			register bool		isdst;
1358 			register int		i;
1359 			register int		j;
1360 
1361 			if (*name != '\0')
1362 			  return false;
1363 			/*
1364 			** Initial values of theirstdoffset and theirdstoffset.
1365 			*/
1366 			theirstdoffset = 0;
1367 			for (i = 0; i < sp->timecnt; ++i) {
1368 				j = sp->types[i];
1369 				if (!sp->ttis[j].tt_isdst) {
1370 					theirstdoffset =
1371 						- sp->ttis[j].tt_utoff;
1372 					break;
1373 				}
1374 			}
1375 			theirdstoffset = 0;
1376 			for (i = 0; i < sp->timecnt; ++i) {
1377 				j = sp->types[i];
1378 				if (sp->ttis[j].tt_isdst) {
1379 					theirdstoffset =
1380 						- sp->ttis[j].tt_utoff;
1381 					break;
1382 				}
1383 			}
1384 			/*
1385 			** Initially we're assumed to be in standard time.
1386 			*/
1387 			isdst = false;
1388 			/*
1389 			** Now juggle transition times and types
1390 			** tracking offsets as you do.
1391 			*/
1392 			for (i = 0; i < sp->timecnt; ++i) {
1393 				j = sp->types[i];
1394 				sp->types[i] = sp->ttis[j].tt_isdst;
1395 				if (sp->ttis[j].tt_ttisut) {
1396 					/* No adjustment to transition time */
1397 				} else {
1398 					/*
1399 					** If daylight saving time is in
1400 					** effect, and the transition time was
1401 					** not specified as standard time, add
1402 					** the daylight saving time offset to
1403 					** the transition time; otherwise, add
1404 					** the standard time offset to the
1405 					** transition time.
1406 					*/
1407 					/*
1408 					** Transitions from DST to DDST
1409 					** will effectively disappear since
1410 					** POSIX provides for only one DST
1411 					** offset.
1412 					*/
1413 					if (isdst && !sp->ttis[j].tt_ttisstd) {
1414 						sp->ats[i] += dstoffset -
1415 							theirdstoffset;
1416 					} else {
1417 						sp->ats[i] += stdoffset -
1418 							theirstdoffset;
1419 					}
1420 				}
1421 				theiroffset = -sp->ttis[j].tt_utoff;
1422 				if (sp->ttis[j].tt_isdst)
1423 					theirdstoffset = theiroffset;
1424 				else	theirstdoffset = theiroffset;
1425 			}
1426 			/*
1427 			** Finally, fill in ttis.
1428 			*/
1429 			init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
1430 			init_ttinfo(&sp->ttis[1], -dstoffset, true, stdlen + 1);
1431 			sp->typecnt = 2;
1432 			sp->defaulttype = 0;
1433 		}
1434 	} else {
1435 		dstlen = 0;
1436 		sp->typecnt = 1;		/* only standard time */
1437 		sp->timecnt = 0;
1438 		init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
1439 		sp->defaulttype = 0;
1440 	}
1441 	sp->charcnt = charcnt;
1442 	cp = sp->chars;
1443 	memcpy(cp, stdname, stdlen);
1444 	cp += stdlen;
1445 	*cp++ = '\0';
1446 	if (dstlen != 0) {
1447 		memcpy(cp, dstname, dstlen);
1448 		*(cp + dstlen) = '\0';
1449 	}
1450 	return true;
1451 }
1452 
1453 static void
1454 gmtload(struct state *const sp)
1455 {
1456 	if (tzload(etc_utc, sp, true) != 0)
1457 	  tzparse("UTC0", sp, NULL);
1458 }
1459 
1460 #ifdef DETECT_TZ_CHANGES
1461 static int
1462 recheck_tzdata()
1463 {
1464 	static time_t last_checked;
1465 	struct timespec now;
1466 	time_t current_time;
1467 	int error;
1468 
1469 	/*
1470 	 * We want to recheck the timezone file every 61 sec.
1471 	 */
1472 	error = clock_gettime(CLOCK_MONOTONIC, &now);
1473 	if (error < 0) {
1474 		/* XXX: Can we somehow report this? */
1475 		return 0;
1476 	}
1477 
1478 	current_time = now.tv_sec;
1479 	if ((current_time - last_checked > DETECT_TZ_CHANGES_INTERVAL) ||
1480 	    (last_checked > current_time)) {
1481 		last_checked = current_time;
1482 		return 1;
1483 	}
1484 
1485 	return 0;
1486 }
1487 #else /* !DETECT_TZ_CHANGES */
1488 #define	recheck_tzdata()	0
1489 #endif /* !DETECT_TZ_CHANGES */
1490 
1491 /* Initialize *SP to a value appropriate for the TZ setting NAME.
1492    Return 0 on success, an errno value on failure.  */
1493 static int
1494 zoneinit(struct state *sp, char const *name)
1495 {
1496   if (name && ! name[0]) {
1497     /*
1498     ** User wants it fast rather than right.
1499     */
1500     sp->leapcnt = 0;		/* so, we're off a little */
1501     sp->timecnt = 0;
1502     sp->typecnt = 0;
1503     sp->charcnt = 0;
1504     sp->goback = sp->goahead = false;
1505     init_ttinfo(&sp->ttis[0], 0, false, 0);
1506     strcpy(sp->chars, utc);
1507     sp->defaulttype = 0;
1508     return 0;
1509   } else {
1510     int err = tzload(name, sp, true);
1511     if (err != 0 && name && name[0] != ':' && tzparse(name, sp, NULL))
1512       err = 0;
1513     if (err == 0)
1514       scrub_abbrs(sp);
1515     return err;
1516   }
1517 }
1518 
1519 static void
1520 tzset_unlocked_name(char const *name)
1521 {
1522   struct state *sp = lclptr;
1523   int lcl = name ? strlen(name) < sizeof lcl_TZname : -1;
1524   if (lcl < 0
1525       ? lcl_is_set < 0
1526       : 0 < lcl_is_set && strcmp(lcl_TZname, name) == 0)
1527     if (recheck_tzdata() == 0)
1528       return;
1529 #ifdef ALL_STATE
1530   if (! sp)
1531     lclptr = sp = malloc(sizeof *lclptr);
1532 #endif /* defined ALL_STATE */
1533   if (sp) {
1534     if (zoneinit(sp, name) != 0)
1535       zoneinit(sp, "");
1536     if (0 < lcl)
1537       strcpy(lcl_TZname, name);
1538   }
1539   settzname();
1540   lcl_is_set = lcl;
1541 }
1542 
1543 static void
1544 tzset_unlocked(void)
1545 {
1546   tzset_unlocked_name(getenv("TZ"));
1547 }
1548 
1549 void
1550 tzset(void)
1551 {
1552   if (lock() != 0)
1553     return;
1554   tzset_unlocked();
1555   unlock();
1556 }
1557 
1558 void
1559 freebsd13_tzsetwall(void)
1560 {
1561   if (lock() != 0)
1562     return;
1563   tzset_unlocked_name(NULL);
1564   unlock();
1565 }
1566 __sym_compat(tzsetwall, freebsd13_tzsetwall, FBSD_1.0);
1567 __warn_references(tzsetwall,
1568     "warning: tzsetwall() is deprecated, use tzset() instead.");
1569 
1570 static void
1571 gmtcheck(void)
1572 {
1573   static bool gmt_is_set;
1574   if (lock() != 0)
1575     return;
1576   if (! gmt_is_set) {
1577 #ifdef ALL_STATE
1578     gmtptr = malloc(sizeof *gmtptr);
1579 #endif
1580     if (gmtptr)
1581       gmtload(gmtptr);
1582     gmt_is_set = true;
1583   }
1584   unlock();
1585 }
1586 
1587 #if NETBSD_INSPIRED
1588 
1589 timezone_t
1590 tzalloc(char const *name)
1591 {
1592   timezone_t sp = malloc(sizeof *sp);
1593   if (sp) {
1594     int err = zoneinit(sp, name);
1595     if (err != 0) {
1596       free(sp);
1597       errno = err;
1598       return NULL;
1599     }
1600   } else if (!HAVE_MALLOC_ERRNO)
1601     errno = ENOMEM;
1602   return sp;
1603 }
1604 
1605 void
1606 tzfree(timezone_t sp)
1607 {
1608   free(sp);
1609 }
1610 
1611 /*
1612 ** NetBSD 6.1.4 has ctime_rz, but omit it because POSIX says ctime and
1613 ** ctime_r are obsolescent and have potential security problems that
1614 ** ctime_rz would share.  Callers can instead use localtime_rz + strftime.
1615 **
1616 ** NetBSD 6.1.4 has tzgetname, but omit it because it doesn't work
1617 ** in zones with three or more time zone abbreviations.
1618 ** Callers can instead use localtime_rz + strftime.
1619 */
1620 
1621 #endif
1622 
1623 /*
1624 ** The easy way to behave "as if no library function calls" localtime
1625 ** is to not call it, so we drop its guts into "localsub", which can be
1626 ** freely called. (And no, the PANS doesn't require the above behavior,
1627 ** but it *is* desirable.)
1628 **
1629 ** If successful and SETNAME is nonzero,
1630 ** set the applicable parts of tzname, timezone and altzone;
1631 ** however, it's OK to omit this step if the timezone is POSIX-compatible,
1632 ** since in that case tzset should have already done this step correctly.
1633 ** SETNAME's type is int_fast32_t for compatibility with gmtsub,
1634 ** but it is actually a boolean and its value should be 0 or 1.
1635 */
1636 
1637 /*ARGSUSED*/
1638 static struct tm *
1639 localsub(struct state const *sp, time_t const *timep, int_fast32_t setname,
1640 	 struct tm *const tmp)
1641 {
1642 	register const struct ttinfo *	ttisp;
1643 	register int			i;
1644 	register struct tm *		result;
1645 	const time_t			t = *timep;
1646 
1647 	if (sp == NULL) {
1648 	  /* Don't bother to set tzname etc.; tzset has already done it.  */
1649 	  return gmtsub(gmtptr, timep, 0, tmp);
1650 	}
1651 	if ((sp->goback && t < sp->ats[0]) ||
1652 		(sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1653 			time_t newt;
1654 			register time_t		seconds;
1655 			register time_t		years;
1656 
1657 			if (t < sp->ats[0])
1658 				seconds = sp->ats[0] - t;
1659 			else	seconds = t - sp->ats[sp->timecnt - 1];
1660 			--seconds;
1661 
1662 			/* Beware integer overflow, as SECONDS might
1663 			   be close to the maximum time_t.  */
1664 			years = seconds / SECSPERREPEAT * YEARSPERREPEAT;
1665 			seconds = years * AVGSECSPERYEAR;
1666 			years += YEARSPERREPEAT;
1667 			if (t < sp->ats[0])
1668 			  newt = t + seconds + SECSPERREPEAT;
1669 			else
1670 			  newt = t - seconds - SECSPERREPEAT;
1671 
1672 			if (newt < sp->ats[0] ||
1673 				newt > sp->ats[sp->timecnt - 1])
1674 					return NULL;	/* "cannot happen" */
1675 			result = localsub(sp, &newt, setname, tmp);
1676 			if (result) {
1677 #if defined ckd_add && defined ckd_sub
1678 				if (t < sp->ats[0]
1679 				    ? ckd_sub(&result->tm_year,
1680 					      result->tm_year, years)
1681 				    : ckd_add(&result->tm_year,
1682 					      result->tm_year, years))
1683 				  return NULL;
1684 #else
1685 				register int_fast64_t newy;
1686 
1687 				newy = result->tm_year;
1688 				if (t < sp->ats[0])
1689 					newy -= years;
1690 				else	newy += years;
1691 				if (! (INT_MIN <= newy && newy <= INT_MAX))
1692 					return NULL;
1693 				result->tm_year = newy;
1694 #endif
1695 			}
1696 			return result;
1697 	}
1698 	if (sp->timecnt == 0 || t < sp->ats[0]) {
1699 		i = sp->defaulttype;
1700 	} else {
1701 		register int	lo = 1;
1702 		register int	hi = sp->timecnt;
1703 
1704 		while (lo < hi) {
1705 			register int	mid = (lo + hi) >> 1;
1706 
1707 			if (t < sp->ats[mid])
1708 				hi = mid;
1709 			else	lo = mid + 1;
1710 		}
1711 		i = sp->types[lo - 1];
1712 	}
1713 	ttisp = &sp->ttis[i];
1714 	/*
1715 	** To get (wrong) behavior that's compatible with System V Release 2.0
1716 	** you'd replace the statement below with
1717 	**	t += ttisp->tt_utoff;
1718 	**	timesub(&t, 0L, sp, tmp);
1719 	*/
1720 	result = timesub(&t, ttisp->tt_utoff, sp, tmp);
1721 	if (result) {
1722 	  result->tm_isdst = ttisp->tt_isdst;
1723 #ifdef TM_ZONE
1724 	  result->TM_ZONE = (char *) &sp->chars[ttisp->tt_desigidx];
1725 #endif /* defined TM_ZONE */
1726 	  if (setname)
1727 	    update_tzname_etc(sp, ttisp);
1728 	}
1729 	return result;
1730 }
1731 
1732 #if NETBSD_INSPIRED
1733 
1734 struct tm *
1735 localtime_rz(struct state *sp, time_t const *timep, struct tm *tmp)
1736 {
1737   return localsub(sp, timep, 0, tmp);
1738 }
1739 
1740 #endif
1741 
1742 static struct tm *
1743 localtime_tzset(time_t const *timep, struct tm *tmp, bool setname)
1744 {
1745   int err = lock();
1746   if (err) {
1747     errno = err;
1748     return NULL;
1749   }
1750 #ifndef DETECT_TZ_CHANGES
1751   if (setname || !lcl_is_set)
1752 #endif
1753     tzset_unlocked();
1754   tmp = localsub(lclptr, timep, setname, tmp);
1755   unlock();
1756   return tmp;
1757 }
1758 
1759 static void
1760 localtime_key_init(void)
1761 {
1762 
1763 	localtime_key_error = _pthread_key_create(&localtime_key, free);
1764 }
1765 
1766 struct tm *
1767 localtime(const time_t *timep)
1768 {
1769 	struct tm *p_tm = &tm;
1770 
1771 	if (__isthreaded != 0) {
1772 		_pthread_once(&localtime_once, localtime_key_init);
1773 		if (localtime_key_error != 0) {
1774 			errno = localtime_key_error;
1775 			return (NULL);
1776 		}
1777 		if ((p_tm = _pthread_getspecific(localtime_key)) == NULL) {
1778 			if ((p_tm = malloc(sizeof(*p_tm))) == NULL) {
1779 				return (NULL);
1780 			}
1781 			if (_pthread_setspecific(localtime_key, p_tm) != 0) {
1782 				free(p_tm);
1783 				return (NULL);
1784 			}
1785 		}
1786 	}
1787 	return localtime_tzset(timep, p_tm, true);
1788 }
1789 
1790 struct tm *
1791 localtime_r(const time_t *timep, struct tm *tmp)
1792 {
1793   return localtime_tzset(timep, tmp, false);
1794 }
1795 
1796 /*
1797 ** gmtsub is to gmtime as localsub is to localtime.
1798 */
1799 
1800 static struct tm *
1801 gmtsub(ATTRIBUTE_MAYBE_UNUSED struct state const *sp, time_t const *timep,
1802        int_fast32_t offset, struct tm *tmp)
1803 {
1804 	register struct tm *	result;
1805 
1806 	result = timesub(timep, offset, gmtptr, tmp);
1807 #ifdef TM_ZONE
1808 	/*
1809 	** Could get fancy here and deliver something such as
1810 	** "+xx" or "-xx" if offset is non-zero,
1811 	** but this is no time for a treasure hunt.
1812 	*/
1813 	tmp->TM_ZONE = ((char *)
1814 			(offset ? wildabbr : gmtptr ? gmtptr->chars : utc));
1815 #endif /* defined TM_ZONE */
1816 	return result;
1817 }
1818 
1819 /*
1820 * Re-entrant version of gmtime.
1821 */
1822 
1823 struct tm *
1824 gmtime_r(const time_t *timep, struct tm *tmp)
1825 {
1826 	_once(&gmt_once, gmtcheck);
1827 	return gmtsub(gmtptr, timep, 0, tmp);
1828 }
1829 
1830 static void
1831 gmtime_key_init(void)
1832 {
1833 
1834 	gmtime_key_error = _pthread_key_create(&gmtime_key, free);
1835 }
1836 
1837 struct tm *
1838 gmtime(const time_t *timep)
1839 {
1840 	struct tm *p_tm = &tm;
1841 
1842 	if (__isthreaded != 0) {
1843 		_pthread_once(&gmtime_once, gmtime_key_init);
1844 		if (gmtime_key_error != 0) {
1845 			errno = gmtime_key_error;
1846 			return (NULL);
1847 		}
1848 		if ((p_tm = _pthread_getspecific(gmtime_key)) == NULL) {
1849 			if ((p_tm = malloc(sizeof(*p_tm))) == NULL) {
1850 				return (NULL);
1851 			}
1852 			if (_pthread_setspecific(gmtime_key, p_tm) != 0) {
1853 				free(p_tm);
1854 				return (NULL);
1855 			}
1856 		}
1857 	}
1858 	return gmtime_r(timep, p_tm);
1859 }
1860 
1861 #ifdef STD_INSPIRED
1862 
1863 struct tm *
1864 offtime(const time_t *timep, long offset)
1865 {
1866   _once(&gmt_once, gmtcheck);
1867   return gmtsub(gmtptr, timep, offset, &tm);
1868 }
1869 
1870 #endif /* defined STD_INSPIRED */
1871 
1872 /*
1873 ** Return the number of leap years through the end of the given year
1874 ** where, to make the math easy, the answer for year zero is defined as zero.
1875 */
1876 
1877 static time_t
1878 leaps_thru_end_of_nonneg(time_t y)
1879 {
1880   return y / 4 - y / 100 + y / 400;
1881 }
1882 
1883 static time_t
1884 leaps_thru_end_of(time_t y)
1885 {
1886   return (y < 0
1887 	  ? -1 - leaps_thru_end_of_nonneg(-1 - y)
1888 	  : leaps_thru_end_of_nonneg(y));
1889 }
1890 
1891 static struct tm *
1892 timesub(const time_t *timep, int_fast32_t offset,
1893 	const struct state *sp, struct tm *tmp)
1894 {
1895 	register const struct lsinfo *	lp;
1896 	register time_t			tdays;
1897 	register const int *		ip;
1898 	register int_fast32_t		corr;
1899 	register int			i;
1900 	int_fast32_t idays, rem, dayoff, dayrem;
1901 	time_t y;
1902 
1903 	/* If less than SECSPERMIN, the number of seconds since the
1904 	   most recent positive leap second; otherwise, do not add 1
1905 	   to localtime tm_sec because of leap seconds.  */
1906 	time_t secs_since_posleap = SECSPERMIN;
1907 
1908 	corr = 0;
1909 	i = (sp == NULL) ? 0 : sp->leapcnt;
1910 	while (--i >= 0) {
1911 		lp = &sp->lsis[i];
1912 		if (*timep >= lp->ls_trans) {
1913 			corr = lp->ls_corr;
1914 			if ((i == 0 ? 0 : lp[-1].ls_corr) < corr)
1915 			  secs_since_posleap = *timep - lp->ls_trans;
1916 			break;
1917 		}
1918 	}
1919 
1920 	/* Calculate the year, avoiding integer overflow even if
1921 	   time_t is unsigned.  */
1922 	tdays = *timep / SECSPERDAY;
1923 	rem = *timep % SECSPERDAY;
1924 	rem += offset % SECSPERDAY - corr % SECSPERDAY + 3 * SECSPERDAY;
1925 	dayoff = offset / SECSPERDAY - corr / SECSPERDAY + rem / SECSPERDAY - 3;
1926 	rem %= SECSPERDAY;
1927 	/* y = (EPOCH_YEAR
1928 	        + floor((tdays + dayoff) / DAYSPERREPEAT) * YEARSPERREPEAT),
1929 	   sans overflow.  But calculate against 1570 (EPOCH_YEAR -
1930 	   YEARSPERREPEAT) instead of against 1970 so that things work
1931 	   for localtime values before 1970 when time_t is unsigned.  */
1932 	dayrem = tdays % DAYSPERREPEAT;
1933 	dayrem += dayoff % DAYSPERREPEAT;
1934 	y = (EPOCH_YEAR - YEARSPERREPEAT
1935 	     + ((1 + dayoff / DAYSPERREPEAT + dayrem / DAYSPERREPEAT
1936 		 - ((dayrem % DAYSPERREPEAT) < 0)
1937 		 + tdays / DAYSPERREPEAT)
1938 		* YEARSPERREPEAT));
1939 	/* idays = (tdays + dayoff) mod DAYSPERREPEAT, sans overflow.  */
1940 	idays = tdays % DAYSPERREPEAT;
1941 	idays += dayoff % DAYSPERREPEAT + 2 * DAYSPERREPEAT;
1942 	idays %= DAYSPERREPEAT;
1943 	/* Increase Y and decrease IDAYS until IDAYS is in range for Y.  */
1944 	while (year_lengths[isleap(y)] <= idays) {
1945 		int tdelta = idays / DAYSPERLYEAR;
1946 		int_fast32_t ydelta = tdelta + !tdelta;
1947 		time_t newy = y + ydelta;
1948 		register int	leapdays;
1949 		leapdays = leaps_thru_end_of(newy - 1) -
1950 			leaps_thru_end_of(y - 1);
1951 		idays -= ydelta * DAYSPERNYEAR;
1952 		idays -= leapdays;
1953 		y = newy;
1954 	}
1955 
1956 #ifdef ckd_add
1957 	if (ckd_add(&tmp->tm_year, y, -TM_YEAR_BASE)) {
1958 	  errno = EOVERFLOW;
1959 	  return NULL;
1960 	}
1961 #else
1962 	if (!TYPE_SIGNED(time_t) && y < TM_YEAR_BASE) {
1963 	  int signed_y = y;
1964 	  tmp->tm_year = signed_y - TM_YEAR_BASE;
1965 	} else if ((!TYPE_SIGNED(time_t) || INT_MIN + TM_YEAR_BASE <= y)
1966 		   && y - TM_YEAR_BASE <= INT_MAX)
1967 	  tmp->tm_year = y - TM_YEAR_BASE;
1968 	else {
1969 	  errno = EOVERFLOW;
1970 	  return NULL;
1971 	}
1972 #endif
1973 	tmp->tm_yday = idays;
1974 	/*
1975 	** The "extra" mods below avoid overflow problems.
1976 	*/
1977 	tmp->tm_wday = (TM_WDAY_BASE
1978 			+ ((tmp->tm_year % DAYSPERWEEK)
1979 			   * (DAYSPERNYEAR % DAYSPERWEEK))
1980 			+ leaps_thru_end_of(y - 1)
1981 			- leaps_thru_end_of(TM_YEAR_BASE - 1)
1982 			+ idays);
1983 	tmp->tm_wday %= DAYSPERWEEK;
1984 	if (tmp->tm_wday < 0)
1985 		tmp->tm_wday += DAYSPERWEEK;
1986 	tmp->tm_hour = rem / SECSPERHOUR;
1987 	rem %= SECSPERHOUR;
1988 	tmp->tm_min = rem / SECSPERMIN;
1989 	tmp->tm_sec = rem % SECSPERMIN;
1990 
1991 	/* Use "... ??:??:60" at the end of the localtime minute containing
1992 	   the second just before the positive leap second.  */
1993 	tmp->tm_sec += secs_since_posleap <= tmp->tm_sec;
1994 
1995 	ip = mon_lengths[isleap(y)];
1996 	for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1997 		idays -= ip[tmp->tm_mon];
1998 	tmp->tm_mday = idays + 1;
1999 	tmp->tm_isdst = 0;
2000 #ifdef TM_GMTOFF
2001 	tmp->TM_GMTOFF = offset;
2002 #endif /* defined TM_GMTOFF */
2003 	return tmp;
2004 }
2005 
2006 char *
2007 ctime(const time_t *timep)
2008 {
2009 /*
2010 ** Section 4.12.3.2 of X3.159-1989 requires that
2011 **	The ctime function converts the calendar time pointed to by timer
2012 **	to local time in the form of a string. It is equivalent to
2013 **		asctime(localtime(timer))
2014 */
2015   struct tm *tmp = localtime(timep);
2016   return tmp ? asctime(tmp) : NULL;
2017 }
2018 
2019 char *
2020 ctime_r(const time_t *timep, char *buf)
2021 {
2022   struct tm mytm;
2023   struct tm *tmp = localtime_r(timep, &mytm);
2024   return tmp ? asctime_r(tmp, buf) : NULL;
2025 }
2026 
2027 /*
2028 ** Adapted from code provided by Robert Elz, who writes:
2029 **	The "best" way to do mktime I think is based on an idea of Bob
2030 **	Kridle's (so its said...) from a long time ago.
2031 **	It does a binary search of the time_t space. Since time_t's are
2032 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
2033 **	would still be very reasonable).
2034 */
2035 
2036 #ifndef WRONG
2037 # define WRONG (-1)
2038 #endif /* !defined WRONG */
2039 
2040 /*
2041 ** Normalize logic courtesy Paul Eggert.
2042 */
2043 
2044 static bool
2045 increment_overflow(int *ip, int j)
2046 {
2047 #ifdef ckd_add
2048 	return ckd_add(ip, *ip, j);
2049 #else
2050 	register int const	i = *ip;
2051 
2052 	/*
2053 	** If i >= 0 there can only be overflow if i + j > INT_MAX
2054 	** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
2055 	** If i < 0 there can only be overflow if i + j < INT_MIN
2056 	** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
2057 	*/
2058 	if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
2059 		return true;
2060 	*ip += j;
2061 	return false;
2062 #endif
2063 }
2064 
2065 static bool
2066 increment_overflow32(int_fast32_t *const lp, int const m)
2067 {
2068 #ifdef ckd_add
2069 	return ckd_add(lp, *lp, m);
2070 #else
2071 	register int_fast32_t const	l = *lp;
2072 
2073 	if ((l >= 0) ? (m > INT_FAST32_MAX - l) : (m < INT_FAST32_MIN - l))
2074 		return true;
2075 	*lp += m;
2076 	return false;
2077 #endif
2078 }
2079 
2080 static bool
2081 increment_overflow_time(time_t *tp, int_fast32_t j)
2082 {
2083 #ifdef ckd_add
2084 	return ckd_add(tp, *tp, j);
2085 #else
2086 	/*
2087 	** This is like
2088 	** 'if (! (TIME_T_MIN <= *tp + j && *tp + j <= TIME_T_MAX)) ...',
2089 	** except that it does the right thing even if *tp + j would overflow.
2090 	*/
2091 	if (! (j < 0
2092 	       ? (TYPE_SIGNED(time_t) ? TIME_T_MIN - j <= *tp : -1 - j < *tp)
2093 	       : *tp <= TIME_T_MAX - j))
2094 		return true;
2095 	*tp += j;
2096 	return false;
2097 #endif
2098 }
2099 
2100 static bool
2101 normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
2102 {
2103 	register int	tensdelta;
2104 
2105 	tensdelta = (*unitsptr >= 0) ?
2106 		(*unitsptr / base) :
2107 		(-1 - (-1 - *unitsptr) / base);
2108 	*unitsptr -= tensdelta * base;
2109 	return increment_overflow(tensptr, tensdelta);
2110 }
2111 
2112 static bool
2113 normalize_overflow32(int_fast32_t *tensptr, int *unitsptr, int base)
2114 {
2115 	register int	tensdelta;
2116 
2117 	tensdelta = (*unitsptr >= 0) ?
2118 		(*unitsptr / base) :
2119 		(-1 - (-1 - *unitsptr) / base);
2120 	*unitsptr -= tensdelta * base;
2121 	return increment_overflow32(tensptr, tensdelta);
2122 }
2123 
2124 static int
2125 tmcomp(register const struct tm *const atmp,
2126        register const struct tm *const btmp)
2127 {
2128 	register int	result;
2129 
2130 	if (atmp->tm_year != btmp->tm_year)
2131 		return atmp->tm_year < btmp->tm_year ? -1 : 1;
2132 	if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
2133 		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
2134 		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
2135 		(result = (atmp->tm_min - btmp->tm_min)) == 0)
2136 			result = atmp->tm_sec - btmp->tm_sec;
2137 	return result;
2138 }
2139 
2140 /* Copy to *DEST from *SRC.  Copy only the members needed for mktime,
2141    as other members might not be initialized.  */
2142 static void
2143 mktmcpy(struct tm *dest, struct tm const *src)
2144 {
2145   dest->tm_sec = src->tm_sec;
2146   dest->tm_min = src->tm_min;
2147   dest->tm_hour = src->tm_hour;
2148   dest->tm_mday = src->tm_mday;
2149   dest->tm_mon = src->tm_mon;
2150   dest->tm_year = src->tm_year;
2151   dest->tm_isdst = src->tm_isdst;
2152 #if defined TM_GMTOFF && ! UNINIT_TRAP
2153   dest->TM_GMTOFF = src->TM_GMTOFF;
2154 #endif
2155 }
2156 
2157 static time_t
2158 time2sub(struct tm *const tmp,
2159 	 struct tm *(*funcp)(struct state const *, time_t const *,
2160 			     int_fast32_t, struct tm *),
2161 	 struct state const *sp,
2162 	 const int_fast32_t offset,
2163 	 bool *okayp,
2164 	 bool do_norm_secs)
2165 {
2166 	register int			dir;
2167 	register int			i, j;
2168 	register int			saved_seconds;
2169 	register int_fast32_t		li;
2170 	register time_t			lo;
2171 	register time_t			hi;
2172 	int_fast32_t			y;
2173 	time_t				newt;
2174 	time_t				t;
2175 	struct tm			yourtm, mytm;
2176 
2177 	*okayp = false;
2178 	mktmcpy(&yourtm, tmp);
2179 
2180 	if (do_norm_secs) {
2181 		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
2182 			SECSPERMIN))
2183 				return WRONG;
2184 	}
2185 	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
2186 		return WRONG;
2187 	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
2188 		return WRONG;
2189 	y = yourtm.tm_year;
2190 	if (normalize_overflow32(&y, &yourtm.tm_mon, MONSPERYEAR))
2191 		return WRONG;
2192 	/*
2193 	** Turn y into an actual year number for now.
2194 	** It is converted back to an offset from TM_YEAR_BASE later.
2195 	*/
2196 	if (increment_overflow32(&y, TM_YEAR_BASE))
2197 		return WRONG;
2198 	while (yourtm.tm_mday <= 0) {
2199 		if (increment_overflow32(&y, -1))
2200 			return WRONG;
2201 		li = y + (1 < yourtm.tm_mon);
2202 		yourtm.tm_mday += year_lengths[isleap(li)];
2203 	}
2204 	while (yourtm.tm_mday > DAYSPERLYEAR) {
2205 		li = y + (1 < yourtm.tm_mon);
2206 		yourtm.tm_mday -= year_lengths[isleap(li)];
2207 		if (increment_overflow32(&y, 1))
2208 			return WRONG;
2209 	}
2210 	for ( ; ; ) {
2211 		i = mon_lengths[isleap(y)][yourtm.tm_mon];
2212 		if (yourtm.tm_mday <= i)
2213 			break;
2214 		yourtm.tm_mday -= i;
2215 		if (++yourtm.tm_mon >= MONSPERYEAR) {
2216 			yourtm.tm_mon = 0;
2217 			if (increment_overflow32(&y, 1))
2218 				return WRONG;
2219 		}
2220 	}
2221 #ifdef ckd_add
2222 	if (ckd_add(&yourtm.tm_year, y, -TM_YEAR_BASE))
2223 	  return WRONG;
2224 #else
2225 	if (increment_overflow32(&y, -TM_YEAR_BASE))
2226 		return WRONG;
2227 	if (! (INT_MIN <= y && y <= INT_MAX))
2228 		return WRONG;
2229 	yourtm.tm_year = y;
2230 #endif
2231 	if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
2232 		saved_seconds = 0;
2233 	else if (yourtm.tm_year < EPOCH_YEAR - TM_YEAR_BASE) {
2234 		/*
2235 		** We can't set tm_sec to 0, because that might push the
2236 		** time below the minimum representable time.
2237 		** Set tm_sec to 59 instead.
2238 		** This assumes that the minimum representable time is
2239 		** not in the same minute that a leap second was deleted from,
2240 		** which is a safer assumption than using 58 would be.
2241 		*/
2242 		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
2243 			return WRONG;
2244 		saved_seconds = yourtm.tm_sec;
2245 		yourtm.tm_sec = SECSPERMIN - 1;
2246 	} else {
2247 		saved_seconds = yourtm.tm_sec;
2248 		yourtm.tm_sec = 0;
2249 	}
2250 	/*
2251 	** Do a binary search (this works whatever time_t's type is).
2252 	*/
2253 	lo = TIME_T_MIN;
2254 	hi = TIME_T_MAX;
2255 	for ( ; ; ) {
2256 		t = lo / 2 + hi / 2;
2257 		if (t < lo)
2258 			t = lo;
2259 		else if (t > hi)
2260 			t = hi;
2261 		if (! funcp(sp, &t, offset, &mytm)) {
2262 			/*
2263 			** Assume that t is too extreme to be represented in
2264 			** a struct tm; arrange things so that it is less
2265 			** extreme on the next pass.
2266 			*/
2267 			dir = (t > 0) ? 1 : -1;
2268 		} else	dir = tmcomp(&mytm, &yourtm);
2269 		if (dir != 0) {
2270 			if (t == lo) {
2271 				if (t == TIME_T_MAX)
2272 					return WRONG;
2273 				++t;
2274 				++lo;
2275 			} else if (t == hi) {
2276 				if (t == TIME_T_MIN)
2277 					return WRONG;
2278 				--t;
2279 				--hi;
2280 			}
2281 			if (lo > hi)
2282 				return WRONG;
2283 			if (dir > 0)
2284 				hi = t;
2285 			else	lo = t;
2286 			continue;
2287 		}
2288 #if defined TM_GMTOFF && ! UNINIT_TRAP
2289 		if (mytm.TM_GMTOFF != yourtm.TM_GMTOFF
2290 		    && (yourtm.TM_GMTOFF < 0
2291 			? (-SECSPERDAY <= yourtm.TM_GMTOFF
2292 			   && (mytm.TM_GMTOFF <=
2293 			       (min(INT_FAST32_MAX, LONG_MAX)
2294 				+ yourtm.TM_GMTOFF)))
2295 			: (yourtm.TM_GMTOFF <= SECSPERDAY
2296 			   && ((max(INT_FAST32_MIN, LONG_MIN)
2297 				+ yourtm.TM_GMTOFF)
2298 			       <= mytm.TM_GMTOFF)))) {
2299 		  /* MYTM matches YOURTM except with the wrong UT offset.
2300 		     YOURTM.TM_GMTOFF is plausible, so try it instead.
2301 		     It's OK if YOURTM.TM_GMTOFF contains uninitialized data,
2302 		     since the guess gets checked.  */
2303 		  time_t altt = t;
2304 		  int_fast32_t diff = mytm.TM_GMTOFF - yourtm.TM_GMTOFF;
2305 		  if (!increment_overflow_time(&altt, diff)) {
2306 		    struct tm alttm;
2307 		    if (funcp(sp, &altt, offset, &alttm)
2308 			&& alttm.tm_isdst == mytm.tm_isdst
2309 			&& alttm.TM_GMTOFF == yourtm.TM_GMTOFF
2310 			&& tmcomp(&alttm, &yourtm) == 0) {
2311 		      t = altt;
2312 		      mytm = alttm;
2313 		    }
2314 		  }
2315 		}
2316 #endif
2317 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
2318 			break;
2319 		/*
2320 		** Right time, wrong type.
2321 		** Hunt for right time, right type.
2322 		** It's okay to guess wrong since the guess
2323 		** gets checked.
2324 		*/
2325 		if (sp == NULL)
2326 			return WRONG;
2327 		for (i = sp->typecnt - 1; i >= 0; --i) {
2328 			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
2329 				continue;
2330 			for (j = sp->typecnt - 1; j >= 0; --j) {
2331 				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
2332 					continue;
2333 				if (ttunspecified(sp, j))
2334 				  continue;
2335 				newt = (t + sp->ttis[j].tt_utoff
2336 					- sp->ttis[i].tt_utoff);
2337 				if (! funcp(sp, &newt, offset, &mytm))
2338 					continue;
2339 				if (tmcomp(&mytm, &yourtm) != 0)
2340 					continue;
2341 				if (mytm.tm_isdst != yourtm.tm_isdst)
2342 					continue;
2343 				/*
2344 				** We have a match.
2345 				*/
2346 				t = newt;
2347 				goto label;
2348 			}
2349 		}
2350 		return WRONG;
2351 	}
2352 label:
2353 	newt = t + saved_seconds;
2354 	if ((newt < t) != (saved_seconds < 0))
2355 		return WRONG;
2356 	t = newt;
2357 	if (funcp(sp, &t, offset, tmp))
2358 		*okayp = true;
2359 	return t;
2360 }
2361 
2362 static time_t
2363 time2(struct tm * const	tmp,
2364       struct tm *(*funcp)(struct state const *, time_t const *,
2365 			  int_fast32_t, struct tm *),
2366       struct state const *sp,
2367       const int_fast32_t offset,
2368       bool *okayp)
2369 {
2370 	time_t	t;
2371 
2372 	/*
2373 	** First try without normalization of seconds
2374 	** (in case tm_sec contains a value associated with a leap second).
2375 	** If that fails, try with normalization of seconds.
2376 	*/
2377 	t = time2sub(tmp, funcp, sp, offset, okayp, false);
2378 	return *okayp ? t : time2sub(tmp, funcp, sp, offset, okayp, true);
2379 }
2380 
2381 static time_t
2382 time1(struct tm *const tmp,
2383       struct tm *(*funcp)(struct state const *, time_t const *,
2384 			  int_fast32_t, struct tm *),
2385       struct state const *sp,
2386       const int_fast32_t offset)
2387 {
2388 	register time_t			t;
2389 	register int			samei, otheri;
2390 	register int			sameind, otherind;
2391 	register int			i;
2392 	register int			nseen;
2393 	char				seen[TZ_MAX_TYPES];
2394 	unsigned char			types[TZ_MAX_TYPES];
2395 	bool				okay;
2396 
2397 	if (tmp == NULL) {
2398 		errno = EINVAL;
2399 		return WRONG;
2400 	}
2401 
2402 	if (tmp->tm_isdst > 1)
2403 		tmp->tm_isdst = 1;
2404 	t = time2(tmp, funcp, sp, offset, &okay);
2405 	if (okay)
2406 		return t;
2407 	if (tmp->tm_isdst < 0)
2408 #ifdef PCTS
2409 		/*
2410 		** POSIX Conformance Test Suite code courtesy Grant Sullivan.
2411 		*/
2412 		tmp->tm_isdst = 0;	/* reset to std and try again */
2413 #else
2414 		return t;
2415 #endif /* !defined PCTS */
2416 	/*
2417 	** We're supposed to assume that somebody took a time of one type
2418 	** and did some math on it that yielded a "struct tm" that's bad.
2419 	** We try to divine the type they started from and adjust to the
2420 	** type they need.
2421 	*/
2422 	if (sp == NULL)
2423 		return WRONG;
2424 	for (i = 0; i < sp->typecnt; ++i)
2425 		seen[i] = false;
2426 	nseen = 0;
2427 	for (i = sp->timecnt - 1; i >= 0; --i)
2428 		if (!seen[sp->types[i]] && !ttunspecified(sp, sp->types[i])) {
2429 			seen[sp->types[i]] = true;
2430 			types[nseen++] = sp->types[i];
2431 		}
2432 	for (sameind = 0; sameind < nseen; ++sameind) {
2433 		samei = types[sameind];
2434 		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
2435 			continue;
2436 		for (otherind = 0; otherind < nseen; ++otherind) {
2437 			otheri = types[otherind];
2438 			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
2439 				continue;
2440 			tmp->tm_sec += (sp->ttis[otheri].tt_utoff
2441 					- sp->ttis[samei].tt_utoff);
2442 			tmp->tm_isdst = !tmp->tm_isdst;
2443 			t = time2(tmp, funcp, sp, offset, &okay);
2444 			if (okay)
2445 				return t;
2446 			tmp->tm_sec -= (sp->ttis[otheri].tt_utoff
2447 					- sp->ttis[samei].tt_utoff);
2448 			tmp->tm_isdst = !tmp->tm_isdst;
2449 		}
2450 	}
2451 	return WRONG;
2452 }
2453 
2454 static time_t
2455 mktime_tzname(struct state *sp, struct tm *tmp, bool setname)
2456 {
2457   if (sp)
2458     return time1(tmp, localsub, sp, setname);
2459   else {
2460     _once(&gmt_once, gmtcheck);
2461     return time1(tmp, gmtsub, gmtptr, 0);
2462   }
2463 }
2464 
2465 #if NETBSD_INSPIRED
2466 
2467 time_t
2468 mktime_z(struct state *sp, struct tm *tmp)
2469 {
2470   return mktime_tzname(sp, tmp, false);
2471 }
2472 
2473 #endif
2474 
2475 time_t
2476 mktime(struct tm *tmp)
2477 {
2478   time_t t;
2479   int err = lock();
2480   if (err) {
2481     errno = err;
2482     return -1;
2483   }
2484   tzset_unlocked();
2485   t = mktime_tzname(lclptr, tmp, true);
2486   unlock();
2487   return t;
2488 }
2489 
2490 #ifdef STD_INSPIRED
2491 time_t
2492 timelocal(struct tm *tmp)
2493 {
2494 	if (tmp != NULL)
2495 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
2496 	return mktime(tmp);
2497 }
2498 #else
2499 static
2500 #endif
2501 time_t
2502 timeoff(struct tm *tmp, long offset)
2503 {
2504   if (tmp)
2505     tmp->tm_isdst = 0;
2506   _once(&gmt_once, gmtcheck);
2507   return time1(tmp, gmtsub, gmtptr, offset);
2508 }
2509 
2510 time_t
2511 timegm(struct tm *tmp)
2512 {
2513   time_t t;
2514   struct tm tmcpy;
2515   mktmcpy(&tmcpy, tmp);
2516   tmcpy.tm_wday = -1;
2517   t = timeoff(&tmcpy, 0);
2518   if (0 <= tmcpy.tm_wday)
2519     *tmp = tmcpy;
2520   return t;
2521 }
2522 
2523 static int_fast32_t
2524 leapcorr(struct state const *sp, time_t t)
2525 {
2526 	register struct lsinfo const *	lp;
2527 	register int			i;
2528 
2529 	i = sp->leapcnt;
2530 	while (--i >= 0) {
2531 		lp = &sp->lsis[i];
2532 		if (t >= lp->ls_trans)
2533 			return lp->ls_corr;
2534 	}
2535 	return 0;
2536 }
2537 
2538 /*
2539 ** XXX--is the below the right way to conditionalize??
2540 */
2541 
2542 #ifdef STD_INSPIRED
2543 
2544 /* NETBSD_INSPIRED_EXTERN functions are exported to callers if
2545    NETBSD_INSPIRED is defined, and are private otherwise.  */
2546 # if NETBSD_INSPIRED
2547 #  define NETBSD_INSPIRED_EXTERN
2548 # else
2549 #  define NETBSD_INSPIRED_EXTERN static
2550 # endif
2551 
2552 /*
2553 ** IEEE Std 1003.1 (POSIX) says that 536457599
2554 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
2555 ** is not the case if we are accounting for leap seconds.
2556 ** So, we provide the following conversion routines for use
2557 ** when exchanging timestamps with POSIX conforming systems.
2558 */
2559 
2560 NETBSD_INSPIRED_EXTERN time_t
2561 time2posix_z(struct state *sp, time_t t)
2562 {
2563   return t - leapcorr(sp, t);
2564 }
2565 
2566 time_t
2567 time2posix(time_t t)
2568 {
2569   int err = lock();
2570   if (err) {
2571     errno = err;
2572     return -1;
2573   }
2574 #ifndef DETECT_TZ_CHANGES
2575   if (!lcl_is_set)
2576 #endif
2577     tzset_unlocked();
2578   if (lclptr)
2579     t = time2posix_z(lclptr, t);
2580   unlock();
2581   return t;
2582 }
2583 
2584 NETBSD_INSPIRED_EXTERN time_t
2585 posix2time_z(struct state *sp, time_t t)
2586 {
2587 	time_t	x;
2588 	time_t	y;
2589 	/*
2590 	** For a positive leap second hit, the result
2591 	** is not unique. For a negative leap second
2592 	** hit, the corresponding time doesn't exist,
2593 	** so we return an adjacent second.
2594 	*/
2595 	x = t + leapcorr(sp, t);
2596 	y = x - leapcorr(sp, x);
2597 	if (y < t) {
2598 		do {
2599 			x++;
2600 			y = x - leapcorr(sp, x);
2601 		} while (y < t);
2602 		x -= y != t;
2603 	} else if (y > t) {
2604 		do {
2605 			--x;
2606 			y = x - leapcorr(sp, x);
2607 		} while (y > t);
2608 		x += y != t;
2609 	}
2610 	return x;
2611 }
2612 
2613 time_t
2614 posix2time(time_t t)
2615 {
2616   int err = lock();
2617   if (err) {
2618     errno = err;
2619     return -1;
2620   }
2621 #ifndef DETECT_TZ_CHANGES
2622   if (!lcl_is_set)
2623 #endif
2624     tzset_unlocked();
2625   if (lclptr)
2626     t = posix2time_z(lclptr, t);
2627   unlock();
2628   return t;
2629 }
2630 
2631 #endif /* defined STD_INSPIRED */
2632 
2633 #if TZ_TIME_T
2634 
2635 # if !USG_COMPAT
2636 #  define daylight 0
2637 #  define timezone 0
2638 # endif
2639 # if !ALTZONE
2640 #  define altzone 0
2641 # endif
2642 
2643 /* Convert from the underlying system's time_t to the ersatz time_tz,
2644    which is called 'time_t' in this file.  Typically, this merely
2645    converts the time's integer width.  On some platforms, the system
2646    time is local time not UT, or uses some epoch other than the POSIX
2647    epoch.
2648 
2649    Although this code appears to define a function named 'time' that
2650    returns time_t, the macros in private.h cause this code to actually
2651    define a function named 'tz_time' that returns tz_time_t.  The call
2652    to sys_time invokes the underlying system's 'time' function.  */
2653 
2654 time_t
2655 time(time_t *p)
2656 {
2657   time_t r = sys_time(0);
2658   if (r != (time_t) -1) {
2659     int_fast32_t offset = EPOCH_LOCAL ? (daylight ? timezone : altzone) : 0;
2660     if (increment_overflow32(&offset, -EPOCH_OFFSET)
2661 	|| increment_overflow_time(&r, offset)) {
2662       errno = EOVERFLOW;
2663       r = -1;
2664     }
2665   }
2666   if (p)
2667     *p = r;
2668   return r;
2669 }
2670 
2671 #endif
2672