stime.c 25 KB

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