convert malloc use under libc-internal locks to use internal allocator
[musl] / src / time / __tz.c
1 #include "time_impl.h"
2 #include <stdint.h>
3 #include <limits.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/mman.h>
7 #include "libc.h"
8 #include "lock.h"
9
10 #define malloc __libc_malloc
11 #define calloc undef
12 #define realloc undef
13 #define free undef
14
15 long  __timezone = 0;
16 int   __daylight = 0;
17 char *__tzname[2] = { 0, 0 };
18
19 weak_alias(__timezone, timezone);
20 weak_alias(__daylight, daylight);
21 weak_alias(__tzname, tzname);
22
23 static char std_name[TZNAME_MAX+1];
24 static char dst_name[TZNAME_MAX+1];
25 const char __utc[] = "UTC";
26
27 static int dst_off;
28 static int r0[5], r1[5];
29
30 static const unsigned char *zi, *trans, *index, *types, *abbrevs, *abbrevs_end;
31 static size_t map_size;
32
33 static char old_tz_buf[32];
34 static char *old_tz = old_tz_buf;
35 static size_t old_tz_size = sizeof old_tz_buf;
36
37 static volatile int lock[1];
38
39 static int getint(const char **p)
40 {
41         unsigned x;
42         for (x=0; **p-'0'<10U; (*p)++) x = **p-'0' + 10*x;
43         return x;
44 }
45
46 static int getoff(const char **p)
47 {
48         int neg = 0;
49         if (**p == '-') {
50                 ++*p;
51                 neg = 1;
52         } else if (**p == '+') {
53                 ++*p;
54         }
55         int off = 3600*getint(p);
56         if (**p == ':') {
57                 ++*p;
58                 off += 60*getint(p);
59                 if (**p == ':') {
60                         ++*p;
61                         off += getint(p);
62                 }
63         }
64         return neg ? -off : off;
65 }
66
67 static void getrule(const char **p, int rule[5])
68 {
69         int r = rule[0] = **p;
70
71         if (r!='M') {
72                 if (r=='J') ++*p;
73                 else rule[0] = 0;
74                 rule[1] = getint(p);
75         } else {
76                 ++*p; rule[1] = getint(p);
77                 ++*p; rule[2] = getint(p);
78                 ++*p; rule[3] = getint(p);
79         }
80
81         if (**p=='/') {
82                 ++*p;
83                 rule[4] = getoff(p);
84         } else {
85                 rule[4] = 7200;
86         }
87 }
88
89 static void getname(char *d, const char **p)
90 {
91         int i;
92         if (**p == '<') {
93                 ++*p;
94                 for (i=0; (*p)[i] && (*p)[i]!='>'; i++)
95                         if (i<TZNAME_MAX) d[i] = (*p)[i];
96                 if ((*p)[i]) ++*p;
97         } else {
98                 for (i=0; ((*p)[i]|32)-'a'<26U; i++)
99                         if (i<TZNAME_MAX) d[i] = (*p)[i];
100         }
101         *p += i;
102         d[i<TZNAME_MAX?i:TZNAME_MAX] = 0;
103 }
104
105 #define VEC(...) ((const unsigned char[]){__VA_ARGS__})
106
107 static uint32_t zi_read32(const unsigned char *z)
108 {
109         return (unsigned)z[0]<<24 | z[1]<<16 | z[2]<<8 | z[3];
110 }
111
112 static size_t zi_dotprod(const unsigned char *z, const unsigned char *v, size_t n)
113 {
114         size_t y;
115         uint32_t x;
116         for (y=0; n; n--, z+=4, v++) {
117                 x = zi_read32(z);
118                 y += x * *v;
119         }
120         return y;
121 }
122
123 static void do_tzset()
124 {
125         char buf[NAME_MAX+25], *pathname=buf+24;
126         const char *try, *s, *p;
127         const unsigned char *map = 0;
128         size_t i;
129         static const char search[] =
130                 "/usr/share/zoneinfo/\0/share/zoneinfo/\0/etc/zoneinfo/\0";
131
132         s = getenv("TZ");
133         if (!s) s = "/etc/localtime";
134         if (!*s) s = __utc;
135
136         if (old_tz && !strcmp(s, old_tz)) return;
137
138         for (i=0; i<5; i++) r0[i] = r1[i] = 0;
139
140         if (zi) __munmap((void *)zi, map_size);
141
142         /* Cache the old value of TZ to check if it has changed. Avoid
143          * free so as not to pull it into static programs. Growth
144          * strategy makes it so free would have minimal benefit anyway. */
145         i = strlen(s);
146         if (i > PATH_MAX+1) s = __utc, i = 3;
147         if (i >= old_tz_size) {
148                 old_tz_size *= 2;
149                 if (i >= old_tz_size) old_tz_size = i+1;
150                 if (old_tz_size > PATH_MAX+2) old_tz_size = PATH_MAX+2;
151                 old_tz = malloc(old_tz_size);
152         }
153         if (old_tz) memcpy(old_tz, s, i+1);
154
155         /* Non-suid can use an absolute tzfile pathname or a relative
156          * pathame beginning with "."; in secure mode, only the
157          * standard path will be searched. */
158         if (*s == ':' || ((p=strchr(s, '/')) && !memchr(s, ',', p-s))) {
159                 if (*s == ':') s++;
160                 if (*s == '/' || *s == '.') {
161                         if (!libc.secure || !strcmp(s, "/etc/localtime"))
162                                 map = __map_file(s, &map_size);
163                 } else {
164                         size_t l = strlen(s);
165                         if (l <= NAME_MAX && !strchr(s, '.')) {
166                                 memcpy(pathname, s, l+1);
167                                 pathname[l] = 0;
168                                 for (try=search; !map && *try; try+=l+1) {
169                                         l = strlen(try);
170                                         memcpy(pathname-l, try, l);
171                                         map = __map_file(pathname-l, &map_size);
172                                 }
173                         }
174                 }
175                 if (!map) s = __utc;
176         }
177         if (map && (map_size < 44 || memcmp(map, "TZif", 4))) {
178                 __munmap((void *)map, map_size);
179                 map = 0;
180                 s = __utc;
181         }
182
183         zi = map;
184         if (map) {
185                 int scale = 2;
186                 if (sizeof(time_t) > 4 && map[4]=='2') {
187                         size_t skip = zi_dotprod(zi+20, VEC(1,1,8,5,6,1), 6);
188                         trans = zi+skip+44+44;
189                         scale++;
190                 } else {
191                         trans = zi+44;
192                 }
193                 index = trans + (zi_read32(trans-12) << scale);
194                 types = index + zi_read32(trans-12);
195                 abbrevs = types + 6*zi_read32(trans-8);
196                 abbrevs_end = abbrevs + zi_read32(trans-4);
197                 if (zi[map_size-1] == '\n') {
198                         for (s = (const char *)zi+map_size-2; *s!='\n'; s--);
199                         s++;
200                 } else {
201                         const unsigned char *p;
202                         __tzname[0] = __tzname[1] = 0;
203                         __daylight = __timezone = dst_off = 0;
204                         for (p=types; p<abbrevs; p+=6) {
205                                 if (!p[4] && !__tzname[0]) {
206                                         __tzname[0] = (char *)abbrevs + p[5];
207                                         __timezone = -zi_read32(p);
208                                 }
209                                 if (p[4] && !__tzname[1]) {
210                                         __tzname[1] = (char *)abbrevs + p[5];
211                                         dst_off = -zi_read32(p);
212                                         __daylight = 1;
213                                 }
214                         }
215                         if (!__tzname[0]) __tzname[0] = __tzname[1];
216                         if (!__tzname[0]) __tzname[0] = (char *)__utc;
217                         if (!__daylight) {
218                                 __tzname[1] = __tzname[0];
219                                 dst_off = __timezone;
220                         }
221                         return;
222                 }
223         }
224
225         if (!s) s = __utc;
226         getname(std_name, &s);
227         __tzname[0] = std_name;
228         __timezone = getoff(&s);
229         getname(dst_name, &s);
230         __tzname[1] = dst_name;
231         if (dst_name[0]) {
232                 __daylight = 1;
233                 if (*s == '+' || *s=='-' || *s-'0'<10U)
234                         dst_off = getoff(&s);
235                 else
236                         dst_off = __timezone - 3600;
237         } else {
238                 __daylight = 0;
239                 dst_off = __timezone;
240         }
241
242         if (*s == ',') s++, getrule(&s, r0);
243         if (*s == ',') s++, getrule(&s, r1);
244 }
245
246 /* Search zoneinfo rules to find the one that applies to the given time,
247  * and determine alternate opposite-DST-status rule that may be needed. */
248
249 static size_t scan_trans(long long t, int local, size_t *alt)
250 {
251         int scale = 3 - (trans == zi+44);
252         uint64_t x;
253         int off = 0;
254
255         size_t a = 0, n = (index-trans)>>scale, m;
256
257         if (!n) {
258                 if (alt) *alt = 0;
259                 return 0;
260         }
261
262         /* Binary search for 'most-recent rule before t'. */
263         while (n > 1) {
264                 m = a + n/2;
265                 x = zi_read32(trans + (m<<scale));
266                 if (scale == 3) x = x<<32 | zi_read32(trans + (m<<scale) + 4);
267                 else x = (int32_t)x;
268                 if (local) off = (int32_t)zi_read32(types + 6 * index[m-1]);
269                 if (t - off < (int64_t)x) {
270                         n /= 2;
271                 } else {
272                         a = m;
273                         n -= n/2;
274                 }
275         }
276
277         /* First and last entry are special. First means to use lowest-index
278          * non-DST type. Last means to apply POSIX-style rule if available. */
279         n = (index-trans)>>scale;
280         if (a == n-1) return -1;
281         if (a == 0) {
282                 x = zi_read32(trans + (a<<scale));
283                 if (scale == 3) x = x<<32 | zi_read32(trans + (a<<scale) + 4);
284                 else x = (int32_t)x;
285                 if (local) off = (int32_t)zi_read32(types + 6 * index[a-1]);
286                 if (t - off < (int64_t)x) {
287                         for (a=0; a<(abbrevs-types)/6; a++) {
288                                 if (types[6*a+4] != types[4]) break;
289                         }
290                         if (a == (abbrevs-types)/6) a = 0;
291                         if (types[6*a+4]) {
292                                 *alt = a;
293                                 return 0;
294                         } else {
295                                 *alt = 0;
296                                 return a;
297                         }
298                 }
299         }
300
301         /* Try to find a neighboring opposite-DST-status rule. */
302         if (alt) {
303                 if (a && types[6*index[a-1]+4] != types[6*index[a]+4])
304                         *alt = index[a-1];
305                 else if (a+1<n && types[6*index[a+1]+4] != types[6*index[a]+4])
306                         *alt = index[a+1];
307                 else
308                         *alt = index[a];
309         }
310
311         return index[a];
312 }
313
314 static int days_in_month(int m, int is_leap)
315 {
316         if (m==2) return 28+is_leap;
317         else return 30+((0xad5>>(m-1))&1);
318 }
319
320 /* Convert a POSIX DST rule plus year to seconds since epoch. */
321
322 static long long rule_to_secs(const int *rule, int year)
323 {
324         int is_leap;
325         long long t = __year_to_secs(year, &is_leap);
326         int x, m, n, d;
327         if (rule[0]!='M') {
328                 x = rule[1];
329                 if (rule[0]=='J' && (x < 60 || !is_leap)) x--;
330                 t += 86400 * x;
331         } else {
332                 m = rule[1];
333                 n = rule[2];
334                 d = rule[3];
335                 t += __month_to_secs(m-1, is_leap);
336                 int wday = (int)((t + 4*86400) % (7*86400)) / 86400;
337                 int days = d - wday;
338                 if (days < 0) days += 7;
339                 if (n == 5 && days+28 >= days_in_month(m, is_leap)) n = 4;
340                 t += 86400 * (days + 7*(n-1));
341         }
342         t += rule[4];
343         return t;
344 }
345
346 /* Determine the time zone in effect for a given time in seconds since the
347  * epoch. It can be given in local or universal time. The results will
348  * indicate whether DST is in effect at the queried time, and will give both
349  * the GMT offset for the active zone/DST rule and the opposite DST. This
350  * enables a caller to efficiently adjust for the case where an explicit
351  * DST specification mismatches what would be in effect at the time. */
352
353 void __secs_to_zone(long long t, int local, int *isdst, long *offset, long *oppoff, const char **zonename)
354 {
355         LOCK(lock);
356
357         do_tzset();
358
359         if (zi) {
360                 size_t alt, i = scan_trans(t, local, &alt);
361                 if (i != -1) {
362                         *isdst = types[6*i+4];
363                         *offset = (int32_t)zi_read32(types+6*i);
364                         *zonename = (const char *)abbrevs + types[6*i+5];
365                         if (oppoff) *oppoff = (int32_t)zi_read32(types+6*alt);
366                         UNLOCK(lock);
367                         return;
368                 }
369         }
370
371         if (!__daylight) goto std;
372
373         /* FIXME: may be broken if DST changes right at year boundary?
374          * Also, this could be more efficient.*/
375         long long y = t / 31556952 + 70;
376         while (__year_to_secs(y, 0) > t) y--;
377         while (__year_to_secs(y+1, 0) < t) y++;
378
379         long long t0 = rule_to_secs(r0, y);
380         long long t1 = rule_to_secs(r1, y);
381
382         if (!local) {
383                 t0 += __timezone;
384                 t1 += dst_off;
385         }
386         if (t0 < t1) {
387                 if (t >= t0 && t < t1) goto dst;
388                 goto std;
389         } else {
390                 if (t >= t1 && t < t0) goto std;
391                 goto dst;
392         }
393 std:
394         *isdst = 0;
395         *offset = -__timezone;
396         if (oppoff) *oppoff = -dst_off;
397         *zonename = __tzname[0];
398         UNLOCK(lock);
399         return;
400 dst:
401         *isdst = 1;
402         *offset = -dst_off;
403         if (oppoff) *oppoff = -__timezone;
404         *zonename = __tzname[1];
405         UNLOCK(lock);
406 }
407
408 static void __tzset()
409 {
410         LOCK(lock);
411         do_tzset();
412         UNLOCK(lock);
413 }
414
415 weak_alias(__tzset, tzset);
416
417 const char *__tm_to_tzname(const struct tm *tm)
418 {
419         const void *p = tm->__tm_zone;
420         LOCK(lock);
421         do_tzset();
422         if (p != __utc && p != __tzname[0] && p != __tzname[1] &&
423             (!zi || (uintptr_t)p-(uintptr_t)abbrevs >= abbrevs_end - abbrevs))
424                 p = "";
425         UNLOCK(lock);
426         return p;
427 }