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 "debug_stacktrace.h"
30 
31 #include <dlfcn.h>
32 #include <inttypes.h>
33 #include <unistd.h>
34 #include <unwind.h>
35 #include <sys/types.h>
36 
37 #include "debug_mapinfo.h"
38 #include "malloc_debug_disable.h"
39 #include "private/libc_logging.h"
40 
41 #if defined(__LP64__)
42 #define PAD_PTR "016" PRIxPTR
43 #else
44 #define PAD_PTR "08" PRIxPTR
45 #endif
46 
47 /* depends how the system includes define this */
48 #ifdef HAVE_UNWIND_CONTEXT_STRUCT
49 typedef struct _Unwind_Context __unwind_context;
50 #else
51 typedef _Unwind_Context __unwind_context;
52 #endif
53 
54 static mapinfo_t* g_map_info = NULL;
55 static void* g_demangler;
56 typedef char* (*DemanglerFn)(const char*, char*, size_t*, int*);
57 static DemanglerFn g_demangler_fn = NULL;
58 
backtrace_startup()59 __LIBC_HIDDEN__ void backtrace_startup() {
60   ScopedDisableDebugCalls disable;
61 
62   g_map_info = mapinfo_create(getpid());
63   g_demangler = dlopen("libgccdemangle.so", RTLD_NOW);
64   if (g_demangler != NULL) {
65     void* sym = dlsym(g_demangler, "__cxa_demangle");
66     g_demangler_fn = reinterpret_cast<DemanglerFn>(sym);
67   }
68 }
69 
backtrace_shutdown()70 __LIBC_HIDDEN__ void backtrace_shutdown() {
71   ScopedDisableDebugCalls disable;
72 
73   mapinfo_destroy(g_map_info);
74   dlclose(g_demangler);
75 }
76 
demangle(const char * symbol)77 static char* demangle(const char* symbol) {
78   if (g_demangler_fn == NULL) {
79     return NULL;
80   }
81   return (*g_demangler_fn)(symbol, NULL, NULL, NULL);
82 }
83 
84 struct stack_crawl_state_t {
85   uintptr_t* frames;
86   size_t frame_count;
87   size_t max_depth;
88   bool have_skipped_self;
89 
stack_crawl_state_tstack_crawl_state_t90   stack_crawl_state_t(uintptr_t* frames, size_t max_depth)
91       : frames(frames), frame_count(0), max_depth(max_depth), have_skipped_self(false) {
92   }
93 };
94 
trace_function(__unwind_context * context,void * arg)95 static _Unwind_Reason_Code trace_function(__unwind_context* context, void* arg) {
96   stack_crawl_state_t* state = static_cast<stack_crawl_state_t*>(arg);
97 
98   uintptr_t ip = _Unwind_GetIP(context);
99 
100   // The first stack frame is get_backtrace itself. Skip it.
101   if (ip != 0 && !state->have_skipped_self) {
102     state->have_skipped_self = true;
103     return _URC_NO_REASON;
104   }
105 
106 #if defined(__arm__)
107   /*
108    * The instruction pointer is pointing at the instruction after the bl(x), and
109    * the _Unwind_Backtrace routine already masks the Thumb mode indicator (LSB
110    * in PC). So we need to do a quick check here to find out if the previous
111    * instruction is a Thumb-mode BLX(2). If so subtract 2 otherwise 4 from PC.
112    */
113   if (ip != 0) {
114     short* ptr = reinterpret_cast<short*>(ip);
115     // Thumb BLX(2)
116     if ((*(ptr-1) & 0xff80) == 0x4780) {
117       ip -= 2;
118     } else {
119       ip -= 4;
120     }
121   }
122 #endif
123 
124   state->frames[state->frame_count++] = ip;
125   return (state->frame_count >= state->max_depth) ? _URC_END_OF_STACK : _URC_NO_REASON;
126 }
127 
get_backtrace(uintptr_t * frames,size_t max_depth)128 __LIBC_HIDDEN__ int get_backtrace(uintptr_t* frames, size_t max_depth) {
129   ScopedDisableDebugCalls disable;
130 
131   stack_crawl_state_t state(frames, max_depth);
132   _Unwind_Backtrace(trace_function, &state);
133   return state.frame_count;
134 }
135 
log_backtrace(uintptr_t * frames,size_t frame_count)136 __LIBC_HIDDEN__ void log_backtrace(uintptr_t* frames, size_t frame_count) {
137   ScopedDisableDebugCalls disable;
138 
139   uintptr_t self_bt[16];
140   if (frames == NULL) {
141     frame_count = get_backtrace(self_bt, 16);
142     frames = self_bt;
143   }
144 
145   __libc_format_log(ANDROID_LOG_ERROR, "libc",
146                     "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
147 
148   for (size_t i = 0 ; i < frame_count; ++i) {
149     uintptr_t offset = 0;
150     const char* symbol = NULL;
151 
152     Dl_info info;
153     if (dladdr((void*) frames[i], &info) != 0) {
154       offset = reinterpret_cast<uintptr_t>(info.dli_saddr);
155       symbol = info.dli_sname;
156     }
157 
158     uintptr_t rel_pc = offset;
159     const mapinfo_t* mi = (g_map_info != NULL) ? mapinfo_find(g_map_info, frames[i], &rel_pc) : NULL;
160     const char* soname = (mi != NULL) ? mi->name : info.dli_fname;
161     if (soname == NULL) {
162       soname = "<unknown>";
163     }
164     if (symbol != NULL) {
165       // TODO: we might need a flag to say whether it's safe to allocate (demangling allocates).
166       char* demangled_symbol = demangle(symbol);
167       const char* best_name = (demangled_symbol != NULL) ? demangled_symbol : symbol;
168 
169       __libc_format_log(ANDROID_LOG_ERROR, "libc",
170                         "          #%02zd  pc %" PAD_PTR "  %s (%s+%" PRIuPTR ")",
171                         i, rel_pc, soname, best_name, frames[i] - offset);
172 
173       free(demangled_symbol);
174     } else {
175       __libc_format_log(ANDROID_LOG_ERROR, "libc",
176                         "          #%02zd  pc %" PAD_PTR "  %s",
177                         i, rel_pc, soname);
178     }
179   }
180 }
181