forked from bombela/backward-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backward.hpp
3819 lines (3283 loc) · 105 KB
/
backward.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* backward.hpp
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
#define H_6B9572DA_A64B_49E6_B234_051480991C89
#ifndef __cplusplus
# error "It's not going to compile without a C++ compiler..."
#endif
#if defined(BACKWARD_CXX11)
#elif defined(BACKWARD_CXX98)
#else
# if __cplusplus >= 201103L
# define BACKWARD_CXX11
# define BACKWARD_ATLEAST_CXX11
# define BACKWARD_ATLEAST_CXX98
# else
# define BACKWARD_CXX98
# define BACKWARD_ATLEAST_CXX98
# endif
#endif
// You can define one of the following (or leave it to the auto-detection):
//
// #define BACKWARD_SYSTEM_LINUX
// - specialization for linux
//
// #define BACKWARD_SYSTEM_DARWIN
// - specialization for Mac OS X 10.5 and later.
//
// #define BACKWARD_SYSTEM_UNKNOWN
// - placebo implementation, does nothing.
//
#if defined(BACKWARD_SYSTEM_LINUX)
#elif defined(BACKWARD_SYSTEM_DARWIN)
#elif defined(BACKWARD_SYSTEM_UNKNOWN)
#else
# if defined(__linux) || defined(__linux__)
# define BACKWARD_SYSTEM_LINUX
# elif defined(__APPLE__)
# define BACKWARD_SYSTEM_DARWIN
# else
# define BACKWARD_SYSTEM_UNKNOWN
# endif
#endif
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <new>
#include <sstream>
#include <streambuf>
#include <string>
#include <vector>
#include <limits>
#include <functional>
#if defined(BACKWARD_SYSTEM_LINUX)
// On linux, backtrace can back-trace or "walk" the stack using the following
// libraries:
//
// #define BACKWARD_HAS_UNWIND 1
// - unwind comes from libgcc, but I saw an equivalent inside clang itself.
// - with unwind, the stacktrace is as accurate as it can possibly be, since
// this is used by the C++ runtine in gcc/clang for stack unwinding on
// exception.
// - normally libgcc is already linked to your program by default.
//
// #define BACKWARD_HAS_BACKTRACE == 1
// - backtrace seems to be a little bit more portable than libunwind, but on
// linux, it uses unwind anyway, but abstract away a tiny information that is
// sadly really important in order to get perfectly accurate stack traces.
// - backtrace is part of the (e)glib library.
//
// The default is:
// #define BACKWARD_HAS_UNWIND == 1
//
// Note that only one of the define should be set to 1 at a time.
//
# if BACKWARD_HAS_UNWIND == 1
# elif BACKWARD_HAS_BACKTRACE == 1
# else
# undef BACKWARD_HAS_UNWIND
# define BACKWARD_HAS_UNWIND 1
# undef BACKWARD_HAS_BACKTRACE
# define BACKWARD_HAS_BACKTRACE 0
# endif
// On linux, backward can extract detailed information about a stack trace
// using one of the following libraries:
//
// #define BACKWARD_HAS_DW 1
// - libdw gives you the most juicy details out of your stack traces:
// - object filename
// - function name
// - source filename
// - line and column numbers
// - source code snippet (assuming the file is accessible)
// - variables name and values (if not optimized out)
// - You need to link with the lib "dw":
// - apt-get install libdw-dev
// - g++/clang++ -ldw ...
//
// #define BACKWARD_HAS_BFD 1
// - With libbfd, you get a fair amount of details:
// - object filename
// - function name
// - source filename
// - line numbers
// - source code snippet (assuming the file is accessible)
// - You need to link with the lib "bfd":
// - apt-get install binutils-dev
// - g++/clang++ -lbfd ...
//
// #define BACKWARD_HAS_DWARF 1
// - libdwarf gives you the most juicy details out of your stack traces:
// - object filename
// - function name
// - source filename
// - line and column numbers
// - source code snippet (assuming the file is accessible)
// - variables name and values (if not optimized out)
// - You need to link with the lib "dwarf":
// - apt-get install libdwarf-dev
// - g++/clang++ -ldwarf ...
//
// #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
// - backtrace provides minimal details for a stack trace:
// - object filename
// - function name
// - backtrace is part of the (e)glib library.
//
// The default is:
// #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
//
// Note that only one of the define should be set to 1 at a time.
//
# if BACKWARD_HAS_DW == 1
# elif BACKWARD_HAS_BFD == 1
# elif BACKWARD_HAS_DWARF == 1
# elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
# else
# undef BACKWARD_HAS_DW
# define BACKWARD_HAS_DW 0
# undef BACKWARD_HAS_BFD
# define BACKWARD_HAS_BFD 0
# undef BACKWARD_HAS_DWARF
# define BACKWARD_HAS_DWARF 0
# undef BACKWARD_HAS_BACKTRACE_SYMBOL
# define BACKWARD_HAS_BACKTRACE_SYMBOL 1
# endif
# include <cxxabi.h>
# include <fcntl.h>
# ifdef __ANDROID__
// Old Android API levels define _Unwind_Ptr in both link.h and unwind.h
// Rename the one in link.h as we are not going to be using it
# define _Unwind_Ptr _Unwind_Ptr_Custom
# include <link.h>
# undef _Unwind_Ptr
# else
# include <link.h>
# endif
# include <sys/stat.h>
# include <syscall.h>
# include <unistd.h>
# include <signal.h>
# if BACKWARD_HAS_BFD == 1
// NOTE: defining PACKAGE{,_VERSION} is required before including
// bfd.h on some platforms, see also:
// https://sourceware.org/bugzilla/show_bug.cgi?id=14243
# ifndef PACKAGE
# define PACKAGE
# endif
# ifndef PACKAGE_VERSION
# define PACKAGE_VERSION
# endif
# include <bfd.h>
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# include <dlfcn.h>
# undef _GNU_SOURCE
# else
# include <dlfcn.h>
# endif
# endif
# if BACKWARD_HAS_DW == 1
# include <elfutils/libdw.h>
# include <elfutils/libdwfl.h>
# include <dwarf.h>
# endif
# if BACKWARD_HAS_DWARF == 1
# include <libelf.h>
# include <dwarf.h>
# include <libdwarf.h>
# include <map>
# include <algorithm>
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# include <dlfcn.h>
# undef _GNU_SOURCE
# else
# include <dlfcn.h>
# endif
# endif
# if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
// then we shall rely on backtrace
# include <execinfo.h>
# endif
#endif // defined(BACKWARD_SYSTEM_LINUX)
#if defined(BACKWARD_SYSTEM_DARWIN)
// On Darwin, backtrace can back-trace or "walk" the stack using the following
// libraries:
//
// #define BACKWARD_HAS_UNWIND 1
// - unwind comes from libgcc, but I saw an equivalent inside clang itself.
// - with unwind, the stacktrace is as accurate as it can possibly be, since
// this is used by the C++ runtine in gcc/clang for stack unwinding on
// exception.
// - normally libgcc is already linked to your program by default.
//
// #define BACKWARD_HAS_BACKTRACE == 1
// - backtrace is available by default, though it does not produce as much information
// as another library might.
//
// The default is:
// #define BACKWARD_HAS_UNWIND == 1
//
// Note that only one of the define should be set to 1 at a time.
//
# if BACKWARD_HAS_UNWIND == 1
# elif BACKWARD_HAS_BACKTRACE == 1
# else
# undef BACKWARD_HAS_UNWIND
# define BACKWARD_HAS_UNWIND 1
# undef BACKWARD_HAS_BACKTRACE
# define BACKWARD_HAS_BACKTRACE 0
# endif
// On Darwin, backward can extract detailed information about a stack trace
// using one of the following libraries:
//
// #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
// - backtrace provides minimal details for a stack trace:
// - object filename
// - function name
//
// The default is:
// #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
//
# if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
# else
# undef BACKWARD_HAS_BACKTRACE_SYMBOL
# define BACKWARD_HAS_BACKTRACE_SYMBOL 1
# endif
# include <cxxabi.h>
# include <fcntl.h>
# include <pthread.h>
# include <sys/stat.h>
# include <unistd.h>
# include <signal.h>
# if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
# include <execinfo.h>
# endif
#endif // defined(BACKWARD_SYSTEM_DARWIN)
#if BACKWARD_HAS_UNWIND == 1
# include <unwind.h>
// while gcc's unwind.h defines something like that:
// extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *);
// extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
//
// clang's unwind.h defines something like this:
// uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context);
//
// Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we
// cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr
// anyway.
//
// Luckily we can play on the fact that the guard macros have a different name:
#ifdef __CLANG_UNWIND_H
// In fact, this function still comes from libgcc (on my different linux boxes,
// clang links against libgcc).
# include <inttypes.h>
extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context*, int*);
#endif
#endif // BACKWARD_HAS_UNWIND == 1
#ifdef BACKWARD_ATLEAST_CXX11
# include <unordered_map>
# include <utility> // for std::swap
namespace backward {
namespace details {
template <typename K, typename V>
struct hashtable {
typedef std::unordered_map<K, V> type;
};
using std::move;
} // namespace details
} // namespace backward
#else // NOT BACKWARD_ATLEAST_CXX11
# define nullptr NULL
# define override
# include <map>
namespace backward {
namespace details {
template <typename K, typename V>
struct hashtable {
typedef std::map<K, V> type;
};
template <typename T>
const T& move(const T& v) { return v; }
template <typename T>
T& move(T& v) { return v; }
} // namespace details
} // namespace backward
#endif // BACKWARD_ATLEAST_CXX11
namespace backward {
namespace system_tag {
struct linux_tag; // seems that I cannot call that "linux" because the name
// is already defined... so I am adding _tag everywhere.
struct darwin_tag;
struct unknown_tag;
#if defined(BACKWARD_SYSTEM_LINUX)
typedef linux_tag current_tag;
#elif defined(BACKWARD_SYSTEM_DARWIN)
typedef darwin_tag current_tag;
#elif defined(BACKWARD_SYSTEM_UNKNOWN)
typedef unknown_tag current_tag;
#else
# error "May I please get my system defines?"
#endif
} // namespace system_tag
namespace trace_resolver_tag {
#if defined(BACKWARD_SYSTEM_LINUX)
struct libdw;
struct libbfd;
struct libdwarf;
struct backtrace_symbol;
# if BACKWARD_HAS_DW == 1
typedef libdw current;
# elif BACKWARD_HAS_BFD == 1
typedef libbfd current;
# elif BACKWARD_HAS_DWARF == 1
typedef libdwarf current;
# elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
typedef backtrace_symbol current;
# else
# error "You shall not pass, until you know what you want."
# endif
#elif defined(BACKWARD_SYSTEM_DARWIN)
struct backtrace_symbol;
# if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
typedef backtrace_symbol current;
# else
# error "You shall not pass, until you know what you want."
# endif
#endif
} // namespace trace_resolver_tag
namespace details {
template <typename T>
struct rm_ptr { typedef T type; };
template <typename T>
struct rm_ptr<T*> { typedef T type; };
template <typename T>
struct rm_ptr<const T*> { typedef const T type; };
template <typename R, typename T, R (*F)(T)>
struct deleter {
template <typename U>
void operator()(U& ptr) const {
(*F)(ptr);
}
};
template <typename T>
struct default_delete {
void operator()(T& ptr) const {
delete ptr;
}
};
template <typename T, typename Deleter = deleter<void, void*, &::free> >
class handle {
struct dummy;
T _val;
bool _empty;
#ifdef BACKWARD_ATLEAST_CXX11
handle(const handle&) = delete;
handle& operator=(const handle&) = delete;
#endif
public:
~handle() {
if (!_empty) {
Deleter()(_val);
}
}
explicit handle(): _val(), _empty(true) {}
explicit handle(T val): _val(val), _empty(false) { if(!_val) _empty = true; }
#ifdef BACKWARD_ATLEAST_CXX11
handle(handle&& from): _empty(true) {
swap(from);
}
handle& operator=(handle&& from) {
swap(from); return *this;
}
#else
explicit handle(const handle& from): _empty(true) {
// some sort of poor man's move semantic.
swap(const_cast<handle&>(from));
}
handle& operator=(const handle& from) {
// some sort of poor man's move semantic.
swap(const_cast<handle&>(from)); return *this;
}
#endif
void reset(T new_val) {
handle tmp(new_val);
swap(tmp);
}
operator const dummy*() const {
if (_empty) {
return nullptr;
}
return reinterpret_cast<const dummy*>(_val);
}
T get() {
return _val;
}
T release() {
_empty = true;
return _val;
}
void swap(handle& b) {
using std::swap;
swap(b._val, _val); // can throw, we are safe here.
swap(b._empty, _empty); // should not throw: if you cannot swap two
// bools without throwing... It's a lost cause anyway!
}
T& operator->() { return _val; }
const T& operator->() const { return _val; }
typedef typename rm_ptr<T>::type& ref_t;
typedef const typename rm_ptr<T>::type& const_ref_t;
ref_t operator*() { return *_val; }
const_ref_t operator*() const { return *_val; }
ref_t operator[](size_t idx) { return _val[idx]; }
// Watch out, we've got a badass over here
T* operator&() {
_empty = false;
return &_val;
}
};
// Default demangler implementation (do nothing).
template <typename TAG>
struct demangler_impl {
static std::string demangle(const char* funcname) {
return funcname;
}
};
#if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
template <>
struct demangler_impl<system_tag::current_tag> {
demangler_impl(): _demangle_buffer_length(0) {}
std::string demangle(const char* funcname) {
using namespace details;
char* result = abi::__cxa_demangle(funcname,
_demangle_buffer.release(), &_demangle_buffer_length, nullptr);
if(result) {
_demangle_buffer.reset(result);
return result;
}
return funcname;
}
private:
details::handle<char*> _demangle_buffer;
size_t _demangle_buffer_length;
};
#endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
struct demangler:
public demangler_impl<system_tag::current_tag> {};
} // namespace details
/*************** A TRACE ***************/
struct Trace {
void* addr;
size_t idx;
Trace():
addr(nullptr), idx(0) {}
explicit Trace(void* _addr, size_t _idx):
addr(_addr), idx(_idx) {}
};
struct ResolvedTrace: public Trace {
struct SourceLoc {
std::string function;
std::string filename;
unsigned line;
unsigned col;
SourceLoc(): line(0), col(0) {}
bool operator==(const SourceLoc& b) const {
return function == b.function
&& filename == b.filename
&& line == b.line
&& col == b.col;
}
bool operator!=(const SourceLoc& b) const {
return !(*this == b);
}
};
// In which binary object this trace is located.
std::string object_filename;
// The function in the object that contain the trace. This is not the same
// as source.function which can be an function inlined in object_function.
std::string object_function;
// The source location of this trace. It is possible for filename to be
// empty and for line/col to be invalid (value 0) if this information
// couldn't be deduced, for example if there is no debug information in the
// binary object.
SourceLoc source;
// An optionals list of "inliners". All the successive sources location
// from where the source location of the trace (the attribute right above)
// is inlined. It is especially useful when you compiled with optimization.
typedef std::vector<SourceLoc> source_locs_t;
source_locs_t inliners;
ResolvedTrace():
Trace() {}
ResolvedTrace(const Trace& mini_trace):
Trace(mini_trace) {}
};
/*************** STACK TRACE ***************/
// default implemention.
template <typename TAG>
class StackTraceImpl {
public:
size_t size() const { return 0; }
Trace operator[](size_t) { return Trace(); }
size_t load_here(size_t=0) { return 0; }
size_t load_from(void*, size_t=0) { return 0; }
size_t thread_id() const { return 0; }
void skip_n_firsts(size_t) { }
};
class StackTraceImplBase {
public:
StackTraceImplBase(): _thread_id(0), _skip(0) {}
size_t thread_id() const {
return _thread_id;
}
void skip_n_firsts(size_t n) { _skip = n; }
protected:
void load_thread_info() {
#ifdef BACKWARD_SYSTEM_LINUX
#ifndef __ANDROID__
_thread_id = static_cast<size_t>(syscall(SYS_gettid));
#else
_thread_id = static_cast<size_t>(gettid());
#endif
if (_thread_id == static_cast<size_t>(getpid())) {
// If the thread is the main one, let's hide that.
// I like to keep little secret sometimes.
_thread_id = 0;
}
#elif defined(BACKWARD_SYSTEM_DARWIN)
_thread_id = reinterpret_cast<size_t>(pthread_self());
if (pthread_main_np() == 1) {
// If the thread is the main one, let's hide that.
_thread_id = 0;
}
#endif
}
size_t skip_n_firsts() const { return _skip; }
private:
size_t _thread_id;
size_t _skip;
};
class StackTraceImplHolder: public StackTraceImplBase {
public:
size_t size() const {
return _stacktrace.size() ? _stacktrace.size() - skip_n_firsts() : 0;
}
Trace operator[](size_t idx) const {
if (idx >= size()) {
return Trace();
}
return Trace(_stacktrace[idx + skip_n_firsts()], idx);
}
void* const* begin() const {
if (size()) {
return &_stacktrace[skip_n_firsts()];
}
return nullptr;
}
protected:
std::vector<void*> _stacktrace;
};
#if BACKWARD_HAS_UNWIND == 1
namespace details {
template <typename F>
class Unwinder {
public:
size_t operator()(F& f, size_t depth) {
_f = &f;
_index = -1;
_depth = depth;
_Unwind_Backtrace(&this->backtrace_trampoline, this);
return static_cast<size_t>(_index);
}
private:
F* _f;
ssize_t _index;
size_t _depth;
static _Unwind_Reason_Code backtrace_trampoline(
_Unwind_Context* ctx, void *self) {
return (static_cast<Unwinder*>(self))->backtrace(ctx);
}
_Unwind_Reason_Code backtrace(_Unwind_Context* ctx) {
if (_index >= 0 && static_cast<size_t>(_index) >= _depth)
return _URC_END_OF_STACK;
int ip_before_instruction = 0;
uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
if (!ip_before_instruction) {
// calculating 0-1 for unsigned, looks like a possible bug to sanitiziers, so let's do it explicitly:
if (ip==0) {
ip = std::numeric_limits<uintptr_t>::max(); // set it to 0xffff... (as from casting 0-1)
} else {
ip -= 1; // else just normally decrement it (no overflow/underflow will happen)
}
}
if (_index >= 0) { // ignore first frame.
(*_f)(static_cast<size_t>(_index), reinterpret_cast<void*>(ip));
}
_index += 1;
return _URC_NO_REASON;
}
};
template <typename F>
size_t unwind(F f, size_t depth) {
Unwinder<F> unwinder;
return unwinder(f, depth);
}
} // namespace details
template <>
class StackTraceImpl<system_tag::current_tag>: public StackTraceImplHolder {
public:
__attribute__ ((noinline)) // TODO use some macro
size_t load_here(size_t depth=32) {
load_thread_info();
if (depth == 0) {
return 0;
}
_stacktrace.resize(depth);
size_t trace_cnt = details::unwind(callback(*this), depth);
_stacktrace.resize(trace_cnt);
skip_n_firsts(0);
return size();
}
size_t load_from(void* addr, size_t depth=32) {
load_here(depth + 8);
for (size_t i = 0; i < _stacktrace.size(); ++i) {
if (_stacktrace[i] == addr) {
skip_n_firsts(i);
break;
}
}
_stacktrace.resize(std::min(_stacktrace.size(),
skip_n_firsts() + depth));
return size();
}
private:
struct callback {
StackTraceImpl& self;
callback(StackTraceImpl& _self): self(_self) {}
void operator()(size_t idx, void* addr) {
self._stacktrace[idx] = addr;
}
};
};
#else // BACKWARD_HAS_UNWIND == 0
template <>
class StackTraceImpl<system_tag::current_tag>: public StackTraceImplHolder {
public:
__attribute__ ((noinline)) // TODO use some macro
size_t load_here(size_t depth=32) {
load_thread_info();
if (depth == 0) {
return 0;
}
_stacktrace.resize(depth + 1);
size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
_stacktrace.resize(trace_cnt);
skip_n_firsts(1);
return size();
}
size_t load_from(void* addr, size_t depth=32) {
load_here(depth + 8);
for (size_t i = 0; i < _stacktrace.size(); ++i) {
if (_stacktrace[i] == addr) {
skip_n_firsts(i);
_stacktrace[i] = (void*)( (uintptr_t)_stacktrace[i] + 1);
break;
}
}
_stacktrace.resize(std::min(_stacktrace.size(),
skip_n_firsts() + depth));
return size();
}
};
#endif // BACKWARD_HAS_UNWIND
class StackTrace:
public StackTraceImpl<system_tag::current_tag> {};
/*************** TRACE RESOLVER ***************/
template <typename TAG>
class TraceResolverImpl;
#ifdef BACKWARD_SYSTEM_UNKNOWN
template <>
class TraceResolverImpl<system_tag::unknown_tag> {
public:
template <class ST>
void load_stacktrace(ST&) {}
ResolvedTrace resolve(ResolvedTrace t) {
return t;
}
};
#endif
class TraceResolverImplBase {
protected:
std::string demangle(const char* funcname) {
return _demangler.demangle(funcname);
}
private:
details::demangler _demangler;
};
#ifdef BACKWARD_SYSTEM_LINUX
template <typename STACKTRACE_TAG>
class TraceResolverLinuxImpl;
#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
template <>
class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>:
public TraceResolverImplBase {
public:
template <class ST>
void load_stacktrace(ST& st) {
using namespace details;
if (st.size() == 0) {
return;
}
_symbols.reset(
backtrace_symbols(st.begin(), (int)st.size())
);
}
ResolvedTrace resolve(ResolvedTrace trace) {
char* filename = _symbols[trace.idx];
char* funcname = filename;
while (*funcname && *funcname != '(') {
funcname += 1;
}
trace.object_filename.assign(filename, funcname); // ok even if funcname is the ending \0 (then we assign entire string)
if (*funcname) { // if it's not end of string (e.g. from last frame ip==0)
funcname += 1;
char* funcname_end = funcname;
while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') {
funcname_end += 1;
}
*funcname_end = '\0';
trace.object_function = this->demangle(funcname);
trace.source.function = trace.object_function; // we cannot do better.
}
return trace;
}
private:
details::handle<char**> _symbols;
};
#endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
#if BACKWARD_HAS_BFD == 1
template <>
class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>:
public TraceResolverImplBase {
static std::string read_symlink(std::string const & symlink_path) {
std::string path;
path.resize(100);
while(true) {
ssize_t len = ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
if(len < 0) {
return "";
}
if (static_cast<size_t>(len) == path.size()) {
path.resize(path.size() * 2);
}
else {
path.resize(static_cast<std::string::size_type>(len));
break;
}
}
return path;
}
public:
TraceResolverLinuxImpl(): _bfd_loaded(false) {}
template <class ST>
void load_stacktrace(ST&) {}
ResolvedTrace resolve(ResolvedTrace trace) {
Dl_info symbol_info;
// trace.addr is a virtual address in memory pointing to some code.
// Let's try to find from which loaded object it comes from.
// The loaded object can be yourself btw.
if (!dladdr(trace.addr, &symbol_info)) {
return trace; // dat broken trace...
}
std::string argv0;
{
std::ifstream ifs("/proc/self/cmdline");
std::getline(ifs, argv0, '\0');
}
std::string tmp;
if(symbol_info.dli_fname == argv0) {
tmp = read_symlink("/proc/self/exe");
symbol_info.dli_fname = tmp.c_str();
}
// Now we get in symbol_info:
// .dli_fname:
// pathname of the shared object that contains the address.
// .dli_fbase:
// where the object is loaded in memory.
// .dli_sname:
// the name of the nearest symbol to trace.addr, we expect a
// function name.
// .dli_saddr:
// the exact address corresponding to .dli_sname.
if (symbol_info.dli_sname) {
trace.object_function = demangle(symbol_info.dli_sname);
}
if (!symbol_info.dli_fname) {
return trace;
}
trace.object_filename = symbol_info.dli_fname;
bfd_fileobject& fobj = load_object_with_bfd(symbol_info.dli_fname);
if (!fobj.handle) {
return trace; // sad, we couldn't load the object :(
}
find_sym_result* details_selected; // to be filled.
// trace.addr is the next instruction to be executed after returning
// from the nested stack frame. In C++ this usually relate to the next
// statement right after the function call that leaded to a new stack
// frame. This is not usually what you want to see when printing out a
// stacktrace...
find_sym_result details_call_site = find_symbol_details(fobj,
trace.addr, symbol_info.dli_fbase);
details_selected = &details_call_site;
#if BACKWARD_HAS_UNWIND == 0
// ...this is why we also try to resolve the symbol that is right
// before the return address. If we are lucky enough, we will get the
// line of the function that was called. But if the code is optimized,
// we might get something absolutely not related since the compiler
// can reschedule the return address with inline functions and
// tail-call optimisation (among other things that I don't even know
// or cannot even dream about with my tiny limited brain).
find_sym_result details_adjusted_call_site = find_symbol_details(fobj,
(void*) (uintptr_t(trace.addr) - 1),