backtrace.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright Oliver Kowalke 2016.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #define UNW_LOCAL_ONLY
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <libunwind.h>
  9. #include <boost/context/continuation.hpp>
  10. namespace ctx = boost::context;
  11. void backtrace() {
  12. unw_cursor_t cursor;
  13. unw_context_t context;
  14. unw_getcontext( & context);
  15. unw_init_local( & cursor, & context);
  16. while ( 0 < unw_step( & cursor) ) {
  17. unw_word_t offset, pc;
  18. unw_get_reg( & cursor, UNW_REG_IP, & pc);
  19. if ( 0 == pc) {
  20. break;
  21. }
  22. std::cout << "0x" << pc << ":";
  23. char sym[256];
  24. if ( 0 == unw_get_proc_name( & cursor, sym, sizeof( sym), & offset) ) {
  25. std::cout << " (" << sym << "+0x" << offset << ")" << std::endl;
  26. } else {
  27. std::cout << " -- error: unable to obtain symbol name for this frame" << std::endl;
  28. }
  29. }
  30. }
  31. void bar() {
  32. backtrace();
  33. }
  34. void foo() {
  35. bar();
  36. }
  37. ctx::continuation f1( ctx::continuation && c) {
  38. foo();
  39. return std::move( c);
  40. }
  41. int main() {
  42. ctx::callcc( f1);
  43. std::cout << "main: done" << std::endl;
  44. return EXIT_SUCCESS;
  45. }