• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2008, 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/utility.h"
20 
21 #include <errno.h>
22 #include <signal.h>
23 #include <string.h>
24 #include <sys/capability.h>
25 #include <sys/prctl.h>
26 #include <sys/ptrace.h>
27 #include <sys/uio.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30 
31 #include <set>
32 #include <string>
33 
34 #include <android-base/properties.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <android-base/unique_fd.h>
38 #include <async_safe/log.h>
39 #include <bionic/reserved_signals.h>
40 #include <debuggerd/handler.h>
41 #include <log/log.h>
42 #include <unwindstack/Memory.h>
43 #include <unwindstack/Unwinder.h>
44 
45 using android::base::StringPrintf;
46 using android::base::unique_fd;
47 
is_allowed_in_logcat(enum logtype ltype)48 bool is_allowed_in_logcat(enum logtype ltype) {
49   if ((ltype == HEADER)
50    || (ltype == REGISTERS)
51    || (ltype == BACKTRACE)) {
52     return true;
53   }
54   return false;
55 }
56 
should_write_to_kmsg()57 static bool should_write_to_kmsg() {
58   // Write to kmsg if tombstoned isn't up, and we're able to do so.
59   if (!android::base::GetBoolProperty("ro.debuggable", false)) {
60     return false;
61   }
62 
63   if (android::base::GetProperty("init.svc.tombstoned", "") == "running") {
64     return false;
65   }
66 
67   return true;
68 }
69 
70 __attribute__((__weak__, visibility("default")))
_LOG(log_t * log,enum logtype ltype,const char * fmt,...)71 void _LOG(log_t* log, enum logtype ltype, const char* fmt, ...) {
72   va_list ap;
73   va_start(ap, fmt);
74   _VLOG(log, ltype, fmt, ap);
75   va_end(ap);
76 }
77 
78 __attribute__((__weak__, visibility("default")))
_VLOG(log_t * log,enum logtype ltype,const char * fmt,va_list ap)79 void _VLOG(log_t* log, enum logtype ltype, const char* fmt, va_list ap) {
80   bool write_to_tombstone = (log->tfd != -1);
81   bool write_to_logcat = is_allowed_in_logcat(ltype)
82                       && log->crashed_tid != -1
83                       && log->current_tid != -1
84                       && (log->crashed_tid == log->current_tid);
85   static bool write_to_kmsg = should_write_to_kmsg();
86 
87   std::string msg;
88   android::base::StringAppendV(&msg, fmt, ap);
89 
90   if (msg.empty()) return;
91 
92   if (write_to_tombstone) {
93     TEMP_FAILURE_RETRY(write(log->tfd, msg.c_str(), msg.size()));
94   }
95 
96   if (write_to_logcat) {
97     __android_log_buf_write(LOG_ID_CRASH, ANDROID_LOG_FATAL, LOG_TAG, msg.c_str());
98     if (log->amfd_data != nullptr) {
99       *log->amfd_data += msg;
100     }
101 
102     if (write_to_kmsg) {
103       unique_fd kmsg_fd(open("/dev/kmsg_debug", O_WRONLY | O_APPEND | O_CLOEXEC));
104       if (kmsg_fd.get() >= 0) {
105         // Our output might contain newlines which would otherwise be handled by the android logger.
106         // Split the lines up ourselves before sending to the kernel logger.
107         if (msg.back() == '\n') {
108           msg.back() = '\0';
109         }
110 
111         std::vector<std::string> fragments = android::base::Split(msg, "\n");
112         for (const std::string& fragment : fragments) {
113           static constexpr char prefix[] = "<3>DEBUG: ";
114           struct iovec iov[3];
115           iov[0].iov_base = const_cast<char*>(prefix);
116           iov[0].iov_len = strlen(prefix);
117           iov[1].iov_base = const_cast<char*>(fragment.c_str());
118           iov[1].iov_len = fragment.length();
119           iov[2].iov_base = const_cast<char*>("\n");
120           iov[2].iov_len = 1;
121           TEMP_FAILURE_RETRY(writev(kmsg_fd.get(), iov, 3));
122         }
123       }
124     }
125   }
126 }
127 
128 #define MEMORY_BYTES_TO_DUMP 256
129 #define MEMORY_BYTES_PER_LINE 16
130 static_assert(MEMORY_BYTES_PER_LINE == kTagGranuleSize);
131 
dump_memory(void * out,size_t len,uint8_t * tags,size_t tags_len,uint64_t * addr,unwindstack::Memory * memory)132 ssize_t dump_memory(void* out, size_t len, uint8_t* tags, size_t tags_len, uint64_t* addr,
133                     unwindstack::Memory* memory) {
134   // Align the address to the number of bytes per line to avoid confusing memory tag output if
135   // memory is tagged and we start from a misaligned address. Start 32 bytes before the address.
136   *addr &= ~(MEMORY_BYTES_PER_LINE - 1);
137   if (*addr >= 4128) {
138     *addr -= 32;
139   }
140 
141   // We don't want the address tag to appear in the addresses in the memory dump.
142   *addr = untag_address(*addr);
143 
144   // Don't bother if the address would overflow, taking tag bits into account. Note that
145   // untag_address truncates to 32 bits on 32-bit platforms as a side effect of returning a
146   // uintptr_t, so this also checks for 32-bit overflow.
147   if (untag_address(*addr + MEMORY_BYTES_TO_DUMP - 1) < *addr) {
148     return -1;
149   }
150 
151   memset(out, 0, len);
152 
153   size_t bytes = memory->Read(*addr, reinterpret_cast<uint8_t*>(out), len);
154   if (bytes % sizeof(uintptr_t) != 0) {
155     // This should never happen, but just in case.
156     ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
157     bytes &= ~(sizeof(uintptr_t) - 1);
158   }
159 
160   bool skip_2nd_read = false;
161   if (bytes == 0) {
162     // In this case, we might want to try another read at the beginning of
163     // the next page only if it's within the amount of memory we would have
164     // read.
165     size_t page_size = sysconf(_SC_PAGE_SIZE);
166     uint64_t next_page = (*addr + (page_size - 1)) & ~(page_size - 1);
167     if (next_page == *addr || next_page >= *addr + len) {
168       skip_2nd_read = true;
169     }
170     *addr = next_page;
171   }
172 
173   if (bytes < len && !skip_2nd_read) {
174     // Try to do one more read. This could happen if a read crosses a map,
175     // but the maps do not have any break between them. Or it could happen
176     // if reading from an unreadable map, but the read would cross back
177     // into a readable map. Only requires one extra read because a map has
178     // to contain at least one page, and the total number of bytes to dump
179     // is smaller than a page.
180     size_t bytes2 = memory->Read(*addr + bytes, static_cast<uint8_t*>(out) + bytes, len - bytes);
181     bytes += bytes2;
182     if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
183       // This should never happen, but we'll try and continue any way.
184       ALOGE("Bytes after second read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
185       bytes &= ~(sizeof(uintptr_t) - 1);
186     }
187   }
188 
189   // If we were unable to read anything, it probably means that the register doesn't contain a
190   // valid pointer.
191   if (bytes == 0) {
192     return -1;
193   }
194 
195   for (uint64_t tag_granule = 0; tag_granule < bytes / kTagGranuleSize; ++tag_granule) {
196     long tag = memory->ReadTag(*addr + kTagGranuleSize * tag_granule);
197     if (tag_granule < tags_len) {
198       tags[tag_granule] = tag >= 0 ? tag : 0;
199     } else {
200       ALOGE("Insufficient space for tags");
201     }
202   }
203 
204   return bytes;
205 }
206 
dump_memory(log_t * log,unwindstack::Memory * memory,uint64_t addr,const std::string & label)207 void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const std::string& label) {
208   // Dump 256 bytes
209   uintptr_t data[MEMORY_BYTES_TO_DUMP / sizeof(uintptr_t)];
210   uint8_t tags[MEMORY_BYTES_TO_DUMP / kTagGranuleSize];
211 
212   ssize_t bytes = dump_memory(data, sizeof(data), tags, sizeof(tags), &addr, memory);
213   if (bytes == -1) {
214     return;
215   }
216 
217   _LOG(log, logtype::MEMORY, "\n%s:\n", label.c_str());
218 
219   // Dump the code around memory as:
220   //  addr             contents                           ascii
221   //  0000000000008d34 ef000000e8bd0090 e1b00000512fff1e  ............../Q
222   //  0000000000008d44 ea00b1f9e92d0090 e3a070fcef000000  ......-..p......
223   // On 32-bit machines, there are still 16 bytes per line but addresses and
224   // words are of course presented differently.
225   uintptr_t* data_ptr = data;
226   uint8_t* tags_ptr = tags;
227   for (size_t line = 0; line < static_cast<size_t>(bytes) / MEMORY_BYTES_PER_LINE; line++) {
228     uint64_t tagged_addr = addr | static_cast<uint64_t>(*tags_ptr++) << 56;
229     std::string logline;
230     android::base::StringAppendF(&logline, "    %" PRIPTR, tagged_addr);
231 
232     addr += MEMORY_BYTES_PER_LINE;
233     std::string ascii;
234     for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
235       android::base::StringAppendF(&logline, " %" PRIPTR, static_cast<uint64_t>(*data_ptr));
236 
237       // Fill out the ascii string from the data.
238       uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr);
239       for (size_t val = 0; val < sizeof(uintptr_t); val++, ptr++) {
240         if (*ptr >= 0x20 && *ptr < 0x7f) {
241           ascii += *ptr;
242         } else {
243           ascii += '.';
244         }
245       }
246       data_ptr++;
247     }
248     _LOG(log, logtype::MEMORY, "%s  %s\n", logline.c_str(), ascii.c_str());
249   }
250 }
251 
drop_capabilities()252 void drop_capabilities() {
253   __user_cap_header_struct capheader;
254   memset(&capheader, 0, sizeof(capheader));
255   capheader.version = _LINUX_CAPABILITY_VERSION_3;
256   capheader.pid = 0;
257 
258   __user_cap_data_struct capdata[2];
259   memset(&capdata, 0, sizeof(capdata));
260 
261   if (capset(&capheader, &capdata[0]) == -1) {
262     async_safe_fatal("failed to drop capabilities: %s", strerror(errno));
263   }
264 
265   if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
266     async_safe_fatal("failed to set PR_SET_NO_NEW_PRIVS: %s", strerror(errno));
267   }
268 }
269 
signal_has_si_addr(const siginfo_t * si)270 bool signal_has_si_addr(const siginfo_t* si) {
271   // Manually sent signals won't have si_addr.
272   if (si->si_code == SI_USER || si->si_code == SI_QUEUE || si->si_code == SI_TKILL) {
273     return false;
274   }
275 
276   switch (si->si_signo) {
277     case SIGBUS:
278     case SIGFPE:
279     case SIGILL:
280     case SIGTRAP:
281       return true;
282     case SIGSEGV:
283       return si->si_code != SEGV_MTEAERR;
284     default:
285       return false;
286   }
287 }
288 
signal_has_sender(const siginfo_t * si,pid_t caller_pid)289 bool signal_has_sender(const siginfo_t* si, pid_t caller_pid) {
290   return SI_FROMUSER(si) && (si->si_pid != 0) && (si->si_pid != caller_pid);
291 }
292 
get_signal_sender(char * buf,size_t n,const siginfo_t * si)293 void get_signal_sender(char* buf, size_t n, const siginfo_t* si) {
294   snprintf(buf, n, " from pid %d, uid %d", si->si_pid, si->si_uid);
295 }
296 
get_signame(const siginfo_t * si)297 const char* get_signame(const siginfo_t* si) {
298   switch (si->si_signo) {
299     case SIGABRT: return "SIGABRT";
300     case SIGBUS: return "SIGBUS";
301     case SIGFPE: return "SIGFPE";
302     case SIGILL: return "SIGILL";
303     case SIGSEGV: return "SIGSEGV";
304     case SIGSTKFLT: return "SIGSTKFLT";
305     case SIGSTOP: return "SIGSTOP";
306     case SIGSYS: return "SIGSYS";
307     case SIGTRAP: return "SIGTRAP";
308     case BIONIC_SIGNAL_DEBUGGER:
309       return "<debuggerd signal>";
310     default: return "?";
311   }
312 }
313 
get_sigcode(const siginfo_t * si)314 const char* get_sigcode(const siginfo_t* si) {
315   // Try the signal-specific codes...
316   switch (si->si_signo) {
317     case SIGILL:
318       switch (si->si_code) {
319         case ILL_ILLOPC: return "ILL_ILLOPC";
320         case ILL_ILLOPN: return "ILL_ILLOPN";
321         case ILL_ILLADR: return "ILL_ILLADR";
322         case ILL_ILLTRP: return "ILL_ILLTRP";
323         case ILL_PRVOPC: return "ILL_PRVOPC";
324         case ILL_PRVREG: return "ILL_PRVREG";
325         case ILL_COPROC: return "ILL_COPROC";
326         case ILL_BADSTK: return "ILL_BADSTK";
327         case ILL_BADIADDR:
328           return "ILL_BADIADDR";
329         case __ILL_BREAK:
330           return "ILL_BREAK";
331         case __ILL_BNDMOD:
332           return "ILL_BNDMOD";
333       }
334       static_assert(NSIGILL == __ILL_BNDMOD, "missing ILL_* si_code");
335       break;
336     case SIGBUS:
337       switch (si->si_code) {
338         case BUS_ADRALN: return "BUS_ADRALN";
339         case BUS_ADRERR: return "BUS_ADRERR";
340         case BUS_OBJERR: return "BUS_OBJERR";
341         case BUS_MCEERR_AR: return "BUS_MCEERR_AR";
342         case BUS_MCEERR_AO: return "BUS_MCEERR_AO";
343       }
344       static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code");
345       break;
346     case SIGFPE:
347       switch (si->si_code) {
348         case FPE_INTDIV: return "FPE_INTDIV";
349         case FPE_INTOVF: return "FPE_INTOVF";
350         case FPE_FLTDIV: return "FPE_FLTDIV";
351         case FPE_FLTOVF: return "FPE_FLTOVF";
352         case FPE_FLTUND: return "FPE_FLTUND";
353         case FPE_FLTRES: return "FPE_FLTRES";
354         case FPE_FLTINV: return "FPE_FLTINV";
355         case FPE_FLTSUB: return "FPE_FLTSUB";
356         case __FPE_DECOVF:
357           return "FPE_DECOVF";
358         case __FPE_DECDIV:
359           return "FPE_DECDIV";
360         case __FPE_DECERR:
361           return "FPE_DECERR";
362         case __FPE_INVASC:
363           return "FPE_INVASC";
364         case __FPE_INVDEC:
365           return "FPE_INVDEC";
366         case FPE_FLTUNK:
367           return "FPE_FLTUNK";
368         case FPE_CONDTRAP:
369           return "FPE_CONDTRAP";
370       }
371       static_assert(NSIGFPE == FPE_CONDTRAP, "missing FPE_* si_code");
372       break;
373     case SIGSEGV:
374       switch (si->si_code) {
375         case SEGV_MAPERR: return "SEGV_MAPERR";
376         case SEGV_ACCERR: return "SEGV_ACCERR";
377         case SEGV_BNDERR: return "SEGV_BNDERR";
378         case SEGV_PKUERR: return "SEGV_PKUERR";
379         case SEGV_ACCADI:
380           return "SEGV_ACCADI";
381         case SEGV_ADIDERR:
382           return "SEGV_ADIDERR";
383         case SEGV_ADIPERR:
384           return "SEGV_ADIPERR";
385         case SEGV_MTEAERR:
386           return "SEGV_MTEAERR";
387         case SEGV_MTESERR:
388           return "SEGV_MTESERR";
389       }
390       static_assert(NSIGSEGV == SEGV_MTESERR, "missing SEGV_* si_code");
391       break;
392     case SIGSYS:
393       switch (si->si_code) {
394         case SYS_SECCOMP: return "SYS_SECCOMP";
395         case SYS_USER_DISPATCH:
396           return "SYS_USER_DISPATCH";
397       }
398       static_assert(NSIGSYS == SYS_USER_DISPATCH, "missing SYS_* si_code");
399       break;
400     case SIGTRAP:
401       switch (si->si_code) {
402         case TRAP_BRKPT: return "TRAP_BRKPT";
403         case TRAP_TRACE: return "TRAP_TRACE";
404         case TRAP_BRANCH: return "TRAP_BRANCH";
405         case TRAP_HWBKPT: return "TRAP_HWBKPT";
406         case TRAP_UNK:
407           return "TRAP_UNDIAGNOSED";
408         case TRAP_PERF:
409           return "TRAP_PERF";
410       }
411       if ((si->si_code & 0xff) == SIGTRAP) {
412         switch ((si->si_code >> 8) & 0xff) {
413           case PTRACE_EVENT_FORK:
414             return "PTRACE_EVENT_FORK";
415           case PTRACE_EVENT_VFORK:
416             return "PTRACE_EVENT_VFORK";
417           case PTRACE_EVENT_CLONE:
418             return "PTRACE_EVENT_CLONE";
419           case PTRACE_EVENT_EXEC:
420             return "PTRACE_EVENT_EXEC";
421           case PTRACE_EVENT_VFORK_DONE:
422             return "PTRACE_EVENT_VFORK_DONE";
423           case PTRACE_EVENT_EXIT:
424             return "PTRACE_EVENT_EXIT";
425           case PTRACE_EVENT_SECCOMP:
426             return "PTRACE_EVENT_SECCOMP";
427           case PTRACE_EVENT_STOP:
428             return "PTRACE_EVENT_STOP";
429         }
430       }
431       static_assert(NSIGTRAP == TRAP_PERF, "missing TRAP_* si_code");
432       break;
433   }
434   // Then the other codes...
435   switch (si->si_code) {
436     case SI_USER: return "SI_USER";
437     case SI_KERNEL: return "SI_KERNEL";
438     case SI_QUEUE: return "SI_QUEUE";
439     case SI_TIMER: return "SI_TIMER";
440     case SI_MESGQ: return "SI_MESGQ";
441     case SI_ASYNCIO: return "SI_ASYNCIO";
442     case SI_SIGIO: return "SI_SIGIO";
443     case SI_TKILL: return "SI_TKILL";
444     case SI_DETHREAD: return "SI_DETHREAD";
445   }
446   // Then give up...
447   return "?";
448 }
449 
450 #define DESCRIBE_FLAG(flag) \
451   if (value & flag) {       \
452     desc += ", ";           \
453     desc += #flag;          \
454     value &= ~flag;         \
455   }
456 
describe_end(long value,std::string & desc)457 static std::string describe_end(long value, std::string& desc) {
458   if (value) {
459     desc += StringPrintf(", unknown 0x%lx", value);
460   }
461   return desc.empty() ? "" : " (" + desc.substr(2) + ")";
462 }
463 
describe_tagged_addr_ctrl(long value)464 std::string describe_tagged_addr_ctrl(long value) {
465   std::string desc;
466   DESCRIBE_FLAG(PR_TAGGED_ADDR_ENABLE);
467   DESCRIBE_FLAG(PR_MTE_TCF_SYNC);
468   DESCRIBE_FLAG(PR_MTE_TCF_ASYNC);
469   if (value & PR_MTE_TAG_MASK) {
470     desc += StringPrintf(", mask 0x%04lx", (value & PR_MTE_TAG_MASK) >> PR_MTE_TAG_SHIFT);
471     value &= ~PR_MTE_TAG_MASK;
472   }
473   return describe_end(value, desc);
474 }
475 
describe_pac_enabled_keys(long value)476 std::string describe_pac_enabled_keys(long value) {
477   std::string desc;
478   DESCRIBE_FLAG(PR_PAC_APIAKEY);
479   DESCRIBE_FLAG(PR_PAC_APIBKEY);
480   DESCRIBE_FLAG(PR_PAC_APDAKEY);
481   DESCRIBE_FLAG(PR_PAC_APDBKEY);
482   DESCRIBE_FLAG(PR_PAC_APGAKEY);
483   return describe_end(value, desc);
484 }
485 
log_backtrace(log_t * log,unwindstack::Unwinder * unwinder,const char * prefix)486 void log_backtrace(log_t* log, unwindstack::Unwinder* unwinder, const char* prefix) {
487   std::set<std::string> unreadable_elf_files;
488   unwinder->SetDisplayBuildID(true);
489   for (const auto& frame : unwinder->frames()) {
490     if (frame.map_info != nullptr && frame.map_info->ElfFileNotReadable()) {
491       unreadable_elf_files.emplace(frame.map_info->name());
492     }
493   }
494 
495   // Put the preamble ahead of the backtrace.
496   if (!unreadable_elf_files.empty()) {
497     _LOG(log, logtype::BACKTRACE,
498          "%sNOTE: Function names and BuildId information is missing for some frames due\n", prefix);
499     _LOG(log, logtype::BACKTRACE,
500          "%sNOTE: to unreadable libraries. For unwinds of apps, only shared libraries\n", prefix);
501     _LOG(log, logtype::BACKTRACE, "%sNOTE: found under the lib/ directory are readable.\n", prefix);
502 #if defined(ROOT_POSSIBLE)
503     _LOG(log, logtype::BACKTRACE,
504          "%sNOTE: On this device, run setenforce 0 to make the libraries readable.\n", prefix);
505 #endif
506     _LOG(log, logtype::BACKTRACE, "%sNOTE: Unreadable libraries:\n", prefix);
507     for (auto& name : unreadable_elf_files) {
508       _LOG(log, logtype::BACKTRACE, "%sNOTE:   %s\n", prefix, name.c_str());
509     }
510   }
511 
512   for (const auto& frame : unwinder->frames()) {
513     _LOG(log, logtype::BACKTRACE, "%s%s\n", prefix, unwinder->FormatFrame(frame).c_str());
514   }
515 }
516