pthread_create.cpp revision 8cf1b305670123aed7638d984ca39bfd22388440
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 <sys/mman.h> 33#include <unistd.h> 34 35#include "pthread_internal.h" 36 37#include "private/bionic_macros.h" 38#include "private/bionic_prctl.h" 39#include "private/bionic_ssp.h" 40#include "private/bionic_tls.h" 41#include "private/libc_logging.h" 42#include "private/ErrnoRestorer.h" 43#include "private/ScopedPthreadMutexLocker.h" 44 45// x86 uses segment descriptors rather than a direct pointer to TLS. 46#if __i386__ 47#include <asm/ldt.h> 48extern "C" __LIBC_HIDDEN__ void __init_user_desc(struct user_desc*, int, void*); 49#endif 50 51extern "C" int __isthreaded; 52 53// This code is used both by each new pthread and the code that initializes the main thread. 54void __init_tls(pthread_internal_t* thread) { 55 if (thread->user_allocated_stack()) { 56 // We don't know where the user got their stack, so assume the worst and zero the TLS area. 57 memset(&thread->tls[0], 0, BIONIC_TLS_SLOTS * sizeof(void*)); 58 } 59 60 // Slot 0 must point to itself. The x86 Linux kernel reads the TLS from %fs:0. 61 thread->tls[TLS_SLOT_SELF] = thread->tls; 62 thread->tls[TLS_SLOT_THREAD_ID] = thread; 63 // GCC looks in the TLS for the stack guard on x86, so copy it there from our global. 64 thread->tls[TLS_SLOT_STACK_GUARD] = (void*) __stack_chk_guard; 65} 66 67void __init_alternate_signal_stack(pthread_internal_t* thread) { 68 // Create and set an alternate signal stack. 69 stack_t ss; 70 ss.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 71 if (ss.ss_sp != MAP_FAILED) { 72 ss.ss_size = SIGSTKSZ; 73 ss.ss_flags = 0; 74 sigaltstack(&ss, NULL); 75 thread->alternate_signal_stack = ss.ss_sp; 76 77 // We can only use const static allocated string for mapped region name, as Android kernel 78 // uses the string pointer directly when dumping /proc/pid/maps. 79 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ss.ss_sp, ss.ss_size, "thread signal stack"); 80 } 81} 82 83int __init_thread(pthread_internal_t* thread, bool add_to_thread_list) { 84 int error = 0; 85 86 // Set the scheduling policy/priority of the thread. 87 if (thread->attr.sched_policy != SCHED_NORMAL) { 88 sched_param param; 89 param.sched_priority = thread->attr.sched_priority; 90 if (sched_setscheduler(thread->tid, thread->attr.sched_policy, ¶m) == -1) { 91#if __LP64__ 92 // For backwards compatibility reasons, we only report failures on 64-bit devices. 93 error = errno; 94#endif 95 __libc_format_log(ANDROID_LOG_WARN, "libc", 96 "pthread_create sched_setscheduler call failed: %s", strerror(errno)); 97 } 98 } 99 100 thread->cleanup_stack = NULL; 101 102 if (add_to_thread_list) { 103 _pthread_internal_add(thread); 104 } 105 106 return error; 107} 108 109static void* __create_thread_stack(const pthread_attr_t& attr) { 110 // Create a new private anonymous map. 111 int prot = PROT_READ | PROT_WRITE; 112 int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE; 113 void* stack = mmap(NULL, attr.stack_size, prot, flags, -1, 0); 114 if (stack == MAP_FAILED) { 115 __libc_format_log(ANDROID_LOG_WARN, 116 "libc", 117 "pthread_create failed: couldn't allocate %zd-byte stack: %s", 118 attr.stack_size, strerror(errno)); 119 return NULL; 120 } 121 122 // Set the guard region at the end of the stack to PROT_NONE. 123 if (mprotect(stack, attr.guard_size, PROT_NONE) == -1) { 124 __libc_format_log(ANDROID_LOG_WARN, "libc", 125 "pthread_create failed: couldn't mprotect PROT_NONE %zd-byte stack guard region: %s", 126 attr.guard_size, strerror(errno)); 127 munmap(stack, attr.stack_size); 128 return NULL; 129 } 130 131 return stack; 132} 133 134static int __allocate_thread(pthread_attr_t* attr, pthread_internal_t** threadp, void** child_stack) { 135 if (attr->stack_base == NULL) { 136 // The caller didn't provide a stack, so allocate one. 137 // Make sure the stack size and guard size are multiples of PAGE_SIZE. 138 attr->stack_size = BIONIC_ALIGN(attr->stack_size, PAGE_SIZE); 139 attr->guard_size = BIONIC_ALIGN(attr->guard_size, PAGE_SIZE); 140 attr->stack_base = __create_thread_stack(*attr); 141 if (attr->stack_base == NULL) { 142 return EAGAIN; 143 } 144 } else { 145 // The caller did provide a stack, so remember we're not supposed to free it. 146 attr->flags |= PTHREAD_ATTR_FLAG_USER_ALLOCATED_STACK; 147 } 148 149 // Thread stack is used for two sections: 150 // pthread_internal_t. 151 // regular stack, from top to down. 152 uint8_t* stack_top = reinterpret_cast<uint8_t*>(attr->stack_base) + attr->stack_size; 153 stack_top -= sizeof(pthread_internal_t); 154 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(stack_top); 155 156 // No need to check stack_top alignment. The size of pthread_internal_t is 16-bytes aligned, 157 // and user allocated stack is guaranteed by pthread_attr_setstack. 158 159 thread->attr = *attr; 160 __init_tls(thread); 161 162 *threadp = thread; 163 *child_stack = stack_top; 164 return 0; 165} 166 167static int __pthread_start(void* arg) { 168 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(arg); 169 170 // Wait for our creating thread to release us. This lets it have time to 171 // notify gdb about this thread before we start doing anything. 172 // This also provides the memory barrier needed to ensure that all memory 173 // accesses previously made by the creating thread are visible to us. 174 pthread_mutex_lock(&thread->startup_handshake_mutex); 175 pthread_mutex_destroy(&thread->startup_handshake_mutex); 176 177 __init_alternate_signal_stack(thread); 178 179 void* result = thread->start_routine(thread->start_routine_arg); 180 pthread_exit(result); 181 182 return 0; 183} 184 185// A dummy start routine for pthread_create failures where we've created a thread but aren't 186// going to run user code on it. We swap out the user's start routine for this and take advantage 187// of the regular thread teardown to free up resources. 188static void* __do_nothing(void*) { 189 return NULL; 190} 191 192int pthread_create(pthread_t* thread_out, pthread_attr_t const* attr, 193 void* (*start_routine)(void*), void* arg) { 194 ErrnoRestorer errno_restorer; 195 196 // Inform the rest of the C library that at least one thread was created. 197 __isthreaded = 1; 198 199 pthread_attr_t thread_attr; 200 if (attr == NULL) { 201 pthread_attr_init(&thread_attr); 202 } else { 203 thread_attr = *attr; 204 attr = NULL; // Prevent misuse below. 205 } 206 207 pthread_internal_t* thread = NULL; 208 void* child_stack = NULL; 209 int result = __allocate_thread(&thread_attr, &thread, &child_stack); 210 if (result != 0) { 211 return result; 212 } 213 214 // Create a mutex for the thread in TLS to wait on once it starts so we can keep 215 // it from doing anything until after we notify the debugger about it 216 // 217 // This also provides the memory barrier we need to ensure that all 218 // memory accesses previously performed by this thread are visible to 219 // the new thread. 220 pthread_mutex_init(&thread->startup_handshake_mutex, NULL); 221 pthread_mutex_lock(&thread->startup_handshake_mutex); 222 223 thread->start_routine = start_routine; 224 thread->start_routine_arg = arg; 225 226 thread->set_cached_pid(getpid()); 227 228 int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | 229 CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID; 230 void* tls = reinterpret_cast<void*>(thread->tls); 231#if defined(__i386__) 232 // On x86 (but not x86-64), CLONE_SETTLS takes a pointer to a struct user_desc rather than 233 // a pointer to the TLS itself. 234 user_desc tls_descriptor; 235 __init_user_desc(&tls_descriptor, false, tls); 236 tls = &tls_descriptor; 237#endif 238 int rc = clone(__pthread_start, child_stack, flags, thread, &(thread->tid), tls, &(thread->tid)); 239 if (rc == -1) { 240 int clone_errno = errno; 241 // We don't have to unlock the mutex at all because clone(2) failed so there's no child waiting to 242 // be unblocked, but we're about to unmap the memory the mutex is stored in, so this serves as a 243 // reminder that you can't rewrite this function to use a ScopedPthreadMutexLocker. 244 pthread_mutex_unlock(&thread->startup_handshake_mutex); 245 if (!thread->user_allocated_stack()) { 246 munmap(thread->attr.stack_base, thread->attr.stack_size); 247 } 248 __libc_format_log(ANDROID_LOG_WARN, "libc", "pthread_create failed: clone failed: %s", strerror(errno)); 249 return clone_errno; 250 } 251 252 int init_errno = __init_thread(thread, true); 253 if (init_errno != 0) { 254 // Mark the thread detached and replace its start_routine with a no-op. 255 // Letting the thread run is the easiest way to clean up its resources. 256 thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED; 257 thread->start_routine = __do_nothing; 258 pthread_mutex_unlock(&thread->startup_handshake_mutex); 259 return init_errno; 260 } 261 262 // Publish the pthread_t and unlock the mutex to let the new thread start running. 263 *thread_out = reinterpret_cast<pthread_t>(thread); 264 pthread_mutex_unlock(&thread->startup_handshake_mutex); 265 266 return 0; 267} 268