Truly independent web browser
LibWebView+WebContent+WebWorker: Run dedicated workers on threads
Andreas Kling79c1bb7afbe3
diff --git a/Documentation/CrashReports.md b/Documentation/CrashReports.mdindex c3c91b1add7..aa33fa1e7d4 100644--- a/Documentation/CrashReports.md+++ b/Documentation/CrashReports.md@@ -2,8 +2,10 @@On macOS and Linux, Ladybird saves local text reports when the browser or ahelper process crashes: WebContent, WebWorker, RequestServer, ImageDecoder,-Compositor, MediaServer, AudioServer and VideoDecoderServer. Reports are stored-in+Compositor, MediaServer, AudioServer and VideoDecoderServer. A dedicated worker+runs on a thread of its owner's WebContent process, so its crash is a+WebContent crash and is reported as one; WebWorker reports come from shared+workers. Reports are stored in`~/Library/Application Support/Ladybird/CrashReports/` on macOS and`~/.local/share/Ladybird/CrashReports/` on Linux, or under`$XDG_DATA_HOME/Ladybird/CrashReports/` if that variable is set.diff --git a/Documentation/StatsLog.md b/Documentation/StatsLog.mdindex 2fd22cf41cd..6c0b0ce4c4b 100644--- a/Documentation/StatsLog.md+++ b/Documentation/StatsLog.md@@ -76,11 +76,14 @@ Unsupported values are omitted, rather than reported as zero.| `css.document_style_sheet_entries` | Sum of document style scopes' sheet vector sizes, excluding shadow scopes and adopted sheets || `fonts.face_entries` | Sum of registered documents' `FontFaceSet` sizes, including loading faces || `fonts.system_fallback_cache_entries` | Process-wide system fallback font cache map size, including cached misses, read under its mutex |+| `workers.agents` | Worker agents alive in this WebContent process, each on a thread of its own || `rendering.updates` | Main event loop's rendering updates run counter || `rendering.paints` | Main event loop's paint counter || `rendering.update_duration_us` | Main event loop's rendering update time counter, in microseconds |-GC values belong to the main VM heap in WebContent and WebWorker. Live sizes and completed durations+GC values belong to the main VM heap in WebContent and WebWorker. The logger never reads GC state+from another thread, so the heaps of dedicated workers, which run on threads of their owner's+WebContent process, are not sampled; their memory and CPU time show in the process values. Live sizes and completed durationsstart at zero until the first sweep finishes. Heap block bytes exclude the reserved address range,unused type-isolated chunks, weak blocks, and blocks retained for reuse or awaiting backgrounddecommit. They are not a measurement of resident memory or committed memory. No heap walk isdiff --git a/Documentation/TabPerformanceMonitor.md b/Documentation/TabPerformanceMonitor.mdindex 95b4f5ef2e8..db044118a78 100644--- a/Documentation/TabPerformanceMonitor.md+++ b/Documentation/TabPerformanceMonitor.md@@ -17,7 +17,8 @@ counter differencing and windowing independently of the UI and OS APIs.* **CPU:** CPU-time deltas divided by actual monotonic elapsed time. 100% isone logical CPU; values above 100% are expected. All live and terminated- threads in exclusively owned WebContent and WebWorker processes contribute.+ threads in exclusively owned WebContent and WebWorker processes contribute,+ so a dedicated worker counts under the WebContent process that hosts it.Registered page and embedded-frame ownership identify WebContent owners.Worker ownership is resolved transitively, including nested workers andshared workers whose owners all resolve to the same tab. Processes shareddiff --git a/Libraries/LibWebCommon/WebView/Utilities.h b/Libraries/LibWebCommon/WebView/Utilities.hindex bd493c67191..a73ac9add59 100644--- a/Libraries/LibWebCommon/WebView/Utilities.h+++ b/Libraries/LibWebCommon/WebView/Utilities.h@@ -16,6 +16,11 @@namespace WebView {+// What a WebContent process exits with, plus the signal, if a worker that runs on one of its threads crashes it. This+// tells such a crash from one of the process's own: the tests that crash a WebContent process on purpose have only the+// latter. It is above the 128 plus signal of an ordinary crash handler, so that it still reads as a crash.+constexpr int worker_thread_crash_exit_status = 192;+WEBCOMMON_API void platform_init(Optional<ByteString> ladybird_binary_path = {});WEBCOMMON_API ErrorOr<Vector<ByteString>> get_paths_for_helper_process(StringView process_name);diff --git a/Libraries/LibWebView/ImageDecoderManager.cpp b/Libraries/LibWebView/ImageDecoderManager.cppindex 293aefce830..89557386b67 100644--- a/Libraries/LibWebView/ImageDecoderManager.cpp+++ b/Libraries/LibWebView/ImageDecoderManager.cpp@@ -31,17 +31,17 @@ ErrorOr<IPC::TransportHandle> ImageDecoderManager::connect_new_client(u64 clientauto instance = m_instances.first_matching([&](auto const& instance) {if (site.has_value())return instance.site == site && instance.session.ptr() == session.ptr();- return !instance.site.has_value() && instance.client_child_ids.contains(client_child_id);+ return !instance.site.has_value() && instance.client_counts.contains(client_child_id);});auto channel = TRY(IPC::TransportHandle::create_pair());if (!instance.has_value()) {auto control_client = TRY(launch_image_decoder_process(client_child_id, site));- m_instances.append({ .control_client = move(control_client), .session = session, .site = move(site), .client_child_ids = {} });+ m_instances.append({ .control_client = move(control_client), .session = session, .site = move(site), .client_counts = {} });instance = m_instances.last();}instance->control_client->async_connect_new_client(channel.first);- instance->client_child_ids.set(client_child_id);+ ++instance->client_counts.ensure(client_child_id, [] { return 0uz; });return move(channel.second);}@@ -64,10 +64,10 @@ bool ImageDecoderManager::remove_client_from_decoder_of_site(u64 client_child_id{bool was_removed = false;m_instances.remove_all_matching([&](auto& instance) {- if (!instance.site.has_value() || !instance.client_child_ids.remove(client_child_id))+ if (!instance.site.has_value() || !instance.client_counts.remove(client_child_id))return false;was_removed = true;- return instance.client_child_ids.is_empty();+ return instance.client_counts.is_empty();});return was_removed;}@@ -75,7 +75,13 @@ bool ImageDecoderManager::remove_client_from_decoder_of_site(u64 client_child_idvoid ImageDecoderManager::process_did_release_decoder(u64 client_child_id){m_instances.remove_all_matching([&](auto& instance) {- return instance.client_child_ids.remove(client_child_id) && instance.client_child_ids.is_empty();+ auto count = instance.client_counts.find(client_child_id);+ if (count == instance.client_counts.end())+ return false;+ if (--count->value > 0)+ return false;+ instance.client_counts.remove(count);+ return instance.client_counts.is_empty();});}@@ -86,7 +92,7 @@ void ImageDecoderManager::process_did_exit(u64 child_id)m_instances.remove_all_matching([&](auto& instance) {if (instance.control_client->child_id() == child_id)return true;- return instance.client_child_ids.remove(child_id) && instance.client_child_ids.is_empty();+ return instance.client_counts.remove(child_id) && instance.client_counts.is_empty();});}diff --git a/Libraries/LibWebView/ImageDecoderManager.h b/Libraries/LibWebView/ImageDecoderManager.hindex 4d23a15866d..0cb095bd396 100644--- a/Libraries/LibWebView/ImageDecoderManager.h+++ b/Libraries/LibWebView/ImageDecoderManager.h@@ -6,7 +6,7 @@#pragma once-#include <AK/HashTable.h>+#include <AK/HashMap.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>#include <AK/Utf16String.h>@@ -49,7 +49,7 @@ public:// Returns whether the process was served by the decoder of a site, and so has to disconnect from it.bool remove_client_from_decoder_of_site(u64 client_child_id);- // Lets go of the decoder of a process that has disconnected from it, which ends once no other process uses it.+ // Lets go of one client that a process connected to its decoder, which ends once no process has a client left.void process_did_release_decoder(u64 client_child_id);void process_did_exit(u64 child_id);@@ -59,7 +59,8 @@ private:NonnullRefPtr<ImageDecoderControlClient> control_client;WeakPtr<BrowsingSession> session;Optional<Utf16String> site;- HashTable<u64> client_child_ids;+ // NB: The threads of a process each have a client of their own, and they let go of them one at a time.+ HashMap<u64, size_t> client_counts;};Vector<Instance> m_instances;diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 7a3d44297d4..c8771f21976 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -810,7 +810,7 @@ Messages::WebContentClient::StartWorkerAgentResponse WebContentClient::start_worif (auto* page = this->page(page_id))return page->start_worker_agent(move(request));- return Web::HTML::WorkerAgentId {};+ return { Web::HTML::WorkerAgentId {}, Optional<IPC::TransportHandle> {} };}void WebContentClient::did_close_browsing_context(Web::PageId page_id)@@ -1195,11 +1195,16 @@ void WebContentClient::did_host_document_of_site(Utf16String site)m_site_of_hosted_documents = move(site);}-Messages::WebContentClient::RequestImageDecoderConnectionResponse WebContentClient::request_image_decoder_connection()+Optional<IPC::TransportHandle> WebContentClient::connect_new_image_decoder_client(){return ImageDecoderManager::the().connect_requesting_process(child_id(), m_session, m_site_of_hosted_documents);}+Messages::WebContentClient::RequestImageDecoderConnectionResponse WebContentClient::request_image_decoder_connection()+{+ return connect_new_image_decoder_client();+}+void WebContentClient::did_release_image_decoder(){ImageDecoderManager::the().process_did_release_decoder(child_id());diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 393c82533c9..18ed288b8ad 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -127,6 +127,9 @@ public:// Documents with no site, such as those of an opaque origin, come with whatever made them, so they do not count.void did_host_document_of_site(Utf16String site);+ // Connects a client to the ImageDecoder of this process, for its main thread or for a worker on a thread of it.+ Optional<IPC::TransportHandle> connect_new_image_decoder_client();+// A process that has hosted local file content may read local files. Site isolation gives such content processes// of its own, which host nothing else.bool has_hosted_local_file_content() const { return m_has_hosted_local_file_content; }diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex acebd272a88..2a255075c27 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -3350,8 +3350,8 @@ Messages::WebContentClient::StartWorkerAgentResponse WebContentPage::start_worke{// A page hosting an isolated iframe's document belongs to its tab's view as much as the view's own page does.auto outside_settings = hosted_environment(request.outside_settings.id);- auto agent_id = WorkerProcessManager::the().start_worker_agent(client(), m_id, outside_settings, move(request));- return { agent_id };+ auto started_agent = WorkerProcessManager::the().start_worker_agent(client(), m_id, outside_settings, move(request));+ return { started_agent.agent_id, move(started_agent.thread_transport) };}Messages::WebContentClient::DidRequestStorageUsageResponse WebContentPage::did_request_storage_usage(Web::HTML::EnvironmentId environment_id)@@ -3365,7 +3365,7 @@ Messages::WebContentClient::DidRequestStorageUsageResponse WebContentPage::did_rvoid WebContentPage::did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message){if (auto settings = hosted_environment(message.environment_id); settings.has_value())- WorkerProcessManager::the().post_broadcast_channel_message(move(message), *settings, client().pid(), client().is_private());+ WorkerProcessManager::the().post_broadcast_channel_message(move(message), *settings, client(), client().is_private());}void WebContentPage::rtc_transform_init(Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record)diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cppindex ae949f605b7..3d56162667a 100644--- a/Libraries/LibWebView/WebWorkerClient.cpp+++ b/Libraries/LibWebView/WebWorkerClient.cpp@@ -15,6 +15,7 @@#include <LibWebView/HelperProcess.h>#include <LibWebView/ImageDecoderManager.h>#include <LibWebView/PermissionManager.h>+#include <LibWebView/WebContentClient.h>#include <LibWebView/WebWorkerClient.h>#include <LibWebView/WorkerProcessManager.h>@@ -38,10 +39,24 @@ WebWorkerClient::~WebWorkerClient()remove_blob_url_entries();}+void WebWorkerClient::set_host(WebContentClient& host)+{+ m_host = host;+ m_runs_on_thread = true;+ set_child_identity({ .child_id = host.child_id(), .pid = host.pid() });+}+void WebWorkerClient::did_misbehave(StringView message_name, StringView reason){+ // NB: A worker on a thread is one trust domain with its process, so all of that goes.+ if (auto host = m_host.strong_ref()) {+ host->did_misbehave(message_name, reason);+ shutdown();+ return;+ }dbgln("WebWorkerClient: terminating helper process {}: {} rejected: {}", pid(), message_name, reason);- terminate_process();+ if (!m_runs_on_thread)+ terminate_process();shutdown();}@@ -55,8 +70,14 @@ void WebWorkerClient::die()remove_blob_url_entries();WorkerProcessManager::the().worker_did_die(m_agent_id);- // NB: A worker whose connection is gone does no more work, so a process that outlives its connection is ended.- terminate_process();+ // NB: The process of a worker on a thread goes on, and so may its use of the decoder.+ if (m_holds_image_decoder_client)+ ImageDecoderManager::the().process_did_release_decoder(child_id());++ // NB: A worker whose connection is gone does no more work, so a process that outlives its connection is ended. A+ // thread closes the connection as it ends.+ if (!m_runs_on_thread)+ terminate_process();WorkerProcessManager::the().worker_process_did_exit(*this);// Otherwise nested workers we own would outlive us, in violation of the HTML spec.@@ -195,24 +216,35 @@ Messages::WebWorkerClient::RequestMediaServerConnectionResponse WebWorkerClient:Messages::WebWorkerClient::RequestImageDecoderConnectionResponse WebWorkerClient::request_image_decoder_connection(){- return ImageDecoderManager::the().connect_requesting_process(child_id(), session(), m_site);+ if (!m_runs_on_thread)+ return ImageDecoderManager::the().connect_requesting_process(child_id(), session(), m_site);++ // NB: A thread is part of its process, and what the decoder of a process may see goes by all that the process hosts.+ auto host = m_host.strong_ref();+ if (!host)+ return Optional<IPC::TransportHandle> {};+ auto handle = host->connect_new_image_decoder_client();+ m_holds_image_decoder_client |= handle.has_value();+ return handle;}void WebWorkerClient::did_release_image_decoder(){+ m_holds_image_decoder_client = false;ImageDecoderManager::the().process_did_release_decoder(child_id());}void WebWorkerClient::did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message){if (auto settings = hosted_environment(message.environment_id); settings.has_value())- WorkerProcessManager::the().post_broadcast_channel_message(move(message), *settings, pid(), m_is_private);+ WorkerProcessManager::the().post_broadcast_channel_message(move(message), *settings, *this, m_is_private);}Messages::WebWorkerClient::StartWorkerAgentResponse WebWorkerClient::start_worker_agent(Web::HTML::WorkerAgentStartRequest request){auto outside_settings = hosted_environment(request.outside_settings.id);- return WorkerProcessManager::the().start_worker_agent(*this, outside_settings, move(request));+ auto started_agent = WorkerProcessManager::the().start_worker_agent(*this, outside_settings, move(request));+ return { started_agent.agent_id, move(started_agent.thread_transport) };}void WebWorkerClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.hindex cf310e3cd31..a087fb7a45c 100644--- a/Libraries/LibWebView/WebWorkerClient.h+++ b/Libraries/LibWebView/WebWorkerClient.h@@ -47,10 +47,16 @@ public:RequestServerSiteBindings& request_server_site_bindings() { return m_request_server_site_bindings; }void remove_blob_url_entries();+ // The process of a worker on a thread is its host's. So, what these say and do is about that process.pid_t pid() const { return m_child_identity.pid; }u64 child_id() const { return m_child_identity.child_id; }void terminate_process();+ // The WebContent process that runs this worker on a thread. A worker with a process of its own has none.+ RefPtr<WebContentClient> host() const { return m_host.strong_ref(); }+ void set_host(WebContentClient&);+ bool runs_on_thread() const { return m_runs_on_thread; }+Optional<CanonicalEnvironmentSettingsObject const&> hosted_environment(Web::HTML::EnvironmentId const& environment_id) const;void set_child_identity(ChildIdentity identity) { m_child_identity = identity; }@@ -85,6 +91,9 @@ private:RequestServerSiteBindings m_request_server_site_bindings;ChildIdentity m_child_identity;+ WeakPtr<WebContentClient> m_host;+ bool m_runs_on_thread { false };+ bool m_holds_image_decoder_client { false };Web::HTML::WorkerAgentId m_agent_id { 0 };Vector<URL::Origin> m_permission_origins;diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex 58791b608e8..24477a8d814 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -24,7 +24,8 @@namespace WebView {-// Generous enough for a site that starts a worker per CPU core, as compute-heavy sites do.+// Generous enough for a site that starts a worker per CPU core, as compute-heavy sites do. A worker on a thread costs+// less than a process, but still has a heap, JIT threads and connections to itself, and one page can start them all.static constexpr size_t maximum_worker_count_per_top_level_site = 64;static constexpr auto worker_exit_grace_period = AK::Duration::from_seconds(5);@@ -38,7 +39,7 @@ WorkerProcessManager& WorkerProcessManager::the()return manager;}-Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(WebContentClient& owner, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request)+WorkerProcessManager::StartedWorkerAgent WorkerProcessManager::start_worker_agent(WebContentClient& owner, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request){auto abstract_owner = Owner {.client = WebContentOwner {@@ -50,7 +51,7 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(WebContentCliereturn start_worker_agent(move(abstract_owner), outside_settings, move(request), owner.is_private());}-Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(WebWorkerClient& owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request)+WorkerProcessManager::StartedWorkerAgent WorkerProcessManager::start_worker_agent(WebWorkerClient& owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request){auto abstract_owner = Owner {.client = WebWorkerOwner {@@ -70,21 +71,21 @@ Optional<CanonicalWorkerEnvironmentSettingsObject const&> WorkerProcessManager::}// https://html.spec.whatwg.org/multipage/workers.html#dom-sharedworker-Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request, IsPrivate is_private)+WorkerProcessManager::StartedWorkerAgent WorkerProcessManager::start_worker_agent(Owner owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request, IsPrivate is_private){// The owner names outside settings, which must be an environment it holds.// FIXME: The worker takes the rest of the outside settings, such as their top-level origin, policy container and// cross-origin isolated capability, as the owner's process gave them.if (!outside_settings.has_value()) {notify_worker_script_load_failure(owner);- return 0;+ return {};}request.outside_settings.origin = outside_settings->origin();// Only dedicated and shared workers are started on an owner's request.if (request.agent_type != Web::HTML::AgentType::DedicatedWorker && request.agent_type != Web::HTML::AgentType::SharedWorker) {notify_worker_script_load_failure(owner);- return 0;+ return {};}// NB: A worker shares the ancestors of the environment that creates it.@@ -144,7 +145,7 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, O|| agent.extended_lifetime != request.extended_lifetime|| (agent.worker_is_secure_context.has_value() && *agent.worker_is_secure_context != request.caller_is_secure_context)) {notify_worker_script_load_failure(owner);- return 0;+ return {};}// 11.5.8. Append the relevant owner to add given outsideSettings to@@ -155,7 +156,7 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Oagent.owners.append(owner);agent.extended_lifetime_timer = nullptr;agent.client->async_connect_shared_worker(move(request.outside_port), request.outside_settings);- return agent.id;+ return { agent.id, {} };}}@@ -163,14 +164,13 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, O}}- // NB: Each worker runs in a process of its own, so a top-level site may run only so many of them at once, wherever- // its documents and workers start them.- // An opaque top-level origin is a site of its own. A worker counts until its process is gone, and one whose- // creator's browsing context has been discarded, leaving it no top-level origin, does not start.+ // NB: A top-level site may run only so many workers at once, wherever its documents and workers start them.+ // An opaque top-level origin is a site of its own. A worker counts until its thread or process is gone, and one+ // whose creator's browsing context has been discarded, leaving it no top-level origin, does not start.auto top_level_origin = outside_settings->top_level_origin();if (!top_level_origin.has_value()) {notify_worker_script_load_failure(owner);- return 0;+ return {};}auto counts_toward_top_level_site = [&](IsPrivate worker_is_private, Optional<URL::Origin> const& worker_top_level_origin) {return worker_is_private == is_private && worker_top_level_origin.has_value() && worker_top_level_origin->is_same_site(*top_level_origin);@@ -186,16 +186,35 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, O}if (worker_count_of_top_level_site >= maximum_worker_count_per_top_level_site) {notify_worker_script_load_failure(owner);- return 0;+ return {};}// 11.6. Otherwise, in parallel, run a worker given worker, urlRecord, outsideSettings, outsidePort,// and options.- // AD-HOC: For DedicatedWorker there is no shared worker manager step; we always launch a fresh- // worker process here.+ // AD-HOC: For DedicatedWorker there is no shared worker manager step. It always gets a fresh thread in the process+ // of its owner, or a fresh process if its owner has none to give.auto agent_id = ++m_next_agent_id;+ RefPtr<WebContentClient> host;+ if (request.agent_type == Web::HTML::AgentType::DedicatedWorker) {+ host = owner.client.visit(+ [](WebContentOwner const& web_content_owner) -> RefPtr<WebContentClient> {+ return web_content_owner.client.strong_ref();+ },+ [](WebWorkerOwner const& web_worker_owner) -> RefPtr<WebContentClient> {+ return web_worker_owner.client->host();+ });+ }+ Optional<IPC::TransportHandle> thread_transport;auto client_or_error = [&]() -> ErrorOr<NonnullRefPtr<WebWorkerClient>> {- auto client = TRY(launch_web_worker_process(request.agent_type, is_private, agent_id));+ auto client = TRY([&]() -> ErrorOr<NonnullRefPtr<WebWorkerClient>> {+ if (!host)+ return launch_web_worker_process(request.agent_type, is_private, agent_id);+ auto transport = TRY(IPC::Transport::create_paired());+ thread_transport = move(transport.remote_handle);+ auto client = TRY(try_make_ref_counted<WebWorkerClient>(move(transport.local), is_private, agent_id));+ client->set_host(*host);+ return client;+ }());// The worker's RequestServer client uses the cookies of the session the worker itself belongs to.auto session = client->session();@@ -226,11 +245,11 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Oclient->async_connect_to_compositor(compositor_handle.release_value());return client;}();- // A worker the system cannot give a process fails to load, as one whose script cannot be fetched does.+ // A worker the system cannot give a thread or a process fails to load, as one whose script cannot be fetched does.if (client_or_error.is_error()) {- dbgln("Unable to start a worker process: {}", client_or_error.error());+ dbgln("Unable to start a worker: {}", client_or_error.error());notify_worker_script_load_failure(owner);- return 0;+ return {};}auto client = client_or_error.release_value();@@ -253,8 +272,8 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Oclient->set_site(URL::Site::serialize_for_partitioning(inside_settings->origin()));// NB: The task manager lists the worker's process with the process that started it, and once that one is gone,- // with the site of the worker's origin.- if (auto process = Application::process_manager().find_child(client->child_id()); process.has_value()) {+ // with the site of the worker's origin. A worker on a thread is part of a process that it lists already.+ if (auto process = Application::process_manager().find_child(client->child_id()); !host && process.has_value()) {owner.client.visit([&](WebContentOwner const& web_content_owner) {if (web_content_owner.client)@@ -326,7 +345,7 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Om_agents.set(agent_id, move(agent));client->async_start_worker(request.url, request.type, request.credentials, request.name, move(request.outside_port), request.outside_settings, request.agent_type, move(inside_origin), move(environment_id));- return agent_id;+ return { agent_id, move(thread_transport) };}void WorkerProcessManager::update_permission_snapshot(PermissionManager const& manager)@@ -427,7 +446,7 @@ void WorkerProcessManager::remove_web_worker_owner(WebWorkerClient& client)// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-postmessage// NB: The processes holding the destinations of step 6 are those hosting an environment whose storage key is// sourceStorageKey. Each finds the destinations among its own BroadcastChannel objects.-void WorkerProcessManager::post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage posted_message, CanonicalEnvironmentSettingsObject const& source_settings, pid_t source_process_id, IsPrivate is_private)+void WorkerProcessManager::post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage posted_message, CanonicalEnvironmentSettingsObject const& source_settings, IPC::ConnectionBase const& source_connection, IsPrivate is_private){// 4. Let sourceOrigin be this's relevant settings object's origin.// 5. Let sourceStorageKey be the result of running obtain a storage key for non-storage purposes with this's relevant@@ -443,7 +462,7 @@ void WorkerProcessManager::post_broadcast_channel_message(Web::HTML::PostedBroad};WebContentClient::for_each_client([&](auto& client) {- if (client.pid() == source_process_id || client.is_private() != is_private)+ if (&client == &source_connection || client.is_private() != is_private)return IterationDecision::Continue;if (client.hosts_an_environment_with_storage_key(source_storage_key))client.async_broadcast_channel_message(message);@@ -452,7 +471,7 @@ void WorkerProcessManager::post_broadcast_channel_message(Web::HTML::PostedBroadfor (auto& entry : m_agents) {auto& agent = entry.value;- if (agent.client->pid() == source_process_id || agent.is_private != is_private)+ if (agent.client.ptr() == &source_connection || agent.is_private != is_private)continue;if (obtain_a_storage_key_for_non_storage_purposes(*agent.inside_settings) == source_storage_key)agent.client->async_broadcast_channel_message(message);@@ -771,12 +790,16 @@ void WorkerProcessManager::remove_agent(Web::HTML::WorkerAgentId agent_id, Agentagent.client->async_close_worker();// NB: A worker busy running script handles no request to close, so its process is terminated if it has not exited- // in time. Until it exits, it counts toward the workers of its top-level site.- auto termination_timer = Core::Timer::create_single_shot(worker_exit_grace_period, [client = agent.client] {- if (client->is_open())- client->terminate_process();- });- termination_timer->start();+ // in time. A worker on a thread cannot be: its thread leaves as soon as it gets out of the builtin or the request+ // it may be in, and nothing waits for it. Until it is gone, it counts toward the workers of its top-level site.+ RefPtr<Core::Timer> termination_timer;+ if (!agent.client->runs_on_thread()) {+ termination_timer = Core::Timer::create_single_shot(worker_exit_grace_period, [client = agent.client] {+ if (client->is_open())+ client->terminate_process();+ });+ termination_timer->start();+ }m_exiting_workers.append({ agent.client, agent.is_private, move(agent.top_level_origin), move(termination_timer) });}@@ -866,8 +889,9 @@ Optional<u64> WorkerProcessManager::exclusive_performance_owner(pid_t pid) const}return result;};+ // NB: A worker on a thread has the process of its owner, which is not this worker's to speak for.for (auto const& agent : m_agents) {- if (agent.value.client->pid() == pid)+ if (agent.value.client->pid() == pid && !agent.value.client->runs_on_thread())return resolve(agent.value);}return {};diff --git a/Libraries/LibWebView/WorkerProcessManager.h b/Libraries/LibWebView/WorkerProcessManager.hindex 8365a38c294..7321ecf9f4c 100644--- a/Libraries/LibWebView/WorkerProcessManager.h+++ b/Libraries/LibWebView/WorkerProcessManager.h@@ -18,6 +18,8 @@#include <AK/WeakPtr.h>#include <AK/kmalloc.h>#include <LibCore/Forward.h>+#include <LibIPC/Forward.h>+#include <LibIPC/TransportHandle.h>#include <LibURL/Origin.h>#include <LibWebCommon/HTML/BroadcastChannelMessage.h>#include <LibWebCommon/HTML/WorkerAgentTypes.h>@@ -50,8 +52,13 @@ public:bool operator==(SharedWorkerKey const&) const = default;};- Web::HTML::WorkerAgentId start_worker_agent(WebContentClient&, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest);- Web::HTML::WorkerAgentId start_worker_agent(WebWorkerClient&, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest);+ // A worker that is to run on a thread of its owner's process comes with the transport that thread is to use.+ struct StartedWorkerAgent {+ Web::HTML::WorkerAgentId agent_id { 0 };+ Optional<IPC::TransportHandle> thread_transport;+ };+ StartedWorkerAgent start_worker_agent(WebContentClient&, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest);+ StartedWorkerAgent start_worker_agent(WebWorkerClient&, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest);Optional<CanonicalWorkerEnvironmentSettingsObject const&> inside_settings(Web::HTML::WorkerAgentId) const;void update_site_compatibility_data(JsonValue const&);// A worker's navigator reports what its owner's page reports, so a changed spoofing choice or language list@@ -69,7 +76,9 @@ public:void remove_web_content_owner(WebContentClient&);void remove_web_worker_owner(WebWorkerClient&);- void post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage, CanonicalEnvironmentSettingsObject const& source_settings, pid_t source_process_id, IsPrivate);+ // The agent behind the source connection has delivered the message to its own channels. Every other agent gets it+ // over its own connection, wherever it runs.+ void post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage, CanonicalEnvironmentSettingsObject const& source_settings, IPC::ConnectionBase const& source_connection, IsPrivate);void for_each_request_server_site_bindings(Function<IterationDecision(RequestServerSiteBindings&)> const&);ErrorOr<void> simulate_request_server_connection_loss_for_testing(WebContentClient&, Web::PageId page_id);@@ -108,7 +117,7 @@ private:Web::HTML::WorkerAgentOwnerToken token { 0 };};- Web::HTML::WorkerAgentId start_worker_agent(Owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest, IsPrivate);+ StartedWorkerAgent start_worker_agent(Owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest, IsPrivate);void notify_worker_script_load_failure(Owner const&);void notify_worker_exception(Owner const&, Utf16String const& message, Utf16String const& filename, u32 lineno, u32 colno);@@ -164,8 +173,8 @@ private:static bool is_same_owner(Owner const&, Owner const& identity);static void forget_removed_outside_settings_owner(WorkerAgent&);- // A worker whose agent is gone counts toward the workers of its top-level site until its process exits, or until its- // connection closes, which ends its process.+ // A worker whose agent is gone counts toward the workers of its top-level site until its connection closes: a thread+ // closes it as it ends, and that also ends a process.struct ExitingWorker {NonnullRefPtr<WebWorkerClient> client;IsPrivate is_private { IsPrivate::No };diff --git a/Services/WebContent/CMakeLists.txt b/Services/WebContent/CMakeLists.txtindex f3b98190f61..4ac22ab2c66 100644--- a/Services/WebContent/CMakeLists.txt+++ b/Services/WebContent/CMakeLists.txt@@ -32,7 +32,7 @@ target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${CMAKE_CUtarget_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${LADYBIRD_SOURCE_DIR}>)target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${LADYBIRD_SOURCE_DIR}/Services/>)-target_link_libraries(webcontentservice PUBLIC LibCompositing LibCore LibCrypto LibDevTools LibFileSystem LibGfx LibHTTP LibIPC LibJS LibMain LibAudio LibMedia LibWeb LibRequests LibImageDecoderClient LibMediaClient LibGC)+target_link_libraries(webcontentservice PUBLIC LibCompositing LibCore LibCrypto LibDevTools LibFileSystem LibGfx LibHTTP LibIPC LibJS LibMain LibAudio LibMedia LibWeb LibRequests LibImageDecoderClient LibMediaClient LibGC webworkerservice)target_link_libraries(webcontentservice PRIVATE OpenSSL::Crypto OpenSSL::SSL)target_compile_options(webcontentservice PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:-Wexit-time-destructors>)diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex dc3e1b2a745..7caaf95d618 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -113,6 +113,7 @@#include <WebContent/WebContentClientEndpoint.h>#include <WebContent/WebContentCompositorHost.h>#include <WebContent/WebDriverBiDi.h>+#include <WebWorker/WorkerThread.h>namespace WebContent {@@ -455,7 +456,11 @@ void ConnectionFromClient::connect_to_web_ui(Web::PageId page_id, IPC::Transportvoid ConnectionFromClient::disconnect_from_image_decoder(){- static_cast<Web::Platform::RemoteImageCodecPlugin&>(Web::Platform::ImageCodecPlugin::the()).disconnect_client();+ auto disconnect = [] {+ static_cast<Web::Platform::RemoteImageCodecPlugin&>(Web::Platform::ImageCodecPlugin::the()).disconnect_client();+ };+ disconnect();+ WebWorker::post_to_worker_threads(disconnect);}void ConnectionFromClient::connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle)@@ -1287,6 +1292,7 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString requestif (request == "clear-cache") {Web::Fetch::Fetching::clear_http_memory_cache();+ WebWorker::post_to_worker_threads(Web::Fetch::Fetching::clear_http_memory_cache);Web::CSS::StyleScope::release_kept_data();return;}diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 21d746ee677..682250e69df 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -79,6 +79,7 @@#include <WebContent/TestConnection.h>#include <WebContent/WebContentClientEndpoint.h>#include <WebContent/WebDriverConnection.h>+#include <WebWorker/WorkerThread.h>#include <WebContent/WebUIConnection.h>namespace WebContent {@@ -2269,6 +2270,12 @@ Web::HTML::WorkerAgentId PageClient::start_worker_agent(Web::HTML::WorkerAgentStCore::Process::terminate_immediately(0);}+ // NB: The UI process notices a transport that nobody takes up, and tells the owner that its worker is gone.+ if (auto transport = response->take_thread_transport(); transport.has_value()) {+ if (auto result = WebWorker::start_worker_thread(transport.release_value()); result.is_error())+ dbgln("Unable to start a thread for a worker: {}", result.error());+ }+return response->agent_id();}diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 8abed7cd4a6..c9b4a385da4 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -320,7 +320,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_find_in_page(Web::PageId page_id, size_t current_match_index, Optional<size_t> total_match_count) =|- [NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id)+ [NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport)[NotRouted] close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|rtc_transform_init(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) =|rtc_transform_teardown(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id) =|diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex 4749e0a1ab3..0b2a7b580ab 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -47,6 +47,7 @@#include <WebContent/PageClient.h>#include <WebContent/WebContentCompositorHost.h>#include <WebContent/WebDriverConnection.h>+#include <WebWorker/WorkerThread.h>#include <openssl/thread.h>@@ -79,7 +80,7 @@ static void crash_signal_handler(int signo)}warnln("\n\033[31;1mCRASH\033[0m: Received signal {} ({})", name, signo);dump_backtrace(2, 100);- Core::Process::terminate_immediately(128 + signo);+ Core::Process::terminate_immediately((WebWorker::is_worker_thread() ? WebView::worker_thread_crash_exit_status : 128) + signo);}static void install_crash_signal_handlers()@@ -320,6 +321,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)stats_log->start_sampling([&heap](JsonObject& values) {heap.add_stats(values);Web::HTML::main_thread_event_loop().add_stats(values);+ values.set("workers.agents"sv, Web::Bindings::worker_agent_count());values.set("fonts.system_fallback_cache_entries"sv, Gfx::system_fallback_font_cache_size());});}diff --git a/Services/WebWorker/CMakeLists.txt b/Services/WebWorker/CMakeLists.txtindex fe84711d673..8fbf97d4ca9 100644--- a/Services/WebWorker/CMakeLists.txt+++ b/Services/WebWorker/CMakeLists.txt@@ -3,6 +3,7 @@ set(WEBWORKER_SOURCESPageHost.cppWebWorkerCompositorHost.cppWorkerHost.cpp+ WorkerThread.cpp)# FIXME: Add Android service@@ -14,7 +15,7 @@ target_include_directories(webworkerservice PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/target_include_directories(webworkerservice PRIVATE ${LADYBIRD_SOURCE_DIR})target_include_directories(webworkerservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)-target_link_libraries(webworkerservice PUBLIC LibCore LibFileSystem LibGfx LibHTTP LibIPC LibJS LibRequests LibCompositing LibWeb LibUnicode LibImageDecoderClient LibMain LibMediaClient LibURL LibGC)+target_link_libraries(webworkerservice PUBLIC LibCore LibFileSystem LibGfx LibHTTP LibIPC LibJS LibRequests LibCompositing LibWeb LibUnicode LibImageDecoderClient LibMain LibMediaClient LibThreading LibURL LibGC)target_link_libraries(webworkerservice PRIVATE OpenSSL::Crypto OpenSSL::SSL)add_executable(WebWorker main.cpp)diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cppindex db56557de56..24fb6bf3e35 100644--- a/Services/WebWorker/ConnectionFromClient.cpp+++ b/Services/WebWorker/ConnectionFromClient.cpp@@ -9,7 +9,11 @@#include <LibCore/EventLoop.h>#include <LibCore/Process.h>#include <LibGC/Function.h>+#include <LibImageDecoderClient/Client.h>#include <LibJS/Runtime/ArrayBuffer.h>+#include <LibMediaClient/Client.h>+#include <LibRequests/RequestClient.h>+#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Compositor/CompositorConnection.h>@@ -30,19 +34,33 @@#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/PermissionsAPI/PermissionStore.h>#include <LibWeb/Platform/FontPlugin.h>+#include <LibWeb/Platform/ImageCodecPlugin.h>+#include <LibWeb/Platform/RemoteImageCodecPlugin.h>#include <LibWeb/WebRTC/RTCEncodedAudioFrame.h>#include <LibWeb/WebRTC/RTCRtpScriptTransformer.h>#include <LibWeb/WebRTC/RTCTransformEvent.h>#include <WebWorker/ConnectionFromClient.h>#include <WebWorker/PageHost.h>#include <WebWorker/WorkerHost.h>+#include <WebWorker/WorkerThread.h>namespace WebWorker {void ConnectionFromClient::connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site){- if (on_request_server_connection)- on_request_server_connection(handle, client_id, top_level_site);+ // NB: Without a client a fetch fails as a network error, and without a loader it would take the whole process down.+ if (!Web::ResourceLoader::is_initialized())+ Web::ResourceLoader::initialize(JS::VM::the().heap());++ auto connect = [&] -> ErrorOr<void> {+ auto transport = TRY(handle.create_transport());+ // Querying the client ID runs the event loop and could dispatch a request before the client is ready.+ auto request_client = TRY(try_make_ref_counted<Requests::RequestClient>(move(transport), client_id));+ Web::ResourceLoader::the().set_client(top_level_site, move(request_client));+ return {};+ };+ if (auto result = connect(); result.is_error())+ dbgln("Failed to connect to resource loader: {}", result.error());// A real connection loss defers this callback. Exercise the case where the replacement connection arrives before// that deferred callback runs.@@ -76,8 +94,13 @@ ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_image_decodvoid ConnectionFromClient::connect_to_compositor(IPC::TransportHandle handle){- auto transport = MUST(handle.create_transport());- m_compositor_connection = adopt_ref(*new Web::Compositor::CompositorConnection(move(transport)));+ // NB: This process may host a page too, so a worker without a compositor goes on without one.+ auto transport_or_error = handle.create_transport();+ if (transport_or_error.is_error()) {+ dbgln("Failed to connect to the compositor: {}", transport_or_error.error());+ return;+ }+ m_compositor_connection = adopt_ref(*new Web::Compositor::CompositorConnection(transport_or_error.release_value()));m_compositor_connection->on_compositor_lost = [this] {m_page_host->compositor_process_lost();};@@ -153,7 +176,37 @@ void ConnectionFromClient::die()void ConnectionFromClient::did_lose_peer_during_sync_request(){// NB: Whatever made the request cannot be unwound from here, and it cannot carry on without a response.- Core::Process::terminate_immediately(0);+ if (m_host == Host::Process)+ Core::Process::terminate_immediately(0);++ // NB: A thread cannot take its process with it, so the script stops instead, and the request fails. That is every+ // caller's to handle, as the connection is shut down from the event loop the script returns to.+ m_script_abort_handle->abort_script();+ deferred_invoke([this] {+ shutdown();+ });+}++void ConnectionFromClient::set_up_agent_services()+{+ MediaClient::Client::set_transport_factory([this] {+ return request_media_server_transport();+ });++ // Many workers never decode an image, so the Browser connects this one to a decoder when it first has one to decode.+ Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(+ [this] -> ErrorOr<NonnullRefPtr<ImageDecoderClient::Client>> {+ return try_make_ref_counted<ImageDecoderClient::Client>(TRY(request_image_decoder_transport()));+ },+ [this] { async_did_release_image_decoder(); }));+}++void ConnectionFromClient::shut_down_agent()+{+ release_agent_state();+ MediaClient::Client::set_transport_factory(nullptr);+ Web::Bindings::shut_down_agent();+ finish_shutdown();}void ConnectionFromClient::release_agent_state()@@ -169,8 +222,6 @@ void ConnectionFromClient::release_agent_state()m_pending_transform_inits.clear();m_requested_files.clear();m_request_server_died_callback_for_testing = nullptr;- on_request_server_connection = nullptr;- on_image_decoder_connection = nullptr;if (m_compositor_connection)m_compositor_connection->on_compositor_lost = nullptr;m_page_host = nullptr;@@ -200,14 +251,16 @@ void ConnectionFromClient::blob_url_entry_removed(Utf16String url)Web::FileAPI::remove_entry_from_blob_url_store(*url_record);}-ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, bool enable_test_mode)+ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, bool enable_test_mode, Host host): IPC::ConnectionFromClient<WebWorkerClientEndpoint, WebWorkerServerEndpoint>(*this, move(transport), 1), m_page_host(PageHost::create(*this)), m_enable_test_mode(enable_test_mode)+ , m_host(host)+ , m_script_abort_handle(Web::HTML::surrounding_agent().script_abort_handle()){- // The UI process spawned this process to run one worker agent, and die() ends it. So, once the UI process has- // closed the connection — e.g. because the page terminated the worker while this process was still starting — shut- // down right away, rather than handle startup messages and make sync requests on a closed connection.+ // The UI process started this worker agent, and die() ends it. So, once the UI process has closed the connection —+ // e.g. because the page terminated the worker while it was still starting — shut down right away, rather than handle+ // startup messages and make sync requests on a closed connection.set_peer_owns_this_process(true);Web::HTML::current_event_loop().set_on_destroyed([] {@@ -216,8 +269,7 @@ ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transpo// NB: The thread that handles close_worker() may be stuck in script, so that message and the loss of the client have// to abort the script from the IO thread, for this thread to get to them at all.- auto& agent = Web::HTML::surrounding_agent();- this->transport().set_incoming_message_observer([script_abort_handle = agent.script_abort_handle()](ReadonlyBytes message) {+ this->transport().set_incoming_message_observer([script_abort_handle = m_script_abort_handle](ReadonlyBytes message) {struct [[gnu::packed]] Header {u32 endpoint_magic;i32 message_id;diff --git a/Services/WebWorker/ConnectionFromClient.h b/Services/WebWorker/ConnectionFromClient.hindex d5390810f57..b4e233d35c2 100644--- a/Services/WebWorker/ConnectionFromClient.h+++ b/Services/WebWorker/ConnectionFromClient.h@@ -13,6 +13,7 @@#include <LibIPC/ConnectionFromClient.h>#include <LibJS/Forward.h>#include <LibWeb/Forward.h>+#include <LibWeb/HTML/Scripting/ScriptAbortHandle.h>#include <LibWeb/Loader/FileRequest.h>#include <LibWeb/WebRTC/RTCRtpScriptTransformer.h>#include <LibWebCommon/Forward.h>@@ -30,15 +31,23 @@ class ConnectionFromClient finalC_OBJECT(ConnectionFromClient);public:+ // What the worker agent has to itself: a process that ends with it, or a thread in a process that goes on without it.+ enum class Host {+ Process,+ Thread,+ };+virtual ~ConnectionFromClient() override;virtual void die() override;virtual void did_lose_peer_during_sync_request() override;- // The two ends of the shutdown of the worker agent, which go around Web::Bindings::shut_down_agent(). The connection- // outlives the heap, as cells in the heap use it until they are gone.- void release_agent_state();- void finish_shutdown();+ // Gives the agent of this thread its connections to other processes.+ void set_up_agent_services();++ // Ends the agent of this thread, in order. The connection outlives the heap, as cells in the heap use it until they+ // are gone.+ void shut_down_agent();virtual void set_font_service(IPC::TransportHandle, IPC::File catalog, u64 catalog_size, u64 generation) override;virtual void close_worker() override;@@ -50,15 +59,13 @@ public:Web::Compositor::CompositorConnection* compositor_process_connection() const;- Function<void(IPC::TransportHandle const&, Optional<int> client_id, Optional<Utf16String> const& top_level_site)> on_request_server_connection;-- // Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.+ // Asks the Browser to spawn this worker's MediaServer if it has none, and to connect a client to it.ErrorOr<NonnullOwnPtr<IPC::Transport>> request_media_server_transport();- // Asks the Browser to connect this process to its ImageDecoder.+ // Asks the Browser to connect this worker to the ImageDecoder of its process.ErrorOr<NonnullOwnPtr<IPC::Transport>> request_image_decoder_transport();private:- ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, bool enable_test_mode);+ ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, bool enable_test_mode, Host = Host::Process);Web::Page& page();Web::Page const& page() const;@@ -100,11 +107,15 @@ private:void run_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record);void begin_closing();+ void release_agent_state();+ void finish_shutdown();RefPtr<WorkerHost> m_worker_host;Function<void()> m_request_server_died_callback_for_testing;bool m_enable_test_mode { false };bool m_shutdown_finished { false };+ Host m_host { Host::Process };+ NonnullRefPtr<Web::HTML::ScriptAbortHandle> m_script_abort_handle;};}diff --git a/Services/WebWorker/PageHost.cpp b/Services/WebWorker/PageHost.cppindex f6cf841f292..1d0f28c6f0f 100644--- a/Services/WebWorker/PageHost.cpp+++ b/Services/WebWorker/PageHost.cpp@@ -9,6 +9,7 @@#include <WebWorker/ConnectionFromClient.h>#include <WebWorker/PageHost.h>#include <WebWorker/WebWorkerCompositorHost.h>+#include <WebWorker/WorkerThread.h>namespace WebWorker {@@ -97,14 +98,20 @@ Optional<Web::Permissions::PermissionSnapshot> PageHost::page_did_request_permisreturn response->take_snapshot();}+// NB: The sync requests here fail once the worker is terminated or the UI process is gone. The script that made one no+// longer runs by then, so what it gets back here does not matter, but it has to get something.HTTP::Cookie::VersionedCookie PageHost::page_did_request_cookie(Optional<Web::HTML::EnvironmentId> const&, URL::URL const& url, HTTP::Cookie::Source source){- return m_client.did_request_cookie(url, source);+ auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::DidRequestCookie>(url, source);+ if (!response)+ return {};+ return response->take_cookie();}bool PageHost::page_did_is_known_hsts_host(String const& domain){- return m_client.did_is_known_hsts_host(domain);+ auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::DidIsKnownHstsHost>(domain);+ return response && response->result();}void PageHost::page_did_report_worker_exception(Utf16String const& message, Utf16String const& filename, u32 lineno, u32 colno)@@ -130,22 +137,37 @@ void PageHost::request_file(Web::FileRequest request)URL::BlobURLEntry::Token PageHost::page_did_add_blob_url_entry(Web::HTML::EnvironmentSettingsObject const& environment, Utf16String const& url, Web::FileAPI::SerializedBlobURLEntry const& entry){- return m_client.did_add_blob_url_entry(environment.id, url, entry);+ auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::DidAddBlobUrlEntry>(environment.id, url, entry);+ if (!response)+ return 0;+ return response->token();}void PageHost::page_did_remove_blob_url_entries(Web::HTML::EnvironmentSettingsObject const& environment, Vector<Utf16String> const& urls){- m_client.did_remove_blob_url_entries(environment.id, urls);+ (void)m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::DidRemoveBlobUrlEntries>(environment.id, urls);}Optional<Web::FileAPI::SerializedBlobURLEntry> PageHost::page_did_request_blob_url_entry(Utf16String const& url, Optional<URL::BlobURLEntry::Token> token){- return m_client.did_request_blob_url_entry(url, token);+ auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::DidRequestBlobUrlEntry>(url, token);+ if (!response)+ return {};+ return response->take_entry();}Web::HTML::WorkerAgentId PageHost::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request){- return m_client.start_worker_agent(move(request));+ auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::StartWorkerAgent>(move(request));+ if (!response)+ return 0;++ // NB: The UI process notices a transport that nobody takes up, and tells the owner that its worker is gone.+ if (auto transport = response->take_thread_transport(); transport.has_value()) {+ if (auto result = start_worker_thread(transport.release_value()); result.is_error())+ dbgln("Unable to start a thread for a worker: {}", result.error());+ }+ return response->agent_id();}void PageHost::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Services/WebWorker/PageHost.h b/Services/WebWorker/PageHost.hindex 0d4c0644513..c38500040ac 100644--- a/Services/WebWorker/PageHost.h+++ b/Services/WebWorker/PageHost.h@@ -25,7 +25,8 @@ public:virtual ~PageHost();- virtual Web::PageId id() const override { VERIFY_NOT_REACHED(); }+ // NB: A worker has no page in the UI process, so nothing there knows this ID.+ virtual Web::PageId id() const override { return 0; }virtual Web::Page& page() override;virtual Web::Page const& page() const override;virtual bool is_connection_open() const override;@@ -55,10 +56,12 @@ public:virtual Web::Compositor::CompositorHost* compositor_host() override { return m_compositor_host.ptr(); }virtual Web::Compositor::CompositorHost const* compositor_host() const override { return m_compositor_host.ptr(); }void compositor_process_lost();- virtual bool is_headless() const override { VERIFY_NOT_REACHED(); }- virtual Queue<Web::QueuedInputEvent>& input_event_queue() override { VERIFY_NOT_REACHED(); }- virtual void report_finished_handling_input_event([[maybe_unused]] Web::PageId page_id, [[maybe_unused]] u64 event_id, [[maybe_unused]] Web::EventResult event_was_handled) override { VERIFY_NOT_REACHED(); }- virtual void request_frame() override { VERIFY_NOT_REACHED(); }+ virtual bool is_headless() const override { return false; }+ // NB: No input reaches a worker, so its queue stays empty.+ virtual Queue<Web::QueuedInputEvent>& input_event_queue() override { return m_input_event_queue; }+ virtual void report_finished_handling_input_event([[maybe_unused]] Web::PageId page_id, [[maybe_unused]] u64 event_id, [[maybe_unused]] Web::EventResult event_was_handled) override { }+ // NB: A worker's event loop schedules its own rendering, and nothing else here asks for a frame.+ virtual void request_frame() override { }virtual double maximum_frames_per_second() const override { return m_maximum_frames_per_second; }void set_maximum_frames_per_second(double maximum_frames_per_second) { m_maximum_frames_per_second = maximum_frames_per_second; }void did_finish_loading_worker_script(bool worker_is_secure_context);@@ -74,6 +77,7 @@ private:OwnPtr<Web::Compositor::CompositorHost> m_compositor_host;GC::Ref<Web::Page> m_page;RefPtr<Gfx::PaletteImpl> m_palette_impl;+ Queue<Web::QueuedInputEvent> m_input_event_queue;double m_maximum_frames_per_second { 60.0 };};diff --git a/Services/WebWorker/WebWorkerClient.ipc b/Services/WebWorker/WebWorkerClient.ipcindex 1b141368477..4edb945cf07 100644--- a/Services/WebWorker/WebWorkerClient.ipc+++ b/Services/WebWorker/WebWorkerClient.ipc@@ -27,7 +27,7 @@ endpoint WebWorkerClient {request_image_decoder_connection() => (Optional<IPC::TransportHandle> handle)did_release_image_decoder() =|did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) =|- start_worker_agent(Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id)+ start_worker_agent(Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport)close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|rtc_transform_encoded_audio_frame_written(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|diff --git a/Services/WebWorker/WorkerThread.cpp b/Services/WebWorker/WorkerThread.cppnew file mode 100644index 00000000000..74ae31c10dd--- /dev/null+++ b/Services/WebWorker/WorkerThread.cpp@@ -0,0 +1,96 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Mutex.h>+#include <AK/NeverDestroyed.h>+#include <AK/NonnullRefPtr.h>+#include <AK/Vector.h>+#include <LibCore/EventLoop.h>+#include <LibIPC/Transport.h>+#include <LibIPC/TransportHandle.h>+#include <LibJS/Runtime/VM.h>+#include <LibThreading/Thread.h>+#include <LibWeb/Bindings/MainThreadVM.h>+#include <WebWorker/ConnectionFromClient.h>+#include <WebWorker/WorkerThread.h>++namespace WebWorker {++struct WorkerThreads {+ Mutex mutex;+ Vector<NonnullRefPtr<Core::WeakEventLoopReference>> event_loops;+};++static WorkerThreads& worker_threads()+{+ static NeverDestroyed<WorkerThreads> threads;+ return *threads;+}++static thread_local bool s_is_worker_thread { false };++bool is_worker_thread()+{+ return s_is_worker_thread;+}++static intptr_t run_worker_thread(IPC::TransportHandle const& worker_handle)+{+ s_is_worker_thread = true;++ auto transport_or_error = worker_handle.create_transport();+ if (transport_or_error.is_error()) {+ dbgln("Unable to take up the transport of a worker: {}", transport_or_error.error());+ return 1;+ }++ Core::EventLoop event_loop;+ Web::Bindings::initialize_agent(Web::HTML::AgentType::DedicatedWorker);++ auto event_loop_reference = Core::EventLoop::current_weak();+ {+ MutexLocker locker(worker_threads().mutex);+ worker_threads().event_loops.append(event_loop_reference);+ }++ auto client = ConnectionFromClient::construct(transport_or_error.release_value(), false, ConnectionFromClient::Host::Thread);+ client->set_up_agent_services();++ auto exit_code = event_loop.exec();++ {+ MutexLocker locker(worker_threads().mutex);+ worker_threads().event_loops.remove_first_matching([&](auto const& reference) { return reference.ptr() == event_loop_reference.ptr(); });+ }++ client->shut_down_agent();+ return exit_code;+}++ErrorOr<void> start_worker_thread(IPC::TransportHandle worker_handle)+{+ auto thread = TRY(Threading::Thread::try_create("WebWorker"sv, [worker_handle = move(worker_handle)] {+ return run_worker_thread(worker_handle);+ }));+ thread->set_stack_size(JS::VM::MINIMUM_THREAD_STACK_SIZE);++ TRY(thread->try_start());++ // NB: Nothing waits for a worker's thread: one that is stuck in a long builtin must not hold up anything else.+ thread->detach();+ return {};+}++void post_to_worker_threads(void (*function)())+{+ MutexLocker locker(worker_threads().mutex);+ for (auto& reference : worker_threads().event_loops) {+ if (auto event_loop = reference->take(); event_loop.is_alive())+ event_loop->deferred_invoke([function] { function(); });+ }+}++}diff --git a/Services/WebWorker/WorkerThread.h b/Services/WebWorker/WorkerThread.hnew file mode 100644index 00000000000..64365b2f624--- /dev/null+++ b/Services/WebWorker/WorkerThread.h@@ -0,0 +1,26 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Error.h>+#include <LibIPC/Forward.h>++namespace WebWorker {++// Starts a thread that hosts a dedicated worker agent, which talks to the UI process over the given transport as a worker+// process does. Nothing ever waits for the thread: it ends once its worker has closed, and otherwise with the process. A+// process that exits takes running workers with it, so it has to leave by Core::Process::terminate_immediately().+ErrorOr<void> start_worker_thread(IPC::TransportHandle);++// Whether the calling thread is one start_worker_thread() started. This can be asked from a signal handler.+bool is_worker_thread();++// Runs the function on each worker thread of this process, from its event loop. The thread may be stuck in script for a+// while before it gets to this.+void post_to_worker_threads(void (*)());++}diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cppindex ac4f538dd97..2eafbf61dd8 100644--- a/Services/WebWorker/main.cpp+++ b/Services/WebWorker/main.cpp@@ -17,11 +17,7 @@#include <LibFileSystem/FileSystem.h>#include <LibIPC/SingleServer.h>#include <LibIPC/Transport.h>-#include <LibIPC/TransportHandle.h>-#include <LibImageDecoderClient/Client.h>#include <LibMain/Main.h>-#include <LibMediaClient/Client.h>-#include <LibRequests/RequestClient.h>#include <LibURL/Parser.h>#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/Fetch/Fetching/Fetching.h>@@ -29,15 +25,12 @@#include <LibWeb/Loader/GeneratedPagesLoader.h>#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/Platform/RemoteImageCodecPlugin.h>#include <LibWebCommon/WebView/Utilities.h>#include <Services/RendererSandbox.h>#include <WebWorker/ConnectionFromClient.h>#include <openssl/thread.h>-static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site);-static ErrorOr<Web::HTML::AgentType> agent_type_from_string(StringView type){if (type == "dedicated"sv)@@ -136,22 +129,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto client = TRY(IPC::take_over_accepted_client_from_system_server<WebWorker::ConnectionFromClient>(mach_server_name, enable_test_mode));- auto& heap = JS::VM::the().heap();- client->on_request_server_connection = [&heap](auto const& handle, auto client_id, auto const& top_level_site) {- if (auto result = connect_to_resource_loader(heap, handle, client_id, top_level_site); result.is_error())- dbgln("Failed to connect to resource loader: {}", result.error());- };- // Many workers never decode an image, so the Browser connects this one to a decoder when it first has one to decode.- Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(- [client] -> ErrorOr<NonnullRefPtr<ImageDecoderClient::Client>> {- return try_make_ref_counted<ImageDecoderClient::Client>(TRY(client->request_image_decoder_transport()));- },- [client] { client->async_did_release_image_decoder(); }));-- MediaClient::Client::set_transport_factory([client] {- return client->request_media_server_transport();- });+ client->set_up_agent_services();+ auto& heap = JS::VM::the().heap();if (stats_log)stats_log->start_sampling([&heap](JsonObject& values) { heap.add_stats(values); });@@ -160,26 +140,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)// The worker has closed. This goes through its agent in order, as a thread that hosts a worker will have to, rather// than leave it all to the end of the process.stats_log = nullptr;- client->release_agent_state();- MediaClient::Client::set_transport_factory(nullptr);- Web::Bindings::shut_down_agent();- client->finish_shutdown();+ client->shut_down_agent();// The client terminates a process that closes the connection, so the connection stays open until this process ends.(void)move(client).leak_ref();return exit_code;}--static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site)-{- auto transport = TRY(handle.create_transport());- // Querying the client ID runs the event loop and could dispatch a request before the client is ready.- auto request_client = client_id.has_value()- ? TRY(try_make_ref_counted<Requests::RequestClient>(move(transport), *client_id))- : TRY(try_make_ref_counted<Requests::RequestClient>(move(transport)));- if (!Web::ResourceLoader::is_initialized())- Web::ResourceLoader::initialize(heap);- Web::ResourceLoader::the().set_client(top_level_site, move(request_client));- return {};-}diff --git a/Tests/LibWebView/TestImageDecoderIsolation.cpp b/Tests/LibWebView/TestImageDecoderIsolation.cppindex f0a1f61ece7..568067d5b72 100644--- a/Tests/LibWebView/TestImageDecoderIsolation.cpp+++ b/Tests/LibWebView/TestImageDecoderIsolation.cpp@@ -330,6 +330,20 @@ TEST_CASE(image_decoders_end_once_released)manager.process_did_release_decoder(2'000'002);Core::EventLoop::current().spin_until([&] { return decoder_count() == 0; });+ // Each worker on a thread of a process has a client of its own, and the process keeps the decoder until all let go.+ Optional<IPC::TransportHandle> page_client = MUST(manager.connect_new_client(2'000'004, session, site));+ Optional<IPC::TransportHandle> worker_client = MUST(manager.connect_new_client(2'000'004, session, site));+ VERIFY(decoder_count() == 1);+ worker_client.clear();+ manager.process_did_release_decoder(2'000'004);+ Optional<IPC::TransportHandle> client_of_same_site = MUST(manager.connect_new_client(2'000'005, session, site));+ VERIFY(decoder_count() == 1);+ page_client.clear();+ client_of_same_site.clear();+ manager.process_did_release_decoder(2'000'004);+ manager.process_did_release_decoder(2'000'005);+ Core::EventLoop::current().spin_until([&] { return decoder_count() == 0; });+// A process that has let go of its decoder gets a new one when it next asks.auto handle = MUST(manager.connect_new_client(2'000'003, session, {}));VERIFY(decoder_count() == 1);diff --git a/Tests/LibWebView/test-webdriver-crash-report.py b/Tests/LibWebView/test-webdriver-crash-report.pyindex 8019915996c..e9f6a61c70d 100755--- a/Tests/LibWebView/test-webdriver-crash-report.py+++ b/Tests/LibWebView/test-webdriver-crash-report.py@@ -99,10 +99,10 @@ def run_test(webdriver_binary, process_name):{"script": """const done = arguments[0];- window.worker = new Worker(URL.createObjectURL(new Blob([- "postMessage('ready'); onmessage = () => {};"+ window.worker = new SharedWorker(URL.createObjectURL(new Blob([+ "onconnect = ({ ports }) => ports[0].postMessage('ready');"], {type: 'text/javascript'})));- worker.onmessage = () => done();+ worker.port.onmessage = () => done();worker.onerror = () => done('worker failed');""","args": [],diff --git a/Tests/LibWebView/test-webdriver-worker-terminated-while-starting.py b/Tests/LibWebView/test-webdriver-worker-terminated-while-starting.pyindex f39c19fac27..bd18b4db0af 100755--- a/Tests/LibWebView/test-webdriver-worker-terminated-while-starting.py+++ b/Tests/LibWebView/test-webdriver-worker-terminated-while-starting.py@@ -62,7 +62,7 @@ def run_test(webdriver_binary):)assert status == 200, body- # Each worker's process is launched before its constructor returns, and is still starting up when+ # Each worker's thread is started before its constructor returns, and is still starting up when# terminate() tears the worker down.status, payload, body = webdriver_helpers.request(port,@@ -91,14 +91,11 @@ def run_test(webdriver_binary):)assert status == 200 and payload == {"value": None}, body- deadline = time.monotonic() + webdriver_helpers.EVENT_TIMEOUT_SECONDS- while descendants_named(webdriver.pid, "WebWorker"):- if time.monotonic() >= deadline:- raise AssertionError("A terminated worker's process never exited")- time.sleep(0.05)+ assert not descendants_named(webdriver.pid, "WebWorker"), "A dedicated worker got a process"+ # A worker that crashes on its way out takes the WebContent process that hosts it along.time.sleep(CRASH_REPORT_GRACE_SECONDS)- reports = list((profile / "data/CrashReports").glob("*-WebWorker-*.txt"))+ reports = list((profile / "data/CrashReports").glob("*-WebContent-*.txt"))assert not reports, reports[0].read_text()webdriver_helpers.request(port, "DELETE", f"/session/{session}")