mktime.c 23 KB

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