stacktrace.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Copyright Antony Polukhin, 2016-2025.
  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_STACKTRACE_HPP
  7. #define BOOST_STACKTRACE_STACKTRACE_HPP
  8. #include <boost/config.hpp>
  9. #ifdef BOOST_HAS_PRAGMA_ONCE
  10. # pragma once
  11. #endif
  12. #include <boost/core/no_exceptions_support.hpp>
  13. #include <boost/container_hash/hash_fwd.hpp>
  14. #include <iosfwd>
  15. #include <string>
  16. #include <vector>
  17. #ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS
  18. # include <type_traits>
  19. #endif
  20. #include <boost/stacktrace/stacktrace_fwd.hpp>
  21. #include <boost/stacktrace/safe_dump_to.hpp>
  22. #include <boost/stacktrace/detail/frame_decl.hpp>
  23. #include <boost/stacktrace/frame.hpp>
  24. #ifdef BOOST_INTEL
  25. # pragma warning(push)
  26. # pragma warning(disable:2196) // warning #2196: routine is both "inline" and "noinline"
  27. #endif
  28. #if defined(BOOST_MSVC)
  29. extern "C" {
  30. const char* boost_stacktrace_impl_current_exception_stacktrace();
  31. bool* boost_stacktrace_impl_ref_capture_stacktraces_at_throw();
  32. }
  33. #ifdef _M_IX86
  34. # pragma comment(linker, "/ALTERNATENAME:_boost_stacktrace_impl_current_exception_stacktrace=_boost_stacktrace_impl_return_nullptr")
  35. # pragma comment(linker, "/ALTERNATENAME:_boost_stacktrace_impl_ref_capture_stacktraces_at_throw=_boost_stacktrace_impl_return_nullptr")
  36. #else
  37. # pragma comment(linker, "/ALTERNATENAME:boost_stacktrace_impl_current_exception_stacktrace=boost_stacktrace_impl_return_nullptr")
  38. # pragma comment(linker, "/ALTERNATENAME:boost_stacktrace_impl_ref_capture_stacktraces_at_throw=boost_stacktrace_impl_return_nullptr")
  39. #endif
  40. #endif
  41. namespace boost { namespace stacktrace {
  42. namespace impl {
  43. #if defined(__GNUC__) && defined(__ELF__)
  44. BOOST_NOINLINE BOOST_SYMBOL_VISIBLE __attribute__((weak))
  45. const char* current_exception_stacktrace() noexcept;
  46. BOOST_NOINLINE BOOST_SYMBOL_VISIBLE __attribute__((weak))
  47. bool& ref_capture_stacktraces_at_throw() noexcept;
  48. #endif
  49. } // namespace impl
  50. /// Class that on construction copies minimal information about call stack into its internals and provides access to that information.
  51. /// @tparam Allocator Allocator to use during stack capture.
  52. template <class Allocator>
  53. class basic_stacktrace {
  54. std::vector<boost::stacktrace::frame, Allocator> impl_;
  55. typedef boost::stacktrace::detail::native_frame_ptr_t native_frame_ptr_t;
  56. /// @cond
  57. void fill(native_frame_ptr_t* begin, std::size_t size) {
  58. if (!size) {
  59. return;
  60. }
  61. impl_.reserve(static_cast<std::size_t>(size));
  62. for (std::size_t i = 0; i < size; ++i) {
  63. if (!begin[i]) {
  64. return;
  65. }
  66. impl_.push_back(
  67. frame(begin[i])
  68. );
  69. }
  70. }
  71. static std::size_t frames_count_from_buffer_size(std::size_t buffer_size) noexcept {
  72. const std::size_t ret = (buffer_size > sizeof(native_frame_ptr_t) ? buffer_size / sizeof(native_frame_ptr_t) : 0);
  73. return (ret > 1024 ? 1024 : ret); // Dealing with suspiciously big sizes
  74. }
  75. BOOST_NOINLINE void init(std::size_t frames_to_skip, std::size_t max_depth) {
  76. constexpr std::size_t buffer_size = 128;
  77. if (!max_depth) {
  78. return;
  79. }
  80. BOOST_TRY {
  81. { // Fast path without additional allocations
  82. native_frame_ptr_t buffer[buffer_size];
  83. const std::size_t frames_count = boost::stacktrace::detail::this_thread_frames::collect(buffer, buffer_size < max_depth ? buffer_size : max_depth, frames_to_skip + 1);
  84. if (buffer_size > frames_count || frames_count == max_depth) {
  85. fill(buffer, frames_count);
  86. return;
  87. }
  88. }
  89. // Failed to fit in `buffer_size`. Allocating memory:
  90. #ifdef BOOST_NO_CXX11_ALLOCATOR
  91. typedef typename Allocator::template rebind<native_frame_ptr_t>::other allocator_void_t;
  92. #else
  93. typedef typename std::allocator_traits<Allocator>::template rebind_alloc<native_frame_ptr_t> allocator_void_t;
  94. #endif
  95. std::vector<native_frame_ptr_t, allocator_void_t> buf(buffer_size * 2, 0, impl_.get_allocator());
  96. do {
  97. const std::size_t frames_count = boost::stacktrace::detail::this_thread_frames::collect(&buf[0], buf.size() < max_depth ? buf.size() : max_depth, frames_to_skip + 1);
  98. if (buf.size() > frames_count || frames_count == max_depth) {
  99. fill(&buf[0], frames_count);
  100. return;
  101. }
  102. buf.resize(buf.size() * 2);
  103. } while (buf.size() < buf.max_size()); // close to `true`, but suppresses `C4127: conditional expression is constant`.
  104. } BOOST_CATCH (...) {
  105. // ignore exception
  106. }
  107. BOOST_CATCH_END
  108. }
  109. /// @endcond
  110. public:
  111. typedef typename std::vector<boost::stacktrace::frame, Allocator>::value_type value_type;
  112. typedef typename std::vector<boost::stacktrace::frame, Allocator>::allocator_type allocator_type;
  113. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_pointer pointer;
  114. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_pointer const_pointer;
  115. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_reference reference;
  116. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_reference const_reference;
  117. typedef typename std::vector<boost::stacktrace::frame, Allocator>::size_type size_type;
  118. typedef typename std::vector<boost::stacktrace::frame, Allocator>::difference_type difference_type;
  119. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_iterator iterator;
  120. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_iterator const_iterator;
  121. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_reverse_iterator reverse_iterator;
  122. typedef typename std::vector<boost::stacktrace::frame, Allocator>::const_reverse_iterator const_reverse_iterator;
  123. /// @brief Stores the current function call sequence inside *this without any decoding or any other heavy platform specific operations.
  124. ///
  125. /// @b Complexity: O(N) where N is call sequence length, O(1) if BOOST_STACKTRACE_USE_NOOP is defined.
  126. ///
  127. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction, copying, Allocator::allocate and Allocator::deallocate are async signal safe.
  128. BOOST_FORCEINLINE basic_stacktrace() noexcept
  129. : impl_()
  130. {
  131. init(0 , static_cast<std::size_t>(-1));
  132. }
  133. /// @brief Stores the current function call sequence inside *this without any decoding or any other heavy platform specific operations.
  134. ///
  135. /// @b Complexity: O(N) where N is call sequence length, O(1) if BOOST_STACKTRACE_USE_NOOP is defined.
  136. ///
  137. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction, copying, Allocator::allocate and Allocator::deallocate are async signal safe.
  138. ///
  139. /// @param a Allocator that would be passed to underlying storage.
  140. BOOST_FORCEINLINE explicit basic_stacktrace(const allocator_type& a) noexcept
  141. : impl_(a)
  142. {
  143. init(0 , static_cast<std::size_t>(-1));
  144. }
  145. /// @brief Stores [skip, skip + max_depth) of the current function call sequence inside *this without any decoding or any other heavy platform specific operations.
  146. ///
  147. /// @b Complexity: O(N) where N is call sequence length, O(1) if BOOST_STACKTRACE_USE_NOOP is defined.
  148. ///
  149. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction, copying, Allocator::allocate and Allocator::deallocate are async signal safe.
  150. ///
  151. /// @param skip How many top calls to skip and do not store in *this.
  152. ///
  153. /// @param max_depth Max call sequence depth to collect.
  154. ///
  155. /// @param a Allocator that would be passed to underlying storage.
  156. ///
  157. /// @throws Nothing. Note that default construction of allocator may throw, however it is
  158. /// performed outside the constructor and exception in `allocator_type()` would not result in calling `std::terminate`.
  159. BOOST_FORCEINLINE basic_stacktrace(std::size_t skip, std::size_t max_depth, const allocator_type& a = allocator_type()) noexcept
  160. : impl_(a)
  161. {
  162. init(skip , max_depth);
  163. }
  164. /// @b Complexity: O(st.size())
  165. ///
  166. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction, copying, Allocator::allocate and Allocator::deallocate are async signal safe.
  167. basic_stacktrace(const basic_stacktrace& st)
  168. : impl_(st.impl_)
  169. {}
  170. /// @b Complexity: O(st.size())
  171. ///
  172. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction, copying, Allocator::allocate and Allocator::deallocate are async signal safe.
  173. basic_stacktrace& operator=(const basic_stacktrace& st) {
  174. impl_ = st.impl_;
  175. return *this;
  176. }
  177. #ifdef BOOST_STACKTRACE_DOXYGEN_INVOKED
  178. /// @b Complexity: O(1)
  179. ///
  180. /// @b Async-Handler-Safety: \asyncsafe if Allocator::deallocate is async signal safe.
  181. ~basic_stacktrace() noexcept = default;
  182. #endif
  183. #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
  184. /// @b Complexity: O(1)
  185. ///
  186. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction and copying are async signal safe.
  187. basic_stacktrace(basic_stacktrace&& st) noexcept
  188. : impl_(std::move(st.impl_))
  189. {}
  190. /// @b Complexity: O(st.size())
  191. ///
  192. /// @b Async-Handler-Safety: \asyncsafe if Allocator construction and copying are async signal safe.
  193. basic_stacktrace& operator=(basic_stacktrace&& st)
  194. #ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS
  195. noexcept(( std::is_nothrow_move_assignable< std::vector<boost::stacktrace::frame, Allocator> >::value ))
  196. #else
  197. noexcept
  198. #endif
  199. {
  200. impl_ = std::move(st.impl_);
  201. return *this;
  202. }
  203. #endif
  204. /// @returns Number of function names stored inside the class.
  205. ///
  206. /// @b Complexity: O(1)
  207. ///
  208. /// @b Async-Handler-Safety: \asyncsafe.
  209. size_type size() const noexcept {
  210. return impl_.size();
  211. }
  212. /// @param frame_no Zero based index of frame to return. 0
  213. /// is the function index where stacktrace was constructed and
  214. /// index close to this->size() contains function `main()`.
  215. /// @returns frame that references the actual frame info, stored inside *this.
  216. ///
  217. /// @b Complexity: O(1).
  218. ///
  219. /// @b Async-Handler-Safety: \asyncsafe.
  220. const_reference operator[](std::size_t frame_no) const noexcept {
  221. return impl_[frame_no];
  222. }
  223. /// @b Complexity: O(1)
  224. ///
  225. /// @b Async-Handler-Safety: \asyncsafe.
  226. const_iterator begin() const noexcept { return impl_.begin(); }
  227. /// @b Complexity: O(1)
  228. ///
  229. /// @b Async-Handler-Safety: \asyncsafe.
  230. const_iterator cbegin() const noexcept { return impl_.begin(); }
  231. /// @b Complexity: O(1)
  232. ///
  233. /// @b Async-Handler-Safety: \asyncsafe.
  234. const_iterator end() const noexcept { return impl_.end(); }
  235. /// @b Complexity: O(1)
  236. ///
  237. /// @b Async-Handler-Safety: \asyncsafe.
  238. const_iterator cend() const noexcept { return impl_.end(); }
  239. /// @b Complexity: O(1)
  240. ///
  241. /// @b Async-Handler-Safety: \asyncsafe.
  242. const_reverse_iterator rbegin() const noexcept { return impl_.rbegin(); }
  243. /// @b Complexity: O(1)
  244. ///
  245. /// @b Async-Handler-Safety: \asyncsafe.
  246. const_reverse_iterator crbegin() const noexcept { return impl_.rbegin(); }
  247. /// @b Complexity: O(1)
  248. ///
  249. /// @b Async-Handler-Safety: \asyncsafe.
  250. const_reverse_iterator rend() const noexcept { return impl_.rend(); }
  251. /// @b Complexity: O(1)
  252. ///
  253. /// @b Async-Handler-Safety: \asyncsafe.
  254. const_reverse_iterator crend() const noexcept { return impl_.rend(); }
  255. /// @brief Allows to check that stack trace capturing was successful.
  256. /// @returns `true` if `this->size() != 0`
  257. ///
  258. /// @b Complexity: O(1)
  259. ///
  260. /// @b Async-Handler-Safety: \asyncsafe.
  261. constexpr explicit operator bool () const noexcept { return !empty(); }
  262. /// @brief Allows to check that stack trace failed.
  263. /// @returns `true` if `this->size() == 0`
  264. ///
  265. /// @b Complexity: O(1)
  266. ///
  267. /// @b Async-Handler-Safety: \asyncsafe.
  268. bool empty() const noexcept { return !size(); }
  269. const std::vector<boost::stacktrace::frame, Allocator>& as_vector() const noexcept {
  270. return impl_;
  271. }
  272. /// Constructs stacktrace from basic_istreamable that references the dumped stacktrace. Terminating zero frame is discarded.
  273. ///
  274. /// @b Complexity: O(N)
  275. template <class Char, class Trait>
  276. static basic_stacktrace from_dump(std::basic_istream<Char, Trait>& in, const allocator_type& a = allocator_type()) {
  277. typedef typename std::basic_istream<Char, Trait>::pos_type pos_type;
  278. basic_stacktrace ret(0, 0, a);
  279. // reserving space
  280. const pos_type pos = in.tellg();
  281. in.seekg(0, in.end);
  282. const std::size_t frames_count = frames_count_from_buffer_size(static_cast<std::size_t>(in.tellg()));
  283. in.seekg(pos);
  284. if (!frames_count) {
  285. return ret;
  286. }
  287. native_frame_ptr_t ptr = 0;
  288. ret.impl_.reserve(frames_count);
  289. while (in.read(reinterpret_cast<Char*>(&ptr), sizeof(ptr))) {
  290. if (!ptr) {
  291. break;
  292. }
  293. ret.impl_.push_back(frame(ptr));
  294. }
  295. return ret;
  296. }
  297. /// Constructs stacktrace from raw memory dump. Terminating zero frame is discarded.
  298. ///
  299. /// @param begin Beginning of the memory where the stacktrace was saved using the boost::stacktrace::safe_dump_to
  300. ///
  301. /// @param buffer_size_in_bytes Size of the memory. Usually the same value that was passed to the boost::stacktrace::safe_dump_to
  302. ///
  303. /// @b Complexity: O(size) in worst case
  304. static basic_stacktrace from_dump(const void* begin, std::size_t buffer_size_in_bytes, const allocator_type& a = allocator_type()) {
  305. basic_stacktrace ret(0, 0, a);
  306. const native_frame_ptr_t* first = static_cast<const native_frame_ptr_t*>(begin);
  307. const std::size_t frames_count = frames_count_from_buffer_size(buffer_size_in_bytes);
  308. if (!frames_count) {
  309. return ret;
  310. }
  311. const native_frame_ptr_t* const last = first + frames_count;
  312. ret.impl_.reserve(frames_count);
  313. for (; first != last; ++first) {
  314. if (!*first) {
  315. break;
  316. }
  317. ret.impl_.push_back(frame(*first));
  318. }
  319. return ret;
  320. }
  321. /// Returns a basic_stacktrace object containing a stacktrace captured at
  322. /// the point where the currently handled exception was thrown by its
  323. /// initial throw-expression (i.e. not a rethrow), or an empty
  324. /// basic_stacktrace object if:
  325. ///
  326. /// - the `boost_stacktrace_from_exception` library is not linked to the
  327. /// current binary, or
  328. /// - the initialization of stacktrace failed, or
  329. /// - stacktrace captures are not enabled for the throwing thread, or
  330. /// - no exception is being handled, or
  331. /// - due to implementation-defined reasons.
  332. ///
  333. /// `alloc` is passed to the constructor of the stacktrace object.
  334. /// Rethrowing an exception using a throw-expression with no operand does
  335. /// not alter the captured stacktrace.
  336. ///
  337. /// Implements https://wg21.link/p2370r1
  338. static basic_stacktrace<Allocator> from_current_exception(const allocator_type& alloc = allocator_type()) noexcept {
  339. // Matches the constant from implementation
  340. constexpr std::size_t kStacktraceDumpSize = 4096;
  341. const char* trace = nullptr;
  342. #if defined(__GNUC__) && defined(__ELF__)
  343. if (impl::current_exception_stacktrace) {
  344. trace = impl::current_exception_stacktrace();
  345. }
  346. #elif defined(BOOST_MSVC)
  347. trace = boost_stacktrace_impl_current_exception_stacktrace();
  348. #endif
  349. if (trace) {
  350. try {
  351. return basic_stacktrace<Allocator>::from_dump(trace, kStacktraceDumpSize, alloc);
  352. } catch (const std::exception&) {
  353. // ignore
  354. }
  355. }
  356. return basic_stacktrace<Allocator>{0, 0, alloc};
  357. }
  358. };
  359. /// @brief Compares stacktraces for less, order is platform dependent.
  360. ///
  361. /// @b Complexity: Amortized O(1); worst case O(size())
  362. ///
  363. /// @b Async-Handler-Safety: \asyncsafe.
  364. template <class Allocator1, class Allocator2>
  365. bool operator< (const basic_stacktrace<Allocator1>& lhs, const basic_stacktrace<Allocator2>& rhs) noexcept {
  366. return lhs.size() < rhs.size() || (lhs.size() == rhs.size() && lhs.as_vector() < rhs.as_vector());
  367. }
  368. /// @brief Compares stacktraces for equality.
  369. ///
  370. /// @b Complexity: Amortized O(1); worst case O(size())
  371. ///
  372. /// @b Async-Handler-Safety: \asyncsafe.
  373. template <class Allocator1, class Allocator2>
  374. bool operator==(const basic_stacktrace<Allocator1>& lhs, const basic_stacktrace<Allocator2>& rhs) noexcept {
  375. return lhs.as_vector() == rhs.as_vector();
  376. }
  377. /// Comparison operators that provide platform dependant ordering and have amortized O(1) complexity; O(size()) worst case complexity; are Async-Handler-Safe.
  378. template <class Allocator1, class Allocator2>
  379. bool operator> (const basic_stacktrace<Allocator1>& lhs, const basic_stacktrace<Allocator2>& rhs) noexcept {
  380. return rhs < lhs;
  381. }
  382. template <class Allocator1, class Allocator2>
  383. bool operator<=(const basic_stacktrace<Allocator1>& lhs, const basic_stacktrace<Allocator2>& rhs) noexcept {
  384. return !(lhs > rhs);
  385. }
  386. template <class Allocator1, class Allocator2>
  387. bool operator>=(const basic_stacktrace<Allocator1>& lhs, const basic_stacktrace<Allocator2>& rhs) noexcept {
  388. return !(lhs < rhs);
  389. }
  390. template <class Allocator1, class Allocator2>
  391. bool operator!=(const basic_stacktrace<Allocator1>& lhs, const basic_stacktrace<Allocator2>& rhs) noexcept {
  392. return !(lhs == rhs);
  393. }
  394. /// Fast hashing support, O(st.size()) complexity; Async-Handler-Safe.
  395. template <class Allocator>
  396. std::size_t hash_value(const basic_stacktrace<Allocator>& st) noexcept {
  397. return boost::hash_range(st.as_vector().begin(), st.as_vector().end());
  398. }
  399. /// Returns std::string with the stacktrace in a human readable format; unsafe to use in async handlers.
  400. template <class Allocator>
  401. std::string to_string(const basic_stacktrace<Allocator>& bt) {
  402. if (!bt) {
  403. return std::string();
  404. }
  405. return boost::stacktrace::detail::to_string(&bt.as_vector()[0], bt.size());
  406. }
  407. /// Outputs stacktrace in a human readable format to the output stream `os`; unsafe to use in async handlers.
  408. template <class CharT, class TraitsT, class Allocator>
  409. std::basic_ostream<CharT, TraitsT>& operator<<(std::basic_ostream<CharT, TraitsT>& os, const basic_stacktrace<Allocator>& bt) {
  410. return os << boost::stacktrace::to_string(bt);
  411. }
  412. /// This is the typedef to use unless you'd like to provide a specific allocator to boost::stacktrace::basic_stacktrace.
  413. typedef basic_stacktrace<> stacktrace;
  414. }} // namespace boost::stacktrace
  415. #ifdef BOOST_INTEL
  416. # pragma warning(pop)
  417. #endif
  418. #endif // BOOST_STACKTRACE_STACKTRACE_HPP