#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 namespace Void::Process { Child::Child(long long, long long, bool, Void::System::OwnedFd, Void::System::OwnedFd, Void::System::OwnedFd, std::chrono::milliseconds) noexcept { } Child::~Child() noexcept = default; Child::Child(Child&&) noexcept = default; Child& Child::operator=(Child&&) noexcept = default; bool Child::valid() const noexcept { return false; } bool Child::running() const noexcept { return false; } long long Child::pid() const noexcept { return -1; } long long Child::pgid() const noexcept { return -1; } bool Child::owns_process_group() const noexcept { return false; } int Child::stdin_fd() const noexcept { return -1; } int Child::stdout_fd() const noexcept { return -1; } int Child::stderr_fd() const noexcept { return -1; } Void::System::OwnedFd Child::take_stdin_fd() noexcept { return {}; } Void::System::OwnedFd Child::take_stdout_fd() noexcept { return {}; } Void::System::OwnedFd Child::take_stderr_fd() noexcept { return {}; } void Child::close_stdin() noexcept {} Void::Result::Result Child::send_signal(int) noexcept { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::Child::send_signal: not implemented on Windows")}; } Void::Result::Result Child::terminate(std::chrono::milliseconds) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::Child::terminate: not implemented on Windows")}; } Void::Result::Result, Void::Result::Error> Child::try_wait() { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::Child::try_wait: not implemented on Windows")}; } Void::Result::Result Child::wait_blocking(std::chrono::milliseconds, std::stop_token, std::chrono::milliseconds) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::Child::wait_blocking: not implemented on Windows")}; } Void::Result::Result spawn(const SpawnOptions&) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::spawn: not implemented on Windows")}; } Void::Result::Result communicate_blocking(Child&, std::string_view, CaptureLimits, std::chrono::milliseconds, std::stop_token, const StreamCallbacks*) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "Process::communicate_blocking: not implemented on Windows")}; } Void::Result::Result run( const std::filesystem::path&, std::vector, std::string_view, std::chrono::milliseconds) { return Void::Result::fail("Process::run: not implemented on Windows"); } Void::Result::Result run_streaming( const std::filesystem::path&, std::vector, const StreamCallbacks&, std::string_view, std::chrono::milliseconds) { return Void::Result::fail( "Process::run_streaming: not implemented on Windows"); } Void::Result::Result shell(std::string_view, std::chrono::milliseconds) { return Void::Result::fail("Process::shell: not implemented on Windows"); } Void::Result::Result reexec(const std::filesystem::path&, const std::vector&) { return Void::Result::fail("Process::reexec: not implemented on Windows"); } Void::Result::Result reexec( const std::filesystem::path&, const std::vector&, bool) { return Void::Result::fail("Process::reexec: not implemented on Windows"); } } // namespace Void::Process #else // POSIX #include #include #include #include #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 signal_target(pid_t pid, pid_t pgid, bool owns_group, int sig, int& out_errno) noexcept { if (owns_group && pgid > 0) { if (::kill(-pgid, sig) == 0) { return true; } out_errno = errno; if (out_errno != ESRCH && out_errno != EPERM) { return false; } } if (::kill(pid, sig) == 0) { return true; } out_errno = errno; return false; } [[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(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_; } 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_) { 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_, 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")}; } if (reaped_) { return cached_status_; } const auto effective_grace = (grace.count() >= 0) ? grace : kill_grace_; if (auto polled = try_wait(); !polled.has_value()) { return std::unexpected{polled.error()}; } else if (polled->has_value()) { return **polled; } int sig_err = 0; (void)signal_target(static_cast(pid_), static_cast(pgid_), owns_group_, SIGTERM, sig_err); const auto grace_deadline = std::chrono::steady_clock::now() + effective_grace; while (std::chrono::steady_clock::now() < grace_deadline) { auto polled = try_wait(); if (!polled.has_value()) { return std::unexpected{polled.error()}; } if (polled->has_value()) { return **polled; } 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{10})); } if (auto polled = try_wait(); !polled.has_value()) { return std::unexpected{polled.error()}; } else if (polled->has_value()) { return **polled; } (void)signal_target(static_cast(pid_), static_cast(pgid_), owns_group_, SIGKILL, sig_err); 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::terminate: final waitpid failed", err)}; } } 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_) { (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}; } 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)}; } } // namespace Void::Process #endif // _WIN32