#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #include #include #include #if defined(__linux__) && __has_include() #include #endif #include #include #include #include extern char** environ; namespace Void::Process { namespace { struct ChildFailureMsg { int phase{0}; int err{0}; }; [[nodiscard]] bool checked_add_size(std::size_t a, std::size_t b, std::size_t& out) noexcept { if (a > std::numeric_limits::max() - b) { return false; } out = a + b; return true; } [[nodiscard]] std::string sanitize_diag(std::string_view text) { std::string out; out.reserve(std::min(text.size(), 256)); for (char ch : text) { if (out.size() >= 256) { break; } const auto uc = static_cast(ch); if (uc < 0x20 || uc == 0x7f) { out.push_back(' '); } else { out.push_back(ch); } } return out; } [[nodiscard]] bool create_cloexec_pipe(int fds[2]) noexcept { fds[0] = -1; fds[1] = -1; #if defined(__linux__) return ::pipe2(fds, O_CLOEXEC) == 0; #else if (::pipe(fds) != 0) { return false; } for (int i = 0; i < 2; ++i) { const int fl = ::fcntl(fds[i], F_GETFD, 0); if (fl < 0 || ::fcntl(fds[i], F_SETFD, fl | FD_CLOEXEC) != 0) { const int err = errno; (void)::close(fds[0]); (void)::close(fds[1]); fds[0] = -1; fds[1] = -1; errno = err; return false; } } return true; #endif } [[nodiscard]] bool set_nonblock(int fd) noexcept { const int flags = ::fcntl(fd, F_GETFL, 0); if (flags < 0) { return false; } return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0; } [[nodiscard]] ssize_t write_pipe_nosigpipe(int fd, const void* buf, std::size_t len, int& out_errno) noexcept { sigset_t pending{}; ::sigemptyset(&pending); ::sigpending(&pending); const bool was_pending = (::sigismember(&pending, SIGPIPE) == 1); sigset_t block{}; ::sigemptyset(&block); ::sigaddset(&block, SIGPIPE); sigset_t old_mask{}; const int mask_rc = ::pthread_sigmask(SIG_BLOCK, &block, &old_mask); const bool was_blocked = (mask_rc == 0) && (::sigismember(&old_mask, SIGPIPE) == 1); ssize_t n = -1; out_errno = 0; for (;;) { n = ::write(fd, buf, len); if (n < 0) { out_errno = errno; if (out_errno == EINTR) { continue; } } break; } if (n < 0 && out_errno == EPIPE && !was_pending && !was_blocked) { const struct timespec zero_wait{0, 0}; for (;;) { if (::sigtimedwait(&block, nullptr, &zero_wait) >= 0) { break; } if (errno != EINTR) { break; } } } if (mask_rc == 0 && !was_blocked) { (void)::pthread_sigmask(SIG_SETMASK, &old_mask, nullptr); } return n; } [[nodiscard]] bool parse_decimal_fd(const char* name, int& out_fd) noexcept { if (name == nullptr || name[0] == '\0') { return false; } long long v = 0; for (const char* p = name; *p != '\0'; ++p) { if (*p < '0' || *p > '9') { return false; } if (v > (std::numeric_limits::max() - (*p - '0')) / 10) { return false; } v = v * 10 + (*p - '0'); } out_fd = static_cast(v); return true; } #if defined(__linux__) struct LinuxDirent64 { std::uint64_t d_ino; std::int64_t d_off; std::uint16_t d_reclen; std::uint8_t d_type; char d_name[1]; }; #endif // Strictly async-signal-safe close of inherited fds >= 3 except keep_fd (-1 if none). void close_fds_from_except(int keep_fd) noexcept { #if defined(__linux__) && defined(SYS_close_range) if (keep_fd < 3) { if (::syscall(SYS_close_range, 3U, ~0U, 0U) == 0) { return; } } else { const long r1 = (keep_fd == 3) ? 0 : ::syscall(SYS_close_range, 3U, static_cast(keep_fd - 1), 0U); const long r2 = ::syscall(SYS_close_range, static_cast(keep_fd + 1), ~0U, 0U); if (r1 == 0 && r2 == 0) { return; } } #endif #if defined(__linux__) && defined(SYS_getdents64) for (int pass = 0; pass < 32; ++pass) { const int dir_fd = ::open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (dir_fd < 0) { break; } bool closed_any = false; std::array buf{}; for (;;) { const long nread = ::syscall(SYS_getdents64, dir_fd, buf.data(), buf.size()); if (nread <= 0) { break; } std::array to_close{}; std::size_t count = 0; for (long pos = 0; pos < nread;) { const auto* ent = reinterpret_cast(buf.data() + pos); int fd_num = -1; if (parse_decimal_fd(ent->d_name, fd_num) && fd_num >= 3 && fd_num != dir_fd && fd_num != keep_fd) { if (count < to_close.size()) { to_close[count++] = fd_num; } } pos += ent->d_reclen; } for (std::size_t i = 0; i < count; ++i) { (void)::close(to_close[i]); closed_any = true; } } (void)::close(dir_fd); if (!closed_any) { return; } } #endif long max_fd = ::sysconf(_SC_OPEN_MAX); if (max_fd <= 0 || max_fd > 4096) { max_fd = 1024; } for (int fd = 3; fd < static_cast(max_fd); ++fd) { if (fd != keep_fd) { (void)::close(fd); } } } void reset_child_signals() noexcept { sigset_t empty{}; ::sigemptyset(&empty); (void)::pthread_sigmask(SIG_SETMASK, &empty, nullptr); struct sigaction sa{}; sa.sa_handler = SIG_DFL; ::sigemptyset(&sa.sa_mask); sa.sa_flags = 0; const int limit = std::min(NSIG, 32); for (int sig = 1; sig < limit; ++sig) { if (sig == SIGKILL || sig == SIGSTOP) { continue; } (void)::sigaction(sig, &sa, nullptr); } } [[nodiscard]] bool redirect_child_fd(int& src_fd, int target_fd) noexcept { if (src_fd < 0) { return true; } if (src_fd == target_fd) { const int fl = ::fcntl(target_fd, F_GETFD, 0); if (fl < 0) { return false; } if ((fl & FD_CLOEXEC) != 0 && ::fcntl(target_fd, F_SETFD, fl & ~FD_CLOEXEC) != 0) { return false; } return true; } while (::dup2(src_fd, target_fd) < 0) { if (errno == EINTR) { continue; } return false; } (void)::close(src_fd); src_fd = -1; return true; } void write_child_failure(int err_fd, int phase, int err) noexcept { ChildFailureMsg msg{phase, err}; const auto* ptr = reinterpret_cast(&msg); std::size_t off = 0; while (off < sizeof(msg)) { const ssize_t n = ::write(err_fd, ptr + off, sizeof(msg) - off); if (n < 0) { if (errno == EINTR) { continue; } break; } if (n == 0) { break; } off += static_cast(n); } } [[nodiscard]] ExitStatus decode_wait_status(int raw) noexcept { ExitStatus st; st.raw_status = raw; if (WIFEXITED(raw)) { st.exited = true; st.code = WEXITSTATUS(raw); } else if (WIFSIGNALED(raw)) { st.exited = false; st.signal = WTERMSIG(raw); st.code = -1; } return st; } [[nodiscard]] bool is_process_group_alive(pid_t pgid) noexcept { if (pgid <= 0) { return false; } for (;;) { if (::kill(-pgid, 0) == 0) { return true; } if (errno == EINTR) { continue; } return errno == EPERM; } } void reap_group_nonblocking(pid_t pid, pid_t pgid, bool owns_group, bool& reaped, ExitStatus& cached, int& out_errno) noexcept { out_errno = 0; if (!reaped && pid > 0) { int raw = 0; for (;;) { const pid_t w = ::waitpid(pid, &raw, WNOHANG); if (w == pid) { cached = decode_wait_status(raw); reaped = true; break; } if (w == 0) { break; } if (errno == EINTR) { continue; } if (errno == ECHILD) { reaped = true; break; } out_errno = errno; break; } } if (owns_group && pgid > 0) { int raw = 0; for (;;) { const pid_t w = ::waitpid(-pgid, &raw, WNOHANG); if (w > 0) { if (w == pid && !reaped) { cached = decode_wait_status(raw); reaped = true; } continue; } if (w == 0) { break; } if (errno == EINTR) { continue; } break; } } } [[nodiscard]] bool signal_target(pid_t pid, pid_t pgid, bool owns_group, bool leader_reaped, int sig, int& out_errno) noexcept { bool delivered = false; out_errno = 0; if (owns_group && pgid > 0) { if (::kill(-pgid, sig) == 0) { delivered = true; } else { out_errno = errno; if (out_errno != ESRCH && out_errno != EPERM) { return false; } } } if (!leader_reaped && pid > 0) { if (::kill(pid, sig) == 0) { delivered = true; } else { out_errno = errno; } } return delivered; } [[nodiscard]] std::optional find_env_value(const std::vector& env_strings, std::string_view key) { for (const auto& entry : env_strings) { const auto eq = entry.find('='); if (eq == key.size() && std::string_view{entry}.substr(0, eq) == key) { return entry.substr(eq + 1); } } return std::nullopt; } [[nodiscard]] Void::Result::Result, Void::Result::Error> build_environment_strings(const EnvironmentPolicy& policy) { std::vector base; auto validate_key = [](std::string_view k) -> bool { return !k.empty() && k.find('=') == std::string_view::npos && k.find('\0') == std::string_view::npos; }; std::set> unset_set; for (const auto& k : policy.unset_keys) { if (!validate_key(k)) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "SpawnOptions: invalid unset environment variable key")}; } unset_set.insert(k); } std::set> allow_set; if (policy.mode == EnvMode::allowlist) { for (const auto& k : policy.allowlist) { if (!validate_key(k)) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "SpawnOptions: invalid allowlist environment key")}; } allow_set.insert(k); } } std::unordered_map env_map; std::vector key_order; auto put_var = [&](std::string key, std::string val) { if (!env_map.contains(key)) { key_order.push_back(key); } env_map.insert_or_assign(std::move(key), std::move(val)); }; if (policy.mode != EnvMode::explicit_only && environ != nullptr) { for (char** p = environ; *p != nullptr; ++p) { const std::string_view entry{*p}; const auto eq = entry.find('='); if (eq == std::string_view::npos) { continue; } const std::string_view k = entry.substr(0, eq); const std::string_view v = entry.substr(eq + 1); if (unset_set.contains(k)) { continue; } if (policy.mode == EnvMode::allowlist && !allow_set.contains(k)) { continue; } put_var(std::string{k}, std::string{v}); } } for (const auto& [k, v] : policy.set_vars) { if (!validate_key(k) || v.find('\0') != std::string_view::npos) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "SpawnOptions: invalid environment key/value in set_vars")}; } put_var(k, v); } base.reserve(key_order.size()); for (const auto& k : key_order) { const auto it = env_map.find(k); if (it != env_map.end()) { base.push_back(k + "=" + it->second); } } return base; } [[nodiscard]] std::string resolve_executable_path( const std::filesystem::path& exe, bool search_path, const std::vector& env_strings) { const std::string raw = exe.string(); if (!search_path || raw.find('/') != std::string::npos) { return raw; } std::optional path_val = find_env_value(env_strings, "PATH"); if (!path_val.has_value()) { if (const char* host_path = std::getenv("PATH")) { path_val = std::string{host_path}; } } if (!path_val.has_value() || path_val->empty()) { return raw; } std::size_t pos = 0; while (pos <= path_val->size()) { const auto colon = path_val->find(':', pos); const std::string_view dir = (colon == std::string::npos) ? std::string_view{*path_val}.substr(pos) : std::string_view{*path_val}.substr(pos, colon - pos); const std::filesystem::path cand = (dir.empty() ? std::filesystem::path{"."} : std::filesystem::path{dir}) / raw; struct stat st {}; if (::stat(cand.c_str(), &st) == 0 && !S_ISDIR(st.st_mode) && ::access(cand.c_str(), X_OK) == 0) { return cand.string(); } if (colon == std::string::npos) { break; } pos = colon + 1; } return raw; } void emit_lines_from_offset(const std::string& buf, std::size_t& off, const std::function& fn, bool flush) { if (!fn) { off = buf.size(); return; } std::size_t nl = 0; while ((nl = buf.find('\n', off)) != std::string::npos) { std::size_t len = nl - off; if (len > 0 && buf[off + len - 1] == '\r') { --len; } fn(std::string_view{buf.data() + off, len}); off = nl + 1; } if (flush && off < buf.size()) { fn(std::string_view{buf.data() + off, buf.size() - off}); off = buf.size(); } } } // namespace Child::Child() noexcept = default; Child::Child(long long pid, long long pgid, bool owns_process_group, Void::System::OwnedFd stdin_fd, Void::System::OwnedFd stdout_fd, Void::System::OwnedFd stderr_fd, std::chrono::milliseconds kill_grace) noexcept : pid_(pid), pgid_(pgid), owns_group_(owns_process_group), reaped_(pid <= 0), stdin_(std::move(stdin_fd)), stdout_(std::move(stdout_fd)), stderr_(std::move(stderr_fd)), kill_grace_(kill_grace.count() >= 0 ? kill_grace : std::chrono::milliseconds{2000}) { } Child::~Child() noexcept { reset_and_reap(); } Child::Child(Child&& other) noexcept : pid_(std::exchange(other.pid_, -1)), pgid_(std::exchange(other.pgid_, -1)), owns_group_(std::exchange(other.owns_group_, false)), reaped_(std::exchange(other.reaped_, true)), cached_status_(other.cached_status_), stdin_(std::move(other.stdin_)), stdout_(std::move(other.stdout_)), stderr_(std::move(other.stderr_)), kill_grace_(other.kill_grace_) { } Child& Child::operator=(Child&& other) noexcept { if (this != &other) { reset_and_reap(); pid_ = std::exchange(other.pid_, -1); pgid_ = std::exchange(other.pgid_, -1); owns_group_ = std::exchange(other.owns_group_, false); reaped_ = std::exchange(other.reaped_, true); cached_status_ = other.cached_status_; stdin_ = std::move(other.stdin_); stdout_ = std::move(other.stdout_); stderr_ = std::move(other.stderr_); kill_grace_ = other.kill_grace_; } return *this; } bool Child::valid() const noexcept { return pid_ > 0; } bool Child::running() const noexcept { return pid_ > 0 && !reaped_; } bool Child::process_group_alive() const noexcept { if (owns_group_ && pgid_ > 0) { return is_process_group_alive(static_cast(pgid_)); } return running(); } long long Child::pid() const noexcept { return pid_; } long long Child::pgid() const noexcept { return pgid_; } bool Child::owns_process_group() const noexcept { return owns_group_; } int Child::stdin_fd() const noexcept { return stdin_.get(); } int Child::stdout_fd() const noexcept { return stdout_.get(); } int Child::stderr_fd() const noexcept { return stderr_.get(); } Void::System::OwnedFd Child::take_stdin_fd() noexcept { return std::move(stdin_); } Void::System::OwnedFd Child::take_stdout_fd() noexcept { return std::move(stdout_); } Void::System::OwnedFd Child::take_stderr_fd() noexcept { return std::move(stderr_); } void Child::close_stdin() noexcept { stdin_.reset(); } Void::Result::Result Child::send_signal(int sig) noexcept { if (pid_ <= 0) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::Child::send_signal: invalid child")}; } if (reaped_ && (!owns_group_ || !process_group_alive())) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::busy, "Process::Child::send_signal: child already reaped")}; } int err = 0; if (!signal_target(static_cast(pid_), static_cast(pgid_), owns_group_, reaped_, sig, err)) { return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::Child::send_signal failed", err)}; } return {}; } Void::Result::Result, Void::Result::Error> Child::try_wait() { if (pid_ <= 0) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::Child::try_wait: invalid child")}; } if (reaped_) { return std::optional{cached_status_}; } int raw = 0; for (;;) { const pid_t w = ::waitpid(static_cast(pid_), &raw, WNOHANG); if (w == static_cast(pid_)) { cached_status_ = decode_wait_status(raw); reaped_ = true; return std::optional{cached_status_}; } if (w == 0) { return std::optional{std::nullopt}; } if (errno == EINTR) { continue; } const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::Child::try_wait: waitpid failed", err)}; } } Void::Result::Result Child::terminate(std::chrono::milliseconds grace) { if (pid_ <= 0) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::Child::terminate: invalid child")}; } const pid_t target_pid = static_cast(pid_); const pid_t target_pgid = static_cast(pgid_); const bool group_owned = owns_group_ && target_pgid > 0; auto group_finished = [&]() noexcept -> bool { int reap_err = 0; reap_group_nonblocking( target_pid, target_pgid, group_owned, reaped_, cached_status_, reap_err); if (!reaped_) { return false; } return !group_owned || !is_process_group_alive(target_pgid); }; if (group_finished()) { return cached_status_; } const auto effective_grace = (grace.count() >= 0) ? grace : kill_grace_; int sig_err = 0; (void)signal_target( target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err); const auto grace_deadline = std::chrono::steady_clock::now() + effective_grace; while (std::chrono::steady_clock::now() < grace_deadline) { if (group_finished()) { return cached_status_; } const auto rem = std::chrono::duration_cast( grace_deadline - std::chrono::steady_clock::now()); if (rem.count() <= 0) { break; } std::this_thread::sleep_for( std::min(rem, std::chrono::milliseconds{5})); } if (group_finished()) { return cached_status_; } (void)signal_target( target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err); if (!reaped_) { int raw = 0; for (;;) { const pid_t w = ::waitpid(target_pid, &raw, 0); if (w == target_pid) { cached_status_ = decode_wait_status(raw); reaped_ = true; break; } if (errno == EINTR) { continue; } if (errno == ECHILD) { reaped_ = true; break; } const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::Child::terminate: final waitpid failed", err)}; } } if (group_owned) { const auto kill_ceiling = std::chrono::steady_clock::now() + std::chrono::seconds{5}; while (!group_finished()) { if (std::chrono::steady_clock::now() >= kill_ceiling) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::timed_out, "Process::Child::terminate: process group members failed " "to exit after SIGKILL")}; } (void)signal_target(target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err); std::this_thread::sleep_for(std::chrono::milliseconds{1}); } } return cached_status_; } Void::Result::Result Child::wait_blocking( std::chrono::milliseconds timeout, std::stop_token stop, std::chrono::milliseconds kill_grace) { if (pid_ <= 0) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::Child::wait_blocking: invalid child")}; } if (reaped_) { return cached_status_; } const bool has_timeout = timeout.count() > 0; const auto deadline = std::chrono::steady_clock::now() + timeout; if (!has_timeout && !stop.stop_possible()) { int raw = 0; for (;;) { const pid_t w = ::waitpid(static_cast(pid_), &raw, 0); if (w == static_cast(pid_)) { cached_status_ = decode_wait_status(raw); reaped_ = true; return cached_status_; } if (errno == EINTR) { continue; } const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::Child::wait_blocking: waitpid failed", err)}; } } for (;;) { auto polled = try_wait(); if (!polled.has_value()) { return std::unexpected{polled.error()}; } if (polled->has_value()) { return **polled; } if (stop.stop_requested()) { auto term = terminate(kill_grace); if (!term.has_value()) { return std::unexpected{term.error()}; } return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::cancelled, "Process wait cancelled; child terminated")}; } if (has_timeout && std::chrono::steady_clock::now() >= deadline) { auto term = terminate(kill_grace); if (!term.has_value()) { return std::unexpected{term.error()}; } return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::timed_out, "Process timed out; child terminated")}; } auto sleep_dur = std::chrono::milliseconds{10}; if (has_timeout) { const auto rem = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()); if (rem.count() <= 0) { continue; } sleep_dur = std::min(sleep_dur, rem); } std::this_thread::sleep_for(sleep_dur); } } void Child::reset_and_reap() noexcept { stdin_.reset(); stdout_.reset(); stderr_.reset(); if (pid_ > 0 && (!reaped_ || process_group_alive())) { (void)terminate(kill_grace_); } pid_ = -1; pgid_ = -1; owns_group_ = false; reaped_ = true; } Void::Result::Result spawn(const SpawnOptions& options) { if (options.executable.empty()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::spawn: executable path cannot be empty")}; } auto env_res = build_environment_strings(options.environment); if (!env_res.has_value()) { return std::unexpected{std::move(env_res.error())}; } std::vector env_strings = std::move(*env_res); const std::string resolved_exe = resolve_executable_path( options.executable, options.search_path, env_strings); if (resolved_exe.find('\0') != std::string::npos) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::spawn: executable path contains NUL byte")}; } // Check total argv + env bytes against kMaxSpawnInputBytes before fork(). std::size_t total_input_bytes = resolved_exe.size() + 1; for (const auto& arg : options.arguments) { if (arg.find('\0') != std::string::npos) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::spawn: argument contains NUL byte")}; } if (!checked_add_size( total_input_bytes, arg.size() + 1, total_input_bytes)) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::limit_exceeded, "Process::spawn: argument size overflow")}; } } for (const auto& e : env_strings) { if (!checked_add_size( total_input_bytes, e.size() + 1, total_input_bytes)) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::limit_exceeded, "Process::spawn: environment size overflow")}; } } if (total_input_bytes > kMaxSpawnInputBytes) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::limit_exceeded, std::format( "Process::spawn: argv+env payload ({} bytes) exceeds limit ({})", total_input_bytes, kMaxSpawnInputBytes))}; } std::string cwd_str; if (options.working_directory.has_value()) { cwd_str = options.working_directory->string(); if (cwd_str.empty() || cwd_str.find('\0') != std::string::npos) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::spawn: invalid working_directory")}; } } // Prepare contiguous C pointer arrays prior to fork(). std::vector argv_storage; argv_storage.reserve(options.arguments.size() + 1); argv_storage.push_back(options.executable.string()); for (const auto& arg : options.arguments) { argv_storage.push_back(arg); } std::vector argv_ptrs; argv_ptrs.reserve(argv_storage.size() + 1); for (auto& a : argv_storage) { argv_ptrs.push_back(a.data()); } argv_ptrs.push_back(nullptr); std::vector env_ptrs; env_ptrs.reserve(env_strings.size() + 1); for (auto& e : env_strings) { env_ptrs.push_back(e.data()); } env_ptrs.push_back(nullptr); int stdin_p[2]{-1, -1}; int stdout_p[2]{-1, -1}; int stderr_p[2]{-1, -1}; int err_p[2]{-1, -1}; auto close_all_pipes = [&]() noexcept { for (int* pair : {stdin_p, stdout_p, stderr_p, err_p}) { if (pair[0] >= 0) { (void)::close(pair[0]); pair[0] = -1; } if (pair[1] >= 0) { (void)::close(pair[1]); pair[1] = -1; } } }; if ((options.stdin_pipe && !create_cloexec_pipe(stdin_p)) || (options.stdout_pipe && !create_cloexec_pipe(stdout_p)) || (options.stderr_pipe && !create_cloexec_pipe(stderr_p)) || !create_cloexec_pipe(err_p)) { const int err = errno; close_all_pipes(); return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::spawn_failed, "Process::spawn: pipe2 failed", err)}; } const pid_t pid = ::fork(); if (pid < 0) { const int err = errno; close_all_pipes(); return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::spawn_failed, "Process::spawn: fork failed", err)}; } if (pid == 0) { // Strictly async-signal-safe path: no heap allocs, locks, or logging. if (err_p[0] >= 0) { (void)::close(err_p[0]); } if (stdin_p[1] >= 0) { (void)::close(stdin_p[1]); } if (stdout_p[0] >= 0) { (void)::close(stdout_p[0]); } if (stderr_p[0] >= 0) { (void)::close(stderr_p[0]); } int err_write = err_p[1]; if (err_write >= 0 && err_write <= 2) { const int moved = ::fcntl(err_write, F_DUPFD_CLOEXEC, 3); if (moved >= 0) { (void)::close(err_write); err_write = moved; } } if (options.new_process_group && ::setpgid(0, 0) != 0) { const int err = errno; write_child_failure(err_write, 1, err); ::_exit(127); } reset_child_signals(); if (!redirect_child_fd(stdin_p[0], STDIN_FILENO) || !redirect_child_fd(stdout_p[1], STDOUT_FILENO) || !redirect_child_fd(stderr_p[1], STDERR_FILENO)) { const int err = errno; write_child_failure(err_write, 3, err); ::_exit(127); } close_fds_from_except(err_write); if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) { const int err = errno; write_child_failure(err_write, 2, err); ::_exit(127); } ::execve(resolved_exe.c_str(), argv_ptrs.data(), env_ptrs.data()); const int exec_err = errno; write_child_failure(err_write, 4, exec_err); ::_exit(127); } // Parent: close child-side pipe ends immediately. for (int fd : {err_p[1], stdin_p[0], stdout_p[1], stderr_p[1]}) { if (fd >= 0) { (void)::close(fd); } } ChildFailureMsg child_fail{}; auto* fail_bytes = reinterpret_cast(&child_fail); std::size_t fail_got = 0; while (fail_got < sizeof(child_fail)) { const ssize_t n = ::read(err_p[0], fail_bytes + fail_got, sizeof(child_fail) - fail_got); if (n < 0) { if (errno == EINTR) { continue; } break; } if (n == 0) { break; } fail_got += static_cast(n); } (void)::close(err_p[0]); if (fail_got == sizeof(child_fail)) { if (stdin_p[1] >= 0) { (void)::close(stdin_p[1]); } if (stdout_p[0] >= 0) { (void)::close(stdout_p[0]); } if (stderr_p[0] >= 0) { (void)::close(stderr_p[0]); } int raw_status = 0; while (::waitpid(pid, &raw_status, 0) < 0 && errno == EINTR) { } const auto err_code = (child_fail.phase == 4) ? Void::System::SystemErrorCode::exec_failed : Void::System::map_errno_to_system_code( child_fail.err); const char* phase_desc = (child_fail.phase == 4) ? "Process::spawn: exec failed" : (child_fail.phase == 2) ? "Process::spawn: chdir failed" : "Process::spawn: child setup failed"; return std::unexpected{Void::System::make_system_error( err_code, std::format("{} '{}'", phase_desc, sanitize_diag(options.executable.string())), child_fail.err)}; } const long long pgid = options.new_process_group ? pid : ::getpgid(pid); Void::Log::debug("Process", "spawn: '{}' pid={}", options.executable.string(), pid); return Child{ static_cast(pid), pgid, options.new_process_group, Void::System::OwnedFd{stdin_p[1]}, Void::System::OwnedFd{stdout_p[0]}, Void::System::OwnedFd{stderr_p[0]}, options.kill_grace}; } BinarySession::BinarySession(Child child, BinarySessionOptions options) : child_(std::move(child)), stdin_(child_.take_stdin_fd()), stdout_(child_.take_stdout_fd()), stderr_(child_.take_stderr_fd()), stdout_eof_(!stdout_.valid()), stderr_eof_(!stderr_.valid()), stdin_closed_(!stdin_.valid()), options_(options) { options_.max_stdout_buffer = std::max(1, options_.max_stdout_buffer); options_.max_stderr_buffer = std::max(1, options_.max_stderr_buffer); if (stdin_.valid()) { (void)set_nonblock(stdin_.get()); } if (stdout_.valid()) { (void)set_nonblock(stdout_.get()); } if (stderr_.valid()) { (void)set_nonblock(stderr_.get()); } } BinarySession::~BinarySession() noexcept = default; BinarySession::BinarySession(BinarySession&& other) noexcept : child_(std::move(other.child_)), stdin_(std::move(other.stdin_)), stdout_(std::move(other.stdout_)), stderr_(std::move(other.stderr_)), stdout_buffer_(std::move(other.stdout_buffer_)), stdout_offset_(std::exchange(other.stdout_offset_, 0)), stderr_buffer_(std::move(other.stderr_buffer_)), stderr_offset_(std::exchange(other.stderr_offset_, 0)), stdout_eof_(other.stdout_eof_), stderr_eof_(other.stderr_eof_), stdin_closed_(other.stdin_closed_), stdout_truncated_(other.stdout_truncated_), stderr_truncated_(other.stderr_truncated_), options_(other.options_), cancelled_(other.cancelled_.exchange(false)), status_(other.status_), reaped_(other.reaped_) { other.stdout_eof_ = true; other.stderr_eof_ = true; other.stdin_closed_ = true; other.reaped_ = true; } BinarySession& BinarySession::operator=(BinarySession&& other) noexcept { if (this != &other) { child_ = std::move(other.child_); stdin_ = std::move(other.stdin_); stdout_ = std::move(other.stdout_); stderr_ = std::move(other.stderr_); stdout_buffer_ = std::move(other.stdout_buffer_); stdout_offset_ = std::exchange(other.stdout_offset_, 0); stderr_buffer_ = std::move(other.stderr_buffer_); stderr_offset_ = std::exchange(other.stderr_offset_, 0); stdout_eof_ = other.stdout_eof_; stderr_eof_ = other.stderr_eof_; stdin_closed_ = other.stdin_closed_; stdout_truncated_ = other.stdout_truncated_; stderr_truncated_ = other.stderr_truncated_; options_ = other.options_; cancelled_.store(other.cancelled_.exchange(false)); status_ = other.status_; reaped_ = other.reaped_; other.stdout_eof_ = true; other.stderr_eof_ = true; other.stdin_closed_ = true; other.reaped_ = true; } return *this; } Void::Result::Result BinarySession::spawn(const SpawnOptions& options, BinarySessionOptions session_options) { auto spawned = Process::spawn(options); if (!spawned.has_value()) { return std::unexpected{std::move(spawned.error())}; } return BinarySession{std::move(*spawned), session_options}; } bool BinarySession::valid() const noexcept { return child_.valid(); } BinarySession::PollFill BinarySession::poll_fill( int timeout_ms, std::span stdin_data, std::size_t& stdin_written, bool discard_on_full) { PollFill result; std::array pfds{}; nfds_t nfds = 0; int stdin_index = -1; int stdout_index = -1; int stderr_index = -1; if (!stdin_data.empty() && stdin_written < stdin_data.size() && !stdin_closed_ && stdin_.valid()) { stdin_index = static_cast(nfds); pfds[nfds++] = {stdin_.get(), POLLOUT, 0}; } const std::size_t stdout_used = stdout_buffer_.size() - stdout_offset_; if (!stdout_eof_ && stdout_.valid() && (discard_on_full || stdout_used < options_.max_stdout_buffer)) { stdout_index = static_cast(nfds); pfds[nfds++] = {stdout_.get(), POLLIN, 0}; } const std::size_t stderr_used = stderr_buffer_.size() - stderr_offset_; if (!stderr_eof_ && stderr_.valid() && (discard_on_full || stderr_used < options_.max_stderr_buffer)) { stderr_index = static_cast(nfds); pfds[nfds++] = {stderr_.get(), POLLIN, 0}; } if (nfds == 0) { result.idle = true; return result; } const int rc = ::poll(pfds.data(), nfds, timeout_ms); if (rc < 0) { if (errno == EINTR) { return result; } const int err = errno; result.failure = BinaryFailureCode::io_error; result.error = Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::BinarySession: poll failed", err); return result; } if (rc == 0) { return result; } if (stdin_index >= 0) { const short revents = pfds[static_cast(stdin_index)].revents; if ((revents & POLLOUT) != 0) { while (stdin_written < stdin_data.size()) { int write_err = 0; const ssize_t n = write_pipe_nosigpipe(stdin_.get(), stdin_data.data() + stdin_written, stdin_data.size() - stdin_written, write_err); if (n > 0) { stdin_written += static_cast(n); continue; } if (n == 0) { break; } if (n < 0 && (write_err == EAGAIN || write_err == EWOULDBLOCK)) { break; } stdin_closed_ = true; stdin_.reset(); result.stdin_broken = true; break; } } if (!result.stdin_broken && (revents & (POLLERR | POLLHUP | POLLNVAL)) != 0 && (revents & POLLOUT) == 0) { stdin_closed_ = true; stdin_.reset(); result.stdin_broken = true; } } std::array chunk{}; auto service_read = [&](int index, int fd, std::vector& buffer, std::size_t& offset, bool& eof, bool& truncated, std::size_t cap) { if (index < 0) { return; } const short revents = pfds[static_cast(index)].revents; if ((revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)) == 0) { return; } for (;;) { const std::size_t used = buffer.size() - offset; const std::size_t space = (cap > used) ? (cap - used) : 0; if (space == 0 && !discard_on_full) { break; } const std::size_t want = discard_on_full ? chunk.size() : std::min(chunk.size(), space); if (want == 0) { break; } const ssize_t n = ::read(fd, chunk.data(), want); if (n > 0) { if (offset > 0 && offset == buffer.size()) { buffer.clear(); offset = 0; } std::size_t take = static_cast(n); if (take > space) { take = space; truncated = true; } buffer.insert(buffer.end(), chunk.begin(), chunk.begin() + take); continue; } if (n == 0) { eof = true; break; } if (errno == EINTR) { continue; } if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } const int err = errno; eof = true; result.failure = BinaryFailureCode::io_error; result.error = Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::BinarySession: read failed", err); break; } if ((revents & (POLLHUP | POLLERR | POLLNVAL)) != 0 && !eof) { eof = true; } }; service_read(stdout_index, stdout_.get(), stdout_buffer_, stdout_offset_, stdout_eof_, stdout_truncated_, options_.max_stdout_buffer); service_read(stderr_index, stderr_.get(), stderr_buffer_, stderr_offset_, stderr_eof_, stderr_truncated_, options_.max_stderr_buffer); return result; } Void::Result::Result BinarySession::write_stdin( std::span data, std::chrono::milliseconds timeout, std::stop_token stop) { if (!valid()) { return std::unexpected{BinaryError{ 0, false, BinaryFailureCode::closed, Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::BinarySession::write_stdin: invalid session")}}; } BinaryTransfer transfer; if (data.empty()) { return transfer; } if (stdin_closed_ || !stdin_.valid()) { return std::unexpected{BinaryError{ 0, false, BinaryFailureCode::closed, Void::System::make_system_error( Void::System::SystemErrorCode::busy, "Process::BinarySession::write_stdin: stdin is closed")}}; } const bool has_deadline = timeout.count() > 0; const auto deadline = std::chrono::steady_clock::now() + timeout; std::size_t written = 0; while (written < data.size()) { if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) { return std::unexpected{BinaryError{ written, false, BinaryFailureCode::cancelled, Void::System::make_system_error( Void::System::SystemErrorCode::cancelled, "Process::BinarySession::write_stdin: cancelled")}}; } if (has_deadline && std::chrono::steady_clock::now() >= deadline) { return std::unexpected{BinaryError{ written, false, BinaryFailureCode::timeout, Void::System::make_system_error( Void::System::SystemErrorCode::timed_out, "Process::BinarySession::write_stdin: timed out")}}; } int poll_timeout_ms = -1; if (has_deadline) { const auto remaining = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()) .count(); if (remaining <= 0) { continue; } poll_timeout_ms = static_cast(std::min(remaining, std::numeric_limits::max())); } // Bound every wait so cancel() (which may come from another thread) // and a stop request are observed promptly. poll_timeout_ms = (poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25); auto filled = poll_fill(poll_timeout_ms, data, written, false); if (filled.failure != BinaryFailureCode::none) { return std::unexpected{BinaryError{ written, false, filled.failure, std::move(filled.error)}}; } if (filled.stdin_broken) { return std::unexpected{BinaryError{ written, false, BinaryFailureCode::closed, Void::System::make_system_error( Void::System::SystemErrorCode::busy, "Process::BinarySession::write_stdin: child closed stdin")}}; } if (filled.idle) { break; } } transfer.bytes = written; return transfer; } Void::Result::Result BinarySession::read_stdout( std::span out, std::chrono::milliseconds timeout, std::stop_token stop) { return read_stream(true, out, timeout, stop); } Void::Result::Result BinarySession::read_stderr( std::span out, std::chrono::milliseconds timeout, std::stop_token stop) { return read_stream(false, out, timeout, stop); } Void::Result::Result BinarySession::read_stream( bool is_stdout, std::span out, std::chrono::milliseconds timeout, std::stop_token stop) { if (!valid()) { return std::unexpected{BinaryError{ 0, false, BinaryFailureCode::closed, Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::BinarySession: invalid session")}}; } BinaryTransfer transfer; if (out.empty()) { return transfer; } auto& buffer = is_stdout ? stdout_buffer_ : stderr_buffer_; auto& offset = is_stdout ? stdout_offset_ : stderr_offset_; bool& eof = is_stdout ? stdout_eof_ : stderr_eof_; bool& truncated = is_stdout ? stdout_truncated_ : stderr_truncated_; const bool has_deadline = timeout.count() > 0; const auto deadline = std::chrono::steady_clock::now() + timeout; while ((buffer.size() - offset) == 0 && !eof) { if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) { return std::unexpected{BinaryError{ 0, eof, BinaryFailureCode::cancelled, Void::System::make_system_error( Void::System::SystemErrorCode::cancelled, "Process::BinarySession: read cancelled")}}; } if (has_deadline && std::chrono::steady_clock::now() >= deadline) { return std::unexpected{BinaryError{ 0, eof, BinaryFailureCode::timeout, Void::System::make_system_error( Void::System::SystemErrorCode::timed_out, "Process::BinarySession: read timed out")}}; } int poll_timeout_ms = -1; if (has_deadline) { const auto remaining = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()) .count(); if (remaining <= 0) { continue; } poll_timeout_ms = static_cast(std::min(remaining, std::numeric_limits::max())); } // Bound every wait so cancel() (which may come from another thread) // and a stop request are observed promptly. poll_timeout_ms = (poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25); std::span no_stdin{}; std::size_t no_written = 0; auto filled = poll_fill(poll_timeout_ms, no_stdin, no_written, options_.truncate_output_on_overflow); if (filled.failure != BinaryFailureCode::none) { return std::unexpected{BinaryError{ 0, eof, filled.failure, std::move(filled.error)}}; } if (filled.idle) { break; } } const std::size_t used = buffer.size() - offset; if (used > 0) { const std::size_t take = std::min(used, out.size()); std::copy_n(buffer.begin() + static_cast(offset), take, out.begin()); offset += take; transfer.bytes = take; if (offset == buffer.size()) { buffer.clear(); offset = 0; } else if (offset >= 65536 && offset * 2 >= buffer.size()) { buffer.erase(buffer.begin(), buffer.begin() + static_cast(offset)); offset = 0; } } else if (eof) { transfer.eof = true; note_exit(); transfer.exited = reaped_; transfer.status = status_; } transfer.truncated = truncated; return transfer; } void BinarySession::note_exit() noexcept { if (reaped_ || !child_.valid()) { return; } auto waited = child_.try_wait(); if (waited.has_value() && waited->has_value()) { status_ = **waited; reaped_ = true; } } Void::Result::Result BinarySession::close_stdin() { if (stdin_closed_) { return {}; } stdin_closed_ = true; return stdin_.close(); } Void::Result::Result BinarySession::wait( std::chrono::milliseconds timeout, std::stop_token stop) { if (!child_.valid()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::BinarySession::wait: invalid session")}; } if (reaped_) { return status_; } const bool has_deadline = timeout.count() > 0; const auto deadline = std::chrono::steady_clock::now() + timeout; for (;;) { auto waited = child_.try_wait(); if (!waited.has_value()) { return std::unexpected{std::move(waited.error())}; } if (waited->has_value()) { status_ = **waited; reaped_ = true; return status_; } if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::cancelled, "Process::BinarySession::wait: cancelled")}; } if (has_deadline && std::chrono::steady_clock::now() >= deadline) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::timed_out, "Process::BinarySession::wait: timed out")}; } int poll_timeout_ms = 5; if (has_deadline) { const auto remaining = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()) .count(); poll_timeout_ms = static_cast(std::clamp( remaining, 1, static_cast(poll_timeout_ms))); } std::span no_stdin{}; std::size_t no_written = 0; auto filled = poll_fill( poll_timeout_ms, no_stdin, no_written, options_.truncate_output_on_overflow); if (filled.failure != BinaryFailureCode::none) { return std::unexpected{std::move(filled.error)}; } if (filled.idle) { std::this_thread::sleep_for(std::chrono::milliseconds{1}); } } } Void::Result::Result BinarySession::terminate( std::chrono::milliseconds grace) { if (!child_.valid()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::BinarySession::terminate: invalid session")}; } auto terminated = child_.terminate(grace); if (terminated.has_value()) { status_ = *terminated; reaped_ = true; } return terminated; } Void::Result::Result communicate_blocking(Child& child, std::string_view stdin_data, CaptureLimits limits, std::chrono::milliseconds timeout, std::stop_token stop, const StreamCallbacks* callbacks) { if (!child.valid()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::communicate_blocking: invalid child")}; } if (stdin_data.size() > limits.max_stdin_bytes) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::limit_exceeded, std::format( "Process::communicate_blocking: stdin ({} bytes) exceeds limit ({})", stdin_data.size(), limits.max_stdin_bytes))}; } if (child.stdin_fd() >= 0) { if (stdin_data.empty()) { child.close_stdin(); } else { (void)set_nonblock(child.stdin_fd()); } } if (child.stdout_fd() >= 0) { (void)set_nonblock(child.stdout_fd()); } if (child.stderr_fd() >= 0) { (void)set_nonblock(child.stderr_fd()); } CommunicateResult res; std::size_t stdin_offset = 0; bool stdin_done = (child.stdin_fd() < 0) || stdin_data.empty(); bool out_done = (child.stdout_fd() < 0); bool err_done = (child.stderr_fd() < 0); std::size_t out_emitted = 0; std::size_t err_emitted = 0; std::size_t out_cur_line = 0; std::size_t err_cur_line = 0; bool out_line_exceeded = false; bool err_line_exceeded = false; bool fail_line_error = false; bool fail_output_error = false; std::string limit_msg; auto handle_read_chunk = [&](const char* data, std::size_t len, bool is_out) -> bool { std::string& dst = is_out ? res.out : res.err; const std::size_t max_bytes = is_out ? limits.max_stdout_bytes : limits.max_stderr_bytes; bool& truncated = is_out ? res.stdout_truncated : res.stderr_truncated; std::size_t& cur_line = is_out ? out_cur_line : err_cur_line; bool& line_exceeded = is_out ? out_line_exceeded : err_line_exceeded; // Track line length across non-'\n' bytes. if (limits.max_line_bytes > 0) { for (std::size_t i = 0; i < len; ++i) { if (data[i] == '\n') { cur_line = 0; } else { ++cur_line; if (cur_line > limits.max_line_bytes) { line_exceeded = true; res.overflowed = true; truncated = true; if (limits.overflow_policy == OverflowPolicy::fail_and_terminate) { fail_line_error = true; limit_msg = std::format( "Process {} line exceeded max_line_bytes ({})", is_out ? "stdout" : "stderr", limits.max_line_bytes); return false; } } } } } const std::size_t remaining_cap = (dst.size() < max_bytes) ? (max_bytes - dst.size()) : 0; const std::size_t to_store = std::min(len, remaining_cap); if (to_store > 0) { dst.append(data, to_store); } if (to_store < len) { truncated = true; res.overflowed = true; if (limits.overflow_policy == OverflowPolicy::fail_and_terminate) { fail_output_error = true; limit_msg = std::format( "Process {} output exceeded limit ({} bytes)", is_out ? "stdout" : "stderr", max_bytes); return false; } } return true; }; const bool has_timeout = timeout.count() > 0; const auto deadline = std::chrono::steady_clock::now() + timeout; while (!stdin_done || !out_done || !err_done) { if (stop.stop_requested()) { res.cancelled = true; break; } if (has_timeout && std::chrono::steady_clock::now() >= deadline) { res.timed_out = true; break; } std::array pfds{}; nfds_t nfds = 0; if (!stdin_done && child.stdin_fd() >= 0) { pfds[nfds++] = {child.stdin_fd(), POLLOUT, 0}; } if (!out_done && child.stdout_fd() >= 0) { pfds[nfds++] = {child.stdout_fd(), POLLIN, 0}; } if (!err_done && child.stderr_fd() >= 0) { pfds[nfds++] = {child.stderr_fd(), POLLIN, 0}; } if (nfds == 0) { break; } int poll_timeout_ms = -1; if (has_timeout) { const auto rem = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()) .count(); if (rem <= 0) { res.timed_out = true; break; } poll_timeout_ms = static_cast( std::min(rem, std::numeric_limits::max())); } if (stop.stop_possible()) { poll_timeout_ms = (poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25); } const int rc = ::poll(pfds.data(), nfds, poll_timeout_ms); if (rc < 0) { if (errno == EINTR) { continue; } const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::communicate_blocking: poll failed", err)}; } if (rc == 0) { continue; } bool abort_loop = false; for (nfds_t i = 0; i < nfds; ++i) { const short rev = pfds[i].revents; if (rev == 0) { continue; } if (pfds[i].fd == child.stdin_fd()) { if ((rev & (POLLERR | POLLHUP | POLLNVAL)) != 0 && (rev & POLLOUT) == 0) { child.close_stdin(); stdin_done = true; continue; } while (stdin_offset < stdin_data.size()) { const std::size_t rem = stdin_data.size() - stdin_offset; int write_err = 0; const ssize_t n = write_pipe_nosigpipe( child.stdin_fd(), stdin_data.data() + stdin_offset, rem, write_err); if (n > 0) { stdin_offset += static_cast(n); continue; } if (n < 0 && (write_err == EAGAIN || write_err == EWOULDBLOCK)) { break; } child.close_stdin(); stdin_done = true; break; } if (stdin_offset >= stdin_data.size()) { child.close_stdin(); stdin_done = true; } } else { const bool is_out = (pfds[i].fd == child.stdout_fd()); std::array buf{}; bool eof = false; for (;;) { const ssize_t n = ::read(pfds[i].fd, buf.data(), buf.size()); if (n > 0) { if (!handle_read_chunk( buf.data(), static_cast(n), is_out)) { abort_loop = true; break; } if (callbacks != nullptr) { emit_lines_from_offset( is_out ? res.out : res.err, is_out ? out_emitted : err_emitted, is_out ? callbacks->on_stdout : callbacks->on_stderr, false); } } else if (n == 0) { eof = true; break; } else { if (errno == EINTR) { continue; } if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } eof = true; break; } } if (abort_loop) { break; } if (eof || (rev & (POLLHUP | POLLERR | POLLNVAL)) != 0) { if (is_out) { out_done = true; } else { err_done = true; } } } } if (abort_loop) { break; } } if (callbacks != nullptr) { emit_lines_from_offset( res.out, out_emitted, callbacks->on_stdout, true); emit_lines_from_offset( res.err, err_emitted, callbacks->on_stderr, true); } (void)child.take_stdin_fd(); (void)child.take_stdout_fd(); (void)child.take_stderr_fd(); if (fail_line_error || fail_output_error) { (void)child.terminate(); return std::unexpected{Void::System::make_system_error( fail_line_error ? Void::System::SystemErrorCode::line_limit : Void::System::SystemErrorCode::output_limit, limit_msg)}; } if (res.timed_out || res.cancelled) { auto term = child.terminate(); if (!term.has_value()) { return std::unexpected{term.error()}; } res.status = *term; return res; } auto waited = child.wait_blocking( has_timeout ? std::max(std::chrono::milliseconds{1}, std::chrono::duration_cast( deadline - std::chrono::steady_clock::now())) : std::chrono::milliseconds{0}, stop); if (!waited.has_value()) { if (waited.error().kind() == Void::Result::ErrorKind::timeout) { res.timed_out = true; if (auto st = child.try_wait(); st.has_value() && st->has_value()) { res.status = **st; } return res; } if (waited.error().kind() == Void::Result::ErrorKind::cancelled) { res.cancelled = true; if (auto st = child.try_wait(); st.has_value() && st->has_value()) { res.status = **st; } return res; } return std::unexpected{waited.error()}; } res.status = *waited; return res; } namespace { Void::Result::Result run_legacy_impl(const std::filesystem::path& executable, std::vector args, std::string_view stdin_data, std::chrono::milliseconds timeout, const StreamCallbacks* cb) { SpawnOptions opts; opts.executable = executable; opts.arguments = std::move(args); opts.search_path = true; opts.new_process_group = true; auto spawned = spawn(opts); if (!spawned.has_value()) { // Preserve legacy 1.x behavior where exec failure returns exit_code 127. if (spawned.error().code().domain == Void::Result::kSystemErrorDomain && spawned.error().code().value == static_cast( Void::System::SystemErrorCode::exec_failed)) { Output out; out.exit_code = 127; return out; } return std::unexpected{std::move(spawned.error())}; } CaptureLimits limits; limits.max_stdout_bytes = 64ULL * 1024ULL * 1024ULL; limits.max_stderr_bytes = 64ULL * 1024ULL * 1024ULL; limits.max_line_bytes = 0; // Do not fail legacy unbounded line reads limits.max_stdin_bytes = 64ULL * 1024ULL * 1024ULL; limits.overflow_policy = OverflowPolicy::drain_and_truncate; auto comm = communicate_blocking( *spawned, stdin_data, limits, timeout, {}, cb); if (!comm.has_value()) { return std::unexpected{std::move(comm.error())}; } Output out; out.exit_code = comm->status.exited ? comm->status.code : -1; out.out = std::move(comm->out); out.err = std::move(comm->err); return out; } } // namespace Void::Result::Result run(const std::filesystem::path& executable, std::vector args, std::string_view stdin_data, std::chrono::milliseconds timeout) { return run_legacy_impl( executable, std::move(args), stdin_data, timeout, nullptr); } Void::Result::Result run_streaming( const std::filesystem::path& executable, std::vector args, const StreamCallbacks& callbacks, std::string_view stdin_data, std::chrono::milliseconds timeout) { return run_legacy_impl( executable, std::move(args), stdin_data, timeout, &callbacks); } Void::Result::Result shell(std::string_view command, std::chrono::milliseconds timeout) { return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); } Void::Result::Result reexec(const std::filesystem::path& executable, const std::vector& arguments) { return reexec(executable, arguments, false); } Void::Result::Result reexec(const std::filesystem::path& executable, const std::vector& arguments, bool close_extra_fds) { if (executable.empty()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "Process::reexec: executable is empty")}; } std::vector owned; owned.reserve(arguments.size() + 1); owned.push_back(executable.string()); owned.insert(owned.end(), arguments.begin(), arguments.end()); std::vector argv; argv.reserve(owned.size() + 1); for (auto& argument : owned) { argv.push_back(argument.data()); } argv.push_back(nullptr); if (close_extra_fds) { close_fds_from_except(-1); } ::execv(executable.c_str(), argv.data()); const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::exec_failed, std::format("Process::reexec: execv '{}' failed", executable.string()), err)}; } Void::Result::Result enable_subreaper() noexcept { #if defined(__linux__) && defined(PR_SET_CHILD_SUBREAPER) if (::prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0) { const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "Process::enable_subreaper: prctl(PR_SET_CHILD_SUBREAPER) failed", err)}; } return {}; #else return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::enable_subreaper: PR_SET_CHILD_SUBREAPER unavailable on this platform")}; #endif } } // namespace Void::Process #endif // !_WIN32