compat_pthreads.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat_pthreads.c
  7. *
  8. * \brief Implementation for the pthreads-based multithreading backend
  9. * functions.
  10. */
  11. #include "orconfig.h"
  12. #include <pthread.h>
  13. #include <signal.h>
  14. #include <time.h>
  15. #include "common/compat.h"
  16. #include "common/torlog.h"
  17. #include "common/util.h"
  18. /** Wraps a void (*)(void*) function and its argument so we can
  19. * invoke them in a way pthreads would expect.
  20. */
  21. typedef struct tor_pthread_data_t {
  22. void (*func)(void *);
  23. void *data;
  24. } tor_pthread_data_t;
  25. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  26. * and free _data. Used to make sure we can call functions the way pthread
  27. * expects. */
  28. static void *
  29. tor_pthread_helper_fn(void *_data)
  30. {
  31. tor_pthread_data_t *data = _data;
  32. void (*func)(void*);
  33. void *arg;
  34. /* mask signals to worker threads to avoid SIGPIPE, etc */
  35. sigset_t sigs;
  36. /* We're in a subthread; don't handle any signals here. */
  37. sigfillset(&sigs);
  38. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  39. func = data->func;
  40. arg = data->data;
  41. tor_free(_data);
  42. func(arg);
  43. return NULL;
  44. }
  45. /**
  46. * A pthread attribute to make threads start detached.
  47. */
  48. static pthread_attr_t attr_detached;
  49. /** True iff we've called tor_threads_init() */
  50. static int threads_initialized = 0;
  51. /** Minimalist interface to run a void function in the background. On
  52. * Unix calls pthread_create, on win32 calls beginthread. Returns -1 on
  53. * failure.
  54. * func should not return, but rather should call spawn_exit.
  55. *
  56. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  57. * since in a multithreaded environment, there is no way to be sure that
  58. * the caller's stack will still be around when the called function is
  59. * running.
  60. */
  61. int
  62. spawn_func(void (*func)(void *), void *data)
  63. {
  64. pthread_t thread;
  65. tor_pthread_data_t *d;
  66. if (PREDICT_UNLIKELY(!threads_initialized)) {
  67. tor_threads_init();
  68. }
  69. d = tor_malloc(sizeof(tor_pthread_data_t));
  70. d->data = data;
  71. d->func = func;
  72. if (pthread_create(&thread, &attr_detached, tor_pthread_helper_fn, d)) {
  73. tor_free(d);
  74. return -1;
  75. }
  76. return 0;
  77. }
  78. /** End the current thread/process.
  79. */
  80. void
  81. spawn_exit(void)
  82. {
  83. pthread_exit(NULL);
  84. }
  85. /** A mutex attribute that we're going to use to tell pthreads that we want
  86. * "recursive" mutexes (i.e., once we can re-lock if we're already holding
  87. * them.) */
  88. static pthread_mutexattr_t attr_recursive;
  89. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  90. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  91. void
  92. tor_mutex_init(tor_mutex_t *mutex)
  93. {
  94. if (PREDICT_UNLIKELY(!threads_initialized))
  95. tor_threads_init(); // LCOV_EXCL_LINE
  96. const int err = pthread_mutex_init(&mutex->mutex, &attr_recursive);
  97. if (PREDICT_UNLIKELY(err)) {
  98. // LCOV_EXCL_START
  99. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  100. tor_assert_unreached();
  101. // LCOV_EXCL_STOP
  102. }
  103. }
  104. /** As tor_mutex_init, but initialize a mutex suitable that may be
  105. * non-recursive, if the OS supports that. */
  106. void
  107. tor_mutex_init_nonrecursive(tor_mutex_t *mutex)
  108. {
  109. int err;
  110. if (!threads_initialized)
  111. tor_threads_init(); // LCOV_EXCL_LINE
  112. err = pthread_mutex_init(&mutex->mutex, NULL);
  113. if (PREDICT_UNLIKELY(err)) {
  114. // LCOV_EXCL_START
  115. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  116. tor_assert_unreached();
  117. // LCOV_EXCL_STOP
  118. }
  119. }
  120. /** Wait until <b>m</b> is free, then acquire it. */
  121. void
  122. tor_mutex_acquire(tor_mutex_t *m)
  123. {
  124. int err;
  125. tor_assert(m);
  126. err = pthread_mutex_lock(&m->mutex);
  127. if (PREDICT_UNLIKELY(err)) {
  128. // LCOV_EXCL_START
  129. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  130. tor_assert_unreached();
  131. // LCOV_EXCL_STOP
  132. }
  133. }
  134. /** Release the lock <b>m</b> so another thread can have it. */
  135. void
  136. tor_mutex_release(tor_mutex_t *m)
  137. {
  138. int err;
  139. tor_assert(m);
  140. err = pthread_mutex_unlock(&m->mutex);
  141. if (PREDICT_UNLIKELY(err)) {
  142. // LCOV_EXCL_START
  143. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  144. tor_assert_unreached();
  145. // LCOV_EXCL_STOP
  146. }
  147. }
  148. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  149. * resources. Does not free <b>m</b>. This function must only be called on
  150. * mutexes from tor_mutex_init(). */
  151. void
  152. tor_mutex_uninit(tor_mutex_t *m)
  153. {
  154. int err;
  155. tor_assert(m);
  156. err = pthread_mutex_destroy(&m->mutex);
  157. if (PREDICT_UNLIKELY(err)) {
  158. // LCOV_EXCL_START
  159. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  160. tor_assert_unreached();
  161. // LCOV_EXCL_STOP
  162. }
  163. }
  164. /** Return an integer representing this thread. */
  165. unsigned long
  166. tor_get_thread_id(void)
  167. {
  168. union {
  169. pthread_t thr;
  170. unsigned long id;
  171. } r;
  172. r.thr = pthread_self();
  173. return r.id;
  174. }
  175. /* Conditions. */
  176. /** Initialize an already-allocated condition variable. */
  177. int
  178. tor_cond_init(tor_cond_t *cond)
  179. {
  180. pthread_condattr_t condattr;
  181. memset(cond, 0, sizeof(tor_cond_t));
  182. /* Default condition attribute. Might be used if clock monotonic is
  183. * available else this won't affect anything. */
  184. if (pthread_condattr_init(&condattr)) {
  185. return -1;
  186. }
  187. #if defined(HAVE_CLOCK_GETTIME)
  188. #if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && \
  189. defined(CLOCK_MONOTONIC)
  190. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  191. * won't affect the timeout value. */
  192. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  193. return -1;
  194. }
  195. #define USE_COND_CLOCK CLOCK_MONOTONIC
  196. #else /* !(defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ...) */
  197. /* On OSX Sierra, there is no pthread_condattr_setclock, so we are stuck
  198. * with the realtime clock.
  199. */
  200. #define USE_COND_CLOCK CLOCK_REALTIME
  201. #endif /* defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ... */
  202. #endif /* defined(HAVE_CLOCK_GETTIME) */
  203. if (pthread_cond_init(&cond->cond, &condattr)) {
  204. return -1;
  205. }
  206. return 0;
  207. }
  208. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  209. * itself. */
  210. void
  211. tor_cond_uninit(tor_cond_t *cond)
  212. {
  213. if (pthread_cond_destroy(&cond->cond)) {
  214. // LCOV_EXCL_START
  215. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  216. return;
  217. // LCOV_EXCL_STOP
  218. }
  219. }
  220. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  221. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  222. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  223. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  224. * needs to have been allocated with tor_mutex_init_for_cond().
  225. *
  226. * Returns 0 on success, -1 on failure, 1 on timeout. */
  227. int
  228. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  229. {
  230. int r;
  231. if (tv == NULL) {
  232. while (1) {
  233. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  234. if (r == EINTR) {
  235. /* EINTR should be impossible according to POSIX, but POSIX, like the
  236. * Pirate's Code, is apparently treated "more like what you'd call
  237. * guidelines than actual rules." */
  238. continue; // LCOV_EXCL_LINE
  239. }
  240. return r ? -1 : 0;
  241. }
  242. } else {
  243. struct timeval tvnow, tvsum;
  244. struct timespec ts;
  245. while (1) {
  246. #if defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)
  247. if (clock_gettime(USE_COND_CLOCK, &ts) < 0) {
  248. return -1;
  249. }
  250. tvnow.tv_sec = ts.tv_sec;
  251. tvnow.tv_usec = (int)(ts.tv_nsec / 1000);
  252. timeradd(tv, &tvnow, &tvsum);
  253. #else /* !(defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)) */
  254. if (gettimeofday(&tvnow, NULL) < 0)
  255. return -1;
  256. timeradd(tv, &tvnow, &tvsum);
  257. #endif /* defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK) */
  258. ts.tv_sec = tvsum.tv_sec;
  259. ts.tv_nsec = tvsum.tv_usec * 1000;
  260. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  261. if (r == 0)
  262. return 0;
  263. else if (r == ETIMEDOUT)
  264. return 1;
  265. else if (r == EINTR)
  266. continue;
  267. else
  268. return -1;
  269. }
  270. }
  271. }
  272. /** Wake up one of the waiters on <b>cond</b>. */
  273. void
  274. tor_cond_signal_one(tor_cond_t *cond)
  275. {
  276. pthread_cond_signal(&cond->cond);
  277. }
  278. /** Wake up all of the waiters on <b>cond</b>. */
  279. void
  280. tor_cond_signal_all(tor_cond_t *cond)
  281. {
  282. pthread_cond_broadcast(&cond->cond);
  283. }
  284. int
  285. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  286. {
  287. int err = pthread_key_create(&threadlocal->key, NULL);
  288. return err ? -1 : 0;
  289. }
  290. void
  291. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  292. {
  293. pthread_key_delete(threadlocal->key);
  294. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  295. }
  296. void *
  297. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  298. {
  299. return pthread_getspecific(threadlocal->key);
  300. }
  301. void
  302. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  303. {
  304. int err = pthread_setspecific(threadlocal->key, value);
  305. tor_assert(err == 0);
  306. }
  307. /** Set up common structures for use by threading. */
  308. void
  309. tor_threads_init(void)
  310. {
  311. if (!threads_initialized) {
  312. pthread_mutexattr_init(&attr_recursive);
  313. pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
  314. const int ret1 = pthread_attr_init(&attr_detached);
  315. tor_assert(ret1 == 0);
  316. #ifndef PTHREAD_CREATE_DETACHED
  317. #define PTHREAD_CREATE_DETACHED 1
  318. #endif
  319. const int ret2 =
  320. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  321. tor_assert(ret2 == 0);
  322. threads_initialized = 1;
  323. set_main_thread();
  324. }
  325. }