pthread_create.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #define _GNU_SOURCE
  2. #include "pthread_impl.h"
  3. #include "stdio_impl.h"
  4. #include "libc.h"
  5. #include <sys/mman.h>
  6. #include <string.h>
  7. #include <stddef.h>
  8. void *__mmap(void *, size_t, int, int, int, off_t);
  9. int __munmap(void *, size_t);
  10. int __mprotect(void *, size_t, int);
  11. static void dummy_0()
  12. {
  13. }
  14. weak_alias(dummy_0, __acquire_ptc);
  15. weak_alias(dummy_0, __release_ptc);
  16. weak_alias(dummy_0, __pthread_tsd_run_dtors);
  17. weak_alias(dummy_0, __do_orphaned_stdio_locks);
  18. weak_alias(dummy_0, __dl_thread_cleanup);
  19. _Noreturn void __pthread_exit(void *result)
  20. {
  21. pthread_t self = __pthread_self();
  22. sigset_t set;
  23. self->canceldisable = 1;
  24. self->cancelasync = 0;
  25. self->result = result;
  26. while (self->cancelbuf) {
  27. void (*f)(void *) = self->cancelbuf->__f;
  28. void *x = self->cancelbuf->__x;
  29. self->cancelbuf = self->cancelbuf->__next;
  30. f(x);
  31. }
  32. __pthread_tsd_run_dtors();
  33. __lock(self->exitlock);
  34. /* Mark this thread dead before decrementing count */
  35. __lock(self->killlock);
  36. self->dead = 1;
  37. /* Block all signals before decrementing the live thread count.
  38. * This is important to ensure that dynamically allocated TLS
  39. * is not under-allocated/over-committed, and possibly for other
  40. * reasons as well. */
  41. __block_all_sigs(&set);
  42. /* Wait to unlock the kill lock, which governs functions like
  43. * pthread_kill which target a thread id, until signals have
  44. * been blocked. This precludes observation of the thread id
  45. * as a live thread (with application code running in it) after
  46. * the thread was reported dead by ESRCH being returned. */
  47. __unlock(self->killlock);
  48. /* It's impossible to determine whether this is "the last thread"
  49. * until performing the atomic decrement, since multiple threads
  50. * could exit at the same time. For the last thread, revert the
  51. * decrement and unblock signals to give the atexit handlers and
  52. * stdio cleanup code a consistent state. */
  53. if (a_fetch_add(&libc.threads_minus_1, -1)==0) {
  54. libc.threads_minus_1 = 0;
  55. __restore_sigs(&set);
  56. exit(0);
  57. }
  58. /* Process robust list in userspace to handle non-pshared mutexes
  59. * and the detached thread case where the robust list head will
  60. * be invalid when the kernel would process it. */
  61. __vm_lock();
  62. volatile void *volatile *rp;
  63. while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {
  64. pthread_mutex_t *m = (void *)((char *)rp
  65. - offsetof(pthread_mutex_t, _m_next));
  66. int waiters = m->_m_waiters;
  67. int priv = (m->_m_type & 128) ^ 128;
  68. self->robust_list.pending = rp;
  69. self->robust_list.head = *rp;
  70. int cont = a_swap(&m->_m_lock, 0x40000000);
  71. self->robust_list.pending = 0;
  72. if (cont < 0 || waiters)
  73. __wake(&m->_m_lock, 1, priv);
  74. }
  75. __vm_unlock();
  76. __do_orphaned_stdio_locks();
  77. __dl_thread_cleanup();
  78. if (self->detached && self->map_base) {
  79. /* Detached threads must avoid the kernel clear_child_tid
  80. * feature, since the virtual address will have been
  81. * unmapped and possibly already reused by a new mapping
  82. * at the time the kernel would perform the write. In
  83. * the case of threads that started out detached, the
  84. * initial clone flags are correct, but if the thread was
  85. * detached later (== 2), we need to clear it here. */
  86. if (self->detached == 2) __syscall(SYS_set_tid_address, 0);
  87. /* Robust list will no longer be valid, and was already
  88. * processed above, so unregister it with the kernel. */
  89. if (self->robust_list.off)
  90. __syscall(SYS_set_robust_list, 0, 3*sizeof(long));
  91. /* Since __unmapself bypasses the normal munmap code path,
  92. * explicitly wait for vmlock holders first. */
  93. __vm_wait();
  94. /* The following call unmaps the thread's stack mapping
  95. * and then exits without touching the stack. */
  96. __unmapself(self->map_base, self->map_size);
  97. }
  98. for (;;) __syscall(SYS_exit, 0);
  99. }
  100. void __do_cleanup_push(struct __ptcb *cb)
  101. {
  102. struct pthread *self = __pthread_self();
  103. cb->__next = self->cancelbuf;
  104. self->cancelbuf = cb;
  105. }
  106. void __do_cleanup_pop(struct __ptcb *cb)
  107. {
  108. __pthread_self()->cancelbuf = cb->__next;
  109. }
  110. static int start(void *p)
  111. {
  112. pthread_t self = p;
  113. if (self->startlock[0]) {
  114. __wait(self->startlock, 0, 1, 1);
  115. if (self->startlock[0]) {
  116. self->detached = 2;
  117. pthread_exit(0);
  118. }
  119. __restore_sigs(self->sigmask);
  120. }
  121. if (self->unblock_cancel)
  122. __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK,
  123. SIGPT_SET, 0, _NSIG/8);
  124. __pthread_exit(self->start(self->start_arg));
  125. return 0;
  126. }
  127. static int start_c11(void *p)
  128. {
  129. pthread_t self = p;
  130. int (*start)(void*) = (int(*)(void*)) self->start;
  131. __pthread_exit((void *)(uintptr_t)start(self->start_arg));
  132. return 0;
  133. }
  134. #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
  135. /* pthread_key_create.c overrides this */
  136. static volatile size_t dummy = 0;
  137. weak_alias(dummy, __pthread_tsd_size);
  138. static void *dummy_tsd[1] = { 0 };
  139. weak_alias(dummy_tsd, __pthread_tsd_main);
  140. volatile int __block_new_threads = 0;
  141. static FILE *volatile dummy_file = 0;
  142. weak_alias(dummy_file, __stdin_used);
  143. weak_alias(dummy_file, __stdout_used);
  144. weak_alias(dummy_file, __stderr_used);
  145. static void init_file_lock(FILE *f)
  146. {
  147. if (f && f->lock<0) f->lock = 0;
  148. }
  149. void *__copy_tls(unsigned char *);
  150. int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)
  151. {
  152. int ret, c11 = (attrp == __ATTRP_C11_THREAD);
  153. size_t size, guard;
  154. struct pthread *self, *new;
  155. unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;
  156. unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
  157. | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
  158. | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
  159. int do_sched = 0;
  160. pthread_attr_t attr = {0};
  161. if (!libc.can_do_threads) return ENOSYS;
  162. self = __pthread_self();
  163. if (!libc.threaded) {
  164. for (FILE *f=*__ofl_lock(); f; f=f->next)
  165. init_file_lock(f);
  166. __ofl_unlock();
  167. init_file_lock(__stdin_used);
  168. init_file_lock(__stdout_used);
  169. init_file_lock(__stderr_used);
  170. __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);
  171. self->tsd = (void **)__pthread_tsd_main;
  172. libc.threaded = 1;
  173. }
  174. if (attrp && !c11) attr = *attrp;
  175. __acquire_ptc();
  176. if (__block_new_threads) __wait(&__block_new_threads, 0, 1, 1);
  177. if (attr._a_stackaddr) {
  178. size_t need = libc.tls_size + __pthread_tsd_size;
  179. size = attr._a_stacksize;
  180. stack = (void *)(attr._a_stackaddr & -16);
  181. stack_limit = (void *)(attr._a_stackaddr - size);
  182. /* Use application-provided stack for TLS only when
  183. * it does not take more than ~12% or 2k of the
  184. * application's stack space. */
  185. if (need < size/8 && need < 2048) {
  186. tsd = stack - __pthread_tsd_size;
  187. stack = tsd - libc.tls_size;
  188. memset(stack, 0, need);
  189. } else {
  190. size = ROUND(need);
  191. guard = 0;
  192. }
  193. } else {
  194. guard = ROUND(attr._a_guardsize);
  195. size = guard + ROUND(attr._a_stacksize
  196. + libc.tls_size + __pthread_tsd_size);
  197. }
  198. if (!tsd) {
  199. if (guard) {
  200. map = __mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);
  201. if (map == MAP_FAILED) goto fail;
  202. if (__mprotect(map+guard, size-guard, PROT_READ|PROT_WRITE)
  203. && errno != ENOSYS) {
  204. __munmap(map, size);
  205. goto fail;
  206. }
  207. } else {
  208. map = __mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
  209. if (map == MAP_FAILED) goto fail;
  210. }
  211. tsd = map + size - __pthread_tsd_size;
  212. if (!stack) {
  213. stack = tsd - libc.tls_size;
  214. stack_limit = map + guard;
  215. }
  216. }
  217. new = __copy_tls(tsd - libc.tls_size);
  218. new->map_base = map;
  219. new->map_size = size;
  220. new->stack = stack;
  221. new->stack_size = stack - stack_limit;
  222. new->start = entry;
  223. new->start_arg = arg;
  224. new->self = new;
  225. new->tsd = (void *)tsd;
  226. new->locale = &libc.global_locale;
  227. if (attr._a_detach) {
  228. new->detached = 1;
  229. flags -= CLONE_CHILD_CLEARTID;
  230. }
  231. if (attr._a_sched) {
  232. do_sched = new->startlock[0] = 1;
  233. __block_app_sigs(new->sigmask);
  234. }
  235. new->robust_list.head = &new->robust_list.head;
  236. new->unblock_cancel = self->cancel;
  237. new->CANARY = self->CANARY;
  238. a_inc(&libc.threads_minus_1);
  239. ret = __clone((c11 ? start_c11 : start), stack, flags, new, &new->tid, TP_ADJ(new), &new->tid);
  240. __release_ptc();
  241. if (do_sched) {
  242. __restore_sigs(new->sigmask);
  243. }
  244. if (ret < 0) {
  245. a_dec(&libc.threads_minus_1);
  246. if (map) __munmap(map, size);
  247. return EAGAIN;
  248. }
  249. if (do_sched) {
  250. ret = __syscall(SYS_sched_setscheduler, new->tid,
  251. attr._a_policy, &attr._a_prio);
  252. a_store(new->startlock, ret<0 ? 2 : 0);
  253. __wake(new->startlock, 1, 1);
  254. if (ret < 0) return -ret;
  255. }
  256. *res = new;
  257. return 0;
  258. fail:
  259. __release_ptc();
  260. return EAGAIN;
  261. }
  262. weak_alias(__pthread_exit, pthread_exit);
  263. weak_alias(__pthread_create, pthread_create);