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 <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/capability.h>
32 #include <sys/mman.h>
33 #include <sys/prctl.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/uio.h>
37 #include <sys/un.h>
38 #include <sys/wait.h>
39 #include <unistd.h>
40 
41 #include <android-base/macros.h>
42 #include <android-base/parsebool.h>
43 #include <android-base/properties.h>
44 #include <android-base/unique_fd.h>
45 #include <async_safe/log.h>
46 #include <bionic/reserved_signals.h>
47 
48 #include <libdebuggerd/utility.h>
49 
50 #include "dump_type.h"
51 #include "protocol.h"
52 
53 #include "handler/fallback.h"
54 
55 using ::android::base::ParseBool;
56 using ::android::base::ParseBoolResult;
57 using ::android::base::Pipe;
58 
59 // We muck with our fds in a 'thread' that doesn't share the same fd table.
60 // Close fds in that thread with a raw close syscall instead of going through libc.
61 struct FdsanBypassCloser {
CloseFdsanBypassCloser62   static void Close(int fd) {
63     syscall(__NR_close, fd);
64   }
65 };
66 
67 using unique_fd = android::base::unique_fd_impl<FdsanBypassCloser>;
68 
69 // see man(2) prctl, specifically the section about PR_GET_NAME
70 #define MAX_TASK_NAME_LEN (16)
71 
72 #if defined(__LP64__)
73 #define CRASH_DUMP_NAME "crash_dump64"
74 #else
75 #define CRASH_DUMP_NAME "crash_dump32"
76 #endif
77 
78 #define CRASH_DUMP_PATH "/apex/com.android.runtime/bin/" CRASH_DUMP_NAME
79 
80 // Wrappers that directly invoke the respective syscalls, in case the cached values are invalid.
81 #pragma GCC poison getpid gettid
__getpid()82 static pid_t __getpid() {
83   return syscall(__NR_getpid);
84 }
85 
__gettid()86 static pid_t __gettid() {
87   return syscall(__NR_gettid);
88 }
89 
property_parse_bool(const char * name)90 static bool property_parse_bool(const char* name) {
91   const prop_info* pi = __system_property_find(name);
92   if (!pi) return false;
93   bool cookie = false;
94   __system_property_read_callback(
95       pi,
96       [](void* cookie, const char*, const char* value, uint32_t) {
97         *reinterpret_cast<bool*>(cookie) = ParseBool(value) == ParseBoolResult::kTrue;
98       },
99       &cookie);
100   return cookie;
101 }
102 
is_permissive_mte()103 static bool is_permissive_mte() {
104   // Environment variable for testing or local use from shell.
105   char* permissive_env = getenv("MTE_PERMISSIVE");
106   char process_sysprop_name[512];
107   async_safe_format_buffer(process_sysprop_name, sizeof(process_sysprop_name),
108                            "persist.device_config.memory_safety_native.permissive.process.%s",
109                            getprogname());
110   // DO NOT REPLACE this with GetBoolProperty. That uses std::string which allocates, so it is
111   // not async-safe (and this functiong gets used in a signal handler).
112   return property_parse_bool("persist.sys.mte.permissive") ||
113          property_parse_bool("persist.device_config.memory_safety_native.permissive.default") ||
114          property_parse_bool(process_sysprop_name) ||
115          (permissive_env && ParseBool(permissive_env) == ParseBoolResult::kTrue);
116 }
117 
futex_wait(volatile void * ftx,int value)118 static inline void futex_wait(volatile void* ftx, int value) {
119   syscall(__NR_futex, ftx, FUTEX_WAIT, value, nullptr, nullptr, 0);
120 }
121 
122 class ErrnoRestorer {
123  public:
ErrnoRestorer()124   ErrnoRestorer() : saved_errno_(errno) {
125   }
126 
~ErrnoRestorer()127   ~ErrnoRestorer() {
128     errno = saved_errno_;
129   }
130 
131  private:
132   int saved_errno_;
133 };
134 
135 extern "C" void* android_fdsan_get_fd_table();
136 extern "C" void debuggerd_fallback_handler(siginfo_t*, ucontext_t*, void*);
137 
138 static debuggerd_callbacks_t g_callbacks;
139 
140 // Mutex to ensure only one crashing thread dumps itself.
141 static pthread_mutex_t crash_mutex = PTHREAD_MUTEX_INITIALIZER;
142 
143 // Don't use async_safe_fatal because it exits via abort, which might put us back into
144 // a signal handler.
fatal(const char * fmt,...)145 static void __noreturn __printflike(1, 2) fatal(const char* fmt, ...) {
146   va_list args;
147   va_start(args, fmt);
148   async_safe_format_log_va_list(ANDROID_LOG_FATAL, "libc", fmt, args);
149   _exit(1);
150 }
151 
fatal_errno(const char * fmt,...)152 static void __noreturn __printflike(1, 2) fatal_errno(const char* fmt, ...) {
153   int err = errno;
154   va_list args;
155   va_start(args, fmt);
156 
157   char buf[256];
158   async_safe_format_buffer_va_list(buf, sizeof(buf), fmt, args);
159   fatal("%s: %s", buf, strerror(err));
160 }
161 
get_main_thread_name(char * buf,size_t len)162 static bool get_main_thread_name(char* buf, size_t len) {
163   unique_fd fd(open("/proc/self/comm", O_RDONLY | O_CLOEXEC));
164   if (fd == -1) {
165     return false;
166   }
167 
168   ssize_t rc = read(fd, buf, len);
169   if (rc == -1) {
170     return false;
171   } else if (rc == 0) {
172     // Should never happen?
173     return false;
174   }
175 
176   // There's a trailing newline, replace it with a NUL.
177   buf[rc - 1] = '\0';
178   return true;
179 }
180 
181 /*
182  * Writes a summary of the signal to the log file.  We do this so that, if
183  * for some reason we're not able to contact debuggerd, there is still some
184  * indication of the failure in the log.
185  *
186  * We could be here as a result of native heap corruption, or while a
187  * mutex is being held, so we don't want to use any libc functions that
188  * could allocate memory or hold a lock.
189  */
log_signal_summary(const siginfo_t * si)190 static void log_signal_summary(const siginfo_t* si) {
191   char main_thread_name[MAX_TASK_NAME_LEN + 1];
192   if (!get_main_thread_name(main_thread_name, sizeof(main_thread_name))) {
193     strncpy(main_thread_name, "<unknown>", sizeof(main_thread_name));
194   }
195 
196   if (si->si_signo == BIONIC_SIGNAL_DEBUGGER) {
197     async_safe_format_log(ANDROID_LOG_INFO, "libc", "Requested dump for pid %d (%s)", __getpid(),
198                           main_thread_name);
199     return;
200   }
201 
202   // Many signals don't have a sender or extra detail, but some do...
203   pid_t self_pid = __getpid();
204   char sender_desc[32] = {};  // " from pid 1234, uid 666"
205   if (signal_has_sender(si, self_pid)) {
206     get_signal_sender(sender_desc, sizeof(sender_desc), si);
207   }
208   char extra_desc[32] = {};  // ", fault addr 0x1234" or ", syscall 1234"
209   if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
210     async_safe_format_buffer(extra_desc, sizeof(extra_desc), ", syscall %d", si->si_syscall);
211   } else if (signal_has_si_addr(si)) {
212     async_safe_format_buffer(extra_desc, sizeof(extra_desc), ", fault addr %p", si->si_addr);
213   }
214 
215   char thread_name[MAX_TASK_NAME_LEN + 1];  // one more for termination
216   if (prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(thread_name), 0, 0, 0) != 0) {
217     strcpy(thread_name, "<name unknown>");
218   } else {
219     // short names are null terminated by prctl, but the man page
220     // implies that 16 byte names are not.
221     thread_name[MAX_TASK_NAME_LEN] = 0;
222   }
223 
224   async_safe_format_log(ANDROID_LOG_FATAL, "libc",
225                         "Fatal signal %d (%s), code %d (%s%s)%s in tid %d (%s), pid %d (%s)",
226                         si->si_signo, get_signame(si), si->si_code, get_sigcode(si), sender_desc,
227                         extra_desc, __gettid(), thread_name, self_pid, main_thread_name);
228 }
229 
230 /*
231  * Returns true if the handler for signal "signum" has SA_SIGINFO set.
232  */
have_siginfo(int signum)233 static bool have_siginfo(int signum) {
234   struct sigaction old_action;
235   if (sigaction(signum, nullptr, &old_action) < 0) {
236     async_safe_format_log(ANDROID_LOG_WARN, "libc", "Failed testing for SA_SIGINFO: %s",
237                           strerror(errno));
238     return false;
239   }
240   return (old_action.sa_flags & SA_SIGINFO) != 0;
241 }
242 
raise_caps()243 static void raise_caps() {
244   // Raise CapInh to match CapPrm, so that we can set the ambient bits.
245   __user_cap_header_struct capheader;
246   memset(&capheader, 0, sizeof(capheader));
247   capheader.version = _LINUX_CAPABILITY_VERSION_3;
248   capheader.pid = 0;
249 
250   __user_cap_data_struct capdata[2];
251   if (capget(&capheader, &capdata[0]) == -1) {
252     fatal_errno("capget failed");
253   }
254 
255   if (capdata[0].permitted != capdata[0].inheritable ||
256       capdata[1].permitted != capdata[1].inheritable) {
257     capdata[0].inheritable = capdata[0].permitted;
258     capdata[1].inheritable = capdata[1].permitted;
259 
260     if (capset(&capheader, &capdata[0]) == -1) {
261       async_safe_format_log(ANDROID_LOG_ERROR, "libc", "capset failed: %s", strerror(errno));
262     }
263   }
264 
265   // Set the ambient capability bits so that crash_dump gets all of our caps and can ptrace us.
266   uint64_t capmask = capdata[0].inheritable;
267   capmask |= static_cast<uint64_t>(capdata[1].inheritable) << 32;
268   for (unsigned long i = 0; i < 64; ++i) {
269     if (capmask & (1ULL << i)) {
270       if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) != 0) {
271         async_safe_format_log(ANDROID_LOG_ERROR, "libc",
272                               "failed to raise ambient capability %lu: %s", i, strerror(errno));
273       }
274     }
275   }
276 }
277 
__fork()278 static pid_t __fork() {
279   return clone(nullptr, nullptr, 0, nullptr);
280 }
281 
282 // Double-clone, with CLONE_FILES to share the file descriptor table for kcmp validation.
283 // Returns 0 in the orphaned child, the pid of the orphan in the original process, or -1 on failure.
create_vm_process()284 static void create_vm_process() {
285   pid_t first = clone(nullptr, nullptr, CLONE_FILES, nullptr);
286   if (first == -1) {
287     fatal_errno("failed to clone vm process");
288   } else if (first == 0) {
289     drop_capabilities();
290 
291     if (clone(nullptr, nullptr, CLONE_FILES, nullptr) == -1) {
292       _exit(errno);
293     }
294 
295     // crash_dump is ptracing both sides of the fork; it'll let the parent exit,
296     // but keep the orphan stopped to peek at its memory.
297 
298     // There appears to be a bug in the kernel where our death causes SIGHUP to
299     // be sent to our process group if we exit while it has stopped jobs (e.g.
300     // because of wait_for_debugger). Use setsid to create a new process group to
301     // avoid hitting this.
302     setsid();
303 
304     _exit(0);
305   }
306 
307   int status;
308   if (TEMP_FAILURE_RETRY(waitpid(first, &status, __WCLONE)) != first) {
309     fatal_errno("failed to waitpid in double fork");
310   } else if (!WIFEXITED(status)) {
311     fatal("intermediate process didn't exit cleanly in double fork (status = %d)", status);
312   } else if (WEXITSTATUS(status)) {
313     fatal("second clone failed: %s", strerror(WEXITSTATUS(status)));
314   }
315 }
316 
317 struct debugger_thread_info {
318   pid_t crashing_tid;
319   pid_t pseudothread_tid;
320   siginfo_t* siginfo;
321   void* ucontext;
322   debugger_process_info process_info;
323 };
324 
325 // Logging and contacting debuggerd requires free file descriptors, which we might not have.
326 // Work around this by spawning a "thread" that shares its parent's address space, but not its file
327 // descriptor table, so that we can close random file descriptors without affecting the original
328 // process. Note that this doesn't go through pthread_create, so TLS is shared with the spawning
329 // process.
330 static void* pseudothread_stack;
331 
get_dump_type(const debugger_thread_info * thread_info)332 static DebuggerdDumpType get_dump_type(const debugger_thread_info* thread_info) {
333   if (thread_info->siginfo->si_signo == BIONIC_SIGNAL_DEBUGGER &&
334       thread_info->siginfo->si_value.sival_int) {
335     return kDebuggerdNativeBacktrace;
336   }
337 
338   return kDebuggerdTombstoneProto;
339 }
340 
debuggerd_dispatch_pseudothread(void * arg)341 static int debuggerd_dispatch_pseudothread(void* arg) {
342   debugger_thread_info* thread_info = static_cast<debugger_thread_info*>(arg);
343 
344   for (int i = 0; i < 1024; ++i) {
345     // Don't use close to avoid bionic's file descriptor ownership checks.
346     syscall(__NR_close, i);
347   }
348 
349   int devnull = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
350   if (devnull == -1) {
351     fatal_errno("failed to open /dev/null");
352   } else if (devnull != 0) {
353     fatal_errno("expected /dev/null fd to be 0, actually %d", devnull);
354   }
355 
356   // devnull will be 0.
357   TEMP_FAILURE_RETRY(dup2(devnull, 1));
358   TEMP_FAILURE_RETRY(dup2(devnull, 2));
359 
360   unique_fd input_read, input_write;
361   unique_fd output_read, output_write;
362   if (!Pipe(&input_read, &input_write) != 0 || !Pipe(&output_read, &output_write)) {
363     fatal_errno("failed to create pipe");
364   }
365 
366   uint32_t version;
367   ssize_t expected;
368 
369   // ucontext_t is absurdly large on AArch64, so piece it together manually with writev.
370   struct iovec iovs[4] = {
371       {.iov_base = &version, .iov_len = sizeof(version)},
372       {.iov_base = thread_info->siginfo, .iov_len = sizeof(siginfo_t)},
373       {.iov_base = thread_info->ucontext, .iov_len = sizeof(ucontext_t)},
374   };
375 
376   constexpr size_t kHeaderSize = sizeof(version) + sizeof(siginfo_t) + sizeof(ucontext_t);
377 
378   if (thread_info->process_info.fdsan_table) {
379     // Dynamic executables always use version 4. There is no need to increment the version number if
380     // the format changes, because the sender (linker) and receiver (crash_dump) are version locked.
381     version = 4;
382     expected = sizeof(CrashInfoHeader) + sizeof(CrashInfoDataDynamic);
383 
384     static_assert(sizeof(CrashInfoHeader) + sizeof(CrashInfoDataDynamic) ==
385                       kHeaderSize + sizeof(thread_info->process_info),
386                   "Wire protocol structs do not match the data sent.");
387 #define ASSERT_SAME_OFFSET(MEMBER1, MEMBER2) \
388     static_assert(sizeof(CrashInfoHeader) + offsetof(CrashInfoDataDynamic, MEMBER1) == \
389                       kHeaderSize + offsetof(debugger_process_info, MEMBER2), \
390                   "Wire protocol offset does not match data sent: " #MEMBER1);
391     ASSERT_SAME_OFFSET(fdsan_table_address, fdsan_table);
392     ASSERT_SAME_OFFSET(gwp_asan_state, gwp_asan_state);
393     ASSERT_SAME_OFFSET(gwp_asan_metadata, gwp_asan_metadata);
394     ASSERT_SAME_OFFSET(scudo_stack_depot, scudo_stack_depot);
395     ASSERT_SAME_OFFSET(scudo_region_info, scudo_region_info);
396     ASSERT_SAME_OFFSET(scudo_ring_buffer, scudo_ring_buffer);
397     ASSERT_SAME_OFFSET(scudo_ring_buffer_size, scudo_ring_buffer_size);
398     ASSERT_SAME_OFFSET(recoverable_gwp_asan_crash, recoverable_gwp_asan_crash);
399 #undef ASSERT_SAME_OFFSET
400 
401     iovs[3] = {.iov_base = &thread_info->process_info,
402                .iov_len = sizeof(thread_info->process_info)};
403   } else {
404     // Static executables always use version 1.
405     version = 1;
406     expected = sizeof(CrashInfoHeader) + sizeof(CrashInfoDataStatic);
407 
408     static_assert(
409         sizeof(CrashInfoHeader) + sizeof(CrashInfoDataStatic) == kHeaderSize + sizeof(uintptr_t),
410         "Wire protocol structs do not match the data sent.");
411 
412     iovs[3] = {.iov_base = &thread_info->process_info.abort_msg, .iov_len = sizeof(uintptr_t)};
413   }
414   errno = 0;
415   if (fcntl(output_write.get(), F_SETPIPE_SZ, expected) < static_cast<int>(expected)) {
416     fatal_errno("failed to set pipe buffer size");
417   }
418 
419   ssize_t rc = TEMP_FAILURE_RETRY(writev(output_write.get(), iovs, arraysize(iovs)));
420   if (rc == -1) {
421     fatal_errno("failed to write crash info");
422   } else if (rc != expected) {
423     fatal("failed to write crash info, wrote %zd bytes, expected %zd", rc, expected);
424   }
425 
426   // Don't use fork(2) to avoid calling pthread_atfork handlers.
427   pid_t crash_dump_pid = __fork();
428   if (crash_dump_pid == -1) {
429     async_safe_format_log(ANDROID_LOG_FATAL, "libc",
430                           "failed to fork in debuggerd signal handler: %s", strerror(errno));
431   } else if (crash_dump_pid == 0) {
432     TEMP_FAILURE_RETRY(dup2(input_write.get(), STDOUT_FILENO));
433     TEMP_FAILURE_RETRY(dup2(output_read.get(), STDIN_FILENO));
434     input_read.reset();
435     input_write.reset();
436     output_read.reset();
437     output_write.reset();
438 
439     raise_caps();
440 
441     char main_tid[10];
442     char pseudothread_tid[10];
443     char debuggerd_dump_type[10];
444     async_safe_format_buffer(main_tid, sizeof(main_tid), "%d", thread_info->crashing_tid);
445     async_safe_format_buffer(pseudothread_tid, sizeof(pseudothread_tid), "%d",
446                              thread_info->pseudothread_tid);
447     async_safe_format_buffer(debuggerd_dump_type, sizeof(debuggerd_dump_type), "%d",
448                              get_dump_type(thread_info));
449 
450     execle(CRASH_DUMP_PATH, CRASH_DUMP_NAME, main_tid, pseudothread_tid, debuggerd_dump_type,
451            nullptr, nullptr);
452     async_safe_format_log(ANDROID_LOG_FATAL, "libc", "failed to exec crash_dump helper: %s",
453                           strerror(errno));
454     return 1;
455   }
456 
457   input_write.reset();
458   output_read.reset();
459 
460   // crash_dump will ptrace and pause all of our threads, and then write to the pipe to tell
461   // us to fork off a process to read memory from.
462   char buf[4];
463   rc = TEMP_FAILURE_RETRY(read(input_read.get(), &buf, sizeof(buf)));
464 
465   bool success = false;
466   if (rc == 1 && buf[0] == '\1') {
467     // crash_dump successfully started, and is ptracing us.
468     // Fork off a copy of our address space for it to use.
469     create_vm_process();
470     success = true;
471   } else {
472     // Something went wrong, log it.
473     if (rc == -1) {
474       async_safe_format_log(ANDROID_LOG_FATAL, "libc", "read of IPC pipe failed: %s",
475                             strerror(errno));
476     } else if (rc == 0) {
477       async_safe_format_log(ANDROID_LOG_FATAL, "libc",
478                             "crash_dump helper failed to exec, or was killed");
479     } else if (rc != 1) {
480       async_safe_format_log(ANDROID_LOG_FATAL, "libc",
481                             "read of IPC pipe returned unexpected value: %zd", rc);
482     } else if (buf[0] != '\1') {
483       async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper reported failure");
484     }
485   }
486 
487   // Don't leave a zombie child.
488   int status;
489   if (TEMP_FAILURE_RETRY(waitpid(crash_dump_pid, &status, 0)) == -1) {
490     async_safe_format_log(ANDROID_LOG_FATAL, "libc", "failed to wait for crash_dump helper: %s",
491                           strerror(errno));
492   } else if (WIFSTOPPED(status) || WIFSIGNALED(status)) {
493     async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper crashed or stopped");
494   }
495 
496   if (success) {
497     if (thread_info->siginfo->si_signo != BIONIC_SIGNAL_DEBUGGER) {
498       // For crashes, we don't need to minimize pause latency.
499       // Wait for the dump to complete before having the process exit, to avoid being murdered by
500       // ActivityManager or init.
501       TEMP_FAILURE_RETRY(read(input_read, &buf, sizeof(buf)));
502     }
503   }
504 
505   return success ? 0 : 1;
506 }
507 
resend_signal(siginfo_t * info)508 static void resend_signal(siginfo_t* info) {
509   // Signals can either be fatal or nonfatal.
510   // For fatal signals, crash_dump will send us the signal we crashed with
511   // before resuming us, so that processes using waitpid on us will see that we
512   // exited with the correct exit status (e.g. so that sh will report
513   // "Segmentation fault" instead of "Killed"). For this to work, we need
514   // to deregister our signal handler for that signal before continuing.
515   if (info->si_signo != BIONIC_SIGNAL_DEBUGGER) {
516     signal(info->si_signo, SIG_DFL);
517     int rc = syscall(SYS_rt_tgsigqueueinfo, __getpid(), __gettid(), info->si_signo, info);
518     if (rc != 0) {
519       fatal_errno("failed to resend signal during crash");
520     }
521   }
522 }
523 
524 // Handler that does crash dumping by forking and doing the processing in the child.
525 // 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)526 static void debuggerd_signal_handler(int signal_number, siginfo_t* info, void* context) {
527   // Make sure we don't change the value of errno, in case a signal comes in between the process
528   // making a syscall and checking errno.
529   ErrnoRestorer restorer;
530 
531   auto *ucontext = static_cast<ucontext_t*>(context);
532 
533   // It's possible somebody cleared the SA_SIGINFO flag, which would mean
534   // our "info" arg holds an undefined value.
535   if (!have_siginfo(signal_number)) {
536     info = nullptr;
537   }
538 
539   struct siginfo dummy_info = {};
540   if (!info) {
541     memset(&dummy_info, 0, sizeof(dummy_info));
542     dummy_info.si_signo = signal_number;
543     dummy_info.si_code = SI_USER;
544     dummy_info.si_pid = __getpid();
545     dummy_info.si_uid = getuid();
546     info = &dummy_info;
547   } else if (info->si_code >= 0 || info->si_code == SI_TKILL) {
548     // rt_tgsigqueueinfo(2)'s documentation appears to be incorrect on kernels
549     // that contain commit 66dd34a (3.9+). The manpage claims to only allow
550     // negative si_code values that are not SI_TKILL, but 66dd34a changed the
551     // check to allow all si_code values in calls coming from inside the house.
552   }
553 
554   debugger_process_info process_info = {};
555   uintptr_t si_val = reinterpret_cast<uintptr_t>(info->si_ptr);
556   if (signal_number == BIONIC_SIGNAL_DEBUGGER) {
557     if (info->si_code == SI_QUEUE && info->si_pid == __getpid()) {
558       // Allow for the abort message to be explicitly specified via the sigqueue value.
559       // Keep the bottom bit intact for representing whether we want a backtrace or a tombstone.
560       if (si_val != kDebuggerdFallbackSivalUintptrRequestDump) {
561         process_info.abort_msg = reinterpret_cast<void*>(si_val & ~1);
562         info->si_ptr = reinterpret_cast<void*>(si_val & 1);
563       }
564     }
565   } else if (g_callbacks.get_process_info) {
566     process_info = g_callbacks.get_process_info();
567   }
568 
569   gwp_asan_callbacks_t gwp_asan_callbacks = {};
570   if (g_callbacks.get_gwp_asan_callbacks != nullptr) {
571     // GWP-ASan catches use-after-free and heap-buffer-overflow by using PROT_NONE
572     // guard pages, which lead to SEGV. Normally, debuggerd prints a bug report
573     // and the process terminates, but in some cases, we actually want to print
574     // the bug report and let the signal handler return, and restart the process.
575     // In order to do that, we need to disable GWP-ASan's guard pages. The
576     // following callbacks handle this case.
577     gwp_asan_callbacks = g_callbacks.get_gwp_asan_callbacks();
578     if (signal_number == SIGSEGV && signal_has_si_addr(info) &&
579         gwp_asan_callbacks.debuggerd_needs_gwp_asan_recovery &&
580         gwp_asan_callbacks.debuggerd_gwp_asan_pre_crash_report &&
581         gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report &&
582         gwp_asan_callbacks.debuggerd_needs_gwp_asan_recovery(info->si_addr)) {
583       gwp_asan_callbacks.debuggerd_gwp_asan_pre_crash_report(info->si_addr);
584       process_info.recoverable_gwp_asan_crash = true;
585     }
586   }
587 
588   // If sival_int is ~0, it means that the fallback handler has been called
589   // once before and this function is being called again to dump the stack
590   // of a specific thread. It is possible that the prctl call might return 1,
591   // then return 0 in subsequent calls, so check the sival_int to determine if
592   // the fallback handler should be called first.
593   bool no_new_privs = prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) == 1;
594   if (si_val == kDebuggerdFallbackSivalUintptrRequestDump || no_new_privs) {
595     // This check might be racy if another thread sets NO_NEW_PRIVS, but this should be unlikely,
596     // you can only set NO_NEW_PRIVS to 1, and the effect should be at worst a single missing
597     // ANR trace.
598     debuggerd_fallback_handler(info, ucontext, process_info.abort_msg);
599     if (no_new_privs && process_info.recoverable_gwp_asan_crash) {
600       gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report(info->si_addr);
601       return;
602     }
603     resend_signal(info);
604     return;
605   }
606 
607   // Only allow one thread to handle a signal at a time.
608   int ret = pthread_mutex_lock(&crash_mutex);
609   if (ret != 0) {
610     async_safe_format_log(ANDROID_LOG_INFO, "libc", "pthread_mutex_lock failed: %s", strerror(ret));
611     return;
612   }
613 
614   log_signal_summary(info);
615 
616   // If we got here due to the signal BIONIC_SIGNAL_DEBUGGER, it's possible
617   // this is not the main thread, which can cause the intercept logic to fail
618   // since the intercept is only looking for the main thread. In this case,
619   // setting crashing_tid to pid instead of the current thread's tid avoids
620   // the problem.
621   debugger_thread_info thread_info = {
622       .crashing_tid = (signal_number == BIONIC_SIGNAL_DEBUGGER) ? __getpid() : __gettid(),
623       .pseudothread_tid = -1,
624       .siginfo = info,
625       .ucontext = context,
626       .process_info = process_info,
627   };
628 
629   // Set PR_SET_DUMPABLE to 1, so that crash_dump can ptrace us.
630   int orig_dumpable = prctl(PR_GET_DUMPABLE);
631   if (prctl(PR_SET_DUMPABLE, 1) != 0) {
632     fatal_errno("failed to set dumpable");
633   }
634 
635   // On kernels with yama_ptrace enabled, also allow any process to attach.
636   bool restore_orig_ptracer = true;
637   if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) != 0) {
638     if (errno == EINVAL) {
639       // This kernel does not support PR_SET_PTRACER_ANY, or Yama is not enabled.
640       restore_orig_ptracer = false;
641     } else {
642       fatal_errno("failed to set traceable");
643     }
644   }
645 
646   // Essentially pthread_create without CLONE_FILES, so we still work during file descriptor
647   // exhaustion.
648   pid_t child_pid =
649     clone(debuggerd_dispatch_pseudothread, pseudothread_stack,
650           CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID,
651           &thread_info, nullptr, nullptr, &thread_info.pseudothread_tid);
652   if (child_pid == -1) {
653     fatal_errno("failed to spawn debuggerd dispatch thread");
654   }
655 
656   // Wait for the child to start...
657   futex_wait(&thread_info.pseudothread_tid, -1);
658 
659   // and then wait for it to terminate.
660   futex_wait(&thread_info.pseudothread_tid, child_pid);
661 
662   // Restore PR_SET_DUMPABLE to its original value.
663   if (prctl(PR_SET_DUMPABLE, orig_dumpable) != 0) {
664     fatal_errno("failed to restore dumpable");
665   }
666 
667   // Restore PR_SET_PTRACER to its original value.
668   if (restore_orig_ptracer && prctl(PR_SET_PTRACER, 0) != 0) {
669     fatal_errno("failed to restore traceable");
670   }
671 
672   if (info->si_signo == BIONIC_SIGNAL_DEBUGGER) {
673     // If the signal is fatal, don't unlock the mutex to prevent other crashing threads from
674     // starting to dump right before our death.
675     pthread_mutex_unlock(&crash_mutex);
676   } else if (process_info.recoverable_gwp_asan_crash) {
677     gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report(info->si_addr);
678     pthread_mutex_unlock(&crash_mutex);
679   }
680 #ifdef __aarch64__
681   else if (info->si_signo == SIGSEGV &&
682            (info->si_code == SEGV_MTESERR || info->si_code == SEGV_MTEAERR) &&
683            is_permissive_mte()) {
684     // If we are in permissive MTE mode, we do not crash, but instead disable MTE on this thread,
685     // and then let the failing instruction be retried. The second time should work (except
686     // if there is another non-MTE fault).
687     int tagged_addr_ctrl = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
688     if (tagged_addr_ctrl < 0) {
689       fatal_errno("failed to PR_GET_TAGGED_ADDR_CTRL");
690     }
691     tagged_addr_ctrl = (tagged_addr_ctrl & ~PR_MTE_TCF_MASK) | PR_MTE_TCF_NONE;
692     if (prctl(PR_SET_TAGGED_ADDR_CTRL, tagged_addr_ctrl, 0, 0, 0) < 0) {
693       fatal_errno("failed to PR_SET_TAGGED_ADDR_CTRL");
694     }
695     async_safe_format_log(ANDROID_LOG_ERROR, "libc",
696                           "MTE ERROR DETECTED BUT RUNNING IN PERMISSIVE MODE. CONTINUING.");
697     pthread_mutex_unlock(&crash_mutex);
698   } else if (info->si_signo == SIGSEGV && info->si_code == SEGV_MTEAERR && getppid() == 1) {
699     // Back channel to init (see system/core/init/service.cpp) to signal that
700     // this process crashed due to an ASYNC MTE fault and should be considered
701     // for upgrade to SYNC mode. We are re-using the ART profiler signal, which
702     // is always handled (ignored in native processes, handled for generating a
703     // dump in ART processes), so a process will never crash from this signal
704     // except from here.
705     // The kernel is not particularly receptive to adding this information:
706     // https://lore.kernel.org/all/20220909180617.374238-1-fmayer@google.com/, so we work around
707     // like this.
708     info->si_signo = BIONIC_SIGNAL_ART_PROFILER;
709     resend_signal(info);
710   }
711 #endif
712   else {
713     // Resend the signal, so that either the debugger or the parent's waitpid sees it.
714     resend_signal(info);
715   }
716 }
717 
debuggerd_init(debuggerd_callbacks_t * callbacks)718 void debuggerd_init(debuggerd_callbacks_t* callbacks) {
719   if (callbacks) {
720     g_callbacks = *callbacks;
721   }
722 
723   size_t thread_stack_pages = 8;
724   void* thread_stack_allocation = mmap(nullptr, PAGE_SIZE * (thread_stack_pages + 2), PROT_NONE,
725                                        MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
726   if (thread_stack_allocation == MAP_FAILED) {
727     fatal_errno("failed to allocate debuggerd thread stack");
728   }
729 
730   char* stack = static_cast<char*>(thread_stack_allocation) + PAGE_SIZE;
731   if (mprotect(stack, PAGE_SIZE * thread_stack_pages, PROT_READ | PROT_WRITE) != 0) {
732     fatal_errno("failed to mprotect debuggerd thread stack");
733   }
734 
735   // Stack grows negatively, set it to the last byte in the page...
736   stack = (stack + thread_stack_pages * PAGE_SIZE - 1);
737   // and align it.
738   stack -= 15;
739   pseudothread_stack = stack;
740 
741   struct sigaction action;
742   memset(&action, 0, sizeof(action));
743   sigfillset(&action.sa_mask);
744   action.sa_sigaction = debuggerd_signal_handler;
745   action.sa_flags = SA_RESTART | SA_SIGINFO;
746 
747   // Use the alternate signal stack if available so we can catch stack overflows.
748   action.sa_flags |= SA_ONSTACK;
749 
750 #define SA_EXPOSE_TAGBITS 0x00000800
751   // Request that the kernel set tag bits in the fault address. This is necessary for diagnosing MTE
752   // faults.
753   action.sa_flags |= SA_EXPOSE_TAGBITS;
754 
755   debuggerd_register_handlers(&action);
756 }
757 
758 // When debuggerd's signal handler is the first handler called, it's great at
759 // handling the recoverable GWP-ASan mode. For apps, sigchain (from libart) is
760 // always the first signal handler, and so the following function is what
761 // sigchain must call before processing the signal. This allows for processing
762 // of a potentially recoverable GWP-ASan crash. If the signal requires GWP-ASan
763 // recovery, then dump a report (via the regular debuggerd hanndler), and patch
764 // up the allocator, and allow the process to continue (indicated by returning
765 // 'true'). If the crash has nothing to do with GWP-ASan, or recovery isn't
766 // possible, return 'false'.
debuggerd_handle_signal(int signal_number,siginfo_t * info,void * context)767 bool debuggerd_handle_signal(int signal_number, siginfo_t* info, void* context) {
768   if (signal_number != SIGSEGV || !signal_has_si_addr(info)) return false;
769 
770   if (g_callbacks.get_gwp_asan_callbacks == nullptr) return false;
771   gwp_asan_callbacks_t gwp_asan_callbacks = g_callbacks.get_gwp_asan_callbacks();
772   if (gwp_asan_callbacks.debuggerd_needs_gwp_asan_recovery == nullptr ||
773       gwp_asan_callbacks.debuggerd_gwp_asan_pre_crash_report == nullptr ||
774       gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report == nullptr ||
775       !gwp_asan_callbacks.debuggerd_needs_gwp_asan_recovery(info->si_addr)) {
776     return false;
777   }
778 
779   // Only dump a crash report for the first GWP-ASan crash. ActivityManager
780   // doesn't like it when an app crashes multiple times, and is even more strict
781   // about an app crashing multiple times in a short time period. While the app
782   // won't crash fully when we do GWP-ASan recovery, ActivityManager still gets
783   // the information about the crash through the DropBoxManager service. If an
784   // app has multiple back-to-back GWP-ASan crashes, this would lead to the app
785   // being killed, which defeats the purpose of having the recoverable mode. To
786   // mitigate against this, only generate a debuggerd crash report for the first
787   // GWP-ASan crash encountered. We still need to do the patching up of the
788   // allocator though, so do that.
789   static pthread_mutex_t first_crash_mutex = PTHREAD_MUTEX_INITIALIZER;
790   pthread_mutex_lock(&first_crash_mutex);
791   static bool first_crash = true;
792 
793   if (first_crash) {
794     // `debuggerd_signal_handler` will call
795     // `debuggerd_gwp_asan_(pre|post)_crash_report`, so no need to manually call
796     // them here.
797     debuggerd_signal_handler(signal_number, info, context);
798     first_crash = false;
799   } else {
800     gwp_asan_callbacks.debuggerd_gwp_asan_pre_crash_report(info->si_addr);
801     gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report(info->si_addr);
802   }
803 
804   pthread_mutex_unlock(&first_crash_mutex);
805   return true;
806 }
807