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

This commit is contained in:
faumaray committed 2026-11-27 01:43:06 +03:00
1 parent ab64147f9d
commit 363fb8200e
33 files changed
+1754 -3155

No files matched your search

+104 -435
View File
@@ -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;
}