| 1 |
#ifdef CPPTRACE_UNWIND_WITH_UNWIND |
| 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 <unwind.h> |
| 14 |
|
| 15 |
CPPTRACE_BEGIN_NAMESPACE |
| 16 |
namespace detail { |
| 17 |
struct unwind_state { |
| 18 |
std::size_t skip; |
| 19 |
std::size_t max_depth; |
| 20 |
std::vector<frame_ptr>& vec; |
| 21 |
}; |
| 22 |
|
| 23 |
_Unwind_Reason_Code unwind_callback(_Unwind_Context* context, void* arg) { |
| 24 |
unwind_state& state = *static_cast<unwind_state*>(arg); |
| 25 |
if(state.skip) { |
| 26 |
state.skip--; |
| 27 |
if(_Unwind_GetIP(context) == frame_ptr(0)) { |
| 28 |
return _URC_END_OF_STACK; |
| 29 |
} else { |
| 30 |
return _URC_NO_REASON; |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
ASSERT( |
| 35 |
state.vec.size() < state.max_depth, |
| 36 |
"Somehow cpptrace::detail::unwind_callback is being called beyond the max_depth" |
| 37 |
); |
| 38 |
int is_before_instruction = 0; |
| 39 |
frame_ptr ip = _Unwind_GetIPInfo(context, &is_before_instruction); |
| 40 |
if(!is_before_instruction && ip != frame_ptr(0)) { |
| 41 |
ip--; |
| 42 |
} |
| 43 |
if (ip == frame_ptr(0)) { |
| 44 |
return _URC_END_OF_STACK; |
| 45 |
} else { |
| 46 |
state.vec.push_back(ip); |
| 47 |
if(state.vec.size() >= state.max_depth) { |
| 48 |
return _URC_END_OF_STACK; |
| 49 |
} else { |
| 50 |
return _URC_NO_REASON; |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
CPPTRACE_FORCE_NO_INLINE |
| 56 |
std::vector<frame_ptr> capture_frames(std::size_t skip, std::size_t max_depth) { |
| 57 |
std::vector<frame_ptr> frames; |
| 58 |
unwind_state state{skip + 1, max_depth, frames}; |
| 59 |
_Unwind_Backtrace(unwind_callback, &state); // presumably thread-safe |
| 60 |
return frames; |
| 61 |
} |
| 62 |
|
| 63 |
CPPTRACE_FORCE_NO_INLINE |
| 64 |
std::size_t safe_capture_frames(frame_ptr*, std::size_t, std::size_t, std::size_t) { |
| 65 |
// Can't safe trace with _Unwind |
| 66 |
return 0; |
| 67 |
} |
| 68 |
|
| 69 |
bool has_safe_unwind() { |
| 70 |
return false; |
| 71 |
} |
| 72 |
} |
| 73 |
CPPTRACE_END_NAMESPACE |
| 74 |
|
| 75 |
#endif |