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