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