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