py10x-core 0.1.3__cp312-cp312-macosx_13_0_universal2.whl

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