stime.c 25 KB

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