#include #include #include #include #include #include #include #include #include #include namespace Void::Stacktrace { std::vector capture_stacktrace(unsigned skip_frames, unsigned max_frames) { std::vector result; try { boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames); for (auto it = bt.begin(); it != bt.end(); ++it) { StackFrame frame; std::string name = it->name(); if (!name.empty()) { frame.function_name = boost::core::demangle(name.c_str()); } frame.source_file = it->source_file(); frame.source_line = it->source_line(); if (!frame.source_file.empty() && frame.source_line > 0) { frame.source_snippet = read_source_snippet(frame.source_file, frame.source_line, 2) .value_or(std::string{}); } result.push_back(std::move(frame)); } } catch (...) { } Void::Log::debug("Stacktrace", "captured {} frames", result.size()); return result; } Void::Result::Result read_source_snippet(const std::string& file, int line, int context_lines) { std::ifstream ifs{file}; if (!ifs.is_open()) { Void::Log::warn("Stacktrace", "read_source_snippet: cannot open '{}'", file); return Void::Result::fail( std::format("read_source_snippet: cannot open '{}'", file)); } std::ostringstream result; std::string current_line; int line_num = 1; int start = std::max(1, line - context_lines); int end = line + context_lines; while (std::getline(ifs, current_line)) { if (line_num >= start && line_num <= end) { std::string prefix = (line_num == line) ? " >>> " : " "; result << std::format("{:>4}{}{}\n", line_num, prefix, current_line); } if (line_num > end) { break; } ++line_num; } return Void::Result::ok(result.str()); } std::string format_stacktrace(const std::vector& frames) { if (frames.empty()) { return " \n"; } std::ostringstream oss; for (size_t i = 0; i < frames.size(); ++i) { const auto& frame = frames[i]; oss << std::format(" #{:02} ", i); if (!frame.function_name.empty()) { oss << (Color::g_color_enabled ? Color::apply(Color::bold_cyan, frame.function_name) : frame.function_name); } else { oss << ""; } if (!frame.source_file.empty() && frame.source_line > 0) { std::filesystem::path p{frame.source_file}; oss << "\n at " << (Color::g_color_enabled ? Color::apply(Color::dim, p.filename().string()) : p.filename().string()) << ":" << frame.source_line; } oss << "\n"; if (!frame.source_snippet.empty() && i < 5) { oss << " " << (Color::g_color_enabled ? Color::apply(Color::dim, frame.source_snippet) : frame.source_snippet); } } return oss.str(); } void print_stacktrace(std::ostream& os, const std::vector& frames) { os << format_stacktrace(frames); } } // namespace Void::Stacktrace