compat_pthreads.c 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 "lib/thread/threads.h"
  13. #include "lib/log/torlog.h"
  14. #include "lib/log/util_bug.h"
  15. #include <sys/time.h>
  16. #include <pthread.h>
  17. #include <signal.h>
  18. #include <time.h>
  19. #include <errno.h>
  20. #include <string.h>
  21. /** Wraps a void (*)(void*) function and its argument so we can
  22. * invoke them in a way pthreads would expect.
  23. */
  24. typedef struct tor_pthread_data_t {
  25. void (*func)(void *);
  26. void *data;
  27. } tor_pthread_data_t;
  28. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  29. * and free _data. Used to make sure we can call functions the way pthread
  30. * expects. */
  31. static void *
  32. tor_pthread_helper_fn(void *_data)
  33. {
  34. tor_pthread_data_t *data = _data;
  35. void (*func)(void*);
  36. void *arg;
  37. /* mask signals to worker threads to avoid SIGPIPE, etc */
  38. sigset_t sigs;
  39. /* We're in a subthread; don't handle any signals here. */
  40. sigfillset(&sigs);
  41. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  42. func = data->func;
  43. arg = data->data;
  44. tor_free(_data);
  45. func(arg);
  46. return NULL;
  47. }
  48. /**
  49. * A pthread attribute to make threads start detached.
  50. */
  51. static pthread_attr_t attr_detached;
  52. /** True iff we've called tor_threads_init() */
  53. static int threads_initialized = 0;
  54. /** Minimalist interface to run a void function in the background. On
  55. * Unix calls pthread_create, on win32 calls beginthread. Returns -1 on
  56. * failure.
  57. * func should not return, but rather should call spawn_exit.
  58. *
  59. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  60. * since in a multithreaded environment, there is no way to be sure that
  61. * the caller's stack will still be around when the called function is
  62. * running.
  63. */
  64. int
  65. spawn_func(void (*func)(void *), void *data)
  66. {
  67. pthread_t thread;
  68. tor_pthread_data_t *d;
  69. if (PREDICT_UNLIKELY(!threads_initialized)) {
  70. tor_threads_init();
  71. }
  72. d = tor_malloc(sizeof(tor_pthread_data_t));
  73. d->data = data;
  74. d->func = func;
  75. if (pthread_create(&thread, &attr_detached, tor_pthread_helper_fn, d)) {
  76. tor_free(d);
  77. return -1;
  78. }
  79. return 0;
  80. }
  81. /** End the current thread/process.
  82. */
  83. void
  84. spawn_exit(void)
  85. {
  86. pthread_exit(NULL);
  87. }
  88. /** Return an integer representing this thread. */
  89. unsigned long
  90. tor_get_thread_id(void)
  91. {
  92. union {
  93. pthread_t thr;
  94. unsigned long id;
  95. } r;
  96. r.thr = pthread_self();
  97. return r.id;
  98. }
  99. /* Conditions. */
  100. /** Initialize an already-allocated condition variable. */
  101. int
  102. tor_cond_init(tor_cond_t *cond)
  103. {
  104. pthread_condattr_t condattr;
  105. memset(cond, 0, sizeof(tor_cond_t));
  106. /* Default condition attribute. Might be used if clock monotonic is
  107. * available else this won't affect anything. */
  108. if (pthread_condattr_init(&condattr)) {
  109. return -1;
  110. }
  111. #if defined(HAVE_CLOCK_GETTIME)
  112. #if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && \
  113. defined(CLOCK_MONOTONIC)
  114. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  115. * won't affect the timeout value. */
  116. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  117. return -1;
  118. }
  119. #define USE_COND_CLOCK CLOCK_MONOTONIC
  120. #else /* !(defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ...) */
  121. /* On OSX Sierra, there is no pthread_condattr_setclock, so we are stuck
  122. * with the realtime clock.
  123. */
  124. #define USE_COND_CLOCK CLOCK_REALTIME
  125. #endif /* defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ... */
  126. #endif /* defined(HAVE_CLOCK_GETTIME) */
  127. if (pthread_cond_init(&cond->cond, &condattr)) {
  128. return -1;
  129. }
  130. return 0;
  131. }
  132. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  133. * itself. */
  134. void
  135. tor_cond_uninit(tor_cond_t *cond)
  136. {
  137. if (pthread_cond_destroy(&cond->cond)) {
  138. // LCOV_EXCL_START
  139. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  140. return;
  141. // LCOV_EXCL_STOP
  142. }
  143. }
  144. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  145. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  146. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  147. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  148. * needs to have been allocated with tor_mutex_init_for_cond().
  149. *
  150. * Returns 0 on success, -1 on failure, 1 on timeout. */
  151. int
  152. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  153. {
  154. int r;
  155. if (tv == NULL) {
  156. while (1) {
  157. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  158. if (r == EINTR) {
  159. /* EINTR should be impossible according to POSIX, but POSIX, like the
  160. * Pirate's Code, is apparently treated "more like what you'd call
  161. * guidelines than actual rules." */
  162. continue; // LCOV_EXCL_LINE
  163. }
  164. return r ? -1 : 0;
  165. }
  166. } else {
  167. struct timeval tvnow, tvsum;
  168. struct timespec ts;
  169. while (1) {
  170. #if defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)
  171. if (clock_gettime(USE_COND_CLOCK, &ts) < 0) {
  172. return -1;
  173. }
  174. tvnow.tv_sec = ts.tv_sec;
  175. tvnow.tv_usec = (int)(ts.tv_nsec / 1000);
  176. timeradd(tv, &tvnow, &tvsum);
  177. #else /* !(defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)) */
  178. if (gettimeofday(&tvnow, NULL) < 0)
  179. return -1;
  180. timeradd(tv, &tvnow, &tvsum);
  181. #endif /* defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK) */
  182. ts.tv_sec = tvsum.tv_sec;
  183. ts.tv_nsec = tvsum.tv_usec * 1000;
  184. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  185. if (r == 0)
  186. return 0;
  187. else if (r == ETIMEDOUT)
  188. return 1;
  189. else if (r == EINTR)
  190. continue;
  191. else
  192. return -1;
  193. }
  194. }
  195. }
  196. /** Wake up one of the waiters on <b>cond</b>. */
  197. void
  198. tor_cond_signal_one(tor_cond_t *cond)
  199. {
  200. pthread_cond_signal(&cond->cond);
  201. }
  202. /** Wake up all of the waiters on <b>cond</b>. */
  203. void
  204. tor_cond_signal_all(tor_cond_t *cond)
  205. {
  206. pthread_cond_broadcast(&cond->cond);
  207. }
  208. int
  209. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  210. {
  211. int err = pthread_key_create(&threadlocal->key, NULL);
  212. return err ? -1 : 0;
  213. }
  214. void
  215. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  216. {
  217. pthread_key_delete(threadlocal->key);
  218. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  219. }
  220. void *
  221. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  222. {
  223. return pthread_getspecific(threadlocal->key);
  224. }
  225. void
  226. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  227. {
  228. int err = pthread_setspecific(threadlocal->key, value);
  229. tor_assert(err == 0);
  230. }
  231. /** Set up common structures for use by threading. */
  232. void
  233. tor_threads_init(void)
  234. {
  235. if (!threads_initialized) {
  236. tor_locking_init();
  237. const int ret1 = pthread_attr_init(&attr_detached);
  238. tor_assert(ret1 == 0);
  239. #ifndef PTHREAD_CREATE_DETACHED
  240. #define PTHREAD_CREATE_DETACHED 1
  241. #endif
  242. const int ret2 =
  243. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  244. tor_assert(ret2 == 0);
  245. threads_initialized = 1;
  246. set_main_thread();
  247. }
  248. }