Skip to content

Truly independent web browser

LibWeb: Survive the origin of thread pool work going away

Andreas Kling576fe303e739
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 9567e6fe818..566863519d1 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -746,6 +746,7 @@ set(SOURCES
Platform/FontPlugin.cpp
Platform/ImageCodecPlugin.cpp
Platform/RemoteImageCodecPlugin.cpp
+ Platform/ThreadPoolWork.cpp
Platform/Timer.cpp
ReferrerPolicy/AbstractOperations.cpp
RequestIdleCallback/IdleDeadline.cpp
diff --git a/Libraries/LibWeb/CSS/FontLoading.cpp b/Libraries/LibWeb/CSS/FontLoading.cpp
index 103522d5c4c..b55313bb928 100644
--- a/Libraries/LibWeb/CSS/FontLoading.cpp
+++ b/Libraries/LibWeb/CSS/FontLoading.cpp
@@ -6,11 +6,10 @@
#include <AK/Endian.h>
#include <AK/GenericShorthands.h>
-#include <LibCore/EventLoop.h>
#include <LibGfx/Font/WOFF/Loader.h>
#include <LibGfx/Font/WOFF2/Loader.h>
-#include <LibThreading/ThreadPool.h>
#include <LibWeb/CSS/FontLoading.h>
+#include <LibWeb/Platform/ThreadPoolWork.h>
namespace Web::CSS {
@@ -80,20 +79,10 @@ ErrorOr<NonnullRefPtr<Gfx::Typeface const>> try_load_vector_font(ByteBuffer cons
void prepare_vector_font_data_off_thread(ByteBuffer data, Function<void(ErrorOr<Core::AnonymousBuffer>)>&& on_complete)
{
- // Keep the callback on the origin thread so any GC roots it captures are
- // also destroyed there.
- auto* callback = new Function<void(ErrorOr<Core::AnonymousBuffer>)>(move(on_complete));
- auto& origin_event_loop = Core::EventLoop::current();
-
- Threading::ThreadPool::the().submit(
- [data = move(data), callback, &origin_event_loop]() mutable {
- auto result = WOFF2::convert_to_ttf(data);
-
- origin_event_loop.deferred_invoke([callback, result = move(result)]() mutable {
- (*callback)(move(result));
- delete callback;
- });
- });
+ auto convert = [data = move(data)] {
+ return WOFF2::convert_to_ttf(data);
+ };
+ Platform::run_on_thread_pool<ErrorOr<Core::AnonymousBuffer>>(move(convert), move(on_complete));
}
}
diff --git a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp
index 9df3995032a..5180ef95a4b 100644
--- a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp
+++ b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp
@@ -7,12 +7,12 @@
#include <AK/Utf16View.h>
#include <LibCore/EventLoop.h>
#include <LibGC/Root.h>
-#include <LibThreading/ThreadPool.h>
#include <LibWeb/CSS/Parser/ErrorReporter.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/Parser/RustSyntaxParsing.h>
#include <LibWeb/CSS/Parser/SourcePosition.h>
#include <LibWeb/DOM/Document.h>
+#include <LibWeb/Platform/ThreadPoolWork.h>
#include <LibWeb/StyleValueRustFFI.h>
#include <LibWeb/ValueParserRustFFI.h>
@@ -185,18 +185,13 @@ void Parser::parse_stylesheet_off_thread(ParsingParams const& params, Utf16Strin
// NB: Retain all borrowed input storage and GC roots on the main thread. The worker only
// accesses the immutable source and context snapshots, plus this private parser's counter.
- auto* callback = new Function<void(RustStyleSheetParse)>(
+ auto parse = [input, parse_context] {
+ return RustStyleSheetParse { rust_parse_css_stylesheet_syntax(input, parse_context) };
+ };
+ Platform::run_on_thread_pool<RustStyleSheetParse>(move(parse),
[source = move(source_storage), parser = move(parser), context = move(context), document = GC::Root<DOM::Document const>::create(params.document.ptr()), on_complete = move(on_complete)](RustStyleSheetParse result) mutable {
on_complete(move(result));
});
- auto& main_thread_event_loop = Core::EventLoop::current();
- Threading::ThreadPool::the().submit([input, parse_context, callback, &main_thread_event_loop] {
- RustStyleSheetParse result { rust_parse_css_stylesheet_syntax(input, parse_context) };
- main_thread_event_loop.deferred_invoke([result = move(result), callback]() mutable {
- (*callback)(move(result));
- delete callback;
- });
- });
}
RustRuleList RustStyleSheetParse::native_rules() const
diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
index 612dcabaa55..ce7079ca0fe 100644
--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
@@ -17,7 +17,6 @@
#include <LibJS/ScriptCompilation.h>
#include <LibJS/SourceCode.h>
#include <LibTextCodec/Decoder.h>
-#include <LibThreading/ThreadPool.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/DOM/Document.h>
@@ -40,6 +39,7 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Infra/SerializedURL.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
+#include <LibWeb/Platform/ThreadPoolWork.h>
#include <LibWeb/ReferrerPolicy/AbstractOperations.h>
#include <LibWebCommon/Fetch/Infrastructure/URL.h>
#include <LibWebCommon/Infra/Strings.h>
@@ -103,42 +103,44 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Nonnu
// The script runs in a task of the settings object's global, so never beside a rendering update in flight that holds
// back the tasks of its document, and the microtasks it queues (e.g. promise reactions from react_to_promise during
// module linking) are drained after it.
- auto* callback = new Function<void(OffThreadCompiledProgram)>(
- [settings_object = GC::make_root(settings_object), on_compiled = move(on_compiled), source_code = move(source_code)](OffThreadCompiledProgram result) mutable {
- queue_global_task(Task::Source::Networking, settings_object->global_object(), GC::create_function(GC::Heap::the(), [on_compiled = move(on_compiled), source_code = move(source_code), result = move(result)]() mutable {
- // NB: The callback holds GC roots. Release them as the task runs: the roots of a function that died
- // would keep what they root alive through the collection that finds it dead.
- auto steps = move(on_compiled);
- steps(move(result), move(source_code));
- }));
- });
+ auto run_callback = [settings_object = GC::make_root(settings_object), on_compiled = move(on_compiled), source_code = move(source_code)](OffThreadCompiledProgram result) mutable {
+ queue_global_task(Task::Source::Networking, settings_object->global_object(), GC::create_function(GC::Heap::the(), [on_compiled = move(on_compiled), source_code = move(source_code), result = move(result)]() mutable {
+ // NB: The callback holds GC roots. Release them as the task runs: the roots of a function that died
+ // would keep what they root alive through the collection that finds it dead.
+ auto steps = move(on_compiled);
+ steps(move(result), move(source_code));
+ }));
+ };
if (cached_program.has_value()) {
- (*callback)(OffThreadCompiledProgram { .compiled = cached_program.release_value() });
- delete callback;
+ run_callback(OffThreadCompiledProgram { .compiled = cached_program.release_value() });
return;
}
- auto& main_thread_event_loop = Core::EventLoop::current();
+ struct OffThreadCompilation {
+ OffThreadCompiledProgram result;
+ Utf16String source_text;
+ };
- Threading::ThreadPool::the().submit([source_text = move(source_text), type, line_number_offset, cache_key = move(cache_key), callback, &main_thread_event_loop]() mutable {
+ auto compile = [source_text = move(source_text), type, line_number_offset]() mutable {
OffThreadCompiledProgram result { .parsed = JS::ParsedProgram::parse(source_text, type, line_number_offset) };
if (result.parsed && !result.parsed.has_errors())
result.compiled = JS::CompiledProgram::compile(move(result.parsed));
-
- main_thread_event_loop.deferred_invoke([result = move(result), source_text = move(source_text), cache_key = move(cache_key), callback]() mutable {
+ return OffThreadCompilation { .result = move(result), .source_text = move(source_text) };
+ };
+ Platform::run_on_thread_pool<OffThreadCompilation>(move(compile),
+ [cache_key = move(cache_key), run_callback = move(run_callback)](OffThreadCompilation compilation) mutable {
+ auto result = move(compilation.result);
if (cache_key.has_value() && result.compiled) {
// NB: Another load of the script may have stored it while this one compiled.
- if (auto cached_program = CompiledScriptCache::the().find(*cache_key, source_text); cached_program.has_value())
+ if (auto cached_program = CompiledScriptCache::the().find(*cache_key, compilation.source_text); cached_program.has_value())
result.compiled = cached_program.release_value();
else
- CompiledScriptCache::the().store(cache_key.release_value(), move(source_text), result.compiled);
+ CompiledScriptCache::the().store(cache_key.release_value(), move(compilation.source_text), result.compiled);
}
- (*callback)(move(result));
- delete callback;
+ run_callback(move(result));
});
- });
}
GC_DEFINE_ALLOCATOR(FetchContext);
diff --git a/Libraries/LibWeb/Platform/ThreadPoolWork.cpp b/Libraries/LibWeb/Platform/ThreadPoolWork.cpp
new file mode 100644
index 00000000000..e1c31732e69
--- /dev/null
+++ b/Libraries/LibWeb/Platform/ThreadPoolWork.cpp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashMap.h>
+#include <AK/NeverDestroyed.h>
+#include <LibWeb/Platform/ThreadPoolWork.h>
+
+namespace Web::Platform {
+
+static thread_local NeverDestroyed<HashMap<u64, ThreadPoolCompletion>> s_completions;
+static thread_local u64 s_next_completion_id { 1 };
+
+u64 add_thread_pool_completion(ThreadPoolCompletion completion)
+{
+ auto id = s_next_completion_id++;
+ s_completions->set(id, move(completion));
+ return id;
+}
+
+ThreadPoolCompletion take_thread_pool_completion(u64 id)
+{
+ return s_completions->take(id).value_or(nullptr);
+}
+
+void discard_thread_pool_completions()
+{
+ s_completions->clear();
+}
+
+}
diff --git a/Libraries/LibWeb/Platform/ThreadPoolWork.h b/Libraries/LibWeb/Platform/ThreadPoolWork.h
new file mode 100644
index 00000000000..4abf1483fbb
--- /dev/null
+++ b/Libraries/LibWeb/Platform/ThreadPoolWork.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/Types.h>
+#include <LibCore/EventLoop.h>
+#include <LibThreading/ThreadPool.h>
+#include <LibWeb/Export.h>
+
+namespace Web::Platform {
+
+// What waits for the thread pool on the thread that submitted the work. It stays on that thread, as it may hold GC roots,
+// and the pool's thread only ever sees its ID.
+using ThreadPoolCompletion = Function<void(void* result)>;
+
+WEB_API u64 add_thread_pool_completion(ThreadPoolCompletion);
+WEB_API ThreadPoolCompletion take_thread_pool_completion(u64 id);
+
+// Forgets every completion that is still waiting on this thread. An agent that goes away does this, so that nothing
+// keeps a root into its heap, and work that finishes later finds nothing to run.
+WEB_API void discard_thread_pool_completions();
+
+// Runs `work` on the thread pool and passes its result to `on_complete` on the event loop of this thread, unless that
+// event loop or the agent of this thread has gone away by then.
+template<typename Result, typename Work>
+void run_on_thread_pool(Work work, Function<void(Result)> on_complete)
+{
+ auto completion_id = add_thread_pool_completion([on_complete = move(on_complete)](void* result) mutable {
+ on_complete(move(*static_cast<Result*>(result)));
+ });
+
+ Threading::ThreadPool::the().submit([work = move(work), completion_id, event_loop = Core::EventLoop::current_weak()]() mutable {
+ Result result = work();
+
+ auto origin_event_loop = event_loop->take();
+ if (!origin_event_loop.is_alive())
+ return;
+ origin_event_loop->deferred_invoke([completion_id, result = move(result)]() mutable {
+ if (auto completion = take_thread_pool_completion(completion_id))
+ completion(&result);
+ });
+ });
+}
+
+}