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