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