blob: 4cde986104c58a190f2747afc7736b46101948b5 [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 Mayer920d95b2024-02-14 12:57:09 -080054#include <bionic/crash_detail_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) {
Mitch Phillipsbf2d6dd2024-02-06 15:18:04 +010099 // Under stack MTE the stack pointer and/or the fault address can be tagged.
100 // In order to calculate deltas between them, strip off the tags off both
101 // addresses.
102 fault_addr = untag_address(fault_addr);
103 sp = untag_address(sp);
Josh Gao76e1e302021-01-26 15:53:11 -0800104 static constexpr uint64_t kMaxDifferenceBytes = 256;
105 uint64_t difference;
106 if (sp >= fault_addr) {
107 difference = sp - fault_addr;
108 } else {
109 difference = fault_addr - sp;
110 }
111 if (difference <= kMaxDifferenceBytes) {
112 // The faulting address is close to the current sp, check if the sp
113 // indicates a stack overflow.
114 // On arm, the sp does not get updated when the instruction faults.
115 // In this case, the sp will still be in a valid map, which is the
116 // last case below.
117 // On aarch64, the sp does get updated when the instruction faults.
118 // In this case, the sp will be in either an invalid map if triggered
119 // on the main thread, or in a guard map if in another thread, which
120 // will be the first case or second case from below.
Christopher Ferrisc6776062021-01-15 15:59:28 -0800121 std::shared_ptr<unwindstack::MapInfo> map_info = maps->Find(sp);
Josh Gao76e1e302021-01-26 15:53:11 -0800122 if (map_info == nullptr) {
123 return "stack pointer is in a non-existent map; likely due to stack overflow.";
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100124 } else if ((map_info->flags() & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
Josh Gao76e1e302021-01-26 15:53:11 -0800125 return "stack pointer is not in a rw map; likely due to stack overflow.";
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100126 } else if ((sp - map_info->start()) <= kMaxDifferenceBytes) {
Josh Gao76e1e302021-01-26 15:53:11 -0800127 return "stack pointer is close to top of stack; likely stack overflow.";
128 }
129 }
130 return {};
131}
132
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800133void set_human_readable_cause(Cause* cause, uint64_t fault_addr) {
134 if (!cause->has_memory_error() || !cause->memory_error().has_heap()) {
135 return;
136 }
137
138 const MemoryError& memory_error = cause->memory_error();
139 const HeapObject& heap_object = memory_error.heap();
140
141 const char *tool_str;
142 switch (memory_error.tool()) {
143 case MemoryError_Tool_GWP_ASAN:
144 tool_str = "GWP-ASan";
145 break;
146 case MemoryError_Tool_SCUDO:
147 tool_str = "MTE";
148 break;
149 default:
150 tool_str = "Unknown";
151 break;
152 }
153
154 const char *error_type_str;
155 switch (memory_error.type()) {
156 case MemoryError_Type_USE_AFTER_FREE:
157 error_type_str = "Use After Free";
158 break;
159 case MemoryError_Type_DOUBLE_FREE:
160 error_type_str = "Double Free";
161 break;
162 case MemoryError_Type_INVALID_FREE:
163 error_type_str = "Invalid (Wild) Free";
164 break;
165 case MemoryError_Type_BUFFER_OVERFLOW:
166 error_type_str = "Buffer Overflow";
167 break;
168 case MemoryError_Type_BUFFER_UNDERFLOW:
169 error_type_str = "Buffer Underflow";
170 break;
171 default:
172 cause->set_human_readable(
173 StringPrintf("[%s]: Unknown error occurred at 0x%" PRIx64 ".", tool_str, fault_addr));
174 return;
175 }
176
177 uint64_t diff;
178 const char* location_str;
179
180 if (fault_addr < heap_object.address()) {
181 // Buffer Underflow, 6 bytes left of a 41-byte allocation at 0xdeadbeef.
182 location_str = "left of";
183 diff = heap_object.address() - fault_addr;
184 } else if (fault_addr - heap_object.address() < heap_object.size()) {
185 // Use After Free, 40 bytes into a 41-byte allocation at 0xdeadbeef.
186 location_str = "into";
187 diff = fault_addr - heap_object.address();
188 } else {
189 // Buffer Overflow, 6 bytes right of a 41-byte allocation at 0xdeadbeef.
190 location_str = "right of";
191 diff = fault_addr - heap_object.address() - heap_object.size();
192 }
193
194 // Suffix of 'bytes', i.e. 4 bytes' vs. '1 byte'.
195 const char* byte_suffix = "s";
196 if (diff == 1) {
197 byte_suffix = "";
198 }
199
200 cause->set_human_readable(StringPrintf(
201 "[%s]: %s, %" PRIu64 " byte%s %s a %" PRIu64 "-byte allocation at 0x%" PRIx64, tool_str,
202 error_type_str, diff, byte_suffix, location_str, heap_object.size(), heap_object.address()));
203}
204
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700205static void dump_probable_cause(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
Florian Mayer2d453312024-04-22 23:43:59 +0000206 const ProcessInfo& process_info, const ThreadInfo& target_thread) {
Christopher Ferris7aad2562021-09-24 00:06:38 -0700207#if defined(USE_SCUDO)
Peter Collingbourne78279912022-06-30 18:39:54 -0700208 ScudoCrashData scudo_crash_data(unwinder->GetProcessMemory().get(), process_info);
209 if (scudo_crash_data.CrashIsMine()) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800210 scudo_crash_data.AddCauseProtos(tombstone, unwinder);
211 return;
212 }
Christopher Ferris7aad2562021-09-24 00:06:38 -0700213#endif
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800214
215 GwpAsanCrashData gwp_asan_crash_data(unwinder->GetProcessMemory().get(), process_info,
Florian Mayer2d453312024-04-22 23:43:59 +0000216 target_thread);
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800217 if (gwp_asan_crash_data.CrashIsMine()) {
218 gwp_asan_crash_data.AddCauseProtos(tombstone, unwinder);
219 return;
220 }
221
Florian Mayer2d453312024-04-22 23:43:59 +0000222 const siginfo *si = target_thread.siginfo;
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800223 auto fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
224 unwindstack::Maps* maps = unwinder->GetMaps();
225
Josh Gao76e1e302021-01-26 15:53:11 -0800226 std::optional<std::string> cause;
227 if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800228 if (fault_addr < 4096) {
Josh Gao76e1e302021-01-26 15:53:11 -0800229 cause = "null pointer dereference";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800230 } else if (fault_addr == 0xffff0ffc) {
Josh Gao76e1e302021-01-26 15:53:11 -0800231 cause = "call to kuser_helper_version";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800232 } else if (fault_addr == 0xffff0fe0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800233 cause = "call to kuser_get_tls";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800234 } else if (fault_addr == 0xffff0fc0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800235 cause = "call to kuser_cmpxchg";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800236 } else if (fault_addr == 0xffff0fa0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800237 cause = "call to kuser_memory_barrier";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800238 } else if (fault_addr == 0xffff0f60) {
Josh Gao76e1e302021-01-26 15:53:11 -0800239 cause = "call to kuser_cmpxchg64";
240 } else {
Florian Mayer2d453312024-04-22 23:43:59 +0000241 cause = get_stack_overflow_cause(fault_addr, target_thread.registers->sp(), maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800242 }
243 } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
Christopher Ferrisc6776062021-01-15 15:59:28 -0800244 auto map_info = maps->Find(fault_addr);
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100245 if (map_info != nullptr && map_info->flags() == PROT_EXEC) {
Josh Gao76e1e302021-01-26 15:53:11 -0800246 cause = "execute-only (no-read) memory access error; likely due to data in .text.";
247 } else {
Florian Mayer2d453312024-04-22 23:43:59 +0000248 cause = get_stack_overflow_cause(fault_addr, target_thread.registers->sp(), maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800249 }
250 } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
251 cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
252 si->si_syscall);
253 }
254
255 if (cause) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800256 Cause *cause_proto = tombstone->add_causes();
257 cause_proto->set_human_readable(*cause);
Josh Gao76e1e302021-01-26 15:53:11 -0800258 }
259}
260
Florian Mayer5fa66632024-02-07 16:42:23 -0800261static void dump_crash_details(Tombstone* tombstone,
262 std::shared_ptr<unwindstack::Memory>& process_memory,
263 const ProcessInfo& process_info) {
264 uintptr_t address = process_info.crash_detail_page;
265 while (address) {
266 struct crash_detail_page_t page;
267 if (!process_memory->ReadFully(address, &page, sizeof(page))) {
268 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read crash detail page: %m");
269 break;
270 }
271 if (page.used > kNumCrashDetails) {
272 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "crash detail: page corrupted");
273 break;
274 }
275 for (size_t i = 0; i < page.used; ++i) {
276 const crash_detail_t& crash_detail = page.crash_details[i];
277 if (!crash_detail.data) {
278 continue;
279 }
280 std::string name(crash_detail.name_size, '\0');
281 if (!process_memory->ReadFully(reinterpret_cast<uintptr_t>(crash_detail.name), name.data(),
282 crash_detail.name_size)) {
283 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "crash detail: failed to read name: %m");
284 continue;
285 }
286 std::string data(crash_detail.data_size, '\0');
287 if (!process_memory->ReadFully(reinterpret_cast<uintptr_t>(crash_detail.data), data.data(),
288 crash_detail.data_size)) {
289 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
290 "crash detail: failed to read data for %s: %m", name.c_str());
291 continue;
292 }
293 auto* proto_detail = tombstone->add_crash_details();
294 proto_detail->set_name(name);
295 proto_detail->set_data(data);
296 }
297 address = reinterpret_cast<uintptr_t>(page.prev);
298 }
299}
300
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700301static void dump_abort_message(Tombstone* tombstone,
302 std::shared_ptr<unwindstack::Memory>& process_memory,
Josh Gao76e1e302021-01-26 15:53:11 -0800303 const ProcessInfo& process_info) {
Josh Gao76e1e302021-01-26 15:53:11 -0800304 uintptr_t address = process_info.abort_msg_address;
305 if (address == 0) {
306 return;
307 }
308
309 size_t length;
310 if (!process_memory->ReadFully(address, &length, sizeof(length))) {
Josh Gao618cea32021-01-26 17:45:43 -0800311 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
312 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800313 return;
314 }
315
316 // The length field includes the length of the length field itself.
317 if (length < sizeof(size_t)) {
Josh Gao618cea32021-01-26 17:45:43 -0800318 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
319 "abort message header malformed: claimed length = %zu", length);
Josh Gao76e1e302021-01-26 15:53:11 -0800320 return;
321 }
322
323 length -= sizeof(size_t);
324
325 // The abort message should be null terminated already, but reserve a spot for NUL just in case.
326 std::string msg;
327 msg.resize(length);
328
329 if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
Josh Gao618cea32021-01-26 17:45:43 -0800330 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
331 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800332 return;
333 }
334
Christopher Ferrise8891452021-08-17 17:34:53 -0700335 // Remove any trailing newlines.
336 size_t index = msg.size();
337 while (index > 0 && (msg[index - 1] == '\0' || msg[index - 1] == '\n')) {
338 --index;
339 }
340 msg.resize(index);
341
Josh Gao76e1e302021-01-26 15:53:11 -0800342 tombstone->set_abort_message(msg);
343}
344
345static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
346 if (open_files) {
347 for (auto& [fd, entry] : *open_files) {
348 FD f;
349
350 f.set_fd(fd);
351
352 const std::optional<std::string>& path = entry.path;
353 if (path) {
354 f.set_path(*path);
355 }
356
357 const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
358 if (fdsan_owner) {
359 const char* type = android_fdsan_get_tag_type(*fdsan_owner);
360 uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
361 f.set_owner(type);
362 f.set_tag(value);
363 }
364
365 *tombstone->add_open_fds() = f;
366 }
367 }
368}
369
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800370void fill_in_backtrace_frame(BacktraceFrame* f, const unwindstack::FrameData& frame) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800371 f->set_rel_pc(frame.rel_pc);
372 f->set_pc(frame.pc);
373 f->set_sp(frame.sp);
374
375 if (!frame.function_name.empty()) {
376 // TODO: Should this happen here, or on the display side?
377 char* demangled_name = __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
378 if (demangled_name) {
379 f->set_function_name(demangled_name);
380 free(demangled_name);
381 } else {
382 f->set_function_name(frame.function_name);
383 }
384 }
385
386 f->set_function_offset(frame.function_offset);
387
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800388 if (frame.map_info == nullptr) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800389 // No valid map associated with this frame.
390 f->set_file_name("<unknown>");
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800391 return;
392 }
393
394 if (!frame.map_info->name().empty()) {
395 f->set_file_name(frame.map_info->GetFullName());
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800396 } else {
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800397 f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_info->start()));
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800398 }
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800399 f->set_file_map_offset(frame.map_info->elf_start_offset());
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800400
Christopher Ferris22ad09b2021-11-10 17:25:11 -0800401 f->set_build_id(frame.map_info->GetPrintableBuildID());
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800402}
403
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700404static void dump_registers(unwindstack::AndroidUnwinder* unwinder,
Christopher Ferrisb999b822022-02-09 17:57:21 -0800405 const std::unique_ptr<unwindstack::Regs>& regs, Thread& thread,
406 bool memory_dump) {
407 if (regs == nullptr) {
408 return;
409 }
410
411 unwindstack::Maps* maps = unwinder->GetMaps();
412 unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
413
414 regs->IterateRegisters([&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
415 Register r;
416 r.set_name(name);
417 r.set_u64(value);
418 *thread.add_registers() = r;
419
420 if (memory_dump) {
421 MemoryDump dump;
422
423 dump.set_register_name(name);
424 std::shared_ptr<unwindstack::MapInfo> map_info = maps->Find(untag_address(value));
425 if (map_info) {
426 dump.set_mapping_name(map_info->name());
427 }
428
429 constexpr size_t kNumBytesAroundRegister = 256;
430 constexpr size_t kNumTagsAroundRegister = kNumBytesAroundRegister / kTagGranuleSize;
431 char buf[kNumBytesAroundRegister];
432 uint8_t tags[kNumTagsAroundRegister];
433 ssize_t bytes = dump_memory(buf, sizeof(buf), tags, sizeof(tags), &value, memory);
434 if (bytes == -1) {
435 return;
436 }
437 dump.set_begin_address(value);
438 dump.set_memory(buf, bytes);
439
440 bool has_tags = false;
441#if defined(__aarch64__)
442 for (size_t i = 0; i < kNumTagsAroundRegister; ++i) {
443 if (tags[i] != 0) {
444 has_tags = true;
445 }
446 }
447#endif // defined(__aarch64__)
448
449 if (has_tags) {
450 dump.mutable_arm_mte_metadata()->set_memory_tags(tags, kNumTagsAroundRegister);
451 }
452
453 *thread.add_memory_dump() = std::move(dump);
454 }
455 });
456}
457
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700458static void dump_thread_backtrace(std::vector<unwindstack::FrameData>& frames, Thread& thread) {
Christopher Ferrisc95047d2022-03-14 15:02:11 -0700459 std::set<std::string> unreadable_elf_files;
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700460 for (const auto& frame : frames) {
Christopher Ferrisc95047d2022-03-14 15:02:11 -0700461 BacktraceFrame* f = thread.add_current_backtrace();
462 fill_in_backtrace_frame(f, frame);
463 if (frame.map_info != nullptr && frame.map_info->ElfFileNotReadable()) {
464 unreadable_elf_files.emplace(frame.map_info->name());
465 }
466 }
467
468 if (!unreadable_elf_files.empty()) {
469 auto unreadable_elf_files_proto = thread.mutable_unreadable_elf_files();
Christopher Ferrisb999b822022-02-09 17:57:21 -0800470 auto backtrace_note = thread.mutable_backtrace_note();
471 *backtrace_note->Add() =
472 "Function names and BuildId information is missing for some frames due";
473 *backtrace_note->Add() = "to unreadable libraries. For unwinds of apps, only shared libraries";
474 *backtrace_note->Add() = "found under the lib/ directory are readable.";
475 *backtrace_note->Add() = "On this device, run setenforce 0 to make the libraries readable.";
Christopher Ferrisc95047d2022-03-14 15:02:11 -0700476 *backtrace_note->Add() = "Unreadable libraries:";
477 for (auto& name : unreadable_elf_files) {
478 *backtrace_note->Add() = " " + name;
479 *unreadable_elf_files_proto->Add() = name;
480 }
Christopher Ferrisb999b822022-02-09 17:57:21 -0800481 }
482}
483
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700484static void dump_thread(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
Josh Gao76e1e302021-01-26 15:53:11 -0800485 const ThreadInfo& thread_info, bool memory_dump = false) {
486 Thread thread;
487
488 thread.set_id(thread_info.tid);
489 thread.set_name(thread_info.thread_name);
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800490 thread.set_tagged_addr_ctrl(thread_info.tagged_addr_ctrl);
Elliott Hughesd13ea522022-01-13 09:20:26 -0800491 thread.set_pac_enabled_keys(thread_info.pac_enabled_keys);
Josh Gao76e1e302021-01-26 15:53:11 -0800492
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700493 unwindstack::AndroidUnwinderData data;
494 // Indicate we want a copy of the initial registers.
495 data.saved_initial_regs = std::make_optional<std::unique_ptr<unwindstack::Regs>>();
496 bool unwind_ret;
497 if (thread_info.registers != nullptr) {
498 unwind_ret = unwinder->Unwind(thread_info.registers.get(), data);
Josh Gao76e1e302021-01-26 15:53:11 -0800499 } else {
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700500 unwind_ret = unwinder->Unwind(thread_info.tid, data);
Josh Gao76e1e302021-01-26 15:53:11 -0800501 }
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700502 if (!unwind_ret) {
503 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "Unwind failed for tid %d: Error %s",
504 thread_info.tid, data.GetErrorString().c_str());
505 } else {
506 dump_thread_backtrace(data.frames, thread);
507 }
508 dump_registers(unwinder, *data.saved_initial_regs, thread, memory_dump);
Josh Gao76e1e302021-01-26 15:53:11 -0800509
510 auto& threads = *tombstone->mutable_threads();
511 threads[thread_info.tid] = thread;
512}
513
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700514static void dump_mappings(Tombstone* tombstone, unwindstack::Maps* maps,
515 std::shared_ptr<unwindstack::Memory>& process_memory) {
Josh Gao76e1e302021-01-26 15:53:11 -0800516 for (const auto& map_info : *maps) {
517 auto* map = tombstone->add_memory_mappings();
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100518 map->set_begin_address(map_info->start());
519 map->set_end_address(map_info->end());
520 map->set_offset(map_info->offset());
Josh Gao76e1e302021-01-26 15:53:11 -0800521
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100522 if (map_info->flags() & PROT_READ) {
Josh Gao76e1e302021-01-26 15:53:11 -0800523 map->set_read(true);
524 }
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100525 if (map_info->flags() & PROT_WRITE) {
Josh Gao76e1e302021-01-26 15:53:11 -0800526 map->set_write(true);
527 }
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100528 if (map_info->flags() & PROT_EXEC) {
Josh Gao76e1e302021-01-26 15:53:11 -0800529 map->set_execute(true);
530 }
531
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100532 map->set_mapping_name(map_info->name());
Josh Gao76e1e302021-01-26 15:53:11 -0800533
534 std::string build_id = map_info->GetPrintableBuildID();
535 if (!build_id.empty()) {
536 map->set_build_id(build_id);
537 }
538
539 map->set_load_bias(map_info->GetLoadBias(process_memory));
540 }
541}
542
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700543// This creates a fake log message that indicates an error occurred when
544// reading the log.
545static void add_error_log_msg(Tombstone* tombstone, const std::string&& error_msg) {
546 LogBuffer buffer;
547 buffer.set_name("ERROR");
548
549 LogMessage* log_msg = buffer.add_logs();
550 log_msg->set_timestamp("00-00 00:00:00.000");
551 log_msg->set_pid(0);
552 log_msg->set_tid(0);
553 log_msg->set_priority(ANDROID_LOG_ERROR);
554 log_msg->set_tag("");
555 log_msg->set_message(error_msg);
556
557 *tombstone->add_log_buffers() = std::move(buffer);
558
559 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
560}
561
Josh Gao76e1e302021-01-26 15:53:11 -0800562static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
Christopher Ferris98d62422023-05-24 20:01:10 +0000563 logger_list* logger_list = android_logger_list_open(android_name_to_log_id(logger),
564 ANDROID_LOG_NONBLOCK, kMaxLogMessages, pid);
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700565 if (logger_list == nullptr) {
566 add_error_log_msg(tombstone, android::base::StringPrintf("Cannot open log file %s", logger));
567 return;
568 }
Josh Gao76e1e302021-01-26 15:53:11 -0800569
570 LogBuffer buffer;
Josh Gao76e1e302021-01-26 15:53:11 -0800571 while (true) {
572 log_msg log_entry;
573 ssize_t actual = android_logger_list_read(logger_list, &log_entry);
Josh Gao76e1e302021-01-26 15:53:11 -0800574 if (actual < 0) {
575 if (actual == -EINTR) {
576 // interrupted by signal, retry
577 continue;
578 }
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700579 // Don't consider EAGAIN an error since this is a non-blocking call.
580 if (actual != -EAGAIN) {
581 add_error_log_msg(tombstone, android::base::StringPrintf("reading log %s failed (%s)",
582 logger, strerror(-actual)));
Josh Gao76e1e302021-01-26 15:53:11 -0800583 }
Christopher Ferris3a0833c2023-07-28 13:07:53 -0700584 break;
Josh Gao76e1e302021-01-26 15:53:11 -0800585 } else if (actual == 0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800586 break;
587 }
588
589 char timestamp_secs[32];
590 time_t sec = static_cast<time_t>(log_entry.entry.sec);
591 tm tm;
592 localtime_r(&sec, &tm);
593 strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
594 std::string timestamp =
595 StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
596
597 // Msg format is: <priority:1><tag:N>\0<message:N>\0
598 char* msg = log_entry.msg();
599 if (msg == nullptr) {
600 continue;
601 }
602
603 unsigned char prio = msg[0];
604 char* tag = msg + 1;
605 msg = tag + strlen(tag) + 1;
606
607 // consume any trailing newlines
608 char* nl = msg + strlen(msg) - 1;
609 while (nl >= msg && *nl == '\n') {
610 *nl-- = '\0';
611 }
612
613 // Look for line breaks ('\n') and display each text line
614 // on a separate line, prefixed with the header, like logcat does.
615 do {
616 nl = strchr(msg, '\n');
617 if (nl != nullptr) {
618 *nl = '\0';
619 ++nl;
620 }
621
622 LogMessage* log_msg = buffer.add_logs();
623 log_msg->set_timestamp(timestamp);
624 log_msg->set_pid(log_entry.entry.pid);
625 log_msg->set_tid(log_entry.entry.tid);
626 log_msg->set_priority(prio);
627 log_msg->set_tag(tag);
628 log_msg->set_message(msg);
629 } while ((msg = nl));
630 }
631 android_logger_list_free(logger_list);
632
633 if (!buffer.logs().empty()) {
634 buffer.set_name(logger);
635 *tombstone->add_log_buffers() = std::move(buffer);
636 }
637}
638
639static void dump_logcat(Tombstone* tombstone, pid_t pid) {
640 dump_log_file(tombstone, "system", pid);
641 dump_log_file(tombstone, "main", pid);
642}
643
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700644static void dump_tags_around_fault_addr(Signal* signal, const Tombstone& tombstone,
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700645 std::shared_ptr<unwindstack::Memory>& process_memory,
646 uintptr_t fault_addr) {
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700647 if (tombstone.arch() != Architecture::ARM64) return;
648
649 fault_addr = untag_address(fault_addr);
650 constexpr size_t kNumGranules = kNumTagRows * kNumTagColumns;
651 constexpr size_t kBytesToRead = kNumGranules * kTagGranuleSize;
652
653 // If the low part of the tag dump would underflow to the high address space, it's probably not
654 // a valid address for us to dump tags from.
655 if (fault_addr < kBytesToRead / 2) return;
656
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700657 constexpr uintptr_t kRowStartMask = ~(kNumTagColumns * kTagGranuleSize - 1);
658 size_t start_address = (fault_addr & kRowStartMask) - kBytesToRead / 2;
659 MemoryDump tag_dump;
660 size_t granules_to_read = kNumGranules;
661
662 // Attempt to read the first tag. If reading fails, this likely indicates the
663 // lowest touched page is inaccessible or not marked with PROT_MTE.
664 // Fast-forward over pages until one has tags, or we exhaust the search range.
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700665 while (process_memory->ReadTag(start_address) < 0) {
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700666 size_t page_size = sysconf(_SC_PAGE_SIZE);
667 size_t bytes_to_next_page = page_size - (start_address % page_size);
668 if (bytes_to_next_page >= granules_to_read * kTagGranuleSize) return;
669 start_address += bytes_to_next_page;
670 granules_to_read -= bytes_to_next_page / kTagGranuleSize;
671 }
672 tag_dump.set_begin_address(start_address);
673
674 std::string* mte_tags = tag_dump.mutable_arm_mte_metadata()->mutable_memory_tags();
675
676 for (size_t i = 0; i < granules_to_read; ++i) {
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700677 long tag = process_memory->ReadTag(start_address + i * kTagGranuleSize);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700678 if (tag < 0) break;
679 mte_tags->push_back(static_cast<uint8_t>(tag));
680 }
681
682 if (!mte_tags->empty()) {
683 *signal->mutable_fault_adjacent_metadata() = tag_dump;
684 }
685}
686
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700687void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
Florian Mayer2d453312024-04-22 23:43:59 +0000688 const std::map<pid_t, ThreadInfo>& threads, pid_t target_tid,
Josh Gao76e1e302021-01-26 15:53:11 -0800689 const ProcessInfo& process_info, const OpenFilesList* open_files) {
690 Tombstone result;
691
692 result.set_arch(get_arch());
693 result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
694 result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
695 result.set_timestamp(get_timestamp());
696
Florian Mayer2d453312024-04-22 23:43:59 +0000697 const ThreadInfo& target_thread = threads.at(target_tid);
698 result.set_pid(target_thread.pid);
699 result.set_tid(target_thread.tid);
700 result.set_uid(target_thread.uid);
701 result.set_selinux_label(target_thread.selinux_label);
Christopher Ferris2b98c822021-09-28 15:50:04 -0700702 // The main thread must have a valid siginfo.
Florian Mayer2d453312024-04-22 23:43:59 +0000703 CHECK(target_thread.siginfo != nullptr);
Josh Gao76e1e302021-01-26 15:53:11 -0800704
Elliott Hughes32d3cdd2021-09-21 12:20:53 -0700705 struct sysinfo si;
706 sysinfo(&si);
707 android::procinfo::ProcessInfo proc_info;
708 std::string error;
Florian Mayer2d453312024-04-22 23:43:59 +0000709 if (android::procinfo::GetProcessInfo(target_thread.pid, &proc_info, &error)) {
Elliott Hughes32d3cdd2021-09-21 12:20:53 -0700710 uint64_t starttime = proc_info.starttime / sysconf(_SC_CLK_TCK);
711 result.set_process_uptime(si.uptime - starttime);
712 } else {
713 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read process info: %s",
714 error.c_str());
715 }
716
Josh Gao31348a72021-03-29 21:53:42 -0700717 auto cmd_line = result.mutable_command_line();
Florian Mayer2d453312024-04-22 23:43:59 +0000718 for (const auto& arg : target_thread.command_line) {
Josh Gao31348a72021-03-29 21:53:42 -0700719 *cmd_line->Add() = arg;
720 }
721
Florian Mayer2d453312024-04-22 23:43:59 +0000722 if (!target_thread.siginfo) {
Josh Gao618cea32021-01-26 17:45:43 -0800723 async_safe_fatal("siginfo missing");
724 }
Josh Gao76e1e302021-01-26 15:53:11 -0800725
726 Signal sig;
Florian Mayer2d453312024-04-22 23:43:59 +0000727 sig.set_number(target_thread.signo);
728 sig.set_name(get_signame(target_thread.siginfo));
729 sig.set_code(target_thread.siginfo->si_code);
730 sig.set_code_name(get_sigcode(target_thread.siginfo));
Josh Gao76e1e302021-01-26 15:53:11 -0800731
Florian Mayer2d453312024-04-22 23:43:59 +0000732 if (signal_has_sender(target_thread.siginfo, target_thread.pid)) {
Josh Gao76e1e302021-01-26 15:53:11 -0800733 sig.set_has_sender(true);
Florian Mayer2d453312024-04-22 23:43:59 +0000734 sig.set_sender_uid(target_thread.siginfo->si_uid);
735 sig.set_sender_pid(target_thread.siginfo->si_pid);
Josh Gao76e1e302021-01-26 15:53:11 -0800736 }
737
738 if (process_info.has_fault_address) {
739 sig.set_has_fault_address(true);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700740 uintptr_t fault_addr = process_info.maybe_tagged_fault_address;
741 sig.set_fault_address(fault_addr);
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700742 dump_tags_around_fault_addr(&sig, result, unwinder->GetProcessMemory(), fault_addr);
Josh Gao76e1e302021-01-26 15:53:11 -0800743 }
744
745 *result.mutable_signal_info() = sig;
746
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700747 dump_abort_message(&result, unwinder->GetProcessMemory(), process_info);
Florian Mayer5fa66632024-02-07 16:42:23 -0800748 dump_crash_details(&result, unwinder->GetProcessMemory(), process_info);
Florian Mayer2d453312024-04-22 23:43:59 +0000749 // Dump the target thread, but save the memory around the registers.
750 dump_thread(&result, unwinder, target_thread, /* memory_dump */ true);
Josh Gao76e1e302021-01-26 15:53:11 -0800751
752 for (const auto& [tid, thread_info] : threads) {
Florian Mayer2d453312024-04-22 23:43:59 +0000753 if (tid != target_tid) {
Josh Gao76e1e302021-01-26 15:53:11 -0800754 dump_thread(&result, unwinder, thread_info);
755 }
756 }
757
Florian Mayer2d453312024-04-22 23:43:59 +0000758 dump_probable_cause(&result, unwinder, process_info, target_thread);
Josh Gao76e1e302021-01-26 15:53:11 -0800759
Christopher Ferris3b7b7ba2022-03-15 16:56:09 -0700760 dump_mappings(&result, unwinder->GetMaps(), unwinder->GetProcessMemory());
Josh Gao76e1e302021-01-26 15:53:11 -0800761
762 // Only dump logs on debuggable devices.
763 if (android::base::GetBoolProperty("ro.debuggable", false)) {
Christopher Ferrisbda10642023-04-24 18:14:53 -0700764 // Get the thread that corresponds to the main pid of the process.
Florian Mayer2d453312024-04-22 23:43:59 +0000765 const ThreadInfo& thread = threads.at(target_thread.pid);
Christopher Ferrisbda10642023-04-24 18:14:53 -0700766
767 // Do not attempt to dump logs of the logd process because the gathering
768 // of logs can hang until a timeout occurs.
769 if (thread.thread_name != "logd") {
Florian Mayer2d453312024-04-22 23:43:59 +0000770 dump_logcat(&result, target_thread.pid);
Christopher Ferrisbda10642023-04-24 18:14:53 -0700771 }
Josh Gao76e1e302021-01-26 15:53:11 -0800772 }
773
774 dump_open_fds(&result, open_files);
775
776 *tombstone = std::move(result);
777}