From 540c3d91174062446ffdbc6a2f8b313718ac569c Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Thu, 3 Dec 2026 15:50:28 +0300 Subject: [PATCH] System: add binary subprocess session (#44) --- include/Void/System/Process.hpp | 156 +++++ src/System/Process.cpp | 728 ++++++++++++++++++++++ tests/helpers/ProcessHelper.cpp | 28 + tests/standalone/System/BinarySession.cpp | 310 +++++++++ 4 files changed, 1222 insertions(+) create mode 100644 tests/standalone/System/BinarySession.cpp diff --git a/include/Void/System/Process.hpp b/include/Void/System/Process.hpp index 275f8d5..36439c9 100644 --- a/include/Void/System/Process.hpp +++ b/include/Void/System/Process.hpp @@ -4,11 +4,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -161,6 +163,160 @@ private: [[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 = {}, diff --git a/src/System/Process.cpp b/src/System/Process.cpp index 70cc25e..1a9c324 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -92,6 +92,162 @@ Void::Result::Result spawn(const SpawnOptions&) "Process::spawn: not implemented on Windows")}; } +BinarySession::BinarySession(Child child, BinarySessionOptions options) + : child_(std::move(child)), options_(options) +{ +} + +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&, BinarySessionOptions) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession: not implemented on Windows")}; +} + +bool BinarySession::valid() const noexcept { return false; } + +Void::Result::Result BinarySession::write_stdin( + std::span, std::chrono::milliseconds, std::stop_token) +{ + return std::unexpected{BinaryError{ + 0, + false, + BinaryFailureCode::io_error, + Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession::write_stdin: not implemented on Windows")}}; +} + +Void::Result::Result BinarySession::read_stdout( + std::span, std::chrono::milliseconds, std::stop_token) +{ + return std::unexpected{BinaryError{ + 0, + false, + BinaryFailureCode::io_error, + Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession::read_stdout: not implemented on Windows")}}; +} + +Void::Result::Result BinarySession::read_stderr( + std::span, std::chrono::milliseconds, std::stop_token) +{ + return std::unexpected{BinaryError{ + 0, + false, + BinaryFailureCode::io_error, + Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession::read_stderr: not implemented on Windows")}}; +} + +Void::Result::Result BinarySession::close_stdin() +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession::close_stdin: not implemented on Windows")}; +} + +Void::Result::Result BinarySession::wait( + std::chrono::milliseconds, std::stop_token) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession::wait: not implemented on Windows")}; +} + +Void::Result::Result BinarySession::terminate( + std::chrono::milliseconds) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession::terminate: not implemented on Windows")}; +} + +BinarySession::PollFill BinarySession::poll_fill(int, + std::span, + std::size_t&, + bool) +{ + PollFill result; + result.failure = BinaryFailureCode::io_error; + result.error = Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession: not implemented on Windows"); + return result; +} + +Void::Result::Result BinarySession::read_stream( + bool, std::span, std::chrono::milliseconds, std::stop_token) +{ + return std::unexpected{BinaryError{ + 0, + false, + BinaryFailureCode::io_error, + Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::BinarySession: not implemented on Windows")}}; +} + +void BinarySession::note_exit() noexcept {} + Void::Result::Result communicate_blocking(Child&, std::string_view, @@ -1327,6 +1483,578 @@ Void::Result::Result 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, diff --git a/tests/helpers/ProcessHelper.cpp b/tests/helpers/ProcessHelper.cpp index e020dbf..486fc3a 100644 --- a/tests/helpers/ProcessHelper.cpp +++ b/tests/helpers/ProcessHelper.cpp @@ -245,6 +245,31 @@ int mode_grandchild_ignore_sigterm(int argc, char** argv) ::_exit(0); } +int mode_descendant_holds_stdout(int argc, char** argv) +{ + std::int64_t hold_ms = 5000; + if (argc >= 3 && !parse_i64(argv[2], hold_ms)) { + return usage_error("descendant-holds-stdout duration must be an integer"); + } + if (hold_ms < 0) { + hold_ms = 0; + } + const pid_t descendant = ::fork(); + if (descendant < 0) { + return 1; + } + if (descendant == 0) { + // Keep the inherited stdout write end open while ignoring graceful + // termination, so the parent's reader sees no EOF. + std::signal(SIGTERM, SIG_IGN); + std::this_thread::sleep_for(std::chrono::milliseconds{hold_ms}); + ::_exit(0); + } + static constexpr char kReady[] = "ready\n"; + (void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1); + ::_exit(0); +} + int mode_simultaneous_io(int argc, char** argv) { if (argc != 3) { @@ -539,6 +564,9 @@ int main(int argc, char** argv) if (mode == "grandchild-ignore-sigterm") { return mode_grandchild_ignore_sigterm(argc, argv); } + if (mode == "descendant-holds-stdout") { + return mode_descendant_holds_stdout(argc, argv); + } if (mode == "simultaneous-io") { return mode_simultaneous_io(argc, argv); } diff --git a/tests/standalone/System/BinarySession.cpp b/tests/standalone/System/BinarySession.cpp new file mode 100644 index 0000000..f8e4e16 --- /dev/null +++ b/tests/standalone/System/BinarySession.cpp @@ -0,0 +1,310 @@ +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +constexpr auto kTestTimeout = std::chrono::seconds{10}; + +std::vector make_pattern(std::size_t size) +{ + std::vector data(size); + for (std::size_t i = 0; i < size; ++i) { + // Include NUL and 0xFF so the transfer is provably binary-safe. + switch (i % 5) { + case 0: + data[i] = std::byte{0x00}; + break; + case 1: + data[i] = std::byte{0xFF}; + break; + case 2: + data[i] = std::byte{0x0A}; + break; + case 3: + data[i] = static_cast(i & 0xFF); + break; + default: + data[i] = std::byte{0x7F}; + break; + } + } + return data; +} + +std::vector read_until_eof(Void::Process::BinarySession& session, + bool from_stdout, + std::chrono::milliseconds timeout = kTestTimeout) +{ + std::vector collected; + std::array chunk{}; + for (;;) { + auto read = from_stdout ? session.read_stdout(chunk, timeout) + : session.read_stderr(chunk, timeout); + require(read.has_value()); + if (read->bytes > 0) { + collected.insert(collected.end(), + chunk.begin(), + chunk.begin() + static_cast(read->bytes)); + } + if (read->eof) { + break; + } + } + return collected; +} + +int open_fd_count() +{ + int count = 0; + for (int fd = 0; fd < 1024; ++fd) { + if (::fcntl(fd, F_GETFD) != -1) { + ++count; + } + } + return count; +} + +Void::Process::SpawnOptions helper_options(std::vector args) +{ + Void::Process::SpawnOptions options; + options.executable = VOID_PROCESS_HELPER_PATH; + options.arguments = std::move(args); + return options; +} + +} // namespace + +Void::Testing::Test binary_session_round_trip_larger_than_pipe_capacity() +{ + Void::Process::BinarySessionOptions session_options; + session_options.max_stdout_buffer = 4ULL * 1024ULL * 1024ULL; + session_options.max_stderr_buffer = 4ULL * 1024ULL * 1024ULL; + + auto spawned = Void::Process::BinarySession::spawn( + helper_options({"cat"}), session_options); + require(spawned.has_value()); + auto& session = *spawned; + + const auto payload = make_pattern(1024ULL * 1024ULL); + auto written = session.write_stdin(payload, kTestTimeout); + require(written.has_value()); + expect_eq(written->bytes, payload.size()); + + auto closed = session.close_stdin(); + require(closed.has_value()); + + const auto echoed = read_until_eof(session, true); + expect_eq(echoed.size(), payload.size()); + expect(echoed == payload); + + auto waited = session.wait(kTestTimeout); + require(waited.has_value()); + expect(waited->exited); + expect_eq(waited->code, 0); +} + +Void::Testing::Test binary_session_drains_stderr_while_stdout_read() +{ + auto spawned = Void::Process::BinarySession::spawn( + helper_options({"flood", "262144", "524288"})); + require(spawned.has_value()); + auto& session = *spawned; + + // Only stdout is read; stderr must still be drained into its bounded + // buffer so the child never blocks on a full stderr pipe. + const auto out = read_until_eof(session, true); + expect_eq(out.size(), std::size_t{262144}); + for (const auto byte : out) { + expect(byte == std::byte{'O'}); + } + + const auto err = read_until_eof(session, false); + expect_eq(err.size(), std::size_t{524288}); + for (const auto byte : err) { + expect(byte == std::byte{'E'}); + } + + auto waited = session.wait(kTestTimeout); + require(waited.has_value()); + expect_eq(waited->code, 0); +} + +Void::Testing::Test binary_session_partial_write_to_slow_sink() +{ + auto spawned = Void::Process::BinarySession::spawn( + helper_options({"ignore-sigterm", "5000"})); + require(spawned.has_value()); + auto& session = *spawned; + + const auto payload = make_pattern(1024ULL * 1024ULL); + auto written = session.write_stdin(payload, std::chrono::milliseconds{100}); + require(!written.has_value()); + expect_eq(written.error().failure, Void::Process::BinaryFailureCode::timeout); + expect(written.error().bytes_transferred > 0); + expect(written.error().bytes_transferred < payload.size()); + + auto terminated = session.terminate(std::chrono::milliseconds{100}); + require(terminated.has_value()); +} + +Void::Testing::Test binary_session_half_close_child_sees_eof() +{ + auto spawned = Void::Process::BinarySession::spawn(helper_options({"cat"})); + require(spawned.has_value()); + auto& session = *spawned; + + const auto payload = make_pattern(4096); + auto written = session.write_stdin(payload, kTestTimeout); + require(written.has_value()); + expect_eq(written->bytes, payload.size()); + + auto closed = session.close_stdin(); + require(closed.has_value()); + // Closing twice is a no-op. + expect(session.close_stdin().has_value()); + + const auto echoed = read_until_eof(session, true); + expect(echoed == payload); + + auto waited = session.wait(kTestTimeout); + require(waited.has_value()); + expect_eq(waited->code, 0); +} + +Void::Testing::Test binary_session_cancellation_race() +{ + for (int iteration = 0; iteration < 5; ++iteration) { + auto spawned = Void::Process::BinarySession::spawn( + helper_options({"ignore-sigterm", "5000"})); + require(spawned.has_value()); + auto& session = *spawned; + + std::atomic cancel_now{false}; + std::thread canceller{[&]() { + while (!cancel_now.load(std::memory_order_acquire)) { + std::this_thread::yield(); + } + std::this_thread::sleep_for(std::chrono::milliseconds{20}); + session.cancel(); + }}; + + std::array chunk{}; + bool observed_cancel = false; + for (;;) { + auto read = session.read_stdout(chunk); + if (!read.has_value()) { + observed_cancel = + read.error().failure == Void::Process::BinaryFailureCode::cancelled; + break; + } + cancel_now.store(true, std::memory_order_release); + } + cancel_now.store(true, std::memory_order_release); + canceller.join(); + expect(observed_cancel); + + auto terminated = session.terminate(std::chrono::milliseconds{100}); + require(terminated.has_value()); + } +} + +Void::Testing::Test binary_session_descendant_held_pipe_times_out_and_cleans_up() +{ + auto spawned = Void::Process::BinarySession::spawn( + helper_options({"descendant-holds-stdout", "5000"})); + require(spawned.has_value()); + auto& session = *spawned; + + std::array chunk{}; + std::string ready; + while (ready.find("ready\n") == std::string::npos) { + auto read = session.read_stdout(chunk, kTestTimeout); + require(read.has_value()); + ready.append(reinterpret_cast(chunk.data()), read->bytes); + require(!read->eof); + } + + // The leader exits but its descendant keeps the stdout pipe open, so no + // EOF arrives; a bounded read must time out instead of hanging. + auto read = session.read_stdout(chunk, std::chrono::milliseconds{100}); + require(!read.has_value()); + expect_eq(read.error().failure, Void::Process::BinaryFailureCode::timeout); + + auto terminated = session.terminate(std::chrono::milliseconds{60}); + require(terminated.has_value()); + expect(!session.child().process_group_alive()); +} + +Void::Testing::Test binary_session_cleanup_leaves_no_fds_or_children() +{ + const int fds_before = open_fd_count(); + long long last_pid = -1; + { + auto spawned = Void::Process::BinarySession::spawn(helper_options({"cat"})); + require(spawned.has_value()); + auto& session = *spawned; + last_pid = session.pid(); + + std::array payload{std::byte{'a'}, + std::byte{0}, + std::byte{0xFF}, + std::byte{'z'}}; + auto written = session.write_stdin(payload, kTestTimeout); + require(written.has_value()); + require(session.close_stdin().has_value()); + const auto echoed = read_until_eof(session, true); + expect_eq(echoed.size(), payload.size()); + auto waited = session.wait(kTestTimeout); + require(waited.has_value()); + expect_eq(waited->code, 0); + } + expect_eq(open_fd_count(), fds_before); + // The session reaped the child before releasing its process slot. + expect(::kill(static_cast(last_pid), 0) == -1); + expect_eq(errno, ESRCH); +} + +Void::Testing::Test binary_session_truncates_when_configured() +{ + Void::Process::BinarySessionOptions session_options; + session_options.max_stdout_buffer = 1024; + session_options.truncate_output_on_overflow = true; + + auto spawned = Void::Process::BinarySession::spawn( + helper_options({"flood", "65536", "0"}), session_options); + require(spawned.has_value()); + auto& session = *spawned; + + const auto out = read_until_eof(session, true); + expect(out.size() < std::size_t{65536}); + expect(session.stdout_truncated()); + for (const auto byte : out) { + expect(byte == std::byte{'O'}); + } + + auto waited = session.wait(kTestTimeout); + require(waited.has_value()); + expect_eq(waited->code, 0); +}