Truly independent web browser
LibWeb+LibWebView+WebContent: Start a dedicated worker from its owner
Aliaksandr Kalenikd48145ebfce8
diff --git a/Libraries/LibWeb/HTML/DedicatedWorkerThreadLink.h b/Libraries/LibWeb/HTML/DedicatedWorkerThreadLink.hindex 6c2c9caa8c5..83ad3e4382a 100644--- a/Libraries/LibWeb/HTML/DedicatedWorkerThreadLink.h+++ b/Libraries/LibWeb/HTML/DedicatedWorkerThreadLink.h@@ -16,6 +16,8 @@ class DedicatedWorkerThreadLink : public AtomicRefCounted<DedicatedWorkerThreadLpublic:virtual ~DedicatedWorkerThreadLink() = default;+ virtual void terminate() = 0;+virtual void rtc_transform_init(u64 transform_id, SerializedTransferRecord options_record) = 0;virtual void rtc_transform_teardown(u64 transform_id) = 0;virtual void rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) = 0;diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cppindex de1091428f4..f5503333e41 100644--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp@@ -131,23 +131,27 @@ void WorkerAgentParent::start().owner_token = m_owner_token,};+ worker_agent_parents().set(m_owner_token, *this);+ auto& page_client = Bindings::principal_host_defined_page(realm).client();++ if (m_agent_type == AgentType::DedicatedWorker) {+ m_dedicated_worker_thread_link = page_client.start_dedicated_worker(move(request));+ if (!m_dedicated_worker_thread_link) {+ dispatch_error_event();+ forget_agent();+ }+ return;+ }+// NB: This blocking IPC call may launch another process.// If spinning the event loop for this can cause other javascript to execute, we're in trouble.- worker_agent_parents().set(m_owner_token, *this);- auto started_agent = Bindings::principal_host_defined_page(realm).client().start_worker_agent(move(request));+ auto started_agent = page_client.start_worker_agent(move(request));m_agent_id = started_agent.agent_id;- m_dedicated_worker_thread_link = move(started_agent.dedicated_worker_thread_link);-if (m_agent_id == 0) {dispatch_error_event();forget_agent();return;}- if (m_agent_type == AgentType::DedicatedWorker && !m_dedicated_worker_thread_link) {- dispatch_error_event();- terminate();- return;- }// NB: This is before any script can use the port, so that it finds out right now whether its peer is in this process.if (!started_agent.is_hosted_in_this_process)@@ -205,6 +209,12 @@ void WorkerAgentParent::did_worker_agent_die(WorkerAgentOwnerToken owner_token)void WorkerAgentParent::terminate(){+ if (auto dedicated_worker_thread_link = m_dedicated_worker_thread_link) {+ forget_agent();+ dedicated_worker_thread_link->terminate();+ return;+ }+if (m_agent_id == 0)return;@@ -290,7 +300,7 @@ void WorkerAgentParent::finalize()worker_agent_parents().remove(m_owner_token);if (!heap().is_collecting_everything())- VERIFY(m_agent_id == 0);+ VERIFY(m_agent_id == 0 && !m_dedicated_worker_thread_link);}void WorkerAgentParent::visit_edges(Cell::Visitor& visitor)diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 9e3b1ea17c4..fd2be957f7f 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -1020,9 +1020,9 @@ public:struct StartedWorkerAgent {HTML::WorkerAgentId agent_id { 0 };bool is_hosted_in_this_process { false };- RefPtr<HTML::DedicatedWorkerThreadLink> dedicated_worker_thread_link;};virtual StartedWorkerAgent start_worker_agent([[maybe_unused]] HTML::WorkerAgentStartRequest&& request) { return {}; }+ virtual RefPtr<HTML::DedicatedWorkerThreadLink> start_dedicated_worker([[maybe_unused]] HTML::WorkerAgentStartRequest&& request) { return {}; }virtual void close_worker_agent([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] HTML::WorkerAgentOwnerToken owner_token) { }virtual void page_did_mutate_dom([[maybe_unused]] Utf16FlyString const& type, [[maybe_unused]] DOM::Node const& target, [[maybe_unused]] DOM::NodeList& added_nodes, [[maybe_unused]] DOM::NodeList& removed_nodes, [[maybe_unused]] GC::Ptr<DOM::Node> previous_sibling, [[maybe_unused]] GC::Ptr<DOM::Node> next_sibling, [[maybe_unused]] Optional<Utf16FlyString> const& attribute_name) { }diff --git a/Libraries/LibWebCommon/HTML/WorkerAgentTypes.h b/Libraries/LibWebCommon/HTML/WorkerAgentTypes.hindex a95fa799ef7..4b83cc029c1 100644--- a/Libraries/LibWebCommon/HTML/WorkerAgentTypes.h+++ b/Libraries/LibWebCommon/HTML/WorkerAgentTypes.h@@ -18,6 +18,11 @@namespace Web::HTML {+// 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.+// The Browser allows this many per top-level site, and a WebContent process this many on its threads.+static constexpr size_t maximum_worker_count = 64;+struct WEBCOMMON_API WorkerAgentStartRequest {URL::URL url;AgentType agent_type { AgentType::DedicatedWorker };diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex e9f096ef721..7e4a1eec2cd 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -823,6 +823,12 @@ Messages::WebContentClient::StartWorkerAgentResponse WebContentClient::start_worreturn { Web::HTML::WorkerAgentId {}, Optional<IPC::TransportHandle> {}, false };}+void WebContentClient::register_dedicated_worker(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport)+{+ if (auto* page = this->page(page_id))+ page->register_dedicated_worker(move(request), move(worker_transport));+}+void WebContentClient::did_close_browsing_context(Web::PageId page_id){if (auto* page = this->page(page_id)) {diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 544fb21e35c..db3ca5e7ad8 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -231,6 +231,7 @@ private:virtual Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;virtual Messages::WebContentClient::DidRequestNewWebViewResponse did_request_new_web_view(Web::PageId page_id, Web::HTML::ActivateTab, Web::HTML::WebViewHints, Web::HTML::CrossProcessId current_navigable_id, Utf16String name, bool no_opener, Optional<URL::URL> current_document_base_url) override;virtual Messages::WebContentClient::StartWorkerAgentResponse start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) override;+ virtual void register_dedicated_worker(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport) override;virtual void did_update_cookie(HTTP::Cookie::Cookie) override;virtual Messages::WebContentClient::DidIsKnownHstsHostResponse did_is_known_hsts_host(String) override;virtual Messages::WebContentClient::DidLoseRequestServerConnectionResponse did_lose_request_server_connection(Optional<Utf16String> top_level_site) override;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex b6e918d096f..1fb6f787916 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -3357,6 +3357,12 @@ Messages::WebContentClient::StartWorkerAgentResponse WebContentPage::start_workereturn { started_agent.agent_id, move(started_agent.thread_transport), started_agent.is_hosted_in_owner_process };}+void WebContentPage::register_dedicated_worker(Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport)+{+ auto outside_settings = hosted_environment(request.outside_settings.id);+ WorkerAgentManager::the().register_dedicated_worker(client(), m_id, outside_settings, move(request), move(worker_transport));+}+Messages::WebContentClient::DidRequestStorageUsageResponse WebContentPage::did_request_storage_usage(Web::HTML::EnvironmentId environment_id){auto canonical_key = canonical_storage_key(environment_id);diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 0224e802730..6b095404ad9 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -388,6 +388,7 @@ private:virtual void did_request_pinch_event_for_testing(Web::HTML::CrossProcessId local_root_id, Web::PinchEvent event) override;virtual void request_unload_check(Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId check_id) override;Messages::WebContentClient::StartWorkerAgentResponse start_worker_agent(Web::HTML::WorkerAgentStartRequest request);+ void register_dedicated_worker(Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport);Messages::WebContentClient::DidRequestStorageUsageResponse did_request_storage_usage(Web::HTML::EnvironmentId environment_id);virtual void did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) override;Messages::WebContentClient::DidRequestCookieResponse did_request_cookie(Optional<Web::HTML::EnvironmentId> const&, URL::URL, HTTP::Cookie::Source);diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cppindex 149baf40392..632ab48b541 100644--- a/Libraries/LibWebView/WebWorkerClient.cpp+++ b/Libraries/LibWebView/WebWorkerClient.cpp@@ -66,13 +66,11 @@ void WebWorkerClient::die()ImageDecoderManager::the().process_did_release_decoder(child_id(), *m_image_decoder_client_generation);WorkerAgentManager::the().worker_thread_did_exit(*this);-- // Otherwise nested workers we own would outlive us, in violation of the HTML spec.- WorkerAgentManager::the().remove_web_worker_owner(*this);}void WebWorkerClient::did_close_worker(){+ forget_inside_settings_of_closing_worker();WorkerAgentManager::the().worker_did_close(m_agent_id);}@@ -110,7 +108,7 @@ void WebWorkerClient::set_inside_settings(NonnullOwnPtr<CanonicalWorkerEnvironmem_may_read_local_files = may_read_local_files;}-void WebWorkerClient::forget_inside_settings_of_removed_agent()+void WebWorkerClient::forget_inside_settings_of_closing_worker(){m_inside_settings = nullptr;m_script_blob_url = {};@@ -257,16 +255,10 @@ void WebWorkerClient::did_post_broadcast_channel_message(Web::HTML::PostedBroadcWorkerAgentManager::the().post_broadcast_channel_message(move(message), *settings, *this, m_is_private);}-Messages::WebWorkerClient::StartWorkerAgentResponse WebWorkerClient::start_worker_agent(Web::HTML::WorkerAgentStartRequest request)+void WebWorkerClient::register_dedicated_worker(Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport){auto outside_settings = hosted_environment(request.outside_settings.id);- auto started_agent = WorkerAgentManager::the().start_worker_agent(*this, outside_settings, move(request));- return { started_agent.agent_id, move(started_agent.thread_transport), started_agent.is_hosted_in_owner_process };-}--void WebWorkerClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)-{- WorkerAgentManager::the().close_worker_agent(*this, agent_id, owner_token);+ WorkerAgentManager::the().register_dedicated_worker(*this, outside_settings, move(request), move(worker_transport));}}diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.hindex 379f6a677d8..d975bdfdb45 100644--- a/Libraries/LibWebView/WebWorkerClient.h+++ b/Libraries/LibWebView/WebWorkerClient.h@@ -56,7 +56,7 @@ public:void set_inside_settings(NonnullOwnPtr<CanonicalWorkerEnvironmentSettingsObject>, bool may_read_local_files);CanonicalWorkerEnvironmentSettingsObject const* inside_settings() const { return m_inside_settings.ptr(); }- void forget_inside_settings_of_removed_agent();+ void forget_inside_settings_of_closing_worker();Optional<URL::Origin> const& top_level_origin() const { return m_top_level_origin; }bool may_read_local_files() const { return m_may_read_local_files; }void keep_script_blob_url_until_script_loads(BlobURLHandle handle) { m_script_blob_url = move(handle); }@@ -78,8 +78,7 @@ public:virtual void did_release_image_decoder() override;virtual Messages::WebWorkerClient::RequestCompositorConnectionResponse request_compositor_connection() override;virtual void did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage) override;- virtual Messages::WebWorkerClient::StartWorkerAgentResponse start_worker_agent(Web::HTML::WorkerAgentStartRequest request) override;- virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;+ virtual void register_dedicated_worker(Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport) override;private:virtual void did_misbehave(StringView message_name, StringView reason) override;diff --git a/Libraries/LibWebView/WorkerAgentManager.cpp b/Libraries/LibWebView/WorkerAgentManager.cppindex d9be69e3e30..1c830661284 100644--- a/Libraries/LibWebView/WorkerAgentManager.cpp+++ b/Libraries/LibWebView/WorkerAgentManager.cpp@@ -25,175 +25,109 @@namespace WebView {-// 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;-WorkerAgentManager& WorkerAgentManager::the(){static auto& manager = *new WorkerAgentManager;return manager;}-WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(WebContentClient& owner, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request)-{- auto abstract_owner = Owner {- .client = WebContentOwner {- .client = owner,- .page_id = page_id,- },- .token = request.owner_token,- };- return start_worker_agent(move(abstract_owner), outside_settings, move(request), owner.is_private());-}--WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(WebWorkerClient& owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request)+// https://html.spec.whatwg.org/multipage/workers.html#dom-sharedworker+WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(WebContentClient& owner_client, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request){- auto abstract_owner = Owner {- .client = WebWorkerOwner {- .client = owner,- },+ auto owner = Owner {+ .client = owner_client,+ .page_id = page_id,.token = request.owner_token,};- return start_worker_agent(move(abstract_owner), outside_settings, move(request), owner.is_private());-}+ auto is_private = owner_client.is_private();-// https://html.spec.whatwg.org/multipage/workers.html#dom-sharedworker-WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::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()) {+ if (!outside_settings.has_value())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) {+ // NB: The process of a dedicated worker's owner starts it, and only registers it here.+ if (request.agent_type != Web::HTML::AgentType::SharedWorker)return {};- }// NB: A worker shares the ancestors of the environment that creates it.- auto has_cross_site_ancestor = owner.client.visit(- [&](WebContentOwner const& web_content_owner) {- auto* page = web_content_owner.client ? web_content_owner.client->page(web_content_owner.page_id) : nullptr;- return !page || page->hosted_environment_has_cross_site_ancestor(outside_settings->id()).value_or(true);- },- [&](WebWorkerOwner const&) {- return static_cast<CanonicalWorkerEnvironmentSettingsObject const&>(*outside_settings).has_cross_site_ancestor();- });+ auto has_cross_site_ancestor = page_environment_has_cross_site_ancestor(owner_client, page_id, *outside_settings);// 9. Let outsideStorageKey be the result of running obtain a storage key for non-storage purposes given// outsideSettings.auto outside_storage_key = obtain_a_storage_key_for_non_storage_purposes(*outside_settings);// 11.1. Let workerGlobalScope be null.- if (request.agent_type == Web::HTML::AgentType::SharedWorker) {- SharedWorkerKey key {- .is_private = is_private,- .storage_key = outside_storage_key,- .url = request.url,- .name = Utf16String::from_utf8(request.name),- .top_level_site = network_isolation_top_level_site(*outside_settings),- .has_cross_site_ancestor = has_cross_site_ancestor,- };-- // 11.2. For each scope in the list of all SharedWorkerGlobalScope objects: if workerStorageKey- // equals outsideStorageKey, scope's closing flag is false, scope's constructor URL equals- // urlRecord, and scope's name equals options["name"], then set workerGlobalScope to scope- // and break.- if (auto existing_agent_id = m_shared_workers.get(key); existing_agent_id.has_value()) {- auto maybe_agent = m_agents.find(*existing_agent_id);- if (maybe_agent != m_agents.end()) {- auto& agent = maybe_agent->value;- if (!agent.closing) {- // FIXME: 11.3. If workerGlobalScope is not null, but the user agent has been- // configured to disallow communication between the worker represented- // by the workerGlobalScope and the scripts whose settings object is- // outsideSettings, then set workerGlobalScope to null.-- // 11.4. If workerGlobalScope is not null, and any of the following are true:- // workerGlobalScope's type is not equal to options["type"];- // workerGlobalScope's credentials is not equal to options["credentials"]; or- // workerGlobalScope's extended lifetime is not equal to- // options["extendedLifetime"], then queue a global task on the DOM- // manipulation task source given worker's relevant global object to fire an- // event named error at worker and abort these steps.- // 11.5.3. If workerIsSecureContext is not callerIsSecureContext, queue a global task- // on the DOM manipulation task source given worker's relevant global object- // to fire an event named error at worker and abort these steps.- // AD-HOC: The owner fires the error itself when it gets no agent back; the spec's- // queue-global-task happens inside WorkerAgentParent in the requesting process.- if (agent.worker_type != request.type- || agent.credentials != request.credentials- || agent.extended_lifetime != request.extended_lifetime- || (agent.worker_is_secure_context.has_value() && *agent.worker_is_secure_context != request.caller_is_secure_context)) {- return {};- }-- // 11.5.8. Append the relevant owner to add given outsideSettings to- // workerGlobalScope's owner set.- // AD-HOC: The browser-side mirror lives in `agent.owners`; the worker-process- // owner_set() is appended inside connect_shared_worker_impl (which also- // handles steps 11.5.5-11.5.7).- agent.owners.append(owner);- agent.extended_lifetime_timer = nullptr;- agent.client->async_connect_shared_worker(move(request.outside_port), request.outside_settings);- auto const* owner_host = owner.client.visit(- [](WebContentOwner const& web_content_owner) -> WebContentClient const* {- return web_content_owner.client.ptr();- },- [](WebWorkerOwner const& web_worker_owner) -> WebContentClient const* {- return web_worker_owner.client->host();- });- return { agent.id, {}, owner_host && owner_host == agent.client->host() };+ SharedWorkerKey key {+ .is_private = is_private,+ .storage_key = outside_storage_key,+ .url = request.url,+ .name = Utf16String::from_utf8(request.name),+ .top_level_site = network_isolation_top_level_site(*outside_settings),+ .has_cross_site_ancestor = has_cross_site_ancestor,+ };++ // 11.2. For each scope in the list of all SharedWorkerGlobalScope objects: if workerStorageKey+ // equals outsideStorageKey, scope's closing flag is false, scope's constructor URL equals+ // urlRecord, and scope's name equals options["name"], then set workerGlobalScope to scope+ // and break.+ if (auto existing_agent_id = m_shared_workers.get(key); existing_agent_id.has_value()) {+ auto maybe_agent = m_agents.find(*existing_agent_id);+ if (maybe_agent != m_agents.end()) {+ auto& agent = maybe_agent->value;+ if (!agent.closing) {+ // FIXME: 11.3. If workerGlobalScope is not null, but the user agent has been+ // configured to disallow communication between the worker represented+ // by the workerGlobalScope and the scripts whose settings object is+ // outsideSettings, then set workerGlobalScope to null.++ // 11.4. If workerGlobalScope is not null, and any of the following are true:+ // workerGlobalScope's type is not equal to options["type"];+ // workerGlobalScope's credentials is not equal to options["credentials"]; or+ // workerGlobalScope's extended lifetime is not equal to+ // options["extendedLifetime"], then queue a global task on the DOM+ // manipulation task source given worker's relevant global object to fire an+ // event named error at worker and abort these steps.+ // 11.5.3. If workerIsSecureContext is not callerIsSecureContext, queue a global task+ // on the DOM manipulation task source given worker's relevant global object+ // to fire an event named error at worker and abort these steps.+ // AD-HOC: The owner fires the error itself when it gets no agent back; the spec's+ // queue-global-task happens inside WorkerAgentParent in the requesting process.+ if (agent.worker_type != request.type+ || agent.credentials != request.credentials+ || agent.extended_lifetime != request.extended_lifetime+ || (agent.worker_is_secure_context.has_value() && *agent.worker_is_secure_context != request.caller_is_secure_context)) {+ return {};}- }- m_shared_workers.remove(key);+ // 11.5.8. Append the relevant owner to add given outsideSettings to+ // workerGlobalScope's owner set.+ // AD-HOC: The browser-side mirror lives in `agent.owners`; the worker-process+ // owner_set() is appended inside connect_shared_worker_impl (which also+ // handles steps 11.5.5-11.5.7).+ agent.owners.append(owner);+ agent.extended_lifetime_timer = nullptr;+ agent.client->async_connect_shared_worker(move(request.outside_port), request.outside_settings);+ return { agent.id, {}, agent.client->host() == &owner_client };+ }}- }- // 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 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()) {- return {};- }- size_t worker_count_of_top_level_site = 0;- for (auto const& client : m_clients) {- auto const& worker_top_level_origin = client->top_level_origin();- if (client->is_private() == is_private && worker_top_level_origin.has_value() && worker_top_level_origin->is_same_site(*top_level_origin))- ++worker_count_of_top_level_site;+ m_shared_workers.remove(key);}- if (worker_count_of_top_level_site >= maximum_worker_count_per_top_level_site) {++ if (has_reached_worker_limit(is_private, *outside_settings))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. It always gets a fresh thread in the process- // of its owner. A shared worker's thread is in the process of the owner that starts it, if that process may- // host it, and otherwise in a process of its own.+ // AD-HOC: A shared worker's thread is in the process of the owner that starts it, if that process may host it, and+ // otherwise in a process of its own.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();- });- } else if (auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>(); web_content_owner && owner_process_may_host_shared_worker(*web_content_owner, *outside_settings)) {- host = web_content_owner->client.strong_ref();- }- // NB: Nothing would close a process started for a dedicated worker, as only shared workers keep a process alive.- if (request.agent_type == Web::HTML::AgentType::DedicatedWorker && !host) {- return {};- }+ if (owner_process_may_host_shared_worker(owner, *outside_settings))+ host = owner_client;bool const host_has_only_this_worker = !host;Optional<IPC::TransportHandle> thread_transport;auto client_or_error = [&]() -> ErrorOr<NonnullRefPtr<WebWorkerClient>> {@@ -208,35 +142,7 @@ WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(Ow} else {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);-- // The worker's RequestServer client uses the cookies of the session the worker itself belongs to.- auto session = client->session();- if (!session)- session = Application::session_for_new_view(is_private);- // The worker makes its requests for the sites its owner makes them for.- owner.client.visit(- [&](WebContentOwner const& web_content_owner) {- if (web_content_owner.client)- client->request_server_site_bindings().bind_sites_of(web_content_owner.client->request_server_site_bindings());- },- [&](WebWorkerOwner const& web_worker_owner) {- client->request_server_site_bindings().bind_sites_of(web_worker_owner.client->request_server_site_bindings());- });-- // The worker's requests go through the RequestServers of its owner's sites.- TRY(client->request_server_site_bindings().connect(*session));- client->async_set_site_compatibility_data(Application::the().site_compatibility_data());- client->async_set_permission_snapshot(session->permission_manager->snapshot_for({}));- // The User-Agent string, the navigator compatibility mode, and the preferred languages live in this process.- // Pages get them through their view; a worker gets the same values here, so its navigator never contradicts- // the page's.- client->async_set_user_agent(Application::the().user_agent_string());- client->async_set_navigator_compatibility_mode(Application::the().navigator_compatibility_mode());- client->async_set_preferred_languages(Application::settings().languages());-- return client;+ return create_worker_client(move(transport.local), is_private, agent_id, *host, owner_client.request_server_site_bindings());}();// A worker the system cannot give a thread fails to load, as one whose script cannot be fetched does.if (client_or_error.is_error()) {@@ -246,43 +152,10 @@ WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(Owreturn {};}auto client = client_or_error.release_value();- m_clients.append(client);Vector<Owner> owners;owners.append(owner);- // https://html.spec.whatwg.org/multipage/workers.html#set-up-a-worker-environment-settings-object- // 3. Let origin be a unique opaque origin if worker global scope's url's scheme is "data"; otherwise outside- // settings's origin.- auto origin = request.url.scheme() == "data"sv ? URL::Origin::create_opaque() : outside_settings->origin();-- // 5. Set settings object's id to a new unique opaque string, [...]- // 6. If worker global scope is a DedicatedWorkerGlobalScope object, then set settings object's top-level origin to- // outside settings's top-level origin.- // 7. Otherwise, set settings object's top-level origin to an implementation-defined value.- // NB: As storage partitioning in other browsers does, a shared worker takes the top-level origin of the outside- // settings it is created for, too.- auto inside_settings = make<CanonicalWorkerEnvironmentSettingsObject>(move(origin), outside_settings->top_level_origin(), has_cross_site_ancestor, Web::HTML::EnvironmentId::generate());- auto environment_id = inside_settings->id();-- // NB: The task manager lists a process with the site of its pages. One that has none left only runs on for its shared- // workers, so it goes by the site of their origin.- if (auto process = Application::process_manager().find_child(client->child_id()); request.agent_type == Web::HTML::AgentType::SharedWorker && process.has_value()) {- if (auto const& worker_origin = inside_settings->origin(); !worker_origin.is_opaque() && !worker_origin.is_file_origin())- process->set_site_url(URL::Parser::basic_parse(worker_origin.serialize()));- }-- // NB: A worker reads local files as its owner does. A worker of a file origin that local file content starts is- // local file content too.- auto may_read_local_files = inside_settings->origin().is_file_origin()- && owner.client.visit(- [](WebContentOwner const& web_content_owner) {- return web_content_owner.client && web_content_owner.client->may_read_local_files();- },- [](WebWorkerOwner const& web_worker_owner) {- return web_worker_owner.client->may_read_local_files();- });-// AD-HOC: Seed worker_is_secure_context with the caller's value so reuse requests arriving before// the worker finishes loading still get a mismatch check.// worker_did_finish_loading_script overwrites this with the worker's actual value (which@@ -290,46 +163,168 @@ WorkerAgentManager::StartedWorkerAgent WorkerAgentManager::start_worker_agent(OwWorkerAgent agent {.id = agent_id,.client = client,- .agent_type = request.agent_type,.worker_type = request.type,.credentials = request.credentials,.extended_lifetime = request.extended_lifetime,.extended_lifetime_timer = {},.worker_is_secure_context = request.caller_is_secure_context,- .shared_worker_key = {},+ .shared_worker_key = move(key),.owners = move(owners),.outside_settings_owner = owner,};+ m_shared_workers.set(agent.shared_worker_key, agent_id);+ m_agents.set(agent_id, move(agent));++ start_worker(*client, move(request), *outside_settings, has_cross_site_ancestor, owner_client.may_read_local_files(), host_has_only_this_worker);++ // NB: The task manager lists a process with the site of its pages. One that has none left only runs on for its shared+ // workers, so it goes by the site of their origin.+ if (auto process = Application::process_manager().find_child(client->child_id()); process.has_value()) {+ if (auto const& worker_origin = client->inside_settings()->origin(); !worker_origin.is_opaque() && !worker_origin.is_file_origin())+ process->set_site_url(URL::Parser::basic_parse(worker_origin.serialize()));+ }++ return { agent_id, move(thread_transport), !host_has_only_this_worker };+}++void WorkerAgentManager::register_dedicated_worker(WebContentClient& owner_client, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport)+{+ if (!outside_settings.has_value())+ return;+ DedicatedWorkerOwner owner {+ .is_private = owner_client.is_private(),+ .process = owner_client,+ .request_server_site_bindings = owner_client.request_server_site_bindings(),+ .may_read_local_files = owner_client.may_read_local_files(),+ .has_cross_site_ancestor = page_environment_has_cross_site_ancestor(owner_client, page_id, *outside_settings),+ };+ register_dedicated_worker(owner, *outside_settings, move(request), move(worker_transport));+}++void WorkerAgentManager::register_dedicated_worker(WebWorkerClient& owner_client, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport)+{+ auto host = owner_client.host();+ if (!outside_settings.has_value() || !host)+ return;+ DedicatedWorkerOwner owner {+ .is_private = owner_client.is_private(),+ .process = *host,+ .request_server_site_bindings = owner_client.request_server_site_bindings(),+ .may_read_local_files = owner_client.may_read_local_files(),+ .has_cross_site_ancestor = static_cast<CanonicalWorkerEnvironmentSettingsObject const&>(*outside_settings).has_cross_site_ancestor(),+ };+ register_dedicated_worker(owner, *outside_settings, move(request), move(worker_transport));+}++// NB: A worker that is not taken up here loses its connection before it starts, and its owner fires an error at it.+void WorkerAgentManager::register_dedicated_worker(DedicatedWorkerOwner const& owner, CanonicalEnvironmentSettingsObject const& outside_settings, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport)+{+ if (request.agent_type != Web::HTML::AgentType::DedicatedWorker)+ return;+ request.outside_settings.origin = outside_settings.origin();++ if (has_reached_worker_limit(owner.is_private, outside_settings))+ return;+ auto client_or_error = [&]() -> ErrorOr<NonnullRefPtr<WebWorkerClient>> {+ auto transport = TRY([&] {+ IPC::ScopedSharedIOThread shared_io_thread;+ return worker_transport.create_transport();+ }());+ return create_worker_client(move(transport), owner.is_private, 0, owner.process, owner.request_server_site_bindings);+ }();+ if (client_or_error.is_error()) {+ dbgln("Unable to start a dedicated worker: {}", client_or_error.error());+ return;+ }++ auto client = client_or_error.release_value();+ start_worker(*client, move(request), outside_settings, owner.has_cross_site_ancestor, owner.may_read_local_files, false);+}++bool WorkerAgentManager::page_environment_has_cross_site_ancestor(WebContentClient& client, Web::PageId page_id, CanonicalEnvironmentSettingsObject const& environment)+{+ auto* page = client.page(page_id);+ return !page || page->hosted_environment_has_cross_site_ancestor(environment.id()).value_or(true);+}++// 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 is gone, and one whose creator's browsing+// context has been discarded, leaving it no top-level origin, does not start.+bool WorkerAgentManager::has_reached_worker_limit(IsPrivate is_private, CanonicalEnvironmentSettingsObject const& outside_settings) const+{+ auto top_level_origin = outside_settings.top_level_origin();+ if (!top_level_origin.has_value())+ return true;+ size_t worker_count_of_top_level_site = 0;+ for (auto const& client : m_clients) {+ auto const& worker_top_level_origin = client->top_level_origin();+ if (client->is_private() == is_private && worker_top_level_origin.has_value() && worker_top_level_origin->is_same_site(*top_level_origin))+ ++worker_count_of_top_level_site;+ }+ return worker_count_of_top_level_site >= Web::HTML::maximum_worker_count;+}++ErrorOr<NonnullRefPtr<WebWorkerClient>> WorkerAgentManager::create_worker_client(NonnullOwnPtr<IPC::Transport> transport, IsPrivate is_private, Web::HTML::WorkerAgentId agent_id, WebContentClient& host, RequestServerSiteBindings const& owner_request_server_site_bindings)+{+ auto client = TRY(try_make_ref_counted<WebWorkerClient>(move(transport), is_private, agent_id));+ client->set_host(host);++ // The worker's RequestServer client uses the cookies of the session the worker itself belongs to.+ auto session = client->session();+ if (!session)+ session = Application::session_for_new_view(is_private);+ // The worker makes its requests for the sites its owner makes them for.+ client->request_server_site_bindings().bind_sites_of(owner_request_server_site_bindings);++ // The worker's requests go through the RequestServers of its owner's sites.+ TRY(client->request_server_site_bindings().connect(*session));+ client->async_set_site_compatibility_data(Application::the().site_compatibility_data());+ client->async_set_permission_snapshot(session->permission_manager->snapshot_for({}));+ // The User-Agent string, the navigator compatibility mode, and the preferred languages live in this process.+ // Pages get them through their view; a worker gets the same values here, so its navigator never contradicts+ // the page's.+ client->async_set_user_agent(Application::the().user_agent_string());+ client->async_set_navigator_compatibility_mode(Application::the().navigator_compatibility_mode());+ client->async_set_preferred_languages(Application::settings().languages());++ m_clients.append(client);+ return client;+}++void WorkerAgentManager::start_worker(WebWorkerClient& client, Web::HTML::WorkerAgentStartRequest request, CanonicalEnvironmentSettingsObject const& outside_settings, bool has_cross_site_ancestor, bool owner_may_read_local_files, bool has_process_to_itself)+{+ // https://html.spec.whatwg.org/multipage/workers.html#set-up-a-worker-environment-settings-object+ // 3. Let origin be a unique opaque origin if worker global scope's url's scheme is "data"; otherwise outside+ // settings's origin.+ auto origin = request.url.scheme() == "data"sv ? URL::Origin::create_opaque() : outside_settings.origin();++ // 5. Set settings object's id to a new unique opaque string, [...]+ // 6. If worker global scope is a DedicatedWorkerGlobalScope object, then set settings object's top-level origin to+ // outside settings's top-level origin.+ // 7. Otherwise, set settings object's top-level origin to an implementation-defined value.+ // NB: As storage partitioning in other browsers does, a shared worker takes the top-level origin of the outside+ // settings it is created for, too.+ auto inside_settings = make<CanonicalWorkerEnvironmentSettingsObject>(move(origin), outside_settings.top_level_origin(), has_cross_site_ancestor, Web::HTML::EnvironmentId::generate());+ auto environment_id = inside_settings->id();auto inside_origin = inside_settings->origin();- client->set_inside_settings(move(inside_settings), may_read_local_files);++ // NB: A worker reads local files as its owner does. A worker of a file origin that local file content starts is+ // local file content too.+ auto may_read_local_files = inside_origin.is_file_origin() && owner_may_read_local_files;+ client.set_inside_settings(move(inside_settings), may_read_local_files);// NB: The worker's URL was parsed with its blob URL entry, so revoking the URL must not stop the worker from// fetching its script.- if (auto session = client->session())- client->keep_script_blob_url_until_script_loads(BlobURLHandle::for_url(session->blob_url_store.ptr(), request.url));-- if (request.agent_type == Web::HTML::AgentType::SharedWorker) {- agent.shared_worker_key = SharedWorkerKey {- .is_private = is_private,- .storage_key = move(outside_storage_key),- .url = request.url,- .name = Utf16String::from_utf8(request.name),- .top_level_site = network_isolation_top_level_site(*outside_settings),- .has_cross_site_ancestor = has_cross_site_ancestor,- };- m_shared_workers.set(*agent.shared_worker_key, agent_id);- }+ if (auto session = client.session())+ client.keep_script_blob_url_until_script_loads(BlobURLHandle::for_url(session->blob_url_store.ptr(), request.url));- m_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), host_has_only_this_worker);-- return { agent_id, move(thread_transport), !host_has_only_this_worker };+ 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), has_process_to_itself);}// Sites decide what runs together in a process, as for the documents of CanonicalNavigable::process_to_host(). The worker's// origin is that of the document starting it, so the process of that document already holds the worker's site.-bool WorkerAgentManager::owner_process_may_host_shared_worker(WebContentOwner const& owner, CanonicalEnvironmentSettingsObject const& outside_settings)+bool WorkerAgentManager::owner_process_may_host_shared_worker(Owner const& owner, CanonicalEnvironmentSettingsObject const& outside_settings){if (!owner.client || owner.client->has_requested_close())return false;@@ -353,7 +348,7 @@ bool WorkerAgentManager::owner_process_may_host_shared_worker(WebContentOwner cobool WorkerAgentManager::hosts_shared_worker(WebContentClient const& process) const{return any_of(m_agents, [&](auto const& entry) {- return entry.value.agent_type == Web::HTML::AgentType::SharedWorker && entry.value.client->host() == &process;+ return entry.value.client->host() == &process;});}@@ -412,16 +407,7 @@ void WorkerAgentManager::update_preferred_languages(Vector<String> const& prefervoid WorkerAgentManager::close_worker_agent(WebContentClient& client, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token){Owner identity {- .client = WebContentOwner { .client = client },- .token = owner_token,- };- remove_owner(agent_id, identity);-}--void WorkerAgentManager::close_worker_agent(WebWorkerClient& client, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)-{- Owner identity {- .client = WebWorkerOwner { .client = client },+ .client = client,.token = owner_token,};remove_owner(agent_id, identity);@@ -433,8 +419,7 @@ void WorkerAgentManager::remove_web_content_owner(WebContentClient& client)for (auto& entry : m_agents) {auto& agent = entry.value;agent.owners.remove_all_matching([&](Owner const& owner) {- auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>();- return web_content_owner && web_content_owner->client.ptr() == &client;+ return owner.client.ptr() == &client;});forget_removed_outside_settings_owner(agent);if (agent.owners.is_empty())@@ -451,8 +436,7 @@ void WorkerAgentManager::remove_web_content_page_owner(WebContentClient& client,for (auto& entry : m_agents) {auto& agent = entry.value;auto did_remove_owner = agent.owners.remove_all_matching([&](Owner const& owner) {- auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>();- return web_content_owner && web_content_owner->client.ptr() == &client && web_content_owner->page_id == page_id;+ return owner.client.ptr() == &client && owner.page_id == page_id;});if (!did_remove_owner)continue;@@ -477,24 +461,6 @@ void WorkerAgentManager::remove_private_workers_without_owners()remove_agent(agent_id, AgentRemovalCause::AgentTerminated);}-void WorkerAgentManager::remove_web_worker_owner(WebWorkerClient& client)-{- Vector<Web::HTML::WorkerAgentId> agents_to_close;- for (auto& entry : m_agents) {- auto& agent = entry.value;- agent.owners.remove_all_matching([&](Owner const& owner) {- auto const* web_worker_owner = owner.client.get_pointer<WebWorkerOwner>();- return web_worker_owner && web_worker_owner->client.ptr() == &client;- });- forget_removed_outside_settings_owner(agent);- if (agent.owners.is_empty())- agents_to_close.append(agent.id);- }-- for (auto agent_id : agents_to_close)- remove_agent(agent_id, AgentRemovalCause::OwnerSetEmptied);-}-// 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.@@ -539,10 +505,12 @@ ErrorOr<void> WorkerAgentManager::simulate_request_server_connection_loss_for_te{auto is_owned_by_page = [&](WorkerAgent const& agent) {return any_of(agent.owners, [&](Owner const& candidate) {- auto const* web_content_owner = candidate.client.get_pointer<WebContentOwner>();- return web_content_owner && web_content_owner->client.ptr() == &owner && web_content_owner->page_id == page_id;+ return candidate.client.ptr() == &owner && candidate.page_id == page_id;});};+ auto runs_a_shared_worker = [&](WebWorkerClient const& client) {+ return any_of(m_agents, [&](auto const& entry) { return entry.value.client.ptr() == &client; });+ };Vector<NonnullRefPtr<WebWorkerClient>> clients;for (auto& entry : m_agents) {@@ -550,6 +518,10 @@ ErrorOr<void> WorkerAgentManager::simulate_request_server_connection_loss_for_teif (agent.client->is_open() && is_owned_by_page(agent))clients.append(agent.client);}+ for (auto& client : m_clients) {+ if (client->is_open() && client->host() == &owner && !runs_a_shared_worker(*client))+ clients.append(client);+ }for (auto& client : clients) {auto& bindings = client->request_server_site_bindings();@@ -570,33 +542,26 @@ ErrorOr<void> WorkerAgentManager::simulate_request_server_connection_loss_for_tevoid WorkerAgentManager::notify_worker_script_load_failure(Owner const& owner){- if (auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>(); web_content_owner && web_content_owner->client)- web_content_owner->client->async_did_worker_agent_fail_loading_script(owner.token);+ if (owner.client)+ owner.client->async_did_worker_agent_fail_loading_script(owner.token);}void WorkerAgentManager::notify_worker_content_security_policy_violation(Owner const& owner, u64 policy_index, String const& effective_directive, URL::URL const& resource){- if (auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>(); web_content_owner && web_content_owner->client)- web_content_owner->client->async_did_worker_agent_report_content_security_policy_violation(owner.token, policy_index, effective_directive, resource);+ if (owner.client)+ owner.client->async_did_worker_agent_report_content_security_policy_violation(owner.token, policy_index, effective_directive, resource);}void WorkerAgentManager::notify_worker_close(Owner const& owner){- if (auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>(); web_content_owner && web_content_owner->client)- web_content_owner->client->async_did_worker_agent_close(owner.token);+ if (owner.client)+ owner.client->async_did_worker_agent_close(owner.token);}void WorkerAgentManager::notify_worker_death(Owner const& owner){- if (auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>(); web_content_owner && web_content_owner->client)- web_content_owner->client->async_did_worker_agent_die(owner.token);-}--Vector<WorkerAgentManager::Owner> WorkerAgentManager::owners_told_by_the_browser(WorkerAgent const& agent)-{- if (agent.agent_type == Web::HTML::AgentType::DedicatedWorker)- return {};- return agent.owners;+ if (owner.client)+ owner.client->async_did_worker_agent_die(owner.token);}void WorkerAgentManager::worker_did_finish_loading_script(Web::HTML::WorkerAgentId agent_id, bool worker_is_secure_context)@@ -622,7 +587,7 @@ void WorkerAgentManager::worker_did_fail_loading_script(Web::HTML::WorkerAgentIdagent.closing = true;agent.outside_settings_owner = {};- auto owners = owners_told_by_the_browser(agent);+ auto owners = agent.owners;for (auto const& owner : owners)notify_worker_script_load_failure(owner);@@ -656,7 +621,7 @@ void WorkerAgentManager::worker_did_close(Web::HTML::WorkerAgentId agent_id)return;agent.closing = true;- auto owners = owners_told_by_the_browser(agent);+ auto owners = agent.owners;for (auto const& owner : owners)notify_worker_close(owner);@@ -669,9 +634,9 @@ void WorkerAgentManager::shared_worker_did_close(Web::HTML::WorkerAgentId agent_{// NB: The script can run on, and its thread with it, but no constructor may connect to this worker any more.auto maybe_agent = m_agents.find(agent_id);- if (maybe_agent == m_agents.end() || !maybe_agent->value.shared_worker_key.has_value())+ if (maybe_agent == m_agents.end())return;- auto const& key = *maybe_agent->value.shared_worker_key;+ auto const& key = maybe_agent->value.shared_worker_key;if (m_shared_workers.get(key) == agent_id)m_shared_workers.remove(key);}@@ -690,7 +655,7 @@ void WorkerAgentManager::worker_did_die(Web::HTML::WorkerAgentId agent_id)}agent.closing = true;- auto owners = owners_told_by_the_browser(agent);+ auto owners = agent.owners;for (auto const& owner : owners)notify_worker_death(owner);@@ -733,12 +698,12 @@ void WorkerAgentManager::remove_agent(Web::HTML::WorkerAgentId agent_id, AgentReCore::deferred_invoke([timer = move(agent.extended_lifetime_timer)] { });// NB: A new worker may have taken this one's place by now.- if (agent.shared_worker_key.has_value() && m_shared_workers.get(*agent.shared_worker_key) == agent_id)- m_shared_workers.remove(*agent.shared_worker_key);+ if (m_shared_workers.get(agent.shared_worker_key) == agent_id)+ m_shared_workers.remove(agent.shared_worker_key);// NB: The owner of a page can be removing the agent from the destructor of the host, which nothing can take a// reference to any more.- if (agent.agent_type == Web::HTML::AgentType::SharedWorker && agent.client->host()) {+ if (agent.client->host()) {Core::deferred_invoke([host = agent.client->host()->make_weak_ptr<WebContentClient>()] {if (auto process = host.strong_ref())process->close_server_if_unused();@@ -746,7 +711,7 @@ void WorkerAgentManager::remove_agent(Web::HTML::WorkerAgentId agent_id, AgentRe}agent.closing = true;- agent.client->forget_inside_settings_of_removed_agent();+ agent.client->forget_inside_settings_of_closing_worker();// NB: A 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.@@ -767,18 +732,7 @@ void WorkerAgentManager::worker_thread_did_exit(WebWorkerClient& client)bool WorkerAgentManager::is_same_owner(Owner const& owner, Owner const& identity){- if (owner.token != identity.token)- return false;-- if (auto const* incoming = identity.client.get_pointer<WebContentOwner>()) {- auto const* candidate = owner.client.get_pointer<WebContentOwner>();- return candidate && candidate->client.ptr() == incoming->client.ptr();- }- if (auto const* incoming = identity.client.get_pointer<WebWorkerOwner>()) {- auto const* candidate = owner.client.get_pointer<WebWorkerOwner>();- return candidate && candidate->client.ptr() == incoming->client.ptr();- }- return false;+ return owner.token == identity.token && owner.client.ptr() == identity.client.ptr();}void WorkerAgentManager::forget_removed_outside_settings_owner(WorkerAgent& agent)@@ -806,8 +760,6 @@ void WorkerAgentManager::remove_owner(Web::HTML::WorkerAgentId agent_id, Owner cif (agent.owners.is_empty())remove_agent(agent_id, AgentRemovalCause::OwnerSetEmptied);- else if (agent.agent_type == Web::HTML::AgentType::DedicatedWorker)- remove_agent(agent_id, AgentRemovalCause::AgentTerminated);}}diff --git a/Libraries/LibWebView/WorkerAgentManager.h b/Libraries/LibWebView/WorkerAgentManager.hindex 227cf14f2c1..cd1c75ae134 100644--- a/Libraries/LibWebView/WorkerAgentManager.h+++ b/Libraries/LibWebView/WorkerAgentManager.h@@ -10,10 +10,10 @@#include <AK/Function.h>#include <AK/HashMap.h>#include <AK/JsonValue.h>+#include <AK/NonnullOwnPtr.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>#include <AK/Utf16String.h>-#include <AK/Variant.h>#include <AK/Vector.h>#include <AK/WeakPtr.h>#include <AK/kmalloc.h>@@ -53,14 +53,16 @@ public:bool operator==(SharedWorkerKey const&) const = default;};- // A worker that is to run on a thread of its owner's process comes with the transport that thread is to use.+ // A shared 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;bool is_hosted_in_owner_process { false };};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);++ void register_dedicated_worker(WebContentClient&, Web::PageId page_id, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest, IPC::TransportHandle worker_transport);+ void register_dedicated_worker(WebWorkerClient&, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest, IPC::TransportHandle worker_transport);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// reaches every live worker too.@@ -69,11 +71,9 @@ public:void update_preferred_languages(Vector<String> const&);void close_worker_agent(WebContentClient&, Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken);- void close_worker_agent(WebWorkerClient&, Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken);void remove_web_content_owner(WebContentClient&);void remove_web_content_page_owner(WebContentClient&, Web::PageId);- void remove_web_worker_owner(WebWorkerClient&);// 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.@@ -94,36 +94,31 @@ public:void update_permission_snapshot(PermissionManager const&);- template<CallableAs<IterationDecision, WebWorkerClient&> Callback>- void for_each_client(Callback callback)- {- for (auto& agent : m_agents) {- if (callback(*agent.value.client) == IterationDecision::Break)- break;- }- }-private:friend class WebWorkerClient;WorkerAgentManager() = default;- struct WebContentOwner {+ struct Owner {WeakPtr<WebContentClient> client;Web::PageId page_id { 0 };+ Web::HTML::WorkerAgentOwnerToken token { 0 };};- struct WebWorkerOwner {- NonnullRefPtr<WebWorkerClient> client;- };-- struct Owner {- Variant<WebContentOwner, WebWorkerOwner> client;- Web::HTML::WorkerAgentOwnerToken token { 0 };+ struct DedicatedWorkerOwner {+ IsPrivate is_private { IsPrivate::No };+ WebContentClient& process;+ RequestServerSiteBindings const& request_server_site_bindings;+ bool may_read_local_files { false };+ bool has_cross_site_ancestor { false };};+ void register_dedicated_worker(DedicatedWorkerOwner const&, CanonicalEnvironmentSettingsObject const& outside_settings, Web::HTML::WorkerAgentStartRequest, IPC::TransportHandle worker_transport);- StartedWorkerAgent start_worker_agent(Owner, Optional<CanonicalEnvironmentSettingsObject const&> outside_settings, Web::HTML::WorkerAgentStartRequest, IsPrivate);- static bool owner_process_may_host_shared_worker(WebContentOwner const&, CanonicalEnvironmentSettingsObject const& outside_settings);+ static bool owner_process_may_host_shared_worker(Owner const&, CanonicalEnvironmentSettingsObject const& outside_settings);+ static bool page_environment_has_cross_site_ancestor(WebContentClient&, Web::PageId, CanonicalEnvironmentSettingsObject const&);+ bool has_reached_worker_limit(IsPrivate, CanonicalEnvironmentSettingsObject const& outside_settings) const;+ ErrorOr<NonnullRefPtr<WebWorkerClient>> create_worker_client(NonnullOwnPtr<IPC::Transport>, IsPrivate, Web::HTML::WorkerAgentId, WebContentClient& host, RequestServerSiteBindings const& owner_request_server_site_bindings);+ static void start_worker(WebWorkerClient&, Web::HTML::WorkerAgentStartRequest, CanonicalEnvironmentSettingsObject const& outside_settings, bool has_cross_site_ancestor, bool owner_may_read_local_files, bool has_process_to_itself);void notify_worker_script_load_failure(Owner const&);void notify_worker_content_security_policy_violation(Owner const&, u64 policy_index, String const& effective_directive, URL::URL const& resource);@@ -149,14 +144,13 @@ private:struct WorkerAgent {Web::HTML::WorkerAgentId id { 0 };NonnullRefPtr<WebWorkerClient> client;- Web::HTML::AgentType agent_type { Web::HTML::AgentType::DedicatedWorker };Web::HTML::WorkerType worker_type { Web::HTML::WorkerType::Classic };Web::HTML::RequestCredentials credentials { Web::HTML::RequestCredentials::SameOrigin };bool extended_lifetime { false };RefPtr<Core::Timer> extended_lifetime_timer;Optional<bool> worker_is_secure_context;bool closing { false };- Optional<SharedWorkerKey> shared_worker_key;+ SharedWorkerKey shared_worker_key;Vector<Owner> owners;// The owner that started the worker, whose outside settings are the client of the worker's script fetch, until// that fetch completes or the owner goes away.@@ -164,7 +158,6 @@ private:};static bool is_same_owner(Owner const&, Owner const& identity);- static Vector<Owner> owners_told_by_the_browser(WorkerAgent const&);static void forget_removed_outside_settings_owner(WorkerAgent&);void for_each_client_with_inside_settings(Function<IterationDecision(WebWorkerClient&, CanonicalWorkerEnvironmentSettingsObject const&)> const&);diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 39d475e8e6d..a7bcc451a41 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -2265,19 +2265,30 @@ void PageClient::reset_gamepad_access_for_testing()Web::PageClient::StartedWorkerAgent PageClient::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request){auto agent_type = request.agent_type;- auto owner_token = request.owner_token;auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::StartWorkerAgent>(m_id, move(request));if (!response) {dbgln("WebContent client disconnected during StartWorkerAgent. Exiting peacefully.");Core::Process::terminate_immediately(0);}- // NB: The UI process notices a transport that nobody takes up, and tells the owner that its worker is gone.- RefPtr<Web::HTML::DedicatedWorkerThreadLink> dedicated_worker_thread_link;- if (auto transport = response->take_thread_transport(); transport.has_value())- dedicated_worker_thread_link = WebWorker::start_worker_thread_for_owner(transport.release_value(), agent_type, owner_token);+ // NB: The UI process notices a transport that nobody takes up, and tells the owners that their worker is gone.+ if (auto transport = response->take_thread_transport(); transport.has_value()) {+ if (auto result = WebWorker::start_worker_thread(transport.release_value(), agent_type); result.is_error())+ dbgln("Unable to start a thread for a worker: {}", result.error());+ }++ return { response->agent_id(), response->is_hosted_in_caller_process() };+}- return { response->agent_id(), response->is_hosted_in_caller_process(), move(dedicated_worker_thread_link) };+RefPtr<Web::HTML::DedicatedWorkerThreadLink> PageClient::start_dedicated_worker(Web::HTML::WorkerAgentStartRequest&& request)+{+ auto started_thread = WebWorker::start_dedicated_worker_thread(request.owner_token);+ if (started_thread.is_error()) {+ dbgln("Unable to start a dedicated worker: {}", started_thread.error());+ return {};+ }+ client().async_register_dedicated_worker(m_id, move(request), move(started_thread.value().browser_end_of_worker_connection));+ return move(started_thread.value().link);}void PageClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex e3b034d1fb2..4bc1713a836 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -412,6 +412,7 @@ private:virtual void pump_gamepad_events() override;virtual void reset_gamepad_access_for_testing() override;virtual Web::PageClient::StartedWorkerAgent start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;+ virtual RefPtr<Web::HTML::DedicatedWorkerThreadLink> start_dedicated_worker(Web::HTML::WorkerAgentStartRequest&&) override;virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;virtual void page_did_mutate_dom(Utf16FlyString const& type, Web::DOM::Node const& target, Web::DOM::NodeList& added_nodes, Web::DOM::NodeList& removed_nodes, GC::Ptr<Web::DOM::Node> previous_sibling, GC::Ptr<Web::DOM::Node> next_sibling, Optional<Utf16FlyString> const& attribute_name) override;virtual void flush_pending_dom_mutations() override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex fdfeaaafa1d..6abae9e37d7 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -322,4 +322,5 @@ endpoint WebContentClient routed by Web::PageId page_id[NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id, Optional<IPC::TransportHandle> thread_transport, bool is_hosted_in_caller_process)[NotRouted] close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|+ [NotRouted] register_dedicated_worker(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport) =|}diff --git a/Services/WebContent/WebWorkerClient.ipc b/Services/WebContent/WebWorkerClient.ipcindex 75af24ca6a0..f5ad6ef3eb9 100644--- a/Services/WebContent/WebWorkerClient.ipc+++ b/Services/WebContent/WebWorkerClient.ipc@@ -28,6 +28,5 @@ endpoint WebWorkerClient {request_compositor_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, Optional<IPC::TransportHandle> thread_transport, bool is_hosted_in_caller_process)- close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|+ register_dedicated_worker(Web::HTML::WorkerAgentStartRequest request, IPC::TransportHandle worker_transport) =|}diff --git a/Services/WebContent/Worker/ConnectionFromClient.h b/Services/WebContent/Worker/ConnectionFromClient.hindex ffac4c3bfb2..bddf201d76e 100644--- a/Services/WebContent/Worker/ConnectionFromClient.h+++ b/Services/WebContent/Worker/ConnectionFromClient.h@@ -48,6 +48,7 @@ public:void request_file(Web::FileRequest);DedicatedWorkerThreadLink* dedicated_worker_thread_link() { return m_dedicated_worker_thread_link.ptr(); }+ NonnullRefPtr<Web::HTML::ScriptAbortHandle> script_abort_handle() const { return m_script_abort_handle; }PageHost& page_host() { return *m_page_host; }PageHost const& page_host() const { return *m_page_host; }diff --git a/Services/WebContent/Worker/DedicatedWorkerThreadLink.cpp b/Services/WebContent/Worker/DedicatedWorkerThreadLink.cppindex ba20a142c7d..db8311caeea 100644--- a/Services/WebContent/Worker/DedicatedWorkerThreadLink.cpp+++ b/Services/WebContent/Worker/DedicatedWorkerThreadLink.cpp@@ -5,6 +5,7 @@*/#include <LibCore/EventLoop.h>+#include <LibWeb/HTML/Scripting/ScriptAbortHandle.h>#include <LibWeb/HTML/WorkerAgentParent.h>#include <WebContent/Worker/ConnectionFromClient.h>#include <WebContent/Worker/DedicatedWorkerThreadLink.h>@@ -30,6 +31,7 @@ void DedicatedWorkerThreadLink::attach_worker_connection(ConnectionFromClient& cMutexLocker locker(m_mutex);m_worker_event_loop = Core::EventLoop::current_weak();+ m_worker_script_abort_handle = connection.script_abort_handle();for (auto& task : m_tasks_posted_before_worker_attached)Core::deferred_invoke(run_on_attached_worker_connection(move(task)));m_tasks_posted_before_worker_attached.clear();@@ -65,6 +67,21 @@ void DedicatedWorkerThreadLink::post_to_owner(Function<void()> function)event_loop->deferred_invoke(move(function));}+void DedicatedWorkerThreadLink::terminate()+{+ RefPtr<Web::HTML::ScriptAbortHandle> worker_script_abort_handle;+ {+ MutexLocker locker(m_mutex);+ worker_script_abort_handle = m_worker_script_abort_handle;+ }+ if (worker_script_abort_handle)+ worker_script_abort_handle->abort_script();++ post_to_worker([](ConnectionFromClient& connection) {+ connection.close_worker();+ });+}+void DedicatedWorkerThreadLink::report_script_load_failure_to_owner(){post_to_owner([owner_token = m_owner_token] {diff --git a/Services/WebContent/Worker/DedicatedWorkerThreadLink.h b/Services/WebContent/Worker/DedicatedWorkerThreadLink.hindex ead666c54a1..ccd773a5f5e 100644--- a/Services/WebContent/Worker/DedicatedWorkerThreadLink.h+++ b/Services/WebContent/Worker/DedicatedWorkerThreadLink.h@@ -14,6 +14,7 @@#include <AK/Vector.h>#include <LibCore/Forward.h>#include <LibURL/URL.h>+#include <LibWeb/Forward.h>#include <LibWeb/HTML/DedicatedWorkerThreadLink.h>#include <LibWebCommon/HTML/WorkerAgentForward.h>#include <WebContent/Worker/Forward.h>@@ -38,6 +39,8 @@ public:void report_close_to_owner();void report_death_to_owner();+ virtual void terminate() override;+virtual void rtc_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record) override;virtual void rtc_transform_teardown(u64 transform_id) override;virtual void rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;@@ -54,6 +57,7 @@ private:Mutex m_mutex;RefPtr<Core::WeakEventLoopReference> m_worker_event_loop;+ RefPtr<Web::HTML::ScriptAbortHandle> m_worker_script_abort_handle;Vector<WorkerConnectionTask> m_tasks_posted_before_worker_attached;ConnectionFromClient* m_worker_connection { nullptr };diff --git a/Services/WebContent/Worker/PageHost.cpp b/Services/WebContent/Worker/PageHost.cppindex 7abf80d35b5..a708b3c9e77 100644--- a/Services/WebContent/Worker/PageHost.cpp+++ b/Services/WebContent/Worker/PageHost.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibCore/EventLoop.h>#include <LibGC/Heap.h>#include <LibWebCommon/HTML/WorkerAgentTypes.h>#include <WebContent/Worker/ConnectionFromClient.h>@@ -167,24 +168,15 @@ Optional<Web::FileAPI::SerializedBlobURLEntry> PageHost::page_did_request_blob_ureturn response->take_entry();}-Web::PageClient::StartedWorkerAgent PageHost::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request)+RefPtr<Web::HTML::DedicatedWorkerThreadLink> PageHost::start_dedicated_worker(Web::HTML::WorkerAgentStartRequest&& request){- auto agent_type = request.agent_type;- auto owner_token = request.owner_token;- auto response = m_client.send_sync_but_allow_failure<Messages::WebWorkerClient::StartWorkerAgent>(move(request));- if (!response)+ auto started_thread = start_dedicated_worker_thread(request.owner_token);+ if (started_thread.is_error()) {+ dbgln("Unable to start a dedicated worker: {}", started_thread.error());return {};-- // NB: The UI process notices a transport that nobody takes up, and tells the owner that its worker is gone.- RefPtr<Web::HTML::DedicatedWorkerThreadLink> dedicated_worker_thread_link;- if (auto transport = response->take_thread_transport(); transport.has_value())- dedicated_worker_thread_link = start_worker_thread_for_owner(transport.release_value(), agent_type, owner_token);- return { response->agent_id(), response->is_hosted_in_caller_process(), move(dedicated_worker_thread_link) };-}--void PageHost::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)-{- m_client.async_close_worker_agent(agent_id, owner_token);+ }+ m_client.async_register_dedicated_worker(move(request), move(started_thread.value().browser_end_of_worker_connection));+ return move(started_thread.value().link);}void PageHost::ensure_compositor_host()@@ -206,8 +198,13 @@ void PageHost::did_finish_loading_worker_script(bool worker_is_secure_context)void PageHost::did_fail_loading_worker_script(){- if (auto* link = m_client.dedicated_worker_thread_link())+ if (auto* link = m_client.dedicated_worker_thread_link()) {link->report_script_load_failure_to_owner();+ Core::deferred_invoke([&client = m_client] {+ client.close_worker();+ });+ return;+ }m_client.async_did_fail_loading_worker_script();}diff --git a/Services/WebContent/Worker/PageHost.h b/Services/WebContent/Worker/PageHost.hindex 7a9d4404d0f..7a521b13eaa 100644--- a/Services/WebContent/Worker/PageHost.h+++ b/Services/WebContent/Worker/PageHost.h@@ -50,8 +50,7 @@ public:virtual URL::BlobURLEntry::Token page_did_add_blob_url_entry(Web::HTML::EnvironmentSettingsObject const&, Utf16String const& url, Web::FileAPI::SerializedBlobURLEntry const&) override;virtual void page_did_remove_blob_url_entries(Web::HTML::EnvironmentSettingsObject const&, Vector<Utf16String> const& urls) override;virtual Optional<Web::FileAPI::SerializedBlobURLEntry> page_did_request_blob_url_entry(Utf16String const& url, Optional<URL::BlobURLEntry::Token> token) override;- virtual Web::PageClient::StartedWorkerAgent start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;- virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;+ virtual RefPtr<Web::HTML::DedicatedWorkerThreadLink> start_dedicated_worker(Web::HTML::WorkerAgentStartRequest&&) override;virtual bool supports_compositor() const override { return true; }virtual void ensure_compositor_host() override;virtual Web::Compositor::CompositorHost* compositor_host() override { return m_compositor_host.ptr(); }diff --git a/Services/WebContent/Worker/WorkerHost.cpp b/Services/WebContent/Worker/WorkerHost.cppindex 7ef65f7e090..67b26b69d26 100644--- a/Services/WebContent/Worker/WorkerHost.cpp+++ b/Services/WebContent/Worker/WorkerHost.cpp@@ -67,6 +67,9 @@ void WorkerHost::run_closing_steps()// 18. Empty worker global scope's owner set.m_worker_global_scope->owner_set().clear();+ // AD-HOC: As a document does when it is destroyed, the worker leaves the owner sets of the workers it owns.+ m_inside_settings->release_owned_worker_agents();+// AD-HOC: The File API only has these steps for a Document, but the blob URLs of a worker go away with it as well.Web::FileAPI::remove_entries_of_environment(*m_inside_settings, *m_worker_global_scope->page());diff --git a/Services/WebContent/Worker/WorkerThread.cpp b/Services/WebContent/Worker/WorkerThread.cppindex e3cc6e4c02a..4926ed9c446 100644--- a/Services/WebContent/Worker/WorkerThread.cpp+++ b/Services/WebContent/Worker/WorkerThread.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Atomic.h>#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/NonnullRefPtr.h>@@ -14,6 +15,7 @@#include <LibJS/Runtime/VM.h>#include <LibThreading/Thread.h>#include <LibWeb/Bindings/MainThreadVM.h>+#include <LibWebCommon/HTML/WorkerAgentTypes.h>#include <WebContent/Worker/ConnectionFromClient.h>#include <WebContent/Worker/DedicatedWorkerThreadLink.h>#include <WebContent/Worker/WorkerThread.h>@@ -33,6 +35,8 @@ static WorkerThreads& worker_threads()static thread_local bool s_is_worker_thread { false };+static Atomic<size_t, AK::MemoryOrder::memory_order_relaxed> s_worker_thread_count { 0 };+bool is_worker_thread(){return s_is_worker_thread;@@ -48,6 +52,7 @@ static intptr_t run_worker_thread(IPC::TransportHandle const& worker_handle, Webauto 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());+ --s_worker_thread_count;if (dedicated_worker_thread_link)dedicated_worker_thread_link->report_death_to_owner();return 1;@@ -77,6 +82,7 @@ static intptr_t run_worker_thread(IPC::TransportHandle const& worker_handle, Webworker_threads().event_loops.remove_first_matching([&](auto const& reference) { return reference.ptr() == event_loop_reference.ptr(); });}+ --s_worker_thread_count;client->shut_down_agent();return exit_code;}@@ -88,7 +94,11 @@ static ErrorOr<void> start_thread(IPC::TransportHandle worker_handle, Web::HTML:}));thread->set_stack_size(JS::VM::MINIMUM_THREAD_STACK_SIZE);- TRY(thread->try_start());+ ++s_worker_thread_count;+ if (auto result = thread->try_start(); result.is_error()) {+ --s_worker_thread_count;+ return result.release_error();+ }// NB: Nothing waits for a worker's thread: one that is stuck in a long builtin must not hold up anything else.thread->detach();@@ -100,17 +110,15 @@ ErrorOr<void> start_worker_thread(IPC::TransportHandle worker_handle, Web::HTML:return start_thread(move(worker_handle), agent_type, nullptr);}-RefPtr<Web::HTML::DedicatedWorkerThreadLink> start_worker_thread_for_owner(IPC::TransportHandle worker_handle, Web::HTML::AgentType agent_type, Web::HTML::WorkerAgentOwnerToken owner_token)+ErrorOr<StartedDedicatedWorkerThread> start_dedicated_worker_thread(Web::HTML::WorkerAgentOwnerToken owner_token){- RefPtr<DedicatedWorkerThreadLink> dedicated_worker_thread_link;- if (agent_type == Web::HTML::AgentType::DedicatedWorker)- dedicated_worker_thread_link = DedicatedWorkerThreadLink::create(owner_token);+ if (s_worker_thread_count >= Web::HTML::maximum_worker_count)+ return Error::from_string_literal("This process already runs as many workers as it may");- if (auto result = start_thread(move(worker_handle), agent_type, dedicated_worker_thread_link); result.is_error()) {- dbgln("Unable to start a thread for a worker: {}", result.error());- return nullptr;- }- return dedicated_worker_thread_link;+ auto worker_connection = TRY(IPC::TransportHandle::create_pair());+ auto link = DedicatedWorkerThreadLink::create(owner_token);+ TRY(start_thread(move(worker_connection.first), Web::HTML::AgentType::DedicatedWorker, link));+ return StartedDedicatedWorkerThread { move(link), move(worker_connection.second) };}void post_to_worker_threads(void (*function)())diff --git a/Services/WebContent/Worker/WorkerThread.h b/Services/WebContent/Worker/WorkerThread.hindex 034c9dbf881..8357c95628f 100644--- a/Services/WebContent/Worker/WorkerThread.h+++ b/Services/WebContent/Worker/WorkerThread.h@@ -7,8 +7,8 @@#pragma once#include <AK/Error.h>-#include <AK/RefPtr.h>-#include <LibIPC/Forward.h>+#include <AK/NonnullRefPtr.h>+#include <LibIPC/TransportHandle.h>#include <LibWeb/Forward.h>#include <LibWebCommon/HTML/WorkerAgentForward.h>#include <LibWebCommon/HTML/WorkerTypes.h>@@ -19,7 +19,12 @@ namespace WebWorker {// 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, Web::HTML::AgentType);-RefPtr<Web::HTML::DedicatedWorkerThreadLink> start_worker_thread_for_owner(IPC::TransportHandle, Web::HTML::AgentType, Web::HTML::WorkerAgentOwnerToken);++struct StartedDedicatedWorkerThread {+ NonnullRefPtr<Web::HTML::DedicatedWorkerThreadLink> link;+ IPC::TransportHandle browser_end_of_worker_connection;+};+ErrorOr<StartedDedicatedWorkerThread> start_dedicated_worker_thread(Web::HTML::WorkerAgentOwnerToken);// Whether the calling thread is one start_worker_thread() started. This can be asked from a signal handler.bool is_worker_thread();diff --git a/Tests/LibWeb/Text/expected/Workers/worker-many-instances.txt b/Tests/LibWeb/Text/expected/Workers/worker-many-instances.txtindex 5b5fac9f47e..9c683cce1c8 100644--- a/Tests/LibWeb/Text/expected/Workers/worker-many-instances.txt+++ b/Tests/LibWeb/Text/expected/Workers/worker-many-instances.txt@@ -1,4 +1,5 @@scripts ran: 64, all alike: trueagents: 64pongs: 64+worker beyond the limit fails: trueagents after terminate: 0diff --git a/Tests/LibWeb/Text/input/Workers/worker-many-instances.html b/Tests/LibWeb/Text/input/Workers/worker-many-instances.htmlindex 6645be96c13..d81a83e7c13 100644--- a/Tests/LibWeb/Text/input/Workers/worker-many-instances.html+++ b/Tests/LibWeb/Text/input/Workers/worker-many-instances.html@@ -34,6 +34,14 @@await waitForCondition(() => replies.length === 2 * WORKER_COUNT, 1200);println(`pongs: ${replies.filter(reply => reply === "pong").length}`);+ const workerBeyondTheLimit = new Worker(url);+ const workerBeyondTheLimitFailed = await new Promise(resolve => {+ workerBeyondTheLimit.onerror = () => resolve(true);+ workerBeyondTheLimit.onmessage = () => resolve(false);+ });+ println(`worker beyond the limit fails: ${workerBeyondTheLimitFailed}`);+ workerBeyondTheLimit.terminate();+for (const worker of workers) worker.terminate();await waitForCondition(() => internals.workerAgentCount() === 0, 1200);println(`agents after terminate: ${internals.workerAgentCount()}`);