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