compat_pthreads.c 8.4 KB

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