Debian Codegraph @

lib/mktime.c

raw
1 /* Convert a 'struct tm' to a time_t value.
2 Copyright (C) 1993-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Paul Eggert <[email protected]>.
5
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
19
20 /* The following macros influence what gets defined when this file is compiled:
21
22 Macro/expression Which gnulib module This compilation unit
23 should define
24
25 _LIBC (glibc proper) mktime
26
27 NEED_MKTIME_WORKING mktime rpl_mktime
28 || NEED_MKTIME_WINDOWS
29
30 NEED_MKTIME_INTERNAL mktime-internal mktime_internal
31 */
32
33 #ifndef _LIBC
34 # include <libc-config.h>
35 #endif
36
37 /* Assume that leap seconds are possible, unless told otherwise.
38 If the host has a 'zic' command with a '-L leapsecondfilename' option,
39 then it supports leap seconds; otherwise it probably doesn't. */
40 #ifndef LEAP_SECONDS_POSSIBLE
41 # define LEAP_SECONDS_POSSIBLE 1
42 #endif
43
44 #include <time.h>
45
46 #include <errno.h>
47 #include <limits.h>
48 #include <stdbool.h>
49 #include <stdckdint.h>
50 #include <stdlib.h>
51 #include <string.h>
52
53 #include <intprops.h>
54
55 #ifndef NEED_MKTIME_INTERNAL
56 # define NEED_MKTIME_INTERNAL 0
57 #endif
58 #ifndef NEED_MKTIME_WINDOWS
59 # define NEED_MKTIME_WINDOWS 0
60 #endif
61 #ifndef NEED_MKTIME_WORKING
62 # define NEED_MKTIME_WORKING 0
63 #endif
64
65 #include "mktime-internal.h"
66
67 #if !defined _LIBC && (NEED_MKTIME_WORKING || NEED_MKTIME_WINDOWS)
68 static void
69 my_tzset (void)
70 {
71 # if NEED_MKTIME_WINDOWS
72 /* Rectify the value of the environment variable TZ.
73 There are four possible kinds of such values:
74 - Traditional US time zone names, e.g. "PST8PDT". Syntax: see
75 <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/tzset>
76 - Time zone names based on geography, that contain one or more
77 slashes, e.g. "Europe/Moscow".
78 - Time zone names based on geography, without slashes, e.g.
79 "Singapore".
80 - Time zone names that contain explicit DST rules. Syntax: see
81 <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03>
82 The Microsoft CRT understands only the first kind. It produces incorrect
83 results if the value of TZ is of the other kinds.
84 But in a Cygwin environment, /etc/profile.d/tzset.sh sets TZ to a value
85 of the second kind for most geographies, or of the first kind in a few
86 other geographies. If it is of the second kind, neutralize it. For the
87 Microsoft CRT, an absent or empty TZ means the time zone that the user
88 has set in the Windows Control Panel.
89 If the value of TZ is of the third or fourth kind -- Cygwin programs
90 understand these syntaxes as well --, it does not matter whether we
91 neutralize it or not, since these values occur only when a Cygwin user
92 has set TZ explicitly; this case is 1. rare and 2. under the user's
93 responsibility. */
94 const char *tz = getenv ("TZ");
95 if (tz != NULL && strchr (tz, '/') != NULL)
96 _putenv ("TZ=");
97 # else
98 tzset ();
99 # endif
100 }
101 # undef __tzset
102 # define __tzset() my_tzset ()
103 #endif
104
105 #if defined _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_INTERNAL
106
107 /* A signed type that can represent an integer number of years
108 multiplied by four times the number of seconds in a year. It is
109 needed when converting a tm_year value times the number of seconds
110 in a year. The factor of four comes because these products need
111 to be subtracted from each other, and sometimes with an offset
112 added to them, and then with another timestamp added, without
113 worrying about overflow.
114
115 Much of the code uses long_int to represent __time64_t values, to
116 lessen the hassle of dealing with platforms where __time64_t is
117 unsigned, and because long_int should suffice to represent all
118 __time64_t values that mktime can generate even on platforms where
119 __time64_t is wider than the int components of struct tm. */
120
121 # if INT_MAX <= LONG_MAX / 4 / 366 / 24 / 60 / 60
122 typedef long int long_int;
123 # else
124 typedef long long int long_int;
125 # endif
126 static_assert (INT_MAX <= TYPE_MAXIMUM (long_int) / 4 / 366 / 24 / 60 / 60);
127
128 /* Shift A right by B bits portably, by dividing A by 2**B and
129 truncating towards minus infinity. B should be in the range 0 <= B
130 <= LONG_INT_BITS - 2, where LONG_INT_BITS is the number of useful
131 bits in a long_int. LONG_INT_BITS is at least 32.
132
133 ISO C99 says that A >> B is implementation-defined if A < 0. Some
134 implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
135 right in the usual way when A < 0, so SHR falls back on division if
136 ordinary A >> B doesn't seem to be the usual signed shift. */
137
138 static long_int
139 shr (long_int a, int b)
140 {
141 long_int one = 1;
142 return (-one >> 1 == -1
143 ? a >> b
144 : (a + (a < 0)) / (one << b) - (a < 0));
145 }
146
147 /* Bounds for the intersection of __time64_t and long_int. */
148
149 static long_int const mktime_min
150 = ((TYPE_SIGNED (__time64_t)
151 && TYPE_MINIMUM (__time64_t) < TYPE_MINIMUM (long_int))
152 ? TYPE_MINIMUM (long_int) : TYPE_MINIMUM (__time64_t));
153 static long_int const mktime_max
154 = (TYPE_MAXIMUM (long_int) < TYPE_MAXIMUM (__time64_t)
155 ? TYPE_MAXIMUM (long_int) : TYPE_MAXIMUM (__time64_t));
156
157 # define EPOCH_YEAR 1970
158 # define TM_YEAR_BASE 1900
159 static_assert (TM_YEAR_BASE % 100 == 0);
160
161 /* Is YEAR + TM_YEAR_BASE a leap year? */
162 static bool
163 leapyear (long_int year)
164 {
165 /* Don't add YEAR to TM_YEAR_BASE, as that might overflow.
166 Also, work even if YEAR is negative. */
167 return
168 ((year & 3) == 0
169 && (year % 100 != 0
170 || ((year / 100) & 3) == (- (TM_YEAR_BASE / 100) & 3)));
171 }
172
173 /* How many days come before each month (0-12). */
174 # ifndef _LIBC
175 static
176 # endif
177 const unsigned short int __mon_yday[2][13] =
178 {
179 /* Normal years. */
180 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
181 /* Leap years. */
182 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
183 };
184
185
186 /* Do the values A and B differ according to the rules for tm_isdst?
187 A and B differ if one is zero and the other positive. */
188 static bool
189 isdst_differ (int a, int b)
190 {
191 return (!a != !b) && (0 <= a) && (0 <= b);
192 }
193
194 /* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
195 (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds, assuming that the clocks
196 were not adjusted between the timestamps.
197
198 The YEAR values uses the same numbering as TP->tm_year. Values
199 need not be in the usual range. However, YEAR1 - YEAR0 must not
200 overflow even when multiplied by three times the number of seconds
201 in a year, and likewise for YDAY1 - YDAY0 and three times the
202 number of seconds in a day. */
203
204 static long_int
205 ydhms_diff (long_int year1, long_int yday1, int hour1, int min1, int sec1,
206 int year0, int yday0, int hour0, int min0, int sec0)
207 {
208 static_assert (-1 / 2 == 0);
209
210 /* Compute intervening leap days correctly even if year is negative.
211 Take care to avoid integer overflow here. */
212 int a4 = shr (year1, 2) + shr (TM_YEAR_BASE, 2) - ! (year1 & 3);
213 int b4 = shr (year0, 2) + shr (TM_YEAR_BASE, 2) - ! (year0 & 3);
214 int a100 = (a4 + (a4 < 0)) / 25 - (a4 < 0);
215 int b100 = (b4 + (b4 < 0)) / 25 - (b4 < 0);
216 int a400 = shr (a100, 2);
217 int b400 = shr (b100, 2);
218 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
219
220 /* Compute the desired time without overflowing. */
221 long_int years = year1 - year0;
222 long_int days = 365 * years + yday1 - yday0 + intervening_leap_days;
223 long_int hours = 24 * days + hour1 - hour0;
224 long_int minutes = 60 * hours + min1 - min0;
225 long_int seconds = 60 * minutes + sec1 - sec0;
226 return seconds;
227 }
228
229 /* Return the average of A and B, even if A + B would overflow.
230 Round toward positive infinity. */
231 static long_int
232 long_int_avg (long_int a, long_int b)
233 {
234 return shr (a, 1) + shr (b, 1) + ((a | b) & 1);
235 }
236
237 /* Return a long_int value corresponding to (YEAR-YDAY HOUR:MIN:SEC)
238 minus *TP seconds, assuming no clock adjustments occurred between
239 the two timestamps.
240
241 YEAR and YDAY must not be so large that multiplying them by three times the
242 number of seconds in a year (or day, respectively) would overflow long_int.
243 *TP should be in the usual range. */
244 static long_int
245 tm_diff (long_int year, long_int yday, int hour, int min, int sec,
246 struct tm const *tp)
247 {
248 return ydhms_diff (year, yday, hour, min, sec,
249 tp->tm_year, tp->tm_yday,
250 tp->tm_hour, tp->tm_min, tp->tm_sec);
251 }
252
253 /* Convert T to a struct tm value in *TM. Use localtime64_r if LOCAL,
254 otherwise gmtime64_r. T must be in range for __time64_t. Return
255 TM if successful, NULL (setting errno) on failure. */
256 static struct tm *
257 convert_time (long_int t, bool local, struct tm *tm)
258 {
259 __time64_t x = t;
260 if (local)
261 return __localtime64_r (&x, tm);
262 else
263 return __gmtime64_r (&x, tm);
264 }
265 /* Call it __tzconvert to sync with other parts of glibc. */
266 #define __tz_convert convert_time
267
268 /* Convert *T to a broken down time in *TP (as if by localtime if
269 LOCAL, otherwise as if by gmtime). If *T is out of range for
270 conversion, adjust it so that it is the nearest in-range value and
271 then convert that. A value is in range if it fits in both
272 __time64_t and long_int. Return TP on success, NULL (setting
273 errno) on failure. */
274 static struct tm *
275 ranged_convert (bool local, long_int *t, struct tm *tp)
276 {
277 long_int t1 = (*t < mktime_min ? mktime_min
278 : *t <= mktime_max ? *t : mktime_max);
279 struct tm *r = __tz_convert (t1, local, tp);
280 if (r)
281 {
282 *t = t1;
283 return r;
284 }
285 if (errno != EOVERFLOW)
286 return NULL;
287
288 long_int bad = t1;
289 long_int ok = 0;
290 struct tm oktm; oktm.tm_sec = -1;
291
292 /* BAD is a known out-of-range value, and OK is a known in-range one.
293 Use binary search to narrow the range between BAD and OK until
294 they differ by 1. */
295 while (true)
296 {
297 long_int mid = long_int_avg (ok, bad);
298 if (mid == ok || mid == bad)
299 break;
300 if (__tz_convert (mid, local, tp))
301 ok = mid, oktm = *tp;
302 else if (errno != EOVERFLOW)
303 return NULL;
304 else
305 bad = mid;
306 }
307
308 if (oktm.tm_sec < 0)
309 return NULL;
310 *t = ok;
311 *tp = oktm;
312 return tp;
313 }
314
315
316 /* Convert *TP to a __time64_t value. If LOCAL, the reverse mapping
317 is performed as if localtime, otherwise as if by gmtime. Use
318 *OFFSET to keep track of a guess at the offset of the result,
319 compared to what the result would be for UTC without leap seconds.
320 If *OFFSET's guess is correct, only one reverse mapping call is
321 needed. If successful, set *TP to the canonicalized struct tm;
322 otherwise leave *TP alone, return ((time_t) -1) and set errno.
323 This function is external because it is used also by timegm.c. */
324 __time64_t
325 __mktime_internal (struct tm *tp, bool local, mktime_offset_t *offset)
326 {
327 struct tm tm;
328
329 /* The maximum number of probes should be enough to handle any
330 combinations of time zone rule changes, solar time, leap seconds,
331 and oscillations around a spring-forward gap. POSIX.1 prohibits
332 leap seconds, but some hosts have them anyway. */
333 int remaining_probes = 6;
334
335 #ifndef _LIBC
336 /* Gnulib mktime doesn't lock the tz state, so it may need to probe
337 more often if some other thread changes local time while
338 __mktime_internal is probing. Double the number of probes; this
339 should suffice for practical cases that are at all likely. */
340 remaining_probes *= 2;
341 #endif
342
343 /* Time requested. Copy it in case gmtime/localtime modify *TP;
344 this can occur if TP is localtime's returned value and CONVERT is
345 localtime. */
346 int sec = tp->tm_sec;
347 int min = tp->tm_min;
348 int hour = tp->tm_hour;
349 int mday = tp->tm_mday;
350 int mon = tp->tm_mon;
351 int year_requested = tp->tm_year;
352
353 /* If the timezone never observes DST, ignore any tm_isdst request. */
354 int isdst = local && __daylight ? tp->tm_isdst : 0;
355
356 /* 1 if the previous probe was DST. */
357 int dst2 = 0;
358
359 /* Ensure that mon is in range, and set year accordingly. */
360 int mon_remainder = mon % 12;
361 int negative_mon_remainder = mon_remainder < 0;
362 int mon_years = mon / 12 - negative_mon_remainder;
363 long_int lyear_requested = year_requested;
364 long_int year = lyear_requested + mon_years;
365
366 /* The other values need not be in range:
367 the remaining code handles overflows correctly. */
368
369 /* Calculate day of year from year, month, and day of month.
370 The result need not be in range. */
371 int mon_yday = ((__mon_yday[leapyear (year)]
372 [mon_remainder + 12 * negative_mon_remainder])
373 - 1);
374 long_int lmday = mday;
375 long_int yday = mon_yday + lmday;
376
377 mktime_offset_t off = *offset;
378 int negative_offset_guess;
379
380 int sec_requested = sec;
381
382 if (LEAP_SECONDS_POSSIBLE)
383 {
384 /* Handle out-of-range seconds specially,
385 since ydhms_diff assumes every minute has 60 seconds. */
386 if (sec < 0)
387 sec = 0;
388 if (59 < sec)
389 sec = 59;
390 }
391
392 /* Invert CONVERT by probing. First assume the same offset as last
393 time. */
394
395 ckd_sub (&negative_offset_guess, 0, off);
396 long_int t0 = ydhms_diff (year, yday, hour, min, sec,
397 EPOCH_YEAR - TM_YEAR_BASE, 0, 0, 0,
398 negative_offset_guess);
399 long_int t = t0, t1 = t0, t2 = t0;
400
401 /* Repeatedly use the error to improve the guess. */
402
403 while (true)
404 {
405 if (! ranged_convert (local, &t, &tm))
406 return -1;
407 long_int dt = tm_diff (year, yday, hour, min, sec, &tm);
408 if (dt == 0)
409 break;
410
411 if (t == t1 && t != t2
412 && (tm.tm_isdst < 0
413 || (isdst < 0
414 ? dst2 <= (tm.tm_isdst != 0)
415 : (isdst != 0) != (tm.tm_isdst != 0))))
416 /* We can't possibly find a match, as we are oscillating
417 between two values. The requested time probably falls
418 within a spring-forward gap of size DT. Follow the common
419 practice in this case, which is to return a time that is DT
420 away from the requested time, preferring a time whose
421 tm_isdst differs from the requested value. (If no tm_isdst
422 was requested and only one of the two values has a nonzero
423 tm_isdst, prefer that value.) In practice, this is more
424 useful than returning -1. */
425 goto offset_found;
426
427 remaining_probes--;
428 if (remaining_probes == 0)
429 {
430 __set_errno (EOVERFLOW);
431 return -1;
432 }
433
434 t1 = t2, t2 = t, t += dt, dst2 = tm.tm_isdst != 0;
435 }
436
437 /* We have a match. Check whether tm.tm_isdst has the requested
438 value, if any. */
439 if (isdst_differ (isdst, tm.tm_isdst))
440 {
441 /* tm.tm_isdst has the wrong value. Look for a neighboring
442 time with the right value, and use its UTC offset.
443
444 Heuristic: probe the adjacent timestamps in both directions,
445 looking for the desired isdst. If none is found within a
446 reasonable duration bound, assume a one-hour DST difference.
447 This should work for all real time zone histories in the tz
448 database. */
449
450 /* +1 if we wanted standard time but got DST, -1 if the reverse. */
451 int dst_difference = (isdst == 0) - (tm.tm_isdst == 0);
452
453 /* Distance between probes when looking for a DST boundary. In
454 tzdata2003a, the shortest period of DST is 601200 seconds
455 (e.g., America/Recife starting 2000-10-08 01:00), and the
456 shortest period of non-DST surrounded by DST is 694800
457 seconds (Africa/Tunis starting 1943-04-17 01:00). Use the
458 minimum of these two values, so we don't miss these short
459 periods when probing. */
460 int stride = 601200;
461
462 /* In TZDB 2021e, the longest period of DST (or of non-DST), in
463 which the DST (or adjacent DST) difference is not one hour,
464 is 457243209 seconds: e.g., America/Cambridge_Bay with leap
465 seconds, starting 1965-10-31 00:00 in a switch from
466 double-daylight time (-05) to standard time (-07), and
467 continuing to 1980-04-27 02:00 in a switch from standard time
468 (-07) to daylight time (-06). */
469 int duration_max = 457243209;
470
471 /* Search in both directions, so the maximum distance is half
472 the duration; add the stride to avoid off-by-1 problems. */
473 int delta_bound = duration_max / 2 + stride;
474
475 int delta, direction;
476
477 for (delta = stride; delta < delta_bound; delta += stride)
478 for (direction = -1; direction <= 1; direction += 2)
479 {
480 long_int ot;
481 if (! ckd_add (&ot, t, delta * direction))
482 {
483 struct tm otm;
484 if (! ranged_convert (local, &ot, &otm))
485 return -1;
486 if (! isdst_differ (isdst, otm.tm_isdst))
487 {
488 /* We found the desired tm_isdst.
489 Extrapolate back to the desired time. */
490 long_int gt = ot + tm_diff (year, yday, hour, min, sec,
491 &otm);
492 if (mktime_min <= gt && gt <= mktime_max)
493 {
494 if (__tz_convert (gt, local, &tm))
495 {
496 t = gt;
497 goto offset_found;
498 }
499 if (errno != EOVERFLOW)
500 return -1;
501 }
502 }
503 }
504 }
505
506 /* No unusual DST offset was found nearby. Assume one-hour DST. */
507 t += 60 * 60 * dst_difference;
508 if (mktime_min <= t && t <= mktime_max && __tz_convert (t, local, &tm))
509 goto offset_found;
510
511 __set_errno (EOVERFLOW);
512 return -1;
513 }
514
515 offset_found:
516 /* Set *OFFSET to the low-order bits of T - T0 - NEGATIVE_OFFSET_GUESS.
517 This is just a heuristic to speed up the next mktime call, and
518 correctness is unaffected if integer overflow occurs here. */
519 ckd_sub (offset, t, t0);
520 ckd_sub (offset, *offset, negative_offset_guess);
521
522 if (LEAP_SECONDS_POSSIBLE && sec_requested != tm.tm_sec)
523 {
524 /* Adjust time to reflect the tm_sec requested, not the normalized value.
525 Also, repair any damage from a false match due to a leap second. */
526 long_int sec_adjustment = sec == 0 && tm.tm_sec == 60;
527 sec_adjustment -= sec;
528 sec_adjustment += sec_requested;
529 if (ckd_add (&t, t, sec_adjustment)
530 || ! (mktime_min <= t && t <= mktime_max))
531 {
532 __set_errno (EOVERFLOW);
533 return -1;
534 }
535 if (! __tz_convert (t, local, &tm))
536 return -1;
537 }
538
539 *tp = tm;
540 return t;
541 }
542
543 #endif /* _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_INTERNAL */
544
545 #if defined _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_WINDOWS
546
547 /* Convert *TP to a __time64_t value. */
548 __time64_t
549 __mktime64 (struct tm *tp)
550 {
551 /* POSIX.1 requires mktime to set external variables like 'tzname'
552 as though tzset had been called. */
553 __tzset ();
554
555 # if defined _LIBC || NEED_MKTIME_WORKING
556 static mktime_offset_t localtime_offset;
557 return __mktime_internal (tp, true, &localtime_offset);
558 # else
559 # undef mktime
560 return mktime (tp);
561 # endif
562 }
563 #endif /* _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_WINDOWS */
564
565 #if defined _LIBC && __TIMESIZE != 64
566
567 libc_hidden_def (__mktime64)
568
569 time_t
570 mktime (struct tm *tp)
571 {
572 struct tm tm = *tp;
573 __time64_t t = __mktime64 (&tm);
574 if (in_time_t_range (t))
575 {
576 *tp = tm;
577 return t;
578 }
579 else
580 {
581 __set_errno (EOVERFLOW);
582 return -1;
583 }
584 }
585
586 #endif
587
588 weak_alias (mktime, timelocal)
589 libc_hidden_def (mktime)
590 libc_hidden_weak (timelocal)