Skip to content

Truly independent web browser

LibIPC+LibWeb: Wake a blocked sync request when script is aborted

Andreas Kling5cd1a476e5c2
diff --git a/Libraries/LibIPC/Connection.cpp b/Libraries/LibIPC/Connection.cpp
index 14f3ff4e445..40d36192084 100644
--- a/Libraries/LibIPC/Connection.cpp
+++ b/Libraries/LibIPC/Connection.cpp
@@ -6,6 +6,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Diagnostics.h>
#include <AK/ScopeGuard.h>
#include <AK/TemporaryChange.h>
#include <AK/Vector.h>
@@ -15,6 +16,38 @@
namespace IPC {
+// NB: Drop each thread's reference when that thread exits.
+#ifdef AK_COMPILER_CLANG
+AK_IGNORE_DIAGNOSTIC("-Wexit-time-destructors", static thread_local RefPtr<SyncRequestCanceller> s_sync_request_canceller)
+#else
+static thread_local RefPtr<SyncRequestCanceller> s_sync_request_canceller;
+#endif
+
+void SyncRequestCanceller::install_on_this_thread()
+{
+ s_sync_request_canceller = *this;
+}
+
+bool SyncRequestCanceller::is_installed_on_this_thread()
+{
+ return s_sync_request_canceller;
+}
+
+void SyncRequestCanceller::cancel()
+{
+ m_cancelled.store(true, AK::MemoryOrder::memory_order_release);
+
+ MutexLocker locker(m_mutex);
+ if (m_transport_waited_on)
+ m_transport_waited_on->interrupt_wait_until_readable();
+}
+
+void SyncRequestCanceller::set_transport_waited_on(Transport* transport)
+{
+ MutexLocker locker(m_mutex);
+ m_transport_waited_on = transport;
+}
+
ConnectionBase::ConnectionBase(IPC::Stub& local_stub, NonnullOwnPtr<Transport> transport, u32 local_endpoint_magic)
: m_local_stub(local_stub)
, m_transport(move(transport))
@@ -210,12 +243,22 @@ ConnectionBase::PeerEOF ConnectionBase::drain_messages_from_peer()
return PeerEOF::No;
}
-OwnPtr<IPC::Message> ConnectionBase::wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id)
+OwnPtr<IPC::Message> ConnectionBase::wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id, MayCancel may_cancel)
{
VERIFY(m_owner_thread_id.is_current_thread());
TemporaryChange waiting_for_sync_response { m_is_waiting_for_sync_response, true };
bool peer_disconnected_during_wait = false;
+ // NB: The canceller knows the transport before this thread looks at its flag, so it cannot slip in between that look
+ // and the wait: if it does not find the transport, this thread sees the flag.
+ auto canceller = may_cancel == MayCancel::Yes ? s_sync_request_canceller : nullptr;
+ if (canceller)
+ canceller->set_transport_waited_on(m_transport.ptr());
+ ScopeGuard forget_transport = [&] {
+ if (canceller)
+ canceller->set_transport_waited_on(nullptr);
+ };
+
auto take_matching_message = [&]() -> OwnPtr<IPC::Message> {
for (size_t i = 0; i < m_unprocessed_messages.size(); ++i) {
auto& message = m_unprocessed_messages[i];
@@ -228,6 +271,12 @@ OwnPtr<IPC::Message> ConnectionBase::wait_for_specific_endpoint_message_impl(u32
};
for (;;) {
+ // NB: Responses have no ID, so one that a cancelled wait left behind would pass for the response to the next
+ // request of that type. A canceller stays cancelled, so nothing takes that response after this point. It
+ // is not dispatched either, as it is not for this endpoint.
+ if (canceller && canceller->is_cancelled())
+ return {};
+
// Double check we don't already have the event waiting for us.
// Otherwise we might end up blocked for a while for no reason.
if (auto message = take_matching_message())
diff --git a/Libraries/LibIPC/Connection.h b/Libraries/LibIPC/Connection.h
index 173ae79a0ba..5a06d13bf2f 100644
--- a/Libraries/LibIPC/Connection.h
+++ b/Libraries/LibIPC/Connection.h
@@ -8,7 +8,11 @@
#pragma once
+#include <AK/Atomic.h>
+#include <AK/AtomicRefCounted.h>
#include <AK/Forward.h>
+#include <AK/Mutex.h>
+#include <AK/NonnullRefPtr.h>
#include <AK/Queue.h>
#include <AK/ThreadID.h>
#include <LibCore/EventReceiver.h>
@@ -19,6 +23,33 @@
namespace IPC {
+// Lets any thread end the sync requests of the thread this is installed on, on whichever connection they are. A request
+// that may fail then fails, now and from then on, rather than wait for a peer that may never answer. This is for a thread
+// that shares its process with others, so that it cannot just exit. Such a thread has no use for a request that cannot
+// fail, which would take the whole process along, so it may not make one; see send_sync().
+class SyncRequestCanceller final : public AtomicRefCounted<SyncRequestCanceller> {
+public:
+ static NonnullRefPtr<SyncRequestCanceller> create() { return adopt_ref(*new SyncRequestCanceller); }
+
+ // This stays the canceller of the current thread until the thread ends.
+ void install_on_this_thread();
+ static bool is_installed_on_this_thread();
+
+ void cancel();
+ bool is_cancelled() const { return m_cancelled.load(AK::MemoryOrder::memory_order_acquire); }
+
+private:
+ friend class ConnectionBase;
+
+ SyncRequestCanceller() = default;
+
+ void set_transport_waited_on(Transport*);
+
+ Atomic<bool> m_cancelled { false };
+ Mutex m_mutex;
+ Transport* m_transport_waited_on { nullptr };
+};
+
class ConnectionBase : public Core::EventReceiver {
C_OBJECT_ABSTRACT(ConnectionBase);
@@ -62,6 +93,9 @@ public:
template<typename RequestType, typename... Args>
NonnullOwnPtr<typename RequestType::ResponseType> send_sync(Args&&... args)
{
+ // NB: A peer that dies here ends this process, and nothing can stop this wait. A thread with a canceller has to
+ // fail on its own, so all it asks for goes through send_sync_but_allow_failure().
+ VERIFY(!SyncRequestCanceller::is_installed_on_this_thread());
MUST(post_sync_request(RequestType(forward<Args>(args)...)));
auto response = wait_for_specific_endpoint_message<typename RequestType::ResponseType>();
VERIFY(response);
@@ -73,14 +107,19 @@ public:
{
if (post_sync_request(RequestType(forward<Args>(args)...)).is_error())
return nullptr;
- return wait_for_specific_endpoint_message<typename RequestType::ResponseType>();
+ return wait_for_specific_endpoint_message<typename RequestType::ResponseType>(MayCancel::Yes);
}
protected:
+ enum class MayCancel {
+ No,
+ Yes,
+ };
+
template<typename MessageType>
- OwnPtr<MessageType> wait_for_specific_endpoint_message()
+ OwnPtr<MessageType> wait_for_specific_endpoint_message(MayCancel may_cancel = MayCancel::No)
{
- if (auto message = wait_for_specific_endpoint_message_impl(MessageType::ENDPOINT_MAGIC, MessageType::static_message_id()))
+ if (auto message = wait_for_specific_endpoint_message_impl(MessageType::ENDPOINT_MAGIC, MessageType::static_message_id(), may_cancel))
return message.template release_nonnull<MessageType>();
return {};
}
@@ -91,7 +130,7 @@ protected:
virtual OwnPtr<Message> try_parse_message(ReadonlyBytes, Queue<Attachment>&) = 0;
ErrorOr<void> post_sync_request(Message const&);
- OwnPtr<IPC::Message> wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id);
+ OwnPtr<IPC::Message> wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id, MayCancel = MayCancel::No);
void wait_for_transport_to_become_readable();
enum class PeerEOF {
No,
diff --git a/Libraries/LibIPC/Forward.h b/Libraries/LibIPC/Forward.h
index 2639ef520d7..a7d806219e1 100644
--- a/Libraries/LibIPC/Forward.h
+++ b/Libraries/LibIPC/Forward.h
@@ -25,6 +25,7 @@ struct HandleBrokerResponse;
class HandleBrokerServer;
class LocalHandleBroker;
class Stub;
+class SyncRequestCanceller;
class TransportHandle;
#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
diff --git a/Libraries/LibIPC/TransportMachPort.cpp b/Libraries/LibIPC/TransportMachPort.cpp
index 429a74d762b..b48d128f67b 100644
--- a/Libraries/LibIPC/TransportMachPort.cpp
+++ b/Libraries/LibIPC/TransportMachPort.cpp
@@ -278,12 +278,12 @@ void TransportMachPort::wait_until_incoming_is_current()
void TransportMachPort::mark_peer_eof()
{
+ notify_incoming_message_observer({});
+
bool should_write_notification = false;
{
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();
@@ -601,11 +601,11 @@ void TransportMachPort::process_received_message(u8* buffer)
if (message->bytes.is_empty() && message->attachments.is_empty())
return;
+ notify_incoming_message_observer(message->bytes.bytes());
+
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)
@@ -618,10 +618,17 @@ void TransportMachPort::process_received_message(u8* buffer)
void TransportMachPort::set_incoming_message_observer(Function<void(ReadonlyBytes)> observer)
{
- MutexLocker locker(m_incoming_mutex);
+ MutexLocker locker(m_incoming_message_observer_mutex);
m_incoming_message_observer = move(observer);
}
+void TransportMachPort::notify_incoming_message_observer(ReadonlyBytes bytes)
+{
+ MutexLocker locker(m_incoming_message_observer_mutex);
+ if (m_incoming_message_observer)
+ m_incoming_message_observer(bytes);
+}
+
void TransportMachPort::set_up_read_hook(Function<void()> hook)
{
m_on_read_hook = move(hook);
@@ -676,8 +683,16 @@ void TransportMachPort::release_send_right_to_peer()
void TransportMachPort::wait_until_readable()
{
MutexLocker lock(m_incoming_mutex);
- while (m_incoming_messages.is_empty() && !m_peer_eof)
+ while (m_incoming_messages.is_empty() && !m_peer_eof && !m_wait_until_readable_interrupted)
m_incoming_cv.wait();
+ m_wait_until_readable_interrupted = false;
+}
+
+void TransportMachPort::interrupt_wait_until_readable()
+{
+ MutexLocker lock(m_incoming_mutex);
+ m_wait_until_readable_interrupted = true;
+ m_incoming_cv.broadcast();
}
ErrorOr<void> TransportMachPort::post_message(MessageDataType bytes, Vector<Attachment>& attachments)
diff --git a/Libraries/LibIPC/TransportMachPort.h b/Libraries/LibIPC/TransportMachPort.h
index 80f342db397..db76aa75876 100644
--- a/Libraries/LibIPC/TransportMachPort.h
+++ b/Libraries/LibIPC/TransportMachPort.h
@@ -62,6 +62,10 @@ public:
void wait_until_readable();
+ // Makes wait_until_readable() return, even with nothing to read, now or if none is under way, the next time. Any
+ // thread may call this.
+ void interrupt_wait_until_readable();
+
// Wait until everything posted so far has been handed to the kernel.
void flush();
@@ -108,6 +112,7 @@ private:
bool schedule_read_notification_if_needed_locked();
void write_read_notification_byte();
void mark_peer_eof();
+ void notify_incoming_message_observer(ReadonlyBytes);
void release_send_waiters();
enum class SendOutcome {
Sent,
@@ -143,7 +148,10 @@ private:
Mutex m_incoming_mutex;
ConditionVariable m_incoming_cv { m_incoming_mutex };
+ bool m_wait_until_readable_interrupted { false };
Vector<NonnullOwnPtr<Message>> m_incoming_messages;
+ // NB: This has a lock of its own, as the observer may interrupt a wait, which takes m_incoming_mutex.
+ Mutex m_incoming_message_observer_mutex;
Function<void(ReadonlyBytes)> m_incoming_message_observer;
u64 m_receive_barriers_sent { 0 };
u64 m_receive_barriers_received { 0 };
diff --git a/Libraries/LibIPC/TransportSocket.cpp b/Libraries/LibIPC/TransportSocket.cpp
index e1eae92114f..b93b57c82fb 100644
--- a/Libraries/LibIPC/TransportSocket.cpp
+++ b/Libraries/LibIPC/TransportSocket.cpp
@@ -331,11 +331,11 @@ intptr_t TransportSocket::io_thread_loop()
break;
}
+ notify_incoming_message_observer({});
+
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();
}
@@ -452,9 +452,17 @@ void TransportSocket::wait_until_incoming_is_current()
void TransportSocket::wait_until_readable()
{
MutexLocker lock(m_incoming_mutex);
- while (m_incoming_messages.is_empty() && m_io_thread_state == IOThreadState::Running) {
+ while (m_incoming_messages.is_empty() && m_io_thread_state == IOThreadState::Running && !m_wait_until_readable_interrupted) {
m_incoming_cv.wait();
}
+ m_wait_until_readable_interrupted = false;
+}
+
+void TransportSocket::interrupt_wait_until_readable()
+{
+ MutexLocker lock(m_incoming_mutex);
+ m_wait_until_readable_interrupted = true;
+ m_incoming_cv.broadcast();
}
static ErrorOr<NonnullRefPtr<AutoCloseFileDescriptor>> copy_payload_to_shared_memory(ReadonlyBytes payload)
@@ -766,11 +774,10 @@ TransportSocket::MoreToRead TransportSocket::read_incoming_messages()
bool const peer_eof = m_peer_eof;
if (!batch.is_empty() || peer_eof) {
+ for (auto const& message : batch)
+ notify_incoming_message_observer(message->bytes.bytes());
+
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
@@ -786,10 +793,17 @@ TransportSocket::MoreToRead TransportSocket::read_incoming_messages()
void TransportSocket::set_incoming_message_observer(Function<void(ReadonlyBytes)> observer)
{
- MutexLocker locker(m_incoming_mutex);
+ MutexLocker locker(m_incoming_message_observer_mutex);
m_incoming_message_observer = move(observer);
}
+void TransportSocket::notify_incoming_message_observer(ReadonlyBytes bytes)
+{
+ MutexLocker locker(m_incoming_message_observer_mutex);
+ if (m_incoming_message_observer)
+ m_incoming_message_observer(bytes);
+}
+
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 d9b23f7846a..e1ca5040245 100644
--- a/Libraries/LibIPC/TransportSocket.h
+++ b/Libraries/LibIPC/TransportSocket.h
@@ -112,6 +112,10 @@ public:
void wait_until_readable();
+ // Makes wait_until_readable() return, even with nothing to read, now or if none is under way, the next time. Any
+ // thread may call this.
+ void interrupt_wait_until_readable();
+
// Wait until everything posted so far has been written to the socket.
void flush();
@@ -170,6 +174,7 @@ private:
[[nodiscard]] MoreToRead read_incoming_messages();
void parse_unprocessed_messages(Vector<NonnullOwnPtr<Message>>&);
void notify_read_available();
+ void notify_incoming_message_observer(ReadonlyBytes);
bool incoming_is_behind_socket() const;
NonnullOwnPtr<Core::LocalSocket> m_socket;
@@ -187,6 +192,8 @@ private:
Mutex m_incoming_mutex;
ConditionVariable m_incoming_cv { m_incoming_mutex };
Vector<NonnullOwnPtr<Message>> m_incoming_messages;
+ // NB: This has a lock of its own, as the observer may interrupt a wait, which takes m_incoming_mutex.
+ Mutex m_incoming_message_observer_mutex;
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 };
@@ -194,6 +201,7 @@ private:
// batch of messages have been parsed and appended to m_incoming_messages under the same lock.
bool m_incoming_eof { false };
bool m_receive_loop_finished { false };
+ bool m_wait_until_readable_interrupted { false };
static Atomic<u32> s_eof_drain_window_for_test_ms;
static Atomic<bool> s_skip_inloop_read_for_test;
diff --git a/Libraries/LibIPC/TransportWindows.cpp b/Libraries/LibIPC/TransportWindows.cpp
index f43fee745c0..b64d88b5da7 100644
--- a/Libraries/LibIPC/TransportWindows.cpp
+++ b/Libraries/LibIPC/TransportWindows.cpp
@@ -118,13 +118,14 @@ TransportWindows::TransportWindows(int handle, Kind kind)
: m_handle(handle)
, m_kind(kind)
, m_handle_broker_channel(get_random<HandleBrokerChannel>())
+ , m_interrupt_event(create_manual_reset_event())
{
}
TransportWindows::~TransportWindows()
{
close();
- for (auto* event : { m_incoming_event, m_io_thread_stop_event }) {
+ for (auto* event : { m_interrupt_event, m_incoming_event, m_io_thread_stop_event }) {
if (event)
CloseHandle(event);
}
@@ -321,29 +322,17 @@ bool TransportWindows::wait_until_readable_or_signaled(HANDLE event)
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),
- .events = POLLRDNORM,
- .revents = 0,
- };
- auto result = WSAPoll(&poll_fd, 1, -1);
- VERIFY(result != SOCKET_ERROR);
- return;
+ HANDLE events[] = { m_incoming_event, m_interrupt_event };
+ WaitForMultipleObjects(2, events, FALSE, INFINITE);
+ } else {
+ (void)wait_until_readable_or_signaled(m_interrupt_event);
}
+ ResetEvent(m_interrupt_event);
+}
- // 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;
- if (GetLastError() != ERROR_IO_PENDING)
- return;
- WaitForSingleObject(operation.event(), INFINITE);
+void TransportWindows::interrupt_wait_until_readable()
+{
+ SetEvent(m_interrupt_event);
}
ErrorOr<size_t> TransportWindows::write_some(ReadonlyBytes bytes)
diff --git a/Libraries/LibIPC/TransportWindows.h b/Libraries/LibIPC/TransportWindows.h
index 23f3cd1feb7..05c847b5ec9 100644
--- a/Libraries/LibIPC/TransportWindows.h
+++ b/Libraries/LibIPC/TransportWindows.h
@@ -64,6 +64,8 @@ public:
void wait_until_readable();
+ void interrupt_wait_until_readable();
+
// 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.
@@ -130,6 +132,7 @@ private:
bool m_disconnects_when_peer_stops_reading { false };
// Manual-reset events, as HANDLEs.
+ void* m_interrupt_event { nullptr };
void* m_incoming_event { nullptr };
void* m_io_thread_stop_event { nullptr };
diff --git a/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp
index 37dd00b8b94..a6b3c3575d4 100644
--- a/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp
@@ -5,6 +5,7 @@
*/
#include <LibCore/EventLoop.h>
+#include <LibIPC/Connection.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/HTML/Scripting/ScriptAbortHandle.h>
@@ -12,12 +13,15 @@ namespace Web::HTML {
NonnullRefPtr<ScriptAbortHandle> ScriptAbortHandle::create(JS::VM& vm)
{
- return adopt_ref(*new ScriptAbortHandle(vm, Core::EventLoop::current_weak()));
+ auto sync_request_canceller = IPC::SyncRequestCanceller::create();
+ sync_request_canceller->install_on_this_thread();
+ return adopt_ref(*new ScriptAbortHandle(vm, Core::EventLoop::current_weak(), move(sync_request_canceller)));
}
-ScriptAbortHandle::ScriptAbortHandle(JS::VM& vm, NonnullRefPtr<Core::WeakEventLoopReference> event_loop)
+ScriptAbortHandle::ScriptAbortHandle(JS::VM& vm, NonnullRefPtr<Core::WeakEventLoopReference> event_loop, NonnullRefPtr<IPC::SyncRequestCanceller> sync_request_canceller)
: m_vm(&vm)
, m_event_loop(move(event_loop))
+ , m_sync_request_canceller(move(sync_request_canceller))
{
}
@@ -25,6 +29,8 @@ ScriptAbortHandle::~ScriptAbortHandle() = default;
void ScriptAbortHandle::abort_script()
{
+ m_sync_request_canceller->cancel();
+
MutexLocker locker(m_mutex);
if (!m_vm)
return;
diff --git a/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h
index de6be065295..e4a7cc20d1f 100644
--- a/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h
+++ b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h
@@ -10,6 +10,7 @@
#include <AK/Mutex.h>
#include <AK/NonnullRefPtr.h>
#include <LibCore/Forward.h>
+#include <LibIPC/Forward.h>
#include <LibJS/Forward.h>
#include <LibWeb/Export.h>
@@ -24,18 +25,20 @@ public:
~ScriptAbortHandle();
- // Stops script on the agent's VM for good (see JS::VM::request_interrupt()). Any thread may call this.
+ // Stops script on the agent's VM for good (see JS::VM::request_interrupt()), and fails the sync requests of its
+ // thread, as script that waits for one is not running. Any thread may call this.
void abort_script();
// The agent's thread calls this before the VM goes away.
void detach();
private:
- ScriptAbortHandle(JS::VM&, NonnullRefPtr<Core::WeakEventLoopReference>);
+ ScriptAbortHandle(JS::VM&, NonnullRefPtr<Core::WeakEventLoopReference>, NonnullRefPtr<IPC::SyncRequestCanceller>);
Mutex m_mutex;
JS::VM* m_vm { nullptr };
NonnullRefPtr<Core::WeakEventLoopReference> m_event_loop;
+ NonnullRefPtr<IPC::SyncRequestCanceller> m_sync_request_canceller;
};
}
diff --git a/Tests/LibIPC/TestConnection.cpp b/Tests/LibIPC/TestConnection.cpp
index f094f1992b2..8b6992b2bd0 100644
--- a/Tests/LibIPC/TestConnection.cpp
+++ b/Tests/LibIPC/TestConnection.cpp
@@ -91,6 +91,7 @@ class TestConnection final : public IPC::ConnectionBase {
public:
using ConnectionBase::drain_messages_from_peer;
using ConnectionBase::handle_messages;
+ using ConnectionBase::MayCancel;
using ConnectionBase::PeerEOF;
using ConnectionBase::post_sync_request;
using ConnectionBase::wait_for_transport_to_become_readable;
@@ -103,9 +104,9 @@ public:
m_unprocessed_messages.append(move(message));
}
- OwnPtr<IPC::Message> call_wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id)
+ OwnPtr<IPC::Message> call_wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id, MayCancel may_cancel = MayCancel::No)
{
- return wait_for_specific_endpoint_message_impl(endpoint_magic, message_id);
+ return wait_for_specific_endpoint_message_impl(endpoint_magic, message_id, may_cancel);
}
protected:
@@ -385,6 +386,39 @@ TEST_CASE(sync_wait_failure_does_not_dispatch_queued_messages)
EXPECT_EQ(stub.handle_count(), 0u);
}
+TEST_CASE(cancelled_thread_does_not_take_a_late_response)
+{
+ // NB: A canceller stays on its thread until that thread ends.
+ auto thread = Threading::Thread::construct("Cancelled"sv, [] -> intptr_t {
+ Core::EventLoop loop;
+
+ auto pair = MUST(IPC::Transport::create_paired());
+
+ CountingStub stub;
+ auto connection = TestConnection::construct(stub, move(pair.local));
+
+ auto canceller = IPC::SyncRequestCanceller::create();
+ EXPECT(!IPC::SyncRequestCanceller::is_installed_on_this_thread());
+ canceller->install_on_this_thread();
+ EXPECT(IPC::SyncRequestCanceller::is_installed_on_this_thread());
+ canceller->cancel();
+
+ // The response to the wait that was cancelled comes in, and the thread then makes a request of the same type.
+ connection->inject_unprocessed_message(make<TestMessage>(TARGET_MESSAGE_ID, 0, TEST_MAGIC + 1));
+ EXPECT(!connection->call_wait_for_specific_endpoint_message_impl(TEST_MAGIC + 1, TARGET_MESSAGE_ID, TestConnection::MayCancel::Yes));
+
+ connection->handle_messages();
+ EXPECT_EQ(stub.handle_count(), 0u);
+
+ connection->shutdown();
+ while (loop.pump(Core::EventLoop::WaitMode::PollForEvents) != 0)
+ ;
+ return 0;
+ });
+ thread->start();
+ TRY_OR_FAIL(thread->join());
+}
+
TEST_CASE(async_posts_from_many_threads_all_arrive)
{
Core::EventLoop loop;
diff --git a/Tests/LibIPC/TestTransportSocket.cpp b/Tests/LibIPC/TestTransportSocket.cpp
index f9385975fcd..d4bf523f46d 100644
--- a/Tests/LibIPC/TestTransportSocket.cpp
+++ b/Tests/LibIPC/TestTransportSocket.cpp
@@ -225,6 +225,40 @@ TEST_CASE(a_sent_descriptor_is_closed_once_written)
EXPECT(!descriptor_is_open(fd));
}
+TEST_CASE(an_interrupted_wait_returns_with_nothing_to_read)
+{
+ TransportPair pair;
+ pair.receiver->interrupt_wait_until_readable();
+ pair.receiver->wait_until_readable();
+}
+
+// A worker's owner aborts its script from the observer, on the IO thread, and that interrupts what the worker waits for.
+TEST_CASE(an_incoming_message_observer_can_interrupt_a_wait)
+{
+ IGNORE_USE_IN_ESCAPING_LAMBDA TransportPair pair;
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> observed { false };
+ pair.receiver->set_incoming_message_observer([&](ReadonlyBytes) {
+ pair.receiver->interrupt_wait_until_readable();
+ observed.store(true);
+ });
+
+ IGNORE_USE_IN_ESCAPING_LAMBDA size_t received = 0;
+ pair.receiver->set_up_read_hook([&] {
+ (void)pair.receiver->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {
+ ++received;
+ while (!message.attachments.is_empty())
+ MUST(Core::System::close(message.attachments.dequeue().to_fd()));
+ });
+ });
+
+ (void)pair.post_with_descriptor('A');
+ spin_until(pair.loop, [&] {
+ return observed.load() && received == 1;
+ });
+ pair.receiver->set_incoming_message_observer({});
+}
+
// A descriptor that another process sends us must not leak into a program that we exec() later.
TEST_CASE(a_received_descriptor_is_close_on_exec)
{