#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 #include #endif namespace Void::Process { #ifdef _WIN32 namespace Detail { /// Opaque owner of the native Windows process, job and pipe state. Defined by /// the System module implementation; it is never an integer descriptor. struct WindowsProcess; struct ChildAccess; } // namespace Detail #endif inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL; inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL; inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL; inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL; inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL; /// Captured output from a completed subprocess. struct Output { int exit_code{0}; std::string out; ///< captured stdout std::string err; ///< captured stderr }; /// Live line callbacks for run_streaming() and communicate_blocking(). struct StreamCallbacks { std::function on_stdout; std::function on_stderr; }; enum class OverflowPolicy { fail_and_terminate, drain_and_truncate, }; enum class EnvMode { inherit, allowlist, explicit_only, }; struct EnvironmentPolicy { EnvMode mode{EnvMode::inherit}; std::vector allowlist{}; std::vector> set_vars{}; std::vector unset_keys{}; std::vector redacted_keys{}; }; struct CaptureLimits { std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes}; std::size_t max_stderr_bytes{kDefaultMaxStderrBytes}; std::size_t max_line_bytes{kDefaultMaxLineBytes}; std::size_t max_stdin_bytes{kDefaultMaxStdinBytes}; OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate}; }; struct SpawnOptions { std::filesystem::path executable{}; std::vector arguments{}; std::optional working_directory{}; EnvironmentPolicy environment{}; bool stdin_pipe{true}; bool stdout_pipe{true}; bool stderr_pipe{true}; bool search_path{true}; bool new_process_group{true}; std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}}; }; struct ExitStatus { bool exited{false}; int code{-1}; int signal{0}; int raw_status{0}; }; struct CommunicateResult { ExitStatus status{}; std::string out{}; std::string err{}; bool stdout_truncated{false}; bool stderr_truncated{false}; bool timed_out{false}; bool cancelled{false}; bool overflowed{false}; }; class Child { public: Child() noexcept; 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; ~Child() noexcept; Child(const Child&) = delete; Child& operator=(const Child&) = delete; Child(Child&& other) noexcept; Child& operator=(Child&& other) noexcept; [[nodiscard]] bool valid() const noexcept; [[nodiscard]] bool running() const noexcept; [[nodiscard]] bool process_group_alive() const noexcept; [[nodiscard]] long long pid() const noexcept; [[nodiscard]] long long pgid() const noexcept; [[nodiscard]] bool owns_process_group() const noexcept; [[nodiscard]] int stdin_fd() const noexcept; [[nodiscard]] int stdout_fd() const noexcept; [[nodiscard]] int stderr_fd() const noexcept; [[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept; [[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept; [[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept; void close_stdin() noexcept; [[nodiscard]] Void::Result::Result send_signal(int sig) noexcept; [[nodiscard]] Void::Result::Result terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1}); [[nodiscard]] Void::Result::Result, Void::Result::Error> try_wait(); [[nodiscard]] Void::Result::Result wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, std::stop_token stop = {}, std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1}); private: long long pid_{-1}; long long pgid_{-1}; bool owns_group_{false}; bool reaped_{true}; ExitStatus cached_status_{}; Void::System::OwnedFd stdin_{}; Void::System::OwnedFd stdout_{}; Void::System::OwnedFd stderr_{}; std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}}; #ifdef _WIN32 std::unique_ptr windows_; friend struct Detail::ChildAccess; friend class BinarySession; #endif void reset_and_reap() noexcept; }; [[nodiscard]] Void::Result::Result spawn(const SpawnOptions& options); inline constexpr std::size_t kDefaultBinaryOutputBufferBytes = 1024ULL * 1024ULL; /// Why a BinarySession operation stopped before completing. enum class BinaryFailureCode : std::int32_t { none = 0, timeout = 1, cancelled = 2, truncated = 3, closed = 4, buffer_full = 5, io_error = 6, }; /// Successful (possibly partial) BinarySession operation. struct BinaryTransfer { std::size_t bytes{0}; bool eof{false}; ///< the stream reached end-of-file bool exited{false}; ///< the child exit status is known (see status) bool truncated{false}; ///< output was discarded because a buffer was full ExitStatus status{}; }; /// Structured BinarySession failure. `bytes_transferred` lets callers resume /// from the exact offset that was not transferred. struct BinaryError { std::size_t bytes_transferred{0}; bool eof{false}; BinaryFailureCode failure{BinaryFailureCode::io_error}; Void::Result::Error error{}; }; struct BinarySessionOptions { std::size_t max_stdout_buffer{kDefaultBinaryOutputBufferBytes}; std::size_t max_stderr_buffer{kDefaultBinaryOutputBufferBytes}; /// When true, output beyond a buffer cap is drained and discarded (marked /// truncated) instead of applying backpressure to the child. bool truncate_output_on_overflow{false}; }; /// Incremental binary I/O session over a spawned child's pipes. /// /// Each call drives both output directions: while stdout is being read, /// stderr is drained into its bounded buffer (and vice versa), so a child /// flooding one stream cannot block the other as long as buffering allows. /// Pipes are non-blocking; operations are poll-driven and bounded by an /// optional timeout and a stop token (or cancel()). class BinarySession { public: BinarySession() noexcept = default; explicit BinarySession(Child child, BinarySessionOptions options = {}); ~BinarySession() noexcept; BinarySession(const BinarySession&) = delete; BinarySession& operator=(const BinarySession&) = delete; BinarySession(BinarySession&& other) noexcept; BinarySession& operator=(BinarySession&& other) noexcept; [[nodiscard]] static Void::Result::Result spawn(const SpawnOptions& options, BinarySessionOptions session_options = {}); [[nodiscard]] bool valid() const noexcept; [[nodiscard]] Child& child() noexcept { return child_; } [[nodiscard]] const Child& child() const noexcept { return child_; } [[nodiscard]] long long pid() const noexcept { return child_.pid(); } /// Writes as much of `data` as the child accepts. Returns the transferred /// count; on timeout/cancellation/closure the BinaryError reports it. [[nodiscard]] Void::Result::Result write_stdin( std::span data, std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, std::stop_token stop = {}); [[nodiscard]] Void::Result::Result read_stdout( std::span out, std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, std::stop_token stop = {}); [[nodiscard]] Void::Result::Result read_stderr( std::span out, std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, std::stop_token stop = {}); /// Closes the child's stdin (flush-free half-close). Idempotent. [[nodiscard]] Void::Result::Result close_stdin(); /// Waits for the child while continuing to drain both output streams. [[nodiscard]] Void::Result::Result wait( std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, std::stop_token stop = {}); /// Terminates the child (and its process group) with the configured grace. [[nodiscard]] Void::Result::Result terminate( std::chrono::milliseconds grace = std::chrono::milliseconds{-1}); /// Requests cancellation of the next/current operation. Safe to call from /// another thread. void cancel() noexcept { cancelled_.store(true, std::memory_order_release); } [[nodiscard]] bool cancelled() const noexcept { return cancelled_.load(std::memory_order_acquire); } [[nodiscard]] bool stdout_eof() const noexcept { return stdout_eof_; } [[nodiscard]] bool stderr_eof() const noexcept { return stderr_eof_; } [[nodiscard]] bool stdout_truncated() const noexcept { return stdout_truncated_; } [[nodiscard]] bool stderr_truncated() const noexcept { return stderr_truncated_; } [[nodiscard]] std::size_t buffered_stdout() const noexcept { return stdout_buffer_.size() - stdout_offset_; } [[nodiscard]] std::size_t buffered_stderr() const noexcept { return stderr_buffer_.size() - stderr_offset_; } private: struct PollFill { bool stdin_broken{false}; bool idle{false}; BinaryFailureCode failure{BinaryFailureCode::none}; Void::Result::Error error{}; }; [[nodiscard]] PollFill poll_fill(int timeout_ms, std::span stdin_data, std::size_t& stdin_written, bool discard_on_full); [[nodiscard]] Void::Result::Result read_stream( bool is_stdout, std::span out, std::chrono::milliseconds timeout, std::stop_token stop); void note_exit() noexcept; Child child_{}; Void::System::OwnedFd stdin_{}; Void::System::OwnedFd stdout_{}; Void::System::OwnedFd stderr_{}; std::vector stdout_buffer_{}; std::size_t stdout_offset_{0}; std::vector stderr_buffer_{}; std::size_t stderr_offset_{0}; bool stdout_eof_{true}; bool stderr_eof_{true}; bool stdin_closed_{true}; bool stdout_truncated_{false}; bool stderr_truncated_{false}; BinarySessionOptions options_{}; std::atomic cancelled_{false}; ExitStatus status_{}; bool reaped_{false}; }; [[nodiscard]] Void::Result::Result communicate_blocking(Child& child, std::string_view stdin_data = {}, CaptureLimits limits = {}, std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, std::stop_token stop = {}, const StreamCallbacks* callbacks = nullptr); /// Run an executable synchronously, capturing stdout and stderr separately. [[nodiscard]] Void::Result::Result run(const std::filesystem::path& executable, std::vector args = {}, std::string_view stdin_data = {}, std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); /// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive. [[nodiscard]] 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 = std::chrono::milliseconds{0}); /// Run a command through /bin/sh -c "command". [[nodiscard]] Void::Result::Result shell(std::string_view command, std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); /// Replace the current process image while preserving its PID and inherited /// environment. [[nodiscard]] Void::Result::Result reexec(const std::filesystem::path& executable, const std::vector& arguments); /// Replace the current process image with explicit open-descriptor cleanup policy. [[nodiscard]] Void::Result::Result reexec(const std::filesystem::path& executable, const std::vector& arguments, bool close_extra_fds); /// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned /// descendant processes in spawned process groups reparent to this process /// and can be reaped directly via waitpid(-pgid, ...). [[nodiscard]] Void::Result::Result enable_subreaper() noexcept; } // namespace Void::Process