blob: b8784b885c205b6b15c0deece50be4d6ee40a574 [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>
Elliott Hughes4b4a8822013-02-12 17:15:59 -080033#include <sys/mman.h>
Elliott Hughes99d54652018-08-22 10:36:23 -070034#include <sys/prctl.h>
Peter Collingbourneda772e22018-09-06 22:20:44 -070035#include <sys/random.h>
Elliott Hughes7086ad62014-06-19 16:39:01 -070036#include <unistd.h>
Elliott Hughes4b4a8822013-02-12 17:15:59 -080037
38#include "pthread_internal.h"
39
Christopher Ferris7a3681e2017-04-24 17:48:32 -070040#include <async_safe/log.h>
41
Peter Collingbourne734beec2018-11-14 12:41:41 -080042#include "private/bionic_constants.h"
dimitryfa432522017-10-25 13:07:45 +020043#include "private/bionic_defs.h"
Ryan Prichard45d13492019-01-03 02:51:30 -080044#include "private/bionic_globals.h"
Christopher Ferris03eebcb2014-06-13 13:57:51 -070045#include "private/bionic_macros.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080046#include "private/bionic_ssp.h"
Philip Cuadra77d0f902019-01-25 10:39:25 -080047#include "private/bionic_systrace.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080048#include "private/bionic_tls.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080049#include "private/ErrnoRestorer.h"
Elliott Hughes4b4a8822013-02-12 17:15:59 -080050
Elliott Hughes0d236aa2014-05-09 14:42:16 -070051// x86 uses segment descriptors rather than a direct pointer to TLS.
Josh Gaocb728e62016-09-15 13:56:37 -070052#if defined(__i386__)
Elliott Hughes0d236aa2014-05-09 14:42:16 -070053#include <asm/ldt.h>
Elliott Hughes01b85d52016-02-09 22:44:16 -080054void __init_user_desc(struct user_desc*, bool, void*);
Elliott Hughes0d236aa2014-05-09 14:42:16 -070055#endif
56
Elliott Hughes70b24b12013-11-15 11:51:07 -080057// This code is used both by each new pthread and the code that initializes the main thread.
Ryan Prichard9cfca862018-11-22 02:44:09 -080058__attribute__((no_stack_protector))
Ryan Prichard45d13492019-01-03 02:51:30 -080059void __init_tcb(bionic_tcb* tcb, pthread_internal_t* thread) {
60#ifdef TLS_SLOT_SELF
61 // On x86, slot 0 must point to itself so code can read the thread pointer by
62 // loading %fs:0 or %gs:0.
63 tcb->tls_slot(TLS_SLOT_SELF) = &tcb->tls_slot(TLS_SLOT_SELF);
64#endif
65 tcb->tls_slot(TLS_SLOT_THREAD_ID) = thread;
Ryan Prichard9cfca862018-11-22 02:44:09 -080066}
Josh Gao5e2285d2017-02-22 12:19:05 -080067
Ryan Prichard9cfca862018-11-22 02:44:09 -080068__attribute__((no_stack_protector))
Ryan Prichard45d13492019-01-03 02:51:30 -080069void __init_tcb_stack_guard(bionic_tcb* tcb) {
Ryan Prichard9cfca862018-11-22 02:44:09 -080070 // 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 -080071 tcb->tls_slot(TLS_SLOT_STACK_GUARD) = reinterpret_cast<void*>(__stack_chk_guard);
Ryan Prichard9cfca862018-11-22 02:44:09 -080072}
73
Ryan Prichard16455b52019-01-18 01:00:59 -080074__attribute__((no_stack_protector))
75void __init_tcb_dtv(bionic_tcb* tcb) {
76 // Initialize the DTV slot to a statically-allocated empty DTV. The first
77 // access to a dynamic TLS variable allocates a new DTV.
78 static const TlsDtv zero_dtv = {};
79 __set_tcb_dtv(tcb, const_cast<TlsDtv*>(&zero_dtv));
80}
81
Ryan Prichard45d13492019-01-03 02:51:30 -080082void __init_bionic_tls_ptrs(bionic_tcb* tcb, bionic_tls* tls) {
83 tcb->thread()->bionic_tls = tls;
84 tcb->tls_slot(TLS_SLOT_BIONIC_TLS) = tls;
85}
86
87// Allocate a temporary bionic_tls that the dynamic linker's main thread can
88// use while it's loading the initial set of ELF modules.
89bionic_tls* __allocate_temp_bionic_tls() {
90 size_t allocation_size = __BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE);
91 void* allocation = mmap(nullptr, allocation_size,
92 PROT_READ | PROT_WRITE,
93 MAP_PRIVATE | MAP_ANONYMOUS,
94 -1, 0);
Josh Gao5e2285d2017-02-22 12:19:05 -080095 if (allocation == MAP_FAILED) {
Ryan Prichard45d13492019-01-03 02:51:30 -080096 // Avoid strerror because it might need bionic_tls.
97 async_safe_fatal("failed to allocate bionic_tls: error %d", errno);
Josh Gao5e2285d2017-02-22 12:19:05 -080098 }
Ryan Prichard45d13492019-01-03 02:51:30 -080099 return static_cast<bionic_tls*>(allocation);
100}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -0700101
Ryan Prichard45d13492019-01-03 02:51:30 -0800102void __free_temp_bionic_tls(bionic_tls* tls) {
103 munmap(tls, __BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800104}
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800105
Peter Collingbourneda772e22018-09-06 22:20:44 -0700106static void __init_alternate_signal_stack(pthread_internal_t* thread) {
Elliott Hughes84114c82013-07-17 13:33:19 -0700107 // Create and set an alternate signal stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700108 void* stack_base = mmap(nullptr, SIGNAL_STACK_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Yabin Cuief115002015-03-30 20:03:57 -0700109 if (stack_base != MAP_FAILED) {
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700110 // Create a guard to catch stack overflows in signal handlers.
111 if (mprotect(stack_base, PTHREAD_GUARD_SIZE, PROT_NONE) == -1) {
Yabin Cuief115002015-03-30 20:03:57 -0700112 munmap(stack_base, SIGNAL_STACK_SIZE);
113 return;
114 }
115 stack_t ss;
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700116 ss.ss_sp = reinterpret_cast<uint8_t*>(stack_base) + PTHREAD_GUARD_SIZE;
117 ss.ss_size = SIGNAL_STACK_SIZE - PTHREAD_GUARD_SIZE;
Elliott Hughes84114c82013-07-17 13:33:19 -0700118 ss.ss_flags = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700119 sigaltstack(&ss, nullptr);
Yabin Cuief115002015-03-30 20:03:57 -0700120 thread->alternate_signal_stack = stack_base;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800121
122 // We can only use const static allocated string for mapped region name, as Android kernel
123 // uses the string pointer directly when dumping /proc/pid/maps.
Elliott Hughesa3125fd2015-03-31 02:42:39 +0000124 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 -0700125 }
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800126}
127
Peter Collingbourneda772e22018-09-06 22:20:44 -0700128static void __init_shadow_call_stack(pthread_internal_t* thread __unused) {
129#ifdef __aarch64__
Peter Collingbourne734beec2018-11-14 12:41:41 -0800130 // Allocate the stack and store its address in register x18. The address is aligned to SCS_SIZE so
131 // that we only need to store the lower log2(SCS_SIZE) bits in jmp_buf.
132 // TODO(pcc): We ought to allocate a larger guard region here and then allocate the SCS at a
133 // random location within it. This will provide greater security since it would mean that an
134 // attacker who can read the pthread_internal_t won't be able to discover the address of the SCS.
135 // However, doing so is blocked on a solution to b/118642754.
136 char* scs_guard_region = reinterpret_cast<char*>(
137 mmap(nullptr, SCS_GUARD_REGION_SIZE, 0, MAP_PRIVATE | MAP_ANON, -1, 0));
138 thread->shadow_call_stack_guard_region = scs_guard_region;
139
140 char* scs =
141 reinterpret_cast<char*>(align_up(reinterpret_cast<uintptr_t>(scs_guard_region), SCS_SIZE));
142 mprotect(scs, SCS_SIZE, PROT_READ | PROT_WRITE);
Peter Collingbourneda772e22018-09-06 22:20:44 -0700143 __asm__ __volatile__("mov x18, %0" ::"r"(scs));
144#endif
145}
146
147void __init_additional_stacks(pthread_internal_t* thread) {
148 __init_alternate_signal_stack(thread);
149 __init_shadow_call_stack(thread);
150}
151
Yabin Cui673b15e2015-03-19 14:19:19 -0700152int __init_thread(pthread_internal_t* thread) {
Elliott Hughes8aecba72017-10-17 15:34:41 -0700153 thread->cleanup_stack = nullptr;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800154
Yabin Cui58cf31b2015-03-06 17:23:53 -0800155 if (__predict_true((thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) == 0)) {
156 atomic_init(&thread->join_state, THREAD_NOT_JOINED);
157 } else {
158 atomic_init(&thread->join_state, THREAD_DETACHED);
159 }
160
Elliott Hughes8aecba72017-10-17 15:34:41 -0700161 // Set the scheduling policy/priority of the thread if necessary.
162 bool need_set = true;
163 int policy;
164 sched_param param;
Elliott Hughes38f01e02017-10-27 15:28:54 -0700165 if ((thread->attr.flags & PTHREAD_ATTR_FLAG_INHERIT) != 0) {
Elliott Hughes8aecba72017-10-17 15:34:41 -0700166 // Unless the parent has SCHED_RESET_ON_FORK set, we've already inherited from the parent.
167 policy = sched_getscheduler(0);
168 need_set = ((policy & SCHED_RESET_ON_FORK) != 0);
169 if (need_set) {
170 if (policy == -1) {
171 async_safe_format_log(ANDROID_LOG_WARN, "libc",
172 "pthread_create sched_getscheduler failed: %s", strerror(errno));
173 return errno;
174 }
175 if (sched_getparam(0, &param) == -1) {
176 async_safe_format_log(ANDROID_LOG_WARN, "libc",
177 "pthread_create sched_getparam failed: %s", strerror(errno));
178 return errno;
179 }
180 }
181 } else {
182 policy = thread->attr.sched_policy;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800183 param.sched_priority = thread->attr.sched_priority;
Elliott Hughes8aecba72017-10-17 15:34:41 -0700184 }
Elliott Hughes38f01e02017-10-27 15:28:54 -0700185 // Backwards compatibility: before P, Android didn't have pthread_attr_setinheritsched,
186 // and our behavior was neither of the POSIX behaviors.
187 if ((thread->attr.flags & (PTHREAD_ATTR_FLAG_INHERIT|PTHREAD_ATTR_FLAG_EXPLICIT)) == 0) {
188 need_set = (thread->attr.sched_policy != SCHED_NORMAL);
189 }
Elliott Hughes8aecba72017-10-17 15:34:41 -0700190 if (need_set) {
191 if (sched_setscheduler(thread->tid, policy, &param) == -1) {
192 async_safe_format_log(ANDROID_LOG_WARN, "libc",
193 "pthread_create sched_setscheduler(%d, {%d}) call failed: %s", policy,
194 param.sched_priority, strerror(errno));
Josh Gaob36efa42016-09-15 13:55:41 -0700195#if defined(__LP64__)
Elliott Hughes98624c32013-10-15 16:51:17 -0700196 // For backwards compatibility reasons, we only report failures on 64-bit devices.
Elliott Hughes8aecba72017-10-17 15:34:41 -0700197 return errno;
Elliott Hughes98624c32013-10-15 16:51:17 -0700198#endif
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800199 }
200 }
201
Elliott Hughes8aecba72017-10-17 15:34:41 -0700202 return 0;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800203}
204
Ryan Prichard45d13492019-01-03 02:51:30 -0800205
206// Allocate a thread's primary mapping. This mapping includes static TLS and
207// optionally a stack. Static TLS includes ELF TLS segments and the bionic_tls
208// struct.
209//
210// The stack_guard_size must be a multiple of the PAGE_SIZE.
211ThreadMapping __allocate_thread_mapping(size_t stack_size, size_t stack_guard_size) {
212 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
213
214 // Allocate in order: stack guard, stack, static TLS, guard page.
215 size_t mmap_size;
216 if (__builtin_add_overflow(stack_size, stack_guard_size, &mmap_size)) return {};
217 if (__builtin_add_overflow(mmap_size, layout.size(), &mmap_size)) return {};
218 if (__builtin_add_overflow(mmap_size, PTHREAD_GUARD_SIZE, &mmap_size)) return {};
219
220 // Align the result to a page size.
221 const size_t unaligned_size = mmap_size;
222 mmap_size = __BIONIC_ALIGN(mmap_size, PAGE_SIZE);
223 if (mmap_size < unaligned_size) return {};
224
225 // Create a new private anonymous map. Make the entire mapping PROT_NONE, then carve out a
226 // read+write area in the middle.
227 const int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
228 char* const space = static_cast<char*>(mmap(nullptr, mmap_size, PROT_NONE, flags, -1, 0));
Yabin Cuiba8dfc22015-01-06 09:31:00 -0800229 if (space == MAP_FAILED) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700230 async_safe_format_log(ANDROID_LOG_WARN,
Ryan Prichard45d13492019-01-03 02:51:30 -0800231 "libc",
232 "pthread_create failed: couldn't allocate %zu-bytes mapped space: %s",
233 mmap_size, strerror(errno));
234 return {};
235 }
236 const size_t writable_size = mmap_size - stack_guard_size - PTHREAD_GUARD_SIZE;
237 if (mprotect(space + stack_guard_size,
238 writable_size,
239 PROT_READ | PROT_WRITE) != 0) {
240 async_safe_format_log(ANDROID_LOG_WARN, "libc",
241 "pthread_create failed: couldn't mprotect R+W %zu-byte thread mapping region: %s",
242 writable_size, strerror(errno));
243 munmap(space, mmap_size);
244 return {};
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800245 }
246
Ryan Prichard45d13492019-01-03 02:51:30 -0800247 ThreadMapping result = {};
248 result.mmap_base = space;
249 result.mmap_size = mmap_size;
250 result.static_tls = space + mmap_size - PTHREAD_GUARD_SIZE - layout.size();
251 result.stack_base = space;
252 result.stack_top = result.static_tls;
253 return result;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800254}
255
Ryan Prichard45d13492019-01-03 02:51:30 -0800256static int __allocate_thread(pthread_attr_t* attr, bionic_tcb** tcbp, void** child_stack) {
257 ThreadMapping mapping;
258 char* stack_top;
259 bool stack_clean = false;
Yabin Cui6a7aaf42014-12-22 19:17:33 -0800260
Yi Kong32bc0fc2018-08-02 17:31:13 -0700261 if (attr->stack_base == nullptr) {
Yabin Cui8cf1b302014-12-03 21:36:24 -0800262 // The caller didn't provide a stack, so allocate one.
Ryan Prichard45d13492019-01-03 02:51:30 -0800263
264 // Make sure the guard size is a multiple of PAGE_SIZE.
265 const size_t unaligned_guard_size = attr->guard_size;
Dan Alberta613d0d2017-10-05 16:39:33 -0700266 attr->guard_size = __BIONIC_ALIGN(attr->guard_size, PAGE_SIZE);
Ryan Prichard45d13492019-01-03 02:51:30 -0800267 if (attr->guard_size < unaligned_guard_size) return EAGAIN;
268
269 mapping = __allocate_thread_mapping(attr->stack_size, attr->guard_size);
270 if (mapping.mmap_base == nullptr) return EAGAIN;
271
272 stack_top = mapping.stack_top;
273 attr->stack_base = mapping.stack_base;
274 stack_clean = true;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800275 } else {
Ryan Prichard45d13492019-01-03 02:51:30 -0800276 mapping = __allocate_thread_mapping(0, PTHREAD_GUARD_SIZE);
277 if (mapping.mmap_base == nullptr) return EAGAIN;
278
279 stack_top = static_cast<char*>(attr->stack_base) + attr->stack_size;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800280 }
281
Ryan Prichard45d13492019-01-03 02:51:30 -0800282 // Carve out space from the stack for the thread's pthread_internal_t. This
283 // memory isn't counted in pthread_attr_getstacksize.
Yabin Cuia2db50d2015-03-20 10:58:04 -0700284
285 // 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 -0800286 stack_top = align_down(stack_top - sizeof(pthread_internal_t), 16);
Yabin Cuia2db50d2015-03-20 10:58:04 -0700287
Yabin Cui8cf1b302014-12-03 21:36:24 -0800288 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(stack_top);
Ryan Prichard45d13492019-01-03 02:51:30 -0800289 if (!stack_clean) {
Yabin Cui304348a2015-12-03 13:01:42 -0800290 // If thread was not allocated by mmap(), it may not have been cleared to zero.
291 // So assume the worst and zero it.
292 memset(thread, 0, sizeof(pthread_internal_t));
293 }
Yabin Cui8cf1b302014-12-03 21:36:24 -0800294
Ryan Prichard45d13492019-01-03 02:51:30 -0800295 // Locate static TLS structures within the mapped region.
296 const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
297 auto tcb = reinterpret_cast<bionic_tcb*>(mapping.static_tls + layout.offset_bionic_tcb());
298 auto tls = reinterpret_cast<bionic_tls*>(mapping.static_tls + layout.offset_bionic_tls());
299
Ryan Prichard361c1b42019-01-15 13:45:27 -0800300 // Initialize TLS memory.
301 __init_static_tls(mapping.static_tls);
Ryan Prichard45d13492019-01-03 02:51:30 -0800302 __init_tcb(tcb, thread);
Ryan Prichard16455b52019-01-18 01:00:59 -0800303 __init_tcb_dtv(tcb);
Ryan Prichard45d13492019-01-03 02:51:30 -0800304 __init_tcb_stack_guard(tcb);
305 __init_bionic_tls_ptrs(tcb, tls);
306
307 attr->stack_size = stack_top - static_cast<char*>(attr->stack_base);
Yabin Cui8cf1b302014-12-03 21:36:24 -0800308 thread->attr = *attr;
Ryan Prichard45d13492019-01-03 02:51:30 -0800309 thread->mmap_base = mapping.mmap_base;
310 thread->mmap_size = mapping.mmap_size;
Ryan Prichard9cfca862018-11-22 02:44:09 -0800311
Ryan Prichard45d13492019-01-03 02:51:30 -0800312 *tcbp = tcb;
Yabin Cui8cf1b302014-12-03 21:36:24 -0800313 *child_stack = stack_top;
314 return 0;
315}
316
Evgenii Stepanov13e8dcb2018-09-19 16:29:12 -0700317__attribute__((no_sanitize("hwaddress")))
Elliott Hughese48b6852013-11-15 14:57:45 -0800318static int __pthread_start(void* arg) {
319 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(arg);
320
Evgenii Stepanov13e8dcb2018-09-19 16:29:12 -0700321 __hwasan_thread_enter();
322
Elliott Hughese48b6852013-11-15 14:57:45 -0800323 // Wait for our creating thread to release us. This lets it have time to
324 // notify gdb about this thread before we start doing anything.
325 // This also provides the memory barrier needed to ensure that all memory
326 // accesses previously made by the creating thread are visible to us.
Yabin Cuid26e7802015-10-22 20:07:56 -0700327 thread->startup_handshake_lock.lock();
Elliott Hughese48b6852013-11-15 14:57:45 -0800328
Peter Collingbourneda772e22018-09-06 22:20:44 -0700329 __init_additional_stacks(thread);
Elliott Hughese48b6852013-11-15 14:57:45 -0800330
Elliott Hughese48b6852013-11-15 14:57:45 -0800331 void* result = thread->start_routine(thread->start_routine_arg);
332 pthread_exit(result);
333
334 return 0;
335}
336
Elliott Hughescef3fae2013-11-19 16:52:24 -0800337// A dummy start routine for pthread_create failures where we've created a thread but aren't
338// going to run user code on it. We swap out the user's start routine for this and take advantage
339// of the regular thread teardown to free up resources.
340static void* __do_nothing(void*) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700341 return nullptr;
Elliott Hughescef3fae2013-11-19 16:52:24 -0800342}
343
dimitryfa432522017-10-25 13:07:45 +0200344
345__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800346int pthread_create(pthread_t* thread_out, pthread_attr_t const* attr,
347 void* (*start_routine)(void*), void* arg) {
348 ErrnoRestorer errno_restorer;
349
Yabin Cui8cf1b302014-12-03 21:36:24 -0800350 pthread_attr_t thread_attr;
Philip Cuadra77d0f902019-01-25 10:39:25 -0800351 ScopedTrace trace("pthread_create");
Yi Kong32bc0fc2018-08-02 17:31:13 -0700352 if (attr == nullptr) {
Yabin Cui8cf1b302014-12-03 21:36:24 -0800353 pthread_attr_init(&thread_attr);
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800354 } else {
Yabin Cui8cf1b302014-12-03 21:36:24 -0800355 thread_attr = *attr;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700356 attr = nullptr; // Prevent misuse below.
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800357 }
358
Ryan Prichard45d13492019-01-03 02:51:30 -0800359 bionic_tcb* tcb = nullptr;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700360 void* child_stack = nullptr;
Ryan Prichard45d13492019-01-03 02:51:30 -0800361 int result = __allocate_thread(&thread_attr, &tcb, &child_stack);
Yabin Cui8cf1b302014-12-03 21:36:24 -0800362 if (result != 0) {
363 return result;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800364 }
365
Ryan Prichard45d13492019-01-03 02:51:30 -0800366 pthread_internal_t* thread = tcb->thread();
367
Yabin Cuid26e7802015-10-22 20:07:56 -0700368 // Create a lock for the thread to wait on once it starts so we can keep
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800369 // it from doing anything until after we notify the debugger about it
370 //
371 // This also provides the memory barrier we need to ensure that all
372 // memory accesses previously performed by this thread are visible to
373 // the new thread.
Yabin Cuid26e7802015-10-22 20:07:56 -0700374 thread->startup_handshake_lock.init(false);
375 thread->startup_handshake_lock.lock();
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800376
Elliott Hughes70b24b12013-11-15 11:51:07 -0800377 thread->start_routine = start_routine;
378 thread->start_routine_arg = arg;
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800379
Elliott Hughes7086ad62014-06-19 16:39:01 -0700380 thread->set_cached_pid(getpid());
381
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800382 int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM |
383 CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
Ryan Prichard45d13492019-01-03 02:51:30 -0800384 void* tls = &tcb->tls_slot(0);
Elliott Hughes80906142013-11-26 13:57:21 -0800385#if defined(__i386__)
386 // 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 -0700387 // a pointer to the TLS itself.
388 user_desc tls_descriptor;
389 __init_user_desc(&tls_descriptor, false, tls);
390 tls = &tls_descriptor;
Elliott Hughes80906142013-11-26 13:57:21 -0800391#endif
Elliott Hughes0d236aa2014-05-09 14:42:16 -0700392 int rc = clone(__pthread_start, child_stack, flags, thread, &(thread->tid), tls, &(thread->tid));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800393 if (rc == -1) {
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800394 int clone_errno = errno;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800395 // We don't have to unlock the mutex at all because clone(2) failed so there's no child waiting to
396 // be unblocked, but we're about to unmap the memory the mutex is stored in, so this serves as a
397 // reminder that you can't rewrite this function to use a ScopedPthreadMutexLocker.
Yabin Cuid26e7802015-10-22 20:07:56 -0700398 thread->startup_handshake_lock.unlock();
Elliott Hughes7484c212017-02-02 02:41:38 +0000399 if (thread->mmap_size != 0) {
Ryan Prichard45d13492019-01-03 02:51:30 -0800400 munmap(thread->mmap_base, thread->mmap_size);
Elliott Hughes7484c212017-02-02 02:41:38 +0000401 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700402 async_safe_format_log(ANDROID_LOG_WARN, "libc", "pthread_create failed: clone failed: %s",
dimitry6de60872017-08-14 14:42:19 +0200403 strerror(clone_errno));
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800404 return clone_errno;
405 }
406
Yabin Cui673b15e2015-03-19 14:19:19 -0700407 int init_errno = __init_thread(thread);
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800408 if (init_errno != 0) {
Elliott Hughescef3fae2013-11-19 16:52:24 -0800409 // Mark the thread detached and replace its start_routine with a no-op.
410 // Letting the thread run is the easiest way to clean up its resources.
Yabin Cui58cf31b2015-03-06 17:23:53 -0800411 atomic_store(&thread->join_state, THREAD_DETACHED);
Elliott Hughes7484c212017-02-02 02:41:38 +0000412 __pthread_internal_add(thread);
Elliott Hughescef3fae2013-11-19 16:52:24 -0800413 thread->start_routine = __do_nothing;
Yabin Cuid26e7802015-10-22 20:07:56 -0700414 thread->startup_handshake_lock.unlock();
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800415 return init_errno;
416 }
417
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800418 // Publish the pthread_t and unlock the mutex to let the new thread start running.
Elliott Hughes7484c212017-02-02 02:41:38 +0000419 *thread_out = __pthread_internal_add(thread);
Yabin Cuid26e7802015-10-22 20:07:56 -0700420 thread->startup_handshake_lock.unlock();
Elliott Hughes4b4a8822013-02-12 17:15:59 -0800421
422 return 0;
423}