1570af302Sopenharmony_ci#define _GNU_SOURCE
2570af302Sopenharmony_ci#define ANON_STACK_NAME_SIZE 50
3570af302Sopenharmony_ci#include "musl_log.h"
4570af302Sopenharmony_ci#include "pthread_impl.h"
5570af302Sopenharmony_ci#include "stdio_impl.h"
6570af302Sopenharmony_ci#include "libc.h"
7570af302Sopenharmony_ci#include "lock.h"
8570af302Sopenharmony_ci#include <sys/mman.h>
9570af302Sopenharmony_ci#include <sys/prctl.h>
10570af302Sopenharmony_ci#include <string.h>
11570af302Sopenharmony_ci#include <stddef.h>
12570af302Sopenharmony_ci#include <stdarg.h>
13570af302Sopenharmony_ci
14570af302Sopenharmony_cipid_t getpid(void);
15570af302Sopenharmony_ci
16570af302Sopenharmony_civoid log_print(const char* info, ...)
17570af302Sopenharmony_ci{
18570af302Sopenharmony_ci    va_list ap;
19570af302Sopenharmony_ci    va_start(ap, info);
20570af302Sopenharmony_ci    vfprintf(stdout, info, ap);
21570af302Sopenharmony_ci    va_end(ap);
22570af302Sopenharmony_ci}
23570af302Sopenharmony_ci
24570af302Sopenharmony_civoid stack_naming(struct pthread *new) {
25570af302Sopenharmony_ci	size_t size_len;
26570af302Sopenharmony_ci	unsigned char *start_addr;
27570af302Sopenharmony_ci	char name[ANON_STACK_NAME_SIZE];
28570af302Sopenharmony_ci	if (new->guard_size) {
29570af302Sopenharmony_ci		snprintf(name, ANON_STACK_NAME_SIZE, "guard:%d", new->tid);
30570af302Sopenharmony_ci		prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, new->map_base, new->guard_size, name);
31570af302Sopenharmony_ci		start_addr = new->map_base + new->guard_size;
32570af302Sopenharmony_ci		size_len = new->map_size - new->guard_size;
33570af302Sopenharmony_ci		memset(name, 0, ANON_STACK_NAME_SIZE);
34570af302Sopenharmony_ci	} else {
35570af302Sopenharmony_ci		start_addr = new->map_base;
36570af302Sopenharmony_ci		size_len = new->map_size;
37570af302Sopenharmony_ci	}
38570af302Sopenharmony_ci	snprintf(name, ANON_STACK_NAME_SIZE, "stack:%d", new->tid);
39570af302Sopenharmony_ci	prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, start_addr, size_len, name);
40570af302Sopenharmony_ci};
41570af302Sopenharmony_ci
42570af302Sopenharmony_ci#ifdef RESERVE_SIGNAL_STACK
43570af302Sopenharmony_ci#if defined (__LP64__)
44570af302Sopenharmony_ci#define RESERVE_SIGNAL_STACK_SIZE (32 * 1024)
45570af302Sopenharmony_ci#else
46570af302Sopenharmony_ci#define RESERVE_SIGNAL_STACK_SIZE (20 * 1024)
47570af302Sopenharmony_ci#endif
48570af302Sopenharmony_civoid __pthread_reserve_signal_stack()
49570af302Sopenharmony_ci{
50570af302Sopenharmony_ci	void* stack = mmap(NULL, RESERVE_SIGNAL_STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
51570af302Sopenharmony_ci	if (stack != MAP_FAILED) {
52570af302Sopenharmony_ci		if (mprotect(stack, __default_guardsize, PROT_NONE) == -1) {
53570af302Sopenharmony_ci			munmap(stack, RESERVE_SIGNAL_STACK_SIZE);
54570af302Sopenharmony_ci			return;
55570af302Sopenharmony_ci		}
56570af302Sopenharmony_ci	}
57570af302Sopenharmony_ci
58570af302Sopenharmony_ci	stack_t signal_stack;
59570af302Sopenharmony_ci	signal_stack.ss_sp = (uint8_t*)stack + __default_guardsize;
60570af302Sopenharmony_ci	signal_stack.ss_size = RESERVE_SIGNAL_STACK_SIZE - __default_guardsize;
61570af302Sopenharmony_ci	signal_stack.ss_flags = 0;
62570af302Sopenharmony_ci	sigaltstack(&signal_stack, NULL);
63570af302Sopenharmony_ci
64570af302Sopenharmony_ci	pthread_t self = __pthread_self();
65570af302Sopenharmony_ci	self->signal_stack = stack;
66570af302Sopenharmony_ci	char name[ANON_STACK_NAME_SIZE];
67570af302Sopenharmony_ci	snprintf(name, ANON_STACK_NAME_SIZE, "signal_stack:%d", __pthread_self()->tid);
68570af302Sopenharmony_ci	prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, signal_stack.ss_sp, signal_stack.ss_size, name);
69570af302Sopenharmony_ci	return;
70570af302Sopenharmony_ci}
71570af302Sopenharmony_ci
72570af302Sopenharmony_civoid __pthread_release_signal_stack()
73570af302Sopenharmony_ci{
74570af302Sopenharmony_ci	pthread_t self = __pthread_self();
75570af302Sopenharmony_ci	if (self->signal_stack == NULL) {
76570af302Sopenharmony_ci		return;
77570af302Sopenharmony_ci	}
78570af302Sopenharmony_ci
79570af302Sopenharmony_ci	stack_t signal_stack, old_stack;
80570af302Sopenharmony_ci	memset(&signal_stack, 0, sizeof(signal_stack));
81570af302Sopenharmony_ci	signal_stack.ss_flags = SS_DISABLE;
82570af302Sopenharmony_ci	sigaltstack(&signal_stack, &old_stack);
83570af302Sopenharmony_ci	munmap(self->signal_stack, __default_guardsize);
84570af302Sopenharmony_ci	if (old_stack.ss_flags != SS_DISABLE) {
85570af302Sopenharmony_ci		munmap(old_stack.ss_sp, old_stack.ss_size);
86570af302Sopenharmony_ci	}
87570af302Sopenharmony_ci	self->signal_stack = NULL;
88570af302Sopenharmony_ci}
89570af302Sopenharmony_ci
90570af302Sopenharmony_ciweak_alias(__pthread_reserve_signal_stack, pthread_reserve_signal_stack);
91570af302Sopenharmony_ciweak_alias(__pthread_release_signal_stack, pthread_release_signal_stack);
92570af302Sopenharmony_ci#endif
93570af302Sopenharmony_ci
94570af302Sopenharmony_cistatic void dummy_0()
95570af302Sopenharmony_ci{
96570af302Sopenharmony_ci}
97570af302Sopenharmony_ciweak_alias(dummy_0, __acquire_ptc);
98570af302Sopenharmony_ciweak_alias(dummy_0, __release_ptc);
99570af302Sopenharmony_ciweak_alias(dummy_0, __pthread_tsd_run_dtors);
100570af302Sopenharmony_ciweak_alias(dummy_0, __do_orphaned_stdio_locks);
101570af302Sopenharmony_ciweak_alias(dummy_0, __dl_thread_cleanup);
102570af302Sopenharmony_ciweak_alias(dummy_0, __membarrier_init);
103570af302Sopenharmony_ci
104570af302Sopenharmony_ci#define TID_ERROR_0 (0)
105570af302Sopenharmony_ci#define TID_ERROR_INIT (-1)
106570af302Sopenharmony_ci#define COUNT_ERROR_INIT (-10000)
107570af302Sopenharmony_ci
108570af302Sopenharmony_cistatic int tl_lock_count;
109570af302Sopenharmony_cistatic int tl_lock_waiters;
110570af302Sopenharmony_cistatic int tl_lock_tid_fail = TID_ERROR_INIT;
111570af302Sopenharmony_cistatic int tl_lock_count_tid = TID_ERROR_INIT;
112570af302Sopenharmony_cistatic int tl_lock_count_fail = COUNT_ERROR_INIT;
113570af302Sopenharmony_cistatic int thread_list_lock_pre_unlock = TID_ERROR_INIT;
114570af302Sopenharmony_ci
115570af302Sopenharmony_ciint get_tl_lock_count(void)
116570af302Sopenharmony_ci{
117570af302Sopenharmony_ci	return tl_lock_count;
118570af302Sopenharmony_ci}
119570af302Sopenharmony_ci
120570af302Sopenharmony_ciint get_tl_lock_waiters(void)
121570af302Sopenharmony_ci{
122570af302Sopenharmony_ci	return tl_lock_waiters;
123570af302Sopenharmony_ci}
124570af302Sopenharmony_ci
125570af302Sopenharmony_ciint get_tl_lock_tid_fail(void)
126570af302Sopenharmony_ci{
127570af302Sopenharmony_ci	return tl_lock_tid_fail;
128570af302Sopenharmony_ci}
129570af302Sopenharmony_ci
130570af302Sopenharmony_ciint get_tl_lock_count_tid(void)
131570af302Sopenharmony_ci{
132570af302Sopenharmony_ci	return tl_lock_count_tid;
133570af302Sopenharmony_ci}
134570af302Sopenharmony_ci
135570af302Sopenharmony_ciint get_tl_lock_count_fail(void)
136570af302Sopenharmony_ci{
137570af302Sopenharmony_ci	return tl_lock_count_fail;
138570af302Sopenharmony_ci}
139570af302Sopenharmony_ci
140570af302Sopenharmony_ciint get_thread_list_lock_pre_unlock(void)
141570af302Sopenharmony_ci{
142570af302Sopenharmony_ci	return thread_list_lock_pre_unlock;
143570af302Sopenharmony_ci}
144570af302Sopenharmony_ci
145570af302Sopenharmony_civoid __tl_lock(void)
146570af302Sopenharmony_ci{
147570af302Sopenharmony_ci	int tid = __pthread_self()->tid;
148570af302Sopenharmony_ci	if (tid == TID_ERROR_0 || tid == TID_ERROR_INIT) {
149570af302Sopenharmony_ci		tl_lock_tid_fail = TID_ERROR_0;
150570af302Sopenharmony_ci		tid = __syscall(SYS_gettid);
151570af302Sopenharmony_ci	}
152570af302Sopenharmony_ci	int val = __thread_list_lock;
153570af302Sopenharmony_ci	if (val == tid) {
154570af302Sopenharmony_ci		tl_lock_count++;
155570af302Sopenharmony_ci		tl_lock_count_tid = val;
156570af302Sopenharmony_ci		return;
157570af302Sopenharmony_ci	}
158570af302Sopenharmony_ci	while ((val = a_cas(&__thread_list_lock, 0, tid)))
159570af302Sopenharmony_ci		__wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
160570af302Sopenharmony_ci}
161570af302Sopenharmony_ci
162570af302Sopenharmony_civoid __tl_unlock(void)
163570af302Sopenharmony_ci{
164570af302Sopenharmony_ci	if (tl_lock_count) {
165570af302Sopenharmony_ci		tl_lock_count--;
166570af302Sopenharmony_ci		return;
167570af302Sopenharmony_ci	}
168570af302Sopenharmony_ci	thread_list_lock_pre_unlock = __thread_list_lock;
169570af302Sopenharmony_ci	a_store(&__thread_list_lock, 0);
170570af302Sopenharmony_ci	if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
171570af302Sopenharmony_ci}
172570af302Sopenharmony_ci
173570af302Sopenharmony_civoid __tl_sync(pthread_t td)
174570af302Sopenharmony_ci{
175570af302Sopenharmony_ci	a_barrier();
176570af302Sopenharmony_ci	int val = __thread_list_lock;
177570af302Sopenharmony_ci	if (!val) return;
178570af302Sopenharmony_ci	__wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
179570af302Sopenharmony_ci	if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
180570af302Sopenharmony_ci}
181570af302Sopenharmony_ci
182570af302Sopenharmony_ci#ifdef CXA_THREAD_USE_TLS
183570af302Sopenharmony_ciextern void __cxa_thread_finalize();
184570af302Sopenharmony_ci#endif
185570af302Sopenharmony_ci
186570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
187570af302Sopenharmony_ciweak void __hwasan_thread_enter();
188570af302Sopenharmony_ciweak void __hwasan_thread_exit();
189570af302Sopenharmony_ci
190570af302Sopenharmony_ci__attribute__((no_sanitize("hwaddress")))
191570af302Sopenharmony_ci#endif
192570af302Sopenharmony_ci_Noreturn void __pthread_exit(void *result)
193570af302Sopenharmony_ci{
194570af302Sopenharmony_ci#ifdef CXA_THREAD_USE_TLS
195570af302Sopenharmony_ci	// Call thread_local dtors.
196570af302Sopenharmony_ci	__cxa_thread_finalize();
197570af302Sopenharmony_ci#endif
198570af302Sopenharmony_ci	pthread_t self = __pthread_self();
199570af302Sopenharmony_ci	sigset_t set;
200570af302Sopenharmony_ci
201570af302Sopenharmony_ci#ifdef FEATURE_PTHREAD_CANCEL
202570af302Sopenharmony_ci	self->canceldisable = 1;
203570af302Sopenharmony_ci	self->cancelasync = 0;
204570af302Sopenharmony_ci#endif
205570af302Sopenharmony_ci	self->result = result;
206570af302Sopenharmony_ci
207570af302Sopenharmony_ci	while (self->cancelbuf) {
208570af302Sopenharmony_ci		void (*f)(void *) = self->cancelbuf->__f;
209570af302Sopenharmony_ci		void *x = self->cancelbuf->__x;
210570af302Sopenharmony_ci		self->cancelbuf = self->cancelbuf->__next;
211570af302Sopenharmony_ci		f(x);
212570af302Sopenharmony_ci	}
213570af302Sopenharmony_ci
214570af302Sopenharmony_ci	__pthread_tsd_run_dtors();
215570af302Sopenharmony_ci
216570af302Sopenharmony_ci	__block_app_sigs(&set);
217570af302Sopenharmony_ci
218570af302Sopenharmony_ci	/* This atomic potentially competes with a concurrent pthread_detach
219570af302Sopenharmony_ci	 * call; the loser is responsible for freeing thread resources. */
220570af302Sopenharmony_ci	int state = a_cas(&self->detach_state, DT_JOINABLE, DT_EXITING);
221570af302Sopenharmony_ci
222570af302Sopenharmony_ci	if (state==DT_DETACHED && self->map_base) {
223570af302Sopenharmony_ci		/* Since __unmapself bypasses the normal munmap code path,
224570af302Sopenharmony_ci		 * explicitly wait for vmlock holders first. This must be
225570af302Sopenharmony_ci		 * done before any locks are taken, to avoid lock ordering
226570af302Sopenharmony_ci		 * issues that could lead to deadlock. */
227570af302Sopenharmony_ci		__vm_wait();
228570af302Sopenharmony_ci	}
229570af302Sopenharmony_ci
230570af302Sopenharmony_ci	/* Access to target the exiting thread with syscalls that use
231570af302Sopenharmony_ci	 * its kernel tid is controlled by killlock. For detached threads,
232570af302Sopenharmony_ci	 * any use past this point would have undefined behavior, but for
233570af302Sopenharmony_ci	 * joinable threads it's a valid usage that must be handled.
234570af302Sopenharmony_ci	 * Signals must be blocked since pthread_kill must be AS-safe. */
235570af302Sopenharmony_ci	LOCK(self->killlock);
236570af302Sopenharmony_ci
237570af302Sopenharmony_ci	/* The thread list lock must be AS-safe, and thus depends on
238570af302Sopenharmony_ci	 * application signals being blocked above. */
239570af302Sopenharmony_ci	__tl_lock();
240570af302Sopenharmony_ci
241570af302Sopenharmony_ci#ifdef RESERVE_SIGNAL_STACK
242570af302Sopenharmony_ci	__pthread_release_signal_stack();
243570af302Sopenharmony_ci#endif
244570af302Sopenharmony_ci	/* If this is the only thread in the list, don't proceed with
245570af302Sopenharmony_ci	 * termination of the thread, but restore the previous lock and
246570af302Sopenharmony_ci	 * signal state to prepare for exit to call atexit handlers. */
247570af302Sopenharmony_ci	if (self->next == self) {
248570af302Sopenharmony_ci		__tl_unlock();
249570af302Sopenharmony_ci		UNLOCK(self->killlock);
250570af302Sopenharmony_ci		self->detach_state = state;
251570af302Sopenharmony_ci		__restore_sigs(&set);
252570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
253570af302Sopenharmony_ci		__hwasan_thread_exit();
254570af302Sopenharmony_ci#endif
255570af302Sopenharmony_ci		exit(0);
256570af302Sopenharmony_ci	}
257570af302Sopenharmony_ci
258570af302Sopenharmony_ci	/* At this point we are committed to thread termination. */
259570af302Sopenharmony_ci
260570af302Sopenharmony_ci	/* After the kernel thread exits, its tid may be reused. Clear it
261570af302Sopenharmony_ci	 * to prevent inadvertent use and inform functions that would use
262570af302Sopenharmony_ci	 * it that it's no longer available. At this point the killlock
263570af302Sopenharmony_ci	 * may be released, since functions that use it will consistently
264570af302Sopenharmony_ci	 * see the thread as having exited. Release it now so that no
265570af302Sopenharmony_ci	 * remaining locks (except thread list) are held if we end up
266570af302Sopenharmony_ci	 * resetting need_locks below. */
267570af302Sopenharmony_ci	self->tid = 0;
268570af302Sopenharmony_ci	UNLOCK(self->killlock);
269570af302Sopenharmony_ci
270570af302Sopenharmony_ci	/* Process robust list in userspace to handle non-pshared mutexes
271570af302Sopenharmony_ci	 * and the detached thread case where the robust list head will
272570af302Sopenharmony_ci	 * be invalid when the kernel would process it. */
273570af302Sopenharmony_ci	__vm_lock();
274570af302Sopenharmony_ci	volatile void *volatile *rp;
275570af302Sopenharmony_ci	while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {
276570af302Sopenharmony_ci		pthread_mutex_t *m = (void *)((char *)rp
277570af302Sopenharmony_ci			- offsetof(pthread_mutex_t, _m_next));
278570af302Sopenharmony_ci		int waiters = m->_m_waiters;
279570af302Sopenharmony_ci		int priv = (m->_m_type & 128) ^ 128;
280570af302Sopenharmony_ci		self->robust_list.pending = rp;
281570af302Sopenharmony_ci		self->robust_list.head = *rp;
282570af302Sopenharmony_ci		int cont = a_swap(&m->_m_lock, 0x40000000);
283570af302Sopenharmony_ci		self->robust_list.pending = 0;
284570af302Sopenharmony_ci		if (cont < 0 || waiters)
285570af302Sopenharmony_ci			__wake(&m->_m_lock, 1, priv);
286570af302Sopenharmony_ci	}
287570af302Sopenharmony_ci	__vm_unlock();
288570af302Sopenharmony_ci
289570af302Sopenharmony_ci	__do_orphaned_stdio_locks();
290570af302Sopenharmony_ci	__dl_thread_cleanup();
291570af302Sopenharmony_ci
292570af302Sopenharmony_ci	/* Last, unlink thread from the list. This change will not be visible
293570af302Sopenharmony_ci	 * until the lock is released, which only happens after SYS_exit
294570af302Sopenharmony_ci	 * has been called, via the exit futex address pointing at the lock.
295570af302Sopenharmony_ci	 * This needs to happen after any possible calls to LOCK() that might
296570af302Sopenharmony_ci	 * skip locking if process appears single-threaded. */
297570af302Sopenharmony_ci	if (!--libc.threads_minus_1) libc.need_locks = -1;
298570af302Sopenharmony_ci	self->next->prev = self->prev;
299570af302Sopenharmony_ci	self->prev->next = self->next;
300570af302Sopenharmony_ci	self->prev = self->next = self;
301570af302Sopenharmony_ci
302570af302Sopenharmony_ci	if (state==DT_DETACHED && self->map_base) {
303570af302Sopenharmony_ci		/* Detached threads must block even implementation-internal
304570af302Sopenharmony_ci		 * signals, since they will not have a stack in their last
305570af302Sopenharmony_ci		 * moments of existence. */
306570af302Sopenharmony_ci		__block_all_sigs(&set);
307570af302Sopenharmony_ci
308570af302Sopenharmony_ci		/* Robust list will no longer be valid, and was already
309570af302Sopenharmony_ci		 * processed above, so unregister it with the kernel. */
310570af302Sopenharmony_ci		if (self->robust_list.off)
311570af302Sopenharmony_ci			__syscall(SYS_set_robust_list, 0, 3*sizeof(long));
312570af302Sopenharmony_ci
313570af302Sopenharmony_ci		/* The following call unmaps the thread's stack mapping
314570af302Sopenharmony_ci		 * and then exits without touching the stack. */
315570af302Sopenharmony_ci		__unmapself(self->map_base, self->map_size);
316570af302Sopenharmony_ci	}
317570af302Sopenharmony_ci
318570af302Sopenharmony_ci	/* Wake any joiner. */
319570af302Sopenharmony_ci	a_store(&self->detach_state, DT_EXITED);
320570af302Sopenharmony_ci	__wake(&self->detach_state, 1, 1);
321570af302Sopenharmony_ci
322570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
323570af302Sopenharmony_ci	__hwasan_thread_exit();
324570af302Sopenharmony_ci#endif
325570af302Sopenharmony_ci
326570af302Sopenharmony_ci	// If a thread call __tl_lock and call __pthread_exit without
327570af302Sopenharmony_ci	// call __tl_unlock, the value of tl_lock_count will appear
328570af302Sopenharmony_ci	// non-zero value, here set it to zero.
329570af302Sopenharmony_ci	if(tl_lock_count != 0) {
330570af302Sopenharmony_ci		tl_lock_count_fail = tl_lock_count;
331570af302Sopenharmony_ci		tl_lock_count = 0;
332570af302Sopenharmony_ci	}
333570af302Sopenharmony_ci
334570af302Sopenharmony_ci	for (;;) __syscall(SYS_exit, 0);
335570af302Sopenharmony_ci}
336570af302Sopenharmony_ci
337570af302Sopenharmony_civoid __do_cleanup_push(struct __ptcb *cb)
338570af302Sopenharmony_ci{
339570af302Sopenharmony_ci	struct pthread *self = __pthread_self();
340570af302Sopenharmony_ci	cb->__next = self->cancelbuf;
341570af302Sopenharmony_ci	self->cancelbuf = cb;
342570af302Sopenharmony_ci}
343570af302Sopenharmony_ci
344570af302Sopenharmony_civoid __do_cleanup_pop(struct __ptcb *cb)
345570af302Sopenharmony_ci{
346570af302Sopenharmony_ci	__pthread_self()->cancelbuf = cb->__next;
347570af302Sopenharmony_ci}
348570af302Sopenharmony_ci
349570af302Sopenharmony_cistruct start_args {
350570af302Sopenharmony_ci	void *(*start_func)(void *);
351570af302Sopenharmony_ci	void *start_arg;
352570af302Sopenharmony_ci	volatile int control;
353570af302Sopenharmony_ci	unsigned long sig_mask[_NSIG/8/sizeof(long)];
354570af302Sopenharmony_ci};
355570af302Sopenharmony_ci
356570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
357570af302Sopenharmony_ci__attribute__((no_sanitize("hwaddress")))
358570af302Sopenharmony_ci#endif
359570af302Sopenharmony_cistatic int start(void *p)
360570af302Sopenharmony_ci{
361570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
362570af302Sopenharmony_ci	__hwasan_thread_enter();
363570af302Sopenharmony_ci#endif
364570af302Sopenharmony_ci	struct start_args *args = p;
365570af302Sopenharmony_ci	int state = args->control;
366570af302Sopenharmony_ci	if (state) {
367570af302Sopenharmony_ci		if (a_cas(&args->control, 1, 2) == 1)
368570af302Sopenharmony_ci			__wait(&args->control, 0, 2, 1);
369570af302Sopenharmony_ci		if (args->control) {
370570af302Sopenharmony_ci			__syscall(SYS_set_tid_address, &args->control);
371570af302Sopenharmony_ci			for (;;) __syscall(SYS_exit, 0);
372570af302Sopenharmony_ci		}
373570af302Sopenharmony_ci	}
374570af302Sopenharmony_ci	__syscall(SYS_rt_sigprocmask, SIG_SETMASK, &args->sig_mask, 0, _NSIG/8);
375570af302Sopenharmony_ci#ifdef RESERVE_SIGNAL_STACK
376570af302Sopenharmony_ci	__pthread_reserve_signal_stack();
377570af302Sopenharmony_ci#endif
378570af302Sopenharmony_ci	__pthread_exit(args->start_func(args->start_arg));
379570af302Sopenharmony_ci	return 0;
380570af302Sopenharmony_ci}
381570af302Sopenharmony_ci
382570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
383570af302Sopenharmony_ci__attribute__((no_sanitize("hwaddress")))
384570af302Sopenharmony_ci#endif
385570af302Sopenharmony_cistatic int start_c11(void *p)
386570af302Sopenharmony_ci{
387570af302Sopenharmony_ci#ifdef RESERVE_SIGNAL_STACK
388570af302Sopenharmony_ci	__pthread_reserve_signal_stack();
389570af302Sopenharmony_ci#endif
390570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
391570af302Sopenharmony_ci	__hwasan_thread_enter();
392570af302Sopenharmony_ci#endif
393570af302Sopenharmony_ci	struct start_args *args = p;
394570af302Sopenharmony_ci	int (*start)(void*) = (int(*)(void*)) args->start_func;
395570af302Sopenharmony_ci	__pthread_exit((void *)(uintptr_t)start(args->start_arg));
396570af302Sopenharmony_ci	return 0;
397570af302Sopenharmony_ci}
398570af302Sopenharmony_ci
399570af302Sopenharmony_ci#define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
400570af302Sopenharmony_ci
401570af302Sopenharmony_ci/* pthread_key_create.c overrides this */
402570af302Sopenharmony_cistatic volatile size_t dummy = 0;
403570af302Sopenharmony_ciweak_alias(dummy, __pthread_tsd_size);
404570af302Sopenharmony_cistatic void *dummy_tsd[1] = { 0 };
405570af302Sopenharmony_ciweak_alias(dummy_tsd, __pthread_tsd_main);
406570af302Sopenharmony_ci
407570af302Sopenharmony_cistatic FILE *volatile dummy_file = 0;
408570af302Sopenharmony_ciweak_alias(dummy_file, __stdin_used);
409570af302Sopenharmony_ciweak_alias(dummy_file, __stdout_used);
410570af302Sopenharmony_ciweak_alias(dummy_file, __stderr_used);
411570af302Sopenharmony_ci
412570af302Sopenharmony_cistatic void init_file_lock(FILE *f)
413570af302Sopenharmony_ci{
414570af302Sopenharmony_ci	if (f && f->lock<0) f->lock = 0;
415570af302Sopenharmony_ci}
416570af302Sopenharmony_ci
417570af302Sopenharmony_ci#ifdef ENABLE_HWASAN
418570af302Sopenharmony_ci__attribute__((no_sanitize("hwaddress")))
419570af302Sopenharmony_ci#endif
420570af302Sopenharmony_ciint __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)
421570af302Sopenharmony_ci{
422570af302Sopenharmony_ci	int ret, c11 = (attrp == __ATTRP_C11_THREAD);
423570af302Sopenharmony_ci	size_t size, guard, size_len;
424570af302Sopenharmony_ci	struct pthread *self, *new;
425570af302Sopenharmony_ci	unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit, *start_addr;
426570af302Sopenharmony_ci	unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
427570af302Sopenharmony_ci		| CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
428570af302Sopenharmony_ci		| CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
429570af302Sopenharmony_ci	pthread_attr_t attr = { 0 };
430570af302Sopenharmony_ci	sigset_t set;
431570af302Sopenharmony_ci
432570af302Sopenharmony_ci	if (!libc.can_do_threads) {
433570af302Sopenharmony_ci		MUSL_LOGE("pthread_create: can't do threads, err: %{public}s", strerror(errno));
434570af302Sopenharmony_ci		return ENOSYS;
435570af302Sopenharmony_ci	}
436570af302Sopenharmony_ci	self = __pthread_self();
437570af302Sopenharmony_ci	if (!libc.threaded) {
438570af302Sopenharmony_ci		for (FILE *f = *__ofl_lock(); f; f = f->next)
439570af302Sopenharmony_ci			init_file_lock(f);
440570af302Sopenharmony_ci		__ofl_unlock();
441570af302Sopenharmony_ci		init_file_lock(__stdin_used);
442570af302Sopenharmony_ci		init_file_lock(__stdout_used);
443570af302Sopenharmony_ci		init_file_lock(__stderr_used);
444570af302Sopenharmony_ci		__syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);
445570af302Sopenharmony_ci		self->tsd = (void **)__pthread_tsd_main;
446570af302Sopenharmony_ci		__membarrier_init();
447570af302Sopenharmony_ci		libc.threaded = 1;
448570af302Sopenharmony_ci	}
449570af302Sopenharmony_ci	if (attrp && !c11) attr = *attrp;
450570af302Sopenharmony_ci
451570af302Sopenharmony_ci	__acquire_ptc();
452570af302Sopenharmony_ci	if (!attrp || c11) {
453570af302Sopenharmony_ci		attr._a_stacksize = __default_stacksize;
454570af302Sopenharmony_ci		attr._a_guardsize = __default_guardsize;
455570af302Sopenharmony_ci	}
456570af302Sopenharmony_ci
457570af302Sopenharmony_ci	if (attr._a_stackaddr) {
458570af302Sopenharmony_ci		size_t need = libc.tls_size + __pthread_tsd_size;
459570af302Sopenharmony_ci		size = attr._a_stacksize;
460570af302Sopenharmony_ci		stack = (void *)(attr._a_stackaddr & -16);
461570af302Sopenharmony_ci		stack_limit = (void *)(attr._a_stackaddr - size);
462570af302Sopenharmony_ci		/* Use application-provided stack for TLS only when
463570af302Sopenharmony_ci		 * it does not take more than ~12% or 2k of the
464570af302Sopenharmony_ci		 * application's stack space. */
465570af302Sopenharmony_ci		if (need < size / 8 && need < 2048) {
466570af302Sopenharmony_ci			tsd = stack - __pthread_tsd_size;
467570af302Sopenharmony_ci			stack = tsd - libc.tls_size;
468570af302Sopenharmony_ci			memset(stack, 0, need);
469570af302Sopenharmony_ci		} else {
470570af302Sopenharmony_ci			size = ROUND(need);
471570af302Sopenharmony_ci		}
472570af302Sopenharmony_ci		guard = 0;
473570af302Sopenharmony_ci	} else {
474570af302Sopenharmony_ci		guard = ROUND(attr._a_guardsize);
475570af302Sopenharmony_ci		size = guard + ROUND(attr._a_stacksize
476570af302Sopenharmony_ci			+ libc.tls_size +  __pthread_tsd_size);
477570af302Sopenharmony_ci	}
478570af302Sopenharmony_ci
479570af302Sopenharmony_ci	if (!tsd) {
480570af302Sopenharmony_ci		if (guard) {
481570af302Sopenharmony_ci			map = __mmap(0, size, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
482570af302Sopenharmony_ci			if (map == MAP_FAILED) {
483570af302Sopenharmony_ci				MUSL_LOGE("pthread_create: mmap PROT_NONE failed, err:%{public}s", strerror(errno));
484570af302Sopenharmony_ci				goto fail;
485570af302Sopenharmony_ci			}
486570af302Sopenharmony_ci			if (__mprotect(map+guard, size-guard, PROT_READ|PROT_WRITE)
487570af302Sopenharmony_ci			    && errno != ENOSYS) {
488570af302Sopenharmony_ci				MUSL_LOGE("pthread_create: mprotect failed, err:%{public}s", strerror(errno));
489570af302Sopenharmony_ci				__munmap(map, size);
490570af302Sopenharmony_ci				goto fail;
491570af302Sopenharmony_ci			}
492570af302Sopenharmony_ci		} else {
493570af302Sopenharmony_ci			map = __mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
494570af302Sopenharmony_ci			if (map == MAP_FAILED) {
495570af302Sopenharmony_ci				MUSL_LOGE("pthread_create: mmap PROT_READ|PROT_WRITE failed, err:%{public}s", strerror(errno));
496570af302Sopenharmony_ci				goto fail;
497570af302Sopenharmony_ci			}
498570af302Sopenharmony_ci		}
499570af302Sopenharmony_ci		tsd = map + size - __pthread_tsd_size;
500570af302Sopenharmony_ci		if (!stack) {
501570af302Sopenharmony_ci			stack = tsd - libc.tls_size;
502570af302Sopenharmony_ci			stack_limit = map + guard;
503570af302Sopenharmony_ci		}
504570af302Sopenharmony_ci	}
505570af302Sopenharmony_ci
506570af302Sopenharmony_ci	new = __copy_tls(tsd - libc.tls_size);
507570af302Sopenharmony_ci	new->map_base = map;
508570af302Sopenharmony_ci	new->map_size = size;
509570af302Sopenharmony_ci	new->stack = stack;
510570af302Sopenharmony_ci	new->stack_size = stack - stack_limit;
511570af302Sopenharmony_ci	new->guard_size = guard;
512570af302Sopenharmony_ci	new->self = new;
513570af302Sopenharmony_ci	new->pid = getpid();
514570af302Sopenharmony_ci	new->proc_tid = -1;
515570af302Sopenharmony_ci	new->tsd = (void *)tsd;
516570af302Sopenharmony_ci	new->locale = &libc.global_locale;
517570af302Sopenharmony_ci	if (attr._a_detach) {
518570af302Sopenharmony_ci		new->detach_state = DT_DETACHED;
519570af302Sopenharmony_ci	} else {
520570af302Sopenharmony_ci		new->detach_state = DT_JOINABLE;
521570af302Sopenharmony_ci	}
522570af302Sopenharmony_ci	new->robust_list.head = &new->robust_list.head;
523570af302Sopenharmony_ci	new->canary = self->canary;
524570af302Sopenharmony_ci	new->sysinfo = self->sysinfo;
525570af302Sopenharmony_ci
526570af302Sopenharmony_ci	/* Setup argument structure for the new thread on its stack.
527570af302Sopenharmony_ci	 * It's safe to access from the caller only until the thread
528570af302Sopenharmony_ci	 * list is unlocked. */
529570af302Sopenharmony_ci	stack -= (uintptr_t)stack % sizeof(uintptr_t);
530570af302Sopenharmony_ci	stack -= sizeof(struct start_args);
531570af302Sopenharmony_ci	struct start_args *args = (void *)stack;
532570af302Sopenharmony_ci	args->start_func = entry;
533570af302Sopenharmony_ci	args->start_arg = arg;
534570af302Sopenharmony_ci	args->control = attr._a_sched ? 1 : 0;
535570af302Sopenharmony_ci
536570af302Sopenharmony_ci	/* Application signals (but not the synccall signal) must be
537570af302Sopenharmony_ci	 * blocked before the thread list lock can be taken, to ensure
538570af302Sopenharmony_ci	 * that the lock is AS-safe. */
539570af302Sopenharmony_ci	__block_app_sigs(&set);
540570af302Sopenharmony_ci
541570af302Sopenharmony_ci	/* Ensure SIGCANCEL is unblocked in new thread. This requires
542570af302Sopenharmony_ci	 * working with a copy of the set so we can restore the
543570af302Sopenharmony_ci	 * original mask in the calling thread. */
544570af302Sopenharmony_ci	memcpy(&args->sig_mask, &set, sizeof args->sig_mask);
545570af302Sopenharmony_ci	args->sig_mask[(SIGCANCEL-1)/8/sizeof(long)] &=
546570af302Sopenharmony_ci		~(1UL<<((SIGCANCEL-1)%(8*sizeof(long))));
547570af302Sopenharmony_ci
548570af302Sopenharmony_ci	__tl_lock();
549570af302Sopenharmony_ci	if (!libc.threads_minus_1++) libc.need_locks = 1;
550570af302Sopenharmony_ci	ret = __clone((c11 ? start_c11 : start), stack, flags, args, &new->tid, TP_ADJ(new), &__thread_list_lock);
551570af302Sopenharmony_ci
552570af302Sopenharmony_ci	/* All clone failures translate to EAGAIN. If explicit scheduling
553570af302Sopenharmony_ci	 * was requested, attempt it before unlocking the thread list so
554570af302Sopenharmony_ci	 * that the failed thread is never exposed and so that we can
555570af302Sopenharmony_ci	 * clean up all transient resource usage before returning. */
556570af302Sopenharmony_ci	if (ret < 0) {
557570af302Sopenharmony_ci		ret = -EAGAIN;
558570af302Sopenharmony_ci	} else if (attr._a_sched) {
559570af302Sopenharmony_ci		ret = __syscall(SYS_sched_setscheduler,
560570af302Sopenharmony_ci			new->tid, attr._a_policy, &attr._a_prio);
561570af302Sopenharmony_ci		if (a_swap(&args->control, ret ? 3 : 0) == 2)
562570af302Sopenharmony_ci			__wake(&args->control, 1, 1);
563570af302Sopenharmony_ci		if (ret)
564570af302Sopenharmony_ci			__wait(&args->control, 0, 3, 0);
565570af302Sopenharmony_ci	}
566570af302Sopenharmony_ci
567570af302Sopenharmony_ci	if (ret >= 0) {
568570af302Sopenharmony_ci		stack_naming(new);
569570af302Sopenharmony_ci
570570af302Sopenharmony_ci		new->next = self->next;
571570af302Sopenharmony_ci		new->prev = self;
572570af302Sopenharmony_ci		new->next->prev = new;
573570af302Sopenharmony_ci		new->prev->next = new;
574570af302Sopenharmony_ci	} else {
575570af302Sopenharmony_ci		if (!--libc.threads_minus_1) libc.need_locks = 0;
576570af302Sopenharmony_ci	}
577570af302Sopenharmony_ci	__tl_unlock();
578570af302Sopenharmony_ci	__restore_sigs(&set);
579570af302Sopenharmony_ci	__release_ptc();
580570af302Sopenharmony_ci
581570af302Sopenharmony_ci	if (ret < 0) {
582570af302Sopenharmony_ci		if (map) __munmap(map, size);
583570af302Sopenharmony_ci		MUSL_LOGE("pthread_create: ret:%{public}d, err:%{public}s", ret, strerror(errno));
584570af302Sopenharmony_ci		return -ret;
585570af302Sopenharmony_ci	}
586570af302Sopenharmony_ci
587570af302Sopenharmony_ci	*res = new;
588570af302Sopenharmony_ci	return 0;
589570af302Sopenharmony_cifail:
590570af302Sopenharmony_ci	__release_ptc();
591570af302Sopenharmony_ci	return EAGAIN;
592570af302Sopenharmony_ci}
593570af302Sopenharmony_ci
594570af302Sopenharmony_ciweak_alias(__pthread_exit, pthread_exit);
595570af302Sopenharmony_ciweak_alias(__pthread_create, pthread_create);
596570af302Sopenharmony_ci
597570af302Sopenharmony_cistruct pthread* __pthread_list_find(pthread_t thread_id, const char* info)
598570af302Sopenharmony_ci{
599570af302Sopenharmony_ci    struct pthread *thread = (struct pthread *)thread_id;
600570af302Sopenharmony_ci    if (NULL == thread) {
601570af302Sopenharmony_ci        log_print("invalid pthread_t (0) passed to %s\n", info);
602570af302Sopenharmony_ci        return NULL;
603570af302Sopenharmony_ci    }
604570af302Sopenharmony_ci
605570af302Sopenharmony_ci    struct pthread *self = __pthread_self();
606570af302Sopenharmony_ci    if (thread == self) {
607570af302Sopenharmony_ci        return thread;
608570af302Sopenharmony_ci    }
609570af302Sopenharmony_ci    struct pthread *t = self;
610570af302Sopenharmony_ci    t = t->next ;
611570af302Sopenharmony_ci    while (t != self) {
612570af302Sopenharmony_ci        if (t == thread) return thread;
613570af302Sopenharmony_ci        t = t->next ;
614570af302Sopenharmony_ci    }
615570af302Sopenharmony_ci    log_print("invalid pthread_t %p passed to %s\n", thread, info);
616570af302Sopenharmony_ci    return NULL;
617570af302Sopenharmony_ci}
618570af302Sopenharmony_ci
619570af302Sopenharmony_cipid_t __pthread_gettid_np(pthread_t t)
620570af302Sopenharmony_ci{
621570af302Sopenharmony_ci    __tl_lock();
622570af302Sopenharmony_ci    struct pthread* thread = __pthread_list_find(t, "pthread_gettid_np");
623570af302Sopenharmony_ci    __tl_unlock();
624570af302Sopenharmony_ci    return thread ? thread->tid : -1;
625570af302Sopenharmony_ci}
626570af302Sopenharmony_ciweak_alias(__pthread_gettid_np, pthread_gettid_np);
627