1 #include "pthread_impl.h"
6 weak_alias(dummy_0, __synccall_lock);
7 weak_alias(dummy_0, __synccall_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 __pthread_tsd_run_dtors();
27 __lock(&self->exitlock);
29 /* Mark this thread dead before decrementing count */
30 __lock(&self->killlock);
32 a_store(&self->killlock, 0);
34 do n = libc.threads_minus_1;
35 while (n && a_cas(&libc.threads_minus_1, n, n-1)!=n);
38 if (self->detached && self->map_base) {
39 __syscall(SYS_rt_sigprocmask, SIG_BLOCK, (uint64_t[]){-1},0,8);
40 __unmapself(self->map_base, self->map_size);
43 __syscall(SYS_exit, 0);
46 static int start(void *p)
48 struct pthread *self = p;
49 if (self->unblock_cancel)
50 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, 8);
51 pthread_exit(self->start(self->start_arg));
55 int __uniclone(void *, int (*)(), void *);
57 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
59 /* pthread_key_create.c overrides this */
60 static const size_t dummy = 0;
61 weak_alias(dummy, __pthread_tsd_size);
63 int pthread_create(pthread_t *res, const pthread_attr_t *attr, void *(*entry)(void *), void *arg)
66 size_t size = DEFAULT_STACK_SIZE + DEFAULT_GUARD_SIZE;
67 size_t guard = DEFAULT_GUARD_SIZE;
68 struct pthread *self = pthread_self(), *new;
69 unsigned char *map, *stack, *tsd;
71 if (!self) return ENOSYS;
73 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, 8);
78 guard = ROUND(attr->_a_guardsize + DEFAULT_GUARD_SIZE);
79 size = guard + ROUND(attr->_a_stacksize + DEFAULT_STACK_SIZE);
81 size += __pthread_tsd_size;
82 map = mmap(0, size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0);
83 if (!map) return EAGAIN;
84 if (guard) mprotect(map, guard, PROT_NONE);
86 tsd = map + size - __pthread_tsd_size;
87 new = (void *)(tsd - sizeof *new - PAGE_SIZE%sizeof *new);
91 new->errno_ptr = &new->errno_val;
95 new->tsd = (void *)tsd;
96 if (attr) new->detached = attr->_a_detach;
97 new->unblock_cancel = self->cancel;
98 memcpy(new->tlsdesc, self->tlsdesc, sizeof new->tlsdesc);
99 new->tlsdesc[1] = (uintptr_t)new;
100 stack = (void *)((uintptr_t)new-1 & ~(uintptr_t)15);
104 a_inc(&libc.threads_minus_1);
105 ret = __uniclone(stack, start, new);
110 a_dec(&libc.threads_minus_1);
118 void pthread_exit(void *result)
120 struct pthread *self = pthread_self();
121 struct __ptcb cb = { .__next = self->cancelbuf };
122 self->result = result;
123 __pthread_unwind_next(&cb);