mktime.c 24 KB

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