Files
Library/src/System/ProcessWindows.cpp
T
faumaray 9f45841c7d Windows: port the process helper and fix a stdin deadlock
- Tests: build VoidProcessHelper on Windows with the fork/poll-based modes
  compiled out, binary stdio, and a Windows fd listing; enable the
  ProcessStream suite there.
- Process (Windows): communicate_blocking could block forever when the
  stdin write completed synchronously: the wait only armed pending
  operations, so the stdin pipe was never closed and the child never saw
  EOF. Complete ready operations before waiting, and report real EOF only
  when a read actually reached end of stream.
2026-12-06 15:42:31 +03:00

2640 lines
65 KiB
C++

// 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 <windows.h>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstring>
#include <expected>
#include <filesystem>
#include <format>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
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::size_t>(std::numeric_limits<int>::max()))
{
return false;
}
const int len = ::MultiByteToWideChar(CP_UTF8,
MB_ERR_INVALID_CHARS,
text.data(),
static_cast<int>(text.size()),
nullptr,
0);
if (len <= 0)
{
return false;
}
out.resize(static_cast<std::size_t>(len));
return ::MultiByteToWideChar(CP_UTF8,
MB_ERR_INVALID_CHARS,
text.data(),
static_cast<int>(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<int>(text.size()),
nullptr,
0,
nullptr,
nullptr);
if (len <= 0)
{
return {};
}
std::string out(static_cast<std::size_t>(len), '\0');
(void)::WideCharToMultiByte(CP_UTF8,
0,
text.data(),
static_cast<int>(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<std::size_t>(text.size(), 256));
for (char ch : text)
{
if (out.size() >= 256)
{
break;
}
const auto uc = static_cast<unsigned char>(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<int>(a.size()),
b.c_str(),
static_cast<int>(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<int>(a.size()),
b.data(),
static_cast<int>(b.size()),
TRUE) == CSTR_EQUAL;
}
[[nodiscard]] Void::Result::Result<std::vector<wchar_t>, 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<std::wstring> 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<std::wstring> 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<std::wstring, std::wstring, CaseInsensitiveLess> 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<wchar_t> 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<wchar_t> buffer(32768);
const DWORD len = ::SearchPathW(nullptr,
wide.c_str(),
L".exe",
static_cast<DWORD>(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<std::byte, 8192> read_buf{};
std::vector<std::byte> 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<OwnedHandle, Void::Result::Error>
create_pipe_end(bool parent_reads, WinStream& parent, const wchar_t* tag)
{
static std::atomic<unsigned long> 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<OwnedHandle, Void::Result::Error>
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<DWORD>(want),
&got,
&stream.ov) != 0)
{
// A zero-byte success is EOF; storing it as "ready" data would
// leave the caller with nothing to wait on (busy loop).
if (got == 0)
{
stream.eof = true;
}
else
{
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;
}
if (got == 0)
{
// Nothing ready is not EOF: a synchronous completion with zero
// bytes sets eof, a not-yet-completed read has neither.
return stream.eof ? IoStatus::eof : IoStatus::none;
}
bytes = got;
return IoStatus::data;
}
void issue_write(WinStream& stream,
std::span<const std::byte> 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<DWORD>(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<WindowsProcess> state) noexcept
{
child.pid_ = static_cast<long long>(state->pid);
child.pgid_ = static_cast<long long>(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<int>(code);
status.signal = 0;
status.raw_status = static_cast<int>(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<long long>(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<void, Void::Result::Error>
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<std::optional<ExitStatus>, 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<ExitStatus>{windows_->cached};
}
if (::WaitForSingleObject(windows_->process.get(), 0) != WAIT_OBJECT_0)
{
return std::optional<ExitStatus>{std::nullopt};
}
windows_->cached = read_exit_status(*windows_);
windows_->reaped = true;
cached_status_ = windows_->cached;
reaped_ = true;
return std::optional<ExitStatus>{windows_->cached};
}
Void::Result::Result<ExitStatus, Void::Result::Error>
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<ExitStatus, Void::Result::Error>
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<std::chrono::milliseconds>(
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<std::size_t>::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<void(std::string_view)>& 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<Child, Void::Result::Error>
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<Detail::WindowsProcess>();
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<std::byte> attribute_storage(attribute_size);
auto* attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(
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<DWORD>(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<wchar_t> 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<Child, Void::Result::Error> {
(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<DWORD>(-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<std::size_t>(1, options_.max_stdout_buffer);
options_.max_stderr_buffer =
std::max<std::size_t>(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, Void::Result::Error>
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<const std::byte> 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<DWORD>(timeout_ms);
(void)::WaitForMultipleObjects(
static_cast<DWORD>(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<std::byte>& 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<std::size_t>(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<std::ptrdiff_t>(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<BinaryTransfer, BinaryError> BinarySession::write_stdin(
std::span<const std::byte> 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<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0)
{
continue;
}
poll_timeout_ms = static_cast<int>(
std::min<long long>(remaining,
std::numeric_limits<int>::max()));
}
poll_timeout_ms = (poll_timeout_ms < 0)
? static_cast<int>(kMaxWaitSliceMs)
: std::min(poll_timeout_ms,
static_cast<int>(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<BinaryTransfer, BinaryError> BinarySession::read_stdout(
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return read_stream(true, out, timeout, stop);
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stderr(
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return read_stream(false, out, timeout, stop);
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stream(
bool is_stdout,
std::span<std::byte> 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<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0)
{
continue;
}
poll_timeout_ms = static_cast<int>(
std::min<long long>(remaining,
std::numeric_limits<int>::max()));
}
poll_timeout_ms = (poll_timeout_ms < 0)
? static_cast<int>(kMaxWaitSliceMs)
: std::min(poll_timeout_ms,
static_cast<int>(kMaxWaitSliceMs));
std::span<const std::byte> 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<std::ptrdiff_t>(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<std::ptrdiff_t>(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<void, Void::Result::Error> BinarySession::close_stdin()
{
if (stdin_closed_)
{
return {};
}
stdin_closed_ = true;
if (child_.windows_ != nullptr)
{
child_.windows_->in.close();
}
return {};
}
Void::Result::Result<ExitStatus, Void::Result::Error> 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<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
poll_timeout_ms = static_cast<int>(std::clamp<long long>(
remaining, 1, static_cast<long long>(poll_timeout_ms)));
}
std::span<const std::byte> 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<ExitStatus, Void::Result::Error> 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<CommunicateResult, Void::Result::Error>
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<Void::Result::Error> 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;
// One step of stdin progress: complete the write (sync or pending) and
// close the pipe as soon as the payload is delivered.
auto advance_stdin = [&] {
if (stdin_done)
{
return;
}
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<const char*>(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);
}
};
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<const std::byte>{
reinterpret_cast<const std::byte*>(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());
}
// Complete operations that finished synchronously before blocking on
// the still-pending ones: a completed stdin write must close the pipe
// even when every read is still pending, or the child never sees EOF.
advance_stdin();
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;
}
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<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0)
{
res.timed_out = true;
break;
}
wait_ms = static_cast<int>(std::min<long long>(
remaining, std::numeric_limits<int>::max()));
}
if (stop.stop_possible())
{
wait_ms = (wait_ms < 0) ? static_cast<int>(kMaxWaitSliceMs)
: std::min(wait_ms,
static_cast<int>(kMaxWaitSliceMs));
}
if (count > 0)
{
(void)::WaitForMultipleObjects(static_cast<DWORD>(count),
events,
FALSE,
wait_ms < 0 ? INFINITE
: static_cast<DWORD>(wait_ms));
}
advance_stdin();
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<std::chrono::milliseconds>(
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<Output, Void::Result::Error>
run_legacy_impl(const std::filesystem::path& executable,
std::vector<std::string> 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<std::int32_t>(
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<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> 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<Output, Void::Result::Error> run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> 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<Output, Void::Result::Error>
shell(std::string_view command, std::chrono::milliseconds timeout)
{
return run(L"cmd.exe", {"/C", std::string{command}}, {}, timeout);
}
Void::Result::Result<void, Void::Result::Error> reexec(
const std::filesystem::path&, const std::vector<std::string>&)
{
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<void, Void::Result::Error> reexec(
const std::filesystem::path&, const std::vector<std::string>&, 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<void, Void::Result::Error> 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