1 /*
2 * Copyright 2016, 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 <arpa/inet.h>
18 #include <dirent.h>
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <sys/prctl.h>
22 #include <sys/ptrace.h>
23 #include <sys/types.h>
24 #include <sys/un.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27
28 #include <limits>
29 #include <map>
30 #include <memory>
31 #include <set>
32 #include <vector>
33
34 #include <android-base/errno_restorer.h>
35 #include <android-base/file.h>
36 #include <android-base/logging.h>
37 #include <android-base/macros.h>
38 #include <android-base/parseint.h>
39 #include <android-base/properties.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/strings.h>
42 #include <android-base/unique_fd.h>
43 #include <bionic/macros.h>
44 #include <bionic/reserved_signals.h>
45 #include <cutils/sockets.h>
46 #include <log/log.h>
47 #include <private/android_filesystem_config.h>
48 #include <procinfo/process.h>
49
50 #define ATRACE_TAG ATRACE_TAG_BIONIC
51 #include <utils/Trace.h>
52
53 #include <unwindstack/AndroidUnwinder.h>
54 #include <unwindstack/Error.h>
55 #include <unwindstack/Regs.h>
56
57 #include "libdebuggerd/backtrace.h"
58 #include "libdebuggerd/tombstone.h"
59 #include "libdebuggerd/utility.h"
60
61 #include "debuggerd/handler.h"
62 #include "tombstone_handler.h"
63
64 #include "protocol.h"
65 #include "util.h"
66
67 using android::base::ErrnoRestorer;
68 using android::base::StringPrintf;
69 using android::base::unique_fd;
70
pid_contains_tid(int pid_proc_fd,pid_t tid)71 static bool pid_contains_tid(int pid_proc_fd, pid_t tid) {
72 struct stat st;
73 std::string task_path = StringPrintf("task/%d", tid);
74 return fstatat(pid_proc_fd, task_path.c_str(), &st, 0) == 0;
75 }
76
get_tracer(pid_t tracee)77 static pid_t get_tracer(pid_t tracee) {
78 // Check to see if the thread is being ptraced by another process.
79 android::procinfo::ProcessInfo process_info;
80 if (android::procinfo::GetProcessInfo(tracee, &process_info)) {
81 return process_info.tracer;
82 }
83 return -1;
84 }
85
86 // Attach to a thread, and verify that it's still a member of the given process
ptrace_seize_thread(int pid_proc_fd,pid_t tid,std::string * error,int flags=0)87 static bool ptrace_seize_thread(int pid_proc_fd, pid_t tid, std::string* error, int flags = 0) {
88 if (ptrace(PTRACE_SEIZE, tid, 0, flags) != 0) {
89 if (errno == EPERM) {
90 ErrnoRestorer errno_restorer; // In case get_tracer() fails and we fall through.
91 pid_t tracer_pid = get_tracer(tid);
92 if (tracer_pid > 0) {
93 *error = StringPrintf("failed to attach to thread %d, already traced by %d (%s)", tid,
94 tracer_pid, get_process_name(tracer_pid).c_str());
95 return false;
96 }
97 }
98
99 *error = StringPrintf("failed to attach to thread %d: %s", tid, strerror(errno));
100 return false;
101 }
102
103 // Make sure that the task we attached to is actually part of the pid we're dumping.
104 if (!pid_contains_tid(pid_proc_fd, tid)) {
105 if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
106 PLOG(WARNING) << "failed to detach from thread " << tid;
107 }
108 *error = StringPrintf("thread %d is not in process", tid);
109 return false;
110 }
111
112 return true;
113 }
114
wait_for_stop(pid_t tid,int * received_signal)115 static bool wait_for_stop(pid_t tid, int* received_signal) {
116 while (true) {
117 int status;
118 pid_t result = waitpid(tid, &status, __WALL);
119 if (result != tid) {
120 PLOG(ERROR) << "waitpid failed on " << tid << " while detaching";
121 return false;
122 }
123
124 if (WIFSTOPPED(status)) {
125 if (status >> 16 == PTRACE_EVENT_STOP) {
126 *received_signal = 0;
127 } else {
128 *received_signal = WSTOPSIG(status);
129 }
130 return true;
131 }
132 }
133 }
134
135 // Interrupt a process and wait for it to be interrupted.
ptrace_interrupt(pid_t tid,int * received_signal)136 static bool ptrace_interrupt(pid_t tid, int* received_signal) {
137 if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) == 0) {
138 return wait_for_stop(tid, received_signal);
139 }
140
141 PLOG(ERROR) << "failed to interrupt " << tid << " to detach";
142 return false;
143 }
144
activity_manager_notify(pid_t pid,int signal,const std::string & amfd_data,bool recoverable_gwp_asan_crash)145 static bool activity_manager_notify(pid_t pid, int signal, const std::string& amfd_data,
146 bool recoverable_gwp_asan_crash) {
147 ATRACE_CALL();
148 android::base::unique_fd amfd(socket_local_client(
149 "/data/system/ndebugsocket", ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM));
150 if (amfd.get() == -1) {
151 PLOG(ERROR) << "unable to connect to activity manager";
152 return false;
153 }
154
155 struct timeval tv = {
156 .tv_sec = 1 * android::base::HwTimeoutMultiplier(),
157 .tv_usec = 0,
158 };
159 if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
160 PLOG(ERROR) << "failed to set send timeout on activity manager socket";
161 return false;
162 }
163 tv.tv_sec = 3 * android::base::HwTimeoutMultiplier(); // 3 seconds on handshake read
164 if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
165 PLOG(ERROR) << "failed to set receive timeout on activity manager socket";
166 return false;
167 }
168
169 // Activity Manager protocol:
170 // - 32-bit network-byte-order: pid
171 // - 32-bit network-byte-order: signal number
172 // - byte: recoverable_gwp_asan_crash
173 // - bytes: raw text of the dump
174 // - null terminator
175
176 uint32_t datum = htonl(pid);
177 if (!android::base::WriteFully(amfd, &datum, sizeof(datum))) {
178 PLOG(ERROR) << "AM pid write failed";
179 return false;
180 }
181
182 datum = htonl(signal);
183 if (!android::base::WriteFully(amfd, &datum, sizeof(datum))) {
184 PLOG(ERROR) << "AM signo write failed";
185 return false;
186 }
187
188 uint8_t recoverable_gwp_asan_crash_byte = recoverable_gwp_asan_crash ? 1 : 0;
189 if (!android::base::WriteFully(amfd, &recoverable_gwp_asan_crash_byte,
190 sizeof(recoverable_gwp_asan_crash_byte))) {
191 PLOG(ERROR) << "AM recoverable_gwp_asan_crash_byte write failed";
192 return false;
193 }
194
195 if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size() + 1)) {
196 PLOG(ERROR) << "AM data write failed";
197 return false;
198 }
199
200 // 3 sec timeout reading the ack; we're fine if the read fails.
201 char ack;
202 android::base::ReadFully(amfd, &ack, 1);
203 return true;
204 }
205
206 // Globals used by the abort handler.
207 static pid_t g_target_thread = -1;
208 static bool g_tombstoned_connected = false;
209 static unique_fd g_tombstoned_socket;
210 static unique_fd g_output_fd;
211 static unique_fd g_proto_fd;
212
DefuseSignalHandlers()213 static void DefuseSignalHandlers() {
214 // Don't try to dump ourselves.
215 struct sigaction action = {};
216 action.sa_handler = SIG_DFL;
217 debuggerd_register_handlers(&action);
218
219 sigset_t mask;
220 sigemptyset(&mask);
221 if (sigprocmask(SIG_SETMASK, &mask, nullptr) != 0) {
222 PLOG(FATAL) << "failed to set signal mask";
223 }
224 }
225
Initialize(char ** argv)226 static void Initialize(char** argv) {
227 android::base::InitLogging(argv);
228 android::base::SetAborter([](const char* abort_msg) {
229 // If we abort before we get an output fd, contact tombstoned to let any
230 // potential listeners know that we failed.
231 if (!g_tombstoned_connected) {
232 if (!connect_tombstone_server(g_target_thread, &g_tombstoned_socket, &g_output_fd,
233 &g_proto_fd, kDebuggerdAnyIntercept)) {
234 // We failed to connect, not much we can do.
235 LOG(ERROR) << "failed to connected to tombstoned to report failure";
236 _exit(1);
237 }
238 }
239
240 dprintf(g_output_fd.get(), "crash_dump failed to dump process");
241 if (g_target_thread != 1) {
242 dprintf(g_output_fd.get(), " %d: %s\n", g_target_thread, abort_msg);
243 } else {
244 dprintf(g_output_fd.get(), ": %s\n", abort_msg);
245 }
246
247 _exit(1);
248 });
249 }
250
ParseArgs(int argc,char ** argv,pid_t * pseudothread_tid,DebuggerdDumpType * dump_type)251 static void ParseArgs(int argc, char** argv, pid_t* pseudothread_tid, DebuggerdDumpType* dump_type) {
252 if (argc != 4) {
253 LOG(FATAL) << "wrong number of args: " << argc << " (expected 4)";
254 }
255
256 if (!android::base::ParseInt(argv[1], &g_target_thread, 1, std::numeric_limits<pid_t>::max())) {
257 LOG(FATAL) << "invalid target tid: " << argv[1];
258 }
259
260 if (!android::base::ParseInt(argv[2], pseudothread_tid, 1, std::numeric_limits<pid_t>::max())) {
261 LOG(FATAL) << "invalid pseudothread tid: " << argv[2];
262 }
263
264 int dump_type_int;
265 if (!android::base::ParseInt(argv[3], &dump_type_int, 0)) {
266 LOG(FATAL) << "invalid requested dump type: " << argv[3];
267 }
268
269 *dump_type = static_cast<DebuggerdDumpType>(dump_type_int);
270 switch (*dump_type) {
271 case kDebuggerdNativeBacktrace:
272 case kDebuggerdTombstone:
273 case kDebuggerdTombstoneProto:
274 break;
275
276 default:
277 LOG(FATAL) << "invalid requested dump type: " << dump_type_int;
278 }
279 }
280
ReadCrashInfo(unique_fd & fd,siginfo_t * siginfo,std::unique_ptr<unwindstack::Regs> * regs,ProcessInfo * process_info,bool * recoverable_gwp_asan_crash)281 static void ReadCrashInfo(unique_fd& fd, siginfo_t* siginfo,
282 std::unique_ptr<unwindstack::Regs>* regs, ProcessInfo* process_info,
283 bool* recoverable_gwp_asan_crash) {
284 std::aligned_storage<sizeof(CrashInfo) + 1, alignof(CrashInfo)>::type buf;
285 CrashInfo* crash_info = reinterpret_cast<CrashInfo*>(&buf);
286 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &buf, sizeof(buf)));
287 *recoverable_gwp_asan_crash = false;
288 if (rc == -1) {
289 PLOG(FATAL) << "failed to read target ucontext";
290 } else {
291 ssize_t expected_size = 0;
292 switch (crash_info->header.version) {
293 case 1:
294 case 2:
295 case 3:
296 expected_size = sizeof(CrashInfoHeader) + sizeof(CrashInfoDataStatic);
297 break;
298
299 case 4:
300 expected_size = sizeof(CrashInfoHeader) + sizeof(CrashInfoDataDynamic);
301 break;
302
303 default:
304 LOG(FATAL) << "unexpected CrashInfo version: " << crash_info->header.version;
305 break;
306 };
307
308 if (rc < expected_size) {
309 LOG(FATAL) << "read " << rc << " bytes when reading target crash information, expected "
310 << expected_size;
311 }
312 }
313
314 switch (crash_info->header.version) {
315 case 4:
316 process_info->fdsan_table_address = crash_info->data.d.fdsan_table_address;
317 process_info->gwp_asan_state = crash_info->data.d.gwp_asan_state;
318 process_info->gwp_asan_metadata = crash_info->data.d.gwp_asan_metadata;
319 process_info->scudo_stack_depot = crash_info->data.d.scudo_stack_depot;
320 process_info->scudo_region_info = crash_info->data.d.scudo_region_info;
321 process_info->scudo_ring_buffer = crash_info->data.d.scudo_ring_buffer;
322 process_info->scudo_ring_buffer_size = crash_info->data.d.scudo_ring_buffer_size;
323 *recoverable_gwp_asan_crash = crash_info->data.d.recoverable_gwp_asan_crash;
324 FALLTHROUGH_INTENDED;
325 case 1:
326 case 2:
327 case 3:
328 process_info->abort_msg_address = crash_info->data.s.abort_msg_address;
329 *siginfo = crash_info->data.s.siginfo;
330 if (signal_has_si_addr(siginfo)) {
331 process_info->has_fault_address = true;
332 process_info->maybe_tagged_fault_address = reinterpret_cast<uintptr_t>(siginfo->si_addr);
333 process_info->untagged_fault_address =
334 untag_address(reinterpret_cast<uintptr_t>(siginfo->si_addr));
335 }
336 regs->reset(unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(),
337 &crash_info->data.s.ucontext));
338 break;
339
340 default:
341 __builtin_unreachable();
342 }
343 }
344
345 // Wait for a process to clone and return the child's pid.
346 // Note: this leaves the parent in PTRACE_EVENT_STOP.
wait_for_clone(pid_t pid,bool resume_child)347 static pid_t wait_for_clone(pid_t pid, bool resume_child) {
348 int status;
349 pid_t result = TEMP_FAILURE_RETRY(waitpid(pid, &status, __WALL));
350 if (result == -1) {
351 PLOG(FATAL) << "failed to waitpid";
352 }
353
354 if (WIFEXITED(status)) {
355 LOG(FATAL) << "traced process exited with status " << WEXITSTATUS(status);
356 } else if (WIFSIGNALED(status)) {
357 LOG(FATAL) << "traced process exited with signal " << WTERMSIG(status);
358 } else if (!WIFSTOPPED(status)) {
359 LOG(FATAL) << "process didn't stop? (status = " << status << ")";
360 }
361
362 if (status >> 8 != (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
363 LOG(FATAL) << "process didn't stop due to PTRACE_O_TRACECLONE (status = " << status << ")";
364 }
365
366 pid_t child;
367 if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &child) != 0) {
368 PLOG(FATAL) << "failed to get child pid via PTRACE_GETEVENTMSG";
369 }
370
371 int stop_signal;
372 if (!wait_for_stop(child, &stop_signal)) {
373 PLOG(FATAL) << "failed to waitpid on child";
374 }
375
376 CHECK_EQ(0, stop_signal);
377
378 if (resume_child) {
379 if (ptrace(PTRACE_CONT, child, 0, 0) != 0) {
380 PLOG(FATAL) << "failed to resume child (pid = " << child << ")";
381 }
382 }
383
384 return child;
385 }
386
wait_for_vm_process(pid_t pseudothread_tid)387 static pid_t wait_for_vm_process(pid_t pseudothread_tid) {
388 // The pseudothread will double-fork, we want its grandchild.
389 pid_t intermediate = wait_for_clone(pseudothread_tid, true);
390 pid_t vm_pid = wait_for_clone(intermediate, false);
391 if (ptrace(PTRACE_DETACH, intermediate, 0, 0) != 0) {
392 PLOG(FATAL) << "failed to detach from intermediate vm process";
393 }
394
395 return vm_pid;
396 }
397
InstallSigPipeHandler()398 static void InstallSigPipeHandler() {
399 struct sigaction action = {};
400 action.sa_handler = SIG_IGN;
401 action.sa_flags = SA_RESTART;
402 sigaction(SIGPIPE, &action, nullptr);
403 }
404
main(int argc,char ** argv)405 int main(int argc, char** argv) {
406 DefuseSignalHandlers();
407 InstallSigPipeHandler();
408
409 // There appears to be a bug in the kernel where our death causes SIGHUP to
410 // be sent to our process group if we exit while it has stopped jobs (e.g.
411 // because of wait_for_debugger). Use setsid to create a new process group to
412 // avoid hitting this.
413 setsid();
414
415 atrace_begin(ATRACE_TAG, "before reparent");
416 pid_t target_process = getppid();
417
418 // Open /proc/`getppid()` before we daemonize.
419 std::string target_proc_path = "/proc/" + std::to_string(target_process);
420 int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
421 if (target_proc_fd == -1) {
422 PLOG(FATAL) << "failed to open " << target_proc_path;
423 }
424
425 // Make sure getppid() hasn't changed.
426 if (getppid() != target_process) {
427 LOG(FATAL) << "parent died";
428 }
429 atrace_end(ATRACE_TAG);
430
431 // Reparent ourselves to init, so that the signal handler can waitpid on the
432 // original process to avoid leaving a zombie for non-fatal dumps.
433 // Move the input/output pipes off of stdout/stderr, out of paranoia.
434 unique_fd output_pipe(dup(STDOUT_FILENO));
435 unique_fd input_pipe(dup(STDIN_FILENO));
436
437 unique_fd fork_exit_read, fork_exit_write;
438 if (!Pipe(&fork_exit_read, &fork_exit_write)) {
439 PLOG(FATAL) << "failed to create pipe";
440 }
441
442 pid_t forkpid = fork();
443 if (forkpid == -1) {
444 PLOG(FATAL) << "fork failed";
445 } else if (forkpid == 0) {
446 fork_exit_read.reset();
447 } else {
448 // We need the pseudothread to live until we get around to verifying the vm pid against it.
449 // The last thing it does is block on a waitpid on us, so wait until our child tells us to die.
450 fork_exit_write.reset();
451 char buf;
452 TEMP_FAILURE_RETRY(read(fork_exit_read.get(), &buf, sizeof(buf)));
453 _exit(0);
454 }
455
456 ATRACE_NAME("after reparent");
457 pid_t pseudothread_tid;
458 DebuggerdDumpType dump_type;
459 ProcessInfo process_info;
460
461 Initialize(argv);
462 ParseArgs(argc, argv, &pseudothread_tid, &dump_type);
463
464 // Die if we take too long.
465 //
466 // Note: processes with many threads and minidebug-info can take a bit to
467 // unwind, do not make this too small. b/62828735
468 alarm(30 * android::base::HwTimeoutMultiplier());
469
470 // Collect the list of open files.
471 OpenFilesList open_files;
472 {
473 ATRACE_NAME("open files");
474 populate_open_files_list(&open_files, g_target_thread);
475 }
476
477 // In order to reduce the duration that we pause the process for, we ptrace
478 // the threads, fetch their registers and associated information, and then
479 // fork a separate process as a snapshot of the process's address space.
480 std::set<pid_t> threads;
481 if (!android::procinfo::GetProcessTids(g_target_thread, &threads)) {
482 PLOG(FATAL) << "failed to get process threads";
483 }
484
485 std::map<pid_t, ThreadInfo> thread_info;
486 siginfo_t siginfo;
487 std::string error;
488 bool recoverable_gwp_asan_crash = false;
489
490 {
491 ATRACE_NAME("ptrace");
492 for (pid_t thread : threads) {
493 // Trace the pseudothread separately, so we can use different options.
494 if (thread == pseudothread_tid) {
495 continue;
496 }
497
498 if (!ptrace_seize_thread(target_proc_fd, thread, &error)) {
499 bool fatal = thread == g_target_thread;
500 LOG(fatal ? FATAL : WARNING) << error;
501 }
502
503 ThreadInfo info;
504 info.pid = target_process;
505 info.tid = thread;
506 info.uid = getuid();
507 info.thread_name = get_thread_name(thread);
508
509 unique_fd attr_fd(openat(target_proc_fd, "attr/current", O_RDONLY | O_CLOEXEC));
510 if (!android::base::ReadFdToString(attr_fd, &info.selinux_label)) {
511 PLOG(WARNING) << "failed to read selinux label";
512 }
513
514 if (!ptrace_interrupt(thread, &info.signo)) {
515 PLOG(WARNING) << "failed to ptrace interrupt thread " << thread;
516 ptrace(PTRACE_DETACH, thread, 0, 0);
517 continue;
518 }
519
520 struct iovec tagged_addr_iov = {
521 &info.tagged_addr_ctrl,
522 sizeof(info.tagged_addr_ctrl),
523 };
524 if (ptrace(PTRACE_GETREGSET, thread, NT_ARM_TAGGED_ADDR_CTRL,
525 reinterpret_cast<void*>(&tagged_addr_iov)) == -1) {
526 info.tagged_addr_ctrl = -1;
527 }
528
529 struct iovec pac_enabled_keys_iov = {
530 &info.pac_enabled_keys,
531 sizeof(info.pac_enabled_keys),
532 };
533 if (ptrace(PTRACE_GETREGSET, thread, NT_ARM_PAC_ENABLED_KEYS,
534 reinterpret_cast<void*>(&pac_enabled_keys_iov)) == -1) {
535 info.pac_enabled_keys = -1;
536 }
537
538 if (thread == g_target_thread) {
539 // Read the thread's registers along with the rest of the crash info out of the pipe.
540 ReadCrashInfo(input_pipe, &siginfo, &info.registers, &process_info,
541 &recoverable_gwp_asan_crash);
542 info.siginfo = &siginfo;
543 info.signo = info.siginfo->si_signo;
544
545 info.command_line = get_command_line(g_target_thread);
546 } else {
547 info.registers.reset(unwindstack::Regs::RemoteGet(thread));
548 if (!info.registers) {
549 PLOG(WARNING) << "failed to fetch registers for thread " << thread;
550 ptrace(PTRACE_DETACH, thread, 0, 0);
551 continue;
552 }
553 }
554
555 thread_info[thread] = std::move(info);
556 }
557 }
558
559 // Trace the pseudothread with PTRACE_O_TRACECLONE and tell it to fork.
560 if (!ptrace_seize_thread(target_proc_fd, pseudothread_tid, &error, PTRACE_O_TRACECLONE)) {
561 LOG(FATAL) << "failed to seize pseudothread: " << error;
562 }
563
564 if (TEMP_FAILURE_RETRY(write(output_pipe.get(), "\1", 1)) != 1) {
565 PLOG(FATAL) << "failed to write to pseudothread";
566 }
567
568 pid_t vm_pid = wait_for_vm_process(pseudothread_tid);
569 if (ptrace(PTRACE_DETACH, pseudothread_tid, 0, 0) != 0) {
570 PLOG(FATAL) << "failed to detach from pseudothread";
571 }
572
573 // The pseudothread can die now.
574 fork_exit_write.reset();
575
576 // Defer the message until later, for readability.
577 bool wait_for_debugger = android::base::GetBoolProperty(
578 "debug.debuggerd.wait_for_debugger",
579 android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false));
580 if (siginfo.si_signo == BIONIC_SIGNAL_DEBUGGER) {
581 wait_for_debugger = false;
582 }
583
584 // Detach from all of our attached threads before resuming.
585 for (const auto& [tid, thread] : thread_info) {
586 int resume_signal = thread.signo == BIONIC_SIGNAL_DEBUGGER ? 0 : thread.signo;
587 if (wait_for_debugger) {
588 resume_signal = 0;
589 if (tgkill(target_process, tid, SIGSTOP) != 0) {
590 PLOG(WARNING) << "failed to send SIGSTOP to " << tid;
591 }
592 }
593
594 LOG(DEBUG) << "detaching from thread " << tid;
595 if (ptrace(PTRACE_DETACH, tid, 0, resume_signal) != 0) {
596 PLOG(ERROR) << "failed to detach from thread " << tid;
597 }
598 }
599
600 // Drop our capabilities now that we've fetched all of the information we need.
601 drop_capabilities();
602
603 {
604 ATRACE_NAME("tombstoned_connect");
605 LOG(INFO) << "obtaining output fd from tombstoned, type: " << dump_type;
606 g_tombstoned_connected = connect_tombstone_server(g_target_thread, &g_tombstoned_socket,
607 &g_output_fd, &g_proto_fd, dump_type);
608 }
609
610 if (g_tombstoned_connected) {
611 if (TEMP_FAILURE_RETRY(dup2(g_output_fd.get(), STDOUT_FILENO)) == -1) {
612 PLOG(ERROR) << "failed to dup2 output fd (" << g_output_fd.get() << ") to STDOUT_FILENO";
613 }
614 } else {
615 unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
616 TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
617 g_output_fd = std::move(devnull);
618 }
619
620 LOG(INFO) << "performing dump of process " << target_process
621 << " (target tid = " << g_target_thread << ")";
622
623 int signo = siginfo.si_signo;
624 bool fatal_signal = signo != BIONIC_SIGNAL_DEBUGGER;
625 bool backtrace = false;
626
627 // si_value is special when used with BIONIC_SIGNAL_DEBUGGER.
628 // 0: dump tombstone
629 // 1: dump backtrace
630 if (!fatal_signal) {
631 int si_val = siginfo.si_value.sival_int;
632 if (si_val == 0) {
633 backtrace = false;
634 } else if (si_val == 1) {
635 backtrace = true;
636 } else {
637 LOG(WARNING) << "unknown si_value value " << si_val;
638 }
639 }
640
641 // TODO: Use seccomp to lock ourselves down.
642
643 unwindstack::AndroidRemoteUnwinder unwinder(vm_pid, unwindstack::Regs::CurrentArch());
644 unwindstack::ErrorData error_data;
645 if (!unwinder.Initialize(error_data)) {
646 LOG(FATAL) << "Failed to initialize unwinder object: "
647 << unwindstack::GetErrorCodeString(error_data.code);
648 }
649
650 std::string amfd_data;
651 if (backtrace) {
652 ATRACE_NAME("dump_backtrace");
653 dump_backtrace(std::move(g_output_fd), &unwinder, thread_info, g_target_thread);
654 } else {
655 {
656 ATRACE_NAME("fdsan table dump");
657 populate_fdsan_table(&open_files, unwinder.GetProcessMemory(),
658 process_info.fdsan_table_address);
659 }
660
661 {
662 ATRACE_NAME("engrave_tombstone");
663 engrave_tombstone(std::move(g_output_fd), std::move(g_proto_fd), &unwinder, thread_info,
664 g_target_thread, process_info, &open_files, &amfd_data);
665 }
666 }
667
668 if (fatal_signal) {
669 // Don't try to notify ActivityManager if it just crashed, or we might hang until timeout.
670 if (thread_info[target_process].thread_name != "system_server") {
671 activity_manager_notify(target_process, signo, amfd_data, recoverable_gwp_asan_crash);
672 }
673 }
674
675 if (wait_for_debugger) {
676 // Use ALOGI to line up with output from engrave_tombstone.
677 ALOGI(
678 "***********************************************************\n"
679 "* Process %d has been suspended while crashing.\n"
680 "* To attach the debugger, run this on the host:\n"
681 "*\n"
682 "* lldbclient.py -p %d\n"
683 "*\n"
684 "***********************************************************",
685 target_process, target_process);
686 }
687
688 // Close stdout before we notify tombstoned of completion.
689 close(STDOUT_FILENO);
690 if (g_tombstoned_connected &&
691 !notify_completion(g_tombstoned_socket.get(), g_output_fd.get(), g_proto_fd.get())) {
692 LOG(ERROR) << "failed to notify tombstoned of completion";
693 }
694
695 return 0;
696 }
697