feat(System): harden OwnedFd/Child process spawn, full-duplex bounds, durable replace_file, safe TempFile/TempDir, and SystemOnly consumer (M-SYSTEM-01, M-SYSTEM-02, M-SYSTEM-05)

This commit is contained in:
faumaray committed 2026-11-24 14:32:05 +03:00
1 parent 3f67b1ecb7
commit fcdbc063b2
14 files changed
+3538 -890

No files matched your search

+105 -84
View File
@@ -1,5 +1,7 @@
#pragma once #pragma once
#include <Void/Time/Clock.hpp>
#include <chrono> #include <chrono>
#include <cstdint> #include <cstdint>
#include <optional> #include <optional>
@@ -12,113 +14,132 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
// Generic, app-agnostic process/system resource queries. Used to feed monitors
// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully
// supported; other platforms return nullopt / 0 so callers degrade gracefully.
namespace Void::SystemInfo namespace Void::SystemInfo
{ {
// ── memory ────────────────────────────────────────────────────────────── /// Resident set size (physical memory) of the current process, in bytes.
/// nullopt if it cannot be determined on this platform.
/// Resident set size (physical memory) of the current process, in bytes. [[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
/// nullopt if it cannot be determined on this platform. {
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
{
#if defined(__linux__) #if defined(__linux__)
// /proc/self/statm: "size resident shared text lib data dt" in pages. std::ifstream statm{"/proc/self/statm"};
std::ifstream statm{"/proc/self/statm"}; std::uint64_t total_pages = 0, resident_pages = 0;
std::uint64_t total_pages = 0, resident_pages = 0; if (statm >> total_pages >> resident_pages) {
if (statm >> total_pages >> resident_pages) { const long page = ::sysconf(_SC_PAGESIZE);
const long page = ::sysconf(_SC_PAGESIZE); if (page > 0) {
if (page > 0) { return resident_pages * static_cast<std::uint64_t>(page);
return resident_pages * static_cast<std::uint64_t>(page); }
} }
} return std::nullopt;
return std::nullopt;
#else #else
return std::nullopt; return std::nullopt;
#endif #endif
} }
struct SystemMemory { struct SystemMemory {
std::uint64_t total = 0; ///< total physical RAM, bytes std::uint64_t total = 0; ///< total physical RAM, bytes
std::uint64_t available = 0; ///< approx. RAM available to new work std::uint64_t available = 0; ///< approx. RAM available to new work
}; };
/// Total and (approximately) available system memory in bytes. /// Total and (approximately) available system memory in bytes.
[[nodiscard]] inline std::optional<SystemMemory> system_memory() [[nodiscard]] inline std::optional<SystemMemory> system_memory()
{ {
#if defined(__linux__) #if defined(__linux__)
struct ::sysinfo info{}; struct ::sysinfo info{};
if (::sysinfo(&info) != 0) { if (::sysinfo(&info) != 0) {
return std::nullopt; return std::nullopt;
} }
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
SystemMemory m; SystemMemory m;
m.total = static_cast<std::uint64_t>(info.totalram) * unit; m.total = static_cast<std::uint64_t>(info.totalram) * unit;
// freeram excludes reclaimable cache/buffers, so this is conservative. m.available =
m.available = (static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit; return m;
return m;
#else #else
return std::nullopt; return std::nullopt;
#endif #endif
} }
// ── CPU ───────────────────────────────────────────────────────────────── struct CpuSample {
double ratio{0.0};
bool valid{false};
};
/// Samples this process's CPU usage between successive calls. usage() /// Samples this process's CPU usage between successive calls.
/// returns the fraction of a single core consumed since the previous /// `sample()` explicitly distinguishes real 0.0 from unavailable sampling.
/// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on class CpuSampler
/// multi-core workloads). The first call establishes the baseline and {
/// returns 0. public:
class CpuSampler explicit CpuSampler(
{ const Void::Time::MonotonicClock* clock =
public: &Void::Time::SystemMonotonicClock::instance())
: clock_(clock != nullptr ? clock
: &Void::Time::SystemMonotonicClock::instance())
{
reset();
}
CpuSampler() { reset(); } void reset()
{
void reset() wall_ = clock_->now();
{ baseline_valid_ = false;
wall_ = std::chrono::steady_clock::now();
#if defined(__linux__) #if defined(__linux__)
struct ::tms t{}; struct ::tms t{};
last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1)) if (::times(&t) != static_cast<::clock_t>(-1)) {
? 0 last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
: (t.tms_utime + t.tms_stime); static_cast<std::int64_t>(t.tms_stime);
baseline_valid_ = true;
}
#endif #endif
} }
[[nodiscard]] double usage() [[nodiscard]] CpuSample sample(
{ const Void::Time::MonotonicClock* override_clock = nullptr)
const auto now = std::chrono::steady_clock::now(); {
const std::chrono::duration<double> wall = now - wall_; const Void::Time::MonotonicClock* active =
wall_ = now; (override_clock != nullptr) ? override_clock : clock_;
const auto now = active->now();
const std::chrono::duration<double> wall = now - wall_;
wall_ = now;
#if defined(__linux__) #if defined(__linux__)
const long hz = ::sysconf(_SC_CLK_TCK); const long hz = ::sysconf(_SC_CLK_TCK);
struct ::tms t{}; struct ::tms t{};
if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) || if (!baseline_valid_ || hz <= 0 ||
wall.count() <= 0.0) { ::times(&t) == static_cast<::clock_t>(-1) || wall.count() <= 0.0) {
return 0.0; if (::times(&t) != static_cast<::clock_t>(-1)) {
} last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
const std::int64_t ticks = t.tms_utime + t.tms_stime; static_cast<std::int64_t>(t.tms_stime);
const double cpu_seconds = baseline_valid_ = true;
static_cast<double>(ticks - last_ticks_) / }
static_cast<double>(hz); return CpuSample{0.0, false};
last_ticks_ = ticks; }
return cpu_seconds / wall.count(); const std::int64_t ticks = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
const std::int64_t delta_ticks =
(ticks >= last_ticks_) ? (ticks - last_ticks_) : 0;
last_ticks_ = ticks;
const double cpu_seconds =
static_cast<double>(delta_ticks) / static_cast<double>(hz);
return CpuSample{cpu_seconds / wall.count(), true};
#else #else
return 0.0; (void)wall;
return CpuSample{0.0, false};
#endif #endif
} }
private: [[nodiscard]] double usage()
{
const auto s = sample();
return s.valid ? s.ratio : 0.0;
}
std::chrono::steady_clock::time_point wall_; private:
const Void::Time::MonotonicClock* clock_;
Void::Time::MonotonicClock::time_point wall_{};
bool baseline_valid_{false};
#if defined(__linux__) #if defined(__linux__)
std::int64_t last_ticks_ = 0; std::int64_t last_ticks_{0};
#endif #endif
}; };
} // namespace Void::SystemInfo } // namespace Void::SystemInfo
+531 -124
View File
@@ -1,144 +1,551 @@
#pragma once #pragma once
#include <Void/Log/Log.hpp>
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Types.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <fstream> #include <functional>
#include <ios> #include <optional>
#include <iterator> #include <span>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <utility> #include <utility>
#include <vector>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/random.h>
#endif
#endif
namespace Void::FileSystem namespace Void::FileSystem
{ {
/// Read the entire contents of a file as a string.
///
/// Failure modes wrapped in `Result`:
/// - File does not exist
/// - File cannot be opened (permissions, etc.)
/// - I/O error during read
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file(const std::filesystem::path& path)
{
std::ifstream f{path, std::ios::binary};
if (!f.is_open()) {
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
return Void::Result::fail(std::format(
"FileSystem::read_file: cannot open '{}'", path.string()));
}
std::string content{std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>()};
if (f.bad()) {
Void::Log::warn("FileSystem", "read_file: I/O error reading '{}'",
path.string());
return Void::Result::fail(
std::format("FileSystem::read_file: I/O error reading '{}'",
path.string()));
}
Void::Log::debug("FileSystem", "read_file: '{}' ({} bytes)", path.string(),
content.size());
return Void::Result::ok(std::move(content));
}
/// Write `content` to `path`, overwriting any existing file. struct ReadFileOptions {
/// std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
/// This is NOT crash-safe — a process killed mid-write may leave a };
/// truncated file. Use `atomic_write` when you need durability.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
write_file(const std::filesystem::path& path, std::string_view content)
{
std::ofstream f{path, std::ios::binary | std::ios::trunc};
if (!f.is_open()) {
Void::Log::warn("FileSystem", "write_file: cannot open '{}'", path.string());
return Void::Result::fail(std::format(
"FileSystem::write_file: cannot open '{}'", path.string()));
}
f.write(content.data(), static_cast<std::streamsize>(content.size()));
f.flush();
if (!f.good()) {
Void::Log::warn("FileSystem", "write_file: I/O error writing '{}'",
path.string());
return Void::Result::fail(
std::format("FileSystem::write_file: I/O error writing '{}'",
path.string()));
}
return {};
}
/// Crash-safe write: stage `content` in a sibling `.tmp` file, then enum class ReplaceDurability {
/// atomically rename onto `path`. The rename is atomic on POSIX atomic_visibility,
/// within the same filesystem; std::filesystem::rename uses the durable_sync,
/// platform-appropriate primitive (`ReplaceFileW` on Windows). };
///
/// Note: this does NOT fsync the staged file before rename. A
/// process or kernel crash between write and rename may leave the
/// `.tmp` file behind, but the original `path` is never corrupted.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_write(const std::filesystem::path& path,
std::string_view content)
{
auto staging = path;
staging += ".tmp";
if (auto r = write_file(staging, content); !r) {
return r;
}
std::error_code ec;
std::filesystem::rename(staging, path, ec);
if (ec) {
std::error_code ignore;
std::filesystem::remove(staging, ignore);
Void::Log::warn("FileSystem", "atomic_write: rename failed for '{}': {}",
path.string(), ec.message());
return Void::Result::fail(std::format(
"FileSystem::atomic_write: rename failed for '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "atomic_write: '{}' committed ({} bytes)",
path.string(), content.size());
return {};
}
/// Create `path` as a directory, including any missing parents. enum class ReplacePhase {
/// Succeeds (no-op) if `path` already exists as a directory. validation,
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error> create_stage,
ensure_directory(const std::filesystem::path& path) write_stage,
{ sync_stage,
std::error_code ec; rename,
if (std::filesystem::is_directory(path, ec)) { sync_parent,
return {}; };
}
std::filesystem::create_directories(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "ensure_directory: cannot create '{}': {}",
path.string(), ec.message());
return Void::Result::fail(std::format(
"FileSystem::ensure_directory: cannot create '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
return {};
}
/// Remove a file or directory (recursively for directories). struct ReplaceFailure {
/// Succeeds (no-op) if the path doesn't exist. Void::Result::Error error{};
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error> ReplacePhase phase{ReplacePhase::validation};
remove_path(const std::filesystem::path& path) bool visible_on_disk{false};
{ bool durability_unknown{false};
std::error_code ec; };
std::filesystem::remove_all(path, ec);
if (ec) { /// Optional test hook: return a POSIX errno to inject a failure at `phase`.
Void::Log::warn("FileSystem", "remove_path: cannot remove '{}': {}", using ReplaceFaultHook = std::function<std::optional<int>(ReplacePhase phase)>;
path.string(), ec.message());
return Void::Result::fail( struct ReplaceOptions {
std::format("FileSystem::remove_path: cannot remove '{}': {}", ReplaceDurability durability{ReplaceDurability::durable_sync};
path.string(), ec.message())); unsigned mode{0644};
} ReplaceFaultHook fault_hook{};
return {}; };
}
namespace detail
{
[[nodiscard]] inline std::uint64_t next_temp_entropy() noexcept
{
static std::atomic<std::uint64_t> counter{0};
std::uint64_t rnd = 0;
#if defined(__linux__)
if (::getrandom(&rnd, sizeof(rnd), 0) == static_cast<ssize_t>(sizeof(rnd))) {
return rnd ^ (counter.fetch_add(1, std::memory_order_relaxed) << 12);
}
#endif
const auto now = static_cast<std::uint64_t>(
std::chrono::steady_clock::now().time_since_epoch().count());
return now ^ (counter.fetch_add(1, std::memory_order_relaxed) *
0x9e3779b97f4a7c15ULL);
}
#ifndef _WIN32
[[nodiscard]] inline int fsync_eintr(int fd) noexcept
{
for (;;) {
if (::fsync(fd) == 0) {
return 0;
}
if (errno == EINTR) {
continue;
}
return errno;
}
}
#endif
} // namespace detail
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file_bounded(const std::filesystem::path& path,
ReadFileOptions options = {})
{
#ifndef _WIN32
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::read_file: cannot open '{}'", path.string()),
err)};
}
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
const auto sz = static_cast<std::uint64_t>(st.st_size);
if (sz > options.max_bytes) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
path.string(),
sz,
options.max_bytes))};
}
}
std::string content;
std::array<char, 8192> buf{};
for (;;) {
const ssize_t n = ::read(fd, buf.data(), buf.size());
if (n > 0) {
const auto un = static_cast<std::size_t>(n);
if (un > options.max_bytes - content.size()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
path.string(),
options.max_bytes))};
}
content.append(buf.data(), un);
} else if (n == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
Void::Log::warn("FileSystem",
"read_file: I/O error reading '{}'",
path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::read_file: I/O error reading '{}'",
path.string()),
err)};
}
}
Void::Log::debug("FileSystem",
"read_file: '{}' ({} bytes)",
path.string(),
content.size());
return content;
#else
(void)path;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::read_file: unsupported platform")};
#endif
}
/// Read the entire contents of a file as a string (bounded at 16 MiB default).
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file(const std::filesystem::path& path)
{
return read_file_bounded(path, ReadFileOptions{});
}
/// Write `content` to `path`, overwriting any existing file (not crash-safe).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
write_file(const std::filesystem::path& path, std::string_view content)
{
#ifndef _WIN32
const int fd =
::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
const int err = errno;
Void::Log::warn("FileSystem",
"write_file: cannot open '{}'",
path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::write_file: cannot open '{}'", path.string()),
err)};
}
Void::System::OwnedFd guard{fd};
std::size_t off = 0;
while (off < content.size()) {
const ssize_t n =
::write(fd, content.data() + off, content.size() - off);
if (n < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
Void::Log::warn("FileSystem",
"write_file: I/O error writing '{}'",
path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::write_file: I/O error writing '{}'",
path.string()),
err)};
}
off += static_cast<std::size_t>(n);
}
return guard.close();
#else
(void)path;
(void)content;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::write_file: unsupported platform")};
#endif
}
/// Atomically stage and replace `path`, distinguishing atomic visibility vs
/// durable commit (`fsync` stage -> `renameat` -> `fsync` parent dir).
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
const std::filesystem::path& path,
std::span<const std::byte> bytes,
ReplaceOptions options = {})
{
#ifndef _WIN32
auto check_fault = [&](ReplacePhase phase,
bool visible,
bool unknown) -> std::optional<ReplaceFailure> {
if (options.fault_hook) {
if (const auto injected = options.fault_hook(phase)) {
return ReplaceFailure{
Void::System::make_system_error(
unknown
? Void::System::SystemErrorCode::durability_unknown
: Void::System::map_errno_to_system_code(*injected),
std::format("FileSystem::replace_file: injected fault for '{}'",
path.string()),
*injected),
phase,
visible,
unknown};
}
}
return std::nullopt;
};
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
return std::unexpected{std::move(*f)};
}
if (path.empty() || !path.has_filename()) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::replace_file: empty path or missing filename"),
ReplacePhase::validation,
false,
false}};
}
const std::filesystem::path parent =
path.parent_path().empty() ? std::filesystem::path{"."}
: path.parent_path();
const std::string target_name = path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::replace_file: invalid target filename"),
ReplacePhase::validation,
false,
false}};
}
const int raw_dir_fd = ::open(
parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir_fd < 0) {
const int err = errno;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::replace_file: cannot open parent '{}'",
parent.string()),
err),
ReplacePhase::validation,
false,
false}};
}
Void::System::OwnedFd dir_fd{raw_dir_fd};
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
return std::unexpected{std::move(*f)};
}
std::string tmp_name;
Void::System::OwnedFd tmp_fd;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_tmp_{:016x}", target_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW |
O_CLOEXEC,
static_cast<mode_t>(options.mode));
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"FileSystem::replace_file: cannot create temp in '{}'",
parent.string()),
last_err),
ReplacePhase::create_stage,
false,
false}};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::replace_file: exhausted temp names",
last_err),
ReplacePhase::create_stage,
false,
false}};
}
bool cleanup_temp = true;
struct TempCleanup {
int dir_fd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempCleanup() noexcept
{
if (active != nullptr && *active && dir_fd >= 0 && name != nullptr) {
(void)::unlinkat(dir_fd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_temp};
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
return std::unexpected{std::move(*f)};
}
std::size_t off = 0;
while (off < bytes.size()) {
const ssize_t n =
::write(tmp_fd.get(), bytes.data() + off, bytes.size() - off);
if (n < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::replace_file: write failed for '{}'",
path.string()),
err),
ReplacePhase::write_stage,
false,
false}};
}
off += static_cast<std::size_t>(n);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
return std::unexpected{std::move(*f)};
}
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format(
"FileSystem::replace_file: stage fsync failed for '{}'",
path.string()),
err),
ReplacePhase::sync_stage,
false,
false}};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{ReplaceFailure{
std::move(closed.error()),
ReplacePhase::write_stage,
false,
false}};
}
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
return std::unexpected{std::move(*f)};
}
if (::renameat(
dir_fd.get(), tmp_name.c_str(), dir_fd.get(), target_name.c_str()) !=
0) {
const int err = errno;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::replace_file: rename failed for '{}'",
path.string()),
err),
ReplacePhase::rename,
false,
false}};
}
// Rename succeeded: target is now visible on disk; never unlink target!
cleanup_temp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
return std::unexpected{std::move(*f)};
}
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::replace_file: parent dir fsync failed after rename for '{}'",
path.string()),
err),
ReplacePhase::sync_parent,
true,
true}};
}
}
Void::Log::debug("FileSystem",
"replace_file: '{}' committed ({} bytes)",
path.string(),
bytes.size());
return {};
#else
(void)path;
(void)bytes;
(void)options;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::replace_file: unsupported platform"),
ReplacePhase::validation,
false,
false}};
#endif
}
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
const std::filesystem::path& path,
std::string_view content,
ReplaceOptions options = {})
{
const auto* ptr = reinterpret_cast<const std::byte*>(content.data());
return replace_file(path, std::span<const std::byte>{ptr, content.size()}, std::move(options));
}
/// Crash-safe write: stages content in a unique temp file and atomically
/// renames onto `path`. Delegates to `replace_file(..., atomic_visibility)` to
/// preserve 1.x atomic replacement behavior safely across concurrent writers.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_write(const std::filesystem::path& path, std::string_view content)
{
auto res = replace_file(
path,
content,
ReplaceOptions{.durability = ReplaceDurability::atomic_visibility});
if (!res.has_value()) {
Void::Log::warn("FileSystem",
"atomic_write: failed for '{}': {}",
path.string(),
res.error().error.message());
return std::unexpected{std::move(res.error().error)};
}
return {};
}
/// Create `path` as a directory, including any missing parents.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
ensure_directory(const std::filesystem::path& path)
{
std::error_code ec;
if (std::filesystem::is_directory(path, ec)) {
return {};
}
std::filesystem::create_directories(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"ensure_directory: cannot create '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::ensure_directory: cannot create '{}': {}",
path.string(),
ec.message()))};
}
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
return {};
}
/// Remove a file or directory (recursively for directories).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
remove_path(const std::filesystem::path& path)
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"remove_path: cannot remove '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::remove_path: cannot remove '{}': {}",
path.string(),
ec.message()))};
}
return {};
}
} // namespace Void::FileSystem } // namespace Void::FileSystem
+182 -51
View File
@@ -2,72 +2,203 @@
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono> #include <chrono>
#include <cstddef>
#include <filesystem> #include <filesystem>
#include <functional> #include <functional>
#include <optional>
#include <stop_token>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <utility>
#include <vector> #include <vector>
namespace Void::Process namespace Void::Process
{ {
/// Captured output from a completed subprocess. inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
struct Output { inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
int exit_code{0}; inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
std::string out; ///< captured stdout inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL;
std::string err; ///< captured stderr inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL;
};
/// Live line callbacks for run_streaming(). Each fires (on the calling /// Captured output from a completed subprocess.
/// thread, as output arrives) with one line of output, newline stripped. struct Output {
/// Either may be left empty. The full output is still accumulated into the int exit_code{0};
/// returned Output. std::string out; ///< captured stdout
struct StreamCallbacks { std::string err; ///< captured stderr
std::function<void(std::string_view line)> on_stdout; };
std::function<void(std::string_view line)> on_stderr;
};
/// Run an executable synchronously, capturing stdout and stderr separately. /// Live line callbacks for run_streaming() and communicate_blocking().
/// struct StreamCallbacks {
/// @param executable Path to the binary (searched via PATH when relative). std::function<void(std::string_view line)> on_stdout;
/// @param args Additional arguments passed after argv[0]. std::function<void(std::string_view line)> on_stderr;
/// @param stdin_data Data written to the process's stdin before reading. };
/// @param timeout Wall-clock limit; zero means no limit. On expiry the
/// process receives SIGTERM and the call returns.
///
/// Returns an error only when process creation itself fails (pipe or fork
/// failure). A process that exits non-zero still yields a successful Result
/// with the appropriate exit_code. A process whose executable is not found
/// exits with code 127 (POSIX convention).
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr enum class OverflowPolicy {
/// arrive, for progress reporting on long-running or streaming processes. fail_and_terminate,
/// The complete output is still captured into the returned Output. drain_and_truncate,
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error> };
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command". enum class EnvMode {
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error> inherit,
shell(std::string_view command, allowlist,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); explicit_only,
};
/// Replace the current process image while preserving its PID and inherited struct EnvironmentPolicy {
/// environment. Returns only when the platform does not support re-exec or EnvMode mode{EnvMode::inherit};
/// exec fails. std::vector<std::string> allowlist{};
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> std::vector<std::pair<std::string, std::string>> set_vars{};
reexec(const std::filesystem::path& executable, std::vector<std::string> unset_keys{};
const std::vector<std::string>& arguments); std::vector<std::string> redacted_keys{};
};
struct CaptureLimits {
std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes};
std::size_t max_stderr_bytes{kDefaultMaxStderrBytes};
std::size_t max_line_bytes{kDefaultMaxLineBytes};
std::size_t max_stdin_bytes{kDefaultMaxStdinBytes};
OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate};
};
struct SpawnOptions {
std::filesystem::path executable{};
std::vector<std::string> arguments{};
std::optional<std::filesystem::path> working_directory{};
EnvironmentPolicy environment{};
bool stdin_pipe{true};
bool stdout_pipe{true};
bool stderr_pipe{true};
bool search_path{true};
bool new_process_group{true};
std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}};
};
struct ExitStatus {
bool exited{false};
int code{-1};
int signal{0};
int raw_status{0};
};
struct CommunicateResult {
ExitStatus status{};
std::string out{};
std::string err{};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
};
class Child
{
public:
Child() noexcept = default;
Child(long long pid,
long long pgid,
bool owns_process_group,
Void::System::OwnedFd stdin_fd,
Void::System::OwnedFd stdout_fd,
Void::System::OwnedFd stderr_fd,
std::chrono::milliseconds kill_grace) noexcept;
~Child() noexcept;
Child(const Child&) = delete;
Child& operator=(const Child&) = delete;
Child(Child&& other) noexcept;
Child& operator=(Child&& other) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
[[nodiscard]] int stdin_fd() const noexcept;
[[nodiscard]] int stdout_fd() const noexcept;
[[nodiscard]] int stderr_fd() const noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept;
void close_stdin() noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_signal(int sig) noexcept;
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
[[nodiscard]] Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
try_wait();
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1});
private:
long long pid_{-1};
long long pgid_{-1};
bool owns_group_{false};
bool reaped_{true};
ExitStatus cached_status_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
void reset_and_reap() noexcept;
};
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
spawn(const SpawnOptions& options);
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data = {},
CaptureLimits limits = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
const StreamCallbacks* callbacks = nullptr);
/// Run an executable synchronously, capturing stdout and stderr separately.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Replace the current process image while preserving its PID and inherited
/// environment.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
/// Replace the current process image with explicit open-descriptor cleanup policy.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments,
bool close_extra_fds);
} // namespace Void::Process } // namespace Void::Process
+133 -81
View File
@@ -1,9 +1,13 @@
#pragma once #pragma once
#include <Void/Log/Log.hpp>
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <system_error> #include <system_error>
@@ -12,113 +16,161 @@
namespace Void::FileSystem namespace Void::FileSystem
{ {
struct ListDirectoryOptions {
std::size_t max_entries{65536};
};
/// Return true if path exists (file, directory, or symlink). /// Return true if path exists (file, directory, or symlink).
[[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept [[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept
{ {
std::error_code ec; std::error_code ec;
return std::filesystem::exists(path, ec); return std::filesystem::exists(path, ec);
} }
/// Return the size of a regular file in bytes. /// Return the size of a regular file in bytes.
[[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error> [[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error>
file_size(const std::filesystem::path& path) file_size(const std::filesystem::path& path)
{ {
std::error_code ec; std::error_code ec;
auto sz = std::filesystem::file_size(path, ec); auto sz = std::filesystem::file_size(path, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(), Void::Log::warn("FileSystem",
ec.message()); "file_size: cannot stat '{}': {}",
return Void::Result::fail( path.string(),
std::format("FileSystem::file_size: cannot stat '{}': {}", ec.message());
path.string(), ec.message())); return std::unexpected{Void::System::make_system_error(
} Void::System::map_errno_to_system_code(ec.value()),
return Void::Result::ok(sz); std::format("FileSystem::file_size: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(sz);
} }
/// Return the last-write time of a path. /// Return the last-write time of a path.
[[nodiscard]] inline Void::Result:: [[nodiscard]] inline Void::Result::
Result<std::filesystem::file_time_type, Void::Result::Error> Result<std::filesystem::file_time_type, Void::Result::Error>
last_modified(const std::filesystem::path& path) last_modified(const std::filesystem::path& path)
{ {
std::error_code ec; std::error_code ec;
auto t = std::filesystem::last_write_time(path, ec); auto t = std::filesystem::last_write_time(path, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(), Void::Log::warn("FileSystem",
ec.message()); "last_modified: cannot stat '{}': {}",
return Void::Result::fail( path.string(),
std::format("FileSystem::last_modified: cannot stat '{}': {}", ec.message());
path.string(), ec.message())); return std::unexpected{Void::System::make_system_error(
} Void::System::map_errno_to_system_code(ec.value()),
return Void::Result::ok(t); std::format("FileSystem::last_modified: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(t);
} }
/// List all entries in a directory (non-recursive, filesystem order). /// List entries in a directory up to `options.max_entries`.
[[nodiscard]] inline Void::Result:: [[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error> Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path) list_directory_bounded(const std::filesystem::path& path,
ListDirectoryOptions options = {})
{ {
std::error_code ec; std::error_code ec;
std::vector<std::filesystem::path> entries; std::vector<std::filesystem::path> entries;
for (const auto& entry : for (const auto& entry : std::filesystem::directory_iterator{path, ec}) {
std::filesystem::directory_iterator{path, ec}) { if (ec) {
if (ec) { break;
break; }
} if (entries.size() >= options.max_entries) {
entries.push_back(entry.path()); return std::unexpected{Void::System::make_system_error(
} Void::System::SystemErrorCode::limit_exceeded,
if (ec) { std::format(
Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}", "FileSystem::list_directory: '{}' exceeded max_entries ({})",
path.string(), ec.message()); path.string(),
return Void::Result::fail( options.max_entries))};
std::format("FileSystem::list_directory: cannot iterate '{}': {}", }
path.string(), ec.message())); entries.push_back(entry.path());
} }
Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)", if (ec) {
path.string(), entries.size()); Void::Log::warn("FileSystem",
return Void::Result::ok(std::move(entries)); "list_directory: cannot iterate '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
path.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"list_directory: '{}' ({} entries)",
path.string(),
entries.size());
return Void::Result::ok(std::move(entries));
}
/// List all entries in a directory (bounded at 65,536 default).
[[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path)
{
return list_directory_bounded(path, ListDirectoryOptions{});
} }
/// Copy a single file. Set overwrite=true to allow replacing an existing dst. /// Copy a single file. Set overwrite=true to allow replacing an existing dst.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error> [[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_file(const std::filesystem::path& src, copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst, const std::filesystem::path& dst,
bool overwrite = false) bool overwrite = false)
{ {
std::error_code ec; std::error_code ec;
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
: std::filesystem::copy_options::none; : std::filesystem::copy_options::none;
std::filesystem::copy_file(src, dst, opts, ec); std::filesystem::copy_file(src, dst, opts, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(), Void::Log::warn("FileSystem",
dst.string(), ec.message()); "copy_file: '{}' -> '{}': {}",
return Void::Result::fail( src.string(),
std::format("FileSystem::copy_file: '{}' -> '{}': {}", dst.string(),
src.string(), dst.string(), ec.message())); ec.message());
} return std::unexpected{Void::System::make_system_error(
Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(), Void::System::map_errno_to_system_code(ec.value()),
dst.string()); std::format("FileSystem::copy_file: '{}' -> '{}': {}",
return {}; src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_file: '{}' -> '{}'",
src.string(),
dst.string());
return {};
} }
/// Recursively copy a directory tree from src to dst. /// Recursively copy a directory tree from src to dst.
/// dst must not already exist; its parent must be accessible.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error> [[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_dir(const std::filesystem::path& src, copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst)
const std::filesystem::path& dst)
{ {
std::error_code ec; std::error_code ec;
std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive, std::filesystem::copy(
ec); src, dst, std::filesystem::copy_options::recursive, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(), Void::Log::warn("FileSystem",
dst.string(), ec.message()); "copy_dir: '{}' -> '{}': {}",
return Void::Result::fail( src.string(),
std::format("FileSystem::copy_dir: '{}' -> '{}': {}", dst.string(),
src.string(), dst.string(), ec.message())); ec.message());
} return std::unexpected{Void::System::make_system_error(
Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(), Void::System::map_errno_to_system_code(ec.value()),
dst.string()); std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
return {}; src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_dir: '{}' -> '{}'",
src.string(),
dst.string());
return {};
} }
} // namespace Void::FileSystem } // namespace Void::FileSystem
+224 -99
View File
@@ -1,126 +1,251 @@
#pragma once #pragma once
#include <Void/System/Path.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstdint> #include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <thread>
#include <utility> #include <utility>
#include <vector>
#ifndef _WIN32
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem namespace Void::FileSystem
{ {
/// RAII scoped directory under `std::filesystem::temp_directory_path()`.
///
/// The directory is created with a unique name on construction and
/// recursively removed on destruction. Useful in tests that need a
/// scratch area without manual cleanup.
///
/// Construction throws `std::system_error` if the directory cannot
/// be created. Use `TempDir::open(prefix)` for a non-throwing
/// `Result`-returning factory.
class TempDir
{
public:
explicit TempDir(std::string_view prefix = "void_test_") /// RAII scoped directory created with private `0700` permissions and removed
: m_path(make_unique_dir(prefix)) /// safely without following symlinks or deleting replaced directories.
{ class TempDir
} {
public:
explicit TempDir(std::string_view prefix = "void_test_")
{
auto created = create_unique_dir(
std::filesystem::temp_directory_path(), prefix);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempDir() noexcept ~TempDir() noexcept { remove_if_owned(); }
{
if (!m_path.empty()) {
Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string());
std::error_code ignore;
std::filesystem::remove_all(m_path, ignore);
}
}
TempDir(const TempDir&) = delete; TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete; TempDir& operator=(const TempDir&) = delete;
TempDir(TempDir&& other) noexcept TempDir(TempDir&& other) noexcept
: m_path(std::exchange(other.m_path, {})) : m_path(std::exchange(other.m_path, {})),
{ m_dev(std::exchange(other.m_dev, 0)),
} m_ino(std::exchange(other.m_ino, 0))
{
}
TempDir& operator=(TempDir&& other) noexcept TempDir& operator=(TempDir&& other) noexcept
{ {
if (this != &other) { if (this != &other) {
if (!m_path.empty()) { remove_if_owned();
std::error_code ignore; m_path = std::exchange(other.m_path, {});
std::filesystem::remove_all(m_path, ignore); m_dev = std::exchange(other.m_dev, 0);
} m_ino = std::exchange(other.m_ino, 0);
m_path = std::exchange(other.m_path, {}); }
} return *this;
return *this; }
}
[[nodiscard]] const std::filesystem::path& path() const noexcept [[nodiscard]] const std::filesystem::path& path() const noexcept
{ {
return m_path; return m_path;
} }
/// Build a path inside the temp dir. [[nodiscard]] std::filesystem::path
/// Example: `auto log_path = tmp / "test.log";` operator/(std::string_view relative) const
[[nodiscard]] std::filesystem::path {
operator/(std::string_view relative) const return m_path / relative;
{ }
return m_path / relative;
}
/// Non-throwing factory. [[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
[[nodiscard]] static Void::Result::Result<TempDir, open(std::string_view prefix = "void_test_")
Void::Result::Error> {
open(std::string_view prefix = "void_test_") return open_in(std::filesystem::temp_directory_path(), prefix);
{ }
try {
return Void::Result::ok(TempDir{prefix});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
private: [[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_test_")
{
return create_unique_dir(directory, prefix);
}
std::filesystem::path m_path; private:
struct InternalEmpty {};
explicit TempDir(InternalEmpty) noexcept {}
static std::filesystem::path std::filesystem::path m_path;
make_unique_dir(std::string_view prefix) std::uint64_t m_dev = 0;
{ std::uint64_t m_ino = 0;
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path(); #ifndef _WIN32
for (int attempt = 0; attempt < 16; ++attempt) { static void clear_dir_contents_nofollow(int dir_fd) noexcept
const auto seed = {
static_cast<std::uint64_t>( const int dup_fd = ::dup(dir_fd);
std::chrono::steady_clock::now() if (dup_fd < 0) {
.time_since_epoch() return;
.count()) ^ }
(counter.fetch_add(1, std::memory_order_relaxed) DIR* dir = ::fdopendir(dup_fd);
<< 16) ^ if (dir == nullptr) {
static_cast<std::uint64_t>(std::hash<std::thread::id>{}( (void)::close(dup_fd);
std::this_thread::get_id())); return;
auto candidate = }
base / std::format("{}{:016x}", prefix, seed); std::vector<std::string> subdirs;
std::error_code ec; std::vector<std::string> files;
if (std::filesystem::create_directory(candidate, ec)) { while (const struct dirent* ent = ::readdir(dir)) {
Void::Log::debug("FileSystem", "TempDir: created '{}'", const std::string_view name{ent->d_name};
candidate.string()); if (name == "." || name == "..") {
return candidate; continue;
} }
} struct stat st {};
throw std::system_error( if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) {
std::make_error_code(std::errc::file_exists), continue;
"TempDir: failed to create unique directory after 16 " }
"attempts"); if (S_ISDIR(st.st_mode)) {
} subdirs.emplace_back(name);
}; } else {
files.emplace_back(name);
}
}
(void)::closedir(dir);
for (const auto& f : files) {
(void)::unlinkat(dir_fd, f.c_str(), 0);
}
for (const auto& d : subdirs) {
const int sub_fd = ::openat(
dir_fd,
d.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (sub_fd >= 0) {
clear_dir_contents_nofollow(sub_fd);
(void)::close(sub_fd);
(void)::unlinkat(dir_fd, d.c_str(), AT_REMOVEDIR);
}
}
}
#endif
void remove_if_owned() noexcept
{
if (m_path.empty()) {
return;
}
#ifndef _WIN32
struct stat st {};
if (::lstat(m_path.c_str(), &st) != 0 || S_ISLNK(st.st_mode) ||
!S_ISDIR(st.st_mode)) {
return;
}
if (static_cast<std::uint64_t>(st.st_dev) != m_dev ||
static_cast<std::uint64_t>(st.st_ino) != m_ino ||
st.st_uid != ::geteuid()) {
return;
}
const int dir_fd = ::open(
m_path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (dir_fd < 0) {
return;
}
struct stat fd_st {};
if (::fstat(dir_fd, &fd_st) == 0 &&
static_cast<std::uint64_t>(fd_st.st_dev) == m_dev &&
static_cast<std::uint64_t>(fd_st.st_ino) == m_ino) {
clear_dir_contents_nofollow(dir_fd);
}
(void)::close(dir_fd);
(void)::rmdir(m_path.c_str());
Void::Log::debug(
"FileSystem", "TempDir: removed '{}'", m_path.string());
#endif
}
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
create_unique_dir(const std::filesystem::path& base,
std::string_view prefix)
{
#ifndef _WIN32
if (prefix.find('/') != std::string_view::npos ||
prefix.find('\0') != std::string_view::npos) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempDir: prefix must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate = base / std::format("{}{:016x}", prefix, seed);
if (::mkdir(candidate.c_str(), 0700) == 0) {
const int fd = ::open(
candidate.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: open failed after mkdir",
err)};
}
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: fstat failed",
err)};
}
TempDir out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempDir: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"TempDir: failed creating '{}'", candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempDir: failed to create unique directory after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempDir: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem } // namespace Void::FileSystem
+163 -105
View File
@@ -2,135 +2,193 @@
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <cstdint> #include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <fstream>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <thread> #include <thread>
#include <utility> #include <utility>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem namespace Void::FileSystem
{ {
/// RAII scoped *file* under `std::filesystem::temp_directory_path()`.
///
/// A uniquely-named empty file is created on construction and removed on
/// destruction, unless `keep()` was called. Move-only. Useful for staging
/// downloads, copying a shared library to a fresh inode, etc.
///
/// Construction throws `std::system_error` if the file cannot be created;
/// use `TempFile::open(prefix, ext)` for a non-throwing factory.
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_", /// RAII scoped regular file created atomically (`O_CREAT|O_EXCL|O_NOFOLLOW`, `0600`).
std::string_view extension = "") class TempFile
: m_path(make_unique_file(prefix, extension)) {
{ public:
} explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
{
auto created = create_unique_file(
std::filesystem::temp_directory_path(), prefix, extension);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempFile() noexcept ~TempFile() noexcept { remove_if_owned(); }
{
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
Void::Log::debug("FileSystem", "TempFile: removed '{}'",
m_path.string());
}
}
TempFile(const TempFile&) = delete; TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete; TempFile& operator=(const TempFile&) = delete;
TempFile(TempFile&& other) noexcept TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})), : m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true)) m_keep(std::exchange(other.m_keep, true)),
{ m_dev(std::exchange(other.m_dev, 0)),
} m_ino(std::exchange(other.m_ino, 0))
{
}
TempFile& operator=(TempFile&& other) noexcept TempFile& operator=(TempFile&& other) noexcept
{ {
if (this != &other) { if (this != &other) {
if (!m_path.empty() && !m_keep) { remove_if_owned();
std::error_code ignore; m_path = std::exchange(other.m_path, {});
std::filesystem::remove(m_path, ignore); m_keep = std::exchange(other.m_keep, true);
} m_dev = std::exchange(other.m_dev, 0);
m_path = std::exchange(other.m_path, {}); m_ino = std::exchange(other.m_ino, 0);
m_keep = std::exchange(other.m_keep, true); }
} return *this;
return *this; }
}
[[nodiscard]] const std::filesystem::path& path() const noexcept [[nodiscard]] const std::filesystem::path& path() const noexcept
{ {
return m_path; return m_path;
} }
/// Persist the file beyond this object's lifetime (no removal on std::filesystem::path keep() noexcept
/// destruction). Returns the path for convenience. {
std::filesystem::path keep() noexcept m_keep = true;
{ return m_path;
m_keep = true; }
return m_path;
}
/// Non-throwing factory. [[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
[[nodiscard]] static Void::Result::Result<TempFile, open(std::string_view prefix = "void_",
Void::Result::Error> std::string_view extension = "")
open(std::string_view prefix = "void_", {
std::string_view extension = "") return open_in(
{ std::filesystem::temp_directory_path(), prefix, extension);
try { }
return Void::Result::ok(TempFile{prefix, extension});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
private: [[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_",
std::string_view extension = "")
{
return create_unique_file(directory, prefix, extension);
}
std::filesystem::path m_path; private:
bool m_keep = false; struct InternalEmpty {};
explicit TempFile(InternalEmpty) noexcept {}
static std::filesystem::path std::filesystem::path m_path;
make_unique_file(std::string_view prefix, bool m_keep = true;
std::string_view extension) std::uint64_t m_dev = 0;
{ std::uint64_t m_ino = 0;
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path(); void remove_if_owned() noexcept
for (int attempt = 0; attempt < 16; ++attempt) { {
const auto seed = if (m_path.empty() || m_keep) {
static_cast<std::uint64_t>( return;
std::chrono::steady_clock::now() }
.time_since_epoch() #ifndef _WIN32
.count()) ^ struct stat st {};
(counter.fetch_add(1, std::memory_order_relaxed) << 16) ^ if (::lstat(m_path.c_str(), &st) == 0 && !S_ISLNK(st.st_mode) &&
static_cast<std::uint64_t>( S_ISREG(st.st_mode) &&
std::hash<std::thread::id>{}( static_cast<std::uint64_t>(st.st_dev) == m_dev &&
std::this_thread::get_id())); static_cast<std::uint64_t>(st.st_ino) == m_ino) {
auto candidate = (void)::unlink(m_path.c_str());
base / std::format("{}{:016x}{}", prefix, seed, extension); Void::Log::debug(
std::error_code ec; "FileSystem", "TempFile: removed '{}'", m_path.string());
if (!std::filesystem::exists(candidate, ec)) { }
std::ofstream f(candidate); #endif
if (f) { }
Void::Log::debug("FileSystem",
"TempFile: created '{}'", [[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
candidate.string()); create_unique_file(const std::filesystem::path& base,
return candidate; std::string_view prefix,
} std::string_view extension)
} {
} #ifndef _WIN32
throw std::system_error( if (prefix.find('/') != std::string_view::npos ||
std::make_error_code(std::errc::file_exists), prefix.find('\0') != std::string_view::npos ||
"TempFile: failed to create unique file after 16 attempts"); extension.find('/') != std::string_view::npos ||
} extension.find('\0') != std::string_view::npos) {
}; return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempFile: prefix/extension must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
const int fd = ::open(candidate.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
0600);
if (fd >= 0) {
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::unlink(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempFile: fstat failed",
err)};
}
TempFile out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_keep = false;
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempFile: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("TempFile: failed creating '{}'",
candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempFile: failed to create unique file after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
(void)extension;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempFile: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem } // namespace Void::FileSystem
+207
View File
@@ -0,0 +1,207 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <expected>
#include <format>
#include <string>
#include <string_view>
#include <utility>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::System
{
enum class SystemErrorCode : std::int32_t {
invalid_argument = 1,
not_found = 2,
permission_denied = 3,
already_exists = 4,
spawn_failed = 5,
exec_failed = 6,
timed_out = 7,
cancelled = 8,
output_limit = 9,
line_limit = 10,
io_error = 11,
sync_failed = 12,
durability_unknown = 13,
limit_exceeded = 14,
busy = 15,
self_join = 16,
unsupported = 17,
unavailable = 18,
internal = 19,
};
[[nodiscard]] constexpr Void::Result::ErrorKind
classify_system_error(SystemErrorCode code) noexcept
{
switch (code) {
case SystemErrorCode::invalid_argument:
return Void::Result::ErrorKind::invalid_argument;
case SystemErrorCode::not_found:
return Void::Result::ErrorKind::not_found;
case SystemErrorCode::already_exists:
case SystemErrorCode::busy:
case SystemErrorCode::self_join:
return Void::Result::ErrorKind::conflict;
case SystemErrorCode::timed_out:
return Void::Result::ErrorKind::timeout;
case SystemErrorCode::cancelled:
return Void::Result::ErrorKind::cancelled;
case SystemErrorCode::output_limit:
case SystemErrorCode::line_limit:
case SystemErrorCode::limit_exceeded:
return Void::Result::ErrorKind::exhausted;
case SystemErrorCode::unsupported:
return Void::Result::ErrorKind::unsupported;
case SystemErrorCode::unavailable:
return Void::Result::ErrorKind::overloaded;
case SystemErrorCode::permission_denied:
case SystemErrorCode::spawn_failed:
case SystemErrorCode::exec_failed:
case SystemErrorCode::io_error:
case SystemErrorCode::sync_failed:
case SystemErrorCode::durability_unknown:
return Void::Result::ErrorKind::io;
case SystemErrorCode::internal:
return Void::Result::ErrorKind::internal;
}
return Void::Result::ErrorKind::internal;
}
[[nodiscard]] inline SystemErrorCode
map_errno_to_system_code(int sys_errno) noexcept
{
switch (sys_errno) {
case ENOENT:
return SystemErrorCode::not_found;
case EACCES:
case EPERM:
case EROFS:
return SystemErrorCode::permission_denied;
case EEXIST:
return SystemErrorCode::already_exists;
case ETIMEDOUT:
return SystemErrorCode::timed_out;
case ECANCELED:
return SystemErrorCode::cancelled;
case EBUSY:
return SystemErrorCode::busy;
case EINVAL:
case ENAMETOOLONG:
case EISDIR:
case ENOTDIR:
return SystemErrorCode::invalid_argument;
case ENOSYS:
case EOPNOTSUPP:
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
case ENOTSUP:
#endif
return SystemErrorCode::unsupported;
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
return SystemErrorCode::unavailable;
default:
return SystemErrorCode::io_error;
}
}
[[nodiscard]] inline Void::Result::Error make_system_error(
SystemErrorCode code, std::string_view message, int sys_errno = 0)
{
std::string detail;
if (sys_errno != 0) {
detail = std::format("{} (errno={}: {})",
message,
sys_errno,
std::strerror(sys_errno));
} else {
detail.assign(message);
}
std::error_code sys_ec{};
if (sys_errno != 0) {
sys_ec = std::error_code{sys_errno, std::generic_category()};
}
return Void::Result::Error{
classify_system_error(code),
std::move(detail),
Void::Result::ErrorCode{Void::Result::kSystemErrorDomain,
static_cast<std::int32_t>(code)},
sys_ec};
}
class OwnedFd
{
public:
OwnedFd() noexcept = default;
explicit OwnedFd(int fd) noexcept : fd_(fd) {}
~OwnedFd() noexcept { reset(); }
OwnedFd(const OwnedFd&) = delete;
OwnedFd& operator=(const OwnedFd&) = delete;
OwnedFd(OwnedFd&& other) noexcept
: fd_(std::exchange(other.fd_, -1))
{
}
OwnedFd& operator=(OwnedFd&& other) noexcept
{
if (this != &other) {
reset();
fd_ = std::exchange(other.fd_, -1);
}
return *this;
}
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] explicit operator bool() const noexcept { return valid(); }
[[nodiscard]] int get() const noexcept { return fd_; }
[[nodiscard]] int release() noexcept { return std::exchange(fd_, -1); }
void reset(int new_fd = -1) noexcept
{
const int old = std::exchange(fd_, new_fd);
#ifndef _WIN32
if (old >= 0) {
(void)::close(old);
}
#else
(void)old;
#endif
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close() noexcept
{
const int old = std::exchange(fd_, -1);
if (old < 0) {
return {};
}
#ifndef _WIN32
if (::close(old) != 0) {
const int err = errno;
return std::unexpected{make_system_error(
map_errno_to_system_code(err), "OwnedFd::close failed", err)};
}
#endif
return {};
}
private:
int fd_{-1};
};
} // namespace Void::System
+1593 -296
View File
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -1,4 +1,7 @@
void_add_module(System void_add_module(System
INTERNAL_DEPS Functional LogState INTERNAL_DEPS Functional Time LogState
EXTERNAL_DEPS Threads::Threads EXTERNAL_DEPS Threads::Threads
EXCLUDE_HEADERS
Void/System/AsyncProcess.hpp
Void/System/AsyncWatcher.hpp
) )
+10
View File
@@ -116,6 +116,16 @@ if(_has_runtime)
run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps}) run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps})
endif() endif()
has_modules(_has_system System Functional Time LogState)
if(_has_system)
run_consumer(SystemOnly "${install_prefix}" "SystemOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_obs_hooks ObservabilityHooks) has_modules(_has_obs_hooks ObservabilityHooks)
if(_has_obs_hooks) if(_has_obs_hooks)
run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps}) run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps})
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidSystemOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS System)
add_executable(void_system_only_consumer main.cpp)
target_link_libraries(void_system_only_consumer PRIVATE Void::System)
target_compile_features(void_system_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME SystemOnlyConsumer COMMAND void_system_only_consumer)
+31
View File
@@ -0,0 +1,31 @@
#include <Void/System/Metrics.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/TempDir.hpp>
#include <iostream>
int main()
{
auto tmp = Void::FileSystem::TempDir::open("void_pkg_sys_");
if (!tmp.has_value()) {
std::cerr << tmp.error().message() << '\n';
return 1;
}
const auto cfg = tmp->path() / "item.txt";
if (!Void::FileSystem::replace_file(cfg, "ok").has_value()) {
return 2;
}
auto content = Void::FileSystem::read_file_bounded(cfg);
if (!content.has_value() || *content != "ok") {
return 3;
}
Void::Process::SpawnOptions opts;
opts.executable = "/nonexistent/void/binary";
opts.search_path = false;
auto bad = Void::Process::spawn(opts);
if (bad.has_value()) {
return 4;
}
return 0;
}
+48 -49
View File
@@ -7,60 +7,59 @@
namespace namespace
{ {
using Void::Testing::Test;
struct ProcessStream : Void::Testing::Suite<ProcessStream> { using Void::Testing::Test;
// stdout lines are delivered to the callback as they arrive, and
// the full output is still captured.
Test streams_stdout_lines()
{
std::vector<std::string> lines;
Void::Process::StreamCallbacks cb;
cb.on_stdout = [&](std::string_view l) {
lines.emplace_back(l);
};
auto r = Void::Process::run_streaming( struct ProcessStream : Void::Testing::Suite<ProcessStream> {
"/bin/sh", {"-c", "printf 'a\\nb\\nc\\n'"}, cb); Test streams_stdout_lines()
Void::Testing::expect(r.has_value()); {
Void::Testing::expect_eq(r->exit_code, 0); std::vector<std::string> lines;
Void::Process::StreamCallbacks cb;
cb.on_stdout = [&](std::string_view l) {
lines.emplace_back(l);
};
const std::vector<std::string> expected{"a", "b", "c"}; auto r = Void::Process::run_streaming(
Void::Testing::expect(lines == expected); VOID_PROCESS_HELPER_PATH, {"lines", "a", "b", "c"}, cb);
Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"}); Void::Testing::expect(r.has_value());
} Void::Testing::expect_eq(r->exit_code, 0);
// A trailing partial line (no newline) is flushed at EOF. const std::vector<std::string> expected{"a", "b", "c"};
Test flushes_trailing_partial_line() Void::Testing::expect(lines == expected);
{ Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"});
std::vector<std::string> lines; }
Void::Process::StreamCallbacks cb;
cb.on_stdout = [&](std::string_view l) {
lines.emplace_back(l);
};
auto r = Void::Process::run_streaming( Test flushes_trailing_partial_line()
"/bin/sh", {"-c", "printf 'no-newline'"}, cb); {
Void::Testing::expect(r.has_value()); std::vector<std::string> lines;
Void::Testing::expect_eq(lines.size(), std::size_t{1}); Void::Process::StreamCallbacks cb;
Void::Testing::expect_eq(lines.at(0), cb.on_stdout = [&](std::string_view l) {
std::string{"no-newline"}); lines.emplace_back(l);
} };
// stderr is routed to its own callback. auto r = Void::Process::run_streaming(
Test streams_stderr_separately() VOID_PROCESS_HELPER_PATH,
{ {"lines", "--no-newline", "no-newline"},
std::vector<std::string> errs; cb);
Void::Process::StreamCallbacks cb; Void::Testing::expect(r.has_value());
cb.on_stderr = [&](std::string_view l) { Void::Testing::expect_eq(lines.size(), std::size_t{1});
errs.emplace_back(l); Void::Testing::expect_eq(lines.at(0), std::string{"no-newline"});
}; }
Test streams_stderr_separately()
{
std::vector<std::string> errs;
Void::Process::StreamCallbacks cb;
cb.on_stderr = [&](std::string_view l) {
errs.emplace_back(l);
};
auto r = Void::Process::run_streaming(
VOID_PROCESS_HELPER_PATH, {"lines", "--stderr", "oops"}, cb);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(errs.size(), std::size_t{1});
Void::Testing::expect_eq(errs.at(0), std::string{"oops"});
}
};
auto r = Void::Process::run_streaming(
"/bin/sh", {"-c", "printf 'oops\\n' 1>&2"}, cb);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(errs.size(), std::size_t{1});
Void::Testing::expect_eq(errs.at(0), std::string{"oops"});
}
};
} // namespace } // namespace
+296
View File
@@ -0,0 +1,296 @@
#include <Void/System/Metrics.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/Query.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/System/TempFile.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <filesystem>
#include <fstream>
#include <stop_token>
#include <string>
#include <vector>
namespace
{
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
} // namespace
Void::Testing::Test system_spawn_distinguishes_exec_failure_and_hygiene()
{
// 1. spawn() returns exec_failed distinct from a child exiting 127.
Void::Process::SpawnOptions missing_opts;
missing_opts.executable = "/nonexistent/void/missing_binary";
missing_opts.search_path = false;
auto missing_res = Void::Process::spawn(missing_opts);
require(!missing_res.has_value());
expect_eq(missing_res.error().code().domain, Void::Result::kSystemErrorDomain);
expect_eq(missing_res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::exec_failed));
Void::Process::SpawnOptions exit127_opts;
exit127_opts.executable = VOID_PROCESS_HELPER_PATH;
exit127_opts.arguments = {"exit", "127"};
auto exit127_child = Void::Process::spawn(exit127_opts);
require(exit127_child.has_value());
auto exit127_res = Void::Process::communicate_blocking(*exit127_child);
require(exit127_res.has_value());
expect(exit127_res->status.exited);
expect_eq(exit127_res->status.code, 127);
// 2. Non-CLOEXEC inherited fds in parent are never leaked across spawn().
int dummy_pipe[2]{-1, -1};
require(::pipe(dummy_pipe) == 0);
Void::System::OwnedFd leak0{dummy_pipe[0]};
Void::System::OwnedFd leak1{dummy_pipe[1]};
Void::Process::SpawnOptions fd_opts;
fd_opts.executable = VOID_PROCESS_HELPER_PATH;
fd_opts.arguments = {"check-fds"};
auto fd_child = Void::Process::spawn(fd_opts);
require(fd_child.has_value());
auto fd_res = Void::Process::communicate_blocking(*fd_child);
require(fd_res.has_value());
expect_eq(fd_res->out, std::string{"clean\n"});
// 3. EnvironmentPolicy allowlist & explicit_only + working_directory.
Void::FileSystem::TempDir tmp{"void_sys_cwd_"};
Void::Process::SpawnOptions env_opts;
env_opts.executable = VOID_PROCESS_HELPER_PATH;
env_opts.arguments = {"env-dump"};
env_opts.environment.mode = Void::Process::EnvMode::explicit_only;
env_opts.environment.set_vars = {{"VOID_Z", "two"}, {"VOID_A", "one"}};
auto env_child = Void::Process::spawn(env_opts);
require(env_child.has_value());
auto env_res = Void::Process::communicate_blocking(*env_child);
require(env_res.has_value());
expect_eq(env_res->out, std::string{"VOID_A=one\nVOID_Z=two\n"});
Void::Process::SpawnOptions cwd_opts;
cwd_opts.executable = VOID_PROCESS_HELPER_PATH;
cwd_opts.arguments = {"cwd"};
cwd_opts.working_directory = tmp.path();
auto cwd_child = Void::Process::spawn(cwd_opts);
require(cwd_child.has_value());
auto cwd_res = Void::Process::communicate_blocking(*cwd_child);
require(cwd_res.has_value());
expect_eq(cwd_res->out, std::filesystem::canonical(tmp.path()).string() + "\n");
// 4. argv+env limit rejected cleanly before fork().
Void::Process::SpawnOptions big_opts;
big_opts.executable = VOID_PROCESS_HELPER_PATH;
big_opts.arguments = {std::string(Void::Process::kMaxSpawnInputBytes + 64, 'x')};
auto big_res = Void::Process::spawn(big_opts);
require(!big_res.has_value());
expect_eq(big_res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::limit_exceeded));
}
Void::Testing::Test system_communicate_duplex_limits_escalation_and_cancel()
{
// 1. Full-duplex simultaneous 256 KiB stdin + stdout + stderr without deadlock.
const std::size_t payload_bytes = 256ULL * 1024ULL;
const std::string big_in(payload_bytes, 'i');
Void::Process::SpawnOptions sim_opts;
sim_opts.executable = VOID_PROCESS_HELPER_PATH;
sim_opts.arguments = {"simultaneous-io", std::to_string(payload_bytes)};
auto sim_child = Void::Process::spawn(sim_opts);
require(sim_child.has_value());
Void::Process::CaptureLimits sim_lim;
sim_lim.max_line_bytes = 512ULL * 1024ULL;
auto sim_res = Void::Process::communicate_blocking(
*sim_child,
big_in,
sim_lim,
std::chrono::milliseconds{0}); // explicit zero-timeout completes normally
require(sim_res.has_value());
expect(!sim_res->timed_out);
expect_eq(sim_res->status.code, 0);
expect_eq(sim_res->out.size(), payload_bytes);
expect_eq(sim_res->err.size(), payload_bytes);
// 2. Capture limit fail_and_terminate vs drain_and_truncate, plus line_limit.
{
Void::Process::SpawnOptions flood_opts;
flood_opts.executable = VOID_PROCESS_HELPER_PATH;
flood_opts.arguments = {"flood", "4096", "0"};
auto ch = Void::Process::spawn(flood_opts);
require(ch.has_value());
Void::Process::CaptureLimits lim;
lim.max_stdout_bytes = 512;
lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate;
auto res = Void::Process::communicate_blocking(*ch, {}, lim);
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::output_limit));
}
{
Void::Process::SpawnOptions flood_opts;
flood_opts.executable = VOID_PROCESS_HELPER_PATH;
flood_opts.arguments = {"flood", "4096", "256"};
auto ch = Void::Process::spawn(flood_opts);
require(ch.has_value());
Void::Process::CaptureLimits lim;
lim.max_stdout_bytes = 512;
lim.overflow_policy = Void::Process::OverflowPolicy::drain_and_truncate;
auto res = Void::Process::communicate_blocking(*ch, {}, lim);
require(res.has_value());
expect(res->overflowed);
expect(res->stdout_truncated);
expect_eq(res->out.size(), std::size_t{512});
expect_eq(res->err.size(), std::size_t{256});
}
{
Void::Process::SpawnOptions long_opts;
long_opts.executable = VOID_PROCESS_HELPER_PATH;
long_opts.arguments = {"long-line", "2048"};
auto ch = Void::Process::spawn(long_opts);
require(ch.has_value());
Void::Process::CaptureLimits lim;
lim.max_line_bytes = 128;
lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate;
auto res = Void::Process::communicate_blocking(*ch, {}, lim);
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::line_limit));
}
// 3. SIGTERM-ignoring child escalates to SIGKILL within short kill_grace.
{
Void::Process::SpawnOptions sig_opts;
sig_opts.executable = VOID_PROCESS_HELPER_PATH;
sig_opts.arguments = {"ignore-sigterm", "10000"};
sig_opts.kill_grace = std::chrono::milliseconds{40};
auto ch = Void::Process::spawn(sig_opts);
require(ch.has_value());
auto res = Void::Process::communicate_blocking(
*ch, {}, Void::Process::CaptureLimits{}, std::chrono::milliseconds{80});
require(res.has_value());
expect(res->timed_out);
expect(!res->status.exited);
expect_eq(res->status.signal, SIGKILL);
}
// 4. Stop token cancels child cleanly.
{
Void::Process::SpawnOptions wait_opts;
wait_opts.executable = VOID_PROCESS_HELPER_PATH;
wait_opts.arguments = {"ignore-sigterm", "10000"};
wait_opts.kill_grace = std::chrono::milliseconds{20};
auto ch = Void::Process::spawn(wait_opts);
require(ch.has_value());
std::stop_source ss;
ss.request_stop();
auto res = ch->wait_blocking(
std::chrono::milliseconds{5000},
ss.get_token(),
std::chrono::milliseconds{20});
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::cancelled));
}
}
Void::Testing::Test system_replace_file_temp_ownership_and_metrics()
{
Void::FileSystem::TempDir tmp{"void_sys_fs_"};
struct stat tmp_st {};
require(::lstat(tmp.path().c_str(), &tmp_st) == 0);
expect_eq(static_cast<unsigned>(tmp_st.st_mode & 0777), 0700U);
const auto target = tmp / "state.cfg";
require(Void::FileSystem::replace_file(target, "initial").has_value());
expect_eq(Void::FileSystem::read_file(target).value(), std::string{"initial"});
// Fault during write/sync/rename removes ONLY owned temp and leaves target intact.
for (auto phase : {Void::FileSystem::ReplacePhase::write_stage,
Void::FileSystem::ReplacePhase::sync_stage,
Void::FileSystem::ReplacePhase::rename}) {
Void::FileSystem::ReplaceOptions opts;
opts.fault_hook = [phase](Void::FileSystem::ReplacePhase p)
-> std::optional<int> {
return (p == phase) ? std::optional<int>{EIO} : std::nullopt;
};
auto fail_res = Void::FileSystem::replace_file(target, "bad", opts);
require(!fail_res.has_value());
expect(!fail_res.error().visible_on_disk);
expect(!fail_res.error().durability_unknown);
expect_eq(Void::FileSystem::read_file(target).value(),
std::string{"initial"});
}
// Post-rename parent sync failure reports visible_on_disk + durability_unknown.
{
Void::FileSystem::ReplaceOptions opts;
opts.fault_hook = [](Void::FileSystem::ReplacePhase p)
-> std::optional<int> {
return (p == Void::FileSystem::ReplacePhase::sync_parent)
? std::optional<int>{EIO}
: std::nullopt;
};
auto sync_res = Void::FileSystem::replace_file(target, "committed", opts);
require(!sync_res.has_value());
expect(sync_res.error().visible_on_disk);
expect(sync_res.error().durability_unknown);
expect_eq(Void::FileSystem::read_file(target).value(),
std::string{"committed"});
}
// Bounded read_file & list_directory.
auto small_read = Void::FileSystem::read_file_bounded(
target, Void::FileSystem::ReadFileOptions{.max_bytes = 4});
require(!small_read.has_value());
expect_eq(small_read.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::limit_exceeded));
(void)Void::FileSystem::write_file(tmp / "extra1.txt", "1");
(void)Void::FileSystem::write_file(tmp / "extra2.txt", "2");
auto bounded_list = Void::FileSystem::list_directory_bounded(
tmp.path(), Void::FileSystem::ListDirectoryOptions{.max_entries = 1});
require(!bounded_list.has_value());
expect_eq(bounded_list.error().code().value,
static_cast<std::int32_t>(Void::System::SystemErrorCode::limit_exceeded));
// TempFile 0600 mode & symlink-swap refusal (destructor must not delete swap target).
const auto victim = tmp / "victim.txt";
require(Void::FileSystem::write_file(victim, "keep_me").has_value());
std::filesystem::path tf_path;
{
auto tf = Void::FileSystem::TempFile::open_in(tmp.path(), "tf_");
require(tf.has_value());
tf_path = tf->path();
struct stat tf_st {};
require(::lstat(tf_path.c_str(), &tf_st) == 0);
expect_eq(static_cast<unsigned>(tf_st.st_mode & 0777), 0600U);
// Replace tf_path with symlink to victim; ~TempFile must NOT unlink it!
std::filesystem::remove(tf_path);
std::filesystem::create_symlink(victim, tf_path);
}
expect(std::filesystem::exists(victim));
expect(std::filesystem::is_symlink(tf_path));
std::filesystem::remove(tf_path);
// CpuSampler::sample with injected ManualClock distinguishes valid vs zero interval.
Void::Time::ManualClock clock;
Void::SystemInfo::CpuSampler sampler{&clock};
expect(!sampler.sample().valid); // zero elapsed delta on ManualClock
(void)clock.advance(std::chrono::seconds{1});
const auto sample = sampler.sample();
expect(sample.valid);
expect(sample.ratio >= 0.0);
}