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