1 /*
2  * Copyright (C) 2020 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 #include "libdebuggerd/gwp_asan.h"
21 #include "libdebuggerd/scudo.h"
22 
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <inttypes.h>
26 #include <signal.h>
27 #include <stddef.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/mman.h>
31 #include <time.h>
32 
33 #include <memory>
34 #include <optional>
35 #include <string>
36 
37 #include <async_safe/log.h>
38 
39 #include <android-base/file.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 
45 #include <android/log.h>
46 #include <bionic/macros.h>
47 #include <log/log.h>
48 #include <log/log_read.h>
49 #include <log/logprint.h>
50 #include <private/android_filesystem_config.h>
51 
52 #include <procinfo/process.h>
53 #include <unwindstack/Maps.h>
54 #include <unwindstack/Memory.h>
55 #include <unwindstack/Regs.h>
56 #include <unwindstack/Unwinder.h>
57 
58 #include "libdebuggerd/open_files_list.h"
59 #include "libdebuggerd/utility.h"
60 #include "util.h"
61 
62 #include "tombstone.pb.h"
63 
64 using android::base::StringPrintf;
65 
66 // Use the demangler from libc++.
67 extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
68 
get_arch()69 static Architecture get_arch() {
70 #if defined(__arm__)
71   return Architecture::ARM32;
72 #elif defined(__aarch64__)
73   return Architecture::ARM64;
74 #elif defined(__i386__)
75   return Architecture::X86;
76 #elif defined(__x86_64__)
77   return Architecture::X86_64;
78 #else
79 #error Unknown architecture!
80 #endif
81 }
82 
get_stack_overflow_cause(uint64_t fault_addr,uint64_t sp,unwindstack::Maps * maps)83 static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
84                                                            unwindstack::Maps* maps) {
85   static constexpr uint64_t kMaxDifferenceBytes = 256;
86   uint64_t difference;
87   if (sp >= fault_addr) {
88     difference = sp - fault_addr;
89   } else {
90     difference = fault_addr - sp;
91   }
92   if (difference <= kMaxDifferenceBytes) {
93     // The faulting address is close to the current sp, check if the sp
94     // indicates a stack overflow.
95     // On arm, the sp does not get updated when the instruction faults.
96     // In this case, the sp will still be in a valid map, which is the
97     // last case below.
98     // On aarch64, the sp does get updated when the instruction faults.
99     // In this case, the sp will be in either an invalid map if triggered
100     // on the main thread, or in a guard map if in another thread, which
101     // will be the first case or second case from below.
102     unwindstack::MapInfo* map_info = maps->Find(sp);
103     if (map_info == nullptr) {
104       return "stack pointer is in a non-existent map; likely due to stack overflow.";
105     } else if ((map_info->flags() & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
106       return "stack pointer is not in a rw map; likely due to stack overflow.";
107     } else if ((sp - map_info->start()) <= kMaxDifferenceBytes) {
108       return "stack pointer is close to top of stack; likely stack overflow.";
109     }
110   }
111   return {};
112 }
113 
set_human_readable_cause(Cause * cause,uint64_t fault_addr)114 void set_human_readable_cause(Cause* cause, uint64_t fault_addr) {
115   if (!cause->has_memory_error() || !cause->memory_error().has_heap()) {
116     return;
117   }
118 
119   const MemoryError& memory_error = cause->memory_error();
120   const HeapObject& heap_object = memory_error.heap();
121 
122   const char *tool_str;
123   switch (memory_error.tool()) {
124     case MemoryError_Tool_GWP_ASAN:
125       tool_str = "GWP-ASan";
126       break;
127     case MemoryError_Tool_SCUDO:
128       tool_str = "MTE";
129       break;
130     default:
131       tool_str = "Unknown";
132       break;
133   }
134 
135   const char *error_type_str;
136   switch (memory_error.type()) {
137     case MemoryError_Type_USE_AFTER_FREE:
138       error_type_str = "Use After Free";
139       break;
140     case MemoryError_Type_DOUBLE_FREE:
141       error_type_str = "Double Free";
142       break;
143     case MemoryError_Type_INVALID_FREE:
144       error_type_str = "Invalid (Wild) Free";
145       break;
146     case MemoryError_Type_BUFFER_OVERFLOW:
147       error_type_str = "Buffer Overflow";
148       break;
149     case MemoryError_Type_BUFFER_UNDERFLOW:
150       error_type_str = "Buffer Underflow";
151       break;
152     default:
153       cause->set_human_readable(
154           StringPrintf("[%s]: Unknown error occurred at 0x%" PRIx64 ".", tool_str, fault_addr));
155       return;
156   }
157 
158   uint64_t diff;
159   const char* location_str;
160 
161   if (fault_addr < heap_object.address()) {
162     // Buffer Underflow, 6 bytes left of a 41-byte allocation at 0xdeadbeef.
163     location_str = "left of";
164     diff = heap_object.address() - fault_addr;
165   } else if (fault_addr - heap_object.address() < heap_object.size()) {
166     // Use After Free, 40 bytes into a 41-byte allocation at 0xdeadbeef.
167     location_str = "into";
168     diff = fault_addr - heap_object.address();
169   } else {
170     // Buffer Overflow, 6 bytes right of a 41-byte allocation at 0xdeadbeef.
171     location_str = "right of";
172     diff = fault_addr - heap_object.address() - heap_object.size();
173   }
174 
175   // Suffix of 'bytes', i.e. 4 bytes' vs. '1 byte'.
176   const char* byte_suffix = "s";
177   if (diff == 1) {
178     byte_suffix = "";
179   }
180 
181   cause->set_human_readable(StringPrintf(
182       "[%s]: %s, %" PRIu64 " byte%s %s a %" PRIu64 "-byte allocation at 0x%" PRIx64, tool_str,
183       error_type_str, diff, byte_suffix, location_str, heap_object.size(), heap_object.address()));
184 }
185 
dump_probable_cause(Tombstone * tombstone,unwindstack::Unwinder * unwinder,const ProcessInfo & process_info,const ThreadInfo & main_thread)186 static void dump_probable_cause(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
187                                 const ProcessInfo& process_info, const ThreadInfo& main_thread) {
188   ScudoCrashData scudo_crash_data(unwinder->GetProcessMemory().get(), process_info);
189   if (scudo_crash_data.CrashIsMine()) {
190     scudo_crash_data.AddCauseProtos(tombstone, unwinder);
191     return;
192   }
193 
194   GwpAsanCrashData gwp_asan_crash_data(unwinder->GetProcessMemory().get(), process_info,
195                                        main_thread);
196   if (gwp_asan_crash_data.CrashIsMine()) {
197     gwp_asan_crash_data.AddCauseProtos(tombstone, unwinder);
198     return;
199   }
200 
201   const siginfo *si = main_thread.siginfo;
202   auto fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
203   unwindstack::Maps* maps = unwinder->GetMaps();
204 
205   std::optional<std::string> cause;
206   if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
207     if (fault_addr < 4096) {
208       cause = "null pointer dereference";
209     } else if (fault_addr == 0xffff0ffc) {
210       cause = "call to kuser_helper_version";
211     } else if (fault_addr == 0xffff0fe0) {
212       cause = "call to kuser_get_tls";
213     } else if (fault_addr == 0xffff0fc0) {
214       cause = "call to kuser_cmpxchg";
215     } else if (fault_addr == 0xffff0fa0) {
216       cause = "call to kuser_memory_barrier";
217     } else if (fault_addr == 0xffff0f60) {
218       cause = "call to kuser_cmpxchg64";
219     } else {
220       cause = get_stack_overflow_cause(fault_addr, main_thread.registers->sp(), maps);
221     }
222   } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
223     unwindstack::MapInfo* map_info = maps->Find(fault_addr);
224     if (map_info != nullptr && map_info->flags() == PROT_EXEC) {
225       cause = "execute-only (no-read) memory access error; likely due to data in .text.";
226     } else {
227       cause = get_stack_overflow_cause(fault_addr, main_thread.registers->sp(), maps);
228     }
229   } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
230     cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
231                          si->si_syscall);
232   }
233 
234   if (cause) {
235     Cause *cause_proto = tombstone->add_causes();
236     cause_proto->set_human_readable(*cause);
237   }
238 }
239 
dump_abort_message(Tombstone * tombstone,unwindstack::Unwinder * unwinder,const ProcessInfo & process_info)240 static void dump_abort_message(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
241                                const ProcessInfo& process_info) {
242   std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
243   uintptr_t address = process_info.abort_msg_address;
244   if (address == 0) {
245     return;
246   }
247 
248   size_t length;
249   if (!process_memory->ReadFully(address, &length, sizeof(length))) {
250     async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
251                           strerror(errno));
252     return;
253   }
254 
255   // The length field includes the length of the length field itself.
256   if (length < sizeof(size_t)) {
257     async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
258                           "abort message header malformed: claimed length = %zu", length);
259     return;
260   }
261 
262   length -= sizeof(size_t);
263 
264   // The abort message should be null terminated already, but reserve a spot for NUL just in case.
265   std::string msg;
266   msg.resize(length);
267 
268   if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
269     async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
270                           strerror(errno));
271     return;
272   }
273 
274   tombstone->set_abort_message(msg);
275 }
276 
dump_open_fds(Tombstone * tombstone,const OpenFilesList * open_files)277 static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
278   if (open_files) {
279     for (auto& [fd, entry] : *open_files) {
280       FD f;
281 
282       f.set_fd(fd);
283 
284       const std::optional<std::string>& path = entry.path;
285       if (path) {
286         f.set_path(*path);
287       }
288 
289       const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
290       if (fdsan_owner) {
291         const char* type = android_fdsan_get_tag_type(*fdsan_owner);
292         uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
293         f.set_owner(type);
294         f.set_tag(value);
295       }
296 
297       *tombstone->add_open_fds() = f;
298     }
299   }
300 }
301 
fill_in_backtrace_frame(BacktraceFrame * f,const unwindstack::FrameData & frame,unwindstack::Maps * maps)302 void fill_in_backtrace_frame(BacktraceFrame* f, const unwindstack::FrameData& frame,
303                              unwindstack::Maps* maps) {
304   f->set_rel_pc(frame.rel_pc);
305   f->set_pc(frame.pc);
306   f->set_sp(frame.sp);
307 
308   if (!frame.function_name.empty()) {
309     // TODO: Should this happen here, or on the display side?
310     char* demangled_name = __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
311     if (demangled_name) {
312       f->set_function_name(demangled_name);
313       free(demangled_name);
314     } else {
315       f->set_function_name(frame.function_name);
316     }
317   }
318 
319   f->set_function_offset(frame.function_offset);
320 
321   if (frame.map_start == frame.map_end) {
322     // No valid map associated with this frame.
323     f->set_file_name("<unknown>");
324   } else if (!frame.map_name.empty()) {
325     f->set_file_name(frame.map_name);
326   } else {
327     f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_start));
328   }
329 
330   f->set_file_map_offset(frame.map_elf_start_offset);
331 
332   unwindstack::MapInfo* map_info = maps->Find(frame.map_start);
333   if (map_info) {
334     f->set_build_id(map_info->GetPrintableBuildID());
335   }
336 }
337 
dump_thread(Tombstone * tombstone,unwindstack::Unwinder * unwinder,const ThreadInfo & thread_info,bool memory_dump=false)338 static void dump_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
339                         const ThreadInfo& thread_info, bool memory_dump = false) {
340   Thread thread;
341 
342   thread.set_id(thread_info.tid);
343   thread.set_name(thread_info.thread_name);
344   thread.set_tagged_addr_ctrl(thread_info.tagged_addr_ctrl);
345 
346   unwindstack::Maps* maps = unwinder->GetMaps();
347   unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
348 
349   thread_info.registers->IterateRegisters(
350       [&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
351         Register r;
352         r.set_name(name);
353         r.set_u64(value);
354         *thread.add_registers() = r;
355 
356         if (memory_dump) {
357           MemoryDump dump;
358 
359           dump.set_register_name(name);
360           unwindstack::MapInfo* map_info = maps->Find(untag_address(value));
361           if (map_info) {
362             dump.set_mapping_name(map_info->name());
363           }
364 
365           constexpr size_t kNumBytesAroundRegister = 256;
366           constexpr size_t kNumTagsAroundRegister = kNumBytesAroundRegister / kTagGranuleSize;
367           char buf[kNumBytesAroundRegister];
368           uint8_t tags[kNumTagsAroundRegister];
369           size_t start_offset = 0;
370           ssize_t bytes = dump_memory(buf, sizeof(buf), tags, sizeof(tags), &value, memory);
371           if (bytes == -1) {
372             return;
373           }
374           dump.set_begin_address(value);
375 
376           if (start_offset + bytes > sizeof(buf)) {
377             async_safe_fatal("dump_memory overflowed? start offset = %zu, bytes read = %zd",
378                              start_offset, bytes);
379           }
380 
381           dump.set_memory(buf, bytes);
382 
383           bool has_tags = false;
384 #if defined(__aarch64__)
385           for (size_t i = 0; i < kNumTagsAroundRegister; ++i) {
386             if (tags[i] != 0) {
387               has_tags = true;
388             }
389           }
390 #endif  // defined(__aarch64__)
391 
392           if (has_tags) {
393             dump.mutable_arm_mte_metadata()->set_memory_tags(tags, kNumTagsAroundRegister);
394           }
395 
396           *thread.add_memory_dump() = std::move(dump);
397         }
398       });
399 
400   std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
401   unwinder->SetRegs(regs_copy.get());
402   unwinder->Unwind();
403   if (unwinder->NumFrames() == 0) {
404     async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to unwind");
405     if (unwinder->LastErrorCode() != unwindstack::ERROR_NONE) {
406       async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "  error code: %s",
407                             unwinder->LastErrorCodeString());
408       async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "  error address: 0x%" PRIx64,
409                             unwinder->LastErrorAddress());
410     }
411   } else {
412     if (unwinder->elf_from_memory_not_file()) {
413       auto backtrace_note = thread.mutable_backtrace_note();
414       *backtrace_note->Add() =
415           "Function names and BuildId information is missing for some frames due";
416       *backtrace_note->Add() =
417           "to unreadable libraries. For unwinds of apps, only shared libraries";
418       *backtrace_note->Add() = "found under the lib/ directory are readable.";
419       *backtrace_note->Add() = "On this device, run setenforce 0 to make the libraries readable.";
420     }
421     unwinder->SetDisplayBuildID(true);
422     for (const auto& frame : unwinder->frames()) {
423       BacktraceFrame* f = thread.add_current_backtrace();
424       fill_in_backtrace_frame(f, frame, maps);
425     }
426   }
427 
428   auto& threads = *tombstone->mutable_threads();
429   threads[thread_info.tid] = thread;
430 }
431 
dump_main_thread(Tombstone * tombstone,unwindstack::Unwinder * unwinder,const ThreadInfo & thread_info)432 static void dump_main_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
433                              const ThreadInfo& thread_info) {
434   dump_thread(tombstone, unwinder, thread_info, true);
435 }
436 
dump_mappings(Tombstone * tombstone,unwindstack::Unwinder * unwinder)437 static void dump_mappings(Tombstone* tombstone, unwindstack::Unwinder* unwinder) {
438   unwindstack::Maps* maps = unwinder->GetMaps();
439   std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
440 
441   for (const auto& map_info : *maps) {
442     auto* map = tombstone->add_memory_mappings();
443     map->set_begin_address(map_info->start());
444     map->set_end_address(map_info->end());
445     map->set_offset(map_info->offset());
446 
447     if (map_info->flags() & PROT_READ) {
448       map->set_read(true);
449     }
450     if (map_info->flags() & PROT_WRITE) {
451       map->set_write(true);
452     }
453     if (map_info->flags() & PROT_EXEC) {
454       map->set_execute(true);
455     }
456 
457     map->set_mapping_name(map_info->name());
458 
459     std::string build_id = map_info->GetPrintableBuildID();
460     if (!build_id.empty()) {
461       map->set_build_id(build_id);
462     }
463 
464     map->set_load_bias(map_info->GetLoadBias(process_memory));
465   }
466 }
467 
dump_log_file(Tombstone * tombstone,const char * logger,pid_t pid)468 static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
469   logger_list* logger_list =
470       android_logger_list_open(android_name_to_log_id(logger), ANDROID_LOG_NONBLOCK, 0, pid);
471 
472   LogBuffer buffer;
473 
474   while (true) {
475     log_msg log_entry;
476     ssize_t actual = android_logger_list_read(logger_list, &log_entry);
477 
478     if (actual < 0) {
479       if (actual == -EINTR) {
480         // interrupted by signal, retry
481         continue;
482       }
483       if (actual == -EAGAIN) {
484         // non-blocking EOF; we're done
485         break;
486       } else {
487         break;
488       }
489     } else if (actual == 0) {
490       break;
491     }
492 
493     char timestamp_secs[32];
494     time_t sec = static_cast<time_t>(log_entry.entry.sec);
495     tm tm;
496     localtime_r(&sec, &tm);
497     strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
498     std::string timestamp =
499         StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
500 
501     // Msg format is: <priority:1><tag:N>\0<message:N>\0
502     char* msg = log_entry.msg();
503     if (msg == nullptr) {
504       continue;
505     }
506 
507     unsigned char prio = msg[0];
508     char* tag = msg + 1;
509     msg = tag + strlen(tag) + 1;
510 
511     // consume any trailing newlines
512     char* nl = msg + strlen(msg) - 1;
513     while (nl >= msg && *nl == '\n') {
514       *nl-- = '\0';
515     }
516 
517     // Look for line breaks ('\n') and display each text line
518     // on a separate line, prefixed with the header, like logcat does.
519     do {
520       nl = strchr(msg, '\n');
521       if (nl != nullptr) {
522         *nl = '\0';
523         ++nl;
524       }
525 
526       LogMessage* log_msg = buffer.add_logs();
527       log_msg->set_timestamp(timestamp);
528       log_msg->set_pid(log_entry.entry.pid);
529       log_msg->set_tid(log_entry.entry.tid);
530       log_msg->set_priority(prio);
531       log_msg->set_tag(tag);
532       log_msg->set_message(msg);
533     } while ((msg = nl));
534   }
535   android_logger_list_free(logger_list);
536 
537   if (!buffer.logs().empty()) {
538     buffer.set_name(logger);
539     *tombstone->add_log_buffers() = std::move(buffer);
540   }
541 }
542 
dump_logcat(Tombstone * tombstone,pid_t pid)543 static void dump_logcat(Tombstone* tombstone, pid_t pid) {
544   dump_log_file(tombstone, "system", pid);
545   dump_log_file(tombstone, "main", pid);
546 }
547 
dump_tags_around_fault_addr(Signal * signal,const Tombstone & tombstone,unwindstack::Unwinder * unwinder,uintptr_t fault_addr)548 static void dump_tags_around_fault_addr(Signal* signal, const Tombstone& tombstone,
549                                         unwindstack::Unwinder* unwinder, uintptr_t fault_addr) {
550   if (tombstone.arch() != Architecture::ARM64) return;
551 
552   fault_addr = untag_address(fault_addr);
553   constexpr size_t kNumGranules = kNumTagRows * kNumTagColumns;
554   constexpr size_t kBytesToRead = kNumGranules * kTagGranuleSize;
555 
556   // If the low part of the tag dump would underflow to the high address space, it's probably not
557   // a valid address for us to dump tags from.
558   if (fault_addr < kBytesToRead / 2) return;
559 
560   unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
561 
562   constexpr uintptr_t kRowStartMask = ~(kNumTagColumns * kTagGranuleSize - 1);
563   size_t start_address = (fault_addr & kRowStartMask) - kBytesToRead / 2;
564   MemoryDump tag_dump;
565   size_t granules_to_read = kNumGranules;
566 
567   // Attempt to read the first tag. If reading fails, this likely indicates the
568   // lowest touched page is inaccessible or not marked with PROT_MTE.
569   // Fast-forward over pages until one has tags, or we exhaust the search range.
570   while (memory->ReadTag(start_address) < 0) {
571     size_t page_size = sysconf(_SC_PAGE_SIZE);
572     size_t bytes_to_next_page = page_size - (start_address % page_size);
573     if (bytes_to_next_page >= granules_to_read * kTagGranuleSize) return;
574     start_address += bytes_to_next_page;
575     granules_to_read -= bytes_to_next_page / kTagGranuleSize;
576   }
577   tag_dump.set_begin_address(start_address);
578 
579   std::string* mte_tags = tag_dump.mutable_arm_mte_metadata()->mutable_memory_tags();
580 
581   for (size_t i = 0; i < granules_to_read; ++i) {
582     long tag = memory->ReadTag(start_address + i * kTagGranuleSize);
583     if (tag < 0) break;
584     mte_tags->push_back(static_cast<uint8_t>(tag));
585   }
586 
587   if (!mte_tags->empty()) {
588     *signal->mutable_fault_adjacent_metadata() = tag_dump;
589   }
590 }
591 
read_uptime_secs()592 static std::optional<uint64_t> read_uptime_secs() {
593   std::string uptime;
594   if (!android::base::ReadFileToString("/proc/uptime", &uptime)) {
595     return {};
596   }
597   return strtoll(uptime.c_str(), nullptr, 10);
598 }
599 
engrave_tombstone_proto(Tombstone * tombstone,unwindstack::Unwinder * unwinder,const std::map<pid_t,ThreadInfo> & threads,pid_t target_thread,const ProcessInfo & process_info,const OpenFilesList * open_files)600 void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
601                              const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
602                              const ProcessInfo& process_info, const OpenFilesList* open_files) {
603   Tombstone result;
604 
605   result.set_arch(get_arch());
606   result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
607   result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
608   result.set_timestamp(get_timestamp());
609 
610   std::optional<uint64_t> system_uptime = read_uptime_secs();
611   if (system_uptime) {
612     android::procinfo::ProcessInfo proc_info;
613     std::string error;
614     if (android::procinfo::GetProcessInfo(target_thread, &proc_info, &error)) {
615       uint64_t starttime = proc_info.starttime / sysconf(_SC_CLK_TCK);
616       result.set_process_uptime(*system_uptime - starttime);
617     } else {
618       async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read process info: %s",
619                             error.c_str());
620     }
621   } else {
622     async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read /proc/uptime: %s",
623                           strerror(errno));
624   }
625 
626   const ThreadInfo& main_thread = threads.at(target_thread);
627   result.set_pid(main_thread.pid);
628   result.set_tid(main_thread.tid);
629   result.set_uid(main_thread.uid);
630   result.set_selinux_label(main_thread.selinux_label);
631 
632   auto cmd_line = result.mutable_command_line();
633   for (const auto& arg : main_thread.command_line) {
634     *cmd_line->Add() = arg;
635   }
636 
637   if (!main_thread.siginfo) {
638     async_safe_fatal("siginfo missing");
639   }
640 
641   Signal sig;
642   sig.set_number(main_thread.signo);
643   sig.set_name(get_signame(main_thread.siginfo));
644   sig.set_code(main_thread.siginfo->si_code);
645   sig.set_code_name(get_sigcode(main_thread.siginfo));
646 
647   if (signal_has_sender(main_thread.siginfo, main_thread.pid)) {
648     sig.set_has_sender(true);
649     sig.set_sender_uid(main_thread.siginfo->si_uid);
650     sig.set_sender_pid(main_thread.siginfo->si_pid);
651   }
652 
653   if (process_info.has_fault_address) {
654     sig.set_has_fault_address(true);
655     uintptr_t fault_addr = process_info.maybe_tagged_fault_address;
656     sig.set_fault_address(fault_addr);
657     dump_tags_around_fault_addr(&sig, result, unwinder, fault_addr);
658   }
659 
660   *result.mutable_signal_info() = sig;
661 
662   dump_abort_message(&result, unwinder, process_info);
663 
664   dump_main_thread(&result, unwinder, main_thread);
665 
666   for (const auto& [tid, thread_info] : threads) {
667     if (tid != target_thread) {
668       dump_thread(&result, unwinder, thread_info);
669     }
670   }
671 
672   dump_probable_cause(&result, unwinder, process_info, main_thread);
673 
674   dump_mappings(&result, unwinder);
675 
676   // Only dump logs on debuggable devices.
677   if (android::base::GetBoolProperty("ro.debuggable", false)) {
678     dump_logcat(&result, main_thread.pid);
679   }
680 
681   dump_open_fds(&result, open_files);
682 
683   *tombstone = std::move(result);
684 }
685