Debian Codegraph @

src/unwind/unwind_with_libunwind.cpp

raw
1 #ifdef CPPTRACE_UNWIND_WITH_LIBUNWIND
2
3 #include "unwind/unwind.hpp"
4 #include "utils/common.hpp"
5 #include "utils/error.hpp"
6 #include "utils/utils.hpp"
7
8 #include <algorithm>
9 #include <cassert>
10 #include <cstddef>
11 #include <vector>
12
13 #include <libunwind.h>
14
15 CPPTRACE_BEGIN_NAMESPACE
16 namespace detail {
17 CPPTRACE_FORCE_NO_INLINE
18 std::vector<frame_ptr> capture_frames(std::size_t skip, std::size_t max_depth) {
19 skip++;
20 std::vector<frame_ptr> frames;
21 unw_context_t context;
22 unw_cursor_t cursor;
23 unw_getcontext(&context);
24 unw_init_local(&cursor, &context);
25 do {
26 unw_word_t pc;
27 unw_word_t sp;
28 unw_get_reg(&cursor, UNW_REG_IP, &pc);
29 unw_get_reg(&cursor, UNW_REG_SP, &sp);
30 if(skip) {
31 skip--;
32 } else {
33 // pc is the instruction after the `call`, adjust back to the previous instruction
34 frames.push_back(to_frame_ptr(pc) - 1);
35 }
36 } while(unw_step(&cursor) > 0 && frames.size() < max_depth);
37 return frames;
38 }
39
40 CPPTRACE_FORCE_NO_INLINE
41 std::size_t safe_capture_frames(frame_ptr* buffer, std::size_t size, std::size_t skip, std::size_t max_depth) {
42 // some code duplication, but whatever
43 skip++;
44 unw_context_t context;
45 unw_cursor_t cursor;
46 // thread and signal-safe https://www.nongnu.org/libunwind/man/unw_getcontext(3).html
47 unw_getcontext(&context);
48 // thread and signal-safe https://www.nongnu.org/libunwind/man/unw_init_local(3).html
49 unw_init_local(&cursor, &context);
50 size_t i = 0;
51 while(i < size && i < max_depth) {
52 unw_word_t pc;
53 unw_word_t sp;
54 // thread and signal-safe https://www.nongnu.org/libunwind/man/unw_get_reg(3).html
55 unw_get_reg(&cursor, UNW_REG_IP, &pc);
56 unw_get_reg(&cursor, UNW_REG_SP, &sp);
57 if(skip) {
58 skip--;
59 } else {
60 // thread and signal-safe
61 if(unw_is_signal_frame(&cursor)) {
62 // pc is the instruction that caused the signal
63 // just a cast, thread and signal safe
64 buffer[i] = to_frame_ptr(pc);
65 } else {
66 // pc is the instruction after the `call`, adjust back to the previous instruction
67 // just a cast, thread and signal safe
68 buffer[i] = to_frame_ptr(pc) - 1;
69 }
70 i++;
71 }
72 // thread and signal-safe as long as the cursor is in the local address space, which it is
73 // https://www.nongnu.org/libunwind/man/unw_step(3).html
74 if(unw_step(&cursor) <= 0) {
75 break;
76 }
77 }
78 return i;
79 }
80
81 bool has_safe_unwind() {
82 return true;
83 }
84 }
85 CPPTRACE_END_NAMESPACE
86
87 #endif