1 /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2003, 2004 Free Software Foundation, Inc.
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.
8 * This library is distributed in the hope that it will be useful,
9 * but 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.
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
21 #define _GNU_SOURCE /* ask glibc for everything, in particular strptime */
22 #define _POSIX_C_SOURCE 199506L /* for gmtime_r prototype */
31 #include "libguile/_scm.h"
32 #include "libguile/feature.h"
33 #include "libguile/strings.h"
34 #include "libguile/vectors.h"
36 #include "libguile/validate.h"
37 #include "libguile/stime.h"
44 # ifdef HAVE_SYS_TYPES_H
45 # include <sys/types.h>
52 #ifdef HAVE_SYS_TIMES_H
53 # include <sys/times.h>
56 #ifdef HAVE_SYS_TIMEB_H
57 # include <sys/timeb.h>
60 #if HAVE_CRT_EXTERNS_H
61 #include <crt_externs.h> /* for Darwin _NSGetEnviron */
64 #ifndef tzname /* For SGI. */
65 extern char *tzname
[]; /* RS6000 and others reject char **tzname. */
67 #if defined (__MINGW32__)
68 # define tzname _tzname
71 #if ! HAVE_DECL_STRPTIME
72 extern char *strptime ();
81 extern char ** environ
;
83 /* On Apple Darwin in a shared library there's no "environ" to access
84 directly, instead the address of that variable must be obtained with
86 #if HAVE__NSGETENVIRON && defined (PIC)
87 #define environ (*_NSGetEnviron())
95 struct tms time_buffer
;
97 return time_buffer
.tms_utime
+ time_buffer
.tms_stime
;
101 # define mytime() ((time((timet*)0) - scm_your_base) * SCM_TIME_UNITS_PER_SECOND)
103 # define mytime clock
108 struct timeb scm_your_base
= {0};
110 timet scm_your_base
= 0;
113 SCM_DEFINE (scm_get_internal_real_time
, "get-internal-real-time", 0, 0, 0,
115 "Return the number of time units since the interpreter was\n"
117 #define FUNC_NAME s_scm_get_internal_real_time
120 struct timeb time_buffer
;
123 ftime (&time_buffer
);
124 time_buffer
.time
-= scm_your_base
.time
;
125 tmp
= scm_from_long (time_buffer
.millitm
- scm_your_base
.millitm
);
127 scm_product (scm_from_int (1000),
128 scm_from_int (time_buffer
.time
)));
129 return scm_quotient (scm_product (tmp
,
130 scm_from_int (SCM_TIME_UNITS_PER_SECOND
)),
131 scm_from_int (1000));
133 return scm_from_long ((time((timet
*)0) - scm_your_base
)
134 * (int)SCM_TIME_UNITS_PER_SECOND
);
135 #endif /* HAVE_FTIME */
141 SCM_DEFINE (scm_times
, "times", 0, 0, 0,
143 "Return an object with information about real and processor\n"
144 "time. The following procedures accept such an object as an\n"
145 "argument and return a selected component:\n"
149 "The current real time, expressed as time units relative to an\n"
152 "The CPU time units used by the calling process.\n"
154 "The CPU time units used by the system on behalf of the calling\n"
157 "The CPU time units used by terminated child processes of the\n"
158 "calling process, whose status has been collected (e.g., using\n"
161 "Similarly, the CPU times units used by the system on behalf of\n"
162 "terminated child processes.\n"
164 #define FUNC_NAME s_scm_times
169 SCM result
= scm_c_make_vector (5, SCM_UNDEFINED
);
173 SCM_VECTOR_SET (result
, 0, scm_from_long (rv
));
174 SCM_VECTOR_SET (result
, 1, scm_from_long (t
.tms_utime
));
175 SCM_VECTOR_SET (result
, 2, scm_from_long (t
.tms_stime
));
176 SCM_VECTOR_SET (result
,3, scm_from_long (t
.tms_cutime
));
177 SCM_VECTOR_SET (result
, 4, scm_from_long (t
.tms_cstime
));
181 #endif /* HAVE_TIMES */
183 static long scm_my_base
= 0;
186 scm_c_get_internal_run_time ()
188 return mytime () - scm_my_base
;
191 SCM_DEFINE (scm_get_internal_run_time
, "get-internal-run-time", 0, 0, 0,
193 "Return the number of time units of processor time used by the\n"
194 "interpreter. Both @emph{system} and @emph{user} time are\n"
195 "included but subprocesses are not.")
196 #define FUNC_NAME s_scm_get_internal_run_time
198 return scm_from_long (scm_c_get_internal_run_time ());
202 /* For reference, note that current-time and gettimeofday both should be
203 protected against setzone/restorezone changes in another thread, since on
204 DOS the system time is normally kept as local time, which means TZ
205 affects the return from current-time and gettimeofday. Not sure if DJGPP
206 etc actually has concurrent multi-threading, but it seems prudent not to
207 make assumptions about this. */
209 SCM_DEFINE (scm_current_time
, "current-time", 0, 0, 0,
211 "Return the number of seconds since 1970-01-01 00:00:00 UTC,\n"
212 "excluding leap seconds.")
213 #define FUNC_NAME s_scm_current_time
218 if ((timv
= time (0)) == -1)
219 SCM_MISC_ERROR ("current time not available", SCM_EOL
);
221 return scm_from_long (timv
);
225 SCM_DEFINE (scm_gettimeofday
, "gettimeofday", 0, 0, 0,
227 "Return a pair containing the number of seconds and microseconds\n"
228 "since 1970-01-01 00:00:00 UTC, excluding leap seconds. Note:\n"
229 "whether true microsecond resolution is available depends on the\n"
231 #define FUNC_NAME s_scm_gettimeofday
233 #ifdef HAVE_GETTIMEOFDAY
237 if (gettimeofday (&time
, NULL
) == -1)
240 return scm_cons (scm_from_long (time
.tv_sec
),
241 scm_from_long (time
.tv_usec
));
247 return scm_cons (scm_from_long (time
.time
),
248 scm_from_int (time
.millitm
* 1000));
253 if ((timv
= time (0)) == -1)
256 return scm_cons (scm_from_long (timv
), scm_from_int (0));
263 filltime (struct tm
*bd_time
, int zoff
, const char *zname
)
265 SCM result
= scm_c_make_vector (11, SCM_UNDEFINED
);
267 SCM_VECTOR_SET (result
,0, scm_from_int (bd_time
->tm_sec
));
268 SCM_VECTOR_SET (result
,1, scm_from_int (bd_time
->tm_min
));
269 SCM_VECTOR_SET (result
,2, scm_from_int (bd_time
->tm_hour
));
270 SCM_VECTOR_SET (result
,3, scm_from_int (bd_time
->tm_mday
));
271 SCM_VECTOR_SET (result
,4, scm_from_int (bd_time
->tm_mon
));
272 SCM_VECTOR_SET (result
,5, scm_from_int (bd_time
->tm_year
));
273 SCM_VECTOR_SET (result
,6, scm_from_int (bd_time
->tm_wday
));
274 SCM_VECTOR_SET (result
,7, scm_from_int (bd_time
->tm_yday
));
275 SCM_VECTOR_SET (result
,8, scm_from_int (bd_time
->tm_isdst
));
276 SCM_VECTOR_SET (result
,9, scm_from_int (zoff
));
277 SCM_VECTOR_SET (result
,10, zname
? scm_makfrom0str (zname
) : SCM_BOOL_F
);
281 static char tzvar
[3] = "TZ";
283 /* if zone is set, create a temporary environment with only a TZ
284 string. other threads or interrupt handlers shouldn't be allowed
285 to run until the corresponding restorezone is called. hence the use
286 of a static variable for tmpenv is no big deal. */
288 setzone (SCM zone
, int pos
, const char *subr
)
292 if (!SCM_UNBNDP (zone
))
294 static char *tmpenv
[2];
297 SCM_ASSERT (SCM_STRINGP (zone
), zone
, pos
, subr
);
298 buf
= scm_malloc (SCM_STRING_LENGTH (zone
) + sizeof (tzvar
) + 1);
299 sprintf (buf
, "%s=%s", tzvar
, SCM_STRING_CHARS (zone
));
309 restorezone (SCM zone
, char **oldenv
, const char *subr SCM_UNUSED
)
311 if (!SCM_UNBNDP (zone
))
316 /* for the possible benefit of user code linked with libguile. */
322 SCM_DEFINE (scm_localtime
, "localtime", 1, 1, 0,
323 (SCM time
, SCM zone
),
324 "Return an object representing the broken down components of\n"
325 "@var{time}, an integer like the one returned by\n"
326 "@code{current-time}. The time zone for the calculation is\n"
327 "optionally specified by @var{zone} (a string), otherwise the\n"
328 "@code{TZ} environment variable or the system default is used.")
329 #define FUNC_NAME s_scm_localtime
332 struct tm
*ltptr
, lt
, *utc
;
339 itime
= SCM_NUM2LONG (1, time
);
341 /* deferring interupts is essential since a) setzone may install a temporary
342 environment b) localtime uses a static buffer. */
344 oldenv
= setzone (zone
, SCM_ARG2
, FUNC_NAME
);
345 #ifdef LOCALTIME_CACHE
348 /* POSIX says localtime sets errno, but C99 doesn't say that.
349 Give a sensible default value in case localtime doesn't set it. */
351 ltptr
= localtime (&itime
);
357 /* copy zone name before calling gmtime or restoring zone. */
358 #if defined (HAVE_TM_ZONE)
359 ptr
= ltptr
->tm_zone
;
360 #elif defined (HAVE_TZNAME)
361 ptr
= tzname
[ (ltptr
->tm_isdst
== 1) ? 1 : 0 ];
365 zname
= scm_malloc (strlen (ptr
) + 1);
368 /* the struct is copied in case localtime and gmtime share a buffer. */
371 /* POSIX says gmtime sets errno, but C99 doesn't say that.
372 Give a sensible default value in case gmtime doesn't set it. */
374 utc
= gmtime (&itime
);
377 restorezone (zone
, oldenv
, FUNC_NAME
);
378 /* delayed until zone has been restored. */
380 if (utc
== NULL
|| ltptr
== NULL
)
383 /* calculate timezone offset in seconds west of UTC. */
384 zoff
= (utc
->tm_hour
- lt
.tm_hour
) * 3600 + (utc
->tm_min
- lt
.tm_min
) * 60
385 + utc
->tm_sec
- lt
.tm_sec
;
386 if (utc
->tm_year
< lt
.tm_year
)
387 zoff
-= 24 * 60 * 60;
388 else if (utc
->tm_year
> lt
.tm_year
)
389 zoff
+= 24 * 60 * 60;
390 else if (utc
->tm_yday
< lt
.tm_yday
)
391 zoff
-= 24 * 60 * 60;
392 else if (utc
->tm_yday
> lt
.tm_yday
)
393 zoff
+= 24 * 60 * 60;
395 result
= filltime (<
, zoff
, zname
);
403 /* tm_zone is normally a pointer, not an array within struct tm, so we might
404 have to worry about the lifespan of what it points to. The posix specs
405 don't seem to say anything about this, let's assume here that tm_zone
406 will be a constant and therefore no protection or anything is needed
407 until we copy it in filltime(). */
409 SCM_DEFINE (scm_gmtime
, "gmtime", 1, 0, 0,
411 "Return an object representing the broken down components of\n"
412 "@var{time}, an integer like the one returned by\n"
413 "@code{current-time}. The values are calculated for UTC.")
414 #define FUNC_NAME s_scm_gmtime
417 struct tm bd_buf
, *bd_time
;
420 itime
= SCM_NUM2LONG (1, time
);
422 /* POSIX says gmtime sets errno, but C99 doesn't say that.
423 Give a sensible default value in case gmtime doesn't set it. */
427 bd_time
= gmtime_r (&itime
, &bd_buf
);
430 bd_time
= gmtime (&itime
);
438 #if HAVE_STRUCT_TM_TM_ZONE
439 zname
= bd_buf
.tm_zone
;
443 return filltime (&bd_buf
, 0, zname
);
447 /* copy time components from a Scheme object to a struct tm. */
449 bdtime2c (SCM sbd_time
, struct tm
*lt
, int pos
, const char *subr
)
454 SCM_ASSERT (SCM_VECTORP (sbd_time
)
455 && SCM_VECTOR_LENGTH (sbd_time
) == 11,
456 sbd_time
, pos
, subr
);
457 velts
= SCM_VELTS (sbd_time
);
458 for (i
= 0; i
< 10; i
++)
460 SCM_ASSERT (scm_is_integer (velts
[i
]), sbd_time
, pos
, subr
);
462 SCM_ASSERT (scm_is_false (velts
[10]) || SCM_STRINGP (velts
[10]),
463 sbd_time
, pos
, subr
);
465 lt
->tm_sec
= scm_to_int (velts
[0]);
466 lt
->tm_min
= scm_to_int (velts
[1]);
467 lt
->tm_hour
= scm_to_int (velts
[2]);
468 lt
->tm_mday
= scm_to_int (velts
[3]);
469 lt
->tm_mon
= scm_to_int (velts
[4]);
470 lt
->tm_year
= scm_to_int (velts
[5]);
471 lt
->tm_wday
= scm_to_int (velts
[6]);
472 lt
->tm_yday
= scm_to_int (velts
[7]);
473 lt
->tm_isdst
= scm_to_int (velts
[8]);
475 lt
->tm_gmtoff
= scm_to_int (velts
[9]);
476 if (scm_is_false (velts
[10]))
479 lt
->tm_zone
= SCM_STRING_CHARS (velts
[10]);
483 SCM_DEFINE (scm_mktime
, "mktime", 1, 1, 0,
484 (SCM sbd_time
, SCM zone
),
485 "@var{bd-time} is an object representing broken down time and @code{zone}\n"
486 "is an optional time zone specifier (otherwise the TZ environment variable\n"
487 "or the system default is used).\n\n"
488 "Returns a pair: the car is a corresponding\n"
489 "integer time value like that returned\n"
490 "by @code{current-time}; the cdr is a broken down time object, similar to\n"
491 "as @var{bd-time} but with normalized values.")
492 #define FUNC_NAME s_scm_mktime
502 bdtime2c (sbd_time
, <
, SCM_ARG1
, FUNC_NAME
);
505 oldenv
= setzone (zone
, SCM_ARG2
, FUNC_NAME
);
506 #ifdef LOCALTIME_CACHE
509 itime
= mktime (<
);
510 /* POSIX doesn't say mktime sets errno, and on glibc 2.3.2 for instance it
511 doesn't. Force a sensible value for our error message. */
518 /* copy zone name before calling gmtime or restoring the zone. */
519 #if defined (HAVE_TM_ZONE)
521 #elif defined (HAVE_TZNAME)
522 ptr
= tzname
[ (lt
.tm_isdst
== 1) ? 1 : 0 ];
526 zname
= scm_malloc (strlen (ptr
) + 1);
530 /* get timezone offset in seconds west of UTC. */
531 /* POSIX says gmtime sets errno, but C99 doesn't say that.
532 Give a sensible default value in case gmtime doesn't set it. */
533 utc
= gmtime (&itime
);
537 restorezone (zone
, oldenv
, FUNC_NAME
);
538 /* delayed until zone has been restored. */
540 if (utc
== NULL
|| itime
== -1)
543 zoff
= (utc
->tm_hour
- lt
.tm_hour
) * 3600 + (utc
->tm_min
- lt
.tm_min
) * 60
544 + utc
->tm_sec
- lt
.tm_sec
;
545 if (utc
->tm_year
< lt
.tm_year
)
546 zoff
-= 24 * 60 * 60;
547 else if (utc
->tm_year
> lt
.tm_year
)
548 zoff
+= 24 * 60 * 60;
549 else if (utc
->tm_yday
< lt
.tm_yday
)
550 zoff
-= 24 * 60 * 60;
551 else if (utc
->tm_yday
> lt
.tm_yday
)
552 zoff
+= 24 * 60 * 60;
554 result
= scm_cons (scm_from_long (itime
),
555 filltime (<
, zoff
, zname
));
564 SCM_DEFINE (scm_tzset
, "tzset", 0, 0, 0,
566 "Initialize the timezone from the TZ environment variable\n"
567 "or the system default. It's not usually necessary to call this procedure\n"
568 "since it's done automatically by other procedures that depend on the\n"
570 #define FUNC_NAME s_scm_tzset
573 return SCM_UNSPECIFIED
;
576 #endif /* HAVE_TZSET */
578 SCM_DEFINE (scm_strftime
, "strftime", 2, 0, 0,
579 (SCM format
, SCM stime
),
580 "Formats a time specification @var{time} using @var{template}. @var{time}\n"
581 "is an object with time components in the form returned by @code{localtime}\n"
582 "or @code{gmtime}. @var{template} is a string which can include formatting\n"
583 "specifications introduced by a @code{%} character. The formatting of\n"
584 "month and day names is dependent on the current locale. The value returned\n"
585 "is the formatted string.\n"
586 "@xref{Formatting Date and Time, , , libc, The GNU C Library Reference Manual}.)")
587 #define FUNC_NAME s_scm_strftime
597 SCM_VALIDATE_STRING (1, format
);
598 bdtime2c (stime
, &t
, SCM_ARG2
, FUNC_NAME
);
600 fmt
= SCM_STRING_CHARS (format
);
601 len
= SCM_STRING_LENGTH (format
);
603 /* Ugly hack: strftime can return 0 if its buffer is too small,
604 but some valid time strings (e.g. "%p") can sometimes produce
605 a zero-byte output string! Workaround is to prepend a junk
606 character to the format string, so that valid returns are always
608 myfmt
= scm_malloc (len
+2);
610 strncpy(myfmt
+1, fmt
, len
);
613 tbuf
= scm_malloc (size
);
615 #if !defined (HAVE_TM_ZONE)
616 /* it seems the only way to tell non-GNU versions of strftime what
617 zone to use (for the %Z format) is to set TZ in the
618 environment. interrupts and thread switching must be deferred
619 until TZ is restored. */
620 char **oldenv
= NULL
;
621 SCM
*velts
= (SCM
*) SCM_VELTS (stime
);
624 if (scm_is_true (velts
[10]) && *SCM_STRING_CHARS (velts
[10]) != 0)
626 /* it's not required that the TZ setting be correct, just that
627 it has the right name. so try something like TZ=EST0.
628 using only TZ=EST would be simpler but it doesn't work on
629 some OSs, e.g., Solaris. */
631 scm_string_append (scm_cons (velts
[10],
632 scm_cons (scm_makfrom0str ("0"),
637 oldenv
= setzone (zone
, SCM_ARG2
, FUNC_NAME
);
641 #ifdef LOCALTIME_CACHE
645 /* POSIX says strftime returns 0 on buffer overrun, but old
646 systems (i.e. libc 4 on GNU/Linux) might return `size' in that
648 while ((len
= strftime (tbuf
, size
, myfmt
, &t
)) == 0 || len
== size
)
652 tbuf
= scm_malloc (size
);
655 #if !defined (HAVE_TM_ZONE)
658 restorezone (velts
[10], oldenv
, FUNC_NAME
);
664 result
= scm_mem2string (tbuf
+ 1, len
- 1);
672 SCM_DEFINE (scm_strptime
, "strptime", 2, 0, 0,
673 (SCM format
, SCM string
),
674 "Performs the reverse action to @code{strftime}, parsing\n"
675 "@var{string} according to the specification supplied in\n"
676 "@var{template}. The interpretation of month and day names is\n"
677 "dependent on the current locale. The value returned is a pair.\n"
678 "The car has an object with time components\n"
679 "in the form returned by @code{localtime} or @code{gmtime},\n"
680 "but the time zone components\n"
681 "are not usefully set.\n"
682 "The cdr reports the number of characters from @var{string}\n"
683 "which were used for the conversion.")
684 #define FUNC_NAME s_scm_strptime
687 char *fmt
, *str
, *rest
;
689 SCM_VALIDATE_STRING (1, format
);
690 SCM_VALIDATE_STRING (2, string
);
692 fmt
= SCM_STRING_CHARS (format
);
693 str
= SCM_STRING_CHARS (string
);
695 /* initialize the struct tm */
696 #define tm_init(field) t.field = 0
707 /* GNU glibc strptime() "%s" is affected by the current timezone, since it
708 reads a UTC time_t value and converts with localtime_r() to set the tm
709 fields, hence the use of SCM_DEFER_INTS. */
712 if ((rest
= strptime (str
, fmt
, &t
)) == NULL
)
714 /* POSIX doesn't say strptime sets errno, and on glibc 2.3.2 for
715 instance it doesn't. Force a sensible value for our error
722 return scm_cons (filltime (&t
, 0, NULL
),
723 scm_from_signed_integer (rest
- str
));
726 #endif /* HAVE_STRPTIME */
731 scm_c_define ("internal-time-units-per-second",
732 scm_from_long (SCM_TIME_UNITS_PER_SECOND
));
735 if (!scm_your_base
.time
) ftime(&scm_your_base
);
737 if (!scm_your_base
) time(&scm_your_base
);
740 if (!scm_my_base
) scm_my_base
= mytime();
742 scm_add_feature ("current-time");
743 #include "libguile/stime.x"