backtrace.cpp revision 63860cb8fd1adf3f679b9b4ad876323a8d65cd9d
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 "backtrace.h"
40#include "debug_disable.h"
41#include "debug_log.h"
42#include "MapData.h"
43
44#if defined(__LP64__)
45#define PAD_PTR "016" PRIxPTR
46#else
47#define PAD_PTR "08" PRIxPTR
48#endif
49
50typedef struct _Unwind_Context __unwind_context;
51
52extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
53
54static MapData* g_map_data = nullptr;
55static const MapEntry* g_current_code_map = nullptr;
56
57static _Unwind_Reason_Code find_current_map(__unwind_context* context, void*) {
58  uintptr_t ip = _Unwind_GetIP(context);
59
60  if (ip == 0) {
61    return _URC_END_OF_STACK;
62  }
63  g_current_code_map = g_map_data->find(ip);
64  return _URC_END_OF_STACK;
65}
66
67void backtrace_startup() {
68  ScopedDisableDebugCalls disable;
69
70  g_map_data = MapData::Create();
71  if (g_map_data) {
72    _Unwind_Backtrace(find_current_map, nullptr);
73  }
74}
75
76void backtrace_shutdown() {
77  ScopedDisableDebugCalls disable;
78
79  delete g_map_data;
80  g_map_data = nullptr;
81}
82
83struct stack_crawl_state_t {
84  uintptr_t* frames;
85  size_t frame_count;
86  size_t cur_frame = 0;
87
88  stack_crawl_state_t(uintptr_t* frames, size_t frame_count)
89      : frames(frames), frame_count(frame_count) {}
90};
91
92static _Unwind_Reason_Code trace_function(__unwind_context* context, void* arg) {
93  stack_crawl_state_t* state = static_cast<stack_crawl_state_t*>(arg);
94
95  uintptr_t ip = _Unwind_GetIP(context);
96
97  // The instruction pointer is pointing at the instruction after the return
98  // call on all architectures.
99  // Modify the pc to point at the real function.
100  if (ip != 0) {
101#if defined(__arm__)
102    // If the ip is suspiciously low, do nothing to avoid a segfault trying
103    // to access this memory.
104    if (ip >= 4096) {
105      // Check bits [15:11] of the first halfword assuming the instruction
106      // is 32 bits long. If the bits are any of these values, then our
107      // assumption was correct:
108      //  b11101
109      //  b11110
110      //  b11111
111      // Otherwise, this is a 16 bit instruction.
112      uint16_t value = (*reinterpret_cast<uint16_t*>(ip - 2)) >> 11;
113      if (value == 0x1f || value == 0x1e || value == 0x1d) {
114        ip -= 4;
115      } else {
116        ip -= 2;
117      }
118    }
119#elif defined(__aarch64__)
120    // All instructions are 4 bytes long, skip back one instruction.
121    ip -= 4;
122#elif defined(__i386__) || defined(__x86_64__)
123    // It's difficult to decode exactly where the previous instruction is,
124    // so subtract 1 to estimate where the instruction lives.
125    ip--;
126#endif
127
128    // Do not record the frames that fall in our own shared library.
129    if (g_current_code_map && (ip >= g_current_code_map->start) && ip < g_current_code_map->end) {
130      return _URC_NO_REASON;
131    }
132  }
133
134  state->frames[state->cur_frame++] = ip;
135  return (state->cur_frame >= state->frame_count) ? _URC_END_OF_STACK : _URC_NO_REASON;
136}
137
138size_t backtrace_get(uintptr_t* frames, size_t frame_count) {
139  ScopedDisableDebugCalls disable;
140
141  stack_crawl_state_t state(frames, frame_count);
142  _Unwind_Backtrace(trace_function, &state);
143  return state.cur_frame;
144}
145
146void backtrace_log(uintptr_t* frames, size_t frame_count) {
147  ScopedDisableDebugCalls disable;
148
149  for (size_t frame_num = 0; frame_num < frame_count; frame_num++) {
150    uintptr_t offset = 0;
151    const char* symbol = nullptr;
152
153    Dl_info info;
154    if (dladdr(reinterpret_cast<void*>(frames[frame_num]), &info) != 0) {
155      offset = reinterpret_cast<uintptr_t>(info.dli_saddr);
156      symbol = info.dli_sname;
157    }
158
159    uintptr_t rel_pc = offset;
160    const MapEntry* entry = nullptr;
161    if (g_map_data) {
162      entry = g_map_data->find(frames[frame_num], &rel_pc);
163    }
164    const char* soname = (entry != nullptr) ? entry->name.c_str() : info.dli_fname;
165    if (soname == nullptr) {
166      soname = "<unknown>";
167    }
168    if (symbol != nullptr) {
169      char* demangled_symbol = __cxa_demangle(symbol, nullptr, nullptr, nullptr);
170      const char* best_name = (demangled_symbol != nullptr) ? demangled_symbol : symbol;
171
172      error_log("          #%02zd  pc %" PAD_PTR "  %s (%s+%" PRIuPTR ")",
173                frame_num, rel_pc, soname, best_name, frames[frame_num] - offset);
174      free(demangled_symbol);
175    } else {
176      error_log("          #%02zd  pc %" PAD_PTR "  %s", frame_num, rel_pc, soname);
177    }
178  }
179}
180