1 #include "pthread_impl.h"
6 weak_alias(dummy_0, __rsyscall_lock);
7 weak_alias(dummy_0, __rsyscall_unlock);
9 static void dummy_1(pthread_t self)
12 weak_alias(dummy_1, __pthread_tsd_run_dtors);
14 #ifdef __pthread_unwind_next
15 #undef __pthread_unwind_next
16 #define __pthread_unwind_next __pthread_unwind_next_3
19 void __pthread_unwind_next(struct __ptcb *cb)
24 if (cb->__next) longjmp((void *)cb->__next->__jb, 1);
26 self = pthread_self();
28 LOCK(&self->exitlock);
30 __pthread_tsd_run_dtors(self);
32 /* Mark this thread dead before decrementing count */
35 do n = libc.threads_minus_1;
36 while (n && a_cas(&libc.threads_minus_1, n, n-1)!=n);
39 if (self->detached && self->map_base) {
40 __syscall(SYS_rt_sigprocmask, SIG_BLOCK, (long)(uint64_t[1]){-1},0,8);
41 __unmapself(self->map_base, self->map_size);
44 __syscall(SYS_exit, 0);
47 static void init_threads()
51 libc.lockfile = __lockfile;
54 sigaddset(&set, SIGSYSCALL);
55 sigaddset(&set, SIGCANCEL);
56 __libc_sigprocmask(SIG_UNBLOCK, &set, 0);
59 static int start(void *p)
61 struct pthread *self = p;
62 if (self->unblock_cancel) {
65 sigaddset(&set, SIGCANCEL);
66 __libc_sigprocmask(SIG_UNBLOCK, &set, 0);
68 pthread_exit(self->start(self->start_arg));
72 int __uniclone(void *, int (*)(), void *);
74 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
76 /* pthread_key_create.c overrides this */
77 static const size_t dummy = 0;
78 weak_alias(dummy, __pthread_tsd_size);
80 int pthread_create(pthread_t *res, const pthread_attr_t *attr, void *(*entry)(void *), void *arg)
85 struct pthread *self = pthread_self(), *new;
86 unsigned char *map, *stack, *tsd;
87 const pthread_attr_t default_attr = { 0 };
89 if (!self) return ENOSYS;
90 if (!init && ++init) init_threads();
92 if (!attr) attr = &default_attr;
93 guard = ROUND(attr->_a_guardsize + DEFAULT_GUARD_SIZE);
94 size = guard + ROUND(attr->_a_stacksize + DEFAULT_STACK_SIZE);
95 size += __pthread_tsd_size;
96 map = mmap(0, size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0);
97 if (!map) return EAGAIN;
98 if (guard) mprotect(map, guard, PROT_NONE);
100 tsd = map + size - __pthread_tsd_size;
101 new = (void *)(tsd - sizeof *new - PAGE_SIZE%sizeof *new);
103 new->map_size = size;
104 new->pid = self->pid;
105 new->errno_ptr = &new->errno_val;
107 new->start_arg = arg;
109 new->tsd = (void *)tsd;
110 new->detached = attr->_a_detach;
112 new->unblock_cancel = self->cancel;
113 new->result = PTHREAD_CANCELED;
114 memcpy(new->tlsdesc, self->tlsdesc, sizeof new->tlsdesc);
115 new->tlsdesc[1] = (uintptr_t)new;
116 stack = (void *)((uintptr_t)new-1 & ~(uintptr_t)15);
120 a_inc(&libc.threads_minus_1);
121 ret = __uniclone(stack, start, new);
126 a_dec(&libc.threads_minus_1);
134 void pthread_exit(void *result)
136 struct pthread *self = pthread_self();
137 struct __ptcb cb = { .__next = self->cancelbuf };
138 self->result = result;
139 self->canceldisable = 1;
140 self->cancelasync = 0;
141 __pthread_unwind_next(&cb);