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