Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s

This commit is contained in:
faumaray committed 2026-11-26 20:45:54 +03:00
1 parent 3cac890ce9
commit ab64147f9d
114 files changed
+23777 -1392

No files matched your search

+444
View File
@@ -0,0 +1,444 @@
#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>
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);
}
} // 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;
if (lock_path.has_parent_path()) {
std::filesystem::create_directories(lock_path.parent_path(), ec);
if (ec) {
return std::unexpected{
sys_err(ec.value(), std::format("FileLock: failed creating parent for '{}': {}",
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;
if (non_blocking) {
op |= LOCK_NB;
}
for (;;) {
if (::flock(fd, op) == 0) {
return FileLock{fd};
}
if (errno == EINTR) {
continue;
}
const int err = errno;
(void)::close(fd);
return std::unexpected{
sys_err(err, std::format("FileLock: flock failed for '{}'", lock_path.string()))};
}
}
Void::Result::Result<FileMetadata, Void::Result::Error>
stat_lstat(const std::filesystem::path &path) {
struct stat st{};
if (::lstat(path.c_str(), &st) != 0) {
const int err = errno;
if (err == ENOENT || err == ENOTDIR) {
FileMetadata missing;
missing.exists = false;
return missing;
}
return std::unexpected{
sys_err(err, std::format("stat_lstat: lstat failed for '{}'", path.string()))};
}
FileMetadata meta;
meta.exists = true;
meta.is_regular = S_ISREG(st.st_mode);
meta.is_directory = S_ISDIR(st.st_mode);
meta.is_symlink = S_ISLNK(st.st_mode);
meta.dev = static_cast<std::uint64_t>(st.st_dev);
meta.ino = static_cast<std::uint64_t>(st.st_ino);
meta.size = static_cast<std::uint64_t>(st.st_size);
meta.nlink = static_cast<std::uint64_t>(st.st_nlink);
meta.mode = static_cast<std::uint32_t>(st.st_mode & 07777u);
meta.mtime_sec = static_cast<std::int64_t>(st.st_mtim.tv_sec);
meta.mtime_nsec = static_cast<std::int64_t>(st.st_mtim.tv_nsec);
if (meta.is_symlink) {
std::size_t buf_size =
st.st_size > 0 ? static_cast<std::size_t>(st.st_size) + 1 : std::size_t{256};
for (int attempt = 0; attempt < 8; ++attempt) {
std::string target(buf_size, '\0');
const ssize_t n = ::readlink(path.c_str(), target.data(), target.size());
if (n < 0) {
const int err = errno;
return std::unexpected{sys_err(
err, std::format("stat_lstat: readlink failed for '{}'", path.string()))};
}
if (static_cast<std::size_t>(n) < target.size()) {
target.resize(static_cast<std::size_t>(n));
meta.symlink_target = std::move(target);
break;
}
buf_size *= 2;
}
}
return meta;
}
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);
if (ec) {
return std::unexpected{sys_err(
ec.value(), std::format("copy_isolated: cannot create parent dir for '{}': {}",
dst.string(), ec.message()))};
}
}
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()))};
}
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;
}
#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;
}
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 {};
}
Void::Result::Result<void, Void::Result::Error>
atomic_write_bytes(const std::filesystem::path &path, std::span<const std::byte> bytes,
bool durable_sync, unsigned mode) {
std::error_code ec;
if (path.has_parent_path()) {
std::filesystem::create_directories(path.parent_path(), ec);
if (ec) {
return std::unexpected{sys_err(
ec.value(), std::format("atomic_write_bytes: create_directories failed for '{}'",
path.string()))};
}
}
Void::FileSystem::ReplaceOptions opts;
opts.durability = durable_sync ? Void::FileSystem::ReplaceDurability::durable_sync
: Void::FileSystem::ReplaceDurability::atomic_visibility;
opts.mode = mode;
auto res = Void::FileSystem::replace_file(path, bytes, opts);
if (!res) {
return std::unexpected{std::move(res.error().error)};
}
return {};
}
Void::Result::Result<void, Void::Result::Error> atomic_write_file(const std::filesystem::path &path,
std::string_view content,
bool durable_sync,
unsigned mode) {
return atomic_write_bytes(path,
std::as_bytes(std::span<const char>{content.data(), content.size()}),
durable_sync, mode);
}
Void::Result::Result<void, Void::Result::Error>
fsync_directory(const std::filesystem::path &dir_path) {
const int fd = ::open(dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
return std::unexpected{
sys_err(err, std::format("fsync_directory: open failed for '{}'", dir_path.string()))};
}
Void::System::OwnedFd guard{fd};
for (;;) {
if (::fsync(fd) == 0) {
return {};
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EINVAL || err == EROFS) {
return {};
}
return std::unexpected{
sys_err(err, std::format("fsync_directory: fsync failed for '{}'", dir_path.string()))};
}
}
Void::Result::Result<void, Void::Result::Error>
atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target) {
std::error_code ec;
const auto parent =
link_path.has_parent_path() ? link_path.parent_path() : std::filesystem::path{"."};
std::filesystem::create_directories(parent, ec);
if (ec) {
return std::unexpected{sys_err(
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);
}
bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) {
const auto norm_root = root.lexically_normal();
const auto norm_path = path.lexically_normal();
auto r_it = norm_root.begin();
auto p_it = norm_path.begin();
for (; r_it != norm_root.end(); ++r_it, ++p_it) {
if (r_it->empty() || *r_it == ".") {
continue;
}
if (p_it == norm_path.end() || *r_it != *p_it) {
return false;
}
}
return true;
}
Void::Result::Result<std::filesystem::path, Void::Result::Error>
resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate,
const std::vector<std::filesystem::path> &allowed_external_roots) {
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(root, ec);
if (ec) {
return std::unexpected{
sys_err(ec.value(), std::format("resolve_confined_path: cannot canonicalize root '{}'",
root.string()))};
}
std::vector<std::filesystem::path> allowed{canonical_root};
for (const auto &ext : allowed_external_roots) {
const auto ce = std::filesystem::weakly_canonical(ext, ec);
if (!ec) {
allowed.push_back(ce);
}
}
std::filesystem::path current =
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;
for (;;) {
std::filesystem::path acc;
bool followed_symlink = false;
auto it = current.begin();
for (; it != current.end(); ++it) {
if (*it == ".") {
continue;
}
if (*it == "..") {
acc = acc.parent_path();
continue;
}
acc /= *it;
auto meta = stat_lstat(acc);
if (!meta) {
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;
}
current = acc.lexically_normal();
break;
}
if (meta->is_symlink) {
if (++hops > kMaxSymlinkHops || !seen.insert(acc).second) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("resolve_confined_path: symlink loop detected at '{}'",
acc.string()),
ELOOP)};
}
std::filesystem::path target_path{meta->symlink_target};
std::filesystem::path rebuilt =
target_path.is_absolute() ? target_path : (acc.parent_path() / target_path);
++it;
for (; it != current.end(); ++it) {
rebuilt /= *it;
}
current = rebuilt.lexically_normal();
followed_symlink = true;
break;
}
}
if (!followed_symlink) {
break;
}
}
for (const auto &allowed_root : allowed) {
if (path_is_within(allowed_root, current)) {
return current;
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::permission_denied,
std::format("resolve_confined_path: '{}' escapes declared roots (root='{}')",
candidate.string(), canonical_root.string()),
EACCES)};
}
} // namespace Void::Build::Platform
+530
View File
@@ -0,0 +1,530 @@
#include <Void/Build/Platform/ProcessSupervisor.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 <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) {
return false;
}
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});
}
}
} // namespace
std::optional<std::filesystem::path>
resolve_executable(const std::filesystem::path &executable,
std::optional<std::string_view> path_override) {
if (executable.empty()) {
return std::nullopt;
}
if (executable.is_absolute() || executable.string().find('/') != std::string::npos) {
std::error_code ec;
const auto abs = std::filesystem::absolute(executable, ec);
if (!ec && is_executable_file(abs)) {
return abs.lexically_normal();
}
return std::nullopt;
}
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;
}
std::size_t start = 0;
while (start <= path_env.size()) {
const auto colon = path_env.find(':', start);
const auto segment = path_env.substr(
start, colon == std::string_view::npos ? std::string_view::npos : colon - start);
const std::filesystem::path dir =
segment.empty() ? std::filesystem::path{"."} : std::filesystem::path{segment};
const auto candidate = dir / executable;
if (is_executable_file(candidate)) {
std::error_code ec;
auto abs = std::filesystem::absolute(candidate, ec);
return ec ? candidate : abs.lexically_normal();
}
if (colon == std::string_view::npos) {
break;
}
start = colon + 1;
}
return std::nullopt;
}
Void::Result::Result<ProcessResult, Void::Result::Error>
run_supervised(const ProcessRequest &request, std::stop_token stop) {
if (request.executable.empty()) {
return std::unexpected{
Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
"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;
}
}
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);
}
}
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{};
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;
}
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};
}
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;
}
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;
}
}
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 (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 (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 (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);
}
}
return result;
}
} // namespace Void::Build::Platform