mktime.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /* Convert a 'struct tm' to a time_t value.
  2. Copyright (C) 1993-2015 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Paul Eggert <eggert@twinsun.com>.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public
  7. License as published by the Free Software Foundation; either
  8. version 3 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. /* Define this to have a standalone program to test this implementation of
  17. mktime. */
  18. /* #define DEBUG 1 */
  19. #ifndef _LIBC
  20. # include <config.h>
  21. #endif
  22. /* Assume that leap seconds are possible, unless told otherwise.
  23. If the host has a 'zic' command with a '-L leapsecondfilename' option,
  24. then it supports leap seconds; otherwise it probably doesn't. */
  25. #ifndef LEAP_SECONDS_POSSIBLE
  26. # define LEAP_SECONDS_POSSIBLE 1
  27. #endif
  28. #include <time.h>
  29. #include <limits.h>
  30. #include <string.h> /* For the real memcpy prototype. */
  31. #if defined DEBUG && DEBUG
  32. # include <stdio.h>
  33. # include <stdlib.h>
  34. /* Make it work even if the system's libc has its own mktime routine. */
  35. # undef mktime
  36. # define mktime my_mktime
  37. #endif /* DEBUG */
  38. /* Some of the code in this file assumes that signed integer overflow
  39. silently wraps around. This assumption can't easily be programmed
  40. around, nor can it be checked for portably at compile-time or
  41. easily eliminated at run-time.
  42. Define WRAPV to 1 if the assumption is valid and if
  43. #pragma GCC optimize ("wrapv")
  44. does not trigger GCC bug 51793
  45. <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51793>.
  46. Otherwise, define it to 0; this forces the use of slower code that,
  47. while not guaranteed by the C Standard, works on all production
  48. platforms that we know about. */
  49. #ifndef WRAPV
  50. # if (((__GNUC__ == 4 && 4 <= __GNUC_MINOR__) || 4 < __GNUC__) \
  51. && defined __GLIBC__)
  52. # pragma GCC optimize ("wrapv")
  53. # define WRAPV 1
  54. # else
  55. # define WRAPV 0
  56. # endif
  57. #endif
  58. /* Verify a requirement at compile-time (unlike assert, which is runtime). */
  59. #define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
  60. /* A signed type that is at least one bit wider than int. */
  61. #if INT_MAX <= LONG_MAX / 2
  62. typedef long int long_int;
  63. #else
  64. typedef long long int long_int;
  65. #endif
  66. verify (long_int_is_wide_enough, INT_MAX == INT_MAX * (long_int) 2 / 2);
  67. /* Shift A right by B bits portably, by dividing A by 2**B and
  68. truncating towards minus infinity. A and B should be free of side
  69. effects, and B should be in the range 0 <= B <= INT_BITS - 2, where
  70. INT_BITS is the number of useful bits in an int. GNU code can
  71. assume that INT_BITS is at least 32.
  72. ISO C99 says that A >> B is implementation-defined if A < 0. Some
  73. implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
  74. right in the usual way when A < 0, so SHR falls back on division if
  75. ordinary A >> B doesn't seem to be the usual signed shift. */
  76. #define SHR(a, b) \
  77. ((-1 >> 1 == -1 \
  78. && (long_int) -1 >> 1 == -1 \
  79. && ((time_t) -1 >> 1 == -1 || ! TYPE_SIGNED (time_t))) \
  80. ? (a) >> (b) \
  81. : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
  82. /* The extra casts in the following macros work around compiler bugs,
  83. e.g., in Cray C 5.0.3.0. */
  84. /* True if the arithmetic type T is an integer type. bool counts as
  85. an integer. */
  86. #define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
  87. /* True if negative values of the signed integer type T use two's
  88. complement, or if T is an unsigned integer type. */
  89. #define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
  90. /* True if the arithmetic type T is signed. */
  91. #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
  92. /* The maximum and minimum values for the integer type T. These
  93. macros have undefined behavior if T is signed and has padding bits.
  94. If this is a problem for you, please let us know how to fix it for
  95. your host. */
  96. #define TYPE_MINIMUM(t) \
  97. ((t) (! TYPE_SIGNED (t) \
  98. ? (t) 0 \
  99. : ~ TYPE_MAXIMUM (t)))
  100. #define TYPE_MAXIMUM(t) \
  101. ((t) (! TYPE_SIGNED (t) \
  102. ? (t) -1 \
  103. : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
  104. #ifndef TIME_T_MIN
  105. # define TIME_T_MIN TYPE_MINIMUM (time_t)
  106. #endif
  107. #ifndef TIME_T_MAX
  108. # define TIME_T_MAX TYPE_MAXIMUM (time_t)
  109. #endif
  110. #define TIME_T_MIDPOINT (SHR (TIME_T_MIN + TIME_T_MAX, 1) + 1)
  111. verify (time_t_is_integer, TYPE_IS_INTEGER (time_t));
  112. verify (twos_complement_arithmetic,
  113. (TYPE_TWOS_COMPLEMENT (int)
  114. && TYPE_TWOS_COMPLEMENT (long_int)
  115. && TYPE_TWOS_COMPLEMENT (time_t)));
  116. #define EPOCH_YEAR 1970
  117. #define TM_YEAR_BASE 1900
  118. verify (base_year_is_a_multiple_of_100, TM_YEAR_BASE % 100 == 0);
  119. /* Return 1 if YEAR + TM_YEAR_BASE is a leap year. */
  120. static int
  121. leapyear (long_int year)
  122. {
  123. /* Don't add YEAR to TM_YEAR_BASE, as that might overflow.
  124. Also, work even if YEAR is negative. */
  125. return
  126. ((year & 3) == 0
  127. && (year % 100 != 0
  128. || ((year / 100) & 3) == (- (TM_YEAR_BASE / 100) & 3)));
  129. }
  130. /* How many days come before each month (0-12). */
  131. #ifndef _LIBC
  132. static
  133. #endif
  134. const unsigned short int __mon_yday[2][13] =
  135. {
  136. /* Normal years. */
  137. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
  138. /* Leap years. */
  139. { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  140. };
  141. #ifndef _LIBC
  142. /* Portable standalone applications should supply a <time.h> that
  143. declares a POSIX-compliant localtime_r, for the benefit of older
  144. implementations that lack localtime_r or have a nonstandard one.
  145. See the gnulib time_r module for one way to implement this. */
  146. # undef __localtime_r
  147. # define __localtime_r localtime_r
  148. # define __mktime_internal mktime_internal
  149. # include "mktime-internal.h"
  150. #endif
  151. /* Return 1 if the values A and B differ according to the rules for
  152. tm_isdst: A and B differ if one is zero and the other positive. */
  153. static int
  154. isdst_differ (int a, int b)
  155. {
  156. return (!a != !b) && (0 <= a) && (0 <= b);
  157. }
  158. /* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
  159. (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds, assuming that the clocks
  160. were not adjusted between the time stamps.
  161. The YEAR values uses the same numbering as TP->tm_year. Values
  162. need not be in the usual range. However, YEAR1 must not be less
  163. than 2 * INT_MIN or greater than 2 * INT_MAX.
  164. The result may overflow. It is the caller's responsibility to
  165. detect overflow. */
  166. static time_t
  167. ydhms_diff (long_int year1, long_int yday1, int hour1, int min1, int sec1,
  168. int year0, int yday0, int hour0, int min0, int sec0)
  169. {
  170. verify (C99_integer_division, -1 / 2 == 0);
  171. /* Compute intervening leap days correctly even if year is negative.
  172. Take care to avoid integer overflow here. */
  173. int a4 = SHR (year1, 2) + SHR (TM_YEAR_BASE, 2) - ! (year1 & 3);
  174. int b4 = SHR (year0, 2) + SHR (TM_YEAR_BASE, 2) - ! (year0 & 3);
  175. int a100 = a4 / 25 - (a4 % 25 < 0);
  176. int b100 = b4 / 25 - (b4 % 25 < 0);
  177. int a400 = SHR (a100, 2);
  178. int b400 = SHR (b100, 2);
  179. int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
  180. /* Compute the desired time in time_t precision. Overflow might
  181. occur here. */
  182. time_t tyear1 = year1;
  183. time_t years = tyear1 - year0;
  184. time_t days = 365 * years + yday1 - yday0 + intervening_leap_days;
  185. time_t hours = 24 * days + hour1 - hour0;
  186. time_t minutes = 60 * hours + min1 - min0;
  187. time_t seconds = 60 * minutes + sec1 - sec0;
  188. return seconds;
  189. }
  190. /* Return the average of A and B, even if A + B would overflow. */
  191. static time_t
  192. time_t_avg (time_t a, time_t b)
  193. {
  194. return SHR (a, 1) + SHR (b, 1) + (a & b & 1);
  195. }
  196. /* Return 1 if A + B does not overflow. If time_t is unsigned and if
  197. B's top bit is set, assume that the sum represents A - -B, and
  198. return 1 if the subtraction does not wrap around. */
  199. static int
  200. time_t_add_ok (time_t a, time_t b)
  201. {
  202. if (! TYPE_SIGNED (time_t))
  203. {
  204. time_t sum = a + b;
  205. return (sum < a) == (TIME_T_MIDPOINT <= b);
  206. }
  207. else if (WRAPV)
  208. {
  209. time_t sum = a + b;
  210. return (sum < a) == (b < 0);
  211. }
  212. else
  213. {
  214. time_t avg = time_t_avg (a, b);
  215. return TIME_T_MIN / 2 <= avg && avg <= TIME_T_MAX / 2;
  216. }
  217. }
  218. /* Return 1 if A + B does not overflow. */
  219. static int
  220. time_t_int_add_ok (time_t a, int b)
  221. {
  222. verify (int_no_wider_than_time_t, INT_MAX <= TIME_T_MAX);
  223. if (WRAPV)
  224. {
  225. time_t sum = a + b;
  226. return (sum < a) == (b < 0);
  227. }
  228. else
  229. {
  230. int a_odd = a & 1;
  231. time_t avg = SHR (a, 1) + (SHR (b, 1) + (a_odd & b));
  232. return TIME_T_MIN / 2 <= avg && avg <= TIME_T_MAX / 2;
  233. }
  234. }
  235. /* Return a time_t value corresponding to (YEAR-YDAY HOUR:MIN:SEC),
  236. assuming that *T corresponds to *TP and that no clock adjustments
  237. occurred between *TP and the desired time.
  238. If TP is null, return a value not equal to *T; this avoids false matches.
  239. If overflow occurs, yield the minimal or maximal value, except do not
  240. yield a value equal to *T. */
  241. static time_t
  242. guess_time_tm (long_int year, long_int yday, int hour, int min, int sec,
  243. const time_t *t, const struct tm *tp)
  244. {
  245. if (tp)
  246. {
  247. time_t d = ydhms_diff (year, yday, hour, min, sec,
  248. tp->tm_year, tp->tm_yday,
  249. tp->tm_hour, tp->tm_min, tp->tm_sec);
  250. if (time_t_add_ok (*t, d))
  251. return *t + d;
  252. }
  253. /* Overflow occurred one way or another. Return the nearest result
  254. that is actually in range, except don't report a zero difference
  255. if the actual difference is nonzero, as that would cause a false
  256. match; and don't oscillate between two values, as that would
  257. confuse the spring-forward gap detector. */
  258. return (*t < TIME_T_MIDPOINT
  259. ? (*t <= TIME_T_MIN + 1 ? *t + 1 : TIME_T_MIN)
  260. : (TIME_T_MAX - 1 <= *t ? *t - 1 : TIME_T_MAX));
  261. }
  262. /* Use CONVERT to convert *T to a broken down time in *TP.
  263. If *T is out of range for conversion, adjust it so that
  264. it is the nearest in-range value and then convert that. */
  265. static struct tm *
  266. ranged_convert (struct tm *(*convert) (const time_t *, struct tm *),
  267. time_t *t, struct tm *tp)
  268. {
  269. struct tm *r = convert (t, tp);
  270. if (!r && *t)
  271. {
  272. time_t bad = *t;
  273. time_t ok = 0;
  274. /* BAD is a known unconvertible time_t, and OK is a known good one.
  275. Use binary search to narrow the range between BAD and OK until
  276. they differ by 1. */
  277. while (bad != ok + (bad < 0 ? -1 : 1))
  278. {
  279. time_t mid = *t = time_t_avg (ok, bad);
  280. r = convert (t, tp);
  281. if (r)
  282. ok = mid;
  283. else
  284. bad = mid;
  285. }
  286. if (!r && ok)
  287. {
  288. /* The last conversion attempt failed;
  289. revert to the most recent successful attempt. */
  290. *t = ok;
  291. r = convert (t, tp);
  292. }
  293. }
  294. return r;
  295. }
  296. /* Convert *TP to a time_t value, inverting
  297. the monotonic and mostly-unit-linear conversion function CONVERT.
  298. Use *OFFSET to keep track of a guess at the offset of the result,
  299. compared to what the result would be for UTC without leap seconds.
  300. If *OFFSET's guess is correct, only one CONVERT call is needed.
  301. This function is external because it is used also by timegm.c. */
  302. time_t
  303. __mktime_internal (struct tm *tp,
  304. struct tm *(*convert) (const time_t *, struct tm *),
  305. time_t *offset)
  306. {
  307. time_t t, gt, t0, t1, t2;
  308. struct tm tm;
  309. /* The maximum number of probes (calls to CONVERT) should be enough
  310. to handle any combinations of time zone rule changes, solar time,
  311. leap seconds, and oscillations around a spring-forward gap.
  312. POSIX.1 prohibits leap seconds, but some hosts have them anyway. */
  313. int remaining_probes = 6;
  314. /* Time requested. Copy it in case CONVERT modifies *TP; this can
  315. occur if TP is localtime's returned value and CONVERT is localtime. */
  316. int sec = tp->tm_sec;
  317. int min = tp->tm_min;
  318. int hour = tp->tm_hour;
  319. int mday = tp->tm_mday;
  320. int mon = tp->tm_mon;
  321. int year_requested = tp->tm_year;
  322. int isdst = tp->tm_isdst;
  323. /* 1 if the previous probe was DST. */
  324. int dst2;
  325. /* Ensure that mon is in range, and set year accordingly. */
  326. int mon_remainder = mon % 12;
  327. int negative_mon_remainder = mon_remainder < 0;
  328. int mon_years = mon / 12 - negative_mon_remainder;
  329. long_int lyear_requested = year_requested;
  330. long_int year = lyear_requested + mon_years;
  331. /* The other values need not be in range:
  332. the remaining code handles minor overflows correctly,
  333. assuming int and time_t arithmetic wraps around.
  334. Major overflows are caught at the end. */
  335. /* Calculate day of year from year, month, and day of month.
  336. The result need not be in range. */
  337. int mon_yday = ((__mon_yday[leapyear (year)]
  338. [mon_remainder + 12 * negative_mon_remainder])
  339. - 1);
  340. long_int lmday = mday;
  341. long_int yday = mon_yday + lmday;
  342. time_t guessed_offset = *offset;
  343. int sec_requested = sec;
  344. if (LEAP_SECONDS_POSSIBLE)
  345. {
  346. /* Handle out-of-range seconds specially,
  347. since ydhms_tm_diff assumes every minute has 60 seconds. */
  348. if (sec < 0)
  349. sec = 0;
  350. if (59 < sec)
  351. sec = 59;
  352. }
  353. /* Invert CONVERT by probing. First assume the same offset as last
  354. time. */
  355. t0 = ydhms_diff (year, yday, hour, min, sec,
  356. EPOCH_YEAR - TM_YEAR_BASE, 0, 0, 0, - guessed_offset);
  357. if (TIME_T_MAX / INT_MAX / 366 / 24 / 60 / 60 < 3)
  358. {
  359. /* time_t isn't large enough to rule out overflows, so check
  360. for major overflows. A gross check suffices, since if t0
  361. has overflowed, it is off by a multiple of TIME_T_MAX -
  362. TIME_T_MIN + 1. So ignore any component of the difference
  363. that is bounded by a small value. */
  364. /* Approximate log base 2 of the number of time units per
  365. biennium. A biennium is 2 years; use this unit instead of
  366. years to avoid integer overflow. For example, 2 average
  367. Gregorian years are 2 * 365.2425 * 24 * 60 * 60 seconds,
  368. which is 63113904 seconds, and rint (log2 (63113904)) is
  369. 26. */
  370. int ALOG2_SECONDS_PER_BIENNIUM = 26;
  371. int ALOG2_MINUTES_PER_BIENNIUM = 20;
  372. int ALOG2_HOURS_PER_BIENNIUM = 14;
  373. int ALOG2_DAYS_PER_BIENNIUM = 10;
  374. int LOG2_YEARS_PER_BIENNIUM = 1;
  375. int approx_requested_biennia =
  376. (SHR (year_requested, LOG2_YEARS_PER_BIENNIUM)
  377. - SHR (EPOCH_YEAR - TM_YEAR_BASE, LOG2_YEARS_PER_BIENNIUM)
  378. + SHR (mday, ALOG2_DAYS_PER_BIENNIUM)
  379. + SHR (hour, ALOG2_HOURS_PER_BIENNIUM)
  380. + SHR (min, ALOG2_MINUTES_PER_BIENNIUM)
  381. + (LEAP_SECONDS_POSSIBLE
  382. ? 0
  383. : SHR (sec, ALOG2_SECONDS_PER_BIENNIUM)));
  384. int approx_biennia = SHR (t0, ALOG2_SECONDS_PER_BIENNIUM);
  385. int diff = approx_biennia - approx_requested_biennia;
  386. int approx_abs_diff = diff < 0 ? -1 - diff : diff;
  387. /* IRIX 4.0.5 cc miscalculates TIME_T_MIN / 3: it erroneously
  388. gives a positive value of 715827882. Setting a variable
  389. first then doing math on it seems to work.
  390. (ghazi@caip.rutgers.edu) */
  391. time_t time_t_max = TIME_T_MAX;
  392. time_t time_t_min = TIME_T_MIN;
  393. time_t overflow_threshold =
  394. (time_t_max / 3 - time_t_min / 3) >> ALOG2_SECONDS_PER_BIENNIUM;
  395. if (overflow_threshold < approx_abs_diff)
  396. {
  397. /* Overflow occurred. Try repairing it; this might work if
  398. the time zone offset is enough to undo the overflow. */
  399. time_t repaired_t0 = -1 - t0;
  400. approx_biennia = SHR (repaired_t0, ALOG2_SECONDS_PER_BIENNIUM);
  401. diff = approx_biennia - approx_requested_biennia;
  402. approx_abs_diff = diff < 0 ? -1 - diff : diff;
  403. if (overflow_threshold < approx_abs_diff)
  404. return -1;
  405. guessed_offset += repaired_t0 - t0;
  406. t0 = repaired_t0;
  407. }
  408. }
  409. /* Repeatedly use the error to improve the guess. */
  410. for (t = t1 = t2 = t0, dst2 = 0;
  411. (gt = guess_time_tm (year, yday, hour, min, sec, &t,
  412. ranged_convert (convert, &t, &tm)),
  413. t != gt);
  414. t1 = t2, t2 = t, t = gt, dst2 = tm.tm_isdst != 0)
  415. if (t == t1 && t != t2
  416. && (tm.tm_isdst < 0
  417. || (isdst < 0
  418. ? dst2 <= (tm.tm_isdst != 0)
  419. : (isdst != 0) != (tm.tm_isdst != 0))))
  420. /* We can't possibly find a match, as we are oscillating
  421. between two values. The requested time probably falls
  422. within a spring-forward gap of size GT - T. Follow the common
  423. practice in this case, which is to return a time that is GT - T
  424. away from the requested time, preferring a time whose
  425. tm_isdst differs from the requested value. (If no tm_isdst
  426. was requested and only one of the two values has a nonzero
  427. tm_isdst, prefer that value.) In practice, this is more
  428. useful than returning -1. */
  429. goto offset_found;
  430. else if (--remaining_probes == 0)
  431. return -1;
  432. /* We have a match. Check whether tm.tm_isdst has the requested
  433. value, if any. */
  434. if (isdst_differ (isdst, tm.tm_isdst))
  435. {
  436. /* tm.tm_isdst has the wrong value. Look for a neighboring
  437. time with the right value, and use its UTC offset.
  438. Heuristic: probe the adjacent timestamps in both directions,
  439. looking for the desired isdst. This should work for all real
  440. time zone histories in the tz database. */
  441. /* Distance between probes when looking for a DST boundary. In
  442. tzdata2003a, the shortest period of DST is 601200 seconds
  443. (e.g., America/Recife starting 2000-10-08 01:00), and the
  444. shortest period of non-DST surrounded by DST is 694800
  445. seconds (Africa/Tunis starting 1943-04-17 01:00). Use the
  446. minimum of these two values, so we don't miss these short
  447. periods when probing. */
  448. int stride = 601200;
  449. /* The longest period of DST in tzdata2003a is 536454000 seconds
  450. (e.g., America/Jujuy starting 1946-10-01 01:00). The longest
  451. period of non-DST is much longer, but it makes no real sense
  452. to search for more than a year of non-DST, so use the DST
  453. max. */
  454. int duration_max = 536454000;
  455. /* Search in both directions, so the maximum distance is half
  456. the duration; add the stride to avoid off-by-1 problems. */
  457. int delta_bound = duration_max / 2 + stride;
  458. int delta, direction;
  459. for (delta = stride; delta < delta_bound; delta += stride)
  460. for (direction = -1; direction <= 1; direction += 2)
  461. if (time_t_int_add_ok (t, delta * direction))
  462. {
  463. time_t ot = t + delta * direction;
  464. struct tm otm;
  465. ranged_convert (convert, &ot, &otm);
  466. if (! isdst_differ (isdst, otm.tm_isdst))
  467. {
  468. /* We found the desired tm_isdst.
  469. Extrapolate back to the desired time. */
  470. t = guess_time_tm (year, yday, hour, min, sec, &ot, &otm);
  471. ranged_convert (convert, &t, &tm);
  472. goto offset_found;
  473. }
  474. }
  475. }
  476. offset_found:
  477. *offset = guessed_offset + t - t0;
  478. if (LEAP_SECONDS_POSSIBLE && sec_requested != tm.tm_sec)
  479. {
  480. /* Adjust time to reflect the tm_sec requested, not the normalized value.
  481. Also, repair any damage from a false match due to a leap second. */
  482. int sec_adjustment = (sec == 0 && tm.tm_sec == 60) - sec;
  483. if (! time_t_int_add_ok (t, sec_requested))
  484. return -1;
  485. t1 = t + sec_requested;
  486. if (! time_t_int_add_ok (t1, sec_adjustment))
  487. return -1;
  488. t2 = t1 + sec_adjustment;
  489. if (! convert (&t2, &tm))
  490. return -1;
  491. t = t2;
  492. }
  493. *tp = tm;
  494. return t;
  495. }
  496. /* FIXME: This should use a signed type wide enough to hold any UTC
  497. offset in seconds. 'int' should be good enough for GNU code. We
  498. can't fix this unilaterally though, as other modules invoke
  499. __mktime_internal. */
  500. static time_t localtime_offset;
  501. /* Convert *TP to a time_t value. */
  502. time_t
  503. mktime (struct tm *tp)
  504. {
  505. #ifdef _LIBC
  506. /* POSIX.1 8.1.1 requires that whenever mktime() is called, the
  507. time zone names contained in the external variable 'tzname' shall
  508. be set as if the tzset() function had been called. */
  509. __tzset ();
  510. #endif
  511. return __mktime_internal (tp, __localtime_r, &localtime_offset);
  512. }
  513. #ifdef weak_alias
  514. weak_alias (mktime, timelocal)
  515. #endif
  516. #ifdef _LIBC
  517. libc_hidden_def (mktime)
  518. libc_hidden_weak (timelocal)
  519. #endif
  520. #if defined DEBUG && DEBUG
  521. static int
  522. not_equal_tm (const struct tm *a, const struct tm *b)
  523. {
  524. return ((a->tm_sec ^ b->tm_sec)
  525. | (a->tm_min ^ b->tm_min)
  526. | (a->tm_hour ^ b->tm_hour)
  527. | (a->tm_mday ^ b->tm_mday)
  528. | (a->tm_mon ^ b->tm_mon)
  529. | (a->tm_year ^ b->tm_year)
  530. | (a->tm_yday ^ b->tm_yday)
  531. | isdst_differ (a->tm_isdst, b->tm_isdst));
  532. }
  533. static void
  534. print_tm (const struct tm *tp)
  535. {
  536. if (tp)
  537. printf ("%04d-%02d-%02d %02d:%02d:%02d yday %03d wday %d isdst %d",
  538. tp->tm_year + TM_YEAR_BASE, tp->tm_mon + 1, tp->tm_mday,
  539. tp->tm_hour, tp->tm_min, tp->tm_sec,
  540. tp->tm_yday, tp->tm_wday, tp->tm_isdst);
  541. else
  542. printf ("0");
  543. }
  544. static int
  545. check_result (time_t tk, struct tm tmk, time_t tl, const struct tm *lt)
  546. {
  547. if (tk != tl || !lt || not_equal_tm (&tmk, lt))
  548. {
  549. printf ("mktime (");
  550. print_tm (lt);
  551. printf (")\nyields (");
  552. print_tm (&tmk);
  553. printf (") == %ld, should be %ld\n", (long int) tk, (long int) tl);
  554. return 1;
  555. }
  556. return 0;
  557. }
  558. int
  559. main (int argc, char **argv)
  560. {
  561. int status = 0;
  562. struct tm tm, tmk, tml;
  563. struct tm *lt;
  564. time_t tk, tl, tl1;
  565. char trailer;
  566. if ((argc == 3 || argc == 4)
  567. && (sscanf (argv[1], "%d-%d-%d%c",
  568. &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &trailer)
  569. == 3)
  570. && (sscanf (argv[2], "%d:%d:%d%c",
  571. &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &trailer)
  572. == 3))
  573. {
  574. tm.tm_year -= TM_YEAR_BASE;
  575. tm.tm_mon--;
  576. tm.tm_isdst = argc == 3 ? -1 : atoi (argv[3]);
  577. tmk = tm;
  578. tl = mktime (&tmk);
  579. lt = localtime (&tl);
  580. if (lt)
  581. {
  582. tml = *lt;
  583. lt = &tml;
  584. }
  585. printf ("mktime returns %ld == ", (long int) tl);
  586. print_tm (&tmk);
  587. printf ("\n");
  588. status = check_result (tl, tmk, tl, lt);
  589. }
  590. else if (argc == 4 || (argc == 5 && strcmp (argv[4], "-") == 0))
  591. {
  592. time_t from = atol (argv[1]);
  593. time_t by = atol (argv[2]);
  594. time_t to = atol (argv[3]);
  595. if (argc == 4)
  596. for (tl = from; by < 0 ? to <= tl : tl <= to; tl = tl1)
  597. {
  598. lt = localtime (&tl);
  599. if (lt)
  600. {
  601. tmk = tml = *lt;
  602. tk = mktime (&tmk);
  603. status |= check_result (tk, tmk, tl, &tml);
  604. }
  605. else
  606. {
  607. printf ("localtime (%ld) yields 0\n", (long int) tl);
  608. status = 1;
  609. }
  610. tl1 = tl + by;
  611. if ((tl1 < tl) != (by < 0))
  612. break;
  613. }
  614. else
  615. for (tl = from; by < 0 ? to <= tl : tl <= to; tl = tl1)
  616. {
  617. /* Null benchmark. */
  618. lt = localtime (&tl);
  619. if (lt)
  620. {
  621. tmk = tml = *lt;
  622. tk = tl;
  623. status |= check_result (tk, tmk, tl, &tml);
  624. }
  625. else
  626. {
  627. printf ("localtime (%ld) yields 0\n", (long int) tl);
  628. status = 1;
  629. }
  630. tl1 = tl + by;
  631. if ((tl1 < tl) != (by < 0))
  632. break;
  633. }
  634. }
  635. else
  636. printf ("Usage:\
  637. \t%s YYYY-MM-DD HH:MM:SS [ISDST] # Test given time.\n\
  638. \t%s FROM BY TO # Test values FROM, FROM+BY, ..., TO.\n\
  639. \t%s FROM BY TO - # Do not test those values (for benchmark).\n",
  640. argv[0], argv[0], argv[0]);
  641. return status;
  642. }
  643. #endif /* DEBUG */
  644. /*
  645. Local Variables:
  646. compile-command: "gcc -DDEBUG -I. -Wall -W -O2 -g mktime.c -o mktime"
  647. End:
  648. */