• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #define _GNU_SOURCE
2 #define ANON_STACK_NAME_SIZE 50
3 #include "musl_log.h"
4 #include "pthread_impl.h"
5 #include "stdio_impl.h"
6 #include "libc.h"
7 #include "lock.h"
8 #include <sys/mman.h>
9 #include <sys/prctl.h>
10 #include <string.h>
11 #include <stddef.h>
12 #include <stdarg.h>
13 
14 pid_t getpid(void);
15 
log_print(const char * info,...)16 void log_print(const char* info, ...)
17 {
18     va_list ap;
19     va_start(ap, info);
20     vfprintf(stdout, info, ap);
21     va_end(ap);
22 }
23 
stack_naming(struct pthread * new)24 void stack_naming(struct pthread *new) {
25 	size_t size_len;
26 	unsigned char *start_addr;
27 	char name[ANON_STACK_NAME_SIZE];
28 	if (new->guard_size) {
29 		snprintf(name, ANON_STACK_NAME_SIZE, "guard:%d", new->tid);
30 		prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, new->map_base, new->guard_size, name);
31 		start_addr = new->map_base + new->guard_size;
32 		size_len = new->map_size - new->guard_size;
33 		memset(name, 0, ANON_STACK_NAME_SIZE);
34 	} else {
35 		start_addr = new->map_base;
36 		size_len = new->map_size;
37 	}
38 	snprintf(name, ANON_STACK_NAME_SIZE, "stack:%d", new->tid);
39 	prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, start_addr, size_len, name);
40 };
41 
42 #ifdef RESERVE_SIGNAL_STACK
43 #if defined (__LP64__)
44 #define RESERVE_SIGNAL_STACK_SIZE (32 * 1024)
45 #else
46 #define RESERVE_SIGNAL_STACK_SIZE (20 * 1024)
47 #endif
__pthread_reserve_signal_stack()48 void __pthread_reserve_signal_stack()
49 {
50 	void* stack = mmap(NULL, RESERVE_SIGNAL_STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
51 	if (stack != MAP_FAILED) {
52 		if (mprotect(stack, __default_guardsize, PROT_NONE) == -1) {
53 			munmap(stack, RESERVE_SIGNAL_STACK_SIZE);
54 			return;
55 		}
56 	}
57 
58 	stack_t signal_stack;
59 	signal_stack.ss_sp = (uint8_t*)stack + __default_guardsize;
60 	signal_stack.ss_size = RESERVE_SIGNAL_STACK_SIZE - __default_guardsize;
61 	signal_stack.ss_flags = 0;
62 	sigaltstack(&signal_stack, NULL);
63 
64 	pthread_t self = __pthread_self();
65 	self->signal_stack = stack;
66 	char name[ANON_STACK_NAME_SIZE];
67 	snprintf(name, ANON_STACK_NAME_SIZE, "signal_stack:%d", __pthread_self()->tid);
68 	prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, signal_stack.ss_sp, signal_stack.ss_size, name);
69 	return;
70 }
71 
72 #ifdef ENABLE_HWASAN
73 __attribute__((no_sanitize("hwaddress")))
74 #endif
__pthread_release_signal_stack()75 void __pthread_release_signal_stack()
76 {
77 	pthread_t self = __pthread_self();
78 	if (self->signal_stack == NULL) {
79 		return;
80 	}
81 
82 	stack_t signal_stack, old_stack;
83 	memset(&signal_stack, 0, sizeof(signal_stack));
84 	signal_stack.ss_flags = SS_DISABLE;
85 	sigaltstack(&signal_stack, &old_stack);
86 	munmap(self->signal_stack, __default_guardsize);
87 	if (old_stack.ss_flags != SS_DISABLE) {
88 		munmap(old_stack.ss_sp, old_stack.ss_size);
89 	}
90 	self->signal_stack = NULL;
91 }
92 
93 weak_alias(__pthread_reserve_signal_stack, pthread_reserve_signal_stack);
94 weak_alias(__pthread_release_signal_stack, pthread_release_signal_stack);
95 #endif
96 
dummy_0()97 static void dummy_0()
98 {
99 }
100 weak_alias(dummy_0, __acquire_ptc);
101 weak_alias(dummy_0, __release_ptc);
102 weak_alias(dummy_0, __pthread_tsd_run_dtors);
103 weak_alias(dummy_0, __do_orphaned_stdio_locks);
104 weak_alias(dummy_0, __dl_thread_cleanup);
105 weak_alias(dummy_0, __membarrier_init);
106 
107 #define TID_ERROR_0 (0)
108 #define TID_ERROR_INIT (-1)
109 #define COUNT_ERROR_INIT (-10000)
110 
111 static int tl_lock_count;
112 static int tl_lock_waiters;
113 static int tl_lock_tid_fail = TID_ERROR_INIT;
114 static int tl_lock_count_tid = TID_ERROR_INIT;
115 static int tl_lock_count_tid_sub = TID_ERROR_INIT;
116 static int tl_lock_count_fail = COUNT_ERROR_INIT;
117 static int thread_list_lock_after_lock = TID_ERROR_INIT;
118 static int thread_list_lock_pre_unlock = TID_ERROR_INIT;
119 static int thread_list_lock_pthread_exit = TID_ERROR_INIT;
120 static int thread_list_lock_tid_overlimit = TID_ERROR_INIT;
121 static int register_count = 0;
122 static pid_t g_dlcloseLockStatus = TID_ERROR_0, g_dlcloseLockLastExitTid = TID_ERROR_0;
123 
124 struct call_tl_lock tl_lock_caller_count = { 0 };
125 
get_tl_lock_count(void)126 int get_tl_lock_count(void)
127 {
128 	return tl_lock_count;
129 }
130 
get_tl_lock_waiters(void)131 int get_tl_lock_waiters(void)
132 {
133 	return tl_lock_waiters;
134 }
135 
get_tl_lock_tid_fail(void)136 int get_tl_lock_tid_fail(void)
137 {
138 	return tl_lock_tid_fail;
139 }
140 
get_tl_lock_count_tid(void)141 int get_tl_lock_count_tid(void)
142 {
143 	return tl_lock_count_tid;
144 }
145 
get_tl_lock_count_tid_sub(void)146 int get_tl_lock_count_tid_sub(void)
147 {
148 	return tl_lock_count_tid_sub;
149 }
150 
get_tl_lock_count_fail(void)151 int get_tl_lock_count_fail(void)
152 {
153 	return tl_lock_count_fail;
154 }
155 
get_thread_list_lock_after_lock(void)156 int get_thread_list_lock_after_lock(void)
157 {
158 	return thread_list_lock_after_lock;
159 }
160 
get_thread_list_lock_pre_unlock(void)161 int get_thread_list_lock_pre_unlock(void)
162 {
163 	return thread_list_lock_pre_unlock;
164 }
165 
get_thread_list_lock_pthread_exit(void)166 int get_thread_list_lock_pthread_exit(void)
167 {
168 	return thread_list_lock_pthread_exit;
169 }
170 
get_thread_list_lock_tid_overlimit(void)171 int get_thread_list_lock_tid_overlimit(void)
172 {
173 	return thread_list_lock_tid_overlimit;
174 }
175 
get_tl_lock_caller_count(void)176 struct call_tl_lock *get_tl_lock_caller_count(void)
177 {
178 	return &tl_lock_caller_count;
179 }
180 
get_register_count(void)181 int get_register_count(void)
182 {
183 	return register_count;
184 }
185 
update_register_count(void)186 void update_register_count(void)
187 {
188 	register_count++;
189 }
190 
getDlcloseLockStatus()191 pid_t getDlcloseLockStatus()
192 {
193 	return g_dlcloseLockStatus;
194 }
195 
getDlcloseLockLastExitTid()196 pid_t getDlcloseLockLastExitTid()
197 {
198 	return g_dlcloseLockLastExitTid;
199 }
200 
setDlcloseLockStatus(pid_t value)201 void setDlcloseLockStatus(pid_t value)
202 {
203 	g_dlcloseLockStatus = value;
204 }
205 
setDlcloseLockLastExitTid(pid_t value)206 void setDlcloseLockLastExitTid(pid_t value)
207 {
208 	g_dlcloseLockLastExitTid = value;
209 }
210 
211 #ifdef ENABLE_HWASAN
212 __attribute__((no_sanitize("hwaddress")))
213 #endif
__tl_lock(void)214 void __tl_lock(void)
215 {
216 	int tid = __pthread_self()->tid;
217 	if (tid == TID_ERROR_0 || tid == TID_ERROR_INIT) {
218 		tl_lock_tid_fail = TID_ERROR_0;
219 		tid = __syscall(SYS_gettid);
220 	}
221 	if ((thread_list_lock_pthread_exit == tid) &&
222 	    (thread_list_lock_pthread_exit == __thread_list_lock)) {
223 			thread_list_lock_tid_overlimit = __thread_list_lock;
224 	}
225 	int val = __thread_list_lock;
226 	if (val == tid) {
227 		tl_lock_count++;
228 		tl_lock_count_tid = val;
229 		return;
230 	}
231 	while ((val = a_cas(&__thread_list_lock, 0, tid)))
232 		__wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
233 	thread_list_lock_after_lock = __thread_list_lock;
234 	if (get_tl_lock_caller_count()) {
235 		get_tl_lock_caller_count()->tl_lock_unlock_count++;
236 	}
237 }
238 
__tl_unlock(void)239 void __tl_unlock(void)
240 {
241 	if (tl_lock_count) {
242 		tl_lock_count--;
243 		tl_lock_count_tid_sub = __thread_list_lock;
244 		return;
245 	}
246 	thread_list_lock_pre_unlock = __thread_list_lock;
247 	if (get_tl_lock_caller_count()) {
248 		get_tl_lock_caller_count()->tl_lock_unlock_count--;
249 	}
250 	a_store(&__thread_list_lock, 0);
251 	if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
252 }
253 
__tl_sync(pthread_t td)254 void __tl_sync(pthread_t td)
255 {
256 	a_barrier();
257 	int val = __thread_list_lock;
258 	if (!val) return;
259 	__wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
260 	if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
261 }
262 
263 #ifdef CXA_THREAD_USE_TLS
264 extern void __cxa_thread_finalize();
265 #endif
266 
267 #ifdef ENABLE_HWASAN
268 weak void __hwasan_thread_enter();
269 weak void __hwasan_thread_exit();
270 
271 __attribute__((no_sanitize("hwaddress")))
272 #endif
__pthread_exit(void * result)273 _Noreturn void __pthread_exit(void *result)
274 {
275 #ifdef CXA_THREAD_USE_TLS
276 	// Call thread_local dtors.
277 	__cxa_thread_finalize();
278 #endif
279 	pthread_t self = __pthread_self();
280 	sigset_t set;
281 
282 #ifdef FEATURE_PTHREAD_CANCEL
283 	self->canceldisable = 1;
284 	self->cancelasync = 0;
285 #endif
286 	self->result = result;
287 
288 	while (self->cancelbuf) {
289 		void (*f)(void *) = self->cancelbuf->__f;
290 		void *x = self->cancelbuf->__x;
291 		self->cancelbuf = self->cancelbuf->__next;
292 		f(x);
293 	}
294 
295 	__pthread_tsd_run_dtors();
296 
297 	__block_app_sigs(&set);
298 
299 	/* This atomic potentially competes with a concurrent pthread_detach
300 	 * call; the loser is responsible for freeing thread resources. */
301 	int state = a_cas(&self->detach_state, DT_JOINABLE, DT_EXITING);
302 
303 	if (state==DT_DETACHED && self->map_base) {
304 		/* Since __unmapself bypasses the normal munmap code path,
305 		 * explicitly wait for vmlock holders first. This must be
306 		 * done before any locks are taken, to avoid lock ordering
307 		 * issues that could lead to deadlock. */
308 		__vm_wait();
309 	}
310 
311 	/* Access to target the exiting thread with syscalls that use
312 	 * its kernel tid is controlled by killlock. For detached threads,
313 	 * any use past this point would have undefined behavior, but for
314 	 * joinable threads it's a valid usage that must be handled.
315 	 * Signals must be blocked since pthread_kill must be AS-safe. */
316 	LOCK(self->killlock);
317 
318 	/* The thread list lock must be AS-safe, and thus depends on
319 	 * application signals being blocked above. */
320 	__tl_lock();
321 	if (get_tl_lock_caller_count()) {
322 		get_tl_lock_caller_count()->__pthread_exit_tl_lock++;
323 	}
324 
325 #ifdef RESERVE_SIGNAL_STACK
326 	__pthread_release_signal_stack();
327 #endif
328 	/* If this is the only thread in the list, don't proceed with
329 	 * termination of the thread, but restore the previous lock and
330 	 * signal state to prepare for exit to call atexit handlers. */
331 	if (self->next == self) {
332 		if (get_tl_lock_caller_count()) {
333 			get_tl_lock_caller_count()->__pthread_exit_tl_lock--;
334 		}
335 		__tl_unlock();
336 		UNLOCK(self->killlock);
337 		self->detach_state = state;
338 		__restore_sigs(&set);
339 #ifdef ENABLE_HWASAN
340 		__hwasan_thread_exit();
341 #endif
342 		exit(0);
343 	}
344 
345 	/* At this point we are committed to thread termination. */
346 
347 	/* After the kernel thread exits, its tid may be reused. Clear it
348 	 * to prevent inadvertent use and inform functions that would use
349 	 * it that it's no longer available. At this point the killlock
350 	 * may be released, since functions that use it will consistently
351 	 * see the thread as having exited. Release it now so that no
352 	 * remaining locks (except thread list) are held if we end up
353 	 * resetting need_locks below. */
354 	self->tid = 0;
355 	UNLOCK(self->killlock);
356 
357 	/* Process robust list in userspace to handle non-pshared mutexes
358 	 * and the detached thread case where the robust list head will
359 	 * be invalid when the kernel would process it. */
360 	__vm_lock();
361 	volatile void *volatile *rp;
362 	while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {
363 		pthread_mutex_t *m = (void *)((char *)rp
364 			- offsetof(pthread_mutex_t, _m_next));
365 		int waiters = m->_m_waiters;
366 		int priv = (m->_m_type & 128) ^ 128;
367 		self->robust_list.pending = rp;
368 		self->robust_list.head = *rp;
369 		int cont = a_swap(&m->_m_lock, 0x40000000);
370 		self->robust_list.pending = 0;
371 		if (cont < 0 || waiters)
372 			__wake(&m->_m_lock, 1, priv);
373 	}
374 	__vm_unlock();
375 
376 	__do_orphaned_stdio_locks();
377 	__dl_thread_cleanup();
378 
379 	/* Last, unlink thread from the list. This change will not be visible
380 	 * until the lock is released, which only happens after SYS_exit
381 	 * has been called, via the exit futex address pointing at the lock.
382 	 * This needs to happen after any possible calls to LOCK() that might
383 	 * skip locking if process appears single-threaded. */
384 	if (!--libc.threads_minus_1) libc.need_locks = -1;
385 	self->next->prev = self->prev;
386 	self->prev->next = self->next;
387 	self->prev = self->next = self;
388 
389 	if (state==DT_DETACHED && self->map_base) {
390 		/* Detached threads must block even implementation-internal
391 		 * signals, since they will not have a stack in their last
392 		 * moments of existence. */
393 		__block_all_sigs(&set);
394 
395 		/* Robust list will no longer be valid, and was already
396 		 * processed above, so unregister it with the kernel. */
397 		if (self->robust_list.off)
398 			__syscall(SYS_set_robust_list, 0, 3*sizeof(long));
399 
400 		/* The following call unmaps the thread's stack mapping
401 		 * and then exits without touching the stack. */
402 		if (tl_lock_count != 0) {
403 			tl_lock_count_fail = tl_lock_count;
404 			tl_lock_count = 0;
405 		}
406 		thread_list_lock_pthread_exit = __thread_list_lock;
407 		if (get_tl_lock_caller_count()) {
408 			get_tl_lock_caller_count()->__pthread_exit_tl_lock--;
409 			get_tl_lock_caller_count()->tl_lock_unlock_count--;
410 		}
411 		__unmapself(self->map_base, self->map_size);
412 	}
413 
414 	/* Wake any joiner. */
415 	a_store(&self->detach_state, DT_EXITED);
416 	__wake(&self->detach_state, 1, 1);
417 
418 #ifdef ENABLE_HWASAN
419 	__hwasan_thread_exit();
420 #endif
421 
422 	// If a thread call __tl_lock and call __pthread_exit without
423 	// call __tl_unlock, the value of tl_lock_count will appear
424 	// non-zero value, here set it to zero.
425 	if (tl_lock_count != 0) {
426 		tl_lock_count_fail = tl_lock_count;
427 		tl_lock_count = 0;
428 	}
429 	thread_list_lock_pthread_exit = __thread_list_lock;
430 	if (get_tl_lock_caller_count()) {
431 		get_tl_lock_caller_count()->__pthread_exit_tl_lock--;
432 		get_tl_lock_caller_count()->tl_lock_unlock_count--;
433 	}
434 
435 	for (;;) __syscall(SYS_exit, 0);
436 }
437 
__do_cleanup_push(struct __ptcb * cb)438 void __do_cleanup_push(struct __ptcb *cb)
439 {
440 	struct pthread *self = __pthread_self();
441 	cb->__next = self->cancelbuf;
442 	self->cancelbuf = cb;
443 }
444 
__do_cleanup_pop(struct __ptcb * cb)445 void __do_cleanup_pop(struct __ptcb *cb)
446 {
447 	__pthread_self()->cancelbuf = cb->__next;
448 }
449 
450 struct start_args {
451 	void *(*start_func)(void *);
452 	void *start_arg;
453 	volatile int control;
454 	unsigned long sig_mask[_NSIG/8/sizeof(long)];
455 };
456 
457 #ifdef ENABLE_HWASAN
458 __attribute__((no_sanitize("hwaddress")))
459 #endif
start(void * p)460 static int start(void *p)
461 {
462 #ifdef ENABLE_HWASAN
463 	__hwasan_thread_enter();
464 #endif
465 	struct start_args *args = p;
466 	int state = args->control;
467 	if (state) {
468 		if (a_cas(&args->control, 1, 2) == 1)
469 			__wait(&args->control, 0, 2, 1);
470 		if (args->control) {
471 			__syscall(SYS_set_tid_address, &args->control);
472 			for (;;) __syscall(SYS_exit, 0);
473 		}
474 	}
475 	__syscall(SYS_rt_sigprocmask, SIG_SETMASK, &args->sig_mask, 0, _NSIG/8);
476 #ifdef RESERVE_SIGNAL_STACK
477 	__pthread_reserve_signal_stack();
478 #endif
479 	__pthread_exit(args->start_func(args->start_arg));
480 	return 0;
481 }
482 
483 #ifdef ENABLE_HWASAN
484 __attribute__((no_sanitize("hwaddress")))
485 #endif
start_c11(void * p)486 static int start_c11(void *p)
487 {
488 #ifdef RESERVE_SIGNAL_STACK
489 	__pthread_reserve_signal_stack();
490 #endif
491 #ifdef ENABLE_HWASAN
492 	__hwasan_thread_enter();
493 #endif
494 	struct start_args *args = p;
495 	int (*start)(void*) = (int(*)(void*)) args->start_func;
496 	__pthread_exit((void *)(uintptr_t)start(args->start_arg));
497 	return 0;
498 }
499 
500 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
501 
502 /* pthread_key_create.c overrides this */
503 static volatile size_t dummy = 0;
504 weak_alias(dummy, __pthread_tsd_size);
505 static void *dummy_tsd[1] = { 0 };
506 weak_alias(dummy_tsd, __pthread_tsd_main);
507 
508 static FILE *volatile dummy_file = 0;
509 weak_alias(dummy_file, __stdin_used);
510 weak_alias(dummy_file, __stdout_used);
511 weak_alias(dummy_file, __stderr_used);
512 
init_file_lock(FILE * f)513 static void init_file_lock(FILE *f)
514 {
515 	if (f && f->lock<0) f->lock = 0;
516 }
517 
518 #ifdef ENABLE_HWASAN
519 __attribute__((no_sanitize("hwaddress")))
520 #endif
__pthread_create(pthread_t * restrict res,const pthread_attr_t * restrict attrp,void * (* entry)(void *),void * restrict arg)521 int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)
522 {
523 	int ret, c11 = (attrp == __ATTRP_C11_THREAD);
524 	size_t size, guard;
525 	struct pthread *self, *new;
526 	unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;
527 	unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
528 		| CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
529 		| CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
530 	pthread_attr_t attr = { 0 };
531 	sigset_t set;
532 
533 	if (!libc.can_do_threads) {
534 		MUSL_LOGW("pthread_create: can't do threads, err: %{public}s", strerror(errno));
535 		return ENOSYS;
536 	}
537 	self = __pthread_self();
538 	if (!libc.threaded) {
539 		for (FILE *f = *__ofl_lock(); f; f = f->next)
540 			init_file_lock(f);
541 		__ofl_unlock();
542 		init_file_lock(__stdin_used);
543 		init_file_lock(__stdout_used);
544 		init_file_lock(__stderr_used);
545 		__syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);
546 		self->tsd = (void **)__pthread_tsd_main;
547 		__membarrier_init();
548 		libc.threaded = 1;
549 	}
550 	if (attrp && !c11) attr = *attrp;
551 
552 	__acquire_ptc();
553 	if (!attrp || c11) {
554 		attr._a_stacksize = __default_stacksize;
555 		attr._a_guardsize = __default_guardsize;
556 	}
557 
558 	if (attr._a_stackaddr) {
559 		size_t need = libc.tls_size + __pthread_tsd_size;
560 		size = attr._a_stacksize;
561 		stack = (void *)(attr._a_stackaddr & -16);
562 		stack_limit = (void *)(attr._a_stackaddr - size);
563 		/* Use application-provided stack for TLS only when
564 		 * it does not take more than ~12% or 2k of the
565 		 * application's stack space. */
566 		if (need < size / 8 && need < 2048) {
567 			tsd = stack - __pthread_tsd_size;
568 			stack = tsd - libc.tls_size;
569 			memset(stack, 0, need);
570 		} else {
571 			size = ROUND(need);
572 		}
573 		guard = 0;
574 	} else {
575 		guard = ROUND(attr._a_guardsize);
576 		size = guard + ROUND(attr._a_stacksize
577 			+ libc.tls_size +  __pthread_tsd_size);
578 	}
579 
580 	if (!tsd) {
581 		if (guard) {
582 			map = __mmap(0, size, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
583 			if (map == MAP_FAILED) {
584 				MUSL_LOGW("pthread_create: mmap PROT_NONE failed, err:%{public}s", strerror(errno));
585 				goto fail;
586 			}
587 			if (__mprotect(map+guard, size-guard, PROT_READ|PROT_WRITE)
588 			    && errno != ENOSYS) {
589 				MUSL_LOGW("pthread_create: mprotect failed, err:%{public}s", strerror(errno));
590 				__munmap(map, size);
591 				goto fail;
592 			}
593 		} else {
594 			map = __mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
595 			if (map == MAP_FAILED) {
596 				MUSL_LOGW("pthread_create: mmap PROT_READ|PROT_WRITE failed, err:%{public}s", strerror(errno));
597 				goto fail;
598 			}
599 		}
600 		tsd = map + size - __pthread_tsd_size;
601 		if (!stack) {
602 			stack = tsd - libc.tls_size;
603 			stack_limit = map + guard;
604 		}
605 	}
606 
607 	new = __copy_tls(tsd - libc.tls_size);
608 	new->map_base = map;
609 	new->map_size = size;
610 	new->stack = stack;
611 	new->stack_size = stack - stack_limit;
612 	new->guard_size = guard;
613 	new->self = new;
614 	new->pid = getpid();
615 	new->proc_tid = -1;
616 	new->tsd = (void *)tsd;
617 	new->locale = &libc.global_locale;
618 	if (attr._a_detach) {
619 		new->detach_state = DT_DETACHED;
620 	} else {
621 		new->detach_state = DT_JOINABLE;
622 	}
623 	new->robust_list.head = &new->robust_list.head;
624 	new->canary = self->canary;
625 	new->sysinfo = self->sysinfo;
626 	/* This is for GWP_ASAN to copy the configure to child thread. */
627 	new->gwp_asan_tls = self->gwp_asan_tls;
628 
629 	/* Setup argument structure for the new thread on its stack.
630 	 * It's safe to access from the caller only until the thread
631 	 * list is unlocked. */
632 	stack -= (uintptr_t)stack % sizeof(uintptr_t);
633 	stack -= sizeof(struct start_args);
634 	struct start_args *args = (void *)stack;
635 	args->start_func = entry;
636 	args->start_arg = arg;
637 	args->control = attr._a_sched ? 1 : 0;
638 
639 	/* Application signals (but not the synccall signal) must be
640 	 * blocked before the thread list lock can be taken, to ensure
641 	 * that the lock is AS-safe. */
642 	__block_app_sigs(&set);
643 
644 	/* Ensure SIGCANCEL is unblocked in new thread. This requires
645 	 * working with a copy of the set so we can restore the
646 	 * original mask in the calling thread. */
647 	memcpy(&args->sig_mask, &set, sizeof args->sig_mask);
648 	args->sig_mask[(SIGCANCEL-1)/8/sizeof(long)] &=
649 		~(1UL<<((SIGCANCEL-1)%(8*sizeof(long))));
650 
651 	__tl_lock();
652 	if (get_tl_lock_caller_count()) {
653 		get_tl_lock_caller_count()->__pthread_create_tl_lock++;
654 	}
655 	if (!libc.threads_minus_1++) libc.need_locks = 1;
656 	ret = __clone((c11 ? start_c11 : start), stack, flags, args, &new->tid, TP_ADJ(new), &__thread_list_lock);
657 	int cloneErrno = 0;
658 	/* All clone failures translate to EAGAIN. If explicit scheduling
659 	 * was requested, attempt it before unlocking the thread list so
660 	 * that the failed thread is never exposed and so that we can
661 	 * clean up all transient resource usage before returning. */
662 	if (ret < 0) {
663 		cloneErrno = ret;
664 		ret = -EAGAIN;
665 	} else if (attr._a_sched) {
666 		ret = __syscall(SYS_sched_setscheduler,
667 			new->tid, attr._a_policy, &attr._a_prio);
668 		if (a_swap(&args->control, ret ? 3 : 0) == 2)
669 			__wake(&args->control, 1, 1);
670 		if (ret)
671 			__wait(&args->control, 0, 3, 0);
672 	}
673 
674 	if (ret >= 0) {
675 		stack_naming(new);
676 
677 		new->next = self->next;
678 		new->prev = self;
679 		new->next->prev = new;
680 		new->prev->next = new;
681 	} else {
682 		if (!--libc.threads_minus_1) libc.need_locks = 0;
683 	}
684 	if (get_tl_lock_caller_count()) {
685 		get_tl_lock_caller_count()->__pthread_create_tl_lock--;
686 	}
687 	__tl_unlock();
688 	__restore_sigs(&set);
689 	__release_ptc();
690 
691 	if (ret < 0) {
692 		if (map) __munmap(map, size);
693 		MUSL_LOGW("pthread_create: ret: %{public}d, cloneErrno: %{public}d, err: %{public}s",
694 			ret, cloneErrno, strerror(errno));
695 		return -ret;
696 	}
697 
698 	*res = new;
699 	return 0;
700 fail:
701 	__release_ptc();
702 	return EAGAIN;
703 }
704 
705 weak_alias(__pthread_exit, pthread_exit);
706 weak_alias(__pthread_create, pthread_create);
707 
__pthread_list_find(pthread_t thread_id,const char * info)708 struct pthread* __pthread_list_find(pthread_t thread_id, const char* info)
709 {
710     struct pthread *thread = (struct pthread *)thread_id;
711     if (NULL == thread) {
712         log_print("invalid pthread_t (0) passed to %s\n", info);
713         return NULL;
714     }
715 
716     struct pthread *self = __pthread_self();
717     if (thread == self) {
718         return thread;
719     }
720     struct pthread *t = self;
721     t = t->next ;
722     while (t != self) {
723         if (t == thread) return thread;
724         t = t->next ;
725     }
726     log_print("invalid pthread_t %p passed to %s\n", thread, info);
727     return NULL;
728 }
729 
__pthread_gettid_np(pthread_t t)730 pid_t __pthread_gettid_np(pthread_t t)
731 {
732 	sigset_t set;
733 	__block_app_sigs(&set);
734     __tl_lock();
735 	if (get_tl_lock_caller_count()) {
736 		get_tl_lock_caller_count()->__pthread_gettid_np_tl_lock++;
737 	}
738     struct pthread* thread = __pthread_list_find(t, "pthread_gettid_np");
739 	if (get_tl_lock_caller_count()) {
740 		get_tl_lock_caller_count()->__pthread_gettid_np_tl_lock--;
741 	}
742     __tl_unlock();
743 	__restore_sigs(&set);
744     return thread ? thread->tid : -1;
745 }
746 weak_alias(__pthread_gettid_np, pthread_gettid_np);
747