Debian Codegraph @

pypy/module/cpyext/src/pytime.c

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