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