blob: 3bfb899cc4556041dc3bb2f85ea649275b314773 [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>
Florian Mayer756e7652024-11-08 15:35:43 -080037#include <sys/types.h>
Elliott Hughes7484c212017-02-02 02:41:38 +000038
Christopher Ferris7a3681e2017-04-24 17:48:32 -070039#include <async_safe/log.h>
Florian Mayera586ba72024-06-20 13:43:36 -070040#include <bionic/mte.h>
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070041#include <bionic/reserved_signals.h>
Florian Mayera586ba72024-06-20 13:43:36 -070042#include <bionic/tls_defines.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070043
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070044#include "private/ErrnoRestorer.h"
Ryan Prichardc86576c2019-01-09 03:09:42 -080045#include "private/ScopedRWLock.h"
Elliott Hughes7484c212017-02-02 02:41:38 +000046#include "private/bionic_futex.h"
Florian Mayere65e1932024-02-15 22:20:54 +000047#include "private/bionic_globals.h"
Elliott Hughes7484c212017-02-02 02:41:38 +000048#include "private/bionic_tls.h"
Elliott Hughes7484c212017-02-02 02:41:38 +000049
Elliott Hughes11859d42017-02-13 17:59:29 -080050static pthread_internal_t* g_thread_list = nullptr;
51static pthread_rwlock_t g_thread_list_lock = PTHREAD_RWLOCK_INITIALIZER;
52
Elliott Hughes7484c212017-02-02 02:41:38 +000053pthread_t __pthread_internal_add(pthread_internal_t* thread) {
Elliott Hughes11859d42017-02-13 17:59:29 -080054 ScopedWriteLock locker(&g_thread_list_lock);
Elliott Hughes7484c212017-02-02 02:41:38 +000055
56 // We insert at the head.
57 thread->next = g_thread_list;
Elliott Hughes11859d42017-02-13 17:59:29 -080058 thread->prev = nullptr;
59 if (thread->next != nullptr) {
Elliott Hughes7484c212017-02-02 02:41:38 +000060 thread->next->prev = thread;
61 }
62 g_thread_list = thread;
63 return reinterpret_cast<pthread_t>(thread);
64}
65
66void __pthread_internal_remove(pthread_internal_t* thread) {
Elliott Hughes11859d42017-02-13 17:59:29 -080067 ScopedWriteLock locker(&g_thread_list_lock);
Elliott Hughes7484c212017-02-02 02:41:38 +000068
Elliott Hughes11859d42017-02-13 17:59:29 -080069 if (thread->next != nullptr) {
Elliott Hughes7484c212017-02-02 02:41:38 +000070 thread->next->prev = thread->prev;
71 }
Elliott Hughes11859d42017-02-13 17:59:29 -080072 if (thread->prev != nullptr) {
Elliott Hughes7484c212017-02-02 02:41:38 +000073 thread->prev->next = thread->next;
74 } else {
75 g_thread_list = thread->next;
76 }
77}
78
79static void __pthread_internal_free(pthread_internal_t* thread) {
Florian Mayerc0aa70a2024-06-24 15:49:20 -070080#ifdef __aarch64__
81 if (void* stack_mte_tls = thread->bionic_tcb->tls_slot(TLS_SLOT_STACK_MTE)) {
Florian Mayer756e7652024-11-08 15:35:43 -080082 stack_mte_free_ringbuffer(reinterpret_cast<uintptr_t>(stack_mte_tls));
Florian Mayerc0aa70a2024-06-24 15:49:20 -070083 }
84#endif
Elliott Hughes7484c212017-02-02 02:41:38 +000085 if (thread->mmap_size != 0) {
86 // Free mapped space, including thread stack and pthread_internal_t.
Ryan Prichard45d13492019-01-03 02:51:30 -080087 munmap(thread->mmap_base, thread->mmap_size);
Elliott Hughes7484c212017-02-02 02:41:38 +000088 }
89}
90
91void __pthread_internal_remove_and_free(pthread_internal_t* thread) {
92 __pthread_internal_remove(thread);
93 __pthread_internal_free(thread);
94}
95
Elliott Hughes5bb113c2019-02-01 16:31:10 -080096pid_t __pthread_internal_gettid(pthread_t thread_id, const char* caller) {
97 pthread_internal_t* thread = __pthread_internal_find(thread_id, caller);
98 return thread ? thread->tid : -1;
99}
100
101pthread_internal_t* __pthread_internal_find(pthread_t thread_id, const char* caller) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000102 pthread_internal_t* thread = reinterpret_cast<pthread_internal_t*>(thread_id);
103
Elliott Hughes11859d42017-02-13 17:59:29 -0800104 // Check if we're looking for ourselves before acquiring the lock.
105 if (thread == __get_thread()) return thread;
106
Christopher Ferris79829142017-09-18 14:39:33 -0700107 {
108 // Make sure to release the lock before the abort below. Otherwise,
109 // some apps might deadlock in their own crash handlers (see b/6565627).
110 ScopedReadLock locker(&g_thread_list_lock);
111 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
112 if (t == thread) return thread;
113 }
Elliott Hughes7484c212017-02-02 02:41:38 +0000114 }
115
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800116 // Historically we'd return null, but from API level 26 we catch this error.
117 if (android_get_application_target_sdk_version() >= 26) {
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800118 if (thread == nullptr) {
119 // This seems to be a common mistake, and it's relatively harmless because
120 // there will never be a valid thread at address 0, whereas other invalid
121 // addresses might sometimes contain threads or things that look enough like
122 // threads for us to do some real damage by continuing.
123 // 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 -0800124 async_safe_format_log(ANDROID_LOG_WARN, "libc", "invalid pthread_t (0) passed to %s", caller);
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800125 } else {
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800126 async_safe_fatal("invalid pthread_t %p passed to %s", thread, caller);
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800127 }
Elliott Hughes7484c212017-02-02 02:41:38 +0000128 }
Elliott Hughes11859d42017-02-13 17:59:29 -0800129 return nullptr;
Elliott Hughes7484c212017-02-02 02:41:38 +0000130}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700131
Florian Mayere65e1932024-02-15 22:20:54 +0000132static uintptr_t __get_main_stack_startstack() {
133 FILE* fp = fopen("/proc/self/stat", "re");
134 if (fp == nullptr) {
135 async_safe_fatal("couldn't open /proc/self/stat: %m");
136 }
137
138 char line[BUFSIZ];
139 if (fgets(line, sizeof(line), fp) == nullptr) {
140 async_safe_fatal("couldn't read /proc/self/stat: %m");
141 }
142
143 fclose(fp);
144
145 // See man 5 proc. There's no reason comm can't contain ' ' or ')',
146 // so we search backwards for the end of it. We're looking for this field:
147 //
148 // startstack %lu (28) The address of the start (i.e., bottom) of the stack.
149 uintptr_t startstack = 0;
150 const char* end_of_comm = strrchr(line, ')');
151 if (sscanf(end_of_comm + 1,
152 " %*c "
153 "%*d %*d %*d %*d %*d "
154 "%*u %*u %*u %*u %*u %*u %*u "
155 "%*d %*d %*d %*d %*d %*d "
156 "%*u %*u %*d %*u %*u %*u %" SCNuPTR,
157 &startstack) != 1) {
158 async_safe_fatal("couldn't parse /proc/self/stat");
159 }
160
161 return startstack;
162}
163
164void __find_main_stack_limits(uintptr_t* low, uintptr_t* high) {
165 // Ask the kernel where our main thread's stack started.
166 uintptr_t startstack = __get_main_stack_startstack();
167
168 // Hunt for the region that contains that address.
169 FILE* fp = fopen("/proc/self/maps", "re");
170 if (fp == nullptr) {
171 async_safe_fatal("couldn't open /proc/self/maps: %m");
172 }
173 char line[BUFSIZ];
174 while (fgets(line, sizeof(line), fp) != nullptr) {
175 uintptr_t lo, hi;
176 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR, &lo, &hi) == 2) {
177 if (lo <= startstack && startstack <= hi) {
178 *low = lo;
179 *high = hi;
180 fclose(fp);
181 return;
182 }
183 }
184 }
185 async_safe_fatal("stack not found in /proc/self/maps");
186}
187
Florian Mayera586ba72024-06-20 13:43:36 -0700188#if defined(__aarch64__)
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700189__LIBC_HIDDEN__ void* __allocate_stack_mte_ringbuffer(size_t n, pthread_internal_t* thread) {
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700190 const char* name;
191 if (thread == nullptr) {
192 name = "stack_mte_ring:main";
193 } else {
194 // The kernel doesn't copy the name string, but this variable will last at least as long as the
195 // mapped area. We unmap the ring buffer before unmapping the rest of the thread storage.
196 auto& name_buffer = thread->stack_mte_ringbuffer_vma_name_buffer;
197 static_assert(arraysize(name_buffer) >= arraysize("stack_mte_ring:") + 11 + 1);
198 async_safe_format_buffer(name_buffer, arraysize(name_buffer), "stack_mte_ring:%d", thread->tid);
199 name = name_buffer;
200 }
Florian Mayera586ba72024-06-20 13:43:36 -0700201 void* ret = stack_mte_ringbuffer_allocate(n, name);
202 if (!ret) async_safe_fatal("error: failed to allocate stack mte ring buffer");
203 return ret;
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700204}
Florian Mayera586ba72024-06-20 13:43:36 -0700205#endif
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700206
Mitch Phillipsf7c5e682024-06-20 14:10:57 +0200207bool __pthread_internal_remap_stack_with_mte() {
Florian Mayere65e1932024-02-15 22:20:54 +0000208#if defined(__aarch64__)
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700209 ScopedWriteLock creation_locker(&g_thread_creation_lock);
210 ScopedReadLock list_locker(&g_thread_list_lock);
211 // If process already uses memtag-stack ABI, we don't need to do anything.
212 if (__libc_memtag_stack_abi) return false;
213 __libc_memtag_stack_abi = true;
214
215 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
216 if (t->terminating) continue;
217 t->bionic_tcb->tls_slot(TLS_SLOT_STACK_MTE) =
218 __allocate_stack_mte_ringbuffer(0, t->is_main() ? nullptr : t);
219 }
Mitch Phillipsf7c5e682024-06-20 14:10:57 +0200220 if (!atomic_load(&__libc_globals->memtag)) return false;
Florian Mayerc0aa70a2024-06-24 15:49:20 -0700221 if (atomic_exchange(&__libc_memtag_stack, true)) return false;
Florian Mayere65e1932024-02-15 22:20:54 +0000222 uintptr_t lo, hi;
223 __find_main_stack_limits(&lo, &hi);
224
225 if (mprotect(reinterpret_cast<void*>(lo), hi - lo,
226 PROT_READ | PROT_WRITE | PROT_MTE | PROT_GROWSDOWN)) {
227 async_safe_fatal("error: failed to set PROT_MTE on main thread");
228 }
Florian Mayere65e1932024-02-15 22:20:54 +0000229 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
230 if (t->terminating || t->is_main()) continue;
231 if (mprotect(t->mmap_base_unguarded, t->mmap_size_unguarded,
232 PROT_READ | PROT_WRITE | PROT_MTE)) {
233 async_safe_fatal("error: failed to set PROT_MTE on thread: %d", t->tid);
234 }
235 }
Mitch Phillipsf7c5e682024-06-20 14:10:57 +0200236 return true;
237#else
238 return false;
239#endif // defined(__aarch64__)
Florian Mayere65e1932024-02-15 22:20:54 +0000240}
241
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700242bool android_run_on_all_threads(bool (*func)(void*), void* arg) {
243 // Take the locks in this order to avoid inversion (pthread_create ->
244 // __pthread_internal_add).
245 ScopedWriteLock creation_locker(&g_thread_creation_lock);
246 ScopedReadLock list_locker(&g_thread_list_lock);
247
248 // Call the function directly for the current thread so that we don't need to worry about
249 // the consequences of synchronizing with ourselves.
250 if (!func(arg)) {
251 return false;
252 }
253
254 static sem_t g_sem;
255 if (sem_init(&g_sem, 0, 0) != 0) {
256 return false;
257 }
258
259 static bool (*g_func)(void*);
260 static void *g_arg;
261 g_func = func;
262 g_arg = arg;
263
264 static _Atomic(bool) g_retval;
265 atomic_init(&g_retval, true);
266
267 auto handler = [](int, siginfo_t*, void*) {
268 ErrnoRestorer restorer;
269 if (!g_func(g_arg)) {
270 atomic_store(&g_retval, false);
271 }
272 sem_post(&g_sem);
273 };
274
275 struct sigaction act = {}, oldact;
276 act.sa_flags = SA_SIGINFO;
277 act.sa_sigaction = handler;
278 sigfillset(&act.sa_mask);
279 if (sigaction(BIONIC_SIGNAL_RUN_ON_ALL_THREADS, &act, &oldact) != 0) {
280 sem_destroy(&g_sem);
281 return false;
282 }
283
284 pid_t my_pid = getpid();
285 size_t num_tids = 0;
286 for (pthread_internal_t* t = g_thread_list; t != nullptr; t = t->next) {
287 // The function is called directly for the current thread above, so no need to send a signal to
288 // ourselves to call it here.
289 if (t == __get_thread()) continue;
290
291 // If a thread is terminating (has blocked signals) or has already terminated, our signal will
292 // never be received, so we need to check for that condition and skip the thread if it is the
293 // case.
294 if (atomic_load(&t->terminating)) continue;
295
296 if (tgkill(my_pid, t->tid, BIONIC_SIGNAL_RUN_ON_ALL_THREADS) == 0) {
297 ++num_tids;
298 } else {
299 atomic_store(&g_retval, false);
300 }
301 }
302
303 for (size_t i = 0; i != num_tids; ++i) {
304 if (TEMP_FAILURE_RETRY(sem_wait(&g_sem)) != 0) {
305 atomic_store(&g_retval, false);
306 break;
307 }
308 }
309
310 sigaction(BIONIC_SIGNAL_RUN_ON_ALL_THREADS, &oldact, 0);
311 sem_destroy(&g_sem);
312 return atomic_load(&g_retval);
313}