mktime.c 21 KB

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