feat: adopt VoidLibrary VL-001..VL-013, self-building build.cpp, live logs, and generated CLI help
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 10s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 10s
This commit is contained in:
1 parent
ab64147f9d
commit
363fb8200e
33 files changed
+1754
-3155
No files matched your search
+28
-159
@@ -1,17 +1,11 @@
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <linux/fs.h>
|
||||
#include <set>
|
||||
#include <sys/file.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
@@ -19,13 +13,6 @@
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
std::atomic<std::uint64_t> g_temp_seq{0};
|
||||
|
||||
std::string unique_suffix() {
|
||||
const auto seq = g_temp_seq.fetch_add(1, std::memory_order_relaxed);
|
||||
return std::format(".vbs_tmp_{}_{}", static_cast<long long>(::getpid()), seq);
|
||||
}
|
||||
|
||||
Void::Result::Error sys_err(int err, std::string message) {
|
||||
return Void::System::make_system_error(Void::System::map_errno_to_system_code(err),
|
||||
std::move(message), err);
|
||||
@@ -33,26 +20,6 @@ Void::Result::Error sys_err(int err, std::string message) {
|
||||
|
||||
} // namespace
|
||||
|
||||
FileLock::~FileLock() noexcept { release(); }
|
||||
|
||||
FileLock::FileLock(FileLock &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {}
|
||||
|
||||
FileLock &FileLock::operator=(FileLock &&other) noexcept {
|
||||
if (this != &other) {
|
||||
release();
|
||||
fd_ = std::exchange(other.fd_, -1);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void FileLock::release() noexcept {
|
||||
if (fd_ >= 0) {
|
||||
(void)::flock(fd_, LOCK_UN);
|
||||
(void)::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<FileLock, Void::Result::Error>
|
||||
FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool non_blocking) {
|
||||
std::error_code ec;
|
||||
@@ -64,28 +31,25 @@ FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool no
|
||||
lock_path.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
const int fd = ::open(lock_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("FileLock: cannot open '{}'", lock_path.string()))};
|
||||
}
|
||||
int op = (mode == LockMode::Exclusive) ? LOCK_EX : LOCK_SH;
|
||||
const auto vl_mode = (mode == LockMode::Exclusive) ? Void::FileSystem::LockMode::Exclusive
|
||||
: Void::FileSystem::LockMode::Shared;
|
||||
if (non_blocking) {
|
||||
op |= LOCK_NB;
|
||||
}
|
||||
for (;;) {
|
||||
if (::flock(fd, op) == 0) {
|
||||
return FileLock{fd};
|
||||
auto res = Void::FileSystem::FileLock::try_lock(lock_path, vl_mode);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
if (!res->has_value()) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::busy,
|
||||
std::format("FileLock: '{}' is already locked", lock_path.string()), EWOULDBLOCK)};
|
||||
}
|
||||
const int err = errno;
|
||||
(void)::close(fd);
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("FileLock: flock failed for '{}'", lock_path.string()))};
|
||||
return FileLock{std::move(**res)};
|
||||
}
|
||||
auto res = Void::FileSystem::FileLock::lock(lock_path, vl_mode);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
return FileLock{std::move(*res)};
|
||||
}
|
||||
|
||||
Void::Result::Result<FileMetadata, Void::Result::Error>
|
||||
@@ -140,26 +104,6 @@ stat_lstat(const std::filesystem::path &path) {
|
||||
Void::Result::Result<bool, Void::Result::Error>
|
||||
copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst,
|
||||
std::optional<std::uint32_t> mode_override) {
|
||||
const int src_fd = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (src_fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: cannot open source '{}'", src.string()))};
|
||||
}
|
||||
Void::System::OwnedFd src_guard{src_fd};
|
||||
|
||||
struct stat src_st{};
|
||||
if (::fstat(src_fd, &src_st) != 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: fstat failed for '{}'", src.string()))};
|
||||
}
|
||||
if (!S_ISREG(src_st.st_mode)) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("copy_isolated: source '{}' is not a regular file", src.string()))};
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
if (dst.has_parent_path()) {
|
||||
std::filesystem::create_directories(dst.parent_path(), ec);
|
||||
@@ -169,86 +113,24 @@ copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst
|
||||
dst.string(), ec.message()))};
|
||||
}
|
||||
}
|
||||
Void::FileSystem::CopyOptions opts;
|
||||
opts.overwrite = true;
|
||||
opts.preserve_permissions = !mode_override.has_value();
|
||||
opts.durability = Void::FileSystem::ReplaceDurability::atomic_visibility;
|
||||
|
||||
const auto mode = mode_override.value_or(static_cast<std::uint32_t>(src_st.st_mode & 0777u));
|
||||
const auto temp_path = dst.parent_path() / (dst.filename().string() + unique_suffix());
|
||||
const int dst_fd = ::open(temp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
|
||||
static_cast<mode_t>(mode));
|
||||
if (dst_fd < 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("copy_isolated: cannot create temp '{}'", temp_path.string()))};
|
||||
auto res = Void::FileSystem::reflink_copy_file(src, dst, opts);
|
||||
if (!res) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
Void::System::OwnedFd dst_guard{dst_fd};
|
||||
auto cleanup = [&] { (void)::unlink(temp_path.c_str()); };
|
||||
|
||||
bool used_reflink = false;
|
||||
#ifdef FICLONE
|
||||
if (::ioctl(dst_fd, FICLONE, src_fd) == 0) {
|
||||
used_reflink = true;
|
||||
if (mode_override) {
|
||||
(void)::chmod(dst.c_str(), static_cast<mode_t>(*mode_override));
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!used_reflink) {
|
||||
std::array<char, 65536> buf{};
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(src_fd, buf.data(), buf.size());
|
||||
if (n > 0) {
|
||||
std::size_t off = 0;
|
||||
while (off < static_cast<std::size_t>(n)) {
|
||||
const ssize_t w =
|
||||
::write(dst_fd, buf.data() + off, static_cast<std::size_t>(n) - off);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
const int err = errno;
|
||||
cleanup();
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: write failed for '{}'",
|
||||
dst.string()))};
|
||||
}
|
||||
off += static_cast<std::size_t>(w);
|
||||
}
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
const int err = errno;
|
||||
cleanup();
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: read failed for '{}'", src.string()))};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(void)::fchmod(dst_fd, static_cast<mode_t>(mode));
|
||||
if (const auto closed = dst_guard.close(); !closed) {
|
||||
cleanup();
|
||||
return std::unexpected{closed.error()};
|
||||
}
|
||||
|
||||
if (::rename(temp_path.c_str(), dst.c_str()) != 0) {
|
||||
const int err = errno;
|
||||
cleanup();
|
||||
return std::unexpected{
|
||||
sys_err(err, std::format("copy_isolated: rename failed for '{}'", dst.string()))};
|
||||
}
|
||||
return used_reflink;
|
||||
return res->method == Void::FileSystem::CopyMethod::Reflink;
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds) {
|
||||
struct timespec times[2];
|
||||
times[0].tv_sec = static_cast<time_t>(epoch_seconds);
|
||||
times[0].tv_nsec = 0;
|
||||
times[1].tv_sec = static_cast<time_t>(epoch_seconds);
|
||||
times[1].tv_nsec = 0;
|
||||
if (::utimensat(AT_FDCWD, path.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("set_canonical_mtime: utimensat failed for '{}'", path.string()))};
|
||||
}
|
||||
return {};
|
||||
return Void::FileSystem::set_canonical_mtime(path, epoch_seconds, 0);
|
||||
}
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error>
|
||||
@@ -319,19 +201,8 @@ atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesyste
|
||||
ec.value(), std::format("atomic_swap_symlink: create_directories failed for '{}'",
|
||||
parent.string()))};
|
||||
}
|
||||
const auto temp_link = parent / (link_path.filename().string() + unique_suffix());
|
||||
if (::symlink(target.c_str(), temp_link.c_str()) != 0) {
|
||||
const int err = errno;
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("atomic_swap_symlink: symlink failed for '{}'", temp_link.string()))};
|
||||
}
|
||||
if (::rename(temp_link.c_str(), link_path.c_str()) != 0) {
|
||||
const int err = errno;
|
||||
(void)::unlink(temp_link.c_str());
|
||||
return std::unexpected{sys_err(
|
||||
err, std::format("atomic_swap_symlink: rename failed for '{}'", link_path.string()))};
|
||||
}
|
||||
return fsync_directory(parent);
|
||||
return Void::FileSystem::atomic_symlink_swap(link_path, target,
|
||||
Void::FileSystem::ReplaceDurability::durable_sync);
|
||||
}
|
||||
|
||||
bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) {
|
||||
@@ -373,7 +244,6 @@ resolve_confined_path(const std::filesystem::path &root, const std::filesystem::
|
||||
candidate.is_absolute() ? candidate : (canonical_root / candidate);
|
||||
current = current.lexically_normal();
|
||||
|
||||
// Manually walk symlinks with a strict hop budget to detect loops explicitly.
|
||||
constexpr int kMaxSymlinkHops = 40;
|
||||
int hops = 0;
|
||||
std::set<std::filesystem::path> seen;
|
||||
@@ -396,7 +266,6 @@ resolve_confined_path(const std::filesystem::path &root, const std::filesystem::
|
||||
return std::unexpected{meta.error()};
|
||||
}
|
||||
if (!meta->exists) {
|
||||
// Append remaining lexical components for non-existent path checks.
|
||||
++it;
|
||||
for (; it != current.end(); ++it) {
|
||||
acc /= *it;
|
||||
|
||||
+104
-435
@@ -1,31 +1,19 @@
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/System/Process.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <format>
|
||||
#include <poll.h>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
namespace Void::Build::Platform {
|
||||
namespace {
|
||||
|
||||
struct ExecErrorPacket {
|
||||
int err_no{0};
|
||||
int stage{0}; // 1 = chdir, 2 = execve
|
||||
};
|
||||
|
||||
bool is_executable_file(const std::filesystem::path &p) {
|
||||
struct stat st{};
|
||||
if (::stat(p.c_str(), &st) != 0) {
|
||||
@@ -34,106 +22,9 @@ bool is_executable_file(const std::filesystem::path &p) {
|
||||
return S_ISREG(st.st_mode) && ::access(p.c_str(), X_OK) == 0;
|
||||
}
|
||||
|
||||
void set_nonblocking(int fd) noexcept {
|
||||
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags >= 0) {
|
||||
(void)::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> build_env_strings(const ProcessEnvironment &policy) {
|
||||
std::map<std::string, std::string, std::less<>> env_map;
|
||||
if (policy.mode != EnvPolicyMode::ExplicitOnly && environ != nullptr) {
|
||||
for (char **ep = environ; *ep != nullptr; ++ep) {
|
||||
const std::string_view entry{*ep};
|
||||
const auto eq = entry.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
continue;
|
||||
}
|
||||
const auto key = std::string{entry.substr(0, eq)};
|
||||
if (policy.mode == EnvPolicyMode::Allowlist &&
|
||||
!std::ranges::contains(policy.allowlist, key)) {
|
||||
continue;
|
||||
}
|
||||
env_map[key] = std::string{entry.substr(eq + 1)};
|
||||
}
|
||||
}
|
||||
for (const auto &k : policy.unset_keys) {
|
||||
env_map.erase(k);
|
||||
}
|
||||
for (const auto &[k, v] : policy.set_vars) {
|
||||
env_map[k] = v;
|
||||
}
|
||||
std::vector<std::string> result;
|
||||
result.reserve(env_map.size());
|
||||
for (const auto &[k, v] : env_map) {
|
||||
result.push_back(k + "=" + v);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool process_group_alive(pid_t pgid) noexcept {
|
||||
if (pgid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (::kill(-pgid, 0) == 0) {
|
||||
return true;
|
||||
}
|
||||
return errno != ESRCH;
|
||||
}
|
||||
|
||||
void reap_leader(pid_t pid, bool &reaped, int &raw_status, bool blocking) noexcept {
|
||||
if (reaped || pid <= 0) {
|
||||
return;
|
||||
}
|
||||
for (;;) {
|
||||
const pid_t r = ::waitpid(pid, &raw_status, blocking ? 0 : WNOHANG);
|
||||
if (r == pid) {
|
||||
reaped = true;
|
||||
return;
|
||||
}
|
||||
if (r == 0) {
|
||||
return;
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == ECHILD) {
|
||||
reaped = true;
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Terminates the entire process group (-pgid) and waits until every descendant
|
||||
// (even grandchildren whose group leader already exited) is gone.
|
||||
void terminate_process_group(pid_t leader_pid, pid_t pgid, bool &leader_reaped, int &raw_status,
|
||||
std::chrono::milliseconds grace) noexcept {
|
||||
if (pgid <= 0) {
|
||||
return;
|
||||
}
|
||||
const auto effective_grace = grace.count() >= 0 ? grace : std::chrono::milliseconds{200};
|
||||
(void)::kill(-pgid, SIGTERM);
|
||||
|
||||
const auto deadline = std::chrono::steady_clock::now() + effective_grace;
|
||||
while (std::chrono::steady_clock::now() < deadline) {
|
||||
reap_leader(leader_pid, leader_reaped, raw_status, false);
|
||||
if (leader_reaped && !process_group_alive(pgid)) {
|
||||
return;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
|
||||
// Escalate to SIGKILL on the entire process group and verify full disappearance.
|
||||
(void)::kill(-pgid, SIGKILL);
|
||||
reap_leader(leader_pid, leader_reaped, raw_status, true);
|
||||
|
||||
const auto kill_deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5};
|
||||
while (process_group_alive(pgid) && std::chrono::steady_clock::now() < kill_deadline) {
|
||||
(void)::kill(-pgid, SIGKILL);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
void ensure_subreaper() noexcept {
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] { (void)Void::Process::enable_subreaper(); });
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -152,11 +43,13 @@ resolve_executable(const std::filesystem::path &executable,
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string owned_env;
|
||||
std::string_view path_env;
|
||||
if (path_override) {
|
||||
path_env = *path_override;
|
||||
} else if (const char *env_val = std::getenv("PATH")) {
|
||||
path_env = env_val;
|
||||
} else if (auto env_val = Void::Configuration::get_env("PATH"); env_val) {
|
||||
owned_env = std::move(*env_val);
|
||||
path_env = owned_env;
|
||||
}
|
||||
std::size_t start = 0;
|
||||
while (start <= path_env.size()) {
|
||||
@@ -187,343 +80,119 @@ run_supervised(const ProcessRequest &request, std::stop_token stop) {
|
||||
"run_supervised: executable path must not be empty")};
|
||||
}
|
||||
|
||||
auto env_strings = build_env_strings(request.environment);
|
||||
std::optional<std::string_view> child_path;
|
||||
for (const auto &entry : env_strings) {
|
||||
if (entry.starts_with("PATH=")) {
|
||||
child_path = std::string_view{entry}.substr(5);
|
||||
break;
|
||||
}
|
||||
ensure_subreaper();
|
||||
|
||||
// Delegate process spawning, streaming, timeout/cancellation, and robust -pgid
|
||||
// descendant SIGTERM -> SIGKILL supervision directly to Void::Process (VL-001).
|
||||
Void::Process::SpawnOptions opts;
|
||||
opts.executable = request.executable;
|
||||
opts.arguments = request.arguments;
|
||||
opts.working_directory = request.working_directory;
|
||||
opts.search_path = request.search_path;
|
||||
opts.new_process_group = true;
|
||||
opts.kill_grace = request.kill_grace;
|
||||
opts.stdin_pipe = true;
|
||||
opts.stdout_pipe = true;
|
||||
opts.stderr_pipe = true;
|
||||
|
||||
switch (request.environment.mode) {
|
||||
case EnvPolicyMode::Inherit:
|
||||
opts.environment.mode = Void::Process::EnvMode::inherit;
|
||||
break;
|
||||
case EnvPolicyMode::Allowlist:
|
||||
opts.environment.mode = Void::Process::EnvMode::allowlist;
|
||||
break;
|
||||
case EnvPolicyMode::ExplicitOnly:
|
||||
opts.environment.mode = Void::Process::EnvMode::explicit_only;
|
||||
break;
|
||||
}
|
||||
opts.environment.allowlist = request.environment.allowlist;
|
||||
opts.environment.unset_keys = request.environment.unset_keys;
|
||||
for (const auto &[k, v] : request.environment.set_vars) {
|
||||
opts.environment.set_vars.emplace_back(k, v);
|
||||
}
|
||||
|
||||
std::filesystem::path resolved_exec = request.executable;
|
||||
if (request.search_path) {
|
||||
if (auto found = resolve_executable(request.executable, child_path)) {
|
||||
resolved_exec = std::move(*found);
|
||||
}
|
||||
auto child = Void::Process::spawn(opts);
|
||||
if (!child) {
|
||||
ProcessResult fail;
|
||||
fail.exec_failed = true;
|
||||
fail.exec_error_message = child.error().message();
|
||||
return fail;
|
||||
}
|
||||
|
||||
int stdin_pipe[2]{-1, -1};
|
||||
int stdout_pipe[2]{-1, -1};
|
||||
int stderr_pipe[2]{-1, -1};
|
||||
int err_pipe[2]{-1, -1};
|
||||
|
||||
auto close_pair = [](int p[2]) {
|
||||
if (p[0] >= 0) {
|
||||
(void)::close(p[0]);
|
||||
p[0] = -1;
|
||||
}
|
||||
if (p[1] >= 0) {
|
||||
(void)::close(p[1]);
|
||||
p[1] = -1;
|
||||
}
|
||||
};
|
||||
|
||||
if (::pipe2(stdin_pipe, O_CLOEXEC) != 0 || ::pipe2(stdout_pipe, O_CLOEXEC) != 0 ||
|
||||
::pipe2(stderr_pipe, O_CLOEXEC) != 0 || ::pipe2(err_pipe, O_CLOEXEC) != 0) {
|
||||
const int err = errno;
|
||||
close_pair(stdin_pipe);
|
||||
close_pair(stdout_pipe);
|
||||
close_pair(stderr_pipe);
|
||||
close_pair(err_pipe);
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err), "run_supervised: pipe2 failed", err)};
|
||||
}
|
||||
|
||||
std::vector<std::string> argv_storage;
|
||||
argv_storage.reserve(request.arguments.size() + 1);
|
||||
argv_storage.push_back(resolved_exec.string());
|
||||
for (const auto &arg : request.arguments) {
|
||||
argv_storage.push_back(arg);
|
||||
}
|
||||
std::vector<char *> argv_ptrs;
|
||||
argv_ptrs.reserve(argv_storage.size() + 1);
|
||||
for (auto &s : argv_storage) {
|
||||
argv_ptrs.push_back(s.data());
|
||||
}
|
||||
argv_ptrs.push_back(nullptr);
|
||||
|
||||
std::vector<char *> envp_ptrs;
|
||||
envp_ptrs.reserve(env_strings.size() + 1);
|
||||
for (auto &s : env_strings) {
|
||||
envp_ptrs.push_back(s.data());
|
||||
}
|
||||
envp_ptrs.push_back(nullptr);
|
||||
|
||||
const std::string exec_str = resolved_exec.string();
|
||||
const std::string cwd_str =
|
||||
request.working_directory ? request.working_directory->string() : std::string{};
|
||||
|
||||
const pid_t pid = ::fork();
|
||||
if (pid < 0) {
|
||||
const int err = errno;
|
||||
close_pair(stdin_pipe);
|
||||
close_pair(stdout_pipe);
|
||||
close_pair(stderr_pipe);
|
||||
close_pair(err_pipe);
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err), "run_supervised: fork failed", err)};
|
||||
}
|
||||
|
||||
if (pid == 0) {
|
||||
// Child: place into its own process group.
|
||||
(void)::setpgid(0, 0);
|
||||
// Reset signals to defaults.
|
||||
::signal(SIGINT, SIG_DFL);
|
||||
::signal(SIGTERM, SIG_DFL);
|
||||
::signal(SIGPIPE, SIG_DFL);
|
||||
|
||||
(void)::dup2(stdin_pipe[0], STDIN_FILENO);
|
||||
(void)::dup2(stdout_pipe[1], STDOUT_FILENO);
|
||||
(void)::dup2(stderr_pipe[1], STDERR_FILENO);
|
||||
|
||||
close_pair(stdin_pipe);
|
||||
close_pair(stdout_pipe);
|
||||
close_pair(stderr_pipe);
|
||||
(void)::close(err_pipe[0]);
|
||||
|
||||
if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) {
|
||||
ExecErrorPacket pkt{errno, 1};
|
||||
(void)::write(err_pipe[1], &pkt, sizeof(pkt));
|
||||
::_exit(127);
|
||||
}
|
||||
|
||||
::execve(exec_str.c_str(), argv_ptrs.data(), envp_ptrs.data());
|
||||
ExecErrorPacket pkt{errno, 2};
|
||||
(void)::write(err_pipe[1], &pkt, sizeof(pkt));
|
||||
::_exit(127);
|
||||
}
|
||||
|
||||
// Parent: ensure pgid is established to avoid race with child setpgid.
|
||||
(void)::setpgid(pid, pid);
|
||||
const pid_t pgid = pid;
|
||||
|
||||
(void)::close(stdin_pipe[0]);
|
||||
(void)::close(stdout_pipe[1]);
|
||||
(void)::close(stderr_pipe[1]);
|
||||
(void)::close(err_pipe[1]);
|
||||
|
||||
int in_fd = stdin_pipe[1];
|
||||
int out_fd = stdout_pipe[0];
|
||||
int err_fd = stderr_pipe[0];
|
||||
int exec_err_fd = err_pipe[0];
|
||||
|
||||
set_nonblocking(in_fd);
|
||||
set_nonblocking(out_fd);
|
||||
set_nonblocking(err_fd);
|
||||
|
||||
if (request.stdin_data.empty()) {
|
||||
(void)::close(in_fd);
|
||||
in_fd = -1;
|
||||
}
|
||||
|
||||
// Read exec error pipe first (blocking is fine because child closes on exec or writes & exits).
|
||||
ExecErrorPacket exec_pkt{};
|
||||
ssize_t exec_read = 0;
|
||||
while (exec_read < static_cast<ssize_t>(sizeof(exec_pkt))) {
|
||||
const ssize_t n = ::read(exec_err_fd, reinterpret_cast<char *>(&exec_pkt) + exec_read,
|
||||
sizeof(exec_pkt) - static_cast<std::size_t>(exec_read));
|
||||
if (n > 0) {
|
||||
exec_read += n;
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(void)::close(exec_err_fd);
|
||||
|
||||
ProcessResult result;
|
||||
bool leader_reaped = false;
|
||||
int raw_status = 0;
|
||||
|
||||
if (exec_read == static_cast<ssize_t>(sizeof(exec_pkt)) && exec_pkt.err_no != 0) {
|
||||
if (in_fd >= 0) {
|
||||
(void)::close(in_fd);
|
||||
}
|
||||
(void)::close(out_fd);
|
||||
(void)::close(err_fd);
|
||||
reap_leader(pid, leader_reaped, raw_status, true);
|
||||
result.exec_failed = true;
|
||||
result.exec_errno = exec_pkt.err_no;
|
||||
result.exec_error_message =
|
||||
exec_pkt.stage == 1
|
||||
? std::format("chdir('{}') failed: {}", cwd_str, std::strerror(exec_pkt.err_no))
|
||||
: std::format("execve('{}') failed: {}", exec_str, std::strerror(exec_pkt.err_no));
|
||||
return result;
|
||||
}
|
||||
|
||||
std::size_t stdin_offset = 0;
|
||||
const auto start_time = std::chrono::steady_clock::now();
|
||||
const bool has_timeout = request.timeout.count() > 0;
|
||||
const auto deadline = start_time + request.timeout;
|
||||
|
||||
std::array<char, 16384> buf{};
|
||||
Void::Process::CaptureLimits limits;
|
||||
limits.max_stdout_bytes = request.max_stdout_bytes;
|
||||
limits.max_stderr_bytes = request.max_stderr_bytes;
|
||||
limits.max_line_bytes = 0; // Do not reject long compiler/linker diagnostic lines.
|
||||
limits.max_stdin_bytes = std::max(limits.max_stdin_bytes, request.stdin_data.size() + 1);
|
||||
limits.overflow_policy = request.fail_on_overflow
|
||||
? Void::Process::OverflowPolicy::fail_and_terminate
|
||||
: Void::Process::OverflowPolicy::drain_and_truncate;
|
||||
|
||||
while (in_fd >= 0 || out_fd >= 0 || err_fd >= 0) {
|
||||
if (stop.stop_requested()) {
|
||||
result.cancelled = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||
result.timed_out = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
Void::Process::StreamCallbacks callbacks;
|
||||
const Void::Process::StreamCallbacks *cb_ptr = nullptr;
|
||||
if (request.on_stdout_chunk || request.on_stderr_chunk) {
|
||||
callbacks.on_stdout = request.on_stdout_chunk;
|
||||
callbacks.on_stderr = request.on_stderr_chunk;
|
||||
cb_ptr = &callbacks;
|
||||
}
|
||||
|
||||
struct pollfd fds[3];
|
||||
int nfds = 0;
|
||||
int in_idx = -1;
|
||||
int out_idx = -1;
|
||||
int err_idx = -1;
|
||||
if (in_fd >= 0) {
|
||||
in_idx = nfds;
|
||||
fds[nfds++] = {in_fd, POLLOUT, 0};
|
||||
}
|
||||
if (out_fd >= 0) {
|
||||
out_idx = nfds;
|
||||
fds[nfds++] = {out_fd, POLLIN, 0};
|
||||
}
|
||||
if (err_fd >= 0) {
|
||||
err_idx = nfds;
|
||||
fds[nfds++] = {err_fd, POLLIN, 0};
|
||||
}
|
||||
auto comm = Void::Process::communicate_blocking(*child, request.stdin_data, limits,
|
||||
request.timeout, stop, cb_ptr);
|
||||
if (!comm) {
|
||||
(void)child->terminate(request.kill_grace);
|
||||
return std::unexpected{std::move(comm.error())};
|
||||
}
|
||||
|
||||
int poll_ms = 25;
|
||||
if (has_timeout) {
|
||||
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
deadline - std::chrono::steady_clock::now());
|
||||
poll_ms = static_cast<int>(std::clamp<long long>(rem.count(), 1, 25));
|
||||
}
|
||||
|
||||
const int ready = ::poll(fds, static_cast<nfds_t>(nfds), poll_ms);
|
||||
if (ready < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
// If the leader exited cleanly while descendants in its process group are still alive
|
||||
// (e.g. background child with redirected stdio), supervise the process group until it
|
||||
// drains, times out, or is cancelled, then escalate via SIGTERM -> kill_grace -> SIGKILL.
|
||||
bool group_timed_out = comm->timed_out;
|
||||
bool group_cancelled = comm->cancelled;
|
||||
const pid_t pgid = static_cast<pid_t>(child->pgid());
|
||||
if (!group_timed_out && !group_cancelled && !comm->overflowed) {
|
||||
while (child->process_group_alive()) {
|
||||
// Reap any adopted descendants in this process group (subreaper) so zombies clear.
|
||||
int wstatus = 0;
|
||||
while (pgid > 0 && ::waitpid(-pgid, &wstatus, WNOHANG) > 0) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (ready == 0) {
|
||||
reap_leader(pid, leader_reaped, raw_status, false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_idx >= 0 && (fds[in_idx].revents & (POLLOUT | POLLERR | POLLHUP))) {
|
||||
const ssize_t w = ::write(in_fd, request.stdin_data.data() + stdin_offset,
|
||||
request.stdin_data.size() - stdin_offset);
|
||||
if (w > 0) {
|
||||
stdin_offset += static_cast<std::size_t>(w);
|
||||
if (stdin_offset >= request.stdin_data.size()) {
|
||||
(void)::close(in_fd);
|
||||
in_fd = -1;
|
||||
}
|
||||
} else if (w < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
|
||||
(void)::close(in_fd);
|
||||
in_fd = -1;
|
||||
if (!child->process_group_alive()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
auto drain_stream = [&](int &fd, std::string &target, std::size_t limit, bool &truncated,
|
||||
const std::function<void(std::string_view)> &cb) {
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
||||
if (n > 0) {
|
||||
const std::string_view chunk{buf.data(), static_cast<std::size_t>(n)};
|
||||
if (cb) {
|
||||
cb(chunk);
|
||||
}
|
||||
if (target.size() < limit) {
|
||||
const std::size_t take = std::min(chunk.size(), limit - target.size());
|
||||
target.append(chunk.data(), take);
|
||||
if (take < chunk.size()) {
|
||||
truncated = true;
|
||||
}
|
||||
} else {
|
||||
truncated = true;
|
||||
}
|
||||
if (truncated && request.fail_on_overflow) {
|
||||
result.overflowed = true;
|
||||
return;
|
||||
}
|
||||
} else if (n == 0) {
|
||||
(void)::close(fd);
|
||||
fd = -1;
|
||||
return;
|
||||
} else {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
return;
|
||||
}
|
||||
(void)::close(fd);
|
||||
fd = -1;
|
||||
return;
|
||||
}
|
||||
if (stop.stop_requested()) {
|
||||
group_cancelled = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if (out_idx >= 0 && (fds[out_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||
drain_stream(out_fd, result.stdout_data, request.max_stdout_bytes,
|
||||
result.stdout_truncated, request.on_stdout_chunk);
|
||||
}
|
||||
if (err_idx >= 0 && (fds[err_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||
drain_stream(err_fd, result.stderr_data, request.max_stderr_bytes,
|
||||
result.stderr_truncated, request.on_stderr_chunk);
|
||||
}
|
||||
if (result.overflowed) {
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||
group_timed_out = true;
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{10});
|
||||
}
|
||||
}
|
||||
|
||||
if (in_fd >= 0) {
|
||||
(void)::close(in_fd);
|
||||
}
|
||||
if (out_fd >= 0) {
|
||||
(void)::close(out_fd);
|
||||
}
|
||||
if (err_fd >= 0) {
|
||||
(void)::close(err_fd);
|
||||
}
|
||||
|
||||
// Wait for leader AND any remaining process-group descendants, polling for stop/timeout.
|
||||
while (!leader_reaped || process_group_alive(pgid)) {
|
||||
reap_leader(pid, leader_reaped, raw_status, false);
|
||||
if (leader_reaped && !process_group_alive(pgid)) {
|
||||
break;
|
||||
}
|
||||
if (stop.stop_requested()) {
|
||||
result.cancelled = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||
result.timed_out = true;
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
|
||||
// Even if the leader exited cleanly or early, ensure no stray process-group
|
||||
// descendants remain alive if we were cancelled/timed out/overflowed, or wait/clean them up.
|
||||
if (result.cancelled || result.timed_out || result.overflowed) {
|
||||
if (process_group_alive(pgid)) {
|
||||
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||
if (group_cancelled || group_timed_out || comm->overflowed || child->process_group_alive()) {
|
||||
(void)child->terminate(request.kill_grace);
|
||||
int wstatus = 0;
|
||||
while (pgid > 0 && ::waitpid(-pgid, &wstatus, WNOHANG) > 0) {
|
||||
}
|
||||
}
|
||||
|
||||
if (leader_reaped) {
|
||||
if (WIFEXITED(raw_status)) {
|
||||
result.exited = true;
|
||||
result.exit_code = WEXITSTATUS(raw_status);
|
||||
} else if (WIFSIGNALED(raw_status)) {
|
||||
result.exited = false;
|
||||
result.term_signal = WTERMSIG(raw_status);
|
||||
}
|
||||
}
|
||||
ProcessResult result;
|
||||
result.exited = comm->status.exited;
|
||||
result.exit_code = comm->status.code;
|
||||
result.term_signal = comm->status.signal;
|
||||
result.stdout_data = std::move(comm->out);
|
||||
result.stderr_data = std::move(comm->err);
|
||||
result.stdout_truncated = comm->stdout_truncated;
|
||||
result.stderr_truncated = comm->stderr_truncated;
|
||||
result.timed_out = group_timed_out;
|
||||
result.cancelled = group_cancelled;
|
||||
result.overflowed = comm->overflowed;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user