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