collect_unwind.ipp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright Antony Polukhin, 2016-2018.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_STACKTRACE_DETAIL_COLLECT_UNWIND_IPP
  7. #define BOOST_STACKTRACE_DETAIL_COLLECT_UNWIND_IPP
  8. #include <boost/config.hpp>
  9. #ifdef BOOST_HAS_PRAGMA_ONCE
  10. # pragma once
  11. #endif
  12. #include <boost/stacktrace/safe_dump_to.hpp>
  13. #include <unwind.h>
  14. #include <cstdio>
  15. #if !defined(_GNU_SOURCE) && !defined(BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED) && !defined(BOOST_WINDOWS)
  16. #error "Boost.Stacktrace requires `_Unwind_Backtrace` function. Define `_GNU_SOURCE` macro or `BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED` if _Unwind_Backtrace is available without `_GNU_SOURCE`."
  17. #endif
  18. namespace boost { namespace stacktrace { namespace detail {
  19. struct unwind_state {
  20. std::size_t frames_to_skip;
  21. native_frame_ptr_t* current;
  22. native_frame_ptr_t* end;
  23. };
  24. inline _Unwind_Reason_Code unwind_callback(::_Unwind_Context* context, void* arg) {
  25. // Note: do not write `::_Unwind_GetIP` because it is a macro on some platforms.
  26. // Use `_Unwind_GetIP` instead!
  27. unwind_state* const state = static_cast<unwind_state*>(arg);
  28. if (state->frames_to_skip) {
  29. --state->frames_to_skip;
  30. return _Unwind_GetIP(context) ? ::_URC_NO_REASON : ::_URC_END_OF_STACK;
  31. }
  32. *state->current = reinterpret_cast<native_frame_ptr_t>(
  33. _Unwind_GetIP(context)
  34. );
  35. ++state->current;
  36. if (!*(state->current - 1) || state->current == state->end) {
  37. return ::_URC_END_OF_STACK;
  38. }
  39. return ::_URC_NO_REASON;
  40. }
  41. std::size_t this_thread_frames::collect(native_frame_ptr_t* out_frames, std::size_t max_frames_count, std::size_t skip) BOOST_NOEXCEPT {
  42. std::size_t frames_count = 0;
  43. if (!max_frames_count) {
  44. return frames_count;
  45. }
  46. boost::stacktrace::detail::unwind_state state = { skip + 1, out_frames, out_frames + max_frames_count };
  47. ::_Unwind_Backtrace(&boost::stacktrace::detail::unwind_callback, &state);
  48. frames_count = state.current - out_frames;
  49. if (frames_count && out_frames[frames_count - 1] == 0) {
  50. -- frames_count;
  51. }
  52. return frames_count;
  53. }
  54. }}} // namespace boost::stacktrace::detail
  55. #endif // BOOST_STACKTRACE_DETAIL_COLLECT_UNWIND_IPP