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.

1103 lines
26 KiB

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