Files

238 lines
8.2 KiB
C++

#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Subprocess.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <atomic>
#include <chrono>
#include <csignal>
#include <filesystem>
#include <fstream>
#include <limits>
#include <stop_token>
#include <string>
#include <vector>
namespace
{
using namespace Void::Stacktrace;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[gnu::noinline]] Void::Result::Result<RawTrace>
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{" <no stacktrace available>\n"});
expect_eq(format_resolved_trace(ResolvedTrace{}),
std::string{" <no stacktrace available>\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<int> 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<std::int32_t>(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<std::int32_t>(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<int>::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<std::int32_t>(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<std::size_t>(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<std::string> 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
}