Truly independent web browser
LibWeb+LibWebView+Services: Launch ImageDecoders on demand
Andreas Klinga809bcbc3c53
diff --git a/Libraries/LibImageDecoderClient/CMakeLists.txt b/Libraries/LibImageDecoderClient/CMakeLists.txtindex 76fd1d8d90d..6010b41027f 100644--- a/Libraries/LibImageDecoderClient/CMakeLists.txt+++ b/Libraries/LibImageDecoderClient/CMakeLists.txt@@ -4,11 +4,15 @@ set(SOURCESif (NOT SERENITYOS)compile_ipc(../../Services/ImageDecoder/ImageDecoderClient.ipc ../../Services/ImageDecoder/ImageDecoderClientEndpoint.h)+ compile_ipc(../../Services/ImageDecoder/ImageDecoderControl.ipc ../../Services/ImageDecoder/ImageDecoderControlEndpoint.h)+ compile_ipc(../../Services/ImageDecoder/ImageDecoderControlClient.ipc ../../Services/ImageDecoder/ImageDecoderControlClientEndpoint.h)compile_ipc(../../Services/ImageDecoder/ImageDecoderServer.ipc ../../Services/ImageDecoder/ImageDecoderServerEndpoint.h)endif()set(GENERATED_SOURCES../../Services/ImageDecoder/ImageDecoderClientEndpoint.h+ ../../Services/ImageDecoder/ImageDecoderControlClientEndpoint.h+ ../../Services/ImageDecoder/ImageDecoderControlEndpoint.h../../Services/ImageDecoder/ImageDecoderServerEndpoint.h)diff --git a/Libraries/LibImageDecoderClient/Client.cpp b/Libraries/LibImageDecoderClient/Client.cppindex 675d0400aad..5ff15f6215e 100644--- a/Libraries/LibImageDecoderClient/Client.cpp+++ b/Libraries/LibImageDecoderClient/Client.cpp@@ -19,11 +19,13 @@ void Client::die()verify_event_loop();auto pending_promises = move(m_token_promises);- for (auto& promise : pending_promises)- promise.value->reject(Error::from_string_literal("ImageDecoder disconnected"));-+ // NB: A rejection may start another decode, so whoever holds this client must have let go of it by then. That may also+ // be the last reference to this client, so nothing here touches it after this.if (auto on_death = move(this->on_death))on_death();++ for (auto& promise : pending_promises)+ promise.value->reject(Error::from_string_literal("ImageDecoder disconnected"));}NonnullRefPtr<Core::Promise<DecodedImage>> Client::decode_image(ReadonlyBytes encoded_data, Function<ErrorOr<void>(DecodedImage&)> on_resolved, Function<void(Error&)> on_rejected, Optional<Gfx::IntSize> ideal_size, Optional<ByteString> mime_type)diff --git a/Libraries/LibWeb/Platform/ImageCodecPlugin.cpp b/Libraries/LibWeb/Platform/ImageCodecPlugin.cppindex 0224eac1904..61136d424ae 100644--- a/Libraries/LibWeb/Platform/ImageCodecPlugin.cpp+++ b/Libraries/LibWeb/Platform/ImageCodecPlugin.cpp@@ -19,11 +19,6 @@ ImageCodecPlugin& ImageCodecPlugin::the()return *s_the;}-bool ImageCodecPlugin::is_initialized()-{- return s_the != nullptr;-}-void ImageCodecPlugin::install(ImageCodecPlugin& plugin){VERIFY(!s_the);diff --git a/Libraries/LibWeb/Platform/ImageCodecPlugin.h b/Libraries/LibWeb/Platform/ImageCodecPlugin.hindex f27f02acef6..5ca20c7d439 100644--- a/Libraries/LibWeb/Platform/ImageCodecPlugin.h+++ b/Libraries/LibWeb/Platform/ImageCodecPlugin.h@@ -40,7 +40,6 @@ struct DecodedFirstFrame {class WEB_API ImageCodecPlugin {public:static ImageCodecPlugin& the();- static bool is_initialized();static void install(ImageCodecPlugin&);virtual ~ImageCodecPlugin();diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cppindex 01591359727..2169817dfa8 100644--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp@@ -12,24 +12,30 @@namespace Web::Platform {-RemoteImageCodecPlugin::RemoteImageCodecPlugin(NonnullRefPtr<ImageDecoderClient::Client> client)- : m_client(move(client))+RemoteImageCodecPlugin::RemoteImageCodecPlugin(ConnectToImageDecoder connect_to_image_decoder)+ : m_connect_to_image_decoder(move(connect_to_image_decoder)){- setup_client_callbacks();}-void RemoteImageCodecPlugin::set_client(NonnullRefPtr<ImageDecoderClient::Client> client)+ImageDecoderClient::Client* RemoteImageCodecPlugin::ensure_client(){- m_client = move(client);- ++m_client_generation;- setup_client_callbacks();-}+ if (m_client)+ return m_client;-void RemoteImageCodecPlugin::setup_client_callbacks()-{+ auto client = m_connect_to_image_decoder();+ if (client.is_error()) {+ dbgln("Failed to connect to an image decoder: {}", client.error());+ return nullptr;+ }++ // NB: The generation also changes here, for a frame channel that was given up on while no client could be had.+ m_client = client.release_value();+ ++m_client_generation;m_client->on_death = [this] {m_client = nullptr;+ ++m_client_generation;};+ return m_client;}RemoteImageCodecPlugin::~RemoteImageCodecPlugin() = default;@@ -42,12 +48,13 @@ NonnullRefPtr<Core::Promise<DecodedImage>> RemoteImageCodecPlugin::decode_image(if (on_rejected)promise->on_rejection = move(on_rejected);- if (!m_client) {+ auto* client = ensure_client();+ if (!client) {promise->reject(Error::from_string_literal("ImageDecoderClient is disconnected"));return promise;}- auto image_decoder_promise = m_client->decode_image(+ auto image_decoder_promise = client->decode_image(bytes,[promise](ImageDecoderClient::DecodedImage& result) -> ErrorOr<void> {// FIXME: Remove this codec plugin and just use the ImageDecoderClient directly to avoid these copies@@ -73,9 +80,10 @@ NonnullRefPtr<Core::Promise<DecodedImage>> RemoteImageCodecPlugin::decode_image(ErrorOr<DecodedFirstFrame> RemoteImageCodecPlugin::decode_first_frame_synchronously(ReadonlyBytes bytes){- if (!m_client)+ auto* client = ensure_client();+ if (!client)return Error::from_string_literal("ImageDecoderClient is disconnected");- auto result = TRY(m_client->decode_first_frame_synchronously(bytes));+ auto result = TRY(client->decode_first_frame_synchronously(bytes));return DecodedFirstFrame { move(result.bitmap), move(result.color_space) };}@@ -87,8 +95,8 @@ void RemoteImageCodecPlugin::stop_animation_decode(i64 session_id)void RemoteImageCodecPlugin::connect_frame_client(IPC::TransportHandle handle){- if (m_client)- m_client->async_connect_frame_client(handle);+ if (auto* client = ensure_client())+ client->async_connect_frame_client(handle);}}diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.hindex c4223c95fa7..39e0fc317d9 100644--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h@@ -18,7 +18,10 @@ class WEB_API RemoteImageCodecPlugin final : public ImageCodecPlugin {public:AK_ALLOC_WITH_KMALLOC;- explicit RemoteImageCodecPlugin(NonnullRefPtr<ImageDecoderClient::Client>);+ // Called for a client whenever one is needed and there is none, at first and after losing one.+ using ConnectToImageDecoder = Function<ErrorOr<NonnullRefPtr<ImageDecoderClient::Client>>()>;++ explicit RemoteImageCodecPlugin(ConnectToImageDecoder);virtual ~RemoteImageCodecPlugin() override;virtual NonnullRefPtr<Core::Promise<DecodedImage>> decode_image(ReadonlyBytes, Function<ErrorOr<void>(DecodedImage&)> on_resolved, Function<void(Error&)> on_rejected) override;@@ -29,11 +32,10 @@ public:virtual void connect_frame_client(IPC::TransportHandle) override;virtual u64 client_generation() const override { return m_client_generation; }- void set_client(NonnullRefPtr<ImageDecoderClient::Client>);-private:- void setup_client_callbacks();+ ImageDecoderClient::Client* ensure_client();+ ConnectToImageDecoder m_connect_to_image_decoder;RefPtr<ImageDecoderClient::Client> m_client;u64 m_client_generation { 0 };};diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 9bdc4f70381..bdfb7acbee3 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -60,6 +60,7 @@#include <LibWebView/HeadlessWebView.h>#include <LibWebView/HelperProcess.h>#include <LibWebView/HistoryStore.h>+#include <LibWebView/ImageDecoderManager.h>#include <LibWebView/Menu.h>#include <LibWebView/NoOpMicrophoneAuthorizer.h>#include <LibWebView/NoOpNotificationBackend.h>@@ -1175,7 +1176,6 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client({// The client's WebContentClient picks up this same session when it is created.auto session = session_for_new_view(is_private);- auto image_decoder = TRY(launch_image_decoder_process());auto cross_process_id_allocator = allocate_cross_process_id_allocator();auto root_navigable_id = navigable_to_adopt.has_value() ? *navigable_to_adopt : cross_process_id_allocator.allocate();@@ -1206,7 +1206,6 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(client->async_set_site_compatibility_data(m_site_compatibility_data);// A process learns a site's permissions only when it shows that site and asks; at launch, just the defaults.client->async_set_permission_snapshot(client->session().permission_manager->snapshot_for({}));- connect_to_image_decoder(*client, move(image_decoder));// NB: A WebDriver BiDi session gives its state to every process hosting web content when it changes.if (auto* webdriver_bidi = WebDriverBiDi::the(); webdriver_bidi && webdriver_bidi->session_state().is_active)@@ -1928,6 +1927,7 @@ ErrorOr<void> Application::launch_services()}}+ m_image_decoder_manager = make<ImageDecoderManager>();TRY(launch_request_server());TRY(launch_compositor_process());@@ -2157,11 +2157,6 @@ void Application::configure_request_server_control_client(Requests::RequestContrTabPerformanceMonitor::configure(control_client);}-void Application::set_image_decoder_exit_handler(u64 child_id, Function<void()> handler)-{- m_image_decoder_exit_handlers.set(child_id, move(handler));-}-ErrorOr<void> Application::launch_devtools_server(){VERIFY(!m_devtools);@@ -2328,6 +2323,8 @@ void Application::process_did_exit(Process&& process, Optional<int>)if (m_event_loop->was_exit_requested())return;+ m_image_decoder_manager->process_did_exit(process.child_id());+dbgln_if(WEBVIEW_PROCESS_DEBUG, "Process {} died, type: {}", process.pid(), process_name_from_type(process.type()));auto const& report_name = process.saved_crash_report_name();@@ -2341,8 +2338,7 @@ void Application::process_did_exit(Process&& process, Optional<int>)}break;case ProcessType::ImageDecoder:- if (auto handler = m_image_decoder_exit_handlers.take(process.child_id()); handler.has_value())- (*handler)();+ // The processes it served ask for a new one when they next have an image to decode.break;case ProcessType::MediaServer:// The connection's holder launches a new MediaServer when it next connects a client.diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex df60aec398f..9afbd273ce5 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -125,6 +125,7 @@ public:virtual Web::CSS::PreferredColorScheme interface_color_scheme() const;static RequestServerManager& request_server_manager() { return *the().m_request_server_manager; }+ static ImageDecoderManager& image_decoder_manager() { return *the().m_image_decoder_manager; }// The UI process's own client of the session's RequestServer with no site.static ErrorOr<NonnullRefPtr<Requests::RequestClient>> request_server_client(IsPrivate = IsPrivate::No);// The control connection of the default session's RequestServer with no site.@@ -246,8 +247,6 @@ public:static IPC::HandleBrokerServer& handle_broker_server() { return *the().m_handle_broker_server; }#endif- // Runs the handler when the ImageDecoder with the given child ID exits.- void set_image_decoder_exit_handler(u64 child_id, Function<void()>);#if defined(AK_OS_MACOS)static IPC::TransportBootstrapMachServer& transport_bootstrap_server() { return the().m_transport_bootstrap_server; }void set_browser_process_transport_handler(Function<void(NonnullOwnPtr<IPC::Transport>)> handler);@@ -674,7 +673,7 @@ private:WebDriverSessionConfig m_webdriver_session_config;OwnPtr<RequestServerManager> m_request_server_manager;- HashMap<u64, Function<void()>> m_image_decoder_exit_handlers;+ OwnPtr<ImageDecoderManager> m_image_decoder_manager;RefPtr<CompositorClient> m_compositor_client;RefPtr<CompositorPresentationClient> m_compositor_presentation_client;u64 m_compositor_presentation_id { 0 };diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txtindex b7ab7add8b9..65784c2caa2 100644--- a/Libraries/LibWebView/CMakeLists.txt+++ b/Libraries/LibWebView/CMakeLists.txt@@ -42,6 +42,8 @@ set(SOURCESHistoryDebug.cppHistoryStore.cppHSTSStore.cpp+ ImageDecoderControlClient.cpp+ ImageDecoderManager.cppLingeringIndicator.cppMenu.cppNavigationLoader.cpp@@ -130,6 +132,8 @@ set(GENERATED_SOURCES${GENERATED_SOURCES}../../Services/AudioServer/AudioServerControlClientEndpoint.h../../Services/AudioServer/AudioServerControlEndpoint.h+ ../../Services/ImageDecoder/ImageDecoderControlClientEndpoint.h+ ../../Services/ImageDecoder/ImageDecoderControlEndpoint.h../../Services/RequestServer/RequestClientEndpoint.h../../Services/RequestServer/RequestServerEndpoint.h../../Services/VideoDecoderServer/VideoDecoderServerControlClientEndpoint.hdiff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.hindex a4fd8ccdb66..b89b6f891f6 100644--- a/Libraries/LibWebView/Forward.h+++ b/Libraries/LibWebView/Forward.h@@ -44,6 +44,8 @@ class FontService;class FontServiceHost;class HistoryStore;class HSTSStore;+class ImageDecoderControlClient;+class ImageDecoderManager;class Menu;class MicrophoneAuthorizer;class NavigationLoader;diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex 513a81ae7c7..708b38ff8a6 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -20,6 +20,7 @@#include <LibWebView/FontService.h>#include <LibWebView/FontServiceHost.h>#include <LibWebView/HelperProcess.h>+#include <LibWebView/ImageDecoderControlClient.h>#include <LibWebView/RequestServerManager.h>#include <LibWebView/Utilities.h>#include <LibWebView/VideoDecoderServerControlClient.h>@@ -307,12 +308,15 @@ template<typename ClientType>static ErrorOr<NonnullRefPtr<ClientType>> launch_server_process_for(u64 owner_child_id, StringView server_name, Vector<ByteString> arguments){RefPtr<ClientType> client;- TRY(launch_helper_process(server_name, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {+ auto identity = TRY(launch_helper_process(server_name, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {auto [process, new_client] = TRY(WebView::Process::spawn<ClientType>(WebView::process_type_from_name(server_name), options, capture_output));process.set_owner_child_id(owner_child_id);client = move(new_client);return move(process);}));++ if constexpr (requires { client->set_child_identity(ChildIdentity {}); })+ client->set_child_identity(identity);return client.release_nonnull();}@@ -392,7 +396,7 @@ ErrorOr<NonnullRefPtr<WebView::WebContentClient>> launch_web_content_process(IsPreturn client;}-ErrorOr<ImageDecoderConnection> launch_image_decoder_process()+ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(u64 owner_child_id){auto const& browser_options = WebView::Application::browser_options();@@ -404,40 +408,7 @@ ErrorOr<ImageDecoderConnection> launch_image_decoder_process()arguments.append(server.value());}- // The decoder parses untrusted images for one client, so it must not see the images of any other. The Browser- // does not talk to it, and hands its end of the transport to the client.- OwnPtr<IPC::Transport> transport;- auto identity = TRY(launch_helper_process("ImageDecoder"sv, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {- auto [process, new_transport] = TRY(WebView::Process::spawn_with_transport(ProcessType::ImageDecoder, options, capture_output));- transport = move(new_transport);- return move(process);- }));-- return ImageDecoderConnection { TRY(transport->release_for_transfer()), identity.child_id };-}--template<typename ClientType>-static void connect_client_to_image_decoder(ClientType& client, ImageDecoderConnection decoder)-{- auto process = Application::process_manager().find_child(decoder.child_id);- VERIFY(process.has_value());- process->set_owner_child_id(client.child_id());- client.async_connect_to_image_decoder(decoder.handle);-- // A decoder exits by itself once its client is gone. One that dies before then is replaced, so a crash costs the- // client the images it was decoding at the time rather than every image after it.- Application::the().set_image_decoder_exit_handler(decoder.child_id, [weak_client = client.template make_weak_ptr<ClientType>()] {- auto client = weak_client.strong_ref();- if (!client || !client->is_open())- return;-- auto new_decoder = launch_image_decoder_process();- if (new_decoder.is_error()) {- dbgln("Failed to replace a crashed image decoder: {}", new_decoder.error());- return;- }- connect_client_to_image_decoder(*client, new_decoder.release_value());- });+ return launch_server_process_for<ImageDecoderControlClient>(owner_child_id, "ImageDecoder"sv, move(arguments));}ErrorOr<IPC::TransportHandle> launch_webrtc_client_process(WebContentClient& client)@@ -465,7 +436,7 @@ ErrorOr<IPC::TransportHandle> launch_webrtc_client_process(WebContentClient& cli}// NB: The renderer's sandbox does not let it spawn processes, so the Browser launches the helper and hands its end- // of the transport over, as it does for the ImageDecoder.+ // of the transport over.OwnPtr<IPC::Transport> transport;auto identity = TRY(launch_helper_process("WebRTCClient"sv, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {auto [process, new_transport] = TRY(WebView::Process::spawn_with_transport(ProcessType::WebRTCClient, options, capture_output));@@ -480,16 +451,6 @@ ErrorOr<IPC::TransportHandle> launch_webrtc_client_process(WebContentClient& clireturn transport->release_for_transfer();}-void connect_to_image_decoder(WebContentClient& client, ImageDecoderConnection decoder)-{- connect_client_to_image_decoder(client, move(decoder));-}--void connect_to_image_decoder(WebWorkerClient& client, ImageDecoderConnection decoder)-{- connect_client_to_image_decoder(client, move(decoder));-}-ErrorOr<NonnullRefPtr<AudioServerControlClient>> launch_audio_server_process(u64 owner_child_id){auto const& browser_options = WebView::Application::browser_options();diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.hindex 21aaa3d2362..60ec8b05159 100644--- a/Libraries/LibWebView/HelperProcess.h+++ b/Libraries/LibWebView/HelperProcess.h@@ -35,17 +35,8 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebWorkerClient>> launch_web_worker_pWEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode);WEBVIEW_API void apply_dns_settings(Requests::RequestControlClient&);-struct ImageDecoderConnection {- IPC::TransportHandle handle;- u64 child_id { 0 };-};--// Launches an ImageDecoder that serves a single renderer or worker, which talks to it over the returned handle.-WEBVIEW_API ErrorOr<ImageDecoderConnection> launch_image_decoder_process();--// Hands the client its ImageDecoder. If that decoder dies while the client is still connected, the client gets a new one.-WEBVIEW_API void connect_to_image_decoder(WebContentClient&, ImageDecoderConnection);-WEBVIEW_API void connect_to_image_decoder(WebWorkerClient&, ImageDecoderConnection);+// Launches an ImageDecoder, which the given process is listed with.+WEBVIEW_API ErrorOr<NonnullRefPtr<ImageDecoderControlClient>> launch_image_decoder_process(u64 owner_child_id);// Launches a WebRTCClient that serves the given renderer alone, which talks to it over the returned handle, and ends any// helper the renderer had before. The helper exits once that renderer's end of the transport is gone.diff --git a/Libraries/LibWebView/ImageDecoderControlClient.cpp b/Libraries/LibWebView/ImageDecoderControlClient.cppnew file mode 100644index 00000000000..6d80a9da1bf--- /dev/null+++ b/Libraries/LibWebView/ImageDecoderControlClient.cpp@@ -0,0 +1,24 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWebView/ImageDecoderControlClient.h>++namespace WebView {++ImageDecoderControlClient::ImageDecoderControlClient(NonnullOwnPtr<IPC::Transport> transport)+ : IPC::ConnectionToServer<ImageDecoderControlClientEndpoint, ImageDecoderControlEndpoint>(*this, move(transport))+{+}++ImageDecoderControlClient::~ImageDecoderControlClient() = default;++void ImageDecoderControlClient::die()+{+ // The clients of a decoder that died hear about it from their own connections, and ask for a new one when they next+ // have an image to decode.+}++}diff --git a/Libraries/LibWebView/ImageDecoderControlClient.h b/Libraries/LibWebView/ImageDecoderControlClient.hnew file mode 100644index 00000000000..40eade27658--- /dev/null+++ b/Libraries/LibWebView/ImageDecoderControlClient.h@@ -0,0 +1,37 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <ImageDecoder/ImageDecoderControlClientEndpoint.h>+#include <ImageDecoder/ImageDecoderControlEndpoint.h>+#include <LibIPC/ConnectionToServer.h>+#include <LibWebView/ChildIdentity.h>+#include <LibWebView/Export.h>++namespace WebView {++// The control plane of an ImageDecoder, spoken only by the Browser, which launched it. A decoder parses untrusted images,+// so this connection carries nothing back from it.+class WEBVIEW_API ImageDecoderControlClient final+ : public IPC::ConnectionToServer<ImageDecoderControlClientEndpoint, ImageDecoderControlEndpoint>+ , public ImageDecoderControlClientEndpoint {+ C_OBJECT_ABSTRACT(ImageDecoderControlClient);++public:+ explicit ImageDecoderControlClient(NonnullOwnPtr<IPC::Transport>);+ virtual ~ImageDecoderControlClient() override;++ u64 child_id() const { return m_child_identity.child_id; }+ void set_child_identity(ChildIdentity identity) { m_child_identity = identity; }++private:+ virtual void die() override;++ ChildIdentity m_child_identity;+};++}diff --git a/Libraries/LibWebView/ImageDecoderManager.cpp b/Libraries/LibWebView/ImageDecoderManager.cppnew file mode 100644index 00000000000..d455b43dffd--- /dev/null+++ b/Libraries/LibWebView/ImageDecoderManager.cpp@@ -0,0 +1,67 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWebView/Application.h>+#include <LibWebView/HelperProcess.h>+#include <LibWebView/ImageDecoderControlClient.h>+#include <LibWebView/ImageDecoderManager.h>++namespace WebView {++ImageDecoderManager& ImageDecoderManager::the()+{+ return Application::image_decoder_manager();+}++ImageDecoderManager::ImageDecoderManager() = default;+ImageDecoderManager::~ImageDecoderManager() = default;++ErrorOr<IPC::TransportHandle> ImageDecoderManager::connect_new_client(u64 client_child_id, IsPrivate)+{+ // NB: A decoder that died is of no use to anyone, whether or not its clients have noticed yet.+ m_instances.remove_all_matching([](auto const& instance) { return !instance.control_client->is_open(); });++ auto instance = m_instances.first_matching([&](auto const& instance) {+ return instance.client_child_ids.contains(client_child_id);+ });+ auto channel = TRY(IPC::TransportHandle::create_pair());+ if (!instance.has_value()) {+ m_instances.append({ .control_client = TRY(launch_image_decoder_process(client_child_id)), .client_child_ids = {} });+ instance = m_instances.last();+ }++ instance->control_client->async_connect_new_client(channel.first);+ instance->client_child_ids.set(client_child_id);+ return move(channel.second);+}++Optional<IPC::TransportHandle> ImageDecoderManager::connect_requesting_process(u64 client_child_id, IsPrivate is_private)+{+ // NB: A request can still be queued when the process's exit is handled. Connecting it then would leave a client that+ // never exits, which would keep its decoder alive for as long as the Browser runs.+ if (!Application::process_manager().find_child(client_child_id).has_value())+ return {};++ auto handle = connect_new_client(client_child_id, is_private);+ if (handle.is_error()) {+ warnln("Unable to connect an ImageDecoder client: {}", handle.error());+ return {};+ }+ return handle.release_value();+}++void ImageDecoderManager::process_did_exit(u64 child_id)+{+ // NB: Letting go of a decoder that exited also closes the channels of any clients that were sent to it, which it can no+ // longer take up, so that those clients learn they have no decoder.+ 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();+ });+}++}diff --git a/Libraries/LibWebView/ImageDecoderManager.h b/Libraries/LibWebView/ImageDecoderManager.hnew file mode 100644index 00000000000..6d60bf116dd--- /dev/null+++ b/Libraries/LibWebView/ImageDecoderManager.h@@ -0,0 +1,48 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/HashTable.h>+#include <AK/NonnullRefPtr.h>+#include <AK/Optional.h>+#include <AK/Vector.h>+#include <LibIPC/TransportHandle.h>+#include <LibWebView/BrowsingSession.h>+#include <LibWebView/Export.h>+#include <LibWebView/Forward.h>++namespace WebView {++// Launches ImageDecoders as processes first ask for them, and ends each once the last process it serves is gone.+class WEBVIEW_API ImageDecoderManager {+public:+ AK_ALLOC_WITH_KMALLOC;++ static ImageDecoderManager& the();++ ImageDecoderManager();+ ~ImageDecoderManager();++ // Connects a renderer or worker to its ImageDecoder, launching one if need be. A process that lost its decoder asks+ // here again, and gets a new one.+ ErrorOr<IPC::TransportHandle> connect_new_client(u64 client_child_id, IsPrivate);++ // Answers a renderer or worker that asked for a decoder, which may have exited by the time its request is handled.+ Optional<IPC::TransportHandle> connect_requesting_process(u64 client_child_id, IsPrivate);++ void process_did_exit(u64 child_id);++private:+ struct Instance {+ NonnullRefPtr<ImageDecoderControlClient> control_client;+ HashTable<u64> client_child_ids;+ };++ Vector<Instance> m_instances;+};++}diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex bd64a5f54c0..cc045712846 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -37,6 +37,7 @@#include <LibWebView/HSTSStore.h>#include <LibWebView/HelperProcess.h>#include <LibWebView/HistoryStore.h>+#include <LibWebView/ImageDecoderManager.h>#include <LibWebView/NavigationLoader.h>#include <LibWebView/NotificationManager.h>#include <LibWebView/PermissionManager.h>@@ -1154,6 +1155,11 @@ Messages::WebContentClient::RequestWebrtcClientConnectionResponse WebContentCliereturn handle.release_value();}+Messages::WebContentClient::RequestImageDecoderConnectionResponse WebContentClient::request_image_decoder_connection()+{+ return ImageDecoderManager::the().connect_requesting_process(child_id(), m_is_private);+}+Optional<u64> WebContentClient::exclusive_performance_owner() const{Optional<u64> owner;diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 864ee78d07a..38c5dc684ed 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -231,6 +231,7 @@ private:virtual Messages::WebContentClient::RequestMediaServerConnectionResponse request_media_server_connection() override;virtual Messages::WebContentClient::RequestAudioServerConnectionResponse request_audio_server_connection() override;virtual Messages::WebContentClient::RequestWebrtcClientConnectionResponse request_webrtc_client_connection() override;+ virtual Messages::WebContentClient::RequestImageDecoderConnectionResponse request_image_decoder_connection() override;virtual void request_video_presentation_channel() override;virtual void gamepad_play_effect(Web::Gamepad::GamepadHandle handle, Web::Gamepad::GamepadEffect effect) override;virtual void gamepad_stop_effects(Web::Gamepad::GamepadHandle handle) override;diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cppindex e0574a336be..617e3a83d2b 100644--- a/Libraries/LibWebView/WebWorkerClient.cpp+++ b/Libraries/LibWebView/WebWorkerClient.cpp@@ -13,6 +13,7 @@#include <LibWebView/CookieJar.h>#include <LibWebView/HSTSStore.h>#include <LibWebView/HelperProcess.h>+#include <LibWebView/ImageDecoderManager.h>#include <LibWebView/PermissionManager.h>#include <LibWebView/WebWorkerClient.h>#include <LibWebView/WorkerProcessManager.h>@@ -192,6 +193,11 @@ Messages::WebWorkerClient::RequestMediaServerConnectionResponse WebWorkerClient:return move(connection.value().handle);}+Messages::WebWorkerClient::RequestImageDecoderConnectionResponse WebWorkerClient::request_image_decoder_connection()+{+ return ImageDecoderManager::the().connect_requesting_process(child_id(), m_is_private);+}+void WebWorkerClient::did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message){if (auto settings = hosted_environment(message.environment_id); settings.has_value())diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.hindex f21baadea9a..fa94d876fa9 100644--- a/Libraries/LibWebView/WebWorkerClient.h+++ b/Libraries/LibWebView/WebWorkerClient.h@@ -64,6 +64,7 @@ public:virtual Messages::WebWorkerClient::DidIsKnownHstsHostResponse did_is_known_hsts_host(String domain) override;virtual Messages::WebWorkerClient::DidRequestPermissionSnapshotResponse did_request_permission_snapshot(URL::Origin top_level_origin) override;virtual Messages::WebWorkerClient::RequestMediaServerConnectionResponse request_media_server_connection() override;+ virtual Messages::WebWorkerClient::RequestImageDecoderConnectionResponse request_image_decoder_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;diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex d51c1352347..02ba8725373 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -210,8 +210,6 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Oclient->request_server_site_bindings().bind_sites_of(web_worker_owner.client->request_server_site_bindings());});- auto image_decoder = TRY(launch_image_decoder_process());-// 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());@@ -222,7 +220,6 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Oclient->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());- connect_to_image_decoder(*client, move(image_decoder));if (auto compositor_handle = Application::the().connect_new_compositor_canvas_client(); !compositor_handle.is_error())client->async_connect_to_compositor(compositor_handle.release_value());diff --git a/Services/ImageDecoder/CMakeLists.txt b/Services/ImageDecoder/CMakeLists.txtindex efd379788fd..5fbb3723a0c 100644--- a/Services/ImageDecoder/CMakeLists.txt+++ b/Services/ImageDecoder/CMakeLists.txt@@ -4,6 +4,7 @@ set(CMAKE_AUTOUIC OFF)set(SOURCESConnectionFromClient.cpp+ ControlConnection.cpp)if (ANDROID)diff --git a/Services/ImageDecoder/ConnectionFromClient.cpp b/Services/ImageDecoder/ConnectionFromClient.cppindex 3d52c91468f..ccca99813f5 100644--- a/Services/ImageDecoder/ConnectionFromClient.cpp+++ b/Services/ImageDecoder/ConnectionFromClient.cpp@@ -23,6 +23,19 @@ static HashMap<int, RefPtr<ConnectionFromClient>> s_connections;static IDAllocator s_client_ids;static i64 s_next_session_id { 1 };+static auto s_is_held_open_by_browser = ConnectionFromClient::IsHeldOpenByBrowser::No;++static void exit_if_no_longer_needed()+{+ if (s_connections.is_empty() && s_is_held_open_by_browser == ConnectionFromClient::IsHeldOpenByBrowser::No)+ Core::Process::terminate_immediately(0);+}++void ConnectionFromClient::set_is_held_open_by_browser(IsHeldOpenByBrowser is_held_open)+{+ s_is_held_open_by_browser = is_held_open;+ exit_if_no_longer_needed();+}ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, RefPtr<ClientGroup> group): IPC::ConnectionFromClient<ImageDecoderClientEndpoint, ImageDecoderServerEndpoint>(*this, move(transport), s_client_ids.allocate())@@ -50,9 +63,7 @@ void ConnectionFromClient::die()s_connections.remove(client_id);s_client_ids.deallocate(client_id);- if (s_connections.is_empty()) {- Core::Process::terminate_immediately(0);- }+ exit_if_no_longer_needed();}static void decode_image_to_bitmaps_and_durations_with_decoder(Gfx::ImageDecoder const& decoder, Optional<Gfx::IntSize> ideal_size, Vector<RefPtr<Gfx::Bitmap>>& bitmaps, Vector<u32>& durations)diff --git a/Services/ImageDecoder/ConnectionFromClient.h b/Services/ImageDecoder/ConnectionFromClient.hindex e64c830c47d..1ce59b002b4 100644--- a/Services/ImageDecoder/ConnectionFromClient.h+++ b/Services/ImageDecoder/ConnectionFromClient.h@@ -32,6 +32,13 @@ public:virtual void die() override;+ // The decoder exits once the Browser has let go of it and its last client is gone.+ enum class IsHeldOpenByBrowser : u8 {+ No,+ Yes,+ };+ static void set_is_held_open_by_browser(IsHeldOpenByBrowser);+struct DecodeResult {bool is_animated = false;u32 loop_count = 0;diff --git a/Services/ImageDecoder/ControlConnection.cpp b/Services/ImageDecoder/ControlConnection.cppnew file mode 100644index 00000000000..de358c9d6fd--- /dev/null+++ b/Services/ImageDecoder/ControlConnection.cpp@@ -0,0 +1,36 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <ImageDecoder/ConnectionFromClient.h>+#include <ImageDecoder/ControlConnection.h>++namespace ImageDecoder {++ControlConnection::ControlConnection(NonnullOwnPtr<IPC::Transport> transport)+ : IPC::ConnectionFromClient<ImageDecoderControlClientEndpoint, ImageDecoderControlEndpoint>(*this, move(transport), 0)+{+ ImageDecoder::ConnectionFromClient::set_is_held_open_by_browser(ImageDecoder::ConnectionFromClient::IsHeldOpenByBrowser::Yes);+}++ControlConnection::~ControlConnection() = default;++void ControlConnection::die()+{+ ImageDecoder::ConnectionFromClient::set_is_held_open_by_browser(ImageDecoder::ConnectionFromClient::IsHeldOpenByBrowser::No);+}++void ControlConnection::connect_new_client(IPC::TransportHandle handle)+{+ auto transport_or_error = handle.create_transport();+ if (transport_or_error.is_error()) {+ dbgln("ImageDecoder: Could not take up a client: {}", transport_or_error.error());+ return;+ }+ // NB: The new connection keeps itself alive until it dies.+ (void)ImageDecoder::ConnectionFromClient::construct(transport_or_error.release_value());+}++}diff --git a/Services/ImageDecoder/ControlConnection.h b/Services/ImageDecoder/ControlConnection.hnew file mode 100644index 00000000000..dc7a7a25346--- /dev/null+++ b/Services/ImageDecoder/ControlConnection.h@@ -0,0 +1,33 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <ImageDecoder/ImageDecoderControlClientEndpoint.h>+#include <ImageDecoder/ImageDecoderControlEndpoint.h>+#include <LibIPC/ConnectionFromClient.h>++namespace ImageDecoder {++// The control plane of the ImageDecoder, spoken only by the Browser over the initial socket. It connects the clients the+// decoder serves, and tells the decoder nothing of what they decode. Once the Browser closes it, the decoder exits with+// the last of its clients.+class ControlConnection final+ : public IPC::ConnectionFromClient<ImageDecoderControlClientEndpoint, ImageDecoderControlEndpoint> {+ C_OBJECT(ControlConnection);++public:+ virtual ~ControlConnection() override;++ virtual void die() override;++private:+ explicit ControlConnection(NonnullOwnPtr<IPC::Transport>);++ virtual void connect_new_client(IPC::TransportHandle) override;+};++}diff --git a/Services/ImageDecoder/ImageDecoderControl.ipc b/Services/ImageDecoder/ImageDecoderControl.ipcnew file mode 100644index 00000000000..337186864ba--- /dev/null+++ b/Services/ImageDecoder/ImageDecoderControl.ipc@@ -0,0 +1,7 @@+#include <LibIPC/TransportHandle.h>++endpoint ImageDecoderControl+{+ // Takes a new client, whose animation sessions are its own.+ connect_new_client(IPC::TransportHandle handle) =|+}diff --git a/Services/ImageDecoder/ImageDecoderControlClient.ipc b/Services/ImageDecoder/ImageDecoderControlClient.ipcnew file mode 100644index 00000000000..4ac37c949ea--- /dev/null+++ b/Services/ImageDecoder/ImageDecoderControlClient.ipc@@ -0,0 +1,3 @@+endpoint ImageDecoderControlClient+{+}diff --git a/Services/ImageDecoder/main.cpp b/Services/ImageDecoder/main.cppindex 598e1cd094e..eff8f746db8 100644--- a/Services/ImageDecoder/main.cpp+++ b/Services/ImageDecoder/main.cpp@@ -6,7 +6,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <ImageDecoder/ConnectionFromClient.h>+#include <ImageDecoder/ControlConnection.h>#include <ImageDecoder/Sandbox.h>#include <LibCore/ArgsParser.h>#include <LibCore/CrashHandler.h>@@ -56,7 +56,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)if (!disable_sandbox)TRY(ImageDecoder::apply_sandbox(mach_server_name));- auto client = TRY(IPC::take_over_accepted_client_from_system_server<ImageDecoder::ConnectionFromClient>(mach_server_name));+ auto client = TRY(IPC::take_over_accepted_client_from_system_server<ImageDecoder::ControlConnection>(mach_server_name));if (stats_log)stats_log->start_sampling();diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex b66ad932179..cc38f8b2e53 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -452,12 +452,6 @@ void ConnectionFromClient::connect_to_web_ui(Web::PageId page_id, IPC::Transport}}-void ConnectionFromClient::connect_to_image_decoder(IPC::TransportHandle handle)-{- if (on_image_decoder_connection)- on_image_decoder_connection(handle);-}-void ConnectionFromClient::connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle){auto transport = MUST(handle.create_transport());@@ -517,6 +511,14 @@ ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_webrtc_cliereturn response->take_handle()->create_transport();}+ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_image_decoder_transport()+{+ auto response = send_sync_but_allow_failure<Messages::WebContentClient::RequestImageDecoderConnection>();+ if (!response || !response->handle().has_value())+ return Error::from_string_literal("The Browser did not connect an image decoder");+ return response->take_handle()->create_transport();+}+TestConnection* ConnectionFromClient::test_connection(){if (m_test_connection)diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex 8b876e62556..22b6fed83b8 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -72,12 +72,12 @@ public:void did_destroy_compositor_context(Web::CompositorContextId);Function<void(IPC::TransportHandle const&, Optional<int> client_id, Optional<Utf16String> const& top_level_site)> on_request_server_connection;- Function<void(IPC::TransportHandle const&)> on_image_decoder_connection;// Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.ErrorOr<NonnullOwnPtr<IPC::Transport>> request_media_server_transport();ErrorOr<NonnullOwnPtr<IPC::Transport>> request_audio_server_transport();ErrorOr<NonnullOwnPtr<IPC::Transport>> request_webrtc_client_transport();+ ErrorOr<NonnullOwnPtr<IPC::Transport>> request_image_decoder_transport();// Null outside test mode: the UI process connects the test endpoint only when it runs tests.TestConnection* test_connection();@@ -116,7 +116,6 @@ private:virtual void connect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) override;virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) override;virtual void connect_to_test_endpoint(IPC::TransportHandle handle) override;- virtual void connect_to_image_decoder(IPC::TransportHandle handle) override;virtual void connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) override;virtual void set_site_compatibility_data(JsonValue data) override;virtual void set_permission_snapshot(Web::Permissions::PermissionSnapshot snapshot) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 13ad38485c1..3272f8a06f5 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -204,6 +204,7 @@ endpoint WebContentClient routed by Web::PageId page_idrequest_media_server_connection() => (Optional<IPC::TransportHandle> handle)request_audio_server_connection() => (Optional<IPC::TransportHandle> handle)request_webrtc_client_connection() => (Optional<IPC::TransportHandle> handle)+ request_image_decoder_connection() => (Optional<IPC::TransportHandle> handle)request_video_presentation_channel() =|[NotRouted] did_request_storage_usage(Web::PageId page_id, Web::HTML::EnvironmentId environment_id) => (u64 usage)diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex 268952c326e..e816309aecd 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -93,7 +93,6 @@ endpoint WebContentServer routed by Web::PageId page_idconnect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) =|connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) =|connect_to_test_endpoint(IPC::TransportHandle handle) =|- connect_to_image_decoder(IPC::TransportHandle handle) =|connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) =|compositor_process_reconnected() =|set_site_compatibility_data(JsonValue data) =|diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex ec212309a40..61702bf5635 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -159,7 +159,6 @@ static void install_crash_signal_handlers()#endifstatic 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<void> connect_to_image_decoder(IPC::TransportHandle const& handle);ErrorOr<int> ladybird_main(Main::Arguments arguments){@@ -300,10 +299,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)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());};- webcontent_client->on_image_decoder_connection = [](auto const& handle) {- if (auto result = connect_to_image_decoder(handle); result.is_error())- dbgln("Failed to connect to image decoder: {}", result.error());- };+ // Many processes 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([webcontent_client] -> ErrorOr<NonnullRefPtr<ImageDecoderClient::Client>> {+ return try_make_ref_counted<ImageDecoderClient::Client>(TRY(webcontent_client->request_image_decoder_transport()));+ }));MediaClient::Client::set_transport_factory([webcontent_client] {return webcontent_client->request_media_server_transport();@@ -340,14 +339,3 @@ ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle coWeb::ResourceLoader::the().set_client(top_level_site, move(request_client));return {};}--ErrorOr<void> connect_to_image_decoder(IPC::TransportHandle const& handle)-{- auto transport = TRY(handle.create_transport());- auto new_client = TRY(try_make_ref_counted<ImageDecoderClient::Client>(move(transport)));- if (Web::Platform::ImageCodecPlugin::is_initialized())- static_cast<Web::Platform::RemoteImageCodecPlugin&>(Web::Platform::ImageCodecPlugin::the()).set_client(move(new_client));- else- Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(move(new_client)));- return {};-}diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cppindex 15710bfa40c..01b4170fbae 100644--- a/Services/WebWorker/ConnectionFromClient.cpp+++ b/Services/WebWorker/ConnectionFromClient.cpp@@ -57,12 +57,6 @@ void ConnectionFromClient::simulate_request_server_connection_loss_and_reconnectconnect_to_request_server(move(replacement_handle), client_id, move(top_level_site));}-void ConnectionFromClient::connect_to_image_decoder(IPC::TransportHandle handle)-{- if (on_image_decoder_connection)- on_image_decoder_connection(handle);-}-ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_media_server_transport(){auto response = send_sync_but_allow_failure<Messages::WebWorkerClient::RequestMediaServerConnection>();@@ -71,6 +65,14 @@ ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_media_servereturn response->take_handle()->create_transport();}+ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_image_decoder_transport()+{+ auto response = send_sync_but_allow_failure<Messages::WebWorkerClient::RequestImageDecoderConnection>();+ if (!response || !response->handle().has_value())+ return Error::from_string_literal("The Browser did not connect an image decoder");+ return response->take_handle()->create_transport();+}+void ConnectionFromClient::connect_to_compositor(IPC::TransportHandle handle){auto transport = MUST(handle.create_transport());diff --git a/Services/WebWorker/ConnectionFromClient.h b/Services/WebWorker/ConnectionFromClient.hindex 2eb9df814fc..7b30f5feb94 100644--- a/Services/WebWorker/ConnectionFromClient.h+++ b/Services/WebWorker/ConnectionFromClient.h@@ -45,10 +45,11 @@ 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;- Function<void(IPC::TransportHandle const&)> on_image_decoder_connection;// Asks the Browser to spawn this process'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.+ ErrorOr<NonnullOwnPtr<IPC::Transport>> request_image_decoder_transport();private:ConnectionFromClient(NonnullOwnPtr<IPC::Transport>, bool enable_test_mode);@@ -58,7 +59,6 @@ private:virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) override;virtual void simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id, Optional<Utf16String> top_level_site) override;- virtual void connect_to_image_decoder(IPC::TransportHandle handle) override;virtual void connect_to_compositor(IPC::TransportHandle handle) override;virtual void set_site_compatibility_data(JsonValue data) override;virtual void set_permission_snapshot(Web::Permissions::PermissionSnapshot snapshot) override;diff --git a/Services/WebWorker/WebWorkerClient.ipc b/Services/WebWorker/WebWorkerClient.ipcindex b1662cd0022..57b9e09dcd9 100644--- a/Services/WebWorker/WebWorkerClient.ipc+++ b/Services/WebWorker/WebWorkerClient.ipc@@ -24,6 +24,7 @@ endpoint WebWorkerClient {did_is_known_hsts_host(String domain) => (bool result)did_request_permission_snapshot(URL::Origin top_level_origin) => (Web::Permissions::PermissionSnapshot snapshot)request_media_server_connection() => (Optional<IPC::TransportHandle> handle)+ request_image_decoder_connection() => (Optional<IPC::TransportHandle> handle)did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) =|start_worker_agent(Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id)close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|diff --git a/Services/WebWorker/WebWorkerServer.ipc b/Services/WebWorker/WebWorkerServer.ipcindex 28ee0610f99..8aa3d9a83a2 100644--- a/Services/WebWorker/WebWorkerServer.ipc+++ b/Services/WebWorker/WebWorkerServer.ipc@@ -16,7 +16,6 @@ endpoint WebWorkerServer {connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) =|simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id, Optional<Utf16String> top_level_site) => ()- connect_to_image_decoder(IPC::TransportHandle handle) =|connect_to_compositor(IPC::TransportHandle handle) =|set_site_compatibility_data(JsonValue data) =|set_permission_snapshot(Web::Permissions::PermissionSnapshot snapshot) =|diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cppindex c1b4bb631bf..70b7c23b721 100644--- a/Services/WebWorker/main.cpp+++ b/Services/WebWorker/main.cpp@@ -37,7 +37,6 @@#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<void> connect_to_image_decoder(IPC::TransportHandle const& handle);static ErrorOr<Web::HTML::AgentType> agent_type_from_string(StringView type){@@ -144,10 +143,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)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());};- client->on_image_decoder_connection = [](auto const& handle) {- if (auto result = connect_to_image_decoder(handle); result.is_error())- dbgln("Failed to connect to image decoder: {}", 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()));+ }));MediaClient::Client::set_transport_factory([client] {return client->request_media_server_transport();@@ -171,14 +170,3 @@ static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHaWeb::ResourceLoader::the().set_client(top_level_site, move(request_client));return {};}--static ErrorOr<void> connect_to_image_decoder(IPC::TransportHandle const& handle)-{- auto transport = TRY(handle.create_transport());- auto new_client = TRY(try_make_ref_counted<ImageDecoderClient::Client>(move(transport)));- if (Web::Platform::ImageCodecPlugin::is_initialized())- static_cast<Web::Platform::RemoteImageCodecPlugin&>(Web::Platform::ImageCodecPlugin::the()).set_client(move(new_client));- else- Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(move(new_client)));- return {};-}diff --git a/Tests/LibImageDecoderClient/TestImageDecoderClient.cpp b/Tests/LibImageDecoderClient/TestImageDecoderClient.cppindex e732f227993..c21834fff8b 100644--- a/Tests/LibImageDecoderClient/TestImageDecoderClient.cpp+++ b/Tests/LibImageDecoderClient/TestImageDecoderClient.cpp@@ -57,3 +57,25 @@ TEST_CASE(a_reply_without_a_duration_for_every_bitmap_is_refused)EXPECT(!reply_is_accepted(bitmaps(1), { 10, 20 }, 0));EXPECT(!reply_is_accepted(bitmaps(3), { 10, 20 }, 1));}++TEST_CASE(a_dying_client_is_let_go_of_before_its_decodes_are_rejected)+{+ Core::EventLoop event_loop;+ auto paired = MUST(IPC::Transport::create_paired());+ RefPtr<ImageDecoderClient::Client> client = adopt_ref(*new ImageDecoderClient::Client(move(paired.local)));++ bool decode_was_rejected = false;+ client->on_death = [&] { client = nullptr; };++ Array<u8, 4> encoded_data {};+ (void)client->decode_image(+ encoded_data.span(),+ [](ImageDecoderClient::DecodedImage&) -> ErrorOr<void> { return {}; },+ [&](Error&) {+ EXPECT(!client);+ decode_was_rejected = true;+ });++ client->shutdown();+ EXPECT(decode_was_rejected);+}diff --git a/Tests/LibWebView/TestImageDecoderIsolation.cpp b/Tests/LibWebView/TestImageDecoderIsolation.cppindex 650050012e7..9add533d930 100644--- a/Tests/LibWebView/TestImageDecoderIsolation.cpp+++ b/Tests/LibWebView/TestImageDecoderIsolation.cpp@@ -47,8 +47,11 @@ HashTable<pid_t> processes_of_type(WebView::ProcessType type)}-// An ImageDecoder parses untrusted images, so each renderer has one of its own, and never sees another's images. A-// decoder that crashes is replaced for its renderer alone.+static constexpr auto page_with_image = "<!DOCTYPE html><img src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\">"sv;++// An ImageDecoder parses untrusted images, so it is launched only for a process that has some to decode. Each such process+// has one of its own, and never sees another's images. A decoder that crashes is replaced for its renderer alone, once the+// renderer next has an image to decode.TEST_CASE(image_decoder_isolation){@@ -62,26 +65,43 @@ TEST_CASE(image_decoder_isolation)auto first_view = WebView::HeadlessWebView::create(theme, { 800, 600 });auto second_view = WebView::HeadlessWebView::create(theme, { 800, 600 });- auto renderers = processes_of_type(WebView::ProcessType::WebContent);+ size_t first_view_loads = 0;+ size_t second_view_loads = 0;+ first_view->on_load_finish = [&](auto const&) { ++first_view_loads; };+ second_view->on_load_finish = [&](auto const&) { ++second_view_loads; };+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 1 && second_view_loads >= 1; });++ // Nothing has had an image to decode yet.+ VERIFY(processes_of_type(WebView::ProcessType::ImageDecoder).is_empty());++ // The load event waits for the image, so its decoder has been launched by the time the load finishes.+ first_view->load_html(page_with_image);+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 2; });+ VERIFY(processes_of_type(WebView::ProcessType::ImageDecoder).size() == 1);++ second_view->load_html(page_with_image);+ Core::EventLoop::current().spin_until([&] { return second_view_loads >= 2; });auto decoders = processes_of_type(WebView::ProcessType::ImageDecoder);- VERIFY(renderers.size() >= 2);- VERIFY(decoders.size() == renderers.size());+ VERIFY(decoders.size() == 2);auto crashed_decoder = *decoders.begin();TRY_OR_FAIL(Core::System::kill(crashed_decoder, SIGKILL));-- // The replacement is launched as the Browser learns that the decoder died, so this cannot finish without it.Core::EventLoop::current().spin_until([&] {return !processes_of_type(WebView::ProcessType::ImageDecoder).contains(crashed_decoder);});- // A spare renderer may have been launched meanwhile, with a decoder of its own.+ // Both renderers decode again, and only the one that lost its decoder gets a new one.+ first_view->load_html(page_with_image);+ second_view->load_html(page_with_image);+ Core::EventLoop::current().spin_until([&] { return first_view_loads >= 3 && second_view_loads >= 3; });+auto decoders_after_crash = processes_of_type(WebView::ProcessType::ImageDecoder);- VERIFY(decoders_after_crash.size() == processes_of_type(WebView::ProcessType::WebContent).size());+ VERIFY(decoders_after_crash.size() == 2);+ VERIFY(!decoders_after_crash.contains(crashed_decoder));for (auto decoder : decoders) {if (decoder != crashed_decoder)VERIFY(decoders_after_crash.contains(decoder));}- outln("PASS: each renderer has an image decoder of its own, which is replaced alone when it crashes");+ outln("PASS: each renderer gets an image decoder of its own when it needs one, which is replaced alone when it crashes");}diff --git a/Tests/LibWebView/test-webdriver-crash-report.py b/Tests/LibWebView/test-webdriver-crash-report.pyindex 664c487b334..823ce9fbe00 100755--- a/Tests/LibWebView/test-webdriver-crash-report.py+++ b/Tests/LibWebView/test-webdriver-crash-report.py@@ -106,6 +106,24 @@ def run_test(webdriver_binary, process_name):},)assert status == 200 and payload == {"value": None}, body+ elif process_name == "ImageDecoder":+ # A process gets its decoder when it first has an image to decode.+ status, payload, body = webdriver_helpers.request(+ port,+ "POST",+ f"/session/{session}/execute/async",+ {+ "script": """+ const done = arguments[0];+ window.image = new Image();+ image.onload = () => done();+ image.onerror = () => done('image failed');+ image.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';+ """,+ "args": [],+ },+ )+ assert status == 200 and payload == {"value": None}, bodyelif process_name == "Compositor":wait_for_compositor(port, session)crash_helper(webdriver.pid, process_name)diff --git a/UI/Android/src/main/cpp/WebContentService.cpp b/UI/Android/src/main/cpp/WebContentService.cppindex ae6d2bf8130..732dcdc67d6 100644--- a/UI/Android/src/main/cpp/WebContentService.cpp+++ b/UI/Android/src/main/cpp/WebContentService.cpp@@ -44,8 +44,7 @@ ErrorOr<int> service_main(int ipc_socket)Web::Platform::EventLoopPlugin::install(*new Web::Platform::EventLoopPlugin);- auto image_decoder_client = TRY(bind_image_decoder_service());- Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(move(image_decoder_client)));+ Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(bind_image_decoder_service));Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);