compat_pthreads.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. raw_assert_unreached_msg("Error creating a mutex.");
  100. // LCOV_EXCL_STOP
  101. }
  102. }
  103. /** As tor_mutex_init, but initialize a mutex suitable that may be
  104. * non-recursive, if the OS supports that. */
  105. void
  106. tor_mutex_init_nonrecursive(tor_mutex_t *mutex)
  107. {
  108. int err;
  109. if (!threads_initialized)
  110. tor_threads_init(); // LCOV_EXCL_LINE
  111. err = pthread_mutex_init(&mutex->mutex, NULL);
  112. if (PREDICT_UNLIKELY(err)) {
  113. // LCOV_EXCL_START
  114. raw_assert_unreached_msg("Error creating a mutex.");
  115. // LCOV_EXCL_STOP
  116. }
  117. }
  118. /** Wait until <b>m</b> is free, then acquire it. */
  119. void
  120. tor_mutex_acquire(tor_mutex_t *m)
  121. {
  122. int err;
  123. raw_assert(m);
  124. err = pthread_mutex_lock(&m->mutex);
  125. if (PREDICT_UNLIKELY(err)) {
  126. // LCOV_EXCL_START
  127. raw_assert_unreached_msg("Error locking a mutex.");
  128. // LCOV_EXCL_STOP
  129. }
  130. }
  131. /** Release the lock <b>m</b> so another thread can have it. */
  132. void
  133. tor_mutex_release(tor_mutex_t *m)
  134. {
  135. int err;
  136. raw_assert(m);
  137. err = pthread_mutex_unlock(&m->mutex);
  138. if (PREDICT_UNLIKELY(err)) {
  139. // LCOV_EXCL_START
  140. raw_assert_unreached_msg("Error unlocking a mutex.");
  141. // LCOV_EXCL_STOP
  142. }
  143. }
  144. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  145. * resources. Does not free <b>m</b>. This function must only be called on
  146. * mutexes from tor_mutex_init(). */
  147. void
  148. tor_mutex_uninit(tor_mutex_t *m)
  149. {
  150. int err;
  151. raw_assert(m);
  152. err = pthread_mutex_destroy(&m->mutex);
  153. if (PREDICT_UNLIKELY(err)) {
  154. // LCOV_EXCL_START
  155. raw_assert_unreached_msg("Error destroying a mutex.");
  156. // LCOV_EXCL_STOP
  157. }
  158. }
  159. /** Return an integer representing this thread. */
  160. unsigned long
  161. tor_get_thread_id(void)
  162. {
  163. union {
  164. pthread_t thr;
  165. unsigned long id;
  166. } r;
  167. r.thr = pthread_self();
  168. return r.id;
  169. }
  170. /* Conditions. */
  171. /** Initialize an already-allocated condition variable. */
  172. int
  173. tor_cond_init(tor_cond_t *cond)
  174. {
  175. pthread_condattr_t condattr;
  176. memset(cond, 0, sizeof(tor_cond_t));
  177. /* Default condition attribute. Might be used if clock monotonic is
  178. * available else this won't affect anything. */
  179. if (pthread_condattr_init(&condattr)) {
  180. return -1;
  181. }
  182. #if defined(HAVE_CLOCK_GETTIME)
  183. #if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && \
  184. defined(CLOCK_MONOTONIC)
  185. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  186. * won't affect the timeout value. */
  187. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  188. return -1;
  189. }
  190. #define USE_COND_CLOCK CLOCK_MONOTONIC
  191. #else /* !(defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ...) */
  192. /* On OSX Sierra, there is no pthread_condattr_setclock, so we are stuck
  193. * with the realtime clock.
  194. */
  195. #define USE_COND_CLOCK CLOCK_REALTIME
  196. #endif /* defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ... */
  197. #endif /* defined(HAVE_CLOCK_GETTIME) */
  198. if (pthread_cond_init(&cond->cond, &condattr)) {
  199. return -1;
  200. }
  201. return 0;
  202. }
  203. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  204. * itself. */
  205. void
  206. tor_cond_uninit(tor_cond_t *cond)
  207. {
  208. if (pthread_cond_destroy(&cond->cond)) {
  209. // LCOV_EXCL_START
  210. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  211. return;
  212. // LCOV_EXCL_STOP
  213. }
  214. }
  215. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  216. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  217. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  218. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  219. * needs to have been allocated with tor_mutex_init_for_cond().
  220. *
  221. * Returns 0 on success, -1 on failure, 1 on timeout. */
  222. int
  223. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  224. {
  225. int r;
  226. if (tv == NULL) {
  227. while (1) {
  228. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  229. if (r == EINTR) {
  230. /* EINTR should be impossible according to POSIX, but POSIX, like the
  231. * Pirate's Code, is apparently treated "more like what you'd call
  232. * guidelines than actual rules." */
  233. continue; // LCOV_EXCL_LINE
  234. }
  235. return r ? -1 : 0;
  236. }
  237. } else {
  238. struct timeval tvnow, tvsum;
  239. struct timespec ts;
  240. while (1) {
  241. #if defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)
  242. if (clock_gettime(USE_COND_CLOCK, &ts) < 0) {
  243. return -1;
  244. }
  245. tvnow.tv_sec = ts.tv_sec;
  246. tvnow.tv_usec = (int)(ts.tv_nsec / 1000);
  247. timeradd(tv, &tvnow, &tvsum);
  248. #else /* !(defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)) */
  249. if (gettimeofday(&tvnow, NULL) < 0)
  250. return -1;
  251. timeradd(tv, &tvnow, &tvsum);
  252. #endif /* defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK) */
  253. ts.tv_sec = tvsum.tv_sec;
  254. ts.tv_nsec = tvsum.tv_usec * 1000;
  255. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  256. if (r == 0)
  257. return 0;
  258. else if (r == ETIMEDOUT)
  259. return 1;
  260. else if (r == EINTR)
  261. continue;
  262. else
  263. return -1;
  264. }
  265. }
  266. }
  267. /** Wake up one of the waiters on <b>cond</b>. */
  268. void
  269. tor_cond_signal_one(tor_cond_t *cond)
  270. {
  271. pthread_cond_signal(&cond->cond);
  272. }
  273. /** Wake up all of the waiters on <b>cond</b>. */
  274. void
  275. tor_cond_signal_all(tor_cond_t *cond)
  276. {
  277. pthread_cond_broadcast(&cond->cond);
  278. }
  279. int
  280. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  281. {
  282. int err = pthread_key_create(&threadlocal->key, NULL);
  283. return err ? -1 : 0;
  284. }
  285. void
  286. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  287. {
  288. pthread_key_delete(threadlocal->key);
  289. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  290. }
  291. void *
  292. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  293. {
  294. return pthread_getspecific(threadlocal->key);
  295. }
  296. void
  297. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  298. {
  299. int err = pthread_setspecific(threadlocal->key, value);
  300. tor_assert(err == 0);
  301. }
  302. /** Set up common structures for use by threading. */
  303. void
  304. tor_threads_init(void)
  305. {
  306. if (!threads_initialized) {
  307. pthread_mutexattr_init(&attr_recursive);
  308. pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
  309. const int ret1 = pthread_attr_init(&attr_detached);
  310. tor_assert(ret1 == 0);
  311. #ifndef PTHREAD_CREATE_DETACHED
  312. #define PTHREAD_CREATE_DETACHED 1
  313. #endif
  314. const int ret2 =
  315. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  316. tor_assert(ret2 == 0);
  317. threads_initialized = 1;
  318. set_main_thread();
  319. }
  320. }