compat_pthreads.c 8.9 KB

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