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