• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <dlfcn.h>
30 #include <errno.h>
31 #include <inttypes.h>
32 #include <malloc.h>
33 #include <pthread.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <unistd.h>
37 #include <unwind.h>
38 
39 #include "MapData.h"
40 #include "backtrace.h"
41 #include "debug_log.h"
42 
43 #if defined(__LP64__)
44 #define PAD_PTR "016" PRIxPTR
45 #else
46 #define PAD_PTR "08" PRIxPTR
47 #endif
48 
49 typedef struct _Unwind_Context __unwind_context;
50 
51 extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
52 
53 static MapData g_map_data;
54 static const MapEntry* g_current_code_map = nullptr;
55 
find_current_map(__unwind_context * context,void *)56 static _Unwind_Reason_Code find_current_map(__unwind_context* context, void*) {
57   uintptr_t ip = _Unwind_GetIP(context);
58 
59   if (ip == 0) {
60     return _URC_END_OF_STACK;
61   }
62   g_current_code_map = g_map_data.find(ip);
63   return _URC_END_OF_STACK;
64 }
65 
backtrace_startup()66 void backtrace_startup() {
67   _Unwind_Backtrace(find_current_map, nullptr);
68 }
69 
backtrace_shutdown()70 void backtrace_shutdown() {}
71 
72 struct stack_crawl_state_t {
73   uintptr_t* frames;
74   size_t frame_count;
75   size_t cur_frame = 0;
76 
stack_crawl_state_tstack_crawl_state_t77   stack_crawl_state_t(uintptr_t* frames, size_t frame_count)
78       : frames(frames), frame_count(frame_count) {}
79 };
80 
trace_function(__unwind_context * context,void * arg)81 static _Unwind_Reason_Code trace_function(__unwind_context* context, void* arg) {
82   stack_crawl_state_t* state = static_cast<stack_crawl_state_t*>(arg);
83 
84   uintptr_t ip = _Unwind_GetIP(context);
85 
86   // The instruction pointer is pointing at the instruction after the return
87   // call on all architectures.
88   // Modify the pc to point at the real function.
89   if (ip != 0) {
90 #if defined(__arm__)
91     // If the ip is suspiciously low, do nothing to avoid a segfault trying
92     // to access this memory.
93     if (ip >= 4096) {
94       // Check bits [15:11] of the first halfword assuming the instruction
95       // is 32 bits long. If the bits are any of these values, then our
96       // assumption was correct:
97       //  b11101
98       //  b11110
99       //  b11111
100       // Otherwise, this is a 16 bit instruction.
101       uint16_t value = (*reinterpret_cast<uint16_t*>(ip - 2)) >> 11;
102       if (value == 0x1f || value == 0x1e || value == 0x1d) {
103         ip -= 4;
104       } else {
105         ip -= 2;
106       }
107     }
108 #elif defined(__aarch64__)
109     // All instructions are 4 bytes long, skip back one instruction.
110     ip -= 4;
111 #elif defined(__i386__) || defined(__x86_64__)
112     // It's difficult to decode exactly where the previous instruction is,
113     // so subtract 1 to estimate where the instruction lives.
114     ip--;
115 #endif
116 
117     // Do not record the frames that fall in our own shared library.
118     if (g_current_code_map && (ip >= g_current_code_map->start) && ip < g_current_code_map->end) {
119       return _URC_NO_REASON;
120     }
121   }
122 
123   state->frames[state->cur_frame++] = ip;
124   return (state->cur_frame >= state->frame_count) ? _URC_END_OF_STACK : _URC_NO_REASON;
125 }
126 
backtrace_get(uintptr_t * frames,size_t frame_count)127 size_t backtrace_get(uintptr_t* frames, size_t frame_count) {
128   stack_crawl_state_t state(frames, frame_count);
129   _Unwind_Backtrace(trace_function, &state);
130   return state.cur_frame;
131 }
132 
backtrace_string(const uintptr_t * frames,size_t frame_count)133 std::string backtrace_string(const uintptr_t* frames, size_t frame_count) {
134   std::string str;
135 
136   for (size_t frame_num = 0; frame_num < frame_count; frame_num++) {
137     uintptr_t offset = 0;
138     const char* symbol = nullptr;
139 
140     Dl_info info;
141     if (dladdr(reinterpret_cast<void*>(frames[frame_num]), &info) != 0) {
142       offset = reinterpret_cast<uintptr_t>(info.dli_saddr);
143       symbol = info.dli_sname;
144     } else {
145       info.dli_fname = nullptr;
146     }
147 
148     uintptr_t rel_pc = offset;
149     const MapEntry* entry = g_map_data.find(frames[frame_num], &rel_pc);
150 
151     const char* soname = (entry != nullptr) ? entry->name.c_str() : info.dli_fname;
152     if (soname == nullptr) {
153       soname = "<unknown>";
154     }
155 
156     char offset_buf[128];
157     if (entry != nullptr && entry->elf_start_offset != 0) {
158       snprintf(offset_buf, sizeof(offset_buf), " (offset 0x%" PRIxPTR ")", entry->elf_start_offset);
159     } else {
160       offset_buf[0] = '\0';
161     }
162 
163     char buf[1024];
164     if (symbol != nullptr) {
165       char* demangled_name = __cxa_demangle(symbol, nullptr, nullptr, nullptr);
166       const char* name;
167       if (demangled_name != nullptr) {
168         name = demangled_name;
169       } else {
170         name = symbol;
171       }
172       async_safe_format_buffer(buf, sizeof(buf),
173                                "          #%02zd  pc %" PAD_PTR "  %s%s (%s+%" PRIuPTR ")\n",
174                                frame_num, rel_pc, soname, offset_buf, name,
175                                frames[frame_num] - offset);
176       free(demangled_name);
177     } else {
178       async_safe_format_buffer(buf, sizeof(buf), "          #%02zd  pc %" PAD_PTR "  %s%s\n",
179                                frame_num, rel_pc, soname, offset_buf);
180     }
181     str += buf;
182   }
183 
184   return str;
185 }
186 
backtrace_log(const uintptr_t * frames,size_t frame_count)187 void backtrace_log(const uintptr_t* frames, size_t frame_count) {
188   error_log_string(backtrace_string(frames, frame_count).c_str());
189 }
190