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.

1149 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. res = -1;
  267. }
  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. res = -1;
  280. }
  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. res = -1;
  307. }
  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. res = -1;
  320. }
  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. py_get_system_clock(_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 (py_get_system_clock(&t, NULL, 0) < 0) {
  671. // If clock_gettime(CLOCK_REALTIME) or gettimeofday() fails:
  672. // silently ignore the failure and return 0.
  673. t = 0;
  674. }
  675. return t;
  676. }
  677. int
  678. _PyTime_GetSystemClockWithInfo(_PyTime_t *t, _Py_clock_info_t *info)
  679. {
  680. return py_get_system_clock(t, info, 1);
  681. }
  682. #if __APPLE__
  683. static int
  684. py_mach_timebase_info(_PyTime_t *pnumer, _PyTime_t *pdenom, int raise)
  685. {
  686. static mach_timebase_info_data_t timebase;
  687. /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
  688. fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
  689. (void)mach_timebase_info(&timebase);
  690. /* Sanity check: should never occur in practice */
  691. if (timebase.numer < 1 || timebase.denom < 1) {
  692. if (raise) {
  693. PyErr_SetString(PyExc_RuntimeError,
  694. "invalid mach_timebase_info");
  695. }
  696. return -1;
  697. }
  698. /* Check that timebase.numer and timebase.denom can be casted to
  699. _PyTime_t. In practice, timebase uses uint32_t, so casting cannot
  700. overflow. At the end, only make sure that the type is uint32_t
  701. (_PyTime_t is 64-bit long). */
  702. Py_BUILD_ASSERT(sizeof(timebase.numer) < sizeof(_PyTime_t));
  703. Py_BUILD_ASSERT(sizeof(timebase.denom) < sizeof(_PyTime_t));
  704. /* Make sure that (ticks * timebase.numer) cannot overflow in
  705. _PyTime_MulDiv(), with ticks < timebase.denom.
  706. Known time bases:
  707. * always (1, 1) on Intel
  708. * (1000000000, 33333335) or (1000000000, 25000000) on PowerPC
  709. None of these time bases can overflow with 64-bit _PyTime_t, but
  710. check for overflow, just in case. */
  711. if ((_PyTime_t)timebase.numer > _PyTime_MAX / (_PyTime_t)timebase.denom) {
  712. if (raise) {
  713. PyErr_SetString(PyExc_OverflowError,
  714. "mach_timebase_info is too large");
  715. }
  716. return -1;
  717. }
  718. *pnumer = (_PyTime_t)timebase.numer;
  719. *pdenom = (_PyTime_t)timebase.denom;
  720. return 0;
  721. }
  722. #endif
  723. static int
  724. py_get_monotonic_clock(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  725. {
  726. #if defined(MS_WINDOWS)
  727. ULONGLONG ticks;
  728. _PyTime_t t;
  729. assert(info == NULL || raise);
  730. ticks = GetTickCount64();
  731. Py_BUILD_ASSERT(sizeof(ticks) <= sizeof(_PyTime_t));
  732. t = (_PyTime_t)ticks;
  733. if (_PyTime_check_mul_overflow(t, MS_TO_NS)) {
  734. if (raise) {
  735. _PyTime_overflow();
  736. return -1;
  737. }
  738. // Truncate to _PyTime_MAX silently.
  739. *tp = _PyTime_MAX;
  740. }
  741. else {
  742. *tp = t * MS_TO_NS;
  743. }
  744. if (info) {
  745. DWORD timeAdjustment, timeIncrement;
  746. BOOL isTimeAdjustmentDisabled, ok;
  747. info->implementation = "GetTickCount64()";
  748. info->monotonic = 1;
  749. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  750. &isTimeAdjustmentDisabled);
  751. if (!ok) {
  752. PyErr_SetFromWindowsErr(0);
  753. return -1;
  754. }
  755. info->resolution = timeIncrement * 1e-7;
  756. info->adjustable = 0;
  757. }
  758. #elif defined(__APPLE__)
  759. static _PyTime_t timebase_numer = 0;
  760. static _PyTime_t timebase_denom = 0;
  761. if (timebase_denom == 0) {
  762. if (py_mach_timebase_info(&timebase_numer, &timebase_denom, raise) < 0) {
  763. return -1;
  764. }
  765. }
  766. if (info) {
  767. info->implementation = "mach_absolute_time()";
  768. info->resolution = (double)timebase_numer / (double)timebase_denom * 1e-9;
  769. info->monotonic = 1;
  770. info->adjustable = 0;
  771. }
  772. uint64_t ticks = mach_absolute_time();
  773. *tp = _PyTime_MulDiv((_PyTime_t)ticks, timebase_numer, timebase_denom);
  774. #elif defined(__hpux)
  775. hrtime_t time;
  776. time = gethrtime();
  777. if (time == -1) {
  778. if (raise) {
  779. PyErr_SetFromErrno(PyExc_OSError);
  780. }
  781. return -1;
  782. }
  783. *tp = time;
  784. if (info) {
  785. info->implementation = "gethrtime()";
  786. info->resolution = 1e-9;
  787. info->monotonic = 1;
  788. info->adjustable = 0;
  789. }
  790. #else
  791. struct timespec ts;
  792. #ifdef CLOCK_HIGHRES
  793. const clockid_t clk_id = CLOCK_HIGHRES;
  794. const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
  795. #else
  796. const clockid_t clk_id = CLOCK_MONOTONIC;
  797. const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
  798. #endif
  799. assert(info == NULL || raise);
  800. if (clock_gettime(clk_id, &ts) != 0) {
  801. if (raise) {
  802. PyErr_SetFromErrno(PyExc_OSError);
  803. return -1;
  804. }
  805. return -1;
  806. }
  807. if (info) {
  808. struct timespec res;
  809. info->monotonic = 1;
  810. info->implementation = implementation;
  811. info->adjustable = 0;
  812. if (clock_getres(clk_id, &res) != 0) {
  813. PyErr_SetFromErrno(PyExc_OSError);
  814. return -1;
  815. }
  816. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  817. }
  818. if (pytime_fromtimespec(tp, &ts, raise) < 0) {
  819. return -1;
  820. }
  821. #endif
  822. return 0;
  823. }
  824. _PyTime_t
  825. _PyTime_GetMonotonicClock(void)
  826. {
  827. _PyTime_t t;
  828. if (py_get_monotonic_clock(&t, NULL, 0) < 0) {
  829. // If mach_timebase_info(), clock_gettime() or gethrtime() fails:
  830. // silently ignore the failure and return 0.
  831. t = 0;
  832. }
  833. return t;
  834. }
  835. int
  836. _PyTime_GetMonotonicClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  837. {
  838. return py_get_monotonic_clock(tp, info, 1);
  839. }
  840. #ifdef MS_WINDOWS
  841. static int
  842. win_perf_counter_frequency(LONGLONG *pfrequency, int raise)
  843. {
  844. LONGLONG frequency;
  845. LARGE_INTEGER freq;
  846. if (!QueryPerformanceFrequency(&freq)) {
  847. if (raise) {
  848. PyErr_SetFromWindowsErr(0);
  849. }
  850. return -1;
  851. }
  852. frequency = freq.QuadPart;
  853. /* Sanity check: should never occur in practice */
  854. if (frequency < 1) {
  855. if (raise) {
  856. PyErr_SetString(PyExc_RuntimeError,
  857. "invalid QueryPerformanceFrequency");
  858. }
  859. return -1;
  860. }
  861. /* Check that frequency can be casted to _PyTime_t.
  862. Make also sure that (ticks * SEC_TO_NS) cannot overflow in
  863. _PyTime_MulDiv(), with ticks < frequency.
  864. Known QueryPerformanceFrequency() values:
  865. * 10,000,000 (10 MHz): 100 ns resolution
  866. * 3,579,545 Hz (3.6 MHz): 279 ns resolution
  867. None of these frequencies can overflow with 64-bit _PyTime_t, but
  868. check for overflow, just in case. */
  869. if (frequency > _PyTime_MAX
  870. || frequency > (LONGLONG)_PyTime_MAX / (LONGLONG)SEC_TO_NS)
  871. {
  872. if (raise) {
  873. PyErr_SetString(PyExc_OverflowError,
  874. "QueryPerformanceFrequency is too large");
  875. }
  876. return -1;
  877. }
  878. *pfrequency = frequency;
  879. return 0;
  880. }
  881. static int
  882. py_get_win_perf_counter(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  883. {
  884. static LONGLONG frequency = 0;
  885. if (frequency == 0) {
  886. if (win_perf_counter_frequency(&frequency, raise) < 0) {
  887. return -1;
  888. }
  889. }
  890. if (info) {
  891. info->implementation = "QueryPerformanceCounter()";
  892. info->resolution = 1.0 / (double)frequency;
  893. info->monotonic = 1;
  894. info->adjustable = 0;
  895. }
  896. LARGE_INTEGER now;
  897. QueryPerformanceCounter(&now);
  898. LONGLONG ticksll = now.QuadPart;
  899. /* Make sure that casting LONGLONG to _PyTime_t cannot overflow,
  900. both types are signed */
  901. _PyTime_t ticks;
  902. Py_BUILD_ASSERT(sizeof(ticksll) <= sizeof(ticks));
  903. ticks = (_PyTime_t)ticksll;
  904. *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)frequency);
  905. return 0;
  906. }
  907. #endif
  908. int
  909. _PyTime_GetPerfCounterWithInfo(_PyTime_t *t, _Py_clock_info_t *info)
  910. {
  911. #ifdef MS_WINDOWS
  912. return py_get_win_perf_counter(t, info, 1);
  913. #else
  914. return _PyTime_GetMonotonicClockWithInfo(t, info);
  915. #endif
  916. }
  917. _PyTime_t
  918. _PyTime_GetPerfCounter(void)
  919. {
  920. _PyTime_t t;
  921. int res;
  922. #ifdef MS_WINDOWS
  923. res = py_get_win_perf_counter(&t, NULL, 0);
  924. #else
  925. res = py_get_monotonic_clock(&t, NULL, 0);
  926. #endif
  927. if (res < 0) {
  928. // If win_perf_counter_frequency() or py_get_monotonic_clock() fails:
  929. // silently ignore the failure and return 0.
  930. t = 0;
  931. }
  932. return t;
  933. }
  934. int
  935. _PyTime_localtime(time_t t, struct tm *tm)
  936. {
  937. #ifdef MS_WINDOWS
  938. int error;
  939. error = localtime_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 defined(_AIX) && (SIZEOF_TIME_T < 8)
  948. /* bpo-34373: AIX does not return NULL if t is too small or too large */
  949. if (t < -2145916800 /* 1902-01-01 */
  950. || t > 2145916800 /* 2038-01-01 */) {
  951. errno = EINVAL;
  952. PyErr_SetString(PyExc_OverflowError,
  953. "localtime argument out of range");
  954. return -1;
  955. }
  956. #endif
  957. errno = 0;
  958. if (localtime_r(&t, tm) == NULL) {
  959. if (errno == 0) {
  960. errno = EINVAL;
  961. }
  962. PyErr_SetFromErrno(PyExc_OSError);
  963. return -1;
  964. }
  965. return 0;
  966. #endif /* MS_WINDOWS */
  967. }
  968. int
  969. _PyTime_gmtime(time_t t, struct tm *tm)
  970. {
  971. #ifdef MS_WINDOWS
  972. int error;
  973. error = gmtime_s(tm, &t);
  974. if (error != 0) {
  975. errno = error;
  976. PyErr_SetFromErrno(PyExc_OSError);
  977. return -1;
  978. }
  979. return 0;
  980. #else /* !MS_WINDOWS */
  981. if (gmtime_r(&t, tm) == NULL) {
  982. #ifdef EINVAL
  983. if (errno == 0) {
  984. errno = EINVAL;
  985. }
  986. #endif
  987. PyErr_SetFromErrno(PyExc_OSError);
  988. return -1;
  989. }
  990. return 0;
  991. #endif /* MS_WINDOWS */
  992. }