stacktrace.hpp 17 KB

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