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