1 /*
2 * Copyright 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "debuggerd/handler.h"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <linux/futex.h>
23 #include <pthread.h>
24 #include <sched.h>
25 #include <signal.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/capability.h>
31 #include <sys/mman.h>
32 #include <sys/prctl.h>
33 #include <sys/socket.h>
34 #include <sys/syscall.h>
35 #include <sys/uio.h>
36 #include <sys/un.h>
37 #include <sys/wait.h>
38 #include <unistd.h>
39
40 #include <android-base/macros.h>
41 #include <android-base/unique_fd.h>
42 #include <async_safe/log.h>
43 #include <bionic/reserved_signals.h>
44
45 #include <libdebuggerd/utility.h>
46
47 #include "dump_type.h"
48 #include "protocol.h"
49
50 #include "handler/fallback.h"
51
52 using android::base::Pipe;
53
54 // We muck with our fds in a 'thread' that doesn't share the same fd table.
55 // Close fds in that thread with a raw close syscall instead of going through libc.
56 struct FdsanBypassCloser {
CloseFdsanBypassCloser57 static void Close(int fd) {
58 syscall(__NR_close, fd);
59 }
60 };
61
62 using unique_fd = android::base::unique_fd_impl<FdsanBypassCloser>;
63
64 // see man(2) prctl, specifically the section about PR_GET_NAME
65 #define MAX_TASK_NAME_LEN (16)
66
67 #if defined(__LP64__)
68 #define CRASH_DUMP_NAME "crash_dump64"
69 #else
70 #define CRASH_DUMP_NAME "crash_dump32"
71 #endif
72
73 #define CRASH_DUMP_PATH "/apex/com.android.runtime/bin/" CRASH_DUMP_NAME
74
75 // Wrappers that directly invoke the respective syscalls, in case the cached values are invalid.
76 #pragma GCC poison getpid gettid
__getpid()77 static pid_t __getpid() {
78 return syscall(__NR_getpid);
79 }
80
__gettid()81 static pid_t __gettid() {
82 return syscall(__NR_gettid);
83 }
84
futex_wait(volatile void * ftx,int value)85 static inline void futex_wait(volatile void* ftx, int value) {
86 syscall(__NR_futex, ftx, FUTEX_WAIT, value, nullptr, nullptr, 0);
87 }
88
89 class ErrnoRestorer {
90 public:
ErrnoRestorer()91 ErrnoRestorer() : saved_errno_(errno) {
92 }
93
~ErrnoRestorer()94 ~ErrnoRestorer() {
95 errno = saved_errno_;
96 }
97
98 private:
99 int saved_errno_;
100 };
101
102 extern "C" void* android_fdsan_get_fd_table();
103 extern "C" void debuggerd_fallback_handler(siginfo_t*, ucontext_t*, void*);
104
105 static debuggerd_callbacks_t g_callbacks;
106
107 // Mutex to ensure only one crashing thread dumps itself.
108 static pthread_mutex_t crash_mutex = PTHREAD_MUTEX_INITIALIZER;
109
110 // Don't use async_safe_fatal because it exits via abort, which might put us back into
111 // a signal handler.
fatal(const char * fmt,...)112 static void __noreturn __printflike(1, 2) fatal(const char* fmt, ...) {
113 va_list args;
114 va_start(args, fmt);
115 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "libc", fmt, args);
116 _exit(1);
117 }
118
fatal_errno(const char * fmt,...)119 static void __noreturn __printflike(1, 2) fatal_errno(const char* fmt, ...) {
120 int err = errno;
121 va_list args;
122 va_start(args, fmt);
123
124 char buf[256];
125 async_safe_format_buffer_va_list(buf, sizeof(buf), fmt, args);
126 fatal("%s: %s", buf, strerror(err));
127 }
128
get_main_thread_name(char * buf,size_t len)129 static bool get_main_thread_name(char* buf, size_t len) {
130 unique_fd fd(open("/proc/self/comm", O_RDONLY | O_CLOEXEC));
131 if (fd == -1) {
132 return false;
133 }
134
135 ssize_t rc = read(fd, buf, len);
136 if (rc == -1) {
137 return false;
138 } else if (rc == 0) {
139 // Should never happen?
140 return false;
141 }
142
143 // There's a trailing newline, replace it with a NUL.
144 buf[rc - 1] = '\0';
145 return true;
146 }
147
148 /*
149 * Writes a summary of the signal to the log file. We do this so that, if
150 * for some reason we're not able to contact debuggerd, there is still some
151 * indication of the failure in the log.
152 *
153 * We could be here as a result of native heap corruption, or while a
154 * mutex is being held, so we don't want to use any libc functions that
155 * could allocate memory or hold a lock.
156 */
log_signal_summary(const siginfo_t * info)157 static void log_signal_summary(const siginfo_t* info) {
158 char main_thread_name[MAX_TASK_NAME_LEN + 1];
159 if (!get_main_thread_name(main_thread_name, sizeof(main_thread_name))) {
160 strncpy(main_thread_name, "<unknown>", sizeof(main_thread_name));
161 }
162
163 if (info->si_signo == BIONIC_SIGNAL_DEBUGGER) {
164 async_safe_format_log(ANDROID_LOG_INFO, "libc", "Requested dump for pid %d (%s)", __getpid(),
165 main_thread_name);
166 return;
167 }
168
169 // Many signals don't have an address or sender.
170 char addr_desc[32] = ""; // ", fault addr 0x1234"
171 if (signal_has_si_addr(info)) {
172 async_safe_format_buffer(addr_desc, sizeof(addr_desc), ", fault addr %p", info->si_addr);
173 }
174 pid_t self_pid = __getpid();
175 char sender_desc[32] = {}; // " from pid 1234, uid 666"
176 if (signal_has_sender(info, self_pid)) {
177 get_signal_sender(sender_desc, sizeof(sender_desc), info);
178 }
179
180 char thread_name[MAX_TASK_NAME_LEN + 1]; // one more for termination
181 if (prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(thread_name), 0, 0, 0) != 0) {
182 strcpy(thread_name, "<name unknown>");
183 } else {
184 // short names are null terminated by prctl, but the man page
185 // implies that 16 byte names are not.
186 thread_name[MAX_TASK_NAME_LEN] = 0;
187 }
188
189 async_safe_format_log(ANDROID_LOG_FATAL, "libc",
190 "Fatal signal %d (%s), code %d (%s%s)%s in tid %d (%s), pid %d (%s)",
191 info->si_signo, get_signame(info), info->si_code, get_sigcode(info),
192 sender_desc, addr_desc, __gettid(), thread_name, self_pid, main_thread_name);
193 }
194
195 /*
196 * Returns true if the handler for signal "signum" has SA_SIGINFO set.
197 */
have_siginfo(int signum)198 static bool have_siginfo(int signum) {
199 struct sigaction old_action;
200 if (sigaction(signum, nullptr, &old_action) < 0) {
201 async_safe_format_log(ANDROID_LOG_WARN, "libc", "Failed testing for SA_SIGINFO: %s",
202 strerror(errno));
203 return false;
204 }
205 return (old_action.sa_flags & SA_SIGINFO) != 0;
206 }
207
raise_caps()208 static void raise_caps() {
209 // Raise CapInh to match CapPrm, so that we can set the ambient bits.
210 __user_cap_header_struct capheader;
211 memset(&capheader, 0, sizeof(capheader));
212 capheader.version = _LINUX_CAPABILITY_VERSION_3;
213 capheader.pid = 0;
214
215 __user_cap_data_struct capdata[2];
216 if (capget(&capheader, &capdata[0]) == -1) {
217 fatal_errno("capget failed");
218 }
219
220 if (capdata[0].permitted != capdata[0].inheritable ||
221 capdata[1].permitted != capdata[1].inheritable) {
222 capdata[0].inheritable = capdata[0].permitted;
223 capdata[1].inheritable = capdata[1].permitted;
224
225 if (capset(&capheader, &capdata[0]) == -1) {
226 async_safe_format_log(ANDROID_LOG_ERROR, "libc", "capset failed: %s", strerror(errno));
227 }
228 }
229
230 // Set the ambient capability bits so that crash_dump gets all of our caps and can ptrace us.
231 uint64_t capmask = capdata[0].inheritable;
232 capmask |= static_cast<uint64_t>(capdata[1].inheritable) << 32;
233 for (unsigned long i = 0; i < 64; ++i) {
234 if (capmask & (1ULL << i)) {
235 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) != 0) {
236 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
237 "failed to raise ambient capability %lu: %s", i, strerror(errno));
238 }
239 }
240 }
241 }
242
__fork()243 static pid_t __fork() {
244 return clone(nullptr, nullptr, 0, nullptr);
245 }
246
247 // Double-clone, with CLONE_FILES to share the file descriptor table for kcmp validation.
248 // Returns 0 in the orphaned child, the pid of the orphan in the original process, or -1 on failure.
create_vm_process()249 static void create_vm_process() {
250 pid_t first = clone(nullptr, nullptr, CLONE_FILES, nullptr);
251 if (first == -1) {
252 fatal_errno("failed to clone vm process");
253 } else if (first == 0) {
254 drop_capabilities();
255
256 if (clone(nullptr, nullptr, CLONE_FILES, nullptr) == -1) {
257 _exit(errno);
258 }
259
260 // crash_dump is ptracing both sides of the fork; it'll let the parent exit,
261 // but keep the orphan stopped to peek at its memory.
262
263 // There appears to be a bug in the kernel where our death causes SIGHUP to
264 // be sent to our process group if we exit while it has stopped jobs (e.g.
265 // because of wait_for_debugger). Use setsid to create a new process group to
266 // avoid hitting this.
267 setsid();
268
269 _exit(0);
270 }
271
272 int status;
273 if (TEMP_FAILURE_RETRY(waitpid(first, &status, __WCLONE)) != first) {
274 fatal_errno("failed to waitpid in double fork");
275 } else if (!WIFEXITED(status)) {
276 fatal("intermediate process didn't exit cleanly in double fork (status = %d)", status);
277 } else if (WEXITSTATUS(status)) {
278 fatal("second clone failed: %s", strerror(WEXITSTATUS(status)));
279 }
280 }
281
282 struct debugger_thread_info {
283 pid_t crashing_tid;
284 pid_t pseudothread_tid;
285 siginfo_t* siginfo;
286 void* ucontext;
287 debugger_process_info process_info;
288 };
289
290 // Logging and contacting debuggerd requires free file descriptors, which we might not have.
291 // Work around this by spawning a "thread" that shares its parent's address space, but not its file
292 // descriptor table, so that we can close random file descriptors without affecting the original
293 // process. Note that this doesn't go through pthread_create, so TLS is shared with the spawning
294 // process.
295 static void* pseudothread_stack;
296
get_dump_type(const debugger_thread_info * thread_info)297 static DebuggerdDumpType get_dump_type(const debugger_thread_info* thread_info) {
298 if (thread_info->siginfo->si_signo == BIONIC_SIGNAL_DEBUGGER &&
299 thread_info->siginfo->si_value.sival_int) {
300 return kDebuggerdNativeBacktrace;
301 }
302
303 return kDebuggerdTombstoneProto;
304 }
305
debuggerd_dispatch_pseudothread(void * arg)306 static int debuggerd_dispatch_pseudothread(void* arg) {
307 debugger_thread_info* thread_info = static_cast<debugger_thread_info*>(arg);
308
309 for (int i = 0; i < 1024; ++i) {
310 // Don't use close to avoid bionic's file descriptor ownership checks.
311 syscall(__NR_close, i);
312 }
313
314 int devnull = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
315 if (devnull == -1) {
316 fatal_errno("failed to open /dev/null");
317 } else if (devnull != 0) {
318 fatal_errno("expected /dev/null fd to be 0, actually %d", devnull);
319 }
320
321 // devnull will be 0.
322 TEMP_FAILURE_RETRY(dup2(devnull, 1));
323 TEMP_FAILURE_RETRY(dup2(devnull, 2));
324
325 unique_fd input_read, input_write;
326 unique_fd output_read, output_write;
327 if (!Pipe(&input_read, &input_write) != 0 || !Pipe(&output_read, &output_write)) {
328 fatal_errno("failed to create pipe");
329 }
330
331 uint32_t version;
332 ssize_t expected;
333
334 // ucontext_t is absurdly large on AArch64, so piece it together manually with writev.
335 struct iovec iovs[4] = {
336 {.iov_base = &version, .iov_len = sizeof(version)},
337 {.iov_base = thread_info->siginfo, .iov_len = sizeof(siginfo_t)},
338 {.iov_base = thread_info->ucontext, .iov_len = sizeof(ucontext_t)},
339 };
340
341 if (thread_info->process_info.fdsan_table) {
342 // Dynamic executables always use version 4. There is no need to increment the version number if
343 // the format changes, because the sender (linker) and receiver (crash_dump) are version locked.
344 version = 4;
345 expected = sizeof(CrashInfoHeader) + sizeof(CrashInfoDataDynamic);
346
347 iovs[3] = {.iov_base = &thread_info->process_info,
348 .iov_len = sizeof(thread_info->process_info)};
349 } else {
350 // Static executables always use version 1.
351 version = 1;
352 expected = sizeof(CrashInfoHeader) + sizeof(CrashInfoDataStatic);
353
354 iovs[3] = {.iov_base = &thread_info->process_info.abort_msg, .iov_len = sizeof(uintptr_t)};
355 }
356 errno = 0;
357 if (fcntl(output_write.get(), F_SETPIPE_SZ, expected) < static_cast<int>(expected)) {
358 fatal_errno("failed to set pipe buffer size");
359 }
360
361 ssize_t rc = TEMP_FAILURE_RETRY(writev(output_write.get(), iovs, arraysize(iovs)));
362 if (rc == -1) {
363 fatal_errno("failed to write crash info");
364 } else if (rc != expected) {
365 fatal("failed to write crash info, wrote %zd bytes, expected %zd", rc, expected);
366 }
367
368 // Don't use fork(2) to avoid calling pthread_atfork handlers.
369 pid_t crash_dump_pid = __fork();
370 if (crash_dump_pid == -1) {
371 async_safe_format_log(ANDROID_LOG_FATAL, "libc",
372 "failed to fork in debuggerd signal handler: %s", strerror(errno));
373 } else if (crash_dump_pid == 0) {
374 TEMP_FAILURE_RETRY(dup2(input_write.get(), STDOUT_FILENO));
375 TEMP_FAILURE_RETRY(dup2(output_read.get(), STDIN_FILENO));
376 input_read.reset();
377 input_write.reset();
378 output_read.reset();
379 output_write.reset();
380
381 raise_caps();
382
383 char main_tid[10];
384 char pseudothread_tid[10];
385 char debuggerd_dump_type[10];
386 async_safe_format_buffer(main_tid, sizeof(main_tid), "%d", thread_info->crashing_tid);
387 async_safe_format_buffer(pseudothread_tid, sizeof(pseudothread_tid), "%d",
388 thread_info->pseudothread_tid);
389 async_safe_format_buffer(debuggerd_dump_type, sizeof(debuggerd_dump_type), "%d",
390 get_dump_type(thread_info));
391
392 execle(CRASH_DUMP_PATH, CRASH_DUMP_NAME, main_tid, pseudothread_tid, debuggerd_dump_type,
393 nullptr, nullptr);
394 async_safe_format_log(ANDROID_LOG_FATAL, "libc", "failed to exec crash_dump helper: %s",
395 strerror(errno));
396 return 1;
397 }
398
399 input_write.reset();
400 output_read.reset();
401
402 // crash_dump will ptrace and pause all of our threads, and then write to the pipe to tell
403 // us to fork off a process to read memory from.
404 char buf[4];
405 rc = TEMP_FAILURE_RETRY(read(input_read.get(), &buf, sizeof(buf)));
406
407 bool success = false;
408 if (rc == 1 && buf[0] == '\1') {
409 // crash_dump successfully started, and is ptracing us.
410 // Fork off a copy of our address space for it to use.
411 create_vm_process();
412 success = true;
413 } else {
414 // Something went wrong, log it.
415 if (rc == -1) {
416 async_safe_format_log(ANDROID_LOG_FATAL, "libc", "read of IPC pipe failed: %s",
417 strerror(errno));
418 } else if (rc == 0) {
419 async_safe_format_log(ANDROID_LOG_FATAL, "libc",
420 "crash_dump helper failed to exec, or was killed");
421 } else if (rc != 1) {
422 async_safe_format_log(ANDROID_LOG_FATAL, "libc",
423 "read of IPC pipe returned unexpected value: %zd", rc);
424 } else if (buf[0] != '\1') {
425 async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper reported failure");
426 }
427 }
428
429 // Don't leave a zombie child.
430 int status;
431 if (TEMP_FAILURE_RETRY(waitpid(crash_dump_pid, &status, 0)) == -1) {
432 async_safe_format_log(ANDROID_LOG_FATAL, "libc", "failed to wait for crash_dump helper: %s",
433 strerror(errno));
434 } else if (WIFSTOPPED(status) || WIFSIGNALED(status)) {
435 async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper crashed or stopped");
436 }
437
438 if (success) {
439 if (thread_info->siginfo->si_signo != BIONIC_SIGNAL_DEBUGGER) {
440 // For crashes, we don't need to minimize pause latency.
441 // Wait for the dump to complete before having the process exit, to avoid being murdered by
442 // ActivityManager or init.
443 TEMP_FAILURE_RETRY(read(input_read, &buf, sizeof(buf)));
444 }
445 }
446
447 return success ? 0 : 1;
448 }
449
resend_signal(siginfo_t * info)450 static void resend_signal(siginfo_t* info) {
451 // Signals can either be fatal or nonfatal.
452 // For fatal signals, crash_dump will send us the signal we crashed with
453 // before resuming us, so that processes using waitpid on us will see that we
454 // exited with the correct exit status (e.g. so that sh will report
455 // "Segmentation fault" instead of "Killed"). For this to work, we need
456 // to deregister our signal handler for that signal before continuing.
457 if (info->si_signo != BIONIC_SIGNAL_DEBUGGER) {
458 signal(info->si_signo, SIG_DFL);
459 int rc = syscall(SYS_rt_tgsigqueueinfo, __getpid(), __gettid(), info->si_signo, info);
460 if (rc != 0) {
461 fatal_errno("failed to resend signal during crash");
462 }
463 }
464 }
465
466 // Handler that does crash dumping by forking and doing the processing in the child.
467 // Do this by ptracing the relevant thread, and then execing debuggerd to do the actual dump.
debuggerd_signal_handler(int signal_number,siginfo_t * info,void * context)468 static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void* context) {
469 // Make sure we don't change the value of errno, in case a signal comes in between the process
470 // making a syscall and checking errno.
471 ErrnoRestorer restorer;
472
473 auto *ucontext = static_cast<ucontext_t*>(context);
474
475 // It's possible somebody cleared the SA_SIGINFO flag, which would mean
476 // our "info" arg holds an undefined value.
477 if (!have_siginfo(signal_number)) {
478 info = nullptr;
479 }
480
481 struct siginfo dummy_info = {};
482 if (!info) {
483 memset(&dummy_info, 0, sizeof(dummy_info));
484 dummy_info.si_signo = signal_number;
485 dummy_info.si_code = SI_USER;
486 dummy_info.si_pid = __getpid();
487 dummy_info.si_uid = getuid();
488 info = &dummy_info;
489 } else if (info->si_code >= 0 || info->si_code == SI_TKILL) {
490 // rt_tgsigqueueinfo(2)'s documentation appears to be incorrect on kernels
491 // that contain commit 66dd34a (3.9+). The manpage claims to only allow
492 // negative si_code values that are not SI_TKILL, but 66dd34a changed the
493 // check to allow all si_code values in calls coming from inside the house.
494 }
495
496 debugger_process_info process_info = {};
497 uintptr_t si_val = reinterpret_cast<uintptr_t>(info->si_ptr);
498 if (signal_number == BIONIC_SIGNAL_DEBUGGER) {
499 if (info->si_code == SI_QUEUE && info->si_pid == __getpid()) {
500 // Allow for the abort message to be explicitly specified via the sigqueue value.
501 // Keep the bottom bit intact for representing whether we want a backtrace or a tombstone.
502 if (si_val != kDebuggerdFallbackSivalUintptrRequestDump) {
503 process_info.abort_msg = reinterpret_cast<void*>(si_val & ~1);
504 info->si_ptr = reinterpret_cast<void*>(si_val & 1);
505 }
506 }
507 } else if (g_callbacks.get_process_info) {
508 process_info = g_callbacks.get_process_info();
509 }
510
511 // If sival_int is ~0, it means that the fallback handler has been called
512 // once before and this function is being called again to dump the stack
513 // of a specific thread. It is possible that the prctl call might return 1,
514 // then return 0 in subsequent calls, so check the sival_int to determine if
515 // the fallback handler should be called first.
516 if (si_val == kDebuggerdFallbackSivalUintptrRequestDump ||
517 prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1) {
518 // This check might be racy if another thread sets NO_NEW_PRIVS, but this should be unlikely,
519 // you can only set NO_NEW_PRIVS to 1, and the effect should be at worst a single missing
520 // ANR trace.
521 debuggerd_fallback_handler(info, ucontext, process_info.abort_msg);
522 resend_signal(info);
523 return;
524 }
525
526 // Only allow one thread to handle a signal at a time.
527 int ret = pthread_mutex_lock(&crash_mutex);
528 if (ret != 0) {
529 async_safe_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
530 return;
531 }
532
533 log_signal_summary(info);
534
535 // If we got here due to the signal BIONIC_SIGNAL_DEBUGGER, it's possible
536 // this is not the main thread, which can cause the intercept logic to fail
537 // since the intercept is only looking for the main thread. In this case,
538 // setting crashing_tid to pid instead of the current thread's tid avoids
539 // the problem.
540 debugger_thread_info thread_info = {
541 .crashing_tid = (signal_number == BIONIC_SIGNAL_DEBUGGER) ? __getpid() : __gettid(),
542 .pseudothread_tid = -1,
543 .siginfo = info,
544 .ucontext = context,
545 .process_info = process_info,
546 };
547
548 // Set PR_SET_DUMPABLE to 1, so that crash_dump can ptrace us.
549 int orig_dumpable = prctl(PR_GET_DUMPABLE);
550 if (prctl(PR_SET_DUMPABLE, 1) != 0) {
551 fatal_errno("failed to set dumpable");
552 }
553
554 // On kernels with yama_ptrace enabled, also allow any process to attach.
555 bool restore_orig_ptracer = true;
556 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) != 0) {
557 if (errno == EINVAL) {
558 // This kernel does not support PR_SET_PTRACER_ANY, or Yama is not enabled.
559 restore_orig_ptracer = false;
560 } else {
561 fatal_errno("failed to set traceable");
562 }
563 }
564
565 // Essentially pthread_create without CLONE_FILES, so we still work during file descriptor
566 // exhaustion.
567 pid_t child_pid =
568 clone(debuggerd_dispatch_pseudothread, pseudothread_stack,
569 CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID,
570 &thread_info, nullptr, nullptr, &thread_info.pseudothread_tid);
571 if (child_pid == -1) {
572 fatal_errno("failed to spawn debuggerd dispatch thread");
573 }
574
575 // Wait for the child to start...
576 futex_wait(&thread_info.pseudothread_tid, -1);
577
578 // and then wait for it to terminate.
579 futex_wait(&thread_info.pseudothread_tid, child_pid);
580
581 // Restore PR_SET_DUMPABLE to its original value.
582 if (prctl(PR_SET_DUMPABLE, orig_dumpable) != 0) {
583 fatal_errno("failed to restore dumpable");
584 }
585
586 // Restore PR_SET_PTRACER to its original value.
587 if (restore_orig_ptracer && prctl(PR_SET_PTRACER, 0) != 0) {
588 fatal_errno("failed to restore traceable");
589 }
590
591 if (info->si_signo == BIONIC_SIGNAL_DEBUGGER) {
592 // If the signal is fatal, don't unlock the mutex to prevent other crashing threads from
593 // starting to dump right before our death.
594 pthread_mutex_unlock(&crash_mutex);
595 } else {
596 // Resend the signal, so that either the debugger or the parent's waitpid sees it.
597 resend_signal(info);
598 }
599 }
600
debuggerd_init(debuggerd_callbacks_t * callbacks)601 void debuggerd_init(debuggerd_callbacks_t* callbacks) {
602 if (callbacks) {
603 g_callbacks = *callbacks;
604 }
605
606 size_t thread_stack_pages = 8;
607 void* thread_stack_allocation = mmap(nullptr, PAGE_SIZE * (thread_stack_pages + 2), PROT_NONE,
608 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
609 if (thread_stack_allocation == MAP_FAILED) {
610 fatal_errno("failed to allocate debuggerd thread stack");
611 }
612
613 char* stack = static_cast<char*>(thread_stack_allocation) + PAGE_SIZE;
614 if (mprotect(stack, PAGE_SIZE * thread_stack_pages, PROT_READ | PROT_WRITE) != 0) {
615 fatal_errno("failed to mprotect debuggerd thread stack");
616 }
617
618 // Stack grows negatively, set it to the last byte in the page...
619 stack = (stack + thread_stack_pages * PAGE_SIZE - 1);
620 // and align it.
621 stack -= 15;
622 pseudothread_stack = stack;
623
624 struct sigaction action;
625 memset(&action, 0, sizeof(action));
626 sigfillset(&action.sa_mask);
627 action.sa_sigaction = debuggerd_signal_handler;
628 action.sa_flags = SA_RESTART | SA_SIGINFO;
629
630 // Use the alternate signal stack if available so we can catch stack overflows.
631 action.sa_flags |= SA_ONSTACK;
632
633 #define SA_EXPOSE_TAGBITS 0x00000800
634 // Request that the kernel set tag bits in the fault address. This is necessary for diagnosing MTE
635 // faults.
636 action.sa_flags |= SA_EXPOSE_TAGBITS;
637
638 debuggerd_register_handlers(&action);
639 }
640