1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include <pthread.h>
30
31 #include <errno.h>
32 #include <string.h>
33 #include <sys/mman.h>
34 #include <sys/prctl.h>
35 #include <sys/random.h>
36 #include <unistd.h>
37
38 #include "pthread_internal.h"
39
40 #include <async_safe/log.h>
41
42 #include "private/bionic_constants.h"
43 #include "private/bionic_defs.h"
44 #include "private/bionic_globals.h"
45 #include "platform/bionic/macros.h"
46 #include "private/bionic_ssp.h"
47 #include "private/bionic_systrace.h"
48 #include "private/bionic_tls.h"
49 #include "private/ErrnoRestorer.h"
50
51 // x86 uses segment descriptors rather than a direct pointer to TLS.
52 #if defined(__i386__)
53 #include <asm/ldt.h>
54 void __init_user_desc(struct user_desc*, bool, void*);
55 #endif
56
57 __attribute__((no_stack_protector))
__init_tcb_stack_guard(bionic_tcb * tcb)58 void __init_tcb_stack_guard(bionic_tcb* tcb) {
59 // GCC looks in the TLS for the stack guard on x86, so copy it there from our global.
60 tcb->tls_slot(TLS_SLOT_STACK_GUARD) = reinterpret_cast<void*>(__stack_chk_guard);
61 }
62
__init_bionic_tls_ptrs(bionic_tcb * tcb,bionic_tls * tls)63 void __init_bionic_tls_ptrs(bionic_tcb* tcb, bionic_tls* tls) {
64 tcb->thread()->bionic_tls = tls;
65 tcb->tls_slot(TLS_SLOT_BIONIC_TLS) = tls;
66 }
67
68 // Allocate a temporary bionic_tls that the dynamic linker's main thread can
69 // use while it's loading the initial set of ELF modules.
__allocate_temp_bionic_tls()70 bionic_tls* __allocate_temp_bionic_tls() {
71 size_t allocation_size = __BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE);
72 void* allocation = mmap(nullptr, allocation_size,
73 PROT_READ | PROT_WRITE,
74 MAP_PRIVATE | MAP_ANONYMOUS,
75 -1, 0);
76 if (allocation == MAP_FAILED) {
77 // Avoid strerror because it might need bionic_tls.
78 async_safe_fatal("failed to allocate bionic_tls: error %d", errno);
79 }
80 return static_cast<bionic_tls*>(allocation);
81 }
82
__free_temp_bionic_tls(bionic_tls * tls)83 void __free_temp_bionic_tls(bionic_tls* tls) {
84 munmap(tls, __BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE));
85 }
86
__init_alternate_signal_stack(pthread_internal_t * thread)87 static void __init_alternate_signal_stack(pthread_internal_t* thread) {
88 // Create and set an alternate signal stack.
89 void* stack_base = mmap(nullptr, SIGNAL_STACK_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
90 if (stack_base != MAP_FAILED) {
91 // Create a guard to catch stack overflows in signal handlers.
92 if (mprotect(stack_base, PTHREAD_GUARD_SIZE, PROT_NONE) == -1) {
93 munmap(stack_base, SIGNAL_STACK_SIZE);
94 return;
95 }
96 stack_t ss;
97 ss.ss_sp = reinterpret_cast<uint8_t*>(stack_base) + PTHREAD_GUARD_SIZE;
98 ss.ss_size = SIGNAL_STACK_SIZE - PTHREAD_GUARD_SIZE;
99 ss.ss_flags = 0;
100 sigaltstack(&ss, nullptr);
101 thread->alternate_signal_stack = stack_base;
102
103 // We can only use const static allocated string for mapped region name, as Android kernel
104 // uses the string pointer directly when dumping /proc/pid/maps.
105 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ss.ss_sp, ss.ss_size, "thread signal stack");
106 }
107 }
108
__init_shadow_call_stack(pthread_internal_t * thread __unused)109 static void __init_shadow_call_stack(pthread_internal_t* thread __unused) {
110 #ifdef __aarch64__
111 // Allocate the stack and the guard region.
112 char* scs_guard_region = reinterpret_cast<char*>(
113 mmap(nullptr, SCS_GUARD_REGION_SIZE, 0, MAP_PRIVATE | MAP_ANON, -1, 0));
114 thread->shadow_call_stack_guard_region = scs_guard_region;
115
116 // The address is aligned to SCS_SIZE so that we only need to store the lower log2(SCS_SIZE) bits
117 // in jmp_buf.
118 char* scs_aligned_guard_region =
119 reinterpret_cast<char*>(align_up(reinterpret_cast<uintptr_t>(scs_guard_region), SCS_SIZE));
120
121 // We need to ensure that [scs_offset,scs_offset+SCS_SIZE) is in the guard region and that there
122 // is at least one unmapped page after the shadow call stack (to catch stack overflows). We can't
123 // use arc4random_uniform in init because /dev/urandom might not have been created yet.
124 size_t scs_offset =
125 (getpid() == 1) ? 0 : (arc4random_uniform(SCS_GUARD_REGION_SIZE / SCS_SIZE - 1) * SCS_SIZE);
126
127 // Make the stack readable and writable and store its address in register x18. This is
128 // deliberately the only place where the address is stored.
129 char *scs = scs_aligned_guard_region + scs_offset;
130 mprotect(scs, SCS_SIZE, PROT_READ | PROT_WRITE);
131 __asm__ __volatile__("mov x18, %0" ::"r"(scs));
132 #endif
133 }
134
__init_additional_stacks(pthread_internal_t * thread)135 void __init_additional_stacks(pthread_internal_t* thread) {
136 __init_alternate_signal_stack(thread);
137 __init_shadow_call_stack(thread);
138 }
139
__init_thread(pthread_internal_t * thread)140 int __init_thread(pthread_internal_t* thread) {
141 thread->cleanup_stack = nullptr;
142
143 if (__predict_true((thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) == 0)) {
144 atomic_init(&thread->join_state, THREAD_NOT_JOINED);
145 } else {
146 atomic_init(&thread->join_state, THREAD_DETACHED);
147 }
148
149 // Set the scheduling policy/priority of the thread if necessary.
150 bool need_set = true;
151 int policy;
152 sched_param param;
153 if ((thread->attr.flags & PTHREAD_ATTR_FLAG_INHERIT) != 0) {
154 // Unless the parent has SCHED_RESET_ON_FORK set, we've already inherited from the parent.
155 policy = sched_getscheduler(0);
156 need_set = ((policy & SCHED_RESET_ON_FORK) != 0);
157 if (need_set) {
158 if (policy == -1) {
159 async_safe_format_log(ANDROID_LOG_WARN, "libc",
160 "pthread_create sched_getscheduler failed: %s", strerror(errno));
161 return errno;
162 }
163 if (sched_getparam(0, ¶m) == -1) {
164 async_safe_format_log(ANDROID_LOG_WARN, "libc",
165 "pthread_create sched_getparam failed: %s", strerror(errno));
166 return errno;
167 }
168 }
169 } else {
170 policy = thread->attr.sched_policy;
171 param.sched_priority = thread->attr.sched_priority;
172 }
173 // Backwards compatibility: before P, Android didn't have pthread_attr_setinheritsched,
174 // and our behavior was neither of the POSIX behaviors.
175 if ((thread->attr.flags & (PTHREAD_ATTR_FLAG_INHERIT|PTHREAD_ATTR_FLAG_EXPLICIT)) == 0) {
176 need_set = (thread->attr.sched_policy != SCHED_NORMAL);
177 }
178 if (need_set) {
179 if (sched_setscheduler(thread->tid, policy, ¶m) == -1) {
180 async_safe_format_log(ANDROID_LOG_WARN, "libc",
181 "pthread_create sched_setscheduler(%d, {%d}) call failed: %s", policy,
182 param.sched_priority, strerror(errno));
183 #if defined(__LP64__)
184 // For backwards compatibility reasons, we only report failures on 64-bit devices.
185 return errno;
186 #endif
187 }
188 }
189
190 return 0;
191 }
192
193
194 // Allocate a thread's primary mapping. This mapping includes static TLS and
195 // optionally a stack. Static TLS includes ELF TLS segments and the bionic_tls
196 // struct.
197 //
198 // The stack_guard_size must be a multiple of the PAGE_SIZE.
__allocate_thread_mapping(size_t stack_size,size_t stack_guard_size)199 ThreadMapping __allocate_thread_mapping(size_t stack_size, size_t stack_guard_size) {
200 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
201
202 // Allocate in order: stack guard, stack, static TLS, guard page.
203 size_t mmap_size;
204 if (__builtin_add_overflow(stack_size, stack_guard_size, &mmap_size)) return {};
205 if (__builtin_add_overflow(mmap_size, layout.size(), &mmap_size)) return {};
206 if (__builtin_add_overflow(mmap_size, PTHREAD_GUARD_SIZE, &mmap_size)) return {};
207
208 // Align the result to a page size.
209 const size_t unaligned_size = mmap_size;
210 mmap_size = __BIONIC_ALIGN(mmap_size, PAGE_SIZE);
211 if (mmap_size < unaligned_size) return {};
212
213 // Create a new private anonymous map. Make the entire mapping PROT_NONE, then carve out a
214 // read+write area in the middle.
215 const int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
216 char* const space = static_cast<char*>(mmap(nullptr, mmap_size, PROT_NONE, flags, -1, 0));
217 if (space == MAP_FAILED) {
218 async_safe_format_log(ANDROID_LOG_WARN,
219 "libc",
220 "pthread_create failed: couldn't allocate %zu-bytes mapped space: %s",
221 mmap_size, strerror(errno));
222 return {};
223 }
224 const size_t writable_size = mmap_size - stack_guard_size - PTHREAD_GUARD_SIZE;
225 if (mprotect(space + stack_guard_size,
226 writable_size,
227 PROT_READ | PROT_WRITE) != 0) {
228 async_safe_format_log(ANDROID_LOG_WARN, "libc",
229 "pthread_create failed: couldn't mprotect R+W %zu-byte thread mapping region: %s",
230 writable_size, strerror(errno));
231 munmap(space, mmap_size);
232 return {};
233 }
234
235 ThreadMapping result = {};
236 result.mmap_base = space;
237 result.mmap_size = mmap_size;
238 result.mmap_base_unguarded = space + stack_guard_size;
239 result.mmap_size_unguarded = mmap_size - stack_guard_size - PTHREAD_GUARD_SIZE;
240 result.static_tls = space + mmap_size - PTHREAD_GUARD_SIZE - layout.size();
241 result.stack_base = space;
242 result.stack_top = result.static_tls;
243 return result;
244 }
245
__allocate_thread(pthread_attr_t * attr,bionic_tcb ** tcbp,void ** child_stack)246 static int __allocate_thread(pthread_attr_t* attr, bionic_tcb** tcbp, void** child_stack) {
247 ThreadMapping mapping;
248 char* stack_top;
249 bool stack_clean = false;
250
251 if (attr->stack_base == nullptr) {
252 // The caller didn't provide a stack, so allocate one.
253
254 // Make sure the guard size is a multiple of PAGE_SIZE.
255 const size_t unaligned_guard_size = attr->guard_size;
256 attr->guard_size = __BIONIC_ALIGN(attr->guard_size, PAGE_SIZE);
257 if (attr->guard_size < unaligned_guard_size) return EAGAIN;
258
259 mapping = __allocate_thread_mapping(attr->stack_size, attr->guard_size);
260 if (mapping.mmap_base == nullptr) return EAGAIN;
261
262 stack_top = mapping.stack_top;
263 attr->stack_base = mapping.stack_base;
264 stack_clean = true;
265 } else {
266 mapping = __allocate_thread_mapping(0, PTHREAD_GUARD_SIZE);
267 if (mapping.mmap_base == nullptr) return EAGAIN;
268
269 stack_top = static_cast<char*>(attr->stack_base) + attr->stack_size;
270 }
271
272 // Carve out space from the stack for the thread's pthread_internal_t. This
273 // memory isn't counted in pthread_attr_getstacksize.
274
275 // To safely access the pthread_internal_t and thread stack, we need to find a 16-byte aligned boundary.
276 stack_top = align_down(stack_top - sizeof(pthread_internal_t), 16);
277
278 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(stack_top);
279 if (!stack_clean) {
280 // If thread was not allocated by mmap(), it may not have been cleared to zero.
281 // So assume the worst and zero it.
282 memset(thread, 0, sizeof(pthread_internal_t));
283 }
284
285 // Locate static TLS structures within the mapped region.
286 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
287 auto tcb = reinterpret_cast<bionic_tcb*>(mapping.static_tls + layout.offset_bionic_tcb());
288 auto tls = reinterpret_cast<bionic_tls*>(mapping.static_tls + layout.offset_bionic_tls());
289
290 // Initialize TLS memory.
291 __init_static_tls(mapping.static_tls);
292 __init_tcb(tcb, thread);
293 __init_tcb_dtv(tcb);
294 __init_tcb_stack_guard(tcb);
295 __init_bionic_tls_ptrs(tcb, tls);
296
297 attr->stack_size = stack_top - static_cast<char*>(attr->stack_base);
298 thread->attr = *attr;
299 thread->mmap_base = mapping.mmap_base;
300 thread->mmap_size = mapping.mmap_size;
301 thread->mmap_base_unguarded = mapping.mmap_base_unguarded;
302 thread->mmap_size_unguarded = mapping.mmap_size_unguarded;
303 thread->stack_top = reinterpret_cast<uintptr_t>(stack_top);
304
305 *tcbp = tcb;
306 *child_stack = stack_top;
307 return 0;
308 }
309
__set_stack_and_tls_vma_name(bool is_main_thread)310 void __set_stack_and_tls_vma_name(bool is_main_thread) {
311 // Name the thread's stack-and-tls area to help with debugging. This mapped area also includes
312 // static TLS data, which is typically a few pages (e.g. bionic_tls).
313 pthread_internal_t* thread = __get_thread();
314 const char* name;
315 if (is_main_thread) {
316 name = "stack_and_tls:main";
317 } else {
318 // The kernel doesn't copy the name string, but this variable will last at least as long as the
319 // mapped area. The mapped area's VMAs are unmapped with a single call to munmap.
320 auto& name_buffer = thread->vma_name_buffer;
321 static_assert(arraysize(name_buffer) >= arraysize("stack_and_tls:") + 11 + 1);
322 async_safe_format_buffer(name_buffer, arraysize(name_buffer), "stack_and_tls:%d", thread->tid);
323 name = name_buffer;
324 }
325 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, thread->mmap_base_unguarded, thread->mmap_size_unguarded,
326 name);
327 }
328
329 extern "C" int __rt_sigprocmask(int, const sigset64_t*, sigset64_t*, size_t);
330
331 __attribute__((no_sanitize("hwaddress")))
__pthread_start(void * arg)332 static int __pthread_start(void* arg) {
333 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(arg);
334
335 __hwasan_thread_enter();
336
337 // Wait for our creating thread to release us. This lets it have time to
338 // notify gdb about this thread before we start doing anything.
339 // This also provides the memory barrier needed to ensure that all memory
340 // accesses previously made by the creating thread are visible to us.
341 thread->startup_handshake_lock.lock();
342
343 __set_stack_and_tls_vma_name(false);
344 __init_additional_stacks(thread);
345 __rt_sigprocmask(SIG_SETMASK, &thread->start_mask, nullptr, sizeof(thread->start_mask));
346
347 void* result = thread->start_routine(thread->start_routine_arg);
348 pthread_exit(result);
349
350 return 0;
351 }
352
353 // A dummy start routine for pthread_create failures where we've created a thread but aren't
354 // going to run user code on it. We swap out the user's start routine for this and take advantage
355 // of the regular thread teardown to free up resources.
__do_nothing(void *)356 static void* __do_nothing(void*) {
357 return nullptr;
358 }
359
360
361 __BIONIC_WEAK_FOR_NATIVE_BRIDGE
pthread_create(pthread_t * thread_out,pthread_attr_t const * attr,void * (* start_routine)(void *),void * arg)362 int pthread_create(pthread_t* thread_out, pthread_attr_t const* attr,
363 void* (*start_routine)(void*), void* arg) {
364 ErrnoRestorer errno_restorer;
365
366 pthread_attr_t thread_attr;
367 ScopedTrace trace("pthread_create");
368 if (attr == nullptr) {
369 pthread_attr_init(&thread_attr);
370 } else {
371 thread_attr = *attr;
372 attr = nullptr; // Prevent misuse below.
373 }
374
375 bionic_tcb* tcb = nullptr;
376 void* child_stack = nullptr;
377 int result = __allocate_thread(&thread_attr, &tcb, &child_stack);
378 if (result != 0) {
379 return result;
380 }
381
382 pthread_internal_t* thread = tcb->thread();
383
384 // Create a lock for the thread to wait on once it starts so we can keep
385 // it from doing anything until after we notify the debugger about it
386 //
387 // This also provides the memory barrier we need to ensure that all
388 // memory accesses previously performed by this thread are visible to
389 // the new thread.
390 thread->startup_handshake_lock.init(false);
391 thread->startup_handshake_lock.lock();
392
393 thread->start_routine = start_routine;
394 thread->start_routine_arg = arg;
395
396 thread->set_cached_pid(getpid());
397
398 int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM |
399 CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
400 void* tls = &tcb->tls_slot(0);
401 #if defined(__i386__)
402 // On x86 (but not x86-64), CLONE_SETTLS takes a pointer to a struct user_desc rather than
403 // a pointer to the TLS itself.
404 user_desc tls_descriptor;
405 __init_user_desc(&tls_descriptor, false, tls);
406 tls = &tls_descriptor;
407 #endif
408
409 sigset64_t block_all_mask;
410 sigfillset64(&block_all_mask);
411 __rt_sigprocmask(SIG_SETMASK, &block_all_mask, &thread->start_mask, sizeof(thread->start_mask));
412 int rc = clone(__pthread_start, child_stack, flags, thread, &(thread->tid), tls, &(thread->tid));
413 __rt_sigprocmask(SIG_SETMASK, &thread->start_mask, nullptr, sizeof(thread->start_mask));
414 if (rc == -1) {
415 int clone_errno = errno;
416 // We don't have to unlock the mutex at all because clone(2) failed so there's no child waiting to
417 // be unblocked, but we're about to unmap the memory the mutex is stored in, so this serves as a
418 // reminder that you can't rewrite this function to use a ScopedPthreadMutexLocker.
419 thread->startup_handshake_lock.unlock();
420 if (thread->mmap_size != 0) {
421 munmap(thread->mmap_base, thread->mmap_size);
422 }
423 async_safe_format_log(ANDROID_LOG_WARN, "libc", "pthread_create failed: clone failed: %s",
424 strerror(clone_errno));
425 return clone_errno;
426 }
427
428 int init_errno = __init_thread(thread);
429 if (init_errno != 0) {
430 // Mark the thread detached and replace its start_routine with a no-op.
431 // Letting the thread run is the easiest way to clean up its resources.
432 atomic_store(&thread->join_state, THREAD_DETACHED);
433 __pthread_internal_add(thread);
434 thread->start_routine = __do_nothing;
435 thread->startup_handshake_lock.unlock();
436 return init_errno;
437 }
438
439 // Publish the pthread_t and unlock the mutex to let the new thread start running.
440 *thread_out = __pthread_internal_add(thread);
441 thread->startup_handshake_lock.unlock();
442
443 return 0;
444 }
445