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 <android/set_abort_message.h>
52 #include <bionic/macros.h>
53 #include <bionic/reserved_signals.h>
54 #include <bionic/crash_detail_internal.h>
55 #include <log/log.h>
56 #include <log/log_read.h>
57 #include <log/logprint.h>
58 #include <private/android_filesystem_config.h>
59
60 #include <procinfo/process.h>
61 #include <unwindstack/AndroidUnwinder.h>
62 #include <unwindstack/Error.h>
63 #include <unwindstack/MapInfo.h>
64 #include <unwindstack/Maps.h>
65 #include <unwindstack/Regs.h>
66
67 #include "libdebuggerd/open_files_list.h"
68 #include "libdebuggerd/utility.h"
69 #include "util.h"
70
71 #include "tombstone.pb.h"
72
73 using android::base::StringPrintf;
74
75 // The maximum number of messages to save in the protobuf per file.
76 static constexpr size_t kMaxLogMessages = 500;
77
78 // Use the demangler from libc++.
79 extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
80
get_arch()81 static 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;
90 #elif defined(__riscv) && (__riscv_xlen == 64)
91 return Architecture::RISCV64;
92 #else
93 #error Unknown architecture!
94 #endif
95 }
96
get_stack_overflow_cause(uint64_t fault_addr,uint64_t sp,unwindstack::Maps * maps)97 static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
98 unwindstack::Maps* maps) {
99 // 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);
104 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.
121 std::shared_ptr<unwindstack::MapInfo> map_info = maps->Find(sp);
122 if (map_info == nullptr) {
123 return "stack pointer is in a non-existent map; likely due to stack overflow.";
124 } else if ((map_info->flags() & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
125 return "stack pointer is not in a rw map; likely due to stack overflow.";
126 } else if ((sp - map_info->start()) <= kMaxDifferenceBytes) {
127 return "stack pointer is close to top of stack; likely stack overflow.";
128 }
129 }
130 return {};
131 }
132
set_human_readable_cause(Cause * cause,uint64_t fault_addr)133 void 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
dump_probable_cause(Tombstone * tombstone,unwindstack::AndroidUnwinder * unwinder,const ProcessInfo & process_info,const ThreadInfo & target_thread)205 static void dump_probable_cause(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
206 const ProcessInfo& process_info, const ThreadInfo& target_thread) {
207 #if defined(USE_SCUDO)
208 ScudoCrashData scudo_crash_data(unwinder->GetProcessMemory().get(), process_info);
209 if (scudo_crash_data.CrashIsMine()) {
210 scudo_crash_data.AddCauseProtos(tombstone, unwinder);
211 return;
212 }
213 #endif
214
215 GwpAsanCrashData gwp_asan_crash_data(unwinder->GetProcessMemory().get(), process_info,
216 target_thread);
217 if (gwp_asan_crash_data.CrashIsMine()) {
218 gwp_asan_crash_data.AddCauseProtos(tombstone, unwinder);
219 return;
220 }
221
222 const siginfo *si = target_thread.siginfo;
223 auto fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
224 unwindstack::Maps* maps = unwinder->GetMaps();
225
226 std::optional<std::string> cause;
227 if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
228 if (fault_addr < 4096) {
229 cause = "null pointer dereference";
230 } else if (fault_addr == 0xffff0ffc) {
231 cause = "call to kuser_helper_version";
232 } else if (fault_addr == 0xffff0fe0) {
233 cause = "call to kuser_get_tls";
234 } else if (fault_addr == 0xffff0fc0) {
235 cause = "call to kuser_cmpxchg";
236 } else if (fault_addr == 0xffff0fa0) {
237 cause = "call to kuser_memory_barrier";
238 } else if (fault_addr == 0xffff0f60) {
239 cause = "call to kuser_cmpxchg64";
240 } else {
241 cause = get_stack_overflow_cause(fault_addr, target_thread.registers->sp(), maps);
242 }
243 } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
244 auto map_info = maps->Find(fault_addr);
245 if (map_info != nullptr && map_info->flags() == PROT_EXEC) {
246 cause = "execute-only (no-read) memory access error; likely due to data in .text.";
247 } else {
248 cause = get_stack_overflow_cause(fault_addr, target_thread.registers->sp(), maps);
249 }
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) {
256 Cause *cause_proto = tombstone->add_causes();
257 cause_proto->set_human_readable(*cause);
258 }
259 }
260
dump_crash_details(Tombstone * tombstone,std::shared_ptr<unwindstack::Memory> & process_memory,const ProcessInfo & process_info)261 static 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
dump_abort_message(Tombstone * tombstone,std::shared_ptr<unwindstack::Memory> & process_memory,const ProcessInfo & process_info)301 static void dump_abort_message(Tombstone* tombstone,
302 std::shared_ptr<unwindstack::Memory>& process_memory,
303 const ProcessInfo& process_info) {
304 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))) {
311 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
312 strerror(errno));
313 return;
314 }
315
316 // The length field includes the length of the length field itself.
317 if (length < sizeof(size_t)) {
318 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
319 "abort message header malformed: claimed length = %zu", length);
320 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)) {
330 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
331 strerror(errno));
332 return;
333 }
334
335 // 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
342 tombstone->set_abort_message(msg);
343 }
344
dump_open_fds(Tombstone * tombstone,const OpenFilesList * open_files)345 static 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
fill_in_backtrace_frame(BacktraceFrame * f,const unwindstack::FrameData & frame)370 void fill_in_backtrace_frame(BacktraceFrame* f, const unwindstack::FrameData& frame) {
371 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
388 if (frame.map_info == nullptr) {
389 // No valid map associated with this frame.
390 f->set_file_name("<unknown>");
391 return;
392 }
393
394 if (!frame.map_info->name().empty()) {
395 f->set_file_name(frame.map_info->GetFullName());
396 } else {
397 f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_info->start()));
398 }
399 f->set_file_map_offset(frame.map_info->elf_start_offset());
400
401 f->set_build_id(frame.map_info->GetPrintableBuildID());
402 }
403
dump_registers(unwindstack::AndroidUnwinder * unwinder,const std::unique_ptr<unwindstack::Regs> & regs,Thread & thread,bool memory_dump)404 static void dump_registers(unwindstack::AndroidUnwinder* unwinder,
405 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
dump_thread_backtrace(std::vector<unwindstack::FrameData> & frames,Thread & thread)458 static void dump_thread_backtrace(std::vector<unwindstack::FrameData>& frames, Thread& thread) {
459 std::set<std::string> unreadable_elf_files;
460 for (const auto& frame : frames) {
461 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();
470 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.";
476 *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 }
481 }
482 }
483
dump_thread(Tombstone * tombstone,unwindstack::AndroidUnwinder * unwinder,const ThreadInfo & thread_info,bool memory_dump=false,unwindstack::AndroidUnwinder * guest_unwinder=nullptr)484 static void dump_thread(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
485 const ThreadInfo& thread_info, bool memory_dump = false,
486 unwindstack::AndroidUnwinder* guest_unwinder = nullptr) {
487 Thread thread;
488
489 thread.set_id(thread_info.tid);
490 thread.set_name(thread_info.thread_name);
491 thread.set_tagged_addr_ctrl(thread_info.tagged_addr_ctrl);
492 thread.set_pac_enabled_keys(thread_info.pac_enabled_keys);
493
494 unwindstack::AndroidUnwinderData data;
495 // Indicate we want a copy of the initial registers.
496 data.saved_initial_regs = std::make_optional<std::unique_ptr<unwindstack::Regs>>();
497 bool unwind_ret;
498 if (thread_info.registers != nullptr) {
499 unwind_ret = unwinder->Unwind(thread_info.registers.get(), data);
500 } else {
501 unwind_ret = unwinder->Unwind(thread_info.tid, data);
502 }
503 if (!unwind_ret) {
504 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "Unwind failed for tid %d: Error %s",
505 thread_info.tid, data.GetErrorString().c_str());
506 } else {
507 dump_thread_backtrace(data.frames, thread);
508 }
509 dump_registers(unwinder, *data.saved_initial_regs, thread, memory_dump);
510
511 auto& threads = *tombstone->mutable_threads();
512 threads[thread_info.tid] = thread;
513
514 if (guest_unwinder) {
515 if (!thread_info.guest_registers) {
516 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
517 "No guest state registers information for tid %d", thread_info.tid);
518 return;
519 }
520 Thread guest_thread;
521 unwindstack::AndroidUnwinderData guest_data;
522 guest_data.saved_initial_regs = std::make_optional<std::unique_ptr<unwindstack::Regs>>();
523 if (guest_unwinder->Unwind(thread_info.guest_registers.get(), guest_data)) {
524 dump_thread_backtrace(guest_data.frames, guest_thread);
525 } else {
526 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
527 "Unwind guest state registers failed for tid %d: Error %s",
528 thread_info.tid, guest_data.GetErrorString().c_str());
529 }
530 dump_registers(guest_unwinder, *guest_data.saved_initial_regs, guest_thread, memory_dump);
531 auto& guest_threads = *tombstone->mutable_guest_threads();
532 guest_threads[thread_info.tid] = guest_thread;
533 }
534 }
535
dump_mappings(Tombstone * tombstone,unwindstack::Maps * maps,std::shared_ptr<unwindstack::Memory> & process_memory)536 static void dump_mappings(Tombstone* tombstone, unwindstack::Maps* maps,
537 std::shared_ptr<unwindstack::Memory>& process_memory) {
538 for (const auto& map_info : *maps) {
539 auto* map = tombstone->add_memory_mappings();
540 map->set_begin_address(map_info->start());
541 map->set_end_address(map_info->end());
542 map->set_offset(map_info->offset());
543
544 if (map_info->flags() & PROT_READ) {
545 map->set_read(true);
546 }
547 if (map_info->flags() & PROT_WRITE) {
548 map->set_write(true);
549 }
550 if (map_info->flags() & PROT_EXEC) {
551 map->set_execute(true);
552 }
553
554 map->set_mapping_name(map_info->name());
555
556 std::string build_id = map_info->GetPrintableBuildID();
557 if (!build_id.empty()) {
558 map->set_build_id(build_id);
559 }
560
561 map->set_load_bias(map_info->GetLoadBias(process_memory));
562 }
563 }
564
565 // This creates a fake log message that indicates an error occurred when
566 // reading the log.
add_error_log_msg(Tombstone * tombstone,const std::string && error_msg)567 static void add_error_log_msg(Tombstone* tombstone, const std::string&& error_msg) {
568 LogBuffer buffer;
569 buffer.set_name("ERROR");
570
571 LogMessage* log_msg = buffer.add_logs();
572 log_msg->set_timestamp("00-00 00:00:00.000");
573 log_msg->set_pid(0);
574 log_msg->set_tid(0);
575 log_msg->set_priority(ANDROID_LOG_ERROR);
576 log_msg->set_tag("");
577 log_msg->set_message(error_msg);
578
579 *tombstone->add_log_buffers() = std::move(buffer);
580
581 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "%s", error_msg.c_str());
582 }
583
dump_log_file(Tombstone * tombstone,const char * logger,pid_t pid)584 static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
585 logger_list* logger_list = android_logger_list_open(android_name_to_log_id(logger),
586 ANDROID_LOG_NONBLOCK, kMaxLogMessages, pid);
587 if (logger_list == nullptr) {
588 add_error_log_msg(tombstone, android::base::StringPrintf("Cannot open log file %s", logger));
589 return;
590 }
591
592 LogBuffer buffer;
593 while (true) {
594 log_msg log_entry;
595 ssize_t actual = android_logger_list_read(logger_list, &log_entry);
596 if (actual < 0) {
597 if (actual == -EINTR) {
598 // interrupted by signal, retry
599 continue;
600 }
601 // Don't consider EAGAIN an error since this is a non-blocking call.
602 if (actual != -EAGAIN) {
603 add_error_log_msg(tombstone, android::base::StringPrintf("reading log %s failed (%s)",
604 logger, strerror(-actual)));
605 }
606 break;
607 } else if (actual == 0) {
608 break;
609 }
610
611 char timestamp_secs[32];
612 time_t sec = static_cast<time_t>(log_entry.entry.sec);
613 tm tm;
614 localtime_r(&sec, &tm);
615 strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
616 std::string timestamp =
617 StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
618
619 // Msg format is: <priority:1><tag:N>\0<message:N>\0
620 char* msg = log_entry.msg();
621 if (msg == nullptr) {
622 continue;
623 }
624
625 unsigned char prio = msg[0];
626 char* tag = msg + 1;
627 msg = tag + strlen(tag) + 1;
628
629 // consume any trailing newlines
630 char* nl = msg + strlen(msg) - 1;
631 while (nl >= msg && *nl == '\n') {
632 *nl-- = '\0';
633 }
634
635 // Look for line breaks ('\n') and display each text line
636 // on a separate line, prefixed with the header, like logcat does.
637 do {
638 nl = strchr(msg, '\n');
639 if (nl != nullptr) {
640 *nl = '\0';
641 ++nl;
642 }
643
644 LogMessage* log_msg = buffer.add_logs();
645 log_msg->set_timestamp(timestamp);
646 log_msg->set_pid(log_entry.entry.pid);
647 log_msg->set_tid(log_entry.entry.tid);
648 log_msg->set_priority(prio);
649 log_msg->set_tag(tag);
650 log_msg->set_message(msg);
651 } while ((msg = nl));
652 }
653 android_logger_list_free(logger_list);
654
655 if (!buffer.logs().empty()) {
656 buffer.set_name(logger);
657 *tombstone->add_log_buffers() = std::move(buffer);
658 }
659 }
660
dump_logcat(Tombstone * tombstone,pid_t pid)661 static void dump_logcat(Tombstone* tombstone, pid_t pid) {
662 dump_log_file(tombstone, "system", pid);
663 dump_log_file(tombstone, "main", pid);
664 }
665
dump_tags_around_fault_addr(Signal * signal,const Tombstone & tombstone,std::shared_ptr<unwindstack::Memory> & process_memory,uintptr_t fault_addr)666 static void dump_tags_around_fault_addr(Signal* signal, const Tombstone& tombstone,
667 std::shared_ptr<unwindstack::Memory>& process_memory,
668 uintptr_t fault_addr) {
669 if (tombstone.arch() != Architecture::ARM64) return;
670
671 fault_addr = untag_address(fault_addr);
672 constexpr size_t kNumGranules = kNumTagRows * kNumTagColumns;
673 constexpr size_t kBytesToRead = kNumGranules * kTagGranuleSize;
674
675 // If the low part of the tag dump would underflow to the high address space, it's probably not
676 // a valid address for us to dump tags from.
677 if (fault_addr < kBytesToRead / 2) return;
678
679 constexpr uintptr_t kRowStartMask = ~(kNumTagColumns * kTagGranuleSize - 1);
680 size_t start_address = (fault_addr & kRowStartMask) - kBytesToRead / 2;
681 MemoryDump tag_dump;
682 size_t granules_to_read = kNumGranules;
683
684 // Attempt to read the first tag. If reading fails, this likely indicates the
685 // lowest touched page is inaccessible or not marked with PROT_MTE.
686 // Fast-forward over pages until one has tags, or we exhaust the search range.
687 while (process_memory->ReadTag(start_address) < 0) {
688 size_t page_size = sysconf(_SC_PAGE_SIZE);
689 size_t bytes_to_next_page = page_size - (start_address % page_size);
690 if (bytes_to_next_page >= granules_to_read * kTagGranuleSize) return;
691 start_address += bytes_to_next_page;
692 granules_to_read -= bytes_to_next_page / kTagGranuleSize;
693 }
694 tag_dump.set_begin_address(start_address);
695
696 std::string* mte_tags = tag_dump.mutable_arm_mte_metadata()->mutable_memory_tags();
697
698 for (size_t i = 0; i < granules_to_read; ++i) {
699 long tag = process_memory->ReadTag(start_address + i * kTagGranuleSize);
700 if (tag < 0) break;
701 mte_tags->push_back(static_cast<uint8_t>(tag));
702 }
703
704 if (!mte_tags->empty()) {
705 *signal->mutable_fault_adjacent_metadata() = tag_dump;
706 }
707 }
708
engrave_tombstone_proto(Tombstone * tombstone,unwindstack::AndroidUnwinder * unwinder,const std::map<pid_t,ThreadInfo> & threads,pid_t target_tid,const ProcessInfo & process_info,const OpenFilesList * open_files,const Architecture * guest_arch,unwindstack::AndroidUnwinder * guest_unwinder)709 void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::AndroidUnwinder* unwinder,
710 const std::map<pid_t, ThreadInfo>& threads, pid_t target_tid,
711 const ProcessInfo& process_info, const OpenFilesList* open_files,
712 const Architecture* guest_arch,
713 unwindstack::AndroidUnwinder* guest_unwinder) {
714 Tombstone result;
715
716 result.set_arch(get_arch());
717 if (guest_arch != nullptr) {
718 result.set_guest_arch(*guest_arch);
719 } else {
720 result.set_guest_arch(Architecture::NONE);
721 }
722 result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
723 result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
724 result.set_timestamp(get_timestamp());
725
726 const ThreadInfo& target_thread = threads.at(target_tid);
727 result.set_pid(target_thread.pid);
728 result.set_tid(target_thread.tid);
729 result.set_uid(target_thread.uid);
730 result.set_selinux_label(target_thread.selinux_label);
731 // The main thread must have a valid siginfo.
732 CHECK(target_thread.siginfo != nullptr);
733
734 struct sysinfo si;
735 sysinfo(&si);
736 android::procinfo::ProcessInfo proc_info;
737 std::string error;
738 if (android::procinfo::GetProcessInfo(target_thread.pid, &proc_info, &error)) {
739 uint64_t starttime = proc_info.starttime / sysconf(_SC_CLK_TCK);
740 result.set_process_uptime(si.uptime - starttime);
741 } else {
742 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read process info: %s",
743 error.c_str());
744 }
745
746 result.set_page_size(getpagesize());
747 result.set_has_been_16kb_mode(android::base::GetBoolProperty("ro.misctrl.16kb_before", false));
748
749 auto cmd_line = result.mutable_command_line();
750 for (const auto& arg : target_thread.command_line) {
751 *cmd_line->Add() = arg;
752 }
753
754 if (!target_thread.siginfo) {
755 async_safe_fatal("siginfo missing");
756 }
757
758 Signal sig;
759 sig.set_number(target_thread.signo);
760 sig.set_name(get_signame(target_thread.siginfo));
761 sig.set_code(target_thread.siginfo->si_code);
762 sig.set_code_name(get_sigcode(target_thread.siginfo));
763
764 if (signal_has_sender(target_thread.siginfo, target_thread.pid)) {
765 sig.set_has_sender(true);
766 sig.set_sender_uid(target_thread.siginfo->si_uid);
767 sig.set_sender_pid(target_thread.siginfo->si_pid);
768 }
769
770 if (process_info.has_fault_address) {
771 sig.set_has_fault_address(true);
772 uintptr_t fault_addr = process_info.maybe_tagged_fault_address;
773 sig.set_fault_address(fault_addr);
774 dump_tags_around_fault_addr(&sig, result, unwinder->GetProcessMemory(), fault_addr);
775 }
776
777 *result.mutable_signal_info() = sig;
778
779 dump_abort_message(&result, unwinder->GetProcessMemory(), process_info);
780 dump_crash_details(&result, unwinder->GetProcessMemory(), process_info);
781 // Dump the target thread, but save the memory around the registers.
782 dump_thread(&result, unwinder, target_thread, /* memory_dump */ true, guest_unwinder);
783
784 for (const auto& [tid, thread_info] : threads) {
785 if (tid != target_tid) {
786 dump_thread(&result, unwinder, thread_info, /* memory_dump */ false, guest_unwinder);
787 }
788 }
789
790 dump_probable_cause(&result, unwinder, process_info, target_thread);
791
792 dump_mappings(&result, unwinder->GetMaps(), unwinder->GetProcessMemory());
793
794 // Only dump logs on debuggable devices.
795 if (android::base::GetBoolProperty("ro.debuggable", false)) {
796 // Get the thread that corresponds to the main pid of the process.
797 const ThreadInfo& thread = threads.at(target_thread.pid);
798
799 // Do not attempt to dump logs of the logd process because the gathering
800 // of logs can hang until a timeout occurs.
801 if (thread.thread_name != "logd") {
802 dump_logcat(&result, target_thread.pid);
803 }
804 }
805
806 dump_open_fds(&result, open_files);
807
808 *tombstone = std::move(result);
809 }
810