fix(runtime): preserve retained child Window globals

This commit is contained in:
ldm0
2026-11-02 06:02:21 +08:00
parent cde21f11d5
commit 4d69d760bf
8 changed files with 237 additions and 6 deletions
@@ -7994,9 +7994,11 @@ html/webappapis/dynamic-markup-insertion/opening-the-input-stream/016.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document-open-cancels-javascript-url-navigation.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-02.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-03.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/event-listeners.window.js?moli-wpt-script=window
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/form-control-state.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/location-set-and-document-open.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/origin-check-in-document-open-basic.html
html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url.window.js?moli-wpt-script=window
html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-documentfragment.html
html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-no-parent.html
html/webappapis/microtask-queuing/queue-microtask-cross-realm-callback-report-exception.html
+116
View File
@@ -0,0 +1,116 @@
(async () => {
const result = {checks: 0, failures: [], observations: []};
const check = (name, action, expected) => {
result.checks++;
try {
const actual = action();
if (JSON.stringify(actual) !== JSON.stringify(expected)) result.failures.push({name, actual, expected});
} catch (error) { result.failures.push({name, error: error.name, message: error.message}); }
};
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
const load = async (node, url) => {
const loaded = new Promise(resolve => node.onload = resolve);
node.src = url;
await loaded;
};
const frame = async (owner, url) => {
const node = owner.createElement('iframe');
const loaded = new Promise(resolve => node.onload = resolve);
if (url) node.src = url;
owner.body.append(node);
if (url) await loaded;
return node;
};
for (const mode of ['parent-navigation', 'parent-open', 'remove-loaded', 'remove-blank', 'remove-reinsert']) {
const parent = await frame(document, '/compat/child-dynamic-markup-document?markup=parent');
const child = await frame(parent.contentDocument, mode === 'remove-blank' ? null : '/compat/child-dynamic-markup-document?markup=child#retained');
const win = child.contentWindow, doc = child.contentDocument;
const url = doc.URL;
const eventConstructor = win.Event;
win.retainedMarker = {value: mode};
const marker = win.retainedMarker;
let existingCalls = 0, newCalls = 0;
const existing = () => existingCalls++;
win.addEventListener('retained-test', existing);
win.dispatchEvent(new Event('retained-test'));
check(mode + ':live-event', () => existingCalls, 1);
let liveTimerCalls = 0;
await new Promise(resolve => win.setTimeout(() => { liveTimerCalls++; resolve(); }, 0));
check(mode + ':live-timer', () => liveTimerCalls, 1);
if (mode === 'parent-navigation') await load(parent, '/compat/child-dynamic-markup-document?markup=replacement');
else if (mode === 'parent-open') { parent.contentDocument.open(); parent.contentDocument.close(); }
else {
child.remove();
if (mode === 'remove-reinsert') {
child.src = '/compat/child-dynamic-markup-document?markup=reinserted';
const loaded = new Promise(resolve => child.onload = resolve);
parent.contentDocument.body.append(child);
await loaded;
}
}
await tick();
let timerCalls = 0;
check(mode + ':retired-timer-registration', () => win.setTimeout(() => timerCalls++, 0), 0);
check(mode + ':retired-source-timer', () => win.setTimeout('globalThis.retiredTimerRan = true', 0), 0);
check(mode + ':retired-interval', () => win.setInterval(() => timerCalls++, 0), 0);
check(mode + ':retired-source-interval', () => win.setInterval('globalThis.retiredTimerRan = true', 0), 0);
await tick();
check(mode + ':retired-timer-inactive', () => timerCalls, 0);
check(mode + ':document', () => win.document === doc, true);
check(mode + ':location', () => win.location.href, url);
result.observations.push({mode, defaultViewIsNull: doc.defaultView === null});
check(mode + ':own-data', () => win.retainedMarker === marker, true);
check(mode + ':intrinsic', () => win.Event === eventConstructor, true);
check(mode + ':self', () => win.self === win, true);
check(mode + ':event-property', () => typeof win.addEventListener, 'function');
check(mode + ':old-event', () => { win.dispatchEvent(new Event('retained-test')); return existingCalls; }, 1);
check(mode + ':new-event', () => {
win.addEventListener('retained-test', () => newCalls++);
win.dispatchEvent(new Event('retained-test'));
return [existingCalls, newCalls];
}, [1, 0]);
check(mode + ':remove-event', () => {
win.removeEventListener('retained-test', existing);
win.dispatchEvent(new Event('retained-test'));
return [existingCalls, newCalls];
}, [1, 0]);
check(mode + ':open', () => doc.open() === doc, true);
check(mode + ':open-url', () => doc.URL, url);
check(mode + ':open-document', () => win.document === doc, true);
check(mode + ':open-keeps-events-retired', () => {
win.dispatchEvent(new Event('retained-test'));
return newCalls;
}, 0);
if (mode === 'remove-reinsert') {
check(mode + ':new-window', () => child.contentWindow !== win, true);
check(mode + ':new-document', () => child.contentWindow.document !== doc, true);
const replacement = child.contentWindow;
const timer = replacement.setTimeout(() => liveTimerCalls++, 0);
check(mode + ':retired-clear', () => {win.clearTimeout(timer); return true;}, true);
await tick();
check(mode + ':replacement-timer', () => liveTimerCalls, 2);
}
doc.close(); parent.remove();
}
const child = await frame(document, '/compat/child-dynamic-markup-document?markup=old');
const win = child.contentWindow, oldDoc = child.contentDocument;
const oldConstructor = win.Event;
win.oldMarker = 'old';
await load(child, '/compat/child-dynamic-markup-document?markup=new');
check('navigation:same-proxy', () => child.contentWindow === win, true);
check('navigation:new-document', () => win.document === child.contentDocument && win.document !== oldDoc, true);
check('navigation:new-intrinsic', () => win.Event !== oldConstructor, true);
check('navigation:old-data-gone', () => win.oldMarker, undefined);
const foreign = new URL('/compat/child-dynamic-markup-document?markup=foreign', location.href);
foreign.hostname = location.hostname === '127.0.0.1' ? 'localhost' : '127.0.0.1';
await load(child, foreign.href);
check('navigation:foreign-proxy', () => child.contentWindow === win, true);
check('navigation:foreign-denied', () => {
try { void win.document; return false; } catch (error) { return error.name === 'SecurityError'; }
}, true);
child.remove(); await tick();
check('navigation:removed-foreign-denied', () => {
try { void win.document; return false; } catch (error) { return ['SecurityError', 'TypeError'].includes(error.name); }
}, true);
return result;
})()
+3
View File
@@ -36,6 +36,9 @@ mod document_close;
#[path = "scripts/document_open_url.rs"]
mod document_open_url;
#[path = "scripts/retained_child_window.rs"]
mod retained_child_window;
#[path = "scripts/document_write_insertion.rs"]
mod document_write_insertion;
@@ -0,0 +1,28 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn retained_child_windows_remain_readable_after_browsing_context_destruction() -> Result<()> {
let server = FixtureServer::spawn().await?;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&server.url("/compat/child-dynamic-markup-document?markup=entry"))
.await?;
let script = include_str!("../fixtures/retained-child-window.js");
let result = tokio::time::timeout(
Duration::from_secs(10),
page.evaluate_runtime_expression_with_await_async(
&format!("({script}).then(JSON.stringify)"),
true,
),
)
.await??;
let observed: serde_json::Value = serde_json::from_str(
result["value"]
.as_str()
.expect("retained child Window observations"),
)?;
assert_eq!(observed["checks"], 111);
assert_eq!(observed["failures"], serde_json::json!([]), "{observed}");
server.shutdown().await;
Ok(())
}
+22 -5
View File
@@ -11,9 +11,9 @@ use crate::{
native_bridge::{
CALLBACK_ERROR_WINDOW_HANDLE_SLOT, OwnerDispatchScope, ResourceTimingBufferId,
RuntimeObservableContextToken, WindowExecutionContextBinding,
WindowExecutionContextIdentity, WindowExecutionContextOwner, active_child_window_handle,
active_lightweight_popup_id, current_runtime_observable_context_token,
lightweight_popup_id_from_window,
WindowExecutionContextIdentity, WindowExecutionContextOwner, WindowOperationReceiver,
active_child_window_handle, active_lightweight_popup_id,
current_runtime_observable_context_token, lightweight_popup_id_from_window,
},
page_task_queue::RendererPageTimerSelection,
script_provenance::CompiledStringProvenance,
@@ -991,8 +991,25 @@ fn scheduled_timer_owner_for_target<'s>(
let host_ptr = context_host_ptr_from_global_bridge(scope)?;
let host = unsafe { &mut *host_ptr };
let execution_context_owner = host.current_window_execution_context_owner(dispatch_scope)?;
let binding =
host.clone_window_execution_context_binding(scope, execution_context_owner, dispatch_scope);
let binding = match (owner, dispatch_scope, receiver) {
(HostTimerOwner::Window, OwnerDispatchScope::Child(_), Some(receiver))
if crate::web_api_interfaces::Window::is_instance(scope, receiver) =>
{
// A retained Window can share an iframe handle with a new browsing
// context after removal/reinsertion. Scheduling and cancellation
// must use that receiver's exact realm, never the replacement.
Some(
WindowOperationReceiver::capture_and_authorize(scope, receiver, host)
.ok()?
.resolve_live_binding(host)?,
)
}
_ => host.clone_window_execution_context_binding(
scope,
execution_context_owner,
dispatch_scope,
),
};
// Lightweight popups share the renderer isolate and install their context
// lazily. Capture the popup object's exact creation context before queueing.
@@ -2934,7 +2934,7 @@ fn detached_first_exposure_retires_prebootstrapped_child_realm() {
vm.prebootstrapped_child_default_contexts
.borrow()
.is_empty(),
"the owner source must detach and release an unclaimed realm for a removed LocalWindow"
"the owner source must release its unclaimed realm record for a removed LocalWindow"
);
assert_eq!(
vm._context_host
@@ -2372,6 +2372,7 @@ mod node_reflection_native_receivers;
mod document_attribute_factory_realms;
mod retained_child_window;
mod script_terminal_completion;
mod speech_events;
mod storage_dense_name_arrays;
@@ -0,0 +1,64 @@
use super::*;
#[test]
fn retained_child_window_survives_context_retirement() {
for materialized in [false, true] {
for reinserted in [false, true] {
let mut vm = new_storage_test_vm("https://retained-child-window.test/");
vm.eval(
r#"
document.appendChild(document.createElement('html'));
document.documentElement.appendChild(document.createElement('body'));
globalThis.frame = document.createElement('iframe');
document.body.append(frame);
globalThis.heldWindow = frame.contentWindow;
globalThis.heldDocument = heldWindow.document;
globalThis.heldEvent = heldWindow.Event;
heldWindow.marker = {retained: true};
globalThis.heldMarker = heldWindow.marker;
"#,
)
.unwrap();
assert_eq!(vm.prebootstrapped_child_default_contexts.borrow().len(), 1);
if materialized {
materialize_single_child_default_realm_for_test(&mut vm, "retained Window");
assert_eq!(vm.child_frame_realm_store.len(), 1);
}
vm.eval(if reinserted {
"frame.remove(); document.body.append(frame); globalThis.replacement = frame.contentWindow;"
} else {
"frame.remove();"
})
.unwrap();
vm.prune_stale_child_default_execution_contexts();
assert_eq!(vm.child_frame_realm_store.len(), 0);
assert_eq!(
vm._context_host
.borrow()
.window_execution_context_registry_counts_for_test(),
if reinserted { (2, 2) } else { (1, 1) },
"retirement must release the old realm registration"
);
let observed = vm.eval(
r#"JSON.stringify([
heldWindow.document === heldDocument,
heldWindow.Event === heldEvent,
heldWindow.marker === heldMarker,
heldWindow.self === heldWindow,
typeof heldWindow.addEventListener === 'function',
heldDocument.open() === heldDocument,
heldWindow.document === heldDocument,
typeof replacement === 'undefined' || replacement !== heldWindow,
typeof replacement === 'undefined' || replacement.document !== heldDocument
])"#,
);
assert_eq!(
observed.unwrap_or_else(|error| panic!(
"materialized={materialized}, reinserted={reinserted}: {error}"
)),
"[true,true,true,true,true,true,true,true,true]"
);
}
}
}