gkdbus: Fix underflow and unreachable code bug
[platform/upstream/glib.git] / glib / gtimer.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 /*
28  * MT safe
29  */
30
31 #include "config.h"
32 #include "glibconfig.h"
33
34 #include <stdlib.h>
35
36 #ifdef G_OS_UNIX
37 #include <unistd.h>
38 #endif /* G_OS_UNIX */
39
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <time.h>
44 #ifndef G_OS_WIN32
45 #include <errno.h>
46 #endif /* G_OS_WIN32 */
47
48 #ifdef G_OS_WIN32
49 #include <windows.h>
50 #endif /* G_OS_WIN32 */
51
52 #include "gtimer.h"
53
54 #include "gmem.h"
55 #include "gstrfuncs.h"
56 #include "gtestutils.h"
57 #include "gmain.h"
58
59 /**
60  * SECTION:timers
61  * @title: Timers
62  * @short_description: keep track of elapsed time
63  *
64  * #GTimer records a start time, and counts microseconds elapsed since
65  * that time. This is done somewhat differently on different platforms,
66  * and can be tricky to get exactly right, so #GTimer provides a
67  * portable/convenient interface.
68  **/
69
70 /**
71  * GTimer:
72  *
73  * Opaque datatype that records a start time.
74  **/
75 struct _GTimer
76 {
77   guint64 start;
78   guint64 end;
79
80   guint active : 1;
81 };
82
83 /**
84  * g_timer_new:
85  *
86  * Creates a new timer, and starts timing (i.e. g_timer_start() is
87  * implicitly called for you).
88  *
89  * Returns: a new #GTimer.
90  **/
91 GTimer*
92 g_timer_new (void)
93 {
94   GTimer *timer;
95
96   timer = g_new (GTimer, 1);
97   timer->active = TRUE;
98
99   timer->start = g_get_monotonic_time ();
100
101   return timer;
102 }
103
104 /**
105  * g_timer_destroy:
106  * @timer: a #GTimer to destroy.
107  *
108  * Destroys a timer, freeing associated resources.
109  **/
110 void
111 g_timer_destroy (GTimer *timer)
112 {
113   g_return_if_fail (timer != NULL);
114
115   g_free (timer);
116 }
117
118 /**
119  * g_timer_start:
120  * @timer: a #GTimer.
121  *
122  * Marks a start time, so that future calls to g_timer_elapsed() will
123  * report the time since g_timer_start() was called. g_timer_new()
124  * automatically marks the start time, so no need to call
125  * g_timer_start() immediately after creating the timer.
126  **/
127 void
128 g_timer_start (GTimer *timer)
129 {
130   g_return_if_fail (timer != NULL);
131
132   timer->active = TRUE;
133
134   timer->start = g_get_monotonic_time ();
135 }
136
137 /**
138  * g_timer_stop:
139  * @timer: a #GTimer.
140  *
141  * Marks an end time, so calls to g_timer_elapsed() will return the
142  * difference between this end time and the start time.
143  **/
144 void
145 g_timer_stop (GTimer *timer)
146 {
147   g_return_if_fail (timer != NULL);
148
149   timer->active = FALSE;
150
151   timer->end = g_get_monotonic_time ();
152 }
153
154 /**
155  * g_timer_reset:
156  * @timer: a #GTimer.
157  *
158  * This function is useless; it's fine to call g_timer_start() on an
159  * already-started timer to reset the start time, so g_timer_reset()
160  * serves no purpose.
161  **/
162 void
163 g_timer_reset (GTimer *timer)
164 {
165   g_return_if_fail (timer != NULL);
166
167   timer->start = g_get_monotonic_time ();
168 }
169
170 /**
171  * g_timer_continue:
172  * @timer: a #GTimer.
173  *
174  * Resumes a timer that has previously been stopped with
175  * g_timer_stop(). g_timer_stop() must be called before using this
176  * function.
177  *
178  * Since: 2.4
179  **/
180 void
181 g_timer_continue (GTimer *timer)
182 {
183   guint64 elapsed;
184
185   g_return_if_fail (timer != NULL);
186   g_return_if_fail (timer->active == FALSE);
187
188   /* Get elapsed time and reset timer start time
189    *  to the current time minus the previously
190    *  elapsed interval.
191    */
192
193   elapsed = timer->end - timer->start;
194
195   timer->start = g_get_monotonic_time ();
196
197   timer->start -= elapsed;
198
199   timer->active = TRUE;
200 }
201
202 /**
203  * g_timer_elapsed:
204  * @timer: a #GTimer.
205  * @microseconds: return location for the fractional part of seconds
206  *                elapsed, in microseconds (that is, the total number
207  *                of microseconds elapsed, modulo 1000000), or %NULL
208  *
209  * If @timer has been started but not stopped, obtains the time since
210  * the timer was started. If @timer has been stopped, obtains the
211  * elapsed time between the time it was started and the time it was
212  * stopped. The return value is the number of seconds elapsed,
213  * including any fractional part. The @microseconds out parameter is
214  * essentially useless.
215  *
216  * Returns: seconds elapsed as a floating point value, including any
217  *          fractional part.
218  **/
219 gdouble
220 g_timer_elapsed (GTimer *timer,
221                  gulong *microseconds)
222 {
223   gdouble total;
224   gint64 elapsed;
225
226   g_return_val_if_fail (timer != NULL, 0);
227
228   if (timer->active)
229     timer->end = g_get_monotonic_time ();
230
231   elapsed = timer->end - timer->start;
232
233   total = elapsed / 1e6;
234
235   if (microseconds)
236     *microseconds = elapsed % 1000000;
237
238   return total;
239 }
240
241 /**
242  * g_timer_is_active:
243  * @timer: a #GTimer.
244  * 
245  * Exposes whether the timer is currently active.
246  *
247  * Returns: %TRUE if the timer is running, %FALSE otherwise
248  * Since: 2.62
249  **/
250 gboolean
251 g_timer_is_active (GTimer *timer)
252 {
253   g_return_val_if_fail (timer != NULL, FALSE);
254
255   return timer->active;
256 }
257
258 /**
259  * g_usleep:
260  * @microseconds: number of microseconds to pause
261  *
262  * Pauses the current thread for the given number of microseconds.
263  *
264  * There are 1 million microseconds per second (represented by the
265  * %G_USEC_PER_SEC macro). g_usleep() may have limited precision,
266  * depending on hardware and operating system; don't rely on the exact
267  * length of the sleep.
268  */
269 void
270 g_usleep (gulong microseconds)
271 {
272   if G_UNLIKELY (microseconds == 0)
273     return;
274
275 #ifdef G_OS_WIN32
276   /* Round up to the next millisecond */
277   Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0);
278 #else
279   struct timespec request, remaining;
280   request.tv_sec = microseconds / G_USEC_PER_SEC;
281   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
282   while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
283     request = remaining;
284 #endif
285 }
286
287 /**
288  * g_time_val_add:
289  * @time_: a #GTimeVal
290  * @microseconds: number of microseconds to add to @time
291  *
292  * Adds the given number of microseconds to @time_. @microseconds can
293  * also be negative to decrease the value of @time_.
294  *
295  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use `guint64` for
296  *    representing microseconds since the epoch, or use #GDateTime.
297  **/
298 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
299 void 
300 g_time_val_add (GTimeVal *time_, glong microseconds)
301 {
302   g_return_if_fail (time_ != NULL &&
303                     time_->tv_usec >= 0 &&
304                     time_->tv_usec < G_USEC_PER_SEC);
305
306   if (microseconds >= 0)
307     {
308       time_->tv_usec += microseconds % G_USEC_PER_SEC;
309       time_->tv_sec += microseconds / G_USEC_PER_SEC;
310       if (time_->tv_usec >= G_USEC_PER_SEC)
311        {
312          time_->tv_usec -= G_USEC_PER_SEC;
313          time_->tv_sec++;
314        }
315     }
316   else
317     {
318       microseconds *= -1;
319       time_->tv_usec -= microseconds % G_USEC_PER_SEC;
320       time_->tv_sec -= microseconds / G_USEC_PER_SEC;
321       if (time_->tv_usec < 0)
322        {
323          time_->tv_usec += G_USEC_PER_SEC;
324          time_->tv_sec--;
325        }      
326     }
327 }
328 G_GNUC_END_IGNORE_DEPRECATIONS
329
330 /* converts a broken down date representation, relative to UTC,
331  * to a timestamp; it uses timegm() if it's available.
332  */
333 static time_t
334 mktime_utc (struct tm *tm)
335 {
336   time_t retval;
337   
338 #ifndef HAVE_TIMEGM
339   static const gint days_before[] =
340   {
341     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
342   };
343 #endif
344
345 #ifndef HAVE_TIMEGM
346   if (tm->tm_mon < 0 || tm->tm_mon > 11)
347     return (time_t) -1;
348
349   retval = (tm->tm_year - 70) * 365;
350   retval += (tm->tm_year - 68) / 4;
351   retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
352   
353   if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
354     retval -= 1;
355   
356   retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
357 #else
358   retval = timegm (tm);
359 #endif /* !HAVE_TIMEGM */
360   
361   return retval;
362 }
363
364 /**
365  * g_time_val_from_iso8601:
366  * @iso_date: an ISO 8601 encoded date string
367  * @time_: (out): a #GTimeVal
368  *
369  * Converts a string containing an ISO 8601 encoded date and time
370  * to a #GTimeVal and puts it into @time_.
371  *
372  * @iso_date must include year, month, day, hours, minutes, and
373  * seconds. It can optionally include fractions of a second and a time
374  * zone indicator. (In the absence of any time zone indication, the
375  * timestamp is assumed to be in local time.)
376  *
377  * Any leading or trailing space in @iso_date is ignored.
378  *
379  * This function was deprecated, along with #GTimeVal itself, in GLib 2.62.
380  * Equivalent functionality is available using code like:
381  * |[
382  * GDateTime *dt = g_date_time_new_from_iso8601 (iso8601_string, NULL);
383  * gint64 time_val = g_date_time_to_unix (dt);
384  * g_date_time_unref (dt);
385  * ]|
386  *
387  * Returns: %TRUE if the conversion was successful.
388  *
389  * Since: 2.12
390  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
391  *    g_date_time_new_from_iso8601() instead.
392  */
393 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
394 gboolean
395 g_time_val_from_iso8601 (const gchar *iso_date,
396                          GTimeVal    *time_)
397 {
398   struct tm tm = {0};
399   long val;
400   long mday, mon, year;
401   long hour, min, sec;
402
403   g_return_val_if_fail (iso_date != NULL, FALSE);
404   g_return_val_if_fail (time_ != NULL, FALSE);
405
406   /* Ensure that the first character is a digit, the first digit
407    * of the date, otherwise we don't have an ISO 8601 date
408    */
409   while (g_ascii_isspace (*iso_date))
410     iso_date++;
411
412   if (*iso_date == '\0')
413     return FALSE;
414
415   if (!g_ascii_isdigit (*iso_date) && *iso_date != '+')
416     return FALSE;
417
418   val = strtoul (iso_date, (char **)&iso_date, 10);
419   if (*iso_date == '-')
420     {
421       /* YYYY-MM-DD */
422       year = val;
423       iso_date++;
424
425       mon = strtoul (iso_date, (char **)&iso_date, 10);
426       if (*iso_date++ != '-')
427         return FALSE;
428       
429       mday = strtoul (iso_date, (char **)&iso_date, 10);
430     }
431   else
432     {
433       /* YYYYMMDD */
434       mday = val % 100;
435       mon = (val % 10000) / 100;
436       year = val / 10000;
437     }
438
439   /* Validation. */
440   if (year < 1900 || year > G_MAXINT)
441     return FALSE;
442   if (mon < 1 || mon > 12)
443     return FALSE;
444   if (mday < 1 || mday > 31)
445     return FALSE;
446
447   tm.tm_mday = mday;
448   tm.tm_mon = mon - 1;
449   tm.tm_year = year - 1900;
450
451   if (*iso_date != 'T')
452     return FALSE;
453
454   iso_date++;
455
456   /* If there is a 'T' then there has to be a time */
457   if (!g_ascii_isdigit (*iso_date))
458     return FALSE;
459
460   val = strtoul (iso_date, (char **)&iso_date, 10);
461   if (*iso_date == ':')
462     {
463       /* hh:mm:ss */
464       hour = val;
465       iso_date++;
466       min = strtoul (iso_date, (char **)&iso_date, 10);
467       
468       if (*iso_date++ != ':')
469         return FALSE;
470       
471       sec = strtoul (iso_date, (char **)&iso_date, 10);
472     }
473   else
474     {
475       /* hhmmss */
476       sec = val % 100;
477       min = (val % 10000) / 100;
478       hour = val / 10000;
479     }
480
481   /* Validation. Allow up to 2 leap seconds when validating @sec. */
482   if (hour > 23)
483     return FALSE;
484   if (min > 59)
485     return FALSE;
486   if (sec > 61)
487     return FALSE;
488
489   tm.tm_hour = hour;
490   tm.tm_min = min;
491   tm.tm_sec = sec;
492
493   time_->tv_usec = 0;
494   
495   if (*iso_date == ',' || *iso_date == '.')
496     {
497       glong mul = 100000;
498
499       while (mul >= 1 && g_ascii_isdigit (*++iso_date))
500         {
501           time_->tv_usec += (*iso_date - '0') * mul;
502           mul /= 10;
503         }
504
505       /* Skip any remaining digits after we’ve reached our limit of precision. */
506       while (g_ascii_isdigit (*iso_date))
507         iso_date++;
508     }
509     
510   /* Now parse the offset and convert tm to a time_t */
511   if (*iso_date == 'Z')
512     {
513       iso_date++;
514       time_->tv_sec = mktime_utc (&tm);
515     }
516   else if (*iso_date == '+' || *iso_date == '-')
517     {
518       gint sign = (*iso_date == '+') ? -1 : 1;
519       
520       val = strtoul (iso_date + 1, (char **)&iso_date, 10);
521       
522       if (*iso_date == ':')
523         {
524           /* hh:mm */
525           hour = val;
526           min = strtoul (iso_date + 1, (char **)&iso_date, 10);
527         }
528       else
529         {
530           /* hhmm */
531           hour = val / 100;
532           min = val % 100;
533         }
534
535       if (hour > 99)
536         return FALSE;
537       if (min > 59)
538         return FALSE;
539
540       time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * (gint64) (60 * hour + min) * sign);
541     }
542   else
543     {
544       /* No "Z" or offset, so local time */
545       tm.tm_isdst = -1; /* locale selects DST */
546       time_->tv_sec = mktime (&tm);
547     }
548
549   while (g_ascii_isspace (*iso_date))
550     iso_date++;
551
552   return *iso_date == '\0';
553 }
554 G_GNUC_END_IGNORE_DEPRECATIONS
555
556 /**
557  * g_time_val_to_iso8601:
558  * @time_: a #GTimeVal
559  * 
560  * Converts @time_ into an RFC 3339 encoded string, relative to the
561  * Coordinated Universal Time (UTC). This is one of the many formats
562  * allowed by ISO 8601.
563  *
564  * ISO 8601 allows a large number of date/time formats, with or without
565  * punctuation and optional elements. The format returned by this function
566  * is a complete date and time, with optional punctuation included, the
567  * UTC time zone represented as "Z", and the @tv_usec part included if
568  * and only if it is nonzero, i.e. either
569  * "YYYY-MM-DDTHH:MM:SSZ" or "YYYY-MM-DDTHH:MM:SS.fffffZ".
570  *
571  * This corresponds to the Internet date/time format defined by
572  * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt),
573  * and to either of the two most-precise formats defined by
574  * the W3C Note
575  * [Date and Time Formats](http://www.w3.org/TR/NOTE-datetime-19980827).
576  * Both of these documents are profiles of ISO 8601.
577  *
578  * Use g_date_time_format() or g_strdup_printf() if a different
579  * variation of ISO 8601 format is required.
580  *
581  * If @time_ represents a date which is too large to fit into a `struct tm`,
582  * %NULL will be returned. This is platform dependent. Note also that since
583  * `GTimeVal` stores the number of seconds as a `glong`, on 32-bit systems it
584  * is subject to the year 2038 problem. Accordingly, since GLib 2.62, this
585  * function has been deprecated. Equivalent functionality is available using:
586  * |[
587  * GDateTime *dt = g_date_time_new_from_unix_utc (time_val);
588  * iso8601_string = g_date_time_format_iso8601 (dt);
589  * g_date_time_unref (dt);
590  * ]|
591  *
592  * The return value of g_time_val_to_iso8601() has been nullable since GLib
593  * 2.54; before then, GLib would crash under the same conditions.
594  *
595  * Returns: (nullable): a newly allocated string containing an ISO 8601 date,
596  *    or %NULL if @time_ was too large
597  *
598  * Since: 2.12
599  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
600  *    g_date_time_format_iso8601(dt) instead.
601  */
602 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
603 gchar *
604 g_time_val_to_iso8601 (GTimeVal *time_)
605 {
606   gchar *retval;
607   struct tm *tm;
608 #ifdef HAVE_GMTIME_R
609   struct tm tm_;
610 #endif
611   time_t secs;
612
613   g_return_val_if_fail (time_ != NULL &&
614                         time_->tv_usec >= 0 &&
615                         time_->tv_usec < G_USEC_PER_SEC, NULL);
616
617   secs = time_->tv_sec;
618 #ifdef _WIN32
619   tm = gmtime (&secs);
620 #else
621 #ifdef HAVE_GMTIME_R
622   tm = gmtime_r (&secs, &tm_);
623 #else
624   tm = gmtime (&secs);
625 #endif
626 #endif
627
628   /* If the gmtime() call has failed, time_->tv_sec is too big. */
629   if (tm == NULL)
630     return NULL;
631
632   if (time_->tv_usec != 0)
633     {
634       /* ISO 8601 date and time format, with fractionary seconds:
635        *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
636        */
637       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
638                                 tm->tm_year + 1900,
639                                 tm->tm_mon + 1,
640                                 tm->tm_mday,
641                                 tm->tm_hour,
642                                 tm->tm_min,
643                                 tm->tm_sec,
644                                 time_->tv_usec);
645     }
646   else
647     {
648       /* ISO 8601 date and time format:
649        *   YYYY-MM-DDTHH:MM:SSZ
650        */
651       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
652                                 tm->tm_year + 1900,
653                                 tm->tm_mon + 1,
654                                 tm->tm_mday,
655                                 tm->tm_hour,
656                                 tm->tm_min,
657                                 tm->tm_sec);
658     }
659   
660   return retval;
661 }
662 G_GNUC_END_IGNORE_DEPRECATIONS