utility.cpp 14 KB

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