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