1 #define _GNU_SOURCE
2 #include "pthread_impl.h"
3 #include "stdio_impl.h"
4 #include "libc.h"
5 #include "lock.h"
6 #include <sys/mman.h>
7 #include <string.h>
8 #include <stddef.h>
9
dummy_0()10 static void dummy_0()
11 {
12 }
13 weak_alias(dummy_0, __acquire_ptc);
14 weak_alias(dummy_0, __release_ptc);
15 weak_alias(dummy_0, __pthread_tsd_run_dtors);
16 weak_alias(dummy_0, __do_orphaned_stdio_locks);
17 weak_alias(dummy_0, __dl_thread_cleanup);
18
19 static int tl_lock_count;
20 static int tl_lock_waiters;
21
__tl_lock(void)22 void __tl_lock(void)
23 {
24 int tid = __pthread_self()->tid;
25 int val = __thread_list_lock;
26 if (val == tid) {
27 tl_lock_count++;
28 return;
29 }
30 while ((val = a_cas(&__thread_list_lock, 0, tid)))
31 __wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
32 }
33
__tl_unlock(void)34 void __tl_unlock(void)
35 {
36 if (tl_lock_count) {
37 tl_lock_count--;
38 return;
39 }
40 a_store(&__thread_list_lock, 0);
41 if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
42 }
43
__tl_sync(pthread_t td)44 void __tl_sync(pthread_t td)
45 {
46 a_barrier();
47 int val = __thread_list_lock;
48 if (!val) return;
49 __wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
50 if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
51 }
52
__pthread_exit(void * result)53 _Noreturn void __pthread_exit(void *result)
54 {
55 pthread_t self = __pthread_self();
56 sigset_t set;
57
58 self->canceldisable = 1;
59 self->cancelasync = 0;
60 self->result = result;
61
62 while (self->cancelbuf) {
63 void (*f)(void *) = self->cancelbuf->__f;
64 void *x = self->cancelbuf->__x;
65 self->cancelbuf = self->cancelbuf->__next;
66 f(x);
67 }
68
69 __pthread_tsd_run_dtors();
70
71 /* Access to target the exiting thread with syscalls that use
72 * its kernel tid is controlled by killlock. For detached threads,
73 * any use past this point would have undefined behavior, but for
74 * joinable threads it's a valid usage that must be handled. */
75 LOCK(self->killlock);
76
77 /* The thread list lock must be AS-safe, and thus requires
78 * application signals to be blocked before it can be taken. */
79 __block_app_sigs(&set);
80 __tl_lock();
81
82 /* If this is the only thread in the list, don't proceed with
83 * termination of the thread, but restore the previous lock and
84 * signal state to prepare for exit to call atexit handlers. */
85 if (self->next == self) {
86 __tl_unlock();
87 __restore_sigs(&set);
88 UNLOCK(self->killlock);
89 exit(0);
90 }
91
92 /* At this point we are committed to thread termination. Unlink
93 * the thread from the list. This change will not be visible
94 * until the lock is released, which only happens after SYS_exit
95 * has been called, via the exit futex address pointing at the lock. */
96 libc.threads_minus_1--;
97 self->next->prev = self->prev;
98 self->prev->next = self->next;
99 self->prev = self->next = self;
100
101 /* Process robust list in userspace to handle non-pshared mutexes
102 * and the detached thread case where the robust list head will
103 * be invalid when the kernel would process it. */
104 __vm_lock();
105 volatile void *volatile *rp;
106 while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {
107 pthread_mutex_t *m = (void *)((char *)rp
108 - offsetof(pthread_mutex_t, _m_next));
109 int waiters = m->_m_waiters;
110 int priv = (m->_m_type & 128) ^ 128;
111 self->robust_list.pending = rp;
112 self->robust_list.head = *rp;
113 int cont = a_swap(&m->_m_lock, 0x40000000);
114 self->robust_list.pending = 0;
115 if (cont < 0 || waiters)
116 __wake(&m->_m_lock, 1, priv);
117 }
118 __vm_unlock();
119
120 __do_orphaned_stdio_locks();
121 __dl_thread_cleanup();
122
123 /* This atomic potentially competes with a concurrent pthread_detach
124 * call; the loser is responsible for freeing thread resources. */
125 int state = a_cas(&self->detach_state, DT_JOINABLE, DT_EXITING);
126 #if 0
127 if (state==DT_DETACHED && self->map_base) {
128 /* Robust list will no longer be valid, and was already
129 * processed above, so unregister it with the kernel. */
130 if (self->robust_list.off)
131 __syscall(SYS_set_robust_list, 0, 3*sizeof(long));
132
133 /* Since __unmapself bypasses the normal munmap code path,
134 * explicitly wait for vmlock holders first. */
135 __vm_wait();
136
137 /* The following call unmaps the thread's stack mapping
138 * and then exits without touching the stack. */
139 __unmapself(self->map_base, self->map_size);
140 }
141
142 /* Wake any joiner. */
143 __wake(&self->detach_state, 1, 1);
144 #endif
145
146 /* After the kernel thread exits, its tid may be reused. Clear it
147 * to prevent inadvertent use and inform functions that would use
148 * it that it's no longer available. */
149 if (self->detach_state == DT_DETACHED) {
150 /* Detached threads must block even implementation-internal
151 * signals, since they will not have a stack in their last
152 * moments of existence. */
153 __block_all_sigs(&set);
154 self->tid = 0;
155 }
156
157 __tl_unlock();
158 UNLOCK(self->killlock);
159
160 for (;;) __syscall(SYS_exit, 0);
161 }
162
__do_cleanup_push(struct __ptcb * cb)163 void __do_cleanup_push(struct __ptcb *cb)
164 {
165 struct pthread *self = __pthread_self();
166 cb->__next = self->cancelbuf;
167 self->cancelbuf = cb;
168 }
169
__do_cleanup_pop(struct __ptcb * cb)170 void __do_cleanup_pop(struct __ptcb *cb)
171 {
172 __pthread_self()->cancelbuf = cb->__next;
173 }
174
175 struct start_args {
176 void *(*start_func)(void *);
177 void *start_arg;
178 volatile int control;
179 unsigned long sig_mask[_NSIG/8/sizeof(long)];
180 };
181
start(void * p)182 static int start(void *p)
183 {
184 struct start_args *args = (struct start_args *)p;
185 __syscall(SYS_rt_sigprocmask, SIG_SETMASK, &args->sig_mask, 0, _NSIG/8);
186 __pthread_exit(args->start_func(args->start_arg));
187 return 0;
188 }
189
start_c11(void * p)190 static int start_c11(void *p)
191 {
192 struct start_args *args = (struct start_args *)p;
193 int (*start)(void*) = (int(*)(void*)) args->start_func;
194 __pthread_exit((void *)(uintptr_t)start(args->start_arg));
195 return 0;
196 }
197
198 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
199
200 /* pthread_key_create.c overrides this */
201 static volatile size_t dummy = 0;
202 weak_alias(dummy, __pthread_tsd_size);
203 static void *dummy_tsd[1] = { 0 };
204 weak_alias(dummy_tsd, __pthread_tsd_main);
205
__pthread_init_and_check_attr(const pthread_attr_t * restrict attrp,pthread_attr_t * attr)206 int __pthread_init_and_check_attr(const pthread_attr_t *restrict attrp, pthread_attr_t *attr)
207 {
208 int policy = 0;
209 struct sched_param param = { 0 };
210 int c11 = (attrp == __ATTRP_C11_THREAD);
211 int ret;
212
213 if (attrp && !c11) memcpy(attr, attrp, sizeof(pthread_attr_t));
214
215 if (!attrp || c11) {
216 pthread_attr_init(attr);
217 }
218
219 if (!attr->_a_sched) {
220 ret = pthread_getschedparam(pthread_self(), &policy, ¶m);
221 if (ret) return ret;
222 attr->_a_policy = policy;
223 attr->_a_prio = param.sched_priority;
224 }
225
226 if (attr->_a_policy != SCHED_RR && attr->_a_policy != SCHED_FIFO) {
227 return EINVAL;
228 }
229
230 if (attr->_a_prio < 0 || attr->_a_prio > PTHREAD_PRIORITY_LOWEST) {
231 return EINVAL;
232 }
233
234 return 0;
235 }
236
__pthread_create(pthread_t * restrict res,const pthread_attr_t * restrict attrp,void * (* entry)(void *),void * restrict arg)237 int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)
238 {
239 int ret, c11 = (attrp == __ATTRP_C11_THREAD);
240 size_t size, guard;
241 struct pthread *self, *new;
242 unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;
243 unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
244 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
245 | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
246 pthread_attr_t attr = { 0 };
247 sigset_t set;
248
249 if (!libc.can_do_threads) return ENOSYS;
250 if (!entry) return EINVAL;
251 self = __pthread_self();
252 __acquire_ptc();
253
254 ret = __pthread_init_and_check_attr(attrp, &attr);
255 if (ret) {
256 __release_ptc();
257 return ret;
258 }
259
260 if (attr._a_stackaddr) {
261 size_t need = libc.tls_size + __pthread_tsd_size;
262 size = attr._a_stacksize;
263 stack = (void *)(attr._a_stackaddr & -16);
264 stack_limit = (void *)(attr._a_stackaddr - size);
265 /* Use application-provided stack for TLS only when
266 * it does not take more than ~12% or 2k of the
267 * application's stack space. */
268 if (need < size/8 && need < 2048) {
269 tsd = stack - __pthread_tsd_size;
270 stack = tsd - libc.tls_size;
271 memset(stack, 0, need);
272 } else {
273 size = ROUND(need);
274 }
275 guard = 0;
276 } else {
277 guard = ROUND(attr._a_guardsize);
278 size = guard + ROUND(attr._a_stacksize
279 + libc.tls_size + __pthread_tsd_size);
280 }
281
282 if (!tsd) {
283 if (guard) {
284 map = __mmap(0, size, PROT_READ|PROT_WRITE|PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);
285 if (map == MAP_FAILED) goto fail;
286 if (__mprotect(map+guard, size-guard, PROT_READ|PROT_WRITE)
287 && errno != ENOSYS) {
288 __munmap(map, size);
289 goto fail;
290 }
291 } else {
292 map = __mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
293 if (map == MAP_FAILED) goto fail;
294 }
295 tsd = map + size - __pthread_tsd_size;
296 if (!stack) {
297 stack = tsd - libc.tls_size;
298 stack_limit = map + guard;
299 }
300 }
301
302 new = __copy_tls(tsd - libc.tls_size);
303 new->map_base = map;
304 new->map_size = size;
305 new->stack = stack;
306 new->stack_size = stack - stack_limit;
307 new->guard_size = guard;
308 new->self = new;
309 new->tsd = (void *)tsd;
310 new->locale = &libc.global_locale;
311 if (attr._a_detach) {
312 new->detach_state = DT_DETACHED;
313 } else {
314 new->detach_state = DT_JOINABLE;
315 }
316 new->robust_list.head = &new->robust_list.head;
317 new->CANARY = self->CANARY;
318 new->sysinfo = self->sysinfo;
319
320 /* Setup argument structure for the new thread on its stack.
321 * It's safe to access from the caller only until the thread
322 * list is unlocked. */
323 stack -= (uintptr_t)stack % sizeof(uintptr_t);
324 stack -= sizeof(struct start_args);
325 struct start_args *args = (void *)stack;
326 args->start_func = entry;
327 args->start_arg = arg;
328 args->control = attr._a_sched ? 1 : 0;
329
330 /* Application signals (but not the synccall signal) must be
331 * blocked before the thread list lock can be taken, to ensure
332 * that the lock is AS-safe. */
333 __block_app_sigs(&set);
334
335 /* Ensure SIGCANCEL is unblocked in new thread. This requires
336 * working with a copy of the set so we can restore the
337 * original mask in the calling thread. */
338 memcpy(&args->sig_mask, &set, sizeof args->sig_mask);
339 args->sig_mask[(SIGCANCEL-1)/8/sizeof(long)] &=
340 ~(1UL<<((SIGCANCEL-1)%(8*sizeof(long))));
341
342 __tl_lock();
343 libc.threads_minus_1++;
344 ret = __thread_clone((c11 ? start_c11 : start), flags, new, stack);
345
346 /* All clone failures translate to EAGAIN. If explicit scheduling
347 * was requested, attempt it before unlocking the thread list so
348 * that the failed thread is never exposed and so that we can
349 * clean up all transient resource usage before returning. */
350 if (ret < 0) {
351 ret = -EAGAIN;
352 } else {
353 new->next = self->next;
354 new->prev = self;
355 new->next->prev = new;
356 new->prev->next = new;
357
358 *res = new;
359 __tl_unlock();
360 __restore_sigs(&set);
361 __release_ptc();
362 ret = __syscall(SYS_sched_setscheduler,
363 new->tid, attr._a_policy, attr._a_prio, MUSL_TYPE_THREAD);
364 }
365
366 if (ret < 0) {
367 libc.threads_minus_1--;
368 __tl_unlock();
369 __restore_sigs(&set);
370 __release_ptc();
371 if (map) __munmap(map, size);
372 return -ret;
373 }
374
375 return 0;
376 fail:
377 __release_ptc();
378 return EAGAIN;
379 }
380
381 weak_alias(__pthread_exit, pthread_exit);
382 weak_alias(__pthread_create, pthread_create);
383