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