diff --git a/cmake/Module.cmake b/cmake/Module.cmake index d556422..ac71b0b 100644 --- a/cmake/Module.cmake +++ b/cmake/Module.cmake @@ -5,13 +5,27 @@ set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "") function(void_add_module MODULE_NAME) cmake_parse_arguments(ARG "" "" - "INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS" + "INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS;EXCLUDE_SOURCES_WIN32;EXCLUDE_SOURCES_UNIX" ${ARGN}) set(TGT ${PROJECT_NAME}_${MODULE_NAME}) set(ALIAS ${PROJECT_NAME}::${MODULE_NAME}) file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp") + # Platform-specific source selection: a module may be fully portable at the + # header level while some translation units only build on one platform. + # Exclusions are relative to the module directory so callers do not depend + # on the global source layout. + if(WIN32 AND ARG_EXCLUDE_SOURCES_WIN32) + foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_WIN32) + list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}") + endforeach() + endif() + if(NOT WIN32 AND ARG_EXCLUDE_SOURCES_UNIX) + foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_UNIX) + list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}") + endforeach() + endif() file(GLOB_RECURSE HDR CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp" "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h") diff --git a/include/Void/System/Process.hpp b/include/Void/System/Process.hpp index 36439c9..bcac7bc 100644 --- a/include/Void/System/Process.hpp +++ b/include/Void/System/Process.hpp @@ -17,9 +17,23 @@ #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; @@ -100,7 +114,7 @@ struct CommunicateResult { class Child { public: - Child() noexcept = default; + Child() noexcept; Child(long long pid, long long pgid, bool owns_process_group, @@ -157,6 +171,12 @@ private: 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; }; diff --git a/src/IO/module.cmake b/src/IO/module.cmake index b12d9da..498e7ce 100644 --- a/src/IO/module.cmake +++ b/src/IO/module.cmake @@ -1,3 +1,8 @@ void_add_module(IO INTERNAL_DEPS Core Functional Time Memory Async -) \ No newline at end of file + # The current native driver is epoll-based and only builds on Linux/Unix. + # Windows capability is not claimed; callers get a fail-closed boundary + # instead of a POSIX driver that cannot compile. + EXCLUDE_SOURCES_WIN32 + EpollDriver.cpp +) diff --git a/src/Net/Http.cpp b/src/Net/Http.cpp index 7bff1cc..6ae8366 100644 --- a/src/Net/Http.cpp +++ b/src/Net/Http.cpp @@ -24,6 +24,19 @@ #include #include #include +#else +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include +#include +#include #endif #include @@ -56,6 +69,26 @@ namespace Void::Net std::atomic g_dl_temp_seq{0}; +#if defined(_WIN32) + // Win32 paths above MAX_PATH must use the extended-length prefix, and + // forward slashes are not accepted by the wide file APIs. + [[nodiscard]] std::filesystem::path + extended_path(const std::filesystem::path& path) + { + std::error_code ec; + const auto absolute = std::filesystem::absolute(path, ec); + std::wstring text = (ec ? path : absolute).wstring(); + std::replace(text.begin(), text.end(), L'/', L'\\'); + if (text.rfind(L"\\\\?\\", 0) == 0 || text.size() < MAX_PATH) { + return std::filesystem::path{text}; + } + if (text.rfind(L"\\\\", 0) == 0) { + return std::filesystem::path{L"\\\\?\\UNC\\" + text.substr(2)}; + } + return std::filesystem::path{L"\\\\?\\" + text}; + } +#endif + [[nodiscard]] bool equal_ascii_ci(std::string_view a, std::string_view b) noexcept { @@ -557,13 +590,26 @@ namespace Void::Net } const std::filesystem::path tmp_path = parent / std::format(".void-dl-{}-{}", +#if defined(_WIN32) + static_cast(::_getpid()), +#else static_cast(::getpid()), +#endif g_dl_temp_seq.fetch_add( 1, std::memory_order_relaxed)); +#if defined(_WIN32) + // Create exclusively next to the destination: an existing entry + // (including a reparse point) is never followed or truncated. + const int fd = ::_wopen( + extended_path(tmp_path).c_str(), + _O_WRONLY | _O_CREAT | _O_EXCL | _O_BINARY | _O_NOINHERIT, + _S_IREAD | _S_IWRITE); +#else const int fd = ::open( tmp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0644); +#endif if (fd < 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, @@ -593,10 +639,17 @@ namespace Void::Net { std::size_t off = 0; while (off < data.size()) { +#if defined(_WIN32) + const int w = ::_write( + m_fd, + reinterpret_cast(data.data()) + off, + static_cast(data.size() - off)); +#else const ssize_t w = ::write( m_fd, reinterpret_cast(data.data()) + off, data.size() - off); +#endif if (w < 0 && errno == EINTR) { continue; } @@ -616,6 +669,50 @@ namespace Void::Net [[nodiscard]] Void::Result::Result commit() { +#if defined(_WIN32) + if (::_commit(m_fd) != 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: flush download file failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + const int raw = std::exchange(m_fd, -1); + if (::_close(raw) != 0) { + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: close download file failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + // Never replace a reparse point: a hostile workspace entry + // could redirect the completed download outside the target. + const DWORD attributes = + ::GetFileAttributesW(extended_path(m_dest).c_str()); + if (attributes != INVALID_FILE_ATTRIBUTES && + (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) { + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + "Net: refusing to replace a reparse-point " + "download destination")}; + } + if (::MoveFileExW(extended_path(m_tmp).c_str(), + extended_path(m_dest).c_str(), + MOVEFILE_REPLACE_EXISTING | + MOVEFILE_WRITE_THROUGH) == 0) { + const DWORD error = ::GetLastError(); + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: replace download file failed: " + "win32={}", + error), + std::error_code{static_cast(error), + std::system_category()})}; + } +#else if (::fsync(m_fd) != 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, @@ -639,9 +736,10 @@ namespace Void::Net return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: rename download file failed: {}", - ec.message()), + ec.message()), ec)}; } +#endif m_committed = true; return {}; } @@ -649,7 +747,11 @@ namespace Void::Net void discard() noexcept { if (m_fd >= 0) { +#if defined(_WIN32) + (void)::_close(m_fd); +#else (void)::close(m_fd); +#endif m_fd = -1; } if (!m_committed && !m_tmp.empty()) { diff --git a/src/Net/module.cmake b/src/Net/module.cmake index 4903212..fd8c6cb 100644 --- a/src/Net/module.cmake +++ b/src/Net/module.cmake @@ -1,5 +1,10 @@ void_add_module(Net INTERNAL_DEPS Functional Text Time + # The HTTP server is POSIX-only. Windows builds get the client-side + # surface; a Windows server port is explicitly out of scope, and any + # server symbol left undefined fails closed at link time. + EXCLUDE_SOURCES_WIN32 + HttpServer.cpp EXTERNAL_DEPS Boost::headers Boost::beast diff --git a/src/System/Process.cpp b/src/System/Process.cpp index 1a9c324..a2eeb19 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -20,295 +20,7 @@ #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; } -bool Child::process_group_alive() 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")}; -} - -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, - 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"); -} - -Void::Result::Result enable_subreaper() noexcept -{ - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::unsupported, - "Process::enable_subreaper: not supported on Windows")}; -} - -} // namespace Void::Process - -#else // POSIX +#ifndef _WIN32 #include #include @@ -896,6 +608,8 @@ void emit_lines_from_offset(const std::string& buf, } // namespace +Child::Child() noexcept = default; + Child::Child(long long pid, long long pgid, bool owns_process_group, @@ -2511,4 +2225,4 @@ Void::Result::Result enable_subreaper() noexcept } // namespace Void::Process -#endif // _WIN32 +#endif // !_WIN32 diff --git a/src/System/ProcessWindows.cpp b/src/System/ProcessWindows.cpp new file mode 100644 index 0000000..19f4393 --- /dev/null +++ b/src/System/ProcessWindows.cpp @@ -0,0 +1,2600 @@ +// Windows process backend for the Void System module. +// +// This translation unit is compiled only for Windows. It implements the same +// public Process API as the POSIX backend in Process.cpp using native Win32 +// primitives: +// * HANDLE ownership through Void::FileSystem::detail::OwnedHandle (never an +// integer file descriptor), +// * CreateProcessW with MSVCRT-compatible argument quoting and a UTF-16 +// environment block, +// * an explicit PROC_THREAD_ATTRIBUTE_HANDLE_LIST so only the three child +// pipe ends are inherited, +// * a Job Object per child for process-tree containment and verified +// cleanup, +// * overlapped named pipes so reads and writes are cancellable and bounded +// by timeout / stop token. +// +// Capabilities that cannot be provided faithfully on Windows (exec-style +// reexec, POSIX signals, subreaper opt-in) fail closed with a typed +// `unsupported` error. + +#ifdef _WIN32 + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Process +{ + +namespace +{ + + using Void::FileSystem::detail::OwnedHandle; + + constexpr DWORD kPipeBufferBytes = 64 * 1024; + constexpr DWORD kMaxWaitSliceMs = 25; + constexpr int kSignalInterrupt = 2; + constexpr int kSignalKill = 9; + constexpr int kSignalTerminate = 15; + constexpr int kSignalBreak = 21; + + [[nodiscard]] bool utf8_to_wide(std::string_view text, std::wstring& out) + { + out.clear(); + if (text.empty()) + { + return true; + } + if (text.size() > + static_cast(std::numeric_limits::max())) + { + return false; + } + const int len = ::MultiByteToWideChar(CP_UTF8, + MB_ERR_INVALID_CHARS, + text.data(), + static_cast(text.size()), + nullptr, + 0); + if (len <= 0) + { + return false; + } + out.resize(static_cast(len)); + return ::MultiByteToWideChar(CP_UTF8, + MB_ERR_INVALID_CHARS, + text.data(), + static_cast(text.size()), + out.data(), + len) == len; + } + + [[nodiscard]] std::string wide_to_utf8(std::wstring_view text) + { + if (text.empty()) + { + return {}; + } + const int len = ::WideCharToMultiByte(CP_UTF8, + 0, + text.data(), + static_cast(text.size()), + nullptr, + 0, + nullptr, + nullptr); + if (len <= 0) + { + return {}; + } + std::string out(static_cast(len), '\0'); + (void)::WideCharToMultiByte(CP_UTF8, + 0, + text.data(), + static_cast(text.size()), + out.data(), + len, + nullptr, + nullptr); + return out; + } + + [[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]] Void::System::SystemErrorCode + map_process_error(DWORD error) noexcept + { + // Sharing violations are transient contention, not a permission + // problem: report them as busy so callers retry instead of treating + // the workspace file as inaccessible. + if (error == ERROR_SHARING_VIOLATION || error == ERROR_LOCK_VIOLATION) + { + return Void::System::SystemErrorCode::busy; + } + return Void::FileSystem::detail::map_win32_error(error); + } + + [[nodiscard]] Void::Result::Error + win_error(Void::System::SystemErrorCode code, + std::string_view what, + DWORD error) + { + return Void::System::make_system_error( + code, + std::format("{} (win32={}: {})", + what, + error, + Void::FileSystem::detail::win32_message(error))); + } + + [[nodiscard]] Void::Result::Error last_win_error( + Void::System::SystemErrorCode fallback, std::string_view what) + { + const DWORD error = ::GetLastError(); + const auto code = (fallback == Void::System::SystemErrorCode::io_error) + ? map_process_error(error) + : fallback; + return win_error(code, what, error); + } + + // MSVCRT / CommandLineToArgvW compatible argument quoting. + void append_quoted_argument(std::wstring& out, std::wstring_view arg) + { + const bool needs_quotes = + arg.empty() || arg.find_first_of(L" \t\n\v\"") != std::wstring_view::npos; + if (!needs_quotes) + { + out.append(arg); + return; + } + out.push_back(L'"'); + std::size_t i = 0; + for (;;) + { + std::size_t backslashes = 0; + while (i < arg.size() && arg[i] == L'\\') + { + ++i; + ++backslashes; + } + if (i == arg.size()) + { + out.append(backslashes * 2, L'\\'); + break; + } + if (arg[i] == L'"') + { + out.append(backslashes * 2 + 1, L'\\'); + out.push_back(L'"'); + } + else + { + out.append(backslashes, L'\\'); + out.push_back(arg[i]); + } + ++i; + } + out.push_back(L'"'); + } + + struct CaseInsensitiveLess + { + [[nodiscard]] bool operator()(const std::wstring& a, + const std::wstring& b) const noexcept + { + return ::CompareStringOrdinal(a.c_str(), + static_cast(a.size()), + b.c_str(), + static_cast(b.size()), + TRUE) == CSTR_LESS_THAN; + } + }; + + [[nodiscard]] bool equal_ci(std::wstring_view a, std::wstring_view b) noexcept + { + return ::CompareStringOrdinal(a.data(), + static_cast(a.size()), + b.data(), + static_cast(b.size()), + TRUE) == CSTR_EQUAL; + } + + [[nodiscard]] Void::Result::Result, Void::Result::Error> + build_environment_block(const EnvironmentPolicy& policy) + { + auto validate_key = [](std::wstring_view key) { + return !key.empty() && key.find(L'=') == std::wstring_view::npos && + key.find(L'\0') == std::wstring_view::npos; + }; + + std::vector unset_keys; + for (const auto& key : policy.unset_keys) + { + std::wstring wide; + if (!utf8_to_wide(key, wide) || !validate_key(wide)) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid unset environment variable key")}; + } + unset_keys.push_back(std::move(wide)); + } + + std::vector allow_keys; + if (policy.mode == EnvMode::allowlist) + { + for (const auto& key : policy.allowlist) + { + std::wstring wide; + if (!utf8_to_wide(key, wide) || !validate_key(wide)) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid allowlist environment key")}; + } + allow_keys.push_back(std::move(wide)); + } + } + + auto is_unset = [&](std::wstring_view name) { + for (const auto& key : unset_keys) + { + if (equal_ci(key, name)) + { + return true; + } + } + return false; + }; + auto is_allowed = [&](std::wstring_view name) { + if (policy.mode != EnvMode::allowlist) + { + return true; + } + for (const auto& key : allow_keys) + { + if (equal_ci(key, name)) + { + return true; + } + } + return false; + }; + + std::map env; + + if (policy.mode != EnvMode::explicit_only) + { + LPWCH block = ::GetEnvironmentStringsW(); + if (block != nullptr) + { + for (const wchar_t* cursor = block; *cursor != L'\0';) + { + std::wstring entry{cursor}; + cursor += entry.size() + 1; + if (entry.empty() || entry.front() == L'=') + { + // Drive-relative hidden entries are not normal + // environment variables and are not inherited. + continue; + } + const auto eq = entry.find(L'='); + if (eq == std::wstring::npos) + { + continue; + } + std::wstring name = entry.substr(0, eq); + std::wstring value = entry.substr(eq + 1); + if (is_unset(name) || !is_allowed(name)) + { + continue; + } + env.insert_or_assign(std::move(name), std::move(value)); + } + ::FreeEnvironmentStringsW(block); + } + } + + for (const auto& [key, value] : policy.set_vars) + { + std::wstring wide_key; + std::wstring wide_value; + if (!utf8_to_wide(key, wide_key) || + !utf8_to_wide(value, wide_value) || !validate_key(wide_key) || + wide_value.find(L'\0') != std::wstring::npos) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid environment key/value in set_vars")}; + } + env.insert_or_assign(std::move(wide_key), std::move(wide_value)); + } + + std::vector out; + for (const auto& [key, value] : env) + { + out.insert(out.end(), key.begin(), key.end()); + out.push_back(L'='); + out.insert(out.end(), value.begin(), value.end()); + out.push_back(L'\0'); + } + out.push_back(L'\0'); + return out; + } + + [[nodiscard]] std::wstring to_extended_path(const std::filesystem::path& path) + { + std::wstring text = path.wstring(); + std::replace(text.begin(), text.end(), L'/', L'\\'); + if (text.empty() || text.rfind(L"\\\\?\\", 0) == 0 || + text.size() < MAX_PATH) + { + return text; + } + std::error_code ec; + const auto absolute = std::filesystem::absolute(path, ec); + if (ec) + { + return text; + } + text = absolute.wstring(); + std::replace(text.begin(), text.end(), L'/', L'\\'); + if (text.rfind(L"\\\\?\\", 0) == 0) + { + return text; + } + if (text.rfind(L"\\\\", 0) == 0) + { + return L"\\\\?\\UNC\\" + text.substr(2); + } + return L"\\\\?\\" + text; + } + + [[nodiscard]] std::wstring resolve_executable( + const std::filesystem::path& executable, bool search_path) + { + std::wstring wide = executable.wstring(); + const bool has_separator = + wide.find_first_of(L"\\/") != std::wstring::npos; + if (search_path && !has_separator && !wide.empty()) + { + std::vector buffer(32768); + const DWORD len = ::SearchPathW(nullptr, + wide.c_str(), + L".exe", + static_cast(buffer.size()), + buffer.data(), + nullptr); + if (len > 0 && len < buffer.size()) + { + wide.assign(buffer.data(), len); + } + } + return to_extended_path(std::filesystem::path{wide}); + } + + // One overlapped pipe endpoint owned by the parent process. + struct WinStream + { + HANDLE event{nullptr}; + OVERLAPPED ov{}; + OwnedHandle handle; + std::array read_buf{}; + std::vector write_buf; + DWORD read_ready{0}; + DWORD write_ready{0}; + bool read_pending{false}; + bool write_pending{false}; + bool eof{false}; + bool broken{false}; + DWORD error{0}; + + WinStream() noexcept + { + event = ::CreateEventW(nullptr, TRUE, FALSE, nullptr); + } + ~WinStream() + { + close(); + if (event != nullptr) + { + (void)::CloseHandle(event); + } + } + WinStream(const WinStream&) = delete; + WinStream& operator=(const WinStream&) = delete; + WinStream(WinStream&&) = delete; + WinStream& operator=(WinStream&&) = delete; + + [[nodiscard]] bool valid() const noexcept + { + return handle.valid() && event != nullptr; + } + + void close() noexcept + { + if (handle.valid()) + { + (void)::CancelIoEx(handle.get(), nullptr); + handle.reset(); + } + } + }; + + [[nodiscard]] Void::Result::Result + create_pipe_end(bool parent_reads, WinStream& parent, const wchar_t* tag) + { + static std::atomic sequence{0}; + const std::wstring name = L"\\\\.\\pipe\\void-" + + std::to_wstring(::GetCurrentProcessId()) + L"-" + + std::to_wstring(sequence.fetch_add(1)) + L"-" + tag; + + DWORD parent_access = + parent_reads ? PIPE_ACCESS_INBOUND : PIPE_ACCESS_OUTBOUND; + DWORD pipe_mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT; +#ifdef PIPE_REJECT_REMOTE_CLIENTS + pipe_mode |= PIPE_REJECT_REMOTE_CLIENTS; +#endif + const HANDLE server = ::CreateNamedPipeW(name.c_str(), + parent_access | FILE_FLAG_OVERLAPPED, + pipe_mode, + 1, + kPipeBufferBytes, + kPipeBufferBytes, + 0, + nullptr); + if (server == INVALID_HANDLE_VALUE) + { + return std::unexpected{last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: CreateNamedPipe failed")}; + } + parent.handle.reset(server); + if (!parent.valid()) + { + parent.close(); + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: overlapped event creation failed")}; + } + + SECURITY_ATTRIBUTES sa{}; + sa.nLength = sizeof(sa); + sa.lpSecurityDescriptor = nullptr; + sa.bInheritHandle = TRUE; + const DWORD child_access = parent_reads ? GENERIC_WRITE : GENERIC_READ; + const HANDLE client = ::CreateFileW(name.c_str(), + child_access, + 0, + &sa, + OPEN_EXISTING, + 0, + nullptr); + if (client == INVALID_HANDLE_VALUE) + { + const std::string message = + std::format("Process::spawn: connect '{}' pipe failed", + wide_to_utf8(tag)); + const auto error = last_win_error( + Void::System::SystemErrorCode::spawn_failed, message); + parent.close(); + return std::unexpected{error}; + } + + // The client end exists now; complete the server-side connection so the + // parent handle is usable. The handle is overlapped, so a pending + // connect is completed through the stream event. + (void)::ResetEvent(parent.event); + OVERLAPPED connect_overlapped{}; + connect_overlapped.hEvent = parent.event; + if (::ConnectNamedPipe(server, &connect_overlapped) == 0) + { + const DWORD error = ::GetLastError(); + if (error == ERROR_IO_PENDING) + { + (void)::WaitForSingleObject(parent.event, INFINITE); + DWORD transferred = 0; + (void)::GetOverlappedResult( + server, &connect_overlapped, &transferred, FALSE); + } + else if (error != ERROR_PIPE_CONNECTED) + { + const auto failure = win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: ConnectNamedPipe failed", + error); + parent.close(); + return std::unexpected{failure}; + } + } + (void)::ResetEvent(parent.event); + return OwnedHandle{client}; + } + + [[nodiscard]] Void::Result::Result + inheritable_standard_handle(DWORD which, bool read) + { + const HANDLE source = ::GetStdHandle(which); + if (source != nullptr && source != INVALID_HANDLE_VALUE) + { + HANDLE duplicate = nullptr; + if (::DuplicateHandle(::GetCurrentProcess(), + source, + ::GetCurrentProcess(), + &duplicate, + 0, + TRUE, + DUPLICATE_SAME_ACCESS)) + { + return OwnedHandle{duplicate}; + } + } + SECURITY_ATTRIBUTES sa{}; + sa.nLength = sizeof(sa); + sa.bInheritHandle = TRUE; + const HANDLE nul = ::CreateFileW(L"NUL", + read ? GENERIC_READ : GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + &sa, + OPEN_EXISTING, + 0, + nullptr); + if (nul == INVALID_HANDLE_VALUE) + { + return std::unexpected{last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: open NUL device failed")}; + } + return OwnedHandle{nul}; + } + + enum class IoStatus + { + none, + data, + eof, + error, + }; + + void issue_read(WinStream& stream, std::size_t max_bytes) noexcept + { + if (stream.read_pending || stream.eof || !stream.handle.valid()) + { + return; + } + const std::size_t want = std::min(max_bytes, stream.read_buf.size()); + if (want == 0) + { + return; + } + (void)::ResetEvent(stream.event); + stream.ov = {}; + stream.ov.hEvent = stream.event; + DWORD got = 0; + if (::ReadFile(stream.handle.get(), + stream.read_buf.data(), + static_cast(want), + &got, + &stream.ov) != 0) + { + stream.read_ready = got; + return; + } + const DWORD error = ::GetLastError(); + if (error == ERROR_IO_PENDING) + { + stream.read_pending = true; + return; + } + if (error == ERROR_BROKEN_PIPE || error == ERROR_HANDLE_EOF || + error == ERROR_PIPE_NOT_CONNECTED) + { + stream.eof = true; + return; + } + stream.error = error; + stream.broken = true; + stream.eof = true; + } + + [[nodiscard]] IoStatus complete_read(WinStream& stream, + DWORD& bytes) noexcept + { + bytes = 0; + if (stream.error != 0 && !stream.read_pending) + { + return IoStatus::error; + } + DWORD got = 0; + if (stream.read_pending) + { + if (::WaitForSingleObject(stream.event, 0) != WAIT_OBJECT_0) + { + return IoStatus::none; + } + if (::GetOverlappedResult(stream.handle.get(), + &stream.ov, + &got, + FALSE) == 0) + { + const DWORD error = ::GetLastError(); + stream.read_pending = false; + if (error == ERROR_OPERATION_ABORTED || + error == ERROR_BROKEN_PIPE || error == ERROR_HANDLE_EOF || + error == ERROR_PIPE_NOT_CONNECTED) + { + stream.eof = true; + return IoStatus::eof; + } + stream.error = error; + stream.broken = true; + stream.eof = true; + return IoStatus::error; + } + stream.read_pending = false; + } + else + { + got = stream.read_ready; + stream.read_ready = 0; + } + bytes = got; + return got > 0 ? IoStatus::data : IoStatus::none; + } + + void issue_write(WinStream& stream, + std::span data) noexcept + { + if (stream.write_pending || data.empty() || !stream.handle.valid() || + stream.broken) + { + return; + } + stream.write_buf.assign(data.begin(), data.end()); + (void)::ResetEvent(stream.event); + stream.ov = {}; + stream.ov.hEvent = stream.event; + DWORD wrote = 0; + if (::WriteFile(stream.handle.get(), + stream.write_buf.data(), + static_cast(stream.write_buf.size()), + &wrote, + &stream.ov) != 0) + { + stream.write_ready = wrote; + return; + } + const DWORD error = ::GetLastError(); + if (error == ERROR_IO_PENDING) + { + stream.write_pending = true; + return; + } + if (error == ERROR_NO_DATA || error == ERROR_BROKEN_PIPE) + { + stream.broken = true; + return; + } + stream.error = error; + stream.broken = true; + } + + [[nodiscard]] std::size_t complete_write(WinStream& stream) noexcept + { + DWORD wrote = 0; + if (stream.write_pending) + { + if (::WaitForSingleObject(stream.event, 0) != WAIT_OBJECT_0) + { + return 0; + } + if (::GetOverlappedResult(stream.handle.get(), + &stream.ov, + &wrote, + FALSE) == 0) + { + const DWORD error = ::GetLastError(); + stream.write_pending = false; + stream.write_buf.clear(); + if (error == ERROR_OPERATION_ABORTED || + error == ERROR_NO_DATA || error == ERROR_BROKEN_PIPE) + { + stream.broken = true; + return 0; + } + stream.error = error; + stream.broken = true; + return 0; + } + stream.write_pending = false; + } + else + { + wrote = stream.write_ready; + stream.write_ready = 0; + } + stream.write_buf.clear(); + return wrote; + } + +} // namespace + +namespace Detail +{ + + struct WindowsProcess + { + Void::FileSystem::detail::OwnedHandle process; + Void::FileSystem::detail::OwnedHandle job; + WinStream in; + WinStream out; + WinStream err; + DWORD pid{0}; + bool owns_job{true}; + bool new_process_group{true}; + bool reaped{false}; + ExitStatus cached{}; + std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}}; + }; + + struct ChildAccess + { + static void install(Child& child, + std::unique_ptr state) noexcept + { + child.pid_ = static_cast(state->pid); + child.pgid_ = static_cast(state->pid); + child.owns_group_ = state->owns_job; + child.reaped_ = false; + child.kill_grace_ = state->kill_grace; + child.windows_ = std::move(state); + } + + static WindowsProcess& get(Child& child) noexcept + { + return *child.windows_; + } + }; + +} // namespace Detail + +namespace +{ + + [[nodiscard]] bool process_signaled(const Detail::WindowsProcess& state) noexcept + { + return state.process.valid() && + ::WaitForSingleObject(state.process.get(), 0) == WAIT_OBJECT_0; + } + + [[nodiscard]] bool job_active(const Detail::WindowsProcess& state) noexcept + { + if (!state.job.valid()) + { + return false; + } + JOBOBJECT_BASIC_ACCOUNTING_INFORMATION info{}; + if (::QueryInformationJobObject(state.job.get(), + JobObjectBasicAccountingInformation, + &info, + sizeof(info), + nullptr) == 0) + { + return false; + } + return info.ActiveProcesses > 0; + } + + [[nodiscard]] ExitStatus read_exit_status( + const Detail::WindowsProcess& state) noexcept + { + ExitStatus status; + DWORD code = 0; + if (state.process.valid()) + { + (void)::GetExitCodeProcess(state.process.get(), &code); + } + status.exited = true; + status.code = static_cast(code); + status.signal = 0; + status.raw_status = static_cast(code); + return status; + } + + void force_terminate(Detail::WindowsProcess& state) noexcept + { + if (state.job.valid()) + { + (void)::TerminateJobObject(state.job.get(), 1); + } + else if (state.process.valid()) + { + (void)::TerminateProcess(state.process.get(), 1); + } + } + +} // namespace + +Child::Child() noexcept = default; + +Child::Child(long long, + long long, + bool, + Void::System::OwnedFd, + Void::System::OwnedFd, + Void::System::OwnedFd, + std::chrono::milliseconds) noexcept +{ +} + +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_), + windows_(std::move(other.windows_)) +{ +} + +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_; + windows_ = std::move(other.windows_); + } + return *this; +} + +bool Child::valid() const noexcept +{ + return windows_ != nullptr && windows_->process.valid(); +} + +bool Child::running() const noexcept +{ + return valid() && !windows_->reaped && !process_signaled(*windows_); +} + +bool Child::process_group_alive() const noexcept +{ + if (windows_ == nullptr) + { + return false; + } + if (windows_->owns_job && windows_->job.valid()) + { + return job_active(*windows_); + } + return running(); +} + +long long Child::pid() const noexcept +{ + return windows_ != nullptr ? static_cast(windows_->pid) : -1; +} + +long long Child::pgid() const noexcept +{ + return pid(); +} + +bool Child::owns_process_group() const noexcept +{ + return windows_ != nullptr && windows_->owns_job; +} + +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 +{ + if (windows_ != nullptr) + { + windows_->in.close(); + } +} + +Void::Result::Result + Child::send_signal(int sig) noexcept +{ + if (!valid()) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::send_signal: invalid child")}; + } + if (sig == kSignalKill) + { + force_terminate(*windows_); + return {}; + } + if (sig == kSignalTerminate || sig == kSignalInterrupt || + sig == kSignalBreak) + { + if (windows_->owns_job && + ::GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, windows_->pid) != 0) + { + return {}; + } + return std::unexpected{last_win_error( + Void::System::SystemErrorCode::unsupported, + "Process::Child::send_signal: no console control event handler")}; + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::Child::send_signal: signal is not supported on Windows")}; +} + +Void::Result::Result, Void::Result::Error> + Child::try_wait() +{ + if (!valid()) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::try_wait: invalid child")}; + } + if (windows_->reaped) + { + return std::optional{windows_->cached}; + } + if (::WaitForSingleObject(windows_->process.get(), 0) != WAIT_OBJECT_0) + { + return std::optional{std::nullopt}; + } + windows_->cached = read_exit_status(*windows_); + windows_->reaped = true; + cached_status_ = windows_->cached; + reaped_ = true; + return std::optional{windows_->cached}; +} + +Void::Result::Result + Child::terminate(std::chrono::milliseconds grace) +{ + if (!valid()) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::terminate: invalid child")}; + } + if (windows_->reaped && !job_active(*windows_)) + { + return windows_->cached; + } + + const auto effective_grace = + (grace.count() >= 0) ? grace : windows_->kill_grace; + const auto grace_deadline = + std::chrono::steady_clock::now() + effective_grace; + + if (!windows_->reaped && windows_->owns_job) + { + (void)::GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, windows_->pid); + } + while (std::chrono::steady_clock::now() < grace_deadline) + { + if (process_signaled(*windows_) && !job_active(*windows_)) + { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + } + + if (!process_signaled(*windows_) || job_active(*windows_)) + { + force_terminate(*windows_); + } + + if (::WaitForSingleObject(windows_->process.get(), 5000) != WAIT_OBJECT_0) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::timed_out, + "Process::Child::terminate: process did not exit after termination")}; + } + const auto kill_ceiling = + std::chrono::steady_clock::now() + std::chrono::seconds{5}; + while (job_active(*windows_)) + { + if (std::chrono::steady_clock::now() >= kill_ceiling) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::timed_out, + "Process::Child::terminate: descendant processes failed to " + "exit after job termination")}; + } + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + + windows_->cached = read_exit_status(*windows_); + windows_->reaped = true; + cached_status_ = windows_->cached; + reaped_ = true; + return windows_->cached; +} + +Void::Result::Result + Child::wait_blocking(std::chrono::milliseconds timeout, + std::stop_token stop, + std::chrono::milliseconds kill_grace) +{ + if (!valid()) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::wait_blocking: invalid child")}; + } + if (windows_->reaped) + { + return windows_->cached; + } + + const bool has_timeout = timeout.count() > 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + + if (!has_timeout && !stop.stop_possible()) + { + (void)::WaitForSingleObject(windows_->process.get(), INFINITE); + windows_->cached = read_exit_status(*windows_); + windows_->reaped = true; + cached_status_ = windows_->cached; + reaped_ = true; + return windows_->cached; + } + + 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_duration = std::chrono::milliseconds{10}; + if (has_timeout) + { + const auto remaining = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()); + if (remaining.count() <= 0) + { + continue; + } + sleep_duration = std::min(sleep_duration, remaining); + } + std::this_thread::sleep_for(sleep_duration); + } +} + +void Child::reset_and_reap() noexcept +{ + stdin_.reset(); + stdout_.reset(); + stderr_.reset(); + if (windows_ != nullptr) + { + windows_->in.close(); + windows_->out.close(); + windows_->err.close(); + if (!windows_->reaped) + { + force_terminate(*windows_); + if (windows_->process.valid()) + { + (void)::WaitForSingleObject(windows_->process.get(), 5000); + } + } + windows_.reset(); + } + pid_ = -1; + pgid_ = -1; + owns_group_ = false; + reaped_ = true; +} + +namespace +{ + + [[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; + } + + void emit_lines_from_offset( + const std::string& buffer, + std::size_t& offset, + const std::function& callback, + bool flush) + { + if (!callback) + { + offset = buffer.size(); + return; + } + std::size_t newline = 0; + while ((newline = buffer.find('\n', offset)) != std::string::npos) + { + std::size_t len = newline - offset; + if (len > 0 && buffer[offset + len - 1] == '\r') + { + --len; + } + callback(std::string_view{buffer.data() + offset, len}); + offset = newline + 1; + } + if (flush && offset < buffer.size()) + { + callback(std::string_view{buffer.data() + offset, + buffer.size() - offset}); + offset = buffer.size(); + } + } + +} // namespace + +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")}; + } + + const std::wstring executable = + resolve_executable(options.executable, options.search_path); + if (executable.empty()) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: executable path resolves to empty")}; + } + + std::wstring command_line; + append_quoted_argument(command_line, executable); + std::size_t total_bytes = executable.size() + 1; + for (const auto& argument : options.arguments) + { + if (argument.find('\0') != std::string::npos) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: argument contains NUL byte")}; + } + std::wstring wide; + if (!utf8_to_wide(argument, wide)) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: argument is not valid UTF-8")}; + } + command_line.push_back(L' '); + append_quoted_argument(command_line, wide); + if (!checked_add_size(total_bytes, wide.size() + 1, total_bytes)) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "Process::spawn: argument size overflow")}; + } + } + + auto environment = build_environment_block(options.environment); + if (!environment.has_value()) + { + return std::unexpected{std::move(environment.error())}; + } + if (!checked_add_size(total_bytes, + environment->size() * sizeof(wchar_t), + total_bytes)) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "Process::spawn: environment size overflow")}; + } + if (total_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_bytes, + kMaxSpawnInputBytes))}; + } + + std::wstring working_directory; + if (options.working_directory.has_value()) + { + if (options.working_directory->empty()) + { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: invalid working_directory")}; + } + working_directory = to_extended_path(*options.working_directory); + } + + auto state = std::make_unique(); + state->kill_grace = options.kill_grace; + state->owns_job = true; + state->new_process_group = options.new_process_group; + + OwnedHandle child_in; + OwnedHandle child_out; + OwnedHandle child_err; + + if (options.stdin_pipe) + { + auto end = create_pipe_end(false, state->in, L"stdin"); + if (!end.has_value()) + { + return std::unexpected{std::move(end.error())}; + } + child_in = std::move(*end); + } + else + { + auto handle = inheritable_standard_handle(STD_INPUT_HANDLE, true); + if (!handle.has_value()) + { + return std::unexpected{std::move(handle.error())}; + } + child_in = std::move(*handle); + } + + if (options.stdout_pipe) + { + auto end = create_pipe_end(true, state->out, L"stdout"); + if (!end.has_value()) + { + return std::unexpected{std::move(end.error())}; + } + child_out = std::move(*end); + } + else + { + auto handle = inheritable_standard_handle(STD_OUTPUT_HANDLE, false); + if (!handle.has_value()) + { + return std::unexpected{std::move(handle.error())}; + } + child_out = std::move(*handle); + } + + if (options.stderr_pipe) + { + auto end = create_pipe_end(true, state->err, L"stderr"); + if (!end.has_value()) + { + return std::unexpected{std::move(end.error())}; + } + child_err = std::move(*end); + } + else + { + auto handle = inheritable_standard_handle(STD_ERROR_HANDLE, false); + if (!handle.has_value()) + { + return std::unexpected{std::move(handle.error())}; + } + child_err = std::move(*handle); + } + + STARTUPINFOEXW startup{}; + startup.StartupInfo.cb = sizeof(startup); + startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES; + startup.StartupInfo.hStdInput = child_in.get(); + startup.StartupInfo.hStdOutput = child_out.get(); + startup.StartupInfo.hStdError = child_err.get(); + + SIZE_T attribute_size = 0; + (void)::InitializeProcThreadAttributeList(nullptr, 1, 0, &attribute_size); + std::vector attribute_storage(attribute_size); + auto* attributes = reinterpret_cast( + attribute_storage.data()); + if (::InitializeProcThreadAttributeList( + attributes, 1, 0, &attribute_size) == 0) + { + return std::unexpected{last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: InitializeProcThreadAttributeList failed")}; + } + HANDLE inherited[3] = { + child_in.get(), child_out.get(), child_err.get()}; + if (::UpdateProcThreadAttribute(attributes, + 0, + PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + inherited, + sizeof(inherited), + nullptr, + nullptr) == 0) + { + const std::size_t error = ::GetLastError(); + ::DeleteProcThreadAttributeList(attributes); + return std::unexpected{win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: restrict inherited handles failed", + static_cast(error))}; + } + startup.lpAttributeList = attributes; + + DWORD creation_flags = EXTENDED_STARTUPINFO_PRESENT | + CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT; + if (options.new_process_group) + { + creation_flags |= CREATE_NEW_PROCESS_GROUP; + } + + std::vector command_buffer(command_line.begin(), + command_line.end()); + command_buffer.push_back(L'\0'); + + PROCESS_INFORMATION process_info{}; + const BOOL created = ::CreateProcessW(executable.c_str(), + command_buffer.data(), + nullptr, + nullptr, + TRUE, + creation_flags, + environment->data(), + working_directory.empty() + ? nullptr + : working_directory.c_str(), + &startup.StartupInfo, + &process_info); + const DWORD creation_error = created ? 0 : ::GetLastError(); + ::DeleteProcThreadAttributeList(attributes); + if (created == 0) + { + return std::unexpected{win_error( + map_process_error(creation_error), + std::format("Process::spawn: CreateProcess failed for '{}'", + sanitize_diag(options.executable.string())), + creation_error)}; + } + + OwnedHandle process{process_info.hProcess}; + OwnedHandle thread{process_info.hThread}; + child_in.reset(); + child_out.reset(); + child_err.reset(); + + auto fail_after_create = [&](Void::Result::Error error) + -> Void::Result::Result { + (void)::TerminateProcess(process.get(), 1); + (void)::WaitForSingleObject(process.get(), 5000); + return std::unexpected{std::move(error)}; + }; + + OwnedHandle job{::CreateJobObjectW(nullptr, nullptr)}; + if (!job.valid()) + { + return fail_after_create(last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: CreateJobObject failed")); + } + JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_limits{}; + job_limits.BasicLimitInformation.LimitFlags = + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (::SetInformationJobObject(job.get(), + JobObjectExtendedLimitInformation, + &job_limits, + sizeof(job_limits)) == 0) + { + return fail_after_create(last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: SetInformationJobObject failed")); + } + if (::AssignProcessToJobObject(job.get(), process.get()) == 0) + { + return fail_after_create(last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: AssignProcessToJobObject failed")); + } + if (::ResumeThread(thread.get()) == static_cast(-1)) + { + return fail_after_create(last_win_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: ResumeThread failed")); + } + + state->process = std::move(process); + state->job = std::move(job); + state->pid = process_info.dwProcessId; + + Void::Log::debug("Process", + "spawn: '{}' pid={}", + options.executable.string(), + process_info.dwProcessId); + + Child child; + Detail::ChildAccess::install(child, std::move(state)); + return child; +} + +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_(true), + stderr_eof_(true), + stdin_closed_(true), + 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 (child_.windows_ != nullptr) + { + stdout_eof_ = !child_.windows_->out.valid(); + stderr_eof_ = !child_.windows_->err.valid(); + stdin_closed_ = !child_.windows_->in.valid(); + } +} + +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; + if (child_.windows_ == nullptr) + { + result.idle = true; + return result; + } + auto& state = *child_.windows_; + + if (!stdin_data.empty() && stdin_written < stdin_data.size() && + !stdin_closed_ && state.in.handle.valid()) + { + issue_write(state.in, stdin_data.subspan(stdin_written)); + } + + const std::size_t stdout_used = stdout_buffer_.size() - stdout_offset_; + const std::size_t stderr_used = stderr_buffer_.size() - stderr_offset_; + if (!stdout_eof_ && state.out.handle.valid() && + (discard_on_full || stdout_used < options_.max_stdout_buffer)) + { + const std::size_t space = + discard_on_full ? state.out.read_buf.size() + : options_.max_stdout_buffer - stdout_used; + issue_read(state.out, space); + } + if (!stderr_eof_ && state.err.handle.valid() && + (discard_on_full || stderr_used < options_.max_stderr_buffer)) + { + const std::size_t space = + discard_on_full ? state.err.read_buf.size() + : options_.max_stderr_buffer - stderr_used; + issue_read(state.err, space); + } + + HANDLE events[3]{}; + int count = 0; + if (state.in.write_pending) + { + events[count++] = state.in.event; + } + if (state.out.read_pending) + { + events[count++] = state.out.event; + } + if (state.err.read_pending) + { + events[count++] = state.err.event; + } + + const bool active = count > 0 || state.in.write_ready > 0 || + state.out.read_ready > 0 || state.err.read_ready > 0; + if (!active) + { + result.idle = true; + return result; + } + if (count > 0) + { + const DWORD wait = + timeout_ms < 0 ? INFINITE : static_cast(timeout_ms); + (void)::WaitForMultipleObjects( + static_cast(count), events, FALSE, wait); + } + + if (state.in.write_pending || state.in.write_ready > 0 || state.in.broken) + { + const std::size_t wrote = complete_write(state.in); + stdin_written += wrote; + if (state.in.broken) + { + stdin_closed_ = true; + state.in.close(); + result.stdin_broken = true; + } + } + + auto service = [&](WinStream& stream, + std::vector& buffer, + std::size_t& offset, + bool& eof, + bool& truncated, + std::size_t cap) { + DWORD got = 0; + const IoStatus status = complete_read(stream, got); + if (status == IoStatus::eof) + { + eof = true; + return; + } + if (status == IoStatus::error) + { + eof = true; + result.failure = BinaryFailureCode::io_error; + result.error = win_error(map_process_error(stream.error), + "Process::BinarySession: read failed", + stream.error); + return; + } + if (status != IoStatus::data || got == 0) + { + return; + } + const std::size_t used = buffer.size() - offset; + const std::size_t space = cap > used ? cap - used : 0; + const std::size_t take = std::min(got, space); + if (take < got) + { + truncated = true; + } + if (take > 0) + { + if (offset > 0 && offset == buffer.size()) + { + buffer.clear(); + offset = 0; + } + buffer.insert( + buffer.end(), + stream.read_buf.begin(), + stream.read_buf.begin() + static_cast(take)); + } + }; + + service(state.out, + stdout_buffer_, + stdout_offset_, + stdout_eof_, + stdout_truncated_, + options_.max_stdout_buffer); + service(state.err, + 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_ || child_.windows_ == nullptr || + !child_.windows_->in.handle.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())); + } + poll_timeout_ms = (poll_timeout_ms < 0) + ? static_cast(kMaxWaitSliceMs) + : std::min(poll_timeout_ms, + static_cast(kMaxWaitSliceMs)); + + 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())); + } + poll_timeout_ms = (poll_timeout_ms < 0) + ? static_cast(kMaxWaitSliceMs) + : std::min(poll_timeout_ms, + static_cast(kMaxWaitSliceMs)); + + 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; + if (child_.windows_ != nullptr) + { + child_.windows_->in.close(); + } + return {}; +} + +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))}; + } + + auto& state = Detail::ChildAccess::get(child); + CommunicateResult res; + std::size_t stdin_offset = 0; + bool stdin_done = !state.in.handle.valid() || stdin_data.empty(); + bool out_done = !state.out.handle.valid(); + bool err_done = !state.err.handle.valid(); + if (stdin_done) + { + state.in.close(); + } + + 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; + bool aborted = false; + std::string limit_msg; + std::optional io_failure; + + auto handle_read_chunk = [&](const char* data, + std::size_t len, + bool is_out) -> bool { + std::string& destination = 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& current_line = is_out ? out_cur_line : err_cur_line; + bool& line_exceeded = is_out ? out_line_exceeded : err_line_exceeded; + + if (limits.max_line_bytes > 0) + { + for (std::size_t i = 0; i < len; ++i) + { + if (data[i] == '\n') + { + current_line = 0; + } + else + { + ++current_line; + if (current_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 = + (destination.size() < max_bytes) ? (max_bytes - destination.size()) + : 0; + const std::size_t to_store = std::min(len, remaining_cap); + if (to_store > 0) + { + destination.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; + } + + if (!stdin_done) + { + issue_write( + state.in, + std::span{ + reinterpret_cast(stdin_data.data()) + + stdin_offset, + stdin_data.size() - stdin_offset}); + } + if (!out_done) + { + issue_read(state.out, state.out.read_buf.size()); + } + if (!err_done) + { + issue_read(state.err, state.err.read_buf.size()); + } + + HANDLE events[3]{}; + int count = 0; + if (!stdin_done && state.in.write_pending) + { + events[count++] = state.in.event; + } + if (!out_done && state.out.read_pending) + { + events[count++] = state.out.event; + } + if (!err_done && state.err.read_pending) + { + events[count++] = state.err.event; + } + + int wait_ms = -1; + if (has_timeout) + { + const auto remaining = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (remaining <= 0) + { + res.timed_out = true; + break; + } + wait_ms = static_cast(std::min( + remaining, std::numeric_limits::max())); + } + if (stop.stop_possible()) + { + wait_ms = (wait_ms < 0) ? static_cast(kMaxWaitSliceMs) + : std::min(wait_ms, + static_cast(kMaxWaitSliceMs)); + } + if (count > 0) + { + (void)::WaitForMultipleObjects(static_cast(count), + events, + FALSE, + wait_ms < 0 ? INFINITE + : static_cast(wait_ms)); + } + + if (!stdin_done) + { + const std::size_t wrote = complete_write(state.in); + stdin_offset += wrote; + if (state.in.broken) + { + state.in.close(); + stdin_done = true; + } + else if (stdin_offset >= stdin_data.size()) + { + state.in.close(); + stdin_done = true; + } + } + + auto capture = [&](WinStream& stream, bool is_out, bool& done) { + DWORD got = 0; + const IoStatus status = complete_read(stream, got); + if (status == IoStatus::eof) + { + done = true; + stream.close(); + return; + } + if (status == IoStatus::error) + { + done = true; + io_failure = win_error( + map_process_error(stream.error), + "Process::communicate_blocking: read failed", + stream.error); + stream.close(); + return; + } + if (status != IoStatus::data || got == 0) + { + return; + } + if (!handle_read_chunk( + reinterpret_cast(stream.read_buf.data()), + got, + is_out)) + { + aborted = true; + } + 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); + } + }; + if (!out_done) + { + capture(state.out, true, out_done); + } + if (!err_done) + { + capture(state.err, false, err_done); + } + if (aborted || io_failure.has_value()) + { + 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); + } + + state.in.close(); + state.out.close(); + state.err.close(); + + 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 (io_failure.has_value()) + { + (void)child.terminate(); + return std::unexpected{std::move(*io_failure)}; + } + + 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 status = child.try_wait(); + status.has_value() && status->has_value()) + { + res.status = **status; + } + return res; + } + if (waited.error().kind() == Void::Result::ErrorKind::cancelled) + { + res.cancelled = true; + if (auto status = child.try_wait(); + status.has_value() && status->has_value()) + { + res.status = **status; + } + 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* callbacks) + { + SpawnOptions options; + options.executable = executable; + options.arguments = std::move(args); + options.search_path = true; + options.new_process_group = true; + + auto spawned = spawn(options); + if (!spawned.has_value()) + { + if (spawned.error().code().domain == + Void::Result::kSystemErrorDomain && + spawned.error().code().value == + static_cast( + Void::System::SystemErrorCode::exec_failed)) + { + Output output; + output.exit_code = 127; + return output; + } + 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; + limits.max_stdin_bytes = 64ULL * 1024ULL * 1024ULL; + limits.overflow_policy = OverflowPolicy::drain_and_truncate; + + auto communicated = communicate_blocking( + *spawned, stdin_data, limits, timeout, {}, callbacks); + if (!communicated.has_value()) + { + return std::unexpected{std::move(communicated.error())}; + } + Output output; + output.exit_code = + communicated->status.exited ? communicated->status.code : -1; + output.out = std::move(communicated->out); + output.err = std::move(communicated->err); + return output; + } + +} // 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(L"cmd.exe", {"/C", std::string{command}}, {}, timeout); +} + +Void::Result::Result reexec( + const std::filesystem::path&, const std::vector&) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::reexec: replacing the process image is not supported on " + "Windows")}; +} + +Void::Result::Result reexec( + const std::filesystem::path&, const std::vector&, bool) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::reexec: replacing the process image is not supported on " + "Windows")}; +} + +Void::Result::Result enable_subreaper() noexcept +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::enable_subreaper: Windows job objects already contain " + "descendants")}; +} + +} // namespace Void::Process + +#else + +// Keep the translation unit non-empty on non-Windows builds (the module +// source list is shared across platforms). +namespace Void::Process::Detail +{ +namespace +{ +[[maybe_unused]] constexpr int kWindowsBackendNotBuilt = 0; +} // namespace +} // namespace Void::Process::Detail + +#endif // _WIN32