24 #ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
25 #define H_6B9572DA_A64B_49E6_B234_051480991C89
28 #error "It's not going to compile without a C++ compiler..."
31 #if defined(BACKWARD_CXX11)
32 #elif defined(BACKWARD_CXX98)
34 #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)
35 #define BACKWARD_CXX11
36 #define BACKWARD_ATLEAST_CXX11
37 #define BACKWARD_ATLEAST_CXX98
38 #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
39 #define BACKWARD_ATLEAST_CXX17
42 #define BACKWARD_CXX98
43 #define BACKWARD_ATLEAST_CXX98
61 #if defined(BACKWARD_SYSTEM_LINUX)
62 #elif defined(BACKWARD_SYSTEM_DARWIN)
63 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
64 #elif defined(BACKWARD_SYSTEM_WINDOWS)
66 #if defined(__linux) || defined(__linux__)
67 #define BACKWARD_SYSTEM_LINUX
68 #elif defined(__APPLE__)
69 #define BACKWARD_SYSTEM_DARWIN
71 #define BACKWARD_SYSTEM_WINDOWS
73 #define BACKWARD_SYSTEM_UNKNOWN
77 #define NOINLINE __attribute__((noinline))
96 #if defined(BACKWARD_SYSTEM_LINUX)
124 #if BACKWARD_HAS_UNWIND == 1
125 #elif BACKWARD_HAS_LIBUNWIND == 1
126 #elif BACKWARD_HAS_BACKTRACE == 1
128 #undef BACKWARD_HAS_UNWIND
129 #define BACKWARD_HAS_UNWIND 1
130 #undef BACKWARD_HAS_LIBUNWIND
131 #define BACKWARD_HAS_LIBUNWIND 0
132 #undef BACKWARD_HAS_BACKTRACE
133 #define BACKWARD_HAS_BACKTRACE 0
185 #if BACKWARD_HAS_DW == 1
186 #elif BACKWARD_HAS_BFD == 1
187 #elif BACKWARD_HAS_DWARF == 1
188 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
190 #undef BACKWARD_HAS_DW
191 #define BACKWARD_HAS_DW 0
192 #undef BACKWARD_HAS_BFD
193 #define BACKWARD_HAS_BFD 0
194 #undef BACKWARD_HAS_DWARF
195 #define BACKWARD_HAS_DWARF 0
196 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
197 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
206 #define _Unwind_Ptr _Unwind_Ptr_Custom
213 #include <sys/stat.h>
217 #if BACKWARD_HAS_BFD == 1
224 #ifndef PACKAGE_VERSION
225 #define PACKAGE_VERSION
237 #if BACKWARD_HAS_DW == 1
239 #include <elfutils/libdw.h>
240 #include <elfutils/libdwfl.h>
243 #if BACKWARD_HAS_DWARF == 1
246 #include <libdwarf.h>
258 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
260 #include <execinfo.h>
263 #endif // defined(BACKWARD_SYSTEM_LINUX)
265 #if defined(BACKWARD_SYSTEM_DARWIN)
291 #if BACKWARD_HAS_UNWIND == 1
292 #elif BACKWARD_HAS_BACKTRACE == 1
293 #elif BACKWARD_HAS_LIBUNWIND == 1
295 #undef BACKWARD_HAS_UNWIND
296 #define BACKWARD_HAS_UNWIND 1
297 #undef BACKWARD_HAS_BACKTRACE
298 #define BACKWARD_HAS_BACKTRACE 0
299 #undef BACKWARD_HAS_LIBUNWIND
300 #define BACKWARD_HAS_LIBUNWIND 0
314 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
316 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
317 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
324 #include <sys/stat.h>
327 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
328 #include <execinfo.h>
330 #endif // defined(BACKWARD_SYSTEM_DARWIN)
332 #if defined(BACKWARD_SYSTEM_WINDOWS)
334 #include <condition_variable>
339 typedef SSIZE_T ssize_t;
350 #define NOINLINE __declspec(noinline)
353 #pragma comment(lib, "psapi.lib")
354 #pragma comment(lib, "dbghelp.lib")
360 #pragma pack(push, before_imagehlp, 8)
361 #include <imagehlp.h>
362 #pragma pack(pop, before_imagehlp)
365 #undef BACKWARD_HAS_UNWIND
366 #undef BACKWARD_HAS_BACKTRACE
367 #if BACKWARD_HAS_PDB_SYMBOL == 1
369 #undef BACKWARD_HAS_PDB_SYMBOL
370 #define BACKWARD_HAS_PDB_SYMBOL 1
375 #if BACKWARD_HAS_UNWIND == 1
390 #ifdef __CLANG_UNWIND_H
393 #include <inttypes.h>
394 extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *,
int *);
397 #endif // BACKWARD_HAS_UNWIND == 1
399 #if BACKWARD_HAS_LIBUNWIND == 1
400 #define UNW_LOCAL_ONLY
401 #include <libunwind.h>
402 #endif // BACKWARD_HAS_LIBUNWIND == 1
404 #ifdef BACKWARD_ATLEAST_CXX11
405 #include <unordered_map>
409 template <
typename K,
typename V>
struct hashtable {
410 typedef std::unordered_map<K, V>
type;
415 #else // NOT BACKWARD_ATLEAST_CXX11
424 template <
typename T>
const T &
move(
const T &v) {
return v; }
425 template <
typename T> T &
move(T &v) {
return v; }
428 #endif // BACKWARD_ATLEAST_CXX11
432 #if defined(BACKWARD_SYSTEM_WINDOWS)
442 namespace system_tag {
449 #if defined(BACKWARD_SYSTEM_LINUX)
451 #elif defined(BACKWARD_SYSTEM_DARWIN)
453 #elif defined(BACKWARD_SYSTEM_WINDOWS)
455 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
458 #error "May I please get my system defines?"
462 namespace trace_resolver_tag {
463 #if defined(BACKWARD_SYSTEM_LINUX)
467 struct backtrace_symbol;
469 #if BACKWARD_HAS_DW == 1
470 typedef libdw current;
471 #elif BACKWARD_HAS_BFD == 1
472 typedef libbfd current;
473 #elif BACKWARD_HAS_DWARF == 1
474 typedef libdwarf current;
475 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
476 typedef backtrace_symbol current;
478 #error "You shall not pass, until you know what you want."
480 #elif defined(BACKWARD_SYSTEM_DARWIN)
481 struct backtrace_symbol;
483 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
484 typedef backtrace_symbol current;
486 #error "You shall not pass, until you know what you want."
488 #elif defined(BACKWARD_SYSTEM_WINDOWS)
490 #if BACKWARD_HAS_PDB_SYMBOL == 1
491 typedef pdb_symbol current;
493 #error "You shall not pass, until you know what you want."
502 template <
typename T>
struct rm_ptr<T *> {
typedef T
type; };
504 template <
typename T>
struct rm_ptr<const T *> {
typedef const T
type; };
506 template <
typename R,
typename T, R (*F)(T)>
struct deleter {
507 template <
typename U>
void operator()(U &ptr)
const { (*F)(ptr); }
514 template <
typename T,
typename Deleter = deleter<
void,
void *, &::free>>
520 #ifdef BACKWARD_ATLEAST_CXX11
538 #ifdef BACKWARD_ATLEAST_CXX11
563 _empty = !
static_cast<bool>(new_val);
566 operator const dummy *()
const {
570 return reinterpret_cast<const dummy *
>(
_val);
602 static std::string
demangle(
const char *funcname) {
return funcname; }
605 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
607 template <>
struct demangler_impl<system_tag::
current_tag> {
608 demangler_impl() : _demangle_buffer_length(0) {}
610 std::string
demangle(
const char *funcname) {
611 using namespace details;
612 char *result = abi::__cxa_demangle(funcname, _demangle_buffer.get(),
613 &_demangle_buffer_length,
nullptr);
615 _demangle_buffer.update(result);
622 details::handle<char *> _demangle_buffer;
623 size_t _demangle_buffer_length;
626 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
639 std::vector<std::string> out;
644 out.push_back(
s.substr(last, next - last));
645 last = next + delimiter_size;
647 if (last <=
s.length()) {
648 out.push_back(
s.substr(last));
663 explicit Trace(
void *_addr,
size_t _idx) : addr(_addr), idx(_idx) {}
669 std::string
function;
677 return function ==
b.function && filename ==
b.filename &&
678 line ==
b.line && col ==
b.col;
712 size_t size()
const {
return 0; }
715 size_t load_from(
void *,
size_t = 0,
void * =
nullptr,
void * =
nullptr) {
725 : _thread_id(0), _skip(0), _context(
nullptr), _error_addr(
nullptr) {}
733 #ifdef BACKWARD_SYSTEM_LINUX
735 _thread_id =
static_cast<size_t>(syscall(SYS_gettid));
737 _thread_id =
static_cast<size_t>(gettid());
739 if (_thread_id ==
static_cast<size_t>(getpid())) {
744 #elif defined(BACKWARD_SYSTEM_DARWIN)
745 _thread_id =
reinterpret_cast<size_t>(pthread_self());
746 if (pthread_main_np() == 1) {
771 return (_stacktrace.size() >= skip_n_firsts())
772 ? _stacktrace.size() - skip_n_firsts()
779 return Trace(_stacktrace[idx + skip_n_firsts()], idx);
783 return &_stacktrace[skip_n_firsts()];
792 #if BACKWARD_HAS_UNWIND == 1
796 template <
typename F>
class Unwinder {
798 size_t operator()(F &
f,
size_t depth) {
802 _Unwind_Backtrace(&this->backtrace_trampoline,
this);
803 return static_cast<size_t>(_index);
811 static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx,
813 return (
static_cast<Unwinder *
>(
self))->backtrace(ctx);
816 _Unwind_Reason_Code backtrace(_Unwind_Context *ctx) {
817 if (_index >= 0 &&
static_cast<size_t>(_index) >= _depth)
818 return _URC_END_OF_STACK;
820 int ip_before_instruction = 0;
821 uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
823 if (!ip_before_instruction) {
827 ip = std::numeric_limits<uintptr_t>::max();
836 (*_f)(
static_cast<size_t>(_index),
reinterpret_cast<void *
>(ip));
839 return _URC_NO_REASON;
843 template <
typename F>
size_t unwind(F
f,
size_t depth) {
844 Unwinder<F> unwinder;
845 return unwinder(
f, depth);
851 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
854 size_t load_here(
size_t depth = 32,
void *context =
nullptr,
855 void *error_addr =
nullptr) {
857 set_context(context);
858 set_error_addr(error_addr);
862 _stacktrace.resize(depth);
863 size_t trace_cnt = details::unwind(callback(*
this), depth);
864 _stacktrace.resize(trace_cnt);
868 size_t load_from(
void *addr,
size_t depth = 32,
void *context =
nullptr,
869 void *error_addr =
nullptr) {
870 load_here(depth + 8, context, error_addr);
872 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
873 if (_stacktrace[i] == addr) {
879 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
885 StackTraceImpl &
self;
886 callback(StackTraceImpl &_self) : self(_self) {}
888 void operator()(
size_t idx,
void *addr) {
self._stacktrace[idx] = addr; }
892 #elif BACKWARD_HAS_LIBUNWIND == 1
895 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
897 __attribute__((noinline))
size_t load_here(
size_t depth = 32,
898 void *_context =
nullptr,
899 void *_error_addr =
nullptr) {
900 set_context(_context);
901 set_error_addr(_error_addr);
906 _stacktrace.resize(depth + 1);
920 ucontext_t *uctx =
reinterpret_cast<ucontext_t *
>(context());
921 #ifdef REG_RIP // x86_64
922 if (uctx->uc_mcontext.gregs[REG_RIP] ==
923 reinterpret_cast<greg_t
>(error_addr())) {
924 uctx->uc_mcontext.gregs[REG_RIP] =
925 *
reinterpret_cast<size_t *
>(uctx->uc_mcontext.gregs[REG_RSP]);
928 reinterpret_cast<void *
>(uctx->uc_mcontext.gregs[REG_RIP]);
930 ctx = *
reinterpret_cast<unw_context_t *
>(uctx);
931 #elif defined(REG_EIP) // x86_32
932 if (uctx->uc_mcontext.gregs[REG_EIP] ==
933 reinterpret_cast<greg_t
>(error_addr())) {
934 uctx->uc_mcontext.gregs[REG_EIP] =
935 *
reinterpret_cast<size_t *
>(uctx->uc_mcontext.gregs[REG_ESP]);
938 reinterpret_cast<void *
>(uctx->uc_mcontext.gregs[REG_EIP]);
940 ctx = *
reinterpret_cast<unw_context_t *
>(uctx);
941 #elif defined(__arm__)
945 unw_getcontext(&ctx);
946 ctx.regs[UNW_ARM_R0] = uctx->uc_mcontext.arm_r0;
947 ctx.regs[UNW_ARM_R1] = uctx->uc_mcontext.arm_r1;
948 ctx.regs[UNW_ARM_R2] = uctx->uc_mcontext.arm_r2;
949 ctx.regs[UNW_ARM_R3] = uctx->uc_mcontext.arm_r3;
950 ctx.regs[UNW_ARM_R4] = uctx->uc_mcontext.arm_r4;
951 ctx.regs[UNW_ARM_R5] = uctx->uc_mcontext.arm_r5;
952 ctx.regs[UNW_ARM_R6] = uctx->uc_mcontext.arm_r6;
953 ctx.regs[UNW_ARM_R7] = uctx->uc_mcontext.arm_r7;
954 ctx.regs[UNW_ARM_R8] = uctx->uc_mcontext.arm_r8;
955 ctx.regs[UNW_ARM_R9] = uctx->uc_mcontext.arm_r9;
956 ctx.regs[UNW_ARM_R10] = uctx->uc_mcontext.arm_r10;
957 ctx.regs[UNW_ARM_R11] = uctx->uc_mcontext.arm_fp;
958 ctx.regs[UNW_ARM_R12] = uctx->uc_mcontext.arm_ip;
959 ctx.regs[UNW_ARM_R13] = uctx->uc_mcontext.arm_sp;
960 ctx.regs[UNW_ARM_R14] = uctx->uc_mcontext.arm_lr;
961 ctx.regs[UNW_ARM_R15] = uctx->uc_mcontext.arm_pc;
965 if (
reinterpret_cast<unsigned long>(error_addr()) ==
966 uctx->uc_mcontext.arm_pc) {
967 ctx.regs[UNW_ARM_R15] =
968 uctx->uc_mcontext.arm_lr -
sizeof(
unsigned long);
970 _stacktrace[index] =
reinterpret_cast<void *
>(ctx.regs[UNW_ARM_R15]);
972 #elif defined(__APPLE__) && defined(__x86_64__)
973 unw_getcontext(&ctx);
978 ctx.data[0] = uctx->uc_mcontext->__ss.__rax;
979 ctx.data[1] = uctx->uc_mcontext->__ss.__rbx;
980 ctx.data[2] = uctx->uc_mcontext->__ss.__rcx;
981 ctx.data[3] = uctx->uc_mcontext->__ss.__rdx;
982 ctx.data[4] = uctx->uc_mcontext->__ss.__rdi;
983 ctx.data[5] = uctx->uc_mcontext->__ss.__rsi;
984 ctx.data[6] = uctx->uc_mcontext->__ss.__rbp;
985 ctx.data[7] = uctx->uc_mcontext->__ss.__rsp;
986 ctx.data[8] = uctx->uc_mcontext->__ss.__r8;
987 ctx.data[9] = uctx->uc_mcontext->__ss.__r9;
988 ctx.data[10] = uctx->uc_mcontext->__ss.__r10;
989 ctx.data[11] = uctx->uc_mcontext->__ss.__r11;
990 ctx.data[12] = uctx->uc_mcontext->__ss.__r12;
991 ctx.data[13] = uctx->uc_mcontext->__ss.__r13;
992 ctx.data[14] = uctx->uc_mcontext->__ss.__r14;
993 ctx.data[15] = uctx->uc_mcontext->__ss.__r15;
994 ctx.data[16] = uctx->uc_mcontext->__ss.__rip;
999 if (uctx->uc_mcontext->__ss.__rip ==
1000 reinterpret_cast<__uint64_t
>(error_addr())) {
1002 *
reinterpret_cast<__uint64_t *
>(uctx->uc_mcontext->__ss.__rsp);
1004 _stacktrace[index] =
reinterpret_cast<void *
>(ctx.data[16]);
1006 #elif defined(__APPLE__)
1007 unw_getcontext(&ctx)
1010 if (ctx.uc_mcontext->__ss.__eip ==
1011 reinterpret_cast<greg_t
>(error_addr())) {
1012 ctx.uc_mcontext->__ss.__eip = ctx.uc_mcontext->__ss.__esp;
1014 _stacktrace[index] =
1015 reinterpret_cast<void *
>(ctx.uc_mcontext->__ss.__eip);
1020 unw_cursor_t cursor;
1022 #if defined(UNW_INIT_SIGNAL_FRAME)
1023 result = unw_init_local2(&cursor, &ctx, UNW_INIT_SIGNAL_FRAME);
1025 result = unw_init_local(&cursor, &ctx);
1028 unw_getcontext(&ctx);
1030 result = unw_init_local(&cursor, &ctx);
1038 while (index <= depth && unw_step(&cursor) > 0) {
1039 result = unw_get_reg(&cursor, UNW_REG_IP, &ip);
1041 _stacktrace[index] =
reinterpret_cast<void *
>(--ip);
1047 _stacktrace.resize(index + 1);
1052 size_t load_from(
void *addr,
size_t depth = 32,
void *context =
nullptr,
1053 void *error_addr =
nullptr) {
1054 load_here(depth + 8, context, error_addr);
1056 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
1057 if (_stacktrace[i] == addr) {
1059 _stacktrace[i] = (
void *)((uintptr_t)_stacktrace[i]);
1064 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1069 #elif defined(BACKWARD_HAS_BACKTRACE)
1072 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
1075 size_t load_here(
size_t depth = 32,
void *context =
nullptr,
1076 void *error_addr =
nullptr) {
1077 set_context(context);
1078 set_error_addr(error_addr);
1083 _stacktrace.resize(depth + 1);
1084 size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
1085 _stacktrace.resize(trace_cnt);
1090 size_t load_from(
void *addr,
size_t depth = 32,
void *context =
nullptr,
1091 void *error_addr =
nullptr) {
1092 load_here(depth + 8, context, error_addr);
1094 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
1095 if (_stacktrace[i] == addr) {
1097 _stacktrace[i] = (
void *)((uintptr_t)_stacktrace[i] + 1);
1102 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1107 #elif defined(BACKWARD_SYSTEM_WINDOWS)
1110 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
1114 void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; }
1115 void set_context(CONTEXT *ctx) { ctx_ = ctx; }
1116 void set_thread_handle(HANDLE handle) { thd_ = handle; }
1119 size_t load_here(
size_t depth = 32,
void *context =
nullptr,
1120 void *error_addr =
nullptr) {
1121 set_context(
static_cast<CONTEXT*
>(context));
1122 set_error_addr(error_addr);
1131 RtlCaptureContext(ctx_);
1135 thd_ = GetCurrentThread();
1138 HANDLE process = GetCurrentProcess();
1141 memset(&s, 0,
sizeof(STACKFRAME64));
1144 s.AddrStack.Mode = AddrModeFlat;
1145 s.AddrFrame.Mode = AddrModeFlat;
1146 s.AddrPC.Mode = AddrModeFlat;
1148 s.AddrPC.Offset = ctx_->Rip;
1149 s.AddrStack.Offset = ctx_->Rsp;
1150 s.AddrFrame.Offset = ctx_->Rbp;
1152 s.AddrPC.Offset = ctx_->Eip;
1153 s.AddrStack.Offset = ctx_->Esp;
1154 s.AddrFrame.Offset = ctx_->Ebp;
1157 if (!machine_type_) {
1159 machine_type_ = IMAGE_FILE_MACHINE_AMD64;
1161 machine_type_ = IMAGE_FILE_MACHINE_I386;
1168 if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL,
1169 SymFunctionTableAccess64, SymGetModuleBase64, NULL))
1172 if (
s.AddrReturn.Offset == 0)
1175 _stacktrace.push_back(
reinterpret_cast<void *
>(
s.AddrPC.Offset));
1177 if (size() >= depth)
1184 size_t load_from(
void *addr,
size_t depth = 32,
void *context =
nullptr,
1185 void *error_addr =
nullptr) {
1186 load_here(depth + 8, context, error_addr);
1188 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
1189 if (_stacktrace[i] == addr) {
1195 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1200 DWORD machine_type_ = 0;
1202 CONTEXT *ctx_ =
nullptr;
1217 (void)address_count;
1221 load_addresses(st.begin(), (
int)st.size());
1228 return _demangler.demangle(funcname);
1237 #ifdef BACKWARD_SYSTEM_UNKNOWN
1244 #ifdef BACKWARD_SYSTEM_LINUX
1248 TraceResolverLinuxBase()
1249 : argv0_(get_argv0()), exec_path_(read_symlink(
"/proc/self/exe")) {}
1250 std::string resolve_exec_path(Dl_info &symbol_info)
const {
1253 if (symbol_info.dli_fname == argv0_) {
1266 symbol_info.dli_fname =
"/proc/self/exe";
1269 return symbol_info.dli_fname;
1275 std::string exec_path_;
1277 static std::string get_argv0() {
1279 std::ifstream ifs(
"/proc/self/cmdline");
1280 std::getline(ifs, argv0,
'\0');
1284 static std::string read_symlink(std::string
const &symlink_path) {
1290 ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
1294 if (
static_cast<size_t>(len) == path.size()) {
1295 path.resize(path.size() * 2);
1297 path.resize(
static_cast<std::string::size_type
>(len));
1306 template <
typename STACKTRACE_TAG>
class TraceResolverLinuxImpl;
1308 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1311 class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>
1312 :
public TraceResolverLinuxBase {
1314 void load_addresses(
void *
const*addresses,
int address_count)
override {
1315 if (address_count == 0) {
1318 _symbols.reset(backtrace_symbols(addresses, address_count));
1321 ResolvedTrace
resolve(ResolvedTrace trace)
override {
1322 char *filename = _symbols[trace.idx];
1323 char *funcname = filename;
1324 while (*funcname && *funcname !=
'(') {
1327 trace.object_filename.assign(filename,
1333 char *funcname_end = funcname;
1334 while (*funcname_end && *funcname_end !=
')' && *funcname_end !=
'+') {
1337 *funcname_end =
'\0';
1338 trace.object_function = this->demangle(funcname);
1339 trace.source.function = trace.object_function;
1345 details::handle<char **> _symbols;
1348 #endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1350 #if BACKWARD_HAS_BFD == 1
1353 class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>
1354 :
public TraceResolverLinuxBase {
1356 TraceResolverLinuxImpl() : _bfd_loaded(false) {}
1358 ResolvedTrace
resolve(ResolvedTrace trace)
override {
1359 Dl_info symbol_info;
1364 if (!dladdr(trace.addr, &symbol_info)) {
1379 if (symbol_info.dli_sname) {
1380 trace.object_function = demangle(symbol_info.dli_sname);
1383 if (!symbol_info.dli_fname) {
1387 trace.object_filename = resolve_exec_path(symbol_info);
1388 bfd_fileobject *fobj;
1405 struct stat obj_stat;
1406 struct stat dli_stat;
1407 if (stat(trace.object_filename.c_str(), &obj_stat) == 0 &&
1408 stat(symbol_info.dli_fname, &dli_stat) == 0 &&
1409 obj_stat.st_ino == dli_stat.st_ino) {
1414 fobj = load_object_with_bfd(trace.object_filename);
1422 if (fobj ==
nullptr || !fobj->handle) {
1423 fobj = load_object_with_bfd(symbol_info.dli_fname);
1424 if (!fobj->handle) {
1429 find_sym_result *details_selected;
1436 find_sym_result details_call_site =
1437 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1438 details_selected = &details_call_site;
1440 #if BACKWARD_HAS_UNWIND == 0
1448 find_sym_result details_adjusted_call_site = find_symbol_details(
1449 fobj, (
void *)(uintptr_t(trace.addr) - 1), symbol_info.dli_fbase);
1452 if (details_call_site.found && details_adjusted_call_site.found) {
1454 details_selected = &details_adjusted_call_site;
1455 trace.addr = (
void *)(uintptr_t(trace.addr) - 1);
1458 if (details_selected == &details_call_site && details_call_site.found) {
1463 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1465 #endif // BACKWARD_HAS_UNWIND
1467 if (details_selected->found) {
1468 if (details_selected->filename) {
1469 trace.source.filename = details_selected->filename;
1471 trace.source.line = details_selected->line;
1473 if (details_selected->funcname) {
1479 trace.source.function = demangle(details_selected->funcname);
1481 if (!symbol_info.dli_sname) {
1485 trace.object_function = trace.source.function;
1492 trace.inliners = backtrace_inliners(fobj, *details_selected);
1495 if (trace.inliners.size() == 0) {
1514 if (symbol_info.dli_saddr) {
1515 find_sym_result details = find_symbol_details(fobj,
1516 symbol_info.dli_saddr,
1517 symbol_info.dli_fbase);
1519 if (details.found) {
1520 ResolvedTrace::SourceLoc diy_inliner;
1521 diy_inliner.line = details.line;
1522 if (details.filename) {
1523 diy_inliner.filename = details.filename;
1525 if (details.funcname) {
1526 diy_inliner.function = demangle(details.funcname);
1528 diy_inliner.function = trace.source.function;
1530 if (diy_inliner != trace.source) {
1531 trace.inliners.push_back(diy_inliner);
1545 typedef details::handle<bfd *,
1546 details::deleter<bfd_boolean, bfd *, &bfd_close>>
1549 typedef details::handle<asymbol **> bfd_symtab_t;
1551 struct bfd_fileobject {
1552 bfd_handle_t handle;
1554 bfd_symtab_t symtab;
1555 bfd_symtab_t dynamic_symtab;
1559 fobj_bfd_map_t _fobj_bfd_map;
1561 bfd_fileobject *load_object_with_bfd(
const std::string &filename_object) {
1562 using namespace details;
1565 using namespace details;
1570 fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object);
1571 if (it != _fobj_bfd_map.end()) {
1576 bfd_fileobject *r = &_fobj_bfd_map[filename_object];
1579 bfd_handle_t bfd_handle;
1581 int fd = open(filename_object.c_str(), O_RDONLY);
1582 bfd_handle.reset(bfd_fdopenr(filename_object.c_str(),
"default", fd));
1588 if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
1592 if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
1596 ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get());
1598 ssize_t dyn_symtab_storage_size =
1599 bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
1601 if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
1605 bfd_symtab_t symtab, dynamic_symtab;
1606 ssize_t symcount = 0, dyn_symcount = 0;
1608 if (symtab_storage_size > 0) {
1609 symtab.reset(
static_cast<bfd_symbol **
>(
1610 malloc(
static_cast<size_t>(symtab_storage_size))));
1611 symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get());
1614 if (dyn_symtab_storage_size > 0) {
1615 dynamic_symtab.reset(
static_cast<bfd_symbol **
>(
1616 malloc(
static_cast<size_t>(dyn_symtab_storage_size))));
1617 dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(),
1618 dynamic_symtab.get());
1621 if (symcount <= 0 && dyn_symcount <= 0) {
1625 r->handle =
move(bfd_handle);
1626 r->symtab =
move(symtab);
1627 r->dynamic_symtab =
move(dynamic_symtab);
1631 struct find_sym_result {
1633 const char *filename;
1634 const char *funcname;
1638 struct find_sym_context {
1639 TraceResolverLinuxImpl *
self;
1640 bfd_fileobject *fobj;
1643 find_sym_result result;
1646 find_sym_result find_symbol_details(bfd_fileobject *fobj,
void *addr,
1648 find_sym_context context;
1649 context.self =
this;
1650 context.fobj = fobj;
1651 context.addr = addr;
1652 context.base_addr = base_addr;
1653 context.result.found =
false;
1654 bfd_map_over_sections(fobj->handle.get(), &find_in_section_trampoline,
1655 static_cast<void *
>(&context));
1656 return context.result;
1659 static void find_in_section_trampoline(bfd *, asection *section,
void *data) {
1660 find_sym_context *context =
static_cast<find_sym_context *
>(data);
1661 context->self->find_in_section(
1662 reinterpret_cast<bfd_vma
>(context->addr),
1663 reinterpret_cast<bfd_vma
>(context->base_addr), context->fobj, section,
1667 void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject *fobj,
1668 asection *section, find_sym_result &result) {
1672 #ifdef bfd_get_section_flags
1673 if ((bfd_get_section_flags(fobj->handle.get(), section) & SEC_ALLOC) == 0)
1675 if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
1679 #ifdef bfd_get_section_vma
1680 bfd_vma sec_addr = bfd_get_section_vma(fobj->handle.get(), section);
1682 bfd_vma sec_addr = bfd_section_vma(section);
1684 #ifdef bfd_get_section_size
1685 bfd_size_type size = bfd_get_section_size(section);
1687 bfd_size_type size = bfd_section_size(section);
1691 if (addr < sec_addr || addr >= sec_addr + size) {
1693 if (addr < sec_addr || addr >= sec_addr + size) {
1698 #if defined(__clang__)
1699 #pragma clang diagnostic push
1700 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1702 if (!result.found && fobj->symtab) {
1703 result.found = bfd_find_nearest_line(
1704 fobj->handle.get(), section, fobj->symtab.get(), addr - sec_addr,
1705 &result.filename, &result.funcname, &result.line);
1708 if (!result.found && fobj->dynamic_symtab) {
1709 result.found = bfd_find_nearest_line(
1710 fobj->handle.get(), section, fobj->dynamic_symtab.get(),
1711 addr - sec_addr, &result.filename, &result.funcname, &result.line);
1713 #if defined(__clang__)
1714 #pragma clang diagnostic pop
1719 backtrace_inliners(bfd_fileobject *fobj, find_sym_result previous_result) {
1723 while (previous_result.found) {
1724 find_sym_result result;
1725 result.found = bfd_find_inliner_info(fobj->handle.get(), &result.filename,
1726 &result.funcname, &result.line);
1736 ResolvedTrace::SourceLoc src_loc;
1737 src_loc.line = result.line;
1738 if (result.filename) {
1739 src_loc.filename = result.filename;
1741 if (result.funcname) {
1742 src_loc.function = demangle(result.funcname);
1744 results.push_back(src_loc);
1746 previous_result = result;
1751 bool cstrings_eq(
const char *a,
const char *
b) {
1755 return strcmp(a,
b) == 0;
1758 #endif // BACKWARD_HAS_BFD == 1
1760 #if BACKWARD_HAS_DW == 1
1763 class TraceResolverLinuxImpl<trace_resolver_tag::libdw>
1764 :
public TraceResolverLinuxBase {
1766 TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {}
1768 ResolvedTrace
resolve(ResolvedTrace trace)
override {
1769 using namespace details;
1771 Dwarf_Addr trace_addr = (Dwarf_Addr)trace.addr;
1773 if (!_dwfl_handle_initialized) {
1775 _dwfl_cb.reset(
new Dwfl_Callbacks);
1776 _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
1777 _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
1778 _dwfl_cb->debuginfo_path = 0;
1780 _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
1781 _dwfl_handle_initialized =
true;
1783 if (!_dwfl_handle) {
1788 dwfl_report_begin(_dwfl_handle.get());
1789 int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid());
1790 dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
1796 if (!_dwfl_handle) {
1803 Dwfl_Module *mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
1807 const char *module_name = dwfl_module_info(mod, 0, 0, 0, 0, 0, 0, 0);
1809 trace.object_filename = module_name;
1816 const char *sym_name = dwfl_module_addrname(mod, trace_addr);
1818 trace.object_function = demangle(sym_name);
1828 Dwarf_Addr mod_bias = 0;
1829 Dwarf_Die *cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias);
1843 while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) {
1846 find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem);
1855 #ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1862 Dwarf_Addr cfi_bias;
1863 Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias);
1866 while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) {
1867 if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
1875 handle<Dwarf_Frame *> frame;
1876 dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
1893 Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
1896 const char *srcfile = dwarf_linesrc(srcloc, 0, 0);
1898 trace.source.filename = srcfile;
1900 int line = 0, col = 0;
1901 dwarf_lineno(srcloc, &line);
1902 dwarf_linecol(srcloc, &col);
1903 trace.source.line = line;
1904 trace.source.col = col;
1907 deep_first_search_by_pc(cudie, trace_addr - mod_bias,
1908 inliners_search_cb(trace));
1909 if (trace.source.function.size() == 0) {
1911 trace.source.function = trace.object_function;
1918 typedef details::handle<Dwfl *, details::deleter<void, Dwfl *, &dwfl_end>>
1920 details::handle<Dwfl_Callbacks *, details::default_delete<Dwfl_Callbacks *>>
1922 dwfl_handle_t _dwfl_handle;
1923 bool _dwfl_handle_initialized;
1927 struct inliners_search_cb {
1928 void operator()(Dwarf_Die *die) {
1929 switch (dwarf_tag(die)) {
1931 case DW_TAG_subprogram:
1932 if ((name = dwarf_diename(die))) {
1933 trace.source.function = name;
1937 case DW_TAG_inlined_subroutine:
1938 ResolvedTrace::SourceLoc sloc;
1939 Dwarf_Attribute attr_mem;
1941 if ((name = dwarf_diename(die))) {
1942 sloc.function = name;
1944 if ((name = die_call_file(die))) {
1945 sloc.filename = name;
1948 Dwarf_Word line = 0, col = 0;
1949 dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line);
1950 dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col);
1951 sloc.line = (unsigned)line;
1952 sloc.col = (unsigned)col;
1954 trace.inliners.push_back(sloc);
1958 ResolvedTrace &trace;
1959 inliners_search_cb(ResolvedTrace &t) : trace(t) {}
1962 static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) {
1963 Dwarf_Addr low, high;
1966 if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) {
1967 if (dwarf_lowpc(die, &low) != 0) {
1970 if (dwarf_highpc(die, &high) != 0) {
1971 Dwarf_Attribute attr_mem;
1972 Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
1974 if (dwarf_formudata(attr, &value) != 0) {
1979 return pc >= low && pc < high;
1984 ptrdiff_t offset = 0;
1985 while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
1986 if (pc >= low && pc < high) {
1993 static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
1994 Dwarf_Die *result) {
1995 if (dwarf_child(parent_die, result) != 0) {
1999 Dwarf_Die *die = result;
2001 switch (dwarf_tag(die)) {
2002 case DW_TAG_subprogram:
2003 case DW_TAG_inlined_subroutine:
2004 if (die_has_pc(die, pc)) {
2008 bool declaration =
false;
2009 Dwarf_Attribute attr_mem;
2010 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
2017 Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem);
2023 }
while (dwarf_siblingof(die, result) == 0);
2027 template <
typename CB>
2028 static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
2031 if (dwarf_child(parent_die, &die_mem) != 0) {
2035 bool branch_has_pc =
false;
2036 Dwarf_Die *die = &die_mem;
2038 bool declaration =
false;
2039 Dwarf_Attribute attr_mem;
2040 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
2047 branch_has_pc = deep_first_search_by_pc(die, pc, cb);
2049 if (!branch_has_pc) {
2050 branch_has_pc = die_has_pc(die, pc);
2052 if (branch_has_pc) {
2055 }
while (dwarf_siblingof(die, &die_mem) == 0);
2056 return branch_has_pc;
2059 static const char *die_call_file(Dwarf_Die *die) {
2060 Dwarf_Attribute attr_mem;
2061 Dwarf_Word file_idx = 0;
2063 dwarf_formudata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx);
2065 if (file_idx == 0) {
2070 Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0);
2075 Dwarf_Files *files = 0;
2077 dwarf_getsrcfiles(cudie, &files, &nfiles);
2082 return dwarf_filesrc(files, file_idx, 0, 0);
2085 #endif // BACKWARD_HAS_DW == 1
2087 #if BACKWARD_HAS_DWARF == 1
2090 class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>
2091 :
public TraceResolverLinuxBase {
2093 TraceResolverLinuxImpl() : _dwarf_loaded(false) {}
2095 ResolvedTrace
resolve(ResolvedTrace trace)
override {
2100 Dl_info symbol_info;
2101 int dladdr_result = 0;
2102 #if defined(__GLIBC__)
2106 dladdr1(trace.addr, &symbol_info,
reinterpret_cast<void **
>(&link_map),
2110 dladdr_result = dladdr(trace.addr, &symbol_info);
2112 if (!dladdr_result) {
2134 if (symbol_info.dli_sname) {
2135 trace.object_function = demangle(symbol_info.dli_sname);
2138 if (!symbol_info.dli_fname) {
2142 trace.object_filename = resolve_exec_path(symbol_info);
2143 dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname);
2144 if (!fobj.dwarf_handle) {
2148 #if defined(__GLIBC__)
2151 Dwarf_Addr address =
reinterpret_cast<uintptr_t
>(trace.addr) -
2152 reinterpret_cast<uintptr_t
>(link_map->l_addr);
2154 Dwarf_Addr address =
reinterpret_cast<uintptr_t
>(trace.addr);
2157 if (trace.object_function.empty()) {
2158 symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address);
2160 if (it != fobj.symbol_cache.end()) {
2161 if (it->first != address) {
2162 if (it != fobj.symbol_cache.begin()) {
2166 trace.object_function = demangle(it->second.c_str());
2171 Dwarf_Die die = find_die(fobj, address);
2180 die_cache_entry &die_object = get_die_cache(fobj, die);
2181 if (die_object.isEmpty())
2184 die_linemap_t::iterator it = die_object.line_section.lower_bound(address);
2186 if (it != die_object.line_section.end()) {
2187 if (it->first != address) {
2188 if (it == die_object.line_section.begin()) {
2203 Dwarf_Line line = die_object.line_buffer[it->second];
2204 Dwarf_Error error = DW_DLE_NE;
2207 if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) {
2208 trace.source.filename = std::string(filename);
2209 dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
2212 Dwarf_Unsigned number = 0;
2213 if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
2214 trace.source.line = number;
2216 trace.source.line = 0;
2219 if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
2220 trace.source.col = number;
2222 trace.source.col = 0;
2225 std::vector<std::string> namespace_stack;
2226 deep_first_search_by_pc(fobj, die, address, namespace_stack,
2227 inliners_search_cb(trace, fobj, die));
2229 dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
2235 static int close_dwarf(Dwarf_Debug dwarf) {
2236 return dwarf_finish(dwarf, NULL);
2242 typedef details::handle<int, details::deleter<int, int, &::close>>
2245 typedef details::handle<Elf *, details::deleter<int, Elf *, &elf_end>>
2248 typedef details::handle<Dwarf_Debug,
2249 details::deleter<int, Dwarf_Debug, &close_dwarf>>
2252 typedef std::map<Dwarf_Addr, int> die_linemap_t;
2254 typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
2256 struct die_cache_entry {
2257 die_specmap_t spec_section;
2258 die_linemap_t line_section;
2259 Dwarf_Line *line_buffer;
2260 Dwarf_Signed line_count;
2261 Dwarf_Line_Context line_context;
2263 inline bool isEmpty() {
2264 return line_buffer == NULL || line_count == 0 || line_context == NULL ||
2265 line_section.empty();
2268 die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {}
2270 ~die_cache_entry() {
2272 dwarf_srclines_dealloc_b(line_context);
2277 typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
2279 typedef std::map<uintptr_t, std::string> symbol_cache_t;
2281 struct dwarf_fileobject {
2282 dwarf_file_t file_handle;
2283 dwarf_elf_t elf_handle;
2284 dwarf_handle_t dwarf_handle;
2285 symbol_cache_t symbol_cache;
2288 die_cache_t die_cache;
2289 die_cache_entry *current_cu;
2294 fobj_dwarf_map_t _fobj_dwarf_map;
2296 static bool cstrings_eq(
const char *a,
const char *
b) {
2300 return strcmp(a,
b) == 0;
2303 dwarf_fileobject &load_object_with_dwarf(
const std::string &filename_object) {
2305 if (!_dwarf_loaded) {
2308 _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
2311 fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object);
2312 if (it != _fobj_dwarf_map.end()) {
2317 dwarf_fileobject &r = _fobj_dwarf_map[filename_object];
2319 dwarf_file_t file_handle;
2320 file_handle.reset(open(filename_object.c_str(), O_RDONLY));
2321 if (file_handle.get() < 0) {
2328 dwarf_elf_t elf_handle;
2329 elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
2334 const char *e_ident = elf_getident(elf_handle.get(), 0);
2342 if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
2347 size_t shdrstrndx = 0;
2348 if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) {
2352 std::string debuglink;
2358 #define ELF_GET_DATA(ARCH) \
2359 Elf_Scn *elf_section = 0; \
2360 Elf_Data *elf_data = 0; \
2361 Elf##ARCH##_Shdr *section_header = 0; \
2362 Elf_Scn *symbol_section = 0; \
2363 size_t symbol_count = 0; \
2364 size_t symbol_strings = 0; \
2365 Elf##ARCH##_Sym *symbol = 0; \
2366 const char *section_name = 0; \
2368 while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \
2369 section_header = elf##ARCH##_getshdr(elf_section); \
2370 if (section_header == NULL) { \
2374 if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \
2375 section_header->sh_name)) == NULL) { \
2379 if (cstrings_eq(section_name, ".gnu_debuglink")) { \
2380 elf_data = elf_getdata(elf_section, NULL); \
2381 if (elf_data && elf_data->d_size > 0) { \
2383 std::string(reinterpret_cast<const char *>(elf_data->d_buf)); \
2387 switch (section_header->sh_type) { \
2389 symbol_section = elf_section; \
2390 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2391 symbol_strings = section_header->sh_link; \
2396 if (!symbol_section) { \
2397 symbol_section = elf_section; \
2398 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2399 symbol_strings = section_header->sh_link; \
2405 if (symbol_section && symbol_count && symbol_strings) { \
2406 elf_data = elf_getdata(symbol_section, NULL); \
2407 symbol = reinterpret_cast<Elf##ARCH##_Sym *>(elf_data->d_buf); \
2408 for (size_t i = 0; i < symbol_count; ++i) { \
2409 int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
2410 if (type == STT_FUNC && symbol->st_value > 0) { \
2411 r.symbol_cache[symbol->st_value] = std::string( \
2412 elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \
2418 if (e_ident[EI_CLASS] == ELFCLASS32) {
2420 }
else if (e_ident[EI_CLASS] == ELFCLASS64) {
2427 if (!debuglink.empty()) {
2431 dwarf_file_t debuglink_file;
2432 debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
2433 if (debuglink_file.get() > 0) {
2434 dwarf_elf_t debuglink_elf;
2435 debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL));
2439 if (debuglink_elf) {
2440 elf_handle =
move(debuglink_elf);
2441 file_handle =
move(debuglink_file);
2447 Dwarf_Debug dwarf_debug;
2448 Dwarf_Error error = DW_DLE_NE;
2449 dwarf_handle_t dwarf_handle;
2451 int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL,
2452 &dwarf_debug, &error);
2457 if (dwarf_result != DW_DLV_OK) {
2461 dwarf_handle.reset(dwarf_debug);
2463 r.file_handle =
move(file_handle);
2464 r.elf_handle =
move(elf_handle);
2465 r.dwarf_handle =
move(dwarf_handle);
2470 die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) {
2471 Dwarf_Error error = DW_DLE_NE;
2474 Dwarf_Off die_offset;
2475 if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
2479 die_cache_t::iterator it = fobj.die_cache.find(die_offset);
2481 if (it != fobj.die_cache.end()) {
2482 fobj.current_cu = &it->second;
2486 die_cache_entry &de = fobj.die_cache[die_offset];
2487 fobj.current_cu = &de;
2489 Dwarf_Addr line_addr;
2490 Dwarf_Small table_count;
2506 if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) ==
2510 if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer,
2512 &error) == DW_DLV_OK) {
2515 for (
int i = 0; i < de.line_count; i++) {
2516 if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) !=
2520 de.line_section.insert(std::pair<Dwarf_Addr, int>(line_addr, i));
2534 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2535 Dwarf_Die current_die = 0;
2536 if (dwarf_child(die, ¤t_die, &error) == DW_DLV_OK) {
2538 Dwarf_Die sibling_die = 0;
2540 Dwarf_Half tag_value;
2541 dwarf_tag(current_die, &tag_value, &error);
2543 if (tag_value == DW_TAG_subprogram ||
2544 tag_value == DW_TAG_inlined_subroutine) {
2546 Dwarf_Bool has_attr = 0;
2547 if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr,
2548 &error) == DW_DLV_OK) {
2550 Dwarf_Attribute attr_mem;
2551 if (dwarf_attr(current_die, DW_AT_specification, &attr_mem,
2552 &error) == DW_DLV_OK) {
2553 Dwarf_Off spec_offset = 0;
2554 if (dwarf_formref(attr_mem, &spec_offset, &error) ==
2556 Dwarf_Off spec_die_offset;
2557 if (dwarf_dieoffset(current_die, &spec_die_offset, &error) ==
2559 de.spec_section[spec_offset] = spec_die_offset;
2563 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2568 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
2569 if (result == DW_DLV_ERROR) {
2571 }
else if (result == DW_DLV_NO_ENTRY) {
2575 if (current_die != die) {
2576 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2580 current_die = sibling_die;
2586 static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die,
2587 Dwarf_Half attr,
bool global) {
2588 Dwarf_Error error = DW_DLE_NE;
2589 Dwarf_Attribute attr_mem;
2591 Dwarf_Die found_die = NULL;
2592 if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
2596 result = dwarf_global_formref(attr_mem, &offset, &error);
2598 result = dwarf_formref(attr_mem, &offset, &error);
2601 if (result == DW_DLV_OK) {
2602 if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) {
2606 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2611 static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die,
2612 Dwarf_Half attr,
bool global) {
2613 Dwarf_Error error = DW_DLE_NE;
2616 Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
2620 if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
2622 value = std::string(name);
2624 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2626 dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
2634 static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) {
2635 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2636 Dwarf_Error error = DW_DLE_NE;
2637 Dwarf_Off die_offset;
2638 if (fobj.current_cu &&
2639 dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) {
2640 die_specmap_t::iterator it =
2641 fobj.current_cu->spec_section.find(die_offset);
2645 if (it != fobj.current_cu->spec_section.end()) {
2646 Dwarf_Die spec_die = 0;
2647 if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) {
2654 return get_referenced_die(fobj.dwarf_handle.get(), die,
2655 DW_AT_abstract_origin,
true);
2658 static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) {
2659 Dwarf_Addr low_pc = 0, high_pc = 0;
2660 Dwarf_Half high_pc_form = 0;
2661 Dwarf_Form_Class return_class;
2662 Dwarf_Error error = DW_DLE_NE;
2663 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2664 bool has_lowpc =
false;
2665 bool has_highpc =
false;
2666 bool has_ranges =
false;
2668 if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
2674 if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) ==
2681 if (return_class == DW_FORM_CLASS_CONSTANT) {
2682 high_pc = low_pc + high_pc;
2687 return pc >= low_pc && pc < high_pc;
2698 bool result =
false;
2700 Dwarf_Attribute attr;
2701 if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
2704 if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
2705 Dwarf_Ranges *ranges;
2706 Dwarf_Signed ranges_count = 0;
2707 Dwarf_Unsigned byte_count = 0;
2709 if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count,
2710 &byte_count, &error) == DW_DLV_OK) {
2711 has_ranges = ranges_count != 0;
2712 for (
int i = 0; i < ranges_count; i++) {
2713 if (ranges[i].dwr_addr1 != 0 &&
2714 pc >= ranges[i].dwr_addr1 + low_pc &&
2715 pc < ranges[i].dwr_addr2 + low_pc) {
2720 dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
2726 if (!result && low_pc != 0 && pc == low_pc) {
2733 if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
2734 Dwarf_Die spec_die = get_spec_die(fobj, die);
2736 result = die_has_pc(fobj, spec_die, pc);
2737 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2744 static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &
type) {
2745 Dwarf_Error error = DW_DLE_NE;
2747 Dwarf_Die child = 0;
2748 if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
2749 get_type(dwarf, child,
type);
2753 type.insert(0,
"::");
2754 dwarf_dealloc(dwarf, child, DW_DLA_DIE);
2758 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2759 type.insert(0, std::string(name));
2760 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2762 type.insert(0,
"<unknown>");
2766 static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
2767 Dwarf_Error error = DW_DLE_NE;
2769 Dwarf_Sig8 signature;
2770 Dwarf_Bool has_attr = 0;
2771 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) {
2773 Dwarf_Attribute attr_mem;
2774 if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) {
2775 if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) {
2776 return std::string(
"<no type signature>");
2779 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2783 Dwarf_Unsigned next_cu_header;
2784 Dwarf_Sig8 tu_signature;
2788 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0,
2789 &next_cu_header, 0, &error) == DW_DLV_OK) {
2791 if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
2792 Dwarf_Die type_cu_die = 0;
2793 if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) {
2794 Dwarf_Die child_die = 0;
2795 if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) {
2796 get_type(dwarf, child_die, result);
2797 found = !result.empty();
2798 dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
2800 dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
2806 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2807 &next_cu_header, 0, &error) == DW_DLV_OK) {
2815 std::ostringstream string_stream;
2816 string_stream <<
"<0x" << std::hex << std::setfill(
'0');
2817 for (
int i = 0; i < 8; ++i) {
2818 string_stream << std::setw(2) << std::hex
2819 << (int)(
unsigned char)(signature.signature[i]);
2821 string_stream <<
">";
2822 result = string_stream.str();
2827 struct type_context_t {
2835 : is_const(false), is_typedef(false), has_type(false), has_name(false) {
2843 static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die,
2844 type_context_t &context) {
2846 Dwarf_Error error = DW_DLE_NE;
2850 if (!context.is_typedef) {
2851 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2852 if (!context.text.empty()) {
2853 context.text.insert(0,
" ");
2855 context.text.insert(0, std::string(name));
2856 dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
2859 context.is_typedef =
false;
2860 context.has_type =
true;
2861 if (context.is_const) {
2862 context.text.insert(0,
"const ");
2863 context.is_const =
false;
2867 bool next_type_is_const =
false;
2868 bool is_keyword =
true;
2871 Dwarf_Bool has_attr = 0;
2872 if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
2874 case DW_TAG_structure_type:
2875 case DW_TAG_union_type:
2876 case DW_TAG_class_type:
2877 case DW_TAG_enumeration_type:
2878 context.has_type =
true;
2879 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) ==
2886 get_type_by_signature(fobj.dwarf_handle.get(), die);
2887 if (context.is_const)
2888 type.insert(0,
"const ");
2890 if (!context.text.empty())
2891 context.text.insert(0,
" ");
2892 context.text.insert(0,
type);
2897 context.is_typedef = (tag == DW_TAG_enumeration_type);
2900 case DW_TAG_const_type:
2901 next_type_is_const =
true;
2903 case DW_TAG_pointer_type:
2904 context.text.insert(0,
"*");
2906 case DW_TAG_reference_type:
2907 context.text.insert(0,
"&");
2909 case DW_TAG_restrict_type:
2910 context.text.insert(0,
"restrict ");
2912 case DW_TAG_rvalue_reference_type:
2913 context.text.insert(0,
"&&");
2915 case DW_TAG_volatile_type:
2916 context.text.insert(0,
"volatile ");
2918 case DW_TAG_typedef:
2921 next_type_is_const = context.is_const;
2922 context.is_typedef =
true;
2923 context.has_type =
true;
2925 case DW_TAG_base_type:
2926 context.has_type =
true;
2928 case DW_TAG_formal_parameter:
2929 context.has_name =
true;
2937 if (!is_keyword && context.is_const) {
2938 context.text.insert(0,
"const ");
2941 context.is_const = next_type_is_const;
2944 get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type,
true);
2946 set_parameter_string(fobj, ref, context);
2947 dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
2950 if (!context.has_type && context.has_name) {
2951 context.text.insert(0,
"void ");
2952 context.has_type =
true;
2957 static void set_function_parameters(std::string &function_name,
2958 std::vector<std::string> &ns,
2959 dwarf_fileobject &fobj, Dwarf_Die die) {
2960 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2961 Dwarf_Error error = DW_DLE_NE;
2962 Dwarf_Die current_die = 0;
2963 std::string parameters;
2964 bool has_spec =
true;
2967 Dwarf_Die spec_die = get_spec_die(fobj, die);
2973 std::vector<std::string>::const_iterator it = ns.begin();
2974 std::string ns_name;
2975 for (it = ns.begin(); it < ns.end(); ++it) {
2976 ns_name.append(*it).append(
"::");
2979 if (!ns_name.empty()) {
2980 function_name.insert(0, ns_name);
2985 std::string return_type =
2986 get_referenced_die_name(dwarf, die, DW_AT_type,
true);
2987 if (return_type.empty()) {
2988 return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type,
true);
2990 if (!return_type.empty()) {
2991 return_type.append(
" ");
2992 function_name.insert(0, return_type);
2995 if (dwarf_child(spec_die, ¤t_die, &error) == DW_DLV_OK) {
2997 Dwarf_Die sibling_die = 0;
2999 Dwarf_Half tag_value;
3000 dwarf_tag(current_die, &tag_value, &error);
3002 if (tag_value == DW_TAG_formal_parameter) {
3004 bool is_artificial =
false;
3005 Dwarf_Attribute attr_mem;
3006 if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) ==
3008 Dwarf_Bool flag = 0;
3009 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3010 is_artificial = flag != 0;
3012 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3015 if (!is_artificial) {
3016 type_context_t context;
3017 set_parameter_string(fobj, current_die, context);
3019 if (parameters.empty()) {
3020 parameters.append(
"(");
3022 parameters.append(
", ");
3024 parameters.append(context.text);
3028 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3029 if (result == DW_DLV_ERROR) {
3031 }
else if (result == DW_DLV_NO_ENTRY) {
3035 if (current_die != die) {
3036 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3040 current_die = sibling_die;
3043 if (parameters.empty())
3045 parameters.append(
")");
3049 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
3051 function_name.append(parameters);
3056 struct inliners_search_cb {
3057 void operator()(Dwarf_Die die, std::vector<std::string> &ns) {
3058 Dwarf_Error error = DW_DLE_NE;
3059 Dwarf_Half tag_value;
3060 Dwarf_Attribute attr_mem;
3061 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3063 dwarf_tag(die, &tag_value, &error);
3065 switch (tag_value) {
3067 case DW_TAG_subprogram:
3068 if (!trace.source.function.empty())
3070 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
3071 trace.source.function = std::string(name);
3072 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
3077 trace.source.function =
3078 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin,
true);
3079 if (trace.source.function.empty()) {
3080 trace.source.function =
3081 get_referenced_die_name(dwarf, die, DW_AT_specification,
true);
3086 set_function_parameters(trace.source.function, ns, fobj, die);
3095 if (trace.object_function.empty()) {
3096 details::demangler demangler;
3098 if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) !=
3100 if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) !=
3107 if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) {
3108 trace.object_function = demangler.demangle(linkage);
3109 dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
3111 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3115 case DW_TAG_inlined_subroutine:
3116 ResolvedTrace::SourceLoc sloc;
3118 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
3119 sloc.function = std::string(name);
3120 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
3127 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin,
true);
3130 set_function_parameters(sloc.function, ns, fobj, die);
3132 std::string file = die_call_file(dwarf, die, cu_die);
3134 sloc.filename = file;
3136 Dwarf_Unsigned number = 0;
3137 if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) {
3138 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
3141 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3144 if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) ==
3146 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
3149 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3152 trace.inliners.push_back(sloc);
3156 ResolvedTrace &trace;
3157 dwarf_fileobject &fobj;
3159 inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &
f, Dwarf_Die
c)
3160 : trace(t), fobj(
f), cu_die(
c) {}
3163 static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj,
3164 Dwarf_Die parent_die, Dwarf_Addr pc,
3166 Dwarf_Die current_die = 0;
3167 Dwarf_Error error = DW_DLE_NE;
3168 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3170 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
3175 Dwarf_Die sibling_die = 0;
3176 Dwarf_Half tag_value;
3177 dwarf_tag(current_die, &tag_value, &error);
3179 switch (tag_value) {
3180 case DW_TAG_subprogram:
3181 case DW_TAG_inlined_subroutine:
3182 if (die_has_pc(fobj, current_die, pc)) {
3186 bool declaration =
false;
3187 Dwarf_Attribute attr_mem;
3188 if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
3190 Dwarf_Bool flag = 0;
3191 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3192 declaration = flag != 0;
3194 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3202 Dwarf_Die die_mem = 0;
3203 Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem);
3210 int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3211 if (res == DW_DLV_ERROR) {
3213 }
else if (res == DW_DLV_NO_ENTRY) {
3217 if (current_die != parent_die) {
3218 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3222 current_die = sibling_die;
3227 template <
typename CB>
3228 static bool deep_first_search_by_pc(dwarf_fileobject &fobj,
3229 Dwarf_Die parent_die, Dwarf_Addr pc,
3230 std::vector<std::string> &ns, CB cb) {
3231 Dwarf_Die current_die = 0;
3232 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3233 Dwarf_Error error = DW_DLE_NE;
3235 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
3239 bool branch_has_pc =
false;
3240 bool has_namespace =
false;
3242 Dwarf_Die sibling_die = 0;
3245 if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
3246 if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
3247 char *ns_name = NULL;
3248 if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) {
3250 ns.push_back(std::string(ns_name));
3252 ns.push_back(
"<unknown>");
3254 dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
3256 ns.push_back(
"<unknown>");
3258 has_namespace =
true;
3262 bool declaration =
false;
3263 Dwarf_Attribute attr_mem;
3264 if (tag != DW_TAG_class_type &&
3265 dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
3267 Dwarf_Bool flag = 0;
3268 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3269 declaration = flag != 0;
3271 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3279 branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb);
3282 if (!branch_has_pc) {
3283 branch_has_pc = die_has_pc(fobj, current_die, pc);
3286 if (branch_has_pc) {
3287 cb(current_die, ns);
3290 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3291 if (result == DW_DLV_ERROR) {
3293 }
else if (result == DW_DLV_NO_ENTRY) {
3297 if (current_die != parent_die) {
3298 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3302 if (has_namespace) {
3303 has_namespace =
false;
3306 current_die = sibling_die;
3309 if (has_namespace) {
3312 return branch_has_pc;
3315 static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die,
3317 Dwarf_Attribute attr_mem;
3318 Dwarf_Error error = DW_DLE_NE;
3319 Dwarf_Unsigned file_index;
3323 if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
3324 if (dwarf_formudata(attr_mem, &file_index, &error) != DW_DLV_OK) {
3327 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3329 if (file_index == 0) {
3333 char **srcfiles = 0;
3334 Dwarf_Signed file_count = 0;
3335 if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) {
3336 if (file_count > 0 && file_index <=
static_cast<Dwarf_Unsigned
>(file_count)) {
3337 file = std::string(srcfiles[file_index - 1]);
3341 for (
int i = 0; i < file_count; ++i) {
3342 dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
3344 dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
3350 Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) {
3354 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3355 Dwarf_Error error = DW_DLE_NE;
3356 Dwarf_Arange *aranges;
3357 Dwarf_Signed arange_count;
3359 Dwarf_Die returnDie;
3361 if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) !=
3368 Dwarf_Arange arange;
3369 if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) ==
3374 Dwarf_Off cu_die_offset;
3375 if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) ==
3381 dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error);
3383 found = dwarf_result == DW_DLV_OK;
3385 dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
3394 Dwarf_Unsigned next_cu_header;
3399 dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3400 &next_cu_header, 0, &error) == DW_DLV_OK) {
3403 dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
3405 if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
3406 if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) &&
3407 tag == DW_TAG_compile_unit) {
3408 if (die_has_pc(fobj, returnDie, addr)) {
3416 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3417 &next_cu_header, 0, &error) == DW_DLV_OK) {
3430 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3431 &next_cu_header, 0, &error) == DW_DLV_OK) {
3432 if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
3433 Dwarf_Die die_mem = 0;
3434 Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem);
3444 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3445 &next_cu_header, 0, &error) == DW_DLV_OK) {
3459 #endif // BACKWARD_HAS_DWARF == 1
3462 class TraceResolverImpl<system_tag::linux_tag>
3463 :
public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
3465 #endif // BACKWARD_SYSTEM_LINUX
3467 #ifdef BACKWARD_SYSTEM_DARWIN
3469 template <
typename STACKTRACE_TAG>
class TraceResolverDarwinImpl;
3472 class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>
3473 :
public TraceResolverImplBase {
3475 void load_addresses(
void *
const*addresses,
int address_count)
override {
3476 if (address_count == 0) {
3479 _symbols.reset(backtrace_symbols(addresses, address_count));
3482 ResolvedTrace
resolve(ResolvedTrace trace)
override {
3485 char *filename = _symbols[trace.idx];
3488 while (*filename && *filename !=
' ')
3490 while (*filename ==
' ')
3494 char *p = filename + strlen(filename) - 1;
3496 while (p > filename && *p !=
' ')
3498 while (p > filename && *p ==
' ')
3500 while (p > filename && *p !=
' ')
3502 while (p > filename && *p ==
' ')
3504 char *funcname_end = p + 1;
3507 while (p > filename && *p !=
' ')
3509 char *funcname = p + 1;
3512 while (p > filename && *p ==
' ')
3514 while (p > filename && *p !=
' ')
3516 while (p > filename && *p ==
' ')
3520 char *filename_end = p + 1;
3521 if (p == filename) {
3523 filename_end = filename + strlen(filename);
3524 funcname = filename_end;
3526 trace.object_filename.assign(
3527 filename, filename_end);
3531 *funcname_end =
'\0';
3533 trace.object_function = this->demangle(funcname);
3534 trace.object_function +=
" ";
3535 trace.object_function += (funcname_end + 1);
3536 trace.source.function = trace.object_function;
3542 details::handle<char **> _symbols;
3546 class TraceResolverImpl<system_tag::darwin_tag>
3547 :
public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
3549 #endif // BACKWARD_SYSTEM_DARWIN
3551 #ifdef BACKWARD_SYSTEM_WINDOWS
3557 struct module_data {
3558 std::string image_name;
3559 std::string module_name;
3564 class get_mod_info {
3566 static const int buffer_length = 4096;
3569 get_mod_info(HANDLE h) : process(h) {}
3571 module_data operator()(HMODULE module) {
3573 char temp[buffer_length];
3576 GetModuleInformation(process, module, &mi,
sizeof(mi));
3577 ret.base_address = mi.lpBaseOfDll;
3578 ret.load_size = mi.SizeOfImage;
3580 GetModuleFileNameExA(process, module, temp,
sizeof(temp));
3581 ret.image_name = temp;
3582 GetModuleBaseNameA(process, module, temp,
sizeof(temp));
3583 ret.module_name = temp;
3584 std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
3585 std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
3586 SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address,
3592 template <>
class TraceResolverImpl<system_tag::windows_tag>
3593 :
public TraceResolverImplBase {
3595 TraceResolverImpl() {
3597 HANDLE process = GetCurrentProcess();
3599 std::vector<module_data> modules;
3601 std::vector<HMODULE> module_handles(1);
3602 SymInitialize(process, NULL,
false);
3603 DWORD symOptions = SymGetOptions();
3604 symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME;
3605 SymSetOptions(symOptions);
3606 EnumProcessModules(process, &module_handles[0],
3607 module_handles.size() *
sizeof(HMODULE), &cbNeeded);
3608 module_handles.resize(cbNeeded /
sizeof(HMODULE));
3609 EnumProcessModules(process, &module_handles[0],
3610 module_handles.size() *
sizeof(HMODULE), &cbNeeded);
3611 std::transform(module_handles.begin(), module_handles.end(),
3612 std::back_inserter(modules), get_mod_info(process));
3613 void *base = modules[0].base_address;
3614 IMAGE_NT_HEADERS *h = ImageNtHeader(base);
3615 image_type = h->FileHeader.Machine;
3618 static const int max_sym_len = 255;
3621 char buffer[max_sym_len];
3624 DWORD64 displacement;
3626 ResolvedTrace
resolve(ResolvedTrace t)
override {
3627 HANDLE process = GetCurrentProcess();
3631 memset(&sym, 0,
sizeof(sym));
3632 sym.sym.SizeOfStruct =
sizeof(SYMBOL_INFO);
3633 sym.sym.MaxNameLen = max_sym_len;
3635 if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) {
3638 DWORD dw = GetLastError();
3640 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3641 FORMAT_MESSAGE_FROM_SYSTEM |
3642 FORMAT_MESSAGE_IGNORE_INSERTS,
3643 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
3644 (
char*)&lpMsgBuf, 0, NULL);
3650 UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE);
3654 if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) {
3655 t.object_filename = line.FileName;
3656 t.source.filename = line.FileName;
3657 t.source.line = line.LineNumber;
3658 t.source.col = offset;
3661 t.source.function = name;
3662 t.object_filename =
"";
3663 t.object_function = name;
3668 DWORD machine_type()
const {
return image_type; }
3682 typedef std::vector<std::pair<unsigned, std::string>>
lines_t;
3689 const std::vector<std::string> &prefixes = get_paths_from_env_variable();
3690 for (
size_t i = 0; i < prefixes.size(); ++i) {
3692 std::string new_path = prefixes[i] +
'/' + path;
3693 _file.reset(
new std::ifstream(new_path.c_str()));
3698 if (!_file || !is_open()) {
3699 _file.reset(
new std::ifstream(path.c_str()));
3705 using namespace std;
3720 for (line_idx = 1; line_idx < line_start; ++line_idx) {
3721 std::getline(*_file, line);
3731 bool operator()(
char c) {
return std::isspace(
c); }
3734 bool started =
false;
3735 for (; line_idx < line_start + line_count; ++line_idx) {
3736 getline(*_file, line);
3741 if (std::find_if(line.begin(), line.end(),
not_isspace()) == line.end())
3745 lines.push_back(make_pair(line_idx, line));
3749 std::find_if(lines.rbegin(), lines.rend(),
not_isempty()).base(),
3756 return get_lines(line_start, line_count, lines);
3768 return !(std::find_if(p.second.begin(), p.second.end(),
not_isspace()) ==
3775 #ifdef BACKWARD_ATLEAST_CXX11
3777 SourceFile &operator=(SourceFile &&from) {
3798 std::vector<std::string> paths;
3799 const char *prefixes_str = std::getenv(
"BACKWARD_CXX_SOURCE_PREFIXES");
3800 if (prefixes_str && prefixes_str[0]) {
3807 static std::vector<std::string> paths = get_paths_from_env_variable_impl();
3811 #ifdef BACKWARD_ATLEAST_CXX11
3822 unsigned context_size) {
3824 SourceFile &src_file = get_src_file(filename);
3825 unsigned start = line_start - context_size / 2;
3830 const std::string &filename_b,
unsigned line_b,
3831 unsigned context_size) {
3832 SourceFile &src_file_a = get_src_file(filename_a);
3833 SourceFile &src_file_b = get_src_file(filename_b);
3836 src_file_a.
get_lines(line_a - context_size / 4, context_size / 2);
3837 src_file_b.
get_lines(line_b - context_size / 4, context_size / 2, lines);
3842 unsigned line_b,
unsigned context_size) {
3843 SourceFile &src_file = get_src_file(filename);
3847 unsigned a = min(line_a, line_b);
3848 unsigned b = max(line_a, line_b);
3850 if ((
b - a) < (context_size / 3)) {
3851 return src_file.
get_lines((a +
b - context_size + 1) / 2, context_size);
3854 lines_t lines = src_file.
get_lines(a - context_size / 4, context_size / 2);
3855 src_file.
get_lines(
b - context_size / 4, context_size / 2, lines);
3864 src_files_t::iterator it = _src_files.find(filename);
3865 if (it != _src_files.end()) {
3868 SourceFile &new_src_file = _src_files[filename];
3870 return new_src_file;
3876 namespace ColorMode {
3883 int_type
underflow()
override {
return traits_type::eof(); }
3885 if (traits_type::not_eof(ch) && fputc(ch, sink) != EOF) {
3888 return traits_type::eof();
3891 std::streamsize
xsputn(
const char_type *s, std::streamsize count)
override {
3892 return static_cast<std::streamsize
>(
3893 fwrite(
s,
sizeof *
s,
static_cast<size_t>(count), sink));
3896 #ifdef BACKWARD_ATLEAST_CXX11
3911 #ifdef BACKWARD_SYSTEM_LINUX
3919 Colorize(std::ostream &os) : _os(os), _reset(false), _enabled(false) {}
3923 void activate(
ColorMode::type mode, FILE *fp) { activate(mode, fileno(fp)); }
3931 _os <<
"\033[" <<
static_cast<int>(ccode) <<
"m";
3952 #else // ndef BACKWARD_SYSTEM_LINUX
3966 #endif // BACKWARD_SYSTEM_LINUX
3978 : snippet(true), color_mode(ColorMode::
automatic), address(false),
3979 object(false), inliner_context_size(5), trace_context_size(7) {}
3981 template <
typename ST> FILE *
print(ST &st, FILE *fp = stderr) {
3983 std::ostream os(&obuf);
3985 colorize.activate(color_mode, fp);
3986 print_stacktrace(st, os, colorize);
3990 template <
typename ST> std::ostream &
print(ST &st, std::ostream &os) {
3992 colorize.activate(color_mode);
3993 print_stacktrace(st, os, colorize);
3997 template <
typename IT>
3998 FILE *
print(IT begin, IT end, FILE *fp = stderr,
size_t thread_id = 0) {
4000 std::ostream os(&obuf);
4002 colorize.activate(color_mode, fp);
4003 print_stacktrace(begin, end, os, thread_id, colorize);
4007 template <
typename IT>
4008 std::ostream &
print(IT begin, IT end, std::ostream &os,
4009 size_t thread_id = 0) {
4011 colorize.activate(color_mode);
4012 print_stacktrace(begin, end, os, thread_id, colorize);
4022 template <
typename ST>
4024 print_header(os, st.thread_id());
4025 _resolver.load_stacktrace(st);
4026 for (
size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
4027 print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize);
4031 template <
typename IT>
4034 print_header(os, thread_id);
4035 for (; begin != end; ++begin) {
4036 print_trace(os, *begin, colorize);
4041 os <<
"Stack trace (most recent call last)";
4043 os <<
" in thread " << thread_id;
4050 os <<
"#" << std::left << std::setw(2) << trace.
idx << std::right;
4051 bool already_indented =
true;
4056 already_indented =
false;
4059 for (
size_t inliner_idx = trace.
inliners.size(); inliner_idx > 0;
4061 if (!already_indented) {
4066 print_source_loc(os,
" | ", inliner_loc);
4068 print_snippet(os,
" | ", inliner_loc, colorize,
Color::purple,
4069 inliner_context_size);
4071 already_indented =
false;
4075 if (!already_indented) {
4078 print_source_loc(os,
" ", trace.
source, trace.
addr);
4081 trace_context_size);
4090 using namespace std;
4094 static_cast<unsigned>(context_size));
4096 for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) {
4097 if (it->first == source_loc.
line) {
4098 colorize.set_color(color_code);
4099 os << indent <<
">";
4101 os << indent <<
" ";
4103 os << std::setw(4) << it->first <<
": " << it->second <<
"\n";
4104 if (it->first == source_loc.
line) {
4112 void *addr =
nullptr) {
4113 os << indent <<
"Source \"" << source_loc.
filename <<
"\", line "
4116 if (address && addr !=
nullptr) {
4117 os <<
" [" << addr <<
"]";
4125 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
4127 class SignalHandling {
4129 static std::vector<int> make_default_signals() {
4130 const int posix_signals[] = {
4143 #if defined(BACKWARD_SYSTEM_DARWIN)
4147 return std::vector<int>(posix_signals,
4149 sizeof posix_signals /
sizeof posix_signals[0]);
4152 SignalHandling(
const std::vector<int> &posix_signals = make_default_signals())
4154 bool success =
true;
4156 const size_t stack_size = 1024 * 1024 * 8;
4157 _stack_content.reset(
static_cast<char *
>(malloc(stack_size)));
4158 if (_stack_content) {
4160 ss.ss_sp = _stack_content.get();
4161 ss.ss_size = stack_size;
4163 if (sigaltstack(&ss,
nullptr) < 0) {
4170 for (
size_t i = 0; i < posix_signals.size(); ++i) {
4171 struct sigaction action;
4172 memset(&action, 0,
sizeof action);
4174 static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
4175 sigfillset(&action.sa_mask);
4176 sigdelset(&action.sa_mask, posix_signals[i]);
4177 #if defined(__clang__)
4178 #pragma clang diagnostic push
4179 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
4181 action.sa_sigaction = &sig_handler;
4182 #if defined(__clang__)
4183 #pragma clang diagnostic pop
4186 int r = sigaction(posix_signals[i], &action,
nullptr);
4194 bool loaded()
const {
return _loaded; }
4196 static void handleSignal(
int, siginfo_t *info,
void *_ctx) {
4197 ucontext_t *uctx =
static_cast<ucontext_t *
>(_ctx);
4200 void *error_addr =
nullptr;
4201 #ifdef REG_RIP // x86_64
4202 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.gregs[REG_RIP]);
4203 #elif defined(REG_EIP) // x86_32
4204 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.gregs[REG_EIP]);
4205 #elif defined(__arm__)
4206 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.arm_pc);
4207 #elif defined(__aarch64__)
4208 #if defined(__APPLE__)
4209 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext->__ss.__pc);
4211 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.pc);
4213 #elif defined(__mips__)
4214 error_addr =
reinterpret_cast<void *
>(
4215 reinterpret_cast<struct sigcontext *
>(&uctx->uc_mcontext)->sc_pc);
4216 #elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
4217 defined(__POWERPC__)
4218 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.regs->nip);
4219 #elif defined(__riscv)
4220 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.__gregs[REG_PC]);
4221 #elif defined(__s390x__)
4222 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.psw.addr);
4223 #elif defined(__APPLE__) && defined(__x86_64__)
4224 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext->__ss.__rip);
4225 #elif defined(__APPLE__)
4226 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext->__ss.__eip);
4228 #warning ":/ sorry, ain't know no nothing none not of your architecture!"
4231 st.load_from(error_addr, 32,
reinterpret_cast<void *
>(uctx),
4234 st.load_here(32,
reinterpret_cast<void *
>(uctx), info->si_addr);
4238 printer.address =
true;
4239 printer.print(st, stderr);
4241 #if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
4242 psiginfo(info,
nullptr);
4249 details::handle<char *> _stack_content;
4256 sig_handler(
int signo, siginfo_t *info,
void *_ctx) {
4257 handleSignal(signo, info, _ctx);
4260 raise(info->si_signo);
4264 _exit(EXIT_FAILURE);
4268 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
4270 #ifdef BACKWARD_SYSTEM_WINDOWS
4272 class SignalHandling {
4274 SignalHandling(
const std::vector<int> & = std::vector<int>())
4275 : reporter_thread_([]() {
4285 std::unique_lock<std::mutex> lk(mtx());
4286 cv().wait(lk, [] {
return crashed() != crash_status::running; });
4288 if (crashed() == crash_status::crashed) {
4289 handle_stacktrace(skip_recs());
4292 std::unique_lock<std::mutex> lk(mtx());
4293 crashed() = crash_status::ending;
4297 SetUnhandledExceptionFilter(crash_handler);
4299 signal(SIGABRT, signal_handler);
4300 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
4302 std::set_terminate(&terminator);
4303 #ifndef BACKWARD_ATLEAST_CXX17
4304 std::set_unexpected(&terminator);
4306 _set_purecall_handler(&terminator);
4307 _set_invalid_parameter_handler(&invalid_parameter_handler);
4309 bool loaded()
const {
return true; }
4313 std::unique_lock<std::mutex> lk(mtx());
4314 crashed() = crash_status::normal_exit;
4319 reporter_thread_.join();
4323 static CONTEXT *ctx() {
4324 static CONTEXT data;
4328 enum class crash_status { running, crashed, normal_exit, ending };
4330 static crash_status &crashed() {
4331 static crash_status data;
4335 static std::mutex &mtx() {
4336 static std::mutex data;
4340 static std::condition_variable &cv() {
4341 static std::condition_variable data;
4345 static HANDLE &thread_handle() {
4346 static HANDLE handle;
4350 std::thread reporter_thread_;
4353 static const constexpr
int signal_skip_recs =
4366 static int &skip_recs() {
4371 static inline void terminator() {
4372 crash_handler(signal_skip_recs);
4376 static inline void signal_handler(
int) {
4377 crash_handler(signal_skip_recs);
4381 static inline void __cdecl invalid_parameter_handler(
const wchar_t *,
4386 crash_handler(signal_skip_recs);
4390 NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) {
4393 crash_handler(0, info->ContextRecord);
4394 return EXCEPTION_CONTINUE_SEARCH;
4397 NOINLINE static void crash_handler(
int skip, CONTEXT *ct =
nullptr) {
4399 if (ct ==
nullptr) {
4400 RtlCaptureContext(ctx());
4402 memcpy(ctx(), ct,
sizeof(CONTEXT));
4404 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
4405 GetCurrentProcess(), &thread_handle(), 0, FALSE,
4406 DUPLICATE_SAME_ACCESS);
4411 std::unique_lock<std::mutex> lk(mtx());
4412 crashed() = crash_status::crashed;
4418 std::unique_lock<std::mutex> lk(mtx());
4419 cv().wait(lk, [] {
return crashed() != crash_status::crashed; });
4423 static void handle_stacktrace(
int skip_frames = 0) {
4432 st.set_machine_type(printer.resolver().machine_type());
4433 st.set_thread_handle(thread_handle());
4434 st.load_here(32 + skip_frames, ctx());
4435 st.skip_n_firsts(skip_frames);
4437 printer.address =
true;
4438 printer.print(st, std::cerr);
4442 #endif // BACKWARD_SYSTEM_WINDOWS
4444 #ifdef BACKWARD_SYSTEM_UNKNOWN
4453 #endif // BACKWARD_SYSTEM_UNKNOWN