compat_time.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat_time.c
  7. * \brief Portable wrappers for finding out the current time, running
  8. * timers, etc.
  9. **/
  10. #define COMPAT_TIME_PRIVATE
  11. #include "compat.h"
  12. #ifdef _WIN32
  13. #include <winsock2.h>
  14. #include <windows.h>
  15. #endif
  16. #ifdef HAVE_SYS_TYPES_H
  17. #include <sys/types.h>
  18. #endif
  19. #ifdef HAVE_UNISTD_H
  20. #include <unistd.h>
  21. #endif
  22. #ifdef TOR_UNIT_TESTS
  23. #if !defined(HAVE_USLEEP) && defined(HAVE_SYS_SELECT_H)
  24. /* as fallback implementation for tor_sleep_msec */
  25. #include <sys/select.h>
  26. #endif
  27. #endif
  28. #ifdef __APPLE__
  29. #include <mach/mach_time.h>
  30. #endif
  31. #include "torlog.h"
  32. #include "util.h"
  33. #include "container.h"
  34. #ifndef HAVE_GETTIMEOFDAY
  35. #ifdef HAVE_FTIME
  36. #include <sys/timeb.h>
  37. #endif
  38. #endif
  39. #ifdef _WIN32
  40. #undef HAVE_CLOCK_GETTIME
  41. #endif
  42. #ifdef TOR_UNIT_TESTS
  43. /** Delay for <b>msec</b> milliseconds. Only used in tests. */
  44. void
  45. tor_sleep_msec(int msec)
  46. {
  47. #ifdef _WIN32
  48. Sleep(msec);
  49. #elif defined(HAVE_USLEEP)
  50. sleep(msec / 1000);
  51. /* Some usleep()s hate sleeping more than 1 sec */
  52. usleep((msec % 1000) * 1000);
  53. #elif defined(HAVE_SYS_SELECT_H)
  54. struct timeval tv = { msec / 1000, (msec % 1000) * 1000};
  55. select(0, NULL, NULL, NULL, &tv);
  56. #else
  57. sleep(CEIL_DIV(msec, 1000));
  58. #endif
  59. }
  60. #endif
  61. /** Set *timeval to the current time of day. On error, log and terminate.
  62. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  63. */
  64. void
  65. tor_gettimeofday(struct timeval *timeval)
  66. {
  67. #ifdef _WIN32
  68. /* Epoch bias copied from perl: number of units between windows epoch and
  69. * Unix epoch. */
  70. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  71. #define UNITS_PER_SEC U64_LITERAL(10000000)
  72. #define USEC_PER_SEC U64_LITERAL(1000000)
  73. #define UNITS_PER_USEC U64_LITERAL(10)
  74. union {
  75. uint64_t ft_64;
  76. FILETIME ft_ft;
  77. } ft;
  78. /* number of 100-nsec units since Jan 1, 1601 */
  79. GetSystemTimeAsFileTime(&ft.ft_ft);
  80. if (ft.ft_64 < EPOCH_BIAS) {
  81. /* LCOV_EXCL_START */
  82. log_err(LD_GENERAL,"System time is before 1970; failing.");
  83. exit(1);
  84. /* LCOV_EXCL_STOP */
  85. }
  86. ft.ft_64 -= EPOCH_BIAS;
  87. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  88. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  89. #elif defined(HAVE_GETTIMEOFDAY)
  90. if (gettimeofday(timeval, NULL)) {
  91. /* LCOV_EXCL_START */
  92. log_err(LD_GENERAL,"gettimeofday failed.");
  93. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  94. or segfaulted.*/
  95. exit(1);
  96. /* LCOV_EXCL_STOP */
  97. }
  98. #elif defined(HAVE_FTIME)
  99. struct timeb tb;
  100. ftime(&tb);
  101. timeval->tv_sec = tb.time;
  102. timeval->tv_usec = tb.millitm * 1000;
  103. #else
  104. #error "No way to get time."
  105. #endif
  106. return;
  107. }
  108. #define ONE_MILLION ((int64_t) (1000 * 1000))
  109. #define ONE_BILLION ((int64_t) (1000 * 1000 * 1000))
  110. /** True iff monotime_init has been called. */
  111. static int monotime_initialized = 0;
  112. static monotime_t initialized_at;
  113. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  114. static monotime_coarse_t initialized_at_coarse;
  115. #endif
  116. #ifdef TOR_UNIT_TESTS
  117. /** True if we are running unit tests and overriding the current monotonic
  118. * time. Note that mocked monotonic time might not be monotonic.
  119. */
  120. static int monotime_mocking_enabled = 0;
  121. static monotime_t initialized_at_saved;
  122. static int64_t mock_time_nsec = 0;
  123. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  124. static int64_t mock_time_nsec_coarse = 0;
  125. static monotime_coarse_t initialized_at_coarse_saved;
  126. #endif
  127. void
  128. monotime_enable_test_mocking(void)
  129. {
  130. if (BUG(monotime_initialized == 0)) {
  131. monotime_init();
  132. }
  133. tor_assert_nonfatal(monotime_mocking_enabled == 0);
  134. monotime_mocking_enabled = 1;
  135. memcpy(&initialized_at_saved,
  136. &initialized_at, sizeof(monotime_t));
  137. memset(&initialized_at, 0, sizeof(monotime_t));
  138. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  139. memcpy(&initialized_at_coarse_saved,
  140. &initialized_at_coarse, sizeof(monotime_coarse_t));
  141. memset(&initialized_at_coarse, 0, sizeof(monotime_coarse_t));
  142. #endif
  143. }
  144. void
  145. monotime_disable_test_mocking(void)
  146. {
  147. tor_assert_nonfatal(monotime_mocking_enabled == 1);
  148. monotime_mocking_enabled = 0;
  149. memcpy(&initialized_at,
  150. &initialized_at_saved, sizeof(monotime_t));
  151. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  152. memcpy(&initialized_at_coarse,
  153. &initialized_at_coarse_saved, sizeof(monotime_coarse_t));
  154. #endif
  155. }
  156. void
  157. monotime_set_mock_time_nsec(int64_t nsec)
  158. {
  159. tor_assert_nonfatal(monotime_mocking_enabled == 1);
  160. mock_time_nsec = nsec;
  161. }
  162. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  163. void
  164. monotime_coarse_set_mock_time_nsec(int64_t nsec)
  165. {
  166. tor_assert_nonfatal(monotime_mocking_enabled == 1);
  167. mock_time_nsec_coarse = nsec;
  168. }
  169. #endif
  170. #endif
  171. /* "ratchet" functions for monotonic time. */
  172. #if defined(_WIN32) || defined(TOR_UNIT_TESTS)
  173. /** Protected by lock: last value returned by monotime_get(). */
  174. static int64_t last_pctr = 0;
  175. /** Protected by lock: offset we must add to monotonic time values. */
  176. static int64_t pctr_offset = 0;
  177. /* If we are using GetTickCount(), how many times has it rolled over? */
  178. static uint32_t rollover_count = 0;
  179. /* If we are using GetTickCount(), what's the last value it returned? */
  180. static int64_t last_tick_count = 0;
  181. /** Helper for windows: Called with a sequence of times that are supposed
  182. * to be monotonic; increments them as appropriate so that they actually
  183. * _are_ monotonic.
  184. *
  185. * Caller must hold lock. */
  186. STATIC int64_t
  187. ratchet_performance_counter(int64_t count_raw)
  188. {
  189. /* must hold lock */
  190. const int64_t count_adjusted = count_raw + pctr_offset;
  191. if (PREDICT_UNLIKELY(count_adjusted < last_pctr)) {
  192. /* Monotonicity failed! Pretend no time elapsed. */
  193. pctr_offset = last_pctr - count_raw;
  194. return last_pctr;
  195. } else {
  196. last_pctr = count_adjusted;
  197. return count_adjusted;
  198. }
  199. }
  200. STATIC int64_t
  201. ratchet_coarse_performance_counter(const int64_t count_raw)
  202. {
  203. int64_t count = count_raw + (((int64_t)rollover_count) << 32);
  204. while (PREDICT_UNLIKELY(count < last_tick_count)) {
  205. ++rollover_count;
  206. count = count_raw + (((int64_t)rollover_count) << 32);
  207. }
  208. last_tick_count = count;
  209. return count;
  210. }
  211. #endif
  212. #if defined(MONOTIME_USING_GETTIMEOFDAY) || defined(TOR_UNIT_TESTS)
  213. static struct timeval last_timeofday = { 0, 0 };
  214. static struct timeval timeofday_offset = { 0, 0 };
  215. /** Helper for gettimeofday(): Called with a sequence of times that are
  216. * supposed to be monotonic; increments them as appropriate so that they
  217. * actually _are_ monotonic.
  218. *
  219. * Caller must hold lock. */
  220. STATIC void
  221. ratchet_timeval(const struct timeval *timeval_raw, struct timeval *out)
  222. {
  223. /* must hold lock */
  224. timeradd(timeval_raw, &timeofday_offset, out);
  225. if (PREDICT_UNLIKELY(timercmp(out, &last_timeofday, <))) {
  226. /* time ran backwards. Instead, declare that no time occurred. */
  227. timersub(&last_timeofday, timeval_raw, &timeofday_offset);
  228. memcpy(out, &last_timeofday, sizeof(struct timeval));
  229. } else {
  230. memcpy(&last_timeofday, out, sizeof(struct timeval));
  231. }
  232. }
  233. #endif
  234. #ifdef TOR_UNIT_TESTS
  235. /** For testing: reset all the ratchets */
  236. void
  237. monotime_reset_ratchets_for_testing(void)
  238. {
  239. last_pctr = pctr_offset = last_tick_count = 0;
  240. rollover_count = 0;
  241. memset(&last_timeofday, 0, sizeof(struct timeval));
  242. memset(&timeofday_offset, 0, sizeof(struct timeval));
  243. }
  244. #endif
  245. #ifdef __APPLE__
  246. /** Initialized on startup: tells is how to convert from ticks to
  247. * nanoseconds.
  248. */
  249. static struct mach_timebase_info mach_time_info;
  250. static void
  251. monotime_init_internal(void)
  252. {
  253. tor_assert(!monotime_initialized);
  254. int r = mach_timebase_info(&mach_time_info);
  255. tor_assert(r == 0);
  256. tor_assert(mach_time_info.denom != 0);
  257. }
  258. /**
  259. * Set "out" to the most recent monotonic time value
  260. */
  261. void
  262. monotime_get(monotime_t *out)
  263. {
  264. #ifdef TOR_UNIT_TESTS
  265. if (monotime_mocking_enabled) {
  266. out->abstime_ = (mock_time_nsec * mach_time_info.denom)
  267. / mach_time_info.numer;
  268. return;
  269. }
  270. #endif
  271. out->abstime_ = mach_absolute_time();
  272. }
  273. /**
  274. * Return the number of nanoseconds between <b>start</b> and <b>end</b>.
  275. */
  276. int64_t
  277. monotime_diff_nsec(const monotime_t *start,
  278. const monotime_t *end)
  279. {
  280. if (BUG(mach_time_info.denom == 0)) {
  281. monotime_init();
  282. }
  283. const int64_t diff_ticks = end->abstime_ - start->abstime_;
  284. const int64_t diff_nsec =
  285. (diff_ticks * mach_time_info.numer) / mach_time_info.denom;
  286. return diff_nsec;
  287. }
  288. /* end of "__APPLE__" */
  289. #elif defined(HAVE_CLOCK_GETTIME)
  290. static void
  291. monotime_init_internal(void)
  292. {
  293. /* no action needed. */
  294. }
  295. void
  296. monotime_get(monotime_t *out)
  297. {
  298. #ifdef TOR_UNIT_TESTS
  299. if (monotime_mocking_enabled) {
  300. out->ts_.tv_sec = (time_t) (mock_time_nsec / ONE_BILLION);
  301. out->ts_.tv_nsec = (int) (mock_time_nsec % ONE_BILLION);
  302. return;
  303. }
  304. #endif
  305. int r = clock_gettime(CLOCK_MONOTONIC, &out->ts_);
  306. tor_assert(r == 0);
  307. }
  308. #ifdef CLOCK_MONOTONIC_COARSE
  309. void
  310. monotime_coarse_get(monotime_coarse_t *out)
  311. {
  312. #ifdef TOR_UNIT_TESTS
  313. if (monotime_mocking_enabled) {
  314. out->ts_.tv_sec = (time_t) (mock_time_nsec_coarse / ONE_BILLION);
  315. out->ts_.tv_nsec = (int) (mock_time_nsec_coarse % ONE_BILLION);
  316. return;
  317. }
  318. #endif
  319. int r = clock_gettime(CLOCK_MONOTONIC_COARSE, &out->ts_);
  320. tor_assert(r == 0);
  321. }
  322. #endif
  323. int64_t
  324. monotime_diff_nsec(const monotime_t *start,
  325. const monotime_t *end)
  326. {
  327. const int64_t diff_sec = end->ts_.tv_sec - start->ts_.tv_sec;
  328. const int64_t diff_nsec = diff_sec * ONE_BILLION +
  329. (end->ts_.tv_nsec - start->ts_.tv_nsec);
  330. return diff_nsec;
  331. }
  332. /* end of "HAVE_CLOCK_GETTIME" */
  333. #elif defined (_WIN32)
  334. /** Result of QueryPerformanceFrequency, as an int64_t. */
  335. static int64_t ticks_per_second = 0;
  336. /** Lock to protect last_pctr and pctr_offset */
  337. static CRITICAL_SECTION monotime_lock;
  338. /** Lock to protect rollover_count and last_tick_count */
  339. static CRITICAL_SECTION monotime_coarse_lock;
  340. typedef ULONGLONG (WINAPI *GetTickCount64_fn_t)(void);
  341. static GetTickCount64_fn_t GetTickCount64_fn = NULL;
  342. static void
  343. monotime_init_internal(void)
  344. {
  345. tor_assert(!monotime_initialized);
  346. BOOL ok = InitializeCriticalSectionAndSpinCount(&monotime_lock, 200);
  347. tor_assert(ok);
  348. ok = InitializeCriticalSectionAndSpinCount(&monotime_coarse_lock, 200);
  349. tor_assert(ok);
  350. LARGE_INTEGER li;
  351. ok = QueryPerformanceFrequency(&li);
  352. tor_assert(ok);
  353. tor_assert(li.QuadPart);
  354. ticks_per_second = li.QuadPart;
  355. last_pctr = 0;
  356. pctr_offset = 0;
  357. HANDLE h = load_windows_system_library(TEXT("kernel32.dll"));
  358. if (h) {
  359. GetTickCount64_fn = (GetTickCount64_fn_t)
  360. GetProcAddress(h, "GetTickCount64");
  361. }
  362. // FreeLibrary(h) ?
  363. }
  364. void
  365. monotime_get(monotime_t *out)
  366. {
  367. if (BUG(monotime_initialized == 0)) {
  368. monotime_init();
  369. }
  370. #ifdef TOR_UNIT_TESTS
  371. if (monotime_mocking_enabled) {
  372. out->pcount_ = (mock_time_nsec * ticks_per_second) / ONE_BILLION;
  373. return;
  374. }
  375. #endif
  376. /* Alas, QueryPerformanceCounter is not always monotonic: see bug list at
  377. https://www.python.org/dev/peps/pep-0418/#windows-queryperformancecounter
  378. */
  379. EnterCriticalSection(&monotime_lock);
  380. LARGE_INTEGER res;
  381. BOOL ok = QueryPerformanceCounter(&res);
  382. tor_assert(ok);
  383. const int64_t count_raw = res.QuadPart;
  384. out->pcount_ = ratchet_performance_counter(count_raw);
  385. LeaveCriticalSection(&monotime_lock);
  386. }
  387. void
  388. monotime_coarse_get(monotime_coarse_t *out)
  389. {
  390. #ifdef TOR_UNIT_TESTS
  391. if (monotime_mocking_enabled) {
  392. out->tick_count_ = mock_time_nsec_coarse / ONE_MILLION;
  393. return;
  394. }
  395. #endif
  396. if (GetTickCount64_fn) {
  397. out->tick_count_ = (int64_t)GetTickCount64_fn();
  398. } else {
  399. EnterCriticalSection(&monotime_coarse_lock);
  400. DWORD tick = GetTickCount();
  401. out->tick_count_ = ratchet_coarse_performance_counter(tick);
  402. LeaveCriticalSection(&monotime_coarse_lock);
  403. }
  404. }
  405. int64_t
  406. monotime_diff_nsec(const monotime_t *start,
  407. const monotime_t *end)
  408. {
  409. if (BUG(monotime_initialized == 0)) {
  410. monotime_init();
  411. }
  412. const int64_t diff_ticks = end->pcount_ - start->pcount_;
  413. return (diff_ticks * ONE_BILLION) / ticks_per_second;
  414. }
  415. int64_t
  416. monotime_coarse_diff_msec(const monotime_coarse_t *start,
  417. const monotime_coarse_t *end)
  418. {
  419. const int64_t diff_ticks = end->tick_count_ - start->tick_count_;
  420. return diff_ticks;
  421. }
  422. int64_t
  423. monotime_coarse_diff_usec(const monotime_coarse_t *start,
  424. const monotime_coarse_t *end)
  425. {
  426. return monotime_coarse_diff_msec(start, end) * 1000;
  427. }
  428. int64_t
  429. monotime_coarse_diff_nsec(const monotime_coarse_t *start,
  430. const monotime_coarse_t *end)
  431. {
  432. return monotime_coarse_diff_msec(start, end) * ONE_MILLION;
  433. }
  434. /* end of "_WIN32" */
  435. #elif defined(MONOTIME_USING_GETTIMEOFDAY)
  436. static tor_mutex_t monotime_lock;
  437. /** Initialize the monotonic timer subsystem. */
  438. static void
  439. monotime_init_internal(void)
  440. {
  441. tor_assert(!monotime_initialized);
  442. tor_mutex_init(&monotime_lock);
  443. }
  444. void
  445. monotime_get(monotime_t *out)
  446. {
  447. if (BUG(monotime_initialized == 0)) {
  448. monotime_init();
  449. }
  450. tor_mutex_acquire(&monotime_lock);
  451. struct timeval timeval_raw;
  452. tor_gettimeofday(&timeval_raw);
  453. ratchet_timeval(&timeval_raw, &out->tv_);
  454. tor_mutex_release(&monotime_lock);
  455. }
  456. int64_t
  457. monotime_diff_nsec(const monotime_t *start,
  458. const monotime_t *end)
  459. {
  460. struct timeval diff;
  461. timersub(&end->tv_, &start->tv_, &diff);
  462. return (diff.tv_sec * ONE_BILLION + diff.tv_usec * 1000);
  463. }
  464. /* end of "MONOTIME_USING_GETTIMEOFDAY" */
  465. #else
  466. #error "No way to implement monotonic timers."
  467. #endif
  468. /**
  469. * Initialize the monotonic timer subsystem. Must be called before any
  470. * monotonic timer functions. This function is idempotent.
  471. */
  472. void
  473. monotime_init(void)
  474. {
  475. if (!monotime_initialized) {
  476. monotime_init_internal();
  477. monotime_initialized = 1;
  478. monotime_get(&initialized_at);
  479. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  480. monotime_coarse_get(&initialized_at_coarse);
  481. #endif
  482. }
  483. }
  484. int64_t
  485. monotime_diff_usec(const monotime_t *start,
  486. const monotime_t *end)
  487. {
  488. const int64_t nsec = monotime_diff_nsec(start, end);
  489. return CEIL_DIV(nsec, 1000);
  490. }
  491. int64_t
  492. monotime_diff_msec(const monotime_t *start,
  493. const monotime_t *end)
  494. {
  495. const int64_t nsec = monotime_diff_nsec(start, end);
  496. return CEIL_DIV(nsec, ONE_MILLION);
  497. }
  498. uint64_t
  499. monotime_absolute_nsec(void)
  500. {
  501. monotime_t now;
  502. if (BUG(monotime_initialized == 0)) {
  503. monotime_init();
  504. }
  505. monotime_get(&now);
  506. return monotime_diff_nsec(&initialized_at, &now);
  507. }
  508. uint64_t
  509. monotime_absolute_usec(void)
  510. {
  511. return monotime_absolute_nsec() / 1000;
  512. }
  513. uint64_t
  514. monotime_absolute_msec(void)
  515. {
  516. return monotime_absolute_nsec() / ONE_MILLION;
  517. }
  518. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  519. uint64_t
  520. monotime_coarse_absolute_nsec(void)
  521. {
  522. if (BUG(monotime_initialized == 0)) {
  523. monotime_init();
  524. }
  525. monotime_coarse_t now;
  526. monotime_coarse_get(&now);
  527. return monotime_coarse_diff_nsec(&initialized_at_coarse, &now);
  528. }
  529. uint64_t
  530. monotime_coarse_absolute_usec(void)
  531. {
  532. return monotime_coarse_absolute_nsec() / 1000;
  533. }
  534. uint64_t
  535. monotime_coarse_absolute_msec(void)
  536. {
  537. return monotime_coarse_absolute_nsec() / ONE_MILLION;
  538. }
  539. #endif