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