/src/spicy/hilti/runtime/src/backtrace.cc
Line | Count | Source |
1 | | // Copyright (c) 2020-now by the Zeek Project. See LICENSE for details. |
2 | | |
3 | | #include <cstring> |
4 | | |
5 | | #include <hilti/rt/autogen/config.h> |
6 | | #include <hilti/rt/backtrace.h> |
7 | | #include <hilti/rt/util.h> |
8 | | |
9 | | using namespace hilti::rt; |
10 | | |
11 | 0 | Backtrace::Backtrace() { |
12 | 0 | #ifdef HILTI_HAVE_BACKTRACE |
13 | 0 | _callstack = std::make_shared<Callstack>(); // allocate on heap to save stack space |
14 | 0 | _frames = ::backtrace(_callstack->begin(), static_cast<int>(_callstack->size())); |
15 | 0 | #endif |
16 | 0 | } |
17 | | |
18 | 0 | std::unique_ptr<std::vector<std::string>> Backtrace::backtrace() const { |
19 | 0 | auto bt = std::make_unique<std::vector<std::string>>(); |
20 | |
|
21 | 0 | #ifdef HILTI_HAVE_BACKTRACE |
22 | 0 | assert(_frames >= 0); |
23 | 0 | char** strings = backtrace_symbols(_callstack->begin(), _frames); |
24 | 0 | if ( ! strings ) { |
25 | 0 | bt->push_back("# <trouble resolving backtrace symbols>"); |
26 | 0 | return bt; |
27 | 0 | } |
28 | | |
29 | 0 | for ( auto i = 0; i < _frames; i++ ) { |
30 | 0 | auto* p1 = strchr(strings[i], '('); |
31 | 0 | auto* p2 = p1 ? strchr(p1, '+') : nullptr; |
32 | 0 | auto* p3 = p2 ? strchr(p2, ')') : nullptr; |
33 | 0 | if ( p1 && p2 && p3 ) { |
34 | 0 | *p2 = '\0'; |
35 | 0 | bt->push_back(fmt("# %s %s", p3 + 2, demangle(p1 + 1))); |
36 | 0 | } |
37 | 0 | else |
38 | 0 | bt->push_back(fmt("# %s", strings[i])); |
39 | 0 | } |
40 | |
|
41 | 0 | free(strings); // NOLINT |
42 | | #else |
43 | | bt->push_back("# <support for stack backtraces not available>"); |
44 | | #endif |
45 | |
|
46 | 0 | return bt; |
47 | 0 | } |
48 | | |
49 | 0 | bool hilti::rt::operator==(const Backtrace& a, const Backtrace& b) { |
50 | 0 | if ( a._frames < 0 && b._frames < 0 ) |
51 | 0 | return true; |
52 | | |
53 | 0 | if ( a._frames != b._frames ) |
54 | 0 | return false; |
55 | | |
56 | 0 | for ( int i = 0; i < a._frames; i++ ) { |
57 | 0 | if ( a._callstack->at(i) != b._callstack->at(i) ) |
58 | 0 | return false; |
59 | 0 | } |
60 | | |
61 | 0 | return true; |
62 | 0 | } |