1 #include "pthread_impl.h"
6 weak_alias(dummy_0, __rsyscall_lock);
7 weak_alias(dummy_0, __rsyscall_unlock);
8 weak_alias(dummy_0, __pthread_tsd_run_dtors);
10 #ifdef __pthread_unwind_next
11 #undef __pthread_unwind_next
12 #define __pthread_unwind_next __pthread_unwind_next_3
15 void __pthread_unwind_next(struct __ptcb *cb)
17 pthread_t self = pthread_self();
21 self->cancelbuf = cb->__next->__next;
22 longjmp((void *)cb->__next->__jb, 1);
25 LOCK(&self->exitlock);
27 __pthread_tsd_run_dtors();
29 /* Mark this thread dead before decrementing count */
32 do n = libc.threads_minus_1;
33 while (n && a_cas(&libc.threads_minus_1, n, n-1)!=n);
36 if (self->detached && self->map_base) {
37 __syscall(SYS_rt_sigprocmask, SIG_BLOCK, (uint64_t[]){-1},0,8);
38 __unmapself(self->map_base, self->map_size);
41 __syscall(SYS_exit, 0);
44 static int start(void *p)
46 struct pthread *self = p;
47 if (self->unblock_cancel)
48 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, 8);
49 pthread_exit(self->start(self->start_arg));
53 int __uniclone(void *, int (*)(), void *);
55 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
57 /* pthread_key_create.c overrides this */
58 static const size_t dummy = 0;
59 weak_alias(dummy, __pthread_tsd_size);
61 int pthread_create(pthread_t *res, const pthread_attr_t *attr, void *(*entry)(void *), void *arg)
64 size_t size = DEFAULT_STACK_SIZE + DEFAULT_GUARD_SIZE;
65 size_t guard = DEFAULT_GUARD_SIZE;
66 struct pthread *self = pthread_self(), *new;
67 unsigned char *map, *stack, *tsd;
69 if (!self) return ENOSYS;
71 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, 8);
76 guard = ROUND(attr->_a_guardsize + DEFAULT_GUARD_SIZE);
77 size = guard + ROUND(attr->_a_stacksize + DEFAULT_STACK_SIZE);
79 size += __pthread_tsd_size;
80 map = mmap(0, size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0);
81 if (!map) return EAGAIN;
82 if (guard) mprotect(map, guard, PROT_NONE);
84 tsd = map + size - __pthread_tsd_size;
85 new = (void *)(tsd - sizeof *new - PAGE_SIZE%sizeof *new);
89 new->errno_ptr = &new->errno_val;
93 new->tsd = (void *)tsd;
94 if (attr) new->detached = attr->_a_detach;
95 new->unblock_cancel = self->cancel;
96 memcpy(new->tlsdesc, self->tlsdesc, sizeof new->tlsdesc);
97 new->tlsdesc[1] = (uintptr_t)new;
98 stack = (void *)((uintptr_t)new-1 & ~(uintptr_t)15);
102 a_inc(&libc.threads_minus_1);
103 ret = __uniclone(stack, start, new);
108 a_dec(&libc.threads_minus_1);
116 void pthread_exit(void *result)
118 struct pthread *self = pthread_self();
119 struct __ptcb cb = { .__next = self->cancelbuf };
120 self->result = result;
121 __pthread_unwind_next(&cb);