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