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