Home | History | Annotate | Line # | Download | only in time
localtime.c revision 1.83
      1 /*	$NetBSD: localtime.c,v 1.83 2014/08/15 11:04:07 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.83 2014/08/15 11:04:07 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 	default:
    966 		_DIAGASSERT(
    967 		    rulep->r_type == JULIAN_DAY ||
    968 		    rulep->r_type == DAY_OF_YEAR ||
    969 		    rulep->r_type == MONTH_NTH_DAY_OF_WEEK);
    970 		value = 0;
    971 		break;
    972 	}
    973 
    974 	/*
    975 	** "value" is the year-relative time of 00:00:00 UT on the day in
    976 	** question. To get the year-relative time of the specified local
    977 	** time on that day, add the transition time and the current offset
    978 	** from UT.
    979 	*/
    980 	return value + rulep->r_time + offset;
    981 }
    982 
    983 /*
    984 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
    985 ** appropriate.
    986 */
    987 
    988 static int
    989 tzparse(timezone_t sp, const char *name, const int lastditch)
    990 {
    991 	const char *		stdname;
    992 	const char *		dstname;
    993 	size_t			stdlen;
    994 	size_t			dstlen;
    995 	int_fast32_t		stdoffset;
    996 	int_fast32_t		dstoffset;
    997 	char *			cp;
    998 	int			load_result;
    999 
   1000 	stdname = name;
   1001 	if (lastditch) {
   1002 		stdlen = strlen(name);	/* length of standard zone name */
   1003 		name += stdlen;
   1004 		if (stdlen >= sizeof sp->chars)
   1005 			stdlen = (sizeof sp->chars) - 1;
   1006 		stdoffset = 0;
   1007 	} else {
   1008 		if (*name == '<') {
   1009 			name++;
   1010 			stdname = name;
   1011 			name = getqzname(name, '>');
   1012 			if (*name != '>')
   1013 				return (-1);
   1014 			stdlen = name - stdname;
   1015 			name++;
   1016 		} else {
   1017 			name = getzname(name);
   1018 			stdlen = name - stdname;
   1019 		}
   1020 		if (*name == '\0')
   1021 			return -1;
   1022 		name = getoffset(name, &stdoffset);
   1023 		if (name == NULL)
   1024 			return -1;
   1025 	}
   1026 	load_result = tzload(sp, TZDEFRULES, FALSE);
   1027 	if (load_result != 0)
   1028 		sp->leapcnt = 0;		/* so, we're off a little */
   1029 	if (*name != '\0') {
   1030 		if (*name == '<') {
   1031 			dstname = ++name;
   1032 			name = getqzname(name, '>');
   1033 			if (*name != '>')
   1034 				return -1;
   1035 			dstlen = name - dstname;
   1036 			name++;
   1037 		} else {
   1038 			dstname = name;
   1039 			name = getzname(name);
   1040 			dstlen = name - dstname; /* length of DST zone name */
   1041 		}
   1042 		if (*name != '\0' && *name != ',' && *name != ';') {
   1043 			name = getoffset(name, &dstoffset);
   1044 			if (name == NULL)
   1045 				return -1;
   1046 		} else	dstoffset = stdoffset - SECSPERHOUR;
   1047 		if (*name == '\0' && load_result != 0)
   1048 			name = TZDEFRULESTRING;
   1049 		if (*name == ',' || *name == ';') {
   1050 			struct rule	start;
   1051 			struct rule	end;
   1052 			int		year;
   1053 			int		yearlim;
   1054 			int		timecnt;
   1055 			time_t		janfirst;
   1056 
   1057 			++name;
   1058 			if ((name = getrule(name, &start)) == NULL)
   1059 				return -1;
   1060 			if (*name++ != ',')
   1061 				return -1;
   1062 			if ((name = getrule(name, &end)) == NULL)
   1063 				return -1;
   1064 			if (*name != '\0')
   1065 				return -1;
   1066 			sp->typecnt = 2;	/* standard time and DST */
   1067 			/*
   1068 			** Two transitions per year, from EPOCH_YEAR forward.
   1069 			*/
   1070 			memset(sp->ttis, 0, sizeof(sp->ttis));
   1071 			sp->ttis[0].tt_gmtoff = -dstoffset;
   1072 			sp->ttis[0].tt_isdst = 1;
   1073 			sp->ttis[0].tt_abbrind = (int)(stdlen + 1);
   1074 			sp->ttis[1].tt_gmtoff = -stdoffset;
   1075 			sp->ttis[1].tt_isdst = 0;
   1076 			sp->ttis[1].tt_abbrind = 0;
   1077 			sp->defaulttype = 0;
   1078 			timecnt = 0;
   1079 			janfirst = 0;
   1080 			sp->timecnt = 0;
   1081 			yearlim = EPOCH_YEAR + YEARSPERREPEAT;
   1082 			for (year = EPOCH_YEAR; year < yearlim; year++) {
   1083 				int_fast32_t
   1084 				  starttime = transtime(year, &start, stdoffset),
   1085 				  endtime = transtime(year, &end, dstoffset);
   1086 				int_fast32_t
   1087 				  yearsecs = (year_lengths[isleap(year)]
   1088 					      * SECSPERDAY);
   1089 				int reversed = endtime < starttime;
   1090 				if (reversed) {
   1091 					int_fast32_t swap = starttime;
   1092 					starttime = endtime;
   1093 					endtime = swap;
   1094 				}
   1095 				if (reversed
   1096 				    || (starttime < endtime
   1097 					&& (endtime - starttime
   1098 					    < (yearsecs
   1099 					       + (stdoffset - dstoffset))))) {
   1100 					if (TZ_MAX_TIMES - 2 < timecnt)
   1101 						break;
   1102 					yearlim = year + YEARSPERREPEAT + 1;
   1103 					sp->ats[timecnt] = janfirst;
   1104 					if (increment_overflow_time
   1105 					    (&sp->ats[timecnt], starttime))
   1106 						break;
   1107 					sp->types[timecnt++] = reversed;
   1108 					sp->ats[timecnt] = janfirst;
   1109 					if (increment_overflow_time
   1110 					    (&sp->ats[timecnt], endtime))
   1111 						break;
   1112 					sp->types[timecnt++] = !reversed;
   1113 				}
   1114 				if (increment_overflow_time(&janfirst, yearsecs))
   1115 					break;
   1116 			}
   1117 			sp->timecnt = timecnt;
   1118 			if (!timecnt)
   1119 				sp->typecnt = 1;	/* Perpetual DST.  */
   1120 		} else {
   1121 			int_fast32_t	theirstdoffset;
   1122 			int_fast32_t	theirdstoffset;
   1123 			int_fast32_t	theiroffset;
   1124 			int		isdst;
   1125 			int		i;
   1126 			int		j;
   1127 
   1128 			if (*name != '\0')
   1129 				return -1;
   1130 			/*
   1131 			** Initial values of theirstdoffset and theirdstoffset.
   1132 			*/
   1133 			theirstdoffset = 0;
   1134 			for (i = 0; i < sp->timecnt; ++i) {
   1135 				j = sp->types[i];
   1136 				if (!sp->ttis[j].tt_isdst) {
   1137 					theirstdoffset =
   1138 						-sp->ttis[j].tt_gmtoff;
   1139 					break;
   1140 				}
   1141 			}
   1142 			theirdstoffset = 0;
   1143 			for (i = 0; i < sp->timecnt; ++i) {
   1144 				j = sp->types[i];
   1145 				if (sp->ttis[j].tt_isdst) {
   1146 					theirdstoffset =
   1147 						-sp->ttis[j].tt_gmtoff;
   1148 					break;
   1149 				}
   1150 			}
   1151 			/*
   1152 			** Initially we're assumed to be in standard time.
   1153 			*/
   1154 			isdst = FALSE;
   1155 			theiroffset = theirstdoffset;
   1156 			/*
   1157 			** Now juggle transition times and types
   1158 			** tracking offsets as you do.
   1159 			*/
   1160 			for (i = 0; i < sp->timecnt; ++i) {
   1161 				j = sp->types[i];
   1162 				sp->types[i] = sp->ttis[j].tt_isdst;
   1163 				if (sp->ttis[j].tt_ttisgmt) {
   1164 					/* No adjustment to transition time */
   1165 				} else {
   1166 					/*
   1167 					** If summer time is in effect, and the
   1168 					** transition time was not specified as
   1169 					** standard time, add the summer time
   1170 					** offset to the transition time;
   1171 					** otherwise, add the standard time
   1172 					** offset to the transition time.
   1173 					*/
   1174 					/*
   1175 					** Transitions from DST to DDST
   1176 					** will effectively disappear since
   1177 					** POSIX provides for only one DST
   1178 					** offset.
   1179 					*/
   1180 					if (isdst && !sp->ttis[j].tt_ttisstd) {
   1181 						sp->ats[i] += (time_t)
   1182 						    (dstoffset - theirdstoffset);
   1183 					} else {
   1184 						sp->ats[i] += (time_t)
   1185 						    (stdoffset - theirstdoffset);
   1186 					}
   1187 				}
   1188 				theiroffset = -sp->ttis[j].tt_gmtoff;
   1189 				if (!sp->ttis[j].tt_isdst)
   1190 					theirstdoffset = theiroffset;
   1191 				else	theirdstoffset = theiroffset;
   1192 			}
   1193 			/*
   1194 			** Finally, fill in ttis.
   1195 			** ttisstd and ttisgmt need not be handled
   1196 			*/
   1197 			memset(sp->ttis, 0, sizeof(sp->ttis));
   1198 			sp->ttis[0].tt_gmtoff = -stdoffset;
   1199 			sp->ttis[0].tt_isdst = FALSE;
   1200 			sp->ttis[0].tt_abbrind = 0;
   1201 			sp->ttis[1].tt_gmtoff = -dstoffset;
   1202 			sp->ttis[1].tt_isdst = TRUE;
   1203 			sp->ttis[1].tt_abbrind = (int)(stdlen + 1);
   1204 			sp->typecnt = 2;
   1205 			sp->defaulttype = 0;
   1206 		}
   1207 	} else {
   1208 		dstlen = 0;
   1209 		sp->typecnt = 1;		/* only standard time */
   1210 		sp->timecnt = 0;
   1211 		memset(sp->ttis, 0, sizeof(sp->ttis));
   1212 		sp->ttis[0].tt_gmtoff = -stdoffset;
   1213 		sp->ttis[0].tt_isdst = 0;
   1214 		sp->ttis[0].tt_abbrind = 0;
   1215 		sp->defaulttype = 0;
   1216 	}
   1217 	sp->charcnt = (int)(stdlen + 1);
   1218 	if (dstlen != 0)
   1219 		sp->charcnt += (int)(dstlen + 1);
   1220 	if ((size_t) sp->charcnt > sizeof sp->chars)
   1221 		return -1;
   1222 	cp = sp->chars;
   1223 	(void) strncpy(cp, stdname, stdlen);
   1224 	cp += stdlen;
   1225 	*cp++ = '\0';
   1226 	if (dstlen != 0) {
   1227 		(void) strncpy(cp, dstname, dstlen);
   1228 		*(cp + dstlen) = '\0';
   1229 	}
   1230 	return 0;
   1231 }
   1232 
   1233 static void
   1234 gmtload(timezone_t sp)
   1235 {
   1236 	if (tzload(sp, gmt, TRUE) != 0)
   1237 		(void) tzparse(sp, gmt, TRUE);
   1238 }
   1239 
   1240 timezone_t
   1241 tzalloc(const char *name)
   1242 {
   1243 	timezone_t sp = malloc(sizeof *sp);
   1244 	if (sp == NULL)
   1245 		return NULL;
   1246 	if (tzload(sp, name, TRUE) != 0) {
   1247 		free(sp);
   1248 		return NULL;
   1249 	}
   1250 	settzname_z(sp);
   1251 	return sp;
   1252 }
   1253 
   1254 void
   1255 tzfree(const timezone_t sp)
   1256 {
   1257 	free(sp);
   1258 }
   1259 
   1260 static void
   1261 tzsetwall_unlocked(void)
   1262 {
   1263 	if (lcl_is_set < 0)
   1264 		return;
   1265 	lcl_is_set = -1;
   1266 
   1267 	if (lclptr == NULL) {
   1268 		int saveerrno = errno;
   1269 		lclptr = malloc(sizeof *lclptr);
   1270 		errno = saveerrno;
   1271 		if (lclptr == NULL) {
   1272 			settzname();	/* all we can do */
   1273 			return;
   1274 		}
   1275 	}
   1276 	if (tzload(lclptr, NULL, TRUE) != 0)
   1277 		gmtload(lclptr);
   1278 	settzname();
   1279 }
   1280 
   1281 #ifndef STD_INSPIRED
   1282 /*
   1283 ** A non-static declaration of tzsetwall in a system header file
   1284 ** may cause a warning about this upcoming static declaration...
   1285 */
   1286 static
   1287 #endif /* !defined STD_INSPIRED */
   1288 void
   1289 tzsetwall(void)
   1290 {
   1291 	rwlock_wrlock(&lcl_lock);
   1292 	tzsetwall_unlocked();
   1293 	rwlock_unlock(&lcl_lock);
   1294 }
   1295 
   1296 #ifndef STD_INSPIRED
   1297 /*
   1298 ** A non-static declaration of tzsetwall in a system header file
   1299 ** may cause a warning about this upcoming static declaration...
   1300 */
   1301 static
   1302 #endif /* !defined STD_INSPIRED */
   1303 void
   1304 tzset_unlocked(void)
   1305 {
   1306 	const char *	name;
   1307 
   1308 	name = getenv("TZ");
   1309 	if (name == NULL) {
   1310 		tzsetwall_unlocked();
   1311 		return;
   1312 	}
   1313 
   1314 	if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
   1315 		return;
   1316 	lcl_is_set = strlen(name) < sizeof lcl_TZname;
   1317 	if (lcl_is_set)
   1318 		(void)strlcpy(lcl_TZname, name, sizeof(lcl_TZname));
   1319 
   1320 	if (lclptr == NULL) {
   1321 		int saveerrno = errno;
   1322 		lclptr = malloc(sizeof *lclptr);
   1323 		errno = saveerrno;
   1324 		if (lclptr == NULL) {
   1325 			settzname();	/* all we can do */
   1326 			return;
   1327 		}
   1328 	}
   1329 	if (*name == '\0') {
   1330 		/*
   1331 		** User wants it fast rather than right.
   1332 		*/
   1333 		lclptr->leapcnt = 0;		/* so, we're off a little */
   1334 		lclptr->timecnt = 0;
   1335 		lclptr->typecnt = 0;
   1336 		lclptr->ttis[0].tt_isdst = 0;
   1337 		lclptr->ttis[0].tt_gmtoff = 0;
   1338 		lclptr->ttis[0].tt_abbrind = 0;
   1339 		(void) strlcpy(lclptr->chars, gmt, sizeof(lclptr->chars));
   1340 	} else if (tzload(lclptr, name, TRUE) != 0)
   1341 		if (name[0] == ':' || tzparse(lclptr, name, FALSE) != 0)
   1342 			(void) gmtload(lclptr);
   1343 	settzname();
   1344 }
   1345 
   1346 void
   1347 tzset(void)
   1348 {
   1349 	rwlock_wrlock(&lcl_lock);
   1350 	tzset_unlocked();
   1351 	rwlock_unlock(&lcl_lock);
   1352 }
   1353 
   1354 /*
   1355 ** The easy way to behave "as if no library function calls" localtime
   1356 ** is to not call it, so we drop its guts into "localsub", which can be
   1357 ** freely called. (And no, the PANS doesn't require the above behavior,
   1358 ** but it *is* desirable.)
   1359 **
   1360 ** The unused offset argument is for the benefit of mktime variants.
   1361 */
   1362 
   1363 /*ARGSUSED*/
   1364 static struct tm *
   1365 localsub(const timezone_t sp, const time_t * const timep, const int_fast32_t offset,
   1366     struct tm *const tmp)
   1367 {
   1368 	const struct ttinfo *	ttisp;
   1369 	int			i;
   1370 	struct tm *		result;
   1371 	const time_t			t = *timep;
   1372 
   1373 	if ((sp->goback && t < sp->ats[0]) ||
   1374 		(sp->goahead && t > sp->ats[sp->timecnt - 1])) {
   1375 			time_t			newt = t;
   1376 			time_t		seconds;
   1377 			time_t		years;
   1378 
   1379 			if (t < sp->ats[0])
   1380 				seconds = sp->ats[0] - t;
   1381 			else	seconds = t - sp->ats[sp->timecnt - 1];
   1382 			--seconds;
   1383 			years = (time_t)((seconds / SECSPERREPEAT + 1) * YEARSPERREPEAT);
   1384 			seconds = (time_t)(years * AVGSECSPERYEAR);
   1385 			if (t < sp->ats[0])
   1386 				newt += seconds;
   1387 			else	newt -= seconds;
   1388 			if (newt < sp->ats[0] ||
   1389 				newt > sp->ats[sp->timecnt - 1])
   1390 					return NULL;	/* "cannot happen" */
   1391 			result = localsub(sp, &newt, offset, tmp);
   1392 			if (result == tmp) {
   1393 				time_t	newy;
   1394 
   1395 				newy = tmp->tm_year;
   1396 				if (t < sp->ats[0])
   1397 					newy -= years;
   1398 				else	newy += years;
   1399 				tmp->tm_year = (int)newy;
   1400 				if (tmp->tm_year != newy)
   1401 					return NULL;
   1402 			}
   1403 			return result;
   1404 	}
   1405 	if (sp->timecnt == 0 || t < sp->ats[0]) {
   1406 		i = sp->defaulttype;
   1407 	} else {
   1408 		int	lo = 1;
   1409 		int	hi = sp->timecnt;
   1410 
   1411 		while (lo < hi) {
   1412 			int	mid = (lo + hi) / 2;
   1413 
   1414 			if (t < sp->ats[mid])
   1415 				hi = mid;
   1416 			else	lo = mid + 1;
   1417 		}
   1418 		i = (int) sp->types[lo - 1];
   1419 	}
   1420 	ttisp = &sp->ttis[i];
   1421 	/*
   1422 	** To get (wrong) behavior that's compatible with System V Release 2.0
   1423 	** you'd replace the statement below with
   1424 	**	t += ttisp->tt_gmtoff;
   1425 	**	timesub(&t, 0L, sp, tmp);
   1426 	*/
   1427 	result = timesub(sp, &t, ttisp->tt_gmtoff, tmp);
   1428 	tmp->tm_isdst = ttisp->tt_isdst;
   1429 	if (sp == lclptr)
   1430 		tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
   1431 #ifdef TM_ZONE
   1432 	tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
   1433 #endif /* defined TM_ZONE */
   1434 	return result;
   1435 }
   1436 
   1437 /*
   1438 ** Re-entrant version of localtime.
   1439 */
   1440 
   1441 struct tm *
   1442 localtime_r(const time_t * __restrict timep, struct tm *tmp)
   1443 {
   1444 	rwlock_rdlock(&lcl_lock);
   1445 	tzset_unlocked();
   1446 	tmp = localtime_rz(lclptr, timep, tmp);
   1447 	rwlock_unlock(&lcl_lock);
   1448 	return tmp;
   1449 }
   1450 
   1451 struct tm *
   1452 localtime(const time_t *const timep)
   1453 {
   1454 	return localtime_r(timep, &tm);
   1455 }
   1456 
   1457 struct tm *
   1458 localtime_rz(const timezone_t sp, const time_t * __restrict timep, struct tm *tmp)
   1459 {
   1460 	if (sp == NULL)
   1461 		tmp = gmtsub(NULL, timep, 0, tmp);
   1462 	else
   1463 		tmp = localsub(sp, timep, 0, tmp);
   1464 	if (tmp == NULL)
   1465 		errno = EOVERFLOW;
   1466 	return tmp;
   1467 }
   1468 
   1469 /*
   1470 ** gmtsub is to gmtime as localsub is to localtime.
   1471 */
   1472 
   1473 static struct tm *
   1474 gmtsub(const timezone_t sp, const time_t *const timep,
   1475     const int_fast32_t offset, struct tm *const tmp)
   1476 {
   1477 	struct tm *	result;
   1478 #ifdef _REENTRANT
   1479 	static mutex_t gmt_mutex = MUTEX_INITIALIZER;
   1480 #endif
   1481 
   1482 	mutex_lock(&gmt_mutex);
   1483 	if (!gmt_is_set) {
   1484 		int saveerrno;
   1485 		gmt_is_set = TRUE;
   1486 		saveerrno = errno;
   1487 		gmtptr = malloc(sizeof *gmtptr);
   1488 		gmt_is_set = gmtptr != NULL;
   1489 		errno = saveerrno;
   1490 		if (gmt_is_set)
   1491 			gmtload(gmtptr);
   1492 	}
   1493 	mutex_unlock(&gmt_mutex);
   1494 	result = timesub(gmtptr, timep, offset, tmp);
   1495 #ifdef TM_ZONE
   1496 	/*
   1497 	** Could get fancy here and deliver something such as
   1498 	** "UT+xxxx" or "UT-xxxx" if offset is non-zero,
   1499 	** but this is no time for a treasure hunt.
   1500 	*/
   1501 	tmp->TM_ZONE = offset ? __UNCONST(wildabbr) : gmtptr ? gmtptr->chars :
   1502 	    __UNCONST(gmt);
   1503 #endif /* defined TM_ZONE */
   1504 	return result;
   1505 }
   1506 
   1507 struct tm *
   1508 gmtime(const time_t *const timep)
   1509 {
   1510 	struct tm *tmp = gmtsub(NULL, timep, 0, &tm);
   1511 
   1512 	if (tmp == NULL)
   1513 		errno = EOVERFLOW;
   1514 
   1515 	return tmp;
   1516 }
   1517 
   1518 /*
   1519 ** Re-entrant version of gmtime.
   1520 */
   1521 
   1522 struct tm *
   1523 gmtime_r(const time_t * const timep, struct tm *tmp)
   1524 {
   1525 	tmp = gmtsub(NULL, timep, 0, tmp);
   1526 
   1527 	if (tmp == NULL)
   1528 		errno = EOVERFLOW;
   1529 
   1530 	return tmp;
   1531 }
   1532 
   1533 #ifdef STD_INSPIRED
   1534 
   1535 struct tm *
   1536 offtime(const time_t *const timep, long offset)
   1537 {
   1538 	struct tm *tmp;
   1539 
   1540 	if ((offset > 0 && offset > INT_FAST32_MAX) ||
   1541 	    (offset < 0 && offset < INT_FAST32_MIN)) {
   1542 		errno = EOVERFLOW;
   1543 		return NULL;
   1544 	}
   1545 	tmp = gmtsub(NULL, timep, (int_fast32_t)offset, &tm);
   1546 
   1547 	if (tmp == NULL)
   1548 		errno = EOVERFLOW;
   1549 
   1550 	return tmp;
   1551 }
   1552 
   1553 struct tm *
   1554 offtime_r(const time_t *timep, long offset, struct tm *tmp)
   1555 {
   1556 	if ((offset > 0 && offset > INT_FAST32_MAX) ||
   1557 	    (offset < 0 && offset < INT_FAST32_MIN)) {
   1558 		errno = EOVERFLOW;
   1559 		return NULL;
   1560 	}
   1561 	tmp = gmtsub(NULL, timep, (int_fast32_t)offset, tmp);
   1562 
   1563 	if (tmp == NULL)
   1564 		errno = EOVERFLOW;
   1565 
   1566 	return tmp;
   1567 }
   1568 
   1569 #endif /* defined STD_INSPIRED */
   1570 
   1571 /*
   1572 ** Return the number of leap years through the end of the given year
   1573 ** where, to make the math easy, the answer for year zero is defined as zero.
   1574 */
   1575 
   1576 static int
   1577 leaps_thru_end_of(const int y)
   1578 {
   1579 	return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
   1580 		-(leaps_thru_end_of(-(y + 1)) + 1);
   1581 }
   1582 
   1583 static struct tm *
   1584 timesub(const timezone_t sp, const time_t *const timep,
   1585     const int_fast32_t offset, struct tm *const tmp)
   1586 {
   1587 	const struct lsinfo *	lp;
   1588 	time_t			tdays;
   1589 	int			idays;	/* unsigned would be so 2003 */
   1590 	int_fast64_t		rem;
   1591 	int			y;
   1592 	const int *		ip;
   1593 	int_fast64_t		corr;
   1594 	int			hit;
   1595 	int			i;
   1596 
   1597 	corr = 0;
   1598 	hit = 0;
   1599 	i = (sp == NULL) ? 0 : sp->leapcnt;
   1600 	while (--i >= 0) {
   1601 		lp = &sp->lsis[i];
   1602 		if (*timep >= lp->ls_trans) {
   1603 			if (*timep == lp->ls_trans) {
   1604 				hit = ((i == 0 && lp->ls_corr > 0) ||
   1605 					lp->ls_corr > sp->lsis[i - 1].ls_corr);
   1606 				if (hit)
   1607 					while (i > 0 &&
   1608 						sp->lsis[i].ls_trans ==
   1609 						sp->lsis[i - 1].ls_trans + 1 &&
   1610 						sp->lsis[i].ls_corr ==
   1611 						sp->lsis[i - 1].ls_corr + 1) {
   1612 							++hit;
   1613 							--i;
   1614 					}
   1615 			}
   1616 			corr = lp->ls_corr;
   1617 			break;
   1618 		}
   1619 	}
   1620 	y = EPOCH_YEAR;
   1621 	tdays = (time_t)(*timep / SECSPERDAY);
   1622 	rem = (int_fast64_t) (*timep - tdays * SECSPERDAY);
   1623 	while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
   1624 		int		newy;
   1625 		time_t	tdelta;
   1626 		int	idelta;
   1627 		int	leapdays;
   1628 
   1629 		tdelta = tdays / DAYSPERLYEAR;
   1630 		if (! ((! TYPE_SIGNED(time_t) || INT_MIN <= tdelta)
   1631 		       && tdelta <= INT_MAX))
   1632 			return NULL;
   1633 		_DIAGASSERT(__type_fit(int, tdelta));
   1634 		idelta = (int)tdelta;
   1635 		if (idelta == 0)
   1636 			idelta = (tdays < 0) ? -1 : 1;
   1637 		newy = y;
   1638 		if (increment_overflow(&newy, idelta))
   1639 			return NULL;
   1640 		leapdays = leaps_thru_end_of(newy - 1) -
   1641 			leaps_thru_end_of(y - 1);
   1642 		tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
   1643 		tdays -= leapdays;
   1644 		y = newy;
   1645 	}
   1646 	{
   1647 		int_fast32_t seconds;
   1648 
   1649 		seconds = (int_fast32_t)(tdays * SECSPERDAY);
   1650 		tdays = (time_t)(seconds / SECSPERDAY);
   1651 		rem += (int_fast64_t)(seconds - tdays * SECSPERDAY);
   1652 	}
   1653 	/*
   1654 	** Given the range, we can now fearlessly cast...
   1655 	*/
   1656 	idays = (int) tdays;
   1657 	rem += offset - corr;
   1658 	while (rem < 0) {
   1659 		rem += SECSPERDAY;
   1660 		--idays;
   1661 	}
   1662 	while (rem >= SECSPERDAY) {
   1663 		rem -= SECSPERDAY;
   1664 		++idays;
   1665 	}
   1666 	while (idays < 0) {
   1667 		if (increment_overflow(&y, -1))
   1668 			return NULL;
   1669 		idays += year_lengths[isleap(y)];
   1670 	}
   1671 	while (idays >= year_lengths[isleap(y)]) {
   1672 		idays -= year_lengths[isleap(y)];
   1673 		if (increment_overflow(&y, 1))
   1674 			return NULL;
   1675 	}
   1676 	tmp->tm_year = y;
   1677 	if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
   1678 		return NULL;
   1679 	tmp->tm_yday = idays;
   1680 	/*
   1681 	** The "extra" mods below avoid overflow problems.
   1682 	*/
   1683 	tmp->tm_wday = EPOCH_WDAY +
   1684 		((y - EPOCH_YEAR) % DAYSPERWEEK) *
   1685 		(DAYSPERNYEAR % DAYSPERWEEK) +
   1686 		leaps_thru_end_of(y - 1) -
   1687 		leaps_thru_end_of(EPOCH_YEAR - 1) +
   1688 		idays;
   1689 	tmp->tm_wday %= DAYSPERWEEK;
   1690 	if (tmp->tm_wday < 0)
   1691 		tmp->tm_wday += DAYSPERWEEK;
   1692 	tmp->tm_hour = (int) (rem / SECSPERHOUR);
   1693 	rem %= SECSPERHOUR;
   1694 	tmp->tm_min = (int) (rem / SECSPERMIN);
   1695 	/*
   1696 	** A positive leap second requires a special
   1697 	** representation. This uses "... ??:59:60" et seq.
   1698 	*/
   1699 	tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
   1700 	ip = mon_lengths[isleap(y)];
   1701 	for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
   1702 		idays -= ip[tmp->tm_mon];
   1703 	tmp->tm_mday = (int) (idays + 1);
   1704 	tmp->tm_isdst = 0;
   1705 #ifdef TM_GMTOFF
   1706 	tmp->TM_GMTOFF = offset;
   1707 #endif /* defined TM_GMTOFF */
   1708 	return tmp;
   1709 }
   1710 
   1711 char *
   1712 ctime(const time_t *const timep)
   1713 {
   1714 /*
   1715 ** Section 4.12.3.2 of X3.159-1989 requires that
   1716 **	The ctime function converts the calendar time pointed to by timer
   1717 **	to local time in the form of a string. It is equivalent to
   1718 **		asctime(localtime(timer))
   1719 */
   1720 	struct tm *rtm = localtime(timep);
   1721 	if (rtm == NULL)
   1722 		return NULL;
   1723 	return asctime(rtm);
   1724 }
   1725 
   1726 char *
   1727 ctime_r(const time_t *const timep, char *buf)
   1728 {
   1729 	struct tm	mytm, *rtm;
   1730 
   1731 	rtm = localtime_r(timep, &mytm);
   1732 	if (rtm == NULL)
   1733 		return NULL;
   1734 	return asctime_r(rtm, buf);
   1735 }
   1736 
   1737 char *
   1738 ctime_rz(const timezone_t sp, const time_t * timep, char *buf)
   1739 {
   1740 	struct tm	mytm, *rtm;
   1741 
   1742 	rtm = localtime_rz(sp, timep, &mytm);
   1743 	if (rtm == NULL)
   1744 		return NULL;
   1745 	return asctime_r(rtm, buf);
   1746 }
   1747 
   1748 /*
   1749 ** Adapted from code provided by Robert Elz, who writes:
   1750 **	The "best" way to do mktime I think is based on an idea of Bob
   1751 **	Kridle's (so its said...) from a long time ago.
   1752 **	It does a binary search of the time_t space. Since time_t's are
   1753 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
   1754 **	would still be very reasonable).
   1755 */
   1756 
   1757 #ifndef WRONG
   1758 #define WRONG	((time_t)-1)
   1759 #endif /* !defined WRONG */
   1760 
   1761 /*
   1762 ** Simplified normalize logic courtesy Paul Eggert.
   1763 */
   1764 
   1765 static int
   1766 increment_overflow(int *const ip, int j)
   1767 {
   1768 	int	i = *ip;
   1769 
   1770 	/*
   1771 	** If i >= 0 there can only be overflow if i + j > INT_MAX
   1772 	** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
   1773 	** If i < 0 there can only be overflow if i + j < INT_MIN
   1774 	** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
   1775 	*/
   1776 	if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
   1777 		return TRUE;
   1778 	*ip += j;
   1779 	return FALSE;
   1780 }
   1781 
   1782 static int
   1783 increment_overflow32(int_fast32_t *const lp, int const m)
   1784 {
   1785 	int_fast32_t l = *lp;
   1786 
   1787 	if ((l >= 0) ? (m > INT_FAST32_MAX - l) : (m < INT_FAST32_MIN - l))
   1788 		return TRUE;
   1789 	*lp += m;
   1790 	return FALSE;
   1791 }
   1792 
   1793 static int
   1794 increment_overflow_time(time_t *tp, int_fast32_t j)
   1795 {
   1796 	/*
   1797 	** This is like
   1798 	** 'if (! (time_t_min <= *tp + j && *tp + j <= time_t_max)) ...',
   1799 	** except that it does the right thing even if *tp + j would overflow.
   1800 	*/
   1801 	if (! (j < 0
   1802 	       ? (TYPE_SIGNED(time_t) ? time_t_min - j <= *tp : -1 - j < *tp)
   1803 	       : *tp <= time_t_max - j))
   1804 		return TRUE;
   1805 	*tp += j;
   1806 	return FALSE;
   1807 }
   1808 
   1809 static int
   1810 normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
   1811 {
   1812 	int	tensdelta;
   1813 
   1814 	tensdelta = (*unitsptr >= 0) ?
   1815 		(*unitsptr / base) :
   1816 		(-1 - (-1 - *unitsptr) / base);
   1817 	*unitsptr -= tensdelta * base;
   1818 	return increment_overflow(tensptr, tensdelta);
   1819 }
   1820 
   1821 static int
   1822 normalize_overflow32(int_fast32_t *const tensptr, int *const unitsptr,
   1823     const int base)
   1824 {
   1825 	int	tensdelta;
   1826 
   1827 	tensdelta = (*unitsptr >= 0) ?
   1828 		(*unitsptr / base) :
   1829 		(-1 - (-1 - *unitsptr) / base);
   1830 	*unitsptr -= tensdelta * base;
   1831 	return increment_overflow32(tensptr, tensdelta);
   1832 }
   1833 
   1834 static int
   1835 tmcomp(const struct tm *const atmp, const struct tm *const btmp)
   1836 {
   1837 	int	result;
   1838 
   1839 	if (atmp->tm_year != btmp->tm_year)
   1840 		return atmp->tm_year < btmp->tm_year ? -1 : 1;
   1841 	if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
   1842 		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
   1843 		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
   1844 		(result = (atmp->tm_min - btmp->tm_min)) == 0)
   1845 			result = atmp->tm_sec - btmp->tm_sec;
   1846 	return result;
   1847 }
   1848 
   1849 static time_t
   1850 time2sub(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
   1851     const int_fast32_t offset, int *const okayp, const int do_norm_secs)
   1852 {
   1853 	int			dir;
   1854 	int			i, j;
   1855 	int			saved_seconds;
   1856 	int_fast32_t		li;
   1857 	time_t			lo;
   1858 	time_t			hi;
   1859 #ifdef NO_ERROR_IN_DST_GAP
   1860 	time_t			ilo;
   1861 #endif
   1862 	int_fast32_t		y;
   1863 	time_t			newt;
   1864 	time_t			t;
   1865 	struct tm		yourtm, mytm;
   1866 
   1867 	*okayp = FALSE;
   1868 	yourtm = *tmp;
   1869 #ifdef NO_ERROR_IN_DST_GAP
   1870 again:
   1871 #endif
   1872 	if (do_norm_secs) {
   1873 		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
   1874 		    SECSPERMIN))
   1875 			goto overflow;
   1876 	}
   1877 	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
   1878 		goto overflow;
   1879 	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
   1880 		goto overflow;
   1881 	y = yourtm.tm_year;
   1882 	if (normalize_overflow32(&y, &yourtm.tm_mon, MONSPERYEAR))
   1883 		goto overflow;
   1884 	/*
   1885 	** Turn y into an actual year number for now.
   1886 	** It is converted back to an offset from TM_YEAR_BASE later.
   1887 	*/
   1888 	if (increment_overflow32(&y, TM_YEAR_BASE))
   1889 		goto overflow;
   1890 	while (yourtm.tm_mday <= 0) {
   1891 		if (increment_overflow32(&y, -1))
   1892 			goto overflow;
   1893 		li = y + (1 < yourtm.tm_mon);
   1894 		yourtm.tm_mday += year_lengths[isleap(li)];
   1895 	}
   1896 	while (yourtm.tm_mday > DAYSPERLYEAR) {
   1897 		li = y + (1 < yourtm.tm_mon);
   1898 		yourtm.tm_mday -= year_lengths[isleap(li)];
   1899 		if (increment_overflow32(&y, 1))
   1900 			goto overflow;
   1901 	}
   1902 	for ( ; ; ) {
   1903 		i = mon_lengths[isleap(y)][yourtm.tm_mon];
   1904 		if (yourtm.tm_mday <= i)
   1905 			break;
   1906 		yourtm.tm_mday -= i;
   1907 		if (++yourtm.tm_mon >= MONSPERYEAR) {
   1908 			yourtm.tm_mon = 0;
   1909 			if (increment_overflow32(&y, 1))
   1910 				goto overflow;
   1911 		}
   1912 	}
   1913 	if (increment_overflow32(&y, -TM_YEAR_BASE))
   1914 		goto overflow;
   1915 	yourtm.tm_year = (int)y;
   1916 	if (yourtm.tm_year != y)
   1917 		goto overflow;
   1918 	if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
   1919 		saved_seconds = 0;
   1920 	else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
   1921 		/*
   1922 		** We can't set tm_sec to 0, because that might push the
   1923 		** time below the minimum representable time.
   1924 		** Set tm_sec to 59 instead.
   1925 		** This assumes that the minimum representable time is
   1926 		** not in the same minute that a leap second was deleted from,
   1927 		** which is a safer assumption than using 58 would be.
   1928 		*/
   1929 		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
   1930 			goto overflow;
   1931 		saved_seconds = yourtm.tm_sec;
   1932 		yourtm.tm_sec = SECSPERMIN - 1;
   1933 	} else {
   1934 		saved_seconds = yourtm.tm_sec;
   1935 		yourtm.tm_sec = 0;
   1936 	}
   1937 	/*
   1938 	** Do a binary search (this works whatever time_t's type is).
   1939 	*/
   1940 	/* LINTED const not */
   1941 	if (!TYPE_SIGNED(time_t)) {
   1942 		lo = 0;
   1943 		hi = lo - 1;
   1944 	} else {
   1945 		lo = 1;
   1946 		for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
   1947 			lo *= 2;
   1948 		hi = -(lo + 1);
   1949 	}
   1950 #ifdef NO_ERROR_IN_DST_GAP
   1951 	ilo = lo;
   1952 #endif
   1953 	for ( ; ; ) {
   1954 		t = lo / 2 + hi / 2;
   1955 		if (t < lo)
   1956 			t = lo;
   1957 		else if (t > hi)
   1958 			t = hi;
   1959 		if ((*funcp)(sp, &t, offset, &mytm) == NULL) {
   1960 			/*
   1961 			** Assume that t is too extreme to be represented in
   1962 			** a struct tm; arrange things so that it is less
   1963 			** extreme on the next pass.
   1964 			*/
   1965 			dir = (t > 0) ? 1 : -1;
   1966 		} else	dir = tmcomp(&mytm, &yourtm);
   1967 		if (dir != 0) {
   1968 			if (t == lo) {
   1969 				if (t == time_t_max)
   1970 					goto overflow;
   1971 				++t;
   1972 				++lo;
   1973 			} else if (t == hi) {
   1974 				if (t == time_t_min)
   1975 					goto overflow;
   1976 				--t;
   1977 				--hi;
   1978 			}
   1979 #ifdef NO_ERROR_IN_DST_GAP
   1980 			if (ilo != lo && lo - 1 == hi && yourtm.tm_isdst < 0 &&
   1981 			    do_norm_secs) {
   1982 				for (i = sp->typecnt - 1; i >= 0; --i) {
   1983 					for (j = sp->typecnt - 1; j >= 0; --j) {
   1984 						time_t off;
   1985 						if (sp->ttis[j].tt_isdst ==
   1986 						    sp->ttis[i].tt_isdst)
   1987 							continue;
   1988 						off = sp->ttis[j].tt_gmtoff -
   1989 						    sp->ttis[i].tt_gmtoff;
   1990 						yourtm.tm_sec += off < 0 ?
   1991 						    -off : off;
   1992 						goto again;
   1993 					}
   1994 				}
   1995 			}
   1996 #endif
   1997 			if (lo > hi)
   1998 				goto invalid;
   1999 			if (dir > 0)
   2000 				hi = t;
   2001 			else	lo = t;
   2002 			continue;
   2003 		}
   2004 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
   2005 			break;
   2006 		/*
   2007 		** Right time, wrong type.
   2008 		** Hunt for right time, right type.
   2009 		** It's okay to guess wrong since the guess
   2010 		** gets checked.
   2011 		*/
   2012 		if (sp == NULL)
   2013 			goto invalid;
   2014 		for (i = sp->typecnt - 1; i >= 0; --i) {
   2015 			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
   2016 				continue;
   2017 			for (j = sp->typecnt - 1; j >= 0; --j) {
   2018 				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
   2019 					continue;
   2020 				newt = (time_t)(t + sp->ttis[j].tt_gmtoff -
   2021 				    sp->ttis[i].tt_gmtoff);
   2022 				if ((*funcp)(sp, &newt, offset, &mytm) == NULL)
   2023 					continue;
   2024 				if (tmcomp(&mytm, &yourtm) != 0)
   2025 					continue;
   2026 				if (mytm.tm_isdst != yourtm.tm_isdst)
   2027 					continue;
   2028 				/*
   2029 				** We have a match.
   2030 				*/
   2031 				t = newt;
   2032 				goto label;
   2033 			}
   2034 		}
   2035 		goto invalid;
   2036 	}
   2037 label:
   2038 	newt = t + saved_seconds;
   2039 	if ((newt < t) != (saved_seconds < 0))
   2040 		goto overflow;
   2041 	t = newt;
   2042 	if ((*funcp)(sp, &t, offset, tmp)) {
   2043 		*okayp = TRUE;
   2044 		return t;
   2045 	}
   2046 overflow:
   2047 	errno = EOVERFLOW;
   2048 	return WRONG;
   2049 invalid:
   2050 	errno = EINVAL;
   2051 	return WRONG;
   2052 }
   2053 
   2054 static time_t
   2055 time2(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
   2056     const int_fast32_t offset, int *const okayp)
   2057 {
   2058 	time_t	t;
   2059 
   2060 	/*
   2061 	** First try without normalization of seconds
   2062 	** (in case tm_sec contains a value associated with a leap second).
   2063 	** If that fails, try with normalization of seconds.
   2064 	*/
   2065 	t = time2sub(sp, tmp, funcp, offset, okayp, FALSE);
   2066 	return *okayp ? t : time2sub(sp, tmp, funcp, offset, okayp, TRUE);
   2067 }
   2068 
   2069 static time_t
   2070 time1(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
   2071     const int_fast32_t offset)
   2072 {
   2073 	time_t			t;
   2074 	int			samei, otheri;
   2075 	int			sameind, otherind;
   2076 	int			i;
   2077 	int			nseen;
   2078 	char				seen[TZ_MAX_TYPES];
   2079 	unsigned char			types[TZ_MAX_TYPES];
   2080 	int				okay;
   2081 
   2082 	if (tmp == NULL) {
   2083 		errno = EINVAL;
   2084 		return WRONG;
   2085 	}
   2086 	if (tmp->tm_isdst > 1)
   2087 		tmp->tm_isdst = 1;
   2088 	t = time2(sp, tmp, funcp, offset, &okay);
   2089 	if (okay)
   2090 		return t;
   2091 	if (tmp->tm_isdst < 0)
   2092 #ifdef PCTS
   2093 		/*
   2094 		** POSIX Conformance Test Suite code courtesy Grant Sullivan.
   2095 		*/
   2096 		tmp->tm_isdst = 0;	/* reset to std and try again */
   2097 #else
   2098 		return t;
   2099 #endif /* !defined PCTS */
   2100 	/*
   2101 	** We're supposed to assume that somebody took a time of one type
   2102 	** and did some math on it that yielded a "struct tm" that's bad.
   2103 	** We try to divine the type they started from and adjust to the
   2104 	** type they need.
   2105 	*/
   2106 	if (sp == NULL) {
   2107 		errno = EINVAL;
   2108 		return WRONG;
   2109 	}
   2110 	for (i = 0; i < sp->typecnt; ++i)
   2111 		seen[i] = FALSE;
   2112 	nseen = 0;
   2113 	for (i = sp->timecnt - 1; i >= 0; --i)
   2114 		if (!seen[sp->types[i]]) {
   2115 			seen[sp->types[i]] = TRUE;
   2116 			types[nseen++] = sp->types[i];
   2117 		}
   2118 	for (sameind = 0; sameind < nseen; ++sameind) {
   2119 		samei = types[sameind];
   2120 		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
   2121 			continue;
   2122 		for (otherind = 0; otherind < nseen; ++otherind) {
   2123 			otheri = types[otherind];
   2124 			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
   2125 				continue;
   2126 			tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
   2127 					sp->ttis[samei].tt_gmtoff);
   2128 			tmp->tm_isdst = !tmp->tm_isdst;
   2129 			t = time2(sp, tmp, funcp, offset, &okay);
   2130 			if (okay)
   2131 				return t;
   2132 			tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
   2133 					sp->ttis[samei].tt_gmtoff);
   2134 			tmp->tm_isdst = !tmp->tm_isdst;
   2135 		}
   2136 	}
   2137 	errno = EOVERFLOW;
   2138 	return WRONG;
   2139 }
   2140 
   2141 time_t
   2142 mktime_z(const timezone_t sp, struct tm *const tmp)
   2143 {
   2144 	time_t t;
   2145 	if (sp == NULL)
   2146 		t = time1(NULL, tmp, gmtsub, 0);
   2147 	else
   2148 		t = time1(sp, tmp, localsub, 0);
   2149 	return t;
   2150 }
   2151 
   2152 time_t
   2153 mktime(struct tm *const tmp)
   2154 {
   2155 	time_t result;
   2156 
   2157 	rwlock_wrlock(&lcl_lock);
   2158 	tzset_unlocked();
   2159 	result = mktime_z(lclptr, tmp);
   2160 	rwlock_unlock(&lcl_lock);
   2161 	return result;
   2162 }
   2163 
   2164 #ifdef STD_INSPIRED
   2165 
   2166 time_t
   2167 timelocal_z(const timezone_t sp, struct tm *const tmp)
   2168 {
   2169 	if (tmp != NULL)
   2170 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
   2171 	return mktime_z(sp, tmp);
   2172 }
   2173 
   2174 time_t
   2175 timelocal(struct tm *const tmp)
   2176 {
   2177 	if (tmp != NULL)
   2178 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
   2179 	return mktime(tmp);
   2180 }
   2181 
   2182 time_t
   2183 timegm(struct tm *const tmp)
   2184 {
   2185 	time_t t;
   2186 
   2187 	if (tmp != NULL)
   2188 		tmp->tm_isdst = 0;
   2189 	t = time1(gmtptr, tmp, gmtsub, 0);
   2190 	return t;
   2191 }
   2192 
   2193 time_t
   2194 timeoff(struct tm *const tmp, long offset)
   2195 {
   2196 	time_t t;
   2197 
   2198 	if ((offset > 0 && offset > INT_FAST32_MAX) ||
   2199 	    (offset < 0 && offset < INT_FAST32_MIN)) {
   2200 		errno = EOVERFLOW;
   2201 		return -1;
   2202 	}
   2203 	if (tmp != NULL)
   2204 		tmp->tm_isdst = 0;
   2205 	t = time1(gmtptr, tmp, gmtsub, (int_fast32_t)offset);
   2206 	return t;
   2207 }
   2208 
   2209 #endif /* defined STD_INSPIRED */
   2210 
   2211 #ifdef CMUCS
   2212 
   2213 /*
   2214 ** The following is supplied for compatibility with
   2215 ** previous versions of the CMUCS runtime library.
   2216 */
   2217 
   2218 long
   2219 gtime(struct tm *const tmp)
   2220 {
   2221 	const time_t t = mktime(tmp);
   2222 
   2223 	if (t == WRONG)
   2224 		return -1;
   2225 	return t;
   2226 }
   2227 
   2228 #endif /* defined CMUCS */
   2229 
   2230 /*
   2231 ** XXX--is the below the right way to conditionalize??
   2232 */
   2233 
   2234 #ifdef STD_INSPIRED
   2235 
   2236 /*
   2237 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
   2238 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
   2239 ** is not the case if we are accounting for leap seconds.
   2240 ** So, we provide the following conversion routines for use
   2241 ** when exchanging timestamps with POSIX conforming systems.
   2242 */
   2243 
   2244 static int_fast64_t
   2245 leapcorr(const timezone_t sp, time_t *timep)
   2246 {
   2247 	struct lsinfo * lp;
   2248 	int		i;
   2249 
   2250 	i = sp->leapcnt;
   2251 	while (--i >= 0) {
   2252 		lp = &sp->lsis[i];
   2253 		if (*timep >= lp->ls_trans)
   2254 			return lp->ls_corr;
   2255 	}
   2256 	return 0;
   2257 }
   2258 
   2259 time_t
   2260 time2posix_z(const timezone_t sp, time_t t)
   2261 {
   2262 	return (time_t)(t - leapcorr(sp, &t));
   2263 }
   2264 
   2265 time_t
   2266 time2posix(time_t t)
   2267 {
   2268 	time_t result;
   2269 	rwlock_wrlock(&lcl_lock);
   2270 	tzset_unlocked();
   2271 	result = (time_t)(t - leapcorr(lclptr, &t));
   2272 	rwlock_unlock(&lcl_lock);
   2273 	return (result);
   2274 }
   2275 
   2276 time_t
   2277 posix2time_z(const timezone_t sp, time_t t)
   2278 {
   2279 	time_t	x;
   2280 	time_t	y;
   2281 
   2282 	/*
   2283 	** For a positive leap second hit, the result
   2284 	** is not unique. For a negative leap second
   2285 	** hit, the corresponding time doesn't exist,
   2286 	** so we return an adjacent second.
   2287 	*/
   2288 	x = (time_t)(t + leapcorr(sp, &t));
   2289 	y = (time_t)(x - leapcorr(sp, &x));
   2290 	if (y < t) {
   2291 		do {
   2292 			x++;
   2293 			y = (time_t)(x - leapcorr(sp, &x));
   2294 		} while (y < t);
   2295 		if (t != y) {
   2296 			return x - 1;
   2297 		}
   2298 	} else if (y > t) {
   2299 		do {
   2300 			--x;
   2301 			y = (time_t)(x - leapcorr(sp, &x));
   2302 		} while (y > t);
   2303 		if (t != y) {
   2304 			return x + 1;
   2305 		}
   2306 	}
   2307 	return x;
   2308 }
   2309 
   2310 
   2311 
   2312 time_t
   2313 posix2time(time_t t)
   2314 {
   2315 	time_t result;
   2316 
   2317 	rwlock_wrlock(&lcl_lock);
   2318 	tzset_unlocked();
   2319 	result = posix2time_z(lclptr, t);
   2320 	rwlock_unlock(&lcl_lock);
   2321 	return result;
   2322 }
   2323 
   2324 #endif /* defined STD_INSPIRED */
   2325