blob: bb3c7eae015d3e6fd9068eee7af7d674f4778c30 [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"
20
21#include <errno.h>
22#include <fcntl.h>
23#include <inttypes.h>
24#include <signal.h>
25#include <stddef.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/mman.h>
29#include <time.h>
30
31#include <memory>
32#include <string>
33
Josh Gao618cea32021-01-26 17:45:43 -080034#include <async_safe/log.h>
35
Josh Gao76e1e302021-01-26 15:53:11 -080036#include <android-base/properties.h>
37#include <android-base/stringprintf.h>
38#include <android-base/strings.h>
39#include <android-base/unique_fd.h>
40
41#include <android/log.h>
42#include <log/log.h>
43#include <log/log_read.h>
44#include <log/logprint.h>
45#include <private/android_filesystem_config.h>
46
47#include <unwindstack/Maps.h>
48#include <unwindstack/Memory.h>
49#include <unwindstack/Regs.h>
50#include <unwindstack/Unwinder.h>
51
52#include "libdebuggerd/open_files_list.h"
53#include "libdebuggerd/utility.h"
54#include "util.h"
55
56#include "tombstone.pb.h"
57
58using android::base::StringPrintf;
59
60// Use the demangler from libc++.
61extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
62
63static Architecture get_arch() {
64#if defined(__arm__)
65 return Architecture::ARM32;
66#elif defined(__aarch64__)
67 return Architecture::ARM64;
68#elif defined(__i386__)
69 return Architecture::X86;
70#elif defined(__x86_64__)
71 return Architecture::X86_64;
72#else
73#error Unknown architecture!
74#endif
75}
76
77static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
78 unwindstack::Maps* maps) {
79 static constexpr uint64_t kMaxDifferenceBytes = 256;
80 uint64_t difference;
81 if (sp >= fault_addr) {
82 difference = sp - fault_addr;
83 } else {
84 difference = fault_addr - sp;
85 }
86 if (difference <= kMaxDifferenceBytes) {
87 // The faulting address is close to the current sp, check if the sp
88 // indicates a stack overflow.
89 // On arm, the sp does not get updated when the instruction faults.
90 // In this case, the sp will still be in a valid map, which is the
91 // last case below.
92 // On aarch64, the sp does get updated when the instruction faults.
93 // In this case, the sp will be in either an invalid map if triggered
94 // on the main thread, or in a guard map if in another thread, which
95 // will be the first case or second case from below.
96 unwindstack::MapInfo* map_info = maps->Find(sp);
97 if (map_info == nullptr) {
98 return "stack pointer is in a non-existent map; likely due to stack overflow.";
99 } else if ((map_info->flags & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
100 return "stack pointer is not in a rw map; likely due to stack overflow.";
101 } else if ((sp - map_info->start) <= kMaxDifferenceBytes) {
102 return "stack pointer is close to top of stack; likely stack overflow.";
103 }
104 }
105 return {};
106}
107
108static void dump_probable_cause(Tombstone* tombstone, const siginfo_t* si, unwindstack::Maps* maps,
109 unwindstack::Regs* regs) {
110 std::optional<std::string> cause;
111 if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
112 if (si->si_addr < reinterpret_cast<void*>(4096)) {
113 cause = "null pointer dereference";
114 } else if (si->si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
115 cause = "call to kuser_helper_version";
116 } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
117 cause = "call to kuser_get_tls";
118 } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
119 cause = "call to kuser_cmpxchg";
120 } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
121 cause = "call to kuser_memory_barrier";
122 } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
123 cause = "call to kuser_cmpxchg64";
124 } else {
125 cause = get_stack_overflow_cause(reinterpret_cast<uint64_t>(si->si_addr), regs->sp(), maps);
126 }
127 } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
128 uint64_t fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
129 unwindstack::MapInfo* map_info = maps->Find(fault_addr);
130 if (map_info != nullptr && map_info->flags == PROT_EXEC) {
131 cause = "execute-only (no-read) memory access error; likely due to data in .text.";
132 } else {
133 cause = get_stack_overflow_cause(fault_addr, regs->sp(), maps);
134 }
135 } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
136 cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
137 si->si_syscall);
138 }
139
140 if (cause) {
141 tombstone->mutable_cause()->set_human_readable(*cause);
142 }
143}
144
145static void dump_abort_message(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
146 const ProcessInfo& process_info) {
147 std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
148 uintptr_t address = process_info.abort_msg_address;
149 if (address == 0) {
150 return;
151 }
152
153 size_t length;
154 if (!process_memory->ReadFully(address, &length, sizeof(length))) {
Josh Gao618cea32021-01-26 17:45:43 -0800155 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
156 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800157 return;
158 }
159
160 // The length field includes the length of the length field itself.
161 if (length < sizeof(size_t)) {
Josh Gao618cea32021-01-26 17:45:43 -0800162 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
163 "abort message header malformed: claimed length = %zu", length);
Josh Gao76e1e302021-01-26 15:53:11 -0800164 return;
165 }
166
167 length -= sizeof(size_t);
168
169 // The abort message should be null terminated already, but reserve a spot for NUL just in case.
170 std::string msg;
171 msg.resize(length);
172
173 if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
Josh Gao618cea32021-01-26 17:45:43 -0800174 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to read abort message header: %s",
175 strerror(errno));
Josh Gao76e1e302021-01-26 15:53:11 -0800176 return;
177 }
178
179 tombstone->set_abort_message(msg);
180}
181
182static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
183 if (open_files) {
184 for (auto& [fd, entry] : *open_files) {
185 FD f;
186
187 f.set_fd(fd);
188
189 const std::optional<std::string>& path = entry.path;
190 if (path) {
191 f.set_path(*path);
192 }
193
194 const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
195 if (fdsan_owner) {
196 const char* type = android_fdsan_get_tag_type(*fdsan_owner);
197 uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
198 f.set_owner(type);
199 f.set_tag(value);
200 }
201
202 *tombstone->add_open_fds() = f;
203 }
204 }
205}
206
207static void dump_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
208 const ThreadInfo& thread_info, bool memory_dump = false) {
209 Thread thread;
210
211 thread.set_id(thread_info.tid);
212 thread.set_name(thread_info.thread_name);
213
214 unwindstack::Maps* maps = unwinder->GetMaps();
215 unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
216
217 thread_info.registers->IterateRegisters(
218 [&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
219 Register r;
220 r.set_name(name);
221 r.set_u64(value);
222 *thread.add_registers() = r;
223
224 if (memory_dump) {
225 MemoryDump dump;
226
227 char buf[256];
228 size_t start_offset = 0;
229 ssize_t bytes = dump_memory(buf, sizeof(buf), &start_offset, &value, memory);
230 if (bytes == -1) {
231 return;
232 }
233
234 dump.set_register_name(name);
235
236 unwindstack::MapInfo* map_info = maps->Find(value);
237 if (map_info) {
238 dump.set_mapping_name(map_info->name);
239 }
240
241 dump.set_begin_address(value);
242
Josh Gao618cea32021-01-26 17:45:43 -0800243 if (start_offset + bytes > sizeof(buf)) {
244 async_safe_fatal("dump_memory overflowed? start offset = %zu, bytes read = %zd",
245 start_offset, bytes);
246 }
247
Josh Gao76e1e302021-01-26 15:53:11 -0800248 dump.set_memory(buf, start_offset + bytes);
249
250 *thread.add_memory_dump() = std::move(dump);
251 }
252 });
253
254 std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
255 unwinder->SetRegs(regs_copy.get());
256 unwinder->Unwind();
257 if (unwinder->NumFrames() == 0) {
Josh Gao618cea32021-01-26 17:45:43 -0800258 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, "failed to unwind");
Josh Gao76e1e302021-01-26 15:53:11 -0800259 if (unwinder->LastErrorCode() != unwindstack::ERROR_NONE) {
Josh Gao618cea32021-01-26 17:45:43 -0800260 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, " error code: %s",
261 unwinder->LastErrorCodeString());
262 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG, " error address: 0x%" PRIx64,
263 unwinder->LastErrorAddress());
Josh Gao76e1e302021-01-26 15:53:11 -0800264 }
265 } else {
266 unwinder->SetDisplayBuildID(true);
267 for (const auto& frame : unwinder->frames()) {
268 BacktraceFrame* f = thread.add_current_backtrace();
269 f->set_rel_pc(frame.rel_pc);
270 f->set_pc(frame.pc);
271 f->set_sp(frame.sp);
272
273 if (!frame.function_name.empty()) {
274 // TODO: Should this happen here, or on the display side?
275 char* demangled_name =
276 __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
277 if (demangled_name) {
278 f->set_function_name(demangled_name);
279 free(demangled_name);
280 } else {
281 f->set_function_name(frame.function_name);
282 }
283 }
284
285 f->set_function_offset(frame.function_offset);
286
287 if (frame.map_start == frame.map_end) {
288 // No valid map associated with this frame.
289 f->set_file_name("<unknown>");
290 } else if (!frame.map_name.empty()) {
291 f->set_file_name(frame.map_name);
292 } else {
293 f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_start));
294 }
295
296 f->set_file_map_offset(frame.map_elf_start_offset);
297
298 unwindstack::MapInfo* map_info = maps->Find(frame.map_start);
299 if (map_info) {
300 f->set_build_id(map_info->GetPrintableBuildID());
301 }
302 }
303 }
304
305 auto& threads = *tombstone->mutable_threads();
306 threads[thread_info.tid] = thread;
307}
308
309static void dump_main_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
310 const ThreadInfo& thread_info) {
311 dump_thread(tombstone, unwinder, thread_info, true);
312}
313
314static void dump_mappings(Tombstone* tombstone, unwindstack::Unwinder* unwinder) {
315 unwindstack::Maps* maps = unwinder->GetMaps();
316 std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
317
318 for (const auto& map_info : *maps) {
319 auto* map = tombstone->add_memory_mappings();
320 map->set_begin_address(map_info->start);
321 map->set_end_address(map_info->end);
322 map->set_offset(map_info->offset);
323
324 if (map_info->flags & PROT_READ) {
325 map->set_read(true);
326 }
327 if (map_info->flags & PROT_WRITE) {
328 map->set_write(true);
329 }
330 if (map_info->flags & PROT_EXEC) {
331 map->set_execute(true);
332 }
333
334 map->set_mapping_name(map_info->name);
335
336 std::string build_id = map_info->GetPrintableBuildID();
337 if (!build_id.empty()) {
338 map->set_build_id(build_id);
339 }
340
341 map->set_load_bias(map_info->GetLoadBias(process_memory));
342 }
343}
344
345static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
346 logger_list* logger_list =
347 android_logger_list_open(android_name_to_log_id(logger), ANDROID_LOG_NONBLOCK, 0, pid);
348
349 LogBuffer buffer;
350
351 while (true) {
352 log_msg log_entry;
353 ssize_t actual = android_logger_list_read(logger_list, &log_entry);
354
355 if (actual < 0) {
356 if (actual == -EINTR) {
357 // interrupted by signal, retry
358 continue;
359 }
360 if (actual == -EAGAIN) {
361 // non-blocking EOF; we're done
362 break;
363 } else {
Josh Gao76e1e302021-01-26 15:53:11 -0800364 break;
365 }
366 } else if (actual == 0) {
Josh Gao76e1e302021-01-26 15:53:11 -0800367 break;
368 }
369
370 char timestamp_secs[32];
371 time_t sec = static_cast<time_t>(log_entry.entry.sec);
372 tm tm;
373 localtime_r(&sec, &tm);
374 strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
375 std::string timestamp =
376 StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
377
378 // Msg format is: <priority:1><tag:N>\0<message:N>\0
379 char* msg = log_entry.msg();
380 if (msg == nullptr) {
381 continue;
382 }
383
384 unsigned char prio = msg[0];
385 char* tag = msg + 1;
386 msg = tag + strlen(tag) + 1;
387
388 // consume any trailing newlines
389 char* nl = msg + strlen(msg) - 1;
390 while (nl >= msg && *nl == '\n') {
391 *nl-- = '\0';
392 }
393
394 // Look for line breaks ('\n') and display each text line
395 // on a separate line, prefixed with the header, like logcat does.
396 do {
397 nl = strchr(msg, '\n');
398 if (nl != nullptr) {
399 *nl = '\0';
400 ++nl;
401 }
402
403 LogMessage* log_msg = buffer.add_logs();
404 log_msg->set_timestamp(timestamp);
405 log_msg->set_pid(log_entry.entry.pid);
406 log_msg->set_tid(log_entry.entry.tid);
407 log_msg->set_priority(prio);
408 log_msg->set_tag(tag);
409 log_msg->set_message(msg);
410 } while ((msg = nl));
411 }
412 android_logger_list_free(logger_list);
413
414 if (!buffer.logs().empty()) {
415 buffer.set_name(logger);
416 *tombstone->add_log_buffers() = std::move(buffer);
417 }
418}
419
420static void dump_logcat(Tombstone* tombstone, pid_t pid) {
421 dump_log_file(tombstone, "system", pid);
422 dump_log_file(tombstone, "main", pid);
423}
424
425void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
426 const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
427 const ProcessInfo& process_info, const OpenFilesList* open_files) {
428 Tombstone result;
429
430 result.set_arch(get_arch());
431 result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
432 result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
433 result.set_timestamp(get_timestamp());
434
435 const ThreadInfo& main_thread = threads.at(target_thread);
436 result.set_pid(main_thread.pid);
437 result.set_tid(main_thread.tid);
438 result.set_uid(main_thread.uid);
439 result.set_selinux_label(main_thread.selinux_label);
440
441 result.set_process_name(main_thread.process_name);
Josh Gao618cea32021-01-26 17:45:43 -0800442 if (!main_thread.siginfo) {
443 async_safe_fatal("siginfo missing");
444 }
Josh Gao76e1e302021-01-26 15:53:11 -0800445
446 Signal sig;
447 sig.set_number(main_thread.signo);
448 sig.set_name(get_signame(main_thread.siginfo));
449 sig.set_code(main_thread.siginfo->si_code);
450 sig.set_code_name(get_sigcode(main_thread.siginfo));
451
452 if (signal_has_sender(main_thread.siginfo, main_thread.pid)) {
453 sig.set_has_sender(true);
454 sig.set_sender_uid(main_thread.siginfo->si_uid);
455 sig.set_sender_pid(main_thread.siginfo->si_pid);
456 }
457
458 if (process_info.has_fault_address) {
459 sig.set_has_fault_address(true);
460 sig.set_fault_address(process_info.untagged_fault_address);
461 }
462
463 *result.mutable_signal_info() = sig;
464
465 dump_abort_message(&result, unwinder, process_info);
466
467 dump_main_thread(&result, unwinder, main_thread);
468
469 for (const auto& [tid, thread_info] : threads) {
470 if (tid != target_thread) {
471 dump_thread(&result, unwinder, thread_info);
472 }
473 }
474
475 dump_probable_cause(&result, main_thread.siginfo, unwinder->GetMaps(),
476 main_thread.registers.get());
477
478 dump_mappings(&result, unwinder);
479
480 // Only dump logs on debuggable devices.
481 if (android::base::GetBoolProperty("ro.debuggable", false)) {
482 dump_logcat(&result, main_thread.pid);
483 }
484
485 dump_open_fds(&result, open_files);
486
487 *tombstone = std::move(result);
488}