compat_pthreads.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2017, 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 "compat.h"
  16. #include "torlog.h"
  17. #include "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(CLOCK_MONOTONIC) && defined(HAVE_PTHREAD_CONDATTR_SETCLOCK)
  189. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  190. * won't affect the timeout value. */
  191. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  192. return -1;
  193. }
  194. #define USE_COND_CLOCK CLOCK_MONOTONIC
  195. #else /* !defined HAVE_PTHREAD_CONDATTR_SETCLOCK */
  196. /* On OSX Sierra, there is no pthread_condattr_setclock, so we are stuck
  197. * with the realtime clock.
  198. */
  199. #define USE_COND_CLOCK CLOCK_REALTIME
  200. #endif /* which clock to use */
  201. #endif /* HAVE_CLOCK_GETTIME */
  202. if (pthread_cond_init(&cond->cond, &condattr)) {
  203. return -1;
  204. }
  205. return 0;
  206. }
  207. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  208. * itself. */
  209. void
  210. tor_cond_uninit(tor_cond_t *cond)
  211. {
  212. if (pthread_cond_destroy(&cond->cond)) {
  213. // LCOV_EXCL_START
  214. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  215. return;
  216. // LCOV_EXCL_STOP
  217. }
  218. }
  219. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  220. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  221. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  222. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  223. * needs to have been allocated with tor_mutex_init_for_cond().
  224. *
  225. * Returns 0 on success, -1 on failure, 1 on timeout. */
  226. int
  227. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  228. {
  229. int r;
  230. if (tv == NULL) {
  231. while (1) {
  232. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  233. if (r == EINTR) {
  234. /* EINTR should be impossible according to POSIX, but POSIX, like the
  235. * Pirate's Code, is apparently treated "more like what you'd call
  236. * guidelines than actual rules." */
  237. continue; // LCOV_EXCL_LINE
  238. }
  239. return r ? -1 : 0;
  240. }
  241. } else {
  242. struct timeval tvnow, tvsum;
  243. struct timespec ts;
  244. while (1) {
  245. #if defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)
  246. if (clock_gettime(USE_COND_CLOCK, &ts) < 0) {
  247. return -1;
  248. }
  249. tvnow.tv_sec = ts.tv_sec;
  250. tvnow.tv_usec = (int)(ts.tv_nsec / 1000);
  251. timeradd(tv, &tvnow, &tvsum);
  252. #else
  253. if (gettimeofday(&tvnow, NULL) < 0)
  254. return -1;
  255. timeradd(tv, &tvnow, &tvsum);
  256. #endif /* HAVE_CLOCK_GETTIME, CLOCK_MONOTONIC */
  257. ts.tv_sec = tvsum.tv_sec;
  258. ts.tv_nsec = tvsum.tv_usec * 1000;
  259. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  260. if (r == 0)
  261. return 0;
  262. else if (r == ETIMEDOUT)
  263. return 1;
  264. else if (r == EINTR)
  265. continue;
  266. else
  267. return -1;
  268. }
  269. }
  270. }
  271. /** Wake up one of the waiters on <b>cond</b>. */
  272. void
  273. tor_cond_signal_one(tor_cond_t *cond)
  274. {
  275. pthread_cond_signal(&cond->cond);
  276. }
  277. /** Wake up all of the waiters on <b>cond</b>. */
  278. void
  279. tor_cond_signal_all(tor_cond_t *cond)
  280. {
  281. pthread_cond_broadcast(&cond->cond);
  282. }
  283. int
  284. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  285. {
  286. int err = pthread_key_create(&threadlocal->key, NULL);
  287. return err ? -1 : 0;
  288. }
  289. void
  290. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  291. {
  292. pthread_key_delete(threadlocal->key);
  293. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  294. }
  295. void *
  296. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  297. {
  298. return pthread_getspecific(threadlocal->key);
  299. }
  300. void
  301. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  302. {
  303. int err = pthread_setspecific(threadlocal->key, value);
  304. tor_assert(err == 0);
  305. }
  306. /** Set up common structures for use by threading. */
  307. void
  308. tor_threads_init(void)
  309. {
  310. if (!threads_initialized) {
  311. pthread_mutexattr_init(&attr_recursive);
  312. pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
  313. const int ret1 = pthread_attr_init(&attr_detached);
  314. tor_assert(ret1 == 0);
  315. #ifndef PTHREAD_CREATE_DETACHED
  316. #define PTHREAD_CREATE_DETACHED 1
  317. #endif
  318. const int ret2 =
  319. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  320. tor_assert(ret2 == 0);
  321. threads_initialized = 1;
  322. set_main_thread();
  323. }
  324. }