1 /*
2  * Copyright (C) 2012-2014 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 #define LOG_TAG "DEBUG"
18 
19 #include "libdebuggerd/tombstone.h"
20 
21 #include <dirent.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <signal.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/mman.h>
31 #include <sys/ptrace.h>
32 #include <sys/stat.h>
33 #include <time.h>
34 
35 #include <memory>
36 #include <string>
37 
38 #include <android-base/file.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 <android/log.h>
44 #include <async_safe/log.h>
45 #include <bionic/macros.h>
46 #include <log/log.h>
47 #include <log/log_read.h>
48 #include <log/logprint.h>
49 #include <private/android_filesystem_config.h>
50 #include <unwindstack/DexFiles.h>
51 #include <unwindstack/JitDebug.h>
52 #include <unwindstack/Maps.h>
53 #include <unwindstack/Memory.h>
54 #include <unwindstack/Regs.h>
55 #include <unwindstack/Unwinder.h>
56 
57 #include "libdebuggerd/backtrace.h"
58 #include "libdebuggerd/gwp_asan.h"
59 #include "libdebuggerd/open_files_list.h"
60 #include "libdebuggerd/scudo.h"
61 #include "libdebuggerd/utility.h"
62 #include "util.h"
63 
64 #include "gwp_asan/common.h"
65 #include "gwp_asan/crash_handler.h"
66 
67 #include "tombstone.pb.h"
68 
69 using android::base::GetBoolProperty;
70 using android::base::GetProperty;
71 using android::base::StringPrintf;
72 using android::base::unique_fd;
73 
74 using namespace std::literals::string_literals;
75 
76 #define STACK_WORDS 16
77 
dump_header_info(log_t * log)78 static void dump_header_info(log_t* log) {
79   auto fingerprint = GetProperty("ro.build.fingerprint", "unknown");
80   auto revision = GetProperty("ro.revision", "unknown");
81 
82   _LOG(log, logtype::HEADER, "Build fingerprint: '%s'\n", fingerprint.c_str());
83   _LOG(log, logtype::HEADER, "Revision: '%s'\n", revision.c_str());
84   _LOG(log, logtype::HEADER, "ABI: '%s'\n", ABI_STRING);
85 }
86 
get_stack_overflow_cause(uint64_t fault_addr,uint64_t sp,unwindstack::Maps * maps)87 static std::string get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
88                                             unwindstack::Maps* maps) {
89   static constexpr uint64_t kMaxDifferenceBytes = 256;
90   uint64_t difference;
91   if (sp >= fault_addr) {
92     difference = sp - fault_addr;
93   } else {
94     difference = fault_addr - sp;
95   }
96   if (difference <= kMaxDifferenceBytes) {
97     // The faulting address is close to the current sp, check if the sp
98     // indicates a stack overflow.
99     // On arm, the sp does not get updated when the instruction faults.
100     // In this case, the sp will still be in a valid map, which is the
101     // last case below.
102     // On aarch64, the sp does get updated when the instruction faults.
103     // In this case, the sp will be in either an invalid map if triggered
104     // on the main thread, or in a guard map if in another thread, which
105     // will be the first case or second case from below.
106     unwindstack::MapInfo* map_info = maps->Find(sp);
107     if (map_info == nullptr) {
108       return "stack pointer is in a non-existent map; likely due to stack overflow.";
109     } else if ((map_info->flags() & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
110       return "stack pointer is not in a rw map; likely due to stack overflow.";
111     } else if ((sp - map_info->start()) <= kMaxDifferenceBytes) {
112       return "stack pointer is close to top of stack; likely stack overflow.";
113     }
114   }
115   return "";
116 }
117 
dump_probable_cause(log_t * log,const siginfo_t * si,unwindstack::Maps * maps,unwindstack::Regs * regs)118 static void dump_probable_cause(log_t* log, const siginfo_t* si, unwindstack::Maps* maps,
119                                 unwindstack::Regs* regs) {
120   std::string cause;
121   if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
122     if (si->si_addr < reinterpret_cast<void*>(4096)) {
123       cause = StringPrintf("null pointer dereference");
124     } else if (si->si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
125       cause = "call to kuser_helper_version";
126     } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
127       cause = "call to kuser_get_tls";
128     } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
129       cause = "call to kuser_cmpxchg";
130     } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
131       cause = "call to kuser_memory_barrier";
132     } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
133       cause = "call to kuser_cmpxchg64";
134     } else {
135       cause = get_stack_overflow_cause(reinterpret_cast<uint64_t>(si->si_addr), regs->sp(), maps);
136     }
137   } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
138     uint64_t fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
139     unwindstack::MapInfo* map_info = maps->Find(fault_addr);
140     if (map_info != nullptr && map_info->flags() == PROT_EXEC) {
141       cause = "execute-only (no-read) memory access error; likely due to data in .text.";
142     } else {
143       cause = get_stack_overflow_cause(fault_addr, regs->sp(), maps);
144     }
145   } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
146     cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
147                          si->si_syscall);
148   }
149 
150   if (!cause.empty()) _LOG(log, logtype::HEADER, "Cause: %s\n", cause.c_str());
151 }
152 
dump_signal_info(log_t * log,const ThreadInfo & thread_info,const ProcessInfo & process_info,unwindstack::Memory * process_memory)153 static void dump_signal_info(log_t* log, const ThreadInfo& thread_info,
154                              const ProcessInfo& process_info, unwindstack::Memory* process_memory) {
155   char addr_desc[64];  // ", fault addr 0x1234"
156   if (process_info.has_fault_address) {
157     // SIGILL faults will never have tagged addresses, so okay to
158     // indiscriminately use the tagged address here.
159     size_t addr = process_info.maybe_tagged_fault_address;
160     if (thread_info.siginfo->si_signo == SIGILL) {
161       uint32_t instruction = {};
162       process_memory->Read(addr, &instruction, sizeof(instruction));
163       snprintf(addr_desc, sizeof(addr_desc), "0x%zx (*pc=%#08x)", addr, instruction);
164     } else {
165       snprintf(addr_desc, sizeof(addr_desc), "0x%zx", addr);
166     }
167   } else {
168     snprintf(addr_desc, sizeof(addr_desc), "--------");
169   }
170 
171   char sender_desc[32] = {};  // " from pid 1234, uid 666"
172   if (signal_has_sender(thread_info.siginfo, thread_info.pid)) {
173     get_signal_sender(sender_desc, sizeof(sender_desc), thread_info.siginfo);
174   }
175 
176   _LOG(log, logtype::HEADER, "signal %d (%s), code %d (%s%s), fault addr %s\n",
177        thread_info.siginfo->si_signo, get_signame(thread_info.siginfo),
178        thread_info.siginfo->si_code, get_sigcode(thread_info.siginfo), sender_desc, addr_desc);
179 }
180 
dump_thread_info(log_t * log,const ThreadInfo & thread_info)181 static void dump_thread_info(log_t* log, const ThreadInfo& thread_info) {
182   // Don't try to collect logs from the threads that implement the logging system itself.
183   if (thread_info.uid == AID_LOGD) log->should_retrieve_logcat = false;
184 
185   const char* process_name = "<unknown>";
186   if (!thread_info.command_line.empty()) {
187     process_name = thread_info.command_line[0].c_str();
188   }
189 
190   _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s  >>> %s <<<\n", thread_info.pid,
191        thread_info.tid, thread_info.thread_name.c_str(), process_name);
192   _LOG(log, logtype::HEADER, "uid: %d\n", thread_info.uid);
193   if (thread_info.tagged_addr_ctrl != -1) {
194     _LOG(log, logtype::HEADER, "tagged_addr_ctrl: %016lx\n", thread_info.tagged_addr_ctrl);
195   }
196 }
197 
get_addr_string(uint64_t addr)198 static std::string get_addr_string(uint64_t addr) {
199   std::string addr_str;
200 #if defined(__LP64__)
201   addr_str = StringPrintf("%08x'%08x", static_cast<uint32_t>(addr >> 32),
202                           static_cast<uint32_t>(addr & 0xffffffff));
203 #else
204   addr_str = StringPrintf("%08x", static_cast<uint32_t>(addr));
205 #endif
206   return addr_str;
207 }
208 
dump_abort_message(log_t * log,unwindstack::Memory * process_memory,uint64_t address)209 static void dump_abort_message(log_t* log, unwindstack::Memory* process_memory, uint64_t address) {
210   if (address == 0) {
211     return;
212   }
213 
214   size_t length;
215   if (!process_memory->ReadFully(address, &length, sizeof(length))) {
216     _LOG(log, logtype::HEADER, "Failed to read abort message header: %s\n", strerror(errno));
217     return;
218   }
219 
220   // The length field includes the length of the length field itself.
221   if (length < sizeof(size_t)) {
222     _LOG(log, logtype::HEADER, "Abort message header malformed: claimed length = %zd\n", length);
223     return;
224   }
225 
226   length -= sizeof(size_t);
227 
228   // The abort message should be null terminated already, but reserve a spot for NUL just in case.
229   std::vector<char> msg(length + 1);
230   if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
231     _LOG(log, logtype::HEADER, "Failed to read abort message: %s\n", strerror(errno));
232     return;
233   }
234 
235   _LOG(log, logtype::HEADER, "Abort message: '%s'\n", &msg[0]);
236 }
237 
dump_all_maps(log_t * log,unwindstack::Unwinder * unwinder,uint64_t addr)238 static void dump_all_maps(log_t* log, unwindstack::Unwinder* unwinder, uint64_t addr) {
239   bool print_fault_address_marker = addr;
240 
241   unwindstack::Maps* maps = unwinder->GetMaps();
242   _LOG(log, logtype::MAPS,
243        "\n"
244        "memory map (%zu entr%s):",
245        maps->Total(), maps->Total() == 1 ? "y" : "ies");
246   if (print_fault_address_marker) {
247     if (maps->Total() != 0 && addr < maps->Get(0)->start()) {
248       _LOG(log, logtype::MAPS, "\n--->Fault address falls at %s before any mapped regions\n",
249            get_addr_string(addr).c_str());
250       print_fault_address_marker = false;
251     } else {
252       _LOG(log, logtype::MAPS, " (fault address prefixed with --->)\n");
253     }
254   } else {
255     _LOG(log, logtype::MAPS, "\n");
256   }
257 
258   std::shared_ptr<unwindstack::Memory>& process_memory = unwinder->GetProcessMemory();
259 
260   std::string line;
261   for (auto const& map_info : *maps) {
262     line = "    ";
263     if (print_fault_address_marker) {
264       if (addr < map_info->start()) {
265         _LOG(log, logtype::MAPS, "--->Fault address falls at %s between mapped regions\n",
266              get_addr_string(addr).c_str());
267         print_fault_address_marker = false;
268       } else if (addr >= map_info->start() && addr < map_info->end()) {
269         line = "--->";
270         print_fault_address_marker = false;
271       }
272     }
273     line += get_addr_string(map_info->start()) + '-' + get_addr_string(map_info->end() - 1) + ' ';
274     if (map_info->flags() & PROT_READ) {
275       line += 'r';
276     } else {
277       line += '-';
278     }
279     if (map_info->flags() & PROT_WRITE) {
280       line += 'w';
281     } else {
282       line += '-';
283     }
284     if (map_info->flags() & PROT_EXEC) {
285       line += 'x';
286     } else {
287       line += '-';
288     }
289     line += StringPrintf("  %8" PRIx64 "  %8" PRIx64, map_info->offset(),
290                          map_info->end() - map_info->start());
291     bool space_needed = true;
292     if (!map_info->name().empty()) {
293       space_needed = false;
294       line += "  " + map_info->name();
295       std::string build_id = map_info->GetPrintableBuildID();
296       if (!build_id.empty()) {
297         line += " (BuildId: " + build_id + ")";
298       }
299     }
300     uint64_t load_bias = map_info->GetLoadBias(process_memory);
301     if (load_bias != 0) {
302       if (space_needed) {
303         line += ' ';
304       }
305       line += StringPrintf(" (load bias 0x%" PRIx64 ")", load_bias);
306     }
307     _LOG(log, logtype::MAPS, "%s\n", line.c_str());
308   }
309   if (print_fault_address_marker) {
310     _LOG(log, logtype::MAPS, "--->Fault address falls at %s after any mapped regions\n",
311          get_addr_string(addr).c_str());
312   }
313 }
314 
print_register_row(log_t * log,const std::vector<std::pair<std::string,uint64_t>> & registers)315 static void print_register_row(log_t* log,
316                                const std::vector<std::pair<std::string, uint64_t>>& registers) {
317   std::string output;
318   for (auto& [name, value] : registers) {
319     output += android::base::StringPrintf("  %-3s %0*" PRIx64, name.c_str(),
320                                           static_cast<int>(2 * sizeof(void*)),
321                                           static_cast<uint64_t>(value));
322   }
323 
324   _LOG(log, logtype::REGISTERS, "  %s\n", output.c_str());
325 }
326 
dump_registers(log_t * log,unwindstack::Regs * regs)327 void dump_registers(log_t* log, unwindstack::Regs* regs) {
328   // Split lr/sp/pc into their own special row.
329   static constexpr size_t column_count = 4;
330   std::vector<std::pair<std::string, uint64_t>> current_row;
331   std::vector<std::pair<std::string, uint64_t>> special_row;
332 
333 #if defined(__arm__) || defined(__aarch64__)
334   static constexpr const char* special_registers[] = {"ip", "lr", "sp", "pc", "pst"};
335 #elif defined(__i386__)
336   static constexpr const char* special_registers[] = {"ebp", "esp", "eip"};
337 #elif defined(__x86_64__)
338   static constexpr const char* special_registers[] = {"rbp", "rsp", "rip"};
339 #else
340   static constexpr const char* special_registers[] = {};
341 #endif
342 
343   regs->IterateRegisters([log, &current_row, &special_row](const char* name, uint64_t value) {
344     auto row = &current_row;
345     for (const char* special_name : special_registers) {
346       if (strcmp(special_name, name) == 0) {
347         row = &special_row;
348         break;
349       }
350     }
351 
352     row->emplace_back(name, value);
353     if (current_row.size() == column_count) {
354       print_register_row(log, current_row);
355       current_row.clear();
356     }
357   });
358 
359   if (!current_row.empty()) {
360     print_register_row(log, current_row);
361   }
362 
363   print_register_row(log, special_row);
364 }
365 
dump_memory_and_code(log_t * log,unwindstack::Maps * maps,unwindstack::Memory * memory,unwindstack::Regs * regs)366 void dump_memory_and_code(log_t* log, unwindstack::Maps* maps, unwindstack::Memory* memory,
367                           unwindstack::Regs* regs) {
368   regs->IterateRegisters([log, maps, memory](const char* reg_name, uint64_t reg_value) {
369     std::string label{"memory near "s + reg_name};
370     if (maps) {
371       unwindstack::MapInfo* map_info = maps->Find(untag_address(reg_value));
372       if (map_info != nullptr && !map_info->name().empty()) {
373         label += " (" + map_info->name() + ")";
374       }
375     }
376     dump_memory(log, memory, reg_value, label);
377   });
378 }
379 
dump_thread(log_t * log,unwindstack::Unwinder * unwinder,const ThreadInfo & thread_info,const ProcessInfo & process_info,bool primary_thread)380 static bool dump_thread(log_t* log, unwindstack::Unwinder* unwinder, const ThreadInfo& thread_info,
381                         const ProcessInfo& process_info, bool primary_thread) {
382   log->current_tid = thread_info.tid;
383   if (!primary_thread) {
384     _LOG(log, logtype::THREAD, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
385   }
386   dump_thread_info(log, thread_info);
387 
388   if (thread_info.siginfo) {
389     dump_signal_info(log, thread_info, process_info, unwinder->GetProcessMemory().get());
390   }
391 
392   std::unique_ptr<GwpAsanCrashData> gwp_asan_crash_data;
393   std::unique_ptr<ScudoCrashData> scudo_crash_data;
394   if (primary_thread) {
395     gwp_asan_crash_data = std::make_unique<GwpAsanCrashData>(unwinder->GetProcessMemory().get(),
396                                                              process_info, thread_info);
397     scudo_crash_data =
398         std::make_unique<ScudoCrashData>(unwinder->GetProcessMemory().get(), process_info);
399   }
400 
401   if (primary_thread && gwp_asan_crash_data->CrashIsMine()) {
402     gwp_asan_crash_data->DumpCause(log);
403   } else if (thread_info.siginfo && !(primary_thread && scudo_crash_data->CrashIsMine())) {
404     dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps(), thread_info.registers.get());
405   }
406 
407   if (primary_thread) {
408     dump_abort_message(log, unwinder->GetProcessMemory().get(), process_info.abort_msg_address);
409   }
410 
411   dump_registers(log, thread_info.registers.get());
412 
413   // Unwind will mutate the registers, so make a copy first.
414   std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
415   unwinder->SetRegs(regs_copy.get());
416   unwinder->Unwind();
417   if (unwinder->NumFrames() == 0) {
418     _LOG(log, logtype::THREAD, "Failed to unwind\n");
419     if (unwinder->LastErrorCode() != unwindstack::ERROR_NONE) {
420       _LOG(log, logtype::THREAD, "  Error code: %s\n", unwinder->LastErrorCodeString());
421       _LOG(log, logtype::THREAD, "  Error address: 0x%" PRIx64 "\n", unwinder->LastErrorAddress());
422     }
423   } else {
424     _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
425     log_backtrace(log, unwinder, "    ");
426   }
427 
428   if (primary_thread) {
429     if (gwp_asan_crash_data->HasDeallocationTrace()) {
430       gwp_asan_crash_data->DumpDeallocationTrace(log, unwinder);
431     }
432 
433     if (gwp_asan_crash_data->HasAllocationTrace()) {
434       gwp_asan_crash_data->DumpAllocationTrace(log, unwinder);
435     }
436 
437     scudo_crash_data->DumpCause(log, unwinder);
438 
439     unwindstack::Maps* maps = unwinder->GetMaps();
440     dump_memory_and_code(log, maps, unwinder->GetProcessMemory().get(),
441                          thread_info.registers.get());
442     if (maps != nullptr) {
443       uint64_t addr = 0;
444       if (process_info.has_fault_address) {
445         addr = process_info.untagged_fault_address;
446       }
447       dump_all_maps(log, unwinder, addr);
448     }
449   }
450 
451   log->current_tid = log->crashed_tid;
452   return true;
453 }
454 
455 // Reads the contents of the specified log device, filters out the entries
456 // that don't match the specified pid, and writes them to the tombstone file.
457 //
458 // If "tail" is non-zero, log the last "tail" number of lines.
dump_log_file(log_t * log,pid_t pid,const char * filename,unsigned int tail)459 static void dump_log_file(log_t* log, pid_t pid, const char* filename, unsigned int tail) {
460   bool first = true;
461   logger_list* logger_list;
462 
463   if (!log->should_retrieve_logcat) {
464     return;
465   }
466 
467   logger_list =
468       android_logger_list_open(android_name_to_log_id(filename), ANDROID_LOG_NONBLOCK, tail, pid);
469 
470   if (!logger_list) {
471     ALOGE("Unable to open %s: %s\n", filename, strerror(errno));
472     return;
473   }
474 
475   while (true) {
476     log_msg log_entry;
477     ssize_t actual = android_logger_list_read(logger_list, &log_entry);
478 
479     if (actual < 0) {
480       if (actual == -EINTR) {
481         // interrupted by signal, retry
482         continue;
483       } else if (actual == -EAGAIN) {
484         // non-blocking EOF; we're done
485         break;
486       } else {
487         ALOGE("Error while reading log: %s\n", strerror(-actual));
488         break;
489       }
490     } else if (actual == 0) {
491       ALOGE("Got zero bytes while reading log: %s\n", strerror(errno));
492       break;
493     }
494 
495     // NOTE: if you ALOGV something here, this will spin forever,
496     // because you will be writing as fast as you're reading.  Any
497     // high-frequency debug diagnostics should just be written to
498     // the tombstone file.
499 
500     if (first) {
501       _LOG(log, logtype::LOGS, "--------- %slog %s\n", tail ? "tail end of " : "", filename);
502       first = false;
503     }
504 
505     // Msg format is: <priority:1><tag:N>\0<message:N>\0
506     //
507     // We want to display it in the same format as "logcat -v threadtime"
508     // (although in this case the pid is redundant).
509     char timeBuf[32];
510     time_t sec = static_cast<time_t>(log_entry.entry.sec);
511     tm tm;
512     localtime_r(&sec, &tm);
513     strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", &tm);
514 
515     char* msg = log_entry.msg();
516     if (msg == nullptr) {
517       continue;
518     }
519     unsigned char prio = msg[0];
520     char* tag = msg + 1;
521     msg = tag + strlen(tag) + 1;
522 
523     // consume any trailing newlines
524     char* nl = msg + strlen(msg) - 1;
525     while (nl >= msg && *nl == '\n') {
526       *nl-- = '\0';
527     }
528 
529     static const char* kPrioChars = "!.VDIWEFS";
530     char prioChar = (prio < strlen(kPrioChars) ? kPrioChars[prio] : '?');
531 
532     // Look for line breaks ('\n') and display each text line
533     // on a separate line, prefixed with the header, like logcat does.
534     do {
535       nl = strchr(msg, '\n');
536       if (nl != nullptr) {
537         *nl = '\0';
538         ++nl;
539       }
540 
541       _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8s: %s\n", timeBuf,
542            log_entry.entry.nsec / 1000000, log_entry.entry.pid, log_entry.entry.tid, prioChar, tag,
543            msg);
544     } while ((msg = nl));
545   }
546 
547   android_logger_list_free(logger_list);
548 }
549 
550 // Dumps the logs generated by the specified pid to the tombstone, from both
551 // "system" and "main" log devices.  Ideally we'd interleave the output.
dump_logs(log_t * log,pid_t pid,unsigned int tail)552 static void dump_logs(log_t* log, pid_t pid, unsigned int tail) {
553   if (pid == getpid()) {
554     // Cowardly refuse to dump logs while we're running in-process.
555     return;
556   }
557 
558   dump_log_file(log, pid, "system", tail);
559   dump_log_file(log, pid, "main", tail);
560 }
561 
engrave_tombstone_ucontext(int tombstone_fd,int proto_fd,uint64_t abort_msg_address,siginfo_t * siginfo,ucontext_t * ucontext)562 void engrave_tombstone_ucontext(int tombstone_fd, int proto_fd, uint64_t abort_msg_address,
563                                 siginfo_t* siginfo, ucontext_t* ucontext) {
564   pid_t uid = getuid();
565   pid_t pid = getpid();
566   pid_t tid = gettid();
567 
568   log_t log;
569   log.current_tid = tid;
570   log.crashed_tid = tid;
571   log.tfd = tombstone_fd;
572   log.amfd_data = nullptr;
573 
574   std::string thread_name = get_thread_name(tid);
575   std::vector<std::string> command_line = get_command_line(pid);
576 
577   std::unique_ptr<unwindstack::Regs> regs(
578       unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), ucontext));
579 
580   std::string selinux_label;
581   android::base::ReadFileToString("/proc/self/attr/current", &selinux_label);
582 
583   std::map<pid_t, ThreadInfo> threads;
584   threads[tid] = ThreadInfo{
585       .registers = std::move(regs),
586       .uid = uid,
587       .tid = tid,
588       .thread_name = std::move(thread_name),
589       .pid = pid,
590       .command_line = std::move(command_line),
591       .selinux_label = std::move(selinux_label),
592       .siginfo = siginfo,
593   };
594 
595   unwindstack::UnwinderFromPid unwinder(kMaxFrames, pid, unwindstack::Regs::CurrentArch());
596   auto process_memory =
597       unwindstack::Memory::CreateProcessMemoryCached(getpid());
598   unwinder.SetProcessMemory(process_memory);
599   if (!unwinder.Init()) {
600     async_safe_fatal("failed to init unwinder object");
601   }
602 
603   ProcessInfo process_info;
604   process_info.abort_msg_address = abort_msg_address;
605   engrave_tombstone(unique_fd(dup(tombstone_fd)), unique_fd(dup(proto_fd)), &unwinder, threads, tid,
606                     process_info, nullptr, nullptr);
607 }
608 
engrave_tombstone(unique_fd output_fd,unique_fd proto_fd,unwindstack::Unwinder * unwinder,const std::map<pid_t,ThreadInfo> & threads,pid_t target_thread,const ProcessInfo & process_info,OpenFilesList * open_files,std::string * amfd_data)609 void engrave_tombstone(unique_fd output_fd, unique_fd proto_fd, unwindstack::Unwinder* unwinder,
610                        const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
611                        const ProcessInfo& process_info, OpenFilesList* open_files,
612                        std::string* amfd_data) {
613   // Don't copy log messages to tombstone unless this is a development device.
614   Tombstone tombstone;
615   engrave_tombstone_proto(&tombstone, unwinder, threads, target_thread, process_info, open_files);
616 
617   if (proto_fd != -1) {
618     if (!tombstone.SerializeToFileDescriptor(proto_fd.get())) {
619       async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to write proto tombstone: %s",
620                             strerror(errno));
621     }
622   }
623 
624   log_t log;
625   log.current_tid = target_thread;
626   log.crashed_tid = target_thread;
627   log.tfd = output_fd.get();
628   log.amfd_data = amfd_data;
629 
630   bool translate_proto = GetBoolProperty("debug.debuggerd.translate_proto_to_text", true);
631   if (translate_proto) {
632     tombstone_proto_to_text(tombstone, [&log](const std::string& line, bool should_log) {
633       _LOG(&log, should_log ? logtype::HEADER : logtype::LOGS, "%s\n", line.c_str());
634     });
635   } else {
636     bool want_logs = GetBoolProperty("ro.debuggable", false);
637 
638     _LOG(&log, logtype::HEADER,
639          "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
640     dump_header_info(&log);
641     _LOG(&log, logtype::HEADER, "Timestamp: %s\n", get_timestamp().c_str());
642 
643     auto it = threads.find(target_thread);
644     if (it == threads.end()) {
645       async_safe_fatal("failed to find target thread");
646     }
647 
648     dump_thread(&log, unwinder, it->second, process_info, true);
649 
650     if (want_logs) {
651       dump_logs(&log, it->second.pid, 50);
652     }
653 
654     for (auto& [tid, thread_info] : threads) {
655       if (tid == target_thread) {
656         continue;
657       }
658 
659       dump_thread(&log, unwinder, thread_info, process_info, false);
660     }
661 
662     if (open_files) {
663       _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
664       dump_open_files_list(&log, *open_files, "    ");
665     }
666 
667     if (want_logs) {
668       dump_logs(&log, it->second.pid, 0);
669     }
670   }
671 }
672