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.

696 lines
16 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. /* To millisecond (10^-3) */
  9. #define SEC_TO_MS 1000
  10. /* To microseconds (10^-6) */
  11. #define MS_TO_US 1000
  12. #define SEC_TO_US (SEC_TO_MS * MS_TO_US)
  13. /* To nanoseconds (10^-9) */
  14. #define US_TO_NS 1000
  15. #define MS_TO_NS (MS_TO_US * US_TO_NS)
  16. #define SEC_TO_NS (SEC_TO_MS * MS_TO_NS)
  17. /* Conversion from nanoseconds */
  18. #define NS_TO_MS (1000 * 1000)
  19. #define NS_TO_US (1000)
  20. static void
  21. error_time_t_overflow(void)
  22. {
  23. PyErr_SetString(PyExc_OverflowError,
  24. "timestamp out of range for platform time_t");
  25. }
  26. time_t
  27. _PyLong_AsTime_t(PyObject *obj)
  28. {
  29. #if defined(HAVE_LONG_LONG) && SIZEOF_TIME_T == SIZEOF_LONG_LONG
  30. PY_LONG_LONG val;
  31. val = PyLong_AsLongLong(obj);
  32. #else
  33. long val;
  34. assert(sizeof(time_t) <= sizeof(long));
  35. val = PyLong_AsLong(obj);
  36. #endif
  37. if (val == -1 && PyErr_Occurred()) {
  38. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  39. error_time_t_overflow();
  40. return -1;
  41. }
  42. return (time_t)val;
  43. }
  44. PyObject *
  45. _PyLong_FromTime_t(time_t t)
  46. {
  47. #if defined(HAVE_LONG_LONG) && SIZEOF_TIME_T == SIZEOF_LONG_LONG
  48. return PyLong_FromLongLong((PY_LONG_LONG)t);
  49. #else
  50. assert(sizeof(time_t) <= sizeof(long));
  51. return PyLong_FromLong((long)t);
  52. #endif
  53. }
  54. static int
  55. _PyTime_ObjectToDenominator(PyObject *obj, time_t *sec, long *numerator,
  56. double denominator, _PyTime_round_t round)
  57. {
  58. assert(denominator <= LONG_MAX);
  59. if (PyFloat_Check(obj)) {
  60. double d, intpart, err;
  61. /* volatile avoids unsafe optimization on float enabled by gcc -O3 */
  62. volatile double floatpart;
  63. d = PyFloat_AsDouble(obj);
  64. floatpart = modf(d, &intpart);
  65. if (floatpart < 0) {
  66. floatpart = 1.0 + floatpart;
  67. intpart -= 1.0;
  68. }
  69. floatpart *= denominator;
  70. if (round == _PyTime_ROUND_CEILING) {
  71. floatpart = ceil(floatpart);
  72. if (floatpart >= denominator) {
  73. floatpart = 0.0;
  74. intpart += 1.0;
  75. }
  76. }
  77. else {
  78. floatpart = floor(floatpart);
  79. }
  80. *sec = (time_t)intpart;
  81. err = intpart - (double)*sec;
  82. if (err <= -1.0 || err >= 1.0) {
  83. error_time_t_overflow();
  84. return -1;
  85. }
  86. *numerator = (long)floatpart;
  87. return 0;
  88. }
  89. else {
  90. *sec = _PyLong_AsTime_t(obj);
  91. if (*sec == (time_t)-1 && PyErr_Occurred())
  92. return -1;
  93. *numerator = 0;
  94. return 0;
  95. }
  96. }
  97. int
  98. _PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round)
  99. {
  100. if (PyFloat_Check(obj)) {
  101. double d, intpart, err;
  102. d = PyFloat_AsDouble(obj);
  103. if (round == _PyTime_ROUND_CEILING)
  104. d = ceil(d);
  105. else
  106. d = floor(d);
  107. (void)modf(d, &intpart);
  108. *sec = (time_t)intpart;
  109. err = intpart - (double)*sec;
  110. if (err <= -1.0 || err >= 1.0) {
  111. error_time_t_overflow();
  112. return -1;
  113. }
  114. return 0;
  115. }
  116. else {
  117. *sec = _PyLong_AsTime_t(obj);
  118. if (*sec == (time_t)-1 && PyErr_Occurred())
  119. return -1;
  120. return 0;
  121. }
  122. }
  123. int
  124. _PyTime_ObjectToTimespec(PyObject *obj, time_t *sec, long *nsec,
  125. _PyTime_round_t round)
  126. {
  127. return _PyTime_ObjectToDenominator(obj, sec, nsec, 1e9, round);
  128. }
  129. int
  130. _PyTime_ObjectToTimeval(PyObject *obj, time_t *sec, long *usec,
  131. _PyTime_round_t round)
  132. {
  133. return _PyTime_ObjectToDenominator(obj, sec, usec, 1e6, round);
  134. }
  135. static void
  136. _PyTime_overflow(void)
  137. {
  138. PyErr_SetString(PyExc_OverflowError,
  139. "timestamp too large to convert to C _PyTime_t");
  140. }
  141. _PyTime_t
  142. _PyTime_FromSeconds(int seconds)
  143. {
  144. _PyTime_t t;
  145. /* ensure that integer overflow cannot happen, int type should have 32
  146. bits, whereas _PyTime_t type has at least 64 bits (SEC_TO_MS takes 30
  147. bits). */
  148. assert((seconds >= 0 && seconds <= _PyTime_MAX / SEC_TO_NS)
  149. || (seconds < 0 && seconds >= _PyTime_MIN / SEC_TO_NS));
  150. t = (_PyTime_t)seconds * SEC_TO_NS;
  151. return t;
  152. }
  153. _PyTime_t
  154. _PyTime_FromNanoseconds(PY_LONG_LONG ns)
  155. {
  156. _PyTime_t t;
  157. assert(sizeof(PY_LONG_LONG) <= sizeof(_PyTime_t));
  158. t = Py_SAFE_DOWNCAST(ns, PY_LONG_LONG, _PyTime_t);
  159. return t;
  160. }
  161. #ifdef HAVE_CLOCK_GETTIME
  162. static int
  163. _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts, int raise)
  164. {
  165. _PyTime_t t;
  166. int res = 0;
  167. t = (_PyTime_t)ts->tv_sec * SEC_TO_NS;
  168. if (t / SEC_TO_NS != ts->tv_sec) {
  169. if (raise)
  170. _PyTime_overflow();
  171. res = -1;
  172. }
  173. t += ts->tv_nsec;
  174. *tp = t;
  175. return res;
  176. }
  177. #elif !defined(MS_WINDOWS)
  178. static int
  179. _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv, int raise)
  180. {
  181. _PyTime_t t;
  182. int res = 0;
  183. t = (_PyTime_t)tv->tv_sec * SEC_TO_NS;
  184. if (t / SEC_TO_NS != tv->tv_sec) {
  185. if (raise)
  186. _PyTime_overflow();
  187. res = -1;
  188. }
  189. t += (_PyTime_t)tv->tv_usec * US_TO_NS;
  190. *tp = t;
  191. return res;
  192. }
  193. #endif
  194. static int
  195. _PyTime_FromObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round,
  196. long to_nanoseconds)
  197. {
  198. if (PyFloat_Check(obj)) {
  199. /* volatile avoids unsafe optimization on float enabled by gcc -O3 */
  200. volatile double d, err;
  201. /* convert to a number of nanoseconds */
  202. d = PyFloat_AsDouble(obj);
  203. d *= to_nanoseconds;
  204. if (round == _PyTime_ROUND_CEILING)
  205. d = ceil(d);
  206. else
  207. d = floor(d);
  208. *t = (_PyTime_t)d;
  209. err = d - (double)*t;
  210. if (fabs(err) >= 1.0) {
  211. _PyTime_overflow();
  212. return -1;
  213. }
  214. return 0;
  215. }
  216. else {
  217. #ifdef HAVE_LONG_LONG
  218. PY_LONG_LONG sec;
  219. sec = PyLong_AsLongLong(obj);
  220. assert(sizeof(PY_LONG_LONG) <= sizeof(_PyTime_t));
  221. #else
  222. long sec;
  223. sec = PyLong_AsLong(obj);
  224. assert(sizeof(PY_LONG_LONG) <= sizeof(_PyTime_t));
  225. #endif
  226. if (sec == -1 && PyErr_Occurred()) {
  227. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  228. _PyTime_overflow();
  229. return -1;
  230. }
  231. *t = sec * to_nanoseconds;
  232. if (*t / to_nanoseconds != sec) {
  233. _PyTime_overflow();
  234. return -1;
  235. }
  236. return 0;
  237. }
  238. }
  239. int
  240. _PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
  241. {
  242. return _PyTime_FromObject(t, obj, round, SEC_TO_NS);
  243. }
  244. int
  245. _PyTime_FromMillisecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
  246. {
  247. return _PyTime_FromObject(t, obj, round, MS_TO_NS);
  248. }
  249. double
  250. _PyTime_AsSecondsDouble(_PyTime_t t)
  251. {
  252. _PyTime_t sec, ns;
  253. /* Divide using integers to avoid rounding issues on the integer part.
  254. 1e-9 cannot be stored exactly in IEEE 64-bit. */
  255. sec = t / SEC_TO_NS;
  256. ns = t % SEC_TO_NS;
  257. return (double)sec + (double)ns * 1e-9;
  258. }
  259. PyObject *
  260. _PyTime_AsNanosecondsObject(_PyTime_t t)
  261. {
  262. #ifdef HAVE_LONG_LONG
  263. assert(sizeof(PY_LONG_LONG) >= sizeof(_PyTime_t));
  264. return PyLong_FromLongLong((PY_LONG_LONG)t);
  265. #else
  266. assert(sizeof(long) >= sizeof(_PyTime_t));
  267. return PyLong_FromLong((long)t);
  268. #endif
  269. }
  270. static _PyTime_t
  271. _PyTime_Divide(const _PyTime_t t, const _PyTime_t k,
  272. const _PyTime_round_t round)
  273. {
  274. assert(k > 1);
  275. if (round == _PyTime_ROUND_CEILING) {
  276. if (t >= 0)
  277. return (t + k - 1) / k;
  278. else
  279. return t / k;
  280. }
  281. else {
  282. if (t >= 0)
  283. return t / k;
  284. else
  285. return (t - (k - 1)) / k;
  286. }
  287. }
  288. _PyTime_t
  289. _PyTime_AsMilliseconds(_PyTime_t t, _PyTime_round_t round)
  290. {
  291. return _PyTime_Divide(t, NS_TO_MS, round);
  292. }
  293. _PyTime_t
  294. _PyTime_AsMicroseconds(_PyTime_t t, _PyTime_round_t round)
  295. {
  296. return _PyTime_Divide(t, NS_TO_US, round);
  297. }
  298. static int
  299. _PyTime_AsTimeval_impl(_PyTime_t t, _PyTime_t *p_secs, int *p_us,
  300. _PyTime_round_t round)
  301. {
  302. _PyTime_t secs, ns;
  303. int usec;
  304. int res = 0;
  305. secs = t / SEC_TO_NS;
  306. ns = t % SEC_TO_NS;
  307. usec = (int)_PyTime_Divide(ns, US_TO_NS, round);
  308. if (usec < 0) {
  309. usec += SEC_TO_US;
  310. if (secs != _PyTime_MIN)
  311. secs -= 1;
  312. else
  313. res = -1;
  314. }
  315. else if (usec >= SEC_TO_US) {
  316. usec -= SEC_TO_US;
  317. if (secs != _PyTime_MAX)
  318. secs += 1;
  319. else
  320. res = -1;
  321. }
  322. assert(0 <= usec && usec < SEC_TO_US);
  323. *p_secs = secs;
  324. *p_us = usec;
  325. return res;
  326. }
  327. static int
  328. _PyTime_AsTimevalStruct_impl(_PyTime_t t, struct timeval *tv,
  329. _PyTime_round_t round, int raise)
  330. {
  331. _PyTime_t secs;
  332. int us;
  333. int res;
  334. res = _PyTime_AsTimeval_impl(t, &secs, &us, round);
  335. #ifdef MS_WINDOWS
  336. tv->tv_sec = (long)secs;
  337. #else
  338. tv->tv_sec = secs;
  339. #endif
  340. tv->tv_usec = us;
  341. if (res < 0 || (_PyTime_t)tv->tv_sec != secs) {
  342. if (raise)
  343. error_time_t_overflow();
  344. return -1;
  345. }
  346. return 0;
  347. }
  348. int
  349. _PyTime_AsTimeval(_PyTime_t t, struct timeval *tv, _PyTime_round_t round)
  350. {
  351. return _PyTime_AsTimevalStruct_impl(t, tv, round, 1);
  352. }
  353. int
  354. _PyTime_AsTimeval_noraise(_PyTime_t t, struct timeval *tv, _PyTime_round_t round)
  355. {
  356. return _PyTime_AsTimevalStruct_impl(t, tv, round, 0);
  357. }
  358. int
  359. _PyTime_AsTimevalTime_t(_PyTime_t t, time_t *p_secs, int *us,
  360. _PyTime_round_t round)
  361. {
  362. _PyTime_t secs;
  363. int res;
  364. res = _PyTime_AsTimeval_impl(t, &secs, us, round);
  365. *p_secs = secs;
  366. if (res < 0 || (_PyTime_t)*p_secs != secs) {
  367. error_time_t_overflow();
  368. return -1;
  369. }
  370. return 0;
  371. }
  372. #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
  373. int
  374. _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts)
  375. {
  376. _PyTime_t secs, nsec;
  377. secs = t / SEC_TO_NS;
  378. nsec = t % SEC_TO_NS;
  379. if (nsec < 0) {
  380. nsec += SEC_TO_NS;
  381. secs -= 1;
  382. }
  383. ts->tv_sec = (time_t)secs;
  384. if ((_PyTime_t)ts->tv_sec != secs) {
  385. _PyTime_overflow();
  386. return -1;
  387. }
  388. ts->tv_nsec = nsec;
  389. assert(0 <= ts->tv_nsec && ts->tv_nsec <= 999999999);
  390. return 0;
  391. }
  392. #endif
  393. static int
  394. pygettimeofday_new(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  395. {
  396. #ifdef MS_WINDOWS
  397. FILETIME system_time;
  398. ULARGE_INTEGER large;
  399. assert(info == NULL || raise);
  400. GetSystemTimeAsFileTime(&system_time);
  401. large.u.LowPart = system_time.dwLowDateTime;
  402. large.u.HighPart = system_time.dwHighDateTime;
  403. /* 11,644,473,600,000,000,000: number of nanoseconds between
  404. the 1st january 1601 and the 1st january 1970 (369 years + 89 leap
  405. days). */
  406. *tp = large.QuadPart * 100 - 11644473600000000000;
  407. if (info) {
  408. DWORD timeAdjustment, timeIncrement;
  409. BOOL isTimeAdjustmentDisabled, ok;
  410. info->implementation = "GetSystemTimeAsFileTime()";
  411. info->monotonic = 0;
  412. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  413. &isTimeAdjustmentDisabled);
  414. if (!ok) {
  415. PyErr_SetFromWindowsErr(0);
  416. return -1;
  417. }
  418. info->resolution = timeIncrement * 1e-7;
  419. info->adjustable = 1;
  420. }
  421. #else /* MS_WINDOWS */
  422. int err;
  423. #ifdef HAVE_CLOCK_GETTIME
  424. struct timespec ts;
  425. #else
  426. struct timeval tv;
  427. #endif
  428. assert(info == NULL || raise);
  429. #ifdef HAVE_CLOCK_GETTIME
  430. err = clock_gettime(CLOCK_REALTIME, &ts);
  431. if (err) {
  432. if (raise)
  433. PyErr_SetFromErrno(PyExc_OSError);
  434. return -1;
  435. }
  436. if (_PyTime_FromTimespec(tp, &ts, raise) < 0)
  437. return -1;
  438. if (info) {
  439. struct timespec res;
  440. info->implementation = "clock_gettime(CLOCK_REALTIME)";
  441. info->monotonic = 0;
  442. info->adjustable = 1;
  443. if (clock_getres(CLOCK_REALTIME, &res) == 0)
  444. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  445. else
  446. info->resolution = 1e-9;
  447. }
  448. #else /* HAVE_CLOCK_GETTIME */
  449. /* test gettimeofday() */
  450. #ifdef GETTIMEOFDAY_NO_TZ
  451. err = gettimeofday(&tv);
  452. #else
  453. err = gettimeofday(&tv, (struct timezone *)NULL);
  454. #endif
  455. if (err) {
  456. if (raise)
  457. PyErr_SetFromErrno(PyExc_OSError);
  458. return -1;
  459. }
  460. if (_PyTime_FromTimeval(tp, &tv, raise) < 0)
  461. return -1;
  462. if (info) {
  463. info->implementation = "gettimeofday()";
  464. info->resolution = 1e-6;
  465. info->monotonic = 0;
  466. info->adjustable = 1;
  467. }
  468. #endif /* !HAVE_CLOCK_GETTIME */
  469. #endif /* !MS_WINDOWS */
  470. return 0;
  471. }
  472. _PyTime_t
  473. _PyTime_GetSystemClock(void)
  474. {
  475. _PyTime_t t;
  476. if (pygettimeofday_new(&t, NULL, 0) < 0) {
  477. /* should not happen, _PyTime_Init() checked the clock at startup */
  478. assert(0);
  479. /* use a fixed value instead of a random value from the stack */
  480. t = 0;
  481. }
  482. return t;
  483. }
  484. int
  485. _PyTime_GetSystemClockWithInfo(_PyTime_t *t, _Py_clock_info_t *info)
  486. {
  487. return pygettimeofday_new(t, info, 1);
  488. }
  489. static int
  490. pymonotonic(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  491. {
  492. #if defined(MS_WINDOWS)
  493. ULONGLONG result;
  494. assert(info == NULL || raise);
  495. result = GetTickCount64();
  496. *tp = result * MS_TO_NS;
  497. if (*tp / MS_TO_NS != result) {
  498. if (raise) {
  499. _PyTime_overflow();
  500. return -1;
  501. }
  502. /* Hello, time traveler! */
  503. assert(0);
  504. }
  505. if (info) {
  506. DWORD timeAdjustment, timeIncrement;
  507. BOOL isTimeAdjustmentDisabled, ok;
  508. info->implementation = "GetTickCount64()";
  509. info->monotonic = 1;
  510. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  511. &isTimeAdjustmentDisabled);
  512. if (!ok) {
  513. PyErr_SetFromWindowsErr(0);
  514. return -1;
  515. }
  516. info->resolution = timeIncrement * 1e-7;
  517. info->adjustable = 0;
  518. }
  519. #elif defined(__APPLE__)
  520. static mach_timebase_info_data_t timebase;
  521. uint64_t time;
  522. if (timebase.denom == 0) {
  523. /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
  524. fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
  525. (void)mach_timebase_info(&timebase);
  526. }
  527. time = mach_absolute_time();
  528. /* apply timebase factor */
  529. time *= timebase.numer;
  530. time /= timebase.denom;
  531. *tp = time;
  532. if (info) {
  533. info->implementation = "mach_absolute_time()";
  534. info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
  535. info->monotonic = 1;
  536. info->adjustable = 0;
  537. }
  538. #else
  539. struct timespec ts;
  540. #ifdef CLOCK_HIGHRES
  541. const clockid_t clk_id = CLOCK_HIGHRES;
  542. const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
  543. #else
  544. const clockid_t clk_id = CLOCK_MONOTONIC;
  545. const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
  546. #endif
  547. assert(info == NULL || raise);
  548. if (clock_gettime(clk_id, &ts) != 0) {
  549. if (raise) {
  550. PyErr_SetFromErrno(PyExc_OSError);
  551. return -1;
  552. }
  553. return -1;
  554. }
  555. if (info) {
  556. struct timespec res;
  557. info->monotonic = 1;
  558. info->implementation = implementation;
  559. info->adjustable = 0;
  560. if (clock_getres(clk_id, &res) != 0) {
  561. PyErr_SetFromErrno(PyExc_OSError);
  562. return -1;
  563. }
  564. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  565. }
  566. if (_PyTime_FromTimespec(tp, &ts, raise) < 0)
  567. return -1;
  568. #endif
  569. return 0;
  570. }
  571. _PyTime_t
  572. _PyTime_GetMonotonicClock(void)
  573. {
  574. _PyTime_t t;
  575. if (pymonotonic(&t, NULL, 0) < 0) {
  576. /* should not happen, _PyTime_Init() checked that monotonic clock at
  577. startup */
  578. assert(0);
  579. /* use a fixed value instead of a random value from the stack */
  580. t = 0;
  581. }
  582. return t;
  583. }
  584. int
  585. _PyTime_GetMonotonicClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  586. {
  587. return pymonotonic(tp, info, 1);
  588. }
  589. int
  590. _PyTime_Init(void)
  591. {
  592. _PyTime_t t;
  593. /* ensure that the system clock works */
  594. if (_PyTime_GetSystemClockWithInfo(&t, NULL) < 0)
  595. return -1;
  596. /* ensure that the operating system provides a monotonic clock */
  597. if (_PyTime_GetMonotonicClockWithInfo(&t, NULL) < 0)
  598. return -1;
  599. /* check that _PyTime_FromSeconds() cannot overflow */
  600. assert(INT_MAX <= _PyTime_MAX / SEC_TO_NS);
  601. assert(INT_MIN >= _PyTime_MIN / SEC_TO_NS);
  602. return 0;
  603. }