feat(Stacktrace): split capture/resolve, add capabilities, bounded resolver cache, safe source snippets, and crash marker (M-STACKTRACE-01..04)

This commit is contained in:
faumaray committed 2026-11-24 10:26:24 +03:00
1 parent 3d8dfb0ea2
commit 7b57b355cd
4 files changed
+1171 -121

No files matched your search

+732 -102
View File
@@ -1,114 +1,744 @@
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Stacktrace/Color.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <filesystem>
#include <format>
#include <fstream>
#include <sstream>
#include <Void/Stacktrace/Color.hpp>
#ifndef _WIN32
#include <dlfcn.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <boost/core/demangle.hpp>
#include <boost/stacktrace.hpp>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <filesystem>
#include <format>
#include <fstream>
#include <list>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <utility>
namespace Void::Stacktrace
{
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
unsigned max_frames)
{
std::vector<StackFrame> 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;
}
namespace
{
Void::Result::Result<std::string, Void::Result::Error>
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());
}
[[nodiscard]] RawFrame build_raw_frame(const void* addr_ptr)
{
RawFrame rf;
rf.address = reinterpret_cast<std::uintptr_t>(addr_ptr);
if (addr_ptr == nullptr) {
return rf;
}
#ifndef _WIN32
Dl_info info{};
if (::dladdr(addr_ptr, &info) != 0 && info.dli_fname != nullptr &&
info.dli_fname[0] != '\0') {
rf.module_path.assign(info.dli_fname);
const auto base = reinterpret_cast<std::uintptr_t>(info.dli_fbase);
rf.module_offset = (rf.address >= base) ? (rf.address - base) : 0;
struct stat st {};
if (::stat(info.dli_fname, &st) == 0) {
rf.module_id = std::format(
"{}:{}:{}:{}",
static_cast<unsigned long long>(st.st_dev),
static_cast<unsigned long long>(st.st_ino),
static_cast<unsigned long long>(st.st_size),
rf.module_path);
} else {
rf.module_id = rf.module_path;
}
}
#endif
return rf;
}
std::string format_stacktrace(const std::vector<StackFrame>& frames)
{
if (frames.empty()) {
return " <no stacktrace available>\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 << "<unknown>";
}
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();
}
[[nodiscard]] std::string redact_source_path(
std::string_view raw_path,
const std::vector<std::string>& redact_prefixes)
{
if (raw_path.empty()) {
return {};
}
if (redact_prefixes.empty()) {
return std::filesystem::path{raw_path}.filename().string();
}
std::string_view best_match;
for (const auto& prefix : redact_prefixes) {
if (!prefix.empty() && raw_path.starts_with(prefix) &&
prefix.size() > best_match.size()) {
best_match = prefix;
}
}
if (!best_match.empty()) {
std::string_view rest = raw_path.substr(best_match.size());
while (!rest.empty() && (rest.front() == '/' || rest.front() == '\\')) {
rest.remove_prefix(1);
}
return std::string{rest};
}
return std::filesystem::path{raw_path}.filename().string();
}
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames)
{
os << format_stacktrace(frames);
}
} // namespace Void::Stacktrace
[[nodiscard]] bool is_under_allowed_roots(
const std::filesystem::path& file,
const std::vector<std::filesystem::path>& roots,
std::filesystem::path& out_canonical,
Void::Result::Error& out_error)
{
if (roots.empty()) {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
"Source snippets require non-empty allowed_source_roots");
return false;
}
for (const auto& part : file) {
if (part == "..") {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
"Path traversal ('..') is rejected for source snippets");
return false;
}
}
std::error_code ec;
const auto canon_file = std::filesystem::canonical(file, ec);
if (ec) {
out_error = make_stacktrace_error(
StacktraceErrorCode::source_unreadable,
std::format("Cannot resolve snippet path '{}': {}",
file.string(), ec.message()));
return false;
}
if (!std::filesystem::is_regular_file(canon_file, ec) || ec) {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
std::format("Snippet target '{}' is not a regular file",
canon_file.string()));
return false;
}
for (const auto& root : roots) {
std::error_code rec;
const auto canon_root = std::filesystem::canonical(root, rec);
if (rec) {
continue;
}
const auto rel = canon_file.lexically_relative(canon_root);
if (!rel.empty() && rel.native() != "." && *rel.begin() != "..") {
out_canonical = canon_file;
return true;
}
}
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
std::format("Snippet path '{}' escapes allowed_source_roots",
canon_file.string()));
return false;
}
struct CacheKey {
std::string module_id;
std::uintptr_t offset{0};
[[nodiscard]] bool operator==(const CacheKey&) const = default;
};
struct CacheKeyHash {
[[nodiscard]] std::size_t operator()(const CacheKey& k) const noexcept
{
std::size_t h1 = std::hash<std::string>{}(k.module_id);
std::size_t h2 = std::hash<std::uintptr_t>{}(k.offset);
return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2));
}
};
struct CacheValue {
std::string function_name;
std::string raw_source_file;
int source_line{0};
FrameResolveStatus status{FrameResolveStatus::unresolved};
std::size_t byte_cost{0};
};
} // namespace
Capabilities capabilities() noexcept
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return Capabilities{
.raw_capture = true,
.symbols = true,
.line_info = true,
.async_signal_safe = false,
.backend_name = "boost.stacktrace.windbg"};
#else
return Capabilities{
.raw_capture = true,
.symbols = true,
.line_info = true,
.async_signal_safe = false,
.backend_name = "boost.stacktrace.addr2line"};
#endif
}
Void::Result::Result<RawTrace> capture(CaptureOptions options)
{
if (options.max_frames == 0 || options.max_frames > kMaxCaptureFrames) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
std::format("CaptureOptions::max_frames must be in [1, {}]",
kMaxCaptureFrames)));
}
RawTrace trace;
try {
const std::size_t probe_depth =
static_cast<std::size_t>(options.max_frames) + 1;
boost::stacktrace::stacktrace bt(
static_cast<std::size_t>(options.skip) + 1, probe_depth);
if (bt.size() > options.max_frames) {
trace.truncated = true;
}
const std::size_t count =
std::min<std::size_t>(bt.size(), options.max_frames);
trace.frames.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
trace.frames.push_back(build_raw_frame(bt[i].address()));
}
return trace;
} catch (const std::exception& e) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::backend_failed,
std::string{"Stacktrace raw capture failed: "} + e.what()));
} catch (...) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::backend_failed,
"Stacktrace raw capture failed"));
}
}
struct Resolver::Impl {
using LruList = std::list<std::pair<CacheKey, CacheValue>>;
using LookupMap = std::unordered_map<CacheKey, LruList::iterator, CacheKeyHash>;
std::size_t max_entries;
std::size_t max_bytes;
mutable std::mutex mutex;
LruList lru;
LookupMap map;
std::size_t current_bytes{0};
Impl(std::size_t entries, std::size_t bytes)
: max_entries(entries), max_bytes(bytes)
{
}
[[nodiscard]] std::optional<CacheValue> find_and_touch(const CacheKey& key)
{
if (key.module_id.empty()) {
return std::nullopt;
}
std::lock_guard lock{mutex};
const auto it = map.find(key);
if (it == map.end()) {
return std::nullopt;
}
lru.splice(lru.begin(), lru, it->second);
return it->second->second;
}
void insert(const CacheKey& key, CacheValue val)
{
if (key.module_id.empty() || max_entries == 0 || max_bytes == 0) {
return;
}
val.byte_cost =
96 + key.module_id.size() + val.function_name.size() +
val.raw_source_file.size();
if (val.byte_cost > max_bytes) {
return;
}
std::lock_guard lock{mutex};
if (const auto it = map.find(key); it != map.end()) {
current_bytes -= std::min(current_bytes, it->second->second.byte_cost);
it->second->second = val;
current_bytes += val.byte_cost;
lru.splice(lru.begin(), lru, it->second);
return;
}
while (!lru.empty() &&
(lru.size() >= max_entries ||
val.byte_cost > max_bytes - std::min(current_bytes, max_bytes))) {
const auto last = std::prev(lru.end());
current_bytes -= std::min(current_bytes, last->second.byte_cost);
map.erase(last->first);
lru.pop_back();
}
lru.emplace_front(key, std::move(val));
map.emplace(key, lru.begin());
current_bytes += lru.front().second.byte_cost;
}
};
Resolver::Resolver(std::size_t max_entries, std::size_t max_bytes)
: impl_(std::make_unique<Impl>(max_entries, max_bytes))
{
}
Resolver::~Resolver() = default;
std::size_t Resolver::invalidate_module(std::string_view module_id)
{
std::lock_guard lock{impl_->mutex};
std::size_t removed = 0;
for (auto it = impl_->lru.begin(); it != impl_->lru.end();) {
if (it->first.module_id == module_id) {
impl_->current_bytes -=
std::min(impl_->current_bytes, it->second.byte_cost);
impl_->map.erase(it->first);
it = impl_->lru.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
void Resolver::clear_cache()
{
std::lock_guard lock{impl_->mutex};
impl_->map.clear();
impl_->lru.clear();
impl_->current_bytes = 0;
}
std::size_t Resolver::cache_entries() const
{
std::lock_guard lock{impl_->mutex};
return impl_->map.size();
}
std::size_t Resolver::cache_bytes() const
{
std::lock_guard lock{impl_->mutex};
return impl_->current_bytes;
}
Void::Result::Result<std::string>
read_source_snippet_checked(const std::filesystem::path& file,
int line,
const ResolveOptions& options)
{
if (line <= 0 || options.context_lines < 0 ||
options.max_snippet_bytes == 0 || options.max_source_scan_bytes == 0 ||
options.max_line_bytes == 0) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
"Invalid line or snippet budget options"));
}
const auto& clock =
options.clock != nullptr
? *options.clock
: Void::Time::SystemMonotonicClock::instance();
if (options.stop.stop_requested()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::cancelled,
"Source snippet read cancelled"));
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::timeout,
"Source snippet read deadline expired"));
}
std::filesystem::path canonical_file;
Void::Result::Error path_err;
if (!is_under_allowed_roots(
file, options.allowed_source_roots, canonical_file, path_err)) {
return Void::Result::fail(std::move(path_err));
}
std::ifstream ifs{canonical_file};
if (!ifs.is_open()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::source_unreadable,
std::format("Cannot open canonical snippet file '{}'",
canonical_file.string())));
}
const std::int64_t target = line;
const std::int64_t ctx = options.context_lines;
const std::int64_t start = std::max<std::int64_t>(1, target - ctx);
const std::int64_t end = target + ctx;
std::string out;
std::string current_line;
std::int64_t line_num = 1;
std::size_t scanned_bytes = 0;
while (std::getline(ifs, current_line)) {
if (options.stop.stop_requested()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::cancelled,
"Source snippet read cancelled"));
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::timeout,
"Source snippet read deadline expired"));
}
scanned_bytes += current_line.size() + 1;
if (scanned_bytes > options.max_source_scan_bytes) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::scan_limit_exceeded,
"Source file scan byte budget exceeded"));
}
if (line_num >= start && line_num <= end) {
std::string_view clipped{current_line};
bool line_clipped = false;
if (clipped.size() > options.max_line_bytes) {
clipped = clipped.substr(0, options.max_line_bytes);
line_clipped = true;
}
const char* marker = (line_num == target) ? " >>> " : " ";
std::string formatted = std::format(
"{:>4}{}{}{}\n",
line_num,
marker,
clipped,
line_clipped ? "..." : "");
if (out.size() + formatted.size() > options.max_snippet_bytes) {
const std::size_t rem =
options.max_snippet_bytes -
std::min(out.size(), options.max_snippet_bytes);
out.append(formatted.data(), rem);
break;
}
out += formatted;
}
if (line_num >= end) {
break;
}
++line_num;
}
return out;
}
Void::Result::Result<ResolvedTrace>
Resolver::resolve(const RawTrace& raw, const ResolveOptions& options)
{
if (options.max_bytes == 0) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
"ResolveOptions::max_bytes must be positive"));
}
const auto& clock =
options.clock != nullptr
? *options.clock
: Void::Time::SystemMonotonicClock::instance();
ResolvedTrace trace;
trace.truncated = raw.truncated;
trace.frames.reserve(raw.frames.size());
for (const auto& rf : raw.frames) {
ResolvedFrame out_frame;
out_frame.raw = rf;
if (options.stop.stop_requested()) {
trace.incomplete = true;
out_frame.status = FrameResolveStatus::cancelled;
trace.frames.push_back(std::move(out_frame));
continue;
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
trace.incomplete = true;
out_frame.status = FrameResolveStatus::timed_out;
trace.frames.push_back(std::move(out_frame));
continue;
}
if (!options.resolve_symbols) {
out_frame.status = FrameResolveStatus::unresolved;
trace.frames.push_back(std::move(out_frame));
continue;
}
const CacheKey key{rf.module_id, rf.module_offset};
std::optional<CacheValue> cached = impl_->find_and_touch(key);
if (!cached.has_value() && rf.address != 0) {
CacheValue resolved;
try {
boost::stacktrace::frame f{
reinterpret_cast<const void*>(rf.address)};
const std::string mangled = f.name();
if (!mangled.empty()) {
resolved.function_name =
boost::core::demangle(mangled.c_str());
}
resolved.raw_source_file = f.source_file();
resolved.source_line =
static_cast<int>(f.source_line());
if (!resolved.function_name.empty()) {
resolved.status =
(!resolved.raw_source_file.empty() &&
resolved.source_line > 0)
? FrameResolveStatus::resolved
: FrameResolveStatus::symbols_only;
} else {
resolved.status = FrameResolveStatus::unresolved;
}
} catch (...) {
resolved.status = FrameResolveStatus::unresolved;
}
impl_->insert(key, resolved);
cached = std::move(resolved);
}
if (cached.has_value()) {
out_frame.function_name = cached->function_name;
out_frame.source_line = cached->source_line;
out_frame.status = cached->status;
out_frame.source_file = redact_source_path(
cached->raw_source_file, options.redact_prefixes);
if (options.source_snippets && !cached->raw_source_file.empty() &&
cached->source_line > 0) {
auto snip = read_source_snippet_checked(
cached->raw_source_file, cached->source_line, options);
if (snip) {
out_frame.source_snippet = std::move(*snip);
} else {
out_frame.diagnostic = std::move(snip).error();
}
}
}
const std::size_t frame_bytes =
96 + out_frame.function_name.size() + out_frame.source_file.size() +
out_frame.source_snippet.size();
if (trace.rendered_bytes + frame_bytes > options.max_bytes) {
out_frame.source_snippet.clear();
trace.truncated = true;
}
trace.rendered_bytes +=
96 + out_frame.function_name.size() + out_frame.source_file.size() +
out_frame.source_snippet.size();
trace.frames.push_back(std::move(out_frame));
}
return trace;
}
Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options)
{
Resolver transient{0, 0};
return transient.resolve(raw, options);
}
std::string format_resolved_trace(
const ResolvedTrace& trace, std::size_t max_bytes)
{
if (trace.frames.empty()) {
return " <no stacktrace available>\n";
}
std::string out;
for (std::size_t i = 0; i < trace.frames.size(); ++i) {
const auto& fr = trace.frames[i];
std::string line = std::format(
" #{:02} 0x{:x} {}\n",
i,
fr.raw.address,
fr.function_name.empty() ? std::string{"<unknown>"}
: fr.function_name);
if (!fr.source_file.empty() && fr.source_line > 0) {
line += std::format(
" at {}:{}\n", fr.source_file, fr.source_line);
}
if (!fr.source_snippet.empty()) {
line += fr.source_snippet;
}
if (out.size() + line.size() > max_bytes) {
constexpr std::string_view kTrunc = " ... [truncated]\n";
if (out.size() + kTrunc.size() <= max_bytes) {
out += kTrunc;
}
break;
}
out += line;
}
return out;
}
bool write_fatal_signal_marker(int fd, int sig) noexcept
{
#ifdef _WIN32
(void)fd;
(void)sig;
return false;
#else
if (fd < 0) {
return false;
}
char buf[64]{};
std::size_t pos = 0;
constexpr char kPrefix[] = "VOID_FATAL_SIGNAL sig=";
for (std::size_t i = 0; i < sizeof(kPrefix) - 1; ++i) {
buf[pos++] = kPrefix[i];
}
unsigned int u = 0;
if (sig < 0) {
buf[pos++] = '-';
u = static_cast<unsigned int>(-(sig + 1)) + 1U;
} else {
u = static_cast<unsigned int>(sig);
}
char rev[16]{};
std::size_t rpos = 0;
do {
rev[rpos++] = static_cast<char>('0' + (u % 10U));
u /= 10U;
} while (u > 0U && rpos < sizeof(rev));
while (rpos > 0U) {
buf[pos++] = rev[--rpos];
}
buf[pos++] = '\n';
std::size_t written = 0;
while (written < pos) {
const auto n = ::write(fd, buf + written, pos - written);
if (n > 0) {
written += static_cast<std::size_t>(n);
} else if (n < 0 && errno == EINTR) {
continue;
} else {
return false;
}
}
return true;
#endif
}
// ── Legacy compatibility API ─────────────────────────────────────────────────
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
unsigned max_frames)
{
std::vector<StackFrame> 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<std::string, Void::Result::Error>
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;
const std::int64_t start = std::max<std::int64_t>(
1, static_cast<std::int64_t>(line) - context_lines);
const std::int64_t end =
static_cast<std::int64_t>(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<StackFrame>& frames)
{
if (frames.empty()) {
return " <no stacktrace available>\n";
}
std::ostringstream oss;
for (std::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 << "<unknown>";
}
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<StackFrame>& frames)
{
os << format_stacktrace(frames);
}
} // namespace Void::Stacktrace