fix(dom): share scoped registries across native owners

This commit is contained in:
ldm0
2026-11-20 22:47:58 +08:00
parent 90084d0c3f
commit dead4b1585
32 changed files with 1311 additions and 118 deletions
+2
View File
@@ -124,7 +124,9 @@ mod registry_clone_retarget;
pub(crate) use registry_clone_retarget::{
registry_association_retargets_for_clone, registry_association_retargets_for_import_clone,
};
mod registry_bindings;
mod registry_install;
pub(crate) use registry_bindings::CustomElementRegistryBindings;
pub(crate) use registry_install::{
build_custom_elements_registry_for_window, custom_elements_registry_for_current_realm,
rebind_materialized_child_custom_elements_registry,
@@ -1,11 +1,10 @@
use crate::document_runtime::DomHandle;
use std::collections::HashSet;
use crate::{document_runtime::DomHandle, native_bridge::NativeDomHostId};
use std::{cell::Cell, collections::HashSet, rc::Rc};
struct PendingConstruction {
constructor: v8::Global<v8::Function>,
wrapper: Option<v8::Global<v8::Object>>,
handle: DomHandle,
kind: PendingConstructionKind,
view: Rc<SharedPendingConstruction>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -14,9 +13,69 @@ enum PendingConstructionKind {
SynchronousCreateElement,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ConstructionState {
Available,
Consumed,
Finished,
}
#[derive(Clone, Copy)]
pub(crate) struct CustomElementConstructionId {
pub(crate) owner: NativeDomHostId,
pub(crate) handle: DomHandle,
}
/// A weak view of a construction owned by one native DOM host. The isolate
/// may locate this view while calling super() in another realm; only the
/// owning stack roots values and stores unqualified node state.
pub(super) struct SharedPendingConstruction {
id: CustomElementConstructionId,
constructor: v8::Weak<v8::Function>,
registry_realm: v8::Weak<v8::Context>,
wrapper: v8::Weak<v8::Object>,
kind: PendingConstructionKind,
state: Cell<ConstructionState>,
}
pub(crate) enum PendingCustomElementConstruction<'s> {
Wrapper(v8::Local<'s, v8::Object>, DomHandle),
AlreadyConstructed(DomHandle),
Wrapper(v8::Local<'s, v8::Object>, CustomElementConstructionId),
AlreadyConstructed(CustomElementConstructionId),
}
impl SharedPendingConstruction {
pub(super) fn matches(
&self,
scope: &mut v8::PinScope<'_, '_>,
new_target: v8::Local<'_, v8::Function>,
) -> bool {
self.state.get() != ConstructionState::Finished
&& self.registry_realm.to_local(scope) == Some(scope.get_current_context())
&& self
.constructor
.to_local(scope)
.is_some_and(|constructor| constructor.strict_equals(new_target.into()))
}
pub(super) fn take<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
) -> Option<PendingCustomElementConstruction<'s>> {
if self.state.get() == ConstructionState::Consumed {
return Some(PendingCustomElementConstruction::AlreadyConstructed(
self.id,
));
}
if self.state.get() == ConstructionState::Finished {
return None;
}
let wrapper = self.wrapper.to_local(scope)?;
self.state.set(match self.kind {
PendingConstructionKind::ExistingElementUpgrade => ConstructionState::Consumed,
PendingConstructionKind::SynchronousCreateElement => ConstructionState::Finished,
});
Some(PendingCustomElementConstruction::Wrapper(wrapper, self.id))
}
}
#[derive(Default)]
@@ -30,15 +89,18 @@ impl CustomElementConstructionStack {
pub(super) fn begin_existing_element_upgrade(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
owner: NativeDomHostId,
registry_realm: v8::Local<'_, v8::Context>,
constructor: v8::Local<'_, v8::Function>,
wrapper: v8::Local<'_, v8::Object>,
handle: DomHandle,
) {
self.begin_with_kind(
scope,
CustomElementConstructionId { owner, handle },
registry_realm,
constructor,
wrapper,
handle,
PendingConstructionKind::ExistingElementUpgrade,
);
}
@@ -46,15 +108,18 @@ impl CustomElementConstructionStack {
pub(super) fn begin_synchronous_create_element(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
owner: NativeDomHostId,
registry_realm: v8::Local<'_, v8::Context>,
constructor: v8::Local<'_, v8::Function>,
wrapper: v8::Local<'_, v8::Object>,
handle: DomHandle,
) {
self.begin_with_kind(
scope,
CustomElementConstructionId { owner, handle },
registry_realm,
constructor,
wrapper,
handle,
PendingConstructionKind::SynchronousCreateElement,
);
}
@@ -62,17 +127,26 @@ impl CustomElementConstructionStack {
fn begin_with_kind(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
id: CustomElementConstructionId,
registry_realm: v8::Local<'_, v8::Context>,
constructor: v8::Local<'_, v8::Function>,
wrapper: v8::Local<'_, v8::Object>,
handle: DomHandle,
kind: PendingConstructionKind,
) {
self.constructing_handles.insert(handle);
let view = Rc::new(SharedPendingConstruction {
id,
constructor: v8::Weak::new(scope, constructor),
registry_realm: v8::Weak::new(scope, registry_realm),
wrapper: v8::Weak::new(scope, wrapper),
kind,
state: Cell::new(ConstructionState::Available),
});
super::CustomElementRegistryBindings::for_isolate(scope).register_construction(&view);
self.constructing_handles.insert(id.handle);
self.stack.push(PendingConstruction {
constructor: v8::Global::new(scope, constructor),
wrapper: Some(v8::Global::new(scope, wrapper)),
handle,
kind,
view,
});
}
@@ -81,9 +155,10 @@ impl CustomElementConstructionStack {
if let Some(index) = self
.stack
.iter()
.rposition(|pending| pending.handle == handle)
.rposition(|pending| pending.view.id.handle == handle)
{
self.stack.remove(index);
let pending = self.stack.remove(index);
pending.view.state.set(ConstructionState::Finished);
}
}
@@ -93,21 +168,16 @@ impl CustomElementConstructionStack {
new_target: v8::Local<'_, v8::Function>,
) -> Option<PendingCustomElementConstruction<'s>> {
let index = self.stack.iter().rposition(|pending| {
let constructor = v8::Local::new(scope, &pending.constructor);
constructor.strict_equals(new_target.into())
pending.view.state.get() != ConstructionState::Finished
&& v8::Local::new(scope, &pending.constructor).strict_equals(new_target.into())
})?;
let pending = &mut self.stack[index];
let Some(wrapper) = pending.wrapper.take() else {
return Some(PendingCustomElementConstruction::AlreadyConstructed(
pending.handle,
));
};
let wrapper = v8::Local::new(scope, &wrapper);
let handle = pending.handle;
if pending.kind == PendingConstructionKind::SynchronousCreateElement {
let result = pending.view.take(scope);
pending.wrapper.take();
if pending.view.kind == PendingConstructionKind::SynchronousCreateElement {
self.stack.remove(index);
}
Some(PendingCustomElementConstruction::Wrapper(wrapper, handle))
result
}
pub(super) fn has_pending_wrapper_for(
@@ -116,36 +186,134 @@ impl CustomElementConstructionStack {
new_target: v8::Local<'_, v8::Function>,
) -> bool {
self.stack.iter().any(|pending| {
let constructor = v8::Local::new(scope, &pending.constructor);
constructor.strict_equals(new_target.into())
pending.view.state.get() != ConstructionState::Finished
&& v8::Local::new(scope, &pending.constructor).strict_equals(new_target.into())
})
}
pub(super) fn is_pending_handle(&self, handle: DomHandle) -> bool {
self.constructing_handles.contains(&handle)
}
pub(super) fn is_already_constructed(&self, handle: DomHandle) -> bool {
self.stack
.iter()
.any(|pending| pending.handle == handle && pending.wrapper.is_none())
self.stack.iter().any(|pending| {
pending.view.id.handle == handle
&& pending.view.state.get() == ConstructionState::Consumed
})
}
pub(super) fn mark_failed(&mut self, handle: DomHandle) {
self.failed_handles.insert(handle);
}
pub(super) fn clear_failed(&mut self, handle: DomHandle) {
self.failed_handles.remove(&handle);
}
pub(super) fn is_failed(&self, handle: DomHandle) -> bool {
self.failed_handles.contains(&handle)
}
pub(super) fn owns_handle(&self, handle: DomHandle) -> bool {
self.constructing_handles.contains(&handle)
|| self.failed_handles.contains(&handle)
|| self.stack.iter().any(|pending| pending.handle == handle)
|| self
.stack
.iter()
.any(|pending| pending.view.id.handle == handle)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn constructor<'s>(
_scope: &mut v8::PinScope<'s, '_>,
_args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'s>,
) {
}
#[test]
fn shared_construction_views_keep_native_ids_qualified_and_follow_nested_order() {
crate::ensure_v8_for_test();
let mut isolate = v8::Isolate::new(Default::default());
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let context = v8::Context::new(scope, Default::default());
let other_context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
let function = v8::Function::new(scope, constructor).unwrap();
let wrapper = v8::Object::new(scope);
let source_owner = NativeDomHostId::default();
let target_owner = NativeDomHostId::default();
let handle = DomHandle::new(7);
let mut source = CustomElementConstructionStack::default();
let mut target = CustomElementConstructionStack::default();
target.begin_existing_element_upgrade(
scope,
target_owner,
context,
function,
wrapper,
handle,
);
assert!(!source.has_pending_wrapper_for(scope, function));
let bindings = super::super::CustomElementRegistryBindings::for_isolate(scope);
{
let scope = &mut v8::ContextScope::new(scope, other_context);
assert!(
!bindings.has_pending_construction(scope, function),
"a foreign super constructor must not consume another realm's construction"
);
}
source.begin_existing_element_upgrade(
scope,
source_owner,
context,
function,
wrapper,
handle,
);
let Some(PendingCustomElementConstruction::Wrapper(_, id)) =
bindings.take_pending_construction(scope, function)
else {
panic!("nested source construction");
};
assert_eq!(id.owner, source_owner);
assert_eq!(id.handle, handle);
assert!(source.is_already_constructed(handle));
assert!(!target.is_already_constructed(handle));
source.discard(handle);
let Some(PendingCustomElementConstruction::Wrapper(value, id)) =
bindings.take_pending_construction(scope, function)
else {
panic!("foreign target construction");
};
assert_eq!(value, wrapper);
assert_eq!(id.owner, target_owner);
assert_eq!(id.handle, handle);
assert!(target.is_already_constructed(handle));
assert!(!source.owns_handle(handle));
assert!(matches!(
bindings.take_pending_construction(scope, function),
Some(PendingCustomElementConstruction::AlreadyConstructed(_))
));
target.discard(handle);
assert!(!bindings.has_pending_construction(scope, function));
target.begin_synchronous_create_element(
scope,
target_owner,
other_context,
function,
wrapper,
handle,
);
assert!(!bindings.has_pending_construction(scope, function));
{
let scope = &mut v8::ContextScope::new(scope, other_context);
assert!(bindings.has_pending_construction(scope, function));
assert!(matches!(
bindings.take_pending_construction(scope, function),
Some(PendingCustomElementConstruction::Wrapper(_, _))
));
}
target.discard(handle);
}
}
@@ -4,7 +4,6 @@ use super::super::{
context_bootstrap::{
dispatch_window_error_event_with_details, new_most_derived_dom_exception_value,
},
document_runtime::DomHandle,
exception_reporting::V8ExceptionReport,
host::report_event_listener_exception,
util::{set_private_value, v8_string, v8str},
@@ -12,6 +11,8 @@ use super::super::{
pub(super) const CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT: &str =
"__moliCustomElementAlreadyConstructedHandle";
pub(super) const CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT: &str =
"__moliCustomElementAlreadyConstructedOwner";
const CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_MESSAGE: &str =
"Custom element constructor already consumed this element";
@@ -96,19 +97,26 @@ fn error_message_for_value(
pub(crate) fn throw_already_constructed_custom_element_error(
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
id: super::construction::CustomElementConstructionId,
) {
let message = v8_string(scope, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_MESSAGE)
.unwrap_or_else(|| v8::String::empty(scope));
let exception = v8::Exception::type_error(scope, message);
if let Ok(object) = v8::Local::<v8::Object>::try_from(exception) {
let handle_value = v8::BigInt::new_from_u64(scope, handle.index() as u64);
let handle_value = v8::BigInt::new_from_u64(scope, id.handle.index() as u64);
set_private_value(
scope,
object,
CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT,
handle_value.into(),
);
let owner_value = v8::BigInt::new_from_u64(scope, id.owner.get());
set_private_value(
scope,
object,
CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT,
owner_value.into(),
);
}
scope.throw_exception(exception);
}
@@ -43,9 +43,10 @@ pub(super) fn create_custom_element_for_registry_key<'s>(
let wrapper = unsafe { &mut *host_ptr }
.native_bridge_mut()
.wrap_handle(scope, host_ptr, handle)?;
let construction_owner = unsafe { &*host_ptr }.custom_element_registry_owner_id();
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.begin_create_element_construction(scope, constructor, wrapper, handle);
.begin_create_element_construction(scope, construction_owner, constructor, wrapper, handle);
let initial_owner_document = unsafe { &*host_ptr }
.dom_host()
@@ -2,6 +2,7 @@ use super::super::document_runtime::DomHandle;
use super::construction::CustomElementConstructionStack;
pub(crate) use super::definition_error::CustomElementDefineError;
use crate::dom::custom_elements::is_valid_custom_element_name as is_valid_dom_custom_element_name;
use crate::native_bridge::NativeDomHostId;
use moli_dom::native::DomStringValue;
use std::{
cell::{Cell, RefCell},
@@ -51,6 +52,39 @@ pub(crate) struct CustomElementRegistryData {
pub(super) definition_is_running: Cell<bool>,
pub(super) roots: RefCell<Option<super::registry_tracing::RegistryRoots>>,
pub(super) retired: Cell<bool>,
associated_documents: RefCell<hashlink::LinkedHashMap<RegistryAssociatedDocument, ()>>,
shared_native_owners: Cell<bool>,
}
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub(crate) struct RegistryAssociatedDocument {
pub(crate) owner: NativeDomHostId,
pub(crate) document: DomHandle,
}
impl CustomElementRegistryData {
pub(crate) fn mark_shared_native_owners(&self) {
self.shared_native_owners.set(true);
}
pub(crate) fn has_shared_native_owners(&self) -> bool {
self.shared_native_owners.get()
}
pub(crate) fn associate_document(
&self,
owner: NativeDomHostId,
document: DomHandle,
retarget: bool,
) {
let key = RegistryAssociatedDocument { owner, document };
let mut documents = self.associated_documents.borrow_mut();
if retarget || !documents.contains_key(&key) {
documents.insert(key, ());
}
}
pub(crate) fn associated_documents(&self) -> Vec<RegistryAssociatedDocument> {
self.associated_documents.borrow().keys().copied().collect()
}
}
// A registry's definitions and promises can be shared by different native DOM
@@ -88,6 +122,10 @@ impl CustomElementStore {
pub(crate) fn retire_execution_state(&mut self) {
self.registry.retire();
self.retire_native_construction_state();
}
pub(crate) fn retire_native_construction_state(&mut self) {
self.construction_stack = CustomElementConstructionStack::default();
}
@@ -56,7 +56,13 @@ fn registry_data_shares_definitions_and_promises_without_sharing_native_handles(
let pending_handle = DomHandle::new(9);
let wrapper = v8::Object::new(scope);
source.begin_construction(scope, constructor, wrapper, pending_handle);
source.begin_construction(
scope,
crate::native_bridge::NativeDomHostId::default(),
constructor,
wrapper,
pending_handle,
);
assert!(source.has_pending_wrapper_for(scope, constructor));
assert!(!target.has_pending_wrapper_for(scope, constructor));
source.mark_failed_construction_handle(pending_handle);
@@ -15,23 +15,35 @@ impl CustomElementStore {
pub(crate) fn begin_construction(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
owner: crate::native_bridge::NativeDomHostId,
constructor: v8::Local<'_, v8::Function>,
wrapper: v8::Local<'_, v8::Object>,
handle: DomHandle,
) {
self.construction_stack
.begin_existing_element_upgrade(scope, constructor, wrapper, handle);
let realm = self.registry.construction_realm(scope);
self.construction_stack.begin_existing_element_upgrade(
scope,
owner,
realm,
constructor,
wrapper,
handle,
);
}
pub(crate) fn begin_create_element_construction(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
owner: crate::native_bridge::NativeDomHostId,
constructor: v8::Local<'_, v8::Function>,
wrapper: v8::Local<'_, v8::Object>,
handle: DomHandle,
) {
let realm = self.registry.construction_realm(scope);
self.construction_stack.begin_synchronous_create_element(
scope,
owner,
realm,
constructor,
wrapper,
handle,
@@ -1,13 +1,10 @@
use super::element_state::definition_name_for_handle;
use super::reactions::{CustomElementReaction, enqueue_custom_element_reaction};
use super::registry_roots::{
is_shadow_including_rooted_in_browsing_context_document, shadow_including_root_document_handle,
};
use super::registry_roots::is_shadow_including_rooted_in_browsing_context_document;
use super::traversal::shadow_including_subtree_handles;
use super::with_custom_element_reaction_scope;
use super::{CustomElementRegistryAssociation, CustomElementRegistryKey};
use crate::{document_runtime::DomHandle, native_bridge::PageScriptHost};
use std::collections::HashSet;
pub(crate) fn upgrade_existing_definition_for_child(
scope: &mut v8::PinScope<'_, '_>,
@@ -46,65 +43,64 @@ pub(crate) fn upgrade_existing_definition_for_registry(
registry_key: CustomElementRegistryKey,
definition_name: &str,
) {
let handles = matching_definition_handles_for_registry_in_upgrade_order(
host_ptr,
registry_key,
definition_name,
);
with_custom_element_reaction_scope(scope, host_ptr, |scope| {
for handle in handles {
enqueue_custom_element_reaction(
scope,
host_ptr,
handle,
CustomElementReaction::Upgrade,
);
}
});
}
fn matching_definition_handles_for_registry_in_upgrade_order(
host_ptr: *mut PageScriptHost,
registry_key: CustomElementRegistryKey,
definition_name: &str,
) -> Vec<DomHandle> {
let host = unsafe { &*host_ptr };
let target_association = CustomElementRegistryAssociation::Registry(registry_key);
let mut documents = Vec::new();
let mut seen_documents = HashSet::new();
for (handle, association) in host.custom_element_registry_associations_in_order() {
if association != target_association {
continue;
}
let Some(document) = shadow_including_root_document_handle(host.dom_host(), handle) else {
let Some(data) = host
.custom_elements_for_registry_key(registry_key)
.map(|store| store.registry_data())
else {
return;
};
let bindings = host.custom_element_registry_bindings.clone();
let mut candidates = Vec::new();
for associated in data.associated_documents() {
let Some(owner) = bindings
.as_ref()
.and_then(|bindings| bindings.host(associated.owner))
else {
continue;
};
if !is_shadow_including_rooted_in_browsing_context_document(host, document) {
let target = owner.as_ptr();
let target_host = unsafe { &*target };
if target_host.browsing_context_is_closed()
|| target_host.context_host_lifecycle_handle().get()
!= crate::util::ContextHostLifecycle::Active
|| !is_shadow_including_rooted_in_browsing_context_document(
target_host,
associated.document,
)
{
continue;
}
if seen_documents.insert(document) {
documents.push(document);
}
let handles = shadow_including_subtree_handles(target, associated.document)
.into_iter()
.filter(|handle| {
target_host.effective_custom_element_registry_association(*handle)
== CustomElementRegistryAssociation::Registry(registry_key)
})
.filter(|handle| {
definition_name_for_handle(target, *handle).as_deref() == Some(definition_name)
})
.collect::<Vec<_>>();
candidates.push((owner, handles));
}
let mut handles = Vec::new();
let mut seen_handles = HashSet::new();
for document in documents {
for handle in shadow_including_subtree_handles(host_ptr, document) {
if !seen_handles.insert(handle) {
continue;
}
if unsafe { &*host_ptr }.effective_custom_element_registry_association(handle)
!= target_association
{
continue;
}
if definition_name_for_handle(host_ptr, handle).as_deref() == Some(definition_name) {
handles.push(handle);
}
// Keep native owners pinned for this reaction turn. Their local handles
// never enter another owner's store or reaction queue.
for (owner, handles) in candidates {
let target = owner.as_ptr();
if unsafe { &*target }.browsing_context_is_closed() {
continue;
}
with_custom_element_reaction_scope(scope, target, |scope| {
for handle in handles {
enqueue_custom_element_reaction(
scope,
target,
handle,
CustomElementReaction::Upgrade,
);
}
});
}
handles
}
fn collect_matching_definition_handles(
@@ -26,9 +26,10 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
let initial_attributes =
observed_attributes_with_current_values(host_ptr, handle, definition_name);
enqueue_existing_upgrade_callbacks(scope, host_ptr, handle, initial_attributes);
let construction_owner = unsafe { &*host_ptr }.custom_element_registry_owner_id();
unsafe { &mut *host_ptr }
.custom_elements_mut_for_node_handle(handle)
.begin_construction(scope, constructor, wrapper, handle);
.begin_construction(scope, construction_owner, constructor, wrapper, handle);
let _dynamic_markup = enter_upgrade_dynamic_markup_insertion(host_ptr, handle);
let invocation = invoke_custom_element_constructor(scope, host_ptr, constructor);
match invocation {
@@ -1,4 +1,6 @@
use super::construction_failure::CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT;
use super::construction_failure::{
CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT,
};
use super::super::{
document_runtime::DomHandle, native_bridge::PageScriptHost, util::get_private_value,
@@ -14,7 +16,8 @@ pub(super) fn already_constructed_reentry_consumed_pending_handle<'s>(
) -> bool {
let host = unsafe { &*host_ptr };
let current_registry_key = host.custom_element_registry_key_for_owned_handle(handle);
already_constructed_error_handle(scope, exception) == Some(handle)
already_constructed_error_handle(scope, exception, host.custom_element_registry_owner_id())
== Some(handle)
&& host
.custom_elements_for_node_handle(handle)
.is_some_and(|store| store.pending_construction_is_already_constructed(handle))
@@ -29,8 +32,14 @@ pub(super) fn already_constructed_reentry_consumed_pending_handle<'s>(
fn already_constructed_error_handle<'s>(
scope: &mut v8::PinScope<'s, '_>,
exception: v8::Local<'s, v8::Value>,
owner: crate::native_bridge::NativeDomHostId,
) -> Option<DomHandle> {
let object = v8::Local::<v8::Object>::try_from(exception).ok()?;
let marker = get_private_value(scope, object, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT)?;
let marker = v8::Local::<v8::BigInt>::try_from(marker).ok()?.u64_value();
if marker != (owner.get(), true) {
return None;
}
let value = get_private_value(
scope,
object,
@@ -64,9 +64,10 @@ pub(super) fn construct_parser_created_custom_element_direct(
return Some(handle);
};
let construction_owner = unsafe { &*host_ptr }.custom_element_registry_owner_id();
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.begin_create_element_construction(scope, constructor, wrapper, handle);
.begin_create_element_construction(scope, construction_owner, constructor, wrapper, handle);
let initial_owner_document = unsafe { &*host_ptr }
.dom_host()
@@ -22,6 +22,9 @@ impl Drop for CustomElementReactionGuard {
impl Drop for CustomElementReactionScope<'_, '_, '_> {
fn drop(&mut self) {
unsafe { &mut *self.host_ptr }
.native_bridge_mut()
.synchronize_custom_element_registry_references(self.scope, self.host_ptr);
super::reactions::flush_current_custom_element_reaction_queue(self.scope, self.host_ptr);
}
}
@@ -80,7 +80,14 @@ fn should_preserve_same_document_registry_association(
host_ptr: *mut PageScriptHost,
root: DomHandle,
) -> bool {
let host = unsafe { &*host_ptr }.dom_host();
let runtime = unsafe { &*host_ptr };
let host = runtime.dom_host();
if host
.owner_document_handle(root)
.is_some_and(|document| runtime.document_uses_scoped_custom_element_registries(document))
{
return true;
}
host.node(root)
.and_then(Node::parent_node)
.is_some_and(|parent| {
@@ -0,0 +1,118 @@
use std::{
cell::RefCell,
collections::HashMap,
rc::{Rc, Weak},
};
use super::{CustomElementRegistryKey, definition::CustomElementRegistryData};
use crate::native_bridge::{NativeDomHostId, PageScriptHost};
struct RegistryBinding {
wrapper: v8::Weak<v8::Object>,
data: Weak<CustomElementRegistryData>,
}
/// Isolate-local discovery only. Neither the native owner nor any JS realm is
/// kept alive by this index. DOM associations own their V8-traced references.
#[derive(Default)]
pub(crate) struct CustomElementRegistryBindings {
registries: RefCell<HashMap<CustomElementRegistryKey, RegistryBinding>>,
hosts: RefCell<HashMap<NativeDomHostId, Weak<RefCell<PageScriptHost>>>>,
constructions: RefCell<Vec<Weak<super::construction::SharedPendingConstruction>>>,
}
impl CustomElementRegistryBindings {
pub(super) fn register_construction(
&self,
view: &Rc<super::construction::SharedPendingConstruction>,
) {
let mut constructions = self.constructions.borrow_mut();
constructions.retain(|view| view.strong_count() != 0);
constructions.push(Rc::downgrade(view));
}
pub(crate) fn has_pending_construction(
&self,
scope: &mut v8::PinScope<'_, '_>,
constructor: v8::Local<'_, v8::Function>,
) -> bool {
self.constructions
.borrow()
.iter()
.rev()
.filter_map(Weak::upgrade)
.any(|view| view.matches(scope, constructor))
}
pub(crate) fn take_pending_construction<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
constructor: v8::Local<'_, v8::Function>,
) -> Option<super::PendingCustomElementConstruction<'s>> {
let view = self
.constructions
.borrow()
.iter()
.rev()
.filter_map(Weak::upgrade)
.find(|view| view.matches(scope, constructor))?;
view.take(scope)
}
pub(crate) fn for_isolate(scope: &mut v8::PinScope<'_, '_>) -> Rc<Self> {
type Store = Rc<CustomElementRegistryBindings>;
if let Some(store) = scope.get_slot::<Store>() {
return store.clone();
}
let store = Store::default();
scope.set_slot(store.clone());
store
}
pub(crate) fn register_host(&self, id: NativeDomHostId, host: &Rc<RefCell<PageScriptHost>>) {
let mut hosts = self.hosts.borrow_mut();
hosts.retain(|_, owner| owner.strong_count() != 0);
hosts.insert(id, Rc::downgrade(host));
}
pub(crate) fn host(&self, id: NativeDomHostId) -> Option<Rc<RefCell<PageScriptHost>>> {
self.hosts.borrow().get(&id)?.upgrade()
}
pub(crate) fn register(
&self,
scope: &mut v8::PinScope<'_, '_>,
key: CustomElementRegistryKey,
wrapper: v8::Local<'_, v8::Object>,
data: &Rc<CustomElementRegistryData>,
) {
let mut registries = self.registries.borrow_mut();
if registries.len().is_multiple_of(64) {
registries.retain(|_, binding| {
!binding.wrapper.is_empty() && binding.data.strong_count() != 0
});
}
registries.insert(
key,
RegistryBinding {
wrapper: v8::Weak::new(scope, wrapper),
data: Rc::downgrade(data),
},
);
}
pub(crate) fn data(
&self,
key: CustomElementRegistryKey,
) -> Option<Rc<CustomElementRegistryData>> {
self.registries.borrow().get(&key)?.data.upgrade()
}
pub(crate) fn wrapper<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
key: CustomElementRegistryKey,
) -> Option<v8::Local<'s, v8::Object>> {
self.registries.borrow().get(&key)?.wrapper.to_local(scope)
}
}
@@ -73,6 +73,8 @@ pub(crate) fn bind_custom_elements_registry_data<'s>(
}
let scope = &mut v8::ContextScope::new(scope, owner);
data.bind_wrapper(scope, registry);
let bindings = super::CustomElementRegistryBindings::for_isolate(scope);
bindings.register(scope, key, registry, &data);
}
pub(crate) fn mark_scoped_custom_elements_registry(
@@ -50,6 +50,18 @@ impl CustomElementRegistryData {
set_private_value(scope, registry, ROOTS_SLOT, anchor.into());
}
pub(super) fn construction_realm<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
) -> v8::Local<'s, v8::Context> {
self.roots
.borrow()
.as_ref()
.and_then(|roots| roots.anchor.to_local(scope))
.and_then(|anchor| anchor.get_creation_context(scope))
.unwrap_or_else(|| scope.get_current_context())
}
pub(super) fn belongs_to_realm(&self, realm_token: RuntimeObservableContextToken) -> bool {
self.roots
.borrow()
@@ -608,7 +608,11 @@ impl DocumentRuntime {
) -> Option<DomHandle> {
let first_node_index = self.dom_host().dom().len();
let parser = HtmlParser::with_scripting_enabled(scripting_enabled);
let context_node = context_handle.and_then(|element| self.dom_host().node(element));
// Tokenization uses the host of a ShadowRoot, while the registry
// comes from the actual fragment context.
let parsing_context = context_handle
.map(|context| self.dom_host().shadow_root_host(context).unwrap_or(context));
let context_node = parsing_context.and_then(|element| self.dom_host().node(element));
let context_namespace = context_node
.and_then(Node::namespace)
.unwrap_or("http://www.w3.org/1999/xhtml")
@@ -618,7 +622,7 @@ impl DocumentRuntime {
.unwrap_or("body")
.to_owned();
let context =
HtmlFragmentContext::new(context_handle, &context_namespace, &context_local_name);
HtmlFragmentContext::new(parsing_context, &context_namespace, &context_local_name);
let is_frameset_context = context_namespace == "http://www.w3.org/1999/xhtml"
&& context_local_name.eq_ignore_ascii_case("frameset");
let registry_association = match context_handle {
@@ -796,7 +800,11 @@ impl DocumentRuntime {
markup: &DomStringValue,
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
) -> Result<Option<DomHandle>, XmlFragmentParseError> {
let parsed = XmlParser.parse_fragment(self.dom_host(), context_handle, markup)?;
let parsing_context = self
.dom_host()
.shadow_root_host(context_handle)
.unwrap_or(context_handle);
let parsed = XmlParser.parse_fragment(self.dom_host(), parsing_context, markup)?;
let first_node_index = self.dom_host().dom().len();
let registry_association =
self.fragment_context_custom_element_registry_association(host_ptr, context_handle);
@@ -904,7 +912,7 @@ impl DocumentRuntime {
handle: DomHandle,
html: &DomStringValue,
) -> Result<bool, XmlFragmentParseError> {
let context = self.dom_host().shadow_root_host(handle).unwrap_or(handle);
let context = handle;
let target = self
.dom_host()
.node(handle)
@@ -1104,6 +1112,8 @@ impl DocumentRuntime {
DomHandle,
) -> bool,
) -> Result<bool, XmlFragmentParseError> {
let registry_association =
self.fragment_context_custom_element_registry_association(host_ptr, context_handle);
let context_is_element = self
.dom_host()
.node(context_handle)
@@ -1117,7 +1127,13 @@ impl DocumentRuntime {
.node(context_handle)
.is_some_and(|node| node.is_html_element_named("html"));
let context_handle = if !context_is_element || context_is_html_root {
self.create_fragment_body_context(document_handle)
let body = self.create_fragment_body_context(document_handle);
self.set_fragment_root_custom_element_registry_association(
host_ptr,
body,
registry_association,
);
body
} else {
context_handle
};
@@ -41,6 +41,15 @@ impl NativeDomBridge {
self.wrap_bridge_handle(scope, host_ptr, BridgeHandle::Node(handle))
}
pub(crate) fn synchronize_custom_element_registry_references(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
) {
self.identity
.synchronize_registry_references(scope, host_ptr);
}
pub(crate) fn cached_handle_wrapper<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
@@ -74,7 +83,14 @@ impl NativeDomBridge {
host_ptr: *mut PageScriptHost,
handle: BridgeHandle,
) -> Option<v8::Local<'s, v8::Object>> {
self.materialize_bridge_wrapper(scope, host_ptr, handle, BridgeWrapperIdentity::Canonical)
let result = self.materialize_bridge_wrapper(
scope,
host_ptr,
handle,
BridgeWrapperIdentity::Canonical,
);
self.synchronize_custom_element_registry_references(scope, host_ptr);
result
}
fn materialize_bridge_wrapper<'s, 'i>(
@@ -80,6 +80,12 @@ impl PageScriptHost {
global: v8::Local<'s, v8::Object>,
) -> Result<PageScriptHostBridgeRef> {
let host_ptr: *mut PageScriptHost = (*host_rc).as_ptr();
let bindings = crate::custom_elements::CustomElementRegistryBindings::for_isolate(scope);
bindings.register_host(
unsafe { &*host_ptr }.custom_element_registry_owner_id(),
host_rc,
);
unsafe { &mut *host_ptr }.custom_element_registry_bindings = Some(bindings);
#[cfg(test)]
let bridge_ref_count = unsafe { &*host_ptr }.bridge_ref_count.clone();
#[cfg(not(test))]
@@ -422,10 +422,14 @@ impl PageScriptHost {
child_custom_elements: HashMap::new(),
scoped_custom_elements: HashMap::new(),
foreign_custom_elements: HashMap::new(),
custom_element_registry_bindings: None,
custom_element_registry_references_enabled: Cell::new(false),
custom_element_registry_references_version: Cell::new(None),
parser_defined_autonomous_custom_elements: VecDeque::new(),
parser_custom_element_handoff_replacements: HashMap::new(),
scoped_custom_element_registry_wrappers: HashMap::new(),
custom_element_registry_associations: LinkedHashMap::new(),
scoped_custom_element_registry_documents: HashSet::new(),
next_scoped_custom_elements_registry_id: 1,
observers: ObserverStore::default(),
child_browsing_contexts: IndexMap::new(),
@@ -2156,9 +2160,30 @@ impl PageScriptHost {
if id.is_multiple_of(64) {
self.compact_scoped_custom_element_registry_wrappers();
}
let document = self
.current_runtime_window_execution_context_identity(scope)
.and_then(|identity| match identity.dispatch_scope() {
OwnerDispatchScope::Child(handle) => {
self.child_browsing_context_document_handle(handle)
}
OwnerDispatchScope::Top | OwnerDispatchScope::LightweightPopup(_) => {
Some(self.document_handle())
}
})
.unwrap_or_else(|| self.document_handle());
self.scoped_custom_element_registry_documents
.insert(document);
Some(id)
}
pub(crate) fn document_uses_scoped_custom_element_registries(
&self,
document: DomHandle,
) -> bool {
self.scoped_custom_element_registry_documents
.contains(&document)
}
fn compact_scoped_custom_element_registry_wrappers(&mut self) {
self.scoped_custom_element_registry_wrappers
.retain(|_, registry| !registry.is_empty());
@@ -2172,6 +2197,61 @@ impl PageScriptHost {
self.scoped_custom_elements.remove(&id);
}
fn bind_custom_element_registry_association(
&mut self,
handle: DomHandle,
association: CustomElementRegistryAssociation,
retarget: bool,
) {
let CustomElementRegistryAssociation::Registry(key) = association else {
return;
};
let document = if self
.dom_host()
.node(handle)
.is_some_and(|node| node.is_document())
{
handle
} else {
let Some(document) = self.dom_host().owner_document_handle(handle) else {
return;
};
document
};
if key.is_scoped()
&& self
.dom_host()
.node(handle)
.is_some_and(|node| node.is_element())
&& association
!= self.default_custom_element_registry_association_for_document(document)
{
self.scoped_custom_element_registry_documents
.insert(document);
}
let owner = self.custom_element_registry_owner_id();
let data = self
.custom_elements_mut_for_registry_key(key)
.registry_data();
data.associate_document(owner, document, retarget);
if key.owner() != owner {
data.mark_shared_native_owners();
if let Some(source) = self
.custom_element_registry_bindings
.as_ref()
.and_then(|bindings| bindings.host(key.owner()))
{
let source = unsafe { &*source.as_ptr() };
source.custom_element_registry_references_enabled.set(true);
source.custom_element_registry_references_version.set(None);
}
}
if data.has_shared_native_owners() {
self.custom_element_registry_references_enabled.set(true);
}
self.custom_element_registry_references_version.set(None);
}
pub(crate) fn set_custom_element_registry_association(
&mut self,
handle: DomHandle,
@@ -2180,6 +2260,7 @@ impl PageScriptHost {
if self.custom_element_registry_associations.get(&handle) == Some(&association) {
return;
}
self.bind_custom_element_registry_association(handle, association, false);
self.custom_element_registry_associations
.insert(handle, association);
}
@@ -2194,6 +2275,11 @@ impl PageScriptHost {
// LinkedHashMap::insert moves existing entries to the back in O(1),
// preserving last-retarget order without scanning unrelated entries.
for retarget in retargets {
self.bind_custom_element_registry_association(
retarget.handle,
retarget.association,
true,
);
self.custom_element_registry_associations
.insert(retarget.handle, retarget.association);
}
@@ -2220,10 +2306,15 @@ impl PageScriptHost {
&mut self,
child_handle: DomHandle,
) {
self.custom_element_registry_references_version.set(None);
let document_handle = self
.child_browsing_context_document_handles
.get(&child_handle)
.copied();
if let Some(document) = document_handle {
self.scoped_custom_element_registry_documents
.remove(&document);
}
let stale_handles = self
.custom_element_registry_associations
.iter()
@@ -2258,6 +2349,9 @@ impl PageScriptHost {
&mut self,
document_handle: DomHandle,
) {
self.scoped_custom_element_registry_documents
.remove(&document_handle);
self.custom_element_registry_references_version.set(None);
let stale_handles = self
.custom_element_registry_associations
.keys()
@@ -2455,7 +2549,10 @@ impl PageScriptHost {
key: CustomElementRegistryKey,
) -> Option<v8::Local<'s, v8::Object>> {
if key.owner() != self.custom_element_registry_owner_id() {
return None;
return self
.custom_element_registry_bindings
.as_ref()?
.wrapper(scope, key);
}
match key.kind() {
CustomElementRegistryKind::Global => {
@@ -2522,7 +2619,14 @@ impl PageScriptHost {
key: CustomElementRegistryKey,
) -> &mut CustomElementStore {
if key.owner() != self.custom_element_registry_owner_id() {
return self.foreign_custom_elements.entry(key).or_default();
let data = self
.custom_element_registry_bindings
.as_ref()
.and_then(|bindings| bindings.data(key));
return self.foreign_custom_elements.entry(key).or_insert_with(|| {
data.map(CustomElementStore::for_registry)
.unwrap_or_default()
});
}
match key.kind() {
CustomElementRegistryKind::Global => &mut self.custom_elements,
@@ -2740,6 +2844,9 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'s, '_>,
new_target: v8::Local<'_, v8::Function>,
) -> Option<crate::custom_elements::PendingCustomElementConstruction<'s>> {
if let Some(bindings) = &self.custom_element_registry_bindings {
return bindings.take_pending_construction(scope, new_target);
}
self.custom_element_store_entries_mut()
.find_map(|store| store.take_pending_wrapper_for(scope, new_target))
}
@@ -2749,6 +2856,9 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'_, '_>,
new_target: v8::Local<'_, v8::Function>,
) -> bool {
if let Some(bindings) = &self.custom_element_registry_bindings {
return bindings.has_pending_construction(scope, new_target);
}
if self
.custom_elements
.has_pending_wrapper_for(scope, new_target)
@@ -937,6 +937,10 @@ pub(crate) struct PageScriptHost {
child_custom_elements: HashMap<DomHandle, CustomElementStore>,
scoped_custom_elements: HashMap<u32, CustomElementStore>,
foreign_custom_elements: HashMap<CustomElementRegistryKey, CustomElementStore>,
pub(crate) custom_element_registry_bindings:
Option<Rc<crate::custom_elements::CustomElementRegistryBindings>>,
pub(in crate::native_bridge) custom_element_registry_references_enabled: Cell<bool>,
pub(in crate::native_bridge) custom_element_registry_references_version: Cell<Option<u64>>,
parser_defined_autonomous_custom_elements: VecDeque<String>,
// Parser-created direct construction leaves html5ever's open-stack
// placeholder alive but detached. The runtime-visible element is the
@@ -944,6 +948,7 @@ pub(crate) struct PageScriptHost {
// that result before the next script observes the DOM.
parser_custom_element_handoff_replacements: HashMap<DomHandle, DomHandle>,
scoped_custom_element_registry_wrappers: HashMap<u32, v8::Weak<v8::Object>>,
scoped_custom_element_registry_documents: HashSet<DomHandle>,
custom_element_registry_associations:
LinkedHashMap<DomHandle, CustomElementRegistryAssociation>,
next_scoped_custom_elements_registry_id: u32,
@@ -225,10 +225,12 @@ impl PageScriptHost {
for store in std::iter::once(&mut self.custom_elements)
.chain(self.child_custom_elements.values_mut())
.chain(self.scoped_custom_elements.values_mut())
.chain(self.foreign_custom_elements.values_mut())
{
store.retire_execution_state();
}
for store in self.foreign_custom_elements.values_mut() {
store.retire_native_construction_state();
}
drop(std::mem::take(&mut self.custom_element_reactions));
drop(std::mem::take(&mut self.observers));
drop(std::mem::take(&mut self.child_window_proxy_records));
@@ -20,6 +20,7 @@ use dense_reflector_map::DenseReflectorMap;
mod dense_reflector_map;
mod node_ownership;
mod registry_references;
#[cfg(test)]
mod wrapper_cache_tests;
pub(in crate::native_bridge) use node_ownership::resolve_object_node_ownership;
@@ -582,6 +583,12 @@ struct IsolatedWorldWrapperCaches {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct NativeDomHostId(NonZeroU64);
impl NativeDomHostId {
pub(crate) fn get(self) -> u64 {
self.0.get()
}
}
impl Default for NativeDomHostId {
fn default() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(1);
@@ -6,6 +6,8 @@ use crate::{document_runtime::DomHandle, util};
const ANCHOR_SLOT: &str = "__moliNativeNodeOwnership";
const OWNER_SLOT: &str = "__moliNativeNodeCurrentOwner";
const HANDLE_SLOT: &str = "__moliNativeNodeCurrentHandle";
const DOCUMENT_SLOT: &str = "__moliNativeNodeOwnerDocument";
const REGISTRIES_SLOT: &str = "__moliNativeNodeRegistryReferences";
pub(in crate::native_bridge) fn resolve_object_node_ownership(
scope: &mut v8::PinScope<'_, '_>,
@@ -43,6 +45,38 @@ struct NodeLocation {
}
impl NodeOwnership {
pub(super) fn existing_anchor<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
) -> Option<v8::Local<'s, v8::Object>> {
self.location.borrow().anchor.to_local(scope)
}
pub(super) fn trace_document(&self, scope: &mut v8::PinScope<'_, '_>, document: &Self) {
let anchor = self
.anchor(scope)
.expect("live node has an ownership anchor");
let document = document
.anchor(scope)
.expect("live Document has an ownership anchor");
util::set_private_value(scope, anchor, DOCUMENT_SLOT, document.into());
}
pub(super) fn trace_registries(
&self,
scope: &mut v8::PinScope<'_, '_>,
values: &[v8::Local<'_, v8::Value>],
) {
let Some(anchor) = self.existing_anchor(scope) else {
return;
};
let value = if values.is_empty() {
v8::undefined(scope).into()
} else {
v8::Array::new_with_elements(scope, values).into()
};
util::set_private_value(scope, anchor, REGISTRIES_SLOT, value);
}
fn new(
scope: &mut v8::PinScope<'_, '_>,
owner: v8::Local<'_, v8::Context>,
@@ -85,6 +119,39 @@ impl NodeOwnership {
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);
let handle = location.handle;
drop(location);
if let Some(host) = util::context_host_ptr_from_context_slot(owner) {
unsafe { &*host }
.custom_element_registry_references_version
.set(None);
if unsafe { &*host }
.custom_element_registry_references_enabled
.get()
{
let document = unsafe { &*host }
.dom_host()
.owner_document_handle(handle)
.filter(|document| *document != handle)
.and_then(|document| {
unsafe { &*host }
.bridge
.identity
.node_ownership
.get(&document)
.cloned()
});
if let Some(document) = document.and_then(|document| document.anchor(scope)) {
util::set_private_value(scope, anchor, DOCUMENT_SLOT, document.into());
}
let values =
super::registry_references::registry_values_for_subtree(scope, host, handle);
if !values.is_empty() {
let values = v8::Array::new_with_elements(scope, &values);
util::set_private_value(scope, anchor, REGISTRIES_SLOT, values.into());
}
}
}
Some(anchor)
}
@@ -109,6 +176,19 @@ impl NodeOwnership {
// 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) {
// The new native tree determines registry and Document edges.
// Do not retain the previous Document through a transferred view.
if util::get_private_object(scope, anchor, DOCUMENT_SLOT).is_some()
|| util::get_private_object(scope, anchor, REGISTRIES_SLOT).is_some()
{
util::set_private_value(scope, anchor, DOCUMENT_SLOT, v8::undefined(scope).into());
util::set_private_value(
scope,
anchor,
REGISTRIES_SLOT,
v8::undefined(scope).into(),
);
}
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());
@@ -227,6 +307,10 @@ impl BridgeIdentityStore {
*descriptor.resolution_cache.0.borrow_mut() = None;
}
}
unsafe { &*source_host }
.custom_element_registry_references_version
.set(None);
source.synchronize_registry_references(scope, source_host);
}
pub(in crate::native_bridge) fn node_ownership(
@@ -244,6 +328,20 @@ impl BridgeIdentityStore {
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());
if unsafe { &*host }
.custom_element_registry_references_enabled
.get()
{
if let Some(document) = unsafe { &*host }.dom_host().owner_document_handle(handle)
&& document != handle
{
let document = self.node_ownership(scope, host, document);
ownership.trace_document(scope, &document);
}
let values =
super::registry_references::registry_values_for_subtree(scope, host, handle);
ownership.trace_registries(scope, &values);
}
ownership
}
@@ -0,0 +1,135 @@
use std::collections::{HashMap, HashSet};
use super::{BridgeIdentityStore, PageScriptHost};
use crate::{
custom_elements::{CustomElementRegistryAssociation, CustomElementRegistryKey},
document_runtime::DomHandle,
};
fn registry_for_node(host: &PageScriptHost, node: DomHandle) -> Option<CustomElementRegistryKey> {
let CustomElementRegistryAssociation::Registry(key) =
host.effective_custom_element_registry_association(node)
else {
return None;
};
host.custom_elements_for_registry_key(key)
.is_some_and(|store| store.registry_data().has_shared_native_owners())
.then_some(key)
}
fn parent(host: &PageScriptHost, node: DomHandle) -> Option<DomHandle> {
host.dom_host()
.node(node)
.and_then(|node| node.parent_node())
.or_else(|| host.dom_host().shadow_root_host(node))
}
pub(super) fn registry_values_for_subtree<'s>(
scope: &mut v8::PinScope<'s, '_>,
host: *mut PageScriptHost,
root: DomHandle,
) -> Vec<v8::Local<'s, v8::Value>> {
let host = unsafe { &*host };
let Some(bindings) = &host.custom_element_registry_bindings else {
return Vec::new();
};
let mut keys = HashSet::new();
if let Some(key) = registry_for_node(host, root) {
keys.insert(key);
}
for (handle, _) in host.custom_element_registry_associations_in_order() {
let Some(key) = registry_for_node(host, handle) else {
continue;
};
let mut current = Some(handle);
while let Some(handle) = current {
if handle == root {
keys.insert(key);
break;
}
current = parent(host, handle);
}
}
keys.into_iter()
.filter_map(|key| bindings.wrapper(scope, key).map(Into::into))
.collect()
}
impl BridgeIdentityStore {
/// Mirrors only registry references into the V8 graph. Connected trees
/// trace through their Document anchor; detached subtrees through retained
/// ancestor/node anchors. The native index and ownership records stay weak.
pub(in crate::native_bridge) fn synchronize_registry_references(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
) {
let host = unsafe { &*host_ptr };
if !host.custom_element_registry_references_enabled.get() {
return;
}
let version = host.dom_host().query_version();
if host.custom_element_registry_references_version.get() == Some(version) {
return;
}
host.custom_element_registry_references_version
.set(Some(version));
let Some(bindings) = host.custom_element_registry_bindings.clone() else {
return;
};
let associations = host
.custom_element_registry_associations_in_order()
.collect::<Vec<_>>();
let mut nodes = self
.node_ownership
.iter()
.map(|(&handle, ownership)| (handle, ownership.clone()))
.collect::<Vec<_>>();
let mut roots: HashMap<DomHandle, HashSet<CustomElementRegistryKey>> = HashMap::new();
// A retained non-element also traces its owner Document and the
// registry of its containing shadow tree.
for (handle, ownership) in &nodes {
if ownership.existing_anchor(scope).is_none() {
continue;
}
if let Some(key) = registry_for_node(host, *handle) {
roots.entry(*handle).or_default().insert(key);
}
if let Some(document) = host.dom_host().owner_document_handle(*handle)
&& document != *handle
{
let document = self.node_ownership(scope, host_ptr, document);
ownership.trace_document(scope, &document);
}
}
// Include Document records first materialized by the loop above.
nodes = self
.node_ownership
.iter()
.map(|(&handle, ownership)| (handle, ownership.clone()))
.collect();
for (handle, _) in associations {
let Some(key) = registry_for_node(host, handle) else {
continue;
};
let mut current = Some(handle);
while let Some(handle) = current {
if self.node_ownership.contains_key(&handle) {
roots.entry(handle).or_default().insert(key);
}
current = parent(host, handle);
}
}
for (handle, ownership) in nodes {
let values = roots
.remove(&handle)
.into_iter()
.flatten()
.filter_map(|key| bindings.wrapper(scope, key).map(Into::into))
.collect::<Vec<_>>();
ownership.trace_registries(scope, &values);
}
host.custom_element_registry_references_version
.set(Some(version));
}
}
@@ -4,6 +4,263 @@ mod split30_registry_native_owner;
use super::*;
use crate::RendererPopupActivationSource;
#[tokio::test]
async fn cross_owner_construction_matches_registry_window_with_implicit_associations() {
let runtime = JsRuntime::initialize();
runtime
.browser_context_runtime()
.delegate_auxiliary_document_responses_to_browser();
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut page = create_test_html_page_with_navigation_dispatch(
&runtime,
&loader,
url::Url::parse("https://registry-realms.test/").unwrap(),
"<!doctype html><body></body>",
RendererTopLevelNavigationDispatch::DelegateToBrowser,
)
.await;
let (reply, _) = page
.run_async_command(RendererPageCommand::EvaluateExpression {
expression: include_str!("custom_element_registry_cross_owner_realms.js").to_owned(),
await_promise: true,
})
.await
.unwrap();
let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else {
panic!("cross-owner realm matrix must return all observations");
};
let facts: serde_json::Value = serde_json::from_str(&result).unwrap();
let expected = serde_json::json!([
{
"case": "main-registry-main-super",
"upgraded": true,
"created": true,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 2,
"exception": null
},
{
"case": "main-registry-popup-super",
"upgraded": false,
"created": false,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 0,
"exception": null
},
{
"case": "popup-registry-main-super",
"upgraded": false,
"created": false,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 0,
"exception": null
},
{
"case": "popup-registry-popup-super",
"upgraded": false,
"created": true,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 1,
"exception": null
}
]);
assert_eq!(facts["rows"], expected);
page.close_async().await.unwrap();
}
#[tokio::test]
async fn cross_owner_construction_matches_registry_window_with_explicit_associations() {
let runtime = JsRuntime::initialize();
runtime
.browser_context_runtime()
.delegate_auxiliary_document_responses_to_browser();
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut page = create_test_html_page_with_navigation_dispatch(
&runtime,
&loader,
url::Url::parse("https://registry-realms.test/").unwrap(),
"<!doctype html><body></body>",
RendererTopLevelNavigationDispatch::DelegateToBrowser,
)
.await;
let (reply, _) = page
.run_async_command(RendererPageCommand::EvaluateExpression {
expression: include_str!("custom_element_registry_cross_owner_explicit_realms.js")
.to_owned(),
await_promise: true,
})
.await
.unwrap();
let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else {
panic!("cross-owner realm matrix must return all observations");
};
let facts: serde_json::Value = serde_json::from_str(&result).unwrap();
let expected = serde_json::json!([
{
"case": "main-registry-main-super",
"upgraded": true,
"created": true,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 2,
"exception": null,
"association": true
},
{
"case": "main-registry-popup-super",
"upgraded": false,
"created": false,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 0,
"exception": null,
"association": true
},
{
"case": "popup-registry-main-super",
"upgraded": false,
"created": false,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 0,
"exception": null,
"association": true
},
{
"case": "popup-registry-popup-super",
"upgraded": true,
"created": true,
"existingOwner": true,
"createdOwner": true,
"constructorCalls": 2,
"exception": null,
"association": true
}
]);
assert_eq!(facts["rows"], expected);
page.close_async().await.unwrap();
}
#[cfg(feature = "devtools")]
#[tokio::test]
async fn cross_owner_registry_references_follow_retained_documents_and_detached_trees() {
let runtime = JsRuntime::initialize();
runtime
.browser_context_runtime()
.delegate_auxiliary_document_responses_to_browser();
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut page = create_test_html_page_with_navigation_dispatch(
&runtime,
&loader,
url::Url::parse("https://cross-owner-registry-gc.test/").unwrap(),
"<!doctype html><body></body>",
RendererTopLevelNavigationDispatch::DelegateToBrowser,
)
.await;
page.run_async_command(RendererPageCommand::EvaluateExpression {
expression: include_str!("custom_element_registry_cross_owner_gc.js").to_owned(),
await_promise: false,
})
.await
.unwrap();
for detached in [false, true] {
page.run_async_command(RendererPageCommand::EvaluateExpression {
expression: format!("crossOwnerRegistryGc.setup({detached})"),
await_promise: true,
})
.await
.unwrap();
page.run_async_command(RendererPageCommand::DevTools(
RendererDevToolsPageCommand::RuntimeCollectGarbage,
))
.await
.unwrap();
let (reply, _) = page
.run_async_command(RendererPageCommand::EvaluateExpression {
expression: "crossOwnerRegistryGc.retained()".to_owned(),
await_promise: false,
})
.await
.unwrap();
assert_eq!(
renderer_json_value(reply),
Some(serde_json::Value::String(
r#"{"alive":true,"identity":true}"#.to_owned()
)),
"detached={detached}"
);
page.run_async_command(RendererPageCommand::EvaluateExpression {
expression: "crossOwnerRegistryGc.release()".to_owned(),
await_promise: true,
})
.await
.unwrap();
page.run_async_command(RendererPageCommand::DevTools(
RendererDevToolsPageCommand::RuntimeCollectGarbage,
))
.await
.unwrap();
let (reply, _) = page
.run_async_command(RendererPageCommand::EvaluateExpression {
expression: "crossOwnerRegistryGc.collected()".to_owned(),
await_promise: false,
})
.await
.unwrap();
assert_eq!(
renderer_json_value(reply),
Some(serde_json::Value::Bool(true)),
"released detached={detached}"
);
}
page.close_async().await.unwrap();
}
#[tokio::test]
async fn scoped_registry_upgrades_and_creates_elements_in_another_native_owner() {
let runtime = JsRuntime::initialize();
runtime
.browser_context_runtime()
.delegate_auxiliary_document_responses_to_browser();
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut page = create_test_html_page_with_navigation_dispatch(
&runtime,
&loader,
url::Url::parse("https://cross-owner-registry.test/").unwrap(),
"<!doctype html><body></body>",
RendererTopLevelNavigationDispatch::DelegateToBrowser,
)
.await;
let (reply, _) = page
.run_async_command(RendererPageCommand::EvaluateExpression {
expression: include_str!("custom_element_registry_cross_owner.js").to_owned(),
await_promise: true,
})
.await
.unwrap();
let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else {
panic!("cross-owner registry probe must return all observations");
};
let facts: serde_json::Value = serde_json::from_str(&result).unwrap();
let rows = facts["rows"].as_array().unwrap();
assert_eq!(rows.len(), 4);
for row in rows {
for (name, value) in row.as_object().unwrap() {
match name.as_str() {
"case" => {}
"constructorCalls" => assert_eq!(value, 1, "{row}"),
"totalConstructorCalls" => assert_eq!(value, 2, "{row}"),
_ => assert_eq!(value, true, "{row}: {name}"),
}
}
}
page.close_async().await.unwrap();
}
#[tokio::test]
async fn retained_popup_registries_preserve_definitions_without_resuming_definition_installation() {
let runtime = JsRuntime::initialize();
@@ -0,0 +1,45 @@
(async () => {
const popup = open('about:blank');
const rows = [];
const registry = new CustomElementRegistry();
const doc = popup.document;
const host = doc.createElement('div');
const root = host.attachShadow({mode: 'open', customElementRegistry: registry});
const name = 'cross-popup-late-upgrade';
const node = doc.createElement(name);
root.append(node);
doc.body.append(host);
const calls = [];
class Element extends HTMLElement {
constructor() { super(); calls.push(this.ownerDocument === doc); }
}
try {
rows.push({case: 'association', rootRegistry: root.customElementRegistry === registry,
inheritedRegistry: node.customElementRegistry === registry,
ownerDocument: node.ownerDocument === doc});
registry.define(name, Element);
rows.push({case: 'late-upgrade', instance: node instanceof Element,
ownerDocument: node.ownerDocument === doc,
constructorCalls: calls.length, correctDocuments: calls.every(Boolean),
sourceLookup: registry.get(name) === Element});
const created = doc.createElement(name, {customElementRegistry: registry});
root.append(created);
rows.push({case: 'create', instance: created instanceof Element,
ownerDocument: created.ownerDocument === doc,
registry: created.customElementRegistry === registry,
totalConstructorCalls: calls.length, correctDocuments: calls.every(Boolean)});
popup.close();
await new Promise(resolve => setTimeout(resolve, 500));
class AfterClose extends HTMLElement {}
const afterName = 'cross-popup-source-still-active';
let resolved;
registry.whenDefined(afterName).then(value => { resolved = value; });
registry.define(afterName, AfterClose);
await Promise.resolve();
rows.push({case: 'target-retirement', oldDefinition: registry.get(name) === Element,
newDefinition: registry.get(afterName) === AfterClose,
whenDefined: resolved === AfterClose,
rootRegistry: root.customElementRegistry === registry});
return JSON.stringify({rows});
} finally { popup.close(); }
})()
@@ -0,0 +1,39 @@
(async () => {
const rows = [];
for (const registryRealm of ['main', 'popup']) {
for (const superRealm of ['main', 'popup']) {
const popup = open('about:blank');
try {
popup.addEventListener('error', event => event.preventDefault());
const owner = registryRealm === 'main' ? window : popup;
const target = registryRealm === 'main' ? popup : window;
const doc = target.document;
const registry = new owner.CustomElementRegistry();
const base = superRealm === 'main' ? HTMLElement : popup.HTMLElement;
const name = `cross-super-${registryRealm}-${superRealm}`;
let calls = 0;
const Constructor = class extends base {
constructor() { super(); ++calls; }
};
const host = doc.createElement('div');
const shadow = host.attachShadow({mode: 'open', customElementRegistry: registry});
const existing = doc.createElement(name, {customElementRegistry: registry});
shadow.append(existing);
doc.body.append(host);
registry.define(name, Constructor);
let created;
let exception = null;
try { created = doc.createElement(name, {customElementRegistry: registry}); }
catch (error) { exception = error.name; }
rows.push({case: `${registryRealm}-registry-${superRealm}-super`,
upgraded: existing instanceof Constructor,
created: created instanceof Constructor,
existingOwner: existing.ownerDocument === doc,
createdOwner: created?.ownerDocument === doc,
constructorCalls: calls, association: existing.customElementRegistry === registry, exception});
host.remove();
} finally { popup.close(); }
}
}
return JSON.stringify({rows});
})()
@@ -0,0 +1,34 @@
(() => {
let state;
globalThis.crossOwnerRegistryGc = {
async setup(detached) {
const popup = open('about:blank');
const doc = popup.document;
const registry = new CustomElementRegistry();
const host = doc.createElement('div');
host.attachShadow({mode: 'open', customElementRegistry: registry});
doc.body.append(host);
state = {popup, retained: detached ? host : doc, reference: new WeakRef(registry), detached};
if (detached) {
host.remove();
popup.close();
await new Promise(resolve => setTimeout(resolve, 500));
}
return 'ready';
},
retained() {
const registry = state.reference.deref();
const host = state.detached ? state.retained : state.retained.body.firstElementChild;
return JSON.stringify({alive: registry !== undefined,
identity: registry !== undefined && host.shadowRoot.customElementRegistry === registry});
},
release() {
state.popup.close();
state.popup = null;
state.retained = null;
return new Promise(resolve => setTimeout(resolve, 500));
},
collected() { return state.reference.deref() === undefined; },
};
return 'ready';
})()
@@ -0,0 +1,39 @@
(async () => {
const rows = [];
for (const registryRealm of ['main', 'popup']) {
for (const superRealm of ['main', 'popup']) {
const popup = open('about:blank');
try {
popup.addEventListener('error', event => event.preventDefault());
const owner = registryRealm === 'main' ? window : popup;
const target = registryRealm === 'main' ? popup : window;
const doc = target.document;
const registry = new owner.CustomElementRegistry();
const base = superRealm === 'main' ? HTMLElement : popup.HTMLElement;
const name = `cross-super-${registryRealm}-${superRealm}`;
let calls = 0;
const Constructor = class extends base {
constructor() { super(); ++calls; }
};
const host = doc.createElement('div');
const shadow = host.attachShadow({mode: 'open', customElementRegistry: registry});
const existing = doc.createElement(name);
shadow.append(existing);
doc.body.append(host);
registry.define(name, Constructor);
let created;
let exception = null;
try { created = doc.createElement(name, {customElementRegistry: registry}); }
catch (error) { exception = error.name; }
rows.push({case: `${registryRealm}-registry-${superRealm}-super`,
upgraded: existing instanceof Constructor,
created: created instanceof Constructor,
existingOwner: existing.ownerDocument === doc,
createdOwner: created?.ownerDocument === doc,
constructorCalls: calls, exception});
host.remove();
} finally { popup.close(); }
}
}
return JSON.stringify({rows});
})()
@@ -209,7 +209,7 @@ fn fragment_html_uses_context_custom_element_registry_association() {
mode: "open",
customElementRegistry: null
});
const nullContainer = document.createElement("div");
const nullContainer = document.createElement("div", { customElementRegistry: null });
nullShadow.appendChild(nullContainer);
nullContainer.innerHTML =
"<wpt-fragment-null id='null-root'>" +
@@ -1474,7 +1474,7 @@ fn attach_shadow_default_registry_uses_owner_document_default() {
const nullRoot = document
.createElement("wpt-null-host")
.attachShadow({ mode: "open", customElementRegistry: null });
const nestedHost = document.createElement("wpt-nested-host");
const nestedHost = document.createElement("wpt-nested-host", { customElementRegistry: null });
nullRoot.appendChild(nestedHost);
const nestedDefaultRoot = nestedHost.attachShadow({ mode: "open" });
@@ -1513,16 +1513,16 @@ fn removing_from_shadow_tree_preserves_non_default_registry_association() {
const scopedRoot = document
.createElement("wpt-scoped-root")
.attachShadow({ mode: "open", customElementRegistry: registry });
const scopedWrapper = document.createElement("div");
const scopedChild = document.createElement("wpt-scoped-child");
const scopedWrapper = document.createElement("div", { customElementRegistry: registry });
const scopedChild = document.createElement("wpt-scoped-child", { customElementRegistry: registry });
scopedWrapper.appendChild(scopedChild);
scopedRoot.appendChild(scopedWrapper);
const nullRoot = document
.createElement("wpt-null-root")
.attachShadow({ mode: "open", customElementRegistry: null });
const nullWrapper = document.createElement("section");
const nullChild = document.createElement("wpt-null-child");
const nullWrapper = document.createElement("section", { customElementRegistry: null });
const nullChild = document.createElement("wpt-null-child", { customElementRegistry: null });
nullWrapper.appendChild(nullChild);
nullRoot.appendChild(nullWrapper);