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.

678 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(_PyTime_t t, _PyTime_t k, _PyTime_round_t round)
  272. {
  273. assert(k > 1);
  274. if (round == _PyTime_ROUND_CEILING) {
  275. if (t >= 0)
  276. return (t + k - 1) / k;
  277. else
  278. return (t - (k - 1)) / k;
  279. }
  280. else
  281. return t / k;
  282. }
  283. _PyTime_t
  284. _PyTime_AsMilliseconds(_PyTime_t t, _PyTime_round_t round)
  285. {
  286. return _PyTime_Divide(t, NS_TO_MS, round);
  287. }
  288. _PyTime_t
  289. _PyTime_AsMicroseconds(_PyTime_t t, _PyTime_round_t round)
  290. {
  291. return _PyTime_Divide(t, NS_TO_US, round);
  292. }
  293. static int
  294. _PyTime_AsTimeval_impl(_PyTime_t t, struct timeval *tv, _PyTime_round_t round,
  295. int raise)
  296. {
  297. _PyTime_t secs, ns;
  298. int res = 0;
  299. secs = t / SEC_TO_NS;
  300. ns = t % SEC_TO_NS;
  301. if (ns < 0) {
  302. ns += SEC_TO_NS;
  303. secs -= 1;
  304. }
  305. #ifdef MS_WINDOWS
  306. /* On Windows, timeval.tv_sec is a long (32 bit),
  307. whereas time_t can be 64-bit. */
  308. assert(sizeof(tv->tv_sec) == sizeof(long));
  309. #if SIZEOF_TIME_T > SIZEOF_LONG
  310. if (secs > LONG_MAX) {
  311. secs = LONG_MAX;
  312. res = -1;
  313. }
  314. else if (secs < LONG_MIN) {
  315. secs = LONG_MIN;
  316. res = -1;
  317. }
  318. #endif
  319. tv->tv_sec = (long)secs;
  320. #else
  321. /* On OpenBSD 5.4, timeval.tv_sec is a long.
  322. Example: long is 64-bit, whereas time_t is 32-bit. */
  323. tv->tv_sec = secs;
  324. if ((_PyTime_t)tv->tv_sec != secs)
  325. res = -1;
  326. #endif
  327. if (round == _PyTime_ROUND_CEILING)
  328. tv->tv_usec = (int)((ns + US_TO_NS - 1) / US_TO_NS);
  329. else
  330. tv->tv_usec = (int)(ns / US_TO_NS);
  331. if (tv->tv_usec >= SEC_TO_US) {
  332. tv->tv_usec -= SEC_TO_US;
  333. tv->tv_sec += 1;
  334. }
  335. if (res && raise)
  336. _PyTime_overflow();
  337. assert(0 <= tv->tv_usec && tv->tv_usec <= 999999);
  338. return res;
  339. }
  340. int
  341. _PyTime_AsTimeval(_PyTime_t t, struct timeval *tv, _PyTime_round_t round)
  342. {
  343. return _PyTime_AsTimeval_impl(t, tv, round, 1);
  344. }
  345. int
  346. _PyTime_AsTimeval_noraise(_PyTime_t t, struct timeval *tv, _PyTime_round_t round)
  347. {
  348. return _PyTime_AsTimeval_impl(t, tv, round, 0);
  349. }
  350. #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
  351. int
  352. _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts)
  353. {
  354. _PyTime_t secs, nsec;
  355. secs = t / SEC_TO_NS;
  356. nsec = t % SEC_TO_NS;
  357. if (nsec < 0) {
  358. nsec += SEC_TO_NS;
  359. secs -= 1;
  360. }
  361. ts->tv_sec = (time_t)secs;
  362. if ((_PyTime_t)ts->tv_sec != secs) {
  363. _PyTime_overflow();
  364. return -1;
  365. }
  366. ts->tv_nsec = nsec;
  367. assert(0 <= ts->tv_nsec && ts->tv_nsec <= 999999999);
  368. return 0;
  369. }
  370. #endif
  371. static int
  372. pygettimeofday_new(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  373. {
  374. #ifdef MS_WINDOWS
  375. FILETIME system_time;
  376. ULARGE_INTEGER large;
  377. assert(info == NULL || raise);
  378. GetSystemTimeAsFileTime(&system_time);
  379. large.u.LowPart = system_time.dwLowDateTime;
  380. large.u.HighPart = system_time.dwHighDateTime;
  381. /* 11,644,473,600,000,000,000: number of nanoseconds between
  382. the 1st january 1601 and the 1st january 1970 (369 years + 89 leap
  383. days). */
  384. *tp = large.QuadPart * 100 - 11644473600000000000;
  385. if (info) {
  386. DWORD timeAdjustment, timeIncrement;
  387. BOOL isTimeAdjustmentDisabled, ok;
  388. info->implementation = "GetSystemTimeAsFileTime()";
  389. info->monotonic = 0;
  390. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  391. &isTimeAdjustmentDisabled);
  392. if (!ok) {
  393. PyErr_SetFromWindowsErr(0);
  394. return -1;
  395. }
  396. info->resolution = timeIncrement * 1e-7;
  397. info->adjustable = 1;
  398. }
  399. #else /* MS_WINDOWS */
  400. int err;
  401. #ifdef HAVE_CLOCK_GETTIME
  402. struct timespec ts;
  403. #else
  404. struct timeval tv;
  405. #endif
  406. assert(info == NULL || raise);
  407. #ifdef HAVE_CLOCK_GETTIME
  408. err = clock_gettime(CLOCK_REALTIME, &ts);
  409. if (err) {
  410. if (raise)
  411. PyErr_SetFromErrno(PyExc_OSError);
  412. return -1;
  413. }
  414. if (_PyTime_FromTimespec(tp, &ts, raise) < 0)
  415. return -1;
  416. if (info) {
  417. struct timespec res;
  418. info->implementation = "clock_gettime(CLOCK_REALTIME)";
  419. info->monotonic = 0;
  420. info->adjustable = 1;
  421. if (clock_getres(CLOCK_REALTIME, &res) == 0)
  422. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  423. else
  424. info->resolution = 1e-9;
  425. }
  426. #else /* HAVE_CLOCK_GETTIME */
  427. /* test gettimeofday() */
  428. #ifdef GETTIMEOFDAY_NO_TZ
  429. err = gettimeofday(&tv);
  430. #else
  431. err = gettimeofday(&tv, (struct timezone *)NULL);
  432. #endif
  433. if (err) {
  434. if (raise)
  435. PyErr_SetFromErrno(PyExc_OSError);
  436. return -1;
  437. }
  438. if (_PyTime_FromTimeval(tp, &tv, raise) < 0)
  439. return -1;
  440. if (info) {
  441. info->implementation = "gettimeofday()";
  442. info->resolution = 1e-6;
  443. info->monotonic = 0;
  444. info->adjustable = 1;
  445. }
  446. #endif /* !HAVE_CLOCK_GETTIME */
  447. #endif /* !MS_WINDOWS */
  448. return 0;
  449. }
  450. _PyTime_t
  451. _PyTime_GetSystemClock(void)
  452. {
  453. _PyTime_t t;
  454. if (pygettimeofday_new(&t, NULL, 0) < 0) {
  455. /* should not happen, _PyTime_Init() checked the clock at startup */
  456. assert(0);
  457. /* use a fixed value instead of a random value from the stack */
  458. t = 0;
  459. }
  460. return t;
  461. }
  462. int
  463. _PyTime_GetSystemClockWithInfo(_PyTime_t *t, _Py_clock_info_t *info)
  464. {
  465. return pygettimeofday_new(t, info, 1);
  466. }
  467. static int
  468. pymonotonic_new(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
  469. {
  470. #ifdef Py_DEBUG
  471. static int last_set = 0;
  472. static _PyTime_t last = 0;
  473. #endif
  474. #if defined(MS_WINDOWS)
  475. ULONGLONG result;
  476. assert(info == NULL || raise);
  477. result = GetTickCount64();
  478. *tp = result * MS_TO_NS;
  479. if (*tp / MS_TO_NS != result) {
  480. if (raise) {
  481. _PyTime_overflow();
  482. return -1;
  483. }
  484. /* Hello, time traveler! */
  485. assert(0);
  486. }
  487. if (info) {
  488. DWORD timeAdjustment, timeIncrement;
  489. BOOL isTimeAdjustmentDisabled, ok;
  490. info->implementation = "GetTickCount64()";
  491. info->monotonic = 1;
  492. ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
  493. &isTimeAdjustmentDisabled);
  494. if (!ok) {
  495. PyErr_SetFromWindowsErr(0);
  496. return -1;
  497. }
  498. info->resolution = timeIncrement * 1e-7;
  499. info->adjustable = 0;
  500. }
  501. #elif defined(__APPLE__)
  502. static mach_timebase_info_data_t timebase;
  503. uint64_t time;
  504. if (timebase.denom == 0) {
  505. /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
  506. fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
  507. (void)mach_timebase_info(&timebase);
  508. }
  509. time = mach_absolute_time();
  510. /* apply timebase factor */
  511. time *= timebase.numer;
  512. time /= timebase.denom;
  513. *tp = time;
  514. if (info) {
  515. info->implementation = "mach_absolute_time()";
  516. info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
  517. info->monotonic = 1;
  518. info->adjustable = 0;
  519. }
  520. #else
  521. struct timespec ts;
  522. #ifdef CLOCK_HIGHRES
  523. const clockid_t clk_id = CLOCK_HIGHRES;
  524. const char *implementation = "clock_gettime(CLOCK_HIGHRES)";
  525. #else
  526. const clockid_t clk_id = CLOCK_MONOTONIC;
  527. const char *implementation = "clock_gettime(CLOCK_MONOTONIC)";
  528. #endif
  529. assert(info == NULL || raise);
  530. if (clock_gettime(clk_id, &ts) != 0) {
  531. if (raise) {
  532. PyErr_SetFromErrno(PyExc_OSError);
  533. return -1;
  534. }
  535. return -1;
  536. }
  537. if (info) {
  538. struct timespec res;
  539. info->monotonic = 1;
  540. info->implementation = implementation;
  541. info->adjustable = 0;
  542. if (clock_getres(clk_id, &res) != 0) {
  543. PyErr_SetFromErrno(PyExc_OSError);
  544. return -1;
  545. }
  546. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  547. }
  548. if (_PyTime_FromTimespec(tp, &ts, raise) < 0)
  549. return -1;
  550. #endif
  551. #ifdef Py_DEBUG
  552. /* monotonic clock cannot go backward */
  553. assert(!last_set || last <= *tp);
  554. last = *tp;
  555. last_set = 1;
  556. #endif
  557. return 0;
  558. }
  559. _PyTime_t
  560. _PyTime_GetMonotonicClock(void)
  561. {
  562. _PyTime_t t;
  563. if (pymonotonic_new(&t, NULL, 0) < 0) {
  564. /* should not happen, _PyTime_Init() checked that monotonic clock at
  565. startup */
  566. assert(0);
  567. /* use a fixed value instead of a random value from the stack */
  568. t = 0;
  569. }
  570. return t;
  571. }
  572. int
  573. _PyTime_GetMonotonicClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  574. {
  575. return pymonotonic_new(tp, info, 1);
  576. }
  577. int
  578. _PyTime_Init(void)
  579. {
  580. _PyTime_t t;
  581. /* ensure that the system clock works */
  582. if (_PyTime_GetSystemClockWithInfo(&t, NULL) < 0)
  583. return -1;
  584. /* ensure that the operating system provides a monotonic clock */
  585. if (_PyTime_GetMonotonicClockWithInfo(&t, NULL) < 0)
  586. return -1;
  587. /* check that _PyTime_FromSeconds() cannot overflow */
  588. assert(INT_MAX <= _PyTime_MAX / SEC_TO_NS);
  589. assert(INT_MIN >= _PyTime_MIN / SEC_TO_NS);
  590. return 0;
  591. }