Skip to content

Truly independent web browser

LibCore: Allow passing descriptors to spawned processes on Windows

Zaggy1024c229404e2f2a
diff --git a/Libraries/LibCore/ProcessWindows.cpp b/Libraries/LibCore/ProcessWindows.cpp
index 42857c8f611..1c6b502e840 100644
--- a/Libraries/LibCore/ProcessWindows.cpp
+++ b/Libraries/LibCore/ProcessWindows.cpp
@@ -8,13 +8,16 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Array.h>
#include <AK/Assertions.h>
+#include <AK/ByteBuffer.h>
#include <AK/ScopeGuard.h>
#include <AK/String.h>
#include <AK/Utf16View.h>
#include <AK/Vector.h>
#include <AK/Windows.h>
#include <LibCore/Process.h>
+#include <LibCore/System.h>
namespace Core {
@@ -40,13 +43,80 @@ Process Process::current()
return GetCurrentProcess();
}
+static ErrorOr<HANDLE> duplicate_inheritable_handle(HANDLE handle)
+{
+ HANDLE duplicate = nullptr;
+ if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &duplicate, 0, TRUE, DUPLICATE_SAME_ACCESS))
+ return Error::from_windows_error();
+ return duplicate;
+}
+
ErrorOr<Process> Process::spawn(ProcessSpawnOptions const& options)
{
- // file actions are not supported
- VERIFY(options.file_actions.is_empty());
// FIXME: Pass a custom environment to CreateProcess.
VERIFY(!options.environment.has_value());
+ // The child inherits only the handles listed for it, as posix_spawn's file actions give a child only the
+ // descriptors they name, so a handle passed to one child never reaches another spawned meanwhile.
+ Vector<HANDLE> inherited_handles;
+ Vector<HANDLE> handles_to_make_uninheritable;
+ Vector<HANDLE> duplicates_to_close;
+ ScopeGuard clean_up_handles = [&] {
+ for (auto* handle : handles_to_make_uninheritable)
+ SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
+ for (auto* handle : duplicates_to_close)
+ CloseHandle(handle);
+ };
+
+ Array<HANDLE, 3> standard_handles { GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE) };
+ // The standard descriptor numbers are this process's own standard handles, which all share one value where it has
+ // none, so an action takes the first matching stream that no earlier action took.
+ Array<int, 3> standard_fds { STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO };
+ Array<bool, 3> standard_handle_is_redirected {};
+ for (auto const& file_action : options.file_actions) {
+ TRY(file_action.visit(
+ [&](FileAction::DupFd const& action) -> ErrorOr<void> {
+ auto handle = to_handle(action.write_fd);
+ for (size_t index : { 1uz, 2uz, 0uz }) {
+ if (action.fd != standard_fds[index] || standard_handle_is_redirected[index])
+ continue;
+ standard_handles[index] = handle;
+ standard_handle_is_redirected[index] = true;
+ return {};
+ }
+ // A handle cannot be renumbered, but an inherited handle keeps its value in the child.
+ if (action.fd != action.write_fd)
+ return Error::from_string_literal("A handle can only reach a child process under its own value");
+ if (inherited_handles.contains_slow(handle))
+ return {};
+ DWORD flags = 0;
+ if (!GetHandleInformation(handle, &flags))
+ return Error::from_windows_error();
+ if (!(flags & HANDLE_FLAG_INHERIT)) {
+ if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
+ return Error::from_windows_error();
+ handles_to_make_uninheritable.append(handle);
+ }
+ TRY(inherited_handles.try_append(handle));
+ return {};
+ },
+ [](auto const&) -> ErrorOr<void> {
+ return Error::from_string_literal("This file action is not supported on Windows");
+ }));
+ }
+
+ // The child finds its standard handles in its startup info, so each is passed as a duplicate that is inheritable
+ // for this spawn alone.
+ bool has_standard_handles = false;
+ for (auto& handle : standard_handles) {
+ if (!handle || handle == INVALID_HANDLE_VALUE)
+ continue;
+ handle = TRY(duplicate_inheritable_handle(handle));
+ TRY(duplicates_to_close.try_append(handle));
+ TRY(inherited_handles.try_append(handle));
+ has_standard_handles = true;
+ }
+
StringBuilder builder;
if (!options.search_for_executable_in_path && !options.executable.find_any_of("\\/:"sv).has_value())
builder.appendff("\"./{}\" ", options.executable);
@@ -59,19 +129,45 @@ ErrorOr<Process> Process::spawn(ProcessSpawnOptions const& options)
builder.append('\0');
ByteBuffer command_line = TRY(builder.to_byte_buffer());
- STARTUPINFO startup_info = {};
+ STARTUPINFOEXA startup_info = {};
+ startup_info.StartupInfo.cb = sizeof(startup_info);
+ if (has_standard_handles) {
+ startup_info.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
+ startup_info.StartupInfo.hStdInput = standard_handles[0];
+ startup_info.StartupInfo.hStdOutput = standard_handles[1];
+ startup_info.StartupInfo.hStdError = standard_handles[2];
+ }
+
+ ByteBuffer attribute_list_storage;
+ if (!inherited_handles.is_empty()) {
+ SIZE_T attribute_list_size = 0;
+ InitializeProcThreadAttributeList(nullptr, 1, 0, &attribute_list_size);
+ attribute_list_storage = TRY(ByteBuffer::create_zeroed(attribute_list_size));
+ startup_info.lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(attribute_list_storage.data());
+ if (!InitializeProcThreadAttributeList(startup_info.lpAttributeList, 1, 0, &attribute_list_size))
+ return Error::from_windows_error();
+ }
+ ScopeGuard delete_attribute_list = [&] {
+ if (startup_info.lpAttributeList)
+ DeleteProcThreadAttributeList(startup_info.lpAttributeList);
+ };
+ if (startup_info.lpAttributeList) {
+ if (!UpdateProcThreadAttribute(startup_info.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, static_cast<void*>(inherited_handles.data()), inherited_handles.size() * sizeof(HANDLE), nullptr, nullptr))
+ return Error::from_windows_error();
+ }
+
PROCESS_INFORMATION process_info = {};
- BOOL result = CreateProcess(
+ BOOL result = CreateProcessA(
NULL,
(char*)command_line.data(),
NULL, // process security attributes
NULL, // primary thread security attributes
- TRUE, // handles are inherited
- 0, // creation flags
+ !inherited_handles.is_empty(),
+ EXTENDED_STARTUPINFO_PRESENT,
NULL, // use parent's environment
NULL, // working directory
- &startup_info,
+ &startup_info.StartupInfo,
&process_info);
if (!result)
diff --git a/Libraries/LibCore/SocketpairWindows.cpp b/Libraries/LibCore/SocketpairWindows.cpp
index ee15529c169..038e4e8621d 100644
--- a/Libraries/LibCore/SocketpairWindows.cpp
+++ b/Libraries/LibCore/SocketpairWindows.cpp
@@ -41,7 +41,10 @@ int windows_socketpair(SOCKET socks[2], int make_overlapped)
SOCKET listener;
int e;
socklen_t addrlen = sizeof(a.inaddr);
- DWORD flags = (make_overlapped ? WSA_FLAG_OVERLAPPED : 0);
+ // Like SOCK_CLOEXEC, the sockets are not inherited by processes spawned later.
+ DWORD flags = WSA_FLAG_NO_HANDLE_INHERIT;
+ if (make_overlapped)
+ flags |= WSA_FLAG_OVERLAPPED;
int reuse = 1;
if (socks == 0) {
@@ -50,7 +53,7 @@ int windows_socketpair(SOCKET socks[2], int make_overlapped)
}
socks[0] = socks[1] = -1;
- listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ listener = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT);
if (listener == INVALID_SOCKET)
return SOCKET_ERROR;
@@ -85,6 +88,8 @@ int windows_socketpair(SOCKET socks[2], int make_overlapped)
socks[1] = ::accept(listener, NULL, NULL);
if (socks[1] == INVALID_SOCKET)
break;
+ if (!SetHandleInformation(reinterpret_cast<HANDLE>(socks[1]), HANDLE_FLAG_INHERIT, 0))
+ break;
closesocket(listener);
return 0;