Skip to content

Truly independent web browser

LibWeb: Abort the script of a worker that is terminated

Andreas Klingc02f5cf1951e
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cpp
index 3a03319adcb..e47033e9721 100644
--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp
+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp
@@ -194,6 +194,10 @@ void initialize_main_thread_vm(HTML::AgentType type)
main_thread_vm_ptr()->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
auto& vm = *main_thread_vm_ptr();
+ // NB: Nothing reports what an aborted script left behind.
+ if (vm.interrupt_requested())
+ return;
+
// 1. Let script be the running script.
// The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
HTML::Script* script { nullptr };
@@ -745,6 +749,8 @@ void shut_down_agent()
{
auto& vm = main_thread_vm();
+ static_cast<HTML::Agent*>(vm.agent())->detach_script_abort_handle();
+
// What the agent keeps outside its heap refers to cells in it, so that goes while the heap is alive.
Platform::discard_thread_pool_completions();
Fetch::Fetching::disarm_all_body_stream_wakes();
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 566863519d1..cd7d5a4e02d 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -589,6 +589,7 @@ set(SOURCES
HTML/Scripting/ModuleMap.cpp
HTML/Scripting/ModuleScript.cpp
HTML/Scripting/Script.cpp
+ HTML/Scripting/ScriptAbortHandle.cpp
HTML/Scripting/ScriptRegistry.cpp
HTML/Scripting/SimilarOriginWindowAgent.cpp
HTML/Scripting/TemporaryExecutionContext.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 8613e49e91c..f942efefd45 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -847,6 +847,7 @@ enum class RequireWellFormed;
enum class SelectionDirection : u8;
struct Agent;
+class ScriptAbortHandle;
struct DeserializedTransferRecord;
struct Environment;
struct EnvironmentSettingsObject;
diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
index 157ee27766c..d7bac0033ea 100644
--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
@@ -1843,7 +1843,8 @@ void EventLoop::perform_a_microtask_checkpoint()
m_performing_a_microtask_checkpoint = true;
// 3. While the event loop's microtask queue is not empty:
- while (!m_microtask_queue.is_empty()) {
+ // AD-HOC: The script these would run was aborted, and nothing in the agent runs anymore.
+ while (!m_microtask_queue.is_empty() && !vm().interrupt_requested()) {
// 1. Let oldestMicrotask be the result of dequeuing from the event loop's microtask queue.
auto oldest_microtask = m_microtask_queue.dequeue();
diff --git a/Libraries/LibWeb/HTML/Scripting/Agent.cpp b/Libraries/LibWeb/HTML/Scripting/Agent.cpp
index d390115ed76..48a9e516b22 100644
--- a/Libraries/LibWeb/HTML/Scripting/Agent.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Agent.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Agent.h>
@@ -28,6 +29,19 @@ void Agent::spin_event_loop_until(GC::Root<GC::Function<bool()>> goal_condition)
event_loop->spin_until(*goal_condition);
}
+NonnullRefPtr<ScriptAbortHandle> Agent::script_abort_handle()
+{
+ if (!m_script_abort_handle)
+ m_script_abort_handle = ScriptAbortHandle::create(JS::VM::the());
+ return *m_script_abort_handle;
+}
+
+void Agent::detach_script_abort_handle()
+{
+ if (m_script_abort_handle)
+ m_script_abort_handle->detach();
+}
+
// https://html.spec.whatwg.org/multipage/webappapis.html#relevant-agent
Agent& relevant_agent(JS::Object const& object)
{
diff --git a/Libraries/LibWeb/HTML/Scripting/Agent.h b/Libraries/LibWeb/HTML/Scripting/Agent.h
index 2a932333edc..ca491e31acb 100644
--- a/Libraries/LibWeb/HTML/Scripting/Agent.h
+++ b/Libraries/LibWeb/HTML/Scripting/Agent.h
@@ -12,6 +12,7 @@
#include <LibJS/Runtime/Agent.h>
#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>
#include <LibWeb/Forward.h>
+#include <LibWeb/HTML/Scripting/ScriptAbortHandle.h>
namespace JS {
@@ -38,6 +39,10 @@ struct WEB_API Agent : public JS::Agent {
virtual void spin_event_loop_until(GC::Root<GC::Function<bool()>> goal_condition) override;
+ // Only the agent's thread may call this, the first time at least. The handle is for other threads.
+ NonnullRefPtr<ScriptAbortHandle> script_abort_handle();
+ void detach_script_abort_handle();
+
protected:
using JS::Agent::Agent;
@@ -49,6 +54,8 @@ private:
// windows in one WebContent process currently share the process's
// SimilarOriginWindowAgent; proper agent-cluster separation is future work.
mutable GC::Root<Bindings::WrapperWorld> m_main_world;
+
+ RefPtr<ScriptAbortHandle> m_script_abort_handle;
};
Agent& relevant_agent(JS::Object const&);
diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
index d968b4b8fea..89a1bfc84d5 100644
--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
@@ -27,6 +27,10 @@ namespace Web::HTML {
void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromise error_in_promise)
{
+ // NB: Whatever comes out of an aborted script is no error of its own.
+ if (realm.vm().interrupt_requested())
+ return;
+
auto& console = realm.intrinsics().console_object()->console();
if (value.is_object()) {
@@ -78,6 +82,10 @@ void report_an_exception(JS::Object& global, JS::Value exception, Optional<Error
auto& realm = relevant_realm(global);
auto& vm = realm.vm();
+ // NB: Whatever comes out of an aborted script is no error of its own.
+ if (vm.interrupt_requested())
+ return;
+
// 1. Let notHandled be true.
bool not_handled = true;
diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
index ce7079ca0fe..c5bebe1c672 100644
--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
@@ -23,6 +23,7 @@
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/Fetching/ClientContextSnapshots.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
+#include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
@@ -618,7 +619,11 @@ WebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_scri
request->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);
request->set_use_url_credentials(true);
- auto process_response_consume_body = [&response, &body_bytes](GC::Ref<Fetch::Infrastructure::ResponseView> res, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bb) {
+ auto is_abandoned = Fetch::Fetching::RefCountedFlag::create(false);
+ auto process_response_consume_body = [&response, &body_bytes, is_abandoned](GC::Ref<Fetch::Infrastructure::ResponseView> res, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bb) {
+ if (is_abandoned->value())
+ return;
+
// 1. Set bodyBytes to bb.
body_bytes = move(bb);
@@ -652,6 +657,12 @@ WebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_scri
Platform::EventLoopPlugin::the().spin_until(response_is_not_null);
}
+ // NB: The fetch outlives an aborted script, whose stack the steps above must not write to anymore.
+ if (!response) {
+ is_abandoned->set_value(true);
+ return WebIDL::NetworkError::create("Network error"_utf16);
+ }
+
// NB: Whether response was CORS-cross-origin must be determined before unwrapping it, since the internal
// response of an opaque filtered response is never CORS-cross-origin itself.
auto response_was_cors_cross_origin = response->is_cors_cross_origin();
diff --git a/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp
new file mode 100644
index 00000000000..37dd00b8b94
--- /dev/null
+++ b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.cpp
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/EventLoop.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/HTML/Scripting/ScriptAbortHandle.h>
+
+namespace Web::HTML {
+
+NonnullRefPtr<ScriptAbortHandle> ScriptAbortHandle::create(JS::VM& vm)
+{
+ return adopt_ref(*new ScriptAbortHandle(vm, Core::EventLoop::current_weak()));
+}
+
+ScriptAbortHandle::ScriptAbortHandle(JS::VM& vm, NonnullRefPtr<Core::WeakEventLoopReference> event_loop)
+ : m_vm(&vm)
+ , m_event_loop(move(event_loop))
+{
+}
+
+ScriptAbortHandle::~ScriptAbortHandle() = default;
+
+void ScriptAbortHandle::abort_script()
+{
+ MutexLocker locker(m_mutex);
+ if (!m_vm)
+ return;
+ m_vm->request_interrupt();
+
+ // NB: A nested event loop may be sleeping, with nothing to wake it up but this.
+ if (auto event_loop = m_event_loop->take(); event_loop.is_alive())
+ event_loop->wake();
+}
+
+void ScriptAbortHandle::detach()
+{
+ MutexLocker locker(m_mutex);
+ m_vm = nullptr;
+}
+
+}
diff --git a/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h
new file mode 100644
index 00000000000..de6be065295
--- /dev/null
+++ b/Libraries/LibWeb/HTML/Scripting/ScriptAbortHandle.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/Mutex.h>
+#include <AK/NonnullRefPtr.h>
+#include <LibCore/Forward.h>
+#include <LibJS/Forward.h>
+#include <LibWeb/Export.h>
+
+namespace Web::HTML {
+
+// What any thread can stop the script of an agent with, whatever that script is doing, including waiting in a nested
+// event loop. It may outlive the agent, which it then has no effect on anymore.
+class WEB_API ScriptAbortHandle final : public AtomicRefCounted<ScriptAbortHandle> {
+public:
+ // Only the agent's thread may create a handle, as it has to know the agent's Core::EventLoop.
+ static NonnullRefPtr<ScriptAbortHandle> create(JS::VM&);
+
+ ~ScriptAbortHandle();
+
+ // Stops script on the agent's VM for good (see JS::VM::request_interrupt()). 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>);
+
+ Mutex m_mutex;
+ JS::VM* m_vm { nullptr };
+ NonnullRefPtr<Core::WeakEventLoopReference> m_event_loop;
+};
+
+}
diff --git a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
index 504d6c78fec..adedabe7c3a 100644
--- a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
@@ -100,10 +100,13 @@ void WorkerGlobalScope::terminate_a_worker()
// discard them without processing them.
close_a_worker();
- // FIXME: 3. Abort the script currently running in the worker.
- // FIXME: 4. If the worker's WorkerGlobalScope object is actually a DedicatedWorkerGlobalScope object (i.e. the
- // worker is a dedicated worker), then empty the port message queue of the port that the worker's implicit
- // port is entangled with.
+ // 3. Abort the script currently running in the worker.
+ relevant_realm(*this).vm().request_interrupt();
+
+ // 4. If the worker's WorkerGlobalScope object is actually a DedicatedWorkerGlobalScope object (i.e. the worker is
+ // a dedicated worker), then empty the port message queue of the port that the worker's implicit port is
+ // entangled with.
+ // NB: That port is in the owner, whose Worker::terminate() empties its queue.
}
// https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries
diff --git a/Libraries/LibWeb/Platform/EventLoopPlugin.cpp b/Libraries/LibWeb/Platform/EventLoopPlugin.cpp
index 50124596977..5ba3364ff05 100644
--- a/Libraries/LibWeb/Platform/EventLoopPlugin.cpp
+++ b/Libraries/LibWeb/Platform/EventLoopPlugin.cpp
@@ -6,6 +6,8 @@
#include <AK/Function.h>
#include <LibCore/EventLoop.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/HTML/Scripting/Agent.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
namespace Web::Platform {
@@ -29,10 +31,18 @@ EventLoopPlugin::~EventLoopPlugin() = default;
void EventLoopPlugin::spin_until(GC::Root<GC::Function<bool()>> goal_condition)
{
Core::EventLoop::current().spin_until([goal_condition = move(goal_condition)]() {
- // NB: A process that shuts down fast has nothing to unwind for. A worker event loop quits only once no script is
- // waiting in here, as its agent has an ordered shutdown ahead of it.
- if (Core::EventLoop::current().was_exit_requested())
- ::exit(0);
+ // NB: Only script can be waiting for the goal, and it has to unwind once aborted, goal or not. Every caller has to
+ // cope with that.
+ if (JS::VM::the().interrupt_requested())
+ return true;
+ if (Core::EventLoop::current().was_exit_requested()) {
+ // NB: A process that shuts down fast has nothing to unwind for. An event loop on a worker's thread can only
+ // end the worker, whose agent has an ordered shutdown ahead of it, so that script is aborted instead.
+ if (HTML::surrounding_agent().is_similar_origin_window_agent())
+ ::exit(0);
+ JS::VM::the().request_interrupt();
+ return true;
+ }
return goal_condition->function()();
});
}
diff --git a/Libraries/LibWeb/ServiceWorker/Job.cpp b/Libraries/LibWeb/ServiceWorker/Job.cpp
index 21f6e1094ad..a7a4983031a 100644
--- a/Libraries/LibWeb/ServiceWorker/Job.cpp
+++ b/Libraries/LibWeb/ServiceWorker/Job.cpp
@@ -460,6 +460,9 @@ static void update(JS::VM& vm, GC::Ref<Job> job)
return false;
}));
+ // NB: The event loop gave up on an aborted script.
+ if (!process_response_completion_result.has_value())
+ return WebIDL::AbortError::create("Service Worker fetch was terminated or aborted"_utf16);
return process_response_completion_result.release_value();
};
auto perform_the_fetch_hook = HTML::create_perform_the_fetch_hook(GC::Heap::the(), move(perform_the_fetch_hook_function));