stacktrace.qbk 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. [library Boost.Stacktrace
  2. [quickbook 1.6]
  3. [version 1.0]
  4. [id stacktrace]
  5. [copyright 2016-2019 Antony Polukhin]
  6. [category Language Features Emulation]
  7. [license
  8. Distributed under the Boost Software License, Version 1.0.
  9. (See accompanying file LICENSE_1_0.txt or copy at
  10. [@http://www.boost.org/LICENSE_1_0.txt])
  11. ]
  12. ]
  13. [section Motivation]
  14. How can one display the call sequence in C++? What function called the current function? What call sequence led to an exception?
  15. Boost.Stacktrace library is a simple C++03 library that provides information about call sequence in a human-readable form.
  16. [endsect]
  17. [section Getting Started]
  18. [import ../example/assert_handler.cpp]
  19. [import ../example/terminate_handler.cpp]
  20. [import ../example/throwing_st.cpp]
  21. [import ../example/trace_addresses.cpp]
  22. [import ../example/debug_function.cpp]
  23. [import ../example/user_config.hpp]
  24. [section How to print current call stack]
  25. [classref boost::stacktrace::stacktrace] contains methods for working with call-stack/backtraces/stacktraces. Here's a small example:
  26. ```
  27. #include <boost/stacktrace.hpp>
  28. // ... somewhere inside the `bar(int)` function that is called recursively:
  29. std::cout << boost::stacktrace::stacktrace();
  30. ```
  31. In that example:
  32. * `boost::stacktrace::` is the namespace that has all the classes and functions to work with stacktraces
  33. * [classref boost::stacktrace::stacktrace stacktrace()] is the default constructor call; constructor stores the current function call sequence inside the stacktrace class.
  34. Code from above will output something like this:
  35. ```
  36. 0# bar(int) at /path/to/source/file.cpp:70
  37. 1# bar(int) at /path/to/source/file.cpp:70
  38. 2# bar(int) at /path/to/source/file.cpp:70
  39. 3# bar(int) at /path/to/source/file.cpp:70
  40. 4# main at /path/to/main.cpp:93
  41. 5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
  42. 6# _start
  43. ```
  44. [note By default the Stacktrace library is very conservative in methods to decode stacktrace. If your output does not look as fancy as in example from above, see [link stacktrace.configuration_and_build section "Configuration and Build"] for allowing advanced features of the library. ]
  45. [endsect]
  46. [section Handle terminates, aborts and Segmentation Faults]
  47. Segmentation Faults and `std::terminate` calls sometimes happen in programs. Programmers usually wish to get as much information as possible on such incidents, so having a stacktrace will significantly improve debugging and fixing.
  48. `std::terminate` calls `std::abort`, so we need to capture stack traces on Segmentation Faults and Abort signals.
  49. [warning Writing a signal handler requires high attention! Only a few system calls allowed in signal handlers, so there's no cross platform way to print a stacktrace without a risk of deadlocking. The only way to deal with the problem - [*dump raw stacktrace into file/socket and parse it on program restart].]
  50. [warning Not all the platforms provide means for even getting stacktrace in async signal safe way. No stack trace will be saved on such platforms. ]
  51. Let's write a handler to safely dump stacktrace:
  52. [getting_started_terminate_handlers]
  53. Registering our handler:
  54. [getting_started_setup_handlers]
  55. At program start we check for a file with stacktrace and if it exist - we're writing it in human readable format:
  56. [getting_started_on_program_restart]
  57. Now we'll get the following output on `std::terminate` call after the program restarts:
  58. ```
  59. Previous run crashed:
  60. 0# 0x00007F2EC0A6A8EF
  61. 1# my_signal_handler(int) at ../example/terminate_handler.cpp:37
  62. 2# 0x00007F2EBFD84CB0
  63. 3# 0x00007F2EBFD84C37
  64. 4# 0x00007F2EBFD88028
  65. 5# 0x00007F2EC0395BBD
  66. 6# 0x00007F2EC0393B96
  67. 7# 0x00007F2EC0393BE1
  68. 8# bar(int) at ../example/terminate_handler.cpp:18
  69. 9# foo(int) at ../example/terminate_handler.cpp:22
  70. 10# bar(int) at ../example/terminate_handler.cpp:14
  71. 11# foo(int) at ../example/terminate_handler.cpp:22
  72. 12# main at ../example/terminate_handler.cpp:84
  73. 13# 0x00007F2EBFD6FF45
  74. 14# 0x0000000000402209
  75. ```
  76. [note Function names from shared libraries may not be decoded due to address space layout randomization. Still better than nothing.]
  77. [endsect]
  78. [section Better asserts]
  79. Pretty often assertions provide not enough information to locate the problem. For example you can see the following message on out-of-range access:
  80. ```
  81. ../../../boost/array.hpp:123: T& boost::array<T, N>::operator[](boost::array<T, N>::size_type) [with T = int; long unsigned int N = 5ul]: Assertion '(i < N)&&("out of range")' failed.
  82. Aborted (core dumped)
  83. ```
  84. That's not enough to locate the problem without debugger. There may be thousand code lines in real world examples and hundred places where that assertion could happen. Let's try to improve the assertions, and make them more informative:
  85. [getting_started_assert_handlers]
  86. We've defined the `BOOST_ENABLE_ASSERT_DEBUG_HANDLER` macro for the whole project. Now all the `BOOST_ASSERT` and `BOOST_ASSERT_MSG` will call our functions `assertion_failed` and `assertion_failed_msg` in case of failure. In `assertion_failed_msg` we output information that was provided by the assertion macro and [classref boost::stacktrace::stacktrace]:
  87. ```
  88. Expression 'i < N' is false in function 'T& boost::array<T, N>::operator[](boost::array<T, N>::size_type) [with T = int; long unsigned int N = 5ul; boost::array<T, N>::reference = int&; boost::array<T, N>::size_type = long unsigned int]': out of range.
  89. Backtrace:
  90. 0# boost::assertion_failed_msg(char const*, char const*, char const*, char const*, long) at ../example/assert_handler.cpp:39
  91. 1# boost::array<int, 5ul>::operator[](unsigned long) at ../../../boost/array.hpp:124
  92. 2# bar(int) at ../example/assert_handler.cpp:17
  93. 3# foo(int) at ../example/assert_handler.cpp:25
  94. 4# bar(int) at ../example/assert_handler.cpp:17
  95. 5# foo(int) at ../example/assert_handler.cpp:25
  96. 6# main at ../example/assert_handler.cpp:54
  97. 7# 0x00007F991FD69F45 in /lib/x86_64-linux-gnu/libc.so.6
  98. 8# 0x0000000000401139
  99. ```
  100. Now we do know the steps that led to the assertion and can find the error without debugger.
  101. [endsect]
  102. [section Exceptions with stacktrace]
  103. You can provide more information along with exception by embedding stacktraces into the exception. There are many ways to do that, here's how to doe that using Boost.Exception:
  104. * Declare a `boost::error_info` typedef that holds the stacktrace:
  105. [getting_started_class_traced]
  106. * Write a helper class for throwing any exception with stacktrace:
  107. [getting_started_class_with_trace]
  108. * Use `throw_with_trace(E);` instead of just `throw E;`:
  109. [getting_started_throwing_with_trace]
  110. * Process exceptions:
  111. [getting_started_catching_trace]
  112. Code from above will output:
  113. ```
  114. 'i' must not be greater than zero in oops()
  115. 0# void throw_with_trace<std::logic_error>(std::logic_error const&) at ../example/throwing_st.cpp:22
  116. 1# oops(int) at ../example/throwing_st.cpp:38
  117. 2# bar(int) at ../example/throwing_st.cpp:54
  118. 3# foo(int) at ../example/throwing_st.cpp:59
  119. 4# bar(int) at ../example/throwing_st.cpp:49
  120. 5# foo(int) at ../example/throwing_st.cpp:59
  121. 6# main at ../example/throwing_st.cpp:76
  122. 7# 0x00007FAC113BEF45 in /lib/x86_64-linux-gnu/libc.so.6
  123. 8# 0x0000000000402ED9
  124. ```
  125. [endsect]
  126. [section Enabling and disabling stacktraces]
  127. At some point arises a requirement to easily enable/disable stacktraces for a whole project. That could be easily achieved.
  128. Just define *BOOST_STACKTRACE_LINK* for a whole project. Now you can enable/disable stacktraces by just linking with different libraries:
  129. * link with `boost_stacktrace_noop` to disable backtracing
  130. * link with other `boost_stacktrace_*` libraries
  131. See [link stacktrace.configuration_and_build section "Configuration and Build"] for more info.
  132. [endsect]
  133. [section Saving stacktraces by specified format]
  134. [classref boost::stacktrace::stacktrace] provides access to individual [classref boost::stacktrace::frame frames] of the stacktrace,
  135. so that you could save stacktrace information in your own format. Consider the example, that saves only function addresses of each frame:
  136. [getting_started_trace_addresses]
  137. Code from above will output:
  138. ```
  139. 0x7fbcfd17f6b5,0x400d4a,0x400d61,0x400d61,0x400d61,0x400d61,0x400d77,0x400cbf,0x400dc0,0x7fbcfc82d830,0x400a79,
  140. ```
  141. [endsect]
  142. [section Getting function information from pointer]
  143. [classref boost::stacktrace::frame] provides information about functions. You may construct that class from function pointer and get the function name at runtime:
  144. [getting_started_debug_function]
  145. Code from above will output:
  146. ```
  147. my_signal_handler(int) at boost/libs/stacktrace/example/debug_function.cpp:21
  148. ```
  149. [endsect]
  150. [section Global control over stacktrace output format]
  151. You may override the behavior of default stacktrace output operator by defining the macro from Boost.Config [macroref BOOST_USER_CONFIG] to point to a file like following:
  152. [getting_started_user_config]
  153. Implementation of `do_stream_st` may be the following:
  154. [getting_started_user_config_impl]
  155. Code from above will output:
  156. ```
  157. Terminate called:
  158. 0# bar(int)
  159. 1# foo(int)
  160. 2# bar(int)
  161. 3# foo(int)
  162. ```
  163. [endsect]
  164. [/
  165. [section Store stacktraces into shared memory]
  166. There's a way to serialize stacktrace in async safe manner and share that serialized representation with another process. Here's another example with signal handlers.
  167. This example is very close to the [link stacktrace.getting_started.handle_terminates_aborts_and_seg "Handle terminates, aborts and Segmentation Faults"], but this time we are dumping stacktrace into shared memory:
  168. [getting_started_terminate_handlers_shmem]
  169. After registering signal handlers and catching a signal, we may print stacktrace dumps on program restart:
  170. [getting_started_on_program_restart_shmem]
  171. The program output will be the following:
  172. ```
  173. Previous run crashed and left trace in shared memory:
  174. 0# 0x00007FD51C7218EF
  175. 1# my_signal_handler2(int) at ../example/terminate_handler.cpp:68
  176. 2# 0x00007FD51B833CB0
  177. 3# 0x00007FD51B833C37
  178. 4# 0x00007FD51B837028
  179. 5# 0x00007FD51BE44BBD
  180. 6# 0x00007FD51BE42B96
  181. 7# 0x00007FD51BE42BE1
  182. 8# bar(int) at ../example/terminate_handler.cpp:18
  183. 9# foo(int) at ../example/terminate_handler.cpp:22
  184. 10# bar(int) at ../example/terminate_handler.cpp:14
  185. 11# foo(int) at ../example/terminate_handler.cpp:22
  186. 12# run_3(char const**) at ../example/terminate_handler.cpp:152
  187. 13# main at ../example/terminate_handler.cpp:207
  188. 14# 0x00007FD51B81EF45
  189. 15# 0x0000000000402999
  190. ```
  191. [endsect]
  192. ]
  193. [endsect]
  194. [section Configuration and Build]
  195. By default Boost.Stacktrace is a header-only library, but you may change that and use the following macros to improve build times or to be able to tune library without recompiling your project:
  196. [table:linkmacro Link macros
  197. [[Macro name] [Effect]]
  198. [[*BOOST_STACKTRACE_LINK*] [Disable header-only build and require linking with shared or static library that contains the tracing implementation. If *BOOST_ALL_DYN_LINK* is defined, then link with shared library.]]
  199. [[*BOOST_STACKTRACE_DYN_LINK*] [Disable header-only build and require linking with shared library that contains tracing implementation.]]
  200. ]
  201. In header only mode library could be tuned by macro. If one of the link macro from above is defined, you have to manually link with one of the libraries:
  202. [table:libconfig Config
  203. [[Macro name or default] [Library] [Effect] [Platforms] [Uses debug information [footnote This will provide more readable backtraces with *source code locations* if the binary is built with debug information.]] [Uses dynamic exports information [footnote This will provide readable function names in backtrace for functions that are exported by the binary. Compiling with `-rdynamic` flag, without `-fisibility=hidden` or marking functions as exported produce a better stacktraces.]] ]
  204. [[['default for MSVC, Intel on Windows, MinGW-w64] / *BOOST_STACKTRACE_USE_WINDBG*] [*boost_stacktrace_windbg*] [ Uses COM to show debug info. May require linking with *ole32* and *dbgeng*. ] [MSVC, MinGW-w64, Intel on Windows] [yes] [no]]
  205. [[['default for other platforms]] [*boost_stacktrace_basic*] [Uses compiler intrinsics to collect stacktrace and if possible `::dladdr` to show information about the symbol. Requires linking with *libdl* library on POSIX platforms.] [Any compiler on POSIX or MinGW] [no] [yes]]
  206. [[*BOOST_STACKTRACE_USE_WINDBG_CACHED*] [*boost_stacktrace_windbg_cached*] [ Uses COM to show debug info and caches COM instances in TLS for better performance. Useful only for cases when traces are gathered very often. [footnote This may affect other components of your program that use COM, because this mode calls the `CoInitializeEx(0, COINIT_MULTITHREADED)` on first use and does not call `::CoUninitialize();` until the current thread is destroyed. ] May require linking with *ole32* and *dbgeng*. ] [MSVC, Intel on Windows] [yes] [no]]
  207. [[*BOOST_STACKTRACE_USE_BACKTRACE*] [*boost_stacktrace_backtrace*] [Requires linking with *libdl* on POSIX and *libbacktrace* libraries. *libbacktrace* is probably already installed in your system[footnote If you are using Clang with libstdc++ you could get into troubles of including `<backtrace.h>`, because on some platforms Clang does not search for headers in the GCC's include paths and any attempt to add GCC's include path leads to linker errors. To explicitly specify a path to the `<backtrace.h>` header you could define the *BOOST_STACKTRACE_BACKTRACE_INCLUDE_FILE* to a full path to the header. For example on Ubuntu Xenial use the command line option *-DBOOST_STACKTRACE_BACKTRACE_INCLUDE_FILE=</usr/lib/gcc/x86_64-linux-gnu/5/include/backtrace.h>* while building with Clang. ], or built into your compiler.
  208. Otherwise (if you are a *MinGW*/*MinGW-w64* user for example) it can be downloaded [@https://github.com/ianlancetaylor/libbacktrace from here] or [@https://github.com/gcc-mirror/gcc/tree/master/libbacktrace from here]. ] [Any compiler on POSIX, or MinGW, or MinGW-w64] [yes] [yes]]
  209. [[*BOOST_STACKTRACE_USE_ADDR2LINE*] [*boost_stacktrace_addr2line*] [Use *addr2line* program to retrieve stacktrace. Requires linking with *libdl* library and `::fork` system call. Macro *BOOST_STACKTRACE_ADDR2LINE_LOCATION* must be defined to the absolute path to the addr2line executable if it is not located in /usr/bin/addr2line. ] [Any compiler on POSIX] [yes] [yes]]
  210. [[*BOOST_STACKTRACE_USE_NOOP*] [*boost_stacktrace_noop*] [Use this if you wish to disable backtracing. `stacktrace::size()` with that macro always returns 0. ] [All] [no] [no]]
  211. ]
  212. [*Examples:]
  213. * if you wish to switch to more powerful implementation on Clang/MinGW and *BOOST_STACKTRACE_LINK* is defined, you just need link with "*-lboost_stacktrace_backtrace -ldl -lbacktrace*" or "*-lboost_stacktrace_addr2line -ldl*"
  214. * if you wish to disable backtracing and *BOOST_STACKTRACE_LINK* is defined, you just need link with *-lboost_stacktrace_noop*
  215. * if you wish to disable backtracing and you use the library in header only mode, you just need to define *BOOST_STACKTRACE_USE_NOOP* for the whole project and recompile it
  216. [section MinGW and MinGW-w64 specific notes]
  217. MinGW-w64 and MinGW (without -w64) users have to install libbacktrace for getting better stacktraces. Follow the instruction:
  218. Let's assume that you've installed MinGW into C:\MinGW and downloaded [@https://github.com/ianlancetaylor/libbacktrace libbacktrace sources] into C:\libbacktrace-master
  219. * Configure & build libbacktrace from console:
  220. * C:\MinGW\msys\1.0\bin\sh.exe
  221. * cd /c/libbacktrace-master
  222. * ./configure CC=/c/MinGW/bin/gcc.exe CXX=/c/MinGW/bin/g++.exe
  223. * make
  224. * ./libtool --mode=install /usr/bin/install -c libbacktrace.la '/c/libbacktrace-master'
  225. * Add info to the project-config.jam in the Boost folder:
  226. * using gcc : 6 : "C:\\MinGW\\bin\\g++.exe" : <compileflags>-I"C:\\libbacktrace-master\\" <linkflags>-L"C:\\libbacktrace-master\\" ;
  227. * Now you can use a header only version by defining *BOOST_STACKTRACE_USE_BACKTRACE* for your project or build the stacktrace library from Boost folder:
  228. * b2.exe toolset=gcc-6 --with-stacktrace
  229. [endsect]
  230. [endsect]
  231. [section Acknowledgements]
  232. In order of helping and advising:
  233. * Great thanks to Bjorn Reese for highlighting the async-signal-safety issues.
  234. * Great thanks to Nat Goodspeed for requesting [classref boost::stacktrace::frame] like class.
  235. * Great thanks to Niall Douglas for making an initial review, helping with some platforms and giving great hints on library design.
  236. * Great thanks to all the library reviewers.
  237. [endsect]
  238. [xinclude autodoc.xml]