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