stime.c 26 KB

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