stime.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. /* Copyright 1995-2001,2003-2009,2011,2013-2014,2016-2019
  2. Free Software Foundation, Inc.
  3. This file is part of Guile.
  4. Guile is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Lesser General Public License as published
  6. by the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. Guile is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  11. License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with Guile. If not, see
  14. <https://www.gnu.org/licenses/>. */
  15. /* _POSIX_C_SOURCE is not defined always, because it causes problems on some
  16. systems, notably
  17. - FreeBSD loses all BSD and XOPEN defines.
  18. - glibc loses some things like CLK_TCK.
  19. - On MINGW it conflicts with the pthread headers.
  20. But on HP-UX _POSIX_C_SOURCE is needed, as noted, for gmtime_r.
  21. Perhaps a configure test could figure out what _POSIX_C_SOURCE gives and
  22. what it takes away, and decide from that whether to use it, instead of
  23. hard coding __hpux. */
  24. #ifndef _REENTRANT
  25. # define _REENTRANT /* ask solaris for gmtime_r prototype */
  26. #endif
  27. #ifdef __hpux
  28. #define _POSIX_C_SOURCE 199506L /* for gmtime_r prototype */
  29. #endif
  30. #ifdef HAVE_CONFIG_H
  31. # include <config.h>
  32. #endif
  33. #include <errno.h>
  34. #include <stdio.h>
  35. #include <strftime.h>
  36. #include <string.h>
  37. #include <sys/times.h>
  38. #include <sys/types.h>
  39. #include <time.h> /* Gnulib-provided */
  40. #include <unistd.h>
  41. #include <unistr.h>
  42. #ifdef HAVE_SYS_TIMEB_H
  43. # include <sys/timeb.h>
  44. #endif
  45. #include "async.h"
  46. #include "boolean.h"
  47. #include "dynwind.h"
  48. #include "feature.h"
  49. #include "gsubr.h"
  50. #include "modules.h"
  51. #include "numbers.h"
  52. #include "pairs.h"
  53. #include "strings.h"
  54. #include "strings.h"
  55. #include "vectors.h"
  56. #include "stime.h"
  57. #if ! HAVE_DECL_STRPTIME
  58. extern char *strptime ();
  59. #endif
  60. #ifdef __STDC__
  61. # define timet time_t
  62. #else
  63. # define timet long
  64. #endif
  65. #if SCM_SIZEOF_LONG >= 8 && defined HAVE_CLOCK_GETTIME
  66. /* Nanoseconds on 64-bit systems with POSIX timers. */
  67. #define TIME_UNITS_PER_SECOND 1000000000
  68. #else
  69. /* Milliseconds for everyone else. */
  70. #define TIME_UNITS_PER_SECOND 1000
  71. #endif
  72. long scm_c_time_units_per_second = TIME_UNITS_PER_SECOND;
  73. static long
  74. time_from_seconds_and_nanoseconds (long s, long ns)
  75. {
  76. return s * TIME_UNITS_PER_SECOND
  77. + ns / (1000000000 / TIME_UNITS_PER_SECOND);
  78. }
  79. /* A runtime-selectable mechanism to choose a timing mechanism. Really
  80. we want to use POSIX timers, but that's not always possible. Notably,
  81. the user may have everything she needs at compile-time, but if she's
  82. running on an SMP machine without a common clock source, she can't
  83. use POSIX CPUTIME clocks. */
  84. static long (*get_internal_real_time) (void);
  85. static long (*get_internal_run_time) (void);
  86. #ifdef HAVE_CLOCK_GETTIME
  87. struct timespec posix_real_time_base;
  88. static long
  89. get_internal_real_time_posix_timer (void)
  90. {
  91. struct timespec ts;
  92. clock_gettime (CLOCK_REALTIME, &ts);
  93. return time_from_seconds_and_nanoseconds
  94. (ts.tv_sec - posix_real_time_base.tv_sec,
  95. ts.tv_nsec - posix_real_time_base.tv_nsec);
  96. }
  97. #if defined _POSIX_CPUTIME && defined CLOCK_PROCESS_CPUTIME_ID
  98. /* You see, FreeBSD defines _POSIX_CPUTIME but not
  99. CLOCK_PROCESS_CPUTIME_ID. */
  100. #define HAVE_POSIX_CPUTIME 1
  101. struct timespec posix_run_time_base;
  102. static long
  103. get_internal_run_time_posix_timer (void)
  104. {
  105. struct timespec ts;
  106. clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &ts);
  107. return time_from_seconds_and_nanoseconds
  108. (ts.tv_sec - posix_run_time_base.tv_sec,
  109. ts.tv_nsec - posix_run_time_base.tv_nsec);
  110. }
  111. #endif /* _POSIX_CPUTIME */
  112. #endif /* HAVE_CLOCKTIME */
  113. #ifdef HAVE_GETTIMEOFDAY
  114. struct timeval gettimeofday_real_time_base;
  115. static long
  116. get_internal_real_time_gettimeofday (void)
  117. {
  118. struct timeval tv;
  119. gettimeofday (&tv, NULL);
  120. return time_from_seconds_and_nanoseconds
  121. (tv.tv_sec - gettimeofday_real_time_base.tv_sec,
  122. (tv.tv_usec - gettimeofday_real_time_base.tv_usec) * 1000);
  123. }
  124. #endif
  125. static long ticks_per_second;
  126. static long
  127. get_internal_run_time_times (void)
  128. {
  129. struct tms time_buffer;
  130. times(&time_buffer);
  131. return (time_buffer.tms_utime + time_buffer.tms_stime)
  132. * TIME_UNITS_PER_SECOND / ticks_per_second;
  133. }
  134. static timet fallback_real_time_base;
  135. static long
  136. get_internal_real_time_fallback (void)
  137. {
  138. return time_from_seconds_and_nanoseconds
  139. ((long) time (NULL) - fallback_real_time_base, 0);
  140. }
  141. SCM_DEFINE (scm_get_internal_real_time, "get-internal-real-time", 0, 0, 0,
  142. (),
  143. "Return the number of time units since the interpreter was\n"
  144. "started.")
  145. #define FUNC_NAME s_scm_get_internal_real_time
  146. {
  147. return scm_from_long (get_internal_real_time ());
  148. }
  149. #undef FUNC_NAME
  150. SCM_DEFINE (scm_times, "times", 0, 0, 0,
  151. (void),
  152. "Return an object with information about real and processor\n"
  153. "time. The following procedures accept such an object as an\n"
  154. "argument and return a selected component:\n"
  155. "\n"
  156. "@table @code\n"
  157. "@item tms:clock\n"
  158. "The current real time, expressed as time units relative to an\n"
  159. "arbitrary base.\n"
  160. "@item tms:utime\n"
  161. "The CPU time units used by the calling process.\n"
  162. "@item tms:stime\n"
  163. "The CPU time units used by the system on behalf of the calling\n"
  164. "process.\n"
  165. "@item tms:cutime\n"
  166. "The CPU time units used by terminated child processes of the\n"
  167. "calling process, whose status has been collected (e.g., using\n"
  168. "@code{waitpid}).\n"
  169. "@item tms:cstime\n"
  170. "Similarly, the CPU times units used by the system on behalf of\n"
  171. "terminated child processes.\n"
  172. "@end table")
  173. #define FUNC_NAME s_scm_times
  174. {
  175. struct tms t;
  176. clock_t rv;
  177. SCM factor;
  178. SCM result = scm_c_make_vector (5, SCM_UNDEFINED);
  179. rv = times (&t);
  180. if (rv == -1)
  181. SCM_SYSERROR;
  182. factor = scm_quotient (scm_from_long (TIME_UNITS_PER_SECOND),
  183. scm_from_long (ticks_per_second));
  184. SCM_SIMPLE_VECTOR_SET (result, 0,
  185. scm_product (scm_from_long (rv), factor));
  186. SCM_SIMPLE_VECTOR_SET (result, 1,
  187. scm_product (scm_from_long (t.tms_utime), factor));
  188. SCM_SIMPLE_VECTOR_SET (result, 2,
  189. scm_product (scm_from_long (t.tms_stime), factor));
  190. SCM_SIMPLE_VECTOR_SET (result ,3,
  191. scm_product (scm_from_long (t.tms_cutime), factor));
  192. SCM_SIMPLE_VECTOR_SET (result, 4,
  193. scm_product (scm_from_long (t.tms_cstime), factor));
  194. return result;
  195. }
  196. #undef FUNC_NAME
  197. long
  198. scm_c_get_internal_run_time (void)
  199. {
  200. return get_internal_run_time ();
  201. }
  202. SCM_DEFINE (scm_get_internal_run_time, "get-internal-run-time", 0, 0, 0,
  203. (void),
  204. "Return the number of time units of processor time used by the\n"
  205. "interpreter. Both @emph{system} and @emph{user} time are\n"
  206. "included but subprocesses are not.")
  207. #define FUNC_NAME s_scm_get_internal_run_time
  208. {
  209. return scm_from_long (scm_c_get_internal_run_time ());
  210. }
  211. #undef FUNC_NAME
  212. /* For reference, note that current-time and gettimeofday both should be
  213. protected against setzone/restorezone changes in another thread, since on
  214. DOS the system time is normally kept as local time, which means TZ
  215. affects the return from current-time and gettimeofday. Not sure if DJGPP
  216. etc actually has concurrent multi-threading, but it seems prudent not to
  217. make assumptions about this. */
  218. SCM_DEFINE (scm_current_time, "current-time", 0, 0, 0,
  219. (void),
  220. "Return the number of seconds since 1970-01-01 00:00:00 UTC,\n"
  221. "excluding leap seconds.")
  222. #define FUNC_NAME s_scm_current_time
  223. {
  224. timet timv;
  225. timv = time (NULL);
  226. if (timv == -1)
  227. SCM_MISC_ERROR ("current time not available", SCM_EOL);
  228. return scm_from_long (timv);
  229. }
  230. #undef FUNC_NAME
  231. SCM_DEFINE (scm_gettimeofday, "gettimeofday", 0, 0, 0,
  232. (void),
  233. "Return a pair containing the number of seconds and microseconds\n"
  234. "since 1970-01-01 00:00:00 UTC, excluding leap seconds. Note:\n"
  235. "whether true microsecond resolution is available depends on the\n"
  236. "operating system.")
  237. #define FUNC_NAME s_scm_gettimeofday
  238. {
  239. #ifdef HAVE_GETTIMEOFDAY
  240. struct timeval time;
  241. if (gettimeofday (&time, NULL))
  242. SCM_SYSERROR;
  243. return scm_cons (scm_from_long (time.tv_sec),
  244. scm_from_long (time.tv_usec));
  245. #else
  246. timet t = time (NULL);
  247. if (errno)
  248. SCM_SYSERROR;
  249. else
  250. return scm_cons (scm_from_long ((long)t), SCM_INUM0);
  251. #endif
  252. }
  253. #undef FUNC_NAME
  254. static SCM
  255. filltime (struct tm *bd_time, int zoff, const char *zname)
  256. {
  257. SCM result = scm_c_make_vector (11, SCM_UNDEFINED);
  258. SCM_SIMPLE_VECTOR_SET (result,0, scm_from_int (bd_time->tm_sec));
  259. SCM_SIMPLE_VECTOR_SET (result,1, scm_from_int (bd_time->tm_min));
  260. SCM_SIMPLE_VECTOR_SET (result,2, scm_from_int (bd_time->tm_hour));
  261. SCM_SIMPLE_VECTOR_SET (result,3, scm_from_int (bd_time->tm_mday));
  262. SCM_SIMPLE_VECTOR_SET (result,4, scm_from_int (bd_time->tm_mon));
  263. SCM_SIMPLE_VECTOR_SET (result,5, scm_from_int (bd_time->tm_year));
  264. SCM_SIMPLE_VECTOR_SET (result,6, scm_from_int (bd_time->tm_wday));
  265. SCM_SIMPLE_VECTOR_SET (result,7, scm_from_int (bd_time->tm_yday));
  266. SCM_SIMPLE_VECTOR_SET (result,8, scm_from_int (bd_time->tm_isdst));
  267. SCM_SIMPLE_VECTOR_SET (result,9, scm_from_int (zoff));
  268. SCM_SIMPLE_VECTOR_SET (result,10, (zname
  269. ? scm_from_locale_string (zname)
  270. : SCM_BOOL_F));
  271. return result;
  272. }
  273. static const char tzvar[3] = "TZ";
  274. static scm_i_pthread_mutex_t tz_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  275. /* if zone is set, create a temporary environment with only a TZ
  276. string. other threads or interrupt handlers shouldn't be allowed
  277. to run until the corresponding restorezone is called. hence the use
  278. of a static variable for tmpenv is no big deal. */
  279. static char **
  280. setzone (SCM zone, int pos, const char *subr)
  281. {
  282. char **oldenv = 0;
  283. if (!SCM_UNBNDP (zone))
  284. {
  285. static char *tmpenv[2];
  286. char dummy_buf[1];
  287. char *buf;
  288. size_t zone_len;
  289. zone_len = scm_to_locale_stringbuf (zone, dummy_buf, 0);
  290. buf = scm_malloc (zone_len + sizeof (tzvar) + 1);
  291. strcpy (buf, tzvar);
  292. buf[sizeof(tzvar)-1] = '=';
  293. scm_to_locale_stringbuf (zone, buf+sizeof(tzvar), zone_len);
  294. buf[sizeof(tzvar)+zone_len] = '\0';
  295. oldenv = environ;
  296. tmpenv[0] = buf;
  297. tmpenv[1] = 0;
  298. environ = tmpenv;
  299. }
  300. return oldenv;
  301. }
  302. static void
  303. restorezone (SCM zone, char **oldenv, const char *subr SCM_UNUSED)
  304. {
  305. if (!SCM_UNBNDP (zone))
  306. {
  307. free (environ[0]);
  308. environ = oldenv;
  309. #ifdef HAVE_TZSET
  310. /* for the possible benefit of user code linked with libguile. */
  311. tzset();
  312. #endif
  313. }
  314. }
  315. SCM_DEFINE (scm_localtime, "localtime", 1, 1, 0,
  316. (SCM time, SCM zone),
  317. "Return an object representing the broken down components of\n"
  318. "@var{time}, an integer like the one returned by\n"
  319. "@code{current-time}. The time zone for the calculation is\n"
  320. "optionally specified by @var{zone} (a string), otherwise the\n"
  321. "@code{TZ} environment variable or the system default is used.")
  322. #define FUNC_NAME s_scm_localtime
  323. {
  324. timet itime;
  325. struct tm *ltptr, lt, *utc;
  326. SCM result;
  327. int zoff;
  328. char *zname = 0;
  329. char **oldenv;
  330. int err;
  331. itime = SCM_NUM2LONG (1, time);
  332. /* Mutual exclusion is essential since a) setzone may install a
  333. temporary environment b) localtime uses a static buffer. */
  334. scm_dynwind_begin (0);
  335. scm_i_dynwind_pthread_mutex_lock (&tz_lock);
  336. oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
  337. #ifdef LOCALTIME_CACHE
  338. tzset ();
  339. #endif
  340. /* POSIX says localtime sets errno, but C99 doesn't say that.
  341. Give a sensible default value in case localtime doesn't set it. */
  342. errno = EINVAL;
  343. ltptr = localtime (&itime);
  344. err = errno;
  345. if (ltptr)
  346. {
  347. const char *ptr;
  348. /* copy zone name before calling gmtime or restoring zone. */
  349. #if defined (HAVE_STRUCT_TM_TM_ZONE)
  350. ptr = ltptr->tm_zone;
  351. #elif defined (HAVE_TZNAME)
  352. ptr = tzname[ (ltptr->tm_isdst == 1) ? 1 : 0 ];
  353. #else
  354. ptr = "";
  355. #endif
  356. zname = scm_malloc (strlen (ptr) + 1);
  357. strcpy (zname, ptr);
  358. }
  359. /* the struct is copied in case localtime and gmtime share a buffer. */
  360. if (ltptr)
  361. lt = *ltptr;
  362. /* POSIX says gmtime sets errno, but C99 doesn't say that.
  363. Give a sensible default value in case gmtime doesn't set it. */
  364. errno = EINVAL;
  365. utc = gmtime (&itime);
  366. if (utc == NULL)
  367. err = errno;
  368. restorezone (zone, oldenv, FUNC_NAME);
  369. /* delayed until zone has been restored. */
  370. errno = err;
  371. if (utc == NULL || ltptr == NULL)
  372. SCM_SYSERROR;
  373. /* calculate timezone offset in seconds west of UTC. */
  374. zoff = (utc->tm_hour - lt.tm_hour) * 3600 + (utc->tm_min - lt.tm_min) * 60
  375. + utc->tm_sec - lt.tm_sec;
  376. if (utc->tm_year < lt.tm_year)
  377. zoff -= 24 * 60 * 60;
  378. else if (utc->tm_year > lt.tm_year)
  379. zoff += 24 * 60 * 60;
  380. else if (utc->tm_yday < lt.tm_yday)
  381. zoff -= 24 * 60 * 60;
  382. else if (utc->tm_yday > lt.tm_yday)
  383. zoff += 24 * 60 * 60;
  384. result = filltime (&lt, zoff, zname);
  385. free (zname);
  386. scm_dynwind_end ();
  387. return result;
  388. }
  389. #undef FUNC_NAME
  390. /* tm_zone is normally a pointer, not an array within struct tm, so we might
  391. have to worry about the lifespan of what it points to. The posix specs
  392. don't seem to say anything about this, let's assume here that tm_zone
  393. will be a constant and therefore no protection or anything is needed
  394. until we copy it in filltime(). */
  395. SCM_DEFINE (scm_gmtime, "gmtime", 1, 0, 0,
  396. (SCM time),
  397. "Return an object representing the broken down components of\n"
  398. "@var{time}, an integer like the one returned by\n"
  399. "@code{current-time}. The values are calculated for UTC.")
  400. #define FUNC_NAME s_scm_gmtime
  401. {
  402. timet itime;
  403. struct tm bd_buf, *bd_time;
  404. const char *zname;
  405. itime = SCM_NUM2LONG (1, time);
  406. /* POSIX says gmtime sets errno, but C99 doesn't say that.
  407. Give a sensible default value in case gmtime doesn't set it. */
  408. errno = EINVAL;
  409. #if HAVE_GMTIME_R
  410. bd_time = gmtime_r (&itime, &bd_buf);
  411. #else
  412. scm_i_pthread_mutex_lock (&tz_lock);
  413. bd_time = gmtime (&itime);
  414. if (bd_time != NULL)
  415. bd_buf = *bd_time;
  416. scm_i_pthread_mutex_unlock (&tz_lock);
  417. #endif
  418. if (bd_time == NULL)
  419. SCM_SYSERROR;
  420. #if HAVE_STRUCT_TM_TM_ZONE
  421. zname = bd_buf.tm_zone;
  422. #else
  423. zname = "GMT";
  424. #endif
  425. return filltime (&bd_buf, 0, zname);
  426. }
  427. #undef FUNC_NAME
  428. /* copy time components from a Scheme object to a struct tm. */
  429. static void
  430. bdtime2c (SCM sbd_time, struct tm *lt, int pos, const char *subr)
  431. {
  432. SCM_ASSERT (scm_is_vector (sbd_time)
  433. && SCM_SIMPLE_VECTOR_LENGTH (sbd_time) == 11,
  434. sbd_time, pos, subr);
  435. lt->tm_sec = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 0));
  436. lt->tm_min = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 1));
  437. lt->tm_hour = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 2));
  438. lt->tm_mday = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 3));
  439. lt->tm_mon = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 4));
  440. lt->tm_year = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 5));
  441. lt->tm_wday = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 6));
  442. lt->tm_yday = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 7));
  443. lt->tm_isdst = scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 8));
  444. #if HAVE_STRUCT_TM_TM_GMTOFF
  445. lt->tm_gmtoff = - scm_to_int (SCM_SIMPLE_VECTOR_REF (sbd_time, 9));
  446. #endif
  447. #ifdef HAVE_STRUCT_TM_TM_ZONE
  448. if (scm_is_false (SCM_SIMPLE_VECTOR_REF (sbd_time, 10)))
  449. lt->tm_zone = NULL;
  450. else
  451. lt->tm_zone = scm_to_locale_string (SCM_SIMPLE_VECTOR_REF (sbd_time, 10));
  452. #endif
  453. }
  454. SCM_DEFINE (scm_mktime, "mktime", 1, 1, 0,
  455. (SCM sbd_time, SCM zone),
  456. "@var{sbd_time} is an object representing broken down time and\n"
  457. "@code{zone} is an optional time zone specifier (otherwise the\n"
  458. "TZ environment variable or the system default is used).\n"
  459. "\n"
  460. "Returns a pair: the car is a corresponding integer time value\n"
  461. "like that returned by @code{current-time}; the cdr is a broken\n"
  462. "down time object, similar to as @var{sbd_time} but with\n"
  463. "normalized values.")
  464. #define FUNC_NAME s_scm_mktime
  465. {
  466. timet itime;
  467. struct tm lt, *utc;
  468. SCM result;
  469. int zoff;
  470. char *zname = 0;
  471. char **oldenv;
  472. int err;
  473. scm_dynwind_begin (0);
  474. bdtime2c (sbd_time, &lt, SCM_ARG1, FUNC_NAME);
  475. #if HAVE_STRUCT_TM_TM_ZONE
  476. scm_dynwind_free ((char *)lt.tm_zone);
  477. #endif
  478. scm_i_dynwind_pthread_mutex_lock (&tz_lock);
  479. oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
  480. #ifdef LOCALTIME_CACHE
  481. tzset ();
  482. #endif
  483. itime = mktime (&lt);
  484. /* POSIX doesn't say mktime sets errno, and on glibc 2.3.2 for instance it
  485. doesn't. Force a sensible value for our error message. */
  486. err = EINVAL;
  487. if (itime != -1)
  488. {
  489. const char *ptr;
  490. /* copy zone name before calling gmtime or restoring the zone. */
  491. #if defined (HAVE_STRUCT_TM_TM_ZONE)
  492. ptr = lt.tm_zone;
  493. #elif defined (HAVE_TZNAME)
  494. ptr = tzname[ (lt.tm_isdst == 1) ? 1 : 0 ];
  495. #else
  496. ptr = "";
  497. #endif
  498. zname = scm_malloc (strlen (ptr) + 1);
  499. strcpy (zname, ptr);
  500. }
  501. /* get timezone offset in seconds west of UTC. */
  502. /* POSIX says gmtime sets errno, but C99 doesn't say that.
  503. Give a sensible default value in case gmtime doesn't set it. */
  504. errno = EINVAL;
  505. utc = gmtime (&itime);
  506. if (utc == NULL)
  507. err = errno;
  508. restorezone (zone, oldenv, FUNC_NAME);
  509. /* delayed until zone has been restored. */
  510. errno = err;
  511. if (utc == NULL || itime == -1)
  512. SCM_SYSERROR;
  513. zoff = (utc->tm_hour - lt.tm_hour) * 3600 + (utc->tm_min - lt.tm_min) * 60
  514. + utc->tm_sec - lt.tm_sec;
  515. if (utc->tm_year < lt.tm_year)
  516. zoff -= 24 * 60 * 60;
  517. else if (utc->tm_year > lt.tm_year)
  518. zoff += 24 * 60 * 60;
  519. else if (utc->tm_yday < lt.tm_yday)
  520. zoff -= 24 * 60 * 60;
  521. else if (utc->tm_yday > lt.tm_yday)
  522. zoff += 24 * 60 * 60;
  523. result = scm_cons (scm_from_long (itime),
  524. filltime (&lt, zoff, zname));
  525. free (zname);
  526. scm_dynwind_end ();
  527. return result;
  528. }
  529. #undef FUNC_NAME
  530. #ifdef HAVE_TZSET
  531. SCM_DEFINE (scm_tzset, "tzset", 0, 0, 0,
  532. (void),
  533. "Initialize the timezone from the TZ environment variable\n"
  534. "or the system default. It's not usually necessary to call this procedure\n"
  535. "since it's done automatically by other procedures that depend on the\n"
  536. "timezone.")
  537. #define FUNC_NAME s_scm_tzset
  538. {
  539. tzset();
  540. return SCM_UNSPECIFIED;
  541. }
  542. #undef FUNC_NAME
  543. #endif /* HAVE_TZSET */
  544. SCM_DEFINE (scm_strftime, "strftime", 2, 0, 0,
  545. (SCM format, SCM stime),
  546. "Return a string which is broken-down time structure @var{stime}\n"
  547. "formatted according to the given @var{format} string.\n"
  548. "\n"
  549. "@var{format} contains field specifications introduced by a\n"
  550. "@samp{%} character. See @ref{Formatting Calendar Time,,, libc,\n"
  551. "The GNU C Library Reference Manual}, or @samp{man 3 strftime},\n"
  552. "for the available formatting.\n"
  553. "\n"
  554. "@lisp\n"
  555. "(strftime \"%c\" (localtime (current-time)))\n"
  556. "@result{} \"Mon Mar 11 20:17:43 2002\"\n"
  557. "@end lisp\n"
  558. "\n"
  559. "If @code{setlocale} has been called (@pxref{Locales}), month\n"
  560. "and day names are from the current locale and in the locale\n"
  561. "character set.")
  562. #define FUNC_NAME s_scm_strftime
  563. {
  564. struct tm t;
  565. char *tbuf;
  566. int size = 50;
  567. char *fmt;
  568. char *myfmt;
  569. size_t len;
  570. SCM result;
  571. SCM_VALIDATE_STRING (1, format);
  572. bdtime2c (stime, &t, SCM_ARG2, FUNC_NAME);
  573. /* Convert string to UTF-8 so that non-ASCII characters in the
  574. format are passed through unchanged. */
  575. fmt = scm_to_utf8_stringn (format, &len);
  576. /* Ugly hack: strftime can return 0 if its buffer is too small,
  577. but some valid time strings (e.g. "%p") can sometimes produce
  578. a zero-byte output string! Workaround is to prepend a junk
  579. character to the format string, so that valid returns are always
  580. nonzero. */
  581. myfmt = scm_malloc (len+2);
  582. *myfmt = (uint8_t) 'x';
  583. strncpy (myfmt + 1, fmt, len);
  584. myfmt[len + 1] = 0;
  585. scm_remember_upto_here_1 (format);
  586. free (fmt);
  587. tbuf = scm_malloc (size);
  588. {
  589. #if !defined (HAVE_STRUCT_TM_TM_ZONE)
  590. /* it seems the only way to tell non-GNU versions of strftime what
  591. zone to use (for the %Z format) is to set TZ in the
  592. environment. interrupts and thread switching must be deferred
  593. until TZ is restored. */
  594. char **oldenv = NULL;
  595. SCM zone_spec = SCM_SIMPLE_VECTOR_REF (stime, 10);
  596. int have_zone = 0;
  597. if (scm_is_true (zone_spec) && scm_c_string_length (zone_spec) > 0)
  598. {
  599. /* it's not required that the TZ setting be correct, just that
  600. it has the right name. so try something like TZ=EST0.
  601. using only TZ=EST would be simpler but it doesn't work on
  602. some OSs, e.g., Solaris. */
  603. SCM zone =
  604. scm_string_append (scm_list_2 (zone_spec,
  605. scm_from_utf8_string ("0")));
  606. have_zone = 1;
  607. scm_i_scm_pthread_mutex_lock (&tz_lock);
  608. oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
  609. }
  610. #endif
  611. #ifdef LOCALTIME_CACHE
  612. tzset ();
  613. #endif
  614. /* Use `nstrftime ()' from Gnulib, which supports all GNU extensions
  615. supported by glibc. */
  616. while ((len = nstrftime (tbuf, size, myfmt, &t, 0, 0)) == 0)
  617. {
  618. free (tbuf);
  619. size *= 2;
  620. tbuf = scm_malloc (size);
  621. }
  622. #if !defined (HAVE_STRUCT_TM_TM_ZONE)
  623. if (have_zone)
  624. {
  625. restorezone (zone_spec, oldenv, FUNC_NAME);
  626. scm_i_pthread_mutex_unlock (&tz_lock);
  627. }
  628. #endif
  629. }
  630. result = scm_from_utf8_string (tbuf + 1);
  631. free (tbuf);
  632. free (myfmt);
  633. #if HAVE_STRUCT_TM_TM_ZONE
  634. free ((char *) t.tm_zone);
  635. #endif
  636. return result;
  637. }
  638. #undef FUNC_NAME
  639. #ifdef HAVE_STRPTIME
  640. SCM_DEFINE (scm_strptime, "strptime", 2, 0, 0,
  641. (SCM format, SCM string),
  642. "Performs the reverse action to @code{strftime}, parsing\n"
  643. "@var{string} according to the specification supplied in\n"
  644. "@var{format}. The interpretation of month and day names is\n"
  645. "dependent on the current locale. The value returned is a pair.\n"
  646. "The car has an object with time components\n"
  647. "in the form returned by @code{localtime} or @code{gmtime},\n"
  648. "but the time zone components\n"
  649. "are not usefully set.\n"
  650. "The cdr reports the number of characters from @var{string}\n"
  651. "which were used for the conversion.")
  652. #define FUNC_NAME s_scm_strptime
  653. {
  654. struct tm t;
  655. char *fmt, *str, *rest;
  656. size_t used_len;
  657. long zoff;
  658. SCM_VALIDATE_STRING (1, format);
  659. SCM_VALIDATE_STRING (2, string);
  660. /* Convert strings to UTF-8 so that non-ASCII characters are passed
  661. through unchanged. */
  662. fmt = scm_to_utf8_string (format);
  663. str = scm_to_utf8_string (string);
  664. /* initialize the struct tm */
  665. #define tm_init(field) t.field = 0
  666. tm_init (tm_sec);
  667. tm_init (tm_min);
  668. tm_init (tm_hour);
  669. tm_init (tm_mday);
  670. tm_init (tm_mon);
  671. tm_init (tm_year);
  672. tm_init (tm_wday);
  673. tm_init (tm_yday);
  674. #if HAVE_STRUCT_TM_TM_GMTOFF
  675. tm_init (tm_gmtoff);
  676. #endif
  677. #undef tm_init
  678. /* GNU glibc strptime() "%s" is affected by the current timezone, since it
  679. reads a UTC time_t value and converts with localtime_r() to set the tm
  680. fields, hence the mutex. */
  681. t.tm_isdst = -1;
  682. scm_i_pthread_mutex_lock (&tz_lock);
  683. rest = strptime (str, fmt, &t);
  684. scm_i_pthread_mutex_unlock (&tz_lock);
  685. if (rest == NULL)
  686. {
  687. /* POSIX doesn't say strptime sets errno, and on glibc 2.3.2 for
  688. instance it doesn't. Force a sensible value for our error
  689. message. */
  690. errno = EINVAL;
  691. scm_remember_upto_here_2 (format, string);
  692. free (str);
  693. free (fmt);
  694. SCM_SYSERROR;
  695. }
  696. /* tm_gmtoff is set by GNU glibc strptime "%s", so capture it when
  697. available */
  698. #if HAVE_STRUCT_TM_TM_GMTOFF
  699. zoff = - t.tm_gmtoff; /* seconds west, not east */
  700. #else
  701. zoff = 0;
  702. #endif
  703. /* Compute the number of UTF-8 characters. */
  704. used_len = u8_strnlen ((uint8_t*) str, rest-str);
  705. scm_remember_upto_here_2 (format, string);
  706. free (str);
  707. free (fmt);
  708. return scm_cons (filltime (&t, zoff, NULL),
  709. scm_from_signed_integer (used_len));
  710. }
  711. #undef FUNC_NAME
  712. #endif /* HAVE_STRPTIME */
  713. void
  714. scm_init_stime()
  715. {
  716. scm_c_define ("internal-time-units-per-second",
  717. scm_from_long (SCM_TIME_UNITS_PER_SECOND));
  718. /* Init POSIX timers, and see if we can use them. */
  719. #ifdef HAVE_CLOCK_GETTIME
  720. if (clock_gettime (CLOCK_REALTIME, &posix_real_time_base) == 0)
  721. get_internal_real_time = get_internal_real_time_posix_timer;
  722. #ifdef HAVE_POSIX_CPUTIME
  723. {
  724. if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &posix_run_time_base) == 0)
  725. get_internal_run_time = get_internal_run_time_posix_timer;
  726. else
  727. errno = 0;
  728. }
  729. #endif /* HAVE_POSIX_CPUTIME */
  730. #endif /* HAVE_CLOCKTIME */
  731. /* If needed, init and use gettimeofday timer. */
  732. #ifdef HAVE_GETTIMEOFDAY
  733. if (!get_internal_real_time
  734. && gettimeofday (&gettimeofday_real_time_base, NULL) == 0)
  735. get_internal_real_time = get_internal_real_time_gettimeofday;
  736. #endif
  737. /* Init ticks_per_second for scm_times, and use times(2)-based
  738. run-time timer if needed. */
  739. #ifdef _SC_CLK_TCK
  740. ticks_per_second = sysconf (_SC_CLK_TCK);
  741. #else
  742. ticks_per_second = CLK_TCK;
  743. #endif
  744. if (!get_internal_run_time)
  745. get_internal_run_time = get_internal_run_time_times;
  746. if (!get_internal_real_time)
  747. /* No POSIX timers, gettimeofday doesn't work... badness! */
  748. {
  749. fallback_real_time_base = time (NULL);
  750. get_internal_real_time = get_internal_real_time_fallback;
  751. }
  752. scm_add_feature ("current-time");
  753. #include "stime.x"
  754. }