Skip to content

Truly independent web browser

LibWeb+LibWebView+Services: Let go of idle ImageDecoders

Andreas Kling868601a78898
diff --git a/Documentation/ProcessArchitecture.md b/Documentation/ProcessArchitecture.md
index 04f8891418a..208044cebca 100644
--- a/Documentation/ProcessArchitecture.md
+++ b/Documentation/ProcessArchitecture.md
@@ -76,7 +76,7 @@ This process decodes images (PNG, JPEG, BMP, ICO, PBM, etc.) into bitmaps. It is
A decoder sees the images of every process it serves, so a malicious image that takes one over gets at those images. With site isolation, the processes of a site share an **ImageDecoder**, because they hold nothing of any other site's that they could not fetch for themselves. The site is that of the documents a process hosts, not their top-level site, so a frame never shares a decoder with the site embedding it, unless it has an opaque origin, which keeps it in the process of the document that made it. Private browsing is kept apart. Any other process, such as one with no site, gets a decoder of its own, and a process that comes to host a second site leaves the decoder of the first.
-**Browser** launches a decoder when a process first has an image to decode, and ends it once the last process it serves is gone. A process that loses its decoder to a crash asks for a new one when it next has an image to decode.
+**Browser** launches a decoder when a process first has an image to decode, and ends it once each process it serves is gone or has let go of it. A process lets go of its decoder once it has gone 30 seconds with nothing to decode and no animation playing. Like a process that loses its decoder to a crash, it asks for a new one when it next has an image to decode.
### Processes: MediaServer, AudioServer and VideoDecoderServer
diff --git a/Libraries/LibImageDecoderClient/Client.cpp b/Libraries/LibImageDecoderClient/Client.cpp
index 5ff15f6215e..d0847ed6d90 100644
--- a/Libraries/LibImageDecoderClient/Client.cpp
+++ b/Libraries/LibImageDecoderClient/Client.cpp
@@ -88,18 +88,30 @@ void Client::did_decode_image(i64 request_id, bool is_animated, u32 loop_count,
Optional<NonnullRefPtr<Core::Promise<DecodedImage>>> maybe_promise = m_token_promises.take(request_id);
+ // NB: A decode that is turned down here leaves nobody to stop the animation it opened, so that is done right away.
+ auto stop_animation = [&] {
+ if (session_id != 0)
+ async_stop_animation_decode(session_id);
+ };
+
if (!maybe_promise.has_value()) {
dbgln("ImageDecoderClient: No pending image with request token {}", request_id);
+ stop_animation();
return;
}
auto promise = maybe_promise.release_value();
+ auto reject = [&](StringView message) {
+ stop_animation();
+ promise->reject(Error::from_string_view(message));
+ };
+
// The decoder parses untrusted data, so its replies are checked rather than trusted. Every frame has a duration,
// even in a streaming decode, which sends the durations of all frames but only the first batch of bitmaps.
auto has_durations_for_bitmaps = session_id != 0 ? durations.size() >= bitmaps.size() : durations.size() == bitmaps.size();
if (bitmaps.is_empty() || !has_durations_for_bitmaps) {
dbgln("ImageDecoderClient: Malformed reply for request {}", request_id);
- promise->reject(Error::from_string_literal("Malformed image decoder reply"));
+ reject("Malformed image decoder reply"sv);
return;
}
@@ -121,7 +133,7 @@ void Client::did_decode_image(i64 request_id, bool is_animated, u32 loop_count,
for (size_t i = 0; i < bitmaps.size(); ++i) {
if (!bitmaps[i]) {
dbgln("ImageDecoderClient: Invalid bitmap for request {} at index {}", request_id, i);
- promise->reject(Error::from_string_literal("Invalid bitmap"));
+ reject("Invalid bitmap"sv);
return;
}
@@ -129,6 +141,8 @@ void Client::did_decode_image(i64 request_id, bool is_animated, u32 loop_count,
image.frames.empend(bitmaps[i].release_nonnull(), duration);
}
+ if (session_id != 0)
+ m_animation_sessions.set(session_id);
promise->resolve(move(image));
}
@@ -180,6 +194,7 @@ void Client::request_animation_frames(i64 session_id, u32 start_frame_index, u32
void Client::stop_animation_decode(i64 session_id)
{
verify_event_loop();
+ m_animation_sessions.remove(session_id);
async_stop_animation_decode(session_id);
}
diff --git a/Libraries/LibImageDecoderClient/Client.h b/Libraries/LibImageDecoderClient/Client.h
index 4f391b9be77..c5bb8c64e16 100644
--- a/Libraries/LibImageDecoderClient/Client.h
+++ b/Libraries/LibImageDecoderClient/Client.h
@@ -7,6 +7,7 @@
#pragma once
#include <AK/HashMap.h>
+#include <AK/HashTable.h>
#include <ImageDecoder/ImageDecoderClientEndpoint.h>
#include <ImageDecoder/ImageDecoderServerEndpoint.h>
#include <LibCore/EventLoop.h>
@@ -52,6 +53,9 @@ public:
void request_animation_frames(i64 session_id, u32 start_frame_index, u32 count);
void stop_animation_decode(i64 session_id);
+ // Whether nothing depends on this connection: no decode waits on it, and no animation it opened is still playing.
+ bool is_idle() const { return m_token_promises.is_empty() && m_animation_sessions.is_empty(); }
+
Function<void()> on_death;
Function<void(i64 session_id, Vector<NonnullRefPtr<Gfx::Bitmap>>)> on_animation_frames_decoded;
Function<void(i64 session_id, String error_message)> on_animation_decode_failed;
@@ -69,6 +73,7 @@ private:
Core::EventLoop* m_creation_event_loop { &Core::EventLoop::current() };
i64 m_next_request_id { 0 };
HashMap<i64, NonnullRefPtr<Core::Promise<DecodedImage>>> m_token_promises;
+ HashTable<i64> m_animation_sessions;
};
}
diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp
index 0346c2f4cf9..0f50f78fca7 100644
--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp
+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.cpp
@@ -5,6 +5,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibCore/Timer.h>
#include <LibGfx/Bitmap.h>
#include <LibIPC/TransportHandle.h>
#include <LibImageDecoderClient/Client.h>
@@ -12,8 +13,14 @@
namespace Web::Platform {
-RemoteImageCodecPlugin::RemoteImageCodecPlugin(ConnectToImageDecoder connect_to_image_decoder)
+// NB: A decoder is a process of its own, with the memory it keeps, while connecting to a new one when the next image comes
+// along takes a few milliseconds. So a client that has had nothing to do for this long is let go of.
+static constexpr AK::Duration idle_time_before_releasing_image_decoder = AK::Duration::from_seconds(30);
+
+RemoteImageCodecPlugin::RemoteImageCodecPlugin(ConnectToImageDecoder connect_to_image_decoder, ReleaseImageDecoder release_image_decoder)
: m_connect_to_image_decoder(move(connect_to_image_decoder))
+ , m_release_image_decoder(move(release_image_decoder))
+ , m_idle_timer(Core::Timer::create_single_shot(idle_time_before_releasing_image_decoder, [this] { release_idle_client(); }))
{
}
@@ -34,10 +41,27 @@ ImageDecoderClient::Client* RemoteImageCodecPlugin::ensure_client()
m_client->on_death = [this] {
m_client = nullptr;
++m_client_generation;
+ m_idle_timer->stop();
};
return m_client;
}
+void RemoteImageCodecPlugin::client_may_have_become_idle()
+{
+ if (m_release_image_decoder && m_client && m_client->is_idle())
+ m_idle_timer->restart();
+}
+
+// NB: Only this process asks its client for anything, so a client that is idle here has nothing in flight, and letting
+// go of it loses nothing. The next image to decode connects a new one.
+void RemoteImageCodecPlugin::release_idle_client()
+{
+ if (!m_client || !m_client->is_idle())
+ return;
+ disconnect_client();
+ m_release_image_decoder();
+}
+
void RemoteImageCodecPlugin::disconnect_client()
{
if (auto client = m_client)
@@ -62,7 +86,7 @@ NonnullRefPtr<Core::Promise<DecodedImage>> RemoteImageCodecPlugin::decode_image(
auto image_decoder_promise = client->decode_image(
bytes,
- [promise](ImageDecoderClient::DecodedImage& result) -> ErrorOr<void> {
+ [this, promise](ImageDecoderClient::DecodedImage& result) -> ErrorOr<void> {
// FIXME: Remove this codec plugin and just use the ImageDecoderClient directly to avoid these copies
DecodedImage decoded_image;
decoded_image.is_animated = result.is_animated;
@@ -75,10 +99,12 @@ NonnullRefPtr<Core::Promise<DecodedImage>> RemoteImageCodecPlugin::decode_image(
}
decoded_image.color_space = move(result.color_space);
promise->resolve(move(decoded_image));
+ client_may_have_become_idle();
return {};
},
- [promise](auto& error) {
+ [this, promise](auto& error) {
promise->reject(Error::copy(error));
+ client_may_have_become_idle();
});
return promise;
@@ -89,20 +115,28 @@ ErrorOr<DecodedFirstFrame> RemoteImageCodecPlugin::decode_first_frame_synchronou
auto* client = ensure_client();
if (!client)
return Error::from_string_literal("ImageDecoderClient is disconnected");
- auto result = TRY(client->decode_first_frame_synchronously(bytes));
- return DecodedFirstFrame { move(result.bitmap), move(result.color_space) };
+ auto result = client->decode_first_frame_synchronously(bytes);
+ client_may_have_become_idle();
+ auto frame = TRY(move(result));
+ return DecodedFirstFrame { move(frame.bitmap), move(frame.color_space) };
}
void RemoteImageCodecPlugin::stop_animation_decode(i64 session_id)
{
- if (m_client)
- m_client->stop_animation_decode(session_id);
+ if (!m_client)
+ return;
+ m_client->stop_animation_decode(session_id);
+ client_may_have_become_idle();
}
void RemoteImageCodecPlugin::connect_frame_client(IPC::TransportHandle handle)
{
- if (auto* client = ensure_client())
- client->async_connect_frame_client(handle);
+ auto* client = ensure_client();
+ if (!client)
+ return;
+ client->async_connect_frame_client(handle);
+ // NB: This may have connected a client that has nothing to do, which must be let go of like any other.
+ client_may_have_become_idle();
}
}
diff --git a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h
index 279c377057b..015f6476546 100644
--- a/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h
+++ b/Libraries/LibWeb/Platform/RemoteImageCodecPlugin.h
@@ -20,8 +20,11 @@ public:
// 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>>()>;
+ // Called after a client that had nothing left to do was let go of, so that its decoder can end. Without it, a client
+ // is kept for as long as its decoder is around.
+ using ReleaseImageDecoder = Function<void()>;
- explicit RemoteImageCodecPlugin(ConnectToImageDecoder);
+ explicit RemoteImageCodecPlugin(ConnectToImageDecoder, ReleaseImageDecoder = {});
virtual ~RemoteImageCodecPlugin() override;
virtual NonnullRefPtr<Core::Promise<DecodedImage>> decode_image(ReadonlyBytes, Function<ErrorOr<void>(DecodedImage&)> on_resolved, Function<void(Error&)> on_rejected) override;
@@ -37,8 +40,12 @@ public:
private:
ImageDecoderClient::Client* ensure_client();
+ void client_may_have_become_idle();
+ void release_idle_client();
ConnectToImageDecoder m_connect_to_image_decoder;
+ ReleaseImageDecoder m_release_image_decoder;
+ NonnullRefPtr<Core::Timer> m_idle_timer;
RefPtr<ImageDecoderClient::Client> m_client;
u64 m_client_generation { 0 };
};
diff --git a/Libraries/LibWebView/ImageDecoderManager.cpp b/Libraries/LibWebView/ImageDecoderManager.cpp
index 7a0a1ce3590..293aefce830 100644
--- a/Libraries/LibWebView/ImageDecoderManager.cpp
+++ b/Libraries/LibWebView/ImageDecoderManager.cpp
@@ -72,6 +72,13 @@ bool ImageDecoderManager::remove_client_from_decoder_of_site(u64 client_child_id
return was_removed;
}
+void ImageDecoderManager::process_did_release_decoder(u64 client_child_id)
+{
+ m_instances.remove_all_matching([&](auto& instance) {
+ return instance.client_child_ids.remove(client_child_id) && instance.client_child_ids.is_empty();
+ });
+}
+
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
diff --git a/Libraries/LibWebView/ImageDecoderManager.h b/Libraries/LibWebView/ImageDecoderManager.h
index 81e79c45c24..4d23a15866d 100644
--- a/Libraries/LibWebView/ImageDecoderManager.h
+++ b/Libraries/LibWebView/ImageDecoderManager.h
@@ -19,7 +19,8 @@
namespace WebView {
-// Launches ImageDecoders as processes first ask for them, and ends each once the last process it serves is gone.
+// Launches ImageDecoders as processes first ask for them, and ends each once each process it serves is gone or has let go
+// of it.
//
// A decoder sees the images of every process it serves, so a malicious image that takes one over gets at those images. The
// processes of a site may share a decoder, because under site isolation they hold nothing of any other site's that they
@@ -48,6 +49,9 @@ public:
// Returns whether the process was served by the decoder of a site, and so has to disconnect from it.
bool remove_client_from_decoder_of_site(u64 client_child_id);
+ // Lets go of the decoder of a process that has disconnected from it, which ends once no other process uses it.
+ void process_did_release_decoder(u64 client_child_id);
+
void process_did_exit(u64 child_id);
private:
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index f6c89740a8a..04614ad5044 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -1175,6 +1175,11 @@ Messages::WebContentClient::RequestImageDecoderConnectionResponse WebContentClie
return ImageDecoderManager::the().connect_requesting_process(child_id(), m_session, m_site_of_hosted_documents);
}
+void WebContentClient::did_release_image_decoder()
+{
+ ImageDecoderManager::the().process_did_release_decoder(child_id());
+}
+
Optional<u64> WebContentClient::exclusive_performance_owner() const
{
Optional<u64> owner;
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index a4d0f1e7006..8bce058eb1f 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -233,6 +233,7 @@ private:
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 did_release_image_decoder() 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.cpp
index c4d593ddaaa..ae949f605b7 100644
--- a/Libraries/LibWebView/WebWorkerClient.cpp
+++ b/Libraries/LibWebView/WebWorkerClient.cpp
@@ -198,6 +198,11 @@ Messages::WebWorkerClient::RequestImageDecoderConnectionResponse WebWorkerClient
return ImageDecoderManager::the().connect_requesting_process(child_id(), session(), m_site);
}
+void WebWorkerClient::did_release_image_decoder()
+{
+ ImageDecoderManager::the().process_did_release_decoder(child_id());
+}
+
void WebWorkerClient::did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message)
{
if (auto settings = hosted_environment(message.environment_id); settings.has_value())
diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.h
index a2925608712..cf310e3cd31 100644
--- a/Libraries/LibWebView/WebWorkerClient.h
+++ b/Libraries/LibWebView/WebWorkerClient.h
@@ -68,6 +68,7 @@ public:
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_release_image_decoder() 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/Services/ImageDecoder/ConnectionFromClient.cpp b/Services/ImageDecoder/ConnectionFromClient.cpp
index ccca99813f5..21407564eda 100644
--- a/Services/ImageDecoder/ConnectionFromClient.cpp
+++ b/Services/ImageDecoder/ConnectionFromClient.cpp
@@ -24,10 +24,11 @@ static IDAllocator s_client_ids;
static i64 s_next_session_id { 1 };
static auto s_is_held_open_by_browser = ConnectionFromClient::IsHeldOpenByBrowser::No;
+static size_t s_client_count { 0 };
static void exit_if_no_longer_needed()
{
- if (s_connections.is_empty() && s_is_held_open_by_browser == ConnectionFromClient::IsHeldOpenByBrowser::No)
+ if (s_client_count == 0 && s_is_held_open_by_browser == ConnectionFromClient::IsHeldOpenByBrowser::No)
Core::Process::terminate_immediately(0);
}
@@ -39,10 +40,13 @@ void ConnectionFromClient::set_is_held_open_by_browser(IsHeldOpenByBrowser is_he
ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, RefPtr<ClientGroup> group)
: IPC::ConnectionFromClient<ImageDecoderClientEndpoint, ImageDecoderServerEndpoint>(*this, move(transport), s_client_ids.allocate())
+ , m_is_frame_client(group ? IsFrameClient::Yes : IsFrameClient::No)
, m_group(group ? group.release_nonnull() : make_ref_counted<ClientGroup>())
{
s_connections.set(client_id(), *this);
m_group->clients.set(this);
+ if (m_is_frame_client == IsFrameClient::No)
+ ++s_client_count;
}
void ConnectionFromClient::die()
@@ -63,6 +67,8 @@ void ConnectionFromClient::die()
s_connections.remove(client_id);
s_client_ids.deallocate(client_id);
+ if (m_is_frame_client == IsFrameClient::No)
+ --s_client_count;
exit_if_no_longer_needed();
}
diff --git a/Services/ImageDecoder/ConnectionFromClient.h b/Services/ImageDecoder/ConnectionFromClient.h
index 1ce59b002b4..6693665f1e3 100644
--- a/Services/ImageDecoder/ConnectionFromClient.h
+++ b/Services/ImageDecoder/ConnectionFromClient.h
@@ -32,7 +32,7 @@ public:
virtual void die() override;
- // The decoder exits once the Browser has let go of it and its last client is gone.
+ // The decoder exits once the Browser has let go of it and the last of the clients the Browser connected is gone.
enum class IsHeldOpenByBrowser : u8 {
No,
Yes,
@@ -90,6 +90,13 @@ private:
NonnullRefPtr<PendingJob> start_decode_image_job(i64 request_id, Core::AnonymousBuffer, Optional<Gfx::IntSize> ideal_size, Optional<ByteString> mime_type);
NonnullRefPtr<PendingJob> start_frame_decode_job(i64 session_id, NonnullRefPtr<AnimationSession>, u32 start_frame_index, u32 end_index);
+ // A frame client only plays the animations of the client that connected it, so it does not keep the decoder running.
+ enum class IsFrameClient : u8 {
+ No,
+ Yes,
+ };
+ IsFrameClient m_is_frame_client { IsFrameClient::No };
+
NonnullRefPtr<ClientGroup> m_group;
HashMap<i64, NonnullRefPtr<PendingJob>> m_pending_jobs;
HashMap<i64, NonnullRefPtr<PendingJob>> m_pending_frame_jobs;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 3272f8a06f5..8bb613374f9 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -205,6 +205,7 @@ endpoint WebContentClient routed by Web::PageId page_id
request_audio_server_connection() => (Optional<IPC::TransportHandle> handle)
request_webrtc_client_connection() => (Optional<IPC::TransportHandle> handle)
request_image_decoder_connection() => (Optional<IPC::TransportHandle> handle)
+ did_release_image_decoder() =|
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/main.cpp b/Services/WebContent/main.cpp
index 61702bf5635..3e49a5dc06b 100644
--- a/Services/WebContent/main.cpp
+++ b/Services/WebContent/main.cpp
@@ -300,9 +300,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
dbgln("Failed to connect to resource loader: {}", 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()));
- }));
+ 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()));
+ },
+ [webcontent_client] { webcontent_client->async_did_release_image_decoder(); }));
MediaClient::Client::set_transport_factory([webcontent_client] {
return webcontent_client->request_media_server_transport();
diff --git a/Services/WebWorker/WebWorkerClient.ipc b/Services/WebWorker/WebWorkerClient.ipc
index 57b9e09dcd9..1b141368477 100644
--- a/Services/WebWorker/WebWorkerClient.ipc
+++ b/Services/WebWorker/WebWorkerClient.ipc
@@ -25,6 +25,7 @@ endpoint WebWorkerClient {
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_release_image_decoder() =|
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/main.cpp b/Services/WebWorker/main.cpp
index 70b7c23b721..f364ae98721 100644
--- a/Services/WebWorker/main.cpp
+++ b/Services/WebWorker/main.cpp
@@ -144,9 +144,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
dbgln("Failed to connect to resource loader: {}", result.error());
};
// Many workers never decode an image, so the Browser connects this one to a decoder when it first has one to decode.
- Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin([client] -> ErrorOr<NonnullRefPtr<ImageDecoderClient::Client>> {
- return try_make_ref_counted<ImageDecoderClient::Client>(TRY(client->request_image_decoder_transport()));
- }));
+ Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(
+ [client] -> ErrorOr<NonnullRefPtr<ImageDecoderClient::Client>> {
+ return try_make_ref_counted<ImageDecoderClient::Client>(TRY(client->request_image_decoder_transport()));
+ },
+ [client] { client->async_did_release_image_decoder(); }));
MediaClient::Client::set_transport_factory([client] {
return client->request_media_server_transport();
diff --git a/Tests/LibWebView/TestImageDecoderIsolation.cpp b/Tests/LibWebView/TestImageDecoderIsolation.cpp
index cca9c92bcda..f0a1f61ece7 100644
--- a/Tests/LibWebView/TestImageDecoderIsolation.cpp
+++ b/Tests/LibWebView/TestImageDecoderIsolation.cpp
@@ -5,6 +5,7 @@
*/
#include "HeadlessTest.h"
+#include <AK/Base64.h>
#include <AK/HashTable.h>
#include <AK/LexicalPath.h>
#include <AK/Utf16String.h>
@@ -13,6 +14,7 @@
#include <LibCore/System.h>
#include <LibGfx/SystemTheme.h>
#include <LibIPC/TransportHandle.h>
+#include <LibImageDecoderClient/Client.h>
#include <LibTest/TestCase.h>
#include <LibURL/URL.h>
#include <LibWebCommon/WebView/SiteIsolation.h>
@@ -304,3 +306,46 @@ TEST_CASE(image_decoder_sharing_rules)
outln("PASS: image decoders are shared within a site and nowhere else, and end with the last process they serve");
}
+
+// A process lets go of its decoder once it has nothing left to decode, and the decoder ends once no process uses it.
+TEST_CASE(image_decoders_end_once_released)
+{
+ Test::HeadlessTestEnvironment environment { "TestImageDecodersEndOnceReleased"sv };
+
+ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());
+
+ auto& manager = WebView::ImageDecoderManager::the();
+ RefPtr<WebView::BrowsingSession> session = WebView::Application::session_for_new_view(WebView::IsPrivate::No);
+ auto site = "https://c.example"_utf16;
+ auto decoder_count = [] { return processes_of_type(WebView::ProcessType::ImageDecoder).size(); };
+
+ // The decoder of a site stays for as long as one of its processes uses it.
+ Optional<IPC::TransportHandle> first = MUST(manager.connect_new_client(2'000'001, session, site));
+ Optional<IPC::TransportHandle> second = MUST(manager.connect_new_client(2'000'002, session, site));
+ VERIFY(decoder_count() == 1);
+ first.clear();
+ manager.process_did_release_decoder(2'000'001);
+ VERIFY(decoder_count() == 1);
+ second.clear();
+ manager.process_did_release_decoder(2'000'002);
+ Core::EventLoop::current().spin_until([&] { return decoder_count() == 0; });
+
+ // A process that has let go of its decoder gets a new one when it next asks.
+ auto handle = MUST(manager.connect_new_client(2'000'003, session, {}));
+ VERIFY(decoder_count() == 1);
+
+ // The frame client of an animation only serves the client that connected it, so it does not keep the decoder.
+ auto client = make_ref_counted<ImageDecoderClient::Client>(MUST(handle.create_transport()));
+ auto frame_channel = MUST(IPC::TransportHandle::create_pair());
+ client->async_connect_frame_client(frame_channel.first);
+ auto frame_client = make_ref_counted<ImageDecoderClient::Client>(MUST(frame_channel.second.create_transport()));
+ // NB: The decoder handles a client's messages in order, so the frame client is connected once this returns.
+ auto image = MUST(decode_base64("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"sv));
+ MUST(client->decode_first_frame_synchronously(image));
+ client->shutdown();
+ manager.process_did_release_decoder(2'000'003);
+ Core::EventLoop::current().spin_until([&] { return decoder_count() == 0; });
+ frame_client->shutdown();
+
+ outln("PASS: image decoders end once the processes they serve let go of them");
+}