compat_pthreads.c 7.8 KB

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