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