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