blob: 417ce761813a737a725c18a008258277f9f7c348 [file] [log] [blame]
Elliott Hughes4b4a8822013-02-12 17:15:59 -08001/*
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>
Elliott Hughes05fc1d72015-01-28 18:02:33 -080032#include <string.h>
Peter Collingbournedcbacd62021-04-22 12:13:40 -070033#include <sys/auxv.h>
Elliott Hughes4b4a8822013-02-12 17:15:59 -080034#include <sys/mman.h>
Elliott Hughes99d54652018-08-22 10:36:23 -070035#include <sys/prctl.h>
Peter Collingbourneda772e22018-09-06 22:20:44 -070036#include <sys/random.h>
Elliott Hughes7086ad62014-06-19 16:39:01 -070037#include <unistd.h>
Elliott Hughes4b4a8822013-02-12 17:15:59 -080038
39#include "pthread_internal.h"
40
Christopher Ferris7a3681e2017-04-24 17:48:32 -070041#include <async_safe/log.h>
42
Evgenii Stepanovf9fa32a2022-05-12 15:54:38 -070043#include "platform/bionic/macros.h"
44#include "platform/bionic/mte.h"
45#include "private/ErrnoRestorer.h"
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070046#include "private/ScopedRWLock.h"
Peter Collingbourne734beec2018-11-14 12:41:41 -080047#include "private/bionic_constants.h"
dimitryfa432522017-10-25 13:07:45 +020048#include "private/bionic_defs.h"
Ryan Prichard45d13492019-01-03 02:51:30 -080049#include "private/bionic_globals.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080050#include "private/bionic_ssp.h"
Philip Cuadra77d0f902019-01-25 10:39:25 -080051#include "private/bionic_systrace.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080052#include "private/bionic_tls.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080053
Elliott Hughes0d236aa2014-05-09 14:42:16 -070054// x86 uses segment descriptors rather than a direct pointer to TLS.
Josh Gaocb728e62016-09-15 13:56:37 -070055#if defined(__i386__)
Elliott Hughes0d236aa2014-05-09 14:42:16 -070056#include <asm/ldt.h>
Elliott Hughes01b85d52016-02-09 22:44:16 -080057void __init_user_desc(struct user_desc*, bool, void*);
Elliott Hughes0d236aa2014-05-09 14:42:16 -070058#endif
59
Ryan Prichard9cfca862018-11-22 02:44:09 -080060__attribute__((no_stack_protector))
Ryan Prichard45d13492019-01-03 02:51:30 -080061void __init_tcb_stack_guard(bionic_tcb* tcb) {
Ryan Prichard9cfca862018-11-22 02:44:09 -080062 // GCC looks in the TLS for the stack guard on x86, so copy it there from our global.
Ryan Prichard45d13492019-01-03 02:51:30 -080063 tcb->tls_slot(TLS_SLOT_STACK_GUARD) = reinterpret_cast<void*>(__stack_chk_guard);
Ryan Prichard9cfca862018-11-22 02:44:09 -080064}
65
Ryan Prichard45d13492019-01-03 02:51:30 -080066void __init_bionic_tls_ptrs(bionic_tcb* tcb, bionic_tls* tls) {
67 tcb->thread()->bionic_tls = tls;
68 tcb->tls_slot(TLS_SLOT_BIONIC_TLS) = tls;
69}
70
71// Allocate a temporary bionic_tls that the dynamic linker's main thread can
72// use while it's loading the initial set of ELF modules.
73bionic_tls* __allocate_temp_bionic_tls() {
74 size_t allocation_size = __BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE);
75 void* allocation = mmap(nullptr, allocation_size,
76 PROT_READ | PROT_WRITE,
77 MAP_PRIVATE | MAP_ANONYMOUS,
78 -1, 0);
Josh Gao5e2285d2017-02-22 12:19:05 -080079 if (allocation == MAP_FAILED) {
Ryan Prichard45d13492019-01-03 02:51:30 -080080 // Avoid strerror because it might need bionic_tls.
81 async_safe_fatal("failed to allocate bionic_tls: error %d", errno);
Josh Gao5e2285d2017-02-22 12:19:05 -080082 }
Ryan Prichard45d13492019-01-03 02:51:30 -080083 return static_cast<bionic_tls*>(allocation);
84}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -070085
Ryan Prichard45d13492019-01-03 02:51:30 -080086void __free_temp_bionic_tls(bionic_tls* tls) {
87 munmap(tls, __BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE));
Elliott Hughes70b24b12013-11-15 11:51:07 -080088}
Elliott Hughes4b4a8822013-02-12 17:15:59 -080089
Peter Collingbourneda772e22018-09-06 22:20:44 -070090static void __init_alternate_signal_stack(pthread_internal_t* thread) {
Elliott Hughes84114c82013-07-17 13:33:19 -070091 // Create and set an alternate signal stack.
Evgenii Stepanovf9fa32a2022-05-12 15:54:38 -070092 int prot = PROT_READ | PROT_WRITE;
93#ifdef __aarch64__
94 if (atomic_load(&__libc_globals->memtag_stack)) {
95 prot |= PROT_MTE;
96 }
97#endif
98 void* stack_base = mmap(nullptr, SIGNAL_STACK_SIZE, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Yabin Cuief115002015-03-30 20:03:57 -070099 if (stack_base != MAP_FAILED) {
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700100 // Create a guard to catch stack overflows in signal handlers.
101 if (mprotect(stack_base, PTHREAD_GUARD_SIZE, PROT_NONE) == -1) {
Yabin Cuief115002015-03-30 20:03:57 -0700102 munmap(stack_base, SIGNAL_STACK_SIZE);
103 return;
104 }
105 stack_t ss;
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700106 ss.ss_sp = reinterpret_cast<uint8_t*>(stack_base) + PTHREAD_GUARD_SIZE;
107 ss.ss_size = SIGNAL_STACK_SIZE - PTHREAD_GUARD_SIZE;
Elliott Hughes84114c82013-07-17 13:33:19 -0700108 ss.ss_flags = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700109 sigaltstack(&ss, nullptr);
Yabin Cuief115002015-03-30 20:03:57 -0700110 thread->alternate_signal_stack = stack_base;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800111
112 // We can only use const static allocated string for mapped region name, as Android kernel
113 // uses the string pointer directly when dumping /proc/pid/maps.
Elliott Hughesa3125fd2015-03-31 02:42:39 +0000114 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ss.ss_sp, ss.ss_size, "thread signal stack");
Elliott Hughes84114c82013-07-17 13:33:19 -0700115 }
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800116}
117
Peter Collingbourneda772e22018-09-06 22:20:44 -0700118static void __init_shadow_call_stack(pthread_internal_t* thread __unused) {
119#ifdef __aarch64__
Peter Collingbournef1ed31f2019-01-31 14:26:43 -0800120 // Allocate the stack and the guard region.
Peter Collingbourne734beec2018-11-14 12:41:41 -0800121 char* scs_guard_region = reinterpret_cast<char*>(
122 mmap(nullptr, SCS_GUARD_REGION_SIZE, 0, MAP_PRIVATE | MAP_ANON, -1, 0));
123 thread->shadow_call_stack_guard_region = scs_guard_region;
124
Peter Collingbournef1ed31f2019-01-31 14:26:43 -0800125 // The address is aligned to SCS_SIZE so that we only need to store the lower log2(SCS_SIZE) bits
126 // in jmp_buf.
127 char* scs_aligned_guard_region =
Peter Collingbourne734beec2018-11-14 12:41:41 -0800128 reinterpret_cast<char*>(align_up(reinterpret_cast<uintptr_t>(scs_guard_region), SCS_SIZE));
Peter Collingbournef1ed31f2019-01-31 14:26:43 -0800129
130 // We need to ensure that [scs_offset,scs_offset+SCS_SIZE) is in the guard region and that there
131 // is at least one unmapped page after the shadow call stack (to catch stack overflows). We can't
132 // use arc4random_uniform in init because /dev/urandom might not have been created yet.
133 size_t scs_offset =
134 (getpid() == 1) ? 0 : (arc4random_uniform(SCS_GUARD_REGION_SIZE / SCS_SIZE - 1) * SCS_SIZE);
135
136 // Make the stack readable and writable and store its address in register x18. This is
137 // deliberately the only place where the address is stored.
138 char *scs = scs_aligned_guard_region + scs_offset;
Peter Collingbourne734beec2018-11-14 12:41:41 -0800139 mprotect(scs, SCS_SIZE, PROT_READ | PROT_WRITE);
Peter Collingbourneda772e22018-09-06 22:20:44 -0700140 __asm__ __volatile__("mov x18, %0" ::"r"(scs));
141#endif
142}
143
144void __init_additional_stacks(pthread_internal_t* thread) {
145 __init_alternate_signal_stack(thread);
146 __init_shadow_call_stack(thread);
147}
148
Yabin Cui673b15e2015-03-19 14:19:19 -0700149int __init_thread(pthread_internal_t* thread) {
Elliott Hughes8aecba72017-10-17 15:34:41 -0700150 thread->cleanup_stack = nullptr;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800151
Yabin Cui58cf31b2015-03-06 17:23:53 -0800152 if (__predict_true((thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) == 0)) {
153 atomic_init(&thread->join_state, THREAD_NOT_JOINED);
154 } else {
155 atomic_init(&thread->join_state, THREAD_DETACHED);
156 }
157
Elliott Hughes8aecba72017-10-17 15:34:41 -0700158 // Set the scheduling policy/priority of the thread if necessary.
159 bool need_set = true;
160 int policy;
161 sched_param param;
Elliott Hughes38f01e02017-10-27 15:28:54 -0700162 if ((thread->attr.flags & PTHREAD_ATTR_FLAG_INHERIT) != 0) {
Elliott Hughes8aecba72017-10-17 15:34:41 -0700163 // Unless the parent has SCHED_RESET_ON_FORK set, we've already inherited from the parent.
164 policy = sched_getscheduler(0);
165 need_set = ((policy & SCHED_RESET_ON_FORK) != 0);
166 if (need_set) {
167 if (policy == -1) {
168 async_safe_format_log(ANDROID_LOG_WARN, "libc",
169 "pthread_create sched_getscheduler failed: %s", strerror(errno));
170 return errno;
171 }
172 if (sched_getparam(0, &param) == -1) {
173 async_safe_format_log(ANDROID_LOG_WARN, "libc",
174 "pthread_create sched_getparam failed: %s", strerror(errno));
175 return errno;
176 }
177 }
178 } else {
179 policy = thread->attr.sched_policy;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800180 param.sched_priority = thread->attr.sched_priority;
Elliott Hughes8aecba72017-10-17 15:34:41 -0700181 }
Elliott Hughes38f01e02017-10-27 15:28:54 -0700182 // Backwards compatibility: before P, Android didn't have pthread_attr_setinheritsched,
183 // and our behavior was neither of the POSIX behaviors.
184 if ((thread->attr.flags & (PTHREAD_ATTR_FLAG_INHERIT|PTHREAD_ATTR_FLAG_EXPLICIT)) == 0) {
185 need_set = (thread->attr.sched_policy != SCHED_NORMAL);
186 }
Elliott Hughes8aecba72017-10-17 15:34:41 -0700187 if (need_set) {
188 if (sched_setscheduler(thread->tid, policy, &param) == -1) {
189 async_safe_format_log(ANDROID_LOG_WARN, "libc",
190 "pthread_create sched_setscheduler(%d, {%d}) call failed: %s", policy,
191 param.sched_priority, strerror(errno));
Josh Gaob36efa42016-09-15 13:55:41 -0700192#if defined(__LP64__)
Elliott Hughes98624c32013-10-15 16:51:17 -0700193 // For backwards compatibility reasons, we only report failures on 64-bit devices.
Elliott Hughes8aecba72017-10-17 15:34:41 -0700194 return errno;
Elliott Hughes98624c32013-10-15 16:51:17 -0700195#endif
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800196 }
197 }
198
Elliott Hughes8aecba72017-10-17 15:34:41 -0700199 return 0;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800200}
201
Ryan Prichard45d13492019-01-03 02:51:30 -0800202
203// Allocate a thread's primary mapping. This mapping includes static TLS and
204// optionally a stack. Static TLS includes ELF TLS segments and the bionic_tls
205// struct.
206//
207// The stack_guard_size must be a multiple of the PAGE_SIZE.
208ThreadMapping __allocate_thread_mapping(size_t stack_size, size_t stack_guard_size) {
209 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
210
211 // Allocate in order: stack guard, stack, static TLS, guard page.
212 size_t mmap_size;
213 if (__builtin_add_overflow(stack_size, stack_guard_size, &mmap_size)) return {};
214 if (__builtin_add_overflow(mmap_size, layout.size(), &mmap_size)) return {};
215 if (__builtin_add_overflow(mmap_size, PTHREAD_GUARD_SIZE, &mmap_size)) return {};
216
217 // Align the result to a page size.
218 const size_t unaligned_size = mmap_size;
219 mmap_size = __BIONIC_ALIGN(mmap_size, PAGE_SIZE);
220 if (mmap_size < unaligned_size) return {};
221
222 // Create a new private anonymous map. Make the entire mapping PROT_NONE, then carve out a
223 // read+write area in the middle.
224 const int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
225 char* const space = static_cast<char*>(mmap(nullptr, mmap_size, PROT_NONE, flags, -1, 0));
Yabin Cuiba8dfc22015-01-06 09:31:00 -0800226 if (space == MAP_FAILED) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700227 async_safe_format_log(ANDROID_LOG_WARN,
Ryan Prichard45d13492019-01-03 02:51:30 -0800228 "libc",
229 "pthread_create failed: couldn't allocate %zu-bytes mapped space: %s",
230 mmap_size, strerror(errno));
231 return {};
232 }
233 const size_t writable_size = mmap_size - stack_guard_size - PTHREAD_GUARD_SIZE;
Evgenii Stepanovf9fa32a2022-05-12 15:54:38 -0700234 int prot = PROT_READ | PROT_WRITE;
235 const char* prot_str = "R+W";
236#ifdef __aarch64__
237 if (atomic_load(&__libc_globals->memtag_stack)) {
238 prot |= PROT_MTE;
239 prot_str = "R+W+MTE";
240 }
241#endif
242 if (mprotect(space + stack_guard_size, writable_size, prot) != 0) {
243 async_safe_format_log(
244 ANDROID_LOG_WARN, "libc",
245 "pthread_create failed: couldn't mprotect %s %zu-byte thread mapping region: %s", prot_str,
246 writable_size, strerror(errno));
Ryan Prichard45d13492019-01-03 02:51:30 -0800247 munmap(space, mmap_size);
248 return {};
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800249 }
250
Ryan Prichard45d13492019-01-03 02:51:30 -0800251 ThreadMapping result = {};
252 result.mmap_base = space;
253 result.mmap_size = mmap_size;
Ryan Prichard03cef382019-06-17 17:57:19 -0700254 result.mmap_base_unguarded = space + stack_guard_size;
255 result.mmap_size_unguarded = mmap_size - stack_guard_size - PTHREAD_GUARD_SIZE;
Ryan Prichard45d13492019-01-03 02:51:30 -0800256 result.static_tls = space + mmap_size - PTHREAD_GUARD_SIZE - layout.size();
257 result.stack_base = space;
258 result.stack_top = result.static_tls;
259 return result;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800260}
261
Ryan Prichard45d13492019-01-03 02:51:30 -0800262static int __allocate_thread(pthread_attr_t* attr, bionic_tcb** tcbp, void** child_stack) {
263 ThreadMapping mapping;
264 char* stack_top;
265 bool stack_clean = false;
Yabin Cui6a7aaf42014-12-22 19:17:33 -0800266
Yi Kong32bc0fc2018-08-02 17:31:13 -0700267 if (attr->stack_base == nullptr) {
Yabin Cui8cf1b302014-12-03 21:36:24 -0800268 // The caller didn't provide a stack, so allocate one.
Ryan Prichard45d13492019-01-03 02:51:30 -0800269
270 // Make sure the guard size is a multiple of PAGE_SIZE.
271 const size_t unaligned_guard_size = attr->guard_size;
Dan Alberta613d0d2017-10-05 16:39:33 -0700272 attr->guard_size = __BIONIC_ALIGN(attr->guard_size, PAGE_SIZE);
Ryan Prichard45d13492019-01-03 02:51:30 -0800273 if (attr->guard_size < unaligned_guard_size) return EAGAIN;
274
275 mapping = __allocate_thread_mapping(attr->stack_size, attr->guard_size);
276 if (mapping.mmap_base == nullptr) return EAGAIN;
277
278 stack_top = mapping.stack_top;
279 attr->stack_base = mapping.stack_base;
280 stack_clean = true;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800281 } else {
Ryan Prichard45d13492019-01-03 02:51:30 -0800282 mapping = __allocate_thread_mapping(0, PTHREAD_GUARD_SIZE);
283 if (mapping.mmap_base == nullptr) return EAGAIN;
284
285 stack_top = static_cast<char*>(attr->stack_base) + attr->stack_size;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800286 }
287
Ryan Prichard45d13492019-01-03 02:51:30 -0800288 // Carve out space from the stack for the thread's pthread_internal_t. This
289 // memory isn't counted in pthread_attr_getstacksize.
Yabin Cuia2db50d2015-03-20 10:58:04 -0700290
291 // To safely access the pthread_internal_t and thread stack, we need to find a 16-byte aligned boundary.
Ryan Prichard45d13492019-01-03 02:51:30 -0800292 stack_top = align_down(stack_top - sizeof(pthread_internal_t), 16);
Yabin Cuia2db50d2015-03-20 10:58:04 -0700293
Yabin Cui8cf1b302014-12-03 21:36:24 -0800294 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(stack_top);
Ryan Prichard45d13492019-01-03 02:51:30 -0800295 if (!stack_clean) {
Yabin Cui304348a2015-12-03 13:01:42 -0800296 // If thread was not allocated by mmap(), it may not have been cleared to zero.
297 // So assume the worst and zero it.
298 memset(thread, 0, sizeof(pthread_internal_t));
299 }
Yabin Cui8cf1b302014-12-03 21:36:24 -0800300
Ryan Prichard45d13492019-01-03 02:51:30 -0800301 // Locate static TLS structures within the mapped region.
302 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
303 auto tcb = reinterpret_cast<bionic_tcb*>(mapping.static_tls + layout.offset_bionic_tcb());
304 auto tls = reinterpret_cast<bionic_tls*>(mapping.static_tls + layout.offset_bionic_tls());
305
Ryan Prichard361c1b42019-01-15 13:45:27 -0800306 // Initialize TLS memory.
307 __init_static_tls(mapping.static_tls);
Ryan Prichard45d13492019-01-03 02:51:30 -0800308 __init_tcb(tcb, thread);
Ryan Prichard16455b52019-01-18 01:00:59 -0800309 __init_tcb_dtv(tcb);
Ryan Prichard45d13492019-01-03 02:51:30 -0800310 __init_tcb_stack_guard(tcb);
311 __init_bionic_tls_ptrs(tcb, tls);
312
313 attr->stack_size = stack_top - static_cast<char*>(attr->stack_base);
Yabin Cui8cf1b302014-12-03 21:36:24 -0800314 thread->attr = *attr;
Ryan Prichard45d13492019-01-03 02:51:30 -0800315 thread->mmap_base = mapping.mmap_base;
316 thread->mmap_size = mapping.mmap_size;
Ryan Prichard03cef382019-06-17 17:57:19 -0700317 thread->mmap_base_unguarded = mapping.mmap_base_unguarded;
318 thread->mmap_size_unguarded = mapping.mmap_size_unguarded;
Peter Collingbourne5f45c182020-01-14 17:59:41 -0800319 thread->stack_top = reinterpret_cast<uintptr_t>(stack_top);
Ryan Prichard9cfca862018-11-22 02:44:09 -0800320
Ryan Prichard45d13492019-01-03 02:51:30 -0800321 *tcbp = tcb;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800322 *child_stack = stack_top;
323 return 0;
324}
325
Ryan Prichard03cef382019-06-17 17:57:19 -0700326void __set_stack_and_tls_vma_name(bool is_main_thread) {
327 // Name the thread's stack-and-tls area to help with debugging. This mapped area also includes
328 // static TLS data, which is typically a few pages (e.g. bionic_tls).
329 pthread_internal_t* thread = __get_thread();
330 const char* name;
331 if (is_main_thread) {
332 name = "stack_and_tls:main";
333 } else {
334 // The kernel doesn't copy the name string, but this variable will last at least as long as the
335 // mapped area. The mapped area's VMAs are unmapped with a single call to munmap.
336 auto& name_buffer = thread->vma_name_buffer;
337 static_assert(arraysize(name_buffer) >= arraysize("stack_and_tls:") + 11 + 1);
338 async_safe_format_buffer(name_buffer, arraysize(name_buffer), "stack_and_tls:%d", thread->tid);
339 name = name_buffer;
340 }
341 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, thread->mmap_base_unguarded, thread->mmap_size_unguarded,
342 name);
343}
344
Evgenii Stepanovb92d1c32019-10-02 16:26:43 -0700345extern "C" int __rt_sigprocmask(int, const sigset64_t*, sigset64_t*, size_t);
346
Evgenii Stepanov13e8dcb2018-09-19 16:29:12 -0700347__attribute__((no_sanitize("hwaddress")))
Elliott Hughes73091772022-03-10 18:01:04 +0000348#ifdef __aarch64__
Peter Collingbourne26d83ba2021-06-04 14:35:13 -0700349// This function doesn't return, but it does appear in stack traces. Avoid using return PAC in this
350// function because we may end up resetting IA, which may confuse unwinders due to mismatching keys.
Elliott Hughes73091772022-03-10 18:01:04 +0000351__attribute__((target("branch-protection=bti")))
352#endif
Elliott Hughese48b6852013-11-15 14:57:45 -0800353static int __pthread_start(void* arg) {
354 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(arg);
355
Evgenii Stepanov13e8dcb2018-09-19 16:29:12 -0700356 __hwasan_thread_enter();
357
Elliott Hughese48b6852013-11-15 14:57:45 -0800358 // Wait for our creating thread to release us. This lets it have time to
359 // notify gdb about this thread before we start doing anything.
360 // This also provides the memory barrier needed to ensure that all memory
361 // accesses previously made by the creating thread are visible to us.
Yabin Cuid26e7802015-10-22 20:07:56 -0700362 thread->startup_handshake_lock.lock();
Elliott Hughese48b6852013-11-15 14:57:45 -0800363
Ryan Prichard03cef382019-06-17 17:57:19 -0700364 __set_stack_and_tls_vma_name(false);
Peter Collingbourneda772e22018-09-06 22:20:44 -0700365 __init_additional_stacks(thread);
Evgenii Stepanovb92d1c32019-10-02 16:26:43 -0700366 __rt_sigprocmask(SIG_SETMASK, &thread->start_mask, nullptr, sizeof(thread->start_mask));
Peter Collingbourne811d1802021-03-25 11:46:44 -0700367#ifdef __aarch64__
368 // Chrome's sandbox prevents this prctl, so only reset IA if the target SDK level is high enough.
Peter Collingbournedcbacd62021-04-22 12:13:40 -0700369 // Furthermore, processes loaded from vendor partitions may have their own sandboxes that would
370 // reject the prctl. Because no devices launched with PAC enabled before S, we can avoid issues on
371 // upgrading devices by checking for PAC support before issuing the prctl.
372 static const bool pac_supported = getauxval(AT_HWCAP) & HWCAP_PACA;
373 if (pac_supported && android_get_application_target_sdk_version() >= __ANDROID_API_S__) {
Peter Collingbourne811d1802021-03-25 11:46:44 -0700374 prctl(PR_PAC_RESET_KEYS, PR_PAC_APIAKEY, 0, 0, 0);
375 }
376#endif
Elliott Hughese48b6852013-11-15 14:57:45 -0800377
Elliott Hughese48b6852013-11-15 14:57:45 -0800378 void* result = thread->start_routine(thread->start_routine_arg);
379 pthread_exit(result);
380
381 return 0;
382}
383
Elliott Hughes68ae6ad2020-07-21 16:11:30 -0700384// A no-op start routine for pthread_create failures where we've created a thread but aren't
Elliott Hughescef3fae2013-11-19 16:52:24 -0800385// going to run user code on it. We swap out the user's start routine for this and take advantage
386// of the regular thread teardown to free up resources.
387static void* __do_nothing(void*) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700388 return nullptr;
Elliott Hughescef3fae2013-11-19 16:52:24 -0800389}
390
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700391pthread_rwlock_t g_thread_creation_lock = PTHREAD_RWLOCK_INITIALIZER;
dimitryfa432522017-10-25 13:07:45 +0200392
393__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800394int pthread_create(pthread_t* thread_out, pthread_attr_t const* attr,
395 void* (*start_routine)(void*), void* arg) {
396 ErrnoRestorer errno_restorer;
397
Yabin Cui8cf1b302014-12-03 21:36:24 -0800398 pthread_attr_t thread_attr;
Philip Cuadra77d0f902019-01-25 10:39:25 -0800399 ScopedTrace trace("pthread_create");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700400 if (attr == nullptr) {
Yabin Cui8cf1b302014-12-03 21:36:24 -0800401 pthread_attr_init(&thread_attr);
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800402 } else {
Yabin Cui8cf1b302014-12-03 21:36:24 -0800403 thread_attr = *attr;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700404 attr = nullptr; // Prevent misuse below.
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800405 }
406
Ryan Prichard45d13492019-01-03 02:51:30 -0800407 bionic_tcb* tcb = nullptr;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700408 void* child_stack = nullptr;
Ryan Prichard45d13492019-01-03 02:51:30 -0800409 int result = __allocate_thread(&thread_attr, &tcb, &child_stack);
Yabin Cui8cf1b302014-12-03 21:36:24 -0800410 if (result != 0) {
411 return result;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800412 }
413
Ryan Prichard45d13492019-01-03 02:51:30 -0800414 pthread_internal_t* thread = tcb->thread();
415
Yabin Cuid26e7802015-10-22 20:07:56 -0700416 // Create a lock for the thread to wait on once it starts so we can keep
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800417 // it from doing anything until after we notify the debugger about it
418 //
419 // This also provides the memory barrier we need to ensure that all
420 // memory accesses previously performed by this thread are visible to
421 // the new thread.
Yabin Cuid26e7802015-10-22 20:07:56 -0700422 thread->startup_handshake_lock.init(false);
423 thread->startup_handshake_lock.lock();
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800424
Elliott Hughes70b24b12013-11-15 11:51:07 -0800425 thread->start_routine = start_routine;
426 thread->start_routine_arg = arg;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800427
Elliott Hughes7086ad62014-06-19 16:39:01 -0700428 thread->set_cached_pid(getpid());
429
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800430 int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM |
431 CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
Ryan Prichard45d13492019-01-03 02:51:30 -0800432 void* tls = &tcb->tls_slot(0);
Elliott Hughes80906142013-11-26 13:57:21 -0800433#if defined(__i386__)
434 // On x86 (but not x86-64), CLONE_SETTLS takes a pointer to a struct user_desc rather than
Elliott Hughes0d236aa2014-05-09 14:42:16 -0700435 // a pointer to the TLS itself.
436 user_desc tls_descriptor;
437 __init_user_desc(&tls_descriptor, false, tls);
438 tls = &tls_descriptor;
Elliott Hughes80906142013-11-26 13:57:21 -0800439#endif
Evgenii Stepanovb92d1c32019-10-02 16:26:43 -0700440
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700441 ScopedReadLock locker(&g_thread_creation_lock);
442
Evgenii Stepanovb92d1c32019-10-02 16:26:43 -0700443 sigset64_t block_all_mask;
444 sigfillset64(&block_all_mask);
445 __rt_sigprocmask(SIG_SETMASK, &block_all_mask, &thread->start_mask, sizeof(thread->start_mask));
Elliott Hughes0d236aa2014-05-09 14:42:16 -0700446 int rc = clone(__pthread_start, child_stack, flags, thread, &(thread->tid), tls, &(thread->tid));
Evgenii Stepanovb92d1c32019-10-02 16:26:43 -0700447 __rt_sigprocmask(SIG_SETMASK, &thread->start_mask, nullptr, sizeof(thread->start_mask));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800448 if (rc == -1) {
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800449 int clone_errno = errno;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800450 // We don't have to unlock the mutex at all because clone(2) failed so there's no child waiting to
451 // be unblocked, but we're about to unmap the memory the mutex is stored in, so this serves as a
452 // reminder that you can't rewrite this function to use a ScopedPthreadMutexLocker.
Yabin Cuid26e7802015-10-22 20:07:56 -0700453 thread->startup_handshake_lock.unlock();
Elliott Hughes7484c212017-02-02 02:41:38 +0000454 if (thread->mmap_size != 0) {
Ryan Prichard45d13492019-01-03 02:51:30 -0800455 munmap(thread->mmap_base, thread->mmap_size);
Elliott Hughes7484c212017-02-02 02:41:38 +0000456 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700457 async_safe_format_log(ANDROID_LOG_WARN, "libc", "pthread_create failed: clone failed: %s",
dimitry6de60872017-08-14 14:42:19 +0200458 strerror(clone_errno));
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800459 return clone_errno;
460 }
461
Yabin Cui673b15e2015-03-19 14:19:19 -0700462 int init_errno = __init_thread(thread);
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800463 if (init_errno != 0) {
Elliott Hughescef3fae2013-11-19 16:52:24 -0800464 // Mark the thread detached and replace its start_routine with a no-op.
465 // Letting the thread run is the easiest way to clean up its resources.
Yabin Cui58cf31b2015-03-06 17:23:53 -0800466 atomic_store(&thread->join_state, THREAD_DETACHED);
Elliott Hughes7484c212017-02-02 02:41:38 +0000467 __pthread_internal_add(thread);
Elliott Hughescef3fae2013-11-19 16:52:24 -0800468 thread->start_routine = __do_nothing;
Yabin Cuid26e7802015-10-22 20:07:56 -0700469 thread->startup_handshake_lock.unlock();
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800470 return init_errno;
471 }
472
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800473 // Publish the pthread_t and unlock the mutex to let the new thread start running.
Elliott Hughes7484c212017-02-02 02:41:38 +0000474 *thread_out = __pthread_internal_add(thread);
Yabin Cuid26e7802015-10-22 20:07:56 -0700475 thread->startup_handshake_lock.unlock();
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800476
477 return 0;
478}