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