stacktrace.hpp 18 KB

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