tombstone.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. /*
  2. * Copyright (C) 2012-2014 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/tombstone.h"
  18. #include <dirent.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <inttypes.h>
  22. #include <signal.h>
  23. #include <stddef.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/mman.h>
  28. #include <sys/ptrace.h>
  29. #include <sys/stat.h>
  30. #include <time.h>
  31. #include <memory>
  32. #include <string>
  33. #include <android-base/file.h>
  34. #include <android-base/logging.h>
  35. #include <android-base/properties.h>
  36. #include <android-base/stringprintf.h>
  37. #include <android-base/strings.h>
  38. #include <android-base/unique_fd.h>
  39. #include <android/log.h>
  40. #include <log/log.h>
  41. #include <log/logprint.h>
  42. #include <private/android_filesystem_config.h>
  43. #include <unwindstack/DexFiles.h>
  44. #include <unwindstack/JitDebug.h>
  45. #include <unwindstack/Maps.h>
  46. #include <unwindstack/Memory.h>
  47. #include <unwindstack/Regs.h>
  48. #include <unwindstack/Unwinder.h>
  49. // Needed to get DEBUGGER_SIGNAL.
  50. #include "debuggerd/handler.h"
  51. #include "libdebuggerd/backtrace.h"
  52. #include "libdebuggerd/open_files_list.h"
  53. #include "libdebuggerd/utility.h"
  54. using android::base::GetBoolProperty;
  55. using android::base::GetProperty;
  56. using android::base::StringPrintf;
  57. using android::base::unique_fd;
  58. using namespace std::literals::string_literals;
  59. #define STACK_WORDS 16
  60. static void dump_header_info(log_t* log) {
  61. auto fingerprint = GetProperty("ro.build.fingerprint", "unknown");
  62. auto revision = GetProperty("ro.revision", "unknown");
  63. _LOG(log, logtype::HEADER, "Build fingerprint: '%s'\n", fingerprint.c_str());
  64. _LOG(log, logtype::HEADER, "Revision: '%s'\n", revision.c_str());
  65. _LOG(log, logtype::HEADER, "ABI: '%s'\n", ABI_STRING);
  66. }
  67. static void dump_timestamp(log_t* log, time_t time) {
  68. struct tm tm;
  69. localtime_r(&time, &tm);
  70. char buf[strlen("1970-01-01 00:00:00+0830") + 1];
  71. strftime(buf, sizeof(buf), "%F %T%z", &tm);
  72. _LOG(log, logtype::HEADER, "Timestamp: %s\n", buf);
  73. }
  74. static void dump_probable_cause(log_t* log, const siginfo_t* si, unwindstack::Maps* maps) {
  75. std::string cause;
  76. if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
  77. if (si->si_addr < reinterpret_cast<void*>(4096)) {
  78. cause = StringPrintf("null pointer dereference");
  79. } else if (si->si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
  80. cause = "call to kuser_helper_version";
  81. } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
  82. cause = "call to kuser_get_tls";
  83. } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
  84. cause = "call to kuser_cmpxchg";
  85. } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
  86. cause = "call to kuser_memory_barrier";
  87. } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
  88. cause = "call to kuser_cmpxchg64";
  89. }
  90. } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
  91. unwindstack::MapInfo* map_info = maps->Find(reinterpret_cast<uint64_t>(si->si_addr));
  92. if (map_info != nullptr && map_info->flags == PROT_EXEC) {
  93. cause = "execute-only (no-read) memory access error; likely due to data in .text.";
  94. }
  95. } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
  96. cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
  97. si->si_syscall);
  98. }
  99. if (!cause.empty()) _LOG(log, logtype::HEADER, "Cause: %s\n", cause.c_str());
  100. }
  101. static void dump_signal_info(log_t* log, const ThreadInfo& thread_info,
  102. unwindstack::Memory* process_memory) {
  103. char addr_desc[64]; // ", fault addr 0x1234"
  104. if (signal_has_si_addr(thread_info.siginfo)) {
  105. void* addr = thread_info.siginfo->si_addr;
  106. if (thread_info.siginfo->si_signo == SIGILL) {
  107. uint32_t instruction = {};
  108. process_memory->Read(reinterpret_cast<uint64_t>(addr), &instruction, sizeof(instruction));
  109. snprintf(addr_desc, sizeof(addr_desc), "%p (*pc=%#08x)", addr, instruction);
  110. } else {
  111. snprintf(addr_desc, sizeof(addr_desc), "%p", addr);
  112. }
  113. } else {
  114. snprintf(addr_desc, sizeof(addr_desc), "--------");
  115. }
  116. char sender_desc[32] = {}; // " from pid 1234, uid 666"
  117. if (signal_has_sender(thread_info.siginfo, thread_info.pid)) {
  118. get_signal_sender(sender_desc, sizeof(sender_desc), thread_info.siginfo);
  119. }
  120. _LOG(log, logtype::HEADER, "signal %d (%s), code %d (%s%s), fault addr %s\n",
  121. thread_info.siginfo->si_signo, get_signame(thread_info.siginfo),
  122. thread_info.siginfo->si_code, get_sigcode(thread_info.siginfo), sender_desc, addr_desc);
  123. }
  124. static void dump_thread_info(log_t* log, const ThreadInfo& thread_info) {
  125. // Blacklist logd, logd.reader, logd.writer, logd.auditd, logd.control ...
  126. // TODO: Why is this controlled by thread name?
  127. if (thread_info.thread_name == "logd" ||
  128. android::base::StartsWith(thread_info.thread_name, "logd.")) {
  129. log->should_retrieve_logcat = false;
  130. }
  131. _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s >>> %s <<<\n", thread_info.pid,
  132. thread_info.tid, thread_info.thread_name.c_str(), thread_info.process_name.c_str());
  133. _LOG(log, logtype::HEADER, "uid: %d\n", thread_info.uid);
  134. }
  135. static void dump_stack_segment(log_t* log, unwindstack::Maps* maps, unwindstack::Memory* memory,
  136. uint64_t* sp, size_t words, int label) {
  137. // Read the data all at once.
  138. word_t stack_data[words];
  139. // TODO: Do we need to word align this for crashes caused by a misaligned sp?
  140. // The process_vm_readv implementation of Memory should handle this appropriately?
  141. size_t bytes_read = memory->Read(*sp, stack_data, sizeof(word_t) * words);
  142. words = bytes_read / sizeof(word_t);
  143. std::string line;
  144. for (size_t i = 0; i < words; i++) {
  145. line = " ";
  146. if (i == 0 && label >= 0) {
  147. // Print the label once.
  148. line += StringPrintf("#%02d ", label);
  149. } else {
  150. line += " ";
  151. }
  152. line += StringPrintf("%" PRIPTR " %" PRIPTR, *sp, static_cast<uint64_t>(stack_data[i]));
  153. unwindstack::MapInfo* map_info = maps->Find(stack_data[i]);
  154. if (map_info != nullptr && !map_info->name.empty()) {
  155. line += " " + map_info->name;
  156. std::string func_name;
  157. uint64_t func_offset = 0;
  158. if (map_info->GetFunctionName(stack_data[i], &func_name, &func_offset)) {
  159. line += " (" + func_name;
  160. if (func_offset) {
  161. line += StringPrintf("+%" PRIu64, func_offset);
  162. }
  163. line += ')';
  164. }
  165. }
  166. _LOG(log, logtype::STACK, "%s\n", line.c_str());
  167. *sp += sizeof(word_t);
  168. }
  169. }
  170. static void dump_stack(log_t* log, const std::vector<unwindstack::FrameData>& frames,
  171. unwindstack::Maps* maps, unwindstack::Memory* memory) {
  172. size_t first = 0, last;
  173. for (size_t i = 0; i < frames.size(); i++) {
  174. if (frames[i].sp) {
  175. if (!first) {
  176. first = i+1;
  177. }
  178. last = i;
  179. }
  180. }
  181. if (!first) {
  182. return;
  183. }
  184. first--;
  185. // Dump a few words before the first frame.
  186. uint64_t sp = frames[first].sp - STACK_WORDS * sizeof(word_t);
  187. dump_stack_segment(log, maps, memory, &sp, STACK_WORDS, -1);
  188. #if defined(__LP64__)
  189. static constexpr const char delimiter[] = " ................ ................\n";
  190. #else
  191. static constexpr const char delimiter[] = " ........ ........\n";
  192. #endif
  193. // Dump a few words from all successive frames.
  194. for (size_t i = first; i <= last; i++) {
  195. auto* frame = &frames[i];
  196. if (sp != frame->sp) {
  197. _LOG(log, logtype::STACK, delimiter);
  198. sp = frame->sp;
  199. }
  200. if (i != last) {
  201. // Print stack data up to the stack from the next frame.
  202. size_t words;
  203. uint64_t next_sp = frames[i + 1].sp;
  204. if (next_sp < sp) {
  205. // The next frame is probably using a completely different stack,
  206. // so dump the max from this stack.
  207. words = STACK_WORDS;
  208. } else {
  209. words = (next_sp - sp) / sizeof(word_t);
  210. if (words == 0) {
  211. // The sp is the same as the next frame, print at least
  212. // one line for this frame.
  213. words = 1;
  214. } else if (words > STACK_WORDS) {
  215. words = STACK_WORDS;
  216. }
  217. }
  218. dump_stack_segment(log, maps, memory, &sp, words, i);
  219. } else {
  220. // Print some number of words past the last stack frame since we
  221. // don't know how large the stack is.
  222. dump_stack_segment(log, maps, memory, &sp, STACK_WORDS, i);
  223. }
  224. }
  225. }
  226. static std::string get_addr_string(uint64_t addr) {
  227. std::string addr_str;
  228. #if defined(__LP64__)
  229. addr_str = StringPrintf("%08x'%08x",
  230. static_cast<uint32_t>(addr >> 32),
  231. static_cast<uint32_t>(addr & 0xffffffff));
  232. #else
  233. addr_str = StringPrintf("%08x", static_cast<uint32_t>(addr));
  234. #endif
  235. return addr_str;
  236. }
  237. static void dump_abort_message(log_t* log, unwindstack::Memory* process_memory, uint64_t address) {
  238. if (address == 0) {
  239. return;
  240. }
  241. size_t length;
  242. if (!process_memory->ReadFully(address, &length, sizeof(length))) {
  243. _LOG(log, logtype::HEADER, "Failed to read abort message header: %s\n", strerror(errno));
  244. return;
  245. }
  246. // The length field includes the length of the length field itself.
  247. if (length < sizeof(size_t)) {
  248. _LOG(log, logtype::HEADER, "Abort message header malformed: claimed length = %zd\n", length);
  249. return;
  250. }
  251. length -= sizeof(size_t);
  252. // The abort message should be null terminated already, but reserve a spot for NUL just in case.
  253. std::vector<char> msg(length + 1);
  254. if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
  255. _LOG(log, logtype::HEADER, "Failed to read abort message: %s\n", strerror(errno));
  256. return;
  257. }
  258. _LOG(log, logtype::HEADER, "Abort message: '%s'\n", &msg[0]);
  259. }
  260. static void dump_all_maps(log_t* log, unwindstack::Unwinder* unwinder, uint64_t addr) {
  261. bool print_fault_address_marker = addr;
  262. unwindstack::Maps* maps = unwinder->GetMaps();
  263. _LOG(log, logtype::MAPS,
  264. "\n"
  265. "memory map (%zu entr%s):",
  266. maps->Total(), maps->Total() == 1 ? "y" : "ies");
  267. if (print_fault_address_marker) {
  268. if (maps->Total() != 0 && addr < maps->Get(0)->start) {
  269. _LOG(log, logtype::MAPS, "\n--->Fault address falls at %s before any mapped regions\n",
  270. get_addr_string(addr).c_str());
  271. print_fault_address_marker = false;
  272. } else {
  273. _LOG(log, logtype::MAPS, " (fault address prefixed with --->)\n");
  274. }
  275. } else {
  276. _LOG(log, logtype::MAPS, "\n");
  277. }
  278. std::shared_ptr<unwindstack::Memory>& process_memory = unwinder->GetProcessMemory();
  279. std::string line;
  280. for (auto const& map_info : *maps) {
  281. line = " ";
  282. if (print_fault_address_marker) {
  283. if (addr < map_info->start) {
  284. _LOG(log, logtype::MAPS, "--->Fault address falls at %s between mapped regions\n",
  285. get_addr_string(addr).c_str());
  286. print_fault_address_marker = false;
  287. } else if (addr >= map_info->start && addr < map_info->end) {
  288. line = "--->";
  289. print_fault_address_marker = false;
  290. }
  291. }
  292. line += get_addr_string(map_info->start) + '-' + get_addr_string(map_info->end - 1) + ' ';
  293. if (map_info->flags & PROT_READ) {
  294. line += 'r';
  295. } else {
  296. line += '-';
  297. }
  298. if (map_info->flags & PROT_WRITE) {
  299. line += 'w';
  300. } else {
  301. line += '-';
  302. }
  303. if (map_info->flags & PROT_EXEC) {
  304. line += 'x';
  305. } else {
  306. line += '-';
  307. }
  308. line += StringPrintf(" %8" PRIx64 " %8" PRIx64, map_info->offset,
  309. map_info->end - map_info->start);
  310. bool space_needed = true;
  311. if (!map_info->name.empty()) {
  312. space_needed = false;
  313. line += " " + map_info->name;
  314. std::string build_id = map_info->GetPrintableBuildID();
  315. if (!build_id.empty()) {
  316. line += " (BuildId: " + build_id + ")";
  317. }
  318. }
  319. uint64_t load_bias = map_info->GetLoadBias(process_memory);
  320. if (load_bias != 0) {
  321. if (space_needed) {
  322. line += ' ';
  323. }
  324. line += StringPrintf(" (load bias 0x%" PRIx64 ")", load_bias);
  325. }
  326. _LOG(log, logtype::MAPS, "%s\n", line.c_str());
  327. }
  328. if (print_fault_address_marker) {
  329. _LOG(log, logtype::MAPS, "--->Fault address falls at %s after any mapped regions\n",
  330. get_addr_string(addr).c_str());
  331. }
  332. }
  333. static void print_register_row(log_t* log,
  334. const std::vector<std::pair<std::string, uint64_t>>& registers) {
  335. std::string output;
  336. for (auto& [name, value] : registers) {
  337. output += android::base::StringPrintf(" %-3s %0*" PRIx64, name.c_str(),
  338. static_cast<int>(2 * sizeof(void*)),
  339. static_cast<uint64_t>(value));
  340. }
  341. _LOG(log, logtype::REGISTERS, " %s\n", output.c_str());
  342. }
  343. void dump_registers(log_t* log, unwindstack::Regs* regs) {
  344. // Split lr/sp/pc into their own special row.
  345. static constexpr size_t column_count = 4;
  346. std::vector<std::pair<std::string, uint64_t>> current_row;
  347. std::vector<std::pair<std::string, uint64_t>> special_row;
  348. #if defined(__arm__) || defined(__aarch64__)
  349. static constexpr const char* special_registers[] = {"ip", "lr", "sp", "pc"};
  350. #elif defined(__i386__)
  351. static constexpr const char* special_registers[] = {"ebp", "esp", "eip"};
  352. #elif defined(__x86_64__)
  353. static constexpr const char* special_registers[] = {"rbp", "rsp", "rip"};
  354. #else
  355. static constexpr const char* special_registers[] = {};
  356. #endif
  357. regs->IterateRegisters([log, &current_row, &special_row](const char* name, uint64_t value) {
  358. auto row = &current_row;
  359. for (const char* special_name : special_registers) {
  360. if (strcmp(special_name, name) == 0) {
  361. row = &special_row;
  362. break;
  363. }
  364. }
  365. row->emplace_back(name, value);
  366. if (current_row.size() == column_count) {
  367. print_register_row(log, current_row);
  368. current_row.clear();
  369. }
  370. });
  371. if (!current_row.empty()) {
  372. print_register_row(log, current_row);
  373. }
  374. print_register_row(log, special_row);
  375. }
  376. void dump_memory_and_code(log_t* log, unwindstack::Maps* maps, unwindstack::Memory* memory,
  377. unwindstack::Regs* regs) {
  378. regs->IterateRegisters([log, maps, memory](const char* reg_name, uint64_t reg_value) {
  379. std::string label{"memory near "s + reg_name};
  380. if (maps) {
  381. unwindstack::MapInfo* map_info = maps->Find(reg_value);
  382. if (map_info != nullptr && !map_info->name.empty()) {
  383. label += " (" + map_info->name + ")";
  384. }
  385. }
  386. dump_memory(log, memory, reg_value, label);
  387. });
  388. }
  389. static bool dump_thread(log_t* log, unwindstack::Unwinder* unwinder, const ThreadInfo& thread_info,
  390. uint64_t abort_msg_address, bool primary_thread) {
  391. log->current_tid = thread_info.tid;
  392. if (!primary_thread) {
  393. _LOG(log, logtype::THREAD, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
  394. }
  395. dump_thread_info(log, thread_info);
  396. if (thread_info.siginfo) {
  397. dump_signal_info(log, thread_info, unwinder->GetProcessMemory().get());
  398. dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps());
  399. }
  400. if (primary_thread) {
  401. dump_abort_message(log, unwinder->GetProcessMemory().get(), abort_msg_address);
  402. }
  403. dump_registers(log, thread_info.registers.get());
  404. // Unwind will mutate the registers, so make a copy first.
  405. std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
  406. unwinder->SetRegs(regs_copy.get());
  407. unwinder->Unwind();
  408. if (unwinder->NumFrames() == 0) {
  409. _LOG(log, logtype::THREAD, "Failed to unwind");
  410. } else {
  411. _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
  412. log_backtrace(log, unwinder, " ");
  413. _LOG(log, logtype::STACK, "\nstack:\n");
  414. dump_stack(log, unwinder->frames(), unwinder->GetMaps(), unwinder->GetProcessMemory().get());
  415. }
  416. if (primary_thread) {
  417. unwindstack::Maps* maps = unwinder->GetMaps();
  418. dump_memory_and_code(log, maps, unwinder->GetProcessMemory().get(),
  419. thread_info.registers.get());
  420. if (maps != nullptr) {
  421. uint64_t addr = 0;
  422. siginfo_t* si = thread_info.siginfo;
  423. if (signal_has_si_addr(si)) {
  424. addr = reinterpret_cast<uint64_t>(si->si_addr);
  425. }
  426. dump_all_maps(log, unwinder, addr);
  427. }
  428. }
  429. log->current_tid = log->crashed_tid;
  430. return true;
  431. }
  432. // Reads the contents of the specified log device, filters out the entries
  433. // that don't match the specified pid, and writes them to the tombstone file.
  434. //
  435. // If "tail" is non-zero, log the last "tail" number of lines.
  436. static EventTagMap* g_eventTagMap = NULL;
  437. static void dump_log_file(log_t* log, pid_t pid, const char* filename, unsigned int tail) {
  438. bool first = true;
  439. logger_list* logger_list;
  440. if (!log->should_retrieve_logcat) {
  441. return;
  442. }
  443. logger_list = android_logger_list_open(
  444. android_name_to_log_id(filename), ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, tail, pid);
  445. if (!logger_list) {
  446. ALOGE("Unable to open %s: %s\n", filename, strerror(errno));
  447. return;
  448. }
  449. while (true) {
  450. log_msg log_entry;
  451. ssize_t actual = android_logger_list_read(logger_list, &log_entry);
  452. if (actual < 0) {
  453. if (actual == -EINTR) {
  454. // interrupted by signal, retry
  455. continue;
  456. } else if (actual == -EAGAIN) {
  457. // non-blocking EOF; we're done
  458. break;
  459. } else {
  460. ALOGE("Error while reading log: %s\n", strerror(-actual));
  461. break;
  462. }
  463. } else if (actual == 0) {
  464. ALOGE("Got zero bytes while reading log: %s\n", strerror(errno));
  465. break;
  466. }
  467. // NOTE: if you ALOGV something here, this will spin forever,
  468. // because you will be writing as fast as you're reading. Any
  469. // high-frequency debug diagnostics should just be written to
  470. // the tombstone file.
  471. if (first) {
  472. _LOG(log, logtype::LOGS, "--------- %slog %s\n",
  473. tail ? "tail end of " : "", filename);
  474. first = false;
  475. }
  476. // Msg format is: <priority:1><tag:N>\0<message:N>\0
  477. //
  478. // We want to display it in the same format as "logcat -v threadtime"
  479. // (although in this case the pid is redundant).
  480. char timeBuf[32];
  481. time_t sec = static_cast<time_t>(log_entry.entry.sec);
  482. struct tm tmBuf;
  483. struct tm* ptm;
  484. ptm = localtime_r(&sec, &tmBuf);
  485. strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
  486. if (log_entry.id() == LOG_ID_EVENTS) {
  487. if (!g_eventTagMap) {
  488. g_eventTagMap = android_openEventTagMap(nullptr);
  489. }
  490. AndroidLogEntry e;
  491. char buf[512];
  492. if (android_log_processBinaryLogBuffer(&log_entry.entry_v1, &e, g_eventTagMap, buf,
  493. sizeof(buf)) == 0) {
  494. _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8.*s: %s\n", timeBuf,
  495. log_entry.entry.nsec / 1000000, log_entry.entry.pid, log_entry.entry.tid, 'I',
  496. (int)e.tagLen, e.tag, e.message);
  497. }
  498. continue;
  499. }
  500. char* msg = log_entry.msg();
  501. if (msg == nullptr) {
  502. continue;
  503. }
  504. unsigned char prio = msg[0];
  505. char* tag = msg + 1;
  506. msg = tag + strlen(tag) + 1;
  507. // consume any trailing newlines
  508. char* nl = msg + strlen(msg) - 1;
  509. while (nl >= msg && *nl == '\n') {
  510. *nl-- = '\0';
  511. }
  512. static const char* kPrioChars = "!.VDIWEFS";
  513. char prioChar = (prio < strlen(kPrioChars) ? kPrioChars[prio] : '?');
  514. // Look for line breaks ('\n') and display each text line
  515. // on a separate line, prefixed with the header, like logcat does.
  516. do {
  517. nl = strchr(msg, '\n');
  518. if (nl != nullptr) {
  519. *nl = '\0';
  520. ++nl;
  521. }
  522. _LOG(log, logtype::LOGS, "%s.%03d %5d %5d %c %-8s: %s\n", timeBuf,
  523. log_entry.entry.nsec / 1000000, log_entry.entry.pid, log_entry.entry.tid, prioChar, tag,
  524. msg);
  525. } while ((msg = nl));
  526. }
  527. android_logger_list_free(logger_list);
  528. }
  529. // Dumps the logs generated by the specified pid to the tombstone, from both
  530. // "system" and "main" log devices. Ideally we'd interleave the output.
  531. static void dump_logs(log_t* log, pid_t pid, unsigned int tail) {
  532. if (pid == getpid()) {
  533. // Cowardly refuse to dump logs while we're running in-process.
  534. return;
  535. }
  536. dump_log_file(log, pid, "system", tail);
  537. dump_log_file(log, pid, "main", tail);
  538. }
  539. void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
  540. ucontext_t* ucontext) {
  541. pid_t uid = getuid();
  542. pid_t pid = getpid();
  543. pid_t tid = gettid();
  544. log_t log;
  545. log.current_tid = tid;
  546. log.crashed_tid = tid;
  547. log.tfd = tombstone_fd;
  548. log.amfd_data = nullptr;
  549. char thread_name[16];
  550. char process_name[128];
  551. read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
  552. read_with_default("/proc/self/cmdline", process_name, sizeof(process_name), "<unknown>");
  553. std::unique_ptr<unwindstack::Regs> regs(
  554. unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), ucontext));
  555. std::map<pid_t, ThreadInfo> threads;
  556. threads[gettid()] = ThreadInfo{
  557. .registers = std::move(regs),
  558. .uid = uid,
  559. .tid = tid,
  560. .thread_name = thread_name,
  561. .pid = pid,
  562. .process_name = process_name,
  563. .siginfo = siginfo,
  564. };
  565. unwindstack::UnwinderFromPid unwinder(kMaxFrames, pid);
  566. if (!unwinder.Init(unwindstack::Regs::CurrentArch())) {
  567. LOG(FATAL) << "Failed to init unwinder object.";
  568. }
  569. engrave_tombstone(unique_fd(dup(tombstone_fd)), &unwinder, threads, tid, abort_msg_address,
  570. nullptr, nullptr);
  571. }
  572. void engrave_tombstone(unique_fd output_fd, unwindstack::Unwinder* unwinder,
  573. const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
  574. uint64_t abort_msg_address, OpenFilesList* open_files,
  575. std::string* amfd_data) {
  576. // don't copy log messages to tombstone unless this is a dev device
  577. bool want_logs = android::base::GetBoolProperty("ro.debuggable", false);
  578. log_t log;
  579. log.current_tid = target_thread;
  580. log.crashed_tid = target_thread;
  581. log.tfd = output_fd.get();
  582. log.amfd_data = amfd_data;
  583. _LOG(&log, logtype::HEADER, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
  584. dump_header_info(&log);
  585. dump_timestamp(&log, time(nullptr));
  586. auto it = threads.find(target_thread);
  587. if (it == threads.end()) {
  588. LOG(FATAL) << "failed to find target thread";
  589. }
  590. dump_thread(&log, unwinder, it->second, abort_msg_address, true);
  591. if (want_logs) {
  592. dump_logs(&log, it->second.pid, 50);
  593. }
  594. for (auto& [tid, thread_info] : threads) {
  595. if (tid == target_thread) {
  596. continue;
  597. }
  598. dump_thread(&log, unwinder, thread_info, 0, false);
  599. }
  600. if (open_files) {
  601. _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
  602. dump_open_files_list(&log, *open_files, " ");
  603. }
  604. if (want_logs) {
  605. dump_logs(&log, it->second.pid, 0);
  606. }
  607. }