Reland protobuf tombstones.
This reverts the following commits:
e156ede145a7fc671c705d045d89b49922a758b5.
eda96eddcbdda9632166232b2363c7b84da0994d.
5ec54d1e843729cd1e38a2f791f001226a653e95.
1e45d3f2239333217d3252f78151f4294fda4e80.
a50f61f8fa903117a6df82d164628de310f16ae9.
Test: treehugger
Test: atest -c CtsSeccompHostTestCases:android.seccomp.cts.SeccompHostJUnit4DeviceTest#testAppZygoteSyscalls
Change-Id: Ic2b1f489ac9f1fec7d7a33c845c29891f4306bbd
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
index 3ff7d62..bf2cbb3 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
@@ -21,6 +21,7 @@
#include <stddef.h>
#include <sys/types.h>
+#include <functional>
#include <map>
#include <string>
@@ -30,6 +31,8 @@
#include "types.h"
// Forward declarations
+class Tombstone;
+
namespace unwindstack {
class Unwinder;
}
@@ -44,13 +47,21 @@
int open_tombstone(std::string* path);
/* Creates a tombstone file and writes the crash dump to it. */
-void engrave_tombstone(android::base::unique_fd output_fd, unwindstack::Unwinder* unwinder,
+void engrave_tombstone(android::base::unique_fd output_fd, android::base::unique_fd proto_fd,
+ unwindstack::Unwinder* unwinder,
const std::map<pid_t, ThreadInfo>& thread_info, pid_t target_thread,
const ProcessInfo& process_info, OpenFilesList* open_files,
std::string* amfd_data);
-void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
- ucontext_t* ucontext);
+void engrave_tombstone_ucontext(int tombstone_fd, int proto_fd, uint64_t abort_msg_address,
+ siginfo_t* siginfo, ucontext_t* ucontext);
+void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+ const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
+ const ProcessInfo& process_info, const OpenFilesList* open_files);
+
+bool tombstone_proto_to_text(
+ const Tombstone& tombstone,
+ std::function<void(const std::string& line, bool should_log)> callback);
#endif // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/types.h b/debuggerd/libdebuggerd/include/libdebuggerd/types.h
index 86522ee..d5b0735 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/types.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/types.h
@@ -31,7 +31,9 @@
std::string thread_name;
pid_t pid;
+
std::string process_name;
+ std::string selinux_label;
int signo = 0;
siginfo_t* siginfo = nullptr;
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
index 29fb9a4..d71b76f 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
@@ -81,6 +81,8 @@
void log_backtrace(log_t* log, unwindstack::Unwinder* unwinder, const char* prefix);
+ssize_t dump_memory(void* out, size_t len, size_t* start_offset, uint64_t* addr,
+ unwindstack::Memory* memory);
void dump_memory(log_t* log, unwindstack::Memory* backtrace, uint64_t addr, const std::string&);
void drop_capabilities();
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index 4bd7192..822b74a 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -63,6 +63,8 @@
#include "gwp_asan/common.h"
#include "gwp_asan/crash_handler.h"
+#include "tombstone.pb.h"
+
using android::base::GetBoolProperty;
using android::base::GetProperty;
using android::base::StringPrintf;
@@ -190,8 +192,7 @@
static std::string get_addr_string(uint64_t addr) {
std::string addr_str;
#if defined(__LP64__)
- addr_str = StringPrintf("%08x'%08x",
- static_cast<uint32_t>(addr >> 32),
+ addr_str = StringPrintf("%08x'%08x", static_cast<uint32_t>(addr >> 32),
static_cast<uint32_t>(addr & 0xffffffff));
#else
addr_str = StringPrintf("%08x", static_cast<uint32_t>(addr));
@@ -394,8 +395,7 @@
if (primary_thread && gwp_asan_crash_data->CrashIsMine()) {
gwp_asan_crash_data->DumpCause(log);
} else if (thread_info.siginfo && !(primary_thread && scudo_crash_data->CrashIsMine())) {
- dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps(),
- thread_info.registers.get());
+ dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps(), thread_info.registers.get());
}
if (primary_thread) {
@@ -492,8 +492,7 @@
// the tombstone file.
if (first) {
- _LOG(log, logtype::LOGS, "--------- %slog %s\n",
- tail ? "tail end of " : "", filename);
+ _LOG(log, logtype::LOGS, "--------- %slog %s\n", tail ? "tail end of " : "", filename);
first = false;
}
@@ -554,8 +553,8 @@
dump_log_file(log, pid, "main", tail);
}
-void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
- ucontext_t* ucontext) {
+void engrave_tombstone_ucontext(int tombstone_fd, int proto_fd, uint64_t abort_msg_address,
+ siginfo_t* siginfo, ucontext_t* ucontext) {
pid_t uid = getuid();
pid_t pid = getpid();
pid_t tid = gettid();
@@ -572,14 +571,18 @@
std::unique_ptr<unwindstack::Regs> regs(
unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), ucontext));
+ std::string selinux_label;
+ android::base::ReadFileToString("/proc/self/attr/current", &selinux_label);
+
std::map<pid_t, ThreadInfo> threads;
threads[tid] = ThreadInfo{
.registers = std::move(regs),
.uid = uid,
.tid = tid,
- .thread_name = thread_name.c_str(),
+ .thread_name = std::move(thread_name),
.pid = pid,
- .process_name = process_name.c_str(),
+ .process_name = std::move(process_name),
+ .selinux_label = std::move(selinux_label),
.siginfo = siginfo,
};
@@ -589,17 +592,23 @@
}
ProcessInfo process_info;
+ unique_fd attr_fd(open("/proc/self/attr/current", O_RDONLY | O_CLOEXEC));
process_info.abort_msg_address = abort_msg_address;
- engrave_tombstone(unique_fd(dup(tombstone_fd)), &unwinder, threads, tid, process_info, nullptr,
- nullptr);
+ engrave_tombstone(unique_fd(dup(tombstone_fd)), unique_fd(dup(proto_fd)), &unwinder, threads, tid,
+ process_info, nullptr, nullptr);
}
-void engrave_tombstone(unique_fd output_fd, unwindstack::Unwinder* unwinder,
+void engrave_tombstone(unique_fd output_fd, unique_fd proto_fd, unwindstack::Unwinder* unwinder,
const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
const ProcessInfo& process_info, OpenFilesList* open_files,
std::string* amfd_data) {
// Don't copy log messages to tombstone unless this is a development device.
- bool want_logs = GetBoolProperty("ro.debuggable", false);
+ Tombstone tombstone;
+ engrave_tombstone_proto(&tombstone, unwinder, threads, target_thread, process_info, open_files);
+
+ if (!tombstone.SerializeToFileDescriptor(proto_fd.get())) {
+ PLOG(ERROR) << "Failed to write proto tombstone";
+ }
log_t log;
log.current_tid = target_thread;
@@ -607,35 +616,45 @@
log.tfd = output_fd.get();
log.amfd_data = amfd_data;
- _LOG(&log, logtype::HEADER, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
- dump_header_info(&log);
- _LOG(&log, logtype::HEADER, "Timestamp: %s\n", get_timestamp().c_str());
+ bool translate_proto = GetBoolProperty("debug.debuggerd.translate_proto_to_text", false);
+ if (translate_proto) {
+ tombstone_proto_to_text(tombstone, [&log](const std::string& line, bool should_log) {
+ _LOG(&log, should_log ? logtype::HEADER : logtype::LOGS, "%s\n", line.c_str());
+ });
+ } else {
+ bool want_logs = GetBoolProperty("ro.debuggable", false);
- auto it = threads.find(target_thread);
- if (it == threads.end()) {
- LOG(FATAL) << "failed to find target thread";
- }
+ _LOG(&log, logtype::HEADER,
+ "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
+ dump_header_info(&log);
+ _LOG(&log, logtype::HEADER, "Timestamp: %s\n", get_timestamp().c_str());
- dump_thread(&log, unwinder, it->second, process_info, true);
-
- if (want_logs) {
- dump_logs(&log, it->second.pid, 50);
- }
-
- for (auto& [tid, thread_info] : threads) {
- if (tid == target_thread) {
- continue;
+ auto it = threads.find(target_thread);
+ if (it == threads.end()) {
+ LOG(FATAL) << "failed to find target thread";
}
- dump_thread(&log, unwinder, thread_info, process_info, false);
- }
+ dump_thread(&log, unwinder, it->second, process_info, true);
- if (open_files) {
- _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
- dump_open_files_list(&log, *open_files, " ");
- }
+ if (want_logs) {
+ dump_logs(&log, it->second.pid, 50);
+ }
- if (want_logs) {
- dump_logs(&log, it->second.pid, 0);
+ for (auto& [tid, thread_info] : threads) {
+ if (tid == target_thread) {
+ continue;
+ }
+
+ dump_thread(&log, unwinder, thread_info, process_info, false);
+ }
+
+ if (open_files) {
+ _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
+ dump_open_files_list(&log, *open_files, " ");
+ }
+
+ if (want_logs) {
+ dump_logs(&log, it->second.pid, 0);
+ }
}
}
diff --git a/debuggerd/libdebuggerd/tombstone_proto.cpp b/debuggerd/libdebuggerd/tombstone_proto.cpp
new file mode 100644
index 0000000..801b112
--- /dev/null
+++ b/debuggerd/libdebuggerd/tombstone_proto.cpp
@@ -0,0 +1,478 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include "libdebuggerd/tombstone.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <time.h>
+
+#include <memory>
+#include <string>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+
+#include <android/log.h>
+#include <log/log.h>
+#include <log/log_read.h>
+#include <log/logprint.h>
+#include <private/android_filesystem_config.h>
+
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
+#include <unwindstack/Unwinder.h>
+
+#include "libdebuggerd/open_files_list.h"
+#include "libdebuggerd/utility.h"
+#include "util.h"
+
+#include "tombstone.pb.h"
+
+using android::base::StringPrintf;
+
+// Use the demangler from libc++.
+extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
+
+static Architecture get_arch() {
+#if defined(__arm__)
+ return Architecture::ARM32;
+#elif defined(__aarch64__)
+ return Architecture::ARM64;
+#elif defined(__i386__)
+ return Architecture::X86;
+#elif defined(__x86_64__)
+ return Architecture::X86_64;
+#else
+#error Unknown architecture!
+#endif
+}
+
+static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
+ unwindstack::Maps* maps) {
+ static constexpr uint64_t kMaxDifferenceBytes = 256;
+ uint64_t difference;
+ if (sp >= fault_addr) {
+ difference = sp - fault_addr;
+ } else {
+ difference = fault_addr - sp;
+ }
+ if (difference <= kMaxDifferenceBytes) {
+ // The faulting address is close to the current sp, check if the sp
+ // indicates a stack overflow.
+ // On arm, the sp does not get updated when the instruction faults.
+ // In this case, the sp will still be in a valid map, which is the
+ // last case below.
+ // On aarch64, the sp does get updated when the instruction faults.
+ // In this case, the sp will be in either an invalid map if triggered
+ // on the main thread, or in a guard map if in another thread, which
+ // will be the first case or second case from below.
+ unwindstack::MapInfo* map_info = maps->Find(sp);
+ if (map_info == nullptr) {
+ return "stack pointer is in a non-existent map; likely due to stack overflow.";
+ } else if ((map_info->flags & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
+ return "stack pointer is not in a rw map; likely due to stack overflow.";
+ } else if ((sp - map_info->start) <= kMaxDifferenceBytes) {
+ return "stack pointer is close to top of stack; likely stack overflow.";
+ }
+ }
+ return {};
+}
+
+static void dump_probable_cause(Tombstone* tombstone, const siginfo_t* si, unwindstack::Maps* maps,
+ unwindstack::Regs* regs) {
+ std::optional<std::string> cause;
+ if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
+ if (si->si_addr < reinterpret_cast<void*>(4096)) {
+ cause = "null pointer dereference";
+ } else if (si->si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
+ cause = "call to kuser_helper_version";
+ } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
+ cause = "call to kuser_get_tls";
+ } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
+ cause = "call to kuser_cmpxchg";
+ } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
+ cause = "call to kuser_memory_barrier";
+ } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
+ cause = "call to kuser_cmpxchg64";
+ } else {
+ cause = get_stack_overflow_cause(reinterpret_cast<uint64_t>(si->si_addr), regs->sp(), maps);
+ }
+ } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
+ uint64_t fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
+ unwindstack::MapInfo* map_info = maps->Find(fault_addr);
+ if (map_info != nullptr && map_info->flags == PROT_EXEC) {
+ cause = "execute-only (no-read) memory access error; likely due to data in .text.";
+ } else {
+ cause = get_stack_overflow_cause(fault_addr, regs->sp(), maps);
+ }
+ } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
+ cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
+ si->si_syscall);
+ }
+
+ if (cause) {
+ tombstone->mutable_cause()->set_human_readable(*cause);
+ }
+}
+
+static void dump_abort_message(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+ const ProcessInfo& process_info) {
+ std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
+ uintptr_t address = process_info.abort_msg_address;
+ if (address == 0) {
+ return;
+ }
+
+ size_t length;
+ if (!process_memory->ReadFully(address, &length, sizeof(length))) {
+ PLOG(ERROR) << "Failed to read abort message header";
+ return;
+ }
+
+ // The length field includes the length of the length field itself.
+ if (length < sizeof(size_t)) {
+ LOG(ERROR) << "Abort message header malformed: claimed length = " << length;
+ return;
+ }
+
+ length -= sizeof(size_t);
+
+ // The abort message should be null terminated already, but reserve a spot for NUL just in case.
+ std::string msg;
+ msg.resize(length);
+
+ if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
+ PLOG(ERROR) << "Failed to read abort message header";
+ return;
+ }
+
+ tombstone->set_abort_message(msg);
+}
+
+static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
+ if (open_files) {
+ for (auto& [fd, entry] : *open_files) {
+ FD f;
+
+ f.set_fd(fd);
+
+ const std::optional<std::string>& path = entry.path;
+ if (path) {
+ f.set_path(*path);
+ }
+
+ const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
+ if (fdsan_owner) {
+ const char* type = android_fdsan_get_tag_type(*fdsan_owner);
+ uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
+ f.set_owner(type);
+ f.set_tag(value);
+ }
+
+ *tombstone->add_open_fds() = f;
+ }
+ }
+}
+
+static void dump_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+ const ThreadInfo& thread_info, bool memory_dump = false) {
+ Thread thread;
+
+ thread.set_id(thread_info.tid);
+ thread.set_name(thread_info.thread_name);
+
+ unwindstack::Maps* maps = unwinder->GetMaps();
+ unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
+
+ thread_info.registers->IterateRegisters(
+ [&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
+ Register r;
+ r.set_name(name);
+ r.set_u64(value);
+ *thread.add_registers() = r;
+
+ if (memory_dump) {
+ MemoryDump dump;
+
+ char buf[256];
+ size_t start_offset = 0;
+ ssize_t bytes = dump_memory(buf, sizeof(buf), &start_offset, &value, memory);
+ if (bytes == -1) {
+ return;
+ }
+
+ dump.set_register_name(name);
+
+ unwindstack::MapInfo* map_info = maps->Find(value);
+ if (map_info) {
+ dump.set_mapping_name(map_info->name);
+ }
+
+ dump.set_begin_address(value);
+
+ CHECK(start_offset + bytes <= sizeof(buf));
+ dump.set_memory(buf, start_offset + bytes);
+
+ *thread.add_memory_dump() = std::move(dump);
+ }
+ });
+
+ std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
+ unwinder->SetRegs(regs_copy.get());
+ unwinder->Unwind();
+ if (unwinder->NumFrames() == 0) {
+ LOG(ERROR) << "Failed to unwind";
+ if (unwinder->LastErrorCode() != unwindstack::ERROR_NONE) {
+ LOG(ERROR) << " Error code: " << unwinder->LastErrorCodeString();
+ LOG(ERROR) << " Error address: " << StringPrintf("0x%" PRIx64, unwinder->LastErrorAddress());
+ }
+ } else {
+ unwinder->SetDisplayBuildID(true);
+ for (const auto& frame : unwinder->frames()) {
+ BacktraceFrame* f = thread.add_current_backtrace();
+ f->set_rel_pc(frame.rel_pc);
+ f->set_pc(frame.pc);
+ f->set_sp(frame.sp);
+
+ if (!frame.function_name.empty()) {
+ // TODO: Should this happen here, or on the display side?
+ char* demangled_name =
+ __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
+ if (demangled_name) {
+ f->set_function_name(demangled_name);
+ free(demangled_name);
+ } else {
+ f->set_function_name(frame.function_name);
+ }
+ }
+
+ f->set_function_offset(frame.function_offset);
+
+ if (frame.map_start == frame.map_end) {
+ // No valid map associated with this frame.
+ f->set_file_name("<unknown>");
+ } else if (!frame.map_name.empty()) {
+ f->set_file_name(frame.map_name);
+ } else {
+ f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_start));
+ }
+
+ f->set_file_map_offset(frame.map_elf_start_offset);
+
+ unwindstack::MapInfo* map_info = maps->Find(frame.map_start);
+ if (map_info) {
+ f->set_build_id(map_info->GetPrintableBuildID());
+ }
+ }
+ }
+
+ auto& threads = *tombstone->mutable_threads();
+ threads[thread_info.tid] = thread;
+}
+
+static void dump_main_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+ const ThreadInfo& thread_info) {
+ dump_thread(tombstone, unwinder, thread_info, true);
+}
+
+static void dump_mappings(Tombstone* tombstone, unwindstack::Unwinder* unwinder) {
+ unwindstack::Maps* maps = unwinder->GetMaps();
+ std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
+
+ for (const auto& map_info : *maps) {
+ auto* map = tombstone->add_memory_mappings();
+ map->set_begin_address(map_info->start);
+ map->set_end_address(map_info->end);
+ map->set_offset(map_info->offset);
+
+ if (map_info->flags & PROT_READ) {
+ map->set_read(true);
+ }
+ if (map_info->flags & PROT_WRITE) {
+ map->set_write(true);
+ }
+ if (map_info->flags & PROT_EXEC) {
+ map->set_execute(true);
+ }
+
+ map->set_mapping_name(map_info->name);
+
+ std::string build_id = map_info->GetPrintableBuildID();
+ if (!build_id.empty()) {
+ map->set_build_id(build_id);
+ }
+
+ map->set_load_bias(map_info->GetLoadBias(process_memory));
+ }
+}
+
+static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
+ logger_list* logger_list =
+ android_logger_list_open(android_name_to_log_id(logger), ANDROID_LOG_NONBLOCK, 0, pid);
+
+ LogBuffer buffer;
+
+ while (true) {
+ log_msg log_entry;
+ ssize_t actual = android_logger_list_read(logger_list, &log_entry);
+
+ if (actual < 0) {
+ if (actual == -EINTR) {
+ // interrupted by signal, retry
+ continue;
+ }
+ if (actual == -EAGAIN) {
+ // non-blocking EOF; we're done
+ break;
+ } else {
+ ALOGE("Error while reading log: %s\n", strerror(-actual));
+ break;
+ }
+ } else if (actual == 0) {
+ ALOGE("Got zero bytes while reading log: %s\n", strerror(errno));
+ break;
+ }
+
+ char timestamp_secs[32];
+ time_t sec = static_cast<time_t>(log_entry.entry.sec);
+ tm tm;
+ localtime_r(&sec, &tm);
+ strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
+ std::string timestamp =
+ StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
+
+ // Msg format is: <priority:1><tag:N>\0<message:N>\0
+ char* msg = log_entry.msg();
+ if (msg == nullptr) {
+ continue;
+ }
+
+ unsigned char prio = msg[0];
+ char* tag = msg + 1;
+ msg = tag + strlen(tag) + 1;
+
+ // consume any trailing newlines
+ char* nl = msg + strlen(msg) - 1;
+ while (nl >= msg && *nl == '\n') {
+ *nl-- = '\0';
+ }
+
+ // Look for line breaks ('\n') and display each text line
+ // on a separate line, prefixed with the header, like logcat does.
+ do {
+ nl = strchr(msg, '\n');
+ if (nl != nullptr) {
+ *nl = '\0';
+ ++nl;
+ }
+
+ LogMessage* log_msg = buffer.add_logs();
+ log_msg->set_timestamp(timestamp);
+ log_msg->set_pid(log_entry.entry.pid);
+ log_msg->set_tid(log_entry.entry.tid);
+ log_msg->set_priority(prio);
+ log_msg->set_tag(tag);
+ log_msg->set_message(msg);
+ } while ((msg = nl));
+ }
+ android_logger_list_free(logger_list);
+
+ if (!buffer.logs().empty()) {
+ buffer.set_name(logger);
+ *tombstone->add_log_buffers() = std::move(buffer);
+ }
+}
+
+static void dump_logcat(Tombstone* tombstone, pid_t pid) {
+ dump_log_file(tombstone, "system", pid);
+ dump_log_file(tombstone, "main", pid);
+}
+
+void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+ const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
+ const ProcessInfo& process_info, const OpenFilesList* open_files) {
+ Tombstone result;
+
+ result.set_arch(get_arch());
+ result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
+ result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
+ result.set_timestamp(get_timestamp());
+
+ const ThreadInfo& main_thread = threads.at(target_thread);
+ result.set_pid(main_thread.pid);
+ result.set_tid(main_thread.tid);
+ result.set_uid(main_thread.uid);
+ result.set_selinux_label(main_thread.selinux_label);
+
+ result.set_process_name(main_thread.process_name);
+ CHECK(main_thread.siginfo != nullptr);
+
+ Signal sig;
+ sig.set_number(main_thread.signo);
+ sig.set_name(get_signame(main_thread.siginfo));
+ sig.set_code(main_thread.siginfo->si_code);
+ sig.set_code_name(get_sigcode(main_thread.siginfo));
+
+ if (signal_has_sender(main_thread.siginfo, main_thread.pid)) {
+ sig.set_has_sender(true);
+ sig.set_sender_uid(main_thread.siginfo->si_uid);
+ sig.set_sender_pid(main_thread.siginfo->si_pid);
+ }
+
+ if (process_info.has_fault_address) {
+ sig.set_has_fault_address(true);
+ sig.set_fault_address(process_info.untagged_fault_address);
+ }
+
+ *result.mutable_signal_info() = sig;
+
+ dump_abort_message(&result, unwinder, process_info);
+
+ dump_main_thread(&result, unwinder, main_thread);
+
+ for (const auto& [tid, thread_info] : threads) {
+ if (tid != target_thread) {
+ dump_thread(&result, unwinder, thread_info);
+ }
+ }
+
+ dump_probable_cause(&result, main_thread.siginfo, unwinder->GetMaps(),
+ main_thread.registers.get());
+
+ dump_mappings(&result, unwinder);
+
+ // Only dump logs on debuggable devices.
+ if (android::base::GetBoolProperty("ro.debuggable", false)) {
+ dump_logcat(&result, main_thread.pid);
+ }
+
+ dump_open_fds(&result, open_files);
+
+ *tombstone = std::move(result);
+}
diff --git a/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp b/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
new file mode 100644
index 0000000..5ba0ad6
--- /dev/null
+++ b/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
@@ -0,0 +1,361 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <libdebuggerd/tombstone.h>
+
+#include <inttypes.h>
+
+#include <functional>
+#include <set>
+#include <string>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+
+#include "tombstone.pb.h"
+
+using android::base::StringAppendF;
+using android::base::StringPrintf;
+
+#define CB(log, ...) callback(StringPrintf(__VA_ARGS__), log)
+#define CBL(...) CB(true, __VA_ARGS__)
+#define CBS(...) CB(false, __VA_ARGS__)
+using CallbackType = std::function<void(const std::string& line, bool should_log)>;
+
+static const char* abi_string(const Tombstone& tombstone) {
+ switch (tombstone.arch()) {
+ case Architecture::ARM32:
+ return "arm";
+ case Architecture::ARM64:
+ return "arm64";
+ case Architecture::X86:
+ return "x86";
+ case Architecture::X86_64:
+ return "x86_64";
+ default:
+ return "<unknown>";
+ }
+}
+
+static int pointer_width(const Tombstone& tombstone) {
+ switch (tombstone.arch()) {
+ case Architecture::ARM32:
+ return 4;
+ case Architecture::ARM64:
+ return 8;
+ case Architecture::X86:
+ return 4;
+ case Architecture::X86_64:
+ return 8;
+ default:
+ return 8;
+ }
+}
+
+static void print_thread_header(CallbackType callback, const Tombstone& tombstone,
+ const Thread& thread, bool should_log) {
+ CB(should_log, "pid: %d, tid: %d, name: %s >>> %s <<<", tombstone.pid(), thread.id(),
+ thread.name().c_str(), tombstone.process_name().c_str());
+ CB(should_log, "uid: %d", tombstone.uid());
+}
+
+static void print_register_row(CallbackType callback, int word_size,
+ std::vector<std::pair<std::string, uint64_t>> row, bool should_log) {
+ std::string output = " ";
+ for (const auto& [name, value] : row) {
+ output += android::base::StringPrintf(" %-3s %0*" PRIx64, name.c_str(), 2 * word_size,
+ static_cast<uint64_t>(value));
+ }
+ callback(output, should_log);
+}
+
+static void print_thread_registers(CallbackType callback, const Tombstone& tombstone,
+ const Thread& thread, bool should_log) {
+ static constexpr size_t column_count = 4;
+ std::vector<std::pair<std::string, uint64_t>> current_row;
+ std::vector<std::pair<std::string, uint64_t>> special_row;
+ std::unordered_set<std::string> special_registers;
+
+ int word_size = pointer_width(tombstone);
+
+ switch (tombstone.arch()) {
+ case Architecture::ARM32:
+ special_registers = {"ip", "lr", "sp", "pc", "pst"};
+ break;
+
+ case Architecture::ARM64:
+ special_registers = {"ip", "lr", "sp", "pc", "pst"};
+ break;
+
+ case Architecture::X86:
+ special_registers = {"ebp", "esp", "eip"};
+ break;
+
+ case Architecture::X86_64:
+ special_registers = {"rbp", "rsp", "rip"};
+ break;
+
+ default:
+ LOG(FATAL) << "unknown architecture";
+ }
+
+ for (const auto& reg : thread.registers()) {
+ auto row = ¤t_row;
+ if (special_registers.count(reg.name()) == 1) {
+ row = &special_row;
+ }
+
+ row->emplace_back(reg.name(), reg.u64());
+ if (current_row.size() == column_count) {
+ print_register_row(callback, word_size, current_row, should_log);
+ current_row.clear();
+ }
+ }
+
+ if (!current_row.empty()) {
+ print_register_row(callback, word_size, current_row, should_log);
+ }
+
+ print_register_row(callback, word_size, special_row, should_log);
+}
+
+static void print_thread_backtrace(CallbackType callback, const Tombstone& tombstone,
+ const Thread& thread, bool should_log) {
+ CBS("");
+ CB(should_log, "backtrace:");
+ int index = 0;
+ for (const auto& frame : thread.current_backtrace()) {
+ std::string function;
+
+ if (!frame.function_name().empty()) {
+ function =
+ StringPrintf(" (%s+%" PRId64 ")", frame.function_name().c_str(), frame.function_offset());
+ }
+
+ std::string build_id;
+ if (!frame.build_id().empty()) {
+ build_id = StringPrintf(" (BuildId: %s)", frame.build_id().c_str());
+ }
+
+ CB(should_log, " #%02d pc %0*" PRIx64 " %s%s%s", index++, pointer_width(tombstone) * 2,
+ frame.rel_pc(), frame.file_name().c_str(), function.c_str(), build_id.c_str());
+ }
+}
+
+static void print_thread_memory_dump(CallbackType callback, const Tombstone& tombstone,
+ const Thread& thread) {
+ static constexpr size_t bytes_per_line = 16;
+ int word_size = pointer_width(tombstone);
+ for (const auto& mem : thread.memory_dump()) {
+ CBS("");
+ CBS("memory near %s (%s):", mem.register_name().c_str(), mem.mapping_name().c_str());
+ uint64_t addr = mem.begin_address();
+ for (size_t offset = 0; offset < mem.memory().size(); offset += bytes_per_line) {
+ std::string line = StringPrintf(" %0*" PRIx64, word_size * 2, addr + offset);
+
+ size_t bytes = std::min(bytes_per_line, mem.memory().size() - offset);
+ for (size_t i = 0; i < bytes; i += word_size) {
+ uint64_t word = 0;
+
+ // Assumes little-endian, but what doesn't?
+ memcpy(&word, mem.memory().data() + offset + i, word_size);
+
+ StringAppendF(&line, " %0*" PRIx64, word_size * 2, word);
+ }
+
+ char ascii[bytes_per_line + 1];
+
+ memset(ascii, '.', sizeof(ascii));
+ ascii[bytes_per_line] = '\0';
+
+ for (size_t i = 0; i < bytes; ++i) {
+ uint8_t byte = mem.memory()[offset + i];
+ if (byte >= 0x20 && byte < 0x7f) {
+ ascii[i] = byte;
+ }
+ }
+
+ CBS("%s %s", line.c_str(), ascii);
+ }
+ }
+}
+
+static void print_thread(CallbackType callback, const Tombstone& tombstone, const Thread& thread) {
+ print_thread_header(callback, tombstone, thread, false);
+ print_thread_registers(callback, tombstone, thread, false);
+ print_thread_backtrace(callback, tombstone, thread, false);
+ print_thread_memory_dump(callback, tombstone, thread);
+}
+
+static void print_main_thread(CallbackType callback, const Tombstone& tombstone,
+ const Thread& thread) {
+ print_thread_header(callback, tombstone, thread, true);
+
+ const Signal& signal_info = tombstone.signal_info();
+ std::string sender_desc;
+
+ if (signal_info.has_sender()) {
+ sender_desc =
+ StringPrintf(" from pid %d, uid %d", signal_info.sender_pid(), signal_info.sender_uid());
+ }
+
+ if (!tombstone.has_signal_info()) {
+ LOG(ERROR) << "signal info missing in tombstone";
+ CBL("signal information missing");
+ } else {
+ std::string fault_addr_desc;
+ if (signal_info.has_fault_address()) {
+ fault_addr_desc = StringPrintf("0x%" PRIx64, signal_info.fault_address());
+ } else {
+ fault_addr_desc = "--------";
+ }
+
+ CBL("signal %d (%s), code %d (%s%s), fault addr %s", signal_info.number(),
+ signal_info.name().c_str(), signal_info.code(), signal_info.code_name().c_str(),
+ sender_desc.c_str(), fault_addr_desc.c_str());
+ }
+
+ if (tombstone.has_cause()) {
+ const Cause& cause = tombstone.cause();
+ CBL("Cause: %s", cause.human_readable().c_str());
+ }
+
+ if (!tombstone.abort_message().empty()) {
+ CBL("Abort message: '%s'", tombstone.abort_message().c_str());
+ }
+
+ print_thread_registers(callback, tombstone, thread, true);
+ print_thread_backtrace(callback, tombstone, thread, true);
+ print_thread_memory_dump(callback, tombstone, thread);
+
+ CBS("");
+ CBS("memory map (%d %s):", tombstone.memory_mappings().size(),
+ tombstone.memory_mappings().size() == 1 ? "entry" : "entries");
+ int word_size = pointer_width(tombstone);
+ const auto format_pointer = [word_size](uint64_t ptr) -> std::string {
+ if (word_size == 8) {
+ uint64_t top = ptr >> 32;
+ uint64_t bottom = ptr & 0xFFFFFFFF;
+ return StringPrintf("%08" PRIx64 "'%08" PRIx64, top, bottom);
+ }
+
+ return StringPrintf("%0*" PRIx64, word_size * 2, ptr);
+ };
+
+ for (const auto& map : tombstone.memory_mappings()) {
+ std::string line = " ";
+ StringAppendF(&line, "%s-%s", format_pointer(map.begin_address()).c_str(),
+ format_pointer(map.end_address() - 1).c_str());
+ StringAppendF(&line, " %s%s%s", map.read() ? "r" : "-", map.write() ? "w" : "-",
+ map.execute() ? "x" : "-");
+ StringAppendF(&line, " %8" PRIx64 " %8" PRIx64, map.offset(),
+ map.end_address() - map.begin_address());
+
+ if (!map.mapping_name().empty()) {
+ StringAppendF(&line, " %s", map.mapping_name().c_str());
+
+ if (!map.build_id().empty()) {
+ StringAppendF(&line, " (BuildId: %s)", map.build_id().c_str());
+ }
+
+ if (map.load_bias() != 0) {
+ StringAppendF(&line, " (load bias 0x%" PRIx64 ")", map.load_bias());
+ }
+ }
+
+ CBS("%s", line.c_str());
+ }
+}
+
+void print_logs(CallbackType callback, const Tombstone& tombstone, int tail) {
+ for (const auto& buffer : tombstone.log_buffers()) {
+ if (tail) {
+ CBS("--------- tail end of log %s", buffer.name().c_str());
+ } else {
+ CBS("--------- log %s", buffer.name().c_str());
+ }
+
+ int begin = 0;
+ if (tail != 0) {
+ begin = std::max(0, buffer.logs().size() - tail);
+ }
+
+ for (int i = begin; i < buffer.logs().size(); ++i) {
+ const LogMessage& msg = buffer.logs(i);
+
+ static const char* kPrioChars = "!.VDIWEFS";
+ char priority = (msg.priority() < strlen(kPrioChars) ? kPrioChars[msg.priority()] : '?');
+ CBS("%s %5u %5u %c %-8s: %s", msg.timestamp().c_str(), msg.pid(), msg.tid(), priority,
+ msg.tag().c_str(), msg.message().c_str());
+ }
+ }
+}
+
+bool tombstone_proto_to_text(const Tombstone& tombstone, CallbackType callback) {
+ CBL("*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***");
+ CBL("Build fingerprint: '%s'", tombstone.build_fingerprint().c_str());
+ CBL("Revision: '%s'", tombstone.revision().c_str());
+ CBL("ABI: '%s'", abi_string(tombstone));
+ CBL("Timestamp: %s", tombstone.timestamp().c_str());
+
+ // Process header
+ const auto& threads = tombstone.threads();
+ auto main_thread_it = threads.find(tombstone.tid());
+ if (main_thread_it == threads.end()) {
+ LOG(ERROR) << "failed to find entry for main thread in tombstone";
+ return false;
+ }
+
+ const auto& main_thread = main_thread_it->second;
+
+ print_main_thread(callback, tombstone, main_thread);
+
+ print_logs(callback, tombstone, 50);
+
+ // protobuf's map is unordered, so sort the keys first.
+ std::set<int> thread_ids;
+ for (const auto& [tid, _] : threads) {
+ if (tid != tombstone.tid()) {
+ thread_ids.insert(tid);
+ }
+ }
+
+ for (const auto& tid : thread_ids) {
+ CBS("--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---");
+ print_thread(callback, tombstone, threads.find(tid)->second);
+ }
+
+ if (tombstone.open_fds().size() > 0) {
+ CBS("");
+ CBS("open files:");
+ for (const auto& fd : tombstone.open_fds()) {
+ std::optional<std::string> owner;
+ if (!fd.owner().empty()) {
+ owner = StringPrintf("owned by %s 0x%" PRIx64, fd.owner().c_str(), fd.tag());
+ }
+
+ CBS(" fd %d: %s (%s)", fd.fd(), fd.path().c_str(), owner ? owner->c_str() : "unowned");
+ }
+ }
+
+ print_logs(callback, tombstone, 0);
+
+ return true;
+}
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 7826efc..f406ad4 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -126,56 +126,56 @@
#define MEMORY_BYTES_TO_DUMP 256
#define MEMORY_BYTES_PER_LINE 16
-void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const std::string& label) {
+ssize_t dump_memory(void* out, size_t len, size_t* start_offset, uint64_t* addr,
+ unwindstack::Memory* memory) {
// Align the address to the number of bytes per line to avoid confusing memory tag output if
// memory is tagged and we start from a misaligned address. Start 32 bytes before the address.
- addr &= ~(MEMORY_BYTES_PER_LINE - 1);
- if (addr >= 4128) {
- addr -= 32;
+ *addr &= ~(MEMORY_BYTES_PER_LINE - 1);
+ if (*addr >= 4128) {
+ *addr -= 32;
}
// We don't want the address tag to appear in the addresses in the memory dump.
- addr = untag_address(addr);
+ *addr = untag_address(*addr);
// Don't bother if the address would overflow, taking tag bits into account. Note that
// untag_address truncates to 32 bits on 32-bit platforms as a side effect of returning a
// uintptr_t, so this also checks for 32-bit overflow.
- if (untag_address(addr + MEMORY_BYTES_TO_DUMP - 1) < addr) {
- return;
+ if (untag_address(*addr + MEMORY_BYTES_TO_DUMP - 1) < *addr) {
+ return -1;
}
- // Dump 256 bytes
- uintptr_t data[MEMORY_BYTES_TO_DUMP/sizeof(uintptr_t)];
- memset(data, 0, MEMORY_BYTES_TO_DUMP);
- size_t bytes = memory->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
+ memset(out, 0, len);
+
+ size_t bytes = memory->Read(*addr, reinterpret_cast<uint8_t*>(out), len);
if (bytes % sizeof(uintptr_t) != 0) {
// This should never happen, but just in case.
ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
bytes &= ~(sizeof(uintptr_t) - 1);
}
- uint64_t start = 0;
+ *start_offset = 0;
bool skip_2nd_read = false;
if (bytes == 0) {
// In this case, we might want to try another read at the beginning of
// the next page only if it's within the amount of memory we would have
// read.
size_t page_size = sysconf(_SC_PAGE_SIZE);
- start = ((addr + (page_size - 1)) & ~(page_size - 1)) - addr;
- if (start == 0 || start >= MEMORY_BYTES_TO_DUMP) {
+ *start_offset = ((*addr + (page_size - 1)) & ~(page_size - 1)) - *addr;
+ if (*start_offset == 0 || *start_offset >= len) {
skip_2nd_read = true;
}
}
- if (bytes < MEMORY_BYTES_TO_DUMP && !skip_2nd_read) {
+ if (bytes < len && !skip_2nd_read) {
// Try to do one more read. This could happen if a read crosses a map,
// but the maps do not have any break between them. Or it could happen
// if reading from an unreadable map, but the read would cross back
// into a readable map. Only requires one extra read because a map has
// to contain at least one page, and the total number of bytes to dump
// is smaller than a page.
- size_t bytes2 = memory->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
- sizeof(data) - bytes - start);
+ size_t bytes2 = memory->Read(*addr + *start_offset + bytes, static_cast<uint8_t*>(out) + bytes,
+ len - bytes - *start_offset);
bytes += bytes2;
if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
// This should never happen, but we'll try and continue any way.
@@ -185,9 +185,21 @@
}
// If we were unable to read anything, it probably means that the register doesn't contain a
- // valid pointer. In that case, skip the output for this register entirely rather than emitting 16
- // lines of dashes.
+ // valid pointer.
if (bytes == 0) {
+ return -1;
+ }
+
+ return bytes;
+}
+
+void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const std::string& label) {
+ // Dump 256 bytes
+ uintptr_t data[MEMORY_BYTES_TO_DUMP / sizeof(uintptr_t)];
+ size_t start_offset = 0;
+
+ ssize_t bytes = dump_memory(data, sizeof(data), &start_offset, &addr, memory);
+ if (bytes == -1) {
return;
}
@@ -201,7 +213,7 @@
// words are of course presented differently.
uintptr_t* data_ptr = data;
size_t current = 0;
- size_t total_bytes = start + bytes;
+ size_t total_bytes = start_offset + bytes;
for (size_t line = 0; line < MEMORY_BYTES_TO_DUMP / MEMORY_BYTES_PER_LINE; line++) {
uint64_t tagged_addr = addr;
long tag = memory->ReadTag(addr);
@@ -214,7 +226,7 @@
addr += MEMORY_BYTES_PER_LINE;
std::string ascii;
for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
- if (current >= start && current + sizeof(uintptr_t) <= total_bytes) {
+ if (current >= start_offset && current + sizeof(uintptr_t) <= total_bytes) {
android::base::StringAppendF(&logline, " %" PRIPTR, static_cast<uint64_t>(*data_ptr));
// Fill out the ascii string from the data.