feat(system,config,sqlite): implement VL-001, VL-003, VL-010, VL-011

This commit is contained in:
faumaray committed 2026-11-26 20:45:52 +03:00
1 parent adfc8548dc
commit b50131f52e
14 files changed
+2660 -139

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0.0)
project(Void VERSION 1.2.1 LANGUAGES CXX)
project(Void VERSION 1.2.1 LANGUAGES C CXX)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
elseif(NOT DEFINED BUILD_SHARED_LIBS)
+82 -2
View File
@@ -158,9 +158,89 @@ function(void_fetch_dependency DEP_NAME)
endif()
if(DEP_NAME STREQUAL "SQLite3")
if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3)
find_package(SQLite3 REQUIRED)
if(TARGET SQLite3::SQLite3)
return()
endif()
if(TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
return()
endif()
set(_void_sqlite_dir "${VOID_SQLITE3_AMALGAMATION_DIR}")
if(NOT _void_sqlite_dir)
find_package(SQLite3 QUIET)
if(TARGET SQLite3::SQLite3)
return()
endif()
if(TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
return()
endif()
endif()
option(VOID_FETCH_SQLITE3
"Allow FetchContent SQLite3 amalgamation fallback when system SQLite3 is unavailable"
ON)
set(VOID_SQLITE3_AMALGAMATION_DIR "" CACHE PATH
"Path containing pre-downloaded sqlite3.c and sqlite3.h amalgamation sources")
set(VOID_SQLITE3_FETCH_URL
"https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip"
CACHE STRING "SQLite3 amalgamation archive URL for FetchContent fallback")
set(VOID_SQLITE3_FETCH_HASH "" CACHE STRING
"Optional SHA256 hash (SHA256=...) for VOID_SQLITE3_FETCH_URL")
if(NOT _void_sqlite_dir AND VOID_FETCH_SQLITE3 AND
NOT CMAKE_DISABLE_FIND_PACKAGE_SQLite3)
message(STATUS "[Void] System SQLite3 not found — falling back to SQLite3 amalgamation")
if(VOID_SQLITE3_FETCH_HASH)
FetchContent_Declare(SQLite3
URL "${VOID_SQLITE3_FETCH_URL}"
URL_HASH "${VOID_SQLITE3_FETCH_HASH}"
SYSTEM
)
else()
FetchContent_Declare(SQLite3
URL "${VOID_SQLITE3_FETCH_URL}"
SYSTEM
)
endif()
FetchContent_MakeAvailable(SQLite3)
if(EXISTS "${sqlite3_SOURCE_DIR}/sqlite3.c")
set(_void_sqlite_dir "${sqlite3_SOURCE_DIR}")
else()
file(GLOB _found_sqlite_c LIST_DIRECTORIES FALSE
"${sqlite3_SOURCE_DIR}/*/sqlite3.c")
if(_found_sqlite_c)
list(GET _found_sqlite_c 0 _first_sqlite_c)
get_filename_component(_void_sqlite_dir "${_first_sqlite_c}" DIRECTORY)
endif()
endif()
endif()
if(_void_sqlite_dir AND EXISTS "${_void_sqlite_dir}/sqlite3.c" AND
EXISTS "${_void_sqlite_dir}/sqlite3.h")
void_fetch_dependency(Threads)
add_library(void_sqlite3_amalgamation STATIC
"${_void_sqlite_dir}/sqlite3.c")
set_target_properties(void_sqlite3_amalgamation PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_STANDARD 11
SYSTEM TRUE)
target_include_directories(void_sqlite3_amalgamation SYSTEM PUBLIC
"${_void_sqlite_dir}")
target_compile_definitions(void_sqlite3_amalgamation PRIVATE
SQLITE_THREADSAFE=1
SQLITE_ENABLE_FTS5
SQLITE_ENABLE_JSON1
SQLITE_DQS=0)
target_link_libraries(void_sqlite3_amalgamation PUBLIC
Threads::Threads
"$<$<NOT:$<PLATFORM_ID:Windows>>:${CMAKE_DL_LIBS};m>")
add_library(SQLite3::SQLite3 ALIAS void_sqlite3_amalgamation)
return()
endif()
find_package(SQLite3 REQUIRED)
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()
+85 -5
View File
@@ -2,7 +2,10 @@
#include <Void/Core/Meta.hpp>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
@@ -11,23 +14,56 @@
namespace Void::Argparse
{
enum class ParseOutcome : std::uint8_t {
Ok,
Help,
Error,
};
struct ParseResult {
ParseOutcome outcome{ParseOutcome::Ok};
std::string message{};
std::vector<std::string> matched_command_path{};
[[nodiscard]] bool ok() const noexcept
{
return outcome == ParseOutcome::Ok;
}
[[nodiscard]] bool is_help() const noexcept
{
return outcome == ParseOutcome::Help;
}
[[nodiscard]] bool is_error() const noexcept
{
return outcome == ParseOutcome::Error;
}
};
// ── Parser
// ────────────────────────────────────────────────────────────────────
// Fluent command-line argument parser.
//
// Supports:
// --flag, -f boolean flag (default false, set to true by
// presence)
// presence)
// --key=value option with value (= or space separator)
// --key value option with value
// option_many(...) repeatable option collecting all occurrences
// subcommand(...) nested subcommand parsers (e.g. "compdb use")
// positional args collected in declaration order
// --help / -h auto-generated help text
// --help / -h auto-generated help text (ParseOutcome::Help)
class Parser
{
public:
explicit Parser(std::string program, std::string description = {});
~Parser();
Parser(const Parser&) = delete;
Parser& operator=(const Parser&) = delete;
Parser(Parser&&) noexcept;
Parser& operator=(Parser&&) noexcept;
// Add a boolean flag.
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
@@ -43,6 +79,12 @@ namespace Void::Argparse
std::string_view description,
std::optional<std::string>& out);
// Add a repeatable option collecting all occurrences into `out`.
Parser& option_many(std::string_view long_name,
std::string_view short_name,
std::string_view description,
std::vector<std::string>& out);
// Add an option with a default value. out is always set after
// parse().
Parser& option_default(std::string_view long_name,
@@ -55,7 +97,28 @@ namespace Void::Argparse
Parser& positional(std::string_view name,
std::string_view description, std::string& out);
// Parse argc/argv. Returns error message on failure.
// Add a variadic trailing positional argument list.
Parser& positional_many(std::string_view name,
std::string_view description,
std::vector<std::string>& out,
bool required = false);
// Register a nested subcommand and return a reference to its
// Parser. The returned reference remains valid for the lifetime of
// the parent Parser.
Parser& subcommand(std::string name, std::string description = {},
std::function<void()> on_selected = {});
// Control whether a parser with subcommands requires one to be
// selected (default: true when any subcommand is registered).
Parser& require_subcommand(bool required = true) noexcept;
// Parse argc/argv with explicit Ok / Help / Error classification.
[[nodiscard]] ParseResult
parse_detailed(int argc, const char* const* argv) const;
// Parse argc/argv. Returns error message (or help text) on
// non-Ok outcome for 1.x compatibility.
[[nodiscard]] std::expected<void, std::string>
parse(int argc, const char* const* argv) const;
@@ -70,18 +133,33 @@ namespace Void::Argparse
};
struct OptionEntry {
std::string lng, sht, desc, def;
std::optional<std::string>* out_opt;
std::string* out_str;
std::optional<std::string>* out_opt{nullptr};
std::string* out_str{nullptr};
std::vector<std::string>* out_many{nullptr};
};
struct PosEntry {
std::string name, desc;
std::string* out;
};
struct MultiPosEntry {
std::string name, desc;
std::vector<std::string>* out{nullptr};
bool required{false};
};
struct SubcommandEntry {
std::string name;
std::unique_ptr<Parser> parser;
std::function<void()> on_selected;
};
std::string program_, description_;
std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_;
std::optional<MultiPosEntry> positional_many_;
std::vector<SubcommandEntry> subcommands_;
bool has_explicit_require_sub_{false};
bool require_subcommand_{true};
};
// ── reflective options struct
@@ -147,6 +225,8 @@ namespace Void::Argparse
parser.flag(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_optional_v<MT>) {
parser.option(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
parser.option_many(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def);
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace Void::FileSystem
{
enum class DirectoryEventKind : std::uint8_t {
Created,
Modified,
Deleted,
Renamed,
AttributeChanged,
RescanRequired,
};
struct DirectoryEvent {
DirectoryEventKind kind{DirectoryEventKind::Modified};
std::filesystem::path path{};
std::filesystem::path old_path{};
bool is_directory{false};
std::string detail{};
};
/// Predicate queried for every discovered/modified path. Returning true skips
/// watching (for directories) and suppresses event delivery for that path.
using IgnorePredicate =
std::function<bool(const std::filesystem::path& path, bool is_directory)>;
struct DirectoryWatcherOptions {
IgnorePredicate ignore{};
std::size_t max_watches{65536};
std::size_t max_queued_events{4096};
std::chrono::milliseconds rename_pair_window{std::chrono::milliseconds{50}};
};
/// Kernel-event (Linux inotify) recursive directory watcher with auto-watch
/// attachment on new subdirectories, rename pairing, ignore filtering, and
/// explicit RescanRequired signaling on queue overflow or watch exhaustion.
class DirectoryWatcher final
{
public:
~DirectoryWatcher() noexcept;
DirectoryWatcher(const DirectoryWatcher&) = delete;
DirectoryWatcher& operator=(const DirectoryWatcher&) = delete;
DirectoryWatcher(DirectoryWatcher&&) noexcept;
DirectoryWatcher& operator=(DirectoryWatcher&&) noexcept;
[[nodiscard]] static Void::Result::Result<DirectoryWatcher,
Void::Result::Error>
create(const std::filesystem::path& root,
DirectoryWatcherOptions options = {});
[[nodiscard]] Void::Result::Result<std::vector<DirectoryEvent>,
Void::Result::Error>
poll(std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Re-walk `root()` and rebuild all inotify watches from scratch.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan();
/// Wake any thread blocked inside poll().
void wake() noexcept;
/// Enqueue a RescanRequired event and wake waiters (deterministic test hook).
void simulate_overflow_for_test();
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> impl_{};
explicit DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::FileSystem
+592
View File
@@ -24,10 +24,17 @@
#ifndef _WIN32
#include <fcntl.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/random.h>
#if __has_include(<linux/fs.h>)
#include <linux/fs.h>
#endif
#endif
#endif
@@ -548,4 +555,589 @@ namespace detail
return {};
}
// ── VL-010: File Locks, Atomic Symlink Swap, Reflink Copy, Timestamps ────────
enum class LockMode : std::uint8_t {
Shared,
Exclusive,
};
/// RAII advisory file lock backed by POSIX flock(2).
class FileLock final
{
public:
FileLock() noexcept = default;
~FileLock() noexcept { unlock(); }
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
FileLock(FileLock&& other) noexcept
: fd_(std::move(other.fd_))
, mode_(other.mode_)
{
}
FileLock& operator=(FileLock&& other) noexcept
{
if (this != &other) {
unlock();
fd_ = std::move(other.fd_);
mode_ = other.mode_;
}
return *this;
}
[[nodiscard]] bool locked() const noexcept { return fd_.valid(); }
[[nodiscard]] LockMode mode() const noexcept { return mode_; }
[[nodiscard]] int native_handle() const noexcept { return fd_.get(); }
void unlock() noexcept
{
#ifndef _WIN32
if (fd_.valid()) {
while (::flock(fd_.get(), LOCK_UN) != 0 && errno == EINTR) {
}
fd_.reset();
}
#endif
}
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
auto res = acquire(path, mode, false);
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
if (!res->has_value()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
"FileSystem::FileLock::lock: unexpected empty result")};
}
return std::move(**res);
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
try_lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
return acquire(path, mode, true);
}
private:
explicit FileLock(Void::System::OwnedFd fd, LockMode mode) noexcept
: fd_(std::move(fd))
, mode_(mode)
{
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
acquire(const std::filesystem::path& path,
LockMode mode,
bool nonblocking)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::FileLock: empty path")};
}
int raw = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666);
if (raw < 0 && mode == LockMode::Shared &&
(errno == EACCES || errno == EROFS)) {
raw = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
}
if (raw < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: cannot open '{}'",
path.string()),
err)};
}
Void::System::OwnedFd fd{raw};
const int op = (mode == LockMode::Shared ? LOCK_SH : LOCK_EX) |
(nonblocking ? LOCK_NB : 0);
for (;;) {
if (::flock(fd.get(), op) == 0) {
return std::optional<FileLock>{
FileLock{std::move(fd), mode}};
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) {
return std::optional<FileLock>{std::nullopt};
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: flock failed for '{}'",
path.string()),
err)};
}
#else
(void)path;
(void)mode;
(void)nonblocking;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::FileLock: unsupported platform")};
#endif
}
Void::System::OwnedFd fd_{};
LockMode mode_{LockMode::Exclusive};
};
/// Atomically create or replace symlink at `link_path` pointing to `target`
/// (symlinkat temp -> renameat -> optional parent dir fsync).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_symlink_swap(
const std::filesystem::path& link_path,
const std::filesystem::path& target,
ReplaceDurability durability = ReplaceDurability::durable_sync)
{
#ifndef _WIN32
if (link_path.empty() || !link_path.has_filename() || target.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: empty link or target path")};
}
const std::string target_name = link_path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: invalid link filename")};
}
const std::filesystem::path parent =
link_path.parent_path().empty() ? std::filesystem::path{"."}
: link_path.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
std::string tmp_name;
bool created = false;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_lnk_{:016x}", target_name, detail::next_temp_entropy());
if (::symlinkat(target.c_str(), dir_fd.get(), tmp_name.c_str()) == 0) {
created = true;
break;
}
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(
"FileSystem::atomic_symlink_swap: symlinkat failed in '{}'",
parent.string()),
last_err)};
}
}
if (!created) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::atomic_symlink_swap: exhausted temporary link names",
last_err)};
}
bool cleanup = true;
struct CleanupGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~CleanupGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} cleanup_guard{dir_fd.get(), &tmp_name, &cleanup};
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
target_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: renameat failed for '{}'",
link_path.string()),
err)};
}
cleanup = false;
if (durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::atomic_symlink_swap: parent dir fsync failed for '{}'",
link_path.string()),
err)};
}
}
return {};
#else
(void)link_path;
(void)target;
(void)durability;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::atomic_symlink_swap: unsupported platform")};
#endif
}
enum class CopyMethod : std::uint8_t {
Reflink,
PrivateCopy,
};
struct CopyResult {
std::uint64_t bytes{0};
CopyMethod method{CopyMethod::PrivateCopy};
};
struct CopyOptions {
bool overwrite{true};
bool preserve_permissions{true};
ReplaceDurability durability{ReplaceDurability::atomic_visibility};
};
/// Copy a regular file using CoW reflink (`ioctl(FICLONE)`) with atomic
/// staging and private-copy fallback. Explicitly never creates hardlinks.
[[nodiscard]] inline Void::Result::Result<CopyResult, Void::Result::Error>
reflink_copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
CopyOptions options = {})
{
#ifndef _WIN32
if (src.empty() || dst.empty() || !dst.has_filename()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid source or destination path")};
}
const std::string dst_name = dst.filename().string();
if (dst_name == "." || dst_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid destination filename")};
}
const int raw_src = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
if (raw_src < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open '{}'",
src.string()),
err)};
}
Void::System::OwnedFd src_fd{raw_src};
struct stat src_st {};
if (::fstat(src_fd.get(), &src_st) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: fstat failed on '{}'",
src.string()),
err)};
}
if (!S_ISREG(src_st.st_mode)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("FileSystem::reflink_copy_file: '{}' is not a regular file",
src.string()))};
}
const std::filesystem::path parent =
dst.parent_path().empty() ? std::filesystem::path{"."}
: dst.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
const mode_t create_mode = options.preserve_permissions
? static_cast<mode_t>(src_st.st_mode & 0777)
: static_cast<mode_t>(0644);
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_cp_{:016x}", dst_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
create_mode);
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
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("FileSystem::reflink_copy_file: create temp in '{}'",
parent.string()),
last_err)};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::reflink_copy_file: exhausted temp names",
last_err)};
}
bool cleanup_tmp = true;
struct TempGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_tmp};
CopyResult result;
result.bytes = static_cast<std::uint64_t>(src_st.st_size);
bool cloned = false;
#if defined(__linux__) && defined(FICLONE)
for (;;) {
if (::ioctl(tmp_fd.get(), FICLONE, src_fd.get()) == 0) {
cloned = true;
result.method = CopyMethod::Reflink;
break;
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EOPNOTSUPP || err == EXDEV || err == EINVAL ||
err == ENOTTY || err == ENOSYS || err == EBADF || err == ETXTBSY
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
|| err == ENOTSUP
#endif
) {
break;
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: FICLONE failed for '{}'",
dst.string()),
err)};
}
#endif
if (!cloned) {
result.method = CopyMethod::PrivateCopy;
std::vector<char> buf(64ULL * 1024ULL);
std::uint64_t copied = 0;
for (;;) {
const ssize_t r = ::read(src_fd.get(), buf.data(), buf.size());
if (r > 0) {
std::size_t off = 0;
const auto ur = static_cast<std::size_t>(r);
while (off < ur) {
const ssize_t w =
::write(tmp_fd.get(), buf.data() + off, ur - off);
if (w < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: write failed for '{}'",
dst.string()),
err)};
}
off += static_cast<std::size_t>(w);
}
copied += ur;
} else if (r == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: read failed on '{}'",
src.string()),
err)};
}
}
result.bytes = copied;
}
if (options.preserve_permissions) {
(void)::fchmod(tmp_fd.get(), create_mode);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format("FileSystem::reflink_copy_file: fsync failed for '{}'",
dst.string()),
err)};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{std::move(closed.error())};
}
if (options.overwrite) {
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: rename failed for '{}'",
dst.string()),
err)};
}
} else {
if (::linkat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str(),
0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: publish failed for '{}'",
dst.string()),
err)};
}
(void)::unlinkat(dir_fd.get(), tmp_name.c_str(), 0);
}
cleanup_tmp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::reflink_copy_file: parent fsync failed for '{}'",
dst.string()),
err)};
}
}
return result;
#else
(void)src;
(void)dst;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::reflink_copy_file: unsupported platform")};
#endif
}
/// Set access and modification timestamps without dereferencing symlinks.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_timestamps_nofollow(const std::filesystem::path& path,
std::int64_t atime_sec,
std::int32_t atime_nsec,
std::int64_t mtime_sec,
std::int32_t mtime_nsec)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: empty path")};
}
auto valid_nsec = [](std::int32_t ns) noexcept {
return (ns >= 0 && ns < 1'000'000'000) || ns == UTIME_NOW ||
ns == UTIME_OMIT;
};
if (!valid_nsec(atime_nsec) || !valid_nsec(mtime_nsec)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: nanoseconds out of range")};
}
struct timespec ts[2]{};
ts[0].tv_sec = static_cast<time_t>(atime_sec);
ts[0].tv_nsec = static_cast<long>(atime_nsec);
ts[1].tv_sec = static_cast<time_t>(mtime_sec);
ts[1].tv_nsec = static_cast<long>(mtime_nsec);
if (::utimensat(AT_FDCWD, path.c_str(), ts, AT_SYMLINK_NOFOLLOW) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::set_timestamps_nofollow: utimensat failed for '{}'",
path.string()),
err)};
}
return {};
#else
(void)path;
(void)atime_sec;
(void)atime_nsec;
(void)mtime_sec;
(void)mtime_nsec;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::set_timestamps_nofollow: unsupported platform")};
#endif
}
/// Set canonical modification and access timestamps (default UNIX epoch 0)
/// without following symlinks (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::int64_t unix_seconds = 0,
std::int32_t nanoseconds = 0)
{
return set_timestamps_nofollow(
path, unix_seconds, nanoseconds, unix_seconds, nanoseconds);
}
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::chrono::sys_seconds tp)
{
return set_canonical_mtime(path, tp.time_since_epoch().count(), 0);
}
} // namespace Void::FileSystem
+7
View File
@@ -116,6 +116,7 @@ public:
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
@@ -201,4 +202,10 @@ private:
const std::vector<std::string>& arguments,
bool close_extra_fds);
/// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned
/// descendant processes in spawned process groups reparent to this process
/// and can be reaped directly via waitpid(-pgid, ...).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
enable_subreaper() noexcept;
} // namespace Void::Process
+276 -77
View File
@@ -7,108 +7,284 @@ namespace Void::Argparse
Parser::Parser(std::string program, std::string description)
: program_{std::move(program)}, description_{std::move(description)}
{}
Parser& Parser::flag(std::string_view lng, std::string_view sht,
std::string_view desc, bool& out)
{
flags_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, &out});
}
Parser::~Parser() = default;
Parser::Parser(Parser&&) noexcept = default;
Parser& Parser::operator=(Parser&&) noexcept = default;
Parser& Parser::flag(std::string_view lng,
std::string_view sht,
std::string_view desc,
bool& out)
{
flags_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, &out});
return *this;
}
Parser& Parser::option(std::string_view lng, std::string_view sht,
std::string_view desc, std::optional<std::string>& out)
Parser& Parser::option(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::optional<std::string>& out)
{
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr});
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr, nullptr});
return *this;
}
Parser& Parser::option_default(std::string_view lng, std::string_view sht,
std::string_view desc, std::string& out,
std::string_view default_value)
Parser& Parser::option_many(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::vector<std::string>& out)
{
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, nullptr, nullptr, &out});
return *this;
}
Parser& Parser::option_default(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::string& out,
std::string_view default_value)
{
out = std::string{default_value};
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc},
std::string{default_value}, nullptr, &out});
options_.push_back({std::string{lng},
std::string{sht},
std::string{desc},
std::string{default_value},
nullptr,
&out,
nullptr});
return *this;
}
Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out)
Parser& Parser::positional(std::string_view name,
std::string_view desc,
std::string& out)
{
positionals_.push_back({std::string{name}, std::string{desc}, &out});
return *this;
}
std::expected<void, std::string>
Parser::parse(int argc, const char* const* argv) const
Parser& Parser::positional_many(std::string_view name,
std::string_view desc,
std::vector<std::string>& out,
bool required)
{
positional_many_ = MultiPosEntry{
std::string{name}, std::string{desc}, &out, required};
return *this;
}
Parser& Parser::subcommand(std::string name,
std::string description,
std::function<void()> on_selected)
{
const std::string sub_prog =
program_.empty() ? name : (program_ + " " + name);
auto sub_parser = std::make_unique<Parser>(sub_prog, std::move(description));
Parser* raw = sub_parser.get();
subcommands_.push_back(SubcommandEntry{
.name = std::move(name),
.parser = std::move(sub_parser),
.on_selected = std::move(on_selected),
});
return *raw;
}
Parser& Parser::require_subcommand(bool required) noexcept
{
has_explicit_require_sub_ = true;
require_subcommand_ = required;
return *this;
}
ParseResult Parser::parse_detailed(int argc, const char* const* argv) const
{
const Parser* active = this;
std::size_t pos_idx = 0;
bool after_double_dash = false;
std::vector<std::string> matched_path;
std::vector<const std::function<void()>*> callbacks;
auto match_flag_or_opt = [&](const Parser* p,
std::string_view arg,
int& i,
bool& matched,
std::string& err) -> bool {
for (const auto& f : p->flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched = true;
return true;
}
}
for (const auto& opt : p->options_) {
std::string_view value;
bool found = false;
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=') {
value = arg.substr(opt.lng.size() + 1);
found = true;
} else if (arg == opt.lng ||
(!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc) {
err = "option '" + std::string{arg} + "' requires a value";
return false;
}
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
if (opt.out_many) opt.out_many->push_back(val_str);
matched = true;
return true;
}
}
matched = false;
return true;
};
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
// Help
if (arg == "--help" || arg == "-h") {
return std::unexpected{help()};
}
if (!after_double_dash) {
if (arg == "--") {
after_double_dash = true;
continue;
}
// Flag check
bool matched_flag = false;
for (const auto& f : flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched_flag = true;
break;
if (arg == "--help" || arg == "-h") {
return ParseResult{
.outcome = ParseOutcome::Help,
.message = active->help(),
.matched_command_path = std::move(matched_path),
};
}
bool matched = false;
std::string err;
if (!match_flag_or_opt(active, arg, i, matched, err)) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = std::move(err),
.matched_command_path = std::move(matched_path),
};
}
if (matched) {
continue;
}
if (arg.size() > 1 && arg[0] == '-') {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown option: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (pos_idx == 0 && !active->subcommands_.empty()) {
const SubcommandEntry* chosen = nullptr;
for (const auto& sub : active->subcommands_) {
if (sub.name == arg) {
chosen = &sub;
break;
}
}
if (chosen != nullptr) {
matched_path.push_back(chosen->name);
if (chosen->on_selected) {
callbacks.push_back(&chosen->on_selected);
}
active = chosen->parser.get();
pos_idx = 0;
continue;
}
if (active->positionals_.empty() &&
!active->positional_many_.has_value()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown subcommand: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
}
}
if (matched_flag) continue;
// Option check: --key=value or --key value or -k value
bool matched_opt = false;
for (const auto& opt : options_) {
std::string_view value;
bool found = false;
// --key=value
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=')
{
value = arg.substr(opt.lng.size() + 1);
found = true;
}
// --key value or -k value
else if (arg == opt.lng || (!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc)
return std::unexpected{"option '" + std::string{arg} + "' requires a value"};
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
matched_opt = true;
break;
}
if (pos_idx < active->positionals_.size()) {
*active->positionals_[pos_idx++].out = std::string{arg};
} else if (active->positional_many_.has_value() &&
active->positional_many_->out != nullptr) {
active->positional_many_->out->push_back(std::string{arg});
} else {
return ParseResult{
.outcome = ParseOutcome::Error,
.message =
"unexpected positional argument: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (matched_opt) continue;
// Unknown --/- prefixed arg
if (arg.size() > 1 && arg[0] == '-')
return std::unexpected{"unknown option: " + std::string{arg}};
// Positional
if (pos_idx >= positionals_.size())
return std::unexpected{"unexpected positional argument: " + std::string{arg}};
*positionals_[pos_idx++].out = std::string{arg};
}
// Check required positionals
for (std::size_t j = pos_idx; j < positionals_.size(); ++j)
return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"};
if (!active->subcommands_.empty()) {
const bool req = active->has_explicit_require_sub_
? active->require_subcommand_
: true;
if (req) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing subcommand for '" + active->program_ + "'",
.matched_command_path = std::move(matched_path),
};
}
}
for (std::size_t j = pos_idx; j < active->positionals_.size(); ++j) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required argument: <" +
active->positionals_[j].name + ">",
.matched_command_path = std::move(matched_path),
};
}
if (active->positional_many_.has_value() &&
active->positional_many_->required &&
active->positional_many_->out != nullptr &&
active->positional_many_->out->empty()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required arguments: <" +
active->positional_many_->name + ">",
.matched_command_path = std::move(matched_path),
};
}
for (const auto* cb : callbacks) {
(*cb)();
}
return ParseResult{
.outcome = ParseOutcome::Ok,
.message = {},
.matched_command_path = std::move(matched_path),
};
}
std::expected<void, std::string> Parser::parse(int argc,
const char* const* argv) const
{
auto res = parse_detailed(argc, argv);
if (!res.ok()) {
return std::unexpected{std::move(res.message)};
}
return {};
}
@@ -116,19 +292,42 @@ std::string Parser::help() const
{
std::ostringstream os;
os << "Usage: " << program_;
for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& o : options_) {
const std::string_view dn = std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
const std::string_view dn =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " [" << o.lng << " <" << dn << ">]";
}
if (!subcommands_.empty()) {
os << " <command>";
}
for (const auto& p : positionals_) os << " <" << p.name << ">";
if (positional_many_.has_value()) {
os << (positional_many_->required ? " <" : " [")
<< positional_many_->name
<< (positional_many_->required ? "...>" : "...]");
}
os << "\n";
if (!description_.empty()) os << "\n" << description_ << "\n";
if (!positionals_.empty()) {
if (!subcommands_.empty()) {
os << "\nCommands:\n";
for (const auto& s : subcommands_) {
os << " " << s.name;
if (!s.parser->description_.empty()) {
os << " " << s.parser->description_;
}
os << "\n";
}
}
if (!positionals_.empty() || positional_many_.has_value()) {
os << "\nArguments:\n";
for (const auto& p : positionals_)
os << " <" << p.name << "> " << p.desc << "\n";
if (positional_many_.has_value()) {
os << " <" << positional_many_->name << "...> "
<< positional_many_->desc << "\n";
}
}
if (!flags_.empty()) {
os << "\nFlags:\n";
@@ -141,13 +340,13 @@ std::string Parser::help() const
if (!options_.empty()) {
os << "\nOptions:\n";
for (const auto& o : options_) {
// Derive a display name from the long option (strip leading --)
const std::string_view dname = std::string_view{o.lng}.substr(
o.lng.size() > 2 ? 2 : 0);
const std::string_view dname =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " " << o.lng;
if (!o.sht.empty()) os << ", " << o.sht;
os << " <" << dname << ">";
if (!o.def.empty()) os << " (default: " << o.def << ")";
if (o.out_many != nullptr) os << " (repeatable)";
os << " " << o.desc << "\n";
}
}
@@ -155,4 +354,4 @@ std::string Parser::help() const
return os.str();
}
} // namespace Void::Argparse
} // namespace Void::Argparse
+833
View File
@@ -0,0 +1,833 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <deque>
#include <filesystem>
#include <format>
#include <map>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(__linux__)
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
#if defined(__linux__)
namespace
{
constexpr std::uint32_t kWatchMask =
IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_FROM |
IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_EXCL_UNLINK |
IN_ONLYDIR;
[[nodiscard]] bool is_subpath_or_equal(const std::filesystem::path& candidate,
const std::filesystem::path& prefix)
{
const std::string c = candidate.lexically_normal().generic_string();
const std::string p = prefix.lexically_normal().generic_string();
if (c == p) {
return true;
}
if (p.empty()) {
return false;
}
const std::size_t plen = p.size();
return c.size() > plen && c.compare(0, plen, p) == 0 && c[plen] == '/';
}
[[nodiscard]] std::filesystem::path
rebase_path(const std::filesystem::path& p,
const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
const std::string ps = p.lexically_normal().generic_string();
const std::string os = old_prefix.lexically_normal().generic_string();
if (ps == os) {
return new_prefix;
}
if (ps.size() > os.size() && ps.compare(0, os.size(), os) == 0 &&
ps[os.size()] == '/') {
return new_prefix / std::filesystem::path{ps.substr(os.size() + 1U)};
}
return p;
}
} // namespace
struct DirectoryWatcher::Impl {
struct PendingMove {
std::filesystem::path path{};
bool is_directory{false};
std::chrono::steady_clock::time_point expires_at{};
};
Void::System::OwnedFd inotify_fd{};
Void::System::OwnedFd wake_fd{};
std::filesystem::path root{};
DirectoryWatcherOptions options{};
mutable std::mutex mutex{};
std::unordered_map<int, std::filesystem::path> wd_to_path{};
std::map<std::filesystem::path, int> path_to_wd{};
std::unordered_map<std::uint32_t, PendingMove> pending_moves{};
std::deque<DirectoryEvent> queue{};
bool rescan_emitted{false};
~Impl() noexcept
{
std::lock_guard lock{mutex};
for (const auto& [wd, _] : wd_to_path) {
if (inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
wd_to_path.clear();
path_to_wd.clear();
}
[[nodiscard]] bool should_ignore(const std::filesystem::path& p,
bool is_dir) const
{
if (options.ignore) {
return options.ignore(p, is_dir);
}
return false;
}
void push_event_locked(DirectoryEvent ev)
{
if (ev.kind == DirectoryEventKind::RescanRequired) {
if (rescan_emitted) {
return;
}
rescan_emitted = true;
queue.push_back(std::move(ev));
return;
}
if (queue.size() >= options.max_queued_events) {
if (!rescan_emitted) {
rescan_emitted = true;
queue.push_back(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher event queue full",
});
}
return;
}
queue.push_back(std::move(ev));
}
void remove_watch_by_wd_locked(int wd, bool call_rm)
{
auto it = wd_to_path.find(wd);
if (it == wd_to_path.end()) {
return;
}
path_to_wd.erase(it->second);
wd_to_path.erase(it);
if (call_rm && inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
void remove_subtree_watches_locked(const std::filesystem::path& prefix)
{
std::vector<int> wds;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, prefix)) {
wds.push_back(wd);
}
}
for (int wd : wds) {
remove_watch_by_wd_locked(wd, true);
}
}
void rewrite_subtree_watches_locked(const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
std::vector<std::pair<int, std::filesystem::path>> updates;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, old_prefix)) {
updates.emplace_back(wd, rebase_path(p, old_prefix, new_prefix));
}
}
for (const auto& [wd, new_p] : updates) {
auto old_it = wd_to_path.find(wd);
if (old_it != wd_to_path.end()) {
path_to_wd.erase(old_it->second);
old_it->second = new_p;
path_to_wd[new_p] = wd;
}
}
}
void attach_single_dir_locked(const std::filesystem::path& dir_path)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
if (path_to_wd.contains(norm)) {
return;
}
if (wd_to_path.size() >= options.max_watches) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher max_watches exceeded",
});
return;
}
const int wd =
::inotify_add_watch(inotify_fd.get(), norm.c_str(), kWatchMask);
if (wd < 0) {
const int err = errno;
if (err == ENOSPC || err == ENOMEM) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = std::format(
"inotify_add_watch exhausted watches (errno={})", err),
});
}
return;
}
// inotify_add_watch may return an existing wd if directory inode aliased.
if (auto existing = wd_to_path.find(wd); existing != wd_to_path.end()) {
if (existing->second != norm) {
path_to_wd.erase(existing->second);
existing->second = norm;
}
} else {
wd_to_path.emplace(wd, norm);
}
path_to_wd[norm] = wd;
}
void attach_subtree_locked(const std::filesystem::path& dir_path,
bool emit_existing_children)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
std::error_code ec;
const auto st = std::filesystem::symlink_status(norm, ec);
if (ec || std::filesystem::is_symlink(st) ||
!std::filesystem::is_directory(st)) {
return;
}
attach_single_dir_locked(norm);
std::vector<std::filesystem::path> stack{norm};
while (!stack.empty()) {
const std::filesystem::path cur = std::move(stack.back());
stack.pop_back();
ec.clear();
std::filesystem::directory_iterator it{
cur,
std::filesystem::directory_options::skip_permission_denied,
ec};
if (ec) {
continue;
}
for (const auto& entry : it) {
std::error_code st_ec;
const auto est = entry.symlink_status(st_ec);
if (st_ec || std::filesystem::is_symlink(est)) {
continue;
}
const bool is_dir = std::filesystem::is_directory(est);
const std::filesystem::path ep =
entry.path().lexically_normal();
if (should_ignore(ep, is_dir)) {
continue;
}
if (emit_existing_children) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = ep,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if (is_dir) {
attach_single_dir_locked(ep);
stack.push_back(ep);
}
}
}
}
void flush_expired_moves_locked(std::chrono::steady_clock::time_point now,
bool force_all)
{
for (auto it = pending_moves.begin(); it != pending_moves.end();) {
if (force_all || now >= it->second.expires_at) {
const auto p = it->second.path;
const bool is_dir = it->second.is_directory;
if (is_dir) {
remove_subtree_watches_locked(p);
}
if (!should_ignore(p, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = p,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
it = pending_moves.erase(it);
} else {
++it;
}
}
}
void process_inotify_event_locked(const struct inotify_event* ev)
{
if ((ev->mask & IN_Q_OVERFLOW) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "inotify kernel event queue overflow (IN_Q_OVERFLOW)",
});
return;
}
if ((ev->mask & IN_IGNORED) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
return;
}
const auto dir_it = wd_to_path.find(ev->wd);
if (dir_it == wd_to_path.end()) {
return;
}
const std::filesystem::path base = dir_it->second;
const bool is_dir = (ev->mask & IN_ISDIR) != 0U;
if ((ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) != 0U && ev->len == 0U) {
if (base == root) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "watched root directory deleted or moved",
});
remove_watch_by_wd_locked(ev->wd, false);
} else if ((ev->mask & IN_DELETE_SELF) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
}
return;
}
const std::string name =
(ev->len > 0U && ev->name[0] != '\0') ? std::string{ev->name}
: std::string{};
const std::filesystem::path full_path =
name.empty() ? base : (base / name).lexically_normal();
if ((ev->mask & IN_MOVED_FROM) != 0U) {
if (ev->cookie != 0U) {
pending_moves.insert_or_assign(
ev->cookie,
PendingMove{
.path = full_path,
.is_directory = is_dir,
.expires_at = std::chrono::steady_clock::now() +
options.rename_pair_window,
});
} else {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
if (!should_ignore(full_path, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
return;
}
if ((ev->mask & IN_MOVED_TO) != 0U) {
if (ev->cookie != 0U) {
if (auto mit = pending_moves.find(ev->cookie);
mit != pending_moves.end()) {
const std::filesystem::path old_path =
std::move(mit->second.path);
pending_moves.erase(mit);
const bool old_ignored = should_ignore(old_path, is_dir);
const bool new_ignored = should_ignore(full_path, is_dir);
if (is_dir) {
if (new_ignored) {
remove_subtree_watches_locked(old_path);
} else {
rewrite_subtree_watches_locked(old_path, full_path);
attach_subtree_locked(full_path, false);
}
}
if (!old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Renamed,
.path = full_path,
.old_path = old_path,
.is_directory = is_dir,
.detail = {},
});
} else if (!old_ignored && new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = old_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
} else if (old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
return;
}
}
if (should_ignore(full_path, is_dir)) {
return;
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
return;
}
if (should_ignore(full_path, is_dir)) {
return;
}
if ((ev->mask & IN_CREATE) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
}
if ((ev->mask & IN_DELETE) != 0U) {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & (IN_MODIFY | IN_CLOSE_WRITE)) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Modified,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & IN_ATTRIB) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::AttributeChanged,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
drain_inotify_locked()
{
alignas(struct inotify_event) std::array<char, 16384> buf{};
for (;;) {
const ssize_t n =
::read(inotify_fd.get(), buf.data(), buf.size());
if (n > 0) {
ssize_t offset = 0;
while (offset < n) {
const auto* ev =
reinterpret_cast<const struct inotify_event*>(
buf.data() + offset);
process_inotify_event_locked(ev);
offset += static_cast<ssize_t>(
sizeof(struct inotify_event) + ev->len);
}
continue;
}
if (n == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher: read(inotify) failed",
err)};
}
return {};
}
void drain_wake_locked() noexcept
{
std::uint64_t val = 0;
while (::read(wake_fd.get(), &val, sizeof(val)) > 0 ||
(errno == EINTR)) {
}
}
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path& root,
DirectoryWatcherOptions options)
{
if (root.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::create: root cannot be empty")};
}
std::error_code ec;
const auto st = std::filesystem::status(root, ec);
if (ec || !std::filesystem::is_directory(st)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::not_found,
std::format(
"FileSystem::DirectoryWatcher::create: '{}' is not a directory",
root.string()))};
}
const int ifd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (ifd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: inotify_init1 failed",
err)};
}
Void::System::OwnedFd owned_ifd{ifd};
const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: eventfd failed",
err)};
}
Void::System::OwnedFd owned_efd{efd};
auto impl = std::make_unique<Impl>();
impl->inotify_fd = std::move(owned_ifd);
impl->wake_fd = std::move(owned_efd);
impl->root = std::filesystem::weakly_canonical(root, ec);
if (ec || impl->root.empty()) {
impl->root = root.lexically_normal();
}
impl->options = std::move(options);
{
std::lock_guard lock{impl->mutex};
impl->attach_subtree_locked(impl->root, false);
}
return DirectoryWatcher{std::move(impl)};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds timeout)
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::poll: moved-from watcher")};
}
const auto start = std::chrono::steady_clock::now();
const auto end_time = start + std::max(std::chrono::milliseconds{0}, timeout);
int ifd = -1;
int efd = -1;
{
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
timeout.count() <= 0);
if (!impl_->queue.empty() && impl_->pending_moves.empty()) {
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
ifd = impl_->inotify_fd.get();
efd = impl_->wake_fd.get();
}
if (timeout.count() > 0) {
for (;;) {
const auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point wait_until = end_time;
{
std::lock_guard lock{impl_->mutex};
for (const auto& [_, pm] : impl_->pending_moves) {
wait_until = std::min(wait_until, pm.expires_at);
}
}
if (now >= wait_until) {
std::lock_guard lock{impl_->mutex};
impl_->flush_expired_moves_locked(now, false);
if (now >= end_time ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
continue;
}
const auto rem_ms = std::max<long long>(
1,
std::chrono::duration_cast<std::chrono::milliseconds>(
wait_until - now)
.count());
std::array<struct pollfd, 2> pfds{{
{ifd, POLLIN, 0},
{efd, POLLIN, 0},
}};
const int rc =
::poll(pfds.data(), pfds.size(), static_cast<int>(rem_ms));
if (rc < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::poll: poll failed",
err)};
}
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
const bool woken = (pfds[1].revents & POLLIN) != 0;
if (woken) {
impl_->drain_wake_locked();
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
false);
if (woken ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
}
}
std::lock_guard lock{impl_->mutex};
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::rescan: moved-from watcher")};
}
std::lock_guard lock{impl_->mutex};
for (const auto& [wd, _] : impl_->wd_to_path) {
(void)::inotify_rm_watch(impl_->inotify_fd.get(), wd);
}
impl_->wd_to_path.clear();
impl_->path_to_wd.clear();
impl_->pending_moves.clear();
impl_->queue.clear();
impl_->rescan_emitted = false;
impl_->attach_subtree_locked(impl_->root, false);
return {};
}
void DirectoryWatcher::wake() noexcept
{
if (!impl_ || !impl_->wake_fd.valid()) {
return;
}
const std::uint64_t one = 1;
while (::write(impl_->wake_fd.get(), &one, sizeof(one)) < 0 &&
errno == EINTR) {
}
}
void DirectoryWatcher::simulate_overflow_for_test()
{
if (!impl_) {
return;
}
{
std::lock_guard lock{impl_->mutex};
impl_->push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = impl_->root,
.old_path = {},
.is_directory = true,
.detail = "simulated IN_Q_OVERFLOW",
});
}
wake();
}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept
{
if (!impl_) {
return 0;
}
std::lock_guard lock{impl_->mutex};
return impl_->wd_to_path.size();
}
int DirectoryWatcher::native_handle() const noexcept
{
return impl_ ? impl_->inotify_fd.get() : -1;
}
#else
struct DirectoryWatcher::Impl {
std::filesystem::path root{};
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path&,
DirectoryWatcherOptions)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: inotify watcher is Linux-only")};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
void DirectoryWatcher::wake() noexcept {}
void DirectoryWatcher::simulate_overflow_for_test() {}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept { return 0; }
int DirectoryWatcher::native_handle() const noexcept { return -1; }
#endif
} // namespace Void::FileSystem
+192 -54
View File
@@ -40,6 +40,7 @@ Child::Child(Child&&) noexcept = default;
Child& Child::operator=(Child&&) noexcept = default;
bool Child::valid() const noexcept { return false; }
bool Child::running() const noexcept { return false; }
bool Child::process_group_alive() const noexcept { return false; }
long long Child::pid() const noexcept { return -1; }
long long Child::pgid() const noexcept { return -1; }
bool Child::owns_process_group() const noexcept { return false; }
@@ -142,6 +143,13 @@ Void::Result::Result<void, Void::Result::Error> reexec(
return Void::Result::fail("Process::reexec: not implemented on Windows");
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: not supported on Windows")};
}
} // namespace Void::Process
#else // POSIX
@@ -150,6 +158,9 @@ Void::Result::Result<void, Void::Result::Error> reexec(
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#if defined(__linux__) && __has_include(<sys/prctl.h>)
#include <sys/prctl.h>
#endif
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
@@ -468,26 +479,102 @@ void write_child_failure(int err_fd, int phase, int err) noexcept
return st;
}
[[nodiscard]] bool is_process_group_alive(pid_t pgid) noexcept
{
if (pgid <= 0) {
return false;
}
for (;;) {
if (::kill(-pgid, 0) == 0) {
return true;
}
if (errno == EINTR) {
continue;
}
return errno == EPERM;
}
}
void reap_group_nonblocking(pid_t pid,
pid_t pgid,
bool owns_group,
bool& reaped,
ExitStatus& cached,
int& out_errno) noexcept
{
out_errno = 0;
if (!reaped && pid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(pid, &raw, WNOHANG);
if (w == pid) {
cached = decode_wait_status(raw);
reaped = true;
break;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped = true;
break;
}
out_errno = errno;
break;
}
}
if (owns_group && pgid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(-pgid, &raw, WNOHANG);
if (w > 0) {
if (w == pid && !reaped) {
cached = decode_wait_status(raw);
reaped = true;
}
continue;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
break;
}
}
}
[[nodiscard]] bool signal_target(pid_t pid,
pid_t pgid,
bool owns_group,
bool leader_reaped,
int sig,
int& out_errno) noexcept
{
bool delivered = false;
out_errno = 0;
if (owns_group && pgid > 0) {
if (::kill(-pgid, sig) == 0) {
return true;
}
out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) {
return false;
delivered = true;
} else {
out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) {
return false;
}
}
}
if (::kill(pid, sig) == 0) {
return true;
if (!leader_reaped && pid > 0) {
if (::kill(pid, sig) == 0) {
delivered = true;
} else {
out_errno = errno;
}
}
out_errno = errno;
return false;
return delivered;
}
[[nodiscard]] std::optional<std::string>
@@ -706,6 +793,13 @@ Child& Child::operator=(Child&& other) noexcept
bool Child::valid() const noexcept { return pid_ > 0; }
bool Child::running() const noexcept { return pid_ > 0 && !reaped_; }
bool Child::process_group_alive() const noexcept
{
if (owns_group_ && pgid_ > 0) {
return is_process_group_alive(static_cast<pid_t>(pgid_));
}
return running();
}
long long Child::pid() const noexcept { return pid_; }
long long Child::pgid() const noexcept { return pgid_; }
bool Child::owns_process_group() const noexcept { return owns_group_; }
@@ -738,7 +832,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
Void::System::SystemErrorCode::invalid_argument,
"Process::Child::send_signal: invalid child")};
}
if (reaped_) {
if (reaped_ && (!owns_group_ || !process_group_alive())) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::Child::send_signal: child already reaped")};
@@ -747,6 +841,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
if (!signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
reaped_,
sig,
err)) {
return std::unexpected{Void::System::make_system_error(
@@ -798,35 +893,37 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
Void::System::SystemErrorCode::invalid_argument,
"Process::Child::terminate: invalid child")};
}
if (reaped_) {
const pid_t target_pid = static_cast<pid_t>(pid_);
const pid_t target_pgid = static_cast<pid_t>(pgid_);
const bool group_owned = owns_group_ && target_pgid > 0;
auto group_finished = [&]() noexcept -> bool {
int reap_err = 0;
reap_group_nonblocking(
target_pid, target_pgid, group_owned, reaped_, cached_status_, reap_err);
if (!reaped_) {
return false;
}
return !group_owned || !is_process_group_alive(target_pgid);
};
if (group_finished()) {
return cached_status_;
}
const auto effective_grace =
(grace.count() >= 0) ? grace : kill_grace_;
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
}
int sig_err = 0;
(void)signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
SIGTERM,
sig_err);
(void)signal_target(
target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err);
const auto grace_deadline =
std::chrono::steady_clock::now() + effective_grace;
while (std::chrono::steady_clock::now() < grace_deadline) {
auto polled = try_wait();
if (!polled.has_value()) {
return std::unexpected{polled.error()};
}
if (polled->has_value()) {
return **polled;
if (group_finished()) {
return cached_status_;
}
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
grace_deadline - std::chrono::steady_clock::now());
@@ -834,38 +931,61 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
break;
}
std::this_thread::sleep_for(
std::min(rem, std::chrono::milliseconds{10}));
std::min(rem, std::chrono::milliseconds{5}));
}
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
if (group_finished()) {
return cached_status_;
}
(void)signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
SIGKILL,
sig_err);
(void)signal_target(
target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err);
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(static_cast<pid_t>(pid_), &raw, 0);
if (w == static_cast<pid_t>(pid_)) {
cached_status_ = decode_wait_status(raw);
reaped_ = true;
return cached_status_;
if (!reaped_) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(target_pid, &raw, 0);
if (w == target_pid) {
cached_status_ = decode_wait_status(raw);
reaped_ = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped_ = true;
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
}
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
}
if (group_owned) {
const auto kill_ceiling =
std::chrono::steady_clock::now() + std::chrono::seconds{5};
while (!group_finished()) {
if (std::chrono::steady_clock::now() >= kill_ceiling) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::Child::terminate: process group members failed "
"to exit after SIGKILL")};
}
(void)signal_target(target_pid,
target_pgid,
group_owned,
reaped_,
SIGKILL,
sig_err);
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
return cached_status_;
}
Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking(
@@ -950,7 +1070,7 @@ void Child::reset_and_reap() noexcept
stdin_.reset();
stdout_.reset();
stderr_.reset();
if (pid_ > 0 && !reaped_) {
if (pid_ > 0 && (!reaped_ || process_group_alive())) {
(void)terminate(kill_grace_);
}
pid_ = -1;
@@ -1643,6 +1763,24 @@ Void::Result::Result<void, Void::Result::Error>
err)};
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
#if defined(__linux__) && defined(PR_SET_CHILD_SUBREAPER)
if (::prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::enable_subreaper: prctl(PR_SET_CHILD_SUBREAPER) failed",
err)};
}
return {};
#else
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: PR_SET_CHILD_SUBREAPER unavailable on this platform")};
#endif
}
} // namespace Void::Process
#endif // _WIN32
+54
View File
@@ -194,6 +194,57 @@ int mode_ignore_sigterm(int argc, char** argv)
return 0;
}
int mode_grandchild_ignore_sigterm(int argc, char** argv)
{
if (argc < 3) {
return usage_error("grandchild-ignore-sigterm requires <marker_file>");
}
const char* marker_path = argv[2];
int ready_p[2]{-1, -1};
if (::pipe(ready_p) != 0) {
return 1;
}
const pid_t gc = ::fork();
if (gc < 0) {
(void)::close(ready_p[0]);
(void)::close(ready_p[1]);
return 1;
}
if (gc == 0) {
(void)::close(ready_p[0]);
std::signal(SIGTERM, SIG_IGN);
const int mfd = ::open(marker_path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
if (mfd < 0) {
(void)::close(ready_p[1]);
::_exit(1);
}
static constexpr char kTick[] = "tick\n";
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
static constexpr char kReady[] = "ready\n";
(void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1);
const char one = '1';
(void)write_all_fd(ready_p[1], &one, 1);
(void)::close(ready_p[1]);
(void)::close(STDIN_FILENO);
(void)::close(STDOUT_FILENO);
(void)::close(STDERR_FILENO);
for (int iter = 0; iter < 500; ++iter) {
std::this_thread::sleep_for(std::chrono::milliseconds{10});
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
}
(void)::close(mfd);
::_exit(0);
}
(void)::close(ready_p[1]);
char dummy = 0;
bool eof = false;
(void)read_exact_fd(ready_p[0], &dummy, 1, eof);
(void)::close(ready_p[0]);
::_exit(0);
}
int mode_simultaneous_io(int argc, char** argv)
{
if (argc != 3) {
@@ -485,6 +536,9 @@ int main(int argc, char** argv)
if (mode == "ignore-sigterm") {
return mode_ignore_sigterm(argc, argv);
}
if (mode == "grandchild-ignore-sigterm") {
return mode_grandchild_ignore_sigterm(argc, argv);
}
if (mode == "simultaneous-io") {
return mode_simultaneous_io(argc, argv);
}
@@ -187,3 +187,89 @@ Void::Testing::Test argparse_help_contains_names()
Void::Testing::expect(h.find("--output") != std::string::npos);
Void::Testing::expect(h.find("A description.") != std::string::npos);
}
Void::Testing::Test argparse_subcommands_option_many_and_distinct_outcomes()
{
bool verbose = false;
std::vector<std::string> targets;
std::vector<std::string> profiles;
std::string compdb_mode;
bool build_selected = false;
bool use_selected = false;
Parser root{"vbs", "Void Build System"};
root.flag("--verbose", "-v", "verbose output", verbose);
auto& build_cmd =
root.subcommand("build", "Build project", [&] { build_selected = true; });
build_cmd.option_many("--target", "-t", "targets", targets);
build_cmd.option_many("--profile", "-p", "profiles", profiles);
auto& compdb_cmd = root.subcommand("compdb", "Compile database commands");
auto& use_cmd =
compdb_cmd.subcommand("use", "Select compdb", [&] { use_selected = true; });
use_cmd.positional("mode", "compdb mode", compdb_mode);
// 1. Subcommand + repeatable option_many
{
const Args a{{"vbs", "-v", "build", "--target", "app", "--target=lib",
"-p", "debug", "--profile", "release"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::require(res.ok());
Void::Testing::expect(verbose);
Void::Testing::expect(build_selected);
Void::Testing::expect(!use_selected);
Void::Testing::expect_eq(res.matched_command_path.size(), std::size_t{1});
Void::Testing::expect_eq(res.matched_command_path[0],
std::string{"build"});
Void::Testing::expect_eq(targets.size(), std::size_t{2});
Void::Testing::expect_eq(targets[0], std::string{"app"});
Void::Testing::expect_eq(targets[1], std::string{"lib"});
Void::Testing::expect_eq(profiles.size(), std::size_t{2});
Void::Testing::expect_eq(profiles[0], std::string{"debug"});
Void::Testing::expect_eq(profiles[1], std::string{"release"});
}
// 2. Nested subcommands ("vbs compdb use active")
{
build_selected = false;
use_selected = false;
const Args a{{"vbs", "compdb", "use", "active"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::require(res.ok());
Void::Testing::expect(!build_selected);
Void::Testing::expect(use_selected);
Void::Testing::expect_eq(res.matched_command_path.size(), std::size_t{2});
Void::Testing::expect_eq(res.matched_command_path[0],
std::string{"compdb"});
Void::Testing::expect_eq(res.matched_command_path[1], std::string{"use"});
Void::Testing::expect_eq(compdb_mode, std::string{"active"});
}
// 3. Help is ParseOutcome::Help (distinct from ParseOutcome::Error)
{
const Args a{{"vbs", "--help"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::expect(res.is_help());
Void::Testing::expect(!res.is_error());
Void::Testing::expect(res.message.find("Commands:") != std::string::npos);
const Args sub_help{{"vbs", "build", "--help"}};
const auto sres = root.parse_detailed(sub_help.argc, sub_help.argv);
Void::Testing::expect(sres.is_help());
Void::Testing::expect(sres.message.find("--target") != std::string::npos);
}
// 4. Missing or unknown subcommand is ParseOutcome::Error without running callbacks
{
build_selected = false;
const Args missing_sub{{"vbs"}};
const auto mres = root.parse_detailed(missing_sub.argc, missing_sub.argv);
Void::Testing::expect(mres.is_error());
const Args bad_sub{{"vbs", "unknowncmd"}};
const auto bres = root.parse_detailed(bad_sub.argc, bad_sub.argv);
Void::Testing::expect(bres.is_error());
Void::Testing::expect(!build_selected);
}
}
@@ -0,0 +1,176 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <string>
#include <vector>
namespace
{
[[nodiscard]] std::vector<Void::FileSystem::DirectoryEvent>
collect_events(Void::FileSystem::DirectoryWatcher& watcher,
std::chrono::milliseconds budget)
{
std::vector<Void::FileSystem::DirectoryEvent> all;
const auto deadline = std::chrono::steady_clock::now() + budget;
while (std::chrono::steady_clock::now() < deadline) {
auto batch = watcher.poll(std::chrono::milliseconds{40});
Void::Testing::require(batch.has_value());
for (auto& ev : *batch) {
all.push_back(std::move(ev));
}
if (!all.empty() && batch->empty()) {
break;
}
}
return all;
}
} // namespace
Void::Testing::Test directory_watcher_tracks_recursive_trees_ignores_and_renames()
{
Void::FileSystem::TempDir tmp{"void_dir_watch_"};
const auto ignored_dir = tmp / ".git";
Void::Testing::require(
Void::FileSystem::ensure_directory(ignored_dir).has_value());
Void::FileSystem::DirectoryWatcherOptions opts;
opts.ignore = [](const std::filesystem::path& p, bool) {
for (const auto& part : p) {
if (part == ".git" || part == "build") {
return true;
}
}
return false;
};
auto w_res = Void::FileSystem::DirectoryWatcher::create(tmp.path(), opts);
Void::Testing::require(w_res.has_value());
auto watcher = std::move(*w_res);
Void::Testing::expect_eq(watcher.watch_count(), std::size_t{1});
// Ignored subtree changes must produce zero events
Void::Testing::require(
Void::FileSystem::write_file(ignored_dir / "HEAD", "ref").has_value());
auto ignored_events = watcher.poll(std::chrono::milliseconds{40});
Void::Testing::require(ignored_events.has_value());
Void::Testing::expect(ignored_events->empty());
// Create nested subdirectories + file immediately -> auto-watched recursively
const auto sub = tmp / "src/core";
Void::Testing::require(Void::FileSystem::ensure_directory(sub).has_value());
Void::Testing::require(
Void::FileSystem::write_file(sub / "main.cpp", "int main(){}")
.has_value());
const auto create_events =
collect_events(watcher, std::chrono::milliseconds{500});
const bool saw_file_create_or_mod = std::any_of(
create_events.begin(), create_events.end(),
[&](const Void::FileSystem::DirectoryEvent& ev) {
return ev.path.filename() == "main.cpp" &&
(ev.kind == Void::FileSystem::DirectoryEventKind::Created ||
ev.kind == Void::FileSystem::DirectoryEventKind::Modified);
});
Void::Testing::expect(saw_file_create_or_mod);
Void::Testing::expect(watcher.watch_count() >= 3U);
// Modify inside auto-watched nested directory
Void::Testing::require(
Void::FileSystem::write_file(sub / "main.cpp", "int main(){return 0;}")
.has_value());
const auto mod_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
mod_events.begin(), mod_events.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Modified &&
ev.path.filename() == "main.cpp";
}));
// File rename pairing (IN_MOVED_FROM / IN_MOVED_TO)
std::filesystem::rename(sub / "main.cpp", sub / "entry.cpp");
const auto ren_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
ren_events.begin(), ren_events.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Renamed &&
ev.old_path.filename() == "main.cpp" &&
ev.path.filename() == "entry.cpp";
}));
// Directory rename rewrites watch paths so modifications inside new path
// still report the new directory path.
const auto renamed_dir = tmp / "src/engine";
std::filesystem::rename(sub, renamed_dir);
(void)collect_events(watcher, std::chrono::milliseconds{300});
Void::Testing::require(
Void::FileSystem::write_file(renamed_dir / "entry.cpp", "// updated")
.has_value());
const auto post_move_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
post_move_events.begin(), post_move_events.end(),
[&](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Modified &&
ev.path == (watcher.root() / "src/engine/entry.cpp");
}));
// Directory replacement / deletion storm
std::filesystem::remove_all(tmp / "src");
const auto del_events =
collect_events(watcher, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
del_events.begin(), del_events.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind == Void::FileSystem::DirectoryEventKind::Deleted;
}));
}
Void::Testing::Test directory_watcher_signals_rescan_on_overflow_and_limit()
{
Void::FileSystem::TempDir tmp{"void_dir_ovf_"};
// 1. Simulated queue overflow emits RescanRequired and wake recovers
{
auto w_res = Void::FileSystem::DirectoryWatcher::create(tmp.path());
Void::Testing::require(w_res.has_value());
w_res->simulate_overflow_for_test();
auto evs = w_res->poll(std::chrono::milliseconds{100});
Void::Testing::require(evs.has_value());
Void::Testing::expect(std::any_of(
evs->begin(), evs->end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind ==
Void::FileSystem::DirectoryEventKind::RescanRequired;
}));
Void::Testing::require(w_res->rescan().has_value());
}
// 2. max_watches exhaustion emits RescanRequired
{
Void::FileSystem::DirectoryWatcherOptions tight;
tight.max_watches = 1U;
auto w_res =
Void::FileSystem::DirectoryWatcher::create(tmp.path(), tight);
Void::Testing::require(w_res.has_value());
Void::Testing::require(
Void::FileSystem::ensure_directory(tmp / "extra_dir").has_value());
const auto evs = collect_events(*w_res, std::chrono::milliseconds{400});
Void::Testing::expect(std::any_of(
evs.begin(), evs.end(),
[](const Void::FileSystem::DirectoryEvent& ev) {
return ev.kind ==
Void::FileSystem::DirectoryEventKind::RescanRequired;
}));
}
}
+116
View File
@@ -96,3 +96,119 @@ Void::Testing::Test remove_path_handles_missing_and_recursive()
Void::Testing::expect(r2.has_value());
Void::Testing::expect(!std::filesystem::exists(tmp.path() / "a"));
}
Void::Testing::Test filesystem_file_lock_symlink_swap_reflink_and_timestamps()
{
Void::FileSystem::TempDir tmp{"void_fs_vl010_"};
// 1. RAII advisory FileLock (shared & exclusive, blocking & try_lock)
{
const auto lock_path = tmp / "resource.lock";
auto ex = Void::FileSystem::FileLock::lock(
lock_path, Void::FileSystem::LockMode::Exclusive);
Void::Testing::require(ex.has_value());
Void::Testing::expect(ex->locked());
auto contended_ex = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Exclusive);
Void::Testing::require(contended_ex.has_value());
Void::Testing::expect(!contended_ex->has_value());
auto contended_sh = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Shared);
Void::Testing::require(contended_sh.has_value());
Void::Testing::expect(!contended_sh->has_value());
ex->unlock();
Void::Testing::expect(!ex->locked());
auto sh1 = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Shared);
auto sh2 = Void::FileSystem::FileLock::try_lock(
lock_path, Void::FileSystem::LockMode::Shared);
Void::Testing::require(sh1.has_value() && sh1->has_value());
Void::Testing::require(sh2.has_value() && sh2->has_value());
}
// 2. Atomic symlink swap over missing, existing, and dangling links
{
const auto link_path = tmp / "current";
Void::Testing::require(
Void::FileSystem::atomic_symlink_swap(link_path, "v1")
.has_value());
Void::Testing::expect_eq(
std::filesystem::read_symlink(link_path).string(),
std::string{"v1"});
Void::Testing::require(
Void::FileSystem::atomic_symlink_swap(link_path, "v2")
.has_value());
Void::Testing::expect_eq(
std::filesystem::read_symlink(link_path).string(),
std::string{"v2"});
}
// 3. reflink_copy_file isolates copied file (never hardlinked)
{
const auto src = tmp / "origin.bin";
const auto dst = tmp / "cloned.bin";
const std::string payload(128ULL * 1024ULL, 'K');
Void::Testing::require(
Void::FileSystem::write_file(src, payload).has_value());
auto cp = Void::FileSystem::reflink_copy_file(src, dst);
Void::Testing::require(cp.has_value());
Void::Testing::expect_eq(cp->bytes, payload.size());
Void::Testing::expect_eq(
Void::FileSystem::read_file(dst).value(), payload);
struct stat st_src {};
struct stat st_dst {};
Void::Testing::require(::lstat(src.c_str(), &st_src) == 0);
Void::Testing::require(::lstat(dst.c_str(), &st_dst) == 0);
Void::Testing::expect(st_src.st_ino != st_dst.st_ino);
Void::Testing::expect_eq(st_src.st_nlink, nlink_t{1});
Void::Testing::expect_eq(st_dst.st_nlink, nlink_t{1});
// overwrite == false must fail cleanly when dst already exists
Void::FileSystem::CopyOptions no_overwrite;
no_overwrite.overwrite = false;
Void::Testing::expect(
!Void::FileSystem::reflink_copy_file(src, dst, no_overwrite)
.has_value());
// Mutating dst must never alter src
Void::Testing::require(
Void::FileSystem::write_file(dst, "mutated").has_value());
Void::Testing::expect_eq(
Void::FileSystem::read_file(src).value(), payload);
}
// 4. Canonical timestamp setter with AT_SYMLINK_NOFOLLOW
{
const auto target = tmp / "real.txt";
const auto link = tmp / "alias.txt";
Void::Testing::require(
Void::FileSystem::write_file(target, "data").has_value());
Void::Testing::require(
Void::FileSystem::atomic_symlink_swap(link, target).has_value());
constexpr std::int64_t kTargetMtime = 1'700'000'000LL;
constexpr std::int64_t kLinkMtime = 1'600'000'123LL;
Void::Testing::require(
Void::FileSystem::set_canonical_mtime(target, kTargetMtime)
.has_value());
Void::Testing::require(
Void::FileSystem::set_canonical_mtime(link, kLinkMtime)
.has_value());
struct stat st_target {};
struct stat st_link {};
Void::Testing::require(::lstat(target.c_str(), &st_target) == 0);
Void::Testing::require(::lstat(link.c_str(), &st_link) == 0);
Void::Testing::expect_eq(static_cast<std::int64_t>(st_target.st_mtim.tv_sec),
kTargetMtime);
Void::Testing::expect_eq(static_cast<std::int64_t>(st_link.st_mtim.tv_sec),
kLinkMtime);
}
}
@@ -19,6 +19,7 @@
#include <fstream>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
@@ -294,3 +295,72 @@ Void::Testing::Test system_replace_file_temp_ownership_and_metrics()
expect(sample.valid);
expect(sample.ratio >= 0.0);
}
Void::Testing::Test system_terminate_reaps_entire_process_group_after_leader_exits()
{
Void::FileSystem::TempDir tmp{"void_sys_pgid_"};
const auto marker = tmp / "grandchild_ticks.txt";
Void::Process::SpawnOptions opts;
opts.executable = VOID_PROCESS_HELPER_PATH;
opts.arguments = {"grandchild-ignore-sigterm", marker.string()};
opts.new_process_group = true;
opts.stdin_pipe = false;
opts.stderr_pipe = false;
auto spawned = Void::Process::spawn(opts);
require(spawned.has_value());
// Wait for grandchild readiness signal on stdout.
std::string ready_buf;
std::array<char, 64> chunk{};
const auto wait_start = std::chrono::steady_clock::now();
while (ready_buf.find("ready\n") == std::string::npos) {
const ssize_t n = ::read(spawned->stdout_fd(), chunk.data(), chunk.size());
if (n > 0) {
ready_buf.append(chunk.data(), static_cast<std::size_t>(n));
continue;
}
if (n < 0 && errno == EINTR) {
continue;
}
if (std::chrono::steady_clock::now() - wait_start > std::chrono::seconds{5}) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
require(ready_buf.find("ready\n") != std::string::npos);
// Wait until direct leader has exited and been reaped, while the
// SIGTERM-ignoring grandchild continues running in the process group.
std::optional<Void::Process::ExitStatus> leader_status;
for (int i = 0; i < 200; ++i) {
auto w = spawned->try_wait();
require(w.has_value());
if (w->has_value()) {
leader_status = *w;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
require(leader_status.has_value());
expect(leader_status->exited);
expect_eq(leader_status->code, 0);
expect(spawned->process_group_alive());
// terminate(60ms) must send SIGTERM to -pgid, wait out grace since the
// grandchild ignores SIGTERM, escalate to SIGKILL, and not return until
// ESRCH confirms all process-group members are gone.
auto term = spawned->terminate(std::chrono::milliseconds{60});
require(term.has_value());
expect(!spawned->process_group_alive());
std::error_code ec;
const auto size_after_terminate = std::filesystem::file_size(marker, ec);
require(!ec);
expect(size_after_terminate > 0U);
std::this_thread::sleep_for(std::chrono::milliseconds{100});
const auto size_later = std::filesystem::file_size(marker, ec);
require(!ec);
expect_eq(size_later, size_after_terminate);
}