fix(dom): preserve native ownership across Page adoption

Move native subtrees while retaining wrappers, collections, styles, canvas resources, and event registrations. Resolve borrowed EventTarget methods through the native node owner and retain callback realms across adoption.

Add real CDP Page regressions for repeated adoption, native receiver validation, retained views, and closed producer realms. Validated with workspace fmt, all-target/all-feature Clippy, and 32-thread nextest (21695 passed, 16 skipped).
This commit is contained in:
ldm0
2026-11-03 18:08:12 +08:00
parent 482124ecba
commit 153d9e993a
21 changed files with 1019 additions and 39 deletions
@@ -6,6 +6,7 @@ mod auxiliary_page_identity;
mod auxiliary_page_retirement;
mod blank_navigation_inheritance;
mod browser_close;
mod native_node_adoption;
mod noopener_blank_inheritance;
mod popup_navigation_referrer;
mod target_opening;
@@ -0,0 +1,302 @@
use super::auxiliary_page_identity::open_auxiliary;
use super::*;
// A ScriptVm popup can share its native host with its opener. Publish and
// attach the auxiliary CDP target so these cases exercise two actual Pages.
#[tokio::test(flavor = "multi_thread")]
async fn borrowed_event_target_methods_use_the_native_node_owner() {
let (addr, server) = spawn_test_protocol_server().await;
let (mut browser, _) =
connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
.await
.unwrap();
let opener_id = create_dynamic_target(&mut browser, 1).await;
let mut opener = connect_dynamic_page(addr, &opener_id).await;
let (producer_id, _producer) = open_auxiliary(
addr,
&mut opener,
"window.foreignNode = p.document.createElement('div'); window.listenerCalls = 0",
)
.await;
assert_eq!(
evaluate_window_name_probe(
&mut opener,
2,
r#"(() => {
const listener = () => { listenerCalls++; };
EventTarget.prototype.addEventListener.call(foreignNode, 'test', listener);
const registered = EventTarget.prototype.dispatchEvent.call(foreignNode, new Event('test')) && listenerCalls === 1;
EventTarget.prototype.removeEventListener.call(foreignNode, 'test', listener);
foreignNode.dispatchEvent(new Event('test'));
const removed = listenerCalls === 1;
const nativeProxy = p.document.implementation.createHTMLDocument('').createElement('select');
let proxyCalls = 0;
EventTarget.prototype.addEventListener.call(nativeProxy, 'test', () => { proxyCalls++; });
const registeredNativeProxy = EventTarget.prototype.dispatchEvent.call(nativeProxy, new Event('test')) && proxyCalls === 1;
const localNode = document.createElement('div');
let reverseCalls = 0;
const reverseListener = () => { reverseCalls++; };
p.EventTarget.prototype.addEventListener.call(localNode, 'test', reverseListener);
p.EventTarget.prototype.dispatchEvent.call(localNode, new Event('test'));
p.EventTarget.prototype.removeEventListener.call(localNode, 'test', reverseListener);
localNode.dispatchEvent(new Event('test'));
let conversions = 0, proxyError, forgedError;
const type = {toString() { conversions++; return 'test'; }};
try { EventTarget.prototype.addEventListener.call(new Proxy(foreignNode, {}), type, listener); }
catch (error) { proxyError = error; }
try { p.EventTarget.prototype.addEventListener.call(Object.create(foreignNode), type, listener); }
catch (error) { forgedError = error; }
return {
registered, removed, registeredNativeProxy,
reverseOwner: reverseCalls === 1,
proxyCalleeRealm: proxyError instanceof TypeError && !(proxyError instanceof p.TypeError),
forgedCalleeRealm: forgedError instanceof p.TypeError && !(forgedError instanceof TypeError),
receiverBeforeConversion: conversions === 0
};
})()"#,
)
.await,
json!({
"registered": true,
"removed": true,
"registeredNativeProxy": true,
"reverseOwner": true,
"proxyCalleeRealm": true,
"forgedCalleeRealm": true,
"receiverBeforeConversion": true
})
);
evaluate_window_name_probe(&mut opener, 3, "p.close(); true").await;
wait_for_target_list(addr, "the producer Page has closed", |targets| {
!targets.iter().any(|target| target["id"] == producer_id)
})
.await;
assert_eq!(
evaluate_window_name_probe(
&mut opener,
4,
"EventTarget.prototype.dispatchEvent.call(foreignNode, new Event('test')) && listenerCalls === 1"
)
.await,
true
);
abort_test_cdp_server(server).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn native_adoption_preserves_views_and_callbacks_across_pages() {
let (addr, server) = spawn_test_protocol_server().await;
let (mut browser, _) =
connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
.await
.unwrap();
let opener_id = create_dynamic_target(&mut browser, 1).await;
let mut opener = connect_dynamic_page(addr, &opener_id).await;
let (producer_id, _producer) = open_auxiliary(
addr,
&mut opener,
r#"
window.sourceDocument = p.document;
window.root = sourceDocument.createElement('section');
window.unmoved = sourceDocument.createElement('div');
sourceDocument.body.appendChild(unmoved);
for (let index = 0; index < 1200; index++) {
const child = sourceDocument.createElement('span');
child.id = 'child-' + index;
root.appendChild(child);
}
sourceDocument.body.appendChild(root);
window.first = root.firstChild;
window.last = root.lastChild;
window.originalPrototype = Object.getPrototypeOf(root);
window.children = root.childNodes;
window.tags = root.getElementsByTagName('span');
window.snapshot = root.querySelectorAll('span');
window.mixed = sourceDocument.querySelectorAll('div, span');
window.style = root.style;
window.classes = root.classList;
window.dataset = root.dataset;
window.controller = new p.AbortController();
window.listenerCalls = 0;
root.addEventListener('owned', () => { listenerCalls++; }, {signal: controller.signal});
window.realmListener = new p.Function('event', 'this.callbackDocument = document; this.eventInSourceRealm = event instanceof Event;');
root.addEventListener('realm', realmListener)
"#,
)
.await;
assert_eq!(
evaluate_window_name_probe(
&mut opener,
2,
r#"(() => {
const returnedOriginal = document.adoptNode(root) === root;
document.body.appendChild(root);
style.setProperty('color', 'red');
classes.add('adopted');
dataset.owner = 'target';
root.dispatchEvent(new Event('owned'));
root.dispatchEvent(new Event('realm'));
const result = {
returnedOriginal,
prototypeRealm: Object.getPrototypeOf(root) === originalPrototype,
nativeOwners: root.ownerDocument === document && first.ownerDocument === document && last.ownerDocument === document,
liveSameObject: root.childNodes === children && children.length === 1200 && children[0] === first,
tags: tags.length === 1200 && tags[1199] === last,
staticItems: snapshot.length === 1200 && snapshot[0] === first && snapshot.item(1199) === last,
staticDescriptor: Object.getOwnPropertyDescriptor(snapshot, '0').value === first,
staticIterator: Array.from(snapshot)[1199] === last,
mixedOwners: mixed.length === 1201 && mixed[0] === unmoved && unmoved.ownerDocument === sourceDocument && mixed[1200] === last,
retainedViews: root.style === style && root.classList === classes && root.dataset === dataset && root.getAttribute('data-owner') === 'target' && root.className === 'adopted' && root.style.color === 'red',
listenerMoved: listenerCalls === 1,
callbackRealm: root.callbackDocument === sourceDocument && root.eventInSourceRealm === false
};
controller.abort();
root.dispatchEvent(new Event('owned'));
result.signalRemovesMovedListener = listenerCalls === 1;
first.remove();
result.liveMutation = children.length === 1199 && tags.length === 1199 && children[0].id === 'child-1';
result.staticRemovedNode = snapshot[0] === first && first.parentNode === null && first.ownerDocument === document;
sourceDocument.adoptNode(root);
sourceDocument.body.appendChild(root);
result.secondAdoption = root.ownerDocument === sourceDocument && last.ownerDocument === sourceDocument && snapshot[1199] === last && tags[1198] === last && first.ownerDocument === document;
document.adoptNode(root);
document.body.appendChild(root);
result.thirdAdoption = root.ownerDocument === document && last.ownerDocument === document && snapshot[1199] === last && mixed[0] === unmoved && unmoved.ownerDocument === sourceDocument;
return result;
})()"#,
)
.await,
json!({
"returnedOriginal": true,
"prototypeRealm": true,
"nativeOwners": true,
"liveSameObject": true,
"tags": true,
"staticItems": true,
"staticDescriptor": true,
"staticIterator": true,
"mixedOwners": true,
"retainedViews": true,
"listenerMoved": true,
"callbackRealm": true,
"signalRemovesMovedListener": true,
"liveMutation": true,
"staticRemovedNode": true,
"secondAdoption": true,
"thirdAdoption": true
})
);
evaluate_window_name_probe(&mut opener, 3, "p.close(); true").await;
wait_for_target_list(addr, "adoption's producer Page has closed", |targets| {
!targets.iter().any(|target| target["id"] == producer_id)
})
.await;
send_cdp_command(
&mut opener,
4,
"HeapProfiler.collectGarbage",
None,
json!({}),
)
.await;
assert_eq!(
evaluate_window_name_probe(
&mut opener,
5,
r#"(() => {
root.dispatchEvent(new Event('realm'));
const callbackRealm = root.callbackDocument === sourceDocument && root.eventInSourceRealm === false;
root.removeEventListener('realm', realmListener);
root.callbackDocument = null;
root.dispatchEvent(new Event('realm'));
root.appendChild(document.createElement('span'));
return {
movedOwner: root.ownerDocument === document && last.ownerDocument === document,
mixedOwners: mixed[0] === unmoved && unmoved.ownerDocument === sourceDocument && mixed[1200] === last,
removedSnapshot: snapshot[0] === first && first.parentNode === null && first.ownerDocument === document,
liveMutation: children.length === 1200 && tags.length === 1200,
callbackRealm,
callbackRemoved: root.callbackDocument === null
};
})()"#,
)
.await,
json!({
"movedOwner": true,
"mixedOwners": true,
"removedSnapshot": true,
"liveMutation": true,
"callbackRealm": true,
"callbackRemoved": true
})
);
abort_test_cdp_server(server).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn retained_closed_page_materializes_nodes_in_their_owner_realm() {
let (addr, server) = spawn_test_protocol_server().await;
let (mut browser, _) =
connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
.await
.unwrap();
let opener_id = create_dynamic_target(&mut browser, 1).await;
let mut opener = connect_dynamic_page(addr, &opener_id).await;
let (producer_id, _producer) = open_auxiliary(
addr,
&mut opener,
r#"
window.retainedDocument = p.document;
window.retainedBody = retainedDocument.body;
window.producerElementPrototype = p.HTMLElement.prototype;
retainedBody.innerHTML = '<article id="late" style="color:red"><b>original</b></article>'
"#,
)
.await;
evaluate_window_name_probe(&mut opener, 2, "p.close(); true").await;
wait_for_target_list(addr, "the retained Document's Page has closed", |targets| {
!targets.iter().any(|target| target["id"] == producer_id)
})
.await;
send_cdp_command(
&mut opener,
3,
"HeapProfiler.collectGarbage",
None,
json!({}),
)
.await;
assert_eq!(
evaluate_window_name_probe(
&mut opener,
4,
r#"(() => {
const getter = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild').get;
const child = getter.call(retainedBody);
const freshStyle = getComputedStyle(child);
child.dataset.afterClose = 'yes';
child.firstChild.textContent = 'changed';
return {
nativeOwner: child.ownerDocument === retainedDocument,
producerPrototype: producerElementPrototype.isPrototypeOf(child),
nativeRead: child.id === 'late' && child.tagName === 'ARTICLE',
nativeMutation: retainedBody.firstChild === child && retainedBody.textContent === 'changed' && child.getAttribute('data-after-close') === 'yes',
freshStyle: freshStyle.color === 'rgb(255, 0, 0)'
};
})()"#,
)
.await,
json!({
"nativeOwner": true,
"producerPrototype": true,
"nativeRead": true,
"nativeMutation": true,
"freshStyle": true
})
);
abort_test_cdp_server(server).await;
}
@@ -13,6 +13,15 @@ use html5ever::tree_builder::QuirksMode;
// they are the "basic DOM access" layer that other modules depend on, but they do not define
// selector semantics or orchestrate mutation side effects on their own.
impl DocumentRuntime {
pub(crate) fn transfer_native_event_targets_from(
&mut self,
source: &mut Self,
handles: &HashMap<DomHandle, DomHandle>,
) -> HashSet<crate::native_bridge::EventCallbackId> {
self.events
.transfer_node_targets_from(&mut source.events, handles)
}
pub(crate) fn document_design_mode_enabled(&self, document: DomHandle) -> bool {
self.dom_host
.document_design_mode_enabled_for_handle(document)
+65
View File
@@ -222,6 +222,71 @@ impl Default for HostEventTargetRegistry {
}
}
impl HostEventTargetRegistry {
pub(crate) fn transfer_node_targets_from(
&mut self,
source: &mut Self,
handles: &HashMap<DomHandle, DomHandle>,
) -> HashSet<crate::native_bridge::EventCallbackId> {
let mut callbacks = HashSet::new();
for (&old, &new) in handles {
let old = EventTargetHandle::Node(old);
let new = EventTargetHandle::Node(new);
let mut listeners = source.listeners.remove(&old).unwrap_or_default();
let mut handlers = source.handler_properties.remove(&old).unwrap_or_default();
let mut event_types = source
.event_type_registration_ids
.remove(&old)
.unwrap_or_default();
let mut ids = std::collections::BTreeSet::new();
for entries in listeners.values() {
ids.extend(entries.iter().map(|entry| entry.id));
}
ids.extend(handlers.values().filter_map(|entry| entry.listener_id));
ids.extend(event_types.values().copied());
let ids = ids
.into_iter()
.map(|old| (old, self.allocate_listener_id()))
.collect::<HashMap<_, _>>();
for entries in listeners.values_mut() {
for entry in entries {
entry.id = ids[&entry.id];
callbacks.insert(entry.callback_id);
}
}
for entry in handlers.values_mut() {
entry.listener_id = entry.listener_id.map(|id| ids[&id]);
match &mut entry.state {
EventHandlerPropertyState::Callback(id) => {
callbacks.insert(*id);
}
EventHandlerPropertyState::Uncompiled(handle) => {
*handle = handles[handle];
}
EventHandlerPropertyState::Null => {}
}
}
for id in event_types.values_mut() {
*id = ids[id];
}
if !listeners.is_empty() {
assert!(self.listeners.insert(new, listeners).is_none());
}
if !handlers.is_empty() {
assert!(self.handler_properties.insert(new, handlers).is_none());
}
if !event_types.is_empty() {
assert!(
self.event_type_registration_ids
.insert(new, event_types)
.is_none()
);
}
}
callbacks
}
}
impl fmt::Debug for HostEventTargetRegistry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HostEventTargetRegistry")
+14 -1
View File
@@ -492,8 +492,21 @@ pub(crate) fn abort_signal<'s>(
v8::tc_scope!(let scope, scope);
if event::invoke_abort_algorithms(scope, signal, reason, dispatch.algorithms) {
for linked in dispatch.linked_target_listeners {
let (host_ptr, target) = match linked.target {
EventTargetHandle::Node(handle) => {
let Some((owner, handle)) = unsafe { &*host_ptr }
.native_bridge()
.identity
.resolve_node_ownership(scope, host_ptr, handle)
else {
continue;
};
(owner, EventTargetHandle::Node(handle))
}
target => (host_ptr, target),
};
unsafe { &mut *host_ptr }.remove_registered_event_listener_by_id(
linked.target,
target,
&linked.event_type,
linked.callback_id,
linked.capture,
@@ -65,23 +65,29 @@ impl NativeDomBridge {
handle: BridgeHandle,
identity: BridgeWrapperIdentity,
) -> Option<v8::Local<'s, v8::Object>> {
let current = scope.get_current_context();
let current_host =
crate::util::context_host_ptr_from_context_slot(scope.get_current_context())?;
crate::util::context_host_ptr_from_context_slot(current)?;
let foreign_host = current_host != host_ptr;
if identity == BridgeWrapperIdentity::Canonical && foreign_host {
// Reflector IDs are local to a DOM bridge. Related Pages share
// an isolate, but must never consult one another's wrapper cache.
let host = unsafe { &*host_ptr };
let dispatch_scope = crate::native_bridge::OwnerDispatchScope::Top;
let owner = host.current_window_execution_context_owner(dispatch_scope)?;
let context = host
.window_execution_context(scope, owner, dispatch_scope)?
.1;
let scope = &mut v8::ContextScope::new(scope, context);
let producer = if handle.node_handle().is_some() {
self.identity.node_owner_context(scope, host_ptr)
} else {
unsafe { &*host_ptr }.page_default_context(scope)
};
if identity == BridgeWrapperIdentity::Canonical
&& foreign_host
&& let Some(producer) = producer
&& super::super::identity::contexts_share_wrapper_world(current, producer)
{
// One-field wrappers resolve their native host from the creation
// context. Canonical wrappers retain their producer realm.
let scope = &mut v8::ContextScope::new(scope, producer);
return self.materialize_bridge_wrapper(scope, host_ptr, handle, identity);
}
let native_owner = if identity == BridgeWrapperIdentity::NewObject && foreign_host {
let producer = unsafe { &*host_ptr }.page_default_context(scope)?;
let native_owner = if foreign_host
&& (identity == BridgeWrapperIdentity::NewObject || handle.node_handle().is_some())
{
let producer = producer?;
let scope = &mut v8::ContextScope::new(scope, producer);
Some(v8::Global::new(scope, v8::Object::new(scope)))
} else {
@@ -96,9 +102,14 @@ impl NativeDomBridge {
return Some(wrapper);
}
let wrapper = self
.bindings
.instantiate_wrapper(scope, host_ptr, handle, reflector_id);
let wrapper =
self.bindings
.instantiate_wrapper(scope, host_ptr, handle.clone(), reflector_id);
if let Some(node) = handle.node_handle() {
self.identity
.node_ownership(scope, host_ptr, node)
.bind(scope, wrapper);
}
if let Some(owner) = native_owner {
let owner = v8::Local::new(scope, owner);
crate::util::set_private_value(
@@ -339,6 +339,27 @@ pub(crate) fn build_static_handle_node_list_wrapper<'s>(
host.native_bridge_mut().static_handle_collection_store()
};
let collection_id = collections.borrow_mut().register(handles.to_vec());
let anchors = v8::Array::new(
scope,
i32::try_from(handles.len()).expect("NodeList length fits V8"),
);
anchors.set_prototype(scope, v8::null(scope).into());
for (index, handle) in handles.iter().copied().enumerate() {
let ownership = unsafe { &mut *runtime_ptr }
.native_bridge_mut()
.identity
.node_ownership(scope, runtime_ptr, handle);
let anchor = ownership
.anchor(scope)
.expect("NodeList node has an owner realm");
anchors.set_index(scope, index as u32, anchor.into());
}
set_private_value(
scope,
wrapper,
"__moliStaticCollectionNodeOwners",
anchors.into(),
);
// Mutation records create short-lived snapshots frequently. Release the
// native handle vector when its wrapper dies, without retaining the host.
crate::v8_finalizer::track_context_owned_v8_finalizer(scope, wrapper, move || {
@@ -403,6 +424,11 @@ pub(in crate::native_bridge) fn build_live_collection_wrapper<'s>(
collection_id,
descriptor.collection_kind,
);
unsafe { &mut *runtime_ptr }
.native_bridge_mut()
.identity
.node_ownership(scope, runtime_ptr, descriptor.root)
.bind(scope, wrapper);
{
let host = unsafe { &mut *runtime_ptr };
host.native_bridge_mut()
@@ -38,7 +38,8 @@ pub(in crate::native_bridge::collections) fn collection_value_at<'s>(
}
if let Ok((runtime_ptr, collection_id)) = static_handle_collection_id_from_object(scope, object)
{
let handle = static_handle_collection_handle_at(runtime_ptr, collection_id, index)?;
let (runtime_ptr, handle) =
static_handle_collection_handle_at(scope, runtime_ptr, collection_id, index)?;
return Some(wrapped_handle_value(scope, runtime_ptr, handle).unwrap_or_else(|| {
panic!(
"failed to materialize handle-backed static collection handle `{handle:?}` at index `{index}`"
@@ -398,8 +398,8 @@ pub(in crate::native_bridge::collections) fn static_handle_collection_indexed_ge
let (runtime_ptr, collection_id) =
static_handle_collection_id_from_object(scope, args.holder())
.expect("handle-backed static NodeList must retain its collection id");
let Some(handle) =
static_handle_collection_handle_at(runtime_ptr, collection_id, index as usize)
let Some((runtime_ptr, handle)) =
static_handle_collection_handle_at(scope, runtime_ptr, collection_id, index as usize)
else {
return v8::Intercepted::kNo;
};
@@ -467,8 +467,8 @@ pub(in crate::native_bridge::collections) fn static_handle_collection_indexed_de
let (runtime_ptr, collection_id) =
static_handle_collection_id_from_object(scope, args.holder())
.expect("handle-backed static NodeList must retain its collection id");
let Some(handle) =
static_handle_collection_handle_at(runtime_ptr, collection_id, index as usize)
let Some((runtime_ptr, handle)) =
static_handle_collection_handle_at(scope, runtime_ptr, collection_id, index as usize)
else {
return v8::Intercepted::kNo;
};
@@ -33,12 +33,18 @@ pub(in crate::native_bridge::collections) fn live_collection_descriptor_from_obj
) -> std::result::Result<(*mut JsContextHost, LiveCollectionDescriptor), String> {
let runtime_ptr = runtime_ptr_from_object(scope, object)?;
let collection_id = object_collection_id(scope, object)?;
let descriptor = unsafe { &mut *runtime_ptr }
let mut descriptor = unsafe { &mut *runtime_ptr }
.native_bridge_mut()
.live_collection_descriptor(collection_id)
.cloned()
.ok_or_else(|| format!("missing live collection descriptor `{collection_id}`"))?;
Ok((runtime_ptr, descriptor))
let (owner, root) = unsafe { &*runtime_ptr }
.native_bridge()
.identity
.resolve_node_ownership(scope, runtime_ptr, descriptor.root)
.ok_or_else(|| "live collection root has no owning realm".to_owned())?;
descriptor.root = root;
Ok((owner, descriptor))
}
pub(in crate::native_bridge::collections) fn static_handle_collection_id_from_object<'s>(
@@ -71,13 +77,18 @@ pub(in crate::native_bridge::collections) fn static_handle_collection_len(
}
pub(in crate::native_bridge::collections) fn static_handle_collection_handle_at(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut JsContextHost,
collection_id: u32,
index: usize,
) -> Option<DomHandle> {
unsafe { &mut *runtime_ptr }
) -> Option<(*mut JsContextHost, DomHandle)> {
let handle = unsafe { &mut *runtime_ptr }
.native_bridge_mut()
.static_handle_collection_handle_at(collection_id, index)
.static_handle_collection_handle_at(collection_id, index)?;
unsafe { &*runtime_ptr }
.native_bridge()
.identity
.resolve_node_ownership(scope, runtime_ptr, handle)
}
pub(in crate::native_bridge::collections) fn object_collection_id(
@@ -12,6 +12,29 @@ pub(super) struct CanvasResourceStore {
}
impl CanvasResourceStore {
pub(super) fn transfer_from(
&mut self,
source: &mut Self,
handles: &HashMap<DomHandle, DomHandle>,
) {
let mut changed = false;
for (&old, &new) in handles {
if let Some(pixels) = source.pixels_by_element.remove(&old) {
source.retained_bytes -= pixels.byte_len();
self.retained_bytes = self
.retained_bytes
.checked_add(pixels.byte_len())
.expect("retained canvas byte accounting fits usize");
assert!(self.pixels_by_element.insert(new, pixels).is_none());
changed = true;
}
}
if changed {
source.visual_generation.bump();
self.visual_generation.bump();
}
}
pub(super) fn new(visual_generation: VisualResourceGeneration) -> Self {
Self {
pixels_by_element: HashMap::new(),
@@ -118,6 +141,37 @@ impl super::JsContextHost {
mod tests {
use super::*;
#[test]
fn ownership_transfer_preserves_canvas_pixels_and_both_hosts_accounting() {
let mut source = CanvasResourceStore::default();
let mut target = CanvasResourceStore::default();
let source_node = DomHandle::new(7);
let unmoved_source = DomHandle::new(8);
let target_node = DomHandle::new(12);
let unmoved_target = DomHandle::new(7);
assert!(source.replace(source_node, 1, 1, vec![1, 2, 3, 4]));
assert!(source.replace(unmoved_source, 1, 1, vec![5, 6, 7, 8]));
assert!(target.replace(unmoved_target, 1, 1, vec![9, 10, 11, 12]));
let retained = source.get(source_node).unwrap();
target.transfer_from(&mut source, &HashMap::from([(source_node, target_node)]));
assert!(source.get(source_node).is_none());
assert!(Arc::ptr_eq(&retained, &target.get(target_node).unwrap()));
assert_eq!(source.retained_bytes, 4);
assert_eq!(target.retained_bytes, 8);
assert_eq!(source.get(unmoved_source).unwrap().rgba, [5, 6, 7, 8]);
assert_eq!(target.get(unmoved_target).unwrap().rgba, [9, 10, 11, 12]);
source.transfer_from(
&mut target,
&HashMap::from([(target_node, DomHandle::new(20))]),
);
assert!(Arc::ptr_eq(
&retained,
&source.get(DomHandle::new(20)).unwrap()
));
assert_eq!(source.retained_bytes, 8);
assert_eq!(target.retained_bytes, 4);
}
#[test]
fn replacing_a_canvas_resource_preserves_old_snapshot_arcs_and_exact_accounting() {
let mut store = CanvasResourceStore::default();
@@ -16,6 +16,7 @@ struct EventCallbackRecord {
callback: WebIdlCallbackInterface,
kind: EventCallbackKind,
relevant_identity: Option<WindowExecutionContextIdentity>,
registration_identity: Option<WindowExecutionContextIdentity>,
#[cfg(test)]
incumbent_identity: Option<WindowExecutionContextIdentity>,
}
@@ -97,17 +98,17 @@ impl PreparedEventCallback {
#[derive(Default)]
pub(super) struct EventCallbackRegistry {
next_id: u64,
records: HashMap<EventCallbackId, EventCallbackRecord>,
}
impl EventCallbackRegistry {
fn allocate_id(&mut self) -> EventCallbackId {
self.next_id = self
.next_id
.checked_add(1)
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
let id = NEXT_ID
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.expect("event callback id overflow");
EventCallbackId(self.next_id)
EventCallbackId(id)
}
fn take_owned_by(&mut self, owner: WindowExecutionContextOwner) -> HashSet<EventCallbackId> {
@@ -116,7 +117,7 @@ impl EventCallbackRegistry {
.iter()
.filter_map(|(id, record)| {
record
.relevant_identity
.registration_identity
.is_some_and(|identity| identity.owner() == owner)
.then_some(*id)
})
@@ -397,6 +398,7 @@ impl JsContextHost {
callback,
kind,
relevant_identity,
registration_identity: relevant_identity,
#[cfg(test)]
incumbent_identity,
},
@@ -481,7 +483,7 @@ impl JsContextHost {
) -> Option<PreparedEventCallback> {
let record = self.event_callbacks.records.get(&id)?;
if record
.relevant_identity
.registration_identity
.is_some_and(|identity| !self.window_execution_context_identity_is_current(identity))
{
return None;
@@ -489,10 +491,35 @@ impl JsContextHost {
Some(PreparedEventCallback {
callback: record.callback.prepare(scope),
kind: record.kind,
relevant_identity: record.relevant_identity,
relevant_identity: record
.relevant_identity
.filter(|identity| self.window_execution_context_identity_is_current(*identity)),
})
}
pub(in crate::native_bridge) fn transfer_node_event_callbacks_from(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
source: &mut Self,
callbacks: &HashSet<EventCallbackId>,
owner: v8::Local<'_, v8::Context>,
) {
let registration_identity =
self.window_execution_context_identity_for_v8_context(scope, owner);
for id in callbacks {
let mut record = source
.event_callbacks
.records
.remove(id)
.expect("native event registration has a callback record");
// The target's lifetime moves; the callback's captured relevant and
// incumbent realms do not. Callback IDs are unique across hosts,
// so retained AbortSignal registrations continue to identify it.
record.registration_identity = registration_identity;
assert!(self.event_callbacks.records.insert(*id, record).is_none());
}
}
pub(in crate::native_bridge::context_host) fn retire_event_callbacks_for_execution_context(
&mut self,
owner: WindowExecutionContextOwner,
@@ -98,6 +98,7 @@ mod file_chooser;
mod file_entry_file_callbacks;
mod fixture_support;
mod focus;
mod node_adoption;
pub(crate) use focus::SequentialFocusStartingPoint;
mod frame_document_ready_routes;
mod hash_changes;
@@ -0,0 +1,73 @@
use super::JsContextHost;
use crate::{
custom_elements, document_runtime::DomHandle,
native_bridge::node_runtime_and_handle_from_object,
};
impl JsContextHost {
pub(in crate::native_bridge) fn adopt_node_from_host(
scope: &mut v8::PinScope<'_, '_>,
target: *mut Self,
document: DomHandle,
object: v8::Local<'_, v8::Object>,
) -> Option<DomHandle> {
let (source, root) = node_runtime_and_handle_from_object(scope, object).ok()?;
if source == target {
return Some(root);
}
let owner = unsafe { &*target }
.bridge
.identity
.node_owner_context(scope, target)?;
custom_elements::with_custom_element_reaction_scope(scope, source, |scope| {
let parent = unsafe { &*source }.dom_host().parent_node(root);
if let Some(parent) = parent
&& !unsafe { &mut *source }
.remove_child_appending_to_current_reaction_queue(scope, source, parent, root)
{
return None;
}
// Removal may synchronously run focus/resource cleanup. Resolve the
// original object again rather than trusting a pre-callback ID.
let (current_source, current_root) =
node_runtime_and_handle_from_object(scope, object).ok()?;
if current_source != source || current_root != root {
return Self::adopt_node_from_host(scope, target, document, object);
}
let transfer = unsafe { &mut *target }
.dom_host_mut()
.transfer_detached_subtree_from(
document,
unsafe { &mut *source }.dom_host_mut(),
root,
)
.ok()?;
let handles = transfer.handles();
let target_host = unsafe { &mut *target };
let source_host = unsafe { &mut *source };
target_host.bridge.identity.transfer_node_ownership_from(
scope,
&mut source_host.bridge.identity,
source,
owner,
handles,
);
for (&old, &new) in handles {
if let Some(style) = source_host.inline_style_declarations.remove(&old) {
assert!(
target_host
.inline_style_declarations
.insert(new, style)
.is_none()
);
}
}
target_host
.canvas_resources
.transfer_from(&mut source_host.canvas_resources, handles);
let callbacks = target_host.transfer_native_event_targets_from(source_host, handles);
target_host.transfer_node_event_callbacks_from(scope, source_host, &callbacks, owner);
Some(transfer.root())
})
}
}
@@ -301,6 +301,11 @@ pub(crate) fn detached_native_handle_for_runtime<'s>(
) -> Option<DomHandle> {
let node = node_backing_object(scope, node)?;
let value = get_private_value(scope, node, DETACHED_NATIVE_HANDLE_SLOT)?;
if let Some((owner, handle)) =
crate::native_bridge::identity::resolve_object_node_ownership(scope, node)
{
return (owner == runtime_ptr).then_some(handle);
}
let big = v8::Local::<v8::BigInt>::try_from(value).ok()?;
let (index, lossless) = big.u64_value();
if !lossless {
@@ -666,6 +671,13 @@ pub(in crate::native_bridge) fn define_detached_native_handle(
) {
let value = v8::BigInt::new_from_u64(scope, handle.index() as u64);
set_private_value(scope, node, DETACHED_NATIVE_HANDLE_SLOT, value.into());
if let Some(host) = context_host_ptr_from_global_bridge(scope) {
unsafe { &mut *host }
.native_bridge_mut()
.identity
.node_ownership(scope, host, handle)
.bind(scope, node);
}
pair_detached_native_handle_with_wrapper(scope, node, handle);
}
@@ -52,5 +52,13 @@ pub(in crate::native_bridge) fn bridge_handle_from_object(
.native_bridge()
.bridge_handle(reflector_id)
.with_context(|| format!("no bridge identity for reflector id {}", reflector_id.raw()))?;
if let Some(node) = handle.node_handle() {
let (owner, node) = unsafe { &*runtime_ptr }
.native_bridge()
.identity
.resolve_node_ownership(scope, runtime_ptr, node)
.context("native node's owning realm has retired")?;
return Ok((owner, handle.with_node_handle(node)));
}
Ok((runtime_ptr, handle))
}
@@ -17,6 +17,8 @@ use super::{JsContextHost, RuntimeObservableContextToken};
use dense_reflector_map::DenseReflectorMap;
mod dense_reflector_map;
mod node_ownership;
pub(in crate::native_bridge) use node_ownership::resolve_object_node_ownership;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) struct ReflectorId(u64);
@@ -53,6 +55,30 @@ pub(super) enum BridgeHandle {
ComputedStyle(DomHandle, Rc<ComputedStyleDescriptor>),
}
impl BridgeHandle {
pub(super) fn node_handle(&self) -> Option<DomHandle> {
match self {
Self::Window => None,
Self::Node(handle)
| Self::ClassList(handle, _)
| Self::Dataset(handle)
| Self::Style(handle)
| Self::ComputedStyle(handle, _) => Some(*handle),
}
}
pub(super) fn with_node_handle(self, handle: DomHandle) -> Self {
match self {
Self::Window => Self::Window,
Self::Node(_) => Self::Node(handle),
Self::ClassList(_, kind) => Self::ClassList(handle, kind),
Self::Dataset(_) => Self::Dataset(handle),
Self::Style(_) => Self::Style(handle),
Self::ComputedStyle(_, descriptor) => Self::ComputedStyle(handle, descriptor),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ComputedStyleDescriptor {
pub(crate) pseudo: ComputedStylePseudoKey,
@@ -642,6 +668,8 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown(
#[derive(Debug, Default)]
pub(super) struct BridgeIdentityStore {
reflector_handles: IndexSet<BridgeHandle>,
node_ownership: HashMap<DomHandle, Rc<node_ownership::NodeOwnership>>,
node_owner_realm: Option<v8::Weak<v8::Context>>,
live_collections: LiveCollectionStore,
static_handle_collections: Rc<RefCell<StaticHandleCollectionStore>>,
default_world_wrapper_cache: Rc<RefCell<BridgeContextWrapperCache>>,
@@ -0,0 +1,304 @@
use std::{cell::RefCell, rc::Rc};
use super::{BridgeIdentityStore, JsContextHost, ReflectorId};
use crate::{document_runtime::DomHandle, util};
const ANCHOR_SLOT: &str = "__moliNativeNodeOwnership";
const OWNER_SLOT: &str = "__moliNativeNodeCurrentOwner";
const HANDLE_SLOT: &str = "__moliNativeNodeCurrentHandle";
pub(in crate::native_bridge) fn resolve_object_node_ownership(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) -> Option<(*mut JsContextHost, DomHandle)> {
let object = v8::Local::new(scope, object);
let anchor = util::get_private_object(scope, object, ANCHOR_SLOT)?;
let handle = util::get_private_value(scope, anchor, HANDLE_SLOT)?;
let handle = v8::Local::<v8::BigInt>::try_from(handle).ok()?;
let (handle, lossless) = handle.u64_value();
let handle = lossless.then(|| usize::try_from(handle).ok()).flatten()?;
let owner = util::get_private_object(scope, anchor, OWNER_SLOT).unwrap_or(anchor);
let owner = owner.get_creation_context(scope)?;
Some((
util::context_host_ptr_from_context_slot(owner)?,
DomHandle::new(handle),
))
}
/// Native location shared by every retained view of a node. The Rust record
/// has only weak V8 edges. Wrappers and collections trace the anchor, which in
/// turn traces the current owning Document realm through a private property.
/// Moving a node updates this one location without changing its JS identity,
/// prototype, or the host-local IDs stored in an older collection snapshot.
#[derive(Debug)]
pub(in crate::native_bridge) struct NodeOwnership {
location: RefCell<NodeLocation>,
}
#[derive(Debug)]
struct NodeLocation {
handle: DomHandle,
owner: v8::Weak<v8::Context>,
anchor: v8::Weak<v8::Object>,
}
impl NodeOwnership {
fn new(
scope: &mut v8::PinScope<'_, '_>,
owner: v8::Local<'_, v8::Context>,
handle: DomHandle,
) -> Self {
let scope = &mut v8::ContextScope::new(scope, owner);
let anchor = util::new_null_prototype_object(scope);
let value = v8::BigInt::new_from_u64(scope, handle.index() as u64);
util::set_private_value(scope, anchor, HANDLE_SLOT, value.into());
Self {
location: RefCell::new(NodeLocation {
handle,
owner: v8::Weak::new(scope, owner),
anchor: v8::Weak::new(scope, anchor),
}),
}
}
pub(in crate::native_bridge) fn resolve(
&self,
scope: &mut v8::PinScope<'_, '_>,
) -> Option<(*mut JsContextHost, DomHandle)> {
let location = self.location.borrow();
let owner = location.owner.to_local(scope)?;
let host = util::context_host_ptr_from_context_slot(owner)?;
Some((host, location.handle))
}
pub(in crate::native_bridge) fn anchor<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
) -> Option<v8::Local<'s, v8::Object>> {
let mut location = self.location.borrow_mut();
if let Some(anchor) = location.anchor.to_local(scope) {
return Some(anchor);
}
let owner = location.owner.to_local(scope)?;
let scope = &mut v8::ContextScope::new(scope, owner);
let anchor = util::new_null_prototype_object(scope);
let value = v8::BigInt::new_from_u64(scope, location.handle.index() as u64);
util::set_private_value(scope, anchor, HANDLE_SLOT, value.into());
location.anchor = v8::Weak::new(scope, anchor);
Some(anchor)
}
pub(in crate::native_bridge) fn bind(
&self,
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) {
let anchor = self
.anchor(scope)
.expect("live native node has an owner realm");
util::set_private_value(scope, object, ANCHOR_SLOT, anchor.into());
}
pub(in crate::native_bridge) fn retarget(
&self,
scope: &mut v8::PinScope<'_, '_>,
owner: v8::Local<'_, v8::Context>,
handle: DomHandle,
) {
// A retained anchor can have been created in an earlier Page. Give it
// a V8-traced edge to the new owner before replacing the weak location.
let mut location = self.location.borrow_mut();
if let Some(anchor) = location.anchor.to_local(scope) {
let scope = &mut v8::ContextScope::new(scope, owner);
let owner_anchor = util::new_null_prototype_object(scope);
util::set_private_value(scope, anchor, OWNER_SLOT, owner_anchor.into());
let value = v8::BigInt::new_from_u64(scope, handle.index() as u64);
util::set_private_value(scope, anchor, HANDLE_SLOT, value.into());
}
location.handle = handle;
location.owner = v8::Weak::new(scope, owner);
}
}
impl BridgeIdentityStore {
pub(in crate::native_bridge) fn transfer_node_ownership_from(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
source: &mut Self,
source_host: *mut JsContextHost,
owner: v8::Local<'_, v8::Context>,
handles: &std::collections::HashMap<DomHandle, DomHandle>,
) {
// Capture existing canonical objects before retargeting. Their internal
// reflector ID still belongs to the original host; its shared location
// resolves to the new owner. No public getter or setter participates.
let wrappers = source
.reflector_handles
.iter()
.enumerate()
.filter_map(|(index, descriptor)| {
let old = descriptor.node_handle()?;
let new = *handles.get(&old)?;
let wrapper = source.cached_wrapper(scope, ReflectorId::from_index(index))?;
Some((
descriptor.clone().with_node_handle(new),
v8::Global::new(scope, wrapper),
))
})
.collect::<Vec<_>>();
let collections = {
let cache = source.current_wrapper_cache(scope);
let cache = cache.borrow();
let mut collections = Vec::new();
for (descriptor, entry) in &cache.live_collection_wrappers {
if let Some(&root) = handles.get(&descriptor.root)
&& let Some(wrapper) = entry.wrapper.to_local(scope)
{
let mut descriptor = descriptor.clone();
*descriptor.resolution_cache.0.borrow_mut() = None;
descriptor.root = root;
collections.push((descriptor, v8::Global::new(scope, wrapper)));
}
}
for (descriptor, entry) in &cache.retired_live_collection_wrappers {
if let Some(&root) = handles.get(&descriptor.root)
&& let Some(wrapper) = entry.to_local(scope)
{
let mut descriptor = descriptor.clone();
*descriptor.resolution_cache.0.borrow_mut() = None;
descriptor.root = root;
collections.push((descriptor, v8::Global::new(scope, wrapper)));
}
}
collections
};
for (&old, &new) in handles {
let ownership = source.node_ownership(scope, source_host, old);
ownership.retarget(scope, owner, new);
assert!(
self.node_ownership.insert(new, ownership).is_none(),
"transferred native IDs are never reused"
);
}
for (descriptor, wrapper) in wrappers {
let id = self.reflector_id(&descriptor);
self.cache_wrapper(scope, id, v8::Local::new(scope, &wrapper));
}
for (descriptor, wrapper) in collections {
self.cache_live_collection_wrapper(scope, descriptor, v8::Local::new(scope, &wrapper));
}
// A retained descriptor not materialized in this world must also lose
// its source-host query cache, whose version can collide with the target.
for descriptor in source.live_collections.descriptors.values() {
if handles.contains_key(&descriptor.root) {
*descriptor.resolution_cache.0.borrow_mut() = None;
}
}
}
pub(in crate::native_bridge) fn node_ownership(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host: *mut JsContextHost,
handle: DomHandle,
) -> Rc<NodeOwnership> {
if let Some(ownership) = self.node_ownership.get(&handle) {
return ownership.clone();
}
let owner = self
.node_owner_context(scope, host)
.expect("native node owner has a Document realm");
self.node_owner_realm = Some(v8::Weak::new(scope, owner));
let ownership = Rc::new(NodeOwnership::new(scope, owner, handle));
self.node_ownership.insert(handle, ownership.clone());
ownership
}
pub(in crate::native_bridge) fn node_owner_context<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
host: *mut JsContextHost,
) -> Option<v8::Local<'s, v8::Context>> {
// Native ownership belongs to the Page, independent of which isolated
// world first materializes a wrapper. Keep only a weak realm reference
// for retained nodes after the Page clears its active default context.
unsafe { &*host }
.page_default_context(scope)
.or_else(|| {
self.node_owner_realm
.as_ref()
.and_then(|owner| owner.to_local(scope))
})
.or_else(|| {
let current = scope.get_current_context();
(util::context_host_ptr_from_context_slot(current) == Some(host)).then_some(current)
})
}
pub(in crate::native_bridge) fn resolve_node_ownership(
&self,
scope: &mut v8::PinScope<'_, '_>,
host: *mut JsContextHost,
handle: DomHandle,
) -> Option<(*mut JsContextHost, DomHandle)> {
match self.node_ownership.get(&handle) {
Some(ownership) => ownership.resolve(scope),
None => Some((host, handle)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retained_node_traces_its_current_owner_and_releases_previous_and_final_owners() {
crate::ensure_v8_for_test();
let mut isolate = v8::Isolate::new(Default::default());
let (ownership, wrapper, first_owner, current_owner) = {
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let original = v8::Context::new(scope, Default::default());
let first = v8::Context::new(scope, Default::default());
let current = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, original);
let wrapper = util::new_null_prototype_object(scope);
let ownership = NodeOwnership::new(scope, original, DomHandle::new(5));
ownership.bind(scope, wrapper);
ownership.retarget(scope, first, DomHandle::new(105));
ownership.retarget(scope, current, DomHandle::new(205));
assert_eq!(wrapper.get_creation_context(scope), Some(original));
let anchor = util::get_private_object(scope, wrapper, ANCHOR_SLOT).unwrap();
let handle = util::get_private_value(scope, anchor, HANDLE_SLOT).unwrap();
assert_eq!(
v8::Local::<v8::BigInt>::try_from(handle)
.unwrap()
.u64_value(),
(205, true)
);
(
ownership,
v8::Global::new(scope, wrapper),
v8::Weak::new(scope, first),
v8::Weak::new(scope, current),
)
};
isolate.low_memory_notification();
assert!(
first_owner.is_empty(),
"retargeting must release the intermediate Document realm"
);
assert!(
!current_owner.is_empty(),
"a retained wrapper traces its current native owner"
);
drop(wrapper);
isolate.low_memory_notification();
assert!(
current_owner.is_empty(),
"Rust ownership metadata must not root a released Document realm"
);
drop(ownership);
}
}
@@ -841,6 +841,9 @@ pub(crate) fn node_runtime_and_handle_from_object_or_detached<'s>(
if let Ok(node) = node_runtime_and_handle_from_object(scope, object) {
return Ok(node);
}
if let Some(node) = super::identity::resolve_object_node_ownership(scope, object) {
return Ok(node);
}
// Detached node indices are host-local too. Borrowed bindings and
// structuredClone can run in another Page, so resolve the producer's
// lifecycle-checked context instead of looking in the caller's arena.
@@ -196,8 +196,12 @@ pub(in crate::native_bridge) fn node_or_foreign_arg_handle(
match resolve_node_argument(scope, runtime_ptr, value) {
NodeArgumentResolution::SameRuntimeNative(handle)
| NodeArgumentResolution::LiveDelegate(handle) => Some(handle),
NodeArgumentResolution::CrossRuntimeNative(object)
| NodeArgumentResolution::ForeignObject(object) => {
NodeArgumentResolution::CrossRuntimeNative(object) => {
let document = document_handle
.unwrap_or_else(|| unsafe { &*runtime_ptr }.dom_host().document_handle());
JsContextHost::adopt_node_from_host(scope, runtime_ptr, document, object)
}
NodeArgumentResolution::ForeignObject(object) => {
let document_handle = document_handle?;
materialize_foreign_node_arg_handle(scope, runtime_ptr, document_handle, object)
}
@@ -248,8 +252,12 @@ pub(crate) fn node_or_foreign_arg_handle_allow_detached(
let object = v8::Local::new(scope, object);
materialize_detached_node_arg_handle(scope, runtime_ptr, document_handle, object)
}
NodeArgumentResolution::CrossRuntimeNative(object)
| NodeArgumentResolution::ForeignObject(object) => {
NodeArgumentResolution::CrossRuntimeNative(object) => {
let document = document_handle
.unwrap_or_else(|| unsafe { &*runtime_ptr }.dom_host().document_handle());
JsContextHost::adopt_node_from_host(scope, runtime_ptr, document, object)
}
NodeArgumentResolution::ForeignObject(object) => {
let document_handle = document_handle?;
materialize_foreign_node_arg_handle(scope, runtime_ptr, document_handle, object)
}
+23
View File
@@ -304,6 +304,11 @@ fn register_dom_event_target_listener<'s>(
window_receiver: Option<WindowOperationReceiver>,
call: AddEventListenerArgs<'s>,
) {
let host_ptr = if window_receiver.is_none() {
native_event_target_host(scope, receiver).unwrap_or(host_ptr)
} else {
host_ptr
};
let host = unsafe { &mut *host_ptr };
let Some(listener) = call.listener else {
return;
@@ -432,6 +437,12 @@ pub(super) fn event_target_remove_event_listener_callback<'s>(
else {
return;
};
let host_ptr = if window_receiver.is_none() {
native_event_target_host(scope, args.this()).unwrap_or(host_ptr)
} else {
host_ptr
};
let host = unsafe { &mut *host_ptr };
let Some(listener) = call.listener else {
return;
};
@@ -478,6 +489,7 @@ pub(super) fn event_target_dispatch_event_callback<'s>(
rv.set_bool(false);
return;
};
let host_ptr = native_event_target_host(scope, args.this()).unwrap_or(host_ptr);
let host = unsafe { &mut *host_ptr };
let Ok(window_receiver) = capture_window_event_target_receiver(scope, args.this(), host) else {
return;
@@ -2264,6 +2276,17 @@ fn dom_handle_from_marker_value(
.map(|value| crate::document_runtime::DomHandle::new(value as usize))
}
fn native_event_target_host<'s>(
scope: &mut v8::PinScope<'s, '_>,
receiver: v8::Local<'s, v8::Object>,
) -> Option<*mut JsContextHost> {
// A Node retains its function/prototype realm across adoption. Resolve its
// native owner after conversion, since an options getter can move it again.
crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, receiver)
.ok()
.map(|(host, _)| host)
}
fn event_target_handle_from_this<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,