Skip to content

Truly independent web browser

LibIPC: Let an observer see messages on the IO thread

Andreas Klingd3c55ca5503b
diff --git a/Libraries/LibIPC/TransportMachPort.cpp b/Libraries/LibIPC/TransportMachPort.cpp
index 0df1d47142d..429a74d762b 100644
--- a/Libraries/LibIPC/TransportMachPort.cpp
+++ b/Libraries/LibIPC/TransportMachPort.cpp
@@ -282,6 +282,8 @@ void TransportMachPort::mark_peer_eof()
{
MutexLocker locker(m_incoming_mutex);
m_peer_eof = true;
+ if (m_incoming_message_observer)
+ m_incoming_message_observer({});
should_write_notification = schedule_read_notification_if_needed_locked();
}
m_incoming_cv.broadcast();
@@ -602,6 +604,8 @@ void TransportMachPort::process_received_message(u8* buffer)
bool should_write_notification = false;
{
MutexLocker locker(m_incoming_mutex);
+ if (m_incoming_message_observer)
+ m_incoming_message_observer(message->bytes.bytes());
auto const was_empty = m_incoming_messages.is_empty();
m_incoming_messages.append(move(message));
if (was_empty)
@@ -612,6 +616,12 @@ void TransportMachPort::process_received_message(u8* buffer)
write_read_notification_byte();
}
+void TransportMachPort::set_incoming_message_observer(Function<void(ReadonlyBytes)> observer)
+{
+ MutexLocker locker(m_incoming_mutex);
+ m_incoming_message_observer = move(observer);
+}
+
void TransportMachPort::set_up_read_hook(Function<void()> hook)
{
m_on_read_hook = move(hook);
diff --git a/Libraries/LibIPC/TransportMachPort.h b/Libraries/LibIPC/TransportMachPort.h
index b846c426554..80f342db397 100644
--- a/Libraries/LibIPC/TransportMachPort.h
+++ b/Libraries/LibIPC/TransportMachPort.h
@@ -49,6 +49,12 @@ public:
~TransportMachPort();
void set_up_read_hook(Function<void()>);
+
+ // Sets what the IO thread shows every message that arrives, before the transport's owner gets to see it, and empty
+ // bytes once the peer is gone. This is for a thread that does not get back to its event loop on its own, like one
+ // stuck in script. It runs while the IO thread holds a lock, so it should only have a look.
+ void set_incoming_message_observer(Function<void(ReadonlyBytes)>);
+
bool is_open() const;
void close();
@@ -138,6 +144,7 @@ private:
Mutex m_incoming_mutex;
ConditionVariable m_incoming_cv { m_incoming_mutex };
Vector<NonnullOwnPtr<Message>> m_incoming_messages;
+ Function<void(ReadonlyBytes)> m_incoming_message_observer;
u64 m_receive_barriers_sent { 0 };
u64 m_receive_barriers_received { 0 };
bool m_read_notification_pending { false };
diff --git a/Libraries/LibIPC/TransportSocket.cpp b/Libraries/LibIPC/TransportSocket.cpp
index ff12f32060a..e1eae92114f 100644
--- a/Libraries/LibIPC/TransportSocket.cpp
+++ b/Libraries/LibIPC/TransportSocket.cpp
@@ -334,6 +334,8 @@ intptr_t TransportSocket::io_thread_loop()
MutexLocker locker(m_incoming_mutex);
m_peer_eof = true;
m_incoming_eof = true;
+ if (m_incoming_message_observer)
+ m_incoming_message_observer({});
m_incoming_cv.broadcast();
notify_read_available();
}
@@ -765,6 +767,10 @@ TransportSocket::MoreToRead TransportSocket::read_incoming_messages()
bool const peer_eof = m_peer_eof;
if (!batch.is_empty() || peer_eof) {
MutexLocker locker(m_incoming_mutex);
+ if (m_incoming_message_observer) {
+ for (auto const& message : batch)
+ m_incoming_message_observer(message->bytes.bytes());
+ }
if (!batch.is_empty())
m_incoming_messages.extend(move(batch));
// Publish EOF only after the final batch is appended — under the same lock the consumer drains with — so that a
@@ -778,6 +784,12 @@ TransportSocket::MoreToRead TransportSocket::read_incoming_messages()
return peer_eof ? MoreToRead::No : more_to_read;
}
+void TransportSocket::set_incoming_message_observer(Function<void(ReadonlyBytes)> observer)
+{
+ MutexLocker locker(m_incoming_mutex);
+ m_incoming_message_observer = move(observer);
+}
+
TransportSocket::ShouldShutdown TransportSocket::read_as_many_messages_as_possible_without_blocking(Function<void(Message&&)>&& callback)
{
Vector<NonnullOwnPtr<Message>> messages;
diff --git a/Libraries/LibIPC/TransportSocket.h b/Libraries/LibIPC/TransportSocket.h
index 1fa02409d2b..d9b23f7846a 100644
--- a/Libraries/LibIPC/TransportSocket.h
+++ b/Libraries/LibIPC/TransportSocket.h
@@ -99,6 +99,12 @@ public:
~TransportSocket();
void set_up_read_hook(Function<void()>);
+
+ // Sets what the IO thread shows every message that arrives, before the transport's owner gets to see it, and empty
+ // bytes once the peer is gone. This is for a thread that does not get back to its event loop on its own, like one
+ // stuck in script. It runs while the IO thread holds a lock, so it should only have a look.
+ void set_incoming_message_observer(Function<void(ReadonlyBytes)>);
+
bool is_open() const;
void close();
@@ -181,6 +187,7 @@ private:
Mutex m_incoming_mutex;
ConditionVariable m_incoming_cv { m_incoming_mutex };
Vector<NonnullOwnPtr<Message>> m_incoming_messages;
+ Function<void(ReadonlyBytes)> m_incoming_message_observer;
// True while the IO thread is between reading the socket and appending what it read.
bool m_read_in_progress { false };
// Consumer-visible EOF, guarded by m_incoming_mutex. Distinct from m_peer_eof. This is set only after the final
diff --git a/Libraries/LibIPC/TransportWindows.cpp b/Libraries/LibIPC/TransportWindows.cpp
index 9c3a678cb46..f43fee745c0 100644
--- a/Libraries/LibIPC/TransportWindows.cpp
+++ b/Libraries/LibIPC/TransportWindows.cpp
@@ -6,11 +6,13 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AtomicRefCounted.h>
#include <AK/Checked.h>
#include <AK/NumericLimits.h>
#include <AK/Random.h>
#include <AK/ScopeGuard.h>
#include <LibCore/AnonymousBuffer.h>
+#include <LibCore/EventLoop.h>
#include <LibCore/Notifier.h>
#include <LibCore/Socket.h>
#include <LibCore/System.h>
@@ -18,6 +20,7 @@
#include <LibIPC/Limits.h>
#include <LibIPC/TransportHandle.h>
#include <LibIPC/TransportWindows.h>
+#include <LibThreading/Thread.h>
#include <AK/Windows.h>
@@ -44,6 +47,22 @@ static constexpr size_t MAX_UNPROCESSED_BUFFER_SIZE = 128 * MiB;
// A send that cannot complete at once waits in slices this long, so that closing the transport ends the wait.
static constexpr DWORD SEND_WAIT_SLICE_MS = 100;
+// WSAPoll() cannot wait for an event as well, so a wait on a socket looks at the event in slices this long.
+static constexpr INT SOCKET_WAIT_SLICE_MS = 100;
+
+// Lets the IO thread call the read hook on the owner's thread, as long as the transport is there.
+struct TransportWindows::ReadHookRelay : public AtomicRefCounted<ReadHookRelay> {
+ TransportWindows* transport { nullptr };
+ Atomic<bool> is_pending { false };
+};
+
+static HANDLE create_manual_reset_event()
+{
+ auto event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+ VERIFY(event);
+ return event;
+}
+
class OverlappedOperation {
AK_MAKE_NONCOPYABLE(OverlappedOperation);
AK_MAKE_NONMOVABLE(OverlappedOperation);
@@ -105,12 +124,18 @@ TransportWindows::TransportWindows(int handle, Kind kind)
TransportWindows::~TransportWindows()
{
close();
+ for (auto* event : { m_incoming_event, m_io_thread_stop_event }) {
+ if (event)
+ CloseHandle(event);
+ }
}
void TransportWindows::set_up_read_hook(Function<void()> hook)
{
VERIFY(is_open());
m_on_read_hook = move(hook);
+ if (m_io_thread)
+ return;
m_read_notifier = Core::Notifier::construct(m_handle, Core::NotificationType::Read);
m_read_notifier->on_activation = [this] {
if (m_on_read_hook)
@@ -146,9 +171,103 @@ void TransportWindows::stop_watching()
notifier->close();
}
+void TransportWindows::set_incoming_message_observer(Function<void(ReadonlyBytes)> observer)
+{
+ {
+ MutexLocker locker(m_incoming_message_observer_mutex);
+ m_incoming_message_observer = move(observer);
+ }
+ if (!m_io_thread && is_open())
+ start_io_thread();
+}
+
+void TransportWindows::notify_incoming_message_observer(ReadonlyBytes bytes)
+{
+ MutexLocker locker(m_incoming_message_observer_mutex);
+ if (m_incoming_message_observer)
+ m_incoming_message_observer(bytes);
+}
+
+void TransportWindows::start_io_thread()
+{
+ m_incoming_event = create_manual_reset_event();
+ m_io_thread_stop_event = create_manual_reset_event();
+ m_read_hook_relay = adopt_ref(*new ReadHookRelay);
+ m_read_hook_relay->transport = this;
+ m_owner_event_loop = Core::EventLoop::current_weak();
+
+ // The notifier's own read of the handle would race the IO thread's reads.
+ stop_watching();
+
+ m_io_thread = Threading::Thread::construct("IPC IO"sv, [this] { return io_thread_loop(); });
+ m_io_thread->start();
+}
+
+// Must not be called with m_send_mutex held, as the IO thread may need it before it can stop.
+void TransportWindows::stop_io_thread()
+{
+ if (!m_io_thread || m_io_thread_has_stopped)
+ return;
+ SetEvent(m_io_thread_stop_event);
+ (void)m_io_thread->join();
+ m_io_thread_has_stopped = true;
+ m_read_hook_relay->transport = nullptr;
+}
+
+intptr_t TransportWindows::io_thread_loop()
+{
+ // NB: A pipe that holds data stays readable while this end is closing, so that alone must end the loop.
+ while (m_is_open.load(AK::MemoryOrder::memory_order_relaxed)) {
+ if (!wait_until_readable_or_signaled(m_io_thread_stop_event))
+ return 0;
+
+ Vector<NonnullOwnPtr<Message>> batch;
+ auto should_shutdown = read_and_parse_messages([&](NonnullOwnPtr<Message> message) {
+ batch.append(move(message));
+ });
+ bool const has_ended = should_shutdown == ShouldShutdown::Yes;
+ if (batch.is_empty() && !has_ended)
+ continue;
+
+ for (auto const& message : batch)
+ notify_incoming_message_observer(message->bytes.bytes());
+ if (has_ended)
+ notify_incoming_message_observer({});
+
+ {
+ MutexLocker locker(m_incoming_mutex);
+ m_incoming_messages.extend(move(batch));
+ if (has_ended)
+ m_incoming_has_ended = true;
+ SetEvent(m_incoming_event);
+ }
+ notify_read_hook();
+
+ if (has_ended)
+ return 0;
+ }
+ return 0;
+}
+
+void TransportWindows::notify_read_hook()
+{
+ if (m_read_hook_relay->is_pending.exchange(true))
+ return;
+ auto event_loop = m_owner_event_loop->take();
+ if (!event_loop.is_alive())
+ return;
+ event_loop->deferred_invoke([relay = m_read_hook_relay] {
+ relay->is_pending.store(false);
+ if (relay->transport && relay->transport->m_on_read_hook)
+ relay->transport->m_on_read_hook();
+ });
+ event_loop->wake();
+}
+
void TransportWindows::close()
{
m_is_open.store(false, AK::MemoryOrder::memory_order_relaxed);
+ stop_io_thread();
MutexLocker locker(m_send_mutex);
stop_watching();
if (m_handle != -1) {
@@ -162,8 +281,50 @@ void TransportWindows::close_after_sending_all_pending_messages()
close();
}
+// Returns false if the event was signaled first.
+bool TransportWindows::wait_until_readable_or_signaled(HANDLE event)
+{
+ if (m_kind == Kind::Socket) {
+ for (;;) {
+ WSAPOLLFD poll_fd {
+ .fd = static_cast<SOCKET>(m_handle),
+ .events = POLLRDNORM,
+ .revents = 0,
+ };
+ auto result = WSAPoll(&poll_fd, 1, SOCKET_WAIT_SLICE_MS);
+ VERIFY(result != SOCKET_ERROR);
+ if (result > 0)
+ return true;
+ if (WaitForSingleObject(event, 0) == WAIT_OBJECT_0)
+ return false;
+ }
+ }
+
+ // A zero-byte read completes once there is something to read, or once the pipe is broken.
+ OverlappedOperation operation;
+ static u8 s_zero_byte_buffer;
+ if (ReadFile(to_handle(m_handle), &s_zero_byte_buffer, 0, nullptr, operation.overlapped()))
+ return true;
+ if (GetLastError() != ERROR_IO_PENDING)
+ return true;
+ HANDLE events[] = { operation.event(), event };
+ if (WaitForMultipleObjects(2, events, FALSE, INFINITE) == WAIT_OBJECT_0)
+ return true;
+
+ // The read must have stopped writing to the OVERLAPPED before it goes away.
+ CancelIoEx(to_handle(m_handle), operation.overlapped());
+ DWORD bytes_read = 0;
+ GetOverlappedResult(to_handle(m_handle), operation.overlapped(), &bytes_read, TRUE);
+ return false;
+}
+
void TransportWindows::wait_until_readable()
{
+ if (m_io_thread) {
+ WaitForSingleObject(m_incoming_event, INFINITE);
+ return;
+ }
+
if (m_kind == Kind::Socket) {
WSAPOLLFD poll_fd {
.fd = static_cast<SOCKET>(m_handle),
@@ -344,6 +505,28 @@ TransportWindows::ReadOutcome TransportWindows::read_some_without_waiting(Bytes
}
TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_possible_without_blocking(Function<void(Message&&)>&& callback)
+{
+ if (!m_io_thread) {
+ return read_and_parse_messages([&](NonnullOwnPtr<Message> message) {
+ callback(move(*message));
+ });
+ }
+
+ Vector<NonnullOwnPtr<Message>> messages;
+ bool has_ended = false;
+ {
+ MutexLocker locker(m_incoming_mutex);
+ messages = move(m_incoming_messages);
+ has_ended = m_incoming_has_ended;
+ if (!has_ended)
+ ResetEvent(m_incoming_event);
+ }
+ for (auto& message : messages)
+ callback(move(*message));
+ return has_ended ? ShouldShutdown::Yes : ShouldShutdown::No;
+}
+
+TransportWindows::ShouldShutdown TransportWindows::read_and_parse_messages(Function<void(NonnullOwnPtr<Message>)>&& callback)
{
auto should_shutdown = ShouldShutdown::No;
@@ -404,7 +587,7 @@ TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_poss
if (message_size.has_overflow() || message_size.value() > m_unprocessed_bytes.size() - index)
break;
- Message message;
+ auto message = make<Message>();
Attachment section;
if (header.attachment_count > 0) {
HandleBrokerToken attachment_token = 0;
@@ -418,7 +601,7 @@ TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_poss
if (payload_is_in_shared_memory)
section = attachments.value().take_last();
for (auto& attachment : attachments.value())
- message.attachments.enqueue(move(attachment));
+ message->attachments.enqueue(move(attachment));
}
auto const* payload = m_unprocessed_bytes.data() + index + sizeof(MessageHeader) + header.token_size();
@@ -436,7 +619,7 @@ TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_poss
should_shutdown = ShouldShutdown::Yes;
break;
}
- message.bytes = ReceivedMessageBytes::from_vector(move(payload_bytes));
+ message->bytes = ReceivedMessageBytes::from_vector(move(payload_bytes));
callback(move(message));
index = message_size.value() + index;
}
@@ -469,6 +652,7 @@ TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_poss
ErrorOr<TransportHandle> TransportWindows::release_for_transfer()
{
m_is_open.store(false, AK::MemoryOrder::memory_order_relaxed);
+ stop_io_thread();
MutexLocker locker(m_send_mutex);
stop_watching();
if (m_handle == -1)
diff --git a/Libraries/LibIPC/TransportWindows.h b/Libraries/LibIPC/TransportWindows.h
index e55664bddd4..23f3cd1feb7 100644
--- a/Libraries/LibIPC/TransportWindows.h
+++ b/Libraries/LibIPC/TransportWindows.h
@@ -12,8 +12,10 @@
#include <AK/ByteBuffer.h>
#include <AK/Function.h>
#include <AK/Mutex.h>
+#include <AK/NonnullOwnPtr.h>
#include <AK/Queue.h>
#include <AK/RefPtr.h>
+#include <AK/Vector.h>
#include <AK/kmalloc.h>
#include <LibCore/Forward.h>
#include <LibIPC/Attachment.h>
@@ -21,6 +23,7 @@
#include <LibIPC/HandleBroker.h>
#include <LibIPC/ReceivedMessageBytes.h>
#include <LibIPC/TransportHandle.h>
+#include <LibThreading/Forward.h>
namespace IPC {
@@ -47,6 +50,11 @@ public:
~TransportWindows();
void set_up_read_hook(Function<void()>);
+
+ // Starts an IO thread that reads the handle from then on, and shows the observer each message before its owner gets
+ // to it, and an empty message once the peer is gone.
+ void set_incoming_message_observer(Function<void(ReadonlyBytes)>);
+
bool is_open() const;
void close();
void close_after_sending_all_pending_messages();
@@ -58,6 +66,7 @@ public:
// Both are no-ops here: post_message() writes to the pipe before it returns, and the read path below reads the
// pipe itself, so neither direction has a queue that can lag behind another transport.
+ // FIXME: Once an observer has started an IO thread, the pipe can hold messages that it has not queued yet.
void flush() { }
void wait_until_incoming_is_current() { }
@@ -68,6 +77,8 @@ public:
Yes,
};
struct Message {
+ AK_ALLOC_WITH_KMALLOC;
+
ReceivedMessageBytes bytes;
Queue<Attachment> attachments;
};
@@ -81,6 +92,7 @@ private:
Socket,
};
struct MessageHeader;
+ struct ReadHookRelay;
enum class ReadOutcome : u8 {
Read,
WouldBlock,
@@ -93,8 +105,16 @@ private:
ErrorOr<void> transfer(ReadonlyBytes);
ErrorOr<size_t> write_some(ReadonlyBytes);
ReadOutcome read_some_without_waiting(Bytes, size_t& bytes_read);
+ bool wait_until_readable_or_signaled(void* event);
+ ShouldShutdown read_and_parse_messages(Function<void(NonnullOwnPtr<Message>)>&&);
void stop_watching();
+ void start_io_thread();
+ void stop_io_thread();
+ intptr_t io_thread_loop();
+ void notify_incoming_message_observer(ReadonlyBytes);
+ void notify_read_hook();
+
int m_handle { -1 };
Kind m_kind { Kind::Pipe };
Atomic<bool> m_is_open { true };
@@ -108,6 +128,23 @@ private:
HandleBrokerChannel m_handle_broker_channel { 0 };
bool m_has_parked_attachments { false };
bool m_disconnects_when_peer_stops_reading { false };
+
+ // Manual-reset events, as HANDLEs.
+ void* m_incoming_event { nullptr };
+ void* m_io_thread_stop_event { nullptr };
+
+ // Only there once an observer is set. The IO thread is then the only reader of the handle and of m_unprocessed_bytes.
+ RefPtr<Threading::Thread> m_io_thread;
+ bool m_io_thread_has_stopped { false };
+ RefPtr<Core::WeakEventLoopReference> m_owner_event_loop;
+ RefPtr<ReadHookRelay> m_read_hook_relay;
+
+ Mutex m_incoming_mutex;
+ Vector<NonnullOwnPtr<Message>> m_incoming_messages;
+ bool m_incoming_has_ended { false };
+
+ Mutex m_incoming_message_observer_mutex;
+ Function<void(ReadonlyBytes)> m_incoming_message_observer;
};
}