1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/debug/stack_trace.h"
6 
7 #include <android/log.h>
8 #include <stddef.h>
9 #include <unwind.h>
10 
11 #include <algorithm>
12 #include <ostream>
13 
14 #include "base/debug/proc_maps_linux.h"
15 #include "base/stl_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/threading/thread_restrictions.h"
18 
19 #ifdef __LP64__
20 #define FMT_ADDR  "0x%016lx"
21 #else
22 #define FMT_ADDR  "0x%08x"
23 #endif
24 
25 namespace {
26 
27 struct StackCrawlState {
StackCrawlState__anon8509b2f80111::StackCrawlState28   StackCrawlState(uintptr_t* frames, size_t max_depth)
29       : frames(frames),
30         frame_count(0),
31         max_depth(max_depth),
32         have_skipped_self(false) {}
33 
34   uintptr_t* frames;
35   size_t frame_count;
36   size_t max_depth;
37   bool have_skipped_self;
38 };
39 
TraceStackFrame(_Unwind_Context * context,void * arg)40 _Unwind_Reason_Code TraceStackFrame(_Unwind_Context* context, void* arg) {
41   StackCrawlState* state = static_cast<StackCrawlState*>(arg);
42   uintptr_t ip = _Unwind_GetIP(context);
43 
44   // The first stack frame is this function itself.  Skip it.
45   if (ip != 0 && !state->have_skipped_self) {
46     state->have_skipped_self = true;
47     return _URC_NO_REASON;
48   }
49 
50   state->frames[state->frame_count++] = ip;
51   if (state->frame_count >= state->max_depth)
52     return _URC_END_OF_STACK;
53   return _URC_NO_REASON;
54 }
55 
EndsWith(const std::string & s,const std::string & suffix)56 bool EndsWith(const std::string& s, const std::string& suffix) {
57   return s.size() >= suffix.size() &&
58          s.substr(s.size() - suffix.size(), suffix.size()) == suffix;
59 }
60 
61 }  // namespace
62 
63 namespace base {
64 namespace debug {
65 
EnableInProcessStackDumping()66 bool EnableInProcessStackDumping() {
67   // When running in an application, our code typically expects SIGPIPE
68   // to be ignored.  Therefore, when testing that same code, it should run
69   // with SIGPIPE ignored as well.
70   // TODO(phajdan.jr): De-duplicate this SIGPIPE code.
71   struct sigaction action;
72   memset(&action, 0, sizeof(action));
73   action.sa_handler = SIG_IGN;
74   sigemptyset(&action.sa_mask);
75   return (sigaction(SIGPIPE, &action, NULL) == 0);
76 }
77 
CollectStackTrace(void ** trace,size_t count)78 size_t CollectStackTrace(void** trace, size_t count) {
79   StackCrawlState state(reinterpret_cast<uintptr_t*>(trace), count);
80   _Unwind_Backtrace(&TraceStackFrame, &state);
81   return state.frame_count;
82 }
83 
PrintWithPrefix(const char * prefix_string) const84 void StackTrace::PrintWithPrefix(const char* prefix_string) const {
85   std::string backtrace = ToStringWithPrefix(prefix_string);
86   __android_log_write(ANDROID_LOG_ERROR, "chromium", backtrace.c_str());
87 }
88 
89 // NOTE: Native libraries in APKs are stripped before installing. Print out the
90 // relocatable address and library names so host computers can use tools to
91 // symbolize and demangle (e.g., addr2line, c++filt).
OutputToStreamWithPrefix(std::ostream * os,const char * prefix_string) const92 void StackTrace::OutputToStreamWithPrefix(std::ostream* os,
93                                           const char* prefix_string) const {
94   std::string proc_maps;
95   std::vector<MappedMemoryRegion> regions;
96   // Allow IO to read /proc/self/maps. Reading this file doesn't hit the disk
97   // since it lives in procfs, and this is currently used to print a stack trace
98   // on fatal log messages in debug builds only. If the restriction is enabled
99   // then it will recursively trigger fatal failures when this enters on the
100   // UI thread.
101   base::ThreadRestrictions::ScopedAllowIO allow_io;
102   if (!ReadProcMaps(&proc_maps)) {
103     __android_log_write(
104         ANDROID_LOG_ERROR, "chromium", "Failed to read /proc/self/maps");
105   } else if (!ParseProcMaps(proc_maps, &regions)) {
106     __android_log_write(
107         ANDROID_LOG_ERROR, "chromium", "Failed to parse /proc/self/maps");
108   }
109 
110   for (size_t i = 0; i < count_; ++i) {
111     // Subtract one as return address of function may be in the next
112     // function when a function is annotated as noreturn.
113     uintptr_t address = reinterpret_cast<uintptr_t>(trace_[i]) - 1;
114 
115     std::vector<MappedMemoryRegion>::iterator iter = regions.begin();
116     while (iter != regions.end()) {
117       if (address >= iter->start && address < iter->end &&
118           !iter->path.empty()) {
119         break;
120       }
121       ++iter;
122     }
123 
124     if (prefix_string)
125       *os << prefix_string;
126 
127     // Adjust absolute address to be an offset within the mapped region, to
128     // match the format dumped by Android's crash output.
129     if (iter != regions.end()) {
130       address -= iter->start;
131     }
132 
133     // The format below intentionally matches that of Android's debuggerd
134     // output. This simplifies decoding by scripts such as stack.py.
135     *os << base::StringPrintf("#%02zd pc " FMT_ADDR " ", i, address);
136 
137     if (iter != regions.end()) {
138       *os << base::StringPrintf("%s", iter->path.c_str());
139       if (EndsWith(iter->path, ".apk")) {
140         *os << base::StringPrintf(" (offset 0x%llx)", iter->offset);
141       }
142     } else {
143       *os << "<unknown>";
144     }
145 
146     *os << "\n";
147   }
148 }
149 
150 }  // namespace debug
151 }  // namespace base
152