stacktrace.hpp 16 KB

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