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
24 #ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
25 #define H_6B9572DA_A64B_49E6_B234_051480991C89
28 # error "It's not going to compile without a C++ compiler..."
31 #if defined(BACKWARD_CXX11)
32 #elif defined(BACKWARD_CXX98)
34 # if __cplusplus >= 201103L
35 # define BACKWARD_CXX11
36 # define BACKWARD_ATLEAST_CXX11
37 # define BACKWARD_ATLEAST_CXX98
39 # define BACKWARD_CXX98
40 # define BACKWARD_ATLEAST_CXX98
44 // You can define one of the following (or leave it to the auto-detection):
46 // #define BACKWARD_SYSTEM_LINUX
47 // - specialization for linux
49 // #define BACKWARD_SYSTEM_DARWIN
50 // - specialization for Mac OS X 10.5 and later.
52 // #define BACKWARD_SYSTEM_UNKNOWN
53 // - placebo implementation, does nothing.
55 #if defined(BACKWARD_SYSTEM_LINUX)
56 #elif defined(BACKWARD_SYSTEM_DARWIN)
57 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
59 # if defined(__linux) || defined(__linux__)
60 # define BACKWARD_SYSTEM_LINUX
61 # elif defined(__APPLE__)
62 # define BACKWARD_SYSTEM_DARWIN
64 # define BACKWARD_SYSTEM_UNKNOWN
83 #if defined(BACKWARD_SYSTEM_LINUX)
85 // On linux, backtrace can back-trace or "walk" the stack using the following
88 // #define BACKWARD_HAS_UNWIND 1
89 // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
90 // - with unwind, the stacktrace is as accurate as it can possibly be, since
91 // this is used by the C++ runtine in gcc/clang for stack unwinding on
93 // - normally libgcc is already linked to your program by default.
95 // #define BACKWARD_HAS_BACKTRACE == 1
96 // - backtrace seems to be a little bit more portable than libunwind, but on
97 // linux, it uses unwind anyway, but abstract away a tiny information that is
98 // sadly really important in order to get perfectly accurate stack traces.
99 // - backtrace is part of the (e)glib library.
102 // #define BACKWARD_HAS_UNWIND == 1
104 // Note that only one of the define should be set to 1 at a time.
106 # if BACKWARD_HAS_UNWIND == 1
107 # elif BACKWARD_HAS_BACKTRACE == 1
109 # undef BACKWARD_HAS_UNWIND
110 # define BACKWARD_HAS_UNWIND 1
111 # undef BACKWARD_HAS_BACKTRACE
112 # define BACKWARD_HAS_BACKTRACE 0
115 // On linux, backward can extract detailed information about a stack trace
116 // using one of the following libraries:
118 // #define BACKWARD_HAS_DW 1
119 // - libdw gives you the most juicy details out of your stack traces:
123 // - line and column numbers
124 // - source code snippet (assuming the file is accessible)
125 // - variables name and values (if not optimized out)
126 // - You need to link with the lib "dw":
127 // - apt-get install libdw-dev
128 // - g++/clang++ -ldw ...
130 // #define BACKWARD_HAS_BFD 1
131 // - With libbfd, you get a fair amount of details:
136 // - source code snippet (assuming the file is accessible)
137 // - You need to link with the lib "bfd":
138 // - apt-get install binutils-dev
139 // - g++/clang++ -lbfd ...
141 // #define BACKWARD_HAS_DWARF 1
142 // - libdwarf 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 // - variables name and values (if not optimized out)
149 // - You need to link with the lib "dwarf":
150 // - apt-get install libdwarf-dev
151 // - g++/clang++ -ldwarf ...
153 // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
154 // - backtrace provides minimal details for a stack trace:
157 // - backtrace is part of the (e)glib library.
160 // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
162 // Note that only one of the define should be set to 1 at a time.
164 # if BACKWARD_HAS_DW == 1
165 # elif BACKWARD_HAS_BFD == 1
166 # elif BACKWARD_HAS_DWARF == 1
167 # elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
169 # undef BACKWARD_HAS_DW
170 # define BACKWARD_HAS_DW 0
171 # undef BACKWARD_HAS_BFD
172 # define BACKWARD_HAS_BFD 0
173 # undef BACKWARD_HAS_DWARF
174 # define BACKWARD_HAS_DWARF 0
175 # undef BACKWARD_HAS_BACKTRACE_SYMBOL
176 # define BACKWARD_HAS_BACKTRACE_SYMBOL 1
182 // Old Android API levels define _Unwind_Ptr in both link.h and unwind.h
183 // Rename the one in link.h as we are not going to be using it
184 # define _Unwind_Ptr _Unwind_Ptr_Custom
190 # include <sys/stat.h>
191 # include <syscall.h>
195 # if BACKWARD_HAS_BFD == 1
196 // NOTE: defining PACKAGE{,_VERSION} is required before including
197 // bfd.h on some platforms, see also:
198 // https://sourceware.org/bugzilla/show_bug.cgi?id=14243
202 # ifndef PACKAGE_VERSION
203 # define PACKAGE_VERSION
215 # if BACKWARD_HAS_DW == 1
216 # include <elfutils/libdw.h>
217 # include <elfutils/libdwfl.h>
221 # if BACKWARD_HAS_DWARF == 1
224 # include <libdwarf.h>
226 # include <algorithm>
236 # if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
237 // then we shall rely on backtrace
238 # include <execinfo.h>
241 #endif // defined(BACKWARD_SYSTEM_LINUX)
243 #if defined(BACKWARD_SYSTEM_DARWIN)
244 // On Darwin, backtrace can back-trace or "walk" the stack using the following
247 // #define BACKWARD_HAS_UNWIND 1
248 // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
249 // - with unwind, the stacktrace is as accurate as it can possibly be, since
250 // this is used by the C++ runtine in gcc/clang for stack unwinding on
252 // - normally libgcc is already linked to your program by default.
254 // #define BACKWARD_HAS_BACKTRACE == 1
255 // - backtrace is available by default, though it does not produce as much information
256 // as another library might.
259 // #define BACKWARD_HAS_UNWIND == 1
261 // Note that only one of the define should be set to 1 at a time.
263 # if BACKWARD_HAS_UNWIND == 1
264 # elif BACKWARD_HAS_BACKTRACE == 1
266 # undef BACKWARD_HAS_UNWIND
267 # define BACKWARD_HAS_UNWIND 1
268 # undef BACKWARD_HAS_BACKTRACE
269 # define BACKWARD_HAS_BACKTRACE 0
272 // On Darwin, backward can extract detailed information about a stack trace
273 // using one of the following libraries:
275 // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
276 // - backtrace provides minimal details for a stack trace:
281 // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
283 # if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
285 # undef BACKWARD_HAS_BACKTRACE_SYMBOL
286 # define BACKWARD_HAS_BACKTRACE_SYMBOL 1
291 # include <pthread.h>
292 # include <sys/stat.h>
296 # if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
297 # include <execinfo.h>
299 #endif // defined(BACKWARD_SYSTEM_DARWIN)
301 #if BACKWARD_HAS_UNWIND == 1
304 // while gcc's unwind.h defines something like that:
305 // extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *);
306 // extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
308 // clang's unwind.h defines something like this:
309 // uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context);
311 // Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we
312 // cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr
315 // Luckily we can play on the fact that the guard macros have a different name:
316 #ifdef __CLANG_UNWIND_H
317 // In fact, this function still comes from libgcc (on my different linux boxes,
318 // clang links against libgcc).
319 # include <inttypes.h>
320 extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context*, int*);
323 #endif // BACKWARD_HAS_UNWIND == 1
325 #ifdef BACKWARD_ATLEAST_CXX11
326 # include <unordered_map>
327 # include <utility> // for std::swap
330 template <typename K, typename V>
332 typedef std::unordered_map<K, V> type;
335 } // namespace details
336 } // namespace backward
337 #else // NOT BACKWARD_ATLEAST_CXX11
338 # define nullptr NULL
343 template <typename K, typename V>
345 typedef std::map<K, V> type;
347 template <typename T>
348 const T& move(const T& v) { return v; }
349 template <typename T>
350 T& move(T& v) { return v; }
351 } // namespace details
352 } // namespace backward
353 #endif // BACKWARD_ATLEAST_CXX11
357 namespace system_tag {
358 struct linux_tag; // seems that I cannot call that "linux" because the name
359 // is already defined... so I am adding _tag everywhere.
363 #if defined(BACKWARD_SYSTEM_LINUX)
364 typedef linux_tag current_tag;
365 #elif defined(BACKWARD_SYSTEM_DARWIN)
366 typedef darwin_tag current_tag;
367 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
368 typedef unknown_tag current_tag;
370 # error "May I please get my system defines?"
372 } // namespace system_tag
375 namespace trace_resolver_tag {
376 #if defined(BACKWARD_SYSTEM_LINUX)
380 struct backtrace_symbol;
382 # if BACKWARD_HAS_DW == 1
383 typedef libdw current;
384 # elif BACKWARD_HAS_BFD == 1
385 typedef libbfd current;
386 # elif BACKWARD_HAS_DWARF == 1
387 typedef libdwarf current;
388 # elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
389 typedef backtrace_symbol current;
391 # error "You shall not pass, until you know what you want."
393 #elif defined(BACKWARD_SYSTEM_DARWIN)
394 struct backtrace_symbol;
396 # if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
397 typedef backtrace_symbol current;
399 # error "You shall not pass, until you know what you want."
402 } // namespace trace_resolver_tag
407 template <typename T>
408 struct rm_ptr { typedef T type; };
410 template <typename T>
411 struct rm_ptr<T*> { typedef T type; };
413 template <typename T>
414 struct rm_ptr<const T*> { typedef const T type; };
416 template <typename R, typename T, R (*F)(T)>
418 template <typename U>
419 void operator()(U& ptr) const {
424 template <typename T>
425 struct default_delete {
426 void operator()(T& ptr) const {
431 template <typename T, typename Deleter = deleter<void, void*, &::free> >
437 #ifdef BACKWARD_ATLEAST_CXX11
438 handle(const handle&) = delete;
439 handle& operator=(const handle&) = delete;
449 explicit handle(): _val(), _empty(true) {}
450 explicit handle(T val): _val(val), _empty(false) { if(!_val) _empty = true; }
452 #ifdef BACKWARD_ATLEAST_CXX11
453 handle(handle&& from): _empty(true) {
456 handle& operator=(handle&& from) {
457 swap(from); return *this;
460 explicit handle(const handle& from): _empty(true) {
461 // some sort of poor man's move semantic.
462 swap(const_cast<handle&>(from));
464 handle& operator=(const handle& from) {
465 // some sort of poor man's move semantic.
466 swap(const_cast<handle&>(from)); return *this;
470 void reset(T new_val) {
474 operator const dummy*() const {
478 return reinterpret_cast<const dummy*>(_val);
487 void swap(handle& b) {
489 swap(b._val, _val); // can throw, we are safe here.
490 swap(b._empty, _empty); // should not throw: if you cannot swap two
491 // bools without throwing... It's a lost cause anyway!
494 T operator->() { return _val; }
495 const T operator->() const { return _val; }
497 typedef typename rm_ptr<T>::type& ref_t;
498 typedef const typename rm_ptr<T>::type& const_ref_t;
499 ref_t operator*() { return *_val; }
500 const_ref_t operator*() const { return *_val; }
501 ref_t operator[](size_t idx) { return _val[idx]; }
503 // Watch out, we've got a badass over here
510 // Default demangler implementation (do nothing).
511 template <typename TAG>
512 struct demangler_impl {
513 static std::string demangle(const char* funcname) {
518 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
521 struct demangler_impl<system_tag::current_tag> {
522 demangler_impl(): _demangle_buffer_length(0) {}
524 std::string demangle(const char* funcname) {
525 using namespace details;
526 char* result = abi::__cxa_demangle(funcname,
527 _demangle_buffer.release(), &_demangle_buffer_length, nullptr);
529 _demangle_buffer.reset(result);
536 details::handle<char*> _demangle_buffer;
537 size_t _demangle_buffer_length;
540 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
543 public demangler_impl<system_tag::current_tag> {};
545 } // namespace details
547 /*************** A TRACE ***************/
554 addr(nullptr), idx(0) {}
556 explicit Trace(void* _addr, size_t _idx):
557 addr(_addr), idx(_idx) {}
560 struct ResolvedTrace: public Trace {
563 std::string function;
564 std::string filename;
568 SourceLoc(): line(0), col(0) {}
570 bool operator==(const SourceLoc& b) const {
571 return function == b.function
572 && filename == b.filename
577 bool operator!=(const SourceLoc& b) const {
578 return !(*this == b);
582 // In which binary object this trace is located.
583 std::string object_filename;
585 // The function in the object that contain the trace. This is not the same
586 // as source.function which can be an function inlined in object_function.
587 std::string object_function;
589 // The source location of this trace. It is possible for filename to be
590 // empty and for line/col to be invalid (value 0) if this information
591 // couldn't be deduced, for example if there is no debug information in the
595 // An optionals list of "inliners". All the successive sources location
596 // from where the source location of the trace (the attribute right above)
597 // is inlined. It is especially useful when you compiled with optimization.
598 typedef std::vector<SourceLoc> source_locs_t;
599 source_locs_t inliners;
603 ResolvedTrace(const Trace& mini_trace):
607 /*************** STACK TRACE ***************/
609 // default implemention.
610 template <typename TAG>
611 class StackTraceImpl {
613 size_t size() const { return 0; }
614 Trace operator[](size_t) { return Trace(); }
615 size_t load_here(size_t=0) { return 0; }
616 size_t load_from(void*, size_t=0) { return 0; }
617 size_t thread_id() const { return 0; }
618 void skip_n_firsts(size_t) { }
621 class StackTraceImplBase {
623 StackTraceImplBase(): _thread_id(0), _skip(0) {}
625 size_t thread_id() const {
629 void skip_n_firsts(size_t n) { _skip = n; }
632 void load_thread_info() {
633 #ifdef BACKWARD_SYSTEM_LINUX
635 _thread_id = static_cast<size_t>(syscall(SYS_gettid));
637 _thread_id = static_cast<size_t>(gettid());
639 if (_thread_id == static_cast<size_t>(getpid())) {
640 // If the thread is the main one, let's hide that.
641 // I like to keep little secret sometimes.
644 #elif defined(BACKWARD_SYSTEM_DARWIN)
645 _thread_id = reinterpret_cast<size_t>(pthread_self());
646 if (pthread_main_np() == 1) {
647 // If the thread is the main one, let's hide that.
653 size_t skip_n_firsts() const { return _skip; }
660 class StackTraceImplHolder: public StackTraceImplBase {
662 size_t size() const {
663 return _stacktrace.size() ? _stacktrace.size() - skip_n_firsts() : 0;
665 Trace operator[](size_t idx) const {
669 return Trace(_stacktrace[idx + skip_n_firsts()], idx);
671 void* const* begin() const {
673 return &_stacktrace[skip_n_firsts()];
679 std::vector<void*> _stacktrace;
683 #if BACKWARD_HAS_UNWIND == 1
687 template <typename F>
690 size_t operator()(F& f, size_t depth) {
694 _Unwind_Backtrace(&this->backtrace_trampoline, this);
695 return static_cast<size_t>(_index);
703 static _Unwind_Reason_Code backtrace_trampoline(
704 _Unwind_Context* ctx, void *self) {
705 return (static_cast<Unwinder*>(self))->backtrace(ctx);
708 _Unwind_Reason_Code backtrace(_Unwind_Context* ctx) {
709 if (_index >= 0 && static_cast<size_t>(_index) >= _depth)
710 return _URC_END_OF_STACK;
712 int ip_before_instruction = 0;
713 uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
715 if (!ip_before_instruction) {
716 // calculating 0-1 for unsigned, looks like a possible bug to sanitiziers, so let's do it explicitly:
718 ip = std::numeric_limits<uintptr_t>::max(); // set it to 0xffff... (as from casting 0-1)
720 ip -= 1; // else just normally decrement it (no overflow/underflow will happen)
724 if (_index >= 0) { // ignore first frame.
725 (*_f)(static_cast<size_t>(_index), reinterpret_cast<void*>(ip));
728 return _URC_NO_REASON;
732 template <typename F>
733 size_t unwind(F f, size_t depth) {
734 Unwinder<F> unwinder;
735 return unwinder(f, depth);
738 } // namespace details
742 class StackTraceImpl<system_tag::current_tag>: public StackTraceImplHolder {
744 __attribute__ ((noinline)) // TODO use some macro
745 size_t load_here(size_t depth=32) {
750 _stacktrace.resize(depth);
751 size_t trace_cnt = details::unwind(callback(*this), depth);
752 _stacktrace.resize(trace_cnt);
756 size_t load_from(void* addr, size_t depth=32) {
757 load_here(depth + 8);
759 for (size_t i = 0; i < _stacktrace.size(); ++i) {
760 if (_stacktrace[i] == addr) {
766 _stacktrace.resize(std::min(_stacktrace.size(),
767 skip_n_firsts() + depth));
773 StackTraceImpl& self;
774 callback(StackTraceImpl& _self): self(_self) {}
776 void operator()(size_t idx, void* addr) {
777 self._stacktrace[idx] = addr;
783 #else // BACKWARD_HAS_UNWIND == 0
786 class StackTraceImpl<system_tag::current_tag>: public StackTraceImplHolder {
788 __attribute__ ((noinline)) // TODO use some macro
789 size_t load_here(size_t depth=32) {
794 _stacktrace.resize(depth + 1);
795 size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
796 _stacktrace.resize(trace_cnt);
801 size_t load_from(void* addr, size_t depth=32) {
802 load_here(depth + 8);
804 for (size_t i = 0; i < _stacktrace.size(); ++i) {
805 if (_stacktrace[i] == addr) {
807 _stacktrace[i] = (void*)( (uintptr_t)_stacktrace[i] + 1);
812 _stacktrace.resize(std::min(_stacktrace.size(),
813 skip_n_firsts() + depth));
818 #endif // BACKWARD_HAS_UNWIND
821 public StackTraceImpl<system_tag::current_tag> {};
823 /*************** TRACE RESOLVER ***************/
825 template <typename TAG>
826 class TraceResolverImpl;
828 #ifdef BACKWARD_SYSTEM_UNKNOWN
831 class TraceResolverImpl<system_tag::unknown_tag> {
834 void load_stacktrace(ST&) {}
835 ResolvedTrace resolve(ResolvedTrace t) {
842 class TraceResolverImplBase {
844 std::string demangle(const char* funcname) {
845 return _demangler.demangle(funcname);
849 details::demangler _demangler;
852 #ifdef BACKWARD_SYSTEM_LINUX
854 template <typename STACKTRACE_TAG>
855 class TraceResolverLinuxImpl;
857 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
860 class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>:
861 public TraceResolverImplBase {
864 void load_stacktrace(ST& st) {
865 using namespace details;
866 if (st.size() == 0) {
870 backtrace_symbols(st.begin(), (int)st.size())
874 ResolvedTrace resolve(ResolvedTrace trace) {
875 char* filename = _symbols[trace.idx];
876 char* funcname = filename;
877 while (*funcname && *funcname != '(') {
880 trace.object_filename.assign(filename, funcname); // ok even if funcname is the ending \0 (then we assign entire string)
882 if (*funcname) { // if it's not end of string (e.g. from last frame ip==0)
884 char* funcname_end = funcname;
885 while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') {
888 *funcname_end = '\0';
889 trace.object_function = this->demangle(funcname);
890 trace.source.function = trace.object_function; // we cannot do better.
896 details::handle<char**> _symbols;
899 #endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
901 #if BACKWARD_HAS_BFD == 1
904 class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>:
905 public TraceResolverImplBase {
906 static std::string read_symlink(std::string const & symlink_path) {
911 ssize_t len = ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
915 if (static_cast<size_t>(len) == path.size()) {
916 path.resize(path.size() * 2);
919 path.resize(static_cast<std::string::size_type>(len));
927 TraceResolverLinuxImpl(): _bfd_loaded(false) {}
930 void load_stacktrace(ST&) {}
932 ResolvedTrace resolve(ResolvedTrace trace) {
935 // trace.addr is a virtual address in memory pointing to some code.
936 // Let's try to find from which loaded object it comes from.
937 // The loaded object can be yourself btw.
938 if (!dladdr(trace.addr, &symbol_info)) {
939 return trace; // dat broken trace...
944 std::ifstream ifs("/proc/self/cmdline");
945 std::getline(ifs, argv0, '\0');
948 if(symbol_info.dli_fname == argv0) {
949 tmp = read_symlink("/proc/self/exe");
950 symbol_info.dli_fname = tmp.c_str();
953 // Now we get in symbol_info:
955 // pathname of the shared object that contains the address.
957 // where the object is loaded in memory.
959 // the name of the nearest symbol to trace.addr, we expect a
962 // the exact address corresponding to .dli_sname.
964 if (symbol_info.dli_sname) {
965 trace.object_function = demangle(symbol_info.dli_sname);
968 if (!symbol_info.dli_fname) {
972 trace.object_filename = symbol_info.dli_fname;
973 bfd_fileobject& fobj = load_object_with_bfd(symbol_info.dli_fname);
975 return trace; // sad, we couldn't load the object :(
979 find_sym_result* details_selected; // to be filled.
981 // trace.addr is the next instruction to be executed after returning
982 // from the nested stack frame. In C++ this usually relate to the next
983 // statement right after the function call that leaded to a new stack
984 // frame. This is not usually what you want to see when printing out a
986 find_sym_result details_call_site = find_symbol_details(fobj,
987 trace.addr, symbol_info.dli_fbase);
988 details_selected = &details_call_site;
990 #if BACKWARD_HAS_UNWIND == 0
991 // ...this is why we also try to resolve the symbol that is right
992 // before the return address. If we are lucky enough, we will get the
993 // line of the function that was called. But if the code is optimized,
994 // we might get something absolutely not related since the compiler
995 // can reschedule the return address with inline functions and
996 // tail-call optimisation (among other things that I don't even know
997 // or cannot even dream about with my tiny limited brain).
998 find_sym_result details_adjusted_call_site = find_symbol_details(fobj,
999 (void*) (uintptr_t(trace.addr) - 1),
1000 symbol_info.dli_fbase);
1002 // In debug mode, we should always get the right thing(TM).
1003 if (details_call_site.found && details_adjusted_call_site.found) {
1004 // Ok, we assume that details_adjusted_call_site is a better estimation.
1005 details_selected = &details_adjusted_call_site;
1006 trace.addr = (void*) (uintptr_t(trace.addr) - 1);
1009 if (details_selected == &details_call_site && details_call_site.found) {
1010 // we have to re-resolve the symbol in order to reset some
1011 // internal state in BFD... so we can call backtrace_inliners
1013 details_call_site = find_symbol_details(fobj, trace.addr,
1014 symbol_info.dli_fbase);
1016 #endif // BACKWARD_HAS_UNWIND
1018 if (details_selected->found) {
1019 if (details_selected->filename) {
1020 trace.source.filename = details_selected->filename;
1022 trace.source.line = details_selected->line;
1024 if (details_selected->funcname) {
1025 // this time we get the name of the function where the code is
1026 // located, instead of the function were the address is
1027 // located. In short, if the code was inlined, we get the
1028 // function correspoding to the code. Else we already got in
1030 trace.source.function = demangle(details_selected->funcname);
1032 if (!symbol_info.dli_sname) {
1033 // for the case dladdr failed to find the symbol name of
1034 // the function, we might as well try to put something
1036 trace.object_function = trace.source.function;
1040 // Maybe the source of the trace got inlined inside the function
1041 // (trace.source.function). Let's see if we can get all the inlined
1042 // calls along the way up to the initial call site.
1043 trace.inliners = backtrace_inliners(fobj, *details_selected);
1046 if (trace.inliners.size() == 0) {
1047 // Maybe the trace was not inlined... or maybe it was and we
1048 // are lacking the debug information. Let's try to make the
1049 // world better and see if we can get the line number of the
1050 // function (trace.source.function) now.
1052 // We will get the location of where the function start (to be
1053 // exact: the first instruction that really start the
1054 // function), not where the name of the function is defined.
1055 // This can be quite far away from the name of the function
1058 // If the source of the function is the same as the source of
1059 // the trace, we cannot say if the trace was really inlined or
1060 // not. However, if the filename of the source is different
1061 // between the function and the trace... we can declare it as
1062 // an inliner. This is not 100% accurate, but better than
1065 if (symbol_info.dli_saddr) {
1066 find_sym_result details = find_symbol_details(fobj,
1067 symbol_info.dli_saddr,
1068 symbol_info.dli_fbase);
1070 if (details.found) {
1071 ResolvedTrace::SourceLoc diy_inliner;
1072 diy_inliner.line = details.line;
1073 if (details.filename) {
1074 diy_inliner.filename = details.filename;
1076 if (details.funcname) {
1077 diy_inliner.function = demangle(details.funcname);
1079 diy_inliner.function = trace.source.function;
1081 if (diy_inliner != trace.source) {
1082 trace.inliners.push_back(diy_inliner);
1096 typedef details::handle<bfd*,
1097 details::deleter<bfd_boolean, bfd*, &bfd_close>
1100 typedef details::handle<asymbol**> bfd_symtab_t;
1103 struct bfd_fileobject {
1104 bfd_handle_t handle;
1106 bfd_symtab_t symtab;
1107 bfd_symtab_t dynamic_symtab;
1110 typedef details::hashtable<std::string, bfd_fileobject>::type
1112 fobj_bfd_map_t _fobj_bfd_map;
1114 bfd_fileobject& load_object_with_bfd(const std::string& filename_object) {
1115 using namespace details;
1118 using namespace details;
1123 fobj_bfd_map_t::iterator it =
1124 _fobj_bfd_map.find(filename_object);
1125 if (it != _fobj_bfd_map.end()) {
1129 // this new object is empty for now.
1130 bfd_fileobject& r = _fobj_bfd_map[filename_object];
1132 // we do the work temporary in this one;
1133 bfd_handle_t bfd_handle;
1135 int fd = open(filename_object.c_str(), O_RDONLY);
1137 bfd_fdopenr(filename_object.c_str(), "default", fd)
1144 if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
1145 return r; // not an object? You lose.
1148 if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
1149 return r; // that's what happen when you forget to compile in debug.
1152 ssize_t symtab_storage_size =
1153 bfd_get_symtab_upper_bound(bfd_handle.get());
1155 ssize_t dyn_symtab_storage_size =
1156 bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
1158 if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
1159 return r; // weird, is the file is corrupted?
1162 bfd_symtab_t symtab, dynamic_symtab;
1163 ssize_t symcount = 0, dyn_symcount = 0;
1165 if (symtab_storage_size > 0) {
1167 static_cast<bfd_symbol**>(malloc(static_cast<size_t>(symtab_storage_size)))
1169 symcount = bfd_canonicalize_symtab(
1170 bfd_handle.get(), symtab.get()
1174 if (dyn_symtab_storage_size > 0) {
1175 dynamic_symtab.reset(
1176 static_cast<bfd_symbol**>(malloc(static_cast<size_t>(dyn_symtab_storage_size)))
1178 dyn_symcount = bfd_canonicalize_dynamic_symtab(
1179 bfd_handle.get(), dynamic_symtab.get()
1184 if (symcount <= 0 && dyn_symcount <= 0) {
1185 return r; // damned, that's a stripped file that you got there!
1188 r.handle = move(bfd_handle);
1189 r.symtab = move(symtab);
1190 r.dynamic_symtab = move(dynamic_symtab);
1194 struct find_sym_result {
1196 const char* filename;
1197 const char* funcname;
1201 struct find_sym_context {
1202 TraceResolverLinuxImpl* self;
1203 bfd_fileobject* fobj;
1206 find_sym_result result;
1209 find_sym_result find_symbol_details(bfd_fileobject& fobj, void* addr,
1211 find_sym_context context;
1212 context.self = this;
1213 context.fobj = &fobj;
1214 context.addr = addr;
1215 context.base_addr = base_addr;
1216 context.result.found = false;
1217 bfd_map_over_sections(fobj.handle.get(), &find_in_section_trampoline,
1218 static_cast<void*>(&context));
1219 return context.result;
1222 static void find_in_section_trampoline(bfd*, asection* section,
1224 find_sym_context* context = static_cast<find_sym_context*>(data);
1225 context->self->find_in_section(
1226 reinterpret_cast<bfd_vma>(context->addr),
1227 reinterpret_cast<bfd_vma>(context->base_addr),
1229 section, context->result
1233 void find_in_section(bfd_vma addr, bfd_vma base_addr,
1234 bfd_fileobject& fobj, asection* section, find_sym_result& result)
1236 if (result.found) return;
1238 if ((bfd_get_section_flags(fobj.handle.get(), section)
1240 return; // a debug section is never loaded automatically.
1242 bfd_vma sec_addr = bfd_get_section_vma(fobj.handle.get(), section);
1243 bfd_size_type size = bfd_get_section_size(section);
1245 // are we in the boundaries of the section?
1246 if (addr < sec_addr || addr >= sec_addr + size) {
1247 addr -= base_addr; // oups, a relocated object, lets try again...
1248 if (addr < sec_addr || addr >= sec_addr + size) {
1253 #pragma clang diagnostic push
1254 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1255 if (!result.found && fobj.symtab) {
1256 result.found = bfd_find_nearest_line(fobj.handle.get(), section,
1257 fobj.symtab.get(), addr - sec_addr, &result.filename,
1258 &result.funcname, &result.line);
1261 if (!result.found && fobj.dynamic_symtab) {
1262 result.found = bfd_find_nearest_line(fobj.handle.get(), section,
1263 fobj.dynamic_symtab.get(), addr - sec_addr,
1264 &result.filename, &result.funcname, &result.line);
1266 #pragma clang diagnostic pop
1270 ResolvedTrace::source_locs_t backtrace_inliners(bfd_fileobject& fobj,
1271 find_sym_result previous_result) {
1272 // This function can be called ONLY after a SUCCESSFUL call to
1273 // find_symbol_details. The state is global to the bfd_handle.
1274 ResolvedTrace::source_locs_t results;
1275 while (previous_result.found) {
1276 find_sym_result result;
1277 result.found = bfd_find_inliner_info(fobj.handle.get(),
1278 &result.filename, &result.funcname, &result.line);
1280 if (result.found) /* and not (
1281 cstrings_eq(previous_result.filename, result.filename)
1282 and cstrings_eq(previous_result.funcname, result.funcname)
1283 and result.line == previous_result.line
1285 ResolvedTrace::SourceLoc src_loc;
1286 src_loc.line = result.line;
1287 if (result.filename) {
1288 src_loc.filename = result.filename;
1290 if (result.funcname) {
1291 src_loc.function = demangle(result.funcname);
1293 results.push_back(src_loc);
1295 previous_result = result;
1300 bool cstrings_eq(const char* a, const char* b) {
1304 return strcmp(a, b) == 0;
1308 #endif // BACKWARD_HAS_BFD == 1
1310 #if BACKWARD_HAS_DW == 1
1313 class TraceResolverLinuxImpl<trace_resolver_tag::libdw>:
1314 public TraceResolverImplBase {
1316 TraceResolverLinuxImpl(): _dwfl_handle_initialized(false) {}
1319 void load_stacktrace(ST&) {}
1321 ResolvedTrace resolve(ResolvedTrace trace) {
1322 using namespace details;
1324 Dwarf_Addr trace_addr = (Dwarf_Addr) trace.addr;
1326 if (!_dwfl_handle_initialized) {
1327 // initialize dwfl...
1328 _dwfl_cb.reset(new Dwfl_Callbacks);
1329 _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
1330 _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
1331 _dwfl_cb->debuginfo_path = 0;
1333 _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
1334 _dwfl_handle_initialized = true;
1336 if (!_dwfl_handle) {
1340 // ...from the current process.
1341 dwfl_report_begin(_dwfl_handle.get());
1342 int r = dwfl_linux_proc_report (_dwfl_handle.get(), getpid());
1343 dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
1349 if (!_dwfl_handle) {
1353 // find the module (binary object) that contains the trace's address.
1354 // This is not using any debug information, but the addresses ranges of
1355 // all the currently loaded binary object.
1356 Dwfl_Module* mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
1358 // now that we found it, lets get the name of it, this will be the
1359 // full path to the running binary or one of the loaded library.
1360 const char* module_name = dwfl_module_info (mod,
1361 0, 0, 0, 0, 0, 0, 0);
1363 trace.object_filename = module_name;
1365 // We also look after the name of the symbol, equal or before this
1366 // address. This is found by walking the symtab. We should get the
1367 // symbol corresponding to the function (mangled) containing the
1368 // address. If the code corresponding to the address was inlined,
1369 // this is the name of the out-most inliner function.
1370 const char* sym_name = dwfl_module_addrname(mod, trace_addr);
1372 trace.object_function = demangle(sym_name);
1376 // now let's get serious, and find out the source location (file and
1377 // line number) of the address.
1379 // This function will look in .debug_aranges for the address and map it
1380 // to the location of the compilation unit DIE in .debug_info and
1382 Dwarf_Addr mod_bias = 0;
1383 Dwarf_Die* cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias);
1387 // Sadly clang does not generate the section .debug_aranges, thus
1388 // dwfl_module_addrdie will fail early. Clang doesn't either set
1389 // the lowpc/highpc/range info for every compilation unit.
1391 // So in order to save the world:
1392 // for every compilation unit, we will iterate over every single
1393 // DIEs. Normally functions should have a lowpc/highpc/range, which
1394 // we will use to infer the compilation unit.
1396 // note that this is probably badly inefficient.
1397 while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) {
1399 Dwarf_Die* fundie = find_fundie_by_pc(cudie,
1400 trace_addr - mod_bias, &die_mem);
1408 //#define BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1409 #ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1411 // If it's still not enough, lets dive deeper in the shit, and try
1412 // to save the world again: for every compilation unit, we will
1413 // load the corresponding .debug_line section, and see if we can
1414 // find our address in it.
1416 Dwarf_Addr cfi_bias;
1417 Dwarf_CFI* cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias);
1420 while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) {
1421 if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
1423 // ...but if we get a match, it might be a false positive
1424 // because our (address - bias) might as well be valid in a
1425 // different compilation unit. So we throw our last card on
1426 // the table and lookup for the address into the .eh_frame
1429 handle<Dwarf_Frame*> frame;
1430 dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
1440 return trace; // this time we lost the game :/
1443 // Now that we have a compilation unit DIE, this function will be able
1444 // to load the corresponding section in .debug_line (if not already
1445 // loaded) and hopefully find the source location mapped to our
1447 Dwarf_Line* srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
1450 const char* srcfile = dwarf_linesrc(srcloc, 0, 0);
1452 trace.source.filename = srcfile;
1454 int line = 0, col = 0;
1455 dwarf_lineno(srcloc, &line);
1456 dwarf_linecol(srcloc, &col);
1457 trace.source.line = line;
1458 trace.source.col = col;
1461 deep_first_search_by_pc(cudie, trace_addr - mod_bias,
1462 inliners_search_cb(trace));
1463 if (trace.source.function.size() == 0) {
1465 trace.source.function = trace.object_function;
1472 typedef details::handle<Dwfl*, details::deleter<void, Dwfl*, &dwfl_end> >
1474 details::handle<Dwfl_Callbacks*, details::default_delete<Dwfl_Callbacks*> >
1476 dwfl_handle_t _dwfl_handle;
1477 bool _dwfl_handle_initialized;
1479 // defined here because in C++98, template function cannot take locally
1480 // defined types... grrr.
1481 struct inliners_search_cb {
1482 void operator()(Dwarf_Die* die) {
1483 switch (dwarf_tag(die)) {
1485 case DW_TAG_subprogram:
1486 if ((name = dwarf_diename(die))) {
1487 trace.source.function = name;
1491 case DW_TAG_inlined_subroutine:
1492 ResolvedTrace::SourceLoc sloc;
1493 Dwarf_Attribute attr_mem;
1495 if ((name = dwarf_diename(die))) {
1496 sloc.function = name;
1498 if ((name = die_call_file(die))) {
1499 sloc.filename = name;
1502 Dwarf_Word line = 0, col = 0;
1503 dwarf_formudata(dwarf_attr(die, DW_AT_call_line,
1505 dwarf_formudata(dwarf_attr(die, DW_AT_call_column,
1507 sloc.line = (unsigned)line;
1508 sloc.col = (unsigned)col;
1510 trace.inliners.push_back(sloc);
1514 ResolvedTrace& trace;
1515 inliners_search_cb(ResolvedTrace& t): trace(t) {}
1519 static bool die_has_pc(Dwarf_Die* die, Dwarf_Addr pc) {
1520 Dwarf_Addr low, high;
1523 if (dwarf_hasattr(die, DW_AT_low_pc) &&
1524 dwarf_hasattr(die, DW_AT_high_pc)) {
1525 if (dwarf_lowpc(die, &low) != 0) {
1528 if (dwarf_highpc(die, &high) != 0) {
1529 Dwarf_Attribute attr_mem;
1530 Dwarf_Attribute* attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
1532 if (dwarf_formudata(attr, &value) != 0) {
1537 return pc >= low && pc < high;
1540 // non-continuous range.
1542 ptrdiff_t offset = 0;
1543 while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
1544 if (pc >= low && pc < high) {
1551 static Dwarf_Die* find_fundie_by_pc(Dwarf_Die* parent_die, Dwarf_Addr pc,
1552 Dwarf_Die* result) {
1553 if (dwarf_child(parent_die, result) != 0) {
1557 Dwarf_Die* die = result;
1559 switch (dwarf_tag(die)) {
1560 case DW_TAG_subprogram:
1561 case DW_TAG_inlined_subroutine:
1562 if (die_has_pc(die, pc)) {
1566 bool declaration = false;
1567 Dwarf_Attribute attr_mem;
1568 dwarf_formflag(dwarf_attr(die, DW_AT_declaration,
1569 &attr_mem), &declaration);
1571 // let's be curious and look deeper in the tree,
1572 // function are not necessarily at the first level, but
1573 // might be nested inside a namespace, structure etc.
1575 Dwarf_Die* indie = find_fundie_by_pc(die, pc, &die_mem);
1581 } while (dwarf_siblingof(die, result) == 0);
1585 template <typename CB>
1586 static bool deep_first_search_by_pc(Dwarf_Die* parent_die,
1587 Dwarf_Addr pc, CB cb) {
1589 if (dwarf_child(parent_die, &die_mem) != 0) {
1593 bool branch_has_pc = false;
1594 Dwarf_Die* die = &die_mem;
1596 bool declaration = false;
1597 Dwarf_Attribute attr_mem;
1598 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem), &declaration);
1600 // let's be curious and look deeper in the tree, function are
1601 // not necessarily at the first level, but might be nested
1602 // inside a namespace, structure, a function, an inlined
1604 branch_has_pc = deep_first_search_by_pc(die, pc, cb);
1606 if (!branch_has_pc) {
1607 branch_has_pc = die_has_pc(die, pc);
1609 if (branch_has_pc) {
1612 } while (dwarf_siblingof(die, &die_mem) == 0);
1613 return branch_has_pc;
1616 static const char* die_call_file(Dwarf_Die *die) {
1617 Dwarf_Attribute attr_mem;
1618 Dwarf_Sword file_idx = 0;
1620 dwarf_formsdata(dwarf_attr(die, DW_AT_call_file, &attr_mem),
1623 if (file_idx == 0) {
1628 Dwarf_Die* cudie = dwarf_diecu(die, &die_mem, 0, 0);
1633 Dwarf_Files* files = 0;
1635 dwarf_getsrcfiles(cudie, &files, &nfiles);
1640 return dwarf_filesrc(files, file_idx, 0, 0);
1644 #endif // BACKWARD_HAS_DW == 1
1646 #if BACKWARD_HAS_DWARF == 1
1649 class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>:
1650 public TraceResolverImplBase {
1651 static std::string read_symlink(std::string const & symlink_path) {
1656 ssize_t len = ::readlink(symlink_path.c_str(),
1657 &*path.begin(), path.size());
1661 if ((size_t)len == path.size()) {
1662 path.resize(path.size() * 2);
1673 TraceResolverLinuxImpl(): _dwarf_loaded(false) {}
1676 void load_stacktrace(ST&) {}
1678 ResolvedTrace resolve(ResolvedTrace trace) {
1679 // trace.addr is a virtual address in memory pointing to some code.
1680 // Let's try to find from which loaded object it comes from.
1681 // The loaded object can be yourself btw.
1683 Dl_info symbol_info;
1684 int dladdr_result = 0;
1687 // We request the link map so we can get information about offsets
1688 dladdr_result = dladdr1(trace.addr, &symbol_info,
1689 reinterpret_cast<void**>(&link_map), RTLD_DL_LINKMAP);
1691 // Android doesn't have dladdr1. Don't use the linker map.
1692 dladdr_result = dladdr(trace.addr, &symbol_info);
1694 if (!dladdr_result) {
1695 return trace; // dat broken trace...
1700 std::ifstream ifs("/proc/self/cmdline");
1701 std::getline(ifs, argv0, '\0');
1704 if(symbol_info.dli_fname == argv0) {
1705 tmp = read_symlink("/proc/self/exe");
1706 symbol_info.dli_fname = tmp.c_str();
1709 // Now we get in symbol_info:
1711 // pathname of the shared object that contains the address.
1713 // where the object is loaded in memory.
1715 // the name of the nearest symbol to trace.addr, we expect a
1718 // the exact address corresponding to .dli_sname.
1722 // difference between the address in the ELF file and the address
1725 // absolute pathname where the object was found
1727 if (symbol_info.dli_sname) {
1728 trace.object_function = demangle(symbol_info.dli_sname);
1731 if (!symbol_info.dli_fname) {
1735 trace.object_filename = symbol_info.dli_fname;
1736 dwarf_fileobject& fobj = load_object_with_dwarf(symbol_info.dli_fname);
1737 if (!fobj.dwarf_handle) {
1738 return trace; // sad, we couldn't load the object :(
1742 // Convert the address to a module relative one by looking at
1743 // the module's loading address in the link map
1744 Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr) -
1745 reinterpret_cast<uintptr_t>(link_map->l_addr);
1747 Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr);
1750 if (trace.object_function.empty()) {
1751 symbol_cache_t::iterator it =
1752 fobj.symbol_cache.lower_bound(address);
1754 if (it != fobj.symbol_cache.end()) {
1755 if (it->first != address) {
1756 if (it != fobj.symbol_cache.begin()) {
1760 trace.object_function = demangle(it->second.c_str());
1764 // Get the Compilation Unit DIE for the address
1765 Dwarf_Die die = find_die(fobj, address);
1768 return trace; // this time we lost the game :/
1771 // libdwarf doesn't give us direct access to its objects, it always
1772 // allocates a copy for the caller. We keep that copy alive in a cache
1773 // and we deallocate it later when it's no longer required.
1774 die_cache_entry& die_object = get_die_cache(fobj, die);
1775 if (die_object.isEmpty())
1776 return trace; // We have no line section for this DIE
1778 die_linemap_t::iterator it =
1779 die_object.line_section.lower_bound(address);
1781 if (it != die_object.line_section.end()) {
1782 if (it->first != address) {
1783 if (it == die_object.line_section.begin()) {
1784 // If we are on the first item of the line section
1785 // but the address does not match it means that
1786 // the address is below the range of the DIE. Give up.
1793 return trace; // We didn't find the address.
1796 // Get the Dwarf_Line that the address points to and call libdwarf
1797 // to get source file, line and column info.
1798 Dwarf_Line line = die_object.line_buffer[it->second];
1799 Dwarf_Error error = DW_DLE_NE;
1802 if (dwarf_linesrc(line, &filename, &error)
1804 trace.source.filename = std::string(filename);
1805 dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
1808 Dwarf_Unsigned number = 0;
1809 if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
1810 trace.source.line = number;
1812 trace.source.line = 0;
1815 if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
1816 trace.source.col = number;
1818 trace.source.col = 0;
1821 std::vector<std::string> namespace_stack;
1822 deep_first_search_by_pc(fobj, die, address, namespace_stack,
1823 inliners_search_cb(trace, fobj, die));
1825 dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
1831 static int close_dwarf(Dwarf_Debug dwarf) {
1832 return dwarf_finish(dwarf, NULL);
1838 typedef details::handle<int,
1839 details::deleter<int, int, &::close>
1842 typedef details::handle<Elf*,
1843 details::deleter<int, Elf*, &elf_end>
1846 typedef details::handle<Dwarf_Debug,
1847 details::deleter<int, Dwarf_Debug, &close_dwarf>
1850 typedef std::map<Dwarf_Addr, int> die_linemap_t;
1852 typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
1854 struct die_cache_entry {
1855 die_specmap_t spec_section;
1856 die_linemap_t line_section;
1857 Dwarf_Line* line_buffer;
1858 Dwarf_Signed line_count;
1859 Dwarf_Line_Context line_context;
1861 inline bool isEmpty() {
1862 return line_buffer == NULL ||
1864 line_context == NULL ||
1865 line_section.empty();
1869 line_buffer(0), line_count(0), line_context(0) {}
1874 dwarf_srclines_dealloc_b(line_context);
1879 typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
1881 typedef std::map<uintptr_t, std::string> symbol_cache_t;
1883 struct dwarf_fileobject {
1884 dwarf_file_t file_handle;
1885 dwarf_elf_t elf_handle;
1886 dwarf_handle_t dwarf_handle;
1887 symbol_cache_t symbol_cache;
1890 die_cache_t die_cache;
1891 die_cache_entry* current_cu;
1894 typedef details::hashtable<std::string, dwarf_fileobject>::type
1896 fobj_dwarf_map_t _fobj_dwarf_map;
1898 static bool cstrings_eq(const char* a, const char* b) {
1902 return strcmp(a, b) == 0;
1905 dwarf_fileobject& load_object_with_dwarf(
1906 const std::string& filename_object) {
1908 if (!_dwarf_loaded) {
1909 // Set the ELF library operating version
1910 // If that fails there's nothing we can do
1911 _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
1914 fobj_dwarf_map_t::iterator it =
1915 _fobj_dwarf_map.find(filename_object);
1916 if (it != _fobj_dwarf_map.end()) {
1920 // this new object is empty for now
1921 dwarf_fileobject& r = _fobj_dwarf_map[filename_object];
1923 dwarf_file_t file_handle;
1924 file_handle.reset(open(filename_object.c_str(), O_RDONLY));
1925 if (file_handle < 0) {
1929 // Try to get an ELF handle. We need to read the ELF sections
1930 // because we want to see if there is a .gnu_debuglink section
1931 // that points to a split debug file
1932 dwarf_elf_t elf_handle;
1933 elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
1938 const char* e_ident = elf_getident(elf_handle.get(), 0);
1943 // Get the number of sections
1944 // We use the new APIs as elf_getshnum is deprecated
1946 if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
1950 // Get the index to the string section
1951 size_t shdrstrndx = 0;
1952 if (elf_getshdrstrndx (elf_handle.get(), &shdrstrndx) == -1) {
1956 std::string debuglink;
1957 // Iterate through the ELF sections to try to get a gnu_debuglink
1958 // note and also to cache the symbol table.
1959 // We go the preprocessor way to avoid having to create templated
1960 // classes or using gelf (which might throw a compiler error if 64 bit
1962 #define ELF_GET_DATA(ARCH) \
1963 Elf_Scn *elf_section = 0; \
1964 Elf_Data *elf_data = 0; \
1965 Elf##ARCH##_Shdr* section_header = 0; \
1966 Elf_Scn *symbol_section = 0; \
1967 size_t symbol_count = 0; \
1968 size_t symbol_strings = 0; \
1969 Elf##ARCH##_Sym *symbol = 0; \
1970 const char* section_name = 0; \
1972 while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) \
1974 section_header = elf##ARCH##_getshdr(elf_section); \
1975 if (section_header == NULL) { \
1979 if ((section_name = elf_strptr( \
1980 elf_handle.get(), shdrstrndx, \
1981 section_header->sh_name)) == NULL) { \
1985 if (cstrings_eq(section_name, ".gnu_debuglink")) { \
1986 elf_data = elf_getdata(elf_section, NULL); \
1987 if (elf_data && elf_data->d_size > 0) { \
1988 debuglink = std::string( \
1989 reinterpret_cast<const char*>(elf_data->d_buf)); \
1993 switch(section_header->sh_type) { \
1995 symbol_section = elf_section; \
1996 symbol_count = section_header->sh_size / \
1997 section_header->sh_entsize; \
1998 symbol_strings = section_header->sh_link; \
2001 /* We use .dynsyms as a last resort, we prefer .symtab */ \
2003 if (!symbol_section) { \
2004 symbol_section = elf_section; \
2005 symbol_count = section_header->sh_size / \
2006 section_header->sh_entsize; \
2007 symbol_strings = section_header->sh_link; \
2013 if (symbol_section && symbol_count && symbol_strings) { \
2014 elf_data = elf_getdata(symbol_section, NULL); \
2015 symbol = reinterpret_cast<Elf##ARCH##_Sym*>(elf_data->d_buf); \
2016 for (size_t i = 0; i < symbol_count; ++i) { \
2017 int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
2018 if (type == STT_FUNC && symbol->st_value > 0) { \
2019 r.symbol_cache[symbol->st_value] = std::string( \
2020 elf_strptr(elf_handle.get(), \
2021 symbol_strings, symbol->st_name)); \
2028 if (e_ident[EI_CLASS] == ELFCLASS32) {
2030 } else if (e_ident[EI_CLASS] == ELFCLASS64) {
2031 // libelf might have been built without 64 bit support
2037 if (!debuglink.empty()) {
2038 // We have a debuglink section! Open an elf instance on that
2039 // file instead. If we can't open the file, then return
2040 // the elf handle we had already opened.
2041 dwarf_file_t debuglink_file;
2042 debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
2043 if (debuglink_file.get() > 0) {
2044 dwarf_elf_t debuglink_elf;
2045 debuglink_elf.reset(
2046 elf_begin(debuglink_file.get(),ELF_C_READ, NULL)
2049 // If we have a valid elf handle, return the new elf handle
2050 // and file handle and discard the original ones
2051 if (debuglink_elf) {
2052 elf_handle = move(debuglink_elf);
2053 file_handle = move(debuglink_file);
2058 // Ok, we have a valid ELF handle, let's try to get debug symbols
2059 Dwarf_Debug dwarf_debug;
2060 Dwarf_Error error = DW_DLE_NE;
2061 dwarf_handle_t dwarf_handle;
2063 int dwarf_result = dwarf_elf_init(elf_handle.get(),
2064 DW_DLC_READ, NULL, NULL, &dwarf_debug, &error);
2066 // We don't do any special handling for DW_DLV_NO_ENTRY specially.
2067 // If we get an error, or the file doesn't have debug information
2069 if (dwarf_result != DW_DLV_OK) {
2073 dwarf_handle.reset(dwarf_debug);
2075 r.file_handle = move(file_handle);
2076 r.elf_handle = move(elf_handle);
2077 r.dwarf_handle = move(dwarf_handle);
2082 die_cache_entry& get_die_cache(dwarf_fileobject& fobj, Dwarf_Die die)
2084 Dwarf_Error error = DW_DLE_NE;
2086 // Get the die offset, we use it as the cache key
2087 Dwarf_Off die_offset;
2088 if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
2092 die_cache_t::iterator it = fobj.die_cache.find(die_offset);
2094 if (it != fobj.die_cache.end()) {
2095 fobj.current_cu = &it->second;
2099 die_cache_entry& de = fobj.die_cache[die_offset];
2100 fobj.current_cu = &de;
2102 Dwarf_Addr line_addr;
2103 Dwarf_Small table_count;
2105 // The addresses in the line section are not fully sorted (they might
2106 // be sorted by block of code belonging to the same file), which makes
2107 // it necessary to do so before searching is possible.
2109 // As libdwarf allocates a copy of everything, let's get the contents
2110 // of the line section and keep it around. We also create a map of
2111 // program counter to line table indices so we can search by address
2112 // and get the line buffer index.
2114 // To make things more difficult, the same address can span more than
2115 // one line, so we need to keep the index pointing to the first line
2116 // by using insert instead of the map's [ operator.
2118 // Get the line context for the DIE
2119 if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error)
2121 // Get the source lines for this line context, to be deallocated
2123 if (dwarf_srclines_from_linecontext(
2124 de.line_context, &de.line_buffer, &de.line_count, &error)
2127 // Add all the addresses to our map
2128 for (int i = 0; i < de.line_count; i++) {
2129 if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error)
2133 de.line_section.insert(
2134 std::pair<Dwarf_Addr, int>(line_addr, i));
2139 // For each CU, cache the function DIEs that contain the
2140 // DW_AT_specification attribute. When building with -g3 the function
2141 // DIEs are separated in declaration and specification, with the
2142 // declaration containing only the name and parameters and the
2143 // specification the low/high pc and other compiler attributes.
2145 // We cache those specifications so we don't skip over the declarations,
2146 // because they have no pc, and we can do namespace resolution for
2147 // DWARF function names.
2148 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2149 Dwarf_Die current_die = 0;
2150 if (dwarf_child(die, ¤t_die, &error) == DW_DLV_OK) {
2152 Dwarf_Die sibling_die = 0;
2154 Dwarf_Half tag_value;
2155 dwarf_tag(current_die, &tag_value, &error);
2157 if (tag_value == DW_TAG_subprogram ||
2158 tag_value == DW_TAG_inlined_subroutine) {
2160 Dwarf_Bool has_attr = 0;
2161 if (dwarf_hasattr(current_die, DW_AT_specification,
2162 &has_attr, &error) == DW_DLV_OK) {
2164 Dwarf_Attribute attr_mem;
2165 if (dwarf_attr(current_die, DW_AT_specification,
2166 &attr_mem, &error) == DW_DLV_OK) {
2167 Dwarf_Off spec_offset = 0;
2168 if (dwarf_formref(attr_mem,
2169 &spec_offset, &error) == DW_DLV_OK) {
2170 Dwarf_Off spec_die_offset;
2171 if (dwarf_dieoffset(current_die,
2172 &spec_die_offset, &error)
2174 de.spec_section[spec_offset] =
2179 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2184 int result = dwarf_siblingof(
2185 dwarf, current_die, &sibling_die, &error);
2186 if (result == DW_DLV_ERROR) {
2188 } else if (result == DW_DLV_NO_ENTRY) {
2192 if (current_die != die) {
2193 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2197 current_die = sibling_die;
2203 static Dwarf_Die get_referenced_die(
2204 Dwarf_Debug dwarf, Dwarf_Die die, Dwarf_Half attr, bool global) {
2205 Dwarf_Error error = DW_DLE_NE;
2206 Dwarf_Attribute attr_mem;
2208 Dwarf_Die found_die = NULL;
2209 if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
2213 result = dwarf_global_formref(attr_mem, &offset, &error);
2215 result = dwarf_formref(attr_mem, &offset, &error);
2218 if (result == DW_DLV_OK) {
2219 if (dwarf_offdie(dwarf, offset, &found_die, &error)
2224 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2229 static std::string get_referenced_die_name(
2230 Dwarf_Debug dwarf, Dwarf_Die die, Dwarf_Half attr, bool global) {
2231 Dwarf_Error error = DW_DLE_NE;
2234 Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
2238 if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
2240 value = std::string(name);
2242 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2244 dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
2250 // Returns a spec DIE linked to the passed one. The caller should
2251 // deallocate the DIE
2252 static Dwarf_Die get_spec_die(dwarf_fileobject& fobj, Dwarf_Die die) {
2253 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2254 Dwarf_Error error = DW_DLE_NE;
2255 Dwarf_Off die_offset;
2256 if (fobj.current_cu && dwarf_die_CU_offset(die, &die_offset, &error)
2258 die_specmap_t::iterator it =
2259 fobj.current_cu->spec_section.find(die_offset);
2261 // If we have a DIE that completes the current one, check if
2262 // that one has the pc we are looking for
2263 if (it != fobj.current_cu->spec_section.end()) {
2264 Dwarf_Die spec_die = 0;
2265 if (dwarf_offdie(dwarf, it->second, &spec_die, &error)
2272 // Maybe we have an abstract origin DIE with the function information?
2273 return get_referenced_die(
2274 fobj.dwarf_handle.get(), die, DW_AT_abstract_origin, true);
2278 static bool die_has_pc(dwarf_fileobject& fobj, Dwarf_Die die, Dwarf_Addr pc)
2280 Dwarf_Addr low_pc = 0, high_pc = 0;
2281 Dwarf_Half high_pc_form = 0;
2282 Dwarf_Form_Class return_class;
2283 Dwarf_Error error = DW_DLE_NE;
2284 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2285 bool has_lowpc = false;
2286 bool has_highpc = false;
2287 bool has_ranges = false;
2289 if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
2290 // If we have a low_pc check if there is a high pc.
2291 // If we don't have a high pc this might mean we have a base
2292 // address for the ranges list or just an address.
2296 die, &high_pc, &high_pc_form, &return_class, &error)
2298 // We do have a high pc. In DWARF 4+ this is an offset from the
2299 // low pc, but in earlier versions it's an absolute address.
2302 // In DWARF 2/3 this would be a DW_FORM_CLASS_ADDRESS
2303 if (return_class == DW_FORM_CLASS_CONSTANT) {
2304 high_pc = low_pc + high_pc;
2307 // We have low and high pc, check if our address
2309 return pc >= low_pc && pc < high_pc;
2312 // Reset the low_pc, in case dwarf_lowpc failing set it to some
2317 // Check if DW_AT_ranges is present and search for the PC in the
2318 // returned ranges list. We always add the low_pc, as it not set it will
2319 // be 0, in case we had a DW_AT_low_pc and DW_AT_ranges pair
2320 bool result = false;
2322 Dwarf_Attribute attr;
2323 if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
2326 if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
2327 Dwarf_Ranges *ranges;
2328 Dwarf_Signed ranges_count = 0;
2329 Dwarf_Unsigned byte_count = 0;
2331 if (dwarf_get_ranges_a(dwarf, offset, die, &ranges,
2332 &ranges_count, &byte_count, &error) == DW_DLV_OK) {
2333 has_ranges = ranges_count != 0;
2334 for (int i = 0; i < ranges_count; i++) {
2335 if (ranges[i].dwr_addr1 != 0 &&
2336 pc >= ranges[i].dwr_addr1 + low_pc &&
2337 pc < ranges[i].dwr_addr2 + low_pc) {
2342 dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
2347 // Last attempt. We might have a single address set as low_pc.
2348 if (!result && low_pc != 0 && pc == low_pc) {
2352 // If we don't have lowpc, highpc and ranges maybe this DIE is a
2353 // declaration that relies on a DW_AT_specification DIE that happens
2354 // later. Use the specification cache we filled when we loaded this CU.
2355 if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
2356 Dwarf_Die spec_die = get_spec_die(fobj, die);
2358 result = die_has_pc(fobj, spec_die, pc);
2359 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2366 static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string& type) {
2367 Dwarf_Error error = DW_DLE_NE;
2369 Dwarf_Die child = 0;
2370 if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
2371 get_type(dwarf, child, type);
2375 type.insert(0, "::");
2376 dwarf_dealloc(dwarf, child, DW_DLA_DIE);
2380 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2381 type.insert(0, std::string(name));
2382 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2384 type.insert(0,"<unknown>");
2388 static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
2389 Dwarf_Error error = DW_DLE_NE;
2391 Dwarf_Sig8 signature;
2392 Dwarf_Bool has_attr = 0;
2393 if (dwarf_hasattr(die, DW_AT_signature,
2394 &has_attr, &error) == DW_DLV_OK) {
2396 Dwarf_Attribute attr_mem;
2397 if (dwarf_attr(die, DW_AT_signature,
2398 &attr_mem, &error) == DW_DLV_OK) {
2399 if (dwarf_formsig8(attr_mem, &signature, &error)
2401 return std::string("<no type signature>");
2404 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2408 Dwarf_Unsigned next_cu_header;
2409 Dwarf_Sig8 tu_signature;
2413 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature,
2414 0, &next_cu_header, 0, &error) == DW_DLV_OK) {
2416 if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
2417 Dwarf_Die type_cu_die = 0;
2418 if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error)
2420 Dwarf_Die child_die = 0;
2421 if (dwarf_child(type_cu_die, &child_die, &error)
2423 get_type(dwarf, child_die, result);
2424 found = !result.empty();
2425 dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
2427 dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
2433 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2434 &next_cu_header, 0, &error) == DW_DLV_OK) {
2435 // Reset the cu header state. Unfortunately, libdwarf's
2436 // next_cu_header API keeps its own iterator per Dwarf_Debug
2437 // that can't be reset. We need to keep fetching elements until
2441 // If we couldn't resolve the type just print out the signature
2442 std::ostringstream string_stream;
2443 string_stream << "<0x" <<
2444 std::hex << std::setfill('0');
2445 for (int i = 0; i < 8; ++i) {
2446 string_stream << std::setw(2) << std::hex
2447 << (int)(unsigned char)(signature.signature[i]);
2449 string_stream << ">";
2450 result = string_stream.str();
2455 struct type_context_t {
2463 is_const(false), is_typedef(false),
2464 has_type(false), has_name(false) {}
2467 // Types are resolved from right to left: we get the variable name first
2468 // and then all specifiers (like const or pointer) in a chain of DW_AT_type
2469 // DIEs. Call this function recursively until we get a complete type
2471 static void set_parameter_string(
2472 dwarf_fileobject& fobj, Dwarf_Die die, type_context_t &context) {
2474 Dwarf_Error error = DW_DLE_NE;
2476 // typedefs contain also the base type, so we skip it and only
2477 // print the typedef name
2478 if (!context.is_typedef) {
2479 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2480 if (!context.text.empty()) {
2481 context.text.insert(0, " ");
2483 context.text.insert(0, std::string(name));
2484 dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
2487 context.is_typedef = false;
2488 context.has_type = true;
2489 if (context.is_const) {
2490 context.text.insert(0, "const ");
2491 context.is_const = false;
2495 bool next_type_is_const = false;
2496 bool is_keyword = true;
2499 Dwarf_Bool has_attr = 0;
2500 if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
2502 case DW_TAG_structure_type:
2503 case DW_TAG_union_type:
2504 case DW_TAG_class_type:
2505 case DW_TAG_enumeration_type:
2506 context.has_type = true;
2507 if (dwarf_hasattr(die, DW_AT_signature,
2508 &has_attr, &error) == DW_DLV_OK) {
2509 // If we have a signature it means the type is defined
2510 // in .debug_types, so we need to load the DIE pointed
2511 // at by the signature and resolve it
2514 get_type_by_signature(fobj.dwarf_handle.get(), die);
2515 if (context.is_const)
2516 type.insert(0, "const ");
2518 if (!context.text.empty())
2519 context.text.insert(0, " ");
2520 context.text.insert(0, type);
2523 // Treat enums like typedefs, and skip printing its
2525 context.is_typedef = (tag == DW_TAG_enumeration_type);
2528 case DW_TAG_const_type:
2529 next_type_is_const = true;
2531 case DW_TAG_pointer_type:
2532 context.text.insert(0, "*");
2534 case DW_TAG_reference_type:
2535 context.text.insert(0, "&");
2537 case DW_TAG_restrict_type:
2538 context.text.insert(0, "restrict ");
2540 case DW_TAG_rvalue_reference_type:
2541 context.text.insert(0, "&&");
2543 case DW_TAG_volatile_type:
2544 context.text.insert(0, "volatile ");
2546 case DW_TAG_typedef:
2547 // Propagate the const-ness to the next type
2548 // as typedefs are linked to its base type
2549 next_type_is_const = context.is_const;
2550 context.is_typedef = true;
2551 context.has_type = true;
2553 case DW_TAG_base_type:
2554 context.has_type = true;
2556 case DW_TAG_formal_parameter:
2557 context.has_name = true;
2565 if (!is_keyword && context.is_const) {
2566 context.text.insert(0, "const ");
2569 context.is_const = next_type_is_const;
2571 Dwarf_Die ref = get_referenced_die(
2572 fobj.dwarf_handle.get(), die, DW_AT_type, true);
2574 set_parameter_string(fobj, ref, context);
2575 dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
2578 if (!context.has_type && context.has_name) {
2579 context.text.insert(0, "void ");
2580 context.has_type = true;
2584 // Resolve the function return type and parameters
2585 static void set_function_parameters(std::string& function_name,
2586 std::vector<std::string>& ns,
2587 dwarf_fileobject& fobj, Dwarf_Die die) {
2588 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2589 Dwarf_Error error = DW_DLE_NE;
2590 Dwarf_Die current_die = 0;
2591 std::string parameters;
2592 bool has_spec = true;
2593 // Check if we have a spec DIE. If we do we use it as it contains
2594 // more information, like parameter names.
2595 Dwarf_Die spec_die = get_spec_die(fobj, die);
2601 std::vector<std::string>::const_iterator it = ns.begin();
2602 std::string ns_name;
2603 for (it = ns.begin(); it < ns.end(); ++it) {
2604 ns_name.append(*it).append("::");
2607 if (!ns_name.empty()) {
2608 function_name.insert(0, ns_name);
2611 // See if we have a function return type. It can be either on the
2612 // current die or in its spec one (usually true for inlined functions)
2613 std::string return_type =
2614 get_referenced_die_name(dwarf, die, DW_AT_type, true);
2615 if (return_type.empty()) {
2617 get_referenced_die_name(dwarf, spec_die, DW_AT_type, true);
2619 if (!return_type.empty()) {
2620 return_type.append(" ");
2621 function_name.insert(0, return_type);
2624 if (dwarf_child(spec_die, ¤t_die, &error) == DW_DLV_OK) {
2626 Dwarf_Die sibling_die = 0;
2628 Dwarf_Half tag_value;
2629 dwarf_tag(current_die, &tag_value, &error);
2631 if (tag_value == DW_TAG_formal_parameter) {
2632 // Ignore artificial (ie, compiler generated) parameters
2633 bool is_artificial = false;
2634 Dwarf_Attribute attr_mem;
2636 current_die, DW_AT_artificial, &attr_mem, &error)
2638 Dwarf_Bool flag = 0;
2639 if (dwarf_formflag(attr_mem, &flag, &error)
2641 is_artificial = flag != 0;
2643 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2646 if (!is_artificial) {
2647 type_context_t context;
2648 set_parameter_string(fobj, current_die, context);
2650 if (parameters.empty()) {
2651 parameters.append("(");
2653 parameters.append(", ");
2655 parameters.append(context.text);
2659 int result = dwarf_siblingof(
2660 dwarf, current_die, &sibling_die, &error);
2661 if (result == DW_DLV_ERROR) {
2663 } else if (result == DW_DLV_NO_ENTRY) {
2667 if (current_die != die) {
2668 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2672 current_die = sibling_die;
2675 if (parameters.empty())
2677 parameters.append(")");
2679 // If we got a spec DIE we need to deallocate it
2681 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2683 function_name.append(parameters);
2686 // defined here because in C++98, template function cannot take locally
2687 // defined types... grrr.
2688 struct inliners_search_cb {
2689 void operator()(Dwarf_Die die, std::vector<std::string>& ns) {
2690 Dwarf_Error error = DW_DLE_NE;
2691 Dwarf_Half tag_value;
2692 Dwarf_Attribute attr_mem;
2693 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2695 dwarf_tag(die, &tag_value, &error);
2697 switch (tag_value) {
2699 case DW_TAG_subprogram:
2700 if (!trace.source.function.empty())
2702 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2703 trace.source.function = std::string(name);
2704 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2706 // We don't have a function name in this DIE.
2707 // Check if there is a referenced non-defining
2709 trace.source.function = get_referenced_die_name(
2710 dwarf, die, DW_AT_abstract_origin, true);
2711 if (trace.source.function.empty()) {
2712 trace.source.function = get_referenced_die_name(
2713 dwarf, die, DW_AT_specification, true);
2717 // Append the function parameters, if available
2718 set_function_parameters(
2719 trace.source.function, ns, fobj, die);
2721 // If the object function name is empty, it's possible that
2722 // there is no dynamic symbol table (maybe the executable
2723 // was stripped or not built with -rdynamic). See if we have
2724 // a DWARF linkage name to use instead. We try both
2725 // linkage_name and MIPS_linkage_name because the MIPS tag
2726 // was the unofficial one until it was adopted in DWARF4.
2727 // Old gcc versions generate MIPS_linkage_name
2728 if (trace.object_function.empty()) {
2729 details::demangler demangler;
2731 if (dwarf_attr(die, DW_AT_linkage_name,
2732 &attr_mem, &error) != DW_DLV_OK) {
2733 if (dwarf_attr(die, DW_AT_MIPS_linkage_name,
2734 &attr_mem, &error) != DW_DLV_OK) {
2740 if (dwarf_formstring(attr_mem, &linkage, &error)
2742 trace.object_function = demangler.demangle(linkage);
2743 dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
2745 dwarf_dealloc(dwarf, name, DW_DLA_ATTR);
2749 case DW_TAG_inlined_subroutine:
2750 ResolvedTrace::SourceLoc sloc;
2752 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2753 sloc.function = std::string(name);
2754 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2756 // We don't have a name for this inlined DIE, it could
2757 // be that there is an abstract origin instead.
2758 // Get the DW_AT_abstract_origin value, which is a
2759 // reference to the source DIE and try to get its name
2760 sloc.function = get_referenced_die_name(
2761 dwarf, die, DW_AT_abstract_origin, true);
2764 set_function_parameters(sloc.function, ns, fobj, die);
2766 std::string file = die_call_file(dwarf, die, cu_die);
2768 sloc.filename = file;
2770 Dwarf_Unsigned number = 0;
2771 if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error)
2773 if (dwarf_formudata(attr_mem, &number, &error)
2777 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2780 if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error)
2782 if (dwarf_formudata(attr_mem, &number, &error)
2786 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2789 trace.inliners.push_back(sloc);
2793 ResolvedTrace& trace;
2794 dwarf_fileobject& fobj;
2796 inliners_search_cb(ResolvedTrace& t, dwarf_fileobject& f, Dwarf_Die c)
2797 : trace(t), fobj(f), cu_die(c) {}
2800 static Dwarf_Die find_fundie_by_pc(dwarf_fileobject& fobj,
2801 Dwarf_Die parent_die, Dwarf_Addr pc, Dwarf_Die result) {
2802 Dwarf_Die current_die = 0;
2803 Dwarf_Error error = DW_DLE_NE;
2804 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2806 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
2811 Dwarf_Die sibling_die = 0;
2812 Dwarf_Half tag_value;
2813 dwarf_tag(current_die, &tag_value, &error);
2815 switch (tag_value) {
2816 case DW_TAG_subprogram:
2817 case DW_TAG_inlined_subroutine:
2818 if (die_has_pc(fobj, current_die, pc)) {
2822 bool declaration = false;
2823 Dwarf_Attribute attr_mem;
2824 if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error)
2826 Dwarf_Bool flag = 0;
2827 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
2828 declaration = flag != 0;
2830 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2834 // let's be curious and look deeper in the tree, functions are
2835 // not necessarily at the first level, but might be nested
2836 // inside a namespace, structure, a function, an inlined
2838 Dwarf_Die die_mem = 0;
2839 Dwarf_Die indie = find_fundie_by_pc(
2840 fobj, current_die, pc, die_mem);
2847 int res = dwarf_siblingof(
2848 dwarf, current_die, &sibling_die, &error);
2849 if (res == DW_DLV_ERROR) {
2851 } else if (res == DW_DLV_NO_ENTRY) {
2855 if (current_die != parent_die) {
2856 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2860 current_die = sibling_die;
2865 template <typename CB>
2866 static bool deep_first_search_by_pc(dwarf_fileobject& fobj,
2867 Dwarf_Die parent_die, Dwarf_Addr pc,
2868 std::vector<std::string>& ns, CB cb) {
2869 Dwarf_Die current_die = 0;
2870 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2871 Dwarf_Error error = DW_DLE_NE;
2873 if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
2877 bool branch_has_pc = false;
2878 bool has_namespace = false;
2880 Dwarf_Die sibling_die = 0;
2883 if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
2884 if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
2885 char* ns_name = NULL;
2886 if (dwarf_diename(current_die, &ns_name, &error)
2889 ns.push_back(std::string(ns_name));
2891 ns.push_back("<unknown>");
2893 dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
2895 ns.push_back("<unknown>");
2897 has_namespace = true;
2901 bool declaration = false;
2902 Dwarf_Attribute attr_mem;
2903 if (tag != DW_TAG_class_type &&
2904 dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error)
2906 Dwarf_Bool flag = 0;
2907 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
2908 declaration = flag != 0;
2910 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2914 // let's be curious and look deeper in the tree, function are
2915 // not necessarily at the first level, but might be nested
2916 // inside a namespace, structure, a function, an inlined
2918 branch_has_pc = deep_first_search_by_pc(
2919 fobj, current_die, pc, ns, cb);
2922 if (!branch_has_pc) {
2923 branch_has_pc = die_has_pc(fobj, current_die, pc);
2926 if (branch_has_pc) {
2927 cb(current_die, ns);
2930 int result = dwarf_siblingof(
2931 dwarf, current_die, &sibling_die, &error);
2932 if (result == DW_DLV_ERROR) {
2934 } else if (result == DW_DLV_NO_ENTRY) {
2938 if (current_die != parent_die) {
2939 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2943 if (has_namespace) {
2944 has_namespace = false;
2947 current_die = sibling_die;
2950 if (has_namespace) {
2953 return branch_has_pc;
2956 static std::string die_call_file(
2957 Dwarf_Debug dwarf, Dwarf_Die die, Dwarf_Die cu_die) {
2958 Dwarf_Attribute attr_mem;
2959 Dwarf_Error error = DW_DLE_NE;
2960 Dwarf_Signed file_index;
2964 if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
2965 if (dwarf_formsdata(attr_mem, &file_index, &error) != DW_DLV_OK) {
2968 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2970 if (file_index == 0) {
2974 char **srcfiles = 0;
2975 Dwarf_Signed file_count = 0;
2976 if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error)
2978 if (file_index <= file_count)
2979 file = std::string(srcfiles[file_index - 1]);
2981 // Deallocate all strings!
2982 for (int i = 0; i < file_count; ++i) {
2983 dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
2985 dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
2992 Dwarf_Die find_die(dwarf_fileobject& fobj, Dwarf_Addr addr)
2994 // Let's get to work! First see if we have a debug_aranges section so
2995 // we can speed up the search
2997 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2998 Dwarf_Error error = DW_DLE_NE;
2999 Dwarf_Arange *aranges;
3000 Dwarf_Signed arange_count;
3002 Dwarf_Die returnDie;
3004 if (dwarf_get_aranges(
3005 dwarf, &aranges, &arange_count, &error) != DW_DLV_OK) {
3010 // We have aranges. Get the one where our address is.
3011 Dwarf_Arange arange;
3012 if (dwarf_get_arange(
3013 aranges, arange_count, addr, &arange, &error)
3016 // We found our address. Get the compilation-unit DIE offset
3017 // represented by the given address range.
3018 Dwarf_Off cu_die_offset;
3019 if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error)
3021 // Get the DIE at the offset returned by the aranges search.
3022 // We set is_info to 1 to specify that the offset is from
3023 // the .debug_info section (and not .debug_types)
3024 int dwarf_result = dwarf_offdie_b(
3025 dwarf, cu_die_offset, 1, &returnDie, &error);
3027 found = dwarf_result == DW_DLV_OK;
3029 dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
3034 return returnDie; // The caller is responsible for freeing the die
3036 // The search for aranges failed. Try to find our address by scanning
3037 // all compilation units.
3038 Dwarf_Unsigned next_cu_header;
3042 while (!found && dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3043 &next_cu_header, 0, &error) == DW_DLV_OK) {
3046 dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
3048 if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
3049 if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK)
3050 && tag == DW_TAG_compile_unit) {
3051 if (die_has_pc(fobj, returnDie, addr)) {
3059 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3060 &next_cu_header, 0, &error) == DW_DLV_OK) {
3061 // Reset the cu header state. Libdwarf's next_cu_header API
3062 // keeps its own iterator per Dwarf_Debug that can't be reset.
3063 // We need to keep fetching elements until the end.
3070 // We couldn't find any compilation units with ranges or a high/low pc.
3071 // Try again by looking at all DIEs in all compilation units.
3073 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3074 &next_cu_header, 0, &error) == DW_DLV_OK) {
3075 if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
3076 Dwarf_Die die_mem = 0;
3077 Dwarf_Die resultDie = find_fundie_by_pc(
3078 fobj, cudie, addr, die_mem);
3088 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3089 &next_cu_header, 0, &error) == DW_DLV_OK) {
3090 // Reset the cu header state. Libdwarf's next_cu_header API
3091 // keeps its own iterator per Dwarf_Debug that can't be reset.
3092 // We need to keep fetching elements until the end.
3103 #endif // BACKWARD_HAS_DWARF == 1
3106 class TraceResolverImpl<system_tag::linux_tag>:
3107 public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
3109 #endif // BACKWARD_SYSTEM_LINUX
3111 #ifdef BACKWARD_SYSTEM_DARWIN
3113 template <typename STACKTRACE_TAG>
3114 class TraceResolverDarwinImpl;
3117 class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>:
3118 public TraceResolverImplBase {
3121 void load_stacktrace(ST& st) {
3122 using namespace details;
3123 if (st.size() == 0) {
3127 backtrace_symbols(st.begin(), st.size())
3131 ResolvedTrace resolve(ResolvedTrace trace) {
3133 // <n> <file> <addr> <mangled-name> + <offset>
3134 char* filename = _symbols[trace.idx];
3137 while(*filename && *filename != ' ') filename++;
3138 while(*filename == ' ') filename++;
3140 // find start of <mangled-name> from end (<file> may contain a space)
3141 char* p = filename + strlen(filename) - 1;
3142 // skip to start of " + <offset>"
3143 while(p > filename && *p != ' ') p--;
3144 while(p > filename && *p == ' ') p--;
3145 while(p > filename && *p != ' ') p--;
3146 while(p > filename && *p == ' ') p--;
3147 char *funcname_end = p + 1;
3149 // skip to start of "<manged-name>"
3150 while(p > filename && *p != ' ') p--;
3151 char *funcname = p + 1;
3153 // skip to start of " <addr> "
3154 while(p > filename && *p == ' ') p--;
3155 while(p > filename && *p != ' ') p--;
3156 while(p > filename && *p == ' ') p--;
3158 // skip "<file>", handling the case where it contains a
3159 char* filename_end = p + 1;
3160 if (p == filename) {
3161 // something went wrong, give up
3162 filename_end = filename + strlen(filename);
3163 funcname = filename_end;
3165 trace.object_filename.assign(filename, filename_end); // ok even if filename_end is the ending \0 (then we assign entire string)
3167 if (*funcname) { // if it's not end of string
3168 *funcname_end = '\0';
3170 trace.object_function = this->demangle(funcname);
3171 trace.object_function += " ";
3172 trace.object_function += (funcname_end + 1);
3173 trace.source.function = trace.object_function; // we cannot do better.
3179 details::handle<char**> _symbols;
3183 class TraceResolverImpl<system_tag::darwin_tag>:
3184 public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
3186 #endif // BACKWARD_SYSTEM_DARWIN
3188 class TraceResolver:
3189 public TraceResolverImpl<system_tag::current_tag> {};
3191 /*************** CODE SNIPPET ***************/
3195 typedef std::vector<std::pair<unsigned, std::string> > lines_t;
3198 SourceFile(const std::string& path): _file(new std::ifstream(path.c_str())) {}
3199 bool is_open() const { return _file->is_open(); }
3201 lines_t& get_lines(unsigned line_start, unsigned line_count, lines_t& lines) {
3202 using namespace std;
3203 // This function make uses of the dumbest algo ever:
3205 // 2) read lines one by one and discard until line_start
3206 // 3) read line one by one until line_start + line_count
3208 // If you are getting snippets many time from the same file, it is
3209 // somewhat a waste of CPU, feel free to benchmark and propose a
3210 // better solution ;)
3217 for (line_idx = 1; line_idx < line_start; ++line_idx) {
3218 std::getline(*_file, line);
3224 // think of it like a lambda in C++98 ;)
3225 // but look, I will reuse it two times!
3226 // What a good boy am I.
3228 bool operator()(char c) {
3229 return std::isspace(c);
3233 bool started = false;
3234 for (; line_idx < line_start + line_count; ++line_idx) {
3235 getline(*_file, line);
3240 if (std::find_if(line.begin(), line.end(),
3241 not_isspace()) == line.end())
3245 lines.push_back(make_pair(line_idx, line));
3249 std::find_if(lines.rbegin(), lines.rend(),
3250 not_isempty()).base(), lines.end()
3255 lines_t get_lines(unsigned line_start, unsigned line_count) {
3257 return get_lines(line_start, line_count, lines);
3260 // there is no find_if_not in C++98, lets do something crappy to
3262 struct not_isspace {
3263 bool operator()(char c) {
3264 return !std::isspace(c);
3267 // and define this one here because C++98 is not happy with local defined
3268 // struct passed to template functions, fuuuu.
3269 struct not_isempty {
3270 bool operator()(const lines_t::value_type& p) {
3271 return !(std::find_if(p.second.begin(), p.second.end(),
3272 not_isspace()) == p.second.end());
3276 void swap(SourceFile& b) {
3277 _file.swap(b._file);
3280 #ifdef BACKWARD_ATLEAST_CXX11
3281 SourceFile(SourceFile&& from): _file(nullptr) {
3284 SourceFile& operator=(SourceFile&& from) {
3285 swap(from); return *this;
3288 explicit SourceFile(const SourceFile& from) {
3289 // some sort of poor man's move semantic.
3290 swap(const_cast<SourceFile&>(from));
3292 SourceFile& operator=(const SourceFile& from) {
3293 // some sort of poor man's move semantic.
3294 swap(const_cast<SourceFile&>(from)); return *this;
3299 details::handle<std::ifstream*,
3300 details::default_delete<std::ifstream*>
3303 #ifdef BACKWARD_ATLEAST_CXX11
3304 SourceFile(const SourceFile&) = delete;
3305 SourceFile& operator=(const SourceFile&) = delete;
3309 class SnippetFactory {
3311 typedef SourceFile::lines_t lines_t;
3313 lines_t get_snippet(const std::string& filename,
3314 unsigned line_start, unsigned context_size) {
3316 SourceFile& src_file = get_src_file(filename);
3317 unsigned start = line_start - context_size / 2;
3318 return src_file.get_lines(start, context_size);
3321 lines_t get_combined_snippet(
3322 const std::string& filename_a, unsigned line_a,
3323 const std::string& filename_b, unsigned line_b,
3324 unsigned context_size) {
3325 SourceFile& src_file_a = get_src_file(filename_a);
3326 SourceFile& src_file_b = get_src_file(filename_b);
3328 lines_t lines = src_file_a.get_lines(line_a - context_size / 4,
3330 src_file_b.get_lines(line_b - context_size / 4, context_size / 2,
3335 lines_t get_coalesced_snippet(const std::string& filename,
3336 unsigned line_a, unsigned line_b, unsigned context_size) {
3337 SourceFile& src_file = get_src_file(filename);
3339 using std::min; using std::max;
3340 unsigned a = min(line_a, line_b);
3341 unsigned b = max(line_a, line_b);
3343 if ((b - a) < (context_size / 3)) {
3344 return src_file.get_lines((a + b - context_size + 1) / 2,
3348 lines_t lines = src_file.get_lines(a - context_size / 4,
3350 src_file.get_lines(b - context_size / 4, context_size / 2, lines);
3356 typedef details::hashtable<std::string, SourceFile>::type src_files_t;
3357 src_files_t _src_files;
3359 SourceFile& get_src_file(const std::string& filename) {
3360 src_files_t::iterator it = _src_files.find(filename);
3361 if (it != _src_files.end()) {
3364 SourceFile& new_src_file = _src_files[filename];
3365 new_src_file = SourceFile(filename);
3366 return new_src_file;
3370 /*************** PRINTER ***************/
3372 namespace ColorMode {
3380 class cfile_streambuf: public std::streambuf {
3382 cfile_streambuf(FILE *_sink): sink(_sink) {}
3383 int_type underflow() override { return traits_type::eof(); }
3384 int_type overflow(int_type ch) override {
3385 if (traits_type::not_eof(ch) && fwrite(&ch, sizeof ch, 1, sink) == 1) {
3388 return traits_type::eof();
3391 std::streamsize xsputn(const char_type* s, std::streamsize count) override {
3392 return static_cast<std::streamsize>(fwrite(s, sizeof *s, static_cast<size_t>(count), sink));
3395 #ifdef BACKWARD_ATLEAST_CXX11
3397 cfile_streambuf(const cfile_streambuf&) = delete;
3398 cfile_streambuf& operator=(const cfile_streambuf&) = delete;
3401 cfile_streambuf(const cfile_streambuf &);
3402 cfile_streambuf &operator= (const cfile_streambuf &);
3407 std::vector<char> buffer;
3410 #ifdef BACKWARD_SYSTEM_LINUX
3418 } // namespace Color
3422 Colorize(std::ostream& os):
3423 _os(os), _reset(false), _enabled(false) {}
3425 void activate(ColorMode::type mode) {
3426 _enabled = mode == ColorMode::always;
3429 void activate(ColorMode::type mode, FILE* fp) {
3430 activate(mode, fileno(fp));
3433 void set_color(Color::type ccode) {
3434 if (!_enabled) return;
3436 // I assume that the terminal can handle basic colors. Seriously I
3437 // don't want to deal with all the termcap shit.
3438 _os << "\033[" << static_cast<int>(ccode) << "m";
3439 _reset = (ccode != Color::reset);
3444 set_color(Color::reset);
3449 void activate(ColorMode::type mode, int fd) {
3450 activate(mode == ColorMode::automatic && isatty(fd) ? ColorMode::always : mode);
3458 #else // ndef BACKWARD_SYSTEM_LINUX
3466 } // namespace Color
3470 Colorize(std::ostream&) {}
3471 void activate(ColorMode::type) {}
3472 void activate(ColorMode::type, FILE*) {}
3473 void set_color(Color::type) {}
3476 #endif // BACKWARD_SYSTEM_LINUX
3482 ColorMode::type color_mode;
3485 int inliner_context_size;
3486 int trace_context_size;
3490 color_mode(ColorMode::automatic),
3493 inliner_context_size(5),
3494 trace_context_size(7)
3497 template <typename ST>
3498 FILE* print(ST& st, FILE* fp = stderr) {
3499 cfile_streambuf obuf(fp);
3500 std::ostream os(&obuf);
3501 Colorize colorize(os);
3502 colorize.activate(color_mode, fp);
3503 print_stacktrace(st, os, colorize);
3507 template <typename ST>
3508 std::ostream& print(ST& st, std::ostream& os) {
3509 Colorize colorize(os);
3510 colorize.activate(color_mode);
3511 print_stacktrace(st, os, colorize);
3515 template <typename IT>
3516 FILE* print(IT begin, IT end, FILE* fp = stderr, size_t thread_id = 0) {
3517 cfile_streambuf obuf(fp);
3518 std::ostream os(&obuf);
3519 Colorize colorize(os);
3520 colorize.activate(color_mode, fp);
3521 print_stacktrace(begin, end, os, thread_id, colorize);
3525 template <typename IT>
3526 std::ostream& print(IT begin, IT end, std::ostream& os, size_t thread_id = 0) {
3527 Colorize colorize(os);
3528 colorize.activate(color_mode);
3529 print_stacktrace(begin, end, os, thread_id, colorize);
3534 TraceResolver _resolver;
3535 SnippetFactory _snippets;
3537 template <typename ST>
3538 void print_stacktrace(ST& st, std::ostream& os, Colorize& colorize) {
3539 print_header(os, st.thread_id());
3540 _resolver.load_stacktrace(st);
3541 for (size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
3542 print_trace(os, _resolver.resolve(st[trace_idx-1]), colorize);
3546 template <typename IT>
3547 void print_stacktrace(IT begin, IT end, std::ostream& os, size_t thread_id, Colorize& colorize) {
3548 print_header(os, thread_id);
3549 for (; begin != end; ++begin) {
3550 print_trace(os, *begin, colorize);
3554 void print_header(std::ostream& os, size_t thread_id) {
3555 os << "Stack trace (most recent call last)";
3557 os << " in thread " << thread_id;
3562 void print_trace(std::ostream& os, const ResolvedTrace& trace,
3563 Colorize& colorize) {
3565 << std::left << std::setw(2) << trace.idx
3567 bool already_indented = true;
3569 if (!trace.source.filename.size() || object) {
3571 << trace.object_filename
3575 << trace.object_function
3577 already_indented = false;
3580 for (size_t inliner_idx = trace.inliners.size();
3581 inliner_idx > 0; --inliner_idx) {
3582 if (!already_indented) {
3585 const ResolvedTrace::SourceLoc& inliner_loc
3586 = trace.inliners[inliner_idx-1];
3587 print_source_loc(os, " | ", inliner_loc);
3589 print_snippet(os, " | ", inliner_loc,
3590 colorize, Color::purple, inliner_context_size);
3592 already_indented = false;
3595 if (trace.source.filename.size()) {
3596 if (!already_indented) {
3599 print_source_loc(os, " ", trace.source, trace.addr);
3601 print_snippet(os, " ", trace.source,
3602 colorize, Color::yellow, trace_context_size);
3607 void print_snippet(std::ostream& os, const char* indent,
3608 const ResolvedTrace::SourceLoc& source_loc,
3609 Colorize& colorize, Color::type color_code,
3612 using namespace std;
3613 typedef SnippetFactory::lines_t lines_t;
3615 lines_t lines = _snippets.get_snippet(source_loc.filename,
3616 source_loc.line, static_cast<unsigned>(context_size));
3618 for (lines_t::const_iterator it = lines.begin();
3619 it != lines.end(); ++it) {
3620 if (it-> first == source_loc.line) {
3621 colorize.set_color(color_code);
3622 os << indent << ">";
3624 os << indent << " ";
3626 os << std::setw(4) << it->first
3630 if (it-> first == source_loc.line) {
3631 colorize.set_color(Color::reset);
3636 void print_source_loc(std::ostream& os, const char* indent,
3637 const ResolvedTrace::SourceLoc& source_loc,
3638 void* addr=nullptr) {
3641 << source_loc.filename
3645 << source_loc.function;
3647 if (address && addr != nullptr) {
3648 os << " [" << addr << "]";
3654 /*************** SIGNALS HANDLING ***************/
3656 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
3659 class SignalHandling {
3661 static std::vector<int> make_default_signals() {
3662 const int posix_signals[] = {
3663 // Signals for which the default action is "Core".
3664 SIGABRT, // Abort signal from abort(3)
3665 SIGBUS, // Bus error (bad memory access)
3666 SIGFPE, // Floating point exception
3667 SIGILL, // Illegal Instruction
3668 SIGIOT, // IOT trap. A synonym for SIGABRT
3669 SIGQUIT, // Quit from keyboard
3670 SIGSEGV, // Invalid memory reference
3671 SIGSYS, // Bad argument to routine (SVr4)
3672 SIGTRAP, // Trace/breakpoint trap
3673 SIGXCPU, // CPU time limit exceeded (4.2BSD)
3674 SIGXFSZ, // File size limit exceeded (4.2BSD)
3675 #if defined(BACKWARD_SYSTEM_DARWIN)
3676 SIGEMT, // emulation instruction executed
3679 return std::vector<int>(posix_signals, posix_signals + sizeof posix_signals / sizeof posix_signals[0] );
3682 SignalHandling(const std::vector<int>& posix_signals = make_default_signals()):
3684 bool success = true;
3686 const size_t stack_size = 1024 * 1024 * 8;
3687 _stack_content.reset(static_cast<char*>(malloc(stack_size)));
3688 if (_stack_content) {
3690 ss.ss_sp = _stack_content.get();
3691 ss.ss_size = stack_size;
3693 if (sigaltstack(&ss, nullptr) < 0) {
3700 for (size_t i = 0; i < posix_signals.size(); ++i) {
3701 struct sigaction action;
3702 memset(&action, 0, sizeof action);
3703 action.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER |
3705 sigfillset(&action.sa_mask);
3706 sigdelset(&action.sa_mask, posix_signals[i]);
3707 #pragma clang diagnostic push
3708 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
3709 action.sa_sigaction = &sig_handler;
3710 #pragma clang diagnostic pop
3712 int r = sigaction(posix_signals[i], &action, nullptr);
3713 if (r < 0) success = false;
3719 bool loaded() const { return _loaded; }
3721 static void handleSignal(int, siginfo_t* info, void* _ctx) {
3722 ucontext_t *uctx = static_cast<ucontext_t*>(_ctx);
3725 void* error_addr = nullptr;
3726 #ifdef REG_RIP // x86_64
3727 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext.gregs[REG_RIP]);
3728 #elif defined(REG_EIP) // x86_32
3729 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext.gregs[REG_EIP]);
3730 #elif defined(__arm__)
3731 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext.arm_pc);
3732 #elif defined(__aarch64__)
3733 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext.pc);
3734 #elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__)
3735 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext.regs->nip);
3736 #elif defined(__s390x__)
3737 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext.psw.addr);
3738 #elif defined(__APPLE__) && defined(__x86_64__)
3739 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext->__ss.__rip);
3740 #elif defined(__APPLE__)
3741 error_addr = reinterpret_cast<void*>(uctx->uc_mcontext->__ss.__eip);
3743 # warning ":/ sorry, ain't know no nothing none not of your architecture!"
3746 st.load_from(error_addr, 32);
3752 printer.address = true;
3753 printer.print(st, stderr);
3755 #if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
3756 psiginfo(info, nullptr);
3763 details::handle<char*> _stack_content;
3767 __attribute__((noreturn))
3769 static void sig_handler(int signo, siginfo_t* info, void* _ctx) {
3770 handleSignal(signo, info, _ctx);
3772 // try to forward the signal.
3773 raise(info->si_signo);
3775 // terminate the process immediately.
3777 _exit(EXIT_FAILURE);
3781 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
3783 #ifdef BACKWARD_SYSTEM_UNKNOWN
3785 class SignalHandling {
3787 SignalHandling(const std::vector<int>& = std::vector<int>()) {}
3788 bool init() { return false; }
3789 bool loaded() { return false; }
3792 #endif // BACKWARD_SYSTEM_UNKNOWN
3794 } // namespace backward
3796 #endif /* H_GUARD */