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
28 #include "libguile/_scm.h"
29 #include "libguile/feature.h"
30 #include "libguile/strings.h"
31 #include "libguile/vectors.h"
33 #include "libguile/validate.h"
34 #include "libguile/stime.h"
41 # ifdef HAVE_SYS_TYPES_H
42 # include <sys/types.h>
49 #ifdef HAVE_SYS_TIMES_H
50 # include <sys/times.h>
53 #ifdef HAVE_SYS_TIMEB_H
54 # include <sys/timeb.h>
57 #if HAVE_CRT_EXTERNS_H
58 #include <crt_externs.h> /* for Darwin _NSGetEnviron */
61 #ifndef tzname /* For SGI. */
62 extern char *tzname
[]; /* RS6000 and others reject char **tzname. */
64 #if defined (__MINGW32__)
65 # define tzname _tzname
68 #ifdef MISSING_STRPTIME_DECL
69 extern char *strptime ();
78 extern char ** environ
;
80 /* On Apple Darwin in a shared library there's no "environ" to access
81 directly, instead the address of that variable must be obtained with
83 #if HAVE__NSGETENVIRON && defined (PIC)
84 #define environ (*_NSGetEnviron())
92 struct tms time_buffer
;
94 return time_buffer
.tms_utime
+ time_buffer
.tms_stime
;
98 # define mytime() ((time((timet*)0) - scm_your_base) * SCM_TIME_UNITS_PER_SECOND)
100 # define mytime clock
105 struct timeb scm_your_base
= {0};
107 timet scm_your_base
= 0;
110 SCM_DEFINE (scm_get_internal_real_time
, "get-internal-real-time", 0, 0, 0,
112 "Return the number of time units since the interpreter was\n"
114 #define FUNC_NAME s_scm_get_internal_real_time
117 struct timeb time_buffer
;
120 ftime (&time_buffer
);
121 time_buffer
.time
-= scm_your_base
.time
;
122 tmp
= scm_long2num (time_buffer
.millitm
- scm_your_base
.millitm
);
124 scm_product (SCM_MAKINUM (1000),
125 SCM_MAKINUM (time_buffer
.time
)));
126 return scm_quotient (scm_product (tmp
, SCM_MAKINUM (SCM_TIME_UNITS_PER_SECOND
)),
129 return scm_long2num((time((timet
*)0) - scm_your_base
) * (int)SCM_TIME_UNITS_PER_SECOND
);
130 #endif /* HAVE_FTIME */
136 SCM_DEFINE (scm_times
, "times", 0, 0, 0,
138 "Return an object with information about real and processor\n"
139 "time. The following procedures accept such an object as an\n"
140 "argument and return a selected component:\n"
144 "The current real time, expressed as time units relative to an\n"
147 "The CPU time units used by the calling process.\n"
149 "The CPU time units used by the system on behalf of the calling\n"
152 "The CPU time units used by terminated child processes of the\n"
153 "calling process, whose status has been collected (e.g., using\n"
156 "Similarly, the CPU times units used by the system on behalf of\n"
157 "terminated child processes.\n"
159 #define FUNC_NAME s_scm_times
164 SCM result
= scm_c_make_vector (5, SCM_UNDEFINED
);
168 SCM_VECTOR_SET (result
, 0, scm_long2num (rv
));
169 SCM_VECTOR_SET (result
, 1, scm_long2num (t
.tms_utime
));
170 SCM_VECTOR_SET (result
, 2, scm_long2num (t
.tms_stime
));
171 SCM_VECTOR_SET (result
,3, scm_long2num (t
.tms_cutime
));
172 SCM_VECTOR_SET (result
, 4, scm_long2num (t
.tms_cstime
));
176 #endif /* HAVE_TIMES */
178 static long scm_my_base
= 0;
181 scm_c_get_internal_run_time ()
183 return mytime () - scm_my_base
;
186 SCM_DEFINE (scm_get_internal_run_time
, "get-internal-run-time", 0, 0, 0,
188 "Return the number of time units of processor time used by the\n"
189 "interpreter. Both @emph{system} and @emph{user} time are\n"
190 "included but subprocesses are not.")
191 #define FUNC_NAME s_scm_get_internal_run_time
193 return scm_long2num (scm_c_get_internal_run_time ());
197 /* For reference, note that current-time and gettimeofday both should be
198 protected against setzone/restorezone changes in another thread, since on
199 DOS the system time is normally kept as local time, which means TZ
200 affects the return from current-time and gettimeofday. Not sure if DJGPP
201 etc actually has concurrent multi-threading, but it seems prudent not to
202 make assumptions about this. */
204 SCM_DEFINE (scm_current_time
, "current-time", 0, 0, 0,
206 "Return the number of seconds since 1970-01-01 00:00:00 UTC,\n"
207 "excluding leap seconds.")
208 #define FUNC_NAME s_scm_current_time
213 if ((timv
= time (0)) == -1)
214 SCM_MISC_ERROR ("current time not available", SCM_EOL
);
216 return scm_long2num((long) timv
);
220 SCM_DEFINE (scm_gettimeofday
, "gettimeofday", 0, 0, 0,
222 "Return a pair containing the number of seconds and microseconds\n"
223 "since 1970-01-01 00:00:00 UTC, excluding leap seconds. Note:\n"
224 "whether true microsecond resolution is available depends on the\n"
226 #define FUNC_NAME s_scm_gettimeofday
228 #ifdef HAVE_GETTIMEOFDAY
232 if (gettimeofday (&time
, NULL
) == -1)
235 return scm_cons (scm_long2num ((long) time
.tv_sec
),
236 scm_long2num ((long) time
.tv_usec
));
242 return scm_cons (scm_long2num ((long) time
.time
),
243 SCM_MAKINUM (time
.millitm
* 1000));
248 if ((timv
= time (0)) == -1)
251 return scm_cons (scm_long2num (timv
), SCM_MAKINUM (0));
258 filltime (struct tm
*bd_time
, int zoff
, char *zname
)
260 SCM result
= scm_c_make_vector (11, SCM_UNDEFINED
);
262 SCM_VECTOR_SET (result
,0, SCM_MAKINUM (bd_time
->tm_sec
));
263 SCM_VECTOR_SET (result
,1, SCM_MAKINUM (bd_time
->tm_min
));
264 SCM_VECTOR_SET (result
,2, SCM_MAKINUM (bd_time
->tm_hour
));
265 SCM_VECTOR_SET (result
,3, SCM_MAKINUM (bd_time
->tm_mday
));
266 SCM_VECTOR_SET (result
,4, SCM_MAKINUM (bd_time
->tm_mon
));
267 SCM_VECTOR_SET (result
,5, SCM_MAKINUM (bd_time
->tm_year
));
268 SCM_VECTOR_SET (result
,6, SCM_MAKINUM (bd_time
->tm_wday
));
269 SCM_VECTOR_SET (result
,7, SCM_MAKINUM (bd_time
->tm_yday
));
270 SCM_VECTOR_SET (result
,8, SCM_MAKINUM (bd_time
->tm_isdst
));
271 SCM_VECTOR_SET (result
,9, SCM_MAKINUM (zoff
));
272 SCM_VECTOR_SET (result
,10, zname
? scm_makfrom0str (zname
) : SCM_BOOL_F
);
276 static char tzvar
[3] = "TZ";
278 /* if zone is set, create a temporary environment with only a TZ
279 string. other threads or interrupt handlers shouldn't be allowed
280 to run until the corresponding restorezone is called. hence the use
281 of a static variable for tmpenv is no big deal. */
283 setzone (SCM zone
, int pos
, const char *subr
)
287 if (!SCM_UNBNDP (zone
))
289 static char *tmpenv
[2];
292 SCM_ASSERT (SCM_STRINGP (zone
), zone
, pos
, subr
);
293 buf
= scm_malloc (SCM_STRING_LENGTH (zone
) + sizeof (tzvar
) + 1);
294 sprintf (buf
, "%s=%s", tzvar
, SCM_STRING_CHARS (zone
));
304 restorezone (SCM zone
, char **oldenv
, const char *subr SCM_UNUSED
)
306 if (!SCM_UNBNDP (zone
))
311 /* for the possible benefit of user code linked with libguile. */
317 SCM_DEFINE (scm_localtime
, "localtime", 1, 1, 0,
318 (SCM time
, SCM zone
),
319 "Return an object representing the broken down components of\n"
320 "@var{time}, an integer like the one returned by\n"
321 "@code{current-time}. The time zone for the calculation is\n"
322 "optionally specified by @var{zone} (a string), otherwise the\n"
323 "@code{TZ} environment variable or the system default is used.")
324 #define FUNC_NAME s_scm_localtime
327 struct tm
*ltptr
, lt
, *utc
;
334 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. */
339 oldenv
= setzone (zone
, SCM_ARG2
, FUNC_NAME
);
340 #ifdef LOCALTIME_CACHE
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. */
346 ltptr
= localtime (&itime
);
352 /* copy zone name before calling gmtime or restoring zone. */
353 #if defined (HAVE_TM_ZONE)
354 ptr
= ltptr
->tm_zone
;
355 #elif defined (HAVE_TZNAME)
356 ptr
= tzname
[ (ltptr
->tm_isdst
== 1) ? 1 : 0 ];
360 zname
= scm_malloc (strlen (ptr
) + 1);
363 /* the struct is copied in case localtime and gmtime share a buffer. */
366 /* POSIX says gmtime sets errno, but C99 doesn't say that.
367 Give a sensible default value in case gmtime doesn't set it. */
369 utc
= gmtime (&itime
);
372 restorezone (zone
, oldenv
, FUNC_NAME
);
373 /* delayed until zone has been restored. */
375 if (utc
== NULL
|| ltptr
== NULL
)
378 /* calculate timezone offset in seconds west of UTC. */
379 zoff
= (utc
->tm_hour
- lt
.tm_hour
) * 3600 + (utc
->tm_min
- lt
.tm_min
) * 60
380 + utc
->tm_sec
- lt
.tm_sec
;
381 if (utc
->tm_year
< lt
.tm_year
)
382 zoff
-= 24 * 60 * 60;
383 else if (utc
->tm_year
> lt
.tm_year
)
384 zoff
+= 24 * 60 * 60;
385 else if (utc
->tm_yday
< lt
.tm_yday
)
386 zoff
-= 24 * 60 * 60;
387 else if (utc
->tm_yday
> lt
.tm_yday
)
388 zoff
+= 24 * 60 * 60;
390 result
= filltime (<
, zoff
, zname
);
398 SCM_DEFINE (scm_gmtime
, "gmtime", 1, 0, 0,
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
409 itime
= SCM_NUM2LONG (1, time
);
411 /* POSIX says gmtime sets errno, but C99 doesn't say that.
412 Give a sensible default value in case gmtime doesn't set it. */
414 bd_time
= gmtime (&itime
);
417 result
= filltime (bd_time
, 0, "GMT");
423 /* copy time components from a Scheme object to a struct tm. */
425 bdtime2c (SCM sbd_time
, struct tm
*lt
, int pos
, const char *subr
)
430 SCM_ASSERT (SCM_VECTORP (sbd_time
)
431 && SCM_VECTOR_LENGTH (sbd_time
) == 11,
432 sbd_time
, pos
, subr
);
433 velts
= SCM_VELTS (sbd_time
);
434 for (i
= 0; i
< 10; i
++)
436 SCM_ASSERT (SCM_INUMP (velts
[i
]), sbd_time
, pos
, subr
);
438 SCM_ASSERT (SCM_FALSEP (velts
[10]) || SCM_STRINGP (velts
[10]),
439 sbd_time
, pos
, subr
);
441 lt
->tm_sec
= SCM_INUM (velts
[0]);
442 lt
->tm_min
= SCM_INUM (velts
[1]);
443 lt
->tm_hour
= SCM_INUM (velts
[2]);
444 lt
->tm_mday
= SCM_INUM (velts
[3]);
445 lt
->tm_mon
= SCM_INUM (velts
[4]);
446 lt
->tm_year
= SCM_INUM (velts
[5]);
447 lt
->tm_wday
= SCM_INUM (velts
[6]);
448 lt
->tm_yday
= SCM_INUM (velts
[7]);
449 lt
->tm_isdst
= SCM_INUM (velts
[8]);
451 lt
->tm_gmtoff
= SCM_INUM (velts
[9]);
452 if (SCM_FALSEP (velts
[10]))
455 lt
->tm_zone
= SCM_STRING_CHARS (velts
[10]);
459 SCM_DEFINE (scm_mktime
, "mktime", 1, 1, 0,
460 (SCM sbd_time
, SCM zone
),
461 "@var{bd-time} is an object representing broken down time and @code{zone}\n"
462 "is an optional time zone specifier (otherwise the TZ environment variable\n"
463 "or the system default is used).\n\n"
464 "Returns a pair: the car is a corresponding\n"
465 "integer time value like that returned\n"
466 "by @code{current-time}; the cdr is a broken down time object, similar to\n"
467 "as @var{bd-time} but with normalized values.")
468 #define FUNC_NAME s_scm_mktime
478 bdtime2c (sbd_time
, <
, SCM_ARG1
, FUNC_NAME
);
481 oldenv
= setzone (zone
, SCM_ARG2
, FUNC_NAME
);
482 #ifdef LOCALTIME_CACHE
485 itime
= mktime (<
);
486 /* POSIX doesn't say mktime sets errno, and on glibc 2.3.2 for instance it
487 doesn't. Force a sensible value for our error message. */
494 /* copy zone name before calling gmtime or restoring the zone. */
495 #if defined (HAVE_TM_ZONE)
497 #elif defined (HAVE_TZNAME)
498 ptr
= tzname
[ (lt
.tm_isdst
== 1) ? 1 : 0 ];
502 zname
= scm_malloc (strlen (ptr
) + 1);
506 /* get timezone offset in seconds west of UTC. */
507 /* POSIX says gmtime sets errno, but C99 doesn't say that.
508 Give a sensible default value in case gmtime doesn't set it. */
509 utc
= gmtime (&itime
);
513 restorezone (zone
, oldenv
, FUNC_NAME
);
514 /* delayed until zone has been restored. */
516 if (utc
== NULL
|| itime
== -1)
519 zoff
= (utc
->tm_hour
- lt
.tm_hour
) * 3600 + (utc
->tm_min
- lt
.tm_min
) * 60
520 + utc
->tm_sec
- lt
.tm_sec
;
521 if (utc
->tm_year
< lt
.tm_year
)
522 zoff
-= 24 * 60 * 60;
523 else if (utc
->tm_year
> lt
.tm_year
)
524 zoff
+= 24 * 60 * 60;
525 else if (utc
->tm_yday
< lt
.tm_yday
)
526 zoff
-= 24 * 60 * 60;
527 else if (utc
->tm_yday
> lt
.tm_yday
)
528 zoff
+= 24 * 60 * 60;
530 result
= scm_cons (scm_long2num ((long) itime
),
531 filltime (<
, zoff
, zname
));
540 SCM_DEFINE (scm_tzset
, "tzset", 0, 0, 0,
542 "Initialize the timezone from the TZ environment variable\n"
543 "or the system default. It's not usually necessary to call this procedure\n"
544 "since it's done automatically by other procedures that depend on the\n"
546 #define FUNC_NAME s_scm_tzset
549 return SCM_UNSPECIFIED
;
552 #endif /* HAVE_TZSET */
554 SCM_DEFINE (scm_strftime
, "strftime", 2, 0, 0,
555 (SCM format
, SCM stime
),
556 "Formats a time specification @var{time} using @var{template}. @var{time}\n"
557 "is an object with time components in the form returned by @code{localtime}\n"
558 "or @code{gmtime}. @var{template} is a string which can include formatting\n"
559 "specifications introduced by a @code{%} character. The formatting of\n"
560 "month and day names is dependent on the current locale. The value returned\n"
561 "is the formatted string.\n"
562 "@xref{Formatting Date and Time, , , libc, The GNU C Library Reference Manual}.)")
563 #define FUNC_NAME s_scm_strftime
573 SCM_VALIDATE_STRING (1, format
);
574 bdtime2c (stime
, &t
, SCM_ARG2
, FUNC_NAME
);
576 fmt
= SCM_STRING_CHARS (format
);
577 len
= SCM_STRING_LENGTH (format
);
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
584 myfmt
= scm_malloc (len
+2);
586 strncpy(myfmt
+1, fmt
, len
);
589 tbuf
= scm_malloc (size
);
591 #if !defined (HAVE_TM_ZONE)
592 /* it seems the only way to tell non-GNU versions of strftime what
593 zone to use (for the %Z format) is to set TZ in the
594 environment. interrupts and thread switching must be deferred
595 until TZ is restored. */
596 char **oldenv
= NULL
;
597 SCM
*velts
= (SCM
*) SCM_VELTS (stime
);
600 if (!SCM_FALSEP (velts
[10]) && *SCM_STRING_CHARS (velts
[10]) != 0)
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. */
607 scm_string_append (scm_cons (velts
[10],
608 scm_cons (scm_makfrom0str ("0"),
613 oldenv
= setzone (zone
, SCM_ARG2
, FUNC_NAME
);
617 #ifdef LOCALTIME_CACHE
621 /* POSIX says strftime returns 0 on buffer overrun, but old
622 systems (i.e. libc 4 on GNU/Linux) might return `size' in that
624 while ((len
= strftime (tbuf
, size
, myfmt
, &t
)) == 0 || len
== size
)
628 tbuf
= scm_malloc (size
);
631 #if !defined (HAVE_TM_ZONE)
634 restorezone (velts
[10], oldenv
, FUNC_NAME
);
640 result
= scm_mem2string (tbuf
+ 1, len
- 1);
648 SCM_DEFINE (scm_strptime
, "strptime", 2, 0, 0,
649 (SCM format
, SCM string
),
650 "Performs the reverse action to @code{strftime}, parsing\n"
651 "@var{string} according to the specification supplied in\n"
652 "@var{template}. The interpretation of month and day names is\n"
653 "dependent on the current locale. The value returned is a pair.\n"
654 "The car has an object with time components\n"
655 "in the form returned by @code{localtime} or @code{gmtime},\n"
656 "but the time zone components\n"
657 "are not usefully set.\n"
658 "The cdr reports the number of characters from @var{string}\n"
659 "which were used for the conversion.")
660 #define FUNC_NAME s_scm_strptime
663 char *fmt
, *str
, *rest
;
665 SCM_VALIDATE_STRING (1, format
);
666 SCM_VALIDATE_STRING (2, string
);
668 fmt
= SCM_STRING_CHARS (format
);
669 str
= SCM_STRING_CHARS (string
);
671 /* initialize the struct tm */
672 #define tm_init(field) t.field = 0
683 /* GNU glibc strptime() "%s" is affected by the current timezone, since it
684 reads a UTC time_t value and converts with localtime_r() to set the tm
685 fields, hence the use of SCM_DEFER_INTS. */
688 if ((rest
= strptime (str
, fmt
, &t
)) == NULL
)
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
698 return scm_cons (filltime (&t
, 0, NULL
), SCM_MAKINUM (rest
- str
));
701 #endif /* HAVE_STRPTIME */
706 scm_c_define ("internal-time-units-per-second",
707 scm_long2num((long) SCM_TIME_UNITS_PER_SECOND
));
710 if (!scm_your_base
.time
) ftime(&scm_your_base
);
712 if (!scm_your_base
) time(&scm_your_base
);
715 if (!scm_my_base
) scm_my_base
= mytime();
717 scm_add_feature ("current-time");
718 #include "libguile/stime.x"