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