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
39 #define BACKWARD_CXX98
40 #define BACKWARD_ATLEAST_CXX98
55 #if defined(BACKWARD_SYSTEM_LINUX)
56 #elif defined(BACKWARD_SYSTEM_DARWIN)
57 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
58 #elif defined(BACKWARD_SYSTEM_WINDOWS)
60 #if defined(__linux) || defined(__linux__)
61 #define BACKWARD_SYSTEM_LINUX
62 #elif defined(__APPLE__)
63 #define BACKWARD_SYSTEM_DARWIN
65 #define BACKWARD_SYSTEM_WINDOWS
67 #define BACKWARD_SYSTEM_UNKNOWN
71 #define NOINLINE __attribute__((noinline))
88 #if defined(BACKWARD_SYSTEM_LINUX)
111 #if BACKWARD_HAS_UNWIND == 1
112 #elif BACKWARD_HAS_BACKTRACE == 1
114 #undef BACKWARD_HAS_UNWIND
115 #define BACKWARD_HAS_UNWIND 1
116 #undef BACKWARD_HAS_BACKTRACE
117 #define BACKWARD_HAS_BACKTRACE 0
169 #if BACKWARD_HAS_DW == 1
170 #elif BACKWARD_HAS_BFD == 1
171 #elif BACKWARD_HAS_DWARF == 1
172 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
174 #undef BACKWARD_HAS_DW
175 #define BACKWARD_HAS_DW 0
176 #undef BACKWARD_HAS_BFD
177 #define BACKWARD_HAS_BFD 0
178 #undef BACKWARD_HAS_DWARF
179 #define BACKWARD_HAS_DWARF 0
180 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
181 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
190 #define _Unwind_Ptr _Unwind_Ptr_Custom
197 #include <sys/stat.h>
201 #if BACKWARD_HAS_BFD == 1
208 #ifndef PACKAGE_VERSION
209 #define PACKAGE_VERSION
221 #if BACKWARD_HAS_DW == 1
223 #include <elfutils/libdw.h>
224 #include <elfutils/libdwfl.h>
227 #if BACKWARD_HAS_DWARF == 1
230 #include <libdwarf.h>
242 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
244 #include <execinfo.h>
247 #endif // defined(BACKWARD_SYSTEM_LINUX)
249 #if defined(BACKWARD_SYSTEM_DARWIN)
269 #if BACKWARD_HAS_UNWIND == 1
270 #elif BACKWARD_HAS_BACKTRACE == 1
272 #undef BACKWARD_HAS_UNWIND
273 #define BACKWARD_HAS_UNWIND 1
274 #undef BACKWARD_HAS_BACKTRACE
275 #define BACKWARD_HAS_BACKTRACE 0
289 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
291 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
292 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
299 #include <sys/stat.h>
302 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
303 #include <execinfo.h>
305 #endif // defined(BACKWARD_SYSTEM_DARWIN)
307 #if defined(BACKWARD_SYSTEM_WINDOWS)
309 #include <condition_variable>
314 typedef SSIZE_T ssize_t;
325 #define NOINLINE __declspec(noinline)
328 #pragma comment(lib, "psapi.lib")
329 #pragma comment(lib, "dbghelp.lib")
335 #pragma pack(push, before_imagehlp, 8)
336 #include <imagehlp.h>
337 #pragma pack(pop, before_imagehlp)
340 #undef BACKWARD_HAS_UNWIND
341 #undef BACKWARD_HAS_BACKTRACE
342 #if BACKWARD_HAS_PDB_SYMBOL == 1
344 #undef BACKWARD_HAS_PDB_SYMBOL
345 #define BACKWARD_HAS_PDB_SYMBOL 1
350 #if BACKWARD_HAS_UNWIND == 1
365 #ifdef __CLANG_UNWIND_H
368 #include <inttypes.h>
369 extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *,
int *);
372 #endif // BACKWARD_HAS_UNWIND == 1
374 #ifdef BACKWARD_ATLEAST_CXX11
375 #include <unordered_map>
379 template <
typename K,
typename V>
struct hashtable {
380 typedef std::unordered_map<K, V>
type;
385 #else // NOT BACKWARD_ATLEAST_CXX11
394 template <
typename T>
const T &
move(
const T &v) {
return v; }
395 template <
typename T> T &
move(T &v) {
return v; }
398 #endif // BACKWARD_ATLEAST_CXX11
402 #if defined(BACKWARD_SYSTEM_WINDOWS)
412 namespace system_tag {
419 #if defined(BACKWARD_SYSTEM_LINUX)
421 #elif defined(BACKWARD_SYSTEM_DARWIN)
423 #elif defined(BACKWARD_SYSTEM_WINDOWS)
425 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
428 #error "May I please get my system defines?"
432 namespace trace_resolver_tag {
433 #if defined(BACKWARD_SYSTEM_LINUX)
437 struct backtrace_symbol;
439 #if BACKWARD_HAS_DW == 1
440 typedef libdw current;
441 #elif BACKWARD_HAS_BFD == 1
442 typedef libbfd current;
443 #elif BACKWARD_HAS_DWARF == 1
444 typedef libdwarf current;
445 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
446 typedef backtrace_symbol current;
448 #error "You shall not pass, until you know what you want."
450 #elif defined(BACKWARD_SYSTEM_DARWIN)
451 struct backtrace_symbol;
453 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
454 typedef backtrace_symbol current;
456 #error "You shall not pass, until you know what you want."
458 #elif defined(BACKWARD_SYSTEM_WINDOWS)
460 #if BACKWARD_HAS_PDB_SYMBOL == 1
461 typedef pdb_symbol current;
463 #error "You shall not pass, until you know what you want."
472 template <
typename T>
struct rm_ptr<T *> {
typedef T
type; };
474 template <
typename T>
struct rm_ptr<const T *> {
typedef const T
type; };
476 template <
typename R,
typename T, R (*F)(T)>
struct deleter {
484 template <
typename T,
typename Deleter = deleter<
void,
void *, &::free> >
490 #ifdef BACKWARD_ATLEAST_CXX11
508 #ifdef BACKWARD_ATLEAST_CXX11
533 _empty =
static_cast<bool>(new_val);
540 return reinterpret_cast<const dummy *
>(
_val);
575 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
577 template <>
struct demangler_impl<system_tag::
current_tag> {
578 demangler_impl() : _demangle_buffer_length(0) {}
581 using namespace details;
582 char *result = abi::__cxa_demangle(
funcname, _demangle_buffer.get(),
583 &_demangle_buffer_length,
nullptr);
585 _demangle_buffer.update(result);
592 details::handle<char *> _demangle_buffer;
593 size_t _demangle_buffer_length;
596 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
609 std::vector<std::string> out;
614 out.push_back(
s.substr(last,
next-last));
615 last =
next + delimiter_size;
617 if (last <=
s.length()) {
618 out.push_back(
s.substr(last));
633 explicit Trace(
void *_addr,
size_t _idx) : addr(_addr), idx(_idx) {}
639 std::string
function;
648 line == b.
line && col == b.
col;
682 size_t size()
const {
return 0; }
700 #ifdef BACKWARD_SYSTEM_LINUX
702 _thread_id =
static_cast<size_t>(syscall(SYS_gettid));
704 _thread_id =
static_cast<size_t>(gettid());
706 if (_thread_id ==
static_cast<size_t>(getpid())) {
711 #elif defined(BACKWARD_SYSTEM_DARWIN)
712 _thread_id =
reinterpret_cast<size_t>(pthread_self());
713 if (pthread_main_np() == 1) {
730 return _stacktrace.size() ? _stacktrace.size() - skip_n_firsts() : 0;
736 return Trace(_stacktrace[idx + skip_n_firsts()], idx);
740 return &_stacktrace[skip_n_firsts()];
749 #if BACKWARD_HAS_UNWIND == 1
753 template <
typename F>
class Unwinder {
755 size_t operator()(F &
f,
size_t depth) {
759 _Unwind_Backtrace(&this->backtrace_trampoline,
this);
760 return static_cast<size_t>(_index);
768 static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx,
770 return (
static_cast<Unwinder *
>(
self))->backtrace(ctx);
773 _Unwind_Reason_Code backtrace(_Unwind_Context *ctx) {
774 if (_index >= 0 &&
static_cast<size_t>(_index) >= _depth)
775 return _URC_END_OF_STACK;
777 int ip_before_instruction = 0;
778 uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
780 if (!ip_before_instruction) {
784 ip = std::numeric_limits<uintptr_t>::max();
793 (*_f)(
static_cast<size_t>(_index),
reinterpret_cast<void *
>(
ip));
796 return _URC_NO_REASON;
800 template <
typename F>
size_t unwind(F f,
size_t depth) {
801 Unwinder<F> unwinder;
802 return unwinder(f, depth);
808 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
811 size_t load_here(
size_t depth = 32) {
816 _stacktrace.resize(depth);
817 size_t trace_cnt = details::unwind(callback(*
this), depth);
818 _stacktrace.resize(trace_cnt);
822 size_t load_from(
void *addr,
size_t depth = 32) {
823 load_here(depth + 8);
825 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
826 if (_stacktrace[i] == addr) {
832 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
838 StackTraceImpl &
self;
839 callback(StackTraceImpl &_self) : self(_self) {}
841 void operator()(
size_t idx,
void *addr) {
self._stacktrace[idx] = addr; }
845 #elif defined(BACKWARD_HAS_BACKTRACE)
848 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
851 size_t load_here(
size_t depth = 32) {
856 _stacktrace.resize(depth + 1);
857 size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
858 _stacktrace.resize(trace_cnt);
863 size_t load_from(
void *addr,
size_t depth = 32) {
864 load_here(depth + 8);
866 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
867 if (_stacktrace[i] == addr) {
869 _stacktrace[i] = (
void *)((
uintptr_t)_stacktrace[i] + 1);
874 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
879 #elif defined(BACKWARD_SYSTEM_WINDOWS)
882 class StackTraceImpl<system_tag::
current_tag> :
public StackTraceImplHolder {
886 void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; }
887 void set_context(CONTEXT *ctx) { ctx_ = ctx; }
888 void set_thread_handle(HANDLE handle) { thd_ = handle; }
891 size_t load_here(
size_t depth = 32) {
901 RtlCaptureContext(ctx_);
905 thd_ = GetCurrentThread();
908 HANDLE process = GetCurrentProcess();
911 memset(&s, 0,
sizeof(STACKFRAME64));
914 s.AddrStack.Mode = AddrModeFlat;
915 s.AddrFrame.Mode = AddrModeFlat;
916 s.AddrPC.Mode = AddrModeFlat;
918 s.AddrPC.Offset = ctx_->Rip;
919 s.AddrStack.Offset = ctx_->Rsp;
920 s.AddrFrame.Offset = ctx_->Rbp;
922 s.AddrPC.Offset = ctx_->Eip;
923 s.AddrStack.Offset = ctx_->Esp;
924 s.AddrFrame.Offset = ctx_->Ebp;
927 if (!machine_type_) {
929 machine_type_ = IMAGE_FILE_MACHINE_AMD64;
931 machine_type_ = IMAGE_FILE_MACHINE_I386;
938 if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL,
939 SymFunctionTableAccess64, SymGetModuleBase64, NULL))
942 if (
s.AddrReturn.Offset == 0)
945 _stacktrace.push_back(
reinterpret_cast<void *
>(
s.AddrPC.Offset));
954 size_t load_from(
void *addr,
size_t depth = 32) {
955 load_here(depth + 8);
957 for (
size_t i = 0; i < _stacktrace.size(); ++i) {
958 if (_stacktrace[i] == addr) {
964 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
969 DWORD machine_type_ = 0;
971 CONTEXT *ctx_ =
nullptr;
982 #ifdef BACKWARD_SYSTEM_UNKNOWN
995 return _demangler.demangle(
funcname);
1002 #ifdef BACKWARD_SYSTEM_LINUX
1004 class TraceResolverLinuxBase
1007 TraceResolverLinuxBase()
1008 : argv0_(get_argv0()), exec_path_(read_symlink(
"/proc/self/exe")) {
1010 std::string resolve_exec_path(Dl_info &symbol_info)
const {
1012 if(symbol_info.dli_fname == argv0_) {
1019 symbol_info.dli_fname =
"/proc/self/exe";
1022 return symbol_info.dli_fname;
1027 std::string exec_path_;
1029 static std::string get_argv0() {
1031 std::ifstream ifs(
"/proc/self/cmdline");
1032 std::getline(ifs, argv0,
'\0');
1036 static std::string read_symlink(std::string
const &symlink_path) {
1042 ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
1046 if (
static_cast<size_t>(len) == path.size()) {
1047 path.resize(path.size() * 2);
1049 path.resize(
static_cast<std::string::size_type
>(len));
1058 template <
typename STACKTRACE_TAG>
class TraceResolverLinuxImpl;
1060 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1063 class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>
1064 :
public TraceResolverLinuxBase {
1066 template <
class ST>
void load_stacktrace(ST &st) {
1067 using namespace details;
1068 if (st.size() == 0) {
1071 _symbols.reset(backtrace_symbols(st.begin(), (
int)st.size()));
1074 ResolvedTrace
resolve(ResolvedTrace trace) {
1075 char *filename = _symbols[trace.idx];
1080 trace.object_filename.assign(filename,
1087 while (*funcname_end && *funcname_end !=
')' && *funcname_end !=
'+') {
1090 *funcname_end =
'\0';
1091 trace.object_function = this->
demangle(funcname);
1092 trace.source.function = trace.object_function;
1098 details::handle<char **> _symbols;
1101 #endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1103 #if BACKWARD_HAS_BFD == 1
1106 class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>
1107 :
public TraceResolverLinuxBase {
1109 TraceResolverLinuxImpl() : _bfd_loaded(false) {}
1111 template <
class ST>
void load_stacktrace(ST &) {}
1113 ResolvedTrace
resolve(ResolvedTrace trace) {
1114 Dl_info symbol_info;
1119 if (!dladdr(trace.addr, &symbol_info)) {
1134 if (symbol_info.dli_sname) {
1135 trace.object_function =
demangle(symbol_info.dli_sname);
1138 if (!symbol_info.dli_fname) {
1142 trace.object_filename = resolve_exec_path(symbol_info);
1143 bfd_fileobject &fobj = load_object_with_bfd(symbol_info.dli_fname);
1148 find_sym_result *details_selected;
1155 find_sym_result details_call_site =
1156 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1157 details_selected = &details_call_site;
1159 #if BACKWARD_HAS_UNWIND == 0
1167 find_sym_result details_adjusted_call_site = find_symbol_details(
1168 fobj, (
void *)(
uintptr_t(trace.addr) - 1), symbol_info.dli_fbase);
1171 if (details_call_site.found && details_adjusted_call_site.found) {
1173 details_selected = &details_adjusted_call_site;
1174 trace.addr = (
void *)(
uintptr_t(trace.addr) - 1);
1177 if (details_selected == &details_call_site && details_call_site.found) {
1182 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1184 #endif // BACKWARD_HAS_UNWIND
1186 if (details_selected->found) {
1187 if (details_selected->filename) {
1188 trace.source.filename = details_selected->filename;
1190 trace.source.line = details_selected->line;
1192 if (details_selected->funcname) {
1198 trace.source.function =
demangle(details_selected->funcname);
1200 if (!symbol_info.dli_sname) {
1204 trace.object_function = trace.source.function;
1211 trace.inliners = backtrace_inliners(fobj, *details_selected);
1214 if (trace.inliners.size() == 0) {
1233 if (symbol_info.dli_saddr) {
1234 find_sym_result details = find_symbol_details(fobj,
1235 symbol_info.dli_saddr,
1236 symbol_info.dli_fbase);
1238 if (details.found) {
1239 ResolvedTrace::SourceLoc diy_inliner;
1240 diy_inliner.line = details.line;
1241 if (details.filename) {
1242 diy_inliner.filename = details.filename;
1244 if (details.funcname) {
1245 diy_inliner.function =
demangle(details.funcname);
1247 diy_inliner.function = trace.source.function;
1249 if (diy_inliner != trace.source) {
1250 trace.inliners.push_back(diy_inliner);
1264 typedef details::handle<bfd *,
1265 details::deleter<bfd_boolean, bfd *, &bfd_close> >
1268 typedef details::handle<asymbol **> bfd_symtab_t;
1270 struct bfd_fileobject {
1271 bfd_handle_t handle;
1273 bfd_symtab_t symtab;
1274 bfd_symtab_t dynamic_symtab;
1278 fobj_bfd_map_t _fobj_bfd_map;
1280 bfd_fileobject &load_object_with_bfd(
const std::string &filename_object) {
1281 using namespace details;
1284 using namespace details;
1289 fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object);
1290 if (it != _fobj_bfd_map.end()) {
1295 bfd_fileobject &r = _fobj_bfd_map[filename_object];
1298 bfd_handle_t bfd_handle;
1300 int fd = open(filename_object.c_str(), O_RDONLY);
1301 bfd_handle.reset(bfd_fdopenr(filename_object.c_str(),
"default", fd));
1307 if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
1311 if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
1315 ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get());
1317 ssize_t dyn_symtab_storage_size =
1318 bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
1320 if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
1324 bfd_symtab_t symtab, dynamic_symtab;
1325 ssize_t symcount = 0, dyn_symcount = 0;
1327 if (symtab_storage_size > 0) {
1328 symtab.reset(
static_cast<bfd_symbol **
>(
1329 malloc(
static_cast<size_t>(symtab_storage_size))));
1330 symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get());
1333 if (dyn_symtab_storage_size > 0) {
1334 dynamic_symtab.reset(
static_cast<bfd_symbol **
>(
1335 malloc(
static_cast<size_t>(dyn_symtab_storage_size))));
1336 dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(),
1337 dynamic_symtab.get());
1340 if (symcount <= 0 && dyn_symcount <= 0) {
1344 r.handle =
move(bfd_handle);
1345 r.symtab =
move(symtab);
1346 r.dynamic_symtab =
move(dynamic_symtab);
1350 struct find_sym_result {
1352 const char *filename;
1357 struct find_sym_context {
1358 TraceResolverLinuxImpl *
self;
1359 bfd_fileobject *fobj;
1362 find_sym_result result;
1365 find_sym_result find_symbol_details(bfd_fileobject &fobj,
void *addr,
1367 find_sym_context context;
1368 context.self =
this;
1369 context.fobj = &fobj;
1370 context.addr = addr;
1371 context.base_addr = base_addr;
1372 context.result.found =
false;
1373 bfd_map_over_sections(fobj.handle.get(), &find_in_section_trampoline,
1374 static_cast<void *
>(&context));
1375 return context.result;
1378 static void find_in_section_trampoline(bfd *, asection *section,
void *
data) {
1379 find_sym_context *context =
static_cast<find_sym_context *
>(
data);
1380 context->self->find_in_section(
1381 reinterpret_cast<bfd_vma
>(context->addr),
1382 reinterpret_cast<bfd_vma
>(context->base_addr), *context->fobj, section,
1386 void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject &fobj,
1387 asection *section, find_sym_result &result) {
1391 #ifdef bfd_get_section_flags
1392 if ((bfd_get_section_flags(fobj.handle.get(), section) & SEC_ALLOC) == 0)
1394 if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
1398 #ifdef bfd_get_section_vma
1399 bfd_vma sec_addr = bfd_get_section_vma(fobj.handle.get(), section);
1401 bfd_vma sec_addr = bfd_section_vma(section);
1403 #ifdef bfd_get_section_size
1404 bfd_size_type
size = bfd_get_section_size(section);
1406 bfd_size_type
size = bfd_section_size(section);
1410 if (addr < sec_addr || addr >= sec_addr +
size) {
1412 if (addr < sec_addr || addr >= sec_addr +
size) {
1417 #if defined(__clang__)
1418 #pragma clang diagnostic push
1419 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1421 if (!result.found && fobj.symtab) {
1422 result.found = bfd_find_nearest_line(
1423 fobj.handle.get(), section, fobj.symtab.get(), addr - sec_addr,
1424 &result.filename, &result.funcname, &result.line);
1427 if (!result.found && fobj.dynamic_symtab) {
1428 result.found = bfd_find_nearest_line(
1429 fobj.handle.get(), section, fobj.dynamic_symtab.get(),
1430 addr - sec_addr, &result.filename, &result.funcname, &result.line);
1432 #if defined(__clang__)
1433 #pragma clang diagnostic pop
1438 backtrace_inliners(bfd_fileobject &fobj, find_sym_result previous_result) {
1442 while (previous_result.found) {
1443 find_sym_result result;
1444 result.found = bfd_find_inliner_info(fobj.handle.get(), &result.filename,
1445 &result.funcname, &result.line);
1455 ResolvedTrace::SourceLoc src_loc;
1456 src_loc.line = result.line;
1457 if (result.filename) {
1458 src_loc.filename = result.filename;
1460 if (result.funcname) {
1461 src_loc.function =
demangle(result.funcname);
1463 results.push_back(src_loc);
1465 previous_result = result;
1470 bool cstrings_eq(
const char *a,
const char *b) {
1474 return strcmp(a, b) == 0;
1477 #endif // BACKWARD_HAS_BFD == 1
1479 #if BACKWARD_HAS_DW == 1
1482 class TraceResolverLinuxImpl<trace_resolver_tag::libdw>
1483 :
public TraceResolverLinuxBase {
1485 TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {}
1487 template <
class ST>
void load_stacktrace(ST &) {}
1489 ResolvedTrace
resolve(ResolvedTrace trace) {
1490 using namespace details;
1492 Dwarf_Addr trace_addr = (Dwarf_Addr)trace.addr;
1494 if (!_dwfl_handle_initialized) {
1496 _dwfl_cb.reset(
new Dwfl_Callbacks);
1497 _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
1498 _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
1499 _dwfl_cb->debuginfo_path = 0;
1501 _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
1502 _dwfl_handle_initialized =
true;
1504 if (!_dwfl_handle) {
1509 dwfl_report_begin(_dwfl_handle.get());
1510 int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid());
1511 dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
1517 if (!_dwfl_handle) {
1524 Dwfl_Module *
mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
1528 const char *module_name = dwfl_module_info(
mod, 0, 0, 0, 0, 0, 0, 0);
1530 trace.object_filename = module_name;
1537 const char *sym_name = dwfl_module_addrname(
mod, trace_addr);
1539 trace.object_function =
demangle(sym_name);
1549 Dwarf_Addr mod_bias = 0;
1550 Dwarf_Die *cudie = dwfl_module_addrdie(
mod, trace_addr, &mod_bias);
1564 while ((cudie = dwfl_module_nextcu(
mod, cudie, &mod_bias))) {
1567 find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem);
1576 #ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1583 Dwarf_Addr cfi_bias;
1584 Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(
mod, &cfi_bias);
1587 while ((cudie = dwfl_module_nextcu(
mod, cudie, &bias))) {
1588 if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
1596 handle<Dwarf_Frame *> frame;
1597 dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
1614 Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
1617 const char *srcfile = dwarf_linesrc(srcloc, 0, 0);
1619 trace.source.filename = srcfile;
1621 int line = 0, col = 0;
1622 dwarf_lineno(srcloc, &line);
1623 dwarf_linecol(srcloc, &col);
1624 trace.source.line = line;
1625 trace.source.col = col;
1628 deep_first_search_by_pc(cudie, trace_addr - mod_bias,
1629 inliners_search_cb(trace));
1630 if (trace.source.function.size() == 0) {
1632 trace.source.function = trace.object_function;
1639 typedef details::handle<Dwfl *, details::deleter<void, Dwfl *, &dwfl_end> >
1641 details::handle<Dwfl_Callbacks *, details::default_delete<Dwfl_Callbacks *> >
1643 dwfl_handle_t _dwfl_handle;
1644 bool _dwfl_handle_initialized;
1648 struct inliners_search_cb {
1649 void operator()(Dwarf_Die *die) {
1650 switch (dwarf_tag(die)) {
1652 case DW_TAG_subprogram:
1653 if ((name = dwarf_diename(die))) {
1654 trace.source.function =
name;
1658 case DW_TAG_inlined_subroutine:
1659 ResolvedTrace::SourceLoc sloc;
1660 Dwarf_Attribute attr_mem;
1662 if ((name = dwarf_diename(die))) {
1663 sloc.function =
name;
1665 if ((name = die_call_file(die))) {
1666 sloc.filename =
name;
1669 Dwarf_Word line = 0, col = 0;
1670 dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line);
1671 dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col);
1672 sloc.line = (unsigned)line;
1673 sloc.col = (unsigned)col;
1675 trace.inliners.push_back(sloc);
1679 ResolvedTrace &trace;
1680 inliners_search_cb(ResolvedTrace &t) : trace(t) {}
1683 static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) {
1684 Dwarf_Addr low, high;
1687 if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) {
1688 if (dwarf_lowpc(die, &low) != 0) {
1691 if (dwarf_highpc(die, &high) != 0) {
1692 Dwarf_Attribute attr_mem;
1693 Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
1695 if (dwarf_formudata(attr, &value) != 0) {
1700 return pc >= low && pc < high;
1705 ptrdiff_t offset = 0;
1706 while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
1707 if (pc >= low && pc < high) {
1714 static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
1715 Dwarf_Die *result) {
1716 if (dwarf_child(parent_die, result) != 0) {
1720 Dwarf_Die *die = result;
1722 switch (dwarf_tag(die)) {
1723 case DW_TAG_subprogram:
1724 case DW_TAG_inlined_subroutine:
1725 if (die_has_pc(die, pc)) {
1729 bool declaration =
false;
1730 Dwarf_Attribute attr_mem;
1731 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
1738 Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem);
1744 }
while (dwarf_siblingof(die, result) == 0);
1748 template <
typename CB>
1749 static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
1752 if (dwarf_child(parent_die, &die_mem) != 0) {
1756 bool branch_has_pc =
false;
1757 Dwarf_Die *die = &die_mem;
1759 bool declaration =
false;
1760 Dwarf_Attribute attr_mem;
1761 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
1768 branch_has_pc = deep_first_search_by_pc(die, pc, cb);
1770 if (!branch_has_pc) {
1771 branch_has_pc = die_has_pc(die, pc);
1773 if (branch_has_pc) {
1776 }
while (dwarf_siblingof(die, &die_mem) == 0);
1777 return branch_has_pc;
1780 static const char *die_call_file(Dwarf_Die *die) {
1781 Dwarf_Attribute attr_mem;
1782 Dwarf_Sword file_idx = 0;
1784 dwarf_formsdata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx);
1786 if (file_idx == 0) {
1791 Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0);
1796 Dwarf_Files *files = 0;
1798 dwarf_getsrcfiles(cudie, &files, &nfiles);
1803 return dwarf_filesrc(files, file_idx, 0, 0);
1806 #endif // BACKWARD_HAS_DW == 1
1808 #if BACKWARD_HAS_DWARF == 1
1811 class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>
1812 :
public TraceResolverLinuxBase {
1814 TraceResolverLinuxImpl() : _dwarf_loaded(false) {}
1816 template <
class ST>
void load_stacktrace(ST &) {}
1818 ResolvedTrace
resolve(ResolvedTrace trace) {
1823 Dl_info symbol_info;
1824 int dladdr_result = 0;
1825 #if defined(__GLIBC__)
1829 dladdr1(trace.addr, &symbol_info,
reinterpret_cast<void **
>(&link_map),
1833 dladdr_result = dladdr(trace.addr, &symbol_info);
1835 if (!dladdr_result) {
1857 if (symbol_info.dli_sname) {
1858 trace.object_function =
demangle(symbol_info.dli_sname);
1861 if (!symbol_info.dli_fname) {
1865 trace.object_filename = resolve_exec_path(symbol_info);
1866 dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname);
1867 if (!fobj.dwarf_handle) {
1871 #if defined(__GLIBC__)
1874 Dwarf_Addr address =
reinterpret_cast<uintptr_t>(trace.addr) -
1875 reinterpret_cast<uintptr_t>(link_map->l_addr);
1877 Dwarf_Addr address =
reinterpret_cast<uintptr_t>(trace.addr);
1880 if (trace.object_function.empty()) {
1881 symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address);
1883 if (it != fobj.symbol_cache.end()) {
1884 if (it->first != address) {
1885 if (it != fobj.symbol_cache.begin()) {
1889 trace.object_function =
demangle(it->second.c_str());
1894 Dwarf_Die die = find_die(fobj, address);
1903 die_cache_entry &die_object = get_die_cache(fobj, die);
1904 if (die_object.isEmpty())
1907 die_linemap_t::iterator it = die_object.line_section.lower_bound(address);
1909 if (it != die_object.line_section.end()) {
1910 if (it->first != address) {
1911 if (it == die_object.line_section.begin()) {
1926 Dwarf_Line line = die_object.line_buffer[it->second];
1927 Dwarf_Error
error = DW_DLE_NE;
1930 if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) {
1931 trace.source.filename = std::string(filename);
1932 dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
1935 Dwarf_Unsigned
number = 0;
1936 if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
1937 trace.source.line =
number;
1939 trace.source.line = 0;
1942 if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
1943 trace.source.col =
number;
1945 trace.source.col = 0;
1948 std::vector<std::string> namespace_stack;
1949 deep_first_search_by_pc(fobj, die, address, namespace_stack,
1950 inliners_search_cb(trace, fobj, die));
1952 dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
1958 static int close_dwarf(Dwarf_Debug dwarf) {
1959 return dwarf_finish(dwarf, NULL);
1965 typedef details::handle<int, details::deleter<int, int, &::close> >
1968 typedef details::handle<Elf *, details::deleter<int, Elf *, &elf_end> >
1971 typedef details::handle<Dwarf_Debug,
1972 details::deleter<int, Dwarf_Debug, &close_dwarf> >
1975 typedef std::map<Dwarf_Addr, int> die_linemap_t;
1977 typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
1979 struct die_cache_entry {
1980 die_specmap_t spec_section;
1981 die_linemap_t line_section;
1982 Dwarf_Line *line_buffer;
1983 Dwarf_Signed line_count;
1984 Dwarf_Line_Context line_context;
1986 inline bool isEmpty() {
1987 return line_buffer == NULL || line_count == 0 || line_context == NULL ||
1988 line_section.empty();
1991 die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {}
1993 ~die_cache_entry() {
1995 dwarf_srclines_dealloc_b(line_context);
2000 typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
2002 typedef std::map<uintptr_t, std::string> symbol_cache_t;
2004 struct dwarf_fileobject {
2005 dwarf_file_t file_handle;
2006 dwarf_elf_t elf_handle;
2007 dwarf_handle_t dwarf_handle;
2008 symbol_cache_t symbol_cache;
2011 die_cache_t die_cache;
2012 die_cache_entry *current_cu;
2017 fobj_dwarf_map_t _fobj_dwarf_map;
2019 static bool cstrings_eq(
const char *a,
const char *b) {
2023 return strcmp(a, b) == 0;
2026 dwarf_fileobject &load_object_with_dwarf(
const std::string &filename_object) {
2028 if (!_dwarf_loaded) {
2031 _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
2034 fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object);
2035 if (it != _fobj_dwarf_map.end()) {
2040 dwarf_fileobject &r = _fobj_dwarf_map[filename_object];
2042 dwarf_file_t file_handle;
2043 file_handle.reset(open(filename_object.c_str(), O_RDONLY));
2044 if (file_handle.get() < 0) {
2051 dwarf_elf_t elf_handle;
2052 elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
2057 const char *e_ident = elf_getident(elf_handle.get(), 0);
2065 if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
2070 size_t shdrstrndx = 0;
2071 if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) {
2075 std::string debuglink;
2081 #define ELF_GET_DATA(ARCH) \
2082 Elf_Scn *elf_section = 0; \
2083 Elf_Data *elf_data = 0; \
2084 Elf##ARCH##_Shdr *section_header = 0; \
2085 Elf_Scn *symbol_section = 0; \
2086 size_t symbol_count = 0; \
2087 size_t symbol_strings = 0; \
2088 Elf##ARCH##_Sym *symbol = 0; \
2089 const char *section_name = 0; \
2091 while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \
2092 section_header = elf##ARCH##_getshdr(elf_section); \
2093 if (section_header == NULL) { \
2097 if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \
2098 section_header->sh_name)) == NULL) { \
2102 if (cstrings_eq(section_name, ".gnu_debuglink")) { \
2103 elf_data = elf_getdata(elf_section, NULL); \
2104 if (elf_data && elf_data->d_size > 0) { \
2106 std::string(reinterpret_cast<const char *>(elf_data->d_buf)); \
2110 switch (section_header->sh_type) { \
2112 symbol_section = elf_section; \
2113 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2114 symbol_strings = section_header->sh_link; \
2119 if (!symbol_section) { \
2120 symbol_section = elf_section; \
2121 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2122 symbol_strings = section_header->sh_link; \
2128 if (symbol_section && symbol_count && symbol_strings) { \
2129 elf_data = elf_getdata(symbol_section, NULL); \
2130 symbol = reinterpret_cast<Elf##ARCH##_Sym *>(elf_data->d_buf); \
2131 for (size_t i = 0; i < symbol_count; ++i) { \
2132 int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
2133 if (type == STT_FUNC && symbol->st_value > 0) { \
2134 r.symbol_cache[symbol->st_value] = std::string( \
2135 elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \
2141 if (e_ident[EI_CLASS] == ELFCLASS32) {
2143 }
else if (e_ident[EI_CLASS] == ELFCLASS64) {
2150 if (!debuglink.empty()) {
2154 dwarf_file_t debuglink_file;
2155 debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
2156 if (debuglink_file.get() > 0) {
2157 dwarf_elf_t debuglink_elf;
2158 debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL));
2162 if (debuglink_elf) {
2163 elf_handle =
move(debuglink_elf);
2164 file_handle =
move(debuglink_file);
2170 Dwarf_Debug dwarf_debug;
2171 Dwarf_Error
error = DW_DLE_NE;
2172 dwarf_handle_t dwarf_handle;
2174 int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL,
2175 &dwarf_debug, &error);
2180 if (dwarf_result != DW_DLV_OK) {
2184 dwarf_handle.reset(dwarf_debug);
2186 r.file_handle =
move(file_handle);
2187 r.elf_handle =
move(elf_handle);
2188 r.dwarf_handle =
move(dwarf_handle);
2193 die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) {
2194 Dwarf_Error
error = DW_DLE_NE;
2197 Dwarf_Off die_offset;
2198 if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
2202 die_cache_t::iterator it = fobj.die_cache.find(die_offset);
2204 if (it != fobj.die_cache.end()) {
2205 fobj.current_cu = &it->second;
2209 die_cache_entry &de = fobj.die_cache[die_offset];
2210 fobj.current_cu = &de;
2212 Dwarf_Addr line_addr;
2213 Dwarf_Small table_count;
2229 if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) ==
2233 if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer,
2235 &error) == DW_DLV_OK) {
2238 for (
int i = 0; i < de.line_count; i++) {
2239 if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) !=
2243 de.line_section.insert(std::pair<Dwarf_Addr, int>(line_addr, i));
2257 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2258 Dwarf_Die current_die = 0;
2259 if (dwarf_child(die, ¤t_die, &error) == DW_DLV_OK) {
2261 Dwarf_Die sibling_die = 0;
2263 Dwarf_Half tag_value;
2264 dwarf_tag(current_die, &tag_value, &error);
2266 if (tag_value == DW_TAG_subprogram ||
2267 tag_value == DW_TAG_inlined_subroutine) {
2269 Dwarf_Bool has_attr = 0;
2270 if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr,
2271 &error) == DW_DLV_OK) {
2273 Dwarf_Attribute attr_mem;
2274 if (dwarf_attr(current_die, DW_AT_specification, &attr_mem,
2275 &error) == DW_DLV_OK) {
2276 Dwarf_Off spec_offset = 0;
2277 if (dwarf_formref(attr_mem, &spec_offset, &error) ==
2279 Dwarf_Off spec_die_offset;
2280 if (dwarf_dieoffset(current_die, &spec_die_offset, &error) ==
2282 de.spec_section[spec_offset] = spec_die_offset;
2286 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2291 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
2292 if (result == DW_DLV_ERROR) {
2294 }
else if (result == DW_DLV_NO_ENTRY) {
2298 if (current_die != die) {
2299 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2303 current_die = sibling_die;
2309 static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die,
2310 Dwarf_Half attr,
bool global) {
2311 Dwarf_Error
error = DW_DLE_NE;
2312 Dwarf_Attribute attr_mem;
2314 Dwarf_Die found_die = NULL;
2315 if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
2319 result = dwarf_global_formref(attr_mem, &offset, &error);
2321 result = dwarf_formref(attr_mem, &offset, &error);
2324 if (result == DW_DLV_OK) {
2325 if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) {
2329 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2334 static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die,
2335 Dwarf_Half attr,
bool global) {
2336 Dwarf_Error
error = DW_DLE_NE;
2339 Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
2343 if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
2345 value = std::string(name);
2347 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2349 dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
2357 static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) {
2358 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2359 Dwarf_Error
error = DW_DLE_NE;
2360 Dwarf_Off die_offset;
2361 if (fobj.current_cu &&
2362 dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) {
2363 die_specmap_t::iterator it =
2364 fobj.current_cu->spec_section.find(die_offset);
2368 if (it != fobj.current_cu->spec_section.end()) {
2369 Dwarf_Die spec_die = 0;
2370 if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) {
2377 return get_referenced_die(fobj.dwarf_handle.get(), die,
2378 DW_AT_abstract_origin,
true);
2381 static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) {
2382 Dwarf_Addr low_pc = 0, high_pc = 0;
2383 Dwarf_Half high_pc_form = 0;
2384 Dwarf_Form_Class return_class;
2385 Dwarf_Error
error = DW_DLE_NE;
2386 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2387 bool has_lowpc =
false;
2388 bool has_highpc =
false;
2389 bool has_ranges =
false;
2391 if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
2397 if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) ==
2404 if (return_class == DW_FORM_CLASS_CONSTANT) {
2405 high_pc = low_pc + high_pc;
2410 return pc >= low_pc && pc < high_pc;
2421 bool result =
false;
2423 Dwarf_Attribute attr;
2424 if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
2427 if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
2428 Dwarf_Ranges *ranges;
2429 Dwarf_Signed ranges_count = 0;
2430 Dwarf_Unsigned byte_count = 0;
2432 if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count,
2433 &byte_count, &error) == DW_DLV_OK) {
2434 has_ranges = ranges_count != 0;
2435 for (
int i = 0; i < ranges_count; i++) {
2436 if (ranges[i].dwr_addr1 != 0 &&
2437 pc >= ranges[i].dwr_addr1 + low_pc &&
2438 pc < ranges[i].dwr_addr2 + low_pc) {
2443 dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
2449 if (!result && low_pc != 0 && pc == low_pc) {
2456 if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
2457 Dwarf_Die spec_die = get_spec_die(fobj, die);
2459 result = die_has_pc(fobj, spec_die, pc);
2460 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2467 static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &type) {
2468 Dwarf_Error
error = DW_DLE_NE;
2470 Dwarf_Die child = 0;
2471 if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
2472 get_type(dwarf, child, type);
2476 type.insert(0,
"::");
2477 dwarf_dealloc(dwarf, child, DW_DLA_DIE);
2481 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2482 type.insert(0, std::string(name));
2483 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2485 type.insert(0,
"<unknown>");
2489 static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
2490 Dwarf_Error
error = DW_DLE_NE;
2492 Dwarf_Sig8 signature;
2493 Dwarf_Bool has_attr = 0;
2494 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) {
2496 Dwarf_Attribute attr_mem;
2497 if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) {
2498 if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) {
2499 return std::string(
"<no type signature>");
2502 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2506 Dwarf_Unsigned next_cu_header;
2507 Dwarf_Sig8 tu_signature;
2511 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0,
2512 &next_cu_header, 0, &error) == DW_DLV_OK) {
2514 if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
2515 Dwarf_Die type_cu_die = 0;
2516 if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) {
2517 Dwarf_Die child_die = 0;
2518 if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) {
2519 get_type(dwarf, child_die, result);
2520 found = !result.empty();
2521 dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
2523 dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
2529 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2530 &next_cu_header, 0, &error) == DW_DLV_OK) {
2538 std::ostringstream string_stream;
2539 string_stream <<
"<0x" << std::hex << std::setfill(
'0');
2540 for (
int i = 0; i < 8; ++i) {
2541 string_stream << std::setw(2) << std::hex
2542 << (
int)(
unsigned char)(signature.signature[i]);
2544 string_stream <<
">";
2545 result = string_stream.str();
2550 struct type_context_t {
2558 : is_const(false), is_typedef(false), has_type(false), has_name(false) {
2566 static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die,
2567 type_context_t &context) {
2569 Dwarf_Error
error = DW_DLE_NE;
2573 if (!context.is_typedef) {
2574 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2575 if (!context.text.empty()) {
2576 context.text.insert(0,
" ");
2578 context.text.insert(0, std::string(name));
2579 dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
2582 context.is_typedef =
false;
2583 context.has_type =
true;
2584 if (context.is_const) {
2585 context.text.insert(0,
"const ");
2586 context.is_const =
false;
2590 bool next_type_is_const =
false;
2591 bool is_keyword =
true;
2594 Dwarf_Bool has_attr = 0;
2595 if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
2597 case DW_TAG_structure_type:
2598 case DW_TAG_union_type:
2599 case DW_TAG_class_type:
2600 case DW_TAG_enumeration_type:
2601 context.has_type =
true;
2602 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) ==
2609 get_type_by_signature(fobj.dwarf_handle.get(), die);
2610 if (context.is_const)
2611 type.insert(0,
"const ");
2613 if (!context.text.empty())
2614 context.text.insert(0,
" ");
2615 context.text.insert(0, type);
2620 context.is_typedef = (tag == DW_TAG_enumeration_type);
2623 case DW_TAG_const_type:
2624 next_type_is_const =
true;
2626 case DW_TAG_pointer_type:
2627 context.text.insert(0,
"*");
2629 case DW_TAG_reference_type:
2630 context.text.insert(0,
"&");
2632 case DW_TAG_restrict_type:
2633 context.text.insert(0,
"restrict ");
2635 case DW_TAG_rvalue_reference_type:
2636 context.text.insert(0,
"&&");
2638 case DW_TAG_volatile_type:
2639 context.text.insert(0,
"volatile ");
2641 case DW_TAG_typedef:
2644 next_type_is_const = context.is_const;
2645 context.is_typedef =
true;
2646 context.has_type =
true;
2648 case DW_TAG_base_type:
2649 context.has_type =
true;
2651 case DW_TAG_formal_parameter:
2652 context.has_name =
true;
2660 if (!is_keyword && context.is_const) {
2661 context.text.insert(0,
"const ");
2664 context.is_const = next_type_is_const;
2667 get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type,
true);
2669 set_parameter_string(fobj, ref, context);
2670 dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
2673 if (!context.has_type && context.has_name) {
2674 context.text.insert(0,
"void ");
2675 context.has_type =
true;
2680 static void set_function_parameters(std::string &function_name,
2681 std::vector<std::string> &ns,
2682 dwarf_fileobject &fobj, Dwarf_Die die) {
2683 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2684 Dwarf_Error
error = DW_DLE_NE;
2685 Dwarf_Die current_die = 0;
2686 std::string parameters;
2687 bool has_spec =
true;
2690 Dwarf_Die spec_die = get_spec_die(fobj, die);
2696 std::vector<std::string>::const_iterator it = ns.begin();
2697 std::string ns_name;
2698 for (it = ns.begin(); it < ns.end(); ++it) {
2699 ns_name.append(*it).append(
"::");
2702 if (!ns_name.empty()) {
2703 function_name.insert(0, ns_name);
2708 std::string return_type =
2709 get_referenced_die_name(dwarf, die, DW_AT_type,
true);
2710 if (return_type.empty()) {
2711 return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type,
true);
2713 if (!return_type.empty()) {
2714 return_type.append(
" ");
2715 function_name.insert(0, return_type);
2718 if (dwarf_child(spec_die, ¤t_die, &error) == DW_DLV_OK) {
2720 Dwarf_Die sibling_die = 0;
2722 Dwarf_Half tag_value;
2723 dwarf_tag(current_die, &tag_value, &error);
2725 if (tag_value == DW_TAG_formal_parameter) {
2727 bool is_artificial =
false;
2728 Dwarf_Attribute attr_mem;
2729 if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) ==
2731 Dwarf_Bool flag = 0;
2732 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
2733 is_artificial = flag != 0;
2735 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2738 if (!is_artificial) {
2739 type_context_t context;
2740 set_parameter_string(fobj, current_die, context);
2742 if (parameters.empty()) {
2743 parameters.append(
"(");
2745 parameters.append(
", ");
2747 parameters.append(context.text);
2751 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
2752 if (result == DW_DLV_ERROR) {
2754 }
else if (result == DW_DLV_NO_ENTRY) {
2758 if (current_die != die) {
2759 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2763 current_die = sibling_die;
2766 if (parameters.empty())
2768 parameters.append(
")");
2772 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2774 function_name.append(parameters);
2779 struct inliners_search_cb {
2780 void operator()(Dwarf_Die die, std::vector<std::string> &ns) {
2781 Dwarf_Error
error = DW_DLE_NE;
2782 Dwarf_Half tag_value;
2783 Dwarf_Attribute attr_mem;
2784 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2786 dwarf_tag(die, &tag_value, &error);
2788 switch (tag_value) {
2790 case DW_TAG_subprogram:
2791 if (!trace.source.function.empty())
2793 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2794 trace.source.function = std::string(name);
2795 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2800 trace.source.function =
2801 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin,
true);
2802 if (trace.source.function.empty()) {
2803 trace.source.function =
2804 get_referenced_die_name(dwarf, die, DW_AT_specification,
true);
2809 set_function_parameters(trace.source.function, ns, fobj, die);
2818 if (trace.object_function.empty()) {
2819 details::demangler demangler;
2821 if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) !=
2823 if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) !=
2830 if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) {
2831 trace.object_function = demangler.demangle(linkage);
2832 dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
2834 dwarf_dealloc(dwarf, name, DW_DLA_ATTR);
2838 case DW_TAG_inlined_subroutine:
2839 ResolvedTrace::SourceLoc sloc;
2841 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2842 sloc.function = std::string(name);
2843 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2850 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin,
true);
2853 set_function_parameters(sloc.function, ns, fobj, die);
2855 std::string
file = die_call_file(dwarf, die, cu_die);
2857 sloc.filename =
file;
2859 Dwarf_Unsigned
number = 0;
2860 if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) {
2861 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
2864 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2867 if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) ==
2869 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
2872 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2875 trace.inliners.push_back(sloc);
2879 ResolvedTrace &trace;
2880 dwarf_fileobject &fobj;
2882 inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &f, Dwarf_Die c)
2883 : trace(t), fobj(
f), cu_die(c) {}
2886 static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj,
2887 Dwarf_Die parent_die, Dwarf_Addr pc,
2889 Dwarf_Die current_die = 0;
2890 Dwarf_Error
error = DW_DLE_NE;
2891 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2893 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
2898 Dwarf_Die sibling_die = 0;
2899 Dwarf_Half tag_value;
2900 dwarf_tag(current_die, &tag_value, &error);
2902 switch (tag_value) {
2903 case DW_TAG_subprogram:
2904 case DW_TAG_inlined_subroutine:
2905 if (die_has_pc(fobj, current_die, pc)) {
2909 bool declaration =
false;
2910 Dwarf_Attribute attr_mem;
2911 if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
2913 Dwarf_Bool flag = 0;
2914 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
2915 declaration = flag != 0;
2917 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2925 Dwarf_Die die_mem = 0;
2926 Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem);
2933 int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
2934 if (res == DW_DLV_ERROR) {
2936 }
else if (res == DW_DLV_NO_ENTRY) {
2940 if (current_die != parent_die) {
2941 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2945 current_die = sibling_die;
2950 template <
typename CB>
2951 static bool deep_first_search_by_pc(dwarf_fileobject &fobj,
2952 Dwarf_Die parent_die, Dwarf_Addr pc,
2953 std::vector<std::string> &ns, CB cb) {
2954 Dwarf_Die current_die = 0;
2955 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2956 Dwarf_Error
error = DW_DLE_NE;
2958 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
2962 bool branch_has_pc =
false;
2963 bool has_namespace =
false;
2965 Dwarf_Die sibling_die = 0;
2968 if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
2969 if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
2970 char *ns_name = NULL;
2971 if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) {
2973 ns.push_back(std::string(ns_name));
2975 ns.push_back(
"<unknown>");
2977 dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
2979 ns.push_back(
"<unknown>");
2981 has_namespace =
true;
2985 bool declaration =
false;
2986 Dwarf_Attribute attr_mem;
2987 if (tag != DW_TAG_class_type &&
2988 dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
2990 Dwarf_Bool flag = 0;
2991 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
2992 declaration = flag != 0;
2994 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3002 branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb);
3005 if (!branch_has_pc) {
3006 branch_has_pc = die_has_pc(fobj, current_die, pc);
3009 if (branch_has_pc) {
3010 cb(current_die, ns);
3013 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3014 if (result == DW_DLV_ERROR) {
3016 }
else if (result == DW_DLV_NO_ENTRY) {
3020 if (current_die != parent_die) {
3021 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3025 if (has_namespace) {
3026 has_namespace =
false;
3029 current_die = sibling_die;
3032 if (has_namespace) {
3035 return branch_has_pc;
3038 static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die,
3040 Dwarf_Attribute attr_mem;
3041 Dwarf_Error
error = DW_DLE_NE;
3042 Dwarf_Signed file_index;
3046 if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
3047 if (dwarf_formsdata(attr_mem, &file_index, &error) != DW_DLV_OK) {
3050 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3052 if (file_index == 0) {
3056 char **srcfiles = 0;
3057 Dwarf_Signed file_count = 0;
3058 if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) {
3059 if (file_index <= file_count)
3060 file = std::string(srcfiles[file_index - 1]);
3063 for (
int i = 0; i < file_count; ++i) {
3064 dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
3066 dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
3072 Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) {
3076 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3077 Dwarf_Error
error = DW_DLE_NE;
3078 Dwarf_Arange *aranges;
3079 Dwarf_Signed arange_count;
3081 Dwarf_Die returnDie;
3083 if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) !=
3090 Dwarf_Arange arange;
3091 if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) ==
3096 Dwarf_Off cu_die_offset;
3097 if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) ==
3103 dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error);
3105 found = dwarf_result == DW_DLV_OK;
3107 dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
3116 Dwarf_Unsigned next_cu_header;
3121 dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3122 &next_cu_header, 0, &error) == DW_DLV_OK) {
3125 dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
3127 if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
3128 if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) &&
3129 tag == DW_TAG_compile_unit) {
3130 if (die_has_pc(fobj, returnDie, addr)) {
3138 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3139 &next_cu_header, 0, &error) == DW_DLV_OK) {
3152 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3153 &next_cu_header, 0, &error) == DW_DLV_OK) {
3154 if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
3155 Dwarf_Die die_mem = 0;
3156 Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem);
3166 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3167 &next_cu_header, 0, &error) == DW_DLV_OK) {
3181 #endif // BACKWARD_HAS_DWARF == 1
3184 class TraceResolverImpl<system_tag::linux_tag>
3185 :
public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
3187 #endif // BACKWARD_SYSTEM_LINUX
3189 #ifdef BACKWARD_SYSTEM_DARWIN
3191 template <
typename STACKTRACE_TAG>
class TraceResolverDarwinImpl;
3194 class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>
3195 :
public TraceResolverImplBase {
3197 template <
class ST>
void load_stacktrace(ST &st) {
3198 using namespace details;
3199 if (st.size() == 0) {
3202 _symbols.reset(backtrace_symbols(st.begin(), st.size()));
3205 ResolvedTrace
resolve(ResolvedTrace trace) {
3208 char *filename = _symbols[trace.idx];
3211 while (*filename && *filename !=
' ')
3213 while (*filename ==
' ')
3217 char *p = filename + strlen(filename) - 1;
3219 while (p > filename && *p !=
' ')
3221 while (p > filename && *p ==
' ')
3223 while (p > filename && *p !=
' ')
3225 while (p > filename && *p ==
' ')
3227 char *funcname_end = p + 1;
3230 while (p > filename && *p !=
' ')
3235 while (p > filename && *p ==
' ')
3237 while (p > filename && *p !=
' ')
3239 while (p > filename && *p ==
' ')
3243 char *filename_end = p + 1;
3244 if (p == filename) {
3246 filename_end = filename + strlen(filename);
3249 trace.object_filename.assign(
3250 filename, filename_end);
3254 *funcname_end =
'\0';
3256 trace.object_function = this->
demangle(funcname);
3257 trace.object_function +=
" ";
3258 trace.object_function += (funcname_end + 1);
3259 trace.source.function = trace.object_function;
3265 details::handle<char **> _symbols;
3269 class TraceResolverImpl<system_tag::darwin_tag>
3270 :
public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
3272 #endif // BACKWARD_SYSTEM_DARWIN
3274 #ifdef BACKWARD_SYSTEM_WINDOWS
3280 struct module_data {
3281 std::string image_name;
3282 std::string module_name;
3287 class get_mod_info {
3289 static const int buffer_length = 4096;
3292 get_mod_info(HANDLE h) : process(h) {}
3294 module_data operator()(HMODULE module) {
3296 char temp[buffer_length];
3299 GetModuleInformation(process, module, &mi,
sizeof(mi));
3300 ret.base_address = mi.lpBaseOfDll;
3301 ret.load_size = mi.SizeOfImage;
3303 GetModuleFileNameEx(process, module, temp,
sizeof(temp));
3304 ret.image_name = temp;
3305 GetModuleBaseName(process, module, temp,
sizeof(temp));
3306 ret.module_name = temp;
3307 std::vector<char> img(
ret.image_name.begin(),
ret.image_name.end());
3308 std::vector<char>
mod(
ret.module_name.begin(),
ret.module_name.end());
3309 SymLoadModule64(process, 0, &img[0], &
mod[0], (DWORD64)
ret.base_address,
3315 template <>
class TraceResolverImpl<system_tag::windows_tag> {
3317 TraceResolverImpl() {
3319 HANDLE process = GetCurrentProcess();
3321 std::vector<module_data> modules;
3323 std::vector<HMODULE> module_handles(1);
3324 SymInitialize(process, NULL,
false);
3325 DWORD symOptions = SymGetOptions();
3326 symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME;
3327 SymSetOptions(symOptions);
3328 EnumProcessModules(process, &module_handles[0],
3329 module_handles.size() *
sizeof(HMODULE), &cbNeeded);
3330 module_handles.resize(cbNeeded /
sizeof(HMODULE));
3331 EnumProcessModules(process, &module_handles[0],
3332 module_handles.size() *
sizeof(HMODULE), &cbNeeded);
3333 std::transform(module_handles.begin(), module_handles.end(),
3334 std::back_inserter(modules), get_mod_info(process));
3335 void *
base = modules[0].base_address;
3336 IMAGE_NT_HEADERS *h = ImageNtHeader(base);
3337 image_type = h->FileHeader.Machine;
3340 template <
class ST>
void load_stacktrace(ST &) {}
3342 static const int max_sym_len = 255;
3345 char buffer[max_sym_len];
3348 DWORD64 displacement;
3350 ResolvedTrace
resolve(ResolvedTrace t) {
3351 HANDLE process = GetCurrentProcess();
3355 memset(&sym,
sizeof(sym), 0);
3356 sym.sym.SizeOfStruct =
sizeof(SYMBOL_INFO);
3357 sym.sym.MaxNameLen = max_sym_len;
3359 if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) {
3362 DWORD dw = GetLastError();
3364 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3365 FORMAT_MESSAGE_FROM_SYSTEM |
3366 FORMAT_MESSAGE_IGNORE_INSERTS,
3367 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
3368 (LPTSTR)&lpMsgBuf, 0, NULL);
3374 UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE);
3378 if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) {
3379 t.object_filename = line.FileName;
3380 t.source.filename = line.FileName;
3381 t.source.line = line.LineNumber;
3382 t.source.col = offset;
3385 t.source.function =
name;
3386 t.object_filename =
"";
3387 t.object_function =
name;
3392 DWORD machine_type()
const {
return image_type; }
3406 typedef std::vector<std::pair<unsigned, std::string> >
lines_t;
3413 const std::vector<std::string>& prefixes = get_paths_from_env_variable();
3414 for (
size_t i = 0; i < prefixes.size(); ++i) {
3416 std::string new_path = prefixes[i] +
'/' + path;
3417 _file.reset(
new std::ifstream(new_path.c_str()));
3418 if (is_open())
break;
3421 if (!_file || !is_open()) {
3422 _file.reset(
new std::ifstream(path.c_str()));
3428 using namespace std;
3443 for (line_idx = 1; line_idx < line_start; ++line_idx) {
3444 std::getline(*_file, line);
3454 bool operator()(
char c) {
return std::isspace(c); }
3457 bool started =
false;
3458 for (; line_idx < line_start + line_count; ++line_idx) {
3459 getline(*_file, line);
3464 if (std::find_if(line.begin(), line.end(),
not_isspace()) == line.end())
3468 lines.push_back(make_pair(line_idx, line));
3472 std::find_if(lines.rbegin(), lines.rend(),
not_isempty()).base(),
3479 return get_lines(line_start, line_count, lines);
3491 return !(std::find_if(p.second.begin(), p.second.end(),
not_isspace()) ==
3498 #ifdef BACKWARD_ATLEAST_CXX11
3500 SourceFile &operator=(SourceFile &&from) {
3521 std::vector<std::string> paths;
3522 const char* prefixes_str = std::getenv(
"BACKWARD_CXX_SOURCE_PREFIXES");
3523 if (prefixes_str && prefixes_str[0]) {
3530 static std::vector<std::string> paths = get_paths_from_env_variable_impl();
3534 #ifdef BACKWARD_ATLEAST_CXX11
3545 unsigned context_size) {
3547 SourceFile &src_file = get_src_file(filename);
3548 unsigned start = line_start - context_size / 2;
3553 const std::string &filename_b,
unsigned line_b,
3554 unsigned context_size) {
3555 SourceFile &src_file_a = get_src_file(filename_a);
3556 SourceFile &src_file_b = get_src_file(filename_b);
3559 src_file_a.
get_lines(line_a - context_size / 4, context_size / 2);
3560 src_file_b.
get_lines(line_b - context_size / 4, context_size / 2, lines);
3565 unsigned line_b,
unsigned context_size) {
3566 SourceFile &src_file = get_src_file(filename);
3570 unsigned a = min(line_a, line_b);
3571 unsigned b = max(line_a, line_b);
3573 if ((b - a) < (context_size / 3)) {
3574 return src_file.
get_lines((a + b - context_size + 1) / 2, context_size);
3577 lines_t lines = src_file.
get_lines(a - context_size / 4, context_size / 2);
3578 src_file.
get_lines(b - context_size / 4, context_size / 2, lines);
3587 src_files_t::iterator it = _src_files.find(filename);
3588 if (it != _src_files.end()) {
3591 SourceFile &new_src_file = _src_files[filename];
3593 return new_src_file;
3599 namespace ColorMode {
3606 int_type
underflow()
override {
return traits_type::eof(); }
3608 if (traits_type::not_eof(ch) && fwrite(&ch,
sizeof ch, 1, sink) == 1) {
3611 return traits_type::eof();
3614 std::streamsize
xsputn(
const char_type *s, std::streamsize count)
override {
3615 return static_cast<std::streamsize
>(
3616 fwrite(
s,
sizeof *
s,
static_cast<size_t>(count), sink));
3619 #ifdef BACKWARD_ATLEAST_CXX11
3634 #ifdef BACKWARD_SYSTEM_LINUX
3637 enum type { yellow = 33, purple = 35,
reset = 39 };
3642 Colorize(std::ostream &os) : _os(
os), _reset(false), _enabled(false) {}
3654 _os <<
"\033[" <<
static_cast<int>(ccode) <<
"m";
3675 #else // ndef BACKWARD_SYSTEM_LINUX
3689 #endif // BACKWARD_SYSTEM_LINUX
3701 : snippet(true), color_mode(ColorMode::
automatic), address(false),
3702 object(false), inliner_context_size(5), trace_context_size(7) {}
3704 template <
typename ST> FILE *
print(ST &st, FILE *
fp = stderr) {
3706 std::ostream os(&obuf);
3708 colorize.activate(color_mode,
fp);
3709 print_stacktrace(st, os, colorize);
3713 template <
typename ST> std::ostream &
print(ST &st, std::ostream &os) {
3715 colorize.activate(color_mode);
3716 print_stacktrace(st, os, colorize);
3720 template <
typename IT>
3721 FILE *
print(IT begin, IT end, FILE *
fp = stderr,
size_t thread_id = 0) {
3723 std::ostream os(&obuf);
3725 colorize.activate(color_mode,
fp);
3726 print_stacktrace(begin, end, os, thread_id, colorize);
3730 template <
typename IT>
3731 std::ostream &
print(IT begin, IT end, std::ostream &os,
3732 size_t thread_id = 0) {
3734 colorize.activate(color_mode);
3735 print_stacktrace(begin, end, os, thread_id, colorize);
3745 template <
typename ST>
3747 print_header(os, st.thread_id());
3748 _resolver.load_stacktrace(st);
3749 for (
size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
3750 print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize);
3754 template <
typename IT>
3757 print_header(os, thread_id);
3758 for (; begin != end; ++begin) {
3759 print_trace(os, *begin, colorize);
3764 os <<
"Stack trace (most recent call last)";
3766 os <<
" in thread " << thread_id;
3774 bool already_indented =
true;
3779 already_indented =
false;
3782 for (
size_t inliner_idx = trace.
inliners.size(); inliner_idx > 0;
3784 if (!already_indented) {
3789 print_source_loc(os,
" | ", inliner_loc);
3791 print_snippet(os,
" | ", inliner_loc, colorize,
Color::purple,
3792 inliner_context_size);
3794 already_indented =
false;
3798 if (!already_indented) {
3801 print_source_loc(os,
" ", trace.
source, trace.
addr);
3804 trace_context_size);
3813 using namespace std;
3817 static_cast<unsigned>(context_size));
3819 for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) {
3820 if (it->first == source_loc.
line) {
3821 colorize.set_color(color_code);
3822 os << indent <<
">";
3824 os << indent <<
" ";
3826 os << std::setw(4) << it->first <<
": " << it->second <<
"\n";
3827 if (it->first == source_loc.
line) {
3835 void *addr =
nullptr) {
3836 os << indent <<
"Source \"" << source_loc.
filename <<
"\", line "
3839 if (address && addr !=
nullptr) {
3840 os <<
" [" << addr <<
"]";
3848 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
3850 class SignalHandling {
3852 static std::vector<int> make_default_signals() {
3853 const int posix_signals[] = {
3866 #if defined(BACKWARD_SYSTEM_DARWIN)
3870 return std::vector<int>(posix_signals,
3872 sizeof posix_signals /
sizeof posix_signals[0]);
3875 SignalHandling(
const std::vector<int> &posix_signals = make_default_signals())
3877 bool success =
true;
3879 const size_t stack_size = 1024 * 1024 * 8;
3880 _stack_content.reset(
static_cast<char *
>(malloc(stack_size)));
3881 if (_stack_content) {
3883 ss.ss_sp = _stack_content.get();
3884 ss.ss_size = stack_size;
3886 if (sigaltstack(&ss,
nullptr) < 0) {
3893 for (
size_t i = 0; i < posix_signals.size(); ++i) {
3894 struct sigaction action;
3895 memset(&action, 0,
sizeof action);
3897 static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
3898 sigfillset(&action.sa_mask);
3899 sigdelset(&action.sa_mask, posix_signals[i]);
3900 #if defined(__clang__)
3901 #pragma clang diagnostic push
3902 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
3904 action.sa_sigaction = &sig_handler;
3905 #if defined(__clang__)
3906 #pragma clang diagnostic pop
3909 int r = sigaction(posix_signals[i], &action,
nullptr);
3917 bool loaded()
const {
return _loaded; }
3919 static void handleSignal(
int, siginfo_t *info,
void *_ctx) {
3920 ucontext_t *uctx =
static_cast<ucontext_t *
>(_ctx);
3923 void *error_addr =
nullptr;
3924 #ifdef REG_RIP // x86_64
3925 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.gregs[REG_RIP]);
3926 #elif defined(REG_EIP) // x86_32
3927 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.gregs[REG_EIP]);
3928 #elif defined(__arm__)
3929 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.arm_pc);
3930 #elif defined(__aarch64__)
3931 #if defined(__APPLE__)
3932 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext->__ss.__pc);
3934 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.pc);
3936 #elif defined(__mips__)
3937 error_addr =
reinterpret_cast<void *
>(
reinterpret_cast<struct sigcontext*
>(&uctx->uc_mcontext)->sc_pc);
3938 #elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
3939 defined(__POWERPC__)
3940 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.regs->nip);
3941 #elif defined(__s390x__)
3942 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext.psw.addr);
3943 #elif defined(__APPLE__) && defined(__x86_64__)
3944 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext->__ss.__rip);
3945 #elif defined(__APPLE__)
3946 error_addr =
reinterpret_cast<void *
>(uctx->uc_mcontext->__ss.__eip);
3948 #warning ":/ sorry, ain't know no nothing none not of your architecture!"
3951 st.load_from(error_addr, 32);
3957 printer.address =
true;
3958 printer.print(st, stderr);
3960 #if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
3961 psiginfo(info,
nullptr);
3968 details::handle<char *> _stack_content;
3972 __attribute__((noreturn))
3975 sig_handler(
int signo, siginfo_t *info,
void *_ctx) {
3976 handleSignal(signo, info, _ctx);
3979 raise(info->si_signo);
3983 _exit(EXIT_FAILURE);
3987 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
3989 #ifdef BACKWARD_SYSTEM_WINDOWS
3991 class SignalHandling {
3993 SignalHandling(
const std::vector<int> & = std::vector<int>())
3994 : reporter_thread_([]() {
4004 std::unique_lock<std::mutex> lk(mtx());
4005 cv().wait(lk, [] {
return crashed() != crash_status::running; });
4007 if (crashed() == crash_status::crashed) {
4008 handle_stacktrace(skip_recs());
4011 std::unique_lock<std::mutex> lk(mtx());
4012 crashed() = crash_status::ending;
4016 SetUnhandledExceptionFilter(crash_handler);
4018 signal(SIGABRT, signal_handler);
4019 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
4021 set_terminate(&terminator);
4022 set_unexpected(&terminator);
4023 _set_purecall_handler(&terminator);
4024 _set_invalid_parameter_handler(&invalid_parameter_handler);
4026 bool loaded()
const {
return true; }
4030 std::unique_lock<std::mutex> lk(mtx());
4031 crashed() = crash_status::normal_exit;
4036 reporter_thread_.join();
4040 static CONTEXT *ctx() {
4041 static CONTEXT
data;
4045 enum class crash_status { running, crashed, normal_exit, ending };
4047 static crash_status &crashed() {
4048 static crash_status
data;
4052 static std::mutex &mtx() {
4053 static std::mutex
data;
4057 static std::condition_variable &cv() {
4058 static std::condition_variable
data;
4062 static HANDLE &thread_handle() {
4063 static HANDLE handle;
4067 std::thread reporter_thread_;
4070 static const constexpr
int signal_skip_recs =
4083 static int &skip_recs() {
4088 static inline void terminator() {
4089 crash_handler(signal_skip_recs);
4093 static inline void signal_handler(
int) {
4094 crash_handler(signal_skip_recs);
4098 static inline void __cdecl invalid_parameter_handler(
const wchar_t *,
4103 crash_handler(signal_skip_recs);
4107 NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) {
4110 crash_handler(0, info->ContextRecord);
4111 return EXCEPTION_CONTINUE_SEARCH;
4114 NOINLINE static void crash_handler(
int skip, CONTEXT *ct =
nullptr) {
4116 if (ct ==
nullptr) {
4117 RtlCaptureContext(ctx());
4119 memcpy(ctx(), ct,
sizeof(CONTEXT));
4121 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
4122 GetCurrentProcess(), &thread_handle(), 0, FALSE,
4123 DUPLICATE_SAME_ACCESS);
4128 std::unique_lock<std::mutex> lk(mtx());
4129 crashed() = crash_status::crashed;
4135 std::unique_lock<std::mutex> lk(mtx());
4136 cv().wait(lk, [] {
return crashed() != crash_status::crashed; });
4140 static void handle_stacktrace(
int skip_frames = 0) {
4149 st.set_machine_type(printer.resolver().machine_type());
4150 st.set_context(ctx());
4151 st.set_thread_handle(thread_handle());
4152 st.load_here(32 + skip_frames);
4153 st.skip_n_firsts(skip_frames);
4155 printer.address =
true;
4156 printer.print(st, std::cerr);
4160 #endif // BACKWARD_SYSTEM_WINDOWS
4162 #ifdef BACKWARD_SYSTEM_UNKNOWN
4171 #endif // BACKWARD_SYSTEM_UNKNOWN