Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
This commit is contained in:
1 parent
3cac890ce9
commit
ab64147f9d
114 files changed
+23777
-1392
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user