Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/pytime.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_initconfig.h"    // _PyStatus_ERR
3
#include "pycore_long.h"          // _PyLong_DivmodNear()
4
#include "pycore_pystate.h"       // _Py_AssertHoldsTstate()
5
#include "pycore_runtime.h"       // _PyRuntime
6
#include "pycore_time.h"          // export _PyLong_FromTime_t()
7
8
#include <time.h>                 // gmtime_r()
9
#ifdef HAVE_SYS_TIME_H
10
#  include <sys/time.h>           // gettimeofday()
11
#endif
12
#ifdef MS_WINDOWS
13
#  include <winsock2.h>           // struct timeval
14
#endif
15
16
#if defined(__APPLE__)
17
#  include <mach/mach_time.h>     // mach_absolute_time(), mach_timebase_info()
18
19
#if defined(__APPLE__) && defined(__has_builtin)
20
#  if __has_builtin(__builtin_available)
21
#    define HAVE_CLOCK_GETTIME_RUNTIME __builtin_available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
22
#  endif
23
#endif
24
#endif
25
26
/* To millisecond (10^-3) */
27
594k
#define SEC_TO_MS 1000
28
29
/* To microseconds (10^-6) */
30
594k
#define MS_TO_US 1000
31
0
#define SEC_TO_US (SEC_TO_MS * MS_TO_US)
32
33
/* To nanoseconds (10^-9) */
34
1.08M
#define US_TO_NS 1000
35
594k
#define MS_TO_NS (MS_TO_US * US_TO_NS)
36
594k
#define SEC_TO_NS (SEC_TO_MS * MS_TO_NS)
37
38
/* Conversion from nanoseconds */
39
0
#define NS_TO_MS (1000 * 1000)
40
0
#define NS_TO_US (1000)
41
#define NS_TO_100NS (100)
42
43
#if SIZEOF_TIME_T == SIZEOF_LONG_LONG
44
0
#  define PY_TIME_T_MAX LLONG_MAX
45
0
#  define PY_TIME_T_MIN LLONG_MIN
46
#elif SIZEOF_TIME_T == SIZEOF_LONG
47
#  define PY_TIME_T_MAX LONG_MAX
48
#  define PY_TIME_T_MIN LONG_MIN
49
#else
50
#  error "unsupported time_t size"
51
#endif
52
53
#if PY_TIME_T_MAX + PY_TIME_T_MIN != -1
54
#  error "time_t is not a two's complement integer type"
55
#endif
56
57
#if PyTime_MIN + PyTime_MAX != -1
58
#  error "PyTime_t is not a two's complement integer type"
59
#endif
60
61
62
static PyTime_t
63
_PyTime_GCD(PyTime_t x, PyTime_t y)
64
74
{
65
    // Euclidean algorithm
66
74
    assert(x >= 1);
67
74
    assert(y >= 1);
68
148
    while (y != 0) {
69
74
        PyTime_t tmp = y;
70
74
        y = x % y;
71
74
        x = tmp;
72
74
    }
73
74
    assert(x >= 1);
74
74
    return x;
75
74
}
76
77
78
int
79
_PyTimeFraction_Set(_PyTimeFraction *frac, PyTime_t numer, PyTime_t denom)
80
74
{
81
74
    if (numer < 1 || denom < 1) {
82
0
        return -1;
83
0
    }
84
85
74
    PyTime_t gcd = _PyTime_GCD(numer, denom);
86
74
    frac->numer = numer / gcd;
87
74
    frac->denom = denom / gcd;
88
74
    return 0;
89
74
}
90
91
92
double
93
_PyTimeFraction_Resolution(const _PyTimeFraction *frac)
94
0
{
95
0
    return (double)frac->numer / (double)frac->denom / 1e9;
96
0
}
97
98
99
static void
100
pytime_time_t_overflow(void)
101
0
{
102
0
    PyErr_SetString(PyExc_OverflowError,
103
0
                    "timestamp out of range for platform time_t");
104
0
}
105
106
107
static void
108
pytime_overflow(void)
109
0
{
110
0
    PyErr_SetString(PyExc_OverflowError,
111
0
                    "timestamp out of range for C PyTime_t");
112
0
}
113
114
115
// Compute t1 + t2. Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
116
static inline int
117
pytime_add(PyTime_t *t1, PyTime_t t2)
118
289k
{
119
289k
    if (t2 > 0 && *t1 > PyTime_MAX - t2) {
120
0
        *t1 = PyTime_MAX;
121
0
        return -1;
122
0
    }
123
289k
    else if (t2 < 0 && *t1 < PyTime_MIN - t2) {
124
0
        *t1 = PyTime_MIN;
125
0
        return -1;
126
0
    }
127
289k
    else {
128
289k
        *t1 += t2;
129
289k
        return 0;
130
289k
    }
131
289k
}
132
133
134
PyTime_t
135
_PyTime_Add(PyTime_t t1, PyTime_t t2)
136
0
{
137
0
    (void)pytime_add(&t1, t2);
138
0
    return t1;
139
0
}
140
141
142
static inline int
143
pytime_mul_check_overflow(PyTime_t a, PyTime_t b)
144
782k
{
145
782k
    if (b != 0) {
146
782k
        assert(b > 0);
147
782k
        return ((a < PyTime_MIN / b) || (PyTime_MAX / b < a));
148
782k
    }
149
0
    else {
150
0
        return 0;
151
0
    }
152
782k
}
153
154
155
// Compute t * k. Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
156
static inline int
157
pytime_mul(PyTime_t *t, PyTime_t k)
158
782k
{
159
782k
    assert(k >= 0);
160
782k
    if (pytime_mul_check_overflow(*t, k)) {
161
0
        *t = (*t >= 0) ? PyTime_MAX : PyTime_MIN;
162
0
        return -1;
163
0
    }
164
782k
    else {
165
782k
        *t *= k;
166
782k
        return 0;
167
782k
    }
168
782k
}
169
170
171
// Compute t * k. Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
172
static inline PyTime_t
173
_PyTime_Mul(PyTime_t t, PyTime_t k)
174
492k
{
175
492k
    (void)pytime_mul(&t, k);
176
492k
    return t;
177
492k
}
178
179
180
PyTime_t
181
_PyTimeFraction_Mul(PyTime_t ticks, const _PyTimeFraction *frac)
182
0
{
183
0
    const PyTime_t mul = frac->numer;
184
0
    const PyTime_t div = frac->denom;
185
186
0
    if (div == 1) {
187
        // Fast-path taken by mach_absolute_time() with 1/1 time base.
188
0
        return _PyTime_Mul(ticks, mul);
189
0
    }
190
191
    /* Compute (ticks * mul / div) in two parts to reduce the risk of integer
192
       overflow: compute the integer part, and then the remaining part.
193
194
       (ticks * mul) / div == (ticks / div) * mul + (ticks % div) * mul / div
195
    */
196
0
    PyTime_t intpart, remaining;
197
0
    intpart = ticks / div;
198
0
    ticks %= div;
199
0
    remaining = _PyTime_Mul(ticks, mul) / div;
200
    // intpart * mul + remaining
201
0
    return _PyTime_Add(_PyTime_Mul(intpart, mul), remaining);
202
0
}
203
204
205
time_t
206
_PyLong_AsTime_t(PyObject *obj)
207
0
{
208
0
#if SIZEOF_TIME_T == SIZEOF_LONG_LONG
209
0
    long long val = PyLong_AsLongLong(obj);
210
#elif SIZEOF_TIME_T <= SIZEOF_LONG
211
    long val = PyLong_AsLong(obj);
212
#else
213
#   error "unsupported time_t size"
214
#endif
215
0
    if (val == -1 && PyErr_Occurred()) {
216
0
        if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
217
0
            pytime_time_t_overflow();
218
0
        }
219
0
        return -1;
220
0
    }
221
0
    return (time_t)val;
222
0
}
223
224
225
PyObject *
226
_PyLong_FromTime_t(time_t t)
227
718k
{
228
718k
#if SIZEOF_TIME_T == SIZEOF_LONG_LONG
229
718k
    return PyLong_FromLongLong((long long)t);
230
#elif SIZEOF_TIME_T <= SIZEOF_LONG
231
    return PyLong_FromLong((long)t);
232
#else
233
#   error "unsupported time_t size"
234
#endif
235
718k
}
236
237
238
// Convert PyTime_t to time_t.
239
// Return 0 on success. Return -1 and clamp the value on overflow.
240
static int
241
_PyTime_AsTime_t(PyTime_t t, time_t *t2)
242
0
{
243
#if SIZEOF_TIME_T < _SIZEOF_PYTIME_T
244
    if ((PyTime_t)PY_TIME_T_MAX < t) {
245
        *t2 = PY_TIME_T_MAX;
246
        return -1;
247
    }
248
    if (t < (PyTime_t)PY_TIME_T_MIN) {
249
        *t2 = PY_TIME_T_MIN;
250
        return -1;
251
    }
252
#endif
253
0
    *t2 = (time_t)t;
254
0
    return 0;
255
0
}
256
257
258
#ifdef MS_WINDOWS
259
// Convert PyTime_t to long.
260
// Return 0 on success. Return -1 and clamp the value on overflow.
261
static int
262
_PyTime_AsCLong(PyTime_t t, long *t2)
263
{
264
#if SIZEOF_LONG < _SIZEOF_PYTIME_T
265
    if ((PyTime_t)LONG_MAX < t) {
266
        *t2 = LONG_MAX;
267
        return -1;
268
    }
269
    if (t < (PyTime_t)LONG_MIN) {
270
        *t2 = LONG_MIN;
271
        return -1;
272
    }
273
#endif
274
    *t2 = (long)t;
275
    return 0;
276
}
277
278
// Seconds between 1601-01-01 and 1970-01-01:
279
// 369 years + 89 leap days.
280
#define SECS_BETWEEN_EPOCHS 11644473600LL
281
#define HUNDRED_NS_PER_SEC 10000000LL
282
283
// Calculate day of year (0-365) from SYSTEMTIME
284
static int
285
_PyTime_calc_yday(const SYSTEMTIME *st)
286
{
287
    // Cumulative days before each month (non-leap year)
288
    static const int days_before_month[] = {
289
        0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
290
    };
291
    int yday = days_before_month[st->wMonth - 1] + st->wDay - 1;
292
    // Account for leap day if we're past February in a leap year.
293
    if (st->wMonth > 2) {
294
        // Leap year rules (Gregorian calendar):
295
        // - Years divisible by 4 are leap years
296
        // - EXCEPT years divisible by 100 are NOT leap years
297
        // - EXCEPT years divisible by 400 ARE leap years
298
        int year = st->wYear;
299
        int is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
300
        yday += is_leap;
301
    }
302
    return yday;
303
}
304
305
// Convert time_t to struct tm using Windows FILETIME API.
306
// If is_local is true, convert to local time.
307
// Fallback for negative timestamps that localtime_s/gmtime_s cannot handle.
308
// Return 0 on success. Return -1 on error.
309
static int
310
_PyTime_windows_filetime(time_t timer, struct tm *tm, int is_local)
311
{
312
    /* Check for underflow - FILETIME epoch is 1601-01-01 */
313
    if (timer < -SECS_BETWEEN_EPOCHS) {
314
        PyErr_SetString(PyExc_OverflowError, "timestamp out of range for Windows FILETIME");
315
        return -1;
316
    }
317
318
    /* Convert time_t to FILETIME (100-nanosecond intervals since 1601-01-01) */
319
    ULONGLONG ticks = ((ULONGLONG)timer + SECS_BETWEEN_EPOCHS) * HUNDRED_NS_PER_SEC;
320
    FILETIME ft;
321
    ft.dwLowDateTime = (DWORD)(ticks); // cast to DWORD truncates to low 32 bits
322
    ft.dwHighDateTime = (DWORD)(ticks >> 32);
323
324
    /* Convert FILETIME to SYSTEMTIME (UTC) */
325
    SYSTEMTIME st_utc;
326
    if (!FileTimeToSystemTime(&ft, &st_utc)) {
327
        PyErr_SetFromWindowsErr(0);
328
        return -1;
329
    }
330
331
    SYSTEMTIME st_result;
332
    if (is_local) {
333
        /* Convert UTC SYSTEMTIME to local SYSTEMTIME.
334
         * We use SystemTimeToTzSpecificLocalTime instead of
335
         * FileTimeToLocalFileTime because the latter always applies the
336
         * _current_ DST bias, whereas the former applies the correct
337
         * DST rules for the date being converted (gh-80620). */
338
        if (!SystemTimeToTzSpecificLocalTime(NULL, &st_utc, &st_result)) {
339
            PyErr_SetFromWindowsErr(0);
340
            return -1;
341
        }
342
    }
343
    else {
344
        st_result = st_utc;
345
    }
346
347
    /* Convert SYSTEMTIME to struct tm */
348
    tm->tm_year = st_result.wYear - 1900;
349
    tm->tm_mon = st_result.wMonth - 1; /* SYSTEMTIME: 1-12, tm: 0-11 */
350
    tm->tm_mday = st_result.wDay;
351
    tm->tm_hour = st_result.wHour;
352
    tm->tm_min = st_result.wMinute;
353
    tm->tm_sec = st_result.wSecond;
354
    tm->tm_wday = st_result.wDayOfWeek; /* 0=Sunday */
355
356
    // `time.gmtime` and `time.localtime` will return `struct_time` containing this
357
    tm->tm_yday = _PyTime_calc_yday(&st_result);
358
359
    /* DST flag: -1 (unknown) for local time on historical dates, 0 for UTC */
360
    tm->tm_isdst = is_local ? -1 : 0;
361
362
    return 0;
363
}
364
#endif
365
366
367
/* Round to nearest with ties going to nearest even integer
368
   (_PyTime_ROUND_HALF_EVEN) */
369
static double
370
pytime_round_half_even(double x)
371
0
{
372
0
    double rounded = round(x);
373
0
    if (fabs(x-rounded) == 0.5) {
374
        /* halfway case: round to even */
375
0
        rounded = 2.0 * round(x / 2.0);
376
0
    }
377
0
    return rounded;
378
0
}
379
380
381
static double
382
pytime_round(double x, _PyTime_round_t round)
383
0
{
384
    /* volatile avoids optimization changing how numbers are rounded */
385
0
    volatile double d;
386
387
0
    d = x;
388
0
    if (round == _PyTime_ROUND_HALF_EVEN) {
389
0
        d = pytime_round_half_even(d);
390
0
    }
391
0
    else if (round == _PyTime_ROUND_CEILING) {
392
0
        d = ceil(d);
393
0
    }
394
0
    else if (round == _PyTime_ROUND_FLOOR) {
395
0
        d = floor(d);
396
0
    }
397
0
    else {
398
0
        assert(round == _PyTime_ROUND_UP);
399
0
        d = (d >= 0.0) ? ceil(d) : floor(d);
400
0
    }
401
0
    return d;
402
0
}
403
404
405
static int
406
pytime_double_to_denominator(double d, time_t *sec, long *numerator,
407
                             long idenominator, _PyTime_round_t round)
408
0
{
409
0
    double denominator = (double)idenominator;
410
0
    double intpart;
411
    /* volatile avoids optimization changing how numbers are rounded */
412
0
    volatile double floatpart;
413
414
0
    floatpart = modf(d, &intpart);
415
416
0
    floatpart *= denominator;
417
0
    floatpart = pytime_round(floatpart, round);
418
0
    if (floatpart >= denominator) {
419
0
        floatpart -= denominator;
420
0
        intpart += 1.0;
421
0
    }
422
0
    else if (floatpart < 0) {
423
0
        floatpart += denominator;
424
0
        intpart -= 1.0;
425
0
    }
426
0
    assert(0.0 <= floatpart && floatpart < denominator);
427
428
    /*
429
       Conversion of an out-of-range value to time_t gives undefined behaviour
430
       (C99 §6.3.1.4p1), so we must guard against it. However, checking that
431
       `intpart` is in range is delicate: the obvious expression `intpart <=
432
       PY_TIME_T_MAX` will first convert the value `PY_TIME_T_MAX` to a double,
433
       potentially changing its value and leading to us failing to catch some
434
       UB-inducing values. The code below works correctly under the mild
435
       assumption that time_t is a two's complement integer type with no trap
436
       representation, and that `PY_TIME_T_MIN` is within the representable
437
       range of a C double.
438
439
       Note: we want the `if` condition below to be true for NaNs; therefore,
440
       resist any temptation to simplify by applying De Morgan's laws.
441
    */
442
0
    if (!((double)PY_TIME_T_MIN <= intpart && intpart < -(double)PY_TIME_T_MIN)) {
443
0
        pytime_time_t_overflow();
444
0
        return -1;
445
0
    }
446
0
    *sec = (time_t)intpart;
447
0
    *numerator = (long)floatpart;
448
0
    assert(0 <= *numerator && *numerator < idenominator);
449
0
    return 0;
450
0
}
451
452
453
/* Convert a number to a fraction representation.
454
 *
455
 * Set *ratio to a 2-tuple (numerator, denominator) and return 1 on success.
456
 * Set *ratio to NULL and return 0 if the number has neither the
457
 * as_integer_ratio() method nor the numerator and denominator attributes.
458
 * Return -1 on error.
459
 */
460
static int
461
maybe_as_integer_ratio(PyObject *number, PyObject **ratio)
462
0
{
463
0
    *ratio = NULL;
464
0
    if (PyType_Check(number)) {
465
0
        PyErr_Format(PyExc_TypeError,
466
0
                     "must be real number, not %T", number);
467
0
        return -1;
468
0
    }
469
0
    PyObject *meth;
470
0
    if (PyObject_GetOptionalAttr(number, &_Py_ID(as_integer_ratio), &meth) < 0) {
471
0
        return -1;
472
0
    }
473
0
    if (meth) {
474
0
        *ratio = PyObject_CallNoArgs(meth);
475
0
        Py_DECREF(meth);
476
0
        if (*ratio == NULL) {
477
0
            return -1;
478
0
        }
479
0
        if (!PyTuple_Check(*ratio)) {
480
0
            PyErr_Format(PyExc_TypeError,
481
0
                         "unexpected return type from %T.as_integer_ratio(): "
482
0
                         "expected tuple, not '%T'",
483
0
                         number, *ratio);
484
0
            Py_CLEAR(*ratio);
485
0
            return -1;
486
0
        }
487
0
        if (PyTuple_GET_SIZE(*ratio) != 2) {
488
0
            PyErr_Format(PyExc_ValueError,
489
0
                         "%T.as_integer_ratio() must return a 2-tuple",
490
0
                         number);
491
0
            Py_CLEAR(*ratio);
492
0
            return -1;
493
0
        }
494
0
        return 1;
495
0
    }
496
497
0
    PyObject *numerator, *denominator;
498
0
    int rc = PyObject_GetOptionalAttr(number, &_Py_ID(numerator), &numerator);
499
0
    if (rc <= 0) {
500
0
        return rc;
501
0
    }
502
0
    rc = PyObject_GetOptionalAttr(number, &_Py_ID(denominator), &denominator);
503
0
    if (rc <= 0) {
504
0
        Py_DECREF(numerator);
505
0
        return rc;
506
0
    }
507
0
    *ratio = PyTuple_Pack(2, numerator, denominator);
508
0
    Py_DECREF(numerator);
509
0
    Py_DECREF(denominator);
510
0
    return *ratio ? 1 : -1;
511
0
}
512
513
/* PyNumber_Divmod() that always returns a 2-tuple. */
514
static PyObject *
515
checked_divmod(PyObject *a, PyObject *b)
516
0
{
517
0
    PyObject *result = PyNumber_Divmod(a, b);
518
0
    if (result == NULL) {
519
0
        return NULL;
520
0
    }
521
0
    if (!PyTuple_Check(result)) {
522
0
        PyErr_Format(PyExc_TypeError,
523
0
                     "divmod() returned non-tuple (type %T)",
524
0
                     result);
525
0
        Py_DECREF(result);
526
0
        return NULL;
527
0
    }
528
0
    if (PyTuple_GET_SIZE(result) != 2) {
529
0
        PyErr_Format(PyExc_TypeError,
530
0
                     "divmod() returned a tuple of size %zd",
531
0
                     PyTuple_GET_SIZE(result));
532
0
        Py_DECREF(result);
533
0
        return NULL;
534
0
    }
535
0
    return result;
536
0
}
537
538
/* Calculate numerator / denominator rounded to integer using
539
 * the specified rounding mode. */
540
static PyObject *
541
divide_and_round(PyObject *numerator, PyObject *denominator, _PyTime_round_t round)
542
0
{
543
0
    if (round == _PyTime_ROUND_UP) {
544
0
        int isneg = PyObject_RichCompareBool(numerator, _PyLong_GetZero(), Py_LT);
545
0
        if (isneg < 0) {
546
0
            return NULL;
547
0
        }
548
0
        round = isneg ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING;
549
0
    }
550
551
0
    if (round == _PyTime_ROUND_FLOOR) {
552
0
        return PyNumber_FloorDivide(numerator, denominator);
553
0
    }
554
555
0
    PyObject *divmod, *result;
556
0
    if (round == _PyTime_ROUND_CEILING) {
557
0
        divmod = checked_divmod(numerator, denominator);
558
0
        if (divmod == NULL) {
559
0
            return NULL;
560
0
        }
561
0
        int nonzero = PyObject_IsTrue(PyTuple_GET_ITEM(divmod, 1));
562
0
        if (nonzero < 0) {
563
0
            result = NULL;
564
0
        }
565
0
        else if (nonzero) {
566
0
            result = PyNumber_Add(PyTuple_GET_ITEM(divmod, 0), _PyLong_GetOne());
567
0
        }
568
0
        else {
569
0
            result = Py_NewRef(PyTuple_GET_ITEM(divmod, 0));
570
0
        }
571
0
    }
572
0
    else {
573
0
        assert(round == _PyTime_ROUND_HALF_EVEN);
574
0
        divmod = _PyLong_DivmodNear(numerator, denominator);
575
0
        if (divmod == NULL) {
576
0
            return NULL;
577
0
        }
578
0
        result = Py_NewRef(PyTuple_GET_ITEM(divmod, 0));
579
0
    }
580
0
    Py_DECREF(divmod);
581
0
    return result;
582
0
}
583
584
/* Calculate scale * numerator / denominator rounded to integer using
585
 * the specified rounding mode. */
586
static PyObject *
587
multiply_divide_and_round(long scale, PyObject *numerator, PyObject *denominator,
588
                          _PyTime_round_t round)
589
0
{
590
0
    PyObject *scaleobj = PyLong_FromLong(scale);
591
0
    if (scaleobj == NULL) {
592
0
        return NULL;
593
0
    }
594
0
    numerator = PyNumber_Multiply(numerator, scaleobj);
595
0
    Py_DECREF(scaleobj);
596
0
    if (numerator == NULL) {
597
0
        return NULL;
598
0
    }
599
0
    PyObject *result = divide_and_round(numerator, denominator, round);
600
0
    Py_DECREF(numerator);
601
0
    return result;
602
0
}
603
604
static int
605
pytime_ratio_to_denominator(PyObject *numerator, PyObject *denominator,
606
                            time_t *sec, long *subsec,
607
                            long scale, _PyTime_round_t round)
608
0
{
609
0
    PyObject *divmod = checked_divmod(numerator, denominator);
610
0
    if (divmod == NULL) {
611
0
        return -1;
612
0
    }
613
0
    *sec = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
614
0
    if (*sec == (time_t)-1 && PyErr_Occurred()) {
615
0
        Py_DECREF(divmod);
616
0
        return -1;
617
0
    }
618
0
    if (round == _PyTime_ROUND_UP) {
619
        /* The remainder is non-negative, so the direction of rounding
620
           depends on the sign of the whole number. */
621
0
        round = *sec < 0 ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING;
622
0
    }
623
0
    PyObject *tmp = multiply_divide_and_round(scale,
624
0
                                              PyTuple_GET_ITEM(divmod, 1),
625
0
                                              denominator,
626
0
                                              round);
627
0
    Py_DECREF(divmod);
628
0
    if (tmp == NULL) {
629
0
        return -1;
630
0
    }
631
0
    *subsec = PyLong_AsLong(tmp);
632
0
    Py_DECREF(tmp);
633
0
    if (*subsec == -1 && PyErr_Occurred()) {
634
0
        return -1;
635
0
    }
636
0
    if (*subsec < 0) {
637
0
        *subsec += scale;
638
0
        if (*sec <= PY_TIME_T_MIN) {
639
0
            pytime_time_t_overflow();
640
0
            return -1;
641
0
        }
642
0
        *sec -= 1;
643
0
    }
644
0
    else if (*subsec >= scale) {
645
0
        *subsec -= scale;
646
0
        if (*sec >= PY_TIME_T_MAX) {
647
0
            pytime_time_t_overflow();
648
0
            return -1;
649
0
        }
650
0
        *sec += 1;
651
0
    }
652
0
    return 0;
653
0
}
654
655
656
static int
657
pytime_pyfloat_to_denominator(PyObject *obj, time_t *sec, long *numerator,
658
                              long denominator, _PyTime_round_t round)
659
0
{
660
0
    double d = PyFloat_AsDouble(obj);
661
0
    if (d == -1 && PyErr_Occurred()) {
662
0
        return -1;
663
0
    }
664
0
    if (isnan(d)) {
665
0
        PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
666
0
        return -1;
667
0
    }
668
0
    return pytime_double_to_denominator(d, sec, numerator,
669
0
                                        denominator, round);
670
0
}
671
672
673
static int
674
pytime_object_to_denominator(PyObject *obj, time_t *sec, long *numerator,
675
                             long denominator, _PyTime_round_t round)
676
0
{
677
0
    assert(denominator >= 1);
678
679
0
    *numerator = 0;
680
0
    if (PyIndex_Check(obj)) {
681
0
        *sec = _PyLong_AsTime_t(obj);
682
0
        if (*sec == (time_t)-1 && PyErr_Occurred()) {
683
0
            return -1;
684
0
        }
685
0
        return 0;
686
0
    }
687
0
    else if (PyFloat_Check(obj)) {
688
0
        return pytime_pyfloat_to_denominator(obj, sec, numerator,
689
0
                                             denominator, round);
690
0
    }
691
0
    else {
692
0
        PyObject *ratio;
693
0
        if (maybe_as_integer_ratio(obj, &ratio) < 0) {
694
0
            return -1;
695
0
        }
696
0
        if (ratio == NULL) {
697
0
            return pytime_pyfloat_to_denominator(obj, sec, numerator,
698
0
                                                 denominator, round);
699
0
        }
700
0
        int rc = pytime_ratio_to_denominator(PyTuple_GET_ITEM(ratio, 0),
701
0
                                             PyTuple_GET_ITEM(ratio, 1),
702
0
                                             sec, numerator,
703
0
                                             denominator, round);
704
0
        Py_DECREF(ratio);
705
0
        return rc;
706
0
    }
707
0
}
708
709
710
static int
711
pytime_pyfloat_to_time_t(PyObject *obj, time_t *sec, _PyTime_round_t round)
712
0
{
713
0
    double intpart;
714
    /* volatile avoids optimization changing how numbers are rounded */
715
0
    volatile double d;
716
717
0
    d = PyFloat_AsDouble(obj);
718
0
    if (d == -1 && PyErr_Occurred()) {
719
0
        return -1;
720
0
    }
721
0
    if (isnan(d)) {
722
0
        PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
723
0
        return -1;
724
0
    }
725
726
0
    d = pytime_round(d, round);
727
0
    (void)modf(d, &intpart);
728
729
    /* See comments in pytime_double_to_denominator */
730
0
    if (!((double)PY_TIME_T_MIN <= intpart && intpart < -(double)PY_TIME_T_MIN)) {
731
0
        pytime_time_t_overflow();
732
0
        return -1;
733
0
    }
734
0
    *sec = (time_t)intpart;
735
0
    return 0;
736
0
}
737
738
739
int
740
_PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round)
741
0
{
742
0
    if (PyIndex_Check(obj)) {
743
0
        *sec = _PyLong_AsTime_t(obj);
744
0
        if (*sec == (time_t)-1 && PyErr_Occurred()) {
745
0
            return -1;
746
0
        }
747
0
        return 0;
748
0
    }
749
0
    else if (PyFloat_Check(obj)) {
750
0
        return pytime_pyfloat_to_time_t(obj, sec, round);
751
0
    }
752
0
    else {
753
0
        PyObject *ratio;
754
0
        if (maybe_as_integer_ratio(obj, &ratio) < 0) {
755
0
            return -1;
756
0
        }
757
0
        if (ratio == NULL) {
758
0
            return pytime_pyfloat_to_time_t(obj, sec, round);
759
0
        }
760
0
        PyObject *secobj = divide_and_round(PyTuple_GET_ITEM(ratio, 0),
761
0
                                            PyTuple_GET_ITEM(ratio, 1),
762
0
                                            round);
763
0
        Py_DECREF(ratio);
764
0
        if (secobj == NULL) {
765
0
            return -1;
766
0
        }
767
0
        *sec = _PyLong_AsTime_t(secobj);
768
0
        Py_DECREF(secobj);
769
0
        if (*sec == (time_t)-1 && PyErr_Occurred()) {
770
0
            return -1;
771
0
        }
772
0
        return 0;
773
0
    }
774
0
}
775
776
777
int
778
_PyTime_ObjectToTimespec(PyObject *obj, time_t *sec, long *nsec,
779
                         _PyTime_round_t round)
780
0
{
781
0
    return pytime_object_to_denominator(obj, sec, nsec, SEC_TO_NS, round);
782
0
}
783
784
785
int
786
_PyTime_ObjectToTimeval(PyObject *obj, time_t *sec, long *usec,
787
                        _PyTime_round_t round)
788
0
{
789
0
    return pytime_object_to_denominator(obj, sec, usec, SEC_TO_US, round);
790
0
}
791
792
793
PyTime_t
794
_PyTime_FromSeconds(int seconds)
795
151k
{
796
    /* ensure that integer overflow cannot happen, int type should have 32
797
       bits, whereas PyTime_t type has at least 64 bits (SEC_TO_NS takes 30
798
       bits). */
799
151k
    static_assert(INT_MAX <= PyTime_MAX / SEC_TO_NS, "PyTime_t overflow");
800
151k
    static_assert(INT_MIN >= PyTime_MIN / SEC_TO_NS, "PyTime_t underflow");
801
802
151k
    PyTime_t t = (PyTime_t)seconds;
803
151k
    assert((t >= 0 && t <= PyTime_MAX / SEC_TO_NS)
804
151k
           || (t < 0 && t >= PyTime_MIN / SEC_TO_NS));
805
151k
    t *= SEC_TO_NS;
806
151k
    return t;
807
151k
}
808
809
810
PyTime_t
811
_PyTime_FromMicrosecondsClamp(PyTime_t us)
812
492k
{
813
492k
    PyTime_t ns = _PyTime_Mul(us, US_TO_NS);
814
492k
    return ns;
815
492k
}
816
817
818
#ifdef HAVE_CLOCK_GETTIME
819
static int
820
pytime_fromtimespec(PyTime_t *tp, const struct timespec *ts, int raise_exc)
821
289k
{
822
289k
    PyTime_t t, tv_nsec;
823
824
289k
    static_assert(sizeof(ts->tv_sec) <= sizeof(PyTime_t),
825
289k
                  "timespec.tv_sec is larger than PyTime_t");
826
289k
    t = (PyTime_t)ts->tv_sec;
827
828
289k
    int res1 = pytime_mul(&t, SEC_TO_NS);
829
830
289k
    tv_nsec = ts->tv_nsec;
831
289k
    int res2 = pytime_add(&t, tv_nsec);
832
833
289k
    *tp = t;
834
835
289k
    if (raise_exc && (res1 < 0 || res2 < 0)) {
836
0
        pytime_overflow();
837
0
        return -1;
838
0
    }
839
289k
    return 0;
840
289k
}
841
842
int
843
_PyTime_FromTimespec(PyTime_t *tp, const struct timespec *ts)
844
0
{
845
0
    return pytime_fromtimespec(tp, ts, 1);
846
0
}
847
#endif
848
849
850
#ifndef MS_WINDOWS
851
static int
852
pytime_fromtimeval(PyTime_t *tp, struct timeval *tv, int raise_exc)
853
0
{
854
0
    static_assert(sizeof(tv->tv_sec) <= sizeof(PyTime_t),
855
0
                  "timeval.tv_sec is larger than PyTime_t");
856
0
    PyTime_t t = (PyTime_t)tv->tv_sec;
857
858
0
    int res1 = pytime_mul(&t, SEC_TO_NS);
859
860
0
    PyTime_t usec = (PyTime_t)tv->tv_usec * US_TO_NS;
861
0
    int res2 = pytime_add(&t, usec);
862
863
0
    *tp = t;
864
865
0
    if (raise_exc && (res1 < 0 || res2 < 0)) {
866
0
        pytime_overflow();
867
0
        return -1;
868
0
    }
869
0
    return 0;
870
0
}
871
872
873
int
874
_PyTime_FromTimeval(PyTime_t *tp, struct timeval *tv)
875
0
{
876
0
    return pytime_fromtimeval(tp, tv, 1);
877
0
}
878
#endif
879
880
881
static int
882
pytime_from_double(PyTime_t *tp, double value, _PyTime_round_t round,
883
                   long unit_to_ns)
884
0
{
885
    /* volatile avoids optimization changing how numbers are rounded */
886
0
    volatile double d;
887
888
    /* convert to a number of nanoseconds */
889
0
    d = value;
890
0
    d *= (double)unit_to_ns;
891
0
    d = pytime_round(d, round);
892
893
    /* See comments in pytime_double_to_denominator */
894
0
    if (!((double)PyTime_MIN <= d && d < -(double)PyTime_MIN)) {
895
0
        pytime_overflow();
896
0
        *tp = 0;
897
0
        return -1;
898
0
    }
899
0
    PyTime_t ns = (PyTime_t)d;
900
901
0
    *tp = ns;
902
0
    return 0;
903
0
}
904
905
906
static int
907
pytime_from_pyfloat(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
908
                    long unit_to_ns)
909
0
{
910
0
    double d = PyFloat_AsDouble(obj);
911
0
    if (d == -1 && PyErr_Occurred()) {
912
0
        return -1;
913
0
    }
914
0
    if (isnan(d)) {
915
0
        PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
916
0
        return -1;
917
0
    }
918
0
    return pytime_from_double(tp, d, round, unit_to_ns);
919
0
}
920
921
922
static int
923
pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
924
                   long unit_to_ns)
925
0
{
926
0
    if (PyIndex_Check(obj)) {
927
0
        long long sec = PyLong_AsLongLong(obj);
928
0
        if (sec == -1 && PyErr_Occurred()) {
929
0
            if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
930
0
                pytime_overflow();
931
0
            }
932
0
            return -1;
933
0
        }
934
935
0
        static_assert(sizeof(long long) <= sizeof(PyTime_t),
936
0
                    "PyTime_t is smaller than long long");
937
0
        PyTime_t ns = (PyTime_t)sec;
938
0
        if (pytime_mul(&ns, unit_to_ns) < 0) {
939
0
            pytime_overflow();
940
0
            return -1;
941
0
        }
942
943
0
        *tp = ns;
944
0
        return 0;
945
0
    }
946
0
    else if (PyFloat_Check(obj)) {
947
0
        return pytime_from_pyfloat(tp, obj, round, unit_to_ns);
948
0
    }
949
0
    else {
950
0
        PyObject *ratio;
951
0
        if (maybe_as_integer_ratio(obj, &ratio) < 0) {
952
0
            return -1;
953
0
        }
954
0
        if (ratio == NULL) {
955
0
            return pytime_from_pyfloat(tp, obj, round, unit_to_ns);
956
0
        }
957
0
        PyObject *divmod = checked_divmod(PyTuple_GET_ITEM(ratio, 0),
958
0
                                          PyTuple_GET_ITEM(ratio, 1));
959
0
        if (divmod == NULL) {
960
0
            Py_DECREF(ratio);
961
0
            return -1;
962
0
        }
963
0
        PyTime_t units;
964
0
        if (PyLong_AsInt64(PyTuple_GET_ITEM(divmod, 0), &units) < 0) {
965
0
            Py_DECREF(divmod);
966
0
            Py_DECREF(ratio);
967
0
            if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
968
0
                pytime_overflow();
969
0
            }
970
0
            return -1;
971
0
        }
972
0
        if (round == _PyTime_ROUND_UP) {
973
            /* The remainder is non-negative, so the direction of rounding
974
               depends on the sign of the whole number. */
975
0
            round = units < 0 ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING;
976
0
        }
977
0
        PyObject *fracobj = multiply_divide_and_round(
978
0
                unit_to_ns, PyTuple_GET_ITEM(divmod, 1),
979
0
                PyTuple_GET_ITEM(ratio, 1), round);
980
0
        Py_DECREF(divmod);
981
0
        Py_DECREF(ratio);
982
0
        if (fracobj == NULL) {
983
0
            return -1;
984
0
        }
985
0
        long frac = PyLong_AsLong(fracobj);
986
0
        Py_DECREF(fracobj);
987
0
        if (frac == -1 && PyErr_Occurred()) {
988
0
            return -1;
989
0
        }
990
0
        if (units < 0 && frac > 0) {
991
            /* Avoid a spurious overflow near PyTime_MIN. */
992
0
            units += 1;
993
0
            frac -= unit_to_ns;
994
0
        }
995
0
        if (pytime_mul(&units, unit_to_ns) < 0
996
0
            || pytime_add(&units, frac) < 0)
997
0
        {
998
0
            pytime_overflow();
999
0
            return -1;
1000
0
        }
1001
0
        *tp = units;
1002
0
        return 0;
1003
0
    }
1004
0
}
1005
1006
1007
int
1008
_PyTime_FromSecondsObject(PyTime_t *tp, PyObject *obj, _PyTime_round_t round)
1009
0
{
1010
0
    return pytime_from_object(tp, obj, round, SEC_TO_NS);
1011
0
}
1012
1013
1014
int
1015
_PyTime_FromMillisecondsObject(PyTime_t *tp, PyObject *obj, _PyTime_round_t round)
1016
0
{
1017
0
    return pytime_from_object(tp, obj, round, MS_TO_NS);
1018
0
}
1019
1020
1021
double
1022
PyTime_AsSecondsDouble(PyTime_t ns)
1023
152k
{
1024
    /* volatile avoids optimization changing how numbers are rounded */
1025
152k
    volatile double d;
1026
1027
152k
    if (ns % SEC_TO_NS == 0) {
1028
        /* Divide using integers to avoid rounding issues on the integer part.
1029
           1e-9 cannot be stored exactly in IEEE 64-bit. */
1030
0
        PyTime_t secs = ns / SEC_TO_NS;
1031
0
        d = (double)secs;
1032
0
    }
1033
152k
    else {
1034
152k
        d = (double)ns;
1035
152k
        d /= 1e9;
1036
152k
    }
1037
152k
    return d;
1038
152k
}
1039
1040
1041
int
1042
_PyTime_FromSecondsDouble(double seconds, _PyTime_round_t round, PyTime_t *result)
1043
0
{
1044
0
    return pytime_from_double(result, seconds, round, SEC_TO_NS);
1045
0
}
1046
1047
1048
static PyTime_t
1049
pytime_divide_round_up(const PyTime_t t, const PyTime_t k)
1050
0
{
1051
0
    assert(k > 1);
1052
0
    if (t >= 0) {
1053
        // Don't use (t + k - 1) / k to avoid integer overflow
1054
        // if t is equal to PyTime_MAX
1055
0
        PyTime_t q = t / k;
1056
0
        if (t % k) {
1057
0
            q += 1;
1058
0
        }
1059
0
        return q;
1060
0
    }
1061
0
    else {
1062
        // Don't use (t - (k - 1)) / k to avoid integer overflow
1063
        // if t is equals to PyTime_MIN.
1064
0
        PyTime_t q = t / k;
1065
0
        if (t % k) {
1066
0
            q -= 1;
1067
0
        }
1068
0
        return q;
1069
0
    }
1070
0
}
1071
1072
1073
static PyTime_t
1074
pytime_divide(const PyTime_t t, const PyTime_t k,
1075
              const _PyTime_round_t round)
1076
0
{
1077
0
    assert(k > 1);
1078
0
    if (round == _PyTime_ROUND_HALF_EVEN) {
1079
0
        PyTime_t x = t / k;
1080
0
        PyTime_t r = t % k;
1081
0
        PyTime_t abs_r = Py_ABS(r);
1082
0
        if (abs_r > k / 2 || (abs_r == k / 2 && (Py_ABS(x) & 1))) {
1083
0
            if (t >= 0) {
1084
0
                x++;
1085
0
            }
1086
0
            else {
1087
0
                x--;
1088
0
            }
1089
0
        }
1090
0
        return x;
1091
0
    }
1092
0
    else if (round == _PyTime_ROUND_CEILING) {
1093
0
        if (t >= 0) {
1094
0
            return pytime_divide_round_up(t, k);
1095
0
        }
1096
0
        else {
1097
0
            return t / k;
1098
0
        }
1099
0
    }
1100
0
    else if (round == _PyTime_ROUND_FLOOR){
1101
0
        if (t >= 0) {
1102
0
            return t / k;
1103
0
        }
1104
0
        else {
1105
0
            return pytime_divide_round_up(t, k);
1106
0
        }
1107
0
    }
1108
0
    else {
1109
0
        assert(round == _PyTime_ROUND_UP);
1110
0
        return pytime_divide_round_up(t, k);
1111
0
    }
1112
0
}
1113
1114
1115
// Compute (t / k, t % k) in (pq, pr).
1116
// Make sure that 0 <= pr < k.
1117
// Return 0 on success.
1118
// Return -1 on underflow and store (PyTime_MIN, 0) in (pq, pr).
1119
static int
1120
pytime_divmod(const PyTime_t t, const PyTime_t k,
1121
              PyTime_t *pq, PyTime_t *pr)
1122
0
{
1123
0
    assert(k > 1);
1124
0
    PyTime_t q = t / k;
1125
0
    PyTime_t r = t % k;
1126
0
    if (r < 0) {
1127
0
        if (q == PyTime_MIN) {
1128
0
            *pq = PyTime_MIN;
1129
0
            *pr = 0;
1130
0
            return -1;
1131
0
        }
1132
0
        r += k;
1133
0
        q -= 1;
1134
0
    }
1135
0
    assert(0 <= r && r < k);
1136
1137
0
    *pq = q;
1138
0
    *pr = r;
1139
0
    return 0;
1140
0
}
1141
1142
1143
#ifdef MS_WINDOWS
1144
PyTime_t
1145
_PyTime_As100Nanoseconds(PyTime_t ns, _PyTime_round_t round)
1146
{
1147
    return pytime_divide(ns, NS_TO_100NS, round);
1148
}
1149
#endif
1150
1151
1152
PyTime_t
1153
_PyTime_AsMicroseconds(PyTime_t ns, _PyTime_round_t round)
1154
0
{
1155
0
    return pytime_divide(ns, NS_TO_US, round);
1156
0
}
1157
1158
1159
PyTime_t
1160
_PyTime_AsMilliseconds(PyTime_t ns, _PyTime_round_t round)
1161
0
{
1162
0
    return pytime_divide(ns, NS_TO_MS, round);
1163
0
}
1164
1165
1166
static int
1167
pytime_as_timeval(PyTime_t ns, PyTime_t *ptv_sec, int *ptv_usec,
1168
                  _PyTime_round_t round)
1169
0
{
1170
0
    PyTime_t us = pytime_divide(ns, US_TO_NS, round);
1171
1172
0
    PyTime_t tv_sec, tv_usec;
1173
0
    int res = pytime_divmod(us, SEC_TO_US, &tv_sec, &tv_usec);
1174
0
    *ptv_sec = tv_sec;
1175
0
    *ptv_usec = (int)tv_usec;
1176
0
    return res;
1177
0
}
1178
1179
1180
static int
1181
pytime_as_timeval_struct(PyTime_t t, struct timeval *tv,
1182
                         _PyTime_round_t round, int raise_exc)
1183
0
{
1184
0
    PyTime_t tv_sec;
1185
0
    int tv_usec;
1186
0
    int res = pytime_as_timeval(t, &tv_sec, &tv_usec, round);
1187
0
    int res2;
1188
#ifdef MS_WINDOWS
1189
    // On Windows, timeval.tv_sec type is long
1190
    res2 = _PyTime_AsCLong(tv_sec, &tv->tv_sec);
1191
#else
1192
0
    res2 = _PyTime_AsTime_t(tv_sec, &tv->tv_sec);
1193
0
#endif
1194
0
    if (res2 < 0) {
1195
0
        tv_usec = 0;
1196
0
    }
1197
0
    tv->tv_usec = tv_usec;
1198
1199
0
    if (raise_exc && (res < 0 || res2 < 0)) {
1200
0
        pytime_time_t_overflow();
1201
0
        return -1;
1202
0
    }
1203
0
    return 0;
1204
0
}
1205
1206
1207
int
1208
_PyTime_AsTimeval(PyTime_t t, struct timeval *tv, _PyTime_round_t round)
1209
0
{
1210
0
    return pytime_as_timeval_struct(t, tv, round, 1);
1211
0
}
1212
1213
1214
void
1215
_PyTime_AsTimeval_clamp(PyTime_t t, struct timeval *tv, _PyTime_round_t round)
1216
0
{
1217
0
    (void)pytime_as_timeval_struct(t, tv, round, 0);
1218
0
}
1219
1220
1221
int
1222
_PyTime_AsTimevalTime_t(PyTime_t t, time_t *p_secs, int *us,
1223
                        _PyTime_round_t round)
1224
0
{
1225
0
    PyTime_t secs;
1226
0
    if (pytime_as_timeval(t, &secs, us, round) < 0) {
1227
0
        pytime_time_t_overflow();
1228
0
        return -1;
1229
0
    }
1230
1231
0
    if (_PyTime_AsTime_t(secs, p_secs) < 0) {
1232
0
        pytime_time_t_overflow();
1233
0
        return -1;
1234
0
    }
1235
0
    return 0;
1236
0
}
1237
1238
1239
#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
1240
static int
1241
pytime_as_timespec(PyTime_t ns, struct timespec *ts, int raise_exc)
1242
0
{
1243
0
    PyTime_t tv_sec, tv_nsec;
1244
0
    int res = pytime_divmod(ns, SEC_TO_NS, &tv_sec, &tv_nsec);
1245
1246
0
    int res2 = _PyTime_AsTime_t(tv_sec, &ts->tv_sec);
1247
0
    if (res2 < 0) {
1248
0
        tv_nsec = 0;
1249
0
    }
1250
0
    ts->tv_nsec = tv_nsec;
1251
1252
0
    if (raise_exc && (res < 0 || res2 < 0)) {
1253
0
        pytime_time_t_overflow();
1254
0
        return -1;
1255
0
    }
1256
0
    return 0;
1257
0
}
1258
1259
void
1260
_PyTime_AsTimespec_clamp(PyTime_t t, struct timespec *ts)
1261
0
{
1262
0
    (void)pytime_as_timespec(t, ts, 0);
1263
0
}
1264
1265
int
1266
_PyTime_AsTimespec(PyTime_t t, struct timespec *ts)
1267
0
{
1268
0
    return pytime_as_timespec(t, ts, 1);
1269
0
}
1270
#endif
1271
1272
1273
// N.B. If raise_exc=0, this may be called without a thread state.
1274
static int
1275
py_get_system_clock(PyTime_t *tp, _Py_clock_info_t *info, int raise_exc)
1276
12
{
1277
12
    assert(info == NULL || raise_exc);
1278
12
    if (raise_exc) {
1279
        // raise_exc requires to hold a thread state
1280
12
        _Py_AssertHoldsTstate();
1281
12
    }
1282
1283
#ifdef MS_WINDOWS
1284
    FILETIME system_time;
1285
    ULARGE_INTEGER large;
1286
1287
    GetSystemTimePreciseAsFileTime(&system_time);
1288
    large.u.LowPart = system_time.dwLowDateTime;
1289
    large.u.HighPart = system_time.dwHighDateTime;
1290
1291
    PyTime_t ns = (large.QuadPart - SECS_BETWEEN_EPOCHS * HUNDRED_NS_PER_SEC) * 100;
1292
    *tp = ns;
1293
    if (info) {
1294
        // GetSystemTimePreciseAsFileTime() is implemented using
1295
        // QueryPerformanceCounter() internally.
1296
        info->implementation = "GetSystemTimePreciseAsFileTime()";
1297
        info->monotonic = 0;
1298
        info->resolution = _PyTimeFraction_Resolution(&_PyRuntime.time.base);
1299
        info->adjustable = 1;
1300
    }
1301
1302
#else   /* MS_WINDOWS */
1303
12
    int err;
1304
12
#if defined(HAVE_CLOCK_GETTIME)
1305
12
    struct timespec ts;
1306
12
#endif
1307
1308
#if !defined(HAVE_CLOCK_GETTIME) || defined(__APPLE__)
1309
    struct timeval tv;
1310
#endif
1311
1312
12
#ifdef HAVE_CLOCK_GETTIME
1313
1314
#ifdef HAVE_CLOCK_GETTIME_RUNTIME
1315
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
1316
#endif
1317
1318
12
    err = clock_gettime(CLOCK_REALTIME, &ts);
1319
12
    if (err) {
1320
0
        if (raise_exc) {
1321
0
            PyErr_SetFromErrno(PyExc_OSError);
1322
0
        }
1323
0
        return -1;
1324
0
    }
1325
12
    if (pytime_fromtimespec(tp, &ts, raise_exc) < 0) {
1326
0
        return -1;
1327
0
    }
1328
1329
12
    if (info) {
1330
0
        struct timespec res;
1331
0
        info->implementation = "clock_gettime(CLOCK_REALTIME)";
1332
0
        info->monotonic = 0;
1333
0
        info->adjustable = 1;
1334
0
        if (clock_getres(CLOCK_REALTIME, &res) == 0) {
1335
0
            info->resolution = (double)res.tv_sec + (double)res.tv_nsec * 1e-9;
1336
0
        }
1337
0
        else {
1338
0
            info->resolution = 1e-9;
1339
0
        }
1340
0
    }
1341
1342
#ifdef HAVE_CLOCK_GETTIME_RUNTIME
1343
    }
1344
    else {
1345
#endif
1346
1347
12
#endif
1348
1349
#if !defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETTIME_RUNTIME)
1350
1351
     /* test gettimeofday() */
1352
    err = gettimeofday(&tv, (struct timezone *)NULL);
1353
    if (err) {
1354
        if (raise_exc) {
1355
            PyErr_SetFromErrno(PyExc_OSError);
1356
        }
1357
        return -1;
1358
    }
1359
    if (pytime_fromtimeval(tp, &tv, raise_exc) < 0) {
1360
        return -1;
1361
    }
1362
1363
    if (info) {
1364
        info->implementation = "gettimeofday()";
1365
        info->resolution = 1e-6;
1366
        info->monotonic = 0;
1367
        info->adjustable = 1;
1368
    }
1369
1370
#if defined(HAVE_CLOCK_GETTIME_RUNTIME) && defined(HAVE_CLOCK_GETTIME)
1371
    } /* end of availability block */
1372
#endif
1373
1374
#endif   /* !HAVE_CLOCK_GETTIME */
1375
12
#endif   /* !MS_WINDOWS */
1376
12
    return 0;
1377
12
}
1378
1379
1380
int
1381
PyTime_Time(PyTime_t *result)
1382
12
{
1383
12
    if (py_get_system_clock(result, NULL, 1) < 0) {
1384
0
        *result = 0;
1385
0
        return -1;
1386
0
    }
1387
12
    return 0;
1388
12
}
1389
1390
1391
int
1392
PyTime_TimeRaw(PyTime_t *result)
1393
0
{
1394
0
    if (py_get_system_clock(result, NULL, 0) < 0) {
1395
0
        *result = 0;
1396
0
        return -1;
1397
0
    }
1398
0
    return 0;
1399
0
}
1400
1401
1402
int
1403
_PyTime_TimeWithInfo(PyTime_t *t, _Py_clock_info_t *info)
1404
0
{
1405
0
    return py_get_system_clock(t, info, 1);
1406
0
}
1407
1408
1409
#ifdef MS_WINDOWS
1410
static PyStatus
1411
py_win_perf_counter_frequency(_PyTimeFraction *base)
1412
{
1413
    LARGE_INTEGER freq;
1414
    // Since Windows XP, the function cannot fail.
1415
    (void)QueryPerformanceFrequency(&freq);
1416
    LONGLONG frequency = freq.QuadPart;
1417
1418
    // Since Windows XP, frequency cannot be zero.
1419
    assert(frequency >= 1);
1420
1421
    Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(frequency));
1422
    PyTime_t denom = (PyTime_t)frequency;
1423
1424
    // Known QueryPerformanceFrequency() values:
1425
    //
1426
    // * 10,000,000 (10 MHz): 100 ns resolution
1427
    // * 3,579,545 Hz (3.6 MHz): 279 ns resolution
1428
    if (_PyTimeFraction_Set(base, SEC_TO_NS, denom) < 0) {
1429
        return _PyStatus_ERR("invalid QueryPerformanceFrequency");
1430
    }
1431
    return PyStatus_Ok();
1432
}
1433
1434
1435
// N.B. If raise_exc=0, this may be called without the GIL.
1436
static int
1437
py_get_win_perf_counter(PyTime_t *tp, _Py_clock_info_t *info, int raise_exc)
1438
{
1439
    assert(info == NULL || raise_exc);
1440
1441
    if (info) {
1442
        info->implementation = "QueryPerformanceCounter()";
1443
        info->resolution = _PyTimeFraction_Resolution(&_PyRuntime.time.base);
1444
        info->monotonic = 1;
1445
        info->adjustable = 0;
1446
    }
1447
1448
    LARGE_INTEGER now;
1449
    QueryPerformanceCounter(&now);
1450
    LONGLONG ticksll = now.QuadPart;
1451
1452
    /* Make sure that casting LONGLONG to PyTime_t cannot overflow,
1453
       both types are signed */
1454
    PyTime_t ticks;
1455
    static_assert(sizeof(ticksll) <= sizeof(ticks),
1456
                  "LONGLONG is larger than PyTime_t");
1457
    ticks = (PyTime_t)ticksll;
1458
1459
    *tp = _PyTimeFraction_Mul(ticks, &_PyRuntime.time.base);
1460
    return 0;
1461
}
1462
#endif  // MS_WINDOWS
1463
1464
1465
#ifdef __APPLE__
1466
static PyStatus
1467
py_mach_timebase_info(_PyTimeFraction *base)
1468
{
1469
    mach_timebase_info_data_t timebase;
1470
    // According to the Technical Q&A QA1398, mach_timebase_info() cannot
1471
    // fail: https://developer.apple.com/library/mac/#qa/qa1398/
1472
    (void)mach_timebase_info(&timebase);
1473
1474
    // Check that timebase.numer and timebase.denom can be casted to
1475
    // PyTime_t. In practice, timebase uses uint32_t, so casting cannot
1476
    // overflow. At the end, only make sure that the type is uint32_t
1477
    // (PyTime_t is 64-bit long).
1478
    Py_BUILD_ASSERT(sizeof(timebase.numer) <= sizeof(PyTime_t));
1479
    Py_BUILD_ASSERT(sizeof(timebase.denom) <= sizeof(PyTime_t));
1480
    PyTime_t numer = (PyTime_t)timebase.numer;
1481
    PyTime_t denom = (PyTime_t)timebase.denom;
1482
1483
    // Known time bases:
1484
    //
1485
    // * (1, 1) on Intel: 1 ns
1486
    // * (1000000000, 33333335) on PowerPC: ~30 ns
1487
    // * (1000000000, 25000000) on PowerPC: 40 ns
1488
    if (_PyTimeFraction_Set(base, numer, denom) < 0) {
1489
        return _PyStatus_ERR("invalid mach_timebase_info");
1490
    }
1491
    return PyStatus_Ok();
1492
}
1493
#endif
1494
1495
PyStatus
1496
_PyTime_Init(struct _Py_time_runtime_state *state)
1497
37
{
1498
#ifdef MS_WINDOWS
1499
    return py_win_perf_counter_frequency(&state->base);
1500
#elif defined(__APPLE__)
1501
    return py_mach_timebase_info(&state->base);
1502
#else
1503
37
    return PyStatus_Ok();
1504
37
#endif
1505
37
}
1506
1507
// N.B. If raise_exc=0, this may be called without a thread state.
1508
static int
1509
py_get_monotonic_clock(PyTime_t *tp, _Py_clock_info_t *info, int raise_exc)
1510
289k
{
1511
289k
    assert(info == NULL || raise_exc);
1512
289k
    if (raise_exc) {
1513
        // raise_exc requires to hold a thread state
1514
15.8k
        _Py_AssertHoldsTstate();
1515
15.8k
    }
1516
1517
#if defined(MS_WINDOWS)
1518
    if (py_get_win_perf_counter(tp, info, raise_exc) < 0) {
1519
        return -1;
1520
    }
1521
#elif defined(__APPLE__)
1522
    if (info) {
1523
        info->implementation = "mach_absolute_time()";
1524
        info->resolution = _PyTimeFraction_Resolution(&_PyRuntime.time.base);
1525
        info->monotonic = 1;
1526
        info->adjustable = 0;
1527
    }
1528
1529
    uint64_t uticks = mach_absolute_time();
1530
    // unsigned => signed
1531
    assert(uticks <= (uint64_t)PyTime_MAX);
1532
    PyTime_t ticks = (PyTime_t)uticks;
1533
1534
    PyTime_t ns = _PyTimeFraction_Mul(ticks, &_PyRuntime.time.base);
1535
    *tp = ns;
1536
1537
#elif defined(__hpux)
1538
    hrtime_t time = gethrtime();
1539
    if (time == -1) {
1540
        if (raise_exc) {
1541
            PyErr_SetFromErrno(PyExc_OSError);
1542
        }
1543
        return -1;
1544
    }
1545
1546
    *tp = time;
1547
1548
    if (info) {
1549
        info->implementation = "gethrtime()";
1550
        info->resolution = 1e-9;
1551
        info->monotonic = 1;
1552
        info->adjustable = 0;
1553
    }
1554
1555
#else
1556
1557
#ifdef CLOCK_HIGHRES
1558
    const clockid_t clk_id = CLOCK_HIGHRES;
1559
    const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
1560
#else
1561
289k
    const clockid_t clk_id = CLOCK_MONOTONIC;
1562
289k
    const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
1563
289k
#endif
1564
1565
289k
    struct timespec ts;
1566
289k
    if (clock_gettime(clk_id, &ts) != 0) {
1567
0
        if (raise_exc) {
1568
0
            PyErr_SetFromErrno(PyExc_OSError);
1569
0
            return -1;
1570
0
        }
1571
0
        return -1;
1572
0
    }
1573
1574
289k
    if (pytime_fromtimespec(tp, &ts, raise_exc) < 0) {
1575
0
        return -1;
1576
0
    }
1577
1578
289k
    if (info) {
1579
0
        info->monotonic = 1;
1580
0
        info->implementation = implementation;
1581
0
        info->adjustable = 0;
1582
0
        struct timespec res;
1583
0
        if (clock_getres(clk_id, &res) != 0) {
1584
0
            PyErr_SetFromErrno(PyExc_OSError);
1585
0
            return -1;
1586
0
        }
1587
0
        info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1588
0
    }
1589
289k
#endif
1590
289k
    return 0;
1591
289k
}
1592
1593
1594
int
1595
PyTime_Monotonic(PyTime_t *result)
1596
15.8k
{
1597
15.8k
    if (py_get_monotonic_clock(result, NULL, 1) < 0) {
1598
0
        *result = 0;
1599
0
        return -1;
1600
0
    }
1601
15.8k
    return 0;
1602
15.8k
}
1603
1604
1605
int
1606
PyTime_MonotonicRaw(PyTime_t *result)
1607
273k
{
1608
273k
    if (py_get_monotonic_clock(result, NULL, 0) < 0) {
1609
0
        *result = 0;
1610
0
        return -1;
1611
0
    }
1612
273k
    return 0;
1613
273k
}
1614
1615
1616
int
1617
_PyTime_MonotonicWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1618
0
{
1619
0
    return py_get_monotonic_clock(tp, info, 1);
1620
0
}
1621
1622
1623
int
1624
_PyTime_PerfCounterWithInfo(PyTime_t *t, _Py_clock_info_t *info)
1625
0
{
1626
0
    return _PyTime_MonotonicWithInfo(t, info);
1627
0
}
1628
1629
1630
int
1631
PyTime_PerfCounter(PyTime_t *result)
1632
15.8k
{
1633
15.8k
    return PyTime_Monotonic(result);
1634
15.8k
}
1635
1636
1637
int
1638
PyTime_PerfCounterRaw(PyTime_t *result)
1639
273k
{
1640
273k
    return PyTime_MonotonicRaw(result);
1641
273k
}
1642
1643
1644
int
1645
_PyTime_localtime(time_t t, struct tm *tm)
1646
74
{
1647
#ifdef MS_WINDOWS
1648
    if (t >= 0) {
1649
        /* For non-negative timestamps, use localtime_s() */
1650
        int error = localtime_s(tm, &t);
1651
        if (error != 0) {
1652
            errno = error;
1653
            PyErr_SetFromErrno(PyExc_OSError);
1654
            return -1;
1655
        }
1656
        return 0;
1657
    }
1658
1659
    /* For negative timestamps, use FILETIME-based conversion */
1660
    return _PyTime_windows_filetime(t, tm, 1);
1661
#else /* !MS_WINDOWS */
1662
1663
#if defined(_AIX) && (SIZEOF_TIME_T < 8)
1664
    /* bpo-34373: AIX does not return NULL if t is too small or too large */
1665
    if (t < -2145916800 /* 1902-01-01 */
1666
       || t > 2145916800 /* 2038-01-01 */) {
1667
        errno = EINVAL;
1668
        PyErr_SetString(PyExc_OverflowError,
1669
                        "localtime argument out of range");
1670
        return -1;
1671
    }
1672
#endif
1673
1674
74
    errno = 0;
1675
74
    if (localtime_r(&t, tm) == NULL) {
1676
0
        if (errno == 0) {
1677
0
            errno = EINVAL;
1678
0
        }
1679
0
        PyErr_SetFromErrno(PyExc_OSError);
1680
0
        return -1;
1681
0
    }
1682
74
    return 0;
1683
74
#endif /* MS_WINDOWS */
1684
74
}
1685
1686
1687
int
1688
_PyTime_gmtime(time_t t, struct tm *tm)
1689
0
{
1690
#ifdef MS_WINDOWS
1691
    /* For non-negative timestamps, use gmtime_s() */
1692
    if (t >= 0) {
1693
        int error = gmtime_s(tm, &t);
1694
        if (error != 0) {
1695
            errno = error;
1696
            PyErr_SetFromErrno(PyExc_OSError);
1697
            return -1;
1698
        }
1699
        return 0;
1700
    }
1701
1702
    /* For negative timestamps, use FILETIME-based conversion */
1703
    return _PyTime_windows_filetime(t, tm, 0);
1704
#else /* !MS_WINDOWS */
1705
0
    if (gmtime_r(&t, tm) == NULL) {
1706
0
#ifdef EINVAL
1707
0
        if (errno == 0) {
1708
0
            errno = EINVAL;
1709
0
        }
1710
0
#endif
1711
0
        PyErr_SetFromErrno(PyExc_OSError);
1712
0
        return -1;
1713
0
    }
1714
0
    return 0;
1715
0
#endif /* MS_WINDOWS */
1716
0
}
1717
1718
1719
PyTime_t
1720
_PyDeadline_Init(PyTime_t timeout)
1721
0
{
1722
0
    PyTime_t now;
1723
    // silently ignore error: cannot report error to the caller
1724
0
    (void)PyTime_MonotonicRaw(&now);
1725
0
    return _PyTime_Add(now, timeout);
1726
0
}
1727
1728
1729
PyTime_t
1730
_PyDeadline_Get(PyTime_t deadline)
1731
0
{
1732
0
    PyTime_t now;
1733
    // silently ignore error: cannot report error to the caller
1734
0
    (void)PyTime_MonotonicRaw(&now);
1735
0
    return deadline - now;
1736
0
}