fork download
  1. #include <array>
  2. #include <cstddef>
  3. #include <stdexcept>
  4. #include <memory>
  5. #include <sstream>
  6. #include <string>
  7. #include <tuple>
  8. #include <vector>
  9. #include <execinfo.h>
  10. #include <cxxabi.h>
  11.  
  12. #include <iostream>
  13.  
  14. namespace bliksems {
  15. namespace internal {
  16. std::string demangle(std::string const& name) {
  17. int status;
  18. char *res = abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status);
  19. switch (status) {
  20. case 0: {
  21. std::string result(res);
  22. free(res);
  23. return result;
  24. }
  25. case -1: throw std::bad_alloc{};
  26. default: return name;
  27. }
  28. }
  29. }
  30.  
  31. struct stack_frame {
  32. void* address;
  33. std::string binary;
  34. std::string function;
  35. std::size_t offset;
  36. };
  37.  
  38. class exception : public std::exception {
  39. public:
  40. exception()
  41. : size{::backtrace(backtrace.data(), backtrace.size())} { }
  42.  
  43. std::vector<stack_frame> stack_trace() const {
  44. std::unique_ptr<char*, decltype(&::free)> symbols
  45. {backtrace_symbols(backtrace.data(), size), &::free};
  46.  
  47. std::vector<stack_frame> trace;
  48. for (int i = 0; i < size; ++i) {
  49. std::istringstream splitter{symbols.get()[i]};
  50.  
  51. std::string ignore;
  52.  
  53. stack_frame frame;
  54. splitter >> ignore;
  55. splitter >> frame.binary;
  56. splitter >> frame.address;
  57. splitter >> frame.function;
  58. splitter >> ignore;
  59. splitter >> frame.offset;
  60.  
  61. frame.function = internal::demangle(frame.function);
  62.  
  63. trace.push_back(std::move(frame));
  64. }
  65. return trace;
  66. }
  67.  
  68. private:
  69. int size;
  70. std::array<void*, 128> backtrace;
  71. };
  72. }
  73.  
  74. int main() {
  75. try {
  76. throw bliksems::exception{};
  77. } catch (bliksems::exception const& e) {
  78. for (auto const& frame : e.stack_trace()) {
  79. std::cout
  80. << frame.binary << " "
  81. << frame.address << " "
  82. << frame.function << " + "
  83. << frame.offset << '\n';
  84. }
  85. std::cerr << e.what() << '\n';
  86. }
  87. }
  88.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'std::string bliksems::internal::demangle(const std::string&)':
prog.cpp:18:59: error: 'nullptr' was not declared in this scope
prog.cpp: In function 'int main()':
prog.cpp:78:32: error: expected initializer before ':' token
prog.cpp:86:5: error: expected primary-expression before '}' token
prog.cpp:86:5: error: expected ')' before '}' token
prog.cpp:86:5: error: expected primary-expression before '}' token
prog.cpp:86:5: error: expected ';' before '}' token
stdout
Standard output is empty