gvariant: Fix bounds checking in GVariant text format parser
[glib.git] / glib / gtimer.c
blob76da128c8a73e91e49244d4686a066780db40a11
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
26 * MT safe
29 #include "config.h"
30 #include "glibconfig.h"
32 #include <stdlib.h>
34 #ifdef G_OS_UNIX
35 #include <unistd.h>
36 #endif /* G_OS_UNIX */
38 #ifdef HAVE_SYS_TIME_H
39 #include <sys/time.h>
40 #endif
41 #include <time.h>
42 #ifndef G_OS_WIN32
43 #include <errno.h>
44 #endif /* G_OS_WIN32 */
46 #ifdef G_OS_WIN32
47 #include <windows.h>
48 #endif /* G_OS_WIN32 */
50 #include "gtimer.h"
52 #include "gmem.h"
53 #include "gstrfuncs.h"
54 #include "gtestutils.h"
55 #include "gmain.h"
57 /**
58 * SECTION:timers
59 * @title: Timers
60 * @short_description: keep track of elapsed time
62 * #GTimer records a start time, and counts microseconds elapsed since
63 * that time. This is done somewhat differently on different platforms,
64 * and can be tricky to get exactly right, so #GTimer provides a
65 * portable/convenient interface.
66 **/
68 /**
69 * GTimer:
71 * Opaque datatype that records a start time.
72 **/
73 struct _GTimer
75 guint64 start;
76 guint64 end;
78 guint active : 1;
81 /**
82 * g_timer_new:
84 * Creates a new timer, and starts timing (i.e. g_timer_start() is
85 * implicitly called for you).
87 * Returns: a new #GTimer.
88 **/
89 GTimer*
90 g_timer_new (void)
92 GTimer *timer;
94 timer = g_new (GTimer, 1);
95 timer->active = TRUE;
97 timer->start = g_get_monotonic_time ();
99 return timer;
103 * g_timer_destroy:
104 * @timer: a #GTimer to destroy.
106 * Destroys a timer, freeing associated resources.
108 void
109 g_timer_destroy (GTimer *timer)
111 g_return_if_fail (timer != NULL);
113 g_free (timer);
117 * g_timer_start:
118 * @timer: a #GTimer.
120 * Marks a start time, so that future calls to g_timer_elapsed() will
121 * report the time since g_timer_start() was called. g_timer_new()
122 * automatically marks the start time, so no need to call
123 * g_timer_start() immediately after creating the timer.
125 void
126 g_timer_start (GTimer *timer)
128 g_return_if_fail (timer != NULL);
130 timer->active = TRUE;
132 timer->start = g_get_monotonic_time ();
136 * g_timer_stop:
137 * @timer: a #GTimer.
139 * Marks an end time, so calls to g_timer_elapsed() will return the
140 * difference between this end time and the start time.
142 void
143 g_timer_stop (GTimer *timer)
145 g_return_if_fail (timer != NULL);
147 timer->active = FALSE;
149 timer->end = g_get_monotonic_time ();
153 * g_timer_reset:
154 * @timer: a #GTimer.
156 * This function is useless; it's fine to call g_timer_start() on an
157 * already-started timer to reset the start time, so g_timer_reset()
158 * serves no purpose.
160 void
161 g_timer_reset (GTimer *timer)
163 g_return_if_fail (timer != NULL);
165 timer->start = g_get_monotonic_time ();
169 * g_timer_continue:
170 * @timer: a #GTimer.
172 * Resumes a timer that has previously been stopped with
173 * g_timer_stop(). g_timer_stop() must be called before using this
174 * function.
176 * Since: 2.4
178 void
179 g_timer_continue (GTimer *timer)
181 guint64 elapsed;
183 g_return_if_fail (timer != NULL);
184 g_return_if_fail (timer->active == FALSE);
186 /* Get elapsed time and reset timer start time
187 * to the current time minus the previously
188 * elapsed interval.
191 elapsed = timer->end - timer->start;
193 timer->start = g_get_monotonic_time ();
195 timer->start -= elapsed;
197 timer->active = TRUE;
201 * g_timer_elapsed:
202 * @timer: a #GTimer.
203 * @microseconds: return location for the fractional part of seconds
204 * elapsed, in microseconds (that is, the total number
205 * of microseconds elapsed, modulo 1000000), or %NULL
207 * If @timer has been started but not stopped, obtains the time since
208 * the timer was started. If @timer has been stopped, obtains the
209 * elapsed time between the time it was started and the time it was
210 * stopped. The return value is the number of seconds elapsed,
211 * including any fractional part. The @microseconds out parameter is
212 * essentially useless.
214 * Returns: seconds elapsed as a floating point value, including any
215 * fractional part.
217 gdouble
218 g_timer_elapsed (GTimer *timer,
219 gulong *microseconds)
221 gdouble total;
222 gint64 elapsed;
224 g_return_val_if_fail (timer != NULL, 0);
226 if (timer->active)
227 timer->end = g_get_monotonic_time ();
229 elapsed = timer->end - timer->start;
231 total = elapsed / 1e6;
233 if (microseconds)
234 *microseconds = elapsed % 1000000;
236 return total;
240 * g_usleep:
241 * @microseconds: number of microseconds to pause
243 * Pauses the current thread for the given number of microseconds.
245 * There are 1 million microseconds per second (represented by the
246 * #G_USEC_PER_SEC macro). g_usleep() may have limited precision,
247 * depending on hardware and operating system; don't rely on the exact
248 * length of the sleep.
250 void
251 g_usleep (gulong microseconds)
253 #ifdef G_OS_WIN32
254 /* Round up to the next millisecond */
255 Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0);
256 #else
257 struct timespec request, remaining;
258 request.tv_sec = microseconds / G_USEC_PER_SEC;
259 request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
260 while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
261 request = remaining;
262 #endif
266 * g_time_val_add:
267 * @time_: a #GTimeVal
268 * @microseconds: number of microseconds to add to @time
270 * Adds the given number of microseconds to @time_. @microseconds can
271 * also be negative to decrease the value of @time_.
273 void
274 g_time_val_add (GTimeVal *time_, glong microseconds)
276 g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
278 if (microseconds >= 0)
280 time_->tv_usec += microseconds % G_USEC_PER_SEC;
281 time_->tv_sec += microseconds / G_USEC_PER_SEC;
282 if (time_->tv_usec >= G_USEC_PER_SEC)
284 time_->tv_usec -= G_USEC_PER_SEC;
285 time_->tv_sec++;
288 else
290 microseconds *= -1;
291 time_->tv_usec -= microseconds % G_USEC_PER_SEC;
292 time_->tv_sec -= microseconds / G_USEC_PER_SEC;
293 if (time_->tv_usec < 0)
295 time_->tv_usec += G_USEC_PER_SEC;
296 time_->tv_sec--;
301 /* converts a broken down date representation, relative to UTC,
302 * to a timestamp; it uses timegm() if it's available.
304 static time_t
305 mktime_utc (struct tm *tm)
307 time_t retval;
309 #ifndef HAVE_TIMEGM
310 static const gint days_before[] =
312 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
314 #endif
316 #ifndef HAVE_TIMEGM
317 if (tm->tm_mon < 0 || tm->tm_mon > 11)
318 return (time_t) -1;
320 retval = (tm->tm_year - 70) * 365;
321 retval += (tm->tm_year - 68) / 4;
322 retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
324 if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
325 retval -= 1;
327 retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
328 #else
329 retval = timegm (tm);
330 #endif /* !HAVE_TIMEGM */
332 return retval;
336 * g_time_val_from_iso8601:
337 * @iso_date: an ISO 8601 encoded date string
338 * @time_: (out): a #GTimeVal
340 * Converts a string containing an ISO 8601 encoded date and time
341 * to a #GTimeVal and puts it into @time_.
343 * @iso_date must include year, month, day, hours, minutes, and
344 * seconds. It can optionally include fractions of a second and a time
345 * zone indicator. (In the absence of any time zone indication, the
346 * timestamp is assumed to be in local time.)
348 * Any leading or trailing space in @iso_date is ignored.
350 * Returns: %TRUE if the conversion was successful.
352 * Since: 2.12
354 gboolean
355 g_time_val_from_iso8601 (const gchar *iso_date,
356 GTimeVal *time_)
358 struct tm tm = {0};
359 long val;
360 long mday, mon, year;
361 long hour, min, sec;
363 g_return_val_if_fail (iso_date != NULL, FALSE);
364 g_return_val_if_fail (time_ != NULL, FALSE);
366 /* Ensure that the first character is a digit, the first digit
367 * of the date, otherwise we don't have an ISO 8601 date
369 while (g_ascii_isspace (*iso_date))
370 iso_date++;
372 if (*iso_date == '\0')
373 return FALSE;
375 if (!g_ascii_isdigit (*iso_date) && *iso_date != '+')
376 return FALSE;
378 val = strtoul (iso_date, (char **)&iso_date, 10);
379 if (*iso_date == '-')
381 /* YYYY-MM-DD */
382 year = val;
383 iso_date++;
385 mon = strtoul (iso_date, (char **)&iso_date, 10);
386 if (*iso_date++ != '-')
387 return FALSE;
389 mday = strtoul (iso_date, (char **)&iso_date, 10);
391 else
393 /* YYYYMMDD */
394 mday = val % 100;
395 mon = (val % 10000) / 100;
396 year = val / 10000;
399 /* Validation. */
400 if (year < 1900 || year > G_MAXINT)
401 return FALSE;
402 if (mon < 1 || mon > 12)
403 return FALSE;
404 if (mday < 1 || mday > 31)
405 return FALSE;
407 tm.tm_mday = mday;
408 tm.tm_mon = mon - 1;
409 tm.tm_year = year - 1900;
411 if (*iso_date != 'T')
412 return FALSE;
414 iso_date++;
416 /* If there is a 'T' then there has to be a time */
417 if (!g_ascii_isdigit (*iso_date))
418 return FALSE;
420 val = strtoul (iso_date, (char **)&iso_date, 10);
421 if (*iso_date == ':')
423 /* hh:mm:ss */
424 hour = val;
425 iso_date++;
426 min = strtoul (iso_date, (char **)&iso_date, 10);
428 if (*iso_date++ != ':')
429 return FALSE;
431 sec = strtoul (iso_date, (char **)&iso_date, 10);
433 else
435 /* hhmmss */
436 sec = val % 100;
437 min = (val % 10000) / 100;
438 hour = val / 10000;
441 /* Validation. Allow up to 2 leap seconds when validating @sec. */
442 if (hour > 23)
443 return FALSE;
444 if (min > 59)
445 return FALSE;
446 if (sec > 61)
447 return FALSE;
449 tm.tm_hour = hour;
450 tm.tm_min = min;
451 tm.tm_sec = sec;
453 time_->tv_usec = 0;
455 if (*iso_date == ',' || *iso_date == '.')
457 glong mul = 100000;
459 while (mul >= 1 && g_ascii_isdigit (*++iso_date))
461 time_->tv_usec += (*iso_date - '0') * mul;
462 mul /= 10;
465 /* Skip any remaining digits after we’ve reached our limit of precision. */
466 while (g_ascii_isdigit (*iso_date))
467 iso_date++;
470 /* Now parse the offset and convert tm to a time_t */
471 if (*iso_date == 'Z')
473 iso_date++;
474 time_->tv_sec = mktime_utc (&tm);
476 else if (*iso_date == '+' || *iso_date == '-')
478 gint sign = (*iso_date == '+') ? -1 : 1;
480 val = strtoul (iso_date + 1, (char **)&iso_date, 10);
482 if (*iso_date == ':')
484 /* hh:mm */
485 hour = val;
486 min = strtoul (iso_date + 1, (char **)&iso_date, 10);
488 else
490 /* hhmm */
491 hour = val / 100;
492 min = val % 100;
495 if (hour > 99)
496 return FALSE;
497 if (min > 59)
498 return FALSE;
500 time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * (60 * hour + min) * sign);
502 else
504 /* No "Z" or offset, so local time */
505 tm.tm_isdst = -1; /* locale selects DST */
506 time_->tv_sec = mktime (&tm);
509 while (g_ascii_isspace (*iso_date))
510 iso_date++;
512 return *iso_date == '\0';
516 * g_time_val_to_iso8601:
517 * @time_: a #GTimeVal
519 * Converts @time_ into an RFC 3339 encoded string, relative to the
520 * Coordinated Universal Time (UTC). This is one of the many formats
521 * allowed by ISO 8601.
523 * ISO 8601 allows a large number of date/time formats, with or without
524 * punctuation and optional elements. The format returned by this function
525 * is a complete date and time, with optional punctuation included, the
526 * UTC time zone represented as "Z", and the @tv_usec part included if
527 * and only if it is nonzero, i.e. either
528 * "YYYY-MM-DDTHH:MM:SSZ" or "YYYY-MM-DDTHH:MM:SS.fffffZ".
530 * This corresponds to the Internet date/time format defined by
531 * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt),
532 * and to either of the two most-precise formats defined by
533 * the W3C Note
534 * [Date and Time Formats](http://www.w3.org/TR/NOTE-datetime-19980827).
535 * Both of these documents are profiles of ISO 8601.
537 * Use g_date_time_format() or g_strdup_printf() if a different
538 * variation of ISO 8601 format is required.
540 * If @time_ represents a date which is too large to fit into a `struct tm`,
541 * %NULL will be returned. This is platform dependent, but it is safe to assume
542 * years up to 3000 are supported. The return value of g_time_val_to_iso8601()
543 * has been nullable since GLib 2.54; before then, GLib would crash under the
544 * same conditions.
546 * Returns: (nullable): a newly allocated string containing an ISO 8601 date,
547 * or %NULL if @time_ was too large
549 * Since: 2.12
551 gchar *
552 g_time_val_to_iso8601 (GTimeVal *time_)
554 gchar *retval;
555 struct tm *tm;
556 #ifdef HAVE_GMTIME_R
557 struct tm tm_;
558 #endif
559 time_t secs;
561 g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
563 secs = time_->tv_sec;
564 #ifdef _WIN32
565 tm = gmtime (&secs);
566 #else
567 #ifdef HAVE_GMTIME_R
568 tm = gmtime_r (&secs, &tm_);
569 #else
570 tm = gmtime (&secs);
571 #endif
572 #endif
574 /* If the gmtime() call has failed, time_->tv_sec is too big. */
575 if (tm == NULL)
576 return NULL;
578 if (time_->tv_usec != 0)
580 /* ISO 8601 date and time format, with fractionary seconds:
581 * YYYY-MM-DDTHH:MM:SS.MMMMMMZ
583 retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
584 tm->tm_year + 1900,
585 tm->tm_mon + 1,
586 tm->tm_mday,
587 tm->tm_hour,
588 tm->tm_min,
589 tm->tm_sec,
590 time_->tv_usec);
592 else
594 /* ISO 8601 date and time format:
595 * YYYY-MM-DDTHH:MM:SSZ
597 retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
598 tm->tm_year + 1900,
599 tm->tm_mon + 1,
600 tm->tm_mday,
601 tm->tm_hour,
602 tm->tm_min,
603 tm->tm_sec);
606 return retval;