compat_time.c 15 KB

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