blob: 14cc7da489488e4e46432cfb2d0d039ac033eb7c [file] [log] [blame]
Elliott Hughes7484c212017-02-02 02:41:38 +00001/*
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_internal.h"
30
31#include <errno.h>
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070032#include <semaphore.h>
Elliott Hughes7484c212017-02-02 02:41:38 +000033#include <stdlib.h>
34#include <string.h>
35#include <sys/mman.h>
Florian Mayerc0aa70a2024-06-24 15:49:20 -070036#include <sys/prctl.h>
Elliott Hughes7484c212017-02-02 02:41:38 +000037
Christopher Ferris7a3681e2017-04-24 17:48:32 -070038#include <async_safe/log.h>
Florian Mayera586ba72024-06-20 13:43:36 -070039#include <bionic/mte.h>
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070040#include <bionic/reserved_signals.h>
Florian Mayera586ba72024-06-20 13:43:36 -070041#include <bionic/tls_defines.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070042
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070043#include "private/ErrnoRestorer.h"
Ryan Prichardc86576c2019-01-09 03:09:42 -080044#include "private/ScopedRWLock.h"
Elliott Hughes7484c212017-02-02 02:41:38 +000045#include "private/bionic_futex.h"
Florian Mayere65e1932024-02-15 22:20:54 +000046#include "private/bionic_globals.h"
Elliott Hughes7484c212017-02-02 02:41:38 +000047#include "private/bionic_tls.h"
Elliott Hughes7484c212017-02-02 02:41:38 +000048
Elliott Hughes11859d42017-02-13 17:59:29 -080049static pthread_internal_t* g_thread_list = nullptr;
50static pthread_rwlock_t g_thread_list_lock = PTHREAD_RWLOCK_INITIALIZER;
51
Elliott Hughes7484c212017-02-02 02:41:38 +000052pthread_t __pthread_internal_add(pthread_internal_t* thread) {
Elliott Hughes11859d42017-02-13 17:59:29 -080053 ScopedWriteLock locker(&g_thread_list_lock);
Elliott Hughes7484c212017-02-02 02:41:38 +000054
55 // We insert at the head.
56 thread->next = g_thread_list;
Elliott Hughes11859d42017-02-13 17:59:29 -080057 thread->prev = nullptr;
58 if (thread->next != nullptr) {
Elliott Hughes7484c212017-02-02 02:41:38 +000059 thread->next->prev = thread;
60 }
61 g_thread_list = thread;
62 return reinterpret_cast<pthread_t>(thread);
63}
64
65void __pthread_internal_remove(pthread_internal_t* thread) {
Elliott Hughes11859d42017-02-13 17:59:29 -080066 ScopedWriteLock locker(&g_thread_list_lock);
Elliott Hughes7484c212017-02-02 02:41:38 +000067
Elliott Hughes11859d42017-02-13 17:59:29 -080068 if (thread->next != nullptr) {
Elliott Hughes7484c212017-02-02 02:41:38 +000069 thread->next->prev = thread->prev;
70 }
Elliott Hughes11859d42017-02-13 17:59:29 -080071 if (thread->prev != nullptr) {
Elliott Hughes7484c212017-02-02 02:41:38 +000072 thread->prev->next = thread->next;
73 } else {
74 g_thread_list = thread->next;
75 }
76}
77
78static void __pthread_internal_free(pthread_internal_t* thread) {
Florian Mayerc0aa70a2024-06-24 15:49:20 -070079#ifdef __aarch64__
80 if (void* stack_mte_tls = thread->bionic_tcb->tls_slot(TLS_SLOT_STACK_MTE)) {
81 size_t size =
Florian Mayera586ba72024-06-20 13:43:36 -070082 stack_mte_ringbuffer_size_from_pointer(reinterpret_cast<uintptr_t>(stack_mte_tls));
Florian Mayerc0aa70a2024-06-24 15:49:20 -070083 void* ptr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(stack_mte_tls) &
84 ((1ULL << 56ULL) - 1ULL));
85 munmap(ptr, size);
86 }
87#endif
Elliott Hughes7484c212017-02-02 02:41:38 +000088 if (thread->mmap_size != 0) {
89 // Free mapped space, including thread stack and pthread_internal_t.
Ryan Prichard45d13492019-01-03 02:51:30 -080090 munmap(thread->mmap_base, thread->mmap_size);
Elliott Hughes7484c212017-02-02 02:41:38 +000091 }
92}
93
94void __pthread_internal_remove_and_free(pthread_internal_t* thread) {
95 __pthread_internal_remove(thread);
96 __pthread_internal_free(thread);
97}
98
Elliott Hughes5bb113c2019-02-01 16:31:10 -080099pid_t __pthread_internal_gettid(pthread_t thread_id, const char* caller) {
100 pthread_internal_t* thread = __pthread_internal_find(thread_id, caller);
101 return thread ? thread->tid : -1;
102}
103
104pthread_internal_t* __pthread_internal_find(pthread_t thread_id, const char* caller) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000105 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(thread_id);
106
Elliott Hughes11859d42017-02-13 17:59:29 -0800107 // Check if we're looking for ourselves before acquiring the lock.
108 if (thread == __get_thread()) return thread;
109
Christopher Ferris79829142017-09-18 14:39:33 -0700110 {
111 // Make sure to release the lock before the abort below. Otherwise,
112 // some apps might deadlock in their own crash handlers (see b/6565627).
113 ScopedReadLock locker(&g_thread_list_lock);
114 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
115 if (t == thread) return thread;
116 }
Elliott Hughes7484c212017-02-02 02:41:38 +0000117 }
118
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800119 // Historically we'd return null, but from API level 26 we catch this error.
120 if (android_get_application_target_sdk_version() >= 26) {
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800121 if (thread == nullptr) {
122 // This seems to be a common mistake, and it's relatively harmless because
123 // there will never be a valid thread at address 0, whereas other invalid
124 // addresses might sometimes contain threads or things that look enough like
125 // threads for us to do some real damage by continuing.
126 // TODO: try getting rid of this when Treble lets us keep vendor blobs on an old API level.
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800127 async_safe_format_log(ANDROID_LOG_WARN, "libc", "invalid pthread_t (0) passed to %s", caller);
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800128 } else {
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800129 async_safe_fatal("invalid pthread_t %p passed to %s", thread, caller);
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800130 }
Elliott Hughes7484c212017-02-02 02:41:38 +0000131 }
Elliott Hughes11859d42017-02-13 17:59:29 -0800132 return nullptr;
Elliott Hughes7484c212017-02-02 02:41:38 +0000133}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700134
Florian Mayere65e1932024-02-15 22:20:54 +0000135static uintptr_t __get_main_stack_startstack() {
136 FILE* fp = fopen("/proc/self/stat", "re");
137 if (fp == nullptr) {
138 async_safe_fatal("couldn't open /proc/self/stat: %m");
139 }
140
141 char line[BUFSIZ];
142 if (fgets(line, sizeof(line), fp) == nullptr) {
143 async_safe_fatal("couldn't read /proc/self/stat: %m");
144 }
145
146 fclose(fp);
147
148 // See man 5 proc. There's no reason comm can't contain ' ' or ')',
149 // so we search backwards for the end of it. We're looking for this field:
150 //
151 // startstack %lu (28) The address of the start (i.e., bottom) of the stack.
152 uintptr_t startstack = 0;
153 const char* end_of_comm = strrchr(line, ')');
154 if (sscanf(end_of_comm + 1,
155 " %*c "
156 "%*d %*d %*d %*d %*d "
157 "%*u %*u %*u %*u %*u %*u %*u "
158 "%*d %*d %*d %*d %*d %*d "
159 "%*u %*u %*d %*u %*u %*u %" SCNuPTR,
160 &startstack) != 1) {
161 async_safe_fatal("couldn't parse /proc/self/stat");
162 }
163
164 return startstack;
165}
166
167void __find_main_stack_limits(uintptr_t* low, uintptr_t* high) {
168 // Ask the kernel where our main thread's stack started.
169 uintptr_t startstack = __get_main_stack_startstack();
170
171 // Hunt for the region that contains that address.
172 FILE* fp = fopen("/proc/self/maps", "re");
173 if (fp == nullptr) {
174 async_safe_fatal("couldn't open /proc/self/maps: %m");
175 }
176 char line[BUFSIZ];
177 while (fgets(line, sizeof(line), fp) != nullptr) {
178 uintptr_t lo, hi;
179 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR, &lo, &hi) == 2) {
180 if (lo <= startstack && startstack <= hi) {
181 *low = lo;
182 *high = hi;
183 fclose(fp);
184 return;
185 }
186 }
187 }
188 async_safe_fatal("stack not found in /proc/self/maps");
189}
190
Florian Mayera586ba72024-06-20 13:43:36 -0700191#if defined(__aarch64__)
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700192__LIBC_HIDDEN__ void* __allocate_stack_mte_ringbuffer(size_t n, pthread_internal_t* thread) {
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700193 const char* name;
194 if (thread == nullptr) {
195 name = "stack_mte_ring:main";
196 } else {
197 // The kernel doesn't copy the name string, but this variable will last at least as long as the
198 // mapped area. We unmap the ring buffer before unmapping the rest of the thread storage.
199 auto& name_buffer = thread->stack_mte_ringbuffer_vma_name_buffer;
200 static_assert(arraysize(name_buffer) >= arraysize("stack_mte_ring:") + 11 + 1);
201 async_safe_format_buffer(name_buffer, arraysize(name_buffer), "stack_mte_ring:%d", thread->tid);
202 name = name_buffer;
203 }
Florian Mayera586ba72024-06-20 13:43:36 -0700204 void* ret = stack_mte_ringbuffer_allocate(n, name);
205 if (!ret) async_safe_fatal("error: failed to allocate stack mte ring buffer");
206 return ret;
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700207}
Florian Mayera586ba72024-06-20 13:43:36 -0700208#endif
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700209
Mitch Phillipsf7c5e682024-06-20 14:10:57 +0200210bool __pthread_internal_remap_stack_with_mte() {
Florian Mayere65e1932024-02-15 22:20:54 +0000211#if defined(__aarch64__)
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700212 ScopedWriteLock creation_locker(&g_thread_creation_lock);
213 ScopedReadLock list_locker(&g_thread_list_lock);
214 // If process already uses memtag-stack ABI, we don't need to do anything.
215 if (__libc_memtag_stack_abi) return false;
216 __libc_memtag_stack_abi = true;
217
218 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
219 if (t->terminating) continue;
220 t->bionic_tcb->tls_slot(TLS_SLOT_STACK_MTE) =
221 __allocate_stack_mte_ringbuffer(0, t->is_main() ? nullptr : t);
222 }
Mitch Phillipsf7c5e682024-06-20 14:10:57 +0200223 if (!atomic_load(&__libc_globals->memtag)) return false;
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700224 if (atomic_exchange(&__libc_memtag_stack, true)) return false;
Florian Mayere65e1932024-02-15 22:20:54 +0000225 uintptr_t lo, hi;
226 __find_main_stack_limits(&lo, &hi);
227
228 if (mprotect(reinterpret_cast<void*>(lo), hi - lo,
229 PROT_READ | PROT_WRITE | PROT_MTE | PROT_GROWSDOWN)) {
230 async_safe_fatal("error: failed to set PROT_MTE on main thread");
231 }
Florian Mayere65e1932024-02-15 22:20:54 +0000232 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
233 if (t->terminating || t->is_main()) continue;
234 if (mprotect(t->mmap_base_unguarded, t->mmap_size_unguarded,
235 PROT_READ | PROT_WRITE | PROT_MTE)) {
236 async_safe_fatal("error: failed to set PROT_MTE on thread: %d", t->tid);
237 }
238 }
Mitch Phillipsf7c5e682024-06-20 14:10:57 +0200239 return true;
240#else
241 return false;
242#endif // defined(__aarch64__)
Florian Mayere65e1932024-02-15 22:20:54 +0000243}
244
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700245bool android_run_on_all_threads(bool (*func)(void*), void* arg) {
246 // Take the locks in this order to avoid inversion (pthread_create ->
247 // __pthread_internal_add).
248 ScopedWriteLock creation_locker(&g_thread_creation_lock);
249 ScopedReadLock list_locker(&g_thread_list_lock);
250
251 // Call the function directly for the current thread so that we don't need to worry about
252 // the consequences of synchronizing with ourselves.
253 if (!func(arg)) {
254 return false;
255 }
256
257 static sem_t g_sem;
258 if (sem_init(&g_sem, 0, 0) != 0) {
259 return false;
260 }
261
262 static bool (*g_func)(void*);
263 static void *g_arg;
264 g_func = func;
265 g_arg = arg;
266
267 static _Atomic(bool) g_retval;
268 atomic_init(&g_retval, true);
269
270 auto handler = [](int, siginfo_t*, void*) {
271 ErrnoRestorer restorer;
272 if (!g_func(g_arg)) {
273 atomic_store(&g_retval, false);
274 }
275 sem_post(&g_sem);
276 };
277
278 struct sigaction act = {}, oldact;
279 act.sa_flags = SA_SIGINFO;
280 act.sa_sigaction = handler;
281 sigfillset(&act.sa_mask);
282 if (sigaction(BIONIC_SIGNAL_RUN_ON_ALL_THREADS, &act, &oldact) != 0) {
283 sem_destroy(&g_sem);
284 return false;
285 }
286
287 pid_t my_pid = getpid();
288 size_t num_tids = 0;
289 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
290 // The function is called directly for the current thread above, so no need to send a signal to
291 // ourselves to call it here.
292 if (t == __get_thread()) continue;
293
294 // If a thread is terminating (has blocked signals) or has already terminated, our signal will
295 // never be received, so we need to check for that condition and skip the thread if it is the
296 // case.
297 if (atomic_load(&t->terminating)) continue;
298
299 if (tgkill(my_pid, t->tid, BIONIC_SIGNAL_RUN_ON_ALL_THREADS) == 0) {
300 ++num_tids;
301 } else {
302 atomic_store(&g_retval, false);
303 }
304 }
305
306 for (size_t i = 0; i != num_tids; ++i) {
307 if (TEMP_FAILURE_RETRY(sem_wait(&g_sem)) != 0) {
308 atomic_store(&g_retval, false);
309 break;
310 }
311 }
312
313 sigaction(BIONIC_SIGNAL_RUN_ON_ALL_THREADS, &oldact, 0);
314 sem_destroy(&g_sem);
315 return atomic_load(&g_retval);
316}