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