blob: d014fa38b1e78d33d872b52d64a32ae073302ebd [file] [log] [blame]
Josh Gao76e1e302021-01-26 15:53:11 -08001/*
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"
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -080020#include "libdebuggerd/gwp_asan.h"
Christopher Ferris7aad2562021-09-24 00:06:38 -070021#if defined(USE_SCUDO)
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -080022#include "libdebuggerd/scudo.h"
Christopher Ferris7aad2562021-09-24 00:06:38 -070023#endif
Josh Gao76e1e302021-01-26 15:53:11 -080024
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>
Elliott Hughes32d3cdd2021-09-21 12:20:53 -070033#include <sys/sysinfo.h>
Josh Gao76e1e302021-01-26 15:53:11 -080034#include <time.h>
35
36#include <memory>
Josh Gaodbb83de2021-03-01 23:13:13 -080037#include <optional>
Christopher Ferrisc95047d2022-03-14 15:02:11 -070038#include <set>
Josh Gao76e1e302021-01-26 15:53:11 -080039#include <string>
40
Josh Gao618cea32021-01-26 17:45:43 -080041#include <async_safe/log.h>
42
Josh Gaodbb83de2021-03-01 23:13:13 -080043#include <android-base/file.h>
Christopher Ferris2b98c822021-09-28 15:50:04 -070044#include <android-base/logging.h>
Josh Gao76e1e302021-01-26 15:53:11 -080045#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>
Florian Mayer5fa66632024-02-07 16:42:23 -080051#include <android/set_abort_message.h>
Peter Collingbourne0ea08c22021-02-05 14:59:08 -080052#include <bionic/macros.h>
Christopher Ferrisb999b822022-02-09 17:57:21 -080053#include <bionic/reserved_signals.h>
Florian Mayer5fa66632024-02-07 16:42:23 -080054#include <bionic/set_abort_message_internal.h>
Josh Gao76e1e302021-01-26 15:53:11 -080055#include <log/log.h>
56#include <log/log_read.h>
57#include <log/logprint.h>
58#include <private/android_filesystem_config.h>
59
Josh Gaodbb83de2021-03-01 23:13:13 -080060#include <procinfo/process.h>
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -070061#include <unwindstack/AndroidUnwinder.h>
62#include <unwindstack/Error.h>
63#include <unwindstack/MapInfo.h>
Josh Gao76e1e302021-01-26 15:53:11 -080064#include <unwindstack/Maps.h>
Josh Gao76e1e302021-01-26 15:53:11 -080065#include <unwindstack/Regs.h>
Josh Gao76e1e302021-01-26 15:53:11 -080066
67#include "libdebuggerd/open_files_list.h"
68#include "libdebuggerd/utility.h"
69#include "util.h"
70
71#include "tombstone.pb.h"
72
73using android::base::StringPrintf;
74
Christopher Ferris98d62422023-05-24 20:01:10 +000075// The maximum number of messages to save in the protobuf per file.
76static constexpr size_t kMaxLogMessages = 500;
77
Josh Gao76e1e302021-01-26 15:53:11 -080078// Use the demangler from libc++.
79extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
80
81static Architecture get_arch() {
82#if defined(__arm__)
83 return Architecture::ARM32;
84#elif defined(__aarch64__)
85 return Architecture::ARM64;
86#elif defined(__i386__)
87 return Architecture::X86;
88#elif defined(__x86_64__)
89 return Architecture::X86_64;
Liu Cunyuan8c0101b2022-10-12 22:35:51 +080090#elif defined(__riscv) && (__riscv_xlen == 64)
91 return Architecture::RISCV64;
Josh Gao76e1e302021-01-26 15:53:11 -080092#else
93#error Unknown architecture!
94#endif
95}
96
97static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
98 unwindstack::Maps* maps) {
99 static constexpr uint64_t kMaxDifferenceBytes = 256;
100 uint64_t difference;
101 if (sp >= fault_addr) {
102 difference = sp - fault_addr;
103 } else {
104 difference = fault_addr - sp;
105 }
106 if (difference <= kMaxDifferenceBytes) {
107 // The faulting address is close to the current sp, check if the sp
108 // indicates a stack overflow.
109 // On arm, the sp does not get updated when the instruction faults.
110 // In this case, the sp will still be in a valid map, which is the
111 // last case below.
112 // On aarch64, the sp does get updated when the instruction faults.
113 // In this case, the sp will be in either an invalid map if triggered
114 // on the main thread, or in a guard map if in another thread, which
115 // will be the first case or second case from below.
Christopher Ferrisc6776062021-01-15 15:59:28 -0800116 std::shared_ptr<unwindstack::MapInfo> map_info = maps->Find(sp);
Josh Gao76e1e302021-01-26 15:53:11 -0800117 if (map_info == nullptr) {
118 return "stack pointer is in a non-existent map; likely due to stack overflow.";
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100119 } else if ((map_info->flags() & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
Josh Gao76e1e302021-01-26 15:53:11 -0800120 return "stack pointer is not in a rw map; likely due to stack overflow.";
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100121 } else if ((sp - map_info->start()) <= kMaxDifferenceBytes) {
Josh Gao76e1e302021-01-26 15:53:11 -0800122 return "stack pointer is close to top of stack; likely stack overflow.";
123 }
124 }
125 return {};
126}
127
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800128void set_human_readable_cause(Cause* cause, uint64_t fault_addr) {
129 if (!cause->has_memory_error() || !cause->memory_error().has_heap()) {
130 return;
131 }
132
133 const MemoryError& memory_error = cause->memory_error();
134 const HeapObject& heap_object = memory_error.heap();
135
136 const char *tool_str;
137 switch (memory_error.tool()) {
138 case MemoryError_Tool_GWP_ASAN:
139 tool_str = "GWP-ASan";
140 break;
141 case MemoryError_Tool_SCUDO:
142 tool_str = "MTE";
143 break;
144 default:
145 tool_str = "Unknown";
146 break;
147 }
148
149 const char *error_type_str;
150 switch (memory_error.type()) {
151 case MemoryError_Type_USE_AFTER_FREE:
152 error_type_str = "Use After Free";
153 break;
154 case MemoryError_Type_DOUBLE_FREE:
155 error_type_str = "Double Free";
156 break;
157 case MemoryError_Type_INVALID_FREE:
158 error_type_str = "Invalid (Wild) Free";
159 break;
160 case MemoryError_Type_BUFFER_OVERFLOW:
161 error_type_str = "Buffer Overflow";
162 break;
163 case MemoryError_Type_BUFFER_UNDERFLOW:
164 error_type_str = "Buffer Underflow";
165 break;
166 default:
167 cause->set_human_readable(
168 StringPrintf("[%s]: Unknown error occurred at 0x%" PRIx64 ".", tool_str, fault_addr));
169 return;
170 }
171
172 uint64_t diff;
173 const char* location_str;
174
175 if (fault_addr < heap_object.address()) {
176 // Buffer Underflow, 6 bytes left of a 41-byte allocation at 0xdeadbeef.
177 location_str = "left of";
178 diff = heap_object.address() - fault_addr;
179 } else if (fault_addr - heap_object.address() < heap_object.size()) {
180 // Use After Free, 40 bytes into a 41-byte allocation at 0xdeadbeef.
181 location_str = "into";
182 diff = fault_addr - heap_object.address();
183 } else {
184 // Buffer Overflow, 6 bytes right of a 41-byte allocation at 0xdeadbeef.
185 location_str = "right of";
186 diff = fault_addr - heap_object.address() - heap_object.size();
187 }
188
189 // Suffix of 'bytes', i.e. 4 bytes' vs. '1 byte'.
190 const char* byte_suffix = "s";
191 if (diff == 1) {
192 byte_suffix = "";
193 }
194
195 cause->set_human_readable(StringPrintf(
196 "[%s]: %s, %" PRIu64 " byte%s %s a %" PRIu64 "-byte allocation at 0x%" PRIx64, tool_str,
197 error_type_str, diff, byte_suffix, location_str, heap_object.size(), heap_object.address()));
198}
199
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700200static void dump_probable_cause(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800201 const ProcessInfo& process_info, const ThreadInfo& main_thread) {
Christopher Ferris7aad2562021-09-24 00:06:38 -0700202#if defined(USE_SCUDO)
Peter Collingbourne78279912022-06-30 18:39:54 -0700203 ScudoCrashData scudo_crash_data(unwinder->GetProcessMemory().get(), process_info);
204 if (scudo_crash_data.CrashIsMine()) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800205 scudo_crash_data.AddCauseProtos(tombstone, unwinder);
206 return;
207 }
Christopher Ferris7aad2562021-09-24 00:06:38 -0700208#endif
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800209
210 GwpAsanCrashData gwp_asan_crash_data(unwinder->GetProcessMemory().get(), process_info,
211 main_thread);
212 if (gwp_asan_crash_data.CrashIsMine()) {
213 gwp_asan_crash_data.AddCauseProtos(tombstone, unwinder);
214 return;
215 }
216
217 const siginfo *si = main_thread.siginfo;
218 auto fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
219 unwindstack::Maps* maps = unwinder->GetMaps();
220
Josh Gao76e1e302021-01-26 15:53:11 -0800221 std::optional<std::string> cause;
222 if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800223 if (fault_addr < 4096) {
Josh Gao76e1e302021-01-26 15:53:11 -0800224 cause = "null pointer dereference";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800225 } else if (fault_addr == 0xffff0ffc) {
Josh Gao76e1e302021-01-26 15:53:11 -0800226 cause = "call to kuser_helper_version";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800227 } else if (fault_addr == 0xffff0fe0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800228 cause = "call to kuser_get_tls";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800229 } else if (fault_addr == 0xffff0fc0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800230 cause = "call to kuser_cmpxchg";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800231 } else if (fault_addr == 0xffff0fa0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800232 cause = "call to kuser_memory_barrier";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800233 } else if (fault_addr == 0xffff0f60) {
Josh Gao76e1e302021-01-26 15:53:11 -0800234 cause = "call to kuser_cmpxchg64";
235 } else {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800236 cause = get_stack_overflow_cause(fault_addr, main_thread.registers->sp(), maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800237 }
238 } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
Christopher Ferrisc6776062021-01-15 15:59:28 -0800239 auto map_info = maps->Find(fault_addr);
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100240 if (map_info != nullptr && map_info->flags() == PROT_EXEC) {
Josh Gao76e1e302021-01-26 15:53:11 -0800241 cause = "execute-only (no-read) memory access error; likely due to data in .text.";
242 } else {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800243 cause = get_stack_overflow_cause(fault_addr, main_thread.registers->sp(), maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800244 }
245 } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
246 cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
247 si->si_syscall);
248 }
249
250 if (cause) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800251 Cause *cause_proto = tombstone->add_causes();
252 cause_proto->set_human_readable(*cause);
Josh Gao76e1e302021-01-26 15:53:11 -0800253 }
254}
255
Florian Mayer5fa66632024-02-07 16:42:23 -0800256static void dump_crash_details(Tombstone* tombstone,
257 std::shared_ptr<unwindstack::Memory>& process_memory,
258 const ProcessInfo& process_info) {
259 uintptr_t address = process_info.crash_detail_page;
260 while (address) {
261 struct crash_detail_page_t page;
262 if (!process_memory->ReadFully(address, &page, sizeof(page))) {
263 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read crash detail page: %m");
264 break;
265 }
266 if (page.used > kNumCrashDetails) {
267 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "crash detail: page corrupted");
268 break;
269 }
270 for (size_t i = 0; i < page.used; ++i) {
271 const crash_detail_t& crash_detail = page.crash_details[i];
272 if (!crash_detail.data) {
273 continue;
274 }
275 std::string name(crash_detail.name_size, '\0');
276 if (!process_memory->ReadFully(reinterpret_cast<uintptr_t>(crash_detail.name), name.data(),
277 crash_detail.name_size)) {
278 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "crash detail: failed to read name: %m");
279 continue;
280 }
281 std::string data(crash_detail.data_size, '\0');
282 if (!process_memory->ReadFully(reinterpret_cast<uintptr_t>(crash_detail.data), data.data(),
283 crash_detail.data_size)) {
284 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
285 "crash detail: failed to read data for %s: %m", name.c_str());
286 continue;
287 }
288 auto* proto_detail = tombstone->add_crash_details();
289 proto_detail->set_name(name);
290 proto_detail->set_data(data);
291 }
292 address = reinterpret_cast<uintptr_t>(page.prev);
293 }
294}
295
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700296static void dump_abort_message(Tombstone* tombstone,
297 std::shared_ptr<unwindstack::Memory>& process_memory,
Josh Gao76e1e302021-01-26 15:53:11 -0800298 const ProcessInfo& process_info) {
Josh Gao76e1e302021-01-26 15:53:11 -0800299 uintptr_t address = process_info.abort_msg_address;
300 if (address == 0) {
301 return;
302 }
303
304 size_t length;
305 if (!process_memory->ReadFully(address, &length, sizeof(length))) {
Josh Gao618cea32021-01-26 17:45:43 -0800306 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
307 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800308 return;
309 }
310
311 // The length field includes the length of the length field itself.
312 if (length < sizeof(size_t)) {
Josh Gao618cea32021-01-26 17:45:43 -0800313 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
314 "abort message header malformed: claimed length = %zu", length);
Josh Gao76e1e302021-01-26 15:53:11 -0800315 return;
316 }
317
318 length -= sizeof(size_t);
319
320 // The abort message should be null terminated already, but reserve a spot for NUL just in case.
321 std::string msg;
322 msg.resize(length);
323
324 if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
Josh Gao618cea32021-01-26 17:45:43 -0800325 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
326 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800327 return;
328 }
329
Christopher Ferrise8891452021-08-17 17:34:53 -0700330 // Remove any trailing newlines.
331 size_t index = msg.size();
332 while (index > 0 && (msg[index - 1] == '\0' || msg[index - 1] == '\n')) {
333 --index;
334 }
335 msg.resize(index);
336
Josh Gao76e1e302021-01-26 15:53:11 -0800337 tombstone->set_abort_message(msg);
338}
339
340static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
341 if (open_files) {
342 for (auto& [fd, entry] : *open_files) {
343 FD f;
344
345 f.set_fd(fd);
346
347 const std::optional<std::string>& path = entry.path;
348 if (path) {
349 f.set_path(*path);
350 }
351
352 const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
353 if (fdsan_owner) {
354 const char* type = android_fdsan_get_tag_type(*fdsan_owner);
355 uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
356 f.set_owner(type);
357 f.set_tag(value);
358 }
359
360 *tombstone->add_open_fds() = f;
361 }
362 }
363}
364
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800365void fill_in_backtrace_frame(BacktraceFrame* f, const unwindstack::FrameData& frame) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800366 f->set_rel_pc(frame.rel_pc);
367 f->set_pc(frame.pc);
368 f->set_sp(frame.sp);
369
370 if (!frame.function_name.empty()) {
371 // TODO: Should this happen here, or on the display side?
372 char* demangled_name = __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
373 if (demangled_name) {
374 f->set_function_name(demangled_name);
375 free(demangled_name);
376 } else {
377 f->set_function_name(frame.function_name);
378 }
379 }
380
381 f->set_function_offset(frame.function_offset);
382
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800383 if (frame.map_info == nullptr) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800384 // No valid map associated with this frame.
385 f->set_file_name("<unknown>");
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800386 return;
387 }
388
389 if (!frame.map_info->name().empty()) {
390 f->set_file_name(frame.map_info->GetFullName());
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800391 } else {
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800392 f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_info->start()));
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800393 }
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800394 f->set_file_map_offset(frame.map_info->elf_start_offset());
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800395
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800396 f->set_build_id(frame.map_info->GetPrintableBuildID());
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800397}
398
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700399static void dump_registers(unwindstack::AndroidUnwinder* unwinder,
Christopher Ferrisb999b822022-02-09 17:57:21 -0800400 const std::unique_ptr<unwindstack::Regs>& regs, Thread& thread,
401 bool memory_dump) {
402 if (regs == nullptr) {
403 return;
404 }
405
406 unwindstack::Maps* maps = unwinder->GetMaps();
407 unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
408
409 regs->IterateRegisters([&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
410 Register r;
411 r.set_name(name);
412 r.set_u64(value);
413 *thread.add_registers() = r;
414
415 if (memory_dump) {
416 MemoryDump dump;
417
418 dump.set_register_name(name);
419 std::shared_ptr<unwindstack::MapInfo> map_info = maps->Find(untag_address(value));
420 if (map_info) {
421 dump.set_mapping_name(map_info->name());
422 }
423
424 constexpr size_t kNumBytesAroundRegister = 256;
425 constexpr size_t kNumTagsAroundRegister = kNumBytesAroundRegister / kTagGranuleSize;
426 char buf[kNumBytesAroundRegister];
427 uint8_t tags[kNumTagsAroundRegister];
428 ssize_t bytes = dump_memory(buf, sizeof(buf), tags, sizeof(tags), &value, memory);
429 if (bytes == -1) {
430 return;
431 }
432 dump.set_begin_address(value);
433 dump.set_memory(buf, bytes);
434
435 bool has_tags = false;
436#if defined(__aarch64__)
437 for (size_t i = 0; i < kNumTagsAroundRegister; ++i) {
438 if (tags[i] != 0) {
439 has_tags = true;
440 }
441 }
442#endif // defined(__aarch64__)
443
444 if (has_tags) {
445 dump.mutable_arm_mte_metadata()->set_memory_tags(tags, kNumTagsAroundRegister);
446 }
447
448 *thread.add_memory_dump() = std::move(dump);
449 }
450 });
451}
452
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700453static void dump_thread_backtrace(std::vector<unwindstack::FrameData>& frames, Thread& thread) {
Christopher Ferrisc95047d2022-03-14 15:02:11 -0700454 std::set<std::string> unreadable_elf_files;
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700455 for (const auto& frame : frames) {
Christopher Ferrisc95047d2022-03-14 15:02:11 -0700456 BacktraceFrame* f = thread.add_current_backtrace();
457 fill_in_backtrace_frame(f, frame);
458 if (frame.map_info != nullptr && frame.map_info->ElfFileNotReadable()) {
459 unreadable_elf_files.emplace(frame.map_info->name());
460 }
461 }
462
463 if (!unreadable_elf_files.empty()) {
464 auto unreadable_elf_files_proto = thread.mutable_unreadable_elf_files();
Christopher Ferrisb999b822022-02-09 17:57:21 -0800465 auto backtrace_note = thread.mutable_backtrace_note();
466 *backtrace_note->Add() =
467 "Function names and BuildId information is missing for some frames due";
468 *backtrace_note->Add() = "to unreadable libraries. For unwinds of apps, only shared libraries";
469 *backtrace_note->Add() = "found under the lib/ directory are readable.";
470 *backtrace_note->Add() = "On this device, run setenforce 0 to make the libraries readable.";
Christopher Ferrisc95047d2022-03-14 15:02:11 -0700471 *backtrace_note->Add() = "Unreadable libraries:";
472 for (auto& name : unreadable_elf_files) {
473 *backtrace_note->Add() = " " + name;
474 *unreadable_elf_files_proto->Add() = name;
475 }
Christopher Ferrisb999b822022-02-09 17:57:21 -0800476 }
477}
478
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700479static void dump_thread(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
Josh Gao76e1e302021-01-26 15:53:11 -0800480 const ThreadInfo& thread_info, bool memory_dump = false) {
481 Thread thread;
482
483 thread.set_id(thread_info.tid);
484 thread.set_name(thread_info.thread_name);
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800485 thread.set_tagged_addr_ctrl(thread_info.tagged_addr_ctrl);
Elliott Hughesd13ea522022-01-13 09:20:26 -0800486 thread.set_pac_enabled_keys(thread_info.pac_enabled_keys);
Josh Gao76e1e302021-01-26 15:53:11 -0800487
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700488 unwindstack::AndroidUnwinderData data;
489 // Indicate we want a copy of the initial registers.
490 data.saved_initial_regs = std::make_optional<std::unique_ptr<unwindstack::Regs>>();
491 bool unwind_ret;
492 if (thread_info.registers != nullptr) {
493 unwind_ret = unwinder->Unwind(thread_info.registers.get(), data);
Josh Gao76e1e302021-01-26 15:53:11 -0800494 } else {
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700495 unwind_ret = unwinder->Unwind(thread_info.tid, data);
Josh Gao76e1e302021-01-26 15:53:11 -0800496 }
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700497 if (!unwind_ret) {
498 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "Unwind failed for tid %d: Error %s",
499 thread_info.tid, data.GetErrorString().c_str());
500 } else {
501 dump_thread_backtrace(data.frames, thread);
502 }
503 dump_registers(unwinder, *data.saved_initial_regs, thread, memory_dump);
Josh Gao76e1e302021-01-26 15:53:11 -0800504
505 auto& threads = *tombstone->mutable_threads();
506 threads[thread_info.tid] = thread;
507}
508
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700509static void dump_mappings(Tombstone* tombstone, unwindstack::Maps* maps,
510 std::shared_ptr<unwindstack::Memory>& process_memory) {
Josh Gao76e1e302021-01-26 15:53:11 -0800511 for (const auto& map_info : *maps) {
512 auto* map = tombstone->add_memory_mappings();
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100513 map->set_begin_address(map_info->start());
514 map->set_end_address(map_info->end());
515 map->set_offset(map_info->offset());
Josh Gao76e1e302021-01-26 15:53:11 -0800516
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100517 if (map_info->flags() & PROT_READ) {
Josh Gao76e1e302021-01-26 15:53:11 -0800518 map->set_read(true);
519 }
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100520 if (map_info->flags() & PROT_WRITE) {
Josh Gao76e1e302021-01-26 15:53:11 -0800521 map->set_write(true);
522 }
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100523 if (map_info->flags() & PROT_EXEC) {
Josh Gao76e1e302021-01-26 15:53:11 -0800524 map->set_execute(true);
525 }
526
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100527 map->set_mapping_name(map_info->name());
Josh Gao76e1e302021-01-26 15:53:11 -0800528
529 std::string build_id = map_info->GetPrintableBuildID();
530 if (!build_id.empty()) {
531 map->set_build_id(build_id);
532 }
533
534 map->set_load_bias(map_info->GetLoadBias(process_memory));
535 }
536}
537
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700538// This creates a fake log message that indicates an error occurred when
539// reading the log.
540static void add_error_log_msg(Tombstone* tombstone, const std::string&& error_msg) {
541 LogBuffer buffer;
542 buffer.set_name("ERROR");
543
544 LogMessage* log_msg = buffer.add_logs();
545 log_msg->set_timestamp("00-00 00:00:00.000");
546 log_msg->set_pid(0);
547 log_msg->set_tid(0);
548 log_msg->set_priority(ANDROID_LOG_ERROR);
549 log_msg->set_tag("");
550 log_msg->set_message(error_msg);
551
552 *tombstone->add_log_buffers() = std::move(buffer);
553
554 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
555}
556
Josh Gao76e1e302021-01-26 15:53:11 -0800557static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
Christopher Ferris98d62422023-05-24 20:01:10 +0000558 logger_list* logger_list = android_logger_list_open(android_name_to_log_id(logger),
559 ANDROID_LOG_NONBLOCK, kMaxLogMessages, pid);
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700560 if (logger_list == nullptr) {
561 add_error_log_msg(tombstone, android::base::StringPrintf("Cannot open log file %s", logger));
562 return;
563 }
Josh Gao76e1e302021-01-26 15:53:11 -0800564
565 LogBuffer buffer;
Josh Gao76e1e302021-01-26 15:53:11 -0800566 while (true) {
567 log_msg log_entry;
568 ssize_t actual = android_logger_list_read(logger_list, &log_entry);
Josh Gao76e1e302021-01-26 15:53:11 -0800569 if (actual < 0) {
570 if (actual == -EINTR) {
571 // interrupted by signal, retry
572 continue;
573 }
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700574 // Don't consider EAGAIN an error since this is a non-blocking call.
575 if (actual != -EAGAIN) {
576 add_error_log_msg(tombstone, android::base::StringPrintf("reading log %s failed (%s)",
577 logger, strerror(-actual)));
Josh Gao76e1e302021-01-26 15:53:11 -0800578 }
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700579 break;
Josh Gao76e1e302021-01-26 15:53:11 -0800580 } else if (actual == 0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800581 break;
582 }
583
584 char timestamp_secs[32];
585 time_t sec = static_cast<time_t>(log_entry.entry.sec);
586 tm tm;
587 localtime_r(&sec, &tm);
588 strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
589 std::string timestamp =
590 StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
591
592 // Msg format is: <priority:1><tag:N>\0<message:N>\0
593 char* msg = log_entry.msg();
594 if (msg == nullptr) {
595 continue;
596 }
597
598 unsigned char prio = msg[0];
599 char* tag = msg + 1;
600 msg = tag + strlen(tag) + 1;
601
602 // consume any trailing newlines
603 char* nl = msg + strlen(msg) - 1;
604 while (nl >= msg && *nl == '\n') {
605 *nl-- = '\0';
606 }
607
608 // Look for line breaks ('\n') and display each text line
609 // on a separate line, prefixed with the header, like logcat does.
610 do {
611 nl = strchr(msg, '\n');
612 if (nl != nullptr) {
613 *nl = '\0';
614 ++nl;
615 }
616
617 LogMessage* log_msg = buffer.add_logs();
618 log_msg->set_timestamp(timestamp);
619 log_msg->set_pid(log_entry.entry.pid);
620 log_msg->set_tid(log_entry.entry.tid);
621 log_msg->set_priority(prio);
622 log_msg->set_tag(tag);
623 log_msg->set_message(msg);
624 } while ((msg = nl));
625 }
626 android_logger_list_free(logger_list);
627
628 if (!buffer.logs().empty()) {
629 buffer.set_name(logger);
630 *tombstone->add_log_buffers() = std::move(buffer);
631 }
632}
633
634static void dump_logcat(Tombstone* tombstone, pid_t pid) {
635 dump_log_file(tombstone, "system", pid);
636 dump_log_file(tombstone, "main", pid);
637}
638
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700639static void dump_tags_around_fault_addr(Signal* signal, const Tombstone& tombstone,
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700640 std::shared_ptr<unwindstack::Memory>& process_memory,
641 uintptr_t fault_addr) {
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700642 if (tombstone.arch() != Architecture::ARM64) return;
643
644 fault_addr = untag_address(fault_addr);
645 constexpr size_t kNumGranules = kNumTagRows * kNumTagColumns;
646 constexpr size_t kBytesToRead = kNumGranules * kTagGranuleSize;
647
648 // If the low part of the tag dump would underflow to the high address space, it's probably not
649 // a valid address for us to dump tags from.
650 if (fault_addr < kBytesToRead / 2) return;
651
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700652 constexpr uintptr_t kRowStartMask = ~(kNumTagColumns * kTagGranuleSize - 1);
653 size_t start_address = (fault_addr & kRowStartMask) - kBytesToRead / 2;
654 MemoryDump tag_dump;
655 size_t granules_to_read = kNumGranules;
656
657 // Attempt to read the first tag. If reading fails, this likely indicates the
658 // lowest touched page is inaccessible or not marked with PROT_MTE.
659 // Fast-forward over pages until one has tags, or we exhaust the search range.
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700660 while (process_memory->ReadTag(start_address) < 0) {
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700661 size_t page_size = sysconf(_SC_PAGE_SIZE);
662 size_t bytes_to_next_page = page_size - (start_address % page_size);
663 if (bytes_to_next_page >= granules_to_read * kTagGranuleSize) return;
664 start_address += bytes_to_next_page;
665 granules_to_read -= bytes_to_next_page / kTagGranuleSize;
666 }
667 tag_dump.set_begin_address(start_address);
668
669 std::string* mte_tags = tag_dump.mutable_arm_mte_metadata()->mutable_memory_tags();
670
671 for (size_t i = 0; i < granules_to_read; ++i) {
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700672 long tag = process_memory->ReadTag(start_address + i * kTagGranuleSize);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700673 if (tag < 0) break;
674 mte_tags->push_back(static_cast<uint8_t>(tag));
675 }
676
677 if (!mte_tags->empty()) {
678 *signal->mutable_fault_adjacent_metadata() = tag_dump;
679 }
680}
681
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700682void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
Josh Gao76e1e302021-01-26 15:53:11 -0800683 const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
684 const ProcessInfo& process_info, const OpenFilesList* open_files) {
685 Tombstone result;
686
687 result.set_arch(get_arch());
688 result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
689 result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
690 result.set_timestamp(get_timestamp());
691
692 const ThreadInfo& main_thread = threads.at(target_thread);
693 result.set_pid(main_thread.pid);
694 result.set_tid(main_thread.tid);
695 result.set_uid(main_thread.uid);
696 result.set_selinux_label(main_thread.selinux_label);
Christopher Ferris2b98c822021-09-28 15:50:04 -0700697 // The main thread must have a valid siginfo.
698 CHECK(main_thread.siginfo != nullptr);
Josh Gao76e1e302021-01-26 15:53:11 -0800699
Elliott Hughes32d3cdd2021-09-21 12:20:53 -0700700 struct sysinfo si;
701 sysinfo(&si);
702 android::procinfo::ProcessInfo proc_info;
703 std::string error;
704 if (android::procinfo::GetProcessInfo(main_thread.pid, &proc_info, &error)) {
705 uint64_t starttime = proc_info.starttime / sysconf(_SC_CLK_TCK);
706 result.set_process_uptime(si.uptime - starttime);
707 } else {
708 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read process info: %s",
709 error.c_str());
710 }
711
Josh Gao31348a72021-03-29 21:53:42 -0700712 auto cmd_line = result.mutable_command_line();
713 for (const auto& arg : main_thread.command_line) {
714 *cmd_line->Add() = arg;
715 }
716
Josh Gao618cea32021-01-26 17:45:43 -0800717 if (!main_thread.siginfo) {
718 async_safe_fatal("siginfo missing");
719 }
Josh Gao76e1e302021-01-26 15:53:11 -0800720
721 Signal sig;
722 sig.set_number(main_thread.signo);
723 sig.set_name(get_signame(main_thread.siginfo));
724 sig.set_code(main_thread.siginfo->si_code);
725 sig.set_code_name(get_sigcode(main_thread.siginfo));
726
727 if (signal_has_sender(main_thread.siginfo, main_thread.pid)) {
728 sig.set_has_sender(true);
729 sig.set_sender_uid(main_thread.siginfo->si_uid);
730 sig.set_sender_pid(main_thread.siginfo->si_pid);
731 }
732
733 if (process_info.has_fault_address) {
734 sig.set_has_fault_address(true);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700735 uintptr_t fault_addr = process_info.maybe_tagged_fault_address;
736 sig.set_fault_address(fault_addr);
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700737 dump_tags_around_fault_addr(&sig, result, unwinder->GetProcessMemory(), fault_addr);
Josh Gao76e1e302021-01-26 15:53:11 -0800738 }
739
740 *result.mutable_signal_info() = sig;
741
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700742 dump_abort_message(&result, unwinder->GetProcessMemory(), process_info);
Florian Mayer5fa66632024-02-07 16:42:23 -0800743 dump_crash_details(&result, unwinder->GetProcessMemory(), process_info);
Christopher Ferrisb999b822022-02-09 17:57:21 -0800744 // Dump the main thread, but save the memory around the registers.
745 dump_thread(&result, unwinder, main_thread, /* memory_dump */ true);
Josh Gao76e1e302021-01-26 15:53:11 -0800746
747 for (const auto& [tid, thread_info] : threads) {
748 if (tid != target_thread) {
749 dump_thread(&result, unwinder, thread_info);
750 }
751 }
752
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800753 dump_probable_cause(&result, unwinder, process_info, main_thread);
Josh Gao76e1e302021-01-26 15:53:11 -0800754
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700755 dump_mappings(&result, unwinder->GetMaps(), unwinder->GetProcessMemory());
Josh Gao76e1e302021-01-26 15:53:11 -0800756
757 // Only dump logs on debuggable devices.
758 if (android::base::GetBoolProperty("ro.debuggable", false)) {
Christopher Ferrisbda10642023-04-24 18:14:53 -0700759 // Get the thread that corresponds to the main pid of the process.
760 const ThreadInfo& thread = threads.at(main_thread.pid);
761
762 // Do not attempt to dump logs of the logd process because the gathering
763 // of logs can hang until a timeout occurs.
764 if (thread.thread_name != "logd") {
765 dump_logcat(&result, main_thread.pid);
766 }
Josh Gao76e1e302021-01-26 15:53:11 -0800767 }
768
769 dump_open_fds(&result, open_files);
770
771 *tombstone = std::move(result);
772}