You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1135 lines
27 KiB

  1. #include "Python.h"
  2. #ifdef MS_WINDOWS
  3. #include <winsock2.h> /* struct timeval */
  4. #endif
  5. #if defined(__APPLE__)
  6. #include <mach/mach_time.h> /* mach_absolute_time(), mach_timebase_info() */
  7. #if defined(__APPLE__) && defined(__has_builtin)
  8. # if __has_builtin(__builtin_available)
  9. # define HAVE_CLOCK_GETTIME_RUNTIME __builtin_available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
  10. # endif
  11. #endif
  12. #endif
  13. #define _PyTime_check_mul_overflow(a, b) \
  14. (assert(b > 0), \
  15. (_PyTime_t)(a) < _PyTime_MIN / (_PyTime_t)(b) \
  16. || _PyTime_MAX / (_PyTime_t)(b) < (_PyTime_t)(a))
  17. /* To millisecond (10^-3) */
  18. #define SEC_TO_MS 1000
  19. /* To microseconds (10^-6) */
  20. #define MS_TO_US 1000
  21. #define SEC_TO_US (SEC_TO_MS * MS_TO_US)
  22. /* To nanoseconds (10^-9) */
  23. #define US_TO_NS 1000
  24. #define MS_TO_NS (MS_TO_US * US_TO_NS)
  25. #define SEC_TO_NS (SEC_TO_MS * MS_TO_NS)
  26. /* Conversion from nanoseconds */
  27. #define NS_TO_MS (1000 * 1000)
  28. #define NS_TO_US (1000)
  29. static void
  30. error_time_t_overflow(void)
  31. {
  32. PyErr_SetString(PyExc_OverflowError,
  33. "timestamp out of range for platform time_t");
  34. }
  35. static void
  36. _PyTime_overflow(void)
  37. {
  38. PyErr_SetString(PyExc_OverflowError,
  39. "timestamp too large to convert to C _PyTime_t");
  40. }
  41. _PyTime_t
  42. _PyTime_MulDiv(_PyTime_t ticks, _PyTime_t mul, _PyTime_t div)
  43. {
  44. _PyTime_t intpart, remaining;
  45. /* Compute (ticks * mul / div) in two parts to prevent integer overflow:
  46. compute integer part, and then the remaining part.
  47. (ticks * mul) / div == (ticks / div) * mul + (ticks % div) * mul / div
  48. The caller must ensure that "(div - 1) * mul" cannot overflow. */
  49. intpart = ticks / div;
  50. ticks %= div;
  51. remaining = ticks * mul;
  52. remaining /= div;
  53. return intpart * mul + remaining;
  54. }
  55. time_t
  56. _PyLong_AsTime_t(PyObject *obj)
  57. {
  58. #if SIZEOF_TIME_T == SIZEOF_LONG_LONG
  59. long long val;
  60. val = PyLong_AsLongLong(obj);
  61. #else
  62. long val;
  63. Py_BUILD_ASSERT(sizeof(time_t) <= sizeof(long));
  64. val = PyLong_AsLong(obj);
  65. #endif
  66. if (val == -1 && PyErr_Occurred()) {
  67. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  68. error_time_t_overflow();
  69. }
  70. return -1;
  71. }
  72. return (time_t)val;
  73. }
  74. PyObject *
  75. _PyLong_FromTime_t(time_t t)
  76. {
  77. #if SIZEOF_TIME_T == SIZEOF_LONG_LONG
  78. return PyLong_FromLongLong((long long)t);
  79. #else
  80. Py_BUILD_ASSERT(sizeof(time_t) <= sizeof(long));
  81. return PyLong_FromLong((long)t);
  82. #endif
  83. }
  84. /* Round to nearest with ties going to nearest even integer
  85. (_PyTime_ROUND_HALF_EVEN) */
  86. static double
  87. _PyTime_RoundHalfEven(double x)
  88. {
  89. double rounded = round(x);
  90. if (fabs(x-rounded) == 0.5) {
  91. /* halfway case: round to even */
  92. rounded = 2.0*round(x/2.0);
  93. }
  94. return rounded;
  95. }
  96. static double
  97. _PyTime_Round(double x, _PyTime_round_t round)
  98. {
  99. /* volatile avoids optimization changing how numbers are rounded */
  100. volatile double d;
  101. d = x;
  102. if (round == _PyTime_ROUND_HALF_EVEN) {
  103. d = _PyTime_RoundHalfEven(d);
  104. }
  105. else if (round == _PyTime_ROUND_CEILING) {
  106. d = ceil(d);
  107. }
  108. else if (round == _PyTime_ROUND_FLOOR) {
  109. d = floor(d);
  110. }
  111. else {
  112. assert(round == _PyTime_ROUND_UP);
  113. d = (d >= 0.0) ? ceil(d) : floor(d);
  114. }
  115. return d;
  116. }
  117. static int
  118. _PyTime_DoubleToDenominator(double d, time_t *sec, long *numerator,
  119. long idenominator, _PyTime_round_t round)
  120. {
  121. double denominator = (double)idenominator;
  122. double intpart;
  123. /* volatile avoids optimization changing how numbers are rounded */
  124. volatile double floatpart;
  125. floatpart = modf(d, &intpart);
  126. floatpart *= denominator;
  127. floatpart = _PyTime_Round(floatpart, round);
  128. if (floatpart >= denominator) {
  129. floatpart -= denominator;
  130. intpart += 1.0;
  131. }
  132. else if (floatpart < 0) {
  133. floatpart += denominator;
  134. intpart -= 1.0;
  135. }
  136. assert(0.0 <= floatpart && floatpart < denominator);
  137. if (!_Py_InIntegralTypeRange(time_t, intpart)) {
  138. error_time_t_overflow();
  139. return -1;
  140. }
  141. *sec = (time_t)intpart;
  142. *numerator = (long)floatpart;
  143. assert(0 <= *numerator && *numerator < idenominator);
  144. return 0;
  145. }
  146. static int
  147. _PyTime_ObjectToDenominator(PyObject *obj, time_t *sec, long *numerator,
  148. long denominator, _PyTime_round_t round)
  149. {
  150. assert(denominator >= 1);
  151. if (PyFloat_Check(obj)) {
  152. double d = PyFloat_AsDouble(obj);
  153. if (Py_IS_NAN(d)) {
  154. *numerator = 0;
  155. PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
  156. return -1;
  157. }
  158. return _PyTime_DoubleToDenominator(d, sec, numerator,
  159. denominator, round);
  160. }
  161. else {
  162. *sec = _PyLong_AsTime_t(obj);
  163. *numerator = 0;
  164. if (*sec == (time_t)-1 && PyErr_Occurred()) {
  165. return -1;
  166. }
  167. return 0;
  168. }
  169. }
  170. int
  171. _PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round)
  172. {
  173. if (PyFloat_Check(obj)) {
  174. double intpart;
  175. /* volatile avoids optimization changing how numbers are rounded */
  176. volatile double d;
  177. d = PyFloat_AsDouble(obj);
  178. if (Py_IS_NAN(d)) {
  179. PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
  180. return -1;
  181. }
  182. d = _PyTime_Round(d, round);
  183. (void)modf(d, &intpart);
  184. if (!_Py_InIntegralTypeRange(time_t, intpart)) {
  185. error_time_t_overflow();
  186. return -1;
  187. }
  188. *sec = (time_t)intpart;
  189. return 0;
  190. }
  191. else {
  192. *sec = _PyLong_AsTime_t(obj);
  193. if (*sec == (time_t)-1 && PyErr_Occurred()) {
  194. return -1;
  195. }
  196. return 0;
  197. }
  198. }
  199. int
  200. _PyTime_ObjectToTimespec(PyObject *obj, time_t *sec, long *nsec,
  201. _PyTime_round_t round)
  202. {
  203. return _PyTime_ObjectToDenominator(obj, sec, nsec, SEC_TO_NS, round);
  204. }
  205. int
  206. _PyTime_ObjectToTimeval(PyObject *obj, time_t *sec, long *usec,
  207. _PyTime_round_t round)
  208. {
  209. return _PyTime_ObjectToDenominator(obj, sec, usec, SEC_TO_US, round);
  210. }
  211. _PyTime_t
  212. _PyTime_FromSeconds(int seconds)
  213. {
  214. _PyTime_t t;
  215. /* ensure that integer overflow cannot happen, int type should have 32
  216. bits, whereas _PyTime_t type has at least 64 bits (SEC_TO_MS takes 30
  217. bits). */
  218. Py_BUILD_ASSERT(INT_MAX <= _PyTime_MAX / SEC_TO_NS);
  219. Py_BUILD_ASSERT(INT_MIN >= _PyTime_MIN / SEC_TO_NS);
  220. t = (_PyTime_t)seconds;
  221. assert((t >= 0 && t <= _PyTime_MAX / SEC_TO_NS)
  222. || (t < 0 && t >= _PyTime_MIN / SEC_TO_NS));
  223. t *= SEC_TO_NS;
  224. return t;
  225. }
  226. _PyTime_t
  227. _PyTime_FromNanoseconds(_PyTime_t ns)
  228. {
  229. /* _PyTime_t already uses nanosecond resolution, no conversion needed */
  230. return ns;
  231. }
  232. int
  233. _PyTime_FromNanosecondsObject(_PyTime_t *tp, PyObject *obj)
  234. {
  235. long long nsec;
  236. _PyTime_t t;
  237. if (!PyLong_Check(obj)) {
  238. PyErr_Format(PyExc_TypeError, "expect int, got %s",
  239. Py_TYPE(obj)->tp_name);
  240. return -1;
  241. }
  242. Py_BUILD_ASSERT(sizeof(long long) == sizeof(_PyTime_t));
  243. nsec = PyLong_AsLongLong(obj);
  244. if (nsec == -1 && PyErr_Occurred()) {
  245. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  246. _PyTime_overflow();
  247. }
  248. return -1;
  249. }
  250. /* _PyTime_t already uses nanosecond resolution, no conversion needed */
  251. t = (_PyTime_t)nsec;
  252. *tp = t;
  253. return 0;
  254. }
  255. #ifdef HAVE_CLOCK_GETTIME
  256. static int
  257. pytime_fromtimespec(_PyTime_t *tp, struct timespec *ts, int raise)
  258. {
  259. _PyTime_t t, nsec;
  260. int res = 0;
  261. Py_BUILD_ASSERT(sizeof(ts->tv_sec) <= sizeof(_PyTime_t));
  262. t = (_PyTime_t)ts->tv_sec;
  263. if (_PyTime_check_mul_overflow(t, SEC_TO_NS)) {
  264. if (raise) {
  265. _PyTime_overflow();
  266. }
  267. res = -1;
  268. t = (t > 0) ? _PyTime_MAX : _PyTime_MIN;
  269. }
  270. else {
  271. t = t * SEC_TO_NS;
  272. }
  273. nsec = ts->tv_nsec;
  274. /* The following test is written for positive only nsec */
  275. assert(nsec >= 0);
  276. if (t > _PyTime_MAX - nsec) {
  277. if (raise) {
  278. _PyTime_overflow();
  279. }
  280. res = -1;
  281. t = _PyTime_MAX;
  282. }
  283. else {
  284. t += nsec;
  285. }
  286. *tp = t;
  287. return res;
  288. }
  289. int
  290. _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts)
  291. {
  292. return pytime_fromtimespec(tp, ts, 1);
  293. }
  294. #endif
  295. #if !defined(MS_WINDOWS)
  296. static int
  297. pytime_fromtimeval(_PyTime_t *tp, struct timeval *tv, int raise)
  298. {
  299. _PyTime_t t, usec;
  300. int res = 0;
  301. Py_BUILD_ASSERT(sizeof(tv->tv_sec) <= sizeof(_PyTime_t));
  302. t = (_PyTime_t)tv->tv_sec;
  303. if (_PyTime_check_mul_overflow(t, SEC_TO_NS)) {
  304. if (raise) {
  305. _PyTime_overflow();
  306. }
  307. res = -1;
  308. t = (t > 0) ? _PyTime_MAX : _PyTime_MIN;
  309. }
  310. else {
  311. t = t * SEC_TO_NS;
  312. }
  313. usec = (_PyTime_t)tv->tv_usec * US_TO_NS;
  314. /* The following test is written for positive only usec */
  315. assert(usec >= 0);
  316. if (t > _PyTime_MAX - usec) {
  317. if (raise) {
  318. _PyTime_overflow();
  319. }
  320. res = -1;
  321. t = _PyTime_MAX;
  322. }
  323. else {
  324. t += usec;
  325. }
  326. *tp = t;
  327. return res;
  328. }
  329. int
  330. _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv)
  331. {
  332. return pytime_fromtimeval(tp, tv, 1);
  333. }
  334. #endif
  335. static int
  336. _PyTime_FromDouble(_PyTime_t *t, double value, _PyTime_round_t round,
  337. long unit_to_ns)
  338. {
  339. /* volatile avoids optimization changing how numbers are rounded */
  340. volatile double d;
  341. /* convert to a number of nanoseconds */
  342. d = value;
  343. d *= (double)unit_to_ns;
  344. d = _PyTime_Round(d, round);
  345. if (!_Py_InIntegralTypeRange(_PyTime_t, d)) {
  346. _PyTime_overflow();
  347. return -1;
  348. }
  349. *t = (_PyTime_t)d;
  350. return 0;
  351. }
  352. static int
  353. _PyTime_FromObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round,
  354. long unit_to_ns)
  355. {
  356. if (PyFloat_Check(obj)) {
  357. double d;
  358. d = PyFloat_AsDouble(obj);
  359. if (Py_IS_NAN(d)) {
  360. PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
  361. return -1;
  362. }
  363. return _PyTime_FromDouble(t, d, round, unit_to_ns);
  364. }
  365. else {
  366. long long sec;
  367. Py_BUILD_ASSERT(sizeof(long long) <= sizeof(_PyTime_t));
  368. sec = PyLong_AsLongLong(obj);
  369. if (sec == -1 && PyErr_Occurred()) {
  370. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  371. _PyTime_overflow();
  372. }
  373. return -1;
  374. }
  375. if (_PyTime_check_mul_overflow(sec, unit_to_ns)) {
  376. _PyTime_overflow();
  377. return -1;
  378. }
  379. *t = sec * unit_to_ns;
  380. return 0;
  381. }
  382. }
  383. int
  384. _PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
  385. {
  386. return _PyTime_FromObject(t, obj, round, SEC_TO_NS);
  387. }
  388. int
  389. _PyTime_FromMillisecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
  390. {
  391. return _PyTime_FromObject(t, obj, round, MS_TO_NS);
  392. }
  393. double
  394. _PyTime_AsSecondsDouble(_PyTime_t t)
  395. {
  396. /* volatile avoids optimization changing how numbers are rounded */
  397. volatile double d;
  398. if (t % SEC_TO_NS == 0) {
  399. _PyTime_t secs;
  400. /* Divide using integers to avoid rounding issues on the integer part.
  401. 1e-9 cannot be stored exactly in IEEE 64-bit. */
  402. secs = t / SEC_TO_NS;
  403. d = (double)secs;
  404. }
  405. else {
  406. d = (double)t;
  407. d /= 1e9;
  408. }
  409. return d;
  410. }
  411. PyObject *
  412. _PyTime_AsNanosecondsObject(_PyTime_t t)
  413. {
  414. Py_BUILD_ASSERT(sizeof(long long) >= sizeof(_PyTime_t));
  415. return PyLong_FromLongLong((long long)t);
  416. }
  417. static _PyTime_t
  418. _PyTime_Divide(const _PyTime_t t, const _PyTime_t k,
  419. const _PyTime_round_t round)
  420. {
  421. assert(k > 1);
  422. if (round == _PyTime_ROUND_HALF_EVEN) {
  423. _PyTime_t x, r, abs_r;
  424. x = t / k;
  425. r = t % k;
  426. abs_r = Py_ABS(r);
  427. if (abs_r > k / 2 || (abs_r == k / 2 && (Py_ABS(x) & 1))) {
  428. if (t >= 0) {
  429. x++;
  430. }
  431. else {
  432. x--;
  433. }
  434. }
  435. return x;
  436. }
  437. else if (round == _PyTime_ROUND_CEILING) {
  438. if (t >= 0) {
  439. return (t + k - 1) / k;
  440. }
  441. else {
  442. return t / k;
  443. }
  444. }
  445. else if (round == _PyTime_ROUND_FLOOR){
  446. if (t >= 0) {
  447. return t / k;
  448. }
  449. else {
  450. return (t - (k - 1)) / k;
  451. }
  452. }
  453. else {
  454. assert(round == _PyTime_ROUND_UP);
  455. if (t >= 0) {
  456. return (t + k - 1) / k;
  457. }
  458. else {
  459. return (t - (k - 1)) / k;
  460. }
  461. }
  462. }
  463. _PyTime_t
  464. _PyTime_AsMilliseconds(_PyTime_t t, _PyTime_round_t round)
  465. {
  466. return _PyTime_Divide(t, NS_TO_MS, round);
  467. }
  468. _PyTime_t
  469. _PyTime_AsMicroseconds(_PyTime_t t, _PyTime_round_t round)
  470. {
  471. return _PyTime_Divide(t, NS_TO_US, round);
  472. }
  473. static int
  474. _PyTime_AsTimeval_impl(_PyTime_t t, _PyTime_t *p_secs, int *p_us,
  475. _PyTime_round_t round)
  476. {
  477. _PyTime_t secs, ns;
  478. int usec;
  479. int res = 0;
  480. secs = t / SEC_TO_NS;
  481. ns = t % SEC_TO_NS;
  482. usec = (int)_PyTime_Divide(ns, US_TO_NS, round);
  483. if (usec < 0) {
  484. usec += SEC_TO_US;
  485. if (secs != _PyTime_MIN) {
  486. secs -= 1;
  487. }
  488. else {
  489. res = -1;
  490. }
  491. }
  492. else if (usec >= SEC_TO_US) {
  493. usec -= SEC_TO_US;
  494. if (secs != _PyTime_MAX) {
  495. secs += 1;
  496. }
  497. else {
  498. res = -1;
  499. }
  500. }
  501. assert(0 <= usec && usec < SEC_TO_US);
  502. *p_secs = secs;
  503. *p_us = usec;
  504. return res;
  505. }
  506. static int
  507. _PyTime_AsTimevalStruct_impl(_PyTime_t t, struct timeval *tv,
  508. _PyTime_round_t round, int raise)
  509. {
  510. _PyTime_t secs, secs2;
  511. int us;
  512. int res;
  513. res = _PyTime_AsTimeval_impl(t, &secs, &us, round);
  514. #ifdef MS_WINDOWS
  515. tv->tv_sec = (long)secs;
  516. #else
  517. tv->tv_sec = secs;
  518. #endif
  519. tv->tv_usec = us;
  520. secs2 = (_PyTime_t)tv->tv_sec;
  521. if (res < 0 || secs2 != secs) {
  522. if (raise) {
  523. error_time_t_overflow();
  524. }
  525. return -1;
  526. }
  527. return 0;
  528. }
  529. int
  530. _PyTime_AsTimeval(_PyTime_t t, struct timeval *tv, _PyTime_round_t round)
  531. {
  532. return _PyTime_AsTimevalStruct_impl(t, tv, round, 1);
  533. }
  534. int
  535. _PyTime_AsTimeval_noraise(_PyTime_t t, struct timeval *tv, _PyTime_round_t round)
  536. {
  537. return _PyTime_AsTimevalStruct_impl(t, tv, round, 0);
  538. }
  539. int
  540. _PyTime_AsTimevalTime_t(_PyTime_t t, time_t *p_secs, int *us,
  541. _PyTime_round_t round)
  542. {
  543. _PyTime_t secs;
  544. int res;
  545. res = _PyTime_AsTimeval_impl(t, &secs, us, round);
  546. *p_secs = secs;
  547. if (res < 0 || (_PyTime_t)*p_secs != secs) {
  548. error_time_t_overflow();
  549. return -1;
  550. }
  551. return 0;
  552. }
  553. #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
  554. int
  555. _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts)
  556. {
  557. _PyTime_t secs, nsec;
  558. secs = t / SEC_TO_NS;
  559. nsec = t % SEC_TO_NS;
  560. if (nsec < 0) {
  561. nsec += SEC_TO_NS;
  562. secs -= 1;
  563. }
  564. ts->tv_sec = (time_t)secs;
  565. assert(0 <= nsec && nsec < SEC_TO_NS);
  566. ts->tv_nsec = nsec;
  567. if ((_PyTime_t)ts->tv_sec != secs) {
  568. error_time_t_overflow();
  569. return -1;
  570. }
  571. return 0;
  572. }
  573. #endif
  574. static int
  575. pygettimeofday(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  576. {
  577. #ifdef MS_WINDOWS
  578. FILETIME system_time;
  579. ULARGE_INTEGER large;
  580. assert(info == NULL || raise);
  581. GetSystemTimeAsFileTime(&system_time);
  582. large.u.LowPart = system_time.dwLowDateTime;
  583. large.u.HighPart = system_time.dwHighDateTime;
  584. /* 11,644,473,600,000,000,000: number of nanoseconds between
  585. the 1st january 1601 and the 1st january 1970 (369 years + 89 leap
  586. days). */
  587. *tp = large.QuadPart * 100 - 11644473600000000000;
  588. if (info) {
  589. DWORD timeAdjustment, timeIncrement;
  590. BOOL isTimeAdjustmentDisabled, ok;
  591. info->implementation = "GetSystemTimeAsFileTime()";
  592. info->monotonic = 0;
  593. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  594. &isTimeAdjustmentDisabled);
  595. if (!ok) {
  596. PyErr_SetFromWindowsErr(0);
  597. return -1;
  598. }
  599. info->resolution = timeIncrement * 1e-7;
  600. info->adjustable = 1;
  601. }
  602. #else /* MS_WINDOWS */
  603. int err;
  604. #if defined(HAVE_CLOCK_GETTIME)
  605. struct timespec ts;
  606. #endif
  607. #if !defined(HAVE_CLOCK_GETTIME) || defined(__APPLE__)
  608. struct timeval tv;
  609. #endif
  610. assert(info == NULL || raise);
  611. #ifdef HAVE_CLOCK_GETTIME
  612. #ifdef HAVE_CLOCK_GETTIME_RUNTIME
  613. if (HAVE_CLOCK_GETTIME_RUNTIME) {
  614. #endif
  615. err = clock_gettime(CLOCK_REALTIME, &ts);
  616. if (err) {
  617. if (raise) {
  618. PyErr_SetFromErrno(PyExc_OSError);
  619. }
  620. return -1;
  621. }
  622. if (pytime_fromtimespec(tp, &ts, raise) < 0) {
  623. return -1;
  624. }
  625. if (info) {
  626. struct timespec res;
  627. info->implementation = "clock_gettime(CLOCK_REALTIME)";
  628. info->monotonic = 0;
  629. info->adjustable = 1;
  630. if (clock_getres(CLOCK_REALTIME, &res) == 0) {
  631. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  632. }
  633. else {
  634. info->resolution = 1e-9;
  635. }
  636. }
  637. #ifdef HAVE_CLOCK_GETTIME_RUNTIME
  638. } else {
  639. #endif
  640. #endif
  641. #if !defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETTIME_RUNTIME)
  642. /* test gettimeofday() */
  643. err = gettimeofday(&tv, (struct timezone *)NULL);
  644. if (err) {
  645. if (raise) {
  646. PyErr_SetFromErrno(PyExc_OSError);
  647. }
  648. return -1;
  649. }
  650. if (pytime_fromtimeval(tp, &tv, raise) < 0) {
  651. return -1;
  652. }
  653. if (info) {
  654. info->implementation = "gettimeofday()";
  655. info->resolution = 1e-6;
  656. info->monotonic = 0;
  657. info->adjustable = 1;
  658. }
  659. #if defined(HAVE_CLOCK_GETTIME_RUNTIME) && defined(HAVE_CLOCK_GETTIME)
  660. } /* end of availibity block */
  661. #endif
  662. #endif /* !HAVE_CLOCK_GETTIME */
  663. #endif /* !MS_WINDOWS */
  664. return 0;
  665. }
  666. _PyTime_t
  667. _PyTime_GetSystemClock(void)
  668. {
  669. _PyTime_t t;
  670. if (pygettimeofday(&t, NULL, 0) < 0) {
  671. /* should not happen, _PyTime_Init() checked the clock at startup */
  672. Py_FatalError("pygettimeofday() failed");
  673. }
  674. return t;
  675. }
  676. int
  677. _PyTime_GetSystemClockWithInfo(_PyTime_t *t, _Py_clock_info_t *info)
  678. {
  679. return pygettimeofday(t, info, 1);
  680. }
  681. static int
  682. pymonotonic(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  683. {
  684. #if defined(MS_WINDOWS)
  685. ULONGLONG ticks;
  686. _PyTime_t t;
  687. assert(info == NULL || raise);
  688. ticks = GetTickCount64();
  689. Py_BUILD_ASSERT(sizeof(ticks) <= sizeof(_PyTime_t));
  690. t = (_PyTime_t)ticks;
  691. if (_PyTime_check_mul_overflow(t, MS_TO_NS)) {
  692. if (raise) {
  693. _PyTime_overflow();
  694. return -1;
  695. }
  696. /* Hello, time traveler! */
  697. Py_FatalError("pymonotonic: integer overflow");
  698. }
  699. *tp = t * MS_TO_NS;
  700. if (info) {
  701. DWORD timeAdjustment, timeIncrement;
  702. BOOL isTimeAdjustmentDisabled, ok;
  703. info->implementation = "GetTickCount64()";
  704. info->monotonic = 1;
  705. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  706. &isTimeAdjustmentDisabled);
  707. if (!ok) {
  708. PyErr_SetFromWindowsErr(0);
  709. return -1;
  710. }
  711. info->resolution = timeIncrement * 1e-7;
  712. info->adjustable = 0;
  713. }
  714. #elif defined(__APPLE__)
  715. static mach_timebase_info_data_t timebase;
  716. static uint64_t t0 = 0;
  717. uint64_t ticks;
  718. if (timebase.denom == 0) {
  719. /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
  720. fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
  721. (void)mach_timebase_info(&timebase);
  722. /* Sanity check: should never occur in practice */
  723. if (timebase.numer < 1 || timebase.denom < 1) {
  724. PyErr_SetString(PyExc_RuntimeError,
  725. "invalid mach_timebase_info");
  726. return -1;
  727. }
  728. /* Check that timebase.numer and timebase.denom can be casted to
  729. _PyTime_t. In practice, timebase uses uint32_t, so casting cannot
  730. overflow. At the end, only make sure that the type is uint32_t
  731. (_PyTime_t is 64-bit long). */
  732. assert(sizeof(timebase.numer) < sizeof(_PyTime_t));
  733. assert(sizeof(timebase.denom) < sizeof(_PyTime_t));
  734. /* Make sure that (ticks * timebase.numer) cannot overflow in
  735. _PyTime_MulDiv(), with ticks < timebase.denom.
  736. Known time bases:
  737. * always (1, 1) on Intel
  738. * (1000000000, 33333335) or (1000000000, 25000000) on PowerPC
  739. None of these time bases can overflow with 64-bit _PyTime_t, but
  740. check for overflow, just in case. */
  741. if ((_PyTime_t)timebase.numer > _PyTime_MAX / (_PyTime_t)timebase.denom) {
  742. PyErr_SetString(PyExc_OverflowError,
  743. "mach_timebase_info is too large");
  744. return -1;
  745. }
  746. t0 = mach_absolute_time();
  747. }
  748. if (info) {
  749. info->implementation = "mach_absolute_time()";
  750. info->resolution = (double)timebase.numer / (double)timebase.denom * 1e-9;
  751. info->monotonic = 1;
  752. info->adjustable = 0;
  753. }
  754. ticks = mach_absolute_time();
  755. /* Use a "time zero" to reduce precision loss when converting time
  756. to floatting point number, as in time.monotonic(). */
  757. ticks -= t0;
  758. *tp = _PyTime_MulDiv(ticks,
  759. (_PyTime_t)timebase.numer,
  760. (_PyTime_t)timebase.denom);
  761. #elif defined(__hpux)
  762. hrtime_t time;
  763. time = gethrtime();
  764. if (time == -1) {
  765. if (raise) {
  766. PyErr_SetFromErrno(PyExc_OSError);
  767. }
  768. return -1;
  769. }
  770. *tp = time;
  771. if (info) {
  772. info->implementation = "gethrtime()";
  773. info->resolution = 1e-9;
  774. info->monotonic = 1;
  775. info->adjustable = 0;
  776. }
  777. #else
  778. struct timespec ts;
  779. #ifdef CLOCK_HIGHRES
  780. const clockid_t clk_id = CLOCK_HIGHRES;
  781. const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
  782. #else
  783. const clockid_t clk_id = CLOCK_MONOTONIC;
  784. const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
  785. #endif
  786. assert(info == NULL || raise);
  787. if (clock_gettime(clk_id, &ts) != 0) {
  788. if (raise) {
  789. PyErr_SetFromErrno(PyExc_OSError);
  790. return -1;
  791. }
  792. return -1;
  793. }
  794. if (info) {
  795. struct timespec res;
  796. info->monotonic = 1;
  797. info->implementation = implementation;
  798. info->adjustable = 0;
  799. if (clock_getres(clk_id, &res) != 0) {
  800. PyErr_SetFromErrno(PyExc_OSError);
  801. return -1;
  802. }
  803. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  804. }
  805. if (pytime_fromtimespec(tp, &ts, raise) < 0) {
  806. return -1;
  807. }
  808. #endif
  809. return 0;
  810. }
  811. _PyTime_t
  812. _PyTime_GetMonotonicClock(void)
  813. {
  814. _PyTime_t t;
  815. if (pymonotonic(&t, NULL, 0) < 0) {
  816. /* should not happen, _PyTime_Init() checked that monotonic clock at
  817. startup */
  818. Py_FatalError("pymonotonic() failed");
  819. }
  820. return t;
  821. }
  822. int
  823. _PyTime_GetMonotonicClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  824. {
  825. return pymonotonic(tp, info, 1);
  826. }
  827. #ifdef MS_WINDOWS
  828. static int
  829. win_perf_counter(_PyTime_t *tp, _Py_clock_info_t *info)
  830. {
  831. static LONGLONG frequency = 0;
  832. static LONGLONG t0 = 0;
  833. LARGE_INTEGER now;
  834. LONGLONG ticksll;
  835. _PyTime_t ticks;
  836. if (frequency == 0) {
  837. LARGE_INTEGER freq;
  838. if (!QueryPerformanceFrequency(&freq)) {
  839. PyErr_SetFromWindowsErr(0);
  840. return -1;
  841. }
  842. frequency = freq.QuadPart;
  843. /* Sanity check: should never occur in practice */
  844. if (frequency < 1) {
  845. PyErr_SetString(PyExc_RuntimeError,
  846. "invalid QueryPerformanceFrequency");
  847. return -1;
  848. }
  849. /* Check that frequency can be casted to _PyTime_t.
  850. Make also sure that (ticks * SEC_TO_NS) cannot overflow in
  851. _PyTime_MulDiv(), with ticks < frequency.
  852. Known QueryPerformanceFrequency() values:
  853. * 10,000,000 (10 MHz): 100 ns resolution
  854. * 3,579,545 Hz (3.6 MHz): 279 ns resolution
  855. None of these frequencies can overflow with 64-bit _PyTime_t, but
  856. check for overflow, just in case. */
  857. if (frequency > _PyTime_MAX
  858. || frequency > (LONGLONG)_PyTime_MAX / (LONGLONG)SEC_TO_NS) {
  859. PyErr_SetString(PyExc_OverflowError,
  860. "QueryPerformanceFrequency is too large");
  861. return -1;
  862. }
  863. QueryPerformanceCounter(&now);
  864. t0 = now.QuadPart;
  865. }
  866. if (info) {
  867. info->implementation = "QueryPerformanceCounter()";
  868. info->resolution = 1.0 / (double)frequency;
  869. info->monotonic = 1;
  870. info->adjustable = 0;
  871. }
  872. QueryPerformanceCounter(&now);
  873. ticksll = now.QuadPart;
  874. /* Use a "time zero" to reduce precision loss when converting time
  875. to floatting point number, as in time.perf_counter(). */
  876. ticksll -= t0;
  877. /* Make sure that casting LONGLONG to _PyTime_t cannot overflow,
  878. both types are signed */
  879. Py_BUILD_ASSERT(sizeof(ticksll) <= sizeof(ticks));
  880. ticks = (_PyTime_t)ticksll;
  881. *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)frequency);
  882. return 0;
  883. }
  884. #endif
  885. int
  886. _PyTime_GetPerfCounterWithInfo(_PyTime_t *t, _Py_clock_info_t *info)
  887. {
  888. #ifdef MS_WINDOWS
  889. return win_perf_counter(t, info);
  890. #else
  891. return _PyTime_GetMonotonicClockWithInfo(t, info);
  892. #endif
  893. }
  894. _PyTime_t
  895. _PyTime_GetPerfCounter(void)
  896. {
  897. _PyTime_t t;
  898. if (_PyTime_GetPerfCounterWithInfo(&t, NULL)) {
  899. Py_FatalError("_PyTime_GetPerfCounterWithInfo() failed");
  900. }
  901. return t;
  902. }
  903. int
  904. _PyTime_Init(void)
  905. {
  906. /* check that time.time(), time.monotonic() and time.perf_counter() clocks
  907. are working properly to not have to check for exceptions at runtime. If
  908. a clock works once, it cannot fail in next calls. */
  909. _PyTime_t t;
  910. if (_PyTime_GetSystemClockWithInfo(&t, NULL) < 0) {
  911. return -1;
  912. }
  913. if (_PyTime_GetMonotonicClockWithInfo(&t, NULL) < 0) {
  914. return -1;
  915. }
  916. if (_PyTime_GetPerfCounterWithInfo(&t, NULL) < 0) {
  917. return -1;
  918. }
  919. return 0;
  920. }
  921. int
  922. _PyTime_localtime(time_t t, struct tm *tm)
  923. {
  924. #ifdef MS_WINDOWS
  925. int error;
  926. error = localtime_s(tm, &t);
  927. if (error != 0) {
  928. errno = error;
  929. PyErr_SetFromErrno(PyExc_OSError);
  930. return -1;
  931. }
  932. return 0;
  933. #else /* !MS_WINDOWS */
  934. #if defined(_AIX) && (SIZEOF_TIME_T < 8)
  935. /* bpo-34373: AIX does not return NULL if t is too small or too large */
  936. if (t < -2145916800 /* 1902-01-01 */
  937. || t > 2145916800 /* 2038-01-01 */) {
  938. errno = EINVAL;
  939. PyErr_SetString(PyExc_OverflowError,
  940. "localtime argument out of range");
  941. return -1;
  942. }
  943. #endif
  944. errno = 0;
  945. if (localtime_r(&t, tm) == NULL) {
  946. if (errno == 0) {
  947. errno = EINVAL;
  948. }
  949. PyErr_SetFromErrno(PyExc_OSError);
  950. return -1;
  951. }
  952. return 0;
  953. #endif /* MS_WINDOWS */
  954. }
  955. int
  956. _PyTime_gmtime(time_t t, struct tm *tm)
  957. {
  958. #ifdef MS_WINDOWS
  959. int error;
  960. error = gmtime_s(tm, &t);
  961. if (error != 0) {
  962. errno = error;
  963. PyErr_SetFromErrno(PyExc_OSError);
  964. return -1;
  965. }
  966. return 0;
  967. #else /* !MS_WINDOWS */
  968. if (gmtime_r(&t, tm) == NULL) {
  969. #ifdef EINVAL
  970. if (errno == 0) {
  971. errno = EINVAL;
  972. }
  973. #endif
  974. PyErr_SetFromErrno(PyExc_OSError);
  975. return -1;
  976. }
  977. return 0;
  978. #endif /* MS_WINDOWS */
  979. }