1 #include "Python.h"
2 #include "pycore_time.h" // PyTime_t
3
4 #include <time.h> // gmtime_r()
5 #ifdef HAVE_SYS_TIME_H
6 # include <sys/time.h> // gettimeofday()
7 #endif
8 #ifdef MS_WINDOWS
9 # include <winsock2.h> // struct timeval
10 #endif
11
12 #if defined(__APPLE__)
13 # include <mach/mach_time.h> // mach_absolute_time(), mach_timebase_info()
14
15 #if defined(__APPLE__) && defined(__has_builtin)
16 # if __has_builtin(__builtin_available)
17 # define HAVE_CLOCK_GETTIME_RUNTIME __builtin_available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
18 # endif
19 #endif
20 #endif
21
22 /* To millisecond (10^-3) */
23 #define SEC_TO_MS 1000
24
25 /* To microseconds (10^-6) */
26 #define MS_TO_US 1000
27 #define SEC_TO_US (SEC_TO_MS * MS_TO_US)
28
29 /* To nanoseconds (10^-9) */
30 #define US_TO_NS 1000
31 #define MS_TO_NS (MS_TO_US * US_TO_NS)
32 #define SEC_TO_NS (SEC_TO_MS * MS_TO_NS)
33
34 /* Conversion from nanoseconds */
35 #define NS_TO_MS (1000 * 1000)
36 #define NS_TO_US (1000)
37 #define NS_TO_100NS (100)
38
39 #if SIZEOF_TIME_T == SIZEOF_LONG_LONG
40 # define PY_TIME_T_MAX LLONG_MAX
41 # define PY_TIME_T_MIN LLONG_MIN
42 #elif SIZEOF_TIME_T == SIZEOF_LONG
43 # define PY_TIME_T_MAX LONG_MAX
44 # define PY_TIME_T_MIN LONG_MIN
45 #else
46 # error "unsupported time_t size"
47 #endif
48
49 #if PY_TIME_T_MAX + PY_TIME_T_MIN != -1
50 # error "time_t is not a two's complement integer type"
51 #endif
52
53 #if PyTime_MIN + PyTime_MAX != -1
54 # error "PyTime_t is not a two's complement integer type"
55 #endif
56
57
58 #ifdef MS_WINDOWS
59 static _PyTimeFraction py_qpc_base = {0, 0};
60
61 // Forward declaration
62 static int py_win_perf_counter_frequency(_PyTimeFraction *base, int raise_exc);
63 #endif
64
65
66 static PyTime_t
_PyTime_GCD(PyTime_t x,PyTime_t y)67 _PyTime_GCD(PyTime_t x, PyTime_t y)
68 {
69 // Euclidean algorithm
70 assert(x >= 1);
71 assert(y >= 1);
72 while (y != 0) {
73 PyTime_t tmp = y;
74 y = x % y;
75 x = tmp;
76 }
77 assert(x >= 1);
78 return x;
79 }
80
81
82 int
_PyTimeFraction_Set(_PyTimeFraction * frac,PyTime_t numer,PyTime_t denom)83 _PyTimeFraction_Set(_PyTimeFraction *frac, PyTime_t numer, PyTime_t denom)
84 {
85 if (numer < 1 || denom < 1) {
86 return -1;
87 }
88
89 PyTime_t gcd = _PyTime_GCD(numer, denom);
90 frac->numer = numer / gcd;
91 frac->denom = denom / gcd;
92 return 0;
93 }
94
95
96 double
_PyTimeFraction_Resolution(const _PyTimeFraction * frac)97 _PyTimeFraction_Resolution(const _PyTimeFraction *frac)
98 {
99 return (double)frac->numer / (double)frac->denom / 1e9;
100 }
101
102
103 static void
pytime_time_t_overflow(void)104 pytime_time_t_overflow(void)
105 {
106 PyErr_SetString(PyExc_OverflowError,
107 "timestamp out of range for platform time_t");
108 }
109
110
111 static void
pytime_overflow(void)112 pytime_overflow(void)
113 {
114 PyErr_SetString(PyExc_OverflowError,
115 "timestamp too large to convert to C PyTime_t");
116 }
117
118
119 // Compute t1 + t2. Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
120 static inline int
pytime_add(PyTime_t * t1,PyTime_t t2)121 pytime_add(PyTime_t *t1, PyTime_t t2)
122 {
123 if (t2 > 0 && *t1 > PyTime_MAX - t2) {
124 *t1 = PyTime_MAX;
125 return -1;
126 }
127 else if (t2 < 0 && *t1 < PyTime_MIN - t2) {
128 *t1 = PyTime_MIN;
129 return -1;
130 }
131 else {
132 *t1 += t2;
133 return 0;
134 }
135 }
136
137
138 PyTime_t
_PyTime_Add(PyTime_t t1,PyTime_t t2)139 _PyTime_Add(PyTime_t t1, PyTime_t t2)
140 {
141 (void)pytime_add(&t1, t2);
142 return t1;
143 }
144
145
146 static inline int
pytime_mul_check_overflow(PyTime_t a,PyTime_t b)147 pytime_mul_check_overflow(PyTime_t a, PyTime_t b)
148 {
149 if (b != 0) {
150 assert(b > 0);
151 return ((a < PyTime_MIN / b) || (PyTime_MAX / b < a));
152 }
153 else {
154 return 0;
155 }
156 }
157
158
159 // Compute t * k. Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
160 static inline int
pytime_mul(PyTime_t * t,PyTime_t k)161 pytime_mul(PyTime_t *t, PyTime_t k)
162 {
163 assert(k >= 0);
164 if (pytime_mul_check_overflow(*t, k)) {
165 *t = (*t >= 0) ? PyTime_MAX : PyTime_MIN;
166 return -1;
167 }
168 else {
169 *t *= k;
170 return 0;
171 }
172 }
173
174
175 // Compute t * k. Clamp to [PyTime_MIN; PyTime_MAX] on overflow.
176 static inline PyTime_t
_PyTime_Mul(PyTime_t t,PyTime_t k)177 _PyTime_Mul(PyTime_t t, PyTime_t k)
178 {
179 (void)pytime_mul(&t, k);
180 return t;
181 }
182
183
184 PyTime_t
_PyTimeFraction_Mul(PyTime_t ticks,const _PyTimeFraction * frac)185 _PyTimeFraction_Mul(PyTime_t ticks, const _PyTimeFraction *frac)
186 {
187 const PyTime_t mul = frac->numer;
188 const PyTime_t div = frac->denom;
189
190 if (div == 1) {
191 // Fast-path taken by mach_absolute_time() with 1/1 time base.
192 return _PyTime_Mul(ticks, mul);
193 }
194
195 /* Compute (ticks * mul / div) in two parts to reduce the risk of integer
196 overflow: compute the integer part, and then the remaining part.
197
198 (ticks * mul) / div == (ticks / div) * mul + (ticks % div) * mul / div
199 */
200 PyTime_t intpart, remaining;
201 intpart = ticks / div;
202 ticks %= div;
203 remaining = _PyTime_Mul(ticks, mul) / div;
204 // intpart * mul + remaining
205 return _PyTime_Add(_PyTime_Mul(intpart, mul), remaining);
206 }
207
208
209 time_t
_PyLong_AsTime_t(PyObject * obj)210 _PyLong_AsTime_t(PyObject *obj)
211 {
212 #if SIZEOF_TIME_T == SIZEOF_LONG_LONG
213 long long val = PyLong_AsLongLong(obj);
214 #elif SIZEOF_TIME_T <= SIZEOF_LONG
215 long val = PyLong_AsLong(obj);
216 #else
217 # error "unsupported time_t size"
218 #endif
219 if (val == -1 && PyErr_Occurred()) {
220 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
221 pytime_time_t_overflow();
222 }
223 return -1;
224 }
225 return (time_t)val;
226 }
227
228
229 PyObject *
_PyLong_FromTime_t(time_t t)230 _PyLong_FromTime_t(time_t t)
231 {
232 #if SIZEOF_TIME_T == SIZEOF_LONG_LONG
233 return PyLong_FromLongLong((long long)t);
234 #elif SIZEOF_TIME_T <= SIZEOF_LONG
235 return PyLong_FromLong((long)t);
236 #else
237 # error "unsupported time_t size"
238 #endif
239 }
240
241
242 // Convert PyTime_t to time_t.
243 // Return 0 on success. Return -1 and clamp the value on overflow.
244 static int
_PyTime_AsTime_t(PyTime_t t,time_t * t2)245 _PyTime_AsTime_t(PyTime_t t, time_t *t2)
246 {
247 #if SIZEOF_TIME_T < _SIZEOF_PYTIME_T
248 if ((PyTime_t)PY_TIME_T_MAX < t) {
249 *t2 = PY_TIME_T_MAX;
250 return -1;
251 }
252 if (t < (PyTime_t)PY_TIME_T_MIN) {
253 *t2 = PY_TIME_T_MIN;
254 return -1;
255 }
256 #endif
257 *t2 = (time_t)t;
258 return 0;
259 }
260
261
262 #ifdef MS_WINDOWS
263 // Convert PyTime_t to long.
264 // Return 0 on success. Return -1 and clamp the value on overflow.
265 static int
_PyTime_AsCLong(PyTime_t t,long * t2)266 _PyTime_AsCLong(PyTime_t t, long *t2)
267 {
268 #if SIZEOF_LONG < _SIZEOF_PYTIME_T
269 if ((PyTime_t)LONG_MAX < t) {
270 *t2 = LONG_MAX;
271 return -1;
272 }
273 if (t < (PyTime_t)LONG_MIN) {
274 *t2 = LONG_MIN;
275 return -1;
276 }
277 #endif
278 *t2 = (long)t;
279 return 0;
280 }
281 #endif
282
283
284 /* Round to nearest with ties going to nearest even integer
285 (_PyTime_ROUND_HALF_EVEN) */
286 static double
pytime_round_half_even(double x)287 pytime_round_half_even(double x)
288 {
289 double rounded = round(x);
290 if (fabs(x-rounded) == 0.5) {
291 /* halfway case: round to even */
292 rounded = 2.0 * round(x / 2.0);
293 }
294 return rounded;
295 }
296
297
298 static double
pytime_round(double x,_PyTime_round_t round)299 pytime_round(double x, _PyTime_round_t round)
300 {
301 /* volatile avoids optimization changing how numbers are rounded */
302 volatile double d;
303
304 d = x;
305 if (round == _PyTime_ROUND_HALF_EVEN) {
306 d = pytime_round_half_even(d);
307 }
308 else if (round == _PyTime_ROUND_CEILING) {
309 d = ceil(d);
310 }
311 else if (round == _PyTime_ROUND_FLOOR) {
312 d = floor(d);
313 }
314 else {
315 assert(round == _PyTime_ROUND_UP);
316 d = (d >= 0.0) ? ceil(d) : floor(d);
317 }
318 return d;
319 }
320
321
322 static int
pytime_double_to_denominator(double d,time_t * sec,long * numerator,long idenominator,_PyTime_round_t round)323 pytime_double_to_denominator(double d, time_t *sec, long *numerator,
324 long idenominator, _PyTime_round_t round)
325 {
326 double denominator = (double)idenominator;
327 double intpart;
328 /* volatile avoids optimization changing how numbers are rounded */
329 volatile double floatpart;
330
331 floatpart = modf(d, &intpart);
332
333 floatpart *= denominator;
334 floatpart = pytime_round(floatpart, round);
335 if (floatpart >= denominator) {
336 floatpart -= denominator;
337 intpart += 1.0;
338 }
339 else if (floatpart < 0) {
340 floatpart += denominator;
341 intpart -= 1.0;
342 }
343 assert(0.0 <= floatpart && floatpart < denominator);
344
345 /*
346 Conversion of an out-of-range value to time_t gives undefined behaviour
347 (C99 §6.3.1.4p1), so we must guard against it. However, checking that
348 `intpart` is in range is delicate: the obvious expression `intpart <=
349 PY_TIME_T_MAX` will first convert the value `PY_TIME_T_MAX` to a double,
350 potentially changing its value and leading to us failing to catch some
351 UB-inducing values. The code below works correctly under the mild
352 assumption that time_t is a two's complement integer type with no trap
353 representation, and that `PY_TIME_T_MIN` is within the representable
354 range of a C double.
355
356 Note: we want the `if` condition below to be true for NaNs; therefore,
357 resist any temptation to simplify by applying De Morgan's laws.
358 */
359 if (!((double)PY_TIME_T_MIN <= intpart && intpart < -(double)PY_TIME_T_MIN)) {
360 pytime_time_t_overflow();
361 return -1;
362 }
363 *sec = (time_t)intpart;
364 *numerator = (long)floatpart;
365 assert(0 <= *numerator && *numerator < idenominator);
366 return 0;
367 }
368
369
370 static int
pytime_object_to_denominator(PyObject * obj,time_t * sec,long * numerator,long denominator,_PyTime_round_t round)371 pytime_object_to_denominator(PyObject *obj, time_t *sec, long *numerator,
372 long denominator, _PyTime_round_t round)
373 {
374 assert(denominator >= 1);
375
376 if (PyFloat_Check(obj)) {
377 double d = PyFloat_AsDouble(obj);
378 if (Py_IS_NAN(d)) {
379 *numerator = 0;
380 PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
381 return -1;
382 }
383 return pytime_double_to_denominator(d, sec, numerator,
384 denominator, round);
385 }
386 else {
387 *sec = _PyLong_AsTime_t(obj);
388 *numerator = 0;
389 if (*sec == (time_t)-1 && PyErr_Occurred()) {
390 return -1;
391 }
392 return 0;
393 }
394 }
395
396
397 int
_PyTime_ObjectToTime_t(PyObject * obj,time_t * sec,_PyTime_round_t round)398 _PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round)
399 {
400 if (PyFloat_Check(obj)) {
401 double intpart;
402 /* volatile avoids optimization changing how numbers are rounded */
403 volatile double d;
404
405 d = PyFloat_AsDouble(obj);
406 if (Py_IS_NAN(d)) {
407 PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
408 return -1;
409 }
410
411 d = pytime_round(d, round);
412 (void)modf(d, &intpart);
413
414 /* See comments in pytime_double_to_denominator */
415 if (!((double)PY_TIME_T_MIN <= intpart && intpart < -(double)PY_TIME_T_MIN)) {
416 pytime_time_t_overflow();
417 return -1;
418 }
419 *sec = (time_t)intpart;
420 return 0;
421 }
422 else {
423 *sec = _PyLong_AsTime_t(obj);
424 if (*sec == (time_t)-1 && PyErr_Occurred()) {
425 return -1;
426 }
427 return 0;
428 }
429 }
430
431
432 int
_PyTime_ObjectToTimespec(PyObject * obj,time_t * sec,long * nsec,_PyTime_round_t round)433 _PyTime_ObjectToTimespec(PyObject *obj, time_t *sec, long *nsec,
434 _PyTime_round_t round)
435 {
436 return pytime_object_to_denominator(obj, sec, nsec, SEC_TO_NS, round);
437 }
438
439
440 int
_PyTime_ObjectToTimeval(PyObject * obj,time_t * sec,long * usec,_PyTime_round_t round)441 _PyTime_ObjectToTimeval(PyObject *obj, time_t *sec, long *usec,
442 _PyTime_round_t round)
443 {
444 return pytime_object_to_denominator(obj, sec, usec, SEC_TO_US, round);
445 }
446
447
448 PyTime_t
_PyTime_FromSeconds(int seconds)449 _PyTime_FromSeconds(int seconds)
450 {
451 /* ensure that integer overflow cannot happen, int type should have 32
452 bits, whereas PyTime_t type has at least 64 bits (SEC_TO_NS takes 30
453 bits). */
454 static_assert(INT_MAX <= PyTime_MAX / SEC_TO_NS, "PyTime_t overflow");
455 static_assert(INT_MIN >= PyTime_MIN / SEC_TO_NS, "PyTime_t underflow");
456
457 PyTime_t t = (PyTime_t)seconds;
458 assert((t >= 0 && t <= PyTime_MAX / SEC_TO_NS)
459 || (t < 0 && t >= PyTime_MIN / SEC_TO_NS));
460 t *= SEC_TO_NS;
461 return t;
462 }
463
464
465 PyTime_t
_PyTime_FromMicrosecondsClamp(PyTime_t us)466 _PyTime_FromMicrosecondsClamp(PyTime_t us)
467 {
468 PyTime_t ns = _PyTime_Mul(us, US_TO_NS);
469 return ns;
470 }
471
472
473 int
_PyTime_FromLong(PyTime_t * tp,PyObject * obj)474 _PyTime_FromLong(PyTime_t *tp, PyObject *obj)
475 {
476 if (!PyLong_Check(obj)) {
477 PyErr_Format(PyExc_TypeError, "expect int, got %s",
478 Py_TYPE(obj)->tp_name);
479 return -1;
480 }
481
482 static_assert(sizeof(long long) == sizeof(PyTime_t),
483 "PyTime_t is not long long");
484 long long nsec = PyLong_AsLongLong(obj);
485 if (nsec == -1 && PyErr_Occurred()) {
486 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
487 pytime_overflow();
488 }
489 return -1;
490 }
491
492 PyTime_t t = (PyTime_t)nsec;
493 *tp = t;
494 return 0;
495 }
496
497
498 #ifdef HAVE_CLOCK_GETTIME
499 static int
pytime_fromtimespec(PyTime_t * tp,const struct timespec * ts,int raise_exc)500 pytime_fromtimespec(PyTime_t *tp, const struct timespec *ts, int raise_exc)
501 {
502 PyTime_t t, tv_nsec;
503
504 static_assert(sizeof(ts->tv_sec) <= sizeof(PyTime_t),
505 "timespec.tv_sec is larger than PyTime_t");
506 t = (PyTime_t)ts->tv_sec;
507
508 int res1 = pytime_mul(&t, SEC_TO_NS);
509
510 tv_nsec = ts->tv_nsec;
511 int res2 = pytime_add(&t, tv_nsec);
512
513 *tp = t;
514
515 if (raise_exc && (res1 < 0 || res2 < 0)) {
516 pytime_overflow();
517 return -1;
518 }
519 return 0;
520 }
521
522 int
_PyTime_FromTimespec(PyTime_t * tp,const struct timespec * ts)523 _PyTime_FromTimespec(PyTime_t *tp, const struct timespec *ts)
524 {
525 return pytime_fromtimespec(tp, ts, 1);
526 }
527 #endif
528
529
530 #ifndef MS_WINDOWS
531 static int
pytime_fromtimeval(PyTime_t * tp,struct timeval * tv,int raise_exc)532 pytime_fromtimeval(PyTime_t *tp, struct timeval *tv, int raise_exc)
533 {
534 static_assert(sizeof(tv->tv_sec) <= sizeof(PyTime_t),
535 "timeval.tv_sec is larger than PyTime_t");
536 PyTime_t t = (PyTime_t)tv->tv_sec;
537
538 int res1 = pytime_mul(&t, SEC_TO_NS);
539
540 PyTime_t usec = (PyTime_t)tv->tv_usec * US_TO_NS;
541 int res2 = pytime_add(&t, usec);
542
543 *tp = t;
544
545 if (raise_exc && (res1 < 0 || res2 < 0)) {
546 pytime_overflow();
547 return -1;
548 }
549 return 0;
550 }
551
552
553 int
_PyTime_FromTimeval(PyTime_t * tp,struct timeval * tv)554 _PyTime_FromTimeval(PyTime_t *tp, struct timeval *tv)
555 {
556 return pytime_fromtimeval(tp, tv, 1);
557 }
558 #endif
559
560
561 static int
pytime_from_double(PyTime_t * tp,double value,_PyTime_round_t round,long unit_to_ns)562 pytime_from_double(PyTime_t *tp, double value, _PyTime_round_t round,
563 long unit_to_ns)
564 {
565 /* volatile avoids optimization changing how numbers are rounded */
566 volatile double d;
567
568 /* convert to a number of nanoseconds */
569 d = value;
570 d *= (double)unit_to_ns;
571 d = pytime_round(d, round);
572
573 /* See comments in pytime_double_to_denominator */
574 if (!((double)PyTime_MIN <= d && d < -(double)PyTime_MIN)) {
575 pytime_time_t_overflow();
576 *tp = 0;
577 return -1;
578 }
579 PyTime_t ns = (PyTime_t)d;
580
581 *tp = ns;
582 return 0;
583 }
584
585
586 static int
pytime_from_object(PyTime_t * tp,PyObject * obj,_PyTime_round_t round,long unit_to_ns)587 pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
588 long unit_to_ns)
589 {
590 if (PyFloat_Check(obj)) {
591 double d;
592 d = PyFloat_AsDouble(obj);
593 if (Py_IS_NAN(d)) {
594 PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
595 return -1;
596 }
597 return pytime_from_double(tp, d, round, unit_to_ns);
598 }
599 else {
600 long long sec = PyLong_AsLongLong(obj);
601 if (sec == -1 && PyErr_Occurred()) {
602 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
603 pytime_overflow();
604 }
605 return -1;
606 }
607
608 static_assert(sizeof(long long) <= sizeof(PyTime_t),
609 "PyTime_t is smaller than long long");
610 PyTime_t ns = (PyTime_t)sec;
611 if (pytime_mul(&ns, unit_to_ns) < 0) {
612 pytime_overflow();
613 return -1;
614 }
615
616 *tp = ns;
617 return 0;
618 }
619 }
620
621
622 int
_PyTime_FromSecondsObject(PyTime_t * tp,PyObject * obj,_PyTime_round_t round)623 _PyTime_FromSecondsObject(PyTime_t *tp, PyObject *obj, _PyTime_round_t round)
624 {
625 return pytime_from_object(tp, obj, round, SEC_TO_NS);
626 }
627
628
629 int
_PyTime_FromMillisecondsObject(PyTime_t * tp,PyObject * obj,_PyTime_round_t round)630 _PyTime_FromMillisecondsObject(PyTime_t *tp, PyObject *obj, _PyTime_round_t round)
631 {
632 return pytime_from_object(tp, obj, round, MS_TO_NS);
633 }
634
635
636 double
PyTime_AsSecondsDouble(PyTime_t ns)637 PyTime_AsSecondsDouble(PyTime_t ns)
638 {
639 /* volatile avoids optimization changing how numbers are rounded */
640 volatile double d;
641
642 if (ns % SEC_TO_NS == 0) {
643 /* Divide using integers to avoid rounding issues on the integer part.
644 1e-9 cannot be stored exactly in IEEE 64-bit. */
645 PyTime_t secs = ns / SEC_TO_NS;
646 d = (double)secs;
647 }
648 else {
649 d = (double)ns;
650 d /= 1e9;
651 }
652 return d;
653 }
654
655
656 PyObject *
_PyTime_AsLong(PyTime_t ns)657 _PyTime_AsLong(PyTime_t ns)
658 {
659 static_assert(sizeof(long long) >= sizeof(PyTime_t),
660 "PyTime_t is larger than long long");
661 return PyLong_FromLongLong((long long)ns);
662 }
663
664 int
_PyTime_FromSecondsDouble(double seconds,_PyTime_round_t round,PyTime_t * result)665 _PyTime_FromSecondsDouble(double seconds, _PyTime_round_t round, PyTime_t *result)
666 {
667 return pytime_from_double(result, seconds, round, SEC_TO_NS);
668 }
669
670
671 static PyTime_t
pytime_divide_round_up(const PyTime_t t,const PyTime_t k)672 pytime_divide_round_up(const PyTime_t t, const PyTime_t k)
673 {
674 assert(k > 1);
675 if (t >= 0) {
676 // Don't use (t + k - 1) / k to avoid integer overflow
677 // if t is equal to PyTime_MAX
678 PyTime_t q = t / k;
679 if (t % k) {
680 q += 1;
681 }
682 return q;
683 }
684 else {
685 // Don't use (t - (k - 1)) / k to avoid integer overflow
686 // if t is equals to PyTime_MIN.
687 PyTime_t q = t / k;
688 if (t % k) {
689 q -= 1;
690 }
691 return q;
692 }
693 }
694
695
696 static PyTime_t
pytime_divide(const PyTime_t t,const PyTime_t k,const _PyTime_round_t round)697 pytime_divide(const PyTime_t t, const PyTime_t k,
698 const _PyTime_round_t round)
699 {
700 assert(k > 1);
701 if (round == _PyTime_ROUND_HALF_EVEN) {
702 PyTime_t x = t / k;
703 PyTime_t r = t % k;
704 PyTime_t abs_r = Py_ABS(r);
705 if (abs_r > k / 2 || (abs_r == k / 2 && (Py_ABS(x) & 1))) {
706 if (t >= 0) {
707 x++;
708 }
709 else {
710 x--;
711 }
712 }
713 return x;
714 }
715 else if (round == _PyTime_ROUND_CEILING) {
716 if (t >= 0) {
717 return pytime_divide_round_up(t, k);
718 }
719 else {
720 return t / k;
721 }
722 }
723 else if (round == _PyTime_ROUND_FLOOR){
724 if (t >= 0) {
725 return t / k;
726 }
727 else {
728 return pytime_divide_round_up(t, k);
729 }
730 }
731 else {
732 assert(round == _PyTime_ROUND_UP);
733 return pytime_divide_round_up(t, k);
734 }
735 }
736
737
738 // Compute (t / k, t % k) in (pq, pr).
739 // Make sure that 0 <= pr < k.
740 // Return 0 on success.
741 // Return -1 on underflow and store (PyTime_MIN, 0) in (pq, pr).
742 static int
pytime_divmod(const PyTime_t t,const PyTime_t k,PyTime_t * pq,PyTime_t * pr)743 pytime_divmod(const PyTime_t t, const PyTime_t k,
744 PyTime_t *pq, PyTime_t *pr)
745 {
746 assert(k > 1);
747 PyTime_t q = t / k;
748 PyTime_t r = t % k;
749 if (r < 0) {
750 if (q == PyTime_MIN) {
751 *pq = PyTime_MIN;
752 *pr = 0;
753 return -1;
754 }
755 r += k;
756 q -= 1;
757 }
758 assert(0 <= r && r < k);
759
760 *pq = q;
761 *pr = r;
762 return 0;
763 }
764
765
766 #ifdef MS_WINDOWS
767 PyTime_t
_PyTime_As100Nanoseconds(PyTime_t ns,_PyTime_round_t round)768 _PyTime_As100Nanoseconds(PyTime_t ns, _PyTime_round_t round)
769 {
770 return pytime_divide(ns, NS_TO_100NS, round);
771 }
772 #endif
773
774
775 PyTime_t
_PyTime_AsMicroseconds(PyTime_t ns,_PyTime_round_t round)776 _PyTime_AsMicroseconds(PyTime_t ns, _PyTime_round_t round)
777 {
778 return pytime_divide(ns, NS_TO_US, round);
779 }
780
781
782 PyTime_t
_PyTime_AsMilliseconds(PyTime_t ns,_PyTime_round_t round)783 _PyTime_AsMilliseconds(PyTime_t ns, _PyTime_round_t round)
784 {
785 return pytime_divide(ns, NS_TO_MS, round);
786 }
787
788
789 static int
pytime_as_timeval(PyTime_t ns,PyTime_t * ptv_sec,int * ptv_usec,_PyTime_round_t round)790 pytime_as_timeval(PyTime_t ns, PyTime_t *ptv_sec, int *ptv_usec,
791 _PyTime_round_t round)
792 {
793 PyTime_t us = pytime_divide(ns, US_TO_NS, round);
794
795 PyTime_t tv_sec, tv_usec;
796 int res = pytime_divmod(us, SEC_TO_US, &tv_sec, &tv_usec);
797 *ptv_sec = tv_sec;
798 *ptv_usec = (int)tv_usec;
799 return res;
800 }
801
802
803 static int
pytime_as_timeval_struct(PyTime_t t,struct timeval * tv,_PyTime_round_t round,int raise_exc)804 pytime_as_timeval_struct(PyTime_t t, struct timeval *tv,
805 _PyTime_round_t round, int raise_exc)
806 {
807 PyTime_t tv_sec;
808 int tv_usec;
809 int res = pytime_as_timeval(t, &tv_sec, &tv_usec, round);
810 int res2;
811 #ifdef MS_WINDOWS
812 // On Windows, timeval.tv_sec type is long
813 res2 = _PyTime_AsCLong(tv_sec, &tv->tv_sec);
814 #else
815 res2 = _PyTime_AsTime_t(tv_sec, &tv->tv_sec);
816 #endif
817 if (res2 < 0) {
818 tv_usec = 0;
819 }
820 tv->tv_usec = tv_usec;
821
822 if (raise_exc && (res < 0 || res2 < 0)) {
823 pytime_time_t_overflow();
824 return -1;
825 }
826 return 0;
827 }
828
829
830 int
_PyTime_AsTimeval(PyTime_t t,struct timeval * tv,_PyTime_round_t round)831 _PyTime_AsTimeval(PyTime_t t, struct timeval *tv, _PyTime_round_t round)
832 {
833 return pytime_as_timeval_struct(t, tv, round, 1);
834 }
835
836
837 void
_PyTime_AsTimeval_clamp(PyTime_t t,struct timeval * tv,_PyTime_round_t round)838 _PyTime_AsTimeval_clamp(PyTime_t t, struct timeval *tv, _PyTime_round_t round)
839 {
840 (void)pytime_as_timeval_struct(t, tv, round, 0);
841 }
842
843
844 int
_PyTime_AsTimevalTime_t(PyTime_t t,time_t * p_secs,int * us,_PyTime_round_t round)845 _PyTime_AsTimevalTime_t(PyTime_t t, time_t *p_secs, int *us,
846 _PyTime_round_t round)
847 {
848 PyTime_t secs;
849 if (pytime_as_timeval(t, &secs, us, round) < 0) {
850 pytime_time_t_overflow();
851 return -1;
852 }
853
854 if (_PyTime_AsTime_t(secs, p_secs) < 0) {
855 pytime_time_t_overflow();
856 return -1;
857 }
858 return 0;
859 }
860
861
862 #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
863 static int
pytime_as_timespec(PyTime_t ns,struct timespec * ts,int raise_exc)864 pytime_as_timespec(PyTime_t ns, struct timespec *ts, int raise_exc)
865 {
866 PyTime_t tv_sec, tv_nsec;
867 int res = pytime_divmod(ns, SEC_TO_NS, &tv_sec, &tv_nsec);
868
869 int res2 = _PyTime_AsTime_t(tv_sec, &ts->tv_sec);
870 if (res2 < 0) {
871 tv_nsec = 0;
872 }
873 ts->tv_nsec = tv_nsec;
874
875 if (raise_exc && (res < 0 || res2 < 0)) {
876 pytime_time_t_overflow();
877 return -1;
878 }
879 return 0;
880 }
881
882 void
_PyTime_AsTimespec_clamp(PyTime_t t,struct timespec * ts)883 _PyTime_AsTimespec_clamp(PyTime_t t, struct timespec *ts)
884 {
885 (void)pytime_as_timespec(t, ts, 0);
886 }
887
888 int
_PyTime_AsTimespec(PyTime_t t,struct timespec * ts)889 _PyTime_AsTimespec(PyTime_t t, struct timespec *ts)
890 {
891 return pytime_as_timespec(t, ts, 1);
892 }
893 #endif
894
895
896 // N.B. If raise_exc=0, this may be called without the GIL.
897 static int
py_get_system_clock(PyTime_t * tp,_Py_clock_info_t * info,int raise_exc)898 py_get_system_clock(PyTime_t *tp, _Py_clock_info_t *info, int raise_exc)
899 {
900 assert(info == NULL || raise_exc);
901 if (raise_exc) {
902 // raise_exc requires to hold the GIL
903 assert(PyGILState_Check());
904 }
905
906 #ifdef MS_WINDOWS
907 FILETIME system_time;
908 ULARGE_INTEGER large;
909
910 GetSystemTimePreciseAsFileTime(&system_time);
911 large.u.LowPart = system_time.dwLowDateTime;
912 large.u.HighPart = system_time.dwHighDateTime;
913 /* 11,644,473,600,000,000,000: number of nanoseconds between
914 the 1st january 1601 and the 1st january 1970 (369 years + 89 leap
915 days). */
916 PyTime_t ns = large.QuadPart * 100 - 11644473600000000000;
917 *tp = ns;
918 if (info) {
919 // GetSystemTimePreciseAsFileTime() is implemented using
920 // QueryPerformanceCounter() internally.
921 if (py_qpc_base.denom == 0) {
922 if (py_win_perf_counter_frequency(&py_qpc_base, raise_exc) < 0) {
923 return -1;
924 }
925 }
926
927 info->implementation = "GetSystemTimePreciseAsFileTime()";
928 info->monotonic = 0;
929 info->resolution = _PyTimeFraction_Resolution(&py_qpc_base);
930 info->adjustable = 1;
931 }
932
933 #else /* MS_WINDOWS */
934 int err;
935 #if defined(HAVE_CLOCK_GETTIME)
936 struct timespec ts;
937 #endif
938
939 #if !defined(HAVE_CLOCK_GETTIME) || defined(__APPLE__)
940 struct timeval tv;
941 #endif
942
943 #ifdef HAVE_CLOCK_GETTIME
944
945 #ifdef HAVE_CLOCK_GETTIME_RUNTIME
946 if (HAVE_CLOCK_GETTIME_RUNTIME) {
947 #endif
948
949 err = clock_gettime(CLOCK_REALTIME, &ts);
950 if (err) {
951 if (raise_exc) {
952 PyErr_SetFromErrno(PyExc_OSError);
953 }
954 return -1;
955 }
956 if (pytime_fromtimespec(tp, &ts, raise_exc) < 0) {
957 return -1;
958 }
959
960 if (info) {
961 struct timespec res;
962 info->implementation = "clock_gettime(CLOCK_REALTIME)";
963 info->monotonic = 0;
964 info->adjustable = 1;
965 if (clock_getres(CLOCK_REALTIME, &res) == 0) {
966 info->resolution = (double)res.tv_sec + (double)res.tv_nsec * 1e-9;
967 }
968 else {
969 info->resolution = 1e-9;
970 }
971 }
972
973 #ifdef HAVE_CLOCK_GETTIME_RUNTIME
974 }
975 else {
976 #endif
977
978 #endif
979
980 #if !defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETTIME_RUNTIME)
981
982 /* test gettimeofday() */
983 err = gettimeofday(&tv, (struct timezone *)NULL);
984 if (err) {
985 if (raise_exc) {
986 PyErr_SetFromErrno(PyExc_OSError);
987 }
988 return -1;
989 }
990 if (pytime_fromtimeval(tp, &tv, raise_exc) < 0) {
991 return -1;
992 }
993
994 if (info) {
995 info->implementation = "gettimeofday()";
996 info->resolution = 1e-6;
997 info->monotonic = 0;
998 info->adjustable = 1;
999 }
1000
1001 #if defined(HAVE_CLOCK_GETTIME_RUNTIME) && defined(HAVE_CLOCK_GETTIME)
1002 } /* end of availability block */
1003 #endif
1004
1005 #endif /* !HAVE_CLOCK_GETTIME */
1006 #endif /* !MS_WINDOWS */
1007 return 0;
1008 }
1009
1010
1011 int
PyTime_Time(PyTime_t * result)1012 PyTime_Time(PyTime_t *result)
1013 {
1014 if (py_get_system_clock(result, NULL, 1) < 0) {
1015 *result = 0;
1016 return -1;
1017 }
1018 return 0;
1019 }
1020
1021
1022 int
PyTime_TimeRaw(PyTime_t * result)1023 PyTime_TimeRaw(PyTime_t *result)
1024 {
1025 if (py_get_system_clock(result, NULL, 0) < 0) {
1026 *result = 0;
1027 return -1;
1028 }
1029 return 0;
1030 }
1031
1032
1033 int
_PyTime_TimeWithInfo(PyTime_t * t,_Py_clock_info_t * info)1034 _PyTime_TimeWithInfo(PyTime_t *t, _Py_clock_info_t *info)
1035 {
1036 return py_get_system_clock(t, info, 1);
1037 }
1038
1039
1040 #ifdef MS_WINDOWS
1041 static int
py_win_perf_counter_frequency(_PyTimeFraction * base,int raise_exc)1042 py_win_perf_counter_frequency(_PyTimeFraction *base, int raise_exc)
1043 {
1044 LARGE_INTEGER freq;
1045 // Since Windows XP, the function cannot fail.
1046 (void)QueryPerformanceFrequency(&freq);
1047 LONGLONG frequency = freq.QuadPart;
1048
1049 // Since Windows XP, frequency cannot be zero.
1050 assert(frequency >= 1);
1051
1052 Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(frequency));
1053 PyTime_t denom = (PyTime_t)frequency;
1054
1055 // Known QueryPerformanceFrequency() values:
1056 //
1057 // * 10,000,000 (10 MHz): 100 ns resolution
1058 // * 3,579,545 Hz (3.6 MHz): 279 ns resolution
1059 if (_PyTimeFraction_Set(base, SEC_TO_NS, denom) < 0) {
1060 if (raise_exc) {
1061 PyErr_SetString(PyExc_RuntimeError,
1062 "invalid QueryPerformanceFrequency");
1063 }
1064 return -1;
1065 }
1066 return 0;
1067 }
1068
1069
1070 // N.B. If raise_exc=0, this may be called without the GIL.
1071 static int
py_get_win_perf_counter(PyTime_t * tp,_Py_clock_info_t * info,int raise_exc)1072 py_get_win_perf_counter(PyTime_t *tp, _Py_clock_info_t *info, int raise_exc)
1073 {
1074 assert(info == NULL || raise_exc);
1075
1076 if (py_qpc_base.denom == 0) {
1077 if (py_win_perf_counter_frequency(&py_qpc_base, raise_exc) < 0) {
1078 return -1;
1079 }
1080 }
1081
1082 if (info) {
1083 info->implementation = "QueryPerformanceCounter()";
1084 info->resolution = _PyTimeFraction_Resolution(&py_qpc_base);
1085 info->monotonic = 1;
1086 info->adjustable = 0;
1087 }
1088
1089 LARGE_INTEGER now;
1090 QueryPerformanceCounter(&now);
1091 LONGLONG ticksll = now.QuadPart;
1092
1093 /* Make sure that casting LONGLONG to PyTime_t cannot overflow,
1094 both types are signed */
1095 PyTime_t ticks;
1096 static_assert(sizeof(ticksll) <= sizeof(ticks),
1097 "LONGLONG is larger than PyTime_t");
1098 ticks = (PyTime_t)ticksll;
1099
1100 *tp = _PyTimeFraction_Mul(ticks, &py_qpc_base);
1101 return 0;
1102 }
1103 #endif // MS_WINDOWS
1104
1105
1106 #ifdef __APPLE__
1107 static int
py_mach_timebase_info(_PyTimeFraction * base,int raise_exc)1108 py_mach_timebase_info(_PyTimeFraction *base, int raise_exc)
1109 {
1110 mach_timebase_info_data_t timebase;
1111 // According to the Technical Q&A QA1398, mach_timebase_info() cannot
1112 // fail: https://developer.apple.com/library/mac/#qa/qa1398/
1113 (void)mach_timebase_info(&timebase);
1114
1115 // Check that timebase.numer and timebase.denom can be casted to
1116 // PyTime_t. In practice, timebase uses uint32_t, so casting cannot
1117 // overflow. At the end, only make sure that the type is uint32_t
1118 // (PyTime_t is 64-bit long).
1119 Py_BUILD_ASSERT(sizeof(timebase.numer) <= sizeof(PyTime_t));
1120 Py_BUILD_ASSERT(sizeof(timebase.denom) <= sizeof(PyTime_t));
1121 PyTime_t numer = (PyTime_t)timebase.numer;
1122 PyTime_t denom = (PyTime_t)timebase.denom;
1123
1124 // Known time bases:
1125 //
1126 // * (1, 1) on Intel: 1 ns
1127 // * (1000000000, 33333335) on PowerPC: ~30 ns
1128 // * (1000000000, 25000000) on PowerPC: 40 ns
1129 if (_PyTimeFraction_Set(base, numer, denom) < 0) {
1130 if (raise_exc) {
1131 PyErr_SetString(PyExc_RuntimeError,
1132 "invalid mach_timebase_info");
1133 }
1134 return -1;
1135 }
1136 return 0;
1137 }
1138 #endif
1139
1140
1141 // N.B. If raise_exc=0, this may be called without the GIL.
1142 static int
py_get_monotonic_clock(PyTime_t * tp,_Py_clock_info_t * info,int raise_exc)1143 py_get_monotonic_clock(PyTime_t *tp, _Py_clock_info_t *info, int raise_exc)
1144 {
1145 assert(info == NULL || raise_exc);
1146 if (raise_exc) {
1147 // raise_exc requires to hold the GIL
1148 assert(PyGILState_Check());
1149 }
1150
1151 #if defined(MS_WINDOWS)
1152 if (py_get_win_perf_counter(tp, info, raise_exc) < 0) {
1153 return -1;
1154 }
1155 #elif defined(__APPLE__)
1156 static _PyTimeFraction base = {0, 0};
1157 if (base.denom == 0) {
1158 if (py_mach_timebase_info(&base, raise_exc) < 0) {
1159 return -1;
1160 }
1161 }
1162
1163 if (info) {
1164 info->implementation = "mach_absolute_time()";
1165 info->resolution = _PyTimeFraction_Resolution(&base);
1166 info->monotonic = 1;
1167 info->adjustable = 0;
1168 }
1169
1170 uint64_t uticks = mach_absolute_time();
1171 // unsigned => signed
1172 assert(uticks <= (uint64_t)PyTime_MAX);
1173 PyTime_t ticks = (PyTime_t)uticks;
1174
1175 PyTime_t ns = _PyTimeFraction_Mul(ticks, &base);
1176 *tp = ns;
1177
1178 #elif defined(__hpux)
1179 hrtime_t time = gethrtime();
1180 if (time == -1) {
1181 if (raise_exc) {
1182 PyErr_SetFromErrno(PyExc_OSError);
1183 }
1184 return -1;
1185 }
1186
1187 *tp = time;
1188
1189 if (info) {
1190 info->implementation = "gethrtime()";
1191 info->resolution = 1e-9;
1192 info->monotonic = 1;
1193 info->adjustable = 0;
1194 }
1195
1196 #else
1197
1198 #ifdef CLOCK_HIGHRES
1199 const clockid_t clk_id = CLOCK_HIGHRES;
1200 const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
1201 #else
1202 const clockid_t clk_id = CLOCK_MONOTONIC;
1203 const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
1204 #endif
1205
1206 struct timespec ts;
1207 if (clock_gettime(clk_id, &ts) != 0) {
1208 if (raise_exc) {
1209 PyErr_SetFromErrno(PyExc_OSError);
1210 return -1;
1211 }
1212 return -1;
1213 }
1214
1215 if (pytime_fromtimespec(tp, &ts, raise_exc) < 0) {
1216 return -1;
1217 }
1218
1219 if (info) {
1220 info->monotonic = 1;
1221 info->implementation = implementation;
1222 info->adjustable = 0;
1223 struct timespec res;
1224 if (clock_getres(clk_id, &res) != 0) {
1225 PyErr_SetFromErrno(PyExc_OSError);
1226 return -1;
1227 }
1228 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1229 }
1230 #endif
1231 return 0;
1232 }
1233
1234
1235 int
PyTime_Monotonic(PyTime_t * result)1236 PyTime_Monotonic(PyTime_t *result)
1237 {
1238 if (py_get_monotonic_clock(result, NULL, 1) < 0) {
1239 *result = 0;
1240 return -1;
1241 }
1242 return 0;
1243 }
1244
1245
1246 int
PyTime_MonotonicRaw(PyTime_t * result)1247 PyTime_MonotonicRaw(PyTime_t *result)
1248 {
1249 if (py_get_monotonic_clock(result, NULL, 0) < 0) {
1250 *result = 0;
1251 return -1;
1252 }
1253 return 0;
1254 }
1255
1256
1257 int
_PyTime_MonotonicWithInfo(PyTime_t * tp,_Py_clock_info_t * info)1258 _PyTime_MonotonicWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1259 {
1260 return py_get_monotonic_clock(tp, info, 1);
1261 }
1262
1263
1264 int
_PyTime_PerfCounterWithInfo(PyTime_t * t,_Py_clock_info_t * info)1265 _PyTime_PerfCounterWithInfo(PyTime_t *t, _Py_clock_info_t *info)
1266 {
1267 return _PyTime_MonotonicWithInfo(t, info);
1268 }
1269
1270
1271 int
PyTime_PerfCounter(PyTime_t * result)1272 PyTime_PerfCounter(PyTime_t *result)
1273 {
1274 return PyTime_Monotonic(result);
1275 }
1276
1277
1278 int
PyTime_PerfCounterRaw(PyTime_t * result)1279 PyTime_PerfCounterRaw(PyTime_t *result)
1280 {
1281 return PyTime_MonotonicRaw(result);
1282 }
1283
1284
1285 int
_PyTime_localtime(time_t t,struct tm * tm)1286 _PyTime_localtime(time_t t, struct tm *tm)
1287 {
1288 #ifdef MS_WINDOWS
1289 int error;
1290
1291 error = localtime_s(tm, &t);
1292 if (error != 0) {
1293 errno = error;
1294 PyErr_SetFromErrno(PyExc_OSError);
1295 return -1;
1296 }
1297 return 0;
1298 #else /* !MS_WINDOWS */
1299
1300 #if defined(_AIX) && (SIZEOF_TIME_T < 8)
1301 /* bpo-34373: AIX does not return NULL if t is too small or too large */
1302 if (t < -2145916800 /* 1902-01-01 */
1303 || t > 2145916800 /* 2038-01-01 */) {
1304 errno = EINVAL;
1305 PyErr_SetString(PyExc_OverflowError,
1306 "localtime argument out of range");
1307 return -1;
1308 }
1309 #endif
1310
1311 errno = 0;
1312 if (localtime_r(&t, tm) == NULL) {
1313 if (errno == 0) {
1314 errno = EINVAL;
1315 }
1316 PyErr_SetFromErrno(PyExc_OSError);
1317 return -1;
1318 }
1319 return 0;
1320 #endif /* MS_WINDOWS */
1321 }
1322
1323
1324 int
_PyTime_gmtime(time_t t,struct tm * tm)1325 _PyTime_gmtime(time_t t, struct tm *tm)
1326 {
1327 #ifdef MS_WINDOWS
1328 int error;
1329
1330 error = gmtime_s(tm, &t);
1331 if (error != 0) {
1332 errno = error;
1333 PyErr_SetFromErrno(PyExc_OSError);
1334 return -1;
1335 }
1336 return 0;
1337 #else /* !MS_WINDOWS */
1338 if (gmtime_r(&t, tm) == NULL) {
1339 #ifdef EINVAL
1340 if (errno == 0) {
1341 errno = EINVAL;
1342 }
1343 #endif
1344 PyErr_SetFromErrno(PyExc_OSError);
1345 return -1;
1346 }
1347 return 0;
1348 #endif /* MS_WINDOWS */
1349 }
1350
1351
1352 PyTime_t
_PyDeadline_Init(PyTime_t timeout)1353 _PyDeadline_Init(PyTime_t timeout)
1354 {
1355 PyTime_t now;
1356 // silently ignore error: cannot report error to the caller
1357 (void)PyTime_MonotonicRaw(&now);
1358 return _PyTime_Add(now, timeout);
1359 }
1360
1361
1362 PyTime_t
_PyDeadline_Get(PyTime_t deadline)1363 _PyDeadline_Get(PyTime_t deadline)
1364 {
1365 PyTime_t now;
1366 // silently ignore error: cannot report error to the caller
1367 (void)PyTime_MonotonicRaw(&now);
1368 return deadline - now;
1369 }
1370