Debian Codegraph @

android/app/jni/extern/backward/backward.hpp

raw
1 /*
2 * backward.hpp
3 * Copyright 2013 Google Inc. All Rights Reserved.
4 *
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:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
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
21 * SOFTWARE.
22 */
23
24 #ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
25 #define H_6B9572DA_A64B_49E6_B234_051480991C89
26
27 #ifndef __cplusplus
28 #error "It's not going to compile without a C++ compiler..."
29 #endif
30
31 #if defined(BACKWARD_CXX11)
32 #elif defined(BACKWARD_CXX98)
33 #else
34 #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)
35 #define BACKWARD_CXX11
36 #define BACKWARD_ATLEAST_CXX11
37 #define BACKWARD_ATLEAST_CXX98
38 #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
39 #define BACKWARD_ATLEAST_CXX17
40 #endif
41 #else
42 #define BACKWARD_CXX98
43 #define BACKWARD_ATLEAST_CXX98
44 #endif
45 #endif
46
47 // You can define one of the following (or leave it to the auto-detection):
48 //
49 // #define BACKWARD_SYSTEM_LINUX
50 // - specialization for linux
51 //
52 // #define BACKWARD_SYSTEM_DARWIN
53 // - specialization for Mac OS X 10.5 and later.
54 //
55 // #define BACKWARD_SYSTEM_WINDOWS
56 // - specialization for Windows (Clang 9 and MSVC2017)
57 //
58 // #define BACKWARD_SYSTEM_UNKNOWN
59 // - placebo implementation, does nothing.
60 //
61 #if defined(BACKWARD_SYSTEM_LINUX)
62 #elif defined(BACKWARD_SYSTEM_DARWIN)
63 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
64 #elif defined(BACKWARD_SYSTEM_WINDOWS)
65 #else
66 #if defined(__linux) || defined(__linux__)
67 #define BACKWARD_SYSTEM_LINUX
68 #elif defined(__APPLE__)
69 #define BACKWARD_SYSTEM_DARWIN
70 #elif defined(_WIN32)
71 #define BACKWARD_SYSTEM_WINDOWS
72 #else
73 #define BACKWARD_SYSTEM_UNKNOWN
74 #endif
75 #endif
76
77 #define NOINLINE __attribute__((noinline))
78
79 #include <algorithm>
80 #include <cctype>
81 #include <cstdio>
82 #include <cstdlib>
83 #include <cstring>
84 #include <fstream>
85 #include <iomanip>
86 #include <iostream>
87 #include <limits>
88 #include <new>
89 #include <sstream>
90 #include <streambuf>
91 #include <string>
92 #include <vector>
93 #include <exception>
94 #include <iterator>
95
96 #if defined(BACKWARD_SYSTEM_LINUX)
97
98 // On linux, backtrace can back-trace or "walk" the stack using the following
99 // libraries:
100 //
101 // #define BACKWARD_HAS_UNWIND 1
102 // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
103 // - with unwind, the stacktrace is as accurate as it can possibly be, since
104 // this is used by the C++ runtine in gcc/clang for stack unwinding on
105 // exception.
106 // - normally libgcc is already linked to your program by default.
107 //
108 // #define BACKWARD_HAS_LIBUNWIND 1
109 // - libunwind provides, in some cases, a more accurate stacktrace as it knows
110 // to decode signal handler frames and lets us edit the context registers when
111 // unwinding, allowing stack traces over bad function references.
112 //
113 // #define BACKWARD_HAS_BACKTRACE == 1
114 // - backtrace seems to be a little bit more portable than libunwind, but on
115 // linux, it uses unwind anyway, but abstract away a tiny information that is
116 // sadly really important in order to get perfectly accurate stack traces.
117 // - backtrace is part of the (e)glib library.
118 //
119 // The default is:
120 // #define BACKWARD_HAS_UNWIND == 1
121 //
122 // Note that only one of the define should be set to 1 at a time.
123 //
124 #if BACKWARD_HAS_UNWIND == 1
125 #elif BACKWARD_HAS_LIBUNWIND == 1
126 #elif BACKWARD_HAS_BACKTRACE == 1
127 #else
128 #undef BACKWARD_HAS_UNWIND
129 #define BACKWARD_HAS_UNWIND 1
130 #undef BACKWARD_HAS_LIBUNWIND
131 #define BACKWARD_HAS_LIBUNWIND 0
132 #undef BACKWARD_HAS_BACKTRACE
133 #define BACKWARD_HAS_BACKTRACE 0
134 #endif
135
136 // On linux, backward can extract detailed information about a stack trace
137 // using one of the following libraries:
138 //
139 // #define BACKWARD_HAS_DW 1
140 // - libdw gives you the most juicy details out of your stack traces:
141 // - object filename
142 // - function name
143 // - source filename
144 // - line and column numbers
145 // - source code snippet (assuming the file is accessible)
146 // - variable names (if not optimized out)
147 // - variable values (not supported by backward-cpp)
148 // - You need to link with the lib "dw":
149 // - apt-get install libdw-dev
150 // - g++/clang++ -ldw ...
151 //
152 // #define BACKWARD_HAS_BFD 1
153 // - With libbfd, you get a fair amount of details:
154 // - object filename
155 // - function name
156 // - source filename
157 // - line numbers
158 // - source code snippet (assuming the file is accessible)
159 // - You need to link with the lib "bfd":
160 // - apt-get install binutils-dev
161 // - g++/clang++ -lbfd ...
162 //
163 // #define BACKWARD_HAS_DWARF 1
164 // - libdwarf gives you the most juicy details out of your stack traces:
165 // - object filename
166 // - function name
167 // - source filename
168 // - line and column numbers
169 // - source code snippet (assuming the file is accessible)
170 // - variable names (if not optimized out)
171 // - variable values (not supported by backward-cpp)
172 // - You need to link with the lib "dwarf":
173 // - apt-get install libdwarf-dev
174 // - g++/clang++ -ldwarf ...
175 //
176 // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
177 // - backtrace provides minimal details for a stack trace:
178 // - object filename
179 // - function name
180 // - backtrace is part of the (e)glib library.
181 //
182 // The default is:
183 // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
184 //
185 // Note that only one of the define should be set to 1 at a time.
186 //
187 #if BACKWARD_HAS_DW == 1
188 #elif BACKWARD_HAS_BFD == 1
189 #elif BACKWARD_HAS_DWARF == 1
190 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
191 #else
192 #undef BACKWARD_HAS_DW
193 #define BACKWARD_HAS_DW 0
194 #undef BACKWARD_HAS_BFD
195 #define BACKWARD_HAS_BFD 0
196 #undef BACKWARD_HAS_DWARF
197 #define BACKWARD_HAS_DWARF 0
198 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
199 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
200 #endif
201
202 #include <cxxabi.h>
203 #include <fcntl.h>
204 #ifdef __ANDROID__
205 // Old Android API levels define _Unwind_Ptr in both link.h and
206 // unwind.h Rename the one in link.h as we are not going to be using
207 // it
208 #define _Unwind_Ptr _Unwind_Ptr_Custom
209 #include <link.h>
210 #undef _Unwind_Ptr
211 #else
212 #include <link.h>
213 #endif
214 #if defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
215 defined(__POWERPC__)
216 // Linux kernel header required for the struct pt_regs definition
217 // to access the NIP (Next Instruction Pointer) register value
218 #include <asm/ptrace.h>
219 #endif
220 #include <signal.h>
221 #include <sys/stat.h>
222 #include <syscall.h>
223 #include <unistd.h>
224 // https://github.com/tildearrow/furnace/issues/588
225 #ifndef _GNU_SOURCE
226 #define _GNU_SOURCE
227 #include <dlfcn.h>
228 #undef _GNU_SOURCE
229 #else
230 #include <dlfcn.h>
231 #endif
232
233 #if BACKWARD_HAS_BFD == 1
234 // NOTE: defining PACKAGE{,_VERSION} is required before including
235 // bfd.h on some platforms, see also:
236 // https://sourceware.org/bugzilla/show_bug.cgi?id=14243
237 #ifndef PACKAGE
238 #define PACKAGE
239 #endif
240 #ifndef PACKAGE_VERSION
241 #define PACKAGE_VERSION
242 #endif
243 #include <bfd.h>
244 #endif
245
246 #if BACKWARD_HAS_DW == 1
247 #include <dwarf.h>
248 #include <elfutils/libdw.h>
249 #include <elfutils/libdwfl.h>
250 #endif
251
252 #if BACKWARD_HAS_DWARF == 1
253 #include <algorithm>
254 #include <dwarf.h>
255 #include <libdwarf.h>
256 #include <libelf.h>
257 #include <map>
258 #endif
259
260 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
261 // then we shall rely on backtrace
262 #include <execinfo.h>
263 #endif
264
265 #endif // defined(BACKWARD_SYSTEM_LINUX)
266
267 #if defined(BACKWARD_SYSTEM_DARWIN)
268 // On Darwin, backtrace can back-trace or "walk" the stack using the following
269 // libraries:
270 //
271 // #define BACKWARD_HAS_UNWIND 1
272 // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
273 // - with unwind, the stacktrace is as accurate as it can possibly be, since
274 // this is used by the C++ runtine in gcc/clang for stack unwinding on
275 // exception.
276 // - normally libgcc is already linked to your program by default.
277 //
278 // #define BACKWARD_HAS_LIBUNWIND 1
279 // - libunwind comes from clang, which implements an API compatible version.
280 // - libunwind provides, in some cases, a more accurate stacktrace as it knows
281 // to decode signal handler frames and lets us edit the context registers when
282 // unwinding, allowing stack traces over bad function references.
283 //
284 // #define BACKWARD_HAS_BACKTRACE == 1
285 // - backtrace is available by default, though it does not produce as much
286 // information as another library might.
287 //
288 // The default is:
289 // #define BACKWARD_HAS_UNWIND == 1
290 //
291 // Note that only one of the define should be set to 1 at a time.
292 //
293 #if BACKWARD_HAS_UNWIND == 1
294 #elif BACKWARD_HAS_BACKTRACE == 1
295 #elif BACKWARD_HAS_LIBUNWIND == 1
296 #else
297 #undef BACKWARD_HAS_UNWIND
298 #define BACKWARD_HAS_UNWIND 1
299 #undef BACKWARD_HAS_BACKTRACE
300 #define BACKWARD_HAS_BACKTRACE 0
301 #undef BACKWARD_HAS_LIBUNWIND
302 #define BACKWARD_HAS_LIBUNWIND 0
303 #endif
304
305 // On Darwin, backward can extract detailed information about a stack trace
306 // using one of the following libraries:
307 //
308 // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
309 // - backtrace provides minimal details for a stack trace:
310 // - object filename
311 // - function name
312 //
313 // The default is:
314 // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
315 //
316 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
317 #else
318 #undef BACKWARD_HAS_BACKTRACE_SYMBOL
319 #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
320 #endif
321
322 #include <cxxabi.h>
323 #include <fcntl.h>
324 #include <pthread.h>
325 #include <signal.h>
326 #include <sys/stat.h>
327 #include <unistd.h>
328
329 #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
330 #include <execinfo.h>
331 #endif
332 #endif // defined(BACKWARD_SYSTEM_DARWIN)
333
334 #if defined(BACKWARD_SYSTEM_WINDOWS)
335
336 #include <condition_variable>
337 #include <mutex>
338 #include <thread>
339
340 #include <basetsd.h>
341
342 #ifdef _WIN64
343 typedef SSIZE_T ssize_t;
344 #else
345 typedef int ssize_t;
346 #endif
347
348 #ifndef NOMINMAX
349 #define NOMINMAX
350 #endif
351 #include <windows.h>
352 #include <winnt.h>
353
354 #include <psapi.h>
355 #include <signal.h>
356
357 #ifndef __clang__
358 #undef NOINLINE
359 #define NOINLINE __declspec(noinline)
360 #endif
361
362 #ifdef _MSC_VER
363 #pragma comment(lib, "psapi.lib")
364 #pragma comment(lib, "dbghelp.lib")
365 #endif
366
367 // Comment / packing is from stackoverflow:
368 // https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
369 // Some versions of imagehlp.dll lack the proper packing directives themselves
370 // so we need to do it.
371 #pragma pack(push, before_imagehlp, 8)
372 #include <imagehlp.h>
373 #pragma pack(pop, before_imagehlp)
374
375 // TODO maybe these should be undefined somewhere else?
376 #undef BACKWARD_HAS_UNWIND
377 #undef BACKWARD_HAS_BACKTRACE
378 #if BACKWARD_HAS_PDB_SYMBOL == 1
379 #else
380 #undef BACKWARD_HAS_PDB_SYMBOL
381 #define BACKWARD_HAS_PDB_SYMBOL 1
382 #endif
383
384 #endif
385
386 #if BACKWARD_HAS_UNWIND == 1
387
388 #include <unwind.h>
389 // while gcc's unwind.h defines something like that:
390 // extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *);
391 // extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
392 //
393 // clang's unwind.h defines something like this:
394 // uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context);
395 //
396 // Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we
397 // cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr
398 // anyway.
399 //
400 // Luckily we can play on the fact that the guard macros have a different name:
401 #ifdef __CLANG_UNWIND_H
402 // In fact, this function still comes from libgcc (on my different linux boxes,
403 // clang links against libgcc).
404 #include <inttypes.h>
405 extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *, int *);
406 #endif
407
408 #endif // BACKWARD_HAS_UNWIND == 1
409
410 #if BACKWARD_HAS_LIBUNWIND == 1
411 #define UNW_LOCAL_ONLY
412 #include <libunwind.h>
413 #endif // BACKWARD_HAS_LIBUNWIND == 1
414
415 #ifdef BACKWARD_ATLEAST_CXX11
416 #include <unordered_map>
417 #include <utility> // for std::swap
418 namespace backward {
419 namespace details {
420 template <typename K, typename V> struct hashtable {
421 typedef std::unordered_map<K, V> type;
422 };
423 using std::move;
424 } // namespace details
425 } // namespace backward
426 #else // NOT BACKWARD_ATLEAST_CXX11
427 #define nullptr NULL
428 #define override
429 #include <map>
430 namespace backward {
431 namespace details {
432 template <typename K, typename V> struct hashtable {
433 typedef std::map<K, V> type;
434 };
435 template <typename T> const T &move(const T &v) { return v; }
436 template <typename T> T &move(T &v) { return v; }
437 } // namespace details
438 } // namespace backward
439 #endif // BACKWARD_ATLEAST_CXX11
440
441 namespace backward {
442 namespace details {
443 #if defined(BACKWARD_SYSTEM_WINDOWS)
444 const char kBackwardPathDelimiter[] = ";";
445 #else
446 const char kBackwardPathDelimiter[] = ":";
447 #endif
448 } // namespace details
449 } // namespace backward
450
451 namespace backward {
452
453 namespace system_tag {
454 struct linux_tag; // seems that I cannot call that "linux" because the name
455 // is already defined... so I am adding _tag everywhere.
456 struct darwin_tag;
457 struct windows_tag;
458 struct unknown_tag;
459
460 #if defined(BACKWARD_SYSTEM_LINUX)
461 typedef linux_tag current_tag;
462 #elif defined(BACKWARD_SYSTEM_DARWIN)
463 typedef darwin_tag current_tag;
464 #elif defined(BACKWARD_SYSTEM_WINDOWS)
465 typedef windows_tag current_tag;
466 #elif defined(BACKWARD_SYSTEM_UNKNOWN)
467 typedef unknown_tag current_tag;
468 #else
469 #error "May I please get my system defines?"
470 #endif
471 } // namespace system_tag
472
473 namespace trace_resolver_tag {
474 #if defined(BACKWARD_SYSTEM_LINUX)
475 struct libdw;
476 struct libbfd;
477 struct libdwarf;
478 struct backtrace_symbol;
479
480 #if BACKWARD_HAS_DW == 1
481 typedef libdw current;
482 #elif BACKWARD_HAS_BFD == 1
483 typedef libbfd current;
484 #elif BACKWARD_HAS_DWARF == 1
485 typedef libdwarf current;
486 #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
487 typedef backtrace_symbol current;
488 #else
489 #error "You shall not pass, until you know what you want."
490 #endif
491 #elif defined(BACKWARD_SYSTEM_DARWIN)
492 struct backtrace_symbol;
493
494 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
495 typedef backtrace_symbol current;
496 #else
497 #error "You shall not pass, until you know what you want."
498 #endif
499 #elif defined(BACKWARD_SYSTEM_WINDOWS)
500 struct pdb_symbol;
501 #if BACKWARD_HAS_PDB_SYMBOL == 1
502 typedef pdb_symbol current;
503 #else
504 #error "You shall not pass, until you know what you want."
505 #endif
506 #endif
507 } // namespace trace_resolver_tag
508
509 namespace details {
510
511 template <typename T> struct rm_ptr { typedef T type; };
512
513 template <typename T> struct rm_ptr<T *> { typedef T type; };
514
515 template <typename T> struct rm_ptr<const T *> { typedef const T type; };
516
517 template <typename R, typename T, R (*F)(T)> struct deleter {
518 template <typename U> void operator()(U &ptr) const { (*F)(ptr); }
519 };
520
521 template <typename T> struct default_delete {
522 void operator()(T &ptr) const { delete ptr; }
523 };
524
525 template <typename T, typename Deleter = deleter<void, void *, &::free> >
526 class handle {
527 struct dummy;
528 T _val;
529 bool _empty;
530
531 #ifdef BACKWARD_ATLEAST_CXX11
532 handle(const handle &) = delete;
533 handle &operator=(const handle &) = delete;
534 #endif
535
536 public:
537 ~handle() {
538 if (!_empty) {
539 Deleter()(_val);
540 }
541 }
542
543 explicit handle() : _val(), _empty(true) {}
544 explicit handle(T val) : _val(val), _empty(false) {
545 if (!_val)
546 _empty = true;
547 }
548
549 #ifdef BACKWARD_ATLEAST_CXX11
550 handle(handle &&from) : _empty(true) { swap(from); }
551 handle &operator=(handle &&from) {
552 swap(from);
553 return *this;
554 }
555 #else
556 explicit handle(const handle &from) : _empty(true) {
557 // some sort of poor man's move semantic.
558 swap(const_cast<handle &>(from));
559 }
560 handle &operator=(const handle &from) {
561 // some sort of poor man's move semantic.
562 swap(const_cast<handle &>(from));
563 return *this;
564 }
565 #endif
566
567 void reset(T new_val) {
568 handle tmp(new_val);
569 swap(tmp);
570 }
571
572 void update(T new_val) {
573 _val = new_val;
574 _empty = !static_cast<bool>(new_val);
575 }
576
577 operator const dummy *() const {
578 if (_empty) {
579 return nullptr;
580 }
581 return reinterpret_cast<const dummy *>(_val);
582 }
583 T get() { return _val; }
584 T release() {
585 _empty = true;
586 return _val;
587 }
588 void swap(handle &b) {
589 using std::swap;
590 swap(b._val, _val); // can throw, we are safe here.
591 swap(b._empty, _empty); // should not throw: if you cannot swap two
592 // bools without throwing... It's a lost cause anyway!
593 }
594
595 T &operator->() { return _val; }
596 const T &operator->() const { return _val; }
597
598 typedef typename rm_ptr<T>::type &ref_t;
599 typedef const typename rm_ptr<T>::type &const_ref_t;
600 ref_t operator*() { return *_val; }
601 const_ref_t operator*() const { return *_val; }
602 ref_t operator[](size_t idx) { return _val[idx]; }
603
604 // Watch out, we've got a badass over here
605 T *operator&() {
606 _empty = false;
607 return &_val;
608 }
609 };
610
611 // Default demangler implementation (do nothing).
612 template <typename TAG> struct demangler_impl {
613 static std::string demangle(const char *funcname) { return funcname; }
614 };
615
616 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
617
618 template <> struct demangler_impl<system_tag::current_tag> {
619 demangler_impl() : _demangle_buffer_length(0) {}
620
621 std::string demangle(const char *funcname) {
622 using namespace details;
623 char *result = abi::__cxa_demangle(funcname, _demangle_buffer.get(),
624 &_demangle_buffer_length, nullptr);
625 if (result) {
626 _demangle_buffer.update(result);
627 return result;
628 }
629 return funcname;
630 }
631
632 private:
633 details::handle<char *> _demangle_buffer;
634 size_t _demangle_buffer_length;
635 };
636
637 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
638
639 struct demangler : public demangler_impl<system_tag::current_tag> {};
640
641 // Split a string on the platform's PATH delimiter. Example: if delimiter
642 // is ":" then:
643 // "" --> []
644 // ":" --> ["",""]
645 // "::" --> ["","",""]
646 // "/a/b/c" --> ["/a/b/c"]
647 // "/a/b/c:/d/e/f" --> ["/a/b/c","/d/e/f"]
648 // etc.
649 inline std::vector<std::string> split_source_prefixes(const std::string &s) {
650 std::vector<std::string> out;
651 size_t last = 0;
652 size_t next = 0;
653 size_t delimiter_size = sizeof(kBackwardPathDelimiter) - 1;
654 while ((next = s.find(kBackwardPathDelimiter, last)) != std::string::npos) {
655 out.push_back(s.substr(last, next - last));
656 last = next + delimiter_size;
657 }
658 if (last <= s.length()) {
659 out.push_back(s.substr(last));
660 }
661 return out;
662 }
663
664 } // namespace details
665
666 /*************** A TRACE ***************/
667
668 struct Trace {
669 void *addr;
670 size_t idx;
671
672 Trace() : addr(nullptr), idx(0) {}
673
674 explicit Trace(void *_addr, size_t _idx) : addr(_addr), idx(_idx) {}
675 };
676
677 struct ResolvedTrace : public Trace {
678
679 struct SourceLoc {
680 std::string function;
681 std::string filename;
682 unsigned line;
683 unsigned col;
684
685 SourceLoc() : line(0), col(0) {}
686
687 bool operator==(const SourceLoc &b) const {
688 return function == b.function && filename == b.filename &&
689 line == b.line && col == b.col;
690 }
691
692 bool operator!=(const SourceLoc &b) const { return !(*this == b); }
693 };
694
695 // In which binary object this trace is located.
696 std::string object_filename;
697
698 // The function in the object that contain the trace. This is not the same
699 // as source.function which can be an function inlined in object_function.
700 std::string object_function;
701
702 // The source location of this trace. It is possible for filename to be
703 // empty and for line/col to be invalid (value 0) if this information
704 // couldn't be deduced, for example if there is no debug information in the
705 // binary object.
706 SourceLoc source;
707
708 // An optionals list of "inliners". All the successive sources location
709 // from where the source location of the trace (the attribute right above)
710 // is inlined. It is especially useful when you compiled with optimization.
711 typedef std::vector<SourceLoc> source_locs_t;
712 source_locs_t inliners;
713
714 ResolvedTrace() : Trace() {}
715 ResolvedTrace(const Trace &mini_trace) : Trace(mini_trace) {}
716 };
717
718 /*************** STACK TRACE ***************/
719
720 // default implemention.
721 template <typename TAG> class StackTraceImpl {
722 public:
723 size_t size() const { return 0; }
724 Trace operator[](size_t) const { return Trace(); }
725 size_t load_here(size_t = 0) { return 0; }
726 size_t load_from(void *, size_t = 0, void * = nullptr, void * = nullptr) {
727 return 0;
728 }
729 size_t thread_id() const { return 0; }
730 void skip_n_firsts(size_t) {}
731 };
732
733 class StackTraceImplBase {
734 public:
735 StackTraceImplBase()
736 : _thread_id(0), _skip(0), _context(nullptr), _error_addr(nullptr) {}
737
738 size_t thread_id() const { return _thread_id; }
739
740 void skip_n_firsts(size_t n) { _skip = n; }
741
742 protected:
743 void load_thread_info() {
744 #ifdef BACKWARD_SYSTEM_LINUX
745 #ifndef __ANDROID__
746 _thread_id = static_cast<size_t>(syscall(SYS_gettid));
747 #else
748 _thread_id = static_cast<size_t>(gettid());
749 #endif
750 if (_thread_id == static_cast<size_t>(getpid())) {
751 // If the thread is the main one, let's hide that.
752 // I like to keep little secret sometimes.
753 _thread_id = 0;
754 }
755 #elif defined(BACKWARD_SYSTEM_DARWIN)
756 _thread_id = reinterpret_cast<size_t>(pthread_self());
757 if (pthread_main_np() == 1) {
758 // If the thread is the main one, let's hide that.
759 _thread_id = 0;
760 }
761 #endif
762 }
763
764 void set_context(void *context) { _context = context; }
765 void *context() const { return _context; }
766
767 void set_error_addr(void *error_addr) { _error_addr = error_addr; }
768 void *error_addr() const { return _error_addr; }
769
770 size_t skip_n_firsts() const { return _skip; }
771
772 private:
773 size_t _thread_id;
774 size_t _skip;
775 void *_context;
776 void *_error_addr;
777 };
778
779 class StackTraceImplHolder : public StackTraceImplBase {
780 public:
781 size_t size() const {
782 return (_stacktrace.size() >= skip_n_firsts())
783 ? _stacktrace.size() - skip_n_firsts()
784 : 0;
785 }
786 Trace operator[](size_t idx) const {
787 if (idx >= size()) {
788 return Trace();
789 }
790 return Trace(_stacktrace[idx + skip_n_firsts()], idx);
791 }
792 void *const *begin() const {
793 if (size()) {
794 return &_stacktrace[skip_n_firsts()];
795 }
796 return nullptr;
797 }
798
799 protected:
800 std::vector<void *> _stacktrace;
801 };
802
803 #if BACKWARD_HAS_UNWIND == 1
804
805 namespace details {
806
807 template <typename F> class Unwinder {
808 public:
809 size_t operator()(F &f, size_t depth) {
810 _f = &f;
811 _index = -1;
812 _depth = depth;
813 _Unwind_Backtrace(&this->backtrace_trampoline, this);
814 return static_cast<size_t>(_index);
815 }
816
817 private:
818 F *_f;
819 ssize_t _index;
820 size_t _depth;
821
822 static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx,
823 void *self) {
824 return (static_cast<Unwinder *>(self))->backtrace(ctx);
825 }
826
827 _Unwind_Reason_Code backtrace(_Unwind_Context *ctx) {
828 if (_index >= 0 && static_cast<size_t>(_index) >= _depth)
829 return _URC_END_OF_STACK;
830
831 int ip_before_instruction = 0;
832 uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
833
834 if (!ip_before_instruction) {
835 // calculating 0-1 for unsigned, looks like a possible bug to sanitiziers,
836 // so let's do it explicitly:
837 if (ip == 0) {
838 ip = std::numeric_limits<uintptr_t>::max(); // set it to 0xffff... (as
839 // from casting 0-1)
840 } else {
841 ip -= 1; // else just normally decrement it (no overflow/underflow will
842 // happen)
843 }
844 }
845
846 if (_index >= 0) { // ignore first frame.
847 (*_f)(static_cast<size_t>(_index), reinterpret_cast<void *>(ip));
848 }
849 _index += 1;
850 return _URC_NO_REASON;
851 }
852 };
853
854 template <typename F> size_t unwind(F f, size_t depth) {
855 Unwinder<F> unwinder;
856 return unwinder(f, depth);
857 }
858
859 } // namespace details
860
861 template <>
862 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
863 public:
864 NOINLINE
865 size_t load_here(size_t depth = 32, void *context = nullptr,
866 void *error_addr = nullptr) {
867 load_thread_info();
868 set_context(context);
869 set_error_addr(error_addr);
870 if (depth == 0) {
871 return 0;
872 }
873 _stacktrace.resize(depth);
874 size_t trace_cnt = details::unwind(callback(*this), depth);
875 _stacktrace.resize(trace_cnt);
876 skip_n_firsts(0);
877 return size();
878 }
879 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
880 void *error_addr = nullptr) {
881 load_here(depth + 8, context, error_addr);
882
883 for (size_t i = 0; i < _stacktrace.size(); ++i) {
884 if (_stacktrace[i] == addr) {
885 skip_n_firsts(i);
886 break;
887 }
888 }
889
890 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
891 return size();
892 }
893
894 private:
895 struct callback {
896 StackTraceImpl &self;
897 callback(StackTraceImpl &_self) : self(_self) {}
898
899 void operator()(size_t idx, void *addr) { self._stacktrace[idx] = addr; }
900 };
901 };
902
903 #elif BACKWARD_HAS_LIBUNWIND == 1
904
905 template <>
906 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
907 public:
908 __attribute__((noinline)) size_t load_here(size_t depth = 32,
909 void *_context = nullptr,
910 void *_error_addr = nullptr) {
911 set_context(_context);
912 set_error_addr(_error_addr);
913 load_thread_info();
914 if (depth == 0) {
915 return 0;
916 }
917 _stacktrace.resize(depth + 1);
918
919 int result = 0;
920
921 unw_context_t ctx;
922 size_t index = 0;
923
924 // Add the tail call. If the Instruction Pointer is the crash address it
925 // means we got a bad function pointer dereference, so we "unwind" the
926 // bad pointer manually by using the return address pointed to by the
927 // Stack Pointer as the Instruction Pointer and letting libunwind do
928 // the rest
929
930 if (context()) {
931 ucontext_t *uctx = reinterpret_cast<ucontext_t *>(context());
932 #ifdef REG_RIP // x86_64
933 if (uctx->uc_mcontext.gregs[REG_RIP] ==
934 reinterpret_cast<greg_t>(error_addr())) {
935 uctx->uc_mcontext.gregs[REG_RIP] =
936 *reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_RSP]);
937 }
938 _stacktrace[index] =
939 reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
940 ++index;
941 ctx = *reinterpret_cast<unw_context_t *>(uctx);
942 #elif defined(REG_EIP) // x86_32
943 if (uctx->uc_mcontext.gregs[REG_EIP] ==
944 reinterpret_cast<greg_t>(error_addr())) {
945 uctx->uc_mcontext.gregs[REG_EIP] =
946 *reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_ESP]);
947 }
948 _stacktrace[index] =
949 reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
950 ++index;
951 ctx = *reinterpret_cast<unw_context_t *>(uctx);
952 #elif defined(__arm__)
953 // libunwind uses its own context type for ARM unwinding.
954 // Copy the registers from the signal handler's context so we can
955 // unwind
956 unw_getcontext(&ctx);
957 ctx.regs[UNW_ARM_R0] = uctx->uc_mcontext.arm_r0;
958 ctx.regs[UNW_ARM_R1] = uctx->uc_mcontext.arm_r1;
959 ctx.regs[UNW_ARM_R2] = uctx->uc_mcontext.arm_r2;
960 ctx.regs[UNW_ARM_R3] = uctx->uc_mcontext.arm_r3;
961 ctx.regs[UNW_ARM_R4] = uctx->uc_mcontext.arm_r4;
962 ctx.regs[UNW_ARM_R5] = uctx->uc_mcontext.arm_r5;
963 ctx.regs[UNW_ARM_R6] = uctx->uc_mcontext.arm_r6;
964 ctx.regs[UNW_ARM_R7] = uctx->uc_mcontext.arm_r7;
965 ctx.regs[UNW_ARM_R8] = uctx->uc_mcontext.arm_r8;
966 ctx.regs[UNW_ARM_R9] = uctx->uc_mcontext.arm_r9;
967 ctx.regs[UNW_ARM_R10] = uctx->uc_mcontext.arm_r10;
968 ctx.regs[UNW_ARM_R11] = uctx->uc_mcontext.arm_fp;
969 ctx.regs[UNW_ARM_R12] = uctx->uc_mcontext.arm_ip;
970 ctx.regs[UNW_ARM_R13] = uctx->uc_mcontext.arm_sp;
971 ctx.regs[UNW_ARM_R14] = uctx->uc_mcontext.arm_lr;
972 ctx.regs[UNW_ARM_R15] = uctx->uc_mcontext.arm_pc;
973
974 // If we have crashed in the PC use the LR instead, as this was
975 // a bad function dereference
976 if (reinterpret_cast<unsigned long>(error_addr()) ==
977 uctx->uc_mcontext.arm_pc) {
978 ctx.regs[UNW_ARM_R15] =
979 uctx->uc_mcontext.arm_lr - sizeof(unsigned long);
980 }
981 _stacktrace[index] = reinterpret_cast<void *>(ctx.regs[UNW_ARM_R15]);
982 ++index;
983 #elif defined(__APPLE__) && defined(__x86_64__)
984 unw_getcontext(&ctx);
985 // OS X's implementation of libunwind uses its own context object
986 // so we need to convert the passed context to libunwind's format
987 // (information about the data layout taken from unw_getcontext.s
988 // in Apple's libunwind source
989 ctx.data[0] = uctx->uc_mcontext->__ss.__rax;
990 ctx.data[1] = uctx->uc_mcontext->__ss.__rbx;
991 ctx.data[2] = uctx->uc_mcontext->__ss.__rcx;
992 ctx.data[3] = uctx->uc_mcontext->__ss.__rdx;
993 ctx.data[4] = uctx->uc_mcontext->__ss.__rdi;
994 ctx.data[5] = uctx->uc_mcontext->__ss.__rsi;
995 ctx.data[6] = uctx->uc_mcontext->__ss.__rbp;
996 ctx.data[7] = uctx->uc_mcontext->__ss.__rsp;
997 ctx.data[8] = uctx->uc_mcontext->__ss.__r8;
998 ctx.data[9] = uctx->uc_mcontext->__ss.__r9;
999 ctx.data[10] = uctx->uc_mcontext->__ss.__r10;
1000 ctx.data[11] = uctx->uc_mcontext->__ss.__r11;
1001 ctx.data[12] = uctx->uc_mcontext->__ss.__r12;
1002 ctx.data[13] = uctx->uc_mcontext->__ss.__r13;
1003 ctx.data[14] = uctx->uc_mcontext->__ss.__r14;
1004 ctx.data[15] = uctx->uc_mcontext->__ss.__r15;
1005 ctx.data[16] = uctx->uc_mcontext->__ss.__rip;
1006
1007 // If the IP is the same as the crash address we have a bad function
1008 // dereference The caller's address is pointed to by %rsp, so we
1009 // dereference that value and set it to be the next frame's IP.
1010 if (uctx->uc_mcontext->__ss.__rip ==
1011 reinterpret_cast<__uint64_t>(error_addr())) {
1012 ctx.data[16] =
1013 *reinterpret_cast<__uint64_t *>(uctx->uc_mcontext->__ss.__rsp);
1014 }
1015 _stacktrace[index] = reinterpret_cast<void *>(ctx.data[16]);
1016 ++index;
1017 #elif defined(__APPLE__)
1018 unw_getcontext(&ctx)
1019 // TODO: Convert the ucontext_t to libunwind's unw_context_t like
1020 // we do in 64 bits
1021 if (ctx.uc_mcontext->__ss.__eip ==
1022 reinterpret_cast<greg_t>(error_addr())) {
1023 ctx.uc_mcontext->__ss.__eip = ctx.uc_mcontext->__ss.__esp;
1024 }
1025 _stacktrace[index] =
1026 reinterpret_cast<void *>(ctx.uc_mcontext->__ss.__eip);
1027 ++index;
1028 #endif
1029 }
1030
1031 unw_cursor_t cursor;
1032 if (context()) {
1033 #if defined(UNW_INIT_SIGNAL_FRAME)
1034 result = unw_init_local2(&cursor, &ctx, UNW_INIT_SIGNAL_FRAME);
1035 #else
1036 result = unw_init_local(&cursor, &ctx);
1037 #endif
1038 } else {
1039 unw_getcontext(&ctx);
1040 ;
1041 result = unw_init_local(&cursor, &ctx);
1042 }
1043
1044 if (result != 0)
1045 return 1;
1046
1047 unw_word_t ip = 0;
1048
1049 while (index <= depth && unw_step(&cursor) > 0) {
1050 result = unw_get_reg(&cursor, UNW_REG_IP, &ip);
1051 if (result == 0) {
1052 _stacktrace[index] = reinterpret_cast<void *>(--ip);
1053 ++index;
1054 }
1055 }
1056 --index;
1057
1058 _stacktrace.resize(index + 1);
1059 skip_n_firsts(0);
1060 return size();
1061 }
1062
1063 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
1064 void *error_addr = nullptr) {
1065 load_here(depth + 8, context, error_addr);
1066
1067 for (size_t i = 0; i < _stacktrace.size(); ++i) {
1068 if (_stacktrace[i] == addr) {
1069 skip_n_firsts(i);
1070 _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i]);
1071 break;
1072 }
1073 }
1074
1075 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1076 return size();
1077 }
1078 };
1079
1080 #elif defined(BACKWARD_HAS_BACKTRACE)
1081
1082 template <>
1083 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
1084 public:
1085 NOINLINE
1086 size_t load_here(size_t depth = 32, void *context = nullptr,
1087 void *error_addr = nullptr) {
1088 set_context(context);
1089 set_error_addr(error_addr);
1090 load_thread_info();
1091 if (depth == 0) {
1092 return 0;
1093 }
1094 _stacktrace.resize(depth + 1);
1095 size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
1096 _stacktrace.resize(trace_cnt);
1097 skip_n_firsts(1);
1098 return size();
1099 }
1100
1101 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
1102 void *error_addr = nullptr) {
1103 load_here(depth + 8, context, error_addr);
1104
1105 for (size_t i = 0; i < _stacktrace.size(); ++i) {
1106 if (_stacktrace[i] == addr) {
1107 skip_n_firsts(i);
1108 _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i] + 1);
1109 break;
1110 }
1111 }
1112
1113 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1114 return size();
1115 }
1116 };
1117
1118 #elif defined(BACKWARD_SYSTEM_WINDOWS)
1119
1120 template <>
1121 class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
1122 public:
1123 // We have to load the machine type from the image info
1124 // So we first initialize the resolver, and it tells us this info
1125 void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; }
1126 void set_context(CONTEXT *ctx) { ctx_ = ctx; }
1127 void set_thread_handle(HANDLE handle) { thd_ = handle; }
1128
1129 NOINLINE
1130 size_t load_here(size_t depth = 32, void *context = nullptr,
1131 void *error_addr = nullptr) {
1132 set_context(static_cast<CONTEXT*>(context));
1133 set_error_addr(error_addr);
1134 CONTEXT localCtx; // used when no context is provided
1135
1136 if (depth == 0) {
1137 return 0;
1138 }
1139
1140 if (!ctx_) {
1141 ctx_ = &localCtx;
1142 RtlCaptureContext(ctx_);
1143 }
1144
1145 if (!thd_) {
1146 thd_ = GetCurrentThread();
1147 }
1148
1149 HANDLE process = GetCurrentProcess();
1150
1151 STACKFRAME64 s;
1152 memset(&s, 0, sizeof(STACKFRAME64));
1153
1154 // TODO: 32 bit context capture
1155 s.AddrStack.Mode = AddrModeFlat;
1156 s.AddrFrame.Mode = AddrModeFlat;
1157 s.AddrPC.Mode = AddrModeFlat;
1158 #ifdef _M_X64
1159 s.AddrPC.Offset = ctx_->Rip;
1160 s.AddrStack.Offset = ctx_->Rsp;
1161 s.AddrFrame.Offset = ctx_->Rbp;
1162 #elif _M_ARM64
1163 s.AddrPC.Offset = ctx_->Pc;
1164 s.AddrStack.Offset = ctx_->Sp;
1165 s.AddrFrame.Offset = ctx_->Fp;
1166 #else
1167 s.AddrPC.Offset = ctx_->Eip;
1168 s.AddrStack.Offset = ctx_->Esp;
1169 s.AddrFrame.Offset = ctx_->Ebp;
1170 #endif
1171
1172 if (!machine_type_) {
1173 #ifdef _M_X64
1174 machine_type_ = IMAGE_FILE_MACHINE_AMD64;
1175 #elif _M_ARM64
1176 machine_type_ = IMAGE_FILE_MACHINE_ARM64;
1177 #else
1178 machine_type_ = IMAGE_FILE_MACHINE_I386;
1179 #endif
1180 }
1181
1182 for (;;) {
1183 // NOTE: this only works if PDBs are already loaded!
1184 SetLastError(0);
1185 if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL,
1186 SymFunctionTableAccess64, SymGetModuleBase64, NULL))
1187 break;
1188
1189 if (s.AddrReturn.Offset == 0)
1190 break;
1191
1192 _stacktrace.push_back(reinterpret_cast<void *>(s.AddrPC.Offset));
1193
1194 if (size() >= depth)
1195 break;
1196 }
1197
1198 return size();
1199 }
1200
1201 size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
1202 void *error_addr = nullptr) {
1203 load_here(depth + 8, context, error_addr);
1204
1205 for (size_t i = 0; i < _stacktrace.size(); ++i) {
1206 if (_stacktrace[i] == addr) {
1207 skip_n_firsts(i);
1208 break;
1209 }
1210 }
1211
1212 _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
1213 return size();
1214 }
1215
1216 private:
1217 DWORD machine_type_ = 0;
1218 HANDLE thd_ = 0;
1219 CONTEXT *ctx_ = nullptr;
1220 };
1221
1222 #endif
1223
1224 class StackTrace : public StackTraceImpl<system_tag::current_tag> {};
1225
1226 /*************** TRACE RESOLVER ***************/
1227
1228 class TraceResolverImplBase {
1229 public:
1230 virtual ~TraceResolverImplBase() {}
1231
1232 virtual void load_addresses(void *const*addresses, int address_count) {
1233 (void)addresses;
1234 (void)address_count;
1235 }
1236
1237 template <class ST> void load_stacktrace(ST &st) {
1238 load_addresses(st.begin(), static_cast<int>(st.size()));
1239 }
1240
1241 virtual ResolvedTrace resolve(ResolvedTrace t) { return t; }
1242
1243 protected:
1244 std::string demangle(const char *funcname) {
1245 return _demangler.demangle(funcname);
1246 }
1247
1248 private:
1249 details::demangler _demangler;
1250 };
1251
1252 template <typename TAG> class TraceResolverImpl;
1253
1254 #ifdef BACKWARD_SYSTEM_UNKNOWN
1255
1256 template <> class TraceResolverImpl<system_tag::unknown_tag>
1257 : public TraceResolverImplBase {};
1258
1259 #endif
1260
1261 #ifdef BACKWARD_SYSTEM_LINUX
1262
1263 class TraceResolverLinuxBase : public TraceResolverImplBase {
1264 public:
1265 TraceResolverLinuxBase()
1266 : argv0_(get_argv0()), exec_path_(read_symlink("/proc/self/exe")) {}
1267 std::string resolve_exec_path(Dl_info &symbol_info) const {
1268 // mutates symbol_info.dli_fname to be filename to open and returns filename
1269 // to display
1270 if (symbol_info.dli_fname == argv0_) {
1271 // dladdr returns argv[0] in dli_fname for symbols contained in
1272 // the main executable, which is not a valid path if the
1273 // executable was found by a search of the PATH environment
1274 // variable; In that case, we actually open /proc/self/exe, which
1275 // is always the actual executable (even if it was deleted/replaced!)
1276 // but display the path that /proc/self/exe links to.
1277 // However, this right away reduces probability of successful symbol
1278 // resolution, because libbfd may try to find *.debug files in the
1279 // same dir, in case symbols are stripped. As a result, it may try
1280 // to find a file /proc/self/<exe_name>.debug, which obviously does
1281 // not exist. /proc/self/exe is a last resort. First load attempt
1282 // should go for the original executable file path.
1283 symbol_info.dli_fname = "/proc/self/exe";
1284 return exec_path_;
1285 } else {
1286 return symbol_info.dli_fname;
1287 }
1288 }
1289
1290 private:
1291 std::string argv0_;
1292 std::string exec_path_;
1293
1294 static std::string get_argv0() {
1295 std::string argv0;
1296 std::ifstream ifs("/proc/self/cmdline");
1297 std::getline(ifs, argv0, '\0');
1298 return argv0;
1299 }
1300
1301 static std::string read_symlink(std::string const &symlink_path) {
1302 std::string path;
1303 path.resize(100);
1304
1305 while (true) {
1306 ssize_t len =
1307 ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
1308 if (len < 0) {
1309 return "";
1310 }
1311 if (static_cast<size_t>(len) == path.size()) {
1312 path.resize(path.size() * 2);
1313 } else {
1314 path.resize(static_cast<std::string::size_type>(len));
1315 break;
1316 }
1317 }
1318
1319 return path;
1320 }
1321 };
1322
1323 template <typename STACKTRACE_TAG> class TraceResolverLinuxImpl;
1324
1325 #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1326
1327 template <>
1328 class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>
1329 : public TraceResolverLinuxBase {
1330 public:
1331 void load_addresses(void *const*addresses, int address_count) override {
1332 if (address_count == 0) {
1333 return;
1334 }
1335 _symbols.reset(backtrace_symbols(addresses, address_count));
1336 }
1337
1338 ResolvedTrace resolve(ResolvedTrace trace) override {
1339 char *filename = _symbols[trace.idx];
1340 char *funcname = filename;
1341 while (*funcname && *funcname != '(') {
1342 funcname += 1;
1343 }
1344 trace.object_filename.assign(filename,
1345 funcname); // ok even if funcname is the ending
1346 // \0 (then we assign entire string)
1347
1348 if (*funcname) { // if it's not end of string (e.g. from last frame ip==0)
1349 funcname += 1;
1350 char *funcname_end = funcname;
1351 while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') {
1352 funcname_end += 1;
1353 }
1354 *funcname_end = '\0';
1355 trace.object_function = this->demangle(funcname);
1356 trace.source.function = trace.object_function; // we cannot do better.
1357 }
1358 return trace;
1359 }
1360
1361 private:
1362 details::handle<char **> _symbols;
1363 };
1364
1365 #endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
1366
1367 #if BACKWARD_HAS_BFD == 1
1368
1369 template <>
1370 class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>
1371 : public TraceResolverLinuxBase {
1372 public:
1373 TraceResolverLinuxImpl() : _bfd_loaded(false) {}
1374
1375 ResolvedTrace resolve(ResolvedTrace trace) override {
1376 Dl_info symbol_info;
1377
1378 // trace.addr is a virtual address in memory pointing to some code.
1379 // Let's try to find from which loaded object it comes from.
1380 // The loaded object can be yourself btw.
1381 if (!dladdr(trace.addr, &symbol_info)) {
1382 return trace; // dat broken trace...
1383 }
1384
1385 // Now we get in symbol_info:
1386 // .dli_fname:
1387 // pathname of the shared object that contains the address.
1388 // .dli_fbase:
1389 // where the object is loaded in memory.
1390 // .dli_sname:
1391 // the name of the nearest symbol to trace.addr, we expect a
1392 // function name.
1393 // .dli_saddr:
1394 // the exact address corresponding to .dli_sname.
1395
1396 if (symbol_info.dli_sname) {
1397 trace.object_function = demangle(symbol_info.dli_sname);
1398 }
1399
1400 if (!symbol_info.dli_fname) {
1401 return trace;
1402 }
1403
1404 trace.object_filename = resolve_exec_path(symbol_info);
1405 bfd_fileobject *fobj;
1406 // Before rushing to resolution need to ensure the executable
1407 // file still can be used. For that compare inode numbers of
1408 // what is stored by the executable's file path, and in the
1409 // dli_fname, which not necessarily equals to the executable.
1410 // It can be a shared library, or /proc/self/exe, and in the
1411 // latter case has drawbacks. See the exec path resolution for
1412 // details. In short - the dli object should be used only as
1413 // the last resort.
1414 // If inode numbers are equal, it is known dli_fname and the
1415 // executable file are the same. This is guaranteed by Linux,
1416 // because if the executable file is changed/deleted, it will
1417 // be done in a new inode. The old file will be preserved in
1418 // /proc/self/exe, and may even have inode 0. The latter can
1419 // happen if the inode was actually reused, and the file was
1420 // kept only in the main memory.
1421 //
1422 struct stat obj_stat;
1423 struct stat dli_stat;
1424 if (stat(trace.object_filename.c_str(), &obj_stat) == 0 &&
1425 stat(symbol_info.dli_fname, &dli_stat) == 0 &&
1426 obj_stat.st_ino == dli_stat.st_ino) {
1427 // The executable file, and the shared object containing the
1428 // address are the same file. Safe to use the original path.
1429 // this is preferable. Libbfd will search for stripped debug
1430 // symbols in the same directory.
1431 fobj = load_object_with_bfd(trace.object_filename);
1432 } else{
1433 // The original object file was *deleted*! The only hope is
1434 // that the debug symbols are either inside the shared
1435 // object file, or are in the same directory, and this is
1436 // not /proc/self/exe.
1437 fobj = nullptr;
1438 }
1439 if (fobj == nullptr || !fobj->handle) {
1440 fobj = load_object_with_bfd(symbol_info.dli_fname);
1441 if (!fobj->handle) {
1442 return trace;
1443 }
1444 }
1445
1446 find_sym_result *details_selected; // to be filled.
1447
1448 // trace.addr is the next instruction to be executed after returning
1449 // from the nested stack frame. In C++ this usually relate to the next
1450 // statement right after the function call that leaded to a new stack
1451 // frame. This is not usually what you want to see when printing out a
1452 // stacktrace...
1453 find_sym_result details_call_site =
1454 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1455 details_selected = &details_call_site;
1456
1457 #if BACKWARD_HAS_UNWIND == 0
1458 // ...this is why we also try to resolve the symbol that is right
1459 // before the return address. If we are lucky enough, we will get the
1460 // line of the function that was called. But if the code is optimized,
1461 // we might get something absolutely not related since the compiler
1462 // can reschedule the return address with inline functions and
1463 // tail-call optimisation (among other things that I don't even know
1464 // or cannot even dream about with my tiny limited brain).
1465 find_sym_result details_adjusted_call_site = find_symbol_details(
1466 fobj, (void *)(uintptr_t(trace.addr) - 1), symbol_info.dli_fbase);
1467
1468 // In debug mode, we should always get the right thing(TM).
1469 if (details_call_site.found && details_adjusted_call_site.found) {
1470 // Ok, we assume that details_adjusted_call_site is a better estimation.
1471 details_selected = &details_adjusted_call_site;
1472 trace.addr = (void *)(uintptr_t(trace.addr) - 1);
1473 }
1474
1475 if (details_selected == &details_call_site && details_call_site.found) {
1476 // we have to re-resolve the symbol in order to reset some
1477 // internal state in BFD... so we can call backtrace_inliners
1478 // thereafter...
1479 details_call_site =
1480 find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
1481 }
1482 #endif // BACKWARD_HAS_UNWIND
1483
1484 if (details_selected->found) {
1485 if (details_selected->filename) {
1486 trace.source.filename = details_selected->filename;
1487 }
1488 trace.source.line = details_selected->line;
1489
1490 if (details_selected->funcname) {
1491 // this time we get the name of the function where the code is
1492 // located, instead of the function were the address is
1493 // located. In short, if the code was inlined, we get the
1494 // function correspoding to the code. Else we already got in
1495 // trace.function.
1496 trace.source.function = demangle(details_selected->funcname);
1497
1498 if (!symbol_info.dli_sname) {
1499 // for the case dladdr failed to find the symbol name of
1500 // the function, we might as well try to put something
1501 // here.
1502 trace.object_function = trace.source.function;
1503 }
1504 }
1505
1506 // Maybe the source of the trace got inlined inside the function
1507 // (trace.source.function). Let's see if we can get all the inlined
1508 // calls along the way up to the initial call site.
1509 trace.inliners = backtrace_inliners(fobj, *details_selected);
1510
1511 #if 0
1512 if (trace.inliners.size() == 0) {
1513 // Maybe the trace was not inlined... or maybe it was and we
1514 // are lacking the debug information. Let's try to make the
1515 // world better and see if we can get the line number of the
1516 // function (trace.source.function) now.
1517 //
1518 // We will get the location of where the function start (to be
1519 // exact: the first instruction that really start the
1520 // function), not where the name of the function is defined.
1521 // This can be quite far away from the name of the function
1522 // btw.
1523 //
1524 // If the source of the function is the same as the source of
1525 // the trace, we cannot say if the trace was really inlined or
1526 // not. However, if the filename of the source is different
1527 // between the function and the trace... we can declare it as
1528 // an inliner. This is not 100% accurate, but better than
1529 // nothing.
1530
1531 if (symbol_info.dli_saddr) {
1532 find_sym_result details = find_symbol_details(fobj,
1533 symbol_info.dli_saddr,
1534 symbol_info.dli_fbase);
1535
1536 if (details.found) {
1537 ResolvedTrace::SourceLoc diy_inliner;
1538 diy_inliner.line = details.line;
1539 if (details.filename) {
1540 diy_inliner.filename = details.filename;
1541 }
1542 if (details.funcname) {
1543 diy_inliner.function = demangle(details.funcname);
1544 } else {
1545 diy_inliner.function = trace.source.function;
1546 }
1547 if (diy_inliner != trace.source) {
1548 trace.inliners.push_back(diy_inliner);
1549 }
1550 }
1551 }
1552 }
1553 #endif
1554 }
1555
1556 return trace;
1557 }
1558
1559 private:
1560 bool _bfd_loaded;
1561
1562 typedef details::handle<bfd *,
1563 details::deleter<bfd_boolean, bfd *, &bfd_close> >
1564 bfd_handle_t;
1565
1566 typedef details::handle<asymbol **> bfd_symtab_t;
1567
1568 struct bfd_fileobject {
1569 bfd_handle_t handle;
1570 bfd_vma base_addr;
1571 bfd_symtab_t symtab;
1572 bfd_symtab_t dynamic_symtab;
1573 };
1574
1575 typedef details::hashtable<std::string, bfd_fileobject>::type fobj_bfd_map_t;
1576 fobj_bfd_map_t _fobj_bfd_map;
1577
1578 bfd_fileobject *load_object_with_bfd(const std::string &filename_object) {
1579 using namespace details;
1580
1581 if (!_bfd_loaded) {
1582 using namespace details;
1583 bfd_init();
1584 _bfd_loaded = true;
1585 }
1586
1587 fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object);
1588 if (it != _fobj_bfd_map.end()) {
1589 return &it->second;
1590 }
1591
1592 // this new object is empty for now.
1593 bfd_fileobject *r = &_fobj_bfd_map[filename_object];
1594
1595 // we do the work temporary in this one;
1596 bfd_handle_t bfd_handle;
1597
1598 int fd = open(filename_object.c_str(), O_RDONLY);
1599 bfd_handle.reset(bfd_fdopenr(filename_object.c_str(), "default", fd));
1600 if (!bfd_handle) {
1601 close(fd);
1602 return r;
1603 }
1604
1605 if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
1606 return r; // not an object? You lose.
1607 }
1608
1609 if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
1610 return r; // that's what happen when you forget to compile in debug.
1611 }
1612
1613 ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get());
1614
1615 ssize_t dyn_symtab_storage_size =
1616 bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
1617
1618 if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
1619 return r; // weird, is the file is corrupted?
1620 }
1621
1622 bfd_symtab_t symtab, dynamic_symtab;
1623 ssize_t symcount = 0, dyn_symcount = 0;
1624
1625 if (symtab_storage_size > 0) {
1626 symtab.reset(static_cast<bfd_symbol **>(
1627 malloc(static_cast<size_t>(symtab_storage_size))));
1628 symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get());
1629 }
1630
1631 if (dyn_symtab_storage_size > 0) {
1632 dynamic_symtab.reset(static_cast<bfd_symbol **>(
1633 malloc(static_cast<size_t>(dyn_symtab_storage_size))));
1634 dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(),
1635 dynamic_symtab.get());
1636 }
1637
1638 if (symcount <= 0 && dyn_symcount <= 0) {
1639 return r; // damned, that's a stripped file that you got there!
1640 }
1641
1642 r->handle = move(bfd_handle);
1643 r->symtab = move(symtab);
1644 r->dynamic_symtab = move(dynamic_symtab);
1645 return r;
1646 }
1647
1648 struct find_sym_result {
1649 bool found;
1650 const char *filename;
1651 const char *funcname;
1652 unsigned int line;
1653 };
1654
1655 struct find_sym_context {
1656 TraceResolverLinuxImpl *self;
1657 bfd_fileobject *fobj;
1658 void *addr;
1659 void *base_addr;
1660 find_sym_result result;
1661 };
1662
1663 find_sym_result find_symbol_details(bfd_fileobject *fobj, void *addr,
1664 void *base_addr) {
1665 find_sym_context context;
1666 context.self = this;
1667 context.fobj = fobj;
1668 context.addr = addr;
1669 context.base_addr = base_addr;
1670 context.result.found = false;
1671 bfd_map_over_sections(fobj->handle.get(), &find_in_section_trampoline,
1672 static_cast<void *>(&context));
1673 return context.result;
1674 }
1675
1676 static void find_in_section_trampoline(bfd *, asection *section, void *data) {
1677 find_sym_context *context = static_cast<find_sym_context *>(data);
1678 context->self->find_in_section(
1679 reinterpret_cast<bfd_vma>(context->addr),
1680 reinterpret_cast<bfd_vma>(context->base_addr), context->fobj, section,
1681 context->result);
1682 }
1683
1684 void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject *fobj,
1685 asection *section, find_sym_result &result) {
1686 if (result.found)
1687 return;
1688
1689 #ifdef bfd_get_section_flags
1690 if ((bfd_get_section_flags(fobj->handle.get(), section) & SEC_ALLOC) == 0)
1691 #else
1692 if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
1693 #endif
1694 return; // a debug section is never loaded automatically.
1695
1696 #ifdef bfd_get_section_vma
1697 bfd_vma sec_addr = bfd_get_section_vma(fobj->handle.get(), section);
1698 #else
1699 bfd_vma sec_addr = bfd_section_vma(section);
1700 #endif
1701 #ifdef bfd_get_section_size
1702 bfd_size_type size = bfd_get_section_size(section);
1703 #else
1704 bfd_size_type size = bfd_section_size(section);
1705 #endif
1706
1707 // are we in the boundaries of the section?
1708 if (addr < sec_addr || addr >= sec_addr + size) {
1709 addr -= base_addr; // oups, a relocated object, lets try again...
1710 if (addr < sec_addr || addr >= sec_addr + size) {
1711 return;
1712 }
1713 }
1714
1715 #if defined(__clang__)
1716 #pragma clang diagnostic push
1717 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1718 #endif
1719 if (!result.found && fobj->symtab) {
1720 result.found = bfd_find_nearest_line(
1721 fobj->handle.get(), section, fobj->symtab.get(), addr - sec_addr,
1722 &result.filename, &result.funcname, &result.line);
1723 }
1724
1725 if (!result.found && fobj->dynamic_symtab) {
1726 result.found = bfd_find_nearest_line(
1727 fobj->handle.get(), section, fobj->dynamic_symtab.get(),
1728 addr - sec_addr, &result.filename, &result.funcname, &result.line);
1729 }
1730 #if defined(__clang__)
1731 #pragma clang diagnostic pop
1732 #endif
1733 }
1734
1735 ResolvedTrace::source_locs_t
1736 backtrace_inliners(bfd_fileobject *fobj, find_sym_result previous_result) {
1737 // This function can be called ONLY after a SUCCESSFUL call to
1738 // find_symbol_details. The state is global to the bfd_handle.
1739 ResolvedTrace::source_locs_t results;
1740 while (previous_result.found) {
1741 find_sym_result result;
1742 result.found = bfd_find_inliner_info(fobj->handle.get(), &result.filename,
1743 &result.funcname, &result.line);
1744
1745 if (result
1746 .found) /* and not (
1747 cstrings_eq(previous_result.filename,
1748 result.filename) and
1749 cstrings_eq(previous_result.funcname, result.funcname)
1750 and result.line == previous_result.line
1751 )) */
1752 {
1753 ResolvedTrace::SourceLoc src_loc;
1754 src_loc.line = result.line;
1755 if (result.filename) {
1756 src_loc.filename = result.filename;
1757 }
1758 if (result.funcname) {
1759 src_loc.function = demangle(result.funcname);
1760 }
1761 results.push_back(src_loc);
1762 }
1763 previous_result = result;
1764 }
1765 return results;
1766 }
1767
1768 bool cstrings_eq(const char *a, const char *b) {
1769 if (!a || !b) {
1770 return false;
1771 }
1772 return strcmp(a, b) == 0;
1773 }
1774 };
1775 #endif // BACKWARD_HAS_BFD == 1
1776
1777 #if BACKWARD_HAS_DW == 1
1778
1779 template <>
1780 class TraceResolverLinuxImpl<trace_resolver_tag::libdw>
1781 : public TraceResolverLinuxBase {
1782 public:
1783 TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {}
1784
1785 ResolvedTrace resolve(ResolvedTrace trace) override {
1786 using namespace details;
1787
1788 Dwarf_Addr trace_addr = (Dwarf_Addr)trace.addr;
1789
1790 if (!_dwfl_handle_initialized) {
1791 // initialize dwfl...
1792 _dwfl_cb.reset(new Dwfl_Callbacks);
1793 _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
1794 _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
1795 _dwfl_cb->debuginfo_path = 0;
1796
1797 _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
1798 _dwfl_handle_initialized = true;
1799
1800 if (!_dwfl_handle) {
1801 return trace;
1802 }
1803
1804 // ...from the current process.
1805 dwfl_report_begin(_dwfl_handle.get());
1806 int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid());
1807 dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
1808 if (r < 0) {
1809 return trace;
1810 }
1811 }
1812
1813 if (!_dwfl_handle) {
1814 return trace;
1815 }
1816
1817 // find the module (binary object) that contains the trace's address.
1818 // This is not using any debug information, but the addresses ranges of
1819 // all the currently loaded binary object.
1820 Dwfl_Module *mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
1821 if (mod) {
1822 // now that we found it, lets get the name of it, this will be the
1823 // full path to the running binary or one of the loaded library.
1824 const char *module_name = dwfl_module_info(mod, 0, 0, 0, 0, 0, 0, 0);
1825 if (module_name) {
1826 trace.object_filename = module_name;
1827 }
1828 // We also look after the name of the symbol, equal or before this
1829 // address. This is found by walking the symtab. We should get the
1830 // symbol corresponding to the function (mangled) containing the
1831 // address. If the code corresponding to the address was inlined,
1832 // this is the name of the out-most inliner function.
1833 const char *sym_name = dwfl_module_addrname(mod, trace_addr);
1834 if (sym_name) {
1835 trace.object_function = demangle(sym_name);
1836 }
1837 }
1838
1839 // now let's get serious, and find out the source location (file and
1840 // line number) of the address.
1841
1842 // This function will look in .debug_aranges for the address and map it
1843 // to the location of the compilation unit DIE in .debug_info and
1844 // return it.
1845 Dwarf_Addr mod_bias = 0;
1846 Dwarf_Die *cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias);
1847
1848 #if 1
1849 if (!cudie) {
1850 // Sadly clang does not generate the section .debug_aranges, thus
1851 // dwfl_module_addrdie will fail early. Clang doesn't either set
1852 // the lowpc/highpc/range info for every compilation unit.
1853 //
1854 // So in order to save the world:
1855 // for every compilation unit, we will iterate over every single
1856 // DIEs. Normally functions should have a lowpc/highpc/range, which
1857 // we will use to infer the compilation unit.
1858
1859 // note that this is probably badly inefficient.
1860 while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) {
1861 Dwarf_Die die_mem;
1862 Dwarf_Die *fundie =
1863 find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem);
1864 if (fundie) {
1865 break;
1866 }
1867 }
1868 }
1869 #endif
1870
1871 //#define BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1872 #ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
1873 if (!cudie) {
1874 // If it's still not enough, lets dive deeper in the shit, and try
1875 // to save the world again: for every compilation unit, we will
1876 // load the corresponding .debug_line section, and see if we can
1877 // find our address in it.
1878
1879 Dwarf_Addr cfi_bias;
1880 Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias);
1881
1882 Dwarf_Addr bias;
1883 while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) {
1884 if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
1885
1886 // ...but if we get a match, it might be a false positive
1887 // because our (address - bias) might as well be valid in a
1888 // different compilation unit. So we throw our last card on
1889 // the table and lookup for the address into the .eh_frame
1890 // section.
1891
1892 handle<Dwarf_Frame *> frame;
1893 dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
1894 if (frame) {
1895 break;
1896 }
1897 }
1898 }
1899 }
1900 #endif
1901
1902 if (!cudie) {
1903 return trace; // this time we lost the game :/
1904 }
1905
1906 // Now that we have a compilation unit DIE, this function will be able
1907 // to load the corresponding section in .debug_line (if not already
1908 // loaded) and hopefully find the source location mapped to our
1909 // address.
1910 Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
1911
1912 if (srcloc) {
1913 const char *srcfile = dwarf_linesrc(srcloc, 0, 0);
1914 if (srcfile) {
1915 trace.source.filename = srcfile;
1916 }
1917 int line = 0, col = 0;
1918 dwarf_lineno(srcloc, &line);
1919 dwarf_linecol(srcloc, &col);
1920 trace.source.line = line;
1921 trace.source.col = col;
1922 }
1923
1924 deep_first_search_by_pc(cudie, trace_addr - mod_bias,
1925 inliners_search_cb(trace));
1926 if (trace.source.function.size() == 0) {
1927 // fallback.
1928 trace.source.function = trace.object_function;
1929 }
1930
1931 return trace;
1932 }
1933
1934 private:
1935 typedef details::handle<Dwfl *, details::deleter<void, Dwfl *, &dwfl_end> >
1936 dwfl_handle_t;
1937 details::handle<Dwfl_Callbacks *, details::default_delete<Dwfl_Callbacks *> >
1938 _dwfl_cb;
1939 dwfl_handle_t _dwfl_handle;
1940 bool _dwfl_handle_initialized;
1941
1942 // defined here because in C++98, template function cannot take locally
1943 // defined types... grrr.
1944 struct inliners_search_cb {
1945 void operator()(Dwarf_Die *die) {
1946 switch (dwarf_tag(die)) {
1947 const char *name;
1948 case DW_TAG_subprogram:
1949 if ((name = dwarf_diename(die))) {
1950 trace.source.function = name;
1951 }
1952 break;
1953
1954 case DW_TAG_inlined_subroutine:
1955 ResolvedTrace::SourceLoc sloc;
1956 Dwarf_Attribute attr_mem;
1957
1958 if ((name = dwarf_diename(die))) {
1959 sloc.function = name;
1960 }
1961 if ((name = die_call_file(die))) {
1962 sloc.filename = name;
1963 }
1964
1965 Dwarf_Word line = 0, col = 0;
1966 dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line);
1967 dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col);
1968 sloc.line = (unsigned)line;
1969 sloc.col = (unsigned)col;
1970
1971 trace.inliners.push_back(sloc);
1972 break;
1973 };
1974 }
1975 ResolvedTrace &trace;
1976 inliners_search_cb(ResolvedTrace &t) : trace(t) {}
1977 };
1978
1979 static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) {
1980 Dwarf_Addr low, high;
1981
1982 // continuous range
1983 if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) {
1984 if (dwarf_lowpc(die, &low) != 0) {
1985 return false;
1986 }
1987 if (dwarf_highpc(die, &high) != 0) {
1988 Dwarf_Attribute attr_mem;
1989 Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
1990 Dwarf_Word value;
1991 if (dwarf_formudata(attr, &value) != 0) {
1992 return false;
1993 }
1994 high = low + value;
1995 }
1996 return pc >= low && pc < high;
1997 }
1998
1999 // non-continuous range.
2000 Dwarf_Addr base;
2001 ptrdiff_t offset = 0;
2002 while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
2003 if (pc >= low && pc < high) {
2004 return true;
2005 }
2006 }
2007 return false;
2008 }
2009
2010 static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
2011 Dwarf_Die *result) {
2012 if (dwarf_child(parent_die, result) != 0) {
2013 return 0;
2014 }
2015
2016 Dwarf_Die *die = result;
2017 do {
2018 switch (dwarf_tag(die)) {
2019 case DW_TAG_subprogram:
2020 case DW_TAG_inlined_subroutine:
2021 if (die_has_pc(die, pc)) {
2022 return result;
2023 }
2024 };
2025 bool declaration = false;
2026 Dwarf_Attribute attr_mem;
2027 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
2028 &declaration);
2029 if (!declaration) {
2030 // let's be curious and look deeper in the tree,
2031 // function are not necessarily at the first level, but
2032 // might be nested inside a namespace, structure etc.
2033 Dwarf_Die die_mem;
2034 Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem);
2035 if (indie) {
2036 *result = die_mem;
2037 return result;
2038 }
2039 }
2040 } while (dwarf_siblingof(die, result) == 0);
2041 return 0;
2042 }
2043
2044 template <typename CB>
2045 static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
2046 CB cb) {
2047 Dwarf_Die die_mem;
2048 if (dwarf_child(parent_die, &die_mem) != 0) {
2049 return false;
2050 }
2051
2052 bool branch_has_pc = false;
2053 Dwarf_Die *die = &die_mem;
2054 do {
2055 bool declaration = false;
2056 Dwarf_Attribute attr_mem;
2057 dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
2058 &declaration);
2059 if (!declaration) {
2060 // let's be curious and look deeper in the tree, function are
2061 // not necessarily at the first level, but might be nested
2062 // inside a namespace, structure, a function, an inlined
2063 // function etc.
2064 branch_has_pc = deep_first_search_by_pc(die, pc, cb);
2065 }
2066 if (!branch_has_pc) {
2067 branch_has_pc = die_has_pc(die, pc);
2068 }
2069 if (branch_has_pc) {
2070 cb(die);
2071 }
2072 } while (dwarf_siblingof(die, &die_mem) == 0);
2073 return branch_has_pc;
2074 }
2075
2076 static const char *die_call_file(Dwarf_Die *die) {
2077 Dwarf_Attribute attr_mem;
2078 Dwarf_Word file_idx = 0;
2079
2080 dwarf_formudata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx);
2081
2082 if (file_idx == 0) {
2083 return 0;
2084 }
2085
2086 Dwarf_Die die_mem;
2087 Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0);
2088 if (!cudie) {
2089 return 0;
2090 }
2091
2092 Dwarf_Files *files = 0;
2093 size_t nfiles;
2094 dwarf_getsrcfiles(cudie, &files, &nfiles);
2095 if (!files) {
2096 return 0;
2097 }
2098
2099 return dwarf_filesrc(files, file_idx, 0, 0);
2100 }
2101 };
2102 #endif // BACKWARD_HAS_DW == 1
2103
2104 #if BACKWARD_HAS_DWARF == 1
2105
2106 template <>
2107 class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>
2108 : public TraceResolverLinuxBase {
2109 public:
2110 TraceResolverLinuxImpl() : _dwarf_loaded(false) {}
2111
2112 ResolvedTrace resolve(ResolvedTrace trace) override {
2113 // trace.addr is a virtual address in memory pointing to some code.
2114 // Let's try to find from which loaded object it comes from.
2115 // The loaded object can be yourself btw.
2116
2117 Dl_info symbol_info;
2118 int dladdr_result = 0;
2119 #if defined(__GLIBC__)
2120 link_map *link_map;
2121 // We request the link map so we can get information about offsets
2122 dladdr_result =
2123 dladdr1(trace.addr, &symbol_info, reinterpret_cast<void **>(&link_map),
2124 RTLD_DL_LINKMAP);
2125 #else
2126 // Android doesn't have dladdr1. Don't use the linker map.
2127 dladdr_result = dladdr(trace.addr, &symbol_info);
2128 #endif
2129 if (!dladdr_result) {
2130 return trace; // dat broken trace...
2131 }
2132
2133 // Now we get in symbol_info:
2134 // .dli_fname:
2135 // pathname of the shared object that contains the address.
2136 // .dli_fbase:
2137 // where the object is loaded in memory.
2138 // .dli_sname:
2139 // the name of the nearest symbol to trace.addr, we expect a
2140 // function name.
2141 // .dli_saddr:
2142 // the exact address corresponding to .dli_sname.
2143 //
2144 // And in link_map:
2145 // .l_addr:
2146 // difference between the address in the ELF file and the address
2147 // in memory
2148 // l_name:
2149 // absolute pathname where the object was found
2150
2151 if (symbol_info.dli_sname) {
2152 trace.object_function = demangle(symbol_info.dli_sname);
2153 }
2154
2155 if (!symbol_info.dli_fname) {
2156 return trace;
2157 }
2158
2159 trace.object_filename = resolve_exec_path(symbol_info);
2160 dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname);
2161 if (!fobj.dwarf_handle) {
2162 return trace; // sad, we couldn't load the object :(
2163 }
2164
2165 #if defined(__GLIBC__)
2166 // Convert the address to a module relative one by looking at
2167 // the module's loading address in the link map
2168 Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr) -
2169 reinterpret_cast<uintptr_t>(link_map->l_addr);
2170 #else
2171 Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr);
2172 #endif
2173
2174 if (trace.object_function.empty()) {
2175 symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address);
2176
2177 if (it != fobj.symbol_cache.end()) {
2178 if (it->first != address) {
2179 if (it != fobj.symbol_cache.begin()) {
2180 --it;
2181 }
2182 }
2183 trace.object_function = demangle(it->second.c_str());
2184 }
2185 }
2186
2187 // Get the Compilation Unit DIE for the address
2188 Dwarf_Die die = find_die(fobj, address);
2189
2190 if (!die) {
2191 return trace; // this time we lost the game :/
2192 }
2193
2194 // libdwarf doesn't give us direct access to its objects, it always
2195 // allocates a copy for the caller. We keep that copy alive in a cache
2196 // and we deallocate it later when it's no longer required.
2197 die_cache_entry &die_object = get_die_cache(fobj, die);
2198 if (die_object.isEmpty())
2199 return trace; // We have no line section for this DIE
2200
2201 die_linemap_t::iterator it = die_object.line_section.lower_bound(address);
2202
2203 if (it != die_object.line_section.end()) {
2204 if (it->first != address) {
2205 if (it == die_object.line_section.begin()) {
2206 // If we are on the first item of the line section
2207 // but the address does not match it means that
2208 // the address is below the range of the DIE. Give up.
2209 return trace;
2210 } else {
2211 --it;
2212 }
2213 }
2214 } else {
2215 return trace; // We didn't find the address.
2216 }
2217
2218 // Get the Dwarf_Line that the address points to and call libdwarf
2219 // to get source file, line and column info.
2220 Dwarf_Line line = die_object.line_buffer[it->second];
2221 Dwarf_Error error = DW_DLE_NE;
2222
2223 char *filename;
2224 if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) {
2225 trace.source.filename = std::string(filename);
2226 dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
2227 }
2228
2229 Dwarf_Unsigned number = 0;
2230 if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
2231 trace.source.line = number;
2232 } else {
2233 trace.source.line = 0;
2234 }
2235
2236 if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
2237 trace.source.col = number;
2238 } else {
2239 trace.source.col = 0;
2240 }
2241
2242 std::vector<std::string> namespace_stack;
2243 deep_first_search_by_pc(fobj, die, address, namespace_stack,
2244 inliners_search_cb(trace, fobj, die));
2245
2246 dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
2247
2248 return trace;
2249 }
2250
2251 public:
2252 static int close_dwarf(Dwarf_Debug dwarf) {
2253 return dwarf_finish(dwarf, NULL);
2254 }
2255
2256 private:
2257 bool _dwarf_loaded;
2258
2259 typedef details::handle<int, details::deleter<int, int, &::close> >
2260 dwarf_file_t;
2261
2262 typedef details::handle<Elf *, details::deleter<int, Elf *, &elf_end> >
2263 dwarf_elf_t;
2264
2265 typedef details::handle<Dwarf_Debug,
2266 details::deleter<int, Dwarf_Debug, &close_dwarf> >
2267 dwarf_handle_t;
2268
2269 typedef std::map<Dwarf_Addr, int> die_linemap_t;
2270
2271 typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
2272
2273 struct die_cache_entry {
2274 die_specmap_t spec_section;
2275 die_linemap_t line_section;
2276 Dwarf_Line *line_buffer;
2277 Dwarf_Signed line_count;
2278 Dwarf_Line_Context line_context;
2279
2280 inline bool isEmpty() {
2281 return line_buffer == NULL || line_count == 0 || line_context == NULL ||
2282 line_section.empty();
2283 }
2284
2285 die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {}
2286
2287 ~die_cache_entry() {
2288 if (line_context) {
2289 dwarf_srclines_dealloc_b(line_context);
2290 }
2291 }
2292 };
2293
2294 typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
2295
2296 typedef std::map<uintptr_t, std::string> symbol_cache_t;
2297
2298 struct dwarf_fileobject {
2299 dwarf_file_t file_handle;
2300 dwarf_elf_t elf_handle;
2301 dwarf_handle_t dwarf_handle;
2302 symbol_cache_t symbol_cache;
2303
2304 // Die cache
2305 die_cache_t die_cache;
2306 die_cache_entry *current_cu;
2307 };
2308
2309 typedef details::hashtable<std::string, dwarf_fileobject>::type
2310 fobj_dwarf_map_t;
2311 fobj_dwarf_map_t _fobj_dwarf_map;
2312
2313 static bool cstrings_eq(const char *a, const char *b) {
2314 if (!a || !b) {
2315 return false;
2316 }
2317 return strcmp(a, b) == 0;
2318 }
2319
2320 dwarf_fileobject &load_object_with_dwarf(const std::string &filename_object) {
2321
2322 if (!_dwarf_loaded) {
2323 // Set the ELF library operating version
2324 // If that fails there's nothing we can do
2325 _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
2326 }
2327
2328 fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object);
2329 if (it != _fobj_dwarf_map.end()) {
2330 return it->second;
2331 }
2332
2333 // this new object is empty for now
2334 dwarf_fileobject &r = _fobj_dwarf_map[filename_object];
2335
2336 dwarf_file_t file_handle;
2337 file_handle.reset(open(filename_object.c_str(), O_RDONLY));
2338 if (file_handle.get() < 0) {
2339 return r;
2340 }
2341
2342 // Try to get an ELF handle. We need to read the ELF sections
2343 // because we want to see if there is a .gnu_debuglink section
2344 // that points to a split debug file
2345 dwarf_elf_t elf_handle;
2346 elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
2347 if (!elf_handle) {
2348 return r;
2349 }
2350
2351 const char *e_ident = elf_getident(elf_handle.get(), 0);
2352 if (!e_ident) {
2353 return r;
2354 }
2355
2356 // Get the number of sections
2357 // We use the new APIs as elf_getshnum is deprecated
2358 size_t shdrnum = 0;
2359 if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
2360 return r;
2361 }
2362
2363 // Get the index to the string section
2364 size_t shdrstrndx = 0;
2365 if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) {
2366 return r;
2367 }
2368
2369 std::string debuglink;
2370 // Iterate through the ELF sections to try to get a gnu_debuglink
2371 // note and also to cache the symbol table.
2372 // We go the preprocessor way to avoid having to create templated
2373 // classes or using gelf (which might throw a compiler error if 64 bit
2374 // is not supported
2375 #define ELF_GET_DATA(ARCH) \
2376 Elf_Scn *elf_section = 0; \
2377 Elf_Data *elf_data = 0; \
2378 Elf##ARCH##_Shdr *section_header = 0; \
2379 Elf_Scn *symbol_section = 0; \
2380 size_t symbol_count = 0; \
2381 size_t symbol_strings = 0; \
2382 Elf##ARCH##_Sym *symbol = 0; \
2383 const char *section_name = 0; \
2384 \
2385 while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \
2386 section_header = elf##ARCH##_getshdr(elf_section); \
2387 if (section_header == NULL) { \
2388 return r; \
2389 } \
2390 \
2391 if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \
2392 section_header->sh_name)) == NULL) { \
2393 return r; \
2394 } \
2395 \
2396 if (cstrings_eq(section_name, ".gnu_debuglink")) { \
2397 elf_data = elf_getdata(elf_section, NULL); \
2398 if (elf_data && elf_data->d_size > 0) { \
2399 debuglink = \
2400 std::string(reinterpret_cast<const char *>(elf_data->d_buf)); \
2401 } \
2402 } \
2403 \
2404 switch (section_header->sh_type) { \
2405 case SHT_SYMTAB: \
2406 symbol_section = elf_section; \
2407 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2408 symbol_strings = section_header->sh_link; \
2409 break; \
2410 \
2411 /* We use .dynsyms as a last resort, we prefer .symtab */ \
2412 case SHT_DYNSYM: \
2413 if (!symbol_section) { \
2414 symbol_section = elf_section; \
2415 symbol_count = section_header->sh_size / section_header->sh_entsize; \
2416 symbol_strings = section_header->sh_link; \
2417 } \
2418 break; \
2419 } \
2420 } \
2421 \
2422 if (symbol_section && symbol_count && symbol_strings) { \
2423 elf_data = elf_getdata(symbol_section, NULL); \
2424 symbol = reinterpret_cast<Elf##ARCH##_Sym *>(elf_data->d_buf); \
2425 for (size_t i = 0; i < symbol_count; ++i) { \
2426 int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
2427 if (type == STT_FUNC && symbol->st_value > 0) { \
2428 r.symbol_cache[symbol->st_value] = std::string( \
2429 elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \
2430 } \
2431 ++symbol; \
2432 } \
2433 }
2434
2435 if (e_ident[EI_CLASS] == ELFCLASS32) {
2436 ELF_GET_DATA(32)
2437 } else if (e_ident[EI_CLASS] == ELFCLASS64) {
2438 // libelf might have been built without 64 bit support
2439 #if __LIBELF64
2440 ELF_GET_DATA(64)
2441 #endif
2442 }
2443
2444 if (!debuglink.empty()) {
2445 // We have a debuglink section! Open an elf instance on that
2446 // file instead. If we can't open the file, then return
2447 // the elf handle we had already opened.
2448 dwarf_file_t debuglink_file;
2449 debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
2450 if (debuglink_file.get() > 0) {
2451 dwarf_elf_t debuglink_elf;
2452 debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL));
2453
2454 // If we have a valid elf handle, return the new elf handle
2455 // and file handle and discard the original ones
2456 if (debuglink_elf) {
2457 elf_handle = move(debuglink_elf);
2458 file_handle = move(debuglink_file);
2459 }
2460 }
2461 }
2462
2463 // Ok, we have a valid ELF handle, let's try to get debug symbols
2464 Dwarf_Debug dwarf_debug;
2465 Dwarf_Error error = DW_DLE_NE;
2466 dwarf_handle_t dwarf_handle;
2467
2468 int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL,
2469 &dwarf_debug, &error);
2470
2471 // We don't do any special handling for DW_DLV_NO_ENTRY specially.
2472 // If we get an error, or the file doesn't have debug information
2473 // we just return.
2474 if (dwarf_result != DW_DLV_OK) {
2475 return r;
2476 }
2477
2478 dwarf_handle.reset(dwarf_debug);
2479
2480 r.file_handle = move(file_handle);
2481 r.elf_handle = move(elf_handle);
2482 r.dwarf_handle = move(dwarf_handle);
2483
2484 return r;
2485 }
2486
2487 die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) {
2488 Dwarf_Error error = DW_DLE_NE;
2489
2490 // Get the die offset, we use it as the cache key
2491 Dwarf_Off die_offset;
2492 if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
2493 die_offset = 0;
2494 }
2495
2496 die_cache_t::iterator it = fobj.die_cache.find(die_offset);
2497
2498 if (it != fobj.die_cache.end()) {
2499 fobj.current_cu = &it->second;
2500 return it->second;
2501 }
2502
2503 die_cache_entry &de = fobj.die_cache[die_offset];
2504 fobj.current_cu = &de;
2505
2506 Dwarf_Addr line_addr;
2507 Dwarf_Small table_count;
2508
2509 // The addresses in the line section are not fully sorted (they might
2510 // be sorted by block of code belonging to the same file), which makes
2511 // it necessary to do so before searching is possible.
2512 //
2513 // As libdwarf allocates a copy of everything, let's get the contents
2514 // of the line section and keep it around. We also create a map of
2515 // program counter to line table indices so we can search by address
2516 // and get the line buffer index.
2517 //
2518 // To make things more difficult, the same address can span more than
2519 // one line, so we need to keep the index pointing to the first line
2520 // by using insert instead of the map's [ operator.
2521
2522 // Get the line context for the DIE
2523 if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) ==
2524 DW_DLV_OK) {
2525 // Get the source lines for this line context, to be deallocated
2526 // later
2527 if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer,
2528 &de.line_count,
2529 &error) == DW_DLV_OK) {
2530
2531 // Add all the addresses to our map
2532 for (int i = 0; i < de.line_count; i++) {
2533 if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) !=
2534 DW_DLV_OK) {
2535 line_addr = 0;
2536 }
2537 de.line_section.insert(std::pair<Dwarf_Addr, int>(line_addr, i));
2538 }
2539 }
2540 }
2541
2542 // For each CU, cache the function DIEs that contain the
2543 // DW_AT_specification attribute. When building with -g3 the function
2544 // DIEs are separated in declaration and specification, with the
2545 // declaration containing only the name and parameters and the
2546 // specification the low/high pc and other compiler attributes.
2547 //
2548 // We cache those specifications so we don't skip over the declarations,
2549 // because they have no pc, and we can do namespace resolution for
2550 // DWARF function names.
2551 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2552 Dwarf_Die current_die = 0;
2553 if (dwarf_child(die, &current_die, &error) == DW_DLV_OK) {
2554 for (;;) {
2555 Dwarf_Die sibling_die = 0;
2556
2557 Dwarf_Half tag_value;
2558 dwarf_tag(current_die, &tag_value, &error);
2559
2560 if (tag_value == DW_TAG_subprogram ||
2561 tag_value == DW_TAG_inlined_subroutine) {
2562
2563 Dwarf_Bool has_attr = 0;
2564 if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr,
2565 &error) == DW_DLV_OK) {
2566 if (has_attr) {
2567 Dwarf_Attribute attr_mem;
2568 if (dwarf_attr(current_die, DW_AT_specification, &attr_mem,
2569 &error) == DW_DLV_OK) {
2570 Dwarf_Off spec_offset = 0;
2571 if (dwarf_formref(attr_mem, &spec_offset, &error) ==
2572 DW_DLV_OK) {
2573 Dwarf_Off spec_die_offset;
2574 if (dwarf_dieoffset(current_die, &spec_die_offset, &error) ==
2575 DW_DLV_OK) {
2576 de.spec_section[spec_offset] = spec_die_offset;
2577 }
2578 }
2579 }
2580 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2581 }
2582 }
2583 }
2584
2585 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
2586 if (result == DW_DLV_ERROR) {
2587 break;
2588 } else if (result == DW_DLV_NO_ENTRY) {
2589 break;
2590 }
2591
2592 if (current_die != die) {
2593 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
2594 current_die = 0;
2595 }
2596
2597 current_die = sibling_die;
2598 }
2599 }
2600 return de;
2601 }
2602
2603 static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die,
2604 Dwarf_Half attr, bool global) {
2605 Dwarf_Error error = DW_DLE_NE;
2606 Dwarf_Attribute attr_mem;
2607
2608 Dwarf_Die found_die = NULL;
2609 if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
2610 Dwarf_Off offset;
2611 int result = 0;
2612 if (global) {
2613 result = dwarf_global_formref(attr_mem, &offset, &error);
2614 } else {
2615 result = dwarf_formref(attr_mem, &offset, &error);
2616 }
2617
2618 if (result == DW_DLV_OK) {
2619 if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) {
2620 found_die = NULL;
2621 }
2622 }
2623 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2624 }
2625 return found_die;
2626 }
2627
2628 static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die,
2629 Dwarf_Half attr, bool global) {
2630 Dwarf_Error error = DW_DLE_NE;
2631 std::string value;
2632
2633 Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
2634
2635 if (found_die) {
2636 char *name;
2637 if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
2638 if (name) {
2639 value = std::string(name);
2640 }
2641 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2642 }
2643 dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
2644 }
2645
2646 return value;
2647 }
2648
2649 // Returns a spec DIE linked to the passed one. The caller should
2650 // deallocate the DIE
2651 static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) {
2652 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2653 Dwarf_Error error = DW_DLE_NE;
2654 Dwarf_Off die_offset;
2655 if (fobj.current_cu &&
2656 dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) {
2657 die_specmap_t::iterator it =
2658 fobj.current_cu->spec_section.find(die_offset);
2659
2660 // If we have a DIE that completes the current one, check if
2661 // that one has the pc we are looking for
2662 if (it != fobj.current_cu->spec_section.end()) {
2663 Dwarf_Die spec_die = 0;
2664 if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) {
2665 return spec_die;
2666 }
2667 }
2668 }
2669
2670 // Maybe we have an abstract origin DIE with the function information?
2671 return get_referenced_die(fobj.dwarf_handle.get(), die,
2672 DW_AT_abstract_origin, true);
2673 }
2674
2675 static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) {
2676 Dwarf_Addr low_pc = 0, high_pc = 0;
2677 Dwarf_Half high_pc_form = 0;
2678 Dwarf_Form_Class return_class;
2679 Dwarf_Error error = DW_DLE_NE;
2680 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2681 bool has_lowpc = false;
2682 bool has_highpc = false;
2683 bool has_ranges = false;
2684
2685 if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
2686 // If we have a low_pc check if there is a high pc.
2687 // If we don't have a high pc this might mean we have a base
2688 // address for the ranges list or just an address.
2689 has_lowpc = true;
2690
2691 if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) ==
2692 DW_DLV_OK) {
2693 // We do have a high pc. In DWARF 4+ this is an offset from the
2694 // low pc, but in earlier versions it's an absolute address.
2695
2696 has_highpc = true;
2697 // In DWARF 2/3 this would be a DW_FORM_CLASS_ADDRESS
2698 if (return_class == DW_FORM_CLASS_CONSTANT) {
2699 high_pc = low_pc + high_pc;
2700 }
2701
2702 // We have low and high pc, check if our address
2703 // is in that range
2704 return pc >= low_pc && pc < high_pc;
2705 }
2706 } else {
2707 // Reset the low_pc, in case dwarf_lowpc failing set it to some
2708 // undefined value.
2709 low_pc = 0;
2710 }
2711
2712 // Check if DW_AT_ranges is present and search for the PC in the
2713 // returned ranges list. We always add the low_pc, as it not set it will
2714 // be 0, in case we had a DW_AT_low_pc and DW_AT_ranges pair
2715 bool result = false;
2716
2717 Dwarf_Attribute attr;
2718 if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
2719
2720 Dwarf_Off offset;
2721 if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
2722 Dwarf_Ranges *ranges;
2723 Dwarf_Signed ranges_count = 0;
2724 Dwarf_Unsigned byte_count = 0;
2725
2726 if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count,
2727 &byte_count, &error) == DW_DLV_OK) {
2728 has_ranges = ranges_count != 0;
2729 for (int i = 0; i < ranges_count; i++) {
2730 if (ranges[i].dwr_addr1 != 0 &&
2731 pc >= ranges[i].dwr_addr1 + low_pc &&
2732 pc < ranges[i].dwr_addr2 + low_pc) {
2733 result = true;
2734 break;
2735 }
2736 }
2737 dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
2738 }
2739 }
2740 }
2741
2742 // Last attempt. We might have a single address set as low_pc.
2743 if (!result && low_pc != 0 && pc == low_pc) {
2744 result = true;
2745 }
2746
2747 // If we don't have lowpc, highpc and ranges maybe this DIE is a
2748 // declaration that relies on a DW_AT_specification DIE that happens
2749 // later. Use the specification cache we filled when we loaded this CU.
2750 if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
2751 Dwarf_Die spec_die = get_spec_die(fobj, die);
2752 if (spec_die) {
2753 result = die_has_pc(fobj, spec_die, pc);
2754 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
2755 }
2756 }
2757
2758 return result;
2759 }
2760
2761 static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &type) {
2762 Dwarf_Error error = DW_DLE_NE;
2763
2764 Dwarf_Die child = 0;
2765 if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
2766 get_type(dwarf, child, type);
2767 }
2768
2769 if (child) {
2770 type.insert(0, "::");
2771 dwarf_dealloc(dwarf, child, DW_DLA_DIE);
2772 }
2773
2774 char *name;
2775 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2776 type.insert(0, std::string(name));
2777 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
2778 } else {
2779 type.insert(0, "<unknown>");
2780 }
2781 }
2782
2783 static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
2784 Dwarf_Error error = DW_DLE_NE;
2785
2786 Dwarf_Sig8 signature;
2787 Dwarf_Bool has_attr = 0;
2788 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) {
2789 if (has_attr) {
2790 Dwarf_Attribute attr_mem;
2791 if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) {
2792 if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) {
2793 return std::string("<no type signature>");
2794 }
2795 }
2796 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
2797 }
2798 }
2799
2800 Dwarf_Unsigned next_cu_header;
2801 Dwarf_Sig8 tu_signature;
2802 std::string result;
2803 bool found = false;
2804
2805 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0,
2806 &next_cu_header, 0, &error) == DW_DLV_OK) {
2807
2808 if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
2809 Dwarf_Die type_cu_die = 0;
2810 if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) {
2811 Dwarf_Die child_die = 0;
2812 if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) {
2813 get_type(dwarf, child_die, result);
2814 found = !result.empty();
2815 dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
2816 }
2817 dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
2818 }
2819 }
2820 }
2821
2822 if (found) {
2823 while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2824 &next_cu_header, 0, &error) == DW_DLV_OK) {
2825 // Reset the cu header state. Unfortunately, libdwarf's
2826 // next_cu_header API keeps its own iterator per Dwarf_Debug
2827 // that can't be reset. We need to keep fetching elements until
2828 // the end.
2829 }
2830 } else {
2831 // If we couldn't resolve the type just print out the signature
2832 std::ostringstream string_stream;
2833 string_stream << "<0x" << std::hex << std::setfill('0');
2834 for (int i = 0; i < 8; ++i) {
2835 string_stream << std::setw(2) << std::hex
2836 << (int)(unsigned char)(signature.signature[i]);
2837 }
2838 string_stream << ">";
2839 result = string_stream.str();
2840 }
2841 return result;
2842 }
2843
2844 struct type_context_t {
2845 bool is_const;
2846 bool is_typedef;
2847 bool has_type;
2848 bool has_name;
2849 std::string text;
2850
2851 type_context_t()
2852 : is_const(false), is_typedef(false), has_type(false), has_name(false) {
2853 }
2854 };
2855
2856 // Types are resolved from right to left: we get the variable name first
2857 // and then all specifiers (like const or pointer) in a chain of DW_AT_type
2858 // DIEs. Call this function recursively until we get a complete type
2859 // string.
2860 static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die,
2861 type_context_t &context) {
2862 char *name;
2863 Dwarf_Error error = DW_DLE_NE;
2864
2865 // typedefs contain also the base type, so we skip it and only
2866 // print the typedef name
2867 if (!context.is_typedef) {
2868 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
2869 if (!context.text.empty()) {
2870 context.text.insert(0, " ");
2871 }
2872 context.text.insert(0, std::string(name));
2873 dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
2874 }
2875 } else {
2876 context.is_typedef = false;
2877 context.has_type = true;
2878 if (context.is_const) {
2879 context.text.insert(0, "const ");
2880 context.is_const = false;
2881 }
2882 }
2883
2884 bool next_type_is_const = false;
2885 bool is_keyword = true;
2886
2887 Dwarf_Half tag = 0;
2888 Dwarf_Bool has_attr = 0;
2889 if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
2890 switch (tag) {
2891 case DW_TAG_structure_type:
2892 case DW_TAG_union_type:
2893 case DW_TAG_class_type:
2894 case DW_TAG_enumeration_type:
2895 context.has_type = true;
2896 if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) ==
2897 DW_DLV_OK) {
2898 // If we have a signature it means the type is defined
2899 // in .debug_types, so we need to load the DIE pointed
2900 // at by the signature and resolve it
2901 if (has_attr) {
2902 std::string type =
2903 get_type_by_signature(fobj.dwarf_handle.get(), die);
2904 if (context.is_const)
2905 type.insert(0, "const ");
2906
2907 if (!context.text.empty())
2908 context.text.insert(0, " ");
2909 context.text.insert(0, type);
2910 }
2911
2912 // Treat enums like typedefs, and skip printing its
2913 // base type
2914 context.is_typedef = (tag == DW_TAG_enumeration_type);
2915 }
2916 break;
2917 case DW_TAG_const_type:
2918 next_type_is_const = true;
2919 break;
2920 case DW_TAG_pointer_type:
2921 context.text.insert(0, "*");
2922 break;
2923 case DW_TAG_reference_type:
2924 context.text.insert(0, "&");
2925 break;
2926 case DW_TAG_restrict_type:
2927 context.text.insert(0, "restrict ");
2928 break;
2929 case DW_TAG_rvalue_reference_type:
2930 context.text.insert(0, "&&");
2931 break;
2932 case DW_TAG_volatile_type:
2933 context.text.insert(0, "volatile ");
2934 break;
2935 case DW_TAG_typedef:
2936 // Propagate the const-ness to the next type
2937 // as typedefs are linked to its base type
2938 next_type_is_const = context.is_const;
2939 context.is_typedef = true;
2940 context.has_type = true;
2941 break;
2942 case DW_TAG_base_type:
2943 context.has_type = true;
2944 break;
2945 case DW_TAG_formal_parameter:
2946 context.has_name = true;
2947 break;
2948 default:
2949 is_keyword = false;
2950 break;
2951 }
2952 }
2953
2954 if (!is_keyword && context.is_const) {
2955 context.text.insert(0, "const ");
2956 }
2957
2958 context.is_const = next_type_is_const;
2959
2960 Dwarf_Die ref =
2961 get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type, true);
2962 if (ref) {
2963 set_parameter_string(fobj, ref, context);
2964 dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
2965 }
2966
2967 if (!context.has_type && context.has_name) {
2968 context.text.insert(0, "void ");
2969 context.has_type = true;
2970 }
2971 }
2972
2973 // Resolve the function return type and parameters
2974 static void set_function_parameters(std::string &function_name,
2975 std::vector<std::string> &ns,
2976 dwarf_fileobject &fobj, Dwarf_Die die) {
2977 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
2978 Dwarf_Error error = DW_DLE_NE;
2979 Dwarf_Die current_die = 0;
2980 std::string parameters;
2981 bool has_spec = true;
2982 // Check if we have a spec DIE. If we do we use it as it contains
2983 // more information, like parameter names.
2984 Dwarf_Die spec_die = get_spec_die(fobj, die);
2985 if (!spec_die) {
2986 has_spec = false;
2987 spec_die = die;
2988 }
2989
2990 std::vector<std::string>::const_iterator it = ns.begin();
2991 std::string ns_name;
2992 for (it = ns.begin(); it < ns.end(); ++it) {
2993 ns_name.append(*it).append("::");
2994 }
2995
2996 if (!ns_name.empty()) {
2997 function_name.insert(0, ns_name);
2998 }
2999
3000 // See if we have a function return type. It can be either on the
3001 // current die or in its spec one (usually true for inlined functions)
3002 std::string return_type =
3003 get_referenced_die_name(dwarf, die, DW_AT_type, true);
3004 if (return_type.empty()) {
3005 return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type, true);
3006 }
3007 if (!return_type.empty()) {
3008 return_type.append(" ");
3009 function_name.insert(0, return_type);
3010 }
3011
3012 if (dwarf_child(spec_die, &current_die, &error) == DW_DLV_OK) {
3013 for (;;) {
3014 Dwarf_Die sibling_die = 0;
3015
3016 Dwarf_Half tag_value;
3017 dwarf_tag(current_die, &tag_value, &error);
3018
3019 if (tag_value == DW_TAG_formal_parameter) {
3020 // Ignore artificial (ie, compiler generated) parameters
3021 bool is_artificial = false;
3022 Dwarf_Attribute attr_mem;
3023 if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) ==
3024 DW_DLV_OK) {
3025 Dwarf_Bool flag = 0;
3026 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3027 is_artificial = flag != 0;
3028 }
3029 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3030 }
3031
3032 if (!is_artificial) {
3033 type_context_t context;
3034 set_parameter_string(fobj, current_die, context);
3035
3036 if (parameters.empty()) {
3037 parameters.append("(");
3038 } else {
3039 parameters.append(", ");
3040 }
3041 parameters.append(context.text);
3042 }
3043 }
3044
3045 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3046 if (result == DW_DLV_ERROR) {
3047 break;
3048 } else if (result == DW_DLV_NO_ENTRY) {
3049 break;
3050 }
3051
3052 if (current_die != die) {
3053 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3054 current_die = 0;
3055 }
3056
3057 current_die = sibling_die;
3058 }
3059 }
3060 if (parameters.empty())
3061 parameters = "(";
3062 parameters.append(")");
3063
3064 // If we got a spec DIE we need to deallocate it
3065 if (has_spec)
3066 dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
3067
3068 function_name.append(parameters);
3069 }
3070
3071 // defined here because in C++98, template function cannot take locally
3072 // defined types... grrr.
3073 struct inliners_search_cb {
3074 void operator()(Dwarf_Die die, std::vector<std::string> &ns) {
3075 Dwarf_Error error = DW_DLE_NE;
3076 Dwarf_Half tag_value;
3077 Dwarf_Attribute attr_mem;
3078 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3079
3080 dwarf_tag(die, &tag_value, &error);
3081
3082 switch (tag_value) {
3083 char *name;
3084 case DW_TAG_subprogram:
3085 if (!trace.source.function.empty())
3086 break;
3087 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
3088 trace.source.function = std::string(name);
3089 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
3090 } else {
3091 // We don't have a function name in this DIE.
3092 // Check if there is a referenced non-defining
3093 // declaration.
3094 trace.source.function =
3095 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
3096 if (trace.source.function.empty()) {
3097 trace.source.function =
3098 get_referenced_die_name(dwarf, die, DW_AT_specification, true);
3099 }
3100 }
3101
3102 // Append the function parameters, if available
3103 set_function_parameters(trace.source.function, ns, fobj, die);
3104
3105 // If the object function name is empty, it's possible that
3106 // there is no dynamic symbol table (maybe the executable
3107 // was stripped or not built with -rdynamic). See if we have
3108 // a DWARF linkage name to use instead. We try both
3109 // linkage_name and MIPS_linkage_name because the MIPS tag
3110 // was the unofficial one until it was adopted in DWARF4.
3111 // Old gcc versions generate MIPS_linkage_name
3112 if (trace.object_function.empty()) {
3113 details::demangler demangler;
3114
3115 if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) !=
3116 DW_DLV_OK) {
3117 if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) !=
3118 DW_DLV_OK) {
3119 break;
3120 }
3121 }
3122
3123 char *linkage;
3124 if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) {
3125 trace.object_function = demangler.demangle(linkage);
3126 dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
3127 }
3128 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3129 }
3130 break;
3131
3132 case DW_TAG_inlined_subroutine:
3133 ResolvedTrace::SourceLoc sloc;
3134
3135 if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
3136 sloc.function = std::string(name);
3137 dwarf_dealloc(dwarf, name, DW_DLA_STRING);
3138 } else {
3139 // We don't have a name for this inlined DIE, it could
3140 // be that there is an abstract origin instead.
3141 // Get the DW_AT_abstract_origin value, which is a
3142 // reference to the source DIE and try to get its name
3143 sloc.function =
3144 get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
3145 }
3146
3147 set_function_parameters(sloc.function, ns, fobj, die);
3148
3149 std::string file = die_call_file(dwarf, die, cu_die);
3150 if (!file.empty())
3151 sloc.filename = file;
3152
3153 Dwarf_Unsigned number = 0;
3154 if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) {
3155 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
3156 sloc.line = number;
3157 }
3158 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3159 }
3160
3161 if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) ==
3162 DW_DLV_OK) {
3163 if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
3164 sloc.col = number;
3165 }
3166 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3167 }
3168
3169 trace.inliners.push_back(sloc);
3170 break;
3171 };
3172 }
3173 ResolvedTrace &trace;
3174 dwarf_fileobject &fobj;
3175 Dwarf_Die cu_die;
3176 inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &f, Dwarf_Die c)
3177 : trace(t), fobj(f), cu_die(c) {}
3178 };
3179
3180 static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj,
3181 Dwarf_Die parent_die, Dwarf_Addr pc,
3182 Dwarf_Die result) {
3183 Dwarf_Die current_die = 0;
3184 Dwarf_Error error = DW_DLE_NE;
3185 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3186
3187 if (dwarf_child(parent_die, &current_die, &error) != DW_DLV_OK) {
3188 return NULL;
3189 }
3190
3191 for (;;) {
3192 Dwarf_Die sibling_die = 0;
3193 Dwarf_Half tag_value;
3194 dwarf_tag(current_die, &tag_value, &error);
3195
3196 switch (tag_value) {
3197 case DW_TAG_subprogram:
3198 case DW_TAG_inlined_subroutine:
3199 if (die_has_pc(fobj, current_die, pc)) {
3200 return current_die;
3201 }
3202 };
3203 bool declaration = false;
3204 Dwarf_Attribute attr_mem;
3205 if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
3206 DW_DLV_OK) {
3207 Dwarf_Bool flag = 0;
3208 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3209 declaration = flag != 0;
3210 }
3211 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3212 }
3213
3214 if (!declaration) {
3215 // let's be curious and look deeper in the tree, functions are
3216 // not necessarily at the first level, but might be nested
3217 // inside a namespace, structure, a function, an inlined
3218 // function etc.
3219 Dwarf_Die die_mem = 0;
3220 Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem);
3221 if (indie) {
3222 result = die_mem;
3223 return result;
3224 }
3225 }
3226
3227 int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3228 if (res == DW_DLV_ERROR) {
3229 return NULL;
3230 } else if (res == DW_DLV_NO_ENTRY) {
3231 break;
3232 }
3233
3234 if (current_die != parent_die) {
3235 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3236 current_die = 0;
3237 }
3238
3239 current_die = sibling_die;
3240 }
3241 return NULL;
3242 }
3243
3244 template <typename CB>
3245 static bool deep_first_search_by_pc(dwarf_fileobject &fobj,
3246 Dwarf_Die parent_die, Dwarf_Addr pc,
3247 std::vector<std::string> &ns, CB cb) {
3248 Dwarf_Die current_die = 0;
3249 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3250 Dwarf_Error error = DW_DLE_NE;
3251
3252 if (dwarf_child(parent_die, &current_die, &error) != DW_DLV_OK) {
3253 return false;
3254 }
3255
3256 bool branch_has_pc = false;
3257 bool has_namespace = false;
3258 for (;;) {
3259 Dwarf_Die sibling_die = 0;
3260
3261 Dwarf_Half tag;
3262 if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
3263 if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
3264 char *ns_name = NULL;
3265 if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) {
3266 if (ns_name) {
3267 ns.push_back(std::string(ns_name));
3268 } else {
3269 ns.push_back("<unknown>");
3270 }
3271 dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
3272 } else {
3273 ns.push_back("<unknown>");
3274 }
3275 has_namespace = true;
3276 }
3277 }
3278
3279 bool declaration = false;
3280 Dwarf_Attribute attr_mem;
3281 if (tag != DW_TAG_class_type &&
3282 dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
3283 DW_DLV_OK) {
3284 Dwarf_Bool flag = 0;
3285 if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
3286 declaration = flag != 0;
3287 }
3288 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3289 }
3290
3291 if (!declaration) {
3292 // let's be curious and look deeper in the tree, function are
3293 // not necessarily at the first level, but might be nested
3294 // inside a namespace, structure, a function, an inlined
3295 // function etc.
3296 branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb);
3297 }
3298
3299 if (!branch_has_pc) {
3300 branch_has_pc = die_has_pc(fobj, current_die, pc);
3301 }
3302
3303 if (branch_has_pc) {
3304 cb(current_die, ns);
3305 }
3306
3307 int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
3308 if (result == DW_DLV_ERROR) {
3309 return false;
3310 } else if (result == DW_DLV_NO_ENTRY) {
3311 break;
3312 }
3313
3314 if (current_die != parent_die) {
3315 dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
3316 current_die = 0;
3317 }
3318
3319 if (has_namespace) {
3320 has_namespace = false;
3321 ns.pop_back();
3322 }
3323 current_die = sibling_die;
3324 }
3325
3326 if (has_namespace) {
3327 ns.pop_back();
3328 }
3329 return branch_has_pc;
3330 }
3331
3332 static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die,
3333 Dwarf_Die cu_die) {
3334 Dwarf_Attribute attr_mem;
3335 Dwarf_Error error = DW_DLE_NE;
3336 Dwarf_Unsigned file_index;
3337
3338 std::string file;
3339
3340 if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
3341 if (dwarf_formudata(attr_mem, &file_index, &error) != DW_DLV_OK) {
3342 file_index = 0;
3343 }
3344 dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
3345
3346 if (file_index == 0) {
3347 return file;
3348 }
3349
3350 char **srcfiles = 0;
3351 Dwarf_Signed file_count = 0;
3352 if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) {
3353 if (file_count > 0 && file_index <= static_cast<Dwarf_Unsigned>(file_count)) {
3354 file = std::string(srcfiles[file_index - 1]);
3355 }
3356
3357 // Deallocate all strings!
3358 for (int i = 0; i < file_count; ++i) {
3359 dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
3360 }
3361 dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
3362 }
3363 }
3364 return file;
3365 }
3366
3367 Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) {
3368 // Let's get to work! First see if we have a debug_aranges section so
3369 // we can speed up the search
3370
3371 Dwarf_Debug dwarf = fobj.dwarf_handle.get();
3372 Dwarf_Error error = DW_DLE_NE;
3373 Dwarf_Arange *aranges;
3374 Dwarf_Signed arange_count;
3375
3376 Dwarf_Die returnDie;
3377 bool found = false;
3378 if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) !=
3379 DW_DLV_OK) {
3380 aranges = NULL;
3381 }
3382
3383 if (aranges) {
3384 // We have aranges. Get the one where our address is.
3385 Dwarf_Arange arange;
3386 if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) ==
3387 DW_DLV_OK) {
3388
3389 // We found our address. Get the compilation-unit DIE offset
3390 // represented by the given address range.
3391 Dwarf_Off cu_die_offset;
3392 if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) ==
3393 DW_DLV_OK) {
3394 // Get the DIE at the offset returned by the aranges search.
3395 // We set is_info to 1 to specify that the offset is from
3396 // the .debug_info section (and not .debug_types)
3397 int dwarf_result =
3398 dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error);
3399
3400 found = dwarf_result == DW_DLV_OK;
3401 }
3402 dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
3403 }
3404 }
3405
3406 if (found)
3407 return returnDie; // The caller is responsible for freeing the die
3408
3409 // The search for aranges failed. Try to find our address by scanning
3410 // all compilation units.
3411 Dwarf_Unsigned next_cu_header;
3412 Dwarf_Half tag = 0;
3413 returnDie = 0;
3414
3415 while (!found &&
3416 dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3417 &next_cu_header, 0, &error) == DW_DLV_OK) {
3418
3419 if (returnDie)
3420 dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
3421
3422 if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
3423 if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) &&
3424 tag == DW_TAG_compile_unit) {
3425 if (die_has_pc(fobj, returnDie, addr)) {
3426 found = true;
3427 }
3428 }
3429 }
3430 }
3431
3432 if (found) {
3433 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3434 &next_cu_header, 0, &error) == DW_DLV_OK) {
3435 // Reset the cu header state. Libdwarf's next_cu_header API
3436 // keeps its own iterator per Dwarf_Debug that can't be reset.
3437 // We need to keep fetching elements until the end.
3438 }
3439 }
3440
3441 if (found)
3442 return returnDie;
3443
3444 // We couldn't find any compilation units with ranges or a high/low pc.
3445 // Try again by looking at all DIEs in all compilation units.
3446 Dwarf_Die cudie;
3447 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3448 &next_cu_header, 0, &error) == DW_DLV_OK) {
3449 if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
3450 Dwarf_Die die_mem = 0;
3451 Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem);
3452
3453 if (resultDie) {
3454 found = true;
3455 break;
3456 }
3457 }
3458 }
3459
3460 if (found) {
3461 while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3462 &next_cu_header, 0, &error) == DW_DLV_OK) {
3463 // Reset the cu header state. Libdwarf's next_cu_header API
3464 // keeps its own iterator per Dwarf_Debug that can't be reset.
3465 // We need to keep fetching elements until the end.
3466 }
3467 }
3468
3469 if (found)
3470 return cudie;
3471
3472 // We failed.
3473 return NULL;
3474 }
3475 };
3476 #endif // BACKWARD_HAS_DWARF == 1
3477
3478 template <>
3479 class TraceResolverImpl<system_tag::linux_tag>
3480 : public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
3481
3482 #endif // BACKWARD_SYSTEM_LINUX
3483
3484 #ifdef BACKWARD_SYSTEM_DARWIN
3485
3486 template <typename STACKTRACE_TAG> class TraceResolverDarwinImpl;
3487
3488 template <>
3489 class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>
3490 : public TraceResolverImplBase {
3491 public:
3492 void load_addresses(void *const*addresses, int address_count) override {
3493 if (address_count == 0) {
3494 return;
3495 }
3496 _symbols.reset(backtrace_symbols(addresses, address_count));
3497 }
3498
3499 ResolvedTrace resolve(ResolvedTrace trace) override {
3500 // parse:
3501 // <n> <file> <addr> <mangled-name> + <offset>
3502 char *filename = _symbols[trace.idx];
3503
3504 // skip "<n> "
3505 while (*filename && *filename != ' ')
3506 filename++;
3507 while (*filename == ' ')
3508 filename++;
3509
3510 // find start of <mangled-name> from end (<file> may contain a space)
3511 char *p = filename + strlen(filename) - 1;
3512 // skip to start of " + <offset>"
3513 while (p > filename && *p != ' ')
3514 p--;
3515 while (p > filename && *p == ' ')
3516 p--;
3517 while (p > filename && *p != ' ')
3518 p--;
3519 while (p > filename && *p == ' ')
3520 p--;
3521 char *funcname_end = p + 1;
3522
3523 // skip to start of "<manged-name>"
3524 while (p > filename && *p != ' ')
3525 p--;
3526 char *funcname = p + 1;
3527
3528 // skip to start of " <addr> "
3529 while (p > filename && *p == ' ')
3530 p--;
3531 while (p > filename && *p != ' ')
3532 p--;
3533 while (p > filename && *p == ' ')
3534 p--;
3535
3536 // skip "<file>", handling the case where it contains a
3537 char *filename_end = p + 1;
3538 if (p == filename) {
3539 // something went wrong, give up
3540 filename_end = filename + strlen(filename);
3541 funcname = filename_end;
3542 }
3543 trace.object_filename.assign(
3544 filename, filename_end); // ok even if filename_end is the ending \0
3545 // (then we assign entire string)
3546
3547 if (*funcname) { // if it's not end of string
3548 *funcname_end = '\0';
3549
3550 trace.object_function = this->demangle(funcname);
3551 trace.object_function += " ";
3552 trace.object_function += (funcname_end + 1);
3553 trace.source.function = trace.object_function; // we cannot do better.
3554 }
3555 return trace;
3556 }
3557
3558 private:
3559 details::handle<char **> _symbols;
3560 };
3561
3562 template <>
3563 class TraceResolverImpl<system_tag::darwin_tag>
3564 : public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
3565
3566 #endif // BACKWARD_SYSTEM_DARWIN
3567
3568 #ifdef BACKWARD_SYSTEM_WINDOWS
3569
3570 // Load all symbol info
3571 // Based on:
3572 // https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
3573
3574 struct module_data {
3575 std::string image_name;
3576 std::string module_name;
3577 void *base_address;
3578 DWORD load_size;
3579 };
3580
3581 class get_mod_info {
3582 HANDLE process;
3583 static const int buffer_length = 4096;
3584
3585 public:
3586 get_mod_info(HANDLE h) : process(h) {}
3587
3588 module_data operator()(HMODULE module) {
3589 module_data ret;
3590 char temp[buffer_length];
3591 MODULEINFO mi;
3592
3593 GetModuleInformation(process, module, &mi, sizeof(mi));
3594 ret.base_address = mi.lpBaseOfDll;
3595 ret.load_size = mi.SizeOfImage;
3596
3597 GetModuleFileNameExA(process, module, temp, sizeof(temp));
3598 ret.image_name = temp;
3599 GetModuleBaseNameA(process, module, temp, sizeof(temp));
3600 ret.module_name = temp;
3601 std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
3602 std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
3603 SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address,
3604 ret.load_size);
3605 return ret;
3606 }
3607 };
3608
3609 template <> class TraceResolverImpl<system_tag::windows_tag>
3610 : public TraceResolverImplBase {
3611 public:
3612 TraceResolverImpl() {
3613
3614 HANDLE process = GetCurrentProcess();
3615
3616 std::vector<module_data> modules;
3617 DWORD cbNeeded;
3618 std::vector<HMODULE> module_handles(1);
3619 SymInitialize(process, NULL, false);
3620 DWORD symOptions = SymGetOptions();
3621 symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME;
3622 SymSetOptions(symOptions);
3623 EnumProcessModules(process, &module_handles[0],
3624 module_handles.size() * sizeof(HMODULE), &cbNeeded);
3625 module_handles.resize(cbNeeded / sizeof(HMODULE));
3626 EnumProcessModules(process, &module_handles[0],
3627 module_handles.size() * sizeof(HMODULE), &cbNeeded);
3628 std::transform(module_handles.begin(), module_handles.end(),
3629 std::back_inserter(modules), get_mod_info(process));
3630 void *base = modules[0].base_address;
3631 IMAGE_NT_HEADERS *h = ImageNtHeader(base);
3632 image_type = h->FileHeader.Machine;
3633 }
3634
3635 static const int max_sym_len = 255;
3636 struct symbol_t {
3637 SYMBOL_INFO sym;
3638 char buffer[max_sym_len];
3639 } sym;
3640
3641 DWORD64 displacement;
3642
3643 ResolvedTrace resolve(ResolvedTrace t) override {
3644 HANDLE process = GetCurrentProcess();
3645
3646 char name[256];
3647
3648 memset(&sym, 0, sizeof(sym));
3649 sym.sym.SizeOfStruct = sizeof(SYMBOL_INFO);
3650 sym.sym.MaxNameLen = max_sym_len;
3651
3652 if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) {
3653 // TODO: error handling everywhere
3654 char* lpMsgBuf;
3655 DWORD dw = GetLastError();
3656
3657 if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
3658 FORMAT_MESSAGE_FROM_SYSTEM |
3659 FORMAT_MESSAGE_IGNORE_INSERTS,
3660 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
3661 (char*)&lpMsgBuf, 0, NULL)) {
3662 std::fprintf(stderr, "%s\n", lpMsgBuf);
3663 LocalFree(lpMsgBuf);
3664 }
3665
3666 // abort();
3667 }
3668 UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE);
3669
3670 DWORD offset = 0;
3671 IMAGEHLP_LINE line;
3672 if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) {
3673 t.object_filename = line.FileName;
3674 t.source.filename = line.FileName;
3675 t.source.line = line.LineNumber;
3676 t.source.col = offset;
3677 }
3678
3679 t.source.function = name;
3680 t.object_filename = "";
3681 t.object_function = name;
3682
3683 return t;
3684 }
3685
3686 DWORD machine_type() const { return image_type; }
3687
3688 private:
3689 DWORD image_type;
3690 };
3691
3692 #endif
3693
3694 class TraceResolver : public TraceResolverImpl<system_tag::current_tag> {};
3695
3696 /*************** CODE SNIPPET ***************/
3697
3698 class SourceFile {
3699 public:
3700 typedef std::vector<std::pair<unsigned, std::string> > lines_t;
3701
3702 SourceFile() {}
3703 SourceFile(const std::string &path) {
3704 // 1. If BACKWARD_CXX_SOURCE_PREFIXES is set then assume it contains
3705 // a colon-separated list of path prefixes. Try prepending each
3706 // to the given path until a valid file is found.
3707 const std::vector<std::string> &prefixes = get_paths_from_env_variable();
3708 for (size_t i = 0; i < prefixes.size(); ++i) {
3709 // Double slashes (//) should not be a problem.
3710 std::string new_path = prefixes[i] + '/' + path;
3711 _file.reset(new std::ifstream(new_path.c_str()));
3712 if (is_open())
3713 break;
3714 }
3715 // 2. If no valid file found then fallback to opening the path as-is.
3716 if (!_file || !is_open()) {
3717 _file.reset(new std::ifstream(path.c_str()));
3718 }
3719 }
3720 bool is_open() const { return _file->is_open(); }
3721
3722 lines_t &get_lines(unsigned line_start, unsigned line_count, lines_t &lines) {
3723 using namespace std;
3724 // This function make uses of the dumbest algo ever:
3725 // 1) seek(0)
3726 // 2) read lines one by one and discard until line_start
3727 // 3) read line one by one until line_start + line_count
3728 //
3729 // If you are getting snippets many time from the same file, it is
3730 // somewhat a waste of CPU, feel free to benchmark and propose a
3731 // better solution ;)
3732
3733 _file->clear();
3734 _file->seekg(0);
3735 string line;
3736 unsigned line_idx;
3737
3738 for (line_idx = 1; line_idx < line_start; ++line_idx) {
3739 std::getline(*_file, line);
3740 if (!*_file) {
3741 return lines;
3742 }
3743 }
3744
3745 // think of it like a lambda in C++98 ;)
3746 // but look, I will reuse it two times!
3747 // What a good boy am I.
3748 struct isspace {
3749 bool operator()(char c) { return std::isspace(c); }
3750 };
3751
3752 bool started = false;
3753 for (; line_idx < line_start + line_count; ++line_idx) {
3754 getline(*_file, line);
3755 if (!*_file) {
3756 return lines;
3757 }
3758 if (!started) {
3759 if (std::find_if(line.begin(), line.end(), not_isspace()) == line.end())
3760 continue;
3761 started = true;
3762 }
3763 lines.push_back(make_pair(line_idx, line));
3764 }
3765
3766 lines.erase(
3767 std::find_if(lines.rbegin(), lines.rend(), not_isempty()).base(),
3768 lines.end());
3769 return lines;
3770 }
3771
3772 lines_t get_lines(unsigned line_start, unsigned line_count) {
3773 lines_t lines;
3774 return get_lines(line_start, line_count, lines);
3775 }
3776
3777 // there is no find_if_not in C++98, lets do something crappy to
3778 // workaround.
3779 struct not_isspace {
3780 bool operator()(char c) { return !std::isspace(c); }
3781 };
3782 // and define this one here because C++98 is not happy with local defined
3783 // struct passed to template functions, fuuuu.
3784 struct not_isempty {
3785 bool operator()(const lines_t::value_type &p) {
3786 return !(std::find_if(p.second.begin(), p.second.end(), not_isspace()) ==
3787 p.second.end());
3788 }
3789 };
3790
3791 void swap(SourceFile &b) { _file.swap(b._file); }
3792
3793 #ifdef BACKWARD_ATLEAST_CXX11
3794 SourceFile(SourceFile &&from) : _file(nullptr) { swap(from); }
3795 SourceFile &operator=(SourceFile &&from) {
3796 swap(from);
3797 return *this;
3798 }
3799 #else
3800 explicit SourceFile(const SourceFile &from) {
3801 // some sort of poor man's move semantic.
3802 swap(const_cast<SourceFile &>(from));
3803 }
3804 SourceFile &operator=(const SourceFile &from) {
3805 // some sort of poor man's move semantic.
3806 swap(const_cast<SourceFile &>(from));
3807 return *this;
3808 }
3809 #endif
3810
3811 private:
3812 details::handle<std::ifstream *, details::default_delete<std::ifstream *> >
3813 _file;
3814
3815 std::vector<std::string> get_paths_from_env_variable_impl() {
3816 std::vector<std::string> paths;
3817 const char *prefixes_str = std::getenv("BACKWARD_CXX_SOURCE_PREFIXES");
3818 if (prefixes_str && prefixes_str[0]) {
3819 paths = details::split_source_prefixes(prefixes_str);
3820 }
3821 return paths;
3822 }
3823
3824 const std::vector<std::string> &get_paths_from_env_variable() {
3825 static std::vector<std::string> paths = get_paths_from_env_variable_impl();
3826 return paths;
3827 }
3828
3829 #ifdef BACKWARD_ATLEAST_CXX11
3830 SourceFile(const SourceFile &) = delete;
3831 SourceFile &operator=(const SourceFile &) = delete;
3832 #endif
3833 };
3834
3835 class SnippetFactory {
3836 public:
3837 typedef SourceFile::lines_t lines_t;
3838
3839 lines_t get_snippet(const std::string &filename, unsigned line_start,
3840 unsigned context_size) {
3841
3842 SourceFile &src_file = get_src_file(filename);
3843 unsigned start = line_start - context_size / 2;
3844 return src_file.get_lines(start, context_size);
3845 }
3846
3847 lines_t get_combined_snippet(const std::string &filename_a, unsigned line_a,
3848 const std::string &filename_b, unsigned line_b,
3849 unsigned context_size) {
3850 SourceFile &src_file_a = get_src_file(filename_a);
3851 SourceFile &src_file_b = get_src_file(filename_b);
3852
3853 lines_t lines =
3854 src_file_a.get_lines(line_a - context_size / 4, context_size / 2);
3855 src_file_b.get_lines(line_b - context_size / 4, context_size / 2, lines);
3856 return lines;
3857 }
3858
3859 lines_t get_coalesced_snippet(const std::string &filename, unsigned line_a,
3860 unsigned line_b, unsigned context_size) {
3861 SourceFile &src_file = get_src_file(filename);
3862
3863 using std::max;
3864 using std::min;
3865 unsigned a = min(line_a, line_b);
3866 unsigned b = max(line_a, line_b);
3867
3868 if ((b - a) < (context_size / 3)) {
3869 return src_file.get_lines((a + b - context_size + 1) / 2, context_size);
3870 }
3871
3872 lines_t lines = src_file.get_lines(a - context_size / 4, context_size / 2);
3873 src_file.get_lines(b - context_size / 4, context_size / 2, lines);
3874 return lines;
3875 }
3876
3877 private:
3878 typedef details::hashtable<std::string, SourceFile>::type src_files_t;
3879 src_files_t _src_files;
3880
3881 SourceFile &get_src_file(const std::string &filename) {
3882 src_files_t::iterator it = _src_files.find(filename);
3883 if (it != _src_files.end()) {
3884 return it->second;
3885 }
3886 SourceFile &new_src_file = _src_files[filename];
3887 new_src_file = SourceFile(filename);
3888 return new_src_file;
3889 }
3890 };
3891
3892 /*************** PRINTER ***************/
3893
3894 namespace ColorMode {
3895 enum type { automatic, never, always };
3896 }
3897
3898 class cfile_streambuf : public std::streambuf {
3899 public:
3900 cfile_streambuf(FILE *_sink) : sink(_sink) {}
3901 int_type underflow() override { return traits_type::eof(); }
3902 int_type overflow(int_type ch) override {
3903 if (traits_type::not_eof(ch) && fputc(ch, sink) != EOF) {
3904 return ch;
3905 }
3906 return traits_type::eof();
3907 }
3908
3909 std::streamsize xsputn(const char_type *s, std::streamsize count) override {
3910 return static_cast<std::streamsize>(
3911 fwrite(s, sizeof *s, static_cast<size_t>(count), sink));
3912 }
3913
3914 #ifdef BACKWARD_ATLEAST_CXX11
3915 public:
3916 cfile_streambuf(const cfile_streambuf &) = delete;
3917 cfile_streambuf &operator=(const cfile_streambuf &) = delete;
3918 #else
3919 private:
3920 cfile_streambuf(const cfile_streambuf &);
3921 cfile_streambuf &operator=(const cfile_streambuf &);
3922 #endif
3923
3924 private:
3925 FILE *sink;
3926 std::vector<char> buffer;
3927 };
3928
3929 #ifdef BACKWARD_SYSTEM_LINUX
3930
3931 namespace Color {
3932 enum type { yellow = 33, purple = 35, reset = 39 };
3933 } // namespace Color
3934
3935 class Colorize {
3936 public:
3937 Colorize(std::ostream &os) : _os(os), _reset(false), _enabled(false) {}
3938
3939 void activate(ColorMode::type mode) { _enabled = mode == ColorMode::always; }
3940
3941 void activate(ColorMode::type mode, FILE *fp) { activate(mode, fileno(fp)); }
3942
3943 void set_color(Color::type ccode) {
3944 if (!_enabled)
3945 return;
3946
3947 // I assume that the terminal can handle basic colors. Seriously I
3948 // don't want to deal with all the termcap shit.
3949 _os << "\033[" << static_cast<int>(ccode) << "m";
3950 _reset = (ccode != Color::reset);
3951 }
3952
3953 ~Colorize() {
3954 if (_reset) {
3955 set_color(Color::reset);
3956 }
3957 }
3958
3959 private:
3960 void activate(ColorMode::type mode, int fd) {
3961 activate(mode == ColorMode::automatic && isatty(fd) ? ColorMode::always
3962 : mode);
3963 }
3964
3965 std::ostream &_os;
3966 bool _reset;
3967 bool _enabled;
3968 };
3969
3970 #else // ndef BACKWARD_SYSTEM_LINUX
3971
3972 namespace Color {
3973 enum type { yellow = 0, purple = 0, reset = 0 };
3974 } // namespace Color
3975
3976 class Colorize {
3977 public:
3978 Colorize(std::ostream &) {}
3979 void activate(ColorMode::type) {}
3980 void activate(ColorMode::type, FILE *) {}
3981 void set_color(Color::type) {}
3982 };
3983
3984 #endif // BACKWARD_SYSTEM_LINUX
3985
3986 class Printer {
3987 public:
3988 bool snippet;
3989 ColorMode::type color_mode;
3990 bool address;
3991 bool object;
3992 int inliner_context_size;
3993 int trace_context_size;
3994
3995 Printer()
3996 : snippet(true), color_mode(ColorMode::automatic), address(false),
3997 object(false), inliner_context_size(5), trace_context_size(7) {}
3998
3999 template <typename ST> FILE *print(ST &st, FILE *fp = stderr) {
4000 cfile_streambuf obuf(fp);
4001 std::ostream os(&obuf);
4002 Colorize colorize(os);
4003 colorize.activate(color_mode, fp);
4004 print_stacktrace(st, os, colorize);
4005 return fp;
4006 }
4007
4008 template <typename ST> std::ostream &print(ST &st, std::ostream &os) {
4009 Colorize colorize(os);
4010 colorize.activate(color_mode);
4011 print_stacktrace(st, os, colorize);
4012 return os;
4013 }
4014
4015 template <typename IT>
4016 FILE *print(IT begin, IT end, FILE *fp = stderr, size_t thread_id = 0) {
4017 cfile_streambuf obuf(fp);
4018 std::ostream os(&obuf);
4019 Colorize colorize(os);
4020 colorize.activate(color_mode, fp);
4021 print_stacktrace(begin, end, os, thread_id, colorize);
4022 return fp;
4023 }
4024
4025 template <typename IT>
4026 std::ostream &print(IT begin, IT end, std::ostream &os,
4027 size_t thread_id = 0) {
4028 Colorize colorize(os);
4029 colorize.activate(color_mode);
4030 print_stacktrace(begin, end, os, thread_id, colorize);
4031 return os;
4032 }
4033
4034 TraceResolver const &resolver() const { return _resolver; }
4035
4036 private:
4037 TraceResolver _resolver;
4038 SnippetFactory _snippets;
4039
4040 template <typename ST>
4041 void print_stacktrace(ST &st, std::ostream &os, Colorize &colorize) {
4042 print_header(os, st.thread_id());
4043 _resolver.load_stacktrace(st);
4044 for (size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
4045 print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize);
4046 }
4047 }
4048
4049 template <typename IT>
4050 void print_stacktrace(IT begin, IT end, std::ostream &os, size_t thread_id,
4051 Colorize &colorize) {
4052 print_header(os, thread_id);
4053 for (; begin != end; ++begin) {
4054 print_trace(os, *begin, colorize);
4055 }
4056 }
4057
4058 void print_header(std::ostream &os, size_t thread_id) {
4059 os << "Stack trace (most recent call last)";
4060 if (thread_id) {
4061 os << " in thread " << thread_id;
4062 }
4063 os << ":\n";
4064 }
4065
4066 void print_trace(std::ostream &os, const ResolvedTrace &trace,
4067 Colorize &colorize) {
4068 os << "#" << std::left << std::setw(2) << trace.idx << std::right;
4069 bool already_indented = true;
4070
4071 if (!trace.source.filename.size() || object) {
4072 os << " Object \"" << trace.object_filename << "\", at " << trace.addr
4073 << ", in " << trace.object_function << "\n";
4074 already_indented = false;
4075 }
4076
4077 for (size_t inliner_idx = trace.inliners.size(); inliner_idx > 0;
4078 --inliner_idx) {
4079 if (!already_indented) {
4080 os << " ";
4081 }
4082 const ResolvedTrace::SourceLoc &inliner_loc =
4083 trace.inliners[inliner_idx - 1];
4084 print_source_loc(os, " | ", inliner_loc);
4085 if (snippet) {
4086 print_snippet(os, " | ", inliner_loc, colorize, Color::purple,
4087 inliner_context_size);
4088 }
4089 already_indented = false;
4090 }
4091
4092 if (trace.source.filename.size()) {
4093 if (!already_indented) {
4094 os << " ";
4095 }
4096 print_source_loc(os, " ", trace.source, trace.addr);
4097 if (snippet) {
4098 print_snippet(os, " ", trace.source, colorize, Color::yellow,
4099 trace_context_size);
4100 }
4101 }
4102 }
4103
4104 void print_snippet(std::ostream &os, const char *indent,
4105 const ResolvedTrace::SourceLoc &source_loc,
4106 Colorize &colorize, Color::type color_code,
4107 int context_size) {
4108 using namespace std;
4109 typedef SnippetFactory::lines_t lines_t;
4110
4111 lines_t lines = _snippets.get_snippet(source_loc.filename, source_loc.line,
4112 static_cast<unsigned>(context_size));
4113
4114 for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) {
4115 if (it->first == source_loc.line) {
4116 colorize.set_color(color_code);
4117 os << indent << ">";
4118 } else {
4119 os << indent << " ";
4120 }
4121 os << std::setw(4) << it->first << ": " << it->second << "\n";
4122 if (it->first == source_loc.line) {
4123 colorize.set_color(Color::reset);
4124 }
4125 }
4126 }
4127
4128 void print_source_loc(std::ostream &os, const char *indent,
4129 const ResolvedTrace::SourceLoc &source_loc,
4130 void *addr = nullptr) {
4131 os << indent << "Source \"" << source_loc.filename << "\", line "
4132 << source_loc.line << ", in " << source_loc.function;
4133
4134 if (address && addr != nullptr) {
4135 os << " [" << addr << "]";
4136 }
4137 os << "\n";
4138 }
4139 };
4140
4141 /*************** SIGNALS HANDLING ***************/
4142
4143 #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
4144
4145 class SignalHandling {
4146 public:
4147 static std::vector<int> make_default_signals() {
4148 const int posix_signals[] = {
4149 // Signals for which the default action is "Core".
4150 SIGABRT, // Abort signal from abort(3)
4151 SIGBUS, // Bus error (bad memory access)
4152 SIGFPE, // Floating point exception
4153 SIGILL, // Illegal Instruction
4154 SIGIOT, // IOT trap. A synonym for SIGABRT
4155 SIGQUIT, // Quit from keyboard
4156 SIGSEGV, // Invalid memory reference
4157 SIGSYS, // Bad argument to routine (SVr4)
4158 SIGTRAP, // Trace/breakpoint trap
4159 SIGXCPU, // CPU time limit exceeded (4.2BSD)
4160 SIGXFSZ, // File size limit exceeded (4.2BSD)
4161 #if defined(BACKWARD_SYSTEM_DARWIN)
4162 SIGEMT, // emulation instruction executed
4163 #endif
4164 };
4165 return std::vector<int>(posix_signals,
4166 posix_signals +
4167 sizeof posix_signals / sizeof posix_signals[0]);
4168 }
4169
4170 SignalHandling(const std::vector<int> &posix_signals = make_default_signals())
4171 : _loaded(false) {
4172 bool success = true;
4173
4174 const size_t stack_size = 1024 * 1024 * 8;
4175 _stack_content.reset(static_cast<char *>(malloc(stack_size)));
4176 if (_stack_content) {
4177 stack_t ss;
4178 ss.ss_sp = _stack_content.get();
4179 ss.ss_size = stack_size;
4180 ss.ss_flags = 0;
4181 if (sigaltstack(&ss, nullptr) < 0) {
4182 success = false;
4183 }
4184 } else {
4185 success = false;
4186 }
4187
4188 for (size_t i = 0; i < posix_signals.size(); ++i) {
4189 struct sigaction action;
4190 memset(&action, 0, sizeof action);
4191 action.sa_flags =
4192 static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
4193 sigfillset(&action.sa_mask);
4194 sigdelset(&action.sa_mask, posix_signals[i]);
4195 #if defined(__clang__)
4196 #pragma clang diagnostic push
4197 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
4198 #endif
4199 action.sa_sigaction = &sig_handler;
4200 #if defined(__clang__)
4201 #pragma clang diagnostic pop
4202 #endif
4203
4204 int r = sigaction(posix_signals[i], &action, nullptr);
4205 if (r < 0)
4206 success = false;
4207 }
4208
4209 _loaded = success;
4210 }
4211
4212 bool loaded() const { return _loaded; }
4213
4214 static void handleSignal(int, siginfo_t *info, void *_ctx) {
4215 ucontext_t *uctx = static_cast<ucontext_t *>(_ctx);
4216
4217 StackTrace st;
4218 void *error_addr = nullptr;
4219 #ifdef REG_RIP // x86_64
4220 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
4221 #elif defined(REG_EIP) // x86_32
4222 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
4223 #elif defined(__arm__)
4224 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.arm_pc);
4225 #elif defined(__aarch64__)
4226 #if defined(__APPLE__)
4227 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__pc);
4228 #else
4229 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.pc);
4230 #endif
4231 #elif defined(__mips__)
4232 error_addr = reinterpret_cast<void *>(
4233 reinterpret_cast<struct sigcontext *>(&uctx->uc_mcontext)->sc_pc);
4234 #elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
4235 defined(__POWERPC__)
4236 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.regs->nip);
4237 #elif defined(__riscv)
4238 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.__gregs[REG_PC]);
4239 #elif defined(__s390x__)
4240 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.psw.addr);
4241 #elif defined(__APPLE__) && defined(__x86_64__)
4242 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__rip);
4243 #elif defined(__APPLE__)
4244 error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__eip);
4245 #else
4246 #warning ":/ sorry, ain't know no nothing none not of your architecture!"
4247 #endif
4248 if (error_addr) {
4249 st.load_from(error_addr, 32, reinterpret_cast<void *>(uctx),
4250 info->si_addr);
4251 } else {
4252 st.load_here(32, reinterpret_cast<void *>(uctx), info->si_addr);
4253 }
4254
4255 #ifdef _WIN32
4256 MessageBox(NULL,"Error","Furnace has crashed! please report this to the issue tracker immediately:\r\nhttps://github.com/tildearrow/furnace/issues/new\r\n\r\na file called furnace_crash.txt will be created in your user directory.\r\nthis will be important for locating the origin of the crash.\r\n\r\nif Furnace keeps crashing and you believe it is caused by a configuration problem, you may start Furnace with the -safemode parameter.",MB_OK|MB_ICONERROR);
4257 std::string crashLocation;
4258 char* userProfile=getenv("USERPROFILE");
4259 if (userProfile==NULL) {
4260 crashLocation="C:\\furnace_crash.txt";
4261 } else {
4262 crashLocation=userProfile;
4263 crashLocation+="\\furnace_crash.txt";
4264 }
4265 FILE* crashDump=fopen(crashLocation.c_str(),"w");
4266 #else
4267 FILE* crashDump=fopen("/tmp/furnace_crash.txt","w");
4268 #endif
4269
4270 Printer printer;
4271 printer.address = true;
4272 printer.print(st, stderr);
4273
4274 if (crashDump!=NULL) {
4275 Printer printer;
4276 printer.address = true;
4277 printer.print(st, crashDump);
4278 fclose(crashDump);
4279 } else {
4280 #ifdef _WIN32
4281 std::string str;
4282 Printer failedPrinter;
4283 failedPrinter.address = true;
4284 failedPrinter.print(st, str);
4285 str+="\r\ncould not open furnace_crash.txt!\r\nplease take a screenshot of this error message box!";
4286 fprintf(stderr,"NOTICE: could not open furnace_crash.txt!\n");
4287 MessageBox(NULL,"Error",str.c_str(),MB_OK|MB_ICONERROR);
4288 #endif
4289 }
4290
4291 #if (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 700) || \
4292 (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200809L)
4293 psiginfo(info, nullptr);
4294 #else
4295 (void)info;
4296 #endif
4297 }
4298
4299 private:
4300 details::handle<char *> _stack_content;
4301 bool _loaded;
4302
4303 #ifdef __GNUC__
4304 __attribute__((noreturn))
4305 #endif
4306 static void
4307 sig_handler(int signo, siginfo_t *info, void *_ctx) {
4308 handleSignal(signo, info, _ctx);
4309
4310 // try to forward the signal.
4311 raise(info->si_signo);
4312
4313 // terminate the process immediately.
4314 puts("watf? exit");
4315 _exit(EXIT_FAILURE);
4316 }
4317 };
4318
4319 #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
4320
4321 #ifdef BACKWARD_SYSTEM_WINDOWS
4322
4323 class SignalHandling {
4324 public:
4325 SignalHandling(const std::vector<int> & = std::vector<int>())
4326 : reporter_thread_([]() {
4327 /* We handle crashes in a utility thread:
4328 backward structures and some Windows functions called here
4329 need stack space, which we do not have when we encounter a
4330 stack overflow.
4331 To support reporting stack traces during a stack overflow,
4332 we create a utility thread at startup, which waits until a
4333 crash happens or the program exits normally. */
4334
4335 {
4336 std::unique_lock<std::mutex> lk(mtx());
4337 cv().wait(lk, [] { return crashed() != crash_status::running; });
4338 }
4339 if (crashed() == crash_status::crashed) {
4340 handle_stacktrace(skip_recs());
4341 }
4342 {
4343 std::unique_lock<std::mutex> lk(mtx());
4344 crashed() = crash_status::ending;
4345 }
4346 cv().notify_one();
4347 }) {
4348 SetUnhandledExceptionFilter(crash_handler);
4349
4350 signal(SIGABRT, signal_handler);
4351 #ifdef _MSC_VER
4352 // TODO: fix for MinGW
4353 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
4354 #endif
4355
4356 std::set_terminate(&terminator);
4357 #ifndef BACKWARD_ATLEAST_CXX17
4358 std::set_unexpected(&terminator);
4359 #endif
4360 _set_purecall_handler(&terminator);
4361 _set_invalid_parameter_handler(&invalid_parameter_handler);
4362 }
4363 bool loaded() const { return true; }
4364
4365 ~SignalHandling() {
4366 {
4367 std::unique_lock<std::mutex> lk(mtx());
4368 crashed() = crash_status::normal_exit;
4369 }
4370
4371 cv().notify_one();
4372
4373 reporter_thread_.join();
4374 }
4375
4376 private:
4377 static CONTEXT *ctx() {
4378 static CONTEXT data;
4379 return &data;
4380 }
4381
4382 enum class crash_status { running, crashed, normal_exit, ending };
4383
4384 static crash_status &crashed() {
4385 static crash_status data;
4386 return data;
4387 }
4388
4389 static std::mutex &mtx() {
4390 static std::mutex data;
4391 return data;
4392 }
4393
4394 static std::condition_variable &cv() {
4395 static std::condition_variable data;
4396 return data;
4397 }
4398
4399 static HANDLE &thread_handle() {
4400 static HANDLE handle;
4401 return handle;
4402 }
4403
4404 std::thread reporter_thread_;
4405
4406 // TODO: how not to hardcode these?
4407 static const constexpr int signal_skip_recs =
4408 #ifdef __clang__
4409 // With clang, RtlCaptureContext also captures the stack frame of the
4410 // current function Below that, there ar 3 internal Windows functions
4411 4
4412 #else
4413 // With MSVC cl, RtlCaptureContext misses the stack frame of the current
4414 // function The first entries during StackWalk are the 3 internal Windows
4415 // functions
4416 3
4417 #endif
4418 ;
4419
4420 static int &skip_recs() {
4421 static int data;
4422 return data;
4423 }
4424
4425 static inline void terminator() {
4426 crash_handler(signal_skip_recs);
4427 abort();
4428 }
4429
4430 static inline void signal_handler(int) {
4431 crash_handler(signal_skip_recs);
4432 abort();
4433 }
4434
4435 static inline void __cdecl invalid_parameter_handler(const wchar_t *,
4436 const wchar_t *,
4437 const wchar_t *,
4438 unsigned int,
4439 uintptr_t) {
4440 crash_handler(signal_skip_recs);
4441 abort();
4442 }
4443
4444 NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) {
4445 // The exception info supplies a trace from exactly where the issue was,
4446 // no need to skip records
4447 crash_handler(0, info->ContextRecord);
4448 return EXCEPTION_CONTINUE_SEARCH;
4449 }
4450
4451 NOINLINE static void crash_handler(int skip, CONTEXT *ct = nullptr) {
4452
4453 if (ct == nullptr) {
4454 RtlCaptureContext(ctx());
4455 } else {
4456 memcpy(ctx(), ct, sizeof(CONTEXT));
4457 }
4458 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
4459 GetCurrentProcess(), &thread_handle(), 0, FALSE,
4460 DUPLICATE_SAME_ACCESS);
4461
4462 skip_recs() = skip;
4463
4464 {
4465 std::unique_lock<std::mutex> lk(mtx());
4466 crashed() = crash_status::crashed;
4467 }
4468
4469 cv().notify_one();
4470
4471 {
4472 std::unique_lock<std::mutex> lk(mtx());
4473 cv().wait(lk, [] { return crashed() != crash_status::crashed; });
4474 }
4475 }
4476
4477 static void handle_stacktrace(int skip_frames = 0) {
4478 // printer creates the TraceResolver, which can supply us a machine type
4479 // for stack walking. Without this, StackTrace can only guess using some
4480 // macros.
4481 // StackTrace also requires that the PDBs are already loaded, which is done
4482 // in the constructor of TraceResolver
4483 Printer printer;
4484
4485 StackTrace st;
4486 st.set_machine_type(printer.resolver().machine_type());
4487 st.set_thread_handle(thread_handle());
4488 st.load_here(32 + skip_frames, ctx());
4489 st.skip_n_firsts(skip_frames);
4490
4491 printer.address = true;
4492 printer.print(st, std::cerr);
4493
4494 #ifdef _WIN32
4495 MessageBox(NULL,"Furnace has crashed! please report this to the issue tracker immediately:\r\nhttps://github.com/tildearrow/furnace/issues/new\r\n\r\na file called furnace_crash.txt will be created in your user directory.\r\nthis will be important for locating the origin of the crash.\r\n\r\nif Furnace keeps crashing and you believe it is caused by a configuration problem, you may start Furnace with the -safemode parameter.","Error",MB_OK|MB_ICONERROR);
4496 std::string crashLocation;
4497 char* userProfile=getenv("USERPROFILE");
4498 if (userProfile==NULL) {
4499 crashLocation="furnace_crash.txt";
4500 } else {
4501 crashLocation=userProfile;
4502 crashLocation+="\\furnace_crash.txt";
4503 }
4504 FILE* crashDump=fopen(crashLocation.c_str(),"w");
4505 #else
4506 FILE* crashDump=fopen("/tmp/furnace_crash.txt","w");
4507 #endif
4508
4509 if (crashDump!=NULL) {
4510 Printer printer;
4511 printer.address = true;
4512 printer.print(st, crashDump);
4513 fclose(crashDump);
4514 } else {
4515 #ifdef _WIN32
4516 std::string str;
4517 //Printer failedPrinter;
4518 //failedPrinter.address = true;
4519 //failedPrinter.print(st, str);
4520 str+="\r\ncould not open furnace_crash.txt!\r\nplease take a screenshot of this error message box!";
4521 fprintf(stderr,"NOTICE: could not open furnace_crash.txt!\n");
4522 MessageBox(NULL,str.c_str(),"Error",MB_OK|MB_ICONERROR);
4523 #endif
4524 }
4525 }
4526 };
4527
4528 #endif // BACKWARD_SYSTEM_WINDOWS
4529
4530 #ifdef BACKWARD_SYSTEM_UNKNOWN
4531
4532 class SignalHandling {
4533 public:
4534 SignalHandling(const std::vector<int> & = std::vector<int>()) {}
4535 bool init() { return false; }
4536 bool loaded() { return false; }
4537 };
4538
4539 #endif // BACKWARD_SYSTEM_UNKNOWN
4540
4541 } // namespace backward
4542
4543 #endif /* H_GUARD */