1 #define _GNU_SOURCE
2 #include "pthread_impl.h"
3 #include "stdio_impl.h"
4 #include "libc.h"
5 #include "lock.h"
6 #include <sys/mman.h>
7 #include <string.h>
8 #include <stddef.h>
9 #include <stdarg.h>
10 
log_print(const char* info,...)11 void log_print(const char* info,...)
12 {
13     va_list ap;
14     va_start(ap, info);
15     vfprintf(stdout,info, ap);
16     va_end(ap);
17 }
18 
dummy_0null19 static void dummy_0()
20 {
21 }
22 weak_alias(dummy_0, __acquire_ptc);
23 weak_alias(dummy_0, __release_ptc);
24 weak_alias(dummy_0, __pthread_tsd_run_dtors);
25 weak_alias(dummy_0, __do_orphaned_stdio_locks);
26 weak_alias(dummy_0, __dl_thread_cleanup);
27 weak_alias(dummy_0, __membarrier_init);
28 
29 static int tl_lock_count;
30 static int tl_lock_waiters;
31 
__tl_lock(void)32 void __tl_lock(void)
33 {
34 	int tid = __pthread_self()->tid;
35 	int val = __thread_list_lock;
36 	if (val == tid) {
37 		tl_lock_count++;
38 		return;
39 	}
40 	while ((val = a_cas(&__thread_list_lock, 0, tid)))
41 		__wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
42 }
43 
__tl_unlock(void)44 void __tl_unlock(void)
45 {
46 	if (tl_lock_count) {
47 		tl_lock_count--;
48 		return;
49 	}
50 	a_store(&__thread_list_lock, 0);
51 	if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
52 }
53 
__tl_sync(pthread_t td)54 void __tl_sync(pthread_t td)
55 {
56 	a_barrier();
57 	int val = __thread_list_lock;
58 	if (!val) return;
59 	__wait(&__thread_list_lock, &tl_lock_waiters, val, 0);
60 	if (tl_lock_waiters) __wake(&__thread_list_lock, 1, 0);
61 }
62 
__pthread_exit(void *result)63 _Noreturn void __pthread_exit(void *result)
64 {
65 	pthread_t self = __pthread_self();
66 	sigset_t set;
67 
68 	self->canceldisable = 1;
69 	self->cancelasync = 0;
70 	self->result = result;
71 
72 	while (self->cancelbuf) {
73 		void (*f)(void *) = self->cancelbuf->__f;
74 		void *x = self->cancelbuf->__x;
75 		self->cancelbuf = self->cancelbuf->__next;
76 		f(x);
77 	}
78 
79 	__pthread_tsd_run_dtors();
80 
81 	__block_app_sigs(&set);
82 
83 	/* This atomic potentially competes with a concurrent pthread_detach
84 	 * call; the loser is responsible for freeing thread resources. */
85 	int state = a_cas(&self->detach_state, DT_JOINABLE, DT_EXITING);
86 
87 	if (state==DT_DETACHED && self->map_base) {
88 		/* Since __unmapself bypasses the normal munmap code path,
89 		 * explicitly wait for vmlock holders first. This must be
90 		 * done before any locks are taken, to avoid lock ordering
91 		 * issues that could lead to deadlock. */
92 		__vm_wait();
93 	}
94 
95 	/* Access to target the exiting thread with syscalls that use
96 	 * its kernel tid is controlled by killlock. For detached threads,
97 	 * any use past this point would have undefined behavior, but for
98 	 * joinable threads it's a valid usage that must be handled.
99 	 * Signals must be blocked since pthread_kill must be AS-safe. */
100 	LOCK(self->killlock);
101 
102 	/* The thread list lock must be AS-safe, and thus depends on
103 	 * application signals being blocked above. */
104 	__tl_lock();
105 
106 	/* If this is the only thread in the list, don't proceed with
107 	 * termination of the thread, but restore the previous lock and
108 	 * signal state to prepare for exit to call atexit handlers. */
109 	if (self->next == self) {
110 		__tl_unlock();
111 		UNLOCK(self->killlock);
112 		self->detach_state = state;
113 		__restore_sigs(&set);
114 		exit(0);
115 	}
116 
117 	/* At this point we are committed to thread termination. */
118 
119 	/* After the kernel thread exits, its tid may be reused. Clear it
120 	 * to prevent inadvertent use and inform functions that would use
121 	 * it that it's no longer available. At this point the killlock
122 	 * may be released, since functions that use it will consistently
123 	 * see the thread as having exited. Release it now so that no
124 	 * remaining locks (except thread list) are held if we end up
125 	 * resetting need_locks below. */
126 	self->tid = 0;
127 	UNLOCK(self->killlock);
128 
129 	/* Process robust list in userspace to handle non-pshared mutexes
130 	 * and the detached thread case where the robust list head will
131 	 * be invalid when the kernel would process it. */
132 	__vm_lock();
133 	volatile void *volatile *rp;
134 	while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {
135 		pthread_mutex_t *m = (void *)((char *)rp
136 			- offsetof(pthread_mutex_t, _m_next));
137 		int waiters = m->_m_waiters;
138 		int priv = (m->_m_type & 128) ^ 128;
139 		self->robust_list.pending = rp;
140 		self->robust_list.head = *rp;
141 		int cont = a_swap(&m->_m_lock, 0x40000000);
142 		self->robust_list.pending = 0;
143 		if (cont < 0 || waiters)
144 			__wake(&m->_m_lock, 1, priv);
145 	}
146 	__vm_unlock();
147 
148 	__do_orphaned_stdio_locks();
149 	__dl_thread_cleanup();
150 
151 	/* Last, unlink thread from the list. This change will not be visible
152 	 * until the lock is released, which only happens after SYS_exit
153 	 * has been called, via the exit futex address pointing at the lock.
154 	 * This needs to happen after any possible calls to LOCK() that might
155 	 * skip locking if process appears single-threaded. */
156 	if (!--libc.threads_minus_1) libc.need_locks = -1;
157 	self->next->prev = self->prev;
158 	self->prev->next = self->next;
159 	self->prev = self->next = self;
160 
161 	if (state==DT_DETACHED && self->map_base) {
162 		/* Detached threads must block even implementation-internal
163 		 * signals, since they will not have a stack in their last
164 		 * moments of existence. */
165 		__block_all_sigs(&set);
166 
167 		/* Robust list will no longer be valid, and was already
168 		 * processed above, so unregister it with the kernel. */
169 		if (self->robust_list.off)
170 			__syscall(SYS_set_robust_list, 0, 3*sizeof(long));
171 
172 		/* The following call unmaps the thread's stack mapping
173 		 * and then exits without touching the stack. */
174 		__unmapself(self->map_base, self->map_size);
175 	}
176 
177 	/* Wake any joiner. */
178 	a_store(&self->detach_state, DT_EXITED);
179 	__wake(&self->detach_state, 1, 1);
180 
181 	for (;;) __syscall(SYS_exit, 0);
182 }
183 
__do_cleanup_push(struct __ptcb *cb)184 void __do_cleanup_push(struct __ptcb *cb)
185 {
186 	struct pthread *self = __pthread_self();
187 	cb->__next = self->cancelbuf;
188 	self->cancelbuf = cb;
189 }
190 
__do_cleanup_pop(struct __ptcb *cb)191 void __do_cleanup_pop(struct __ptcb *cb)
192 {
193 	__pthread_self()->cancelbuf = cb->__next;
194 }
195 
196 struct start_args {
197 	void *(*start_func)(void *);
198 	void *start_arg;
199 	volatile int control;
200 	unsigned long sig_mask[_NSIG/8/sizeof(long)];
201 };
202 
start(void *p)203 static int start(void *p)
204 {
205 	struct start_args *args = p;
206 	int state = args->control;
207 	if (state) {
208 		if (a_cas(&args->control, 1, 2)==1)
209 			__wait(&args->control, 0, 2, 1);
210 		if (args->control) {
211 			__syscall(SYS_set_tid_address, &args->control);
212 			for (;;) __syscall(SYS_exit, 0);
213 		}
214 	}
215 	__syscall(SYS_rt_sigprocmask, SIG_SETMASK, &args->sig_mask, 0, _NSIG/8);
216 	__pthread_exit(args->start_func(args->start_arg));
217 	return 0;
218 }
219 
start_c11(void *p)220 static int start_c11(void *p)
221 {
222 	struct start_args *args = p;
223 	int (*start)(void*) = (int(*)(void*)) args->start_func;
224 	__pthread_exit((void *)(uintptr_t)start(args->start_arg));
225 	return 0;
226 }
227 
228 #define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
229 
230 /* pthread_key_create.c overrides this */
231 static volatile size_t dummy = 0;
232 weak_alias(dummy, __pthread_tsd_size);
233 static void *dummy_tsd[1] = { 0 };
234 weak_alias(dummy_tsd, __pthread_tsd_main);
235 
236 static FILE *volatile dummy_file = 0;
237 weak_alias(dummy_file, __stdin_used);
238 weak_alias(dummy_file, __stdout_used);
239 weak_alias(dummy_file, __stderr_used);
240 
init_file_lock(FILE *f)241 static void init_file_lock(FILE *f)
242 {
243 	if (f && f->lock<0) f->lock = 0;
244 }
245 
__pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)246 int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg)
247 {
248 	int ret, c11 = (attrp == __ATTRP_C11_THREAD);
249 	size_t size, guard;
250 	struct pthread *self, *new;
251 	unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;
252 	unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
253 		| CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
254 		| CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
255 	pthread_attr_t attr = { 0 };
256 	sigset_t set;
257 
258 	if (!libc.can_do_threads) return ENOSYS;
259 	self = __pthread_self();
260 	if (!libc.threaded) {
261 		for (FILE *f=*__ofl_lock(); f; f=f->next)
262 			init_file_lock(f);
263 		__ofl_unlock();
264 		init_file_lock(__stdin_used);
265 		init_file_lock(__stdout_used);
266 		init_file_lock(__stderr_used);
267 		__syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);
268 		self->tsd = (void **)__pthread_tsd_main;
269 		__membarrier_init();
270 		libc.threaded = 1;
271 	}
272 	if (attrp && !c11) attr = *attrp;
273 
274 	__acquire_ptc();
275 	if (!attrp || c11) {
276 		attr._a_stacksize = __default_stacksize;
277 		attr._a_guardsize = __default_guardsize;
278 	}
279 
280 	if (attr._a_stackaddr) {
281 		size_t need = libc.tls_size + __pthread_tsd_size;
282 		size = attr._a_stacksize;
283 		stack = (void *)(attr._a_stackaddr & -16);
284 		stack_limit = (void *)(attr._a_stackaddr - size);
285 		/* Use application-provided stack for TLS only when
286 		 * it does not take more than ~12% or 2k of the
287 		 * application's stack space. */
288 		if (need < size/8 && need < 2048) {
289 			tsd = stack - __pthread_tsd_size;
290 			stack = tsd - libc.tls_size;
291 			memset(stack, 0, need);
292 		} else {
293 			size = ROUND(need);
294 		}
295 		guard = 0;
296 	} else {
297 		guard = ROUND(attr._a_guardsize);
298 		size = guard + ROUND(attr._a_stacksize
299 			+ libc.tls_size +  __pthread_tsd_size);
300 	}
301 
302 	if (!tsd) {
303 		if (guard) {
304 			map = __mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);
305 			if (map == MAP_FAILED) goto fail;
306 			if (__mprotect(map+guard, size-guard, PROT_READ|PROT_WRITE)
307 			    && errno != ENOSYS) {
308 				__munmap(map, size);
309 				goto fail;
310 			}
311 		} else {
312 			map = __mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
313 			if (map == MAP_FAILED) goto fail;
314 		}
315 		tsd = map + size - __pthread_tsd_size;
316 		if (!stack) {
317 			stack = tsd - libc.tls_size;
318 			stack_limit = map + guard;
319 		}
320 	}
321 
322 	new = __copy_tls(tsd - libc.tls_size);
323 	new->map_base = map;
324 	new->map_size = size;
325 	new->stack = stack;
326 	new->stack_size = stack - stack_limit;
327 	new->guard_size = guard;
328 	new->self = new;
329 	new->tsd = (void *)tsd;
330 	new->locale = &libc.global_locale;
331 	if (attr._a_detach) {
332 		new->detach_state = DT_DETACHED;
333 	} else {
334 		new->detach_state = DT_JOINABLE;
335 	}
336 	new->robust_list.head = &new->robust_list.head;
337 	new->canary = self->canary;
338 	new->sysinfo = self->sysinfo;
339 
340 	/* Setup argument structure for the new thread on its stack.
341 	 * It's safe to access from the caller only until the thread
342 	 * list is unlocked. */
343 	stack -= (uintptr_t)stack % sizeof(uintptr_t);
344 	stack -= sizeof(struct start_args);
345 	struct start_args *args = (void *)stack;
346 	args->start_func = entry;
347 	args->start_arg = arg;
348 	args->control = attr._a_sched ? 1 : 0;
349 
350 	/* Application signals (but not the synccall signal) must be
351 	 * blocked before the thread list lock can be taken, to ensure
352 	 * that the lock is AS-safe. */
353 	__block_app_sigs(&set);
354 
355 	/* Ensure SIGCANCEL is unblocked in new thread. This requires
356 	 * working with a copy of the set so we can restore the
357 	 * original mask in the calling thread. */
358 	memcpy(&args->sig_mask, &set, sizeof args->sig_mask);
359 	args->sig_mask[(SIGCANCEL-1)/8/sizeof(long)] &=
360 		~(1UL<<((SIGCANCEL-1)%(8*sizeof(long))));
361 
362 	__tl_lock();
363 	if (!libc.threads_minus_1++) libc.need_locks = 1;
364 	ret = __clone((c11 ? start_c11 : start), stack, flags, args, &new->tid, TP_ADJ(new), &__thread_list_lock);
365 
366 	/* All clone failures translate to EAGAIN. If explicit scheduling
367 	 * was requested, attempt it before unlocking the thread list so
368 	 * that the failed thread is never exposed and so that we can
369 	 * clean up all transient resource usage before returning. */
370 	if (ret < 0) {
371 		ret = -EAGAIN;
372 	} else if (attr._a_sched) {
373 		ret = __syscall(SYS_sched_setscheduler,
374 			new->tid, attr._a_policy, &attr._a_prio);
375 		if (a_swap(&args->control, ret ? 3 : 0)==2)
376 			__wake(&args->control, 1, 1);
377 		if (ret)
378 			__wait(&args->control, 0, 3, 0);
379 	}
380 
381 	if (ret >= 0) {
382 		new->next = self->next;
383 		new->prev = self;
384 		new->next->prev = new;
385 		new->prev->next = new;
386 	} else {
387 		if (!--libc.threads_minus_1) libc.need_locks = 0;
388 	}
389 	__tl_unlock();
390 	__restore_sigs(&set);
391 	__release_ptc();
392 
393 	if (ret < 0) {
394 		if (map) __munmap(map, size);
395 		return -ret;
396 	}
397 
398 	*res = new;
399 	return 0;
400 fail:
401 	__release_ptc();
402 	return EAGAIN;
403 }
404 
405 weak_alias(__pthread_exit, pthread_exit);
406 weak_alias(__pthread_create, pthread_create);
407 
__pthread_list_find(pthread_t thread_id, const char* info)408 struct pthread* __pthread_list_find(pthread_t thread_id, const char* info)
409 {
410     struct pthread *thread = (struct pthread *)thread_id;
411     if (NULL == thread) {
412         log_print("invalid pthread_t (0) passed to %s\n", info);
413         return NULL;
414     }
415 
416     struct pthread *self = __pthread_self();
417     if (thread == self) {
418         return thread;
419     }
420     struct pthread *t = self;
421     t = t->next ;
422     while (t != self) {
423         if (t == thread) return thread;
424         t = t->next ;
425     }
426     log_print("invalid pthread_t %p passed to %s\n", thread, info);
427     return NULL;
428 }
429 
__pthread_gettid_np(pthread_t t)430 pid_t __pthread_gettid_np(pthread_t t)
431 {
432     __tl_lock();
433     struct pthread* thread = __pthread_list_find(t, "pthread_gettid_np");
434     __tl_unlock();
435     return thread ? thread->tid : -1;
436 }
437 weak_alias(__pthread_gettid_np, pthread_gettid_np);