Skip to content

Truly independent web browser

AK+LibCore+test-web: Implement pipe notifiers on Windows

Zaggy1024c10840697f5b
diff --git a/AK/Windows.h b/AK/Windows.h
index f30c37a7e5b..665db84029a 100644
--- a/AK/Windows.h
+++ b/AK/Windows.h
@@ -47,6 +47,15 @@ NTAPI NTSTATUS NtCreateWaitCompletionPacket(
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes);
+// https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryinformationfile
+NTAPI NTSTATUS NtQueryInformationFile(
+ _In_ HANDLE FileHandle,
+ _Out_ PIO_STATUS_BLOCK IoStatusBlock,
+ _Out_ PVOID FileInformation,
+ _In_ ULONG Length,
+ // winternl.h's FILE_INFORMATION_CLASS lacks most of the classes, so the class is taken as its value.
+ _In_ ULONG FileInformationClass);
+
// https://learn.microsoft.com/en-us/windows/win32/seccng/processprng
BOOL WINAPI ProcessPrng(PBYTE pbData, SIZE_T cbData);
}
@@ -54,12 +63,14 @@ BOOL WINAPI ProcessPrng(PBYTE pbData, SIZE_T cbData);
using PFN_NtCreateWaitCompletionPacket = decltype(&NtCreateWaitCompletionPacket);
using PFN_NtCancelWaitCompletionPacket = decltype(&NtCancelWaitCompletionPacket);
using PFN_NtAssociateWaitCompletionPacket = decltype(&NtAssociateWaitCompletionPacket);
+using PFN_NtQueryInformationFile = decltype(&NtQueryInformationFile);
using PFN_ProcessPrng = decltype(&ProcessPrng);
inline struct SystemApi {
PFN_NtAssociateWaitCompletionPacket NtAssociateWaitCompletionPacket = NULL;
PFN_NtCancelWaitCompletionPacket NtCancelWaitCompletionPacket = NULL;
PFN_NtCreateWaitCompletionPacket NtCreateWaitCompletionPacket = NULL;
+ PFN_NtQueryInformationFile NtQueryInformationFile = NULL;
PFN_ProcessPrng ProcessPrng = NULL;
SystemApi()
@@ -72,10 +83,12 @@ inline struct SystemApi {
NtAssociateWaitCompletionPacket = (PFN_NtAssociateWaitCompletionPacket)GetProcAddress(hNtdll, "NtAssociateWaitCompletionPacket");
NtCancelWaitCompletionPacket = (PFN_NtCancelWaitCompletionPacket)GetProcAddress(hNtdll, "NtCancelWaitCompletionPacket");
NtCreateWaitCompletionPacket = (PFN_NtCreateWaitCompletionPacket)GetProcAddress(hNtdll, "NtCreateWaitCompletionPacket");
+ NtQueryInformationFile = (PFN_NtQueryInformationFile)GetProcAddress(hNtdll, "NtQueryInformationFile");
ProcessPrng = (PFN_ProcessPrng)GetProcAddress(hBcryptprimitives, "ProcessPrng");)
VERIFY(NtAssociateWaitCompletionPacket);
VERIFY(NtCancelWaitCompletionPacket);
VERIFY(NtCreateWaitCompletionPacket);
+ VERIFY(NtQueryInformationFile);
VERIFY(ProcessPrng);
}
} g_system;
diff --git a/Libraries/LibCore/EventLoopImplementationWindows.cpp b/Libraries/LibCore/EventLoopImplementationWindows.cpp
index e574499446e..f22bea32622 100644
--- a/Libraries/LibCore/EventLoopImplementationWindows.cpp
+++ b/Libraries/LibCore/EventLoopImplementationWindows.cpp
@@ -21,6 +21,7 @@
#include <AK/kmalloc.h>
#include <LibCore/EventLoopImplementationWindows.h>
#include <LibCore/Notifier.h>
+#include <LibCore/System.h>
#include <LibCore/ThreadEventQueue.h>
#include <LibCore/TimeoutSet.h>
#include <LibCore/Timer.h>
@@ -74,6 +75,7 @@ enum class CompletionType : u8 {
Wake,
Timer,
Notifer,
+ PipeNotifier,
Process,
Signal,
};
@@ -207,6 +209,15 @@ struct EventLoopNotifier final : CompletionPacket {
OwnHandle wait_event;
};
+struct EventLoopPipeNotifier final : CompletionPacket {
+ Notifier* notifier;
+ OwnHandle wait_packet;
+ OwnHandle wait_event;
+ HANDLE pipe_handle { nullptr };
+ OVERLAPPED pipe_read {};
+ bool pipe_read_is_pending { false };
+};
+
struct EventLoopProcess final : CompletionPacket {
~EventLoopProcess() = default;
@@ -262,6 +273,12 @@ struct ThreadData {
// These are only used to register and unregister. The event loop doesn't access these.
HashMap<Notifier*, NonnullOwnPtr<EventLoopNotifier>> notifiers;
+ HashMap<Notifier*, NonnullOwnPtr<EventLoopPipeNotifier>> pipe_notifiers;
+
+ // Pipe notifiers whose activation has been posted. Each reads its pipe again only on the next pump, once its
+ // activation has been handled, so that it activates again only if there is still something to read, as a poll()
+ // would report.
+ Vector<EventLoopPipeNotifier*, 8> pipe_notifiers_to_rearm;
// Owns the timer allocations; ids stay valid until unregister_timer even after a one-shot timer fires.
HashMap<intptr_t, NonnullOwnPtr<EventLoopTimer>> timers;
@@ -332,11 +349,55 @@ int EventLoopImplementationWindows::exec()
static constexpr bool debug_event_loop = false;
+static bool handle_is_overlapped(HANDLE handle)
+{
+ constexpr ULONG file_mode_information = 16;
+ constexpr ULONG synchronous_io_alert = 0x10;
+ constexpr ULONG synchronous_io_nonalert = 0x20;
+
+ IO_STATUS_BLOCK io_status {};
+ ULONG mode = 0;
+ NTSTATUS status = g_system.NtQueryInformationFile(handle, &io_status, &mode, sizeof(mode), file_mode_information);
+ VERIFY(NT_SUCCESS(status));
+ return !(mode & (synchronous_io_alert | synchronous_io_nonalert));
+}
+
+static void read_pipe_until_readable(EventLoopPipeNotifier& notifier_data)
+{
+ static u8 s_zero_byte_buffer;
+ notifier_data.pipe_read = {};
+ notifier_data.pipe_read.hEvent = notifier_data.wait_event.handle;
+ notifier_data.pipe_read_is_pending = false;
+ if (ReadFile(notifier_data.pipe_handle, &s_zero_byte_buffer, 0, nullptr, &notifier_data.pipe_read))
+ return;
+ if (GetLastError() == ERROR_IO_PENDING) {
+ notifier_data.pipe_read_is_pending = true;
+ return;
+ }
+ // A read that fails at once, as one does at the end of the pipe, does not set the event, but the reader must still
+ // be activated to see it.
+ SetEvent(notifier_data.wait_event.handle);
+}
+
+static void cancel_pipe_read(EventLoopPipeNotifier& notifier_data)
+{
+ if (!notifier_data.pipe_read_is_pending || HasOverlappedIoCompleted(&notifier_data.pipe_read))
+ return;
+ CancelIoEx(notifier_data.pipe_handle, &notifier_data.pipe_read);
+ // The read must have stopped writing to pipe_read before it can be freed.
+ while (!HasOverlappedIoCompleted(&notifier_data.pipe_read))
+ WaitForSingleObject(notifier_data.wait_event.handle, INFINITE);
+}
+
size_t EventLoopImplementationWindows::pump(PumpMode pump_mode)
{
auto& event_queue = ThreadEventQueue::current();
auto* thread_data = ThreadData::the();
+ for (auto* notifier_data : thread_data->pipe_notifiers_to_rearm)
+ read_pipe_until_readable(*notifier_data);
+ thread_data->pipe_notifiers_to_rearm.clear();
+
// NOTE: The number of entries to dequeue is to be optimized. Ideally we always dequeue all outstanding packets,
// but we don't want to increase the cost of each pump unnecessarily. If more than one entry is never dequeued
// at once, we could switch to using GetQueuedCompletionStatus which directly returns the values.
@@ -390,6 +451,14 @@ size_t EventLoopImplementationWindows::pump(PumpMode pump_mode)
VERIFY(NT_SUCCESS(status));
continue;
}
+ if (packet->type == CompletionType::PipeNotifier) {
+ auto* notifier_data = static_cast<EventLoopPipeNotifier*>(packet);
+ event_queue.post_event(notifier_data->notifier, Core::Event::Type::NotifierActivation);
+ NTSTATUS status = g_system.NtAssociateWaitCompletionPacket(notifier_data->wait_packet.handle, thread_data->iocp.handle, notifier_data->wait_event.handle, notifier_data, NULL, 0, 0, NULL);
+ VERIFY(NT_SUCCESS(status));
+ thread_data->pipe_notifiers_to_rearm.append(notifier_data);
+ continue;
+ }
if (packet->type == CompletionType::Process) {
auto* process_data = static_cast<EventLoopProcess*>(packet);
pid_t const process_id = process_data->pid;
@@ -457,14 +526,50 @@ static int notifier_type_to_network_event(NotificationType type)
return events;
}
+static void register_pipe_notifier(ThreadData& thread_data, Notifier& notifier)
+{
+ auto* handle = to_handle(notifier.fd());
+ VERIFY(!has_flag(notifier.type(), NotificationType::Write));
+ // A zero-byte read of a pipe that is not overlapped would block until there is data. Pipes from pipe2() are
+ // overlapped unless they are read by another process.
+ VERIFY(handle_is_overlapped(handle));
+
+ auto notifier_data = make<EventLoopPipeNotifier>();
+ notifier_data->type = CompletionType::PipeNotifier;
+ notifier_data->notifier = &notifier;
+ notifier_data->wait_event.handle = CreateEvent(NULL, FALSE, FALSE, NULL);
+ VERIFY(notifier_data->wait_event.handle);
+ notifier_data->pipe_handle = handle;
+ NTSTATUS status = g_system.NtCreateWaitCompletionPacket(&notifier_data->wait_packet.handle, GENERIC_READ | GENERIC_WRITE, NULL);
+ VERIFY(NT_SUCCESS(status));
+ status = g_system.NtAssociateWaitCompletionPacket(notifier_data->wait_packet.handle, thread_data.iocp.handle, notifier_data->wait_event.handle, notifier_data.ptr(), NULL, 0, 0, NULL);
+ VERIFY(NT_SUCCESS(status));
+ read_pipe_until_readable(*notifier_data);
+ thread_data.pipe_notifiers.set(&notifier, move(notifier_data));
+}
+
+static void unregister_pipe_notifier(ThreadData& thread_data, NonnullOwnPtr<EventLoopPipeNotifier> notifier_data)
+{
+ // We are removing the signalled packets since the caller no longer expects them
+ NTSTATUS status = g_system.NtCancelWaitCompletionPacket(notifier_data->wait_packet.handle, TRUE);
+ VERIFY(NT_SUCCESS(status));
+ thread_data.pipe_notifiers_to_rearm.remove_first_matching([&](auto* entry) { return entry == notifier_data.ptr(); });
+ cancel_pipe_read(*notifier_data);
+}
+
void EventLoopManagerWindows::register_notifier(Notifier& notifier)
{
auto* thread_data = ThreadData::the();
auto& notifiers = thread_data->notifiers;
- if (notifiers.contains(&notifier))
+ if (notifiers.contains(&notifier) || thread_data->pipe_notifiers.contains(&notifier))
return;
+ if (!System::is_socket(notifier.fd()) && GetFileType(to_handle(notifier.fd())) == FILE_TYPE_PIPE) {
+ register_pipe_notifier(*thread_data, notifier);
+ return;
+ }
+
HANDLE event = CreateEvent(NULL, FALSE, FALSE, NULL);
VERIFY(event);
int rc = WSAEventSelect(notifier.fd(), event, notifier_type_to_network_event(notifier.type()));
@@ -486,8 +591,12 @@ void EventLoopManagerWindows::unregister_notifier(Notifier& notifier)
auto* thread_data = ThreadData::the();
VERIFY(thread_data);
- auto& notifiers = thread_data->notifiers;
- auto maybe_notifier_data = notifiers.take(&notifier);
+ if (auto notifier_data = thread_data->pipe_notifiers.take(&notifier); notifier_data.has_value()) {
+ unregister_pipe_notifier(*thread_data, notifier_data.release_value());
+ return;
+ }
+
+ auto maybe_notifier_data = thread_data->notifiers.take(&notifier);
if (!maybe_notifier_data.has_value())
return;
auto notifier_data = move(maybe_notifier_data.value());
diff --git a/Libraries/LibCore/FileWindows.cpp b/Libraries/LibCore/FileWindows.cpp
index 05c266ee58a..39027f92a33 100644
--- a/Libraries/LibCore/FileWindows.cpp
+++ b/Libraries/LibCore/FileWindows.cpp
@@ -125,6 +125,26 @@ ErrorOr<void> File::open_path(StringView filename, mode_t)
return {};
}
+// A pipe's read end that this process reads is overlapped (see System::pipe2()), so it can only be read with an
+// OVERLAPPED of its own, waited for to read the way POSIX read() does. A pipe end that is not overlapped reads the same
+// way, completing at once.
+static DWORD read_pipe(HANDLE handle, Bytes buffer, DWORD& n_read)
+{
+ OVERLAPPED overlapped {};
+ overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+ if (!overlapped.hEvent)
+ return GetLastError();
+
+ DWORD error = ERROR_SUCCESS;
+ if (!ReadFile(handle, buffer.data(), buffer.size(), &n_read, &overlapped)) {
+ error = GetLastError();
+ if (error == ERROR_IO_PENDING)
+ error = GetOverlappedResult(handle, &overlapped, &n_read, TRUE) ? ERROR_SUCCESS : GetLastError();
+ }
+ CloseHandle(overlapped.hEvent);
+ return error;
+}
+
ErrorOr<Bytes> File::read_some(Bytes buffer)
{
if (!has_flag(m_mode, OpenMode::Read)) {
@@ -132,9 +152,14 @@ ErrorOr<Bytes> File::read_some(Bytes buffer)
return Error::from_errno(EBADF);
}
+ auto handle = to_handle(m_fd);
DWORD n_read = 0;
- if (!ReadFile(to_handle(m_fd), buffer.data(), buffer.size(), &n_read, nullptr)) {
- auto error = GetLastError();
+ DWORD error = ERROR_SUCCESS;
+ if (GetFileType(handle) == FILE_TYPE_PIPE)
+ error = read_pipe(handle, buffer, n_read);
+ else if (!ReadFile(handle, buffer.data(), buffer.size(), &n_read, nullptr))
+ error = GetLastError();
+ if (error != ERROR_SUCCESS) {
// Reading a pipe whose write end has closed fails with ERROR_BROKEN_PIPE once
// drained; POSIX read() reports that (and end-of-file) as reading 0 bytes.
if (error != ERROR_BROKEN_PIPE && error != ERROR_HANDLE_EOF)
diff --git a/Libraries/LibCore/System.cpp b/Libraries/LibCore/System.cpp
index a84c597b073..202d98664c4 100644
--- a/Libraries/LibCore/System.cpp
+++ b/Libraries/LibCore/System.cpp
@@ -756,7 +756,7 @@ ErrorOr<void> socketpair(int domain, int type, int protocol, int sv[2])
return {};
}
-ErrorOr<Array<int, 2>> pipe2(int flags)
+ErrorOr<Array<int, 2>> pipe2(int flags, PipeReadEnd)
{
Array<int, 2> fds;
diff --git a/Libraries/LibCore/System.h b/Libraries/LibCore/System.h
index 39ad81470d8..70140573fd1 100644
--- a/Libraries/LibCore/System.h
+++ b/Libraries/LibCore/System.h
@@ -147,7 +147,14 @@ CORE_API ErrorOr<void> map_shared_memory_fixed(void* address, size_t size, int f
CORE_API ErrorOr<void> close(int fd);
CORE_API ErrorOr<int> dup(int source_fd);
-CORE_API ErrorOr<Array<int, 2>> pipe2(int flags);
+// Whether a pipe's read end is read by this process's own code, or by another process's, such as a child that is given
+// it as its standard input. On Windows, a Notifier can only watch a read end that is read internally, and only one that
+// is read externally can be read by code that does not use overlapped I/O.
+enum class PipeReadEnd : u8 {
+ ReadInternally,
+ ReadExternally,
+};
+CORE_API ErrorOr<Array<int, 2>> pipe2(int flags, PipeReadEnd = PipeReadEnd::ReadInternally);
CORE_API ErrorOr<void> set_close_on_exec(int fd, bool enabled);
CORE_API bool is_socket(int fd);
diff --git a/Libraries/LibCore/SystemWindows.cpp b/Libraries/LibCore/SystemWindows.cpp
index 1aefd9c90f6..86d31dbcd6d 100644
--- a/Libraries/LibCore/SystemWindows.cpp
+++ b/Libraries/LibCore/SystemWindows.cpp
@@ -14,6 +14,7 @@
#include <AK/Array.h>
#include <AK/ByteString.h>
#include <AK/Checked.h>
+#include <AK/Random.h>
#include <LibCore/MappedFile.h>
#include <LibCore/Process.h>
#include <LibCore/SocketAddress.h>
@@ -293,17 +294,31 @@ ErrorOr<void> set_close_on_exec(int handle, bool enabled)
return {};
}
-ErrorOr<Array<int, 2>> pipe2(int flags)
+ErrorOr<Array<int, 2>> pipe2(int flags, PipeReadEnd read_end)
{
SECURITY_ATTRIBUTES sa = {};
sa.nLength = sizeof(sa);
sa.bInheritHandle = (flags & O_CLOEXEC) ? FALSE : TRUE;
- HANDLE read_handle = nullptr;
- HANDLE write_handle = nullptr;
- if (!CreatePipe(&read_handle, &write_handle, &sa, 0))
+ // Only a named pipe can have an overlapped end, which a Notifier needs to watch it. The name is unpredictable, and
+ // the pipe has a single instance, so no other process can take either end of it.
+ auto name = ByteString::formatted("\\\\.\\pipe\\ladybird-{}-{:016x}", GetCurrentProcessId(), get_random<u64>());
+
+ DWORD read_end_flags = PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE;
+ if (read_end == PipeReadEnd::ReadInternally)
+ read_end_flags |= FILE_FLAG_OVERLAPPED;
+ constexpr DWORD buffer_size = 64 * KiB;
+ HANDLE read_handle = CreateNamedPipeA(name.characters(), read_end_flags, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, 0, buffer_size, 0, &sa);
+ if (read_handle == INVALID_HANDLE_VALUE)
return Error::from_windows_error();
+ HANDLE write_handle = CreateFileA(name.characters(), GENERIC_WRITE, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
+ if (write_handle == INVALID_HANDLE_VALUE) {
+ auto error = GetLastError();
+ CloseHandle(read_handle);
+ return Error::from_windows_error(error);
+ }
+
return Array<int, 2> { to_fd(read_handle), to_fd(write_handle) };
}
diff --git a/Tests/LibWeb/test-web/Fixture.cpp b/Tests/LibWeb/test-web/Fixture.cpp
index 447f399744c..0d517e3b62d 100644
--- a/Tests/LibWeb/test-web/Fixture.cpp
+++ b/Tests/LibWeb/test-web/Fixture.cpp
@@ -63,7 +63,7 @@ ErrorOr<void> HttpEchoServerFixture::setup(WebView::WebContentOptions& web_conte
// FIXME: Pick a more reasonable log path that is more observable
auto const log_path = LexicalPath::join(Core::StandardPaths::tempfile_directory(), "http-test-server.log"sv).string();
- auto stdin_fds = TRY(Core::System::pipe2(O_CLOEXEC));
+ auto stdin_fds = TRY(Core::System::pipe2(O_CLOEXEC, Core::System::PipeReadEnd::ReadExternally));
auto stdout_fds = TRY(Core::System::pipe2(O_CLOEXEC));
auto stderr_file = TRY(Core::File::open(ByteString::formatted("{}.stderr", log_path), Core::File::OpenMode::Write));