3 * Copyright 2013 Google Inc. All Rights Reserved.
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * Used in Geeqie with minor changes as backward.h
26 #ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
27 #define H_6B9572DA_A64B_49E6_B234_051480991C89
30 #error "It's not going to compile without a C++ compiler..."
33 #if defined(BACKWARD_CXX11)
34 #elif defined(BACKWARD_CXX98)
36 #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)
37 #define BACKWARD_CXX11
38 #define BACKWARD_ATLEAST_CXX11
39 #define BACKWARD_ATLEAST_CXX98
40 #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
41 #define BACKWARD_ATLEAST_CXX17
44 #define BACKWARD_CXX98
45 #define BACKWARD_ATLEAST_CXX98
49 // You can define one of the following (or leave it to the auto-detection):
51 #define BACKWARD_SYSTEM_LINUX
52 // - specialization for linux
54 // #define BACKWARD_SYSTEM_DARWIN
55 // - specialization for Mac OS X 10.5 and later.
57 // #define BACKWARD_SYSTEM_WINDOWS
58 // - specialization for Windows (Clang 9 and MSVC2017)
60 // #define BACKWARD_SYSTEM_UNKNOWN
61 // - placebo implementation, does nothing.
63 #if defined(BACKWARD_SYSTEM_LINUX)
64 #elif defined(BACKWARD_SYSTEM_DARWIN)
65 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
66 #elif defined(BACKWARD_SYSTEM_WINDOWS)
68 #if defined(__linux) || defined(__linux__)
69 #define BACKWARD_SYSTEM_LINUX
70 #elif defined(__APPLE__)
71 #define BACKWARD_SYSTEM_DARWIN
73 #define BACKWARD_SYSTEM_WINDOWS
75 #define BACKWARD_SYSTEM_UNKNOWN
79 #define NOINLINE __attribute__((noinline))
98 #if defined(BACKWARD_SYSTEM_LINUX)
100 // On linux, backtrace can back-trace or "walk" the stack using the following
103 // #define BACKWARD_HAS_UNWIND 1
104 // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
105 // - with unwind, the stacktrace is as accurate as it can possibly be, since
106 // this is used by the C++ runtime in gcc/clang for stack unwinding on
108 // - normally libgcc is already linked to your program by default.
110 #define BACKWARD_HAS_LIBUNWIND 1
111 // - libunwind provides, in some cases, a more accurate stacktrace as it knows
112 // to decode signal handler frames and lets us edit the context registers when
113 // unwinding, allowing stack traces over bad function references.
115 // #define BACKWARD_HAS_BACKTRACE == 1
116 // - backtrace seems to be a little bit more portable than libunwind, but on
117 // linux, it uses unwind anyway, but abstract away a tiny information that is
118 // sadly really important in order to get perfectly accurate stack traces.
119 // - backtrace is part of the (e)glib library.
122 // #define BACKWARD_HAS_UNWIND == 1
124 // Note that only one of the define should be set to 1 at a time.
126 #if BACKWARD_HAS_UNWIND == 1
127 #elif BACKWARD_HAS_LIBUNWIND == 1
128 #elif BACKWARD_HAS_BACKTRACE == 1
130 #undef BACKWARD_HAS_UNWIND
131 #define BACKWARD_HAS_UNWIND 1
132 #undef BACKWARD_HAS_LIBUNWIND
133 #define BACKWARD_HAS_LIBUNWIND 0
134 #undef BACKWARD_HAS_BACKTRACE
135 #define BACKWARD_HAS_BACKTRACE 0
138 // On linux, backward can extract detailed information about a stack trace
139 // using one of the following libraries:
141 // #define BACKWARD_HAS_DW 1
142 // - libdw gives you the most juicy details out of your stack traces:
146 // - line and column numbers
147 // - source code snippet (assuming the file is accessible)
148 // - variable names (if not optimized out)
149 // - variable values (not supported by backward-cpp)
150 // - You need to link with the lib "dw":
151 // - apt-get install libdw-dev
152 // - g++/clang++ -ldw ...
154 // #define BACKWARD_HAS_BFD 1
155 // - With libbfd, you get a fair amount of details:
160 // - source code snippet (assuming the file is accessible)
161 // - You need to link with the lib "bfd":
162 // - apt-get install binutils-dev
163 // - g++/clang++ -lbfd ...
165 #define BACKWARD_HAS_DWARF 1
166 // - libdwarf gives you the most juicy details out of your stack traces:
170 // - line and column numbers
171 // - source code snippet (assuming the file is accessible)
172 // - variable names (if not optimized out)
173 // - variable values (not supported by backward-cpp)
174 // - You need to link with the lib "dwarf":
175 // - apt-get install libdwarf-dev
176 // - g++/clang++ -ldwarf ...
178 // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
179 // - backtrace provides minimal details for a stack trace:
182 // - backtrace is part of the (e)glib library.
185 // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
187 // Note that only one of the define should be set to 1 at a time.
189 #if BACKWARD_HAS_DW == 1
190 #elif BACKWARD_HAS_BFD == 1
191 #elif BACKWARD_HAS_DWARF == 1
192 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
194 #undef BACKWARD_HAS_DW
195 #define BACKWARD_HAS_DW 0
196 #undef BACKWARD_HAS_BFD
197 #define BACKWARD_HAS_BFD 0
198 #undef BACKWARD_HAS_DWARF
199 #define BACKWARD_HAS_DWARF 0
200 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
201 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
207 // Old Android API levels define _Unwind_Ptr in both link.h and
208 // unwind.h Rename the one in link.h as we are not going to be using
210 #define _Unwind_Ptr _Unwind_Ptr_Custom
216 #if defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
218 // Linux kernel header required for the struct pt_regs definition
219 // to access the NIP (Next Instruction Pointer) register value
220 #include <asm/ptrace.h>
223 #include <sys/stat.h>
234 #if BACKWARD_HAS_BFD == 1
235 // NOTE: defining PACKAGE{,_VERSION} is required before including
236 // bfd.h on some platforms, see also:
237 // https://sourceware.org/bugzilla/show_bug.cgi?id=14243
241 #ifndef PACKAGE_VERSION
242 #define PACKAGE_VERSION
247 #if BACKWARD_HAS_DW == 1
249 #include <elfutils/libdw.h>
250 #include <elfutils/libdwfl.h>
253 #if BACKWARD_HAS_DWARF == 1
256 #include "/usr/include/libdwarf/libdwarf.h"
257 //~ #include <libdwarf.h>
262 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
263 // then we shall rely on backtrace
264 #include <execinfo.h>
267 #endif // defined(BACKWARD_SYSTEM_LINUX)
269 #if defined(BACKWARD_SYSTEM_DARWIN)
270 // On Darwin, backtrace can back-trace or "walk" the stack using the following
273 // #define BACKWARD_HAS_UNWIND 1
274 // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
275 // - with unwind, the stacktrace is as accurate as it can possibly be, since
276 // this is used by the C++ runtime in gcc/clang for stack unwinding on
278 // - normally libgcc is already linked to your program by default.
280 // #define BACKWARD_HAS_LIBUNWIND 1
281 // - libunwind comes from clang, which implements an API compatible version.
282 // - libunwind provides, in some cases, a more accurate stacktrace as it knows
283 // to decode signal handler frames and lets us edit the context registers when
284 // unwinding, allowing stack traces over bad function references.
286 // #define BACKWARD_HAS_BACKTRACE == 1
287 // - backtrace is available by default, though it does not produce as much
288 // information as another library might.
291 // #define BACKWARD_HAS_UNWIND == 1
293 // Note that only one of the define should be set to 1 at a time.
295 #if BACKWARD_HAS_UNWIND == 1
296 #elif BACKWARD_HAS_BACKTRACE == 1
297 #elif BACKWARD_HAS_LIBUNWIND == 1
299 #undef BACKWARD_HAS_UNWIND
300 #define BACKWARD_HAS_UNWIND 1
301 #undef BACKWARD_HAS_BACKTRACE
302 #define BACKWARD_HAS_BACKTRACE 0
303 #undef BACKWARD_HAS_LIBUNWIND
304 #define BACKWARD_HAS_LIBUNWIND 0
307 // On Darwin, backward can extract detailed information about a stack trace
308 // using one of the following libraries:
310 // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
311 // - backtrace provides minimal details for a stack trace:
316 // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
318 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
320 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
321 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
328 #include <sys/stat.h>
331 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
332 #include <execinfo.h>
334 #endif // defined(BACKWARD_SYSTEM_DARWIN)
336 #if defined(BACKWARD_SYSTEM_WINDOWS)
338 #include <condition_variable>
345 typedef SSIZE_T ssize_t;
361 #define NOINLINE __declspec(noinline)
365 #pragma comment(lib, "psapi.lib")
366 #pragma comment(lib, "dbghelp.lib")
369 // Comment / packing is from stackoverflow:
370 // https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
371 // Some versions of imagehlp.dll lack the proper packing directives themselves
372 // so we need to do it.
373 #pragma pack(push, before_imagehlp, 8)
374 #include <imagehlp.h>
375 #pragma pack(pop, before_imagehlp)
377 // TODO maybe these should be undefined somewhere else?
378 #undef BACKWARD_HAS_UNWIND
379 #undef BACKWARD_HAS_BACKTRACE
380 #if BACKWARD_HAS_PDB_SYMBOL == 1
382 #undef BACKWARD_HAS_PDB_SYMBOL
383 #define BACKWARD_HAS_PDB_SYMBOL 1
388 #if BACKWARD_HAS_UNWIND == 1
391 // while gcc's unwind.h defines something like that:
392 // extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *);
393 // extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
395 // clang's unwind.h defines something like this:
396 // uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context);
398 // Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we
399 // cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr
402 // Luckily we can play on the fact that the guard macros have a different name:
403 #ifdef __CLANG_UNWIND_H
404 // In fact, this function still comes from libgcc (on my different linux boxes,
405 // clang links against libgcc).
406 #include <inttypes.h>
407 extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *, int *);
410 #endif // BACKWARD_HAS_UNWIND == 1
412 #if BACKWARD_HAS_LIBUNWIND == 1
413 #define UNW_LOCAL_ONLY
414 #include <libunwind.h>
415 #endif // BACKWARD_HAS_LIBUNWIND == 1
417 #ifdef BACKWARD_ATLEAST_CXX11
418 #include <unordered_map>
419 #include <utility> // for std::swap
422 template <typename K, typename V> struct hashtable {
423 typedef std::unordered_map<K, V> type;
426 } // namespace details
427 } // namespace backward
428 #else // NOT BACKWARD_ATLEAST_CXX11
434 template <typename K, typename V> struct hashtable {
435 typedef std::map<K, V> type;
437 template <typename T> const T &move(const T &v) { return v; }
438 template <typename T> T &move(T &v) { return v; }
439 } // namespace details
440 } // namespace backward
441 #endif // BACKWARD_ATLEAST_CXX11
445 #if defined(BACKWARD_SYSTEM_WINDOWS)
446 const char kBackwardPathDelimiter[] = ";";
448 const char kBackwardPathDelimiter[] = ":";
450 } // namespace details
451 } // namespace backward
455 namespace system_tag {
456 struct linux_tag; // seems that I cannot call that "linux" because the name
457 // is already defined... so I am adding _tag everywhere.
462 #if defined(BACKWARD_SYSTEM_LINUX)
463 typedef linux_tag current_tag;
464 #elif defined(BACKWARD_SYSTEM_DARWIN)
465 typedef darwin_tag current_tag;
466 #elif defined(BACKWARD_SYSTEM_WINDOWS)
467 typedef windows_tag current_tag;
468 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
469 typedef unknown_tag current_tag;
471 #error "May I please get my system defines?"
473 } // namespace system_tag
475 namespace trace_resolver_tag {
476 #if defined(BACKWARD_SYSTEM_LINUX)
480 struct backtrace_symbol;
482 #if BACKWARD_HAS_DW == 1
483 typedef libdw current;
484 #elif BACKWARD_HAS_BFD == 1
485 typedef libbfd current;
486 #elif BACKWARD_HAS_DWARF == 1
487 typedef libdwarf current;
488 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
489 typedef backtrace_symbol current;
491 #error "You shall not pass, until you know what you want."
493 #elif defined(BACKWARD_SYSTEM_DARWIN)
494 struct backtrace_symbol;
496 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
497 typedef backtrace_symbol current;
499 #error "You shall not pass, until you know what you want."
501 #elif defined(BACKWARD_SYSTEM_WINDOWS)
503 #if BACKWARD_HAS_PDB_SYMBOL == 1
504 typedef pdb_symbol current;
506 #error "You shall not pass, until you know what you want."
509 } // namespace trace_resolver_tag
513 template <typename T> struct rm_ptr { typedef T type; };
515 template <typename T> struct rm_ptr<T *> { typedef T type; };
517 template <typename T> struct rm_ptr<const T *> { typedef const T type; };
519 template <typename R, typename T, R (*F)(T)> struct deleter {
520 template <typename U> void operator()(U &ptr) const { (*F)(ptr); }
523 template <typename T> struct default_delete {
524 void operator()(T &ptr) const { delete ptr; }
527 template <typename T, typename Deleter = deleter<void, void *, &::free> >
533 #ifdef BACKWARD_ATLEAST_CXX11
534 handle(const handle &) = delete;
535 handle &operator=(const handle &) = delete;
545 explicit handle() : _val(), _empty(true) {}
546 explicit handle(T val) : _val(val), _empty(false) {
551 #ifdef BACKWARD_ATLEAST_CXX11
552 handle(handle &&from) : _empty(true) { swap(from); }
553 handle &operator=(handle &&from) {
558 explicit handle(const handle &from) : _empty(true) {
559 // some sort of poor man's move semantic.
560 swap(const_cast<handle &>(from));
562 handle &operator=(const handle &from) {
563 // some sort of poor man's move semantic.
564 swap(const_cast<handle &>(from));
569 void reset(T new_val) {
574 void update(T new_val) {
576 _empty = !static_cast<bool>(new_val);
579 operator const dummy *() const {
583 return reinterpret_cast<const dummy *>(_val);
585 T get() { return _val; }
590 void swap(handle &b) {
592 swap(b._val, _val); // can throw, we are safe here.
593 swap(b._empty, _empty); // should not throw: if you cannot swap two
594 // bools without throwing... It's a lost cause anyway!
597 T &operator->() { return _val; }
598 const T &operator->() const { return _val; }
600 typedef typename rm_ptr<T>::type &ref_t;
601 typedef const typename rm_ptr<T>::type &const_ref_t;
602 ref_t operator*() { return *_val; }
603 const_ref_t operator*() const { return *_val; }
604 ref_t operator[](size_t idx) { return _val[idx]; }
606 // Watch out, we've got a badass over here
613 // Default demangler implementation (do nothing).
614 template <typename TAG> struct demangler_impl {
615 static std::string demangle(const char *funcname) { return funcname; }
618 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
620 template <> struct demangler_impl<system_tag::current_tag> {
621 demangler_impl() : _demangle_buffer_length(0) {}
623 std::string demangle(const char *funcname) {
624 using namespace details;
625 char *result = abi::__cxa_demangle(funcname, _demangle_buffer.get(),
626 &_demangle_buffer_length, nullptr);
628 _demangle_buffer.update(result);
635 details::handle<char *> _demangle_buffer;
636 size_t _demangle_buffer_length;
639 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
641 struct demangler : public demangler_impl<system_tag::current_tag> {};
643 // Split a string on the platform's PATH delimiter. Example: if delimiter
647 // "::" --> ["","",""]
648 // "/a/b/c" --> ["/a/b/c"]
649 // "/a/b/c:/d/e/f" --> ["/a/b/c","/d/e/f"]
651 inline std::vector<std::string> split_source_prefixes(const std::string &s) {
652 std::vector<std::string> out;
655 size_t delimiter_size = sizeof(kBackwardPathDelimiter) - 1;
656 while ((next = s.find(kBackwardPathDelimiter, last)) != std::string::npos) {
657 out.push_back(s.substr(last, next - last));
658 last = next + delimiter_size;
660 if (last <= s.length()) {
661 out.push_back(s.substr(last));
666 } // namespace details
668 /*************** A TRACE ***************/
674 Trace() : addr(nullptr), idx(0) {}
676 explicit Trace(void *_addr, size_t _idx) : addr(_addr), idx(_idx) {}
679 struct ResolvedTrace : public Trace {
682 std::string function;
683 std::string filename;
687 SourceLoc() : line(0), col(0) {}
689 bool operator==(const SourceLoc &b) const {
690 return function == b.function && filename == b.filename &&
691 line == b.line && col == b.col;
694 bool operator!=(const SourceLoc &b) const { return !(*this == b); }
697 // In which binary object this trace is located.
698 std::string object_filename;
700 // The function in the object that contain the trace. This is not the same
701 // as source.function which can be an function inlined in object_function.
702 std::string object_function;
704 // The source location of this trace. It is possible for filename to be
705 // empty and for line/col to be invalid (value 0) if this information
706 // couldn't be deduced, for example if there is no debug information in the
710 // An optionals list of "inliners". All the successive sources location
711 // from where the source location of the trace (the attribute right above)
712 // is inlined. It is especially useful when you compiled with optimization.
713 typedef std::vector<SourceLoc> source_locs_t;
714 source_locs_t inliners;
716 ResolvedTrace() : Trace() {}
717 ResolvedTrace(const Trace &mini_trace) : Trace(mini_trace) {}
720 /*************** STACK TRACE ***************/
722 // default implemention.
723 template <typename TAG> class StackTraceImpl {
725 size_t size() const { return 0; }
726 Trace operator[](size_t) const { return Trace(); }
727 size_t load_here(size_t = 0) { return 0; }
728 size_t load_from(void *, size_t = 0, void * = nullptr, void * = nullptr) {
731 size_t thread_id() const { return 0; }
732 void skip_n_firsts(size_t) {}
735 class StackTraceImplBase {
738 : _thread_id(0), _skip(0), _context(nullptr), _error_addr(nullptr) {}
740 size_t thread_id() const { return _thread_id; }
742 void skip_n_firsts(size_t n) { _skip = n; }
745 void load_thread_info() {
746 #ifdef BACKWARD_SYSTEM_LINUX
748 _thread_id = static_cast<size_t>(syscall(SYS_gettid));
750 _thread_id = static_cast<size_t>(gettid());
752 if (_thread_id == static_cast<size_t>(getpid())) {
753 // If the thread is the main one, let's hide that.
754 // I like to keep little secret sometimes.
757 #elif defined(BACKWARD_SYSTEM_DARWIN)
758 _thread_id = reinterpret_cast<size_t>(pthread_self());
759 if (pthread_main_np() == 1) {
760 // If the thread is the main one, let's hide that.
766 void set_context(void *context) { _context = context; }
767 void *context() const { return _context; }
769 void set_error_addr(void *error_addr) { _error_addr = error_addr; }
770 void *error_addr() const { return _error_addr; }
772 size_t skip_n_firsts() const { return _skip; }
781 class StackTraceImplHolder : public StackTraceImplBase {
783 size_t size() const {
784 return (_stacktrace.size() >= skip_n_firsts())
785 ? _stacktrace.size() - skip_n_firsts()
788 Trace operator[](size_t idx) const {
792 return Trace(_stacktrace[idx + skip_n_firsts()], idx);
794 void *const *begin() const {
796 return &_stacktrace[skip_n_firsts()];
802 std::vector<void *> _stacktrace;
805 #if BACKWARD_HAS_UNWIND == 1
809 template <typename F> class Unwinder {
811 size_t operator()(F &f, size_t depth) {
815 _Unwind_Backtrace(&this->backtrace_trampoline, this);
817 // _Unwind_Backtrace has failed to obtain any backtraces
820 return static_cast<size_t>(_index);
829 static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx,
831 return (static_cast<Unwinder *>(self))->backtrace(ctx);
834 _Unwind_Reason_Code backtrace(_Unwind_Context *ctx) {
835 if (_index >= 0 && static_cast<size_t>(_index) >= _depth)
836 return _URC_END_OF_STACK;
838 int ip_before_instruction = 0;
839 uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
841 if (!ip_before_instruction) {
842 // calculating 0-1 for unsigned, looks like a possible bug to sanitizers,
843 // so let's do it explicitly:
845 ip = std::numeric_limits<uintptr_t>::max(); // set it to 0xffff... (as
848 ip -= 1; // else just normally decrement it (no overflow/underflow will
853 if (_index >= 0) { // ignore first frame.
854 (*_f)(static_cast<size_t>(_index), reinterpret_cast<void *>(ip));
857 return _URC_NO_REASON;
861 template <typename F> size_t unwind(F f, size_t depth) {
862 Unwinder<F> unwinder;
863 return unwinder(f, depth);
866 } // namespace details
869 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
872 size_t load_here(size_t depth = 32, void *context = nullptr,
873 void *error_addr = nullptr) {
875 set_context(context);
876 set_error_addr(error_addr);
880 _stacktrace.resize(depth);
881 size_t trace_cnt = details::unwind(callback(*this), depth);
882 _stacktrace.resize(trace_cnt);
886 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
887 void *error_addr = nullptr) {
888 load_here(depth + 8, context, error_addr);
890 for (size_t i = 0; i < _stacktrace.size(); ++i) {
891 if (_stacktrace[i] == addr) {
897 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
903 StackTraceImpl &self;
904 callback(StackTraceImpl &_self) : self(_self) {}
906 void operator()(size_t idx, void *addr) { self._stacktrace[idx] = addr; }
910 #elif BACKWARD_HAS_LIBUNWIND == 1
913 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
915 __attribute__((noinline)) size_t load_here(size_t depth = 32,
916 void *_context = nullptr,
917 void *_error_addr = nullptr) {
918 set_context(_context);
919 set_error_addr(_error_addr);
924 _stacktrace.resize(depth + 1);
931 // Add the tail call. If the Instruction Pointer is the crash address it
932 // means we got a bad function pointer dereference, so we "unwind" the
933 // bad pointer manually by using the return address pointed to by the
934 // Stack Pointer as the Instruction Pointer and letting libunwind do
938 ucontext_t *uctx = reinterpret_cast<ucontext_t *>(context());
939 #ifdef REG_RIP // x86_64
940 if (uctx->uc_mcontext.gregs[REG_RIP] ==
941 reinterpret_cast<greg_t>(error_addr())) {
942 uctx->uc_mcontext.gregs[REG_RIP] =
943 *reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_RSP]);
946 reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
948 ctx = *reinterpret_cast<unw_context_t *>(uctx);
949 #elif defined(REG_EIP) // x86_32
950 if (uctx->uc_mcontext.gregs[REG_EIP] ==
951 reinterpret_cast<greg_t>(error_addr())) {
952 uctx->uc_mcontext.gregs[REG_EIP] =
953 *reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_ESP]);
956 reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
958 ctx = *reinterpret_cast<unw_context_t *>(uctx);
959 #elif defined(__arm__)
960 // libunwind uses its own context type for ARM unwinding.
961 // Copy the registers from the signal handler's context so we can
963 unw_getcontext(&ctx);
964 ctx.regs[UNW_ARM_R0] = uctx->uc_mcontext.arm_r0;
965 ctx.regs[UNW_ARM_R1] = uctx->uc_mcontext.arm_r1;
966 ctx.regs[UNW_ARM_R2] = uctx->uc_mcontext.arm_r2;
967 ctx.regs[UNW_ARM_R3] = uctx->uc_mcontext.arm_r3;
968 ctx.regs[UNW_ARM_R4] = uctx->uc_mcontext.arm_r4;
969 ctx.regs[UNW_ARM_R5] = uctx->uc_mcontext.arm_r5;
970 ctx.regs[UNW_ARM_R6] = uctx->uc_mcontext.arm_r6;
971 ctx.regs[UNW_ARM_R7] = uctx->uc_mcontext.arm_r7;
972 ctx.regs[UNW_ARM_R8] = uctx->uc_mcontext.arm_r8;
973 ctx.regs[UNW_ARM_R9] = uctx->uc_mcontext.arm_r9;
974 ctx.regs[UNW_ARM_R10] = uctx->uc_mcontext.arm_r10;
975 ctx.regs[UNW_ARM_R11] = uctx->uc_mcontext.arm_fp;
976 ctx.regs[UNW_ARM_R12] = uctx->uc_mcontext.arm_ip;
977 ctx.regs[UNW_ARM_R13] = uctx->uc_mcontext.arm_sp;
978 ctx.regs[UNW_ARM_R14] = uctx->uc_mcontext.arm_lr;
979 ctx.regs[UNW_ARM_R15] = uctx->uc_mcontext.arm_pc;
981 // If we have crashed in the PC use the LR instead, as this was
982 // a bad function dereference
983 if (reinterpret_cast<unsigned long>(error_addr()) ==
984 uctx->uc_mcontext.arm_pc) {
985 ctx.regs[UNW_ARM_R15] =
986 uctx->uc_mcontext.arm_lr - sizeof(unsigned long);
988 _stacktrace[index] = reinterpret_cast<void *>(ctx.regs[UNW_ARM_R15]);
990 #elif defined(__APPLE__) && defined(__x86_64__)
991 unw_getcontext(&ctx);
992 // OS X's implementation of libunwind uses its own context object
993 // so we need to convert the passed context to libunwind's format
994 // (information about the data layout taken from unw_getcontext.s
995 // in Apple's libunwind source
996 ctx.data[0] = uctx->uc_mcontext->__ss.__rax;
997 ctx.data[1] = uctx->uc_mcontext->__ss.__rbx;
998 ctx.data[2] = uctx->uc_mcontext->__ss.__rcx;
999 ctx.data[3] = uctx->uc_mcontext->__ss.__rdx;
1000 ctx.data[4] = uctx->uc_mcontext->__ss.__rdi;
1001 ctx.data[5] = uctx->uc_mcontext->__ss.__rsi;
1002 ctx.data[6] = uctx->uc_mcontext->__ss.__rbp;
1003 ctx.data[7] = uctx->uc_mcontext->__ss.__rsp;
1004 ctx.data[8] = uctx->uc_mcontext->__ss.__r8;
1005 ctx.data[9] = uctx->uc_mcontext->__ss.__r9;
1006 ctx.data[10] = uctx->uc_mcontext->__ss.__r10;
1007 ctx.data[11] = uctx->uc_mcontext->__ss.__r11;
1008 ctx.data[12] = uctx->uc_mcontext->__ss.__r12;
1009 ctx.data[13] = uctx->uc_mcontext->__ss.__r13;
1010 ctx.data[14] = uctx->uc_mcontext->__ss.__r14;
1011 ctx.data[15] = uctx->uc_mcontext->__ss.__r15;
1012 ctx.data[16] = uctx->uc_mcontext->__ss.__rip;
1014 // If the IP is the same as the crash address we have a bad function
1015 // dereference The caller's address is pointed to by %rsp, so we
1016 // dereference that value and set it to be the next frame's IP.
1017 if (uctx->uc_mcontext->__ss.__rip ==
1018 reinterpret_cast<__uint64_t>(error_addr())) {
1020 *reinterpret_cast<__uint64_t *>(uctx->uc_mcontext->__ss.__rsp);
1022 _stacktrace[index] = reinterpret_cast<void *>(ctx.data[16]);
1024 #elif defined(__APPLE__)
1025 unw_getcontext(&ctx)
1026 // TODO: Convert the ucontext_t to libunwind's unw_context_t like
1028 if (ctx.uc_mcontext->__ss.__eip ==
1029 reinterpret_cast<greg_t>(error_addr())) {
1030 ctx.uc_mcontext->__ss.__eip = ctx.uc_mcontext->__ss.__esp;
1032 _stacktrace[index] =
1033 reinterpret_cast<void *>(ctx.uc_mcontext->__ss.__eip);
1038 unw_cursor_t cursor;
1040 #if defined(UNW_INIT_SIGNAL_FRAME)
1041 result = unw_init_local2(&cursor, &ctx, UNW_INIT_SIGNAL_FRAME);
1043 result = unw_init_local(&cursor, &ctx);
1046 unw_getcontext(&ctx);
1048 result = unw_init_local(&cursor, &ctx);
1056 while (index <= depth && unw_step(&cursor) > 0) {
1057 result = unw_get_reg(&cursor, UNW_REG_IP, &ip);
1059 _stacktrace[index] = reinterpret_cast<void *>(--ip);
1065 _stacktrace.resize(index + 1);
1070 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
1071 void *error_addr = nullptr) {
1072 load_here(depth + 8, context, error_addr);
1074 for (size_t i = 0; i < _stacktrace.size(); ++i) {
1075 if (_stacktrace[i] == addr) {
1077 _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i]);
1082 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1087 #elif defined(BACKWARD_HAS_BACKTRACE)
1090 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
1093 size_t load_here(size_t depth = 32, void *context = nullptr,
1094 void *error_addr = nullptr) {
1095 set_context(context);
1096 set_error_addr(error_addr);
1101 _stacktrace.resize(depth + 1);
1102 size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
1103 _stacktrace.resize(trace_cnt);
1108 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
1109 void *error_addr = nullptr) {
1110 load_here(depth + 8, context, error_addr);
1112 for (size_t i = 0; i < _stacktrace.size(); ++i) {
1113 if (_stacktrace[i] == addr) {
1115 _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i] + 1);
1120 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1125 #elif defined(BACKWARD_SYSTEM_WINDOWS)
1128 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
1130 // We have to load the machine type from the image info
1131 // So we first initialize the resolver, and it tells us this info
1132 void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; }
1133 void set_context(CONTEXT *ctx) { ctx_ = ctx; }
1134 void set_thread_handle(HANDLE handle) { thd_ = handle; }
1137 size_t load_here(size_t depth = 32, void *context = nullptr,
1138 void *error_addr = nullptr) {
1139 set_context(static_cast<CONTEXT*>(context));
1140 set_error_addr(error_addr);
1141 CONTEXT localCtx; // used when no context is provided
1149 RtlCaptureContext(ctx_);
1153 thd_ = GetCurrentThread();
1156 HANDLE process = GetCurrentProcess();
1159 memset(&s, 0, sizeof(STACKFRAME64));
1161 // TODO: 32 bit context capture
1162 s.AddrStack.Mode = AddrModeFlat;
1163 s.AddrFrame.Mode = AddrModeFlat;
1164 s.AddrPC.Mode = AddrModeFlat;
1166 s.AddrPC.Offset = ctx_->Rip;
1167 s.AddrStack.Offset = ctx_->Rsp;
1168 s.AddrFrame.Offset = ctx_->Rbp;
1170 s.AddrPC.Offset = ctx_->Eip;
1171 s.AddrStack.Offset = ctx_->Esp;
1172 s.AddrFrame.Offset = ctx_->Ebp;
1175 if (!machine_type_) {
1177 machine_type_ = IMAGE_FILE_MACHINE_AMD64;
1179 machine_type_ = IMAGE_FILE_MACHINE_I386;
1184 // NOTE: this only works if PDBs are already loaded!
1186 if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL,
1187 SymFunctionTableAccess64, SymGetModuleBase64, NULL))
1190 if (s.AddrReturn.Offset == 0)
1193 _stacktrace.push_back(reinterpret_cast<void *>(s.AddrPC.Offset));
1195 if (size() >= depth)
1202 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
1203 void *error_addr = nullptr) {
1204 load_here(depth + 8, context, error_addr);
1206 for (size_t i = 0; i < _stacktrace.size(); ++i) {
1207 if (_stacktrace[i] == addr) {
1213 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1218 DWORD machine_type_ = 0;
1220 CONTEXT *ctx_ = nullptr;
1225 class StackTrace : public StackTraceImpl<system_tag::current_tag> {};
1227 /*************** TRACE RESOLVER ***************/
1229 class TraceResolverImplBase {
1231 virtual ~TraceResolverImplBase() {}
1233 virtual void load_addresses(void *const*addresses, int address_count) {
1235 (void)address_count;
1238 template <class ST> void load_stacktrace(ST &st) {
1239 load_addresses(st.begin(), static_cast<int>(st.size()));
1242 virtual ResolvedTrace resolve(ResolvedTrace t) { return t; }
1245 std::string demangle(const char *funcname) {
1246 return _demangler.demangle(funcname);
1250 details::demangler _demangler;
1253 template <typename TAG> class TraceResolverImpl;
1255 #ifdef BACKWARD_SYSTEM_UNKNOWN
1257 template <> class TraceResolverImpl<system_tag::unknown_tag>
1258 : public TraceResolverImplBase {};
1262 #ifdef BACKWARD_SYSTEM_LINUX
1264 class TraceResolverLinuxBase : public TraceResolverImplBase {
1266 TraceResolverLinuxBase()
1267 : argv0_(get_argv0()), exec_path_(read_symlink("/proc/self/exe")) {}
1268 std::string resolve_exec_path(Dl_info &symbol_info) const {
1269 // mutates symbol_info.dli_fname to be filename to open and returns filename
1271 if (symbol_info.dli_fname == argv0_) {
1272 // dladdr returns argv[0] in dli_fname for symbols contained in
1273 // the main executable, which is not a valid path if the
1274 // executable was found by a search of the PATH environment
1275 // variable; In that case, we actually open /proc/self/exe, which
1276 // is always the actual executable (even if it was deleted/replaced!)
1277 // but display the path that /proc/self/exe links to.
1278 // However, this right away reduces probability of successful symbol
1279 // resolution, because libbfd may try to find *.debug files in the
1280 // same dir, in case symbols are stripped. As a result, it may try
1281 // to find a file /proc/self/<exe_name>.debug, which obviously does
1282 // not exist. /proc/self/exe is a last resort. First load attempt
1283 // should go for the original executable file path.
1284 symbol_info.dli_fname = "/proc/self/exe";
1287 return symbol_info.dli_fname;
1293 std::string exec_path_;
1295 static std::string get_argv0() {
1297 std::ifstream ifs("/proc/self/cmdline");
1298 std::getline(ifs, argv0, '\0');
1302 static std::string read_symlink(std::string const &symlink_path) {
1308 ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
1312 if (static_cast<size_t>(len) == path.size()) {
1313 path.resize(path.size() * 2);
1315 path.resize(static_cast<std::string::size_type>(len));
1324 template <typename STACKTRACE_TAG> class TraceResolverLinuxImpl;
1326 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1329 class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>
1330 : public TraceResolverLinuxBase {
1332 void load_addresses(void *const*addresses, int address_count) override {
1333 if (address_count == 0) {
1336 _symbols.reset(backtrace_symbols(addresses, address_count));
1339 ResolvedTrace resolve(ResolvedTrace trace) override {
1340 char *filename = _symbols[trace.idx];
1341 char *funcname = filename;
1342 while (*funcname && *funcname != '(') {
1345 trace.object_filename.assign(filename,
1346 funcname); // ok even if funcname is the ending
1347 // \0 (then we assign entire string)
1349 if (*funcname) { // if it's not end of string (e.g. from last frame ip==0)
1351 char *funcname_end = funcname;
1352 while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') {
1355 *funcname_end = '\0';
1356 trace.object_function = this->demangle(funcname);
1357 trace.source.function = trace.object_function; // we cannot do better.
1363 details::handle<char **> _symbols;
1366 #endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1368 #if BACKWARD_HAS_BFD == 1
1371 class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>
1372 : public TraceResolverLinuxBase {
1374 TraceResolverLinuxImpl() : _bfd_loaded(false) {}
1376 ResolvedTrace resolve(ResolvedTrace trace) override {
1377 Dl_info symbol_info;
1379 // trace.addr is a virtual address in memory pointing to some code.
1380 // Let's try to find from which loaded object it comes from.
1381 // The loaded object can be yourself btw.
1382 if (!dladdr(trace.addr, &symbol_info)) {
1383 return trace; // dat broken trace...
1386 // Now we get in symbol_info:
1388 // pathname of the shared object that contains the address.
1390 // where the object is loaded in memory.
1392 // the name of the nearest symbol to trace.addr, we expect a
1395 // the exact address corresponding to .dli_sname.
1397 if (symbol_info.dli_sname) {
1398 trace.object_function = demangle(symbol_info.dli_sname);
1401 if (!symbol_info.dli_fname) {
1405 trace.object_filename = resolve_exec_path(symbol_info);
1406 bfd_fileobject *fobj;
1407 // Before rushing to resolution need to ensure the executable
1408 // file still can be used. For that compare inode numbers of
1409 // what is stored by the executable's file path, and in the
1410 // dli_fname, which not necessarily equals to the executable.
1411 // It can be a shared library, or /proc/self/exe, and in the
1412 // latter case has drawbacks. See the exec path resolution for
1413 // details. In short - the dli object should be used only as
1415 // If inode numbers are equal, it is known dli_fname and the
1416 // executable file are the same. This is guaranteed by Linux,
1417 // because if the executable file is changed/deleted, it will
1418 // be done in a new inode. The old file will be preserved in
1419 // /proc/self/exe, and may even have inode 0. The latter can
1420 // happen if the inode was actually reused, and the file was
1421 // kept only in the main memory.
1423 struct stat obj_stat;
1424 struct stat dli_stat;
1425 if (stat(trace.object_filename.c_str(), &obj_stat) == 0 &&
1426 stat(symbol_info.dli_fname, &dli_stat) == 0 &&
1427 obj_stat.st_ino == dli_stat.st_ino) {
1428 // The executable file, and the shared object containing the
1429 // address are the same file. Safe to use the original path.
1430 // this is preferable. Libbfd will search for stripped debug
1431 // symbols in the same directory.
1432 fobj = load_object_with_bfd(trace.object_filename);
1434 // The original object file was *deleted*! The only hope is
1435 // that the debug symbols are either inside the shared
1436 // object file, or are in the same directory, and this is
1437 // not /proc/self/exe.
1440 if (fobj == nullptr || !fobj->handle) {
1441 fobj = load_object_with_bfd(symbol_info.dli_fname);
1442 if (!fobj->handle) {
1447 find_sym_result *details_selected; // to be filled.
1449 // trace.addr is the next instruction to be executed after returning
1450 // from the nested stack frame. In C++ this usually relate to the next
1451 // statement right after the function call that leaded to a new stack
1452 // frame. This is not usually what you want to see when printing out a
1454 find_sym_result details_call_site =
1455 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1456 details_selected = &details_call_site;
1458 #if BACKWARD_HAS_UNWIND == 0
1459 // ...this is why we also try to resolve the symbol that is right
1460 // before the return address. If we are lucky enough, we will get the
1461 // line of the function that was called. But if the code is optimized,
1462 // we might get something absolutely not related since the compiler
1463 // can reschedule the return address with inline functions and
1464 // tail-call optimization (among other things that I don't even know
1465 // or cannot even dream about with my tiny limited brain).
1466 find_sym_result details_adjusted_call_site = find_symbol_details(
1467 fobj, (void *)(uintptr_t(trace.addr) - 1), symbol_info.dli_fbase);
1469 // In debug mode, we should always get the right thing(TM).
1470 if (details_call_site.found && details_adjusted_call_site.found) {
1471 // Ok, we assume that details_adjusted_call_site is a better estimation.
1472 details_selected = &details_adjusted_call_site;
1473 trace.addr = (void *)(uintptr_t(trace.addr) - 1);
1476 if (details_selected == &details_call_site && details_call_site.found) {
1477 // we have to re-resolve the symbol in order to reset some
1478 // internal state in BFD... so we can call backtrace_inliners
1481 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1483 #endif // BACKWARD_HAS_UNWIND
1485 if (details_selected->found) {
1486 if (details_selected->filename) {
1487 trace.source.filename = details_selected->filename;
1489 trace.source.line = details_selected->line;
1491 if (details_selected->funcname) {
1492 // this time we get the name of the function where the code is
1493 // located, instead of the function were the address is
1494 // located. In short, if the code was inlined, we get the
1495 // function corresponding to the code. Else we already got in
1497 trace.source.function = demangle(details_selected->funcname);
1499 if (!symbol_info.dli_sname) {
1500 // for the case dladdr failed to find the symbol name of
1501 // the function, we might as well try to put something
1503 trace.object_function = trace.source.function;
1507 // Maybe the source of the trace got inlined inside the function
1508 // (trace.source.function). Let's see if we can get all the inlined
1509 // calls along the way up to the initial call site.
1510 trace.inliners = backtrace_inliners(fobj, *details_selected);
1513 if (trace.inliners.size() == 0) {
1514 // Maybe the trace was not inlined... or maybe it was and we
1515 // are lacking the debug information. Let's try to make the
1516 // world better and see if we can get the line number of the
1517 // function (trace.source.function) now.
1519 // We will get the location of where the function start (to be
1520 // exact: the first instruction that really start the
1521 // function), not where the name of the function is defined.
1522 // This can be quite far away from the name of the function
1525 // If the source of the function is the same as the source of
1526 // the trace, we cannot say if the trace was really inlined or
1527 // not. However, if the filename of the source is different
1528 // between the function and the trace... we can declare it as
1529 // an inliner. This is not 100% accurate, but better than
1532 if (symbol_info.dli_saddr) {
1533 find_sym_result details = find_symbol_details(fobj,
1534 symbol_info.dli_saddr,
1535 symbol_info.dli_fbase);
1537 if (details.found) {
1538 ResolvedTrace::SourceLoc diy_inliner;
1539 diy_inliner.line = details.line;
1540 if (details.filename) {
1541 diy_inliner.filename = details.filename;
1543 if (details.funcname) {
1544 diy_inliner.function = demangle(details.funcname);
1546 diy_inliner.function = trace.source.function;
1548 if (diy_inliner != trace.source) {
1549 trace.inliners.push_back(diy_inliner);
1563 typedef details::handle<bfd *,
1564 details::deleter<bfd_boolean, bfd *, &bfd_close> >
1567 typedef details::handle<asymbol **> bfd_symtab_t;
1569 struct bfd_fileobject {
1570 bfd_handle_t handle;
1572 bfd_symtab_t symtab;
1573 bfd_symtab_t dynamic_symtab;
1576 typedef details::hashtable<std::string, bfd_fileobject>::type fobj_bfd_map_t;
1577 fobj_bfd_map_t _fobj_bfd_map;
1579 bfd_fileobject *load_object_with_bfd(const std::string &filename_object) {
1580 using namespace details;
1583 using namespace details;
1588 fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object);
1589 if (it != _fobj_bfd_map.end()) {
1593 // this new object is empty for now.
1594 bfd_fileobject *r = &_fobj_bfd_map[filename_object];
1596 // we do the work temporary in this one;
1597 bfd_handle_t bfd_handle;
1599 int fd = open(filename_object.c_str(), O_RDONLY);
1600 bfd_handle.reset(bfd_fdopenr(filename_object.c_str(), "default", fd));
1606 if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
1607 return r; // not an object? You lose.
1610 if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
1611 return r; // that's what happen when you forget to compile in debug.
1614 ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get());
1616 ssize_t dyn_symtab_storage_size =
1617 bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
1619 if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
1620 return r; // weird, is the file is corrupted?
1623 bfd_symtab_t symtab, dynamic_symtab;
1624 ssize_t symcount = 0, dyn_symcount = 0;
1626 if (symtab_storage_size > 0) {
1627 symtab.reset(static_cast<bfd_symbol **>(
1628 malloc(static_cast<size_t>(symtab_storage_size))));
1629 symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get());
1632 if (dyn_symtab_storage_size > 0) {
1633 dynamic_symtab.reset(static_cast<bfd_symbol **>(
1634 malloc(static_cast<size_t>(dyn_symtab_storage_size))));
1635 dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(),
1636 dynamic_symtab.get());
1639 if (symcount <= 0 && dyn_symcount <= 0) {
1640 return r; // damned, that's a stripped file that you got there!
1643 r->handle = move(bfd_handle);
1644 r->symtab = move(symtab);
1645 r->dynamic_symtab = move(dynamic_symtab);
1649 struct find_sym_result {
1651 const char *filename;
1652 const char *funcname;
1656 struct find_sym_context {
1657 TraceResolverLinuxImpl *self;
1658 bfd_fileobject *fobj;
1661 find_sym_result result;
1664 find_sym_result find_symbol_details(bfd_fileobject *fobj, void *addr,
1666 find_sym_context context;
1667 context.self = this;
1668 context.fobj = fobj;
1669 context.addr = addr;
1670 context.base_addr = base_addr;
1671 context.result.found = false;
1672 bfd_map_over_sections(fobj->handle.get(), &find_in_section_trampoline,
1673 static_cast<void *>(&context));
1674 return context.result;
1677 static void find_in_section_trampoline(bfd *, asection *section, void *data) {
1678 find_sym_context *context = static_cast<find_sym_context *>(data);
1679 context->self->find_in_section(
1680 reinterpret_cast<bfd_vma>(context->addr),
1681 reinterpret_cast<bfd_vma>(context->base_addr), context->fobj, section,
1685 void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject *fobj,
1686 asection *section, find_sym_result &result) {
1690 #ifdef bfd_get_section_flags
1691 if ((bfd_get_section_flags(fobj->handle.get(), section) & SEC_ALLOC) == 0)
1693 if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
1695 return; // a debug section is never loaded automatically.
1697 #ifdef bfd_get_section_vma
1698 bfd_vma sec_addr = bfd_get_section_vma(fobj->handle.get(), section);
1700 bfd_vma sec_addr = bfd_section_vma(section);
1702 #ifdef bfd_get_section_size
1703 bfd_size_type size = bfd_get_section_size(section);
1705 bfd_size_type size = bfd_section_size(section);
1708 // are we in the boundaries of the section?
1709 if (addr < sec_addr || addr >= sec_addr + size) {
1710 addr -= base_addr; // oops, a relocated object, lets try again...
1711 if (addr < sec_addr || addr >= sec_addr + size) {
1716 #if defined(__clang__)
1717 #pragma clang diagnostic push
1718 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1720 if (!result.found && fobj->symtab) {
1721 result.found = bfd_find_nearest_line(
1722 fobj->handle.get(), section, fobj->symtab.get(), addr - sec_addr,
1723 &result.filename, &result.funcname, &result.line);
1726 if (!result.found && fobj->dynamic_symtab) {
1727 result.found = bfd_find_nearest_line(
1728 fobj->handle.get(), section, fobj->dynamic_symtab.get(),
1729 addr - sec_addr, &result.filename, &result.funcname, &result.line);
1731 #if defined(__clang__)
1732 #pragma clang diagnostic pop
1736 ResolvedTrace::source_locs_t
1737 backtrace_inliners(bfd_fileobject *fobj, find_sym_result previous_result) {
1738 // This function can be called ONLY after a SUCCESSFUL call to
1739 // find_symbol_details. The state is global to the bfd_handle.
1740 ResolvedTrace::source_locs_t results;
1741 while (previous_result.found) {
1742 find_sym_result result;
1743 result.found = bfd_find_inliner_info(fobj->handle.get(), &result.filename,
1744 &result.funcname, &result.line);
1747 .found) /* and not (
1748 cstrings_eq(previous_result.filename,
1749 result.filename) and
1750 cstrings_eq(previous_result.funcname, result.funcname)
1751 and result.line == previous_result.line
1754 ResolvedTrace::SourceLoc src_loc;
1755 src_loc.line = result.line;
1756 if (result.filename) {
1757 src_loc.filename = result.filename;
1759 if (result.funcname) {
1760 src_loc.function = demangle(result.funcname);
1762 results.push_back(src_loc);
1764 previous_result = result;
1769 bool cstrings_eq(const char *a, const char *b) {
1773 return strcmp(a, b) == 0;
1776 #endif // BACKWARD_HAS_BFD == 1
1778 #if BACKWARD_HAS_DW == 1
1781 class TraceResolverLinuxImpl<trace_resolver_tag::libdw>
1782 : public TraceResolverLinuxBase {
1784 TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {}
1786 ResolvedTrace resolve(ResolvedTrace trace) override {
1787 using namespace details;
1789 Dwarf_Addr trace_addr = reinterpret_cast<Dwarf_Addr>(trace.addr);
1791 if (!_dwfl_handle_initialized) {
1792 // initialize dwfl...
1793 _dwfl_cb.reset(new Dwfl_Callbacks);
1794 _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
1795 _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
1796 _dwfl_cb->debuginfo_path = 0;
1798 _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
1799 _dwfl_handle_initialized = true;
1801 if (!_dwfl_handle) {
1805 // ...from the current process.
1806 dwfl_report_begin(_dwfl_handle.get());
1807 int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid());
1808 dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
1814 if (!_dwfl_handle) {
1818 // find the module (binary object) that contains the trace's address.
1819 // This is not using any debug information, but the addresses ranges of
1820 // all the currently loaded binary object.
1821 Dwfl_Module *mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
1823 // now that we found it, lets get the name of it, this will be the
1824 // full path to the running binary or one of the loaded library.
1825 const char *module_name = dwfl_module_info(mod, 0, 0, 0, 0, 0, 0, 0);
1827 trace.object_filename = module_name;
1829 // We also look after the name of the symbol, equal or before this
1830 // address. This is found by walking the symtab. We should get the
1831 // symbol corresponding to the function (mangled) containing the
1832 // address. If the code corresponding to the address was inlined,
1833 // this is the name of the out-most inliner function.
1834 const char *sym_name = dwfl_module_addrname(mod, trace_addr);
1836 trace.object_function = demangle(sym_name);
1840 // now let's get serious, and find out the source location (file and
1841 // line number) of the address.
1843 // This function will look in .debug_aranges for the address and map it
1844 // to the location of the compilation unit DIE in .debug_info and
1846 Dwarf_Addr mod_bias = 0;
1847 Dwarf_Die *cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias);
1851 // Sadly clang does not generate the section .debug_aranges, thus
1852 // dwfl_module_addrdie will fail early. Clang doesn't either set
1853 // the lowpc/highpc/range info for every compilation unit.
1855 // So in order to save the world:
1856 // for every compilation unit, we will iterate over every single
1857 // DIEs. Normally functions should have a lowpc/highpc/range, which
1858 // we will use to infer the compilation unit.
1860 // note that this is probably badly inefficient.
1861 while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) {
1864 find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem);
1872 //#define BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1873 #ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1875 // If it's still not enough, lets dive deeper in the shit, and try
1876 // to save the world again: for every compilation unit, we will
1877 // load the corresponding .debug_line section, and see if we can
1878 // find our address in it.
1880 Dwarf_Addr cfi_bias;
1881 Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias);
1884 while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) {
1885 if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
1887 // ...but if we get a match, it might be a false positive
1888 // because our (address - bias) might as well be valid in a
1889 // different compilation unit. So we throw our last card on
1890 // the table and lookup for the address into the .eh_frame
1893 handle<Dwarf_Frame *> frame;
1894 dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
1904 return trace; // this time we lost the game :/
1907 // Now that we have a compilation unit DIE, this function will be able
1908 // to load the corresponding section in .debug_line (if not already
1909 // loaded) and hopefully find the source location mapped to our
1911 Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
1914 const char *srcfile = dwarf_linesrc(srcloc, 0, 0);
1916 trace.source.filename = srcfile;
1918 int line = 0, col = 0;
1919 dwarf_lineno(srcloc, &line);
1920 dwarf_linecol(srcloc, &col);
1921 trace.source.line = static_cast<unsigned>(line);
1922 trace.source.col = static_cast<unsigned>(col);
1925 deep_first_search_by_pc(cudie, trace_addr - mod_bias,
1926 inliners_search_cb(trace));
1927 if (trace.source.function.size() == 0) {
1929 trace.source.function = trace.object_function;
1936 typedef details::handle<Dwfl *, details::deleter<void, Dwfl *, &dwfl_end> >
1938 details::handle<Dwfl_Callbacks *, details::default_delete<Dwfl_Callbacks *> >
1940 dwfl_handle_t _dwfl_handle;
1941 bool _dwfl_handle_initialized;
1943 // defined here because in C++98, template function cannot take locally
1944 // defined types... grrr.
1945 struct inliners_search_cb {
1946 void operator()(Dwarf_Die *die) {
1947 switch (dwarf_tag(die)) {
1949 case DW_TAG_subprogram:
1950 if ((name = dwarf_diename(die))) {
1951 trace.source.function = name;
1955 case DW_TAG_inlined_subroutine:
1956 ResolvedTrace::SourceLoc sloc;
1957 Dwarf_Attribute attr_mem;
1959 if ((name = dwarf_diename(die))) {
1960 sloc.function = name;
1962 if ((name = die_call_file(die))) {
1963 sloc.filename = name;
1966 Dwarf_Word line = 0, col = 0;
1967 dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line);
1968 dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col);
1969 sloc.line = static_cast<unsigned>(line);
1970 sloc.col = static_cast<unsigned>(col);
1972 trace.inliners.push_back(sloc);
1976 ResolvedTrace &trace;
1977 inliners_search_cb(ResolvedTrace &t) : trace(t) {}
1980 static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) {
1981 Dwarf_Addr low, high;
1984 if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) {
1985 if (dwarf_lowpc(die, &low) != 0) {
1988 if (dwarf_highpc(die, &high) != 0) {
1989 Dwarf_Attribute attr_mem;
1990 Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
1992 if (dwarf_formudata(attr, &value) != 0) {
1997 return pc >= low && pc < high;
2000 // non-continuous range.
2002 ptrdiff_t offset = 0;
2003 while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
2004 if (pc >= low && pc < high) {
2011 static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
2012 Dwarf_Die *result) {
2013 if (dwarf_child(parent_die, result) != 0) {
2017 Dwarf_Die *die = result;
2019 switch (dwarf_tag(die)) {
2020 case DW_TAG_subprogram:
2021 case DW_TAG_inlined_subroutine:
2022 if (die_has_pc(die, pc)) {
2026 bool declaration = false;
2027 Dwarf_Attribute attr_mem;
2028 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
2031 // let's be curious and look deeper in the tree,
2032 // function are not necessarily at the first level, but
2033 // might be nested inside a namespace, structure etc.
2035 Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem);
2041 } while (dwarf_siblingof(die, result) == 0);
2045 template <typename CB>
2046 static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
2049 if (dwarf_child(parent_die, &die_mem) != 0) {
2053 bool branch_has_pc = false;
2054 Dwarf_Die *die = &die_mem;
2056 bool declaration = false;
2057 Dwarf_Attribute attr_mem;
2058 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
2061 // let's be curious and look deeper in the tree, function are
2062 // not necessarily at the first level, but might be nested
2063 // inside a namespace, structure, a function, an inlined
2065 branch_has_pc = deep_first_search_by_pc(die, pc, cb);
2067 if (!branch_has_pc) {
2068 branch_has_pc = die_has_pc(die, pc);
2070 if (branch_has_pc) {
2073 } while (dwarf_siblingof(die, &die_mem) == 0);
2074 return branch_has_pc;
2077 static const char *die_call_file(Dwarf_Die *die) {
2078 Dwarf_Attribute attr_mem;
2079 Dwarf_Word file_idx = 0;
2081 dwarf_formudata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx);
2083 if (file_idx == 0) {
2088 Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0);
2093 Dwarf_Files *files = 0;
2095 dwarf_getsrcfiles(cudie, &files, &nfiles);
2100 return dwarf_filesrc(files, file_idx, 0, 0);
2103 #endif // BACKWARD_HAS_DW == 1
2105 #if BACKWARD_HAS_DWARF == 1
2108 class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>
2109 : public TraceResolverLinuxBase {
2111 TraceResolverLinuxImpl() : _dwarf_loaded(false) {}
2113 ResolvedTrace resolve(ResolvedTrace trace) override {
2114 // trace.addr is a virtual address in memory pointing to some code.
2115 // Let's try to find from which loaded object it comes from.
2116 // The loaded object can be yourself btw.
2118 Dl_info symbol_info;
2119 int dladdr_result = 0;
2120 #if defined(__GLIBC__)
2122 // We request the link map so we can get information about offsets
2124 dladdr1(trace.addr, &symbol_info, reinterpret_cast<void **>(&link_map),
2127 // Android doesn't have dladdr1. Don't use the linker map.
2128 dladdr_result = dladdr(trace.addr, &symbol_info);
2130 if (!dladdr_result) {
2131 return trace; // dat broken trace...
2134 // Now we get in symbol_info:
2136 // pathname of the shared object that contains the address.
2138 // where the object is loaded in memory.
2140 // the name of the nearest symbol to trace.addr, we expect a
2143 // the exact address corresponding to .dli_sname.
2147 // difference between the address in the ELF file and the address
2150 // absolute pathname where the object was found
2152 if (symbol_info.dli_sname) {
2153 trace.object_function = demangle(symbol_info.dli_sname);
2156 if (!symbol_info.dli_fname) {
2160 trace.object_filename = resolve_exec_path(symbol_info);
2161 dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname);
2162 if (!fobj.dwarf_handle) {
2163 return trace; // sad, we couldn't load the object :(
2166 #if defined(__GLIBC__)
2167 // Convert the address to a module relative one by looking at
2168 // the module's loading address in the link map
2169 Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr) -
2170 reinterpret_cast<uintptr_t>(link_map->l_addr);
2172 Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr);
2175 if (trace.object_function.empty()) {
2176 symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address);
2178 if (it != fobj.symbol_cache.end()) {
2179 if (it->first != address) {
2180 if (it != fobj.symbol_cache.begin()) {
2184 trace.object_function = demangle(it->second.c_str());
2188 // Get the Compilation Unit DIE for the address
2189 Dwarf_Die die = find_die(fobj, address);
2192 return trace; // this time we lost the game :/
2195 // libdwarf doesn't give us direct access to its objects, it always
2196 // allocates a copy for the caller. We keep that copy alive in a cache
2197 // and we deallocate it later when it's no longer required.
2198 die_cache_entry &die_object = get_die_cache(fobj, die);
2199 if (die_object.isEmpty())
2200 return trace; // We have no line section for this DIE
2202 die_linemap_t::iterator it = die_object.line_section.lower_bound(address);
2204 if (it != die_object.line_section.end()) {
2205 if (it->first != address) {
2206 if (it == die_object.line_section.begin()) {
2207 // If we are on the first item of the line section
2208 // but the address does not match it means that
2209 // the address is below the range of the DIE. Give up.
2216 return trace; // We didn't find the address.
2219 // Get the Dwarf_Line that the address points to and call libdwarf
2220 // to get source file, line and column info.
2221 Dwarf_Line line = die_object.line_buffer[it->second];
2222 Dwarf_Error error = DW_DLE_NE;
2225 if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) {
2226 trace.source.filename = std::string(filename);
2227 dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
2230 Dwarf_Unsigned number = 0;
2231 if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
2232 trace.source.line = number;
2234 trace.source.line = 0;
2237 if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
2238 trace.source.col = number;
2240 trace.source.col = 0;
2243 std::vector<std::string> namespace_stack;
2244 deep_first_search_by_pc(fobj, die, address, namespace_stack,
2245 inliners_search_cb(trace, fobj, die));
2247 dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
2253 static int close_dwarf(Dwarf_Debug dwarf) {
2254 return dwarf_finish(dwarf, NULL);
2260 typedef details::handle<int, details::deleter<int, int, &::close> >
2263 typedef details::handle<Elf *, details::deleter<int, Elf *, &elf_end> >
2266 typedef details::handle<Dwarf_Debug,
2267 details::deleter<int, Dwarf_Debug, &close_dwarf> >
2270 typedef std::map<Dwarf_Addr, int> die_linemap_t;
2272 typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
2274 struct die_cache_entry {
2275 die_specmap_t spec_section;
2276 die_linemap_t line_section;
2277 Dwarf_Line *line_buffer;
2278 Dwarf_Signed line_count;
2279 Dwarf_Line_Context line_context;
2281 inline bool isEmpty() {
2282 return line_buffer == NULL || line_count == 0 || line_context == NULL ||
2283 line_section.empty();
2286 die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {}
2288 ~die_cache_entry() {
2290 dwarf_srclines_dealloc_b(line_context);
2295 typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
2297 typedef std::map<uintptr_t, std::string> symbol_cache_t;
2299 struct dwarf_fileobject {
2300 dwarf_file_t file_handle;
2301 dwarf_elf_t elf_handle;
2302 dwarf_handle_t dwarf_handle;
2303 symbol_cache_t symbol_cache;
2306 die_cache_t die_cache;
2307 die_cache_entry *current_cu;
2310 typedef details::hashtable<std::string, dwarf_fileobject>::type
2312 fobj_dwarf_map_t _fobj_dwarf_map;
2314 static bool cstrings_eq(const char *a, const char *b) {
2318 return strcmp(a, b) == 0;
2321 dwarf_fileobject &load_object_with_dwarf(const std::string &filename_object) {
2323 if (!_dwarf_loaded) {
2324 // Set the ELF library operating version
2325 // If that fails there's nothing we can do
2326 _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
2329 fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object);
2330 if (it != _fobj_dwarf_map.end()) {
2334 // this new object is empty for now
2335 dwarf_fileobject &r = _fobj_dwarf_map[filename_object];
2337 dwarf_file_t file_handle;
2338 file_handle.reset(open(filename_object.c_str(), O_RDONLY));
2339 if (file_handle.get() < 0) {
2343 // Try to get an ELF handle. We need to read the ELF sections
2344 // because we want to see if there is a .gnu_debuglink section
2345 // that points to a split debug file
2346 dwarf_elf_t elf_handle;
2347 elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
2352 const char *e_ident = elf_getident(elf_handle.get(), 0);
2357 // Get the number of sections
2358 // We use the new APIs as elf_getshnum is deprecated
2360 if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
2364 // Get the index to the string section
2365 size_t shdrstrndx = 0;
2366 if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) {
2370 std::string debuglink;
2371 // Iterate through the ELF sections to try to get a gnu_debuglink
2372 // note and also to cache the symbol table.
2373 // We go the preprocessor way to avoid having to create templated
2374 // classes or using gelf (which might throw a compiler error if 64 bit
2376 #define ELF_GET_DATA(ARCH) \
2377 Elf_Scn *elf_section = 0; \
2378 Elf_Data *elf_data = 0; \
2379 Elf##ARCH##_Shdr *section_header = 0; \
2380 Elf_Scn *symbol_section = 0; \
2381 size_t symbol_count = 0; \
2382 size_t symbol_strings = 0; \
2383 Elf##ARCH##_Sym *symbol = 0; \
2384 const char *section_name = 0; \
2386 while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \
2387 section_header = elf##ARCH##_getshdr(elf_section); \
2388 if (section_header == NULL) { \
2392 if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \
2393 section_header->sh_name)) == NULL) { \
2397 if (cstrings_eq(section_name, ".gnu_debuglink")) { \
2398 elf_data = elf_getdata(elf_section, NULL); \
2399 if (elf_data && elf_data->d_size > 0) { \
2401 std::string(reinterpret_cast<const char *>(elf_data->d_buf)); \
2405 switch (section_header->sh_type) { \
2407 symbol_section = elf_section; \
2408 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2409 symbol_strings = section_header->sh_link; \
2412 /* We use .dynsyms as a last resort, we prefer .symtab */ \
2414 if (!symbol_section) { \
2415 symbol_section = elf_section; \
2416 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2417 symbol_strings = section_header->sh_link; \
2423 if (symbol_section && symbol_count && symbol_strings) { \
2424 elf_data = elf_getdata(symbol_section, NULL); \
2425 symbol = reinterpret_cast<Elf##ARCH##_Sym *>(elf_data->d_buf); \
2426 for (size_t i = 0; i < symbol_count; ++i) { \
2427 int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
2428 if (type == STT_FUNC && symbol->st_value > 0) { \
2429 r.symbol_cache[symbol->st_value] = std::string( \
2430 elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \
2436 if (e_ident[EI_CLASS] == ELFCLASS32) {
2438 } else if (e_ident[EI_CLASS] == ELFCLASS64) {
2439 // libelf might have been built without 64 bit support
2445 if (!debuglink.empty()) {
2446 // We have a debuglink section! Open an elf instance on that
2447 // file instead. If we can't open the file, then return
2448 // the elf handle we had already opened.
2449 dwarf_file_t debuglink_file;
2450 debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
2451 if (debuglink_file.get() > 0) {
2452 dwarf_elf_t debuglink_elf;
2453 debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL));
2455 // If we have a valid elf handle, return the new elf handle
2456 // and file handle and discard the original ones
2457 if (debuglink_elf) {
2458 elf_handle = move(debuglink_elf);
2459 file_handle = move(debuglink_file);
2464 // Ok, we have a valid ELF handle, let's try to get debug symbols
2465 Dwarf_Debug dwarf_debug;
2466 Dwarf_Error error = DW_DLE_NE;
2467 dwarf_handle_t dwarf_handle;
2469 int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL,
2470 &dwarf_debug, &error);
2472 // We don't do any special handling for DW_DLV_NO_ENTRY specially.
2473 // If we get an error, or the file doesn't have debug information
2475 if (dwarf_result != DW_DLV_OK) {
2479 dwarf_handle.reset(dwarf_debug);
2481 r.file_handle = move(file_handle);
2482 r.elf_handle = move(elf_handle);
2483 r.dwarf_handle = move(dwarf_handle);
2488 die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) {
2489 Dwarf_Error error = DW_DLE_NE;
2491 // Get the die offset, we use it as the cache key
2492 Dwarf_Off die_offset;
2493 if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
2497 die_cache_t::iterator it = fobj.die_cache.find(die_offset);
2499 if (it != fobj.die_cache.end()) {
2500 fobj.current_cu = &it->second;
2504 die_cache_entry &de = fobj.die_cache[die_offset];
2505 fobj.current_cu = &de;
2507 Dwarf_Addr line_addr;
2508 Dwarf_Small table_count;
2510 // The addresses in the line section are not fully sorted (they might
2511 // be sorted by block of code belonging to the same file), which makes
2512 // it necessary to do so before searching is possible.
2514 // As libdwarf allocates a copy of everything, let's get the contents
2515 // of the line section and keep it around. We also create a map of
2516 // program counter to line table indices so we can search by address
2517 // and get the line buffer index.
2519 // To make things more difficult, the same address can span more than
2520 // one line, so we need to keep the index pointing to the first line
2521 // by using insert instead of the map's [ operator.
2523 // Get the line context for the DIE
2524 if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) ==
2526 // Get the source lines for this line context, to be deallocated
2528 if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer,
2530 &error) == DW_DLV_OK) {
2532 // Add all the addresses to our map
2533 for (int i = 0; i < de.line_count; i++) {
2534 if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) !=
2538 de.line_section.insert(std::pair<Dwarf_Addr, int>(line_addr, i));
2543 // For each CU, cache the function DIEs that contain the
2544 // DW_AT_specification attribute. When building with -g3 the function
2545 // DIEs are separated in declaration and specification, with the
2546 // declaration containing only the name and parameters and the
2547 // specification the low/high pc and other compiler attributes.
2549 // We cache those specifications so we don't skip over the declarations,
2550 // because they have no pc, and we can do namespace resolution for
2551 // DWARF function names.
2552 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2553 Dwarf_Die current_die = 0;
2554 if (dwarf_child(die, ¤t_die, &error) == DW_DLV_OK) {
2556 Dwarf_Die sibling_die = 0;
2558 Dwarf_Half tag_value;
2559 dwarf_tag(current_die, &tag_value, &error);
2561 if (tag_value == DW_TAG_subprogram ||
2562 tag_value == DW_TAG_inlined_subroutine) {
2564 Dwarf_Bool has_attr = 0;
2565 if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr,
2566 &error) == DW_DLV_OK) {
2568 Dwarf_Attribute attr_mem;
2569 if (dwarf_attr(current_die, DW_AT_specification, &attr_mem,
2570 &error) == DW_DLV_OK) {
2571 Dwarf_Off spec_offset = 0;
2572 if (dwarf_formref(attr_mem, &spec_offset, &error) ==
2574 Dwarf_Off spec_die_offset;
2575 if (dwarf_dieoffset(current_die, &spec_die_offset, &error) ==
2577 de.spec_section[spec_offset] = spec_die_offset;
2581 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2586 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
2587 if (result == DW_DLV_ERROR) {
2589 } else if (result == DW_DLV_NO_ENTRY) {
2593 if (current_die != die) {
2594 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2598 current_die = sibling_die;
2604 static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die,
2605 Dwarf_Half attr, bool global) {
2606 Dwarf_Error error = DW_DLE_NE;
2607 Dwarf_Attribute attr_mem;
2609 Dwarf_Die found_die = NULL;
2610 if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
2614 result = dwarf_global_formref(attr_mem, &offset, &error);
2616 result = dwarf_formref(attr_mem, &offset, &error);
2619 if (result == DW_DLV_OK) {
2620 if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) {
2624 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2629 static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die,
2630 Dwarf_Half attr, bool global) {
2631 Dwarf_Error error = DW_DLE_NE;
2634 Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
2638 if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
2640 value = std::string(name);
2642 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2644 dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
2650 // Returns a spec DIE linked to the passed one. The caller should
2651 // deallocate the DIE
2652 static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) {
2653 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2654 Dwarf_Error error = DW_DLE_NE;
2655 Dwarf_Off die_offset;
2656 if (fobj.current_cu &&
2657 dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) {
2658 die_specmap_t::iterator it =
2659 fobj.current_cu->spec_section.find(die_offset);
2661 // If we have a DIE that completes the current one, check if
2662 // that one has the pc we are looking for
2663 if (it != fobj.current_cu->spec_section.end()) {
2664 Dwarf_Die spec_die = 0;
2665 if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) {
2671 // Maybe we have an abstract origin DIE with the function information?
2672 return get_referenced_die(fobj.dwarf_handle.get(), die,
2673 DW_AT_abstract_origin, true);
2676 static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) {
2677 Dwarf_Addr low_pc = 0, high_pc = 0;
2678 Dwarf_Half high_pc_form = 0;
2679 Dwarf_Form_Class return_class;
2680 Dwarf_Error error = DW_DLE_NE;
2681 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2682 bool has_lowpc = false;
2683 bool has_highpc = false;
2684 bool has_ranges = false;
2686 if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
2687 // If we have a low_pc check if there is a high pc.
2688 // If we don't have a high pc this might mean we have a base
2689 // address for the ranges list or just an address.
2692 if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) ==
2694 // We do have a high pc. In DWARF 4+ this is an offset from the
2695 // low pc, but in earlier versions it's an absolute address.
2698 // In DWARF 2/3 this would be a DW_FORM_CLASS_ADDRESS
2699 if (return_class == DW_FORM_CLASS_CONSTANT) {
2700 high_pc = low_pc + high_pc;
2703 // We have low and high pc, check if our address
2705 return pc >= low_pc && pc < high_pc;
2708 // Reset the low_pc, in case dwarf_lowpc failing set it to some
2713 // Check if DW_AT_ranges is present and search for the PC in the
2714 // returned ranges list. We always add the low_pc, as it not set it will
2715 // be 0, in case we had a DW_AT_low_pc and DW_AT_ranges pair
2716 bool result = false;
2718 Dwarf_Attribute attr;
2719 if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
2722 if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
2723 Dwarf_Ranges *ranges;
2724 Dwarf_Signed ranges_count = 0;
2725 Dwarf_Unsigned byte_count = 0;
2727 if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count,
2728 &byte_count, &error) == DW_DLV_OK) {
2729 has_ranges = ranges_count != 0;
2730 for (int i = 0; i < ranges_count; i++) {
2731 if (ranges[i].dwr_addr1 != 0 &&
2732 pc >= ranges[i].dwr_addr1 + low_pc &&
2733 pc < ranges[i].dwr_addr2 + low_pc) {
2738 dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
2743 // Last attempt. We might have a single address set as low_pc.
2744 if (!result && low_pc != 0 && pc == low_pc) {
2748 // If we don't have lowpc, highpc and ranges maybe this DIE is a
2749 // declaration that relies on a DW_AT_specification DIE that happens
2750 // later. Use the specification cache we filled when we loaded this CU.
2751 if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
2752 Dwarf_Die spec_die = get_spec_die(fobj, die);
2754 result = die_has_pc(fobj, spec_die, pc);
2755 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2762 static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &type) {
2763 Dwarf_Error error = DW_DLE_NE;
2765 Dwarf_Die child = 0;
2766 if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
2767 get_type(dwarf, child, type);
2771 type.insert(0, "::");
2772 dwarf_dealloc(dwarf, child, DW_DLA_DIE);
2776 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2777 type.insert(0, std::string(name));
2778 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2780 type.insert(0, "<unknown>");
2784 static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
2785 Dwarf_Error error = DW_DLE_NE;
2787 Dwarf_Sig8 signature;
2788 Dwarf_Bool has_attr = 0;
2789 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) {
2791 Dwarf_Attribute attr_mem;
2792 if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) {
2793 if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) {
2794 return std::string("<no type signature>");
2797 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2801 Dwarf_Unsigned next_cu_header;
2802 Dwarf_Sig8 tu_signature;
2806 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0,
2807 &next_cu_header, 0, &error) == DW_DLV_OK) {
2809 if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
2810 Dwarf_Die type_cu_die = 0;
2811 if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) {
2812 Dwarf_Die child_die = 0;
2813 if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) {
2814 get_type(dwarf, child_die, result);
2815 found = !result.empty();
2816 dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
2818 dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
2824 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2825 &next_cu_header, 0, &error) == DW_DLV_OK) {
2826 // Reset the cu header state. Unfortunately, libdwarf's
2827 // next_cu_header API keeps its own iterator per Dwarf_Debug
2828 // that can't be reset. We need to keep fetching elements until
2832 // If we couldn't resolve the type just print out the signature
2833 std::ostringstream string_stream;
2834 string_stream << "<0x" << std::hex << std::setfill('0');
2835 for (int i = 0; i < 8; ++i) {
2836 string_stream << std::setw(2) << std::hex
2837 << (int)(unsigned char)(signature.signature[i]);
2839 string_stream << ">";
2840 result = string_stream.str();
2845 struct type_context_t {
2853 : is_const(false), is_typedef(false), has_type(false), has_name(false) {
2857 // Types are resolved from right to left: we get the variable name first
2858 // and then all specifiers (like const or pointer) in a chain of DW_AT_type
2859 // DIEs. Call this function recursively until we get a complete type
2861 static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die,
2862 type_context_t &context) {
2864 Dwarf_Error error = DW_DLE_NE;
2866 // typedefs contain also the base type, so we skip it and only
2867 // print the typedef name
2868 if (!context.is_typedef) {
2869 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2870 if (!context.text.empty()) {
2871 context.text.insert(0, " ");
2873 context.text.insert(0, std::string(name));
2874 dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
2877 context.is_typedef = false;
2878 context.has_type = true;
2879 if (context.is_const) {
2880 context.text.insert(0, "const ");
2881 context.is_const = false;
2885 bool next_type_is_const = false;
2886 bool is_keyword = true;
2889 Dwarf_Bool has_attr = 0;
2890 if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
2892 case DW_TAG_structure_type:
2893 case DW_TAG_union_type:
2894 case DW_TAG_class_type:
2895 case DW_TAG_enumeration_type:
2896 context.has_type = true;
2897 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) ==
2899 // If we have a signature it means the type is defined
2900 // in .debug_types, so we need to load the DIE pointed
2901 // at by the signature and resolve it
2904 get_type_by_signature(fobj.dwarf_handle.get(), die);
2905 if (context.is_const)
2906 type.insert(0, "const ");
2908 if (!context.text.empty())
2909 context.text.insert(0, " ");
2910 context.text.insert(0, type);
2913 // Treat enums like typedefs, and skip printing its
2915 context.is_typedef = (tag == DW_TAG_enumeration_type);
2918 case DW_TAG_const_type:
2919 next_type_is_const = true;
2921 case DW_TAG_pointer_type:
2922 context.text.insert(0, "*");
2924 case DW_TAG_reference_type:
2925 context.text.insert(0, "&");
2927 case DW_TAG_restrict_type:
2928 context.text.insert(0, "restrict ");
2930 case DW_TAG_rvalue_reference_type:
2931 context.text.insert(0, "&&");
2933 case DW_TAG_volatile_type:
2934 context.text.insert(0, "volatile ");
2936 case DW_TAG_typedef:
2937 // Propagate the const-ness to the next type
2938 // as typedefs are linked to its base type
2939 next_type_is_const = context.is_const;
2940 context.is_typedef = true;
2941 context.has_type = true;
2943 case DW_TAG_base_type:
2944 context.has_type = true;
2946 case DW_TAG_formal_parameter:
2947 context.has_name = true;
2955 if (!is_keyword && context.is_const) {
2956 context.text.insert(0, "const ");
2959 context.is_const = next_type_is_const;
2962 get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type, true);
2964 set_parameter_string(fobj, ref, context);
2965 dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
2968 if (!context.has_type && context.has_name) {
2969 context.text.insert(0, "void ");
2970 context.has_type = true;
2974 // Resolve the function return type and parameters
2975 static void set_function_parameters(std::string &function_name,
2976 std::vector<std::string> &ns,
2977 dwarf_fileobject &fobj, Dwarf_Die die) {
2978 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2979 Dwarf_Error error = DW_DLE_NE;
2980 Dwarf_Die current_die = 0;
2981 std::string parameters;
2982 bool has_spec = true;
2983 // Check if we have a spec DIE. If we do we use it as it contains
2984 // more information, like parameter names.
2985 Dwarf_Die spec_die = get_spec_die(fobj, die);
2991 std::vector<std::string>::const_iterator it = ns.begin();
2992 std::string ns_name;
2993 for (it = ns.begin(); it < ns.end(); ++it) {
2994 ns_name.append(*it).append("::");
2997 if (!ns_name.empty()) {
2998 function_name.insert(0, ns_name);
3001 // See if we have a function return type. It can be either on the
3002 // current die or in its spec one (usually true for inlined functions)
3003 std::string return_type =
3004 get_referenced_die_name(dwarf, die, DW_AT_type, true);
3005 if (return_type.empty()) {
3006 return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type, true);
3008 if (!return_type.empty()) {
3009 return_type.append(" ");
3010 function_name.insert(0, return_type);
3013 if (dwarf_child(spec_die, ¤t_die, &error) == DW_DLV_OK) {
3015 Dwarf_Die sibling_die = 0;
3017 Dwarf_Half tag_value;
3018 dwarf_tag(current_die, &tag_value, &error);
3020 if (tag_value == DW_TAG_formal_parameter) {
3021 // Ignore artificial (ie, compiler generated) parameters
3022 bool is_artificial = false;
3023 Dwarf_Attribute attr_mem;
3024 if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) ==
3026 Dwarf_Bool flag = 0;
3027 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3028 is_artificial = flag != 0;
3030 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3033 if (!is_artificial) {
3034 type_context_t context;
3035 set_parameter_string(fobj, current_die, context);
3037 if (parameters.empty()) {
3038 parameters.append("(");
3040 parameters.append(", ");
3042 parameters.append(context.text);
3046 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3047 if (result == DW_DLV_ERROR) {
3049 } else if (result == DW_DLV_NO_ENTRY) {
3053 if (current_die != die) {
3054 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3058 current_die = sibling_die;
3061 if (parameters.empty())
3063 parameters.append(")");
3065 // If we got a spec DIE we need to deallocate it
3067 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
3069 function_name.append(parameters);
3072 // defined here because in C++98, template function cannot take locally
3073 // defined types... grrr.
3074 struct inliners_search_cb {
3075 void operator()(Dwarf_Die die, std::vector<std::string> &ns) {
3076 Dwarf_Error error = DW_DLE_NE;
3077 Dwarf_Half tag_value;
3078 Dwarf_Attribute attr_mem;
3079 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3081 dwarf_tag(die, &tag_value, &error);
3083 switch (tag_value) {
3085 case DW_TAG_subprogram:
3086 if (!trace.source.function.empty())
3088 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
3089 trace.source.function = std::string(name);
3090 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
3092 // We don't have a function name in this DIE.
3093 // Check if there is a referenced non-defining
3095 trace.source.function =
3096 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
3097 if (trace.source.function.empty()) {
3098 trace.source.function =
3099 get_referenced_die_name(dwarf, die, DW_AT_specification, true);
3103 // Append the function parameters, if available
3104 set_function_parameters(trace.source.function, ns, fobj, die);
3106 // If the object function name is empty, it's possible that
3107 // there is no dynamic symbol table (maybe the executable
3108 // was stripped or not built with -rdynamic). See if we have
3109 // a DWARF linkage name to use instead. We try both
3110 // linkage_name and MIPS_linkage_name because the MIPS tag
3111 // was the unofficial one until it was adopted in DWARF4.
3112 // Old gcc versions generate MIPS_linkage_name
3113 if (trace.object_function.empty()) {
3114 details::demangler demangler;
3116 if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) !=
3118 if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) !=
3125 if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) {
3126 trace.object_function = demangler.demangle(linkage);
3127 dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
3129 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3133 case DW_TAG_inlined_subroutine:
3134 ResolvedTrace::SourceLoc sloc;
3136 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
3137 sloc.function = std::string(name);
3138 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
3140 // We don't have a name for this inlined DIE, it could
3141 // be that there is an abstract origin instead.
3142 // Get the DW_AT_abstract_origin value, which is a
3143 // reference to the source DIE and try to get its name
3145 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
3148 set_function_parameters(sloc.function, ns, fobj, die);
3150 std::string file = die_call_file(dwarf, die, cu_die);
3152 sloc.filename = file;
3154 Dwarf_Unsigned number = 0;
3155 if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) {
3156 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
3159 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3162 if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) ==
3164 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
3167 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3170 trace.inliners.push_back(sloc);
3174 ResolvedTrace &trace;
3175 dwarf_fileobject &fobj;
3177 inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &f, Dwarf_Die c)
3178 : trace(t), fobj(f), cu_die(c) {}
3181 static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj,
3182 Dwarf_Die parent_die, Dwarf_Addr pc,
3184 Dwarf_Die current_die = 0;
3185 Dwarf_Error error = DW_DLE_NE;
3186 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3188 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
3193 Dwarf_Die sibling_die = 0;
3194 Dwarf_Half tag_value;
3195 dwarf_tag(current_die, &tag_value, &error);
3197 switch (tag_value) {
3198 case DW_TAG_subprogram:
3199 case DW_TAG_inlined_subroutine:
3200 if (die_has_pc(fobj, current_die, pc)) {
3204 bool declaration = false;
3205 Dwarf_Attribute attr_mem;
3206 if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
3208 Dwarf_Bool flag = 0;
3209 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3210 declaration = flag != 0;
3212 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3216 // let's be curious and look deeper in the tree, functions are
3217 // not necessarily at the first level, but might be nested
3218 // inside a namespace, structure, a function, an inlined
3220 Dwarf_Die die_mem = 0;
3221 Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem);
3228 int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3229 if (res == DW_DLV_ERROR) {
3231 } else if (res == DW_DLV_NO_ENTRY) {
3235 if (current_die != parent_die) {
3236 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3240 current_die = sibling_die;
3245 template <typename CB>
3246 static bool deep_first_search_by_pc(dwarf_fileobject &fobj,
3247 Dwarf_Die parent_die, Dwarf_Addr pc,
3248 std::vector<std::string> &ns, CB cb) {
3249 Dwarf_Die current_die = 0;
3250 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3251 Dwarf_Error error = DW_DLE_NE;
3253 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
3257 bool branch_has_pc = false;
3258 bool has_namespace = false;
3260 Dwarf_Die sibling_die = 0;
3263 if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
3264 if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
3265 char *ns_name = NULL;
3266 if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) {
3268 ns.push_back(std::string(ns_name));
3270 ns.push_back("<unknown>");
3272 dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
3274 ns.push_back("<unknown>");
3276 has_namespace = true;
3280 bool declaration = false;
3281 Dwarf_Attribute attr_mem;
3282 if (tag != DW_TAG_class_type &&
3283 dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
3285 Dwarf_Bool flag = 0;
3286 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3287 declaration = flag != 0;
3289 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3293 // let's be curious and look deeper in the tree, function are
3294 // not necessarily at the first level, but might be nested
3295 // inside a namespace, structure, a function, an inlined
3297 branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb);
3300 if (!branch_has_pc) {
3301 branch_has_pc = die_has_pc(fobj, current_die, pc);
3304 if (branch_has_pc) {
3305 cb(current_die, ns);
3308 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3309 if (result == DW_DLV_ERROR) {
3311 } else if (result == DW_DLV_NO_ENTRY) {
3315 if (current_die != parent_die) {
3316 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3320 if (has_namespace) {
3321 has_namespace = false;
3324 current_die = sibling_die;
3327 if (has_namespace) {
3330 return branch_has_pc;
3333 static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die,
3335 Dwarf_Attribute attr_mem;
3336 Dwarf_Error error = DW_DLE_NE;
3337 Dwarf_Unsigned file_index;
3341 if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
3342 if (dwarf_formudata(attr_mem, &file_index, &error) != DW_DLV_OK) {
3345 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3347 if (file_index == 0) {
3351 char **srcfiles = 0;
3352 Dwarf_Signed file_count = 0;
3353 if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) {
3354 if (file_count > 0 && file_index <= static_cast<Dwarf_Unsigned>(file_count)) {
3355 file = std::string(srcfiles[file_index - 1]);
3358 // Deallocate all strings!
3359 for (int i = 0; i < file_count; ++i) {
3360 dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
3362 dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
3368 Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) {
3369 // Let's get to work! First see if we have a debug_aranges section so
3370 // we can speed up the search
3372 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3373 Dwarf_Error error = DW_DLE_NE;
3374 Dwarf_Arange *aranges;
3375 Dwarf_Signed arange_count;
3377 Dwarf_Die returnDie;
3379 if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) !=
3385 // We have aranges. Get the one where our address is.
3386 Dwarf_Arange arange;
3387 if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) ==
3390 // We found our address. Get the compilation-unit DIE offset
3391 // represented by the given address range.
3392 Dwarf_Off cu_die_offset;
3393 if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) ==
3395 // Get the DIE at the offset returned by the aranges search.
3396 // We set is_info to 1 to specify that the offset is from
3397 // the .debug_info section (and not .debug_types)
3399 dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error);
3401 found = dwarf_result == DW_DLV_OK;
3403 dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
3408 return returnDie; // The caller is responsible for freeing the die
3410 // The search for aranges failed. Try to find our address by scanning
3411 // all compilation units.
3412 Dwarf_Unsigned next_cu_header;
3417 dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3418 &next_cu_header, 0, &error) == DW_DLV_OK) {
3421 dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
3423 if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
3424 if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) &&
3425 tag == DW_TAG_compile_unit) {
3426 if (die_has_pc(fobj, returnDie, addr)) {
3434 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3435 &next_cu_header, 0, &error) == DW_DLV_OK) {
3436 // Reset the cu header state. Libdwarf's next_cu_header API
3437 // keeps its own iterator per Dwarf_Debug that can't be reset.
3438 // We need to keep fetching elements until the end.
3445 // We couldn't find any compilation units with ranges or a high/low pc.
3446 // Try again by looking at all DIEs in all compilation units.
3448 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3449 &next_cu_header, 0, &error) == DW_DLV_OK) {
3450 if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
3451 Dwarf_Die die_mem = 0;
3452 Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem);
3462 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3463 &next_cu_header, 0, &error) == DW_DLV_OK) {
3464 // Reset the cu header state. Libdwarf's next_cu_header API
3465 // keeps its own iterator per Dwarf_Debug that can't be reset.
3466 // We need to keep fetching elements until the end.
3477 #endif // BACKWARD_HAS_DWARF == 1
3480 class TraceResolverImpl<system_tag::linux_tag>
3481 : public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
3483 #endif // BACKWARD_SYSTEM_LINUX
3485 #ifdef BACKWARD_SYSTEM_DARWIN
3487 template <typename STACKTRACE_TAG> class TraceResolverDarwinImpl;
3490 class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>
3491 : public TraceResolverImplBase {
3493 void load_addresses(void *const*addresses, int address_count) override {
3494 if (address_count == 0) {
3497 _symbols.reset(backtrace_symbols(addresses, address_count));
3500 ResolvedTrace resolve(ResolvedTrace trace) override {
3502 // <n> <file> <addr> <mangled-name> + <offset>
3503 char *filename = _symbols[trace.idx];
3506 while (*filename && *filename != ' ')
3508 while (*filename == ' ')
3511 // find start of <mangled-name> from end (<file> may contain a space)
3512 char *p = filename + strlen(filename) - 1;
3513 // skip to start of " + <offset>"
3514 while (p > filename && *p != ' ')
3516 while (p > filename && *p == ' ')
3518 while (p > filename && *p != ' ')
3520 while (p > filename && *p == ' ')
3522 char *funcname_end = p + 1;
3524 // skip to start of "<manged-name>"
3525 while (p > filename && *p != ' ')
3527 char *funcname = p + 1;
3529 // skip to start of " <addr> "
3530 while (p > filename && *p == ' ')
3532 while (p > filename && *p != ' ')
3534 while (p > filename && *p == ' ')
3537 // skip "<file>", handling the case where it contains a
3538 char *filename_end = p + 1;
3539 if (p == filename) {
3540 // something went wrong, give up
3541 filename_end = filename + strlen(filename);
3542 funcname = filename_end;
3544 trace.object_filename.assign(
3545 filename, filename_end); // ok even if filename_end is the ending \0
3546 // (then we assign entire string)
3548 if (*funcname) { // if it's not end of string
3549 *funcname_end = '\0';
3551 trace.object_function = this->demangle(funcname);
3552 trace.object_function += " ";
3553 trace.object_function += (funcname_end + 1);
3554 trace.source.function = trace.object_function; // we cannot do better.
3560 details::handle<char **> _symbols;
3564 class TraceResolverImpl<system_tag::darwin_tag>
3565 : public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
3567 #endif // BACKWARD_SYSTEM_DARWIN
3569 #ifdef BACKWARD_SYSTEM_WINDOWS
3571 // Load all symbol info
3573 // https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
3575 struct module_data {
3576 std::string image_name;
3577 std::string module_name;
3582 class get_mod_info {
3584 static const int buffer_length = 4096;
3587 get_mod_info(HANDLE h) : process(h) {}
3589 module_data operator()(HMODULE module) {
3591 char temp[buffer_length];
3594 GetModuleInformation(process, module, &mi, sizeof(mi));
3595 ret.base_address = mi.lpBaseOfDll;
3596 ret.load_size = mi.SizeOfImage;
3598 GetModuleFileNameExA(process, module, temp, sizeof(temp));
3599 ret.image_name = temp;
3600 GetModuleBaseNameA(process, module, temp, sizeof(temp));
3601 ret.module_name = temp;
3602 std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
3603 std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
3604 SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address,
3610 template <> class TraceResolverImpl<system_tag::windows_tag>
3611 : public TraceResolverImplBase {
3613 TraceResolverImpl() {
3615 HANDLE process = GetCurrentProcess();
3617 std::vector<module_data> modules;
3619 std::vector<HMODULE> module_handles(1);
3620 SymInitialize(process, NULL, false);
3621 DWORD symOptions = SymGetOptions();
3622 symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME;
3623 SymSetOptions(symOptions);
3624 EnumProcessModules(process, &module_handles[0],
3625 static_cast<DWORD>(module_handles.size() * sizeof(HMODULE)),
3627 module_handles.resize(cbNeeded / sizeof(HMODULE));
3628 EnumProcessModules(process, &module_handles[0],
3629 static_cast<DWORD>(module_handles.size() * sizeof(HMODULE)),
3631 std::transform(module_handles.begin(), module_handles.end(),
3632 std::back_inserter(modules), get_mod_info(process));
3633 void *base = modules[0].base_address;
3634 IMAGE_NT_HEADERS *h = ImageNtHeader(base);
3635 image_type = h->FileHeader.Machine;
3638 static const int max_sym_len = 255;
3641 char buffer[max_sym_len];
3644 DWORD64 displacement;
3646 ResolvedTrace resolve(ResolvedTrace t) override {
3647 HANDLE process = GetCurrentProcess();
3651 memset(&sym, 0, sizeof(sym));
3652 sym.sym.SizeOfStruct = sizeof(SYMBOL_INFO);
3653 sym.sym.MaxNameLen = max_sym_len;
3655 if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) {
3656 // TODO: error handling everywhere
3658 DWORD dw = GetLastError();
3660 if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3661 FORMAT_MESSAGE_FROM_SYSTEM |
3662 FORMAT_MESSAGE_IGNORE_INSERTS,
3663 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
3664 (char*)&lpMsgBuf, 0, NULL)) {
3665 std::fprintf(stderr, "%s\n", lpMsgBuf);
3666 LocalFree(lpMsgBuf);
3671 UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE);
3675 if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) {
3676 t.object_filename = line.FileName;
3677 t.source.filename = line.FileName;
3678 t.source.line = line.LineNumber;
3679 t.source.col = offset;
3682 t.source.function = name;
3683 t.object_filename = "";
3684 t.object_function = name;
3689 DWORD machine_type() const { return image_type; }
3697 class TraceResolver : public TraceResolverImpl<system_tag::current_tag> {};
3699 /*************** CODE SNIPPET ***************/
3703 typedef std::vector<std::pair<unsigned, std::string> > lines_t;
3706 SourceFile(const std::string &path) {
3707 // 1. If BACKWARD_CXX_SOURCE_PREFIXES is set then assume it contains
3708 // a colon-separated list of path prefixes. Try prepending each
3709 // to the given path until a valid file is found.
3710 const std::vector<std::string> &prefixes = get_paths_from_env_variable();
3711 for (size_t i = 0; i < prefixes.size(); ++i) {
3712 // Double slashes (//) should not be a problem.
3713 std::string new_path = prefixes[i] + '/' + path;
3714 _file.reset(new std::ifstream(new_path.c_str()));
3718 // 2. If no valid file found then fallback to opening the path as-is.
3719 if (!_file || !is_open()) {
3720 _file.reset(new std::ifstream(path.c_str()));
3723 bool is_open() const { return _file->is_open(); }
3725 lines_t &get_lines(unsigned line_start, unsigned line_count, lines_t &lines) {
3726 using namespace std;
3727 // This function make uses of the dumbest algo ever:
3729 // 2) read lines one by one and discard until line_start
3730 // 3) read line one by one until line_start + line_count
3732 // If you are getting snippets many time from the same file, it is
3733 // somewhat a waste of CPU, feel free to benchmark and propose a
3734 // better solution ;)
3741 for (line_idx = 1; line_idx < line_start; ++line_idx) {
3742 std::getline(*_file, line);
3748 // think of it like a lambda in C++98 ;)
3749 // but look, I will reuse it two times!
3750 // What a good boy am I.
3752 bool operator()(char c) { return std::isspace(c); }
3755 bool started = false;
3756 for (; line_idx < line_start + line_count; ++line_idx) {
3757 getline(*_file, line);
3762 if (std::find_if(line.begin(), line.end(), not_isspace()) == line.end())
3766 lines.push_back(make_pair(line_idx, line));
3770 std::find_if(lines.rbegin(), lines.rend(), not_isempty()).base(),
3775 lines_t get_lines(unsigned line_start, unsigned line_count) {
3777 return get_lines(line_start, line_count, lines);
3780 // there is no find_if_not in C++98, lets do something crappy to
3782 struct not_isspace {
3783 bool operator()(char c) { return !std::isspace(c); }
3785 // and define this one here because C++98 is not happy with local defined
3786 // struct passed to template functions, fuuuu.
3787 struct not_isempty {
3788 bool operator()(const lines_t::value_type &p) {
3789 return !(std::find_if(p.second.begin(), p.second.end(), not_isspace()) ==
3794 void swap(SourceFile &b) { _file.swap(b._file); }
3796 #ifdef BACKWARD_ATLEAST_CXX11
3797 SourceFile(SourceFile &&from) : _file(nullptr) { swap(from); }
3798 SourceFile &operator=(SourceFile &&from) {
3803 explicit SourceFile(const SourceFile &from) {
3804 // some sort of poor man's move semantic.
3805 swap(const_cast<SourceFile &>(from));
3807 SourceFile &operator=(const SourceFile &from) {
3808 // some sort of poor man's move semantic.
3809 swap(const_cast<SourceFile &>(from));
3814 // Allow adding to paths gotten from BACKWARD_CXX_SOURCE_PREFIXES after loading the
3815 // library; this can be useful when the library is loaded when the locations are unknown
3816 // Warning: Because this edits the static paths variable, it is *not* intrinsiclly thread safe
3817 static void add_paths_to_env_variable_impl(const std::string & to_add) {
3818 get_mutable_paths_from_env_variable().push_back(to_add);
3822 details::handle<std::ifstream *, details::default_delete<std::ifstream *> >
3825 static std::vector<std::string> get_paths_from_env_variable_impl() {
3826 std::vector<std::string> paths;
3827 const char *prefixes_str = std::getenv("BACKWARD_CXX_SOURCE_PREFIXES");
3828 if (prefixes_str && prefixes_str[0]) {
3829 paths = details::split_source_prefixes(prefixes_str);
3834 static std::vector<std::string> &get_mutable_paths_from_env_variable() {
3835 static volatile std::vector<std::string> paths = get_paths_from_env_variable_impl();
3836 return const_cast<std::vector<std::string>&>(paths);
3839 static const std::vector<std::string> &get_paths_from_env_variable() {
3840 return get_mutable_paths_from_env_variable();
3843 #ifdef BACKWARD_ATLEAST_CXX11
3844 SourceFile(const SourceFile &) = delete;
3845 SourceFile &operator=(const SourceFile &) = delete;
3849 class SnippetFactory {
3851 typedef SourceFile::lines_t lines_t;
3853 lines_t get_snippet(const std::string &filename, unsigned line_start,
3854 unsigned context_size) {
3856 SourceFile &src_file = get_src_file(filename);
3857 unsigned start = line_start - context_size / 2;
3858 return src_file.get_lines(start, context_size);
3861 lines_t get_combined_snippet(const std::string &filename_a, unsigned line_a,
3862 const std::string &filename_b, unsigned line_b,
3863 unsigned context_size) {
3864 SourceFile &src_file_a = get_src_file(filename_a);
3865 SourceFile &src_file_b = get_src_file(filename_b);
3868 src_file_a.get_lines(line_a - context_size / 4, context_size / 2);
3869 src_file_b.get_lines(line_b - context_size / 4, context_size / 2, lines);
3873 lines_t get_coalesced_snippet(const std::string &filename, unsigned line_a,
3874 unsigned line_b, unsigned context_size) {
3875 SourceFile &src_file = get_src_file(filename);
3879 unsigned a = min(line_a, line_b);
3880 unsigned b = max(line_a, line_b);
3882 if ((b - a) < (context_size / 3)) {
3883 return src_file.get_lines((a + b - context_size + 1) / 2, context_size);
3886 lines_t lines = src_file.get_lines(a - context_size / 4, context_size / 2);
3887 src_file.get_lines(b - context_size / 4, context_size / 2, lines);
3892 typedef details::hashtable<std::string, SourceFile>::type src_files_t;
3893 src_files_t _src_files;
3895 SourceFile &get_src_file(const std::string &filename) {
3896 src_files_t::iterator it = _src_files.find(filename);
3897 if (it != _src_files.end()) {
3900 SourceFile &new_src_file = _src_files[filename];
3901 new_src_file = SourceFile(filename);
3902 return new_src_file;
3906 /*************** PRINTER ***************/
3908 namespace ColorMode {
3909 enum type { automatic, never, always };
3912 class cfile_streambuf : public std::streambuf {
3914 cfile_streambuf(FILE *_sink) : sink(_sink) {}
3915 int_type underflow() override { return traits_type::eof(); }
3916 int_type overflow(int_type ch) override {
3917 if (traits_type::not_eof(ch) && fputc(ch, sink) != EOF) {
3920 return traits_type::eof();
3923 std::streamsize xsputn(const char_type *s, std::streamsize count) override {
3924 return static_cast<std::streamsize>(
3925 fwrite(s, sizeof *s, static_cast<size_t>(count), sink));
3928 #ifdef BACKWARD_ATLEAST_CXX11
3930 cfile_streambuf(const cfile_streambuf &) = delete;
3931 cfile_streambuf &operator=(const cfile_streambuf &) = delete;
3934 cfile_streambuf(const cfile_streambuf &);
3935 cfile_streambuf &operator=(const cfile_streambuf &);
3940 std::vector<char> buffer;
3943 #ifdef BACKWARD_SYSTEM_LINUX
3946 enum type { yellow = 33, purple = 35, reset = 39 };
3947 } // namespace Color
3951 Colorize(std::ostream &os) : _os(os), _reset(false), _enabled(false) {}
3953 void activate(ColorMode::type mode) { _enabled = mode == ColorMode::always; }
3955 void activate(ColorMode::type mode, FILE *fp) { activate(mode, fileno(fp)); }
3957 void set_color(Color::type ccode) {
3961 // I assume that the terminal can handle basic colors. Seriously I
3962 // don't want to deal with all the termcap shit.
3963 _os << "\033[" << static_cast<int>(ccode) << "m";
3964 _reset = (ccode != Color::reset);
3969 set_color(Color::reset);
3974 void activate(ColorMode::type mode, int fd) {
3975 activate(mode == ColorMode::automatic && isatty(fd) ? ColorMode::always
3984 #else // ndef BACKWARD_SYSTEM_LINUX
3987 enum type { yellow = 0, purple = 0, reset = 0 };
3988 } // namespace Color
3992 Colorize(std::ostream &) {}
3993 void activate(ColorMode::type) {}
3994 void activate(ColorMode::type, FILE *) {}
3995 void set_color(Color::type) {}
3998 #endif // BACKWARD_SYSTEM_LINUX
4003 ColorMode::type color_mode;
4006 int inliner_context_size;
4007 int trace_context_size;
4011 : snippet(true), color_mode(ColorMode::automatic), address(false),
4012 object(false), inliner_context_size(5), trace_context_size(7),
4015 template <typename ST> FILE *print(ST &st, FILE *fp = stderr) {
4016 cfile_streambuf obuf(fp);
4017 std::ostream os(&obuf);
4018 Colorize colorize(os);
4019 colorize.activate(color_mode, fp);
4020 print_stacktrace(st, os, colorize);
4024 template <typename ST> std::ostream &print(ST &st, std::ostream &os) {
4025 Colorize colorize(os);
4026 colorize.activate(color_mode);
4027 print_stacktrace(st, os, colorize);
4031 template <typename IT>
4032 FILE *print(IT begin, IT end, FILE *fp = stderr, size_t thread_id = 0) {
4033 cfile_streambuf obuf(fp);
4034 std::ostream os(&obuf);
4035 Colorize colorize(os);
4036 colorize.activate(color_mode, fp);
4037 print_stacktrace(begin, end, os, thread_id, colorize);
4041 template <typename IT>
4042 std::ostream &print(IT begin, IT end, std::ostream &os,
4043 size_t thread_id = 0) {
4044 Colorize colorize(os);
4045 colorize.activate(color_mode);
4046 print_stacktrace(begin, end, os, thread_id, colorize);
4050 TraceResolver const &resolver() const { return _resolver; }
4053 TraceResolver _resolver;
4054 SnippetFactory _snippets;
4056 template <typename ST>
4057 void print_stacktrace(ST &st, std::ostream &os, Colorize &colorize) {
4058 print_header(os, st.thread_id());
4059 _resolver.load_stacktrace(st);
4061 for (size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
4062 print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize);
4065 for (size_t trace_idx = 0; trace_idx < st.size(); ++trace_idx) {
4066 print_trace(os, _resolver.resolve(st[trace_idx]), colorize);
4071 template <typename IT>
4072 void print_stacktrace(IT begin, IT end, std::ostream &os, size_t thread_id,
4073 Colorize &colorize) {
4074 print_header(os, thread_id);
4075 for (; begin != end; ++begin) {
4076 print_trace(os, *begin, colorize);
4080 void print_header(std::ostream &os, size_t thread_id) {
4081 os << "Stack trace (most recent call last)";
4083 os << " in thread " << thread_id;
4088 void print_trace(std::ostream &os, const ResolvedTrace &trace,
4089 Colorize &colorize) {
4090 os << "#" << std::left << std::setw(2) << trace.idx << std::right;
4091 bool already_indented = true;
4093 if (!trace.source.filename.size() || object) {
4094 os << " Object \"" << trace.object_filename << "\", at " << trace.addr
4095 << ", in " << trace.object_function << "\n";
4096 already_indented = false;
4099 for (size_t inliner_idx = trace.inliners.size(); inliner_idx > 0;
4101 if (!already_indented) {
4104 const ResolvedTrace::SourceLoc &inliner_loc =
4105 trace.inliners[inliner_idx - 1];
4106 print_source_loc(os, " | ", inliner_loc);
4108 print_snippet(os, " | ", inliner_loc, colorize, Color::purple,
4109 inliner_context_size);
4111 already_indented = false;
4114 if (trace.source.filename.size()) {
4115 if (!already_indented) {
4118 print_source_loc(os, " ", trace.source, trace.addr);
4120 print_snippet(os, " ", trace.source, colorize, Color::yellow,
4121 trace_context_size);
4126 void print_snippet(std::ostream &os, const char *indent,
4127 const ResolvedTrace::SourceLoc &source_loc,
4128 Colorize &colorize, Color::type color_code,
4130 using namespace std;
4131 typedef SnippetFactory::lines_t lines_t;
4133 lines_t lines = _snippets.get_snippet(source_loc.filename, source_loc.line,
4134 static_cast<unsigned>(context_size));
4136 for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) {
4137 if (it->first == source_loc.line) {
4138 colorize.set_color(color_code);
4139 os << indent << ">";
4141 os << indent << " ";
4143 os << std::setw(4) << it->first << ": " << it->second << "\n";
4144 if (it->first == source_loc.line) {
4145 colorize.set_color(Color::reset);
4150 void print_source_loc(std::ostream &os, const char *indent,
4151 const ResolvedTrace::SourceLoc &source_loc,
4152 void *addr = nullptr) {
4153 os << indent << "Source \"" << source_loc.filename << ":"
4154 << source_loc.line << "\", in " << source_loc.function;
4156 if (address && addr != nullptr) {
4157 os << " [" << addr << "]";
4163 /*************** SIGNALS HANDLING ***************/
4165 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
4167 class SignalHandling {
4169 static std::vector<int> make_default_signals() {
4170 const int posix_signals[] = {
4171 // Signals for which the default action is "Core".
4172 SIGABRT, // Abort signal from abort(3)
4173 SIGBUS, // Bus error (bad memory access)
4174 SIGFPE, // Floating point exception
4175 SIGILL, // Illegal Instruction
4176 SIGIOT, // IOT trap. A synonym for SIGABRT
4177 SIGQUIT, // Quit from keyboard
4178 SIGSEGV, // Invalid memory reference
4179 SIGSYS, // Bad argument to routine (SVr4)
4180 SIGTRAP, // Trace/breakpoint trap
4181 SIGXCPU, // CPU time limit exceeded (4.2BSD)
4182 SIGXFSZ, // File size limit exceeded (4.2BSD)
4183 #if defined(BACKWARD_SYSTEM_DARWIN)
4184 SIGEMT, // emulation instruction executed
4187 return std::vector<int>(posix_signals,
4189 sizeof posix_signals / sizeof posix_signals[0]);
4192 SignalHandling(const std::vector<int> &posix_signals = make_default_signals())
4194 bool success = true;
4196 const size_t stack_size = 1024 * 1024 * 8;
4197 _stack_content.reset(static_cast<char *>(malloc(stack_size)));
4198 if (_stack_content) {
4200 ss.ss_sp = _stack_content.get();
4201 ss.ss_size = stack_size;
4203 if (sigaltstack(&ss, nullptr) < 0) {
4210 for (size_t i = 0; i < posix_signals.size(); ++i) {
4211 struct sigaction action;
4212 memset(&action, 0, sizeof action);
4214 static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
4215 sigfillset(&action.sa_mask);
4216 sigdelset(&action.sa_mask, posix_signals[i]);
4217 #if defined(__clang__)
4218 #pragma clang diagnostic push
4219 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
4221 action.sa_sigaction = &sig_handler;
4222 #if defined(__clang__)
4223 #pragma clang diagnostic pop
4226 int r = sigaction(posix_signals[i], &action, nullptr);
4234 bool loaded() const { return _loaded; }
4236 static void handleSignal(int, siginfo_t *info, void *_ctx) {
4237 ucontext_t *uctx = static_cast<ucontext_t *>(_ctx);
4240 void *error_addr = nullptr;
4241 #ifdef REG_RIP // x86_64
4242 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
4243 #elif defined(REG_EIP) // x86_32
4244 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
4245 #elif defined(__arm__)
4246 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.arm_pc);
4247 #elif defined(__aarch64__)
4248 #if defined(__APPLE__)
4249 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__pc);
4251 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.pc);
4253 #elif defined(__mips__)
4254 error_addr = reinterpret_cast<void *>(
4255 reinterpret_cast<struct sigcontext *>(&uctx->uc_mcontext)->sc_pc);
4256 #elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
4257 defined(__POWERPC__)
4258 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.regs->nip);
4259 #elif defined(__riscv)
4260 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.__gregs[REG_PC]);
4261 #elif defined(__s390x__)
4262 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.psw.addr);
4263 #elif defined(__APPLE__) && defined(__x86_64__)
4264 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__rip);
4265 #elif defined(__APPLE__)
4266 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__eip);
4268 #warning ":/ sorry, ain't know no nothing none not of your architecture!"
4271 st.load_from(error_addr, 32, reinterpret_cast<void *>(uctx),
4274 st.load_here(32, reinterpret_cast<void *>(uctx), info->si_addr);
4278 printer.address = true;
4279 printer.print(st, stderr);
4281 #if (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 700) || \
4282 (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200809L)
4283 psiginfo(info, nullptr);
4290 details::handle<char *> _stack_content;
4294 __attribute__((noreturn))
4297 sig_handler(int signo, siginfo_t *info, void *_ctx) {
4298 handleSignal(signo, info, _ctx);
4300 // try to forward the signal.
4301 raise(info->si_signo);
4303 // terminate the process immediately.
4305 _exit(EXIT_FAILURE);
4309 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
4311 #ifdef BACKWARD_SYSTEM_WINDOWS
4313 class SignalHandling {
4315 SignalHandling(const std::vector<int> & = std::vector<int>())
4316 : reporter_thread_([]() {
4317 /* We handle crashes in a utility thread:
4318 backward structures and some Windows functions called here
4319 need stack space, which we do not have when we encounter a
4321 To support reporting stack traces during a stack overflow,
4322 we create a utility thread at startup, which waits until a
4323 crash happens or the program exits normally. */
4326 std::unique_lock<std::mutex> lk(mtx());
4327 cv().wait(lk, [] { return crashed() != crash_status::running; });
4329 if (crashed() == crash_status::crashed) {
4330 handle_stacktrace(skip_recs());
4333 std::unique_lock<std::mutex> lk(mtx());
4334 crashed() = crash_status::ending;
4338 SetUnhandledExceptionFilter(crash_handler);
4340 signal(SIGABRT, signal_handler);
4341 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
4343 std::set_terminate(&terminator);
4344 #ifndef BACKWARD_ATLEAST_CXX17
4345 std::set_unexpected(&terminator);
4347 _set_purecall_handler(&terminator);
4348 _set_invalid_parameter_handler(&invalid_parameter_handler);
4350 bool loaded() const { return true; }
4354 std::unique_lock<std::mutex> lk(mtx());
4355 crashed() = crash_status::normal_exit;
4360 reporter_thread_.join();
4364 static CONTEXT *ctx() {
4365 static CONTEXT data;
4369 enum class crash_status { running, crashed, normal_exit, ending };
4371 static crash_status &crashed() {
4372 static crash_status data;
4376 static std::mutex &mtx() {
4377 static std::mutex data;
4381 static std::condition_variable &cv() {
4382 static std::condition_variable data;
4386 static HANDLE &thread_handle() {
4387 static HANDLE handle;
4391 std::thread reporter_thread_;
4393 // TODO: how not to hardcode these?
4394 static const constexpr int signal_skip_recs =
4396 // With clang, RtlCaptureContext also captures the stack frame of the
4397 // current function Below that, there are 3 internal Windows functions
4400 // With MSVC cl, RtlCaptureContext misses the stack frame of the current
4401 // function The first entries during StackWalk are the 3 internal Windows
4407 static int &skip_recs() {
4412 static inline void terminator() {
4413 crash_handler(signal_skip_recs);
4417 static inline void signal_handler(int) {
4418 crash_handler(signal_skip_recs);
4422 static inline void __cdecl invalid_parameter_handler(const wchar_t *,
4427 crash_handler(signal_skip_recs);
4431 NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) {
4432 // The exception info supplies a trace from exactly where the issue was,
4433 // no need to skip records
4434 crash_handler(0, info->ContextRecord);
4435 return EXCEPTION_CONTINUE_SEARCH;
4438 NOINLINE static void crash_handler(int skip, CONTEXT *ct = nullptr) {
4440 if (ct == nullptr) {
4441 RtlCaptureContext(ctx());
4443 memcpy(ctx(), ct, sizeof(CONTEXT));
4445 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
4446 GetCurrentProcess(), &thread_handle(), 0, FALSE,
4447 DUPLICATE_SAME_ACCESS);
4452 std::unique_lock<std::mutex> lk(mtx());
4453 crashed() = crash_status::crashed;
4459 std::unique_lock<std::mutex> lk(mtx());
4460 cv().wait(lk, [] { return crashed() != crash_status::crashed; });
4464 static void handle_stacktrace(int skip_frames = 0) {
4465 // printer creates the TraceResolver, which can supply us a machine type
4466 // for stack walking. Without this, StackTrace can only guess using some
4468 // StackTrace also requires that the PDBs are already loaded, which is done
4469 // in the constructor of TraceResolver
4473 st.set_machine_type(printer.resolver().machine_type());
4474 st.set_thread_handle(thread_handle());
4475 st.load_here(32 + skip_frames, ctx());
4476 st.skip_n_firsts(skip_frames);
4478 printer.address = true;
4479 printer.print(st, std::cerr);
4483 #endif // BACKWARD_SYSTEM_WINDOWS
4485 #ifdef BACKWARD_SYSTEM_UNKNOWN
4487 class SignalHandling {
4489 SignalHandling(const std::vector<int> & = std::vector<int>()) {}
4490 bool init() { return false; }
4491 bool loaded() { return false; }
4494 #endif // BACKWARD_SYSTEM_UNKNOWN
4496 } // namespace backward
4498 #endif /* H_GUARD */