Skip to content

Truly independent web browser

LibWeb: Ignore stale SVG image request completions

Andreas Kling1982e62b612a
diff --git a/Libraries/LibWeb/SVG/SVGImageElement.cpp b/Libraries/LibWeb/SVG/SVGImageElement.cpp
index a5c4696afe7..15f144dd0a5 100644
--- a/Libraries/LibWeb/SVG/SVGImageElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGImageElement.cpp
@@ -90,25 +90,55 @@ void SVGImageElement::process_the_url(Optional<Utf16String> const& href)
{
if (!href.has_value()) {
m_href = {};
+ abandon_the_current_fetch();
return;
}
m_href = document().encoding_parse_url(*href);
- if (!m_href.has_value())
+ if (!m_href.has_value()) {
+ abandon_the_current_fetch();
return;
+ }
fetch_the_document(*m_href);
}
+void SVGImageElement::abandon_the_current_fetch()
+{
+ // AD-HOC: Without a URL to fetch, the element has no image request. An earlier request that is still loading must
+ // not fire events or keep delaying the load event, and an image that has already loaded is no longer the
+ // element's image.
+ ++m_current_fetch_id;
+ m_load_event_delayer.clear();
+ if (!m_resource_request)
+ return;
+ unregister_with_decoded_image_data_if_needed();
+ m_resource_request = nullptr;
+ CSS::record_element_replaced_content_input(*this);
+ Painting::push_replaced_image_paint_facts(*this, *this);
+ set_needs_layout_update(DOM::SetNeedsLayoutReason::SVGImageElementFetchTheDocument);
+}
+
// https://svgwg.org/svg2-draft/linking.html#processingURL-fetch
void SVGImageElement::fetch_the_document(URL::URL const& url)
{
+ // NB: Replacing the delayer releases the one held for the previous request, so the document only waits for the
+ // current request.
m_load_event_delayer.emplace(document());
unregister_with_decoded_image_data_if_needed();
- m_resource_request = HTML::SharedResourceRequest::get_or_create(document(), url);
+ auto resource_request = HTML::SharedResourceRequest::get_or_create(document(), url);
+ m_resource_request = resource_request;
+ auto fetch_id = ++m_current_fetch_id;
CSS::record_element_replaced_content_input(*this);
- m_resource_request->add_callbacks(
- [this, resource_request = GC::Root { m_resource_request }] {
+
+ // AD-HOC: A request that finishes after href has changed is no longer the element's image request. Its completion
+ // must not fire events or release the load event delayer of the current request. Shared resource requests
+ // are shared per URL, so each fetch gets its own ID instead of comparing requests.
+ resource_request->add_callbacks(
+ [this, fetch_id] {
+ if (fetch_id != m_current_fetch_id)
+ return;
+
m_load_event_delayer.clear();
register_with_decoded_image_data_if_needed();
CSS::record_element_replaced_content_input(*this);
@@ -119,27 +149,36 @@ void SVGImageElement::fetch_the_document(URL::URL const& url)
// When an Element element's associated image request has become completely available, run the algorithm
// to process an image that finished loading passing in element and its associated image request as
// inputs.
- // NB: A request that finishes after href has changed is no longer the element's image request.
- if (m_resource_request.ptr() == resource_request.ptr())
- PaintTiming::process_an_image_that_finished_loading(*this, PaintTiming::image_request_info(Utf16String::from_utf8(resource_request->url().serialize()), resource_request->image_data()));
+ PaintTiming::process_an_image_that_finished_loading(*this, PaintTiming::image_request_info(Utf16String::from_utf8(m_resource_request->url().serialize()), m_resource_request->image_data()));
dispatch_event(DOM::Event::create(HTML::EventNames::load,
HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));
},
- [this] {
+ [this, fetch_id] {
+ if (fetch_id != m_current_fetch_id)
+ return;
+
m_load_event_delayer.clear();
dispatch_event(DOM::Event::create(HTML::EventNames::error,
HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));
},
- [this] {
+ [this, fetch_id] {
+ if (fetch_id != m_current_fetch_id)
+ return;
+
m_load_event_delayer.clear();
});
- if (m_resource_request->needs_fetching()) {
+ // NB: A request that has already completed runs its callbacks right away, and an event handler can change href.
+ // Then this fetch is no longer the current one.
+ if (fetch_id != m_current_fetch_id)
+ return;
+
+ if (resource_request->needs_fetching()) {
auto request = HTML::create_potential_CORS_request(url, Fetch::Infrastructure::Request::Destination::Image, HTML::CORSSettingAttribute::NoCORS);
request->set_client(&document().relevant_settings_object());
- m_resource_request->fetch_resource(request);
+ resource_request->fetch_resource(request);
}
}
diff --git a/Libraries/LibWeb/SVG/SVGImageElement.h b/Libraries/LibWeb/SVG/SVGImageElement.h
index 7d457c1f0b0..ca29e235f01 100644
--- a/Libraries/LibWeb/SVG/SVGImageElement.h
+++ b/Libraries/LibWeb/SVG/SVGImageElement.h
@@ -56,6 +56,7 @@ protected:
void process_the_url(Optional<Utf16String> const& href);
void fetch_the_document(URL::URL const& url);
+ void abandon_the_current_fetch();
private:
virtual void finalize() override;
@@ -69,6 +70,7 @@ private:
GC::Ptr<HTML::SharedResourceRequest> m_resource_request;
Optional<DOM::DocumentLoadEventDelayer> m_load_event_delayer;
+ u64 m_current_fetch_id { 0 };
GC::Ptr<SVGAnimatedPreserveAspectRatio> m_preserve_aspect_ratio;
};
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-image-href-changed-while-loading.txt b/Tests/LibWeb/Text/expected/SVG/svg-image-href-changed-while-loading.txt
new file mode 100644
index 00000000000..a2de79af769
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-image-href-changed-while-loading.txt
@@ -0,0 +1,28 @@
+stale-load:
+ image load, width: 20
+ window load, width: 20
+stale-error:
+ image load, width: 20
+ window load, width: 20
+removed-while-loading:
+ witness load, width: 0
+ window load, width: 0
+unparsable-while-loading:
+ witness load, width: 0
+ window load, width: 0
+removed-after-load:
+ image load, width: 10
+ window load, width: 10
+ href changed, width: 0
+unparsable-after-load:
+ image load, width: 10
+ window load, width: 10
+ href changed, width: 0
+removed-by-load-handler:
+ witness load, width: 0
+ image load, width: 10
+ href set, width: 0
+removed-by-error-handler:
+ witness error, width: 0
+ image error, width: 0
+ href set, width: 0
diff --git a/Tests/LibWeb/Text/input/SVG/svg-image-href-changed-while-loading.html b/Tests/LibWeb/Text/input/SVG/svg-image-href-changed-while-loading.html
new file mode 100644
index 00000000000..f007d0b768b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-image-href-changed-while-loading.html
@@ -0,0 +1,136 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const echo = (path, status, size, delay) => server.createEcho("GET", path, {
+ status,
+ headers: { "Content-Type": "image/svg+xml", "Cache-Control": "no-store" },
+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}"><rect width="100%" height="100%" fill="green"/></svg>`,
+ delay_ms: delay,
+ });
+
+ // The first request finishes after href has changed, long before the second one. Only the second request
+ // is the element's image request, so only its completion fires an event on the element. The rendered width
+ // shows which image the element has: 0 for none, 20 for the second one.
+ async function run(name, firstStatus) {
+ const firstURL = await echo(`/svg-image-href-changed-while-loading-${name}-first.svg`, firstStatus, 10, 100);
+ const secondURL = await echo(`/svg-image-href-changed-while-loading-${name}-second.svg`, 200, 20, 1000);
+
+ const iframe = document.createElement("iframe");
+ const finished = new Promise(resolve => {
+ window.addEventListener("message", function listener(event) {
+ if (event.source !== iframe.contentWindow)
+ return;
+ window.removeEventListener("message", listener);
+ resolve(event.data);
+ });
+ });
+ iframe.srcdoc = `<!DOCTYPE html>
+<svg width="100" height="100"><image id="target"></image></svg>
+<script>
+ const log = [];
+ const target = document.getElementById("target");
+ const width = () => target.getBoundingClientRect().width;
+ for (const type of ["load", "error"])
+ target.addEventListener(type, () => log.push(\`image \${type}, width: \${width()}\`));
+ window.addEventListener("load", () => {
+ log.push(\`window load, width: \${width()}\`);
+ parent.postMessage(log, "*");
+ });
+ target.setAttribute("href", "${firstURL}");
+ target.setAttribute("href", "${secondURL}");
+<\/script>`;
+ document.body.appendChild(iframe);
+ const log = await finished;
+ iframe.remove();
+
+ println(`${name}:`);
+ for (const line of log)
+ println(` ${line}`);
+ }
+
+ async function runInIframe(name, body) {
+ const iframe = document.createElement("iframe");
+ const finished = new Promise(resolve => {
+ window.addEventListener("message", function listener(event) {
+ if (event.source !== iframe.contentWindow)
+ return;
+ window.removeEventListener("message", listener);
+ resolve(event.data);
+ });
+ });
+ iframe.srcdoc = `<!DOCTYPE html>
+<svg width="100" height="100"><image id="target"></image><image id="witness"></image></svg>
+<script>
+ const log = [];
+ const target = document.getElementById("target");
+ const witness = document.getElementById("witness");
+ const width = () => target.getBoundingClientRect().width;
+ for (const type of ["load", "error"]) {
+ target.addEventListener(type, () => log.push(\`image \${type}, width: \${width()}\`));
+ witness.addEventListener(type, () => log.push(\`witness \${type}, width: \${width()}\`));
+ }
+ ${body}
+<\/script>`;
+ document.body.appendChild(iframe);
+ const log = await finished;
+ iframe.remove();
+
+ println(`${name}:`);
+ for (const line of log)
+ println(` ${line}`);
+ }
+
+ // When href is removed or does not parse while a request is loading, that request is no longer the element's
+ // image request. The witness shares the request, and its callbacks run after the target's, so its load event
+ // shows that the request has finished.
+ async function runWhileLoading(name, changeHref) {
+ const url = await echo(`/svg-image-href-changed-while-loading-${name}.svg`, 200, 10, 100);
+ await runInIframe(name, `
+ window.addEventListener("load", () => {
+ log.push(\`window load, width: \${width()}\`);
+ parent.postMessage(log, "*");
+ });
+ target.setAttribute("href", "${url}");
+ ${changeHref}
+ witness.setAttribute("href", "${url}");`);
+ }
+
+ // When href is removed or does not parse after the image has loaded, the element no longer has an image.
+ async function runAfterLoad(name, changeHref) {
+ const url = await echo(`/svg-image-href-changed-while-loading-${name}.svg`, 200, 10, 0);
+ await runInIframe(name, `
+ window.addEventListener("load", () => {
+ log.push(\`window load, width: \${width()}\`);
+ ${changeHref}
+ log.push(\`href changed, width: \${width()}\`);
+ parent.postMessage(log, "*");
+ });
+ target.setAttribute("href", "${url}");`);
+ }
+
+ // When the shared request has already finished, the element's request completes as soon as href is set. A
+ // handler that removes href at that point drops the request that is being set up.
+ async function runRemovedByHandler(name, status, type) {
+ const url = await echo(`/svg-image-href-changed-while-loading-${name}.svg`, status, 10, 0);
+ await runInIframe(name, `
+ witness.addEventListener("${type}", () => {
+ target.addEventListener("${type}", () => target.removeAttribute("href"));
+ target.setAttribute("href", "${url}");
+ log.push(\`href set, width: \${width()}\`);
+ parent.postMessage(log, "*");
+ });
+ witness.setAttribute("href", "${url}");`);
+ }
+
+ await run("stale-load", 200);
+ await run("stale-error", 404);
+ await runWhileLoading("removed-while-loading", `target.removeAttribute("href");`);
+ await runWhileLoading("unparsable-while-loading", `target.setAttribute("href", "http://[");`);
+ await runAfterLoad("removed-after-load", `target.removeAttribute("href");`);
+ await runAfterLoad("unparsable-after-load", `target.setAttribute("href", "http://[");`);
+ await runRemovedByHandler("removed-by-load-handler", 200, "load");
+ await runRemovedByHandler("removed-by-error-handler", 404, "error");
+ });
+</script>