| 45 | namespace stack_trace { |
| 46 | |
| 47 | std::string get() |
| 48 | { |
| 49 | std::stringstream ss; |
| 50 | |
| 51 | // Get stack frames |
| 52 | std::vector<void*> frames(128, nullptr); |
| 53 | const auto& frames_size = backtrace(frames.data(), frames.size()); |
| 54 | frames.resize(frames_size, nullptr); |
| 55 | |
| 56 | // Get demangled stack frame names |
| 57 | auto* symbols = backtrace_symbols(frames.data(), frames.size()); |
| 58 | for (size_t i = 0; i < frames.size(); ++i) { |
| 59 | ss << std::setw(4) << i << ": "; |
| 60 | Dl_info info; |
| 61 | dladdr(frames[i], &info); |
| 62 | if (info.dli_sname != nullptr) { |
| 63 | auto* name = |
| 64 | abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, nullptr); |
| 65 | if (name == nullptr) { |
| 66 | ss << info.dli_sname << " (demangling failed)"; |
| 67 | } |
| 68 | else { |
| 69 | ss << name; |
| 70 | } |
| 71 | std::free(name); |
| 72 | } |
| 73 | else { |
| 74 | if (symbols != nullptr) { |
| 75 | ss << symbols[i] << " "; |
| 76 | } |
| 77 | ss << "(could not find stack frame symbol)"; |
| 78 | } |
| 79 | ss << std::endl; |
| 80 | } |
| 81 | std::free(symbols); |
| 82 | |
| 83 | return ss.str(); |
| 84 | } |
| 85 | |
| 86 | namespace { |
| 87 | |