stacktrace.hpp 16 KB

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