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.

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