blob: 99f636e645d54b7911d72263b0c036b19e9e8a96 [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"
21#include "libdebuggerd/scudo.h"
Josh Gao76e1e302021-01-26 15:53:11 -080022
23#include <errno.h>
24#include <fcntl.h>
25#include <inttypes.h>
26#include <signal.h>
27#include <stddef.h>
28#include <stdlib.h>
29#include <string.h>
30#include <sys/mman.h>
Elliott Hughes32d3cdd2021-09-21 12:20:53 -070031#include <sys/sysinfo.h>
Josh Gao76e1e302021-01-26 15:53:11 -080032#include <time.h>
33
34#include <memory>
Josh Gaodbb83de2021-03-01 23:13:13 -080035#include <optional>
Josh Gao76e1e302021-01-26 15:53:11 -080036#include <string>
37
Josh Gao618cea32021-01-26 17:45:43 -080038#include <async_safe/log.h>
39
Josh Gaodbb83de2021-03-01 23:13:13 -080040#include <android-base/file.h>
Josh Gao76e1e302021-01-26 15:53:11 -080041#include <android-base/properties.h>
42#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
44#include <android-base/unique_fd.h>
45
46#include <android/log.h>
Peter Collingbourne0ea08c22021-02-05 14:59:08 -080047#include <bionic/macros.h>
Josh Gao76e1e302021-01-26 15:53:11 -080048#include <log/log.h>
49#include <log/log_read.h>
50#include <log/logprint.h>
51#include <private/android_filesystem_config.h>
52
Josh Gaodbb83de2021-03-01 23:13:13 -080053#include <procinfo/process.h>
Josh Gao76e1e302021-01-26 15:53:11 -080054#include <unwindstack/Maps.h>
55#include <unwindstack/Memory.h>
56#include <unwindstack/Regs.h>
57#include <unwindstack/Unwinder.h>
58
59#include "libdebuggerd/open_files_list.h"
60#include "libdebuggerd/utility.h"
61#include "util.h"
62
63#include "tombstone.pb.h"
64
65using android::base::StringPrintf;
66
67// Use the demangler from libc++.
68extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
69
70static Architecture get_arch() {
71#if defined(__arm__)
72 return Architecture::ARM32;
73#elif defined(__aarch64__)
74 return Architecture::ARM64;
75#elif defined(__i386__)
76 return Architecture::X86;
77#elif defined(__x86_64__)
78 return Architecture::X86_64;
79#else
80#error Unknown architecture!
81#endif
82}
83
84static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
85 unwindstack::Maps* maps) {
86 static constexpr uint64_t kMaxDifferenceBytes = 256;
87 uint64_t difference;
88 if (sp >= fault_addr) {
89 difference = sp - fault_addr;
90 } else {
91 difference = fault_addr - sp;
92 }
93 if (difference <= kMaxDifferenceBytes) {
94 // The faulting address is close to the current sp, check if the sp
95 // indicates a stack overflow.
96 // On arm, the sp does not get updated when the instruction faults.
97 // In this case, the sp will still be in a valid map, which is the
98 // last case below.
99 // On aarch64, the sp does get updated when the instruction faults.
100 // In this case, the sp will be in either an invalid map if triggered
101 // on the main thread, or in a guard map if in another thread, which
102 // will be the first case or second case from below.
103 unwindstack::MapInfo* map_info = maps->Find(sp);
104 if (map_info == nullptr) {
105 return "stack pointer is in a non-existent map; likely due to stack overflow.";
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100106 } else if ((map_info->flags() & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
Josh Gao76e1e302021-01-26 15:53:11 -0800107 return "stack pointer is not in a rw map; likely due to stack overflow.";
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100108 } else if ((sp - map_info->start()) <= kMaxDifferenceBytes) {
Josh Gao76e1e302021-01-26 15:53:11 -0800109 return "stack pointer is close to top of stack; likely stack overflow.";
110 }
111 }
112 return {};
113}
114
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800115void set_human_readable_cause(Cause* cause, uint64_t fault_addr) {
116 if (!cause->has_memory_error() || !cause->memory_error().has_heap()) {
117 return;
118 }
119
120 const MemoryError& memory_error = cause->memory_error();
121 const HeapObject& heap_object = memory_error.heap();
122
123 const char *tool_str;
124 switch (memory_error.tool()) {
125 case MemoryError_Tool_GWP_ASAN:
126 tool_str = "GWP-ASan";
127 break;
128 case MemoryError_Tool_SCUDO:
129 tool_str = "MTE";
130 break;
131 default:
132 tool_str = "Unknown";
133 break;
134 }
135
136 const char *error_type_str;
137 switch (memory_error.type()) {
138 case MemoryError_Type_USE_AFTER_FREE:
139 error_type_str = "Use After Free";
140 break;
141 case MemoryError_Type_DOUBLE_FREE:
142 error_type_str = "Double Free";
143 break;
144 case MemoryError_Type_INVALID_FREE:
145 error_type_str = "Invalid (Wild) Free";
146 break;
147 case MemoryError_Type_BUFFER_OVERFLOW:
148 error_type_str = "Buffer Overflow";
149 break;
150 case MemoryError_Type_BUFFER_UNDERFLOW:
151 error_type_str = "Buffer Underflow";
152 break;
153 default:
154 cause->set_human_readable(
155 StringPrintf("[%s]: Unknown error occurred at 0x%" PRIx64 ".", tool_str, fault_addr));
156 return;
157 }
158
159 uint64_t diff;
160 const char* location_str;
161
162 if (fault_addr < heap_object.address()) {
163 // Buffer Underflow, 6 bytes left of a 41-byte allocation at 0xdeadbeef.
164 location_str = "left of";
165 diff = heap_object.address() - fault_addr;
166 } else if (fault_addr - heap_object.address() < heap_object.size()) {
167 // Use After Free, 40 bytes into a 41-byte allocation at 0xdeadbeef.
168 location_str = "into";
169 diff = fault_addr - heap_object.address();
170 } else {
171 // Buffer Overflow, 6 bytes right of a 41-byte allocation at 0xdeadbeef.
172 location_str = "right of";
173 diff = fault_addr - heap_object.address() - heap_object.size();
174 }
175
176 // Suffix of 'bytes', i.e. 4 bytes' vs. '1 byte'.
177 const char* byte_suffix = "s";
178 if (diff == 1) {
179 byte_suffix = "";
180 }
181
182 cause->set_human_readable(StringPrintf(
183 "[%s]: %s, %" PRIu64 " byte%s %s a %" PRIu64 "-byte allocation at 0x%" PRIx64, tool_str,
184 error_type_str, diff, byte_suffix, location_str, heap_object.size(), heap_object.address()));
185}
186
187static void dump_probable_cause(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
188 const ProcessInfo& process_info, const ThreadInfo& main_thread) {
189 ScudoCrashData scudo_crash_data(unwinder->GetProcessMemory().get(), process_info);
190 if (scudo_crash_data.CrashIsMine()) {
191 scudo_crash_data.AddCauseProtos(tombstone, unwinder);
192 return;
193 }
194
195 GwpAsanCrashData gwp_asan_crash_data(unwinder->GetProcessMemory().get(), process_info,
196 main_thread);
197 if (gwp_asan_crash_data.CrashIsMine()) {
198 gwp_asan_crash_data.AddCauseProtos(tombstone, unwinder);
199 return;
200 }
201
202 const siginfo *si = main_thread.siginfo;
203 auto fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
204 unwindstack::Maps* maps = unwinder->GetMaps();
205
Josh Gao76e1e302021-01-26 15:53:11 -0800206 std::optional<std::string> cause;
207 if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800208 if (fault_addr < 4096) {
Josh Gao76e1e302021-01-26 15:53:11 -0800209 cause = "null pointer dereference";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800210 } else if (fault_addr == 0xffff0ffc) {
Josh Gao76e1e302021-01-26 15:53:11 -0800211 cause = "call to kuser_helper_version";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800212 } else if (fault_addr == 0xffff0fe0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800213 cause = "call to kuser_get_tls";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800214 } else if (fault_addr == 0xffff0fc0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800215 cause = "call to kuser_cmpxchg";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800216 } else if (fault_addr == 0xffff0fa0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800217 cause = "call to kuser_memory_barrier";
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800218 } else if (fault_addr == 0xffff0f60) {
Josh Gao76e1e302021-01-26 15:53:11 -0800219 cause = "call to kuser_cmpxchg64";
220 } else {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800221 cause = get_stack_overflow_cause(fault_addr, main_thread.registers->sp(), maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800222 }
223 } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
Josh Gao76e1e302021-01-26 15:53:11 -0800224 unwindstack::MapInfo* map_info = maps->Find(fault_addr);
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100225 if (map_info != nullptr && map_info->flags() == PROT_EXEC) {
Josh Gao76e1e302021-01-26 15:53:11 -0800226 cause = "execute-only (no-read) memory access error; likely due to data in .text.";
227 } else {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800228 cause = get_stack_overflow_cause(fault_addr, main_thread.registers->sp(), maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800229 }
230 } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
231 cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
232 si->si_syscall);
233 }
234
235 if (cause) {
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800236 Cause *cause_proto = tombstone->add_causes();
237 cause_proto->set_human_readable(*cause);
Josh Gao76e1e302021-01-26 15:53:11 -0800238 }
239}
240
241static void dump_abort_message(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
242 const ProcessInfo& process_info) {
243 std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
244 uintptr_t address = process_info.abort_msg_address;
245 if (address == 0) {
246 return;
247 }
248
249 size_t length;
250 if (!process_memory->ReadFully(address, &length, sizeof(length))) {
Josh Gao618cea32021-01-26 17:45:43 -0800251 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
252 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800253 return;
254 }
255
256 // The length field includes the length of the length field itself.
257 if (length < sizeof(size_t)) {
Josh Gao618cea32021-01-26 17:45:43 -0800258 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
259 "abort message header malformed: claimed length = %zu", length);
Josh Gao76e1e302021-01-26 15:53:11 -0800260 return;
261 }
262
263 length -= sizeof(size_t);
264
265 // The abort message should be null terminated already, but reserve a spot for NUL just in case.
266 std::string msg;
267 msg.resize(length);
268
269 if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
Josh Gao618cea32021-01-26 17:45:43 -0800270 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
271 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800272 return;
273 }
274
Christopher Ferrise8891452021-08-17 17:34:53 -0700275 // Remove any trailing newlines.
276 size_t index = msg.size();
277 while (index > 0 && (msg[index - 1] == '\0' || msg[index - 1] == '\n')) {
278 --index;
279 }
280 msg.resize(index);
281
Josh Gao76e1e302021-01-26 15:53:11 -0800282 tombstone->set_abort_message(msg);
283}
284
285static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
286 if (open_files) {
287 for (auto& [fd, entry] : *open_files) {
288 FD f;
289
290 f.set_fd(fd);
291
292 const std::optional<std::string>& path = entry.path;
293 if (path) {
294 f.set_path(*path);
295 }
296
297 const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
298 if (fdsan_owner) {
299 const char* type = android_fdsan_get_tag_type(*fdsan_owner);
300 uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
301 f.set_owner(type);
302 f.set_tag(value);
303 }
304
305 *tombstone->add_open_fds() = f;
306 }
307 }
308}
309
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800310void fill_in_backtrace_frame(BacktraceFrame* f, const unwindstack::FrameData& frame,
311 unwindstack::Maps* maps) {
312 f->set_rel_pc(frame.rel_pc);
313 f->set_pc(frame.pc);
314 f->set_sp(frame.sp);
315
316 if (!frame.function_name.empty()) {
317 // TODO: Should this happen here, or on the display side?
318 char* demangled_name = __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
319 if (demangled_name) {
320 f->set_function_name(demangled_name);
321 free(demangled_name);
322 } else {
323 f->set_function_name(frame.function_name);
324 }
325 }
326
327 f->set_function_offset(frame.function_offset);
328
329 if (frame.map_start == frame.map_end) {
330 // No valid map associated with this frame.
331 f->set_file_name("<unknown>");
332 } else if (!frame.map_name.empty()) {
333 f->set_file_name(frame.map_name);
334 } else {
335 f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_start));
336 }
337
338 f->set_file_map_offset(frame.map_elf_start_offset);
339
340 unwindstack::MapInfo* map_info = maps->Find(frame.map_start);
341 if (map_info) {
342 f->set_build_id(map_info->GetPrintableBuildID());
343 }
344}
345
Josh Gao76e1e302021-01-26 15:53:11 -0800346static void dump_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
347 const ThreadInfo& thread_info, bool memory_dump = false) {
348 Thread thread;
349
350 thread.set_id(thread_info.tid);
351 thread.set_name(thread_info.thread_name);
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800352 thread.set_tagged_addr_ctrl(thread_info.tagged_addr_ctrl);
Josh Gao76e1e302021-01-26 15:53:11 -0800353
354 unwindstack::Maps* maps = unwinder->GetMaps();
355 unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
356
357 thread_info.registers->IterateRegisters(
358 [&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
359 Register r;
360 r.set_name(name);
361 r.set_u64(value);
362 *thread.add_registers() = r;
363
364 if (memory_dump) {
365 MemoryDump dump;
366
Josh Gao76e1e302021-01-26 15:53:11 -0800367 dump.set_register_name(name);
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800368 unwindstack::MapInfo* map_info = maps->Find(untag_address(value));
Josh Gao76e1e302021-01-26 15:53:11 -0800369 if (map_info) {
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100370 dump.set_mapping_name(map_info->name());
Josh Gao76e1e302021-01-26 15:53:11 -0800371 }
372
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700373 constexpr size_t kNumBytesAroundRegister = 256;
374 constexpr size_t kNumTagsAroundRegister = kNumBytesAroundRegister / kTagGranuleSize;
375 char buf[kNumBytesAroundRegister];
376 uint8_t tags[kNumTagsAroundRegister];
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800377 size_t start_offset = 0;
378 ssize_t bytes = dump_memory(buf, sizeof(buf), tags, sizeof(tags), &value, memory);
379 if (bytes == -1) {
380 return;
381 }
Josh Gao76e1e302021-01-26 15:53:11 -0800382 dump.set_begin_address(value);
383
Josh Gao618cea32021-01-26 17:45:43 -0800384 if (start_offset + bytes > sizeof(buf)) {
385 async_safe_fatal("dump_memory overflowed? start offset = %zu, bytes read = %zd",
386 start_offset, bytes);
387 }
388
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800389 dump.set_memory(buf, bytes);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700390
391 bool has_tags = false;
392#if defined(__aarch64__)
393 for (size_t i = 0; i < kNumTagsAroundRegister; ++i) {
394 if (tags[i] != 0) {
395 has_tags = true;
396 }
397 }
398#endif // defined(__aarch64__)
399
400 if (has_tags) {
401 dump.mutable_arm_mte_metadata()->set_memory_tags(tags, kNumTagsAroundRegister);
402 }
Josh Gao76e1e302021-01-26 15:53:11 -0800403
404 *thread.add_memory_dump() = std::move(dump);
405 }
406 });
407
408 std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
409 unwinder->SetRegs(regs_copy.get());
410 unwinder->Unwind();
411 if (unwinder->NumFrames() == 0) {
Josh Gao618cea32021-01-26 17:45:43 -0800412 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to unwind");
Josh Gao76e1e302021-01-26 15:53:11 -0800413 if (unwinder->LastErrorCode() != unwindstack::ERROR_NONE) {
Josh Gao618cea32021-01-26 17:45:43 -0800414 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, " error code: %s",
415 unwinder->LastErrorCodeString());
416 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, " error address: 0x%" PRIx64,
417 unwinder->LastErrorAddress());
Josh Gao76e1e302021-01-26 15:53:11 -0800418 }
419 } else {
Christopher Ferrisfe751c52021-04-16 09:40:40 -0700420 if (unwinder->elf_from_memory_not_file()) {
421 auto backtrace_note = thread.mutable_backtrace_note();
422 *backtrace_note->Add() =
423 "Function names and BuildId information is missing for some frames due";
424 *backtrace_note->Add() =
425 "to unreadable libraries. For unwinds of apps, only shared libraries";
426 *backtrace_note->Add() = "found under the lib/ directory are readable.";
427 *backtrace_note->Add() = "On this device, run setenforce 0 to make the libraries readable.";
428 }
Josh Gao76e1e302021-01-26 15:53:11 -0800429 unwinder->SetDisplayBuildID(true);
430 for (const auto& frame : unwinder->frames()) {
431 BacktraceFrame* f = thread.add_current_backtrace();
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800432 fill_in_backtrace_frame(f, frame, maps);
Josh Gao76e1e302021-01-26 15:53:11 -0800433 }
434 }
435
436 auto& threads = *tombstone->mutable_threads();
437 threads[thread_info.tid] = thread;
438}
439
440static void dump_main_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
441 const ThreadInfo& thread_info) {
442 dump_thread(tombstone, unwinder, thread_info, true);
443}
444
445static void dump_mappings(Tombstone* tombstone, unwindstack::Unwinder* unwinder) {
446 unwindstack::Maps* maps = unwinder->GetMaps();
447 std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
448
449 for (const auto& map_info : *maps) {
450 auto* map = tombstone->add_memory_mappings();
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100451 map->set_begin_address(map_info->start());
452 map->set_end_address(map_info->end());
453 map->set_offset(map_info->offset());
Josh Gao76e1e302021-01-26 15:53:11 -0800454
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100455 if (map_info->flags() & PROT_READ) {
Josh Gao76e1e302021-01-26 15:53:11 -0800456 map->set_read(true);
457 }
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100458 if (map_info->flags() & PROT_WRITE) {
Josh Gao76e1e302021-01-26 15:53:11 -0800459 map->set_write(true);
460 }
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100461 if (map_info->flags() & PROT_EXEC) {
Josh Gao76e1e302021-01-26 15:53:11 -0800462 map->set_execute(true);
463 }
464
David Srbeckyd8ab48b2021-05-13 00:03:26 +0100465 map->set_mapping_name(map_info->name());
Josh Gao76e1e302021-01-26 15:53:11 -0800466
467 std::string build_id = map_info->GetPrintableBuildID();
468 if (!build_id.empty()) {
469 map->set_build_id(build_id);
470 }
471
472 map->set_load_bias(map_info->GetLoadBias(process_memory));
473 }
474}
475
476static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
477 logger_list* logger_list =
478 android_logger_list_open(android_name_to_log_id(logger), ANDROID_LOG_NONBLOCK, 0, pid);
479
480 LogBuffer buffer;
481
482 while (true) {
483 log_msg log_entry;
484 ssize_t actual = android_logger_list_read(logger_list, &log_entry);
485
486 if (actual < 0) {
487 if (actual == -EINTR) {
488 // interrupted by signal, retry
489 continue;
490 }
491 if (actual == -EAGAIN) {
492 // non-blocking EOF; we're done
493 break;
494 } else {
Josh Gao76e1e302021-01-26 15:53:11 -0800495 break;
496 }
497 } else if (actual == 0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800498 break;
499 }
500
501 char timestamp_secs[32];
502 time_t sec = static_cast<time_t>(log_entry.entry.sec);
503 tm tm;
504 localtime_r(&sec, &tm);
505 strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
506 std::string timestamp =
507 StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
508
509 // Msg format is: <priority:1><tag:N>\0<message:N>\0
510 char* msg = log_entry.msg();
511 if (msg == nullptr) {
512 continue;
513 }
514
515 unsigned char prio = msg[0];
516 char* tag = msg + 1;
517 msg = tag + strlen(tag) + 1;
518
519 // consume any trailing newlines
520 char* nl = msg + strlen(msg) - 1;
521 while (nl >= msg && *nl == '\n') {
522 *nl-- = '\0';
523 }
524
525 // Look for line breaks ('\n') and display each text line
526 // on a separate line, prefixed with the header, like logcat does.
527 do {
528 nl = strchr(msg, '\n');
529 if (nl != nullptr) {
530 *nl = '\0';
531 ++nl;
532 }
533
534 LogMessage* log_msg = buffer.add_logs();
535 log_msg->set_timestamp(timestamp);
536 log_msg->set_pid(log_entry.entry.pid);
537 log_msg->set_tid(log_entry.entry.tid);
538 log_msg->set_priority(prio);
539 log_msg->set_tag(tag);
540 log_msg->set_message(msg);
541 } while ((msg = nl));
542 }
543 android_logger_list_free(logger_list);
544
545 if (!buffer.logs().empty()) {
546 buffer.set_name(logger);
547 *tombstone->add_log_buffers() = std::move(buffer);
548 }
549}
550
551static void dump_logcat(Tombstone* tombstone, pid_t pid) {
552 dump_log_file(tombstone, "system", pid);
553 dump_log_file(tombstone, "main", pid);
554}
555
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700556static void dump_tags_around_fault_addr(Signal* signal, const Tombstone& tombstone,
557 unwindstack::Unwinder* unwinder, uintptr_t fault_addr) {
558 if (tombstone.arch() != Architecture::ARM64) return;
559
560 fault_addr = untag_address(fault_addr);
561 constexpr size_t kNumGranules = kNumTagRows * kNumTagColumns;
562 constexpr size_t kBytesToRead = kNumGranules * kTagGranuleSize;
563
564 // If the low part of the tag dump would underflow to the high address space, it's probably not
565 // a valid address for us to dump tags from.
566 if (fault_addr < kBytesToRead / 2) return;
567
568 unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
569
570 constexpr uintptr_t kRowStartMask = ~(kNumTagColumns * kTagGranuleSize - 1);
571 size_t start_address = (fault_addr & kRowStartMask) - kBytesToRead / 2;
572 MemoryDump tag_dump;
573 size_t granules_to_read = kNumGranules;
574
575 // Attempt to read the first tag. If reading fails, this likely indicates the
576 // lowest touched page is inaccessible or not marked with PROT_MTE.
577 // Fast-forward over pages until one has tags, or we exhaust the search range.
578 while (memory->ReadTag(start_address) < 0) {
579 size_t page_size = sysconf(_SC_PAGE_SIZE);
580 size_t bytes_to_next_page = page_size - (start_address % page_size);
581 if (bytes_to_next_page >= granules_to_read * kTagGranuleSize) return;
582 start_address += bytes_to_next_page;
583 granules_to_read -= bytes_to_next_page / kTagGranuleSize;
584 }
585 tag_dump.set_begin_address(start_address);
586
587 std::string* mte_tags = tag_dump.mutable_arm_mte_metadata()->mutable_memory_tags();
588
589 for (size_t i = 0; i < granules_to_read; ++i) {
590 long tag = memory->ReadTag(start_address + i * kTagGranuleSize);
591 if (tag < 0) break;
592 mte_tags->push_back(static_cast<uint8_t>(tag));
593 }
594
595 if (!mte_tags->empty()) {
596 *signal->mutable_fault_adjacent_metadata() = tag_dump;
597 }
598}
599
Josh Gao76e1e302021-01-26 15:53:11 -0800600void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
601 const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
602 const ProcessInfo& process_info, const OpenFilesList* open_files) {
603 Tombstone result;
604
605 result.set_arch(get_arch());
606 result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
607 result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
608 result.set_timestamp(get_timestamp());
609
610 const ThreadInfo& main_thread = threads.at(target_thread);
611 result.set_pid(main_thread.pid);
612 result.set_tid(main_thread.tid);
613 result.set_uid(main_thread.uid);
614 result.set_selinux_label(main_thread.selinux_label);
615
Elliott Hughes32d3cdd2021-09-21 12:20:53 -0700616 struct sysinfo si;
617 sysinfo(&si);
618 android::procinfo::ProcessInfo proc_info;
619 std::string error;
620 if (android::procinfo::GetProcessInfo(main_thread.pid, &proc_info, &error)) {
621 uint64_t starttime = proc_info.starttime / sysconf(_SC_CLK_TCK);
622 result.set_process_uptime(si.uptime - starttime);
623 } else {
624 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read process info: %s",
625 error.c_str());
626 }
627
Josh Gao31348a72021-03-29 21:53:42 -0700628 auto cmd_line = result.mutable_command_line();
629 for (const auto& arg : main_thread.command_line) {
630 *cmd_line->Add() = arg;
631 }
632
Josh Gao618cea32021-01-26 17:45:43 -0800633 if (!main_thread.siginfo) {
634 async_safe_fatal("siginfo missing");
635 }
Josh Gao76e1e302021-01-26 15:53:11 -0800636
637 Signal sig;
638 sig.set_number(main_thread.signo);
639 sig.set_name(get_signame(main_thread.siginfo));
640 sig.set_code(main_thread.siginfo->si_code);
641 sig.set_code_name(get_sigcode(main_thread.siginfo));
642
643 if (signal_has_sender(main_thread.siginfo, main_thread.pid)) {
644 sig.set_has_sender(true);
645 sig.set_sender_uid(main_thread.siginfo->si_uid);
646 sig.set_sender_pid(main_thread.siginfo->si_pid);
647 }
648
649 if (process_info.has_fault_address) {
650 sig.set_has_fault_address(true);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700651 uintptr_t fault_addr = process_info.maybe_tagged_fault_address;
652 sig.set_fault_address(fault_addr);
653 dump_tags_around_fault_addr(&sig, result, unwinder, fault_addr);
Josh Gao76e1e302021-01-26 15:53:11 -0800654 }
655
656 *result.mutable_signal_info() = sig;
657
658 dump_abort_message(&result, unwinder, process_info);
659
660 dump_main_thread(&result, unwinder, main_thread);
661
662 for (const auto& [tid, thread_info] : threads) {
663 if (tid != target_thread) {
664 dump_thread(&result, unwinder, thread_info);
665 }
666 }
667
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800668 dump_probable_cause(&result, unwinder, process_info, main_thread);
Josh Gao76e1e302021-01-26 15:53:11 -0800669
670 dump_mappings(&result, unwinder);
671
672 // Only dump logs on debuggable devices.
673 if (android::base::GetBoolProperty("ro.debuggable", false)) {
674 dump_logcat(&result, main_thread.pid);
675 }
676
677 dump_open_fds(&result, open_files);
678
679 *tombstone = std::move(result);
680}