From 7b57b355cd75cd3f81cc2fa79a40452299b9f9d9 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 10:26:24 +0300 Subject: [PATCH] feat(Stacktrace): split capture/resolve, add capabilities, bounded resolver cache, safe source snippets, and crash marker (M-STACKTRACE-01..04) --- include/Void/Stacktrace/Stacktrace.hpp | 219 +++++- src/Stacktrace/Stacktrace.cpp | 834 ++++++++++++++++++--- src/Stacktrace/module.cmake | 2 +- tests/standalone/Stacktrace/Stacktrace.cpp | 237 ++++++ 4 files changed, 1171 insertions(+), 121 deletions(-) create mode 100644 tests/standalone/Stacktrace/Stacktrace.cpp diff --git a/include/Void/Stacktrace/Stacktrace.hpp b/include/Void/Stacktrace/Stacktrace.hpp index cb16d9c..2c6e40b 100644 --- a/include/Void/Stacktrace/Stacktrace.hpp +++ b/include/Void/Stacktrace/Stacktrace.hpp @@ -1,31 +1,214 @@ #pragma once + #include #include +#include + +#include +#include +#include +#include +#include #include +#include #include +#include #include namespace Void::Stacktrace { - struct StackFrame { - std::string function_name; - std::string source_file; - int source_line{0}; - std::string source_snippet; - }; - std::vector capture_stacktrace(unsigned skip_frames = 0, - unsigned max_frames = 32); +inline constexpr std::size_t kMaxCaptureFrames = 256; +inline constexpr std::size_t kDefaultMaxSnippetBytes = 4096; +inline constexpr std::size_t kDefaultMaxRenderedBytes = 65536; +inline constexpr std::size_t kDefaultMaxSourceScanBytes = 1048576; +inline constexpr std::size_t kDefaultMaxLineLength = 4096; +inline constexpr std::size_t kDefaultResolverCacheEntries = 1024; +inline constexpr std::size_t kDefaultResolverCacheBytes = 4ULL * 1024ULL * 1024ULL; - /// Read a snippet of source around `line`. On failure (file missing, - /// not readable, etc.) returns Failure instead of an empty - /// string — callers that want the silent fallback can still do - /// `read_source_snippet(...).value_or("")`. - Void::Result::Result - read_source_snippet(const std::string& file, int line, - int context_lines = 3); +enum class StacktraceErrorCode : std::int32_t { + invalid_argument = 1, + unsafe_path = 2, + source_unreadable = 3, + scan_limit_exceeded = 4, + cancelled = 5, + timeout = 6, + backend_failed = 7 +}; + +[[nodiscard]] inline Void::Result::Error + make_stacktrace_error(StacktraceErrorCode code, std::string message = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case StacktraceErrorCode::invalid_argument: + case StacktraceErrorCode::unsafe_path: + kind = ErrorKind::invalid_argument; + break; + case StacktraceErrorCode::source_unreadable: + kind = ErrorKind::not_found; + break; + case StacktraceErrorCode::scan_limit_exceeded: + kind = ErrorKind::exhausted; + break; + case StacktraceErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case StacktraceErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case StacktraceErrorCode::backend_failed: + kind = ErrorKind::internal; + break; + } + + return Error{ + kind, + std::move(message), + ErrorCode{Void::Result::kStacktraceErrorDomain, + static_cast(code)}}; +} + +struct Capabilities { + bool raw_capture{true}; + bool symbols{true}; + bool line_info{true}; + bool async_signal_safe{false}; + std::string_view backend_name{"boost.stacktrace"}; +}; + +[[nodiscard]] Capabilities capabilities() noexcept; + +struct CaptureOptions { + unsigned skip{0}; + unsigned max_frames{32}; +}; + +struct RawFrame { + std::uintptr_t address{0}; + std::uintptr_t module_offset{0}; + std::string module_path{}; + std::string module_id{}; +}; + +struct RawTrace { + std::vector frames{}; + bool truncated{false}; +}; + +/// Capture raw instruction addresses and owned module identity metadata without +/// reading source files or emitting Void::Log events. +[[nodiscard]] Void::Result::Result + capture(CaptureOptions options = {}); + +enum class FrameResolveStatus : std::uint8_t { + resolved = 0, + symbols_only, + unresolved, + unsupported, + cancelled, + timed_out +}; + +struct ResolveOptions { + bool resolve_symbols{true}; + bool source_snippets{false}; + std::vector allowed_source_roots{}; + std::vector redact_prefixes{}; + int context_lines{3}; + std::size_t max_snippet_bytes{kDefaultMaxSnippetBytes}; + std::size_t max_bytes{kDefaultMaxRenderedBytes}; + std::size_t max_source_scan_bytes{kDefaultMaxSourceScanBytes}; + std::size_t max_line_bytes{kDefaultMaxLineLength}; + std::stop_token stop{}; + std::optional deadline{}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; +}; + +struct ResolvedFrame { + RawFrame raw{}; + std::string function_name{}; + std::string source_file{}; + int source_line{0}; + std::string source_snippet{}; + FrameResolveStatus status{FrameResolveStatus::unresolved}; + std::optional diagnostic{}; +}; + +struct ResolvedTrace { + std::vector frames{}; + bool truncated{false}; + bool incomplete{false}; + std::size_t rendered_bytes{0}; +}; + +/// Stateful bounded LRU resolver cache keyed by owned (module_id, module_offset). +class Resolver +{ +public: + explicit Resolver(std::size_t max_entries = kDefaultResolverCacheEntries, + std::size_t max_bytes = kDefaultResolverCacheBytes); + ~Resolver(); + + Resolver(const Resolver&) = delete; + Resolver& operator=(const Resolver&) = delete; + Resolver(Resolver&&) noexcept = delete; + Resolver& operator=(Resolver&&) noexcept = delete; + + [[nodiscard]] Void::Result::Result + resolve(const RawTrace& raw, const ResolveOptions& options = {}); + + std::size_t invalidate_module(std::string_view module_id); + void clear_cache(); + + [[nodiscard]] std::size_t cache_entries() const; + [[nodiscard]] std::size_t cache_bytes() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +[[nodiscard]] Void::Result::Result + resolve(const RawTrace& raw, const ResolveOptions& options = {}); + +[[nodiscard]] Void::Result::Result + read_source_snippet_checked(const std::filesystem::path& file, + int line, + const ResolveOptions& options); + +[[nodiscard]] std::string format_resolved_trace( + const ResolvedTrace& trace, + std::size_t max_bytes = kDefaultMaxRenderedBytes); + +/// Async-signal-safe fixed-buffer fatal diagnostic marker writer using only +/// stack storage and raw descriptor write(). +bool write_fatal_signal_marker(int fd, int sig) noexcept; + +// ── Legacy compatibility API ───────────────────────────────────────────────── + +struct StackFrame { + std::string function_name; + std::string source_file; + int source_line{0}; + std::string source_snippet; +}; + +std::vector capture_stacktrace(unsigned skip_frames = 0, + unsigned max_frames = 32); + +Void::Result::Result + read_source_snippet(const std::string& file, + int line, + int context_lines = 3); + +std::string format_stacktrace(const std::vector& frames); +void print_stacktrace(std::ostream& os, + const std::vector& frames); - std::string format_stacktrace(const std::vector& frames); - void print_stacktrace(std::ostream& os, - const std::vector& frames); } // namespace Void::Stacktrace diff --git a/src/Stacktrace/Stacktrace.cpp b/src/Stacktrace/Stacktrace.cpp index 8247581..8349ca6 100644 --- a/src/Stacktrace/Stacktrace.cpp +++ b/src/Stacktrace/Stacktrace.cpp @@ -1,114 +1,744 @@ #include -#include #include -#include -#include -#include -#include -#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif #include #include +#include +#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; - } +namespace +{ - 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()); - } +[[nodiscard]] RawFrame build_raw_frame(const void* addr_ptr) +{ + RawFrame rf; + rf.address = reinterpret_cast(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(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(st.st_dev), + static_cast(st.st_ino), + static_cast(st.st_size), + rf.module_path); + } else { + rf.module_id = rf.module_path; + } + } +#endif + return rf; +} - 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(); - } +[[nodiscard]] std::string redact_source_path( + std::string_view raw_path, + const std::vector& 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& frames) - { - os << format_stacktrace(frames); - } -} // namespace Void::Stacktrace +[[nodiscard]] bool is_under_allowed_roots( + const std::filesystem::path& file, + const std::vector& 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{}(k.module_id); + std::size_t h2 = std::hash{}(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 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(options.max_frames) + 1; + boost::stacktrace::stacktrace bt( + static_cast(options.skip) + 1, probe_depth); + if (bt.size() > options.max_frames) { + trace.truncated = true; + } + const std::size_t count = + std::min(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>; + using LookupMap = std::unordered_map; + + 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 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(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 + 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(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 + 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 cached = impl_->find_and_touch(key); + if (!cached.has_value() && rf.address != 0) { + CacheValue resolved; + try { + boost::stacktrace::frame f{ + reinterpret_cast(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(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 + 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 " \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{""} + : 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(-(sig + 1)) + 1U; + } else { + u = static_cast(sig); + } + char rev[16]{}; + std::size_t rpos = 0; + do { + rev[rpos++] = static_cast('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(n); + } else if (n < 0 && errno == EINTR) { + continue; + } else { + return false; + } + } + return true; +#endif +} + +// ── Legacy compatibility API ───────────────────────────────────────────────── + +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; + const std::int64_t start = std::max( + 1, static_cast(line) - context_lines); + const std::int64_t end = + static_cast(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 (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 << ""; + } + 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 \ No newline at end of file diff --git a/src/Stacktrace/module.cmake b/src/Stacktrace/module.cmake index 9401453..62cf316 100644 --- a/src/Stacktrace/module.cmake +++ b/src/Stacktrace/module.cmake @@ -5,7 +5,7 @@ else() endif() void_add_module(Stacktrace - INTERNAL_DEPS Functional LogState + INTERNAL_DEPS Functional Time LogState EXTERNAL_DEPS ${_void_stacktrace_target} DEPS_UNIX dl OPTIONS_UNIX -g -fno-omit-frame-pointer diff --git a/tests/standalone/Stacktrace/Stacktrace.cpp b/tests/standalone/Stacktrace/Stacktrace.cpp new file mode 100644 index 0000000..68fada9 --- /dev/null +++ b/tests/standalone/Stacktrace/Stacktrace.cpp @@ -0,0 +1,237 @@ +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Stacktrace; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +[[gnu::noinline]] Void::Result::Result + nested_capture_helper(CaptureOptions opt) +{ + return capture(opt); +} + +} // namespace + +Void::Testing::Test stacktrace_capabilities_and_empty_formatting() +{ + const auto caps = capabilities(); + expect(caps.raw_capture); + expect(!caps.async_signal_safe); + expect(!caps.backend_name.empty()); + + expect_eq(format_stacktrace({}), std::string{" \n"}); + expect_eq(format_resolved_trace(ResolvedTrace{}), + std::string{" \n"}); + + expect(!capture(CaptureOptions{.max_frames = 0}).has_value()); + expect(!capture(CaptureOptions{.max_frames = kMaxCaptureFrames + 1}).has_value()); +} + +Void::Testing::Test stacktrace_capture_no_log_recursion_and_no_source_io() +{ + std::atomic log_calls{0}; + struct LogReset { + ~LogReset() { (void)Void::Log::detach_and_drain(0); } + } guard; + Void::Log::set_sink([&](Void::Log::Level, + std::string_view, + std::string_view, + const std::source_location&) { + log_calls.fetch_add(1, std::memory_order_relaxed); + }); + + auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 8}); + require(raw.has_value()); + expect(!raw->frames.empty()); + expect_eq(log_calls.load(), 0); + + // Asking for 1 frame on a deeper call stack sets truncated = true. + auto trunc = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 1}); + require(trunc.has_value()); + expect_eq(trunc->frames.size(), std::size_t{1}); + expect(trunc->truncated); + + // Default resolve() performs no snippet file reads and emits no Void::Log calls. + auto res = resolve(*raw, ResolveOptions{}); + require(res.has_value()); + expect_eq(res->frames.size(), raw->frames.size()); + expect_eq(log_calls.load(), 0); + for (const auto& f : res->frames) { + expect(f.source_snippet.empty()); + } +} + +Void::Testing::Test stacktrace_resolver_cache_redaction_and_safe_snippets() +{ + const auto base = std::filesystem::temp_directory_path() / "void_stacktrace_test"; + std::filesystem::remove_all(base); + const auto allowed_root = base / "allowed"; + const auto secret_root = base / "secret"; + std::filesystem::create_directories(allowed_root); + std::filesystem::create_directories(secret_root); + + const auto src_file = allowed_root / "sample.cpp"; + { + std::ofstream os{src_file}; + for (int i = 1; i <= 20; ++i) { + os << "int line_" << i << " = " << i << ";\n"; + } + } + const auto outside_file = secret_root / "creds.txt"; + { + std::ofstream os{outside_file}; + os << "SECRET_KEY=12345\n"; + } + + ResolveOptions opt; + opt.allowed_source_roots = {allowed_root}; + opt.redact_prefixes = {allowed_root.string()}; + opt.context_lines = 1; + opt.max_snippet_bytes = 256; + + // 1. Valid read under allowed root. + auto ok_snip = read_source_snippet_checked(src_file, 10, opt); + require(ok_snip.has_value()); + expect(ok_snip->find(" >>> int line_10") != std::string::npos); + + // 2. Rejects empty allowed_source_roots, traversal, outside file, and symlinks escaping root. + ResolveOptions no_roots = opt; + no_roots.allowed_source_roots.clear(); + expect(!read_source_snippet_checked(src_file, 5, no_roots).has_value()); + + const auto traversal = allowed_root / ".." / "secret" / "creds.txt"; + auto trav_res = read_source_snippet_checked(traversal, 1, opt); + expect(!trav_res.has_value()); + expect_eq(trav_res.error().code().value, + static_cast(StacktraceErrorCode::unsafe_path)); + +#ifndef _WIN32 + const auto sym_escape = allowed_root / "escape.txt"; + std::error_code sym_ec; + std::filesystem::create_symlink(outside_file, sym_escape, sym_ec); + if (!sym_ec) { + auto sym_res = read_source_snippet_checked(sym_escape, 1, opt); + expect(!sym_res.has_value()); + expect_eq(sym_res.error().code().value, + static_cast(StacktraceErrorCode::unsafe_path)); + } +#endif + + // 3. Overflow-safe INT_MAX line arithmetic and scan byte limit. + auto int_max_res = read_source_snippet_checked( + src_file, std::numeric_limits::max(), opt); + expect(int_max_res.has_value()); + + ResolveOptions tiny_scan = opt; + tiny_scan.max_source_scan_bytes = 32; + auto scan_res = read_source_snippet_checked(src_file, 15, tiny_scan); + expect(!scan_res.has_value()); + expect_eq(scan_res.error().code().value, + static_cast(StacktraceErrorCode::scan_limit_exceeded)); + + // 4. Resolver cache hit, module invalidation, and entry/byte cap eviction. + Resolver resolver{2, kDefaultResolverCacheBytes}; + auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 4}); + require(raw.has_value() && !raw->frames.empty()); + + ResolveOptions sym_opt = opt; + sym_opt.source_snippets = false; + auto r1 = resolver.resolve(*raw, sym_opt); + require(r1.has_value()); + expect(resolver.cache_entries() <= 2); + + std::string first_mod; + for (const auto& f : raw->frames) { + if (!f.module_id.empty()) { + first_mod = f.module_id; + break; + } + } + if (!first_mod.empty()) { + (void)resolver.invalidate_module(first_mod); + } + resolver.clear_cache(); + expect_eq(resolver.cache_entries(), std::size_t{0}); + expect_eq(resolver.cache_bytes(), std::size_t{0}); + + std::filesystem::remove_all(base); +} + +Void::Testing::Test stacktrace_cancellation_deadline_and_subprocess_crash() +{ + auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 4}); + require(raw.has_value() && !raw->frames.empty()); + + // Pre-cancelled stop_token marks incomplete = true while retaining raw frames. + std::stop_source ss; + ss.request_stop(); + ResolveOptions cancelled_opt; + cancelled_opt.stop = ss.get_token(); + auto cres = resolve(*raw, cancelled_opt); + require(cres.has_value()); + expect(cres->incomplete); + expect_eq(cres->frames.size(), raw->frames.size()); + expect(cres->frames[0].status == FrameResolveStatus::cancelled); + expect_eq(cres->frames[0].raw.address, raw->frames[0].address); + + // Expired ManualClock deadline also marks incomplete = true cleanly. + Void::Time::ManualClock clock; + const auto past = clock.now(); + (void)clock.advance(std::chrono::seconds{1}); + ResolveOptions timeout_opt; + timeout_opt.clock = &clock; + timeout_opt.deadline = past; + auto tres = resolve(*raw, timeout_opt); + require(tres.has_value()); + expect(tres->incomplete); + expect(tres->frames[0].status == FrameResolveStatus::timed_out); + +#ifndef _WIN32 + // Async-signal-safe fatal marker writer writes clean ASCII record. + int pipefd[2]{-1, -1}; + require(::pipe(pipefd) == 0); + expect(write_fatal_signal_marker(pipefd[1], SIGABRT)); + ::close(pipefd[1]); + char buf[128]{}; + const auto n = ::read(pipefd[0], buf, sizeof(buf) - 1); + ::close(pipefd[0]); + require(n > 0); + const std::string marker{buf, static_cast(n)}; + expect(marker.find("VOID_FATAL_SIGNAL sig=") != std::string::npos); + + // Subprocess crash isolation for fatal child aborts (replaced in-process signal UB). + const std::string self_exe = Void::Testing::current_executable_path(); + if (!self_exe.empty()) { + const std::vector args{"--selftest-child", "abort"}; + const auto run = Void::Testing::run_isolated_subprocess( + self_exe, + args, + Void::Testing::ProcessTestOptions{.timeout = std::chrono::seconds{5}}); + expect(run.outcome == Void::Testing::ProcessOutcome::crashed); + expect_eq(run.term_signal, SIGABRT); + } +#endif +}