• 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 <string>
32 
33 #include <android-base/logging.h>
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 <backtrace/Backtrace.h>
39 #include <debuggerd/handler.h>
40 #include <log/log.h>
41 #include <unwindstack/Memory.h>
42 
43 using android::base::unique_fd;
44 
45 // Whitelist output desired in the logcat output.
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   bool write_to_tombstone = (log->tfd != -1);
71   bool write_to_logcat = is_allowed_in_logcat(ltype)
72                       && log->crashed_tid != -1
73                       && log->current_tid != -1
74                       && (log->crashed_tid == log->current_tid);
75   static bool write_to_kmsg = should_write_to_kmsg();
76 
77   char buf[512];
78   va_list ap;
79   va_start(ap, fmt);
80   vsnprintf(buf, sizeof(buf), fmt, ap);
81   va_end(ap);
82 
83   size_t len = strlen(buf);
84   if (len <= 0) {
85     return;
86   }
87 
88   if (write_to_tombstone) {
89     TEMP_FAILURE_RETRY(write(log->tfd, buf, len));
90   }
91 
92   if (write_to_logcat) {
93     __android_log_buf_write(LOG_ID_CRASH, ANDROID_LOG_FATAL, LOG_TAG, buf);
94     if (log->amfd_data != nullptr) {
95       *log->amfd_data += buf;
96     }
97 
98     if (write_to_kmsg) {
99       unique_fd kmsg_fd(open("/dev/kmsg_debug", O_WRONLY | O_APPEND | O_CLOEXEC));
100       if (kmsg_fd.get() >= 0) {
101         // Our output might contain newlines which would otherwise be handled by the android logger.
102         // Split the lines up ourselves before sending to the kernel logger.
103         if (buf[len - 1] == '\n') {
104           buf[len - 1] = '\0';
105         }
106 
107         std::vector<std::string> fragments = android::base::Split(buf, "\n");
108         for (const std::string& fragment : fragments) {
109           static constexpr char prefix[] = "<3>DEBUG: ";
110           struct iovec iov[3];
111           iov[0].iov_base = const_cast<char*>(prefix);
112           iov[0].iov_len = strlen(prefix);
113           iov[1].iov_base = const_cast<char*>(fragment.c_str());
114           iov[1].iov_len = fragment.length();
115           iov[2].iov_base = const_cast<char*>("\n");
116           iov[2].iov_len = 1;
117           TEMP_FAILURE_RETRY(writev(kmsg_fd.get(), iov, 3));
118         }
119       }
120     }
121   }
122 }
123 
124 #define MEMORY_BYTES_TO_DUMP 256
125 #define MEMORY_BYTES_PER_LINE 16
126 
dump_memory(log_t * log,unwindstack::Memory * memory,uint64_t addr,const std::string & label)127 void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const std::string& label) {
128   // Align the address to sizeof(long) and start 32 bytes before the address.
129   addr &= ~(sizeof(long) - 1);
130   if (addr >= 4128) {
131     addr -= 32;
132   }
133 
134   // Don't bother if the address looks too low, or looks too high.
135   if (addr < 4096 ||
136 #if defined(__LP64__)
137       addr > 0x4000000000000000UL - MEMORY_BYTES_TO_DUMP) {
138 #else
139       addr > 0xffff0000 - MEMORY_BYTES_TO_DUMP) {
140 #endif
141     return;
142   }
143 
144   _LOG(log, logtype::MEMORY, "\n%s:\n", label.c_str());
145 
146   // Dump 256 bytes
147   uintptr_t data[MEMORY_BYTES_TO_DUMP/sizeof(uintptr_t)];
148   memset(data, 0, MEMORY_BYTES_TO_DUMP);
149   size_t bytes = memory->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
150   if (bytes % sizeof(uintptr_t) != 0) {
151     // This should never happen, but just in case.
152     ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
153     bytes &= ~(sizeof(uintptr_t) - 1);
154   }
155 
156   uint64_t start = 0;
157   bool skip_2nd_read = false;
158   if (bytes == 0) {
159     // In this case, we might want to try another read at the beginning of
160     // the next page only if it's within the amount of memory we would have
161     // read.
162     size_t page_size = sysconf(_SC_PAGE_SIZE);
163     start = ((addr + (page_size - 1)) & ~(page_size - 1)) - addr;
164     if (start == 0 || start >= MEMORY_BYTES_TO_DUMP) {
165       skip_2nd_read = true;
166     }
167   }
168 
169   if (bytes < MEMORY_BYTES_TO_DUMP && !skip_2nd_read) {
170     // Try to do one more read. This could happen if a read crosses a map,
171     // but the maps do not have any break between them. Or it could happen
172     // if reading from an unreadable map, but the read would cross back
173     // into a readable map. Only requires one extra read because a map has
174     // to contain at least one page, and the total number of bytes to dump
175     // is smaller than a page.
176     size_t bytes2 = memory->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
177                                  sizeof(data) - bytes - start);
178     bytes += bytes2;
179     if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
180       // This should never happen, but we'll try and continue any way.
181       ALOGE("Bytes after second read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
182       bytes &= ~(sizeof(uintptr_t) - 1);
183     }
184   }
185 
186   // Dump the code around memory as:
187   //  addr             contents                           ascii
188   //  0000000000008d34 ef000000e8bd0090 e1b00000512fff1e  ............../Q
189   //  0000000000008d44 ea00b1f9e92d0090 e3a070fcef000000  ......-..p......
190   // On 32-bit machines, there are still 16 bytes per line but addresses and
191   // words are of course presented differently.
192   uintptr_t* data_ptr = data;
193   size_t current = 0;
194   size_t total_bytes = start + bytes;
195   for (size_t line = 0; line < MEMORY_BYTES_TO_DUMP / MEMORY_BYTES_PER_LINE; line++) {
196     std::string logline;
197     android::base::StringAppendF(&logline, "    %" PRIPTR, addr);
198 
199     addr += MEMORY_BYTES_PER_LINE;
200     std::string ascii;
201     for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
202       if (current >= start && current + sizeof(uintptr_t) <= total_bytes) {
203         android::base::StringAppendF(&logline, " %" PRIPTR, static_cast<uint64_t>(*data_ptr));
204 
205         // Fill out the ascii string from the data.
206         uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr);
207         for (size_t val = 0; val < sizeof(uintptr_t); val++, ptr++) {
208           if (*ptr >= 0x20 && *ptr < 0x7f) {
209             ascii += *ptr;
210           } else {
211             ascii += '.';
212           }
213         }
214         data_ptr++;
215       } else {
216         logline += ' ' + std::string(sizeof(uintptr_t) * 2, '-');
217         ascii += std::string(sizeof(uintptr_t), '.');
218       }
219       current += sizeof(uintptr_t);
220     }
221     _LOG(log, logtype::MEMORY, "%s  %s\n", logline.c_str(), ascii.c_str());
222   }
223 }
224 
225 void read_with_default(const char* path, char* buf, size_t len, const char* default_value) {
226   unique_fd fd(open(path, O_RDONLY | O_CLOEXEC));
227   if (fd != -1) {
228     int rc = TEMP_FAILURE_RETRY(read(fd.get(), buf, len - 1));
229     if (rc != -1) {
230       buf[rc] = '\0';
231 
232       // Trim trailing newlines.
233       if (rc > 0 && buf[rc - 1] == '\n') {
234         buf[rc - 1] = '\0';
235       }
236       return;
237     }
238   }
239   strcpy(buf, default_value);
240 }
241 
242 void drop_capabilities() {
243   __user_cap_header_struct capheader;
244   memset(&capheader, 0, sizeof(capheader));
245   capheader.version = _LINUX_CAPABILITY_VERSION_3;
246   capheader.pid = 0;
247 
248   __user_cap_data_struct capdata[2];
249   memset(&capdata, 0, sizeof(capdata));
250 
251   if (capset(&capheader, &capdata[0]) == -1) {
252     PLOG(FATAL) << "failed to drop capabilities";
253   }
254 
255   if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
256     PLOG(FATAL) << "failed to set PR_SET_NO_NEW_PRIVS";
257   }
258 }
259 
260 bool signal_has_si_addr(int si_signo, int si_code) {
261   // Manually sent signals won't have si_addr.
262   if (si_code == SI_USER || si_code == SI_QUEUE || si_code == SI_TKILL) {
263     return false;
264   }
265 
266   switch (si_signo) {
267     case SIGBUS:
268     case SIGFPE:
269     case SIGILL:
270     case SIGSEGV:
271     case SIGTRAP:
272       return true;
273     default:
274       return false;
275   }
276 }
277 
278 const char* get_signame(int sig) {
279   switch (sig) {
280     case SIGABRT: return "SIGABRT";
281     case SIGBUS: return "SIGBUS";
282     case SIGFPE: return "SIGFPE";
283     case SIGILL: return "SIGILL";
284     case SIGSEGV: return "SIGSEGV";
285 #if defined(SIGSTKFLT)
286     case SIGSTKFLT: return "SIGSTKFLT";
287 #endif
288     case SIGSTOP: return "SIGSTOP";
289     case SIGSYS: return "SIGSYS";
290     case SIGTRAP: return "SIGTRAP";
291     case DEBUGGER_SIGNAL: return "<debuggerd signal>";
292     default: return "?";
293   }
294 }
295 
296 const char* get_sigcode(int signo, int code) {
297   // Try the signal-specific codes...
298   switch (signo) {
299     case SIGILL:
300       switch (code) {
301         case ILL_ILLOPC: return "ILL_ILLOPC";
302         case ILL_ILLOPN: return "ILL_ILLOPN";
303         case ILL_ILLADR: return "ILL_ILLADR";
304         case ILL_ILLTRP: return "ILL_ILLTRP";
305         case ILL_PRVOPC: return "ILL_PRVOPC";
306         case ILL_PRVREG: return "ILL_PRVREG";
307         case ILL_COPROC: return "ILL_COPROC";
308         case ILL_BADSTK: return "ILL_BADSTK";
309       }
310       static_assert(NSIGILL == ILL_BADSTK, "missing ILL_* si_code");
311       break;
312     case SIGBUS:
313       switch (code) {
314         case BUS_ADRALN: return "BUS_ADRALN";
315         case BUS_ADRERR: return "BUS_ADRERR";
316         case BUS_OBJERR: return "BUS_OBJERR";
317         case BUS_MCEERR_AR: return "BUS_MCEERR_AR";
318         case BUS_MCEERR_AO: return "BUS_MCEERR_AO";
319       }
320       static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code");
321       break;
322     case SIGFPE:
323       switch (code) {
324         case FPE_INTDIV: return "FPE_INTDIV";
325         case FPE_INTOVF: return "FPE_INTOVF";
326         case FPE_FLTDIV: return "FPE_FLTDIV";
327         case FPE_FLTOVF: return "FPE_FLTOVF";
328         case FPE_FLTUND: return "FPE_FLTUND";
329         case FPE_FLTRES: return "FPE_FLTRES";
330         case FPE_FLTINV: return "FPE_FLTINV";
331         case FPE_FLTSUB: return "FPE_FLTSUB";
332       }
333       static_assert(NSIGFPE == FPE_FLTSUB, "missing FPE_* si_code");
334       break;
335     case SIGSEGV:
336       switch (code) {
337         case SEGV_MAPERR: return "SEGV_MAPERR";
338         case SEGV_ACCERR: return "SEGV_ACCERR";
339 #if defined(SEGV_BNDERR)
340         case SEGV_BNDERR: return "SEGV_BNDERR";
341 #endif
342 #if defined(SEGV_PKUERR)
343         case SEGV_PKUERR: return "SEGV_PKUERR";
344 #endif
345       }
346 #if defined(SEGV_PKUERR)
347       static_assert(NSIGSEGV == SEGV_PKUERR, "missing SEGV_* si_code");
348 #elif defined(SEGV_BNDERR)
349       static_assert(NSIGSEGV == SEGV_BNDERR, "missing SEGV_* si_code");
350 #else
351       static_assert(NSIGSEGV == SEGV_ACCERR, "missing SEGV_* si_code");
352 #endif
353       break;
354 #if defined(SYS_SECCOMP) // Our glibc is too old, and we build this for the host too.
355     case SIGSYS:
356       switch (code) {
357         case SYS_SECCOMP: return "SYS_SECCOMP";
358       }
359       static_assert(NSIGSYS == SYS_SECCOMP, "missing SYS_* si_code");
360       break;
361 #endif
362     case SIGTRAP:
363       switch (code) {
364         case TRAP_BRKPT: return "TRAP_BRKPT";
365         case TRAP_TRACE: return "TRAP_TRACE";
366         case TRAP_BRANCH: return "TRAP_BRANCH";
367         case TRAP_HWBKPT: return "TRAP_HWBKPT";
368       }
369       if ((code & 0xff) == SIGTRAP) {
370         switch ((code >> 8) & 0xff) {
371           case PTRACE_EVENT_FORK:
372             return "PTRACE_EVENT_FORK";
373           case PTRACE_EVENT_VFORK:
374             return "PTRACE_EVENT_VFORK";
375           case PTRACE_EVENT_CLONE:
376             return "PTRACE_EVENT_CLONE";
377           case PTRACE_EVENT_EXEC:
378             return "PTRACE_EVENT_EXEC";
379           case PTRACE_EVENT_VFORK_DONE:
380             return "PTRACE_EVENT_VFORK_DONE";
381           case PTRACE_EVENT_EXIT:
382             return "PTRACE_EVENT_EXIT";
383           case PTRACE_EVENT_SECCOMP:
384             return "PTRACE_EVENT_SECCOMP";
385           case PTRACE_EVENT_STOP:
386             return "PTRACE_EVENT_STOP";
387         }
388       }
389       static_assert(NSIGTRAP == TRAP_HWBKPT, "missing TRAP_* si_code");
390       break;
391   }
392   // Then the other codes...
393   switch (code) {
394     case SI_USER: return "SI_USER";
395     case SI_KERNEL: return "SI_KERNEL";
396     case SI_QUEUE: return "SI_QUEUE";
397     case SI_TIMER: return "SI_TIMER";
398     case SI_MESGQ: return "SI_MESGQ";
399     case SI_ASYNCIO: return "SI_ASYNCIO";
400     case SI_SIGIO: return "SI_SIGIO";
401     case SI_TKILL: return "SI_TKILL";
402     case SI_DETHREAD: return "SI_DETHREAD";
403   }
404   // Then give up...
405   return "?";
406 }
407