mirror of
https://github.com/lexmount/moli.git
synced 2026-11-23 16:02:35 +00:00
fix(dom): preserve registry data on realm retirement
This commit is contained in:
@@ -138,6 +138,11 @@ pub(in crate::context_bootstrap) fn custom_elements_registry_constructor_callbac
|
||||
return;
|
||||
};
|
||||
custom_elements::mark_scoped_custom_elements_registry(scope, registry, scoped_id);
|
||||
let key = custom_elements::CustomElementRegistryKey::scoped(
|
||||
unsafe { &*host_ptr }.custom_element_registry_owner_id(),
|
||||
scoped_id,
|
||||
);
|
||||
custom_elements::bind_custom_elements_registry_data(scope, registry, host_ptr, key);
|
||||
rv.set(registry.into());
|
||||
}
|
||||
|
||||
@@ -161,6 +166,7 @@ pub(in crate::context_bootstrap) fn custom_elements_define_callback<'s>(
|
||||
let Some(registry_key) = custom_elements::registry_store_key(scope, args.this()) else {
|
||||
return;
|
||||
};
|
||||
custom_elements::bind_custom_elements_registry_data(scope, args.this(), host_ptr, registry_key);
|
||||
let disables_shadow = match custom_elements::define_custom_element_for_registry(
|
||||
scope,
|
||||
host_ptr,
|
||||
@@ -169,7 +175,8 @@ pub(in crate::context_bootstrap) fn custom_elements_define_callback<'s>(
|
||||
parsed.constructor,
|
||||
extends_local_name,
|
||||
) {
|
||||
Ok(disables_shadow) => disables_shadow,
|
||||
Ok(Some(disables_shadow)) => disables_shadow,
|
||||
Ok(None) => return,
|
||||
Err(err) => {
|
||||
if err.is_pending_exception() {
|
||||
return;
|
||||
@@ -427,6 +434,7 @@ pub(in crate::context_bootstrap) fn custom_elements_when_defined_callback<'s>(
|
||||
let Some(registry_key) = custom_elements::registry_store_key(scope, args.this()) else {
|
||||
return;
|
||||
};
|
||||
custom_elements::bind_custom_elements_registry_data(scope, args.this(), host_ptr, registry_key);
|
||||
let registry = unsafe { &mut *host_ptr }
|
||||
.custom_elements_mut_for_registry_key(registry_key)
|
||||
.registry_data();
|
||||
|
||||
@@ -130,10 +130,11 @@ pub(crate) use registry_install::{
|
||||
rebind_materialized_child_custom_elements_registry,
|
||||
};
|
||||
mod registry_runtime;
|
||||
mod registry_tracing;
|
||||
pub(crate) use registry_runtime::{
|
||||
mark_custom_elements_registry_owner, mark_scoped_custom_elements_registry,
|
||||
registry_association_from_value, registry_association_matches_document, registry_owner_host,
|
||||
registry_store_key,
|
||||
bind_custom_elements_registry_data, mark_custom_elements_registry_owner,
|
||||
mark_scoped_custom_elements_registry, registry_association_from_value,
|
||||
registry_association_matches_document, registry_owner_host, registry_store_key,
|
||||
};
|
||||
mod registry_initializer;
|
||||
pub(crate) use registry_initializer::initialize_registry_for_subtree;
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
};
|
||||
|
||||
pub(super) struct CustomElementDefinition {
|
||||
pub(super) constructor: v8::Global<v8::Function>,
|
||||
pub(super) constructor: v8::Weak<v8::Function>,
|
||||
pub(super) observed_attributes: Rc<[String]>,
|
||||
pub(super) callbacks: CustomElementCallbacks,
|
||||
pub(super) disables_shadow: bool,
|
||||
@@ -21,20 +21,20 @@ pub(super) struct CustomElementDefinition {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CustomElementCallbacks {
|
||||
pub(super) connected: Option<v8::Global<v8::Function>>,
|
||||
pub(super) disconnected: Option<v8::Global<v8::Function>>,
|
||||
pub(super) connected_move: Option<v8::Global<v8::Function>>,
|
||||
pub(super) adopted: Option<v8::Global<v8::Function>>,
|
||||
pub(super) attribute_changed: Option<v8::Global<v8::Function>>,
|
||||
pub(super) form_associated: Option<v8::Global<v8::Function>>,
|
||||
pub(super) form_reset: Option<v8::Global<v8::Function>>,
|
||||
pub(super) form_disabled: Option<v8::Global<v8::Function>>,
|
||||
pub(super) form_state_restore: Option<v8::Global<v8::Function>>,
|
||||
pub(super) connected: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) disconnected: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) connected_move: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) adopted: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) attribute_changed: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) form_associated: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) form_reset: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) form_disabled: Option<v8::Weak<v8::Function>>,
|
||||
pub(super) form_state_restore: Option<v8::Weak<v8::Function>>,
|
||||
}
|
||||
|
||||
pub(super) struct PendingWhenDefined {
|
||||
pub(super) promise: v8::Global<v8::Promise>,
|
||||
pub(super) resolver: v8::Global<v8::PromiseResolver>,
|
||||
pub(super) promise: v8::Weak<v8::Promise>,
|
||||
pub(super) resolver: v8::Weak<v8::PromiseResolver>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -49,6 +49,8 @@ pub(crate) struct CustomElementRegistryData {
|
||||
pub(super) definitions: RefCell<HashMap<String, Rc<CustomElementDefinition>>>,
|
||||
pub(super) pending_when_defined: RefCell<HashMap<String, PendingWhenDefined>>,
|
||||
pub(super) definition_is_running: Cell<bool>,
|
||||
pub(super) roots: RefCell<Option<super::registry_tracing::RegistryRoots>>,
|
||||
pub(super) retired: Cell<bool>,
|
||||
}
|
||||
|
||||
// A registry's definitions and promises can be shared by different native DOM
|
||||
@@ -83,6 +85,20 @@ impl CustomElementStore {
|
||||
pub(crate) fn registry_data(&self) -> Rc<CustomElementRegistryData> {
|
||||
self.registry.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn retire_execution_state(&mut self) {
|
||||
self.registry.retire();
|
||||
self.construction_stack = CustomElementConstructionStack::default();
|
||||
}
|
||||
|
||||
pub(crate) fn retire_execution_state_for_realm(
|
||||
&mut self,
|
||||
realm_token: crate::native_bridge::RuntimeObservableContextToken,
|
||||
) {
|
||||
if self.registry.belongs_to_realm(realm_token) {
|
||||
self.retire_execution_state();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_valid_custom_element_name(name: &str) -> bool {
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(super) fn build_custom_element_definition<'s>(
|
||||
}
|
||||
|
||||
Ok(CustomElementDefinition {
|
||||
constructor: v8::Global::new(scope, constructor),
|
||||
constructor: v8::Weak::new(scope, constructor),
|
||||
observed_attributes: observed_attributes.into(),
|
||||
callbacks,
|
||||
disables_shadow,
|
||||
|
||||
@@ -17,7 +17,7 @@ impl CustomElementStore {
|
||||
"adoptedCallback" => definition.callbacks.adopted.as_ref(),
|
||||
_ => None,
|
||||
}?;
|
||||
Some(v8::Local::new(scope, callback))
|
||||
callback.to_local(scope)
|
||||
}
|
||||
|
||||
pub(super) fn attribute_changed_callback_for_handle<'s>(
|
||||
@@ -28,7 +28,7 @@ impl CustomElementStore {
|
||||
) -> Option<v8::Local<'s, v8::Function>> {
|
||||
let definition = self.definition_for_handle(host_ptr, handle)?;
|
||||
let callback = definition.callbacks.attribute_changed.as_ref()?;
|
||||
Some(v8::Local::new(scope, callback))
|
||||
callback.to_local(scope)
|
||||
}
|
||||
|
||||
pub(super) fn form_associated_callback_for_handle<'s>(
|
||||
@@ -39,7 +39,7 @@ impl CustomElementStore {
|
||||
) -> Option<v8::Local<'s, v8::Function>> {
|
||||
let definition = self.definition_for_handle(host_ptr, handle)?;
|
||||
let callback = definition.callbacks.form_associated.as_ref()?;
|
||||
Some(v8::Local::new(scope, callback))
|
||||
callback.to_local(scope)
|
||||
}
|
||||
|
||||
pub(super) fn form_disabled_callback_for_handle<'s>(
|
||||
@@ -50,7 +50,7 @@ impl CustomElementStore {
|
||||
) -> Option<v8::Local<'s, v8::Function>> {
|
||||
let definition = self.definition_for_handle(host_ptr, handle)?;
|
||||
let callback = definition.callbacks.form_disabled.as_ref()?;
|
||||
Some(v8::Local::new(scope, callback))
|
||||
callback.to_local(scope)
|
||||
}
|
||||
|
||||
pub(super) fn form_reset_callback_for_handle<'s>(
|
||||
@@ -61,7 +61,7 @@ impl CustomElementStore {
|
||||
) -> Option<v8::Local<'s, v8::Function>> {
|
||||
let definition = self.definition_for_handle(host_ptr, handle)?;
|
||||
let callback = definition.callbacks.form_reset.as_ref()?;
|
||||
Some(v8::Local::new(scope, callback))
|
||||
callback.to_local(scope)
|
||||
}
|
||||
|
||||
pub(super) fn form_state_restore_callback_for_handle<'s>(
|
||||
@@ -72,6 +72,6 @@ impl CustomElementStore {
|
||||
) -> Option<v8::Local<'s, v8::Function>> {
|
||||
let definition = self.definition_for_handle(host_ptr, handle)?;
|
||||
let callback = definition.callbacks.form_state_restore.as_ref()?;
|
||||
Some(v8::Local::new(scope, callback))
|
||||
callback.to_local(scope)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ fn callback_for_prototype<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
prototype: v8::Local<'s, v8::Object>,
|
||||
callback_name: &'static str,
|
||||
) -> Result<Option<v8::Global<v8::Function>>, CustomElementDefineError> {
|
||||
) -> Result<Option<v8::Weak<v8::Function>>, CustomElementDefineError> {
|
||||
let callback_key =
|
||||
v8_string(scope, callback_name).ok_or(CustomElementDefineError::PendingException)?;
|
||||
let callback = prototype
|
||||
@@ -63,5 +63,7 @@ fn callback_for_prototype<'s>(
|
||||
}
|
||||
let callback = v8::Local::<v8::Function>::try_from(callback)
|
||||
.map_err(|_| CustomElementDefineError::InvalidCallback(callback_name))?;
|
||||
Ok(Some(v8::Global::new(scope, callback)))
|
||||
// This Local remains rooted by the caller's HandleScope until the complete
|
||||
// definition is installed in the registry's V8-traced private map.
|
||||
Ok(Some(v8::Weak::new(scope, callback)))
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ pub(crate) fn define_custom_element_for_registry<'s>(
|
||||
name: &str,
|
||||
constructor: v8::Local<'s, v8::Function>,
|
||||
extends_local_name: Option<String>,
|
||||
) -> Result<bool, CustomElementDefineError> {
|
||||
) -> Result<Option<bool>, CustomElementDefineError> {
|
||||
let constructor_value: v8::Local<'_, v8::Value> = constructor.into();
|
||||
if constructor_value.is_async_function() || constructor_value.is_generator_function() {
|
||||
return Err(CustomElementDefineError::ConstructorNotConstructable);
|
||||
@@ -45,8 +45,10 @@ pub(crate) fn define_custom_element_for_registry<'s>(
|
||||
));
|
||||
}
|
||||
if definitions.values().any(|definition| {
|
||||
let registered_constructor = v8::Local::new(scope, &definition.constructor);
|
||||
registered_constructor.strict_equals(constructor.into())
|
||||
definition
|
||||
.constructor
|
||||
.to_local(scope)
|
||||
.is_some_and(|registered| registered.strict_equals(constructor.into()))
|
||||
}) {
|
||||
return Err(CustomElementDefineError::ConstructorAlreadyRegistered);
|
||||
}
|
||||
@@ -70,9 +72,12 @@ pub(crate) fn define_custom_element_for_registry<'s>(
|
||||
registry.definition_is_running.set(false);
|
||||
|
||||
let definition = definition_result?;
|
||||
if registry.retired.get() {
|
||||
return Ok(None);
|
||||
}
|
||||
let disables_shadow = definition.disables_shadow;
|
||||
registry.install_definition(scope, name, definition);
|
||||
Ok(disables_shadow)
|
||||
Ok(Some(disables_shadow))
|
||||
}
|
||||
|
||||
impl CustomElementStore {
|
||||
@@ -120,8 +125,10 @@ impl CustomElementStore {
|
||||
.borrow()
|
||||
.iter()
|
||||
.find(|(_, definition)| {
|
||||
let registered_constructor = v8::Local::new(scope, &definition.constructor);
|
||||
registered_constructor.strict_equals(constructor.into())
|
||||
definition
|
||||
.constructor
|
||||
.to_local(scope)
|
||||
.is_some_and(|registered| registered.strict_equals(constructor.into()))
|
||||
})
|
||||
.map(|(name, definition)| {
|
||||
(
|
||||
@@ -143,7 +150,7 @@ impl CustomElementRegistryData {
|
||||
name: &str,
|
||||
) -> Option<v8::Local<'s, v8::Function>> {
|
||||
self.definition(name)
|
||||
.map(|definition| v8::Local::new(scope, &definition.constructor))
|
||||
.and_then(|definition| definition.constructor.to_local(scope))
|
||||
}
|
||||
|
||||
pub(super) fn install_definition(
|
||||
@@ -152,7 +159,11 @@ impl CustomElementRegistryData {
|
||||
name: &str,
|
||||
definition: CustomElementDefinition,
|
||||
) {
|
||||
let constructor = v8::Local::new(scope, &definition.constructor);
|
||||
let constructor = definition
|
||||
.constructor
|
||||
.to_local(scope)
|
||||
.expect("definition construction retains the constructor");
|
||||
self.trace_definition(scope, name, &definition);
|
||||
self.definitions
|
||||
.borrow_mut()
|
||||
.insert(name.to_owned(), Rc::new(definition));
|
||||
@@ -160,8 +171,11 @@ impl CustomElementRegistryData {
|
||||
if let Some(pending) = pending {
|
||||
// Promise resolution reads constructor.then and can re-enter this
|
||||
// registry. Both table borrows must end before executing it.
|
||||
let resolver = v8::Local::new(scope, &pending.resolver);
|
||||
let _ = resolver.resolve(scope, constructor.into());
|
||||
let resolver = pending.resolver.to_local(scope);
|
||||
self.remove_pending_promise_root(scope, name);
|
||||
if let Some(resolver) = resolver {
|
||||
let _ = resolver.resolve(scope, constructor.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,16 +191,17 @@ impl CustomElementRegistryData {
|
||||
}
|
||||
|
||||
if let Some(pending) = self.pending_when_defined.borrow().get(name) {
|
||||
return Some(v8::Local::new(scope, &pending.promise));
|
||||
return pending.promise.to_local(scope);
|
||||
}
|
||||
|
||||
let resolver = v8::PromiseResolver::new(scope)?;
|
||||
let promise = resolver.get_promise(scope);
|
||||
self.trace_pending_promise(scope, name, promise, resolver);
|
||||
self.pending_when_defined.borrow_mut().insert(
|
||||
name.to_owned(),
|
||||
PendingWhenDefined {
|
||||
promise: v8::Global::new(scope, promise),
|
||||
resolver: v8::Global::new(scope, resolver),
|
||||
promise: v8::Weak::new(scope, promise),
|
||||
resolver: v8::Weak::new(scope, resolver),
|
||||
},
|
||||
);
|
||||
Some(promise)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::document_runtime::DomHandle;
|
||||
use crate::{document_runtime::DomHandle, util::v8str};
|
||||
|
||||
fn test_constructor<'s>(
|
||||
_scope: &mut v8::PinScope<'s, '_>,
|
||||
@@ -21,6 +21,8 @@ fn registry_data_shares_definitions_and_promises_without_sharing_native_handles(
|
||||
let target = CustomElementStore::for_registry(source.registry_data());
|
||||
let unrelated = CustomElementStore::default();
|
||||
let registry = source.registry_data();
|
||||
let registry_wrapper = v8::Object::new(scope);
|
||||
registry.bind_wrapper(scope, registry_wrapper);
|
||||
let source_promise = registry.when_defined(scope, "x-shared").unwrap();
|
||||
let target_promise = target
|
||||
.registry_data()
|
||||
@@ -66,3 +68,78 @@ fn registry_data_shares_definitions_and_promises_without_sharing_native_handles(
|
||||
assert!(!target.is_subtree_lifecycle_quiescent());
|
||||
assert!(!target.owns_custom_element_handle(handle));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retired_registry_traces_captured_values_without_rooting_an_unreachable_registry() {
|
||||
crate::ensure_v8_for_test();
|
||||
let mut isolate = v8::Isolate::new(Default::default());
|
||||
let data = Rc::new(CustomElementRegistryData::default());
|
||||
let (registry, weak_registry, constructor, callback, promise, resolver) = {
|
||||
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
|
||||
let scope = &mut scope.init();
|
||||
let context = v8::Context::new(scope, Default::default());
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let registry = v8::Object::new(scope);
|
||||
data.bind_wrapper(scope, registry);
|
||||
let script = v8str(
|
||||
scope,
|
||||
"(class { get connectedCallback() { return function captured() {}; } })",
|
||||
);
|
||||
let script = v8::Script::compile(scope, script, None).unwrap();
|
||||
let value = crate::script_execution::execute_compiled_script(scope, script).unwrap();
|
||||
let constructor = v8::Local::<v8::Function>::try_from(value).unwrap();
|
||||
let definition = build_custom_element_definition(scope, constructor, None).unwrap();
|
||||
let captured = definition.callbacks.connected.as_ref().unwrap().clone();
|
||||
data.install_definition(scope, "x-traced", definition);
|
||||
data.when_defined(scope, "x-pending").unwrap();
|
||||
let pending = data.pending_when_defined.borrow();
|
||||
let pending = pending.get("x-pending").unwrap();
|
||||
(
|
||||
v8::Global::new(scope, registry),
|
||||
v8::Weak::new(scope, registry),
|
||||
v8::Weak::new(scope, constructor),
|
||||
captured,
|
||||
pending.promise.clone(),
|
||||
pending.resolver.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
data.retire();
|
||||
isolate.low_memory_notification();
|
||||
assert!(!weak_registry.is_empty());
|
||||
assert!(!constructor.is_empty());
|
||||
assert!(!callback.is_empty(), "captured getter result stays alive");
|
||||
assert!(!promise.is_empty());
|
||||
assert!(!resolver.is_empty(), "pending resolution stays possible");
|
||||
|
||||
drop(registry);
|
||||
isolate.low_memory_notification();
|
||||
assert!(weak_registry.is_empty());
|
||||
assert!(constructor.is_empty());
|
||||
assert!(callback.is_empty());
|
||||
assert!(promise.is_empty());
|
||||
assert!(resolver.is_empty());
|
||||
assert_eq!(data.definitions.borrow().len(), 1);
|
||||
assert_eq!(data.pending_when_defined.borrow().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_registry_metadata_does_not_root_its_creation_context() {
|
||||
crate::ensure_v8_for_test();
|
||||
let mut isolate = v8::Isolate::new(Default::default());
|
||||
let data = CustomElementRegistryData::default();
|
||||
let context = {
|
||||
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
|
||||
let scope = &mut scope.init();
|
||||
let context = v8::Context::new(scope, Default::default());
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let registry = v8::Object::new(scope);
|
||||
data.bind_wrapper(scope, registry);
|
||||
v8::Weak::new(scope, context)
|
||||
};
|
||||
isolate.low_memory_notification();
|
||||
assert!(
|
||||
context.is_empty(),
|
||||
"an empty registry has no execution-owned values"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -142,16 +142,20 @@ fn new_custom_elements_registry_for_owner<'s>(
|
||||
) -> Result<v8::Local<'s, v8::Object>> {
|
||||
let registry = new_custom_elements_registry(scope)?;
|
||||
super::registry_runtime::mark_custom_elements_registry_owner(scope, registry);
|
||||
let Some(child_handle) = child_handle else {
|
||||
return Ok(registry);
|
||||
};
|
||||
let handle_value = v8::BigInt::new_from_u64(scope, child_handle.index() as u64);
|
||||
set_private_value(
|
||||
scope,
|
||||
registry,
|
||||
CUSTOM_ELEMENTS_REGISTRY_CHILD_HANDLE_SLOT,
|
||||
handle_value.into(),
|
||||
);
|
||||
if let Some(child_handle) = child_handle {
|
||||
let handle_value = v8::BigInt::new_from_u64(scope, child_handle.index() as u64);
|
||||
set_private_value(
|
||||
scope,
|
||||
registry,
|
||||
CUSTOM_ELEMENTS_REGISTRY_CHILD_HANDLE_SLOT,
|
||||
handle_value.into(),
|
||||
);
|
||||
}
|
||||
if let Some(host_ptr) = super::registry_runtime::registry_owner_host(scope, registry)
|
||||
&& let Some(key) = super::registry_runtime::registry_store_key(scope, registry)
|
||||
{
|
||||
super::registry_runtime::bind_custom_elements_registry_data(scope, registry, host_ptr, key);
|
||||
}
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,42 @@ pub(crate) fn registry_owner_host<'s>(
|
||||
context_host_ptr_from_context_slot(owner.get_creation_context(scope)?)
|
||||
}
|
||||
|
||||
pub(crate) fn bind_custom_elements_registry_data<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
registry: v8::Local<'s, v8::Object>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
key: CustomElementRegistryKey,
|
||||
) {
|
||||
// Constructors already know the native owner and key. Their receiver is
|
||||
// not branded until the generated constructor binding returns.
|
||||
let owner = get_private_object(scope, registry, CUSTOM_ELEMENTS_REGISTRY_OWNER_SLOT)
|
||||
.and_then(|owner| owner.get_creation_context(scope))
|
||||
.expect("native registry has a constructing realm");
|
||||
let data = unsafe { &mut *host_ptr }
|
||||
.custom_elements_mut_for_registry_key(key)
|
||||
.registry_data();
|
||||
let host = unsafe { &*host_ptr };
|
||||
let inactive_identity = host
|
||||
.window_execution_context_identity_for_access_check(owner)
|
||||
.is_some_and(|identity| {
|
||||
!host.window_execution_context_identity_is_current(identity)
|
||||
|| matches!(
|
||||
identity.dispatch_scope(),
|
||||
crate::native_bridge::OwnerDispatchScope::Child(handle)
|
||||
if !host.dom_host().is_connected(handle)
|
||||
)
|
||||
});
|
||||
if crate::util::page_context_is_detached_document(owner)
|
||||
|| crate::util::page_context_is_disconnected(owner)
|
||||
|| host.browsing_context_is_closed()
|
||||
|| inactive_identity
|
||||
{
|
||||
data.retire();
|
||||
}
|
||||
let scope = &mut v8::ContextScope::new(scope, owner);
|
||||
data.bind_wrapper(scope, registry);
|
||||
}
|
||||
|
||||
pub(crate) fn mark_scoped_custom_elements_registry(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
registry: v8::Local<'_, v8::Object>,
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
use super::definition::{CustomElementDefinition, CustomElementRegistryData};
|
||||
use crate::native_bridge::RuntimeObservableContextToken;
|
||||
use crate::util::{get_private_value, new_null_prototype_object, set_private_value, v8_string};
|
||||
|
||||
const ROOTS_SLOT: &str = "__moliCustomElementRegistryRoots";
|
||||
const DEFINITIONS_SLOT: &str = "__moliCustomElementRegistryDefinitions";
|
||||
const PROMISES_SLOT: &str = "__moliCustomElementRegistryPromises";
|
||||
|
||||
// The registry object traces constructors, captured callbacks and pending
|
||||
// resolvers. All wrappers for the same data trace one anchor. Active native
|
||||
// DOM stores also retain this anchor, as they retained individual values
|
||||
// before. Retirement releases those execution-owned roots;
|
||||
// only the V8 graph may then keep the registry's values and realm alive.
|
||||
pub(super) struct RegistryRoots {
|
||||
anchor: v8::Weak<v8::Object>,
|
||||
active: Option<v8::Global<v8::Object>>,
|
||||
realm_token: Option<RuntimeObservableContextToken>,
|
||||
}
|
||||
|
||||
impl CustomElementRegistryData {
|
||||
pub(crate) fn bind_wrapper(
|
||||
&self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
registry: v8::Local<'_, v8::Object>,
|
||||
) {
|
||||
let realm_token = scope
|
||||
.get_current_context()
|
||||
.get_slot::<RuntimeObservableContextToken>()
|
||||
.as_deref()
|
||||
.copied();
|
||||
let existing = self
|
||||
.roots
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.and_then(|roots| roots.anchor.to_local(scope));
|
||||
let anchor = existing.unwrap_or_else(|| {
|
||||
let anchor = new_null_prototype_object(scope);
|
||||
*self.roots.borrow_mut() = Some(RegistryRoots {
|
||||
anchor: v8::Weak::new(scope, anchor),
|
||||
active: None,
|
||||
realm_token,
|
||||
});
|
||||
anchor
|
||||
});
|
||||
if let Some(roots) = self.roots.borrow_mut().as_mut()
|
||||
&& roots.realm_token.is_none()
|
||||
{
|
||||
roots.realm_token = realm_token;
|
||||
}
|
||||
set_private_value(scope, registry, ROOTS_SLOT, anchor.into());
|
||||
}
|
||||
|
||||
pub(super) fn belongs_to_realm(&self, realm_token: RuntimeObservableContextToken) -> bool {
|
||||
self.roots
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.is_some_and(|roots| roots.realm_token == Some(realm_token))
|
||||
}
|
||||
|
||||
pub(super) fn retire(&self) {
|
||||
self.retired.set(true);
|
||||
if let Some(roots) = self.roots.borrow_mut().as_mut() {
|
||||
roots.active = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn roots_map<'s>(
|
||||
&self,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
slot: &str,
|
||||
) -> v8::Local<'s, v8::Map> {
|
||||
let anchor = self
|
||||
.roots
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.and_then(|roots| roots.anchor.to_local(scope))
|
||||
.expect("registry operations retain their receiver");
|
||||
if !self.retired.get() {
|
||||
let mut roots = self.roots.borrow_mut();
|
||||
let roots = roots.as_mut().expect("live registry has bound roots");
|
||||
roots
|
||||
.active
|
||||
.get_or_insert_with(|| v8::Global::new(scope, anchor));
|
||||
}
|
||||
if let Some(map) = get_private_value(scope, anchor, slot)
|
||||
.and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
|
||||
{
|
||||
return map;
|
||||
}
|
||||
let map = v8::Map::new(scope);
|
||||
set_private_value(scope, anchor, slot, map.into());
|
||||
map
|
||||
}
|
||||
|
||||
pub(super) fn trace_definition(
|
||||
&self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
name: &str,
|
||||
definition: &CustomElementDefinition,
|
||||
) {
|
||||
let constructor = definition
|
||||
.constructor
|
||||
.to_local(scope)
|
||||
.expect("definition construction retains the constructor");
|
||||
let mut values = vec![constructor.into()];
|
||||
let callbacks = &definition.callbacks;
|
||||
for callback in [
|
||||
&callbacks.connected,
|
||||
&callbacks.disconnected,
|
||||
&callbacks.connected_move,
|
||||
&callbacks.adopted,
|
||||
&callbacks.attribute_changed,
|
||||
&callbacks.form_associated,
|
||||
&callbacks.form_reset,
|
||||
&callbacks.form_disabled,
|
||||
&callbacks.form_state_restore,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let callback = callback
|
||||
.to_local(scope)
|
||||
.expect("definition construction retains captured callbacks");
|
||||
values.push(callback.into());
|
||||
}
|
||||
let record = v8::Array::new_with_elements(scope, &values);
|
||||
let map = self.roots_map(scope, DEFINITIONS_SLOT);
|
||||
let name = v8_string(scope, name).expect("registry name fits in a V8 string");
|
||||
let _ = map.set(scope, name.into(), record.into());
|
||||
}
|
||||
|
||||
pub(super) fn trace_pending_promise(
|
||||
&self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
name: &str,
|
||||
promise: v8::Local<'_, v8::Promise>,
|
||||
resolver: v8::Local<'_, v8::PromiseResolver>,
|
||||
) {
|
||||
let record = v8::Array::new_with_elements(scope, &[promise.into(), resolver.into()]);
|
||||
let map = self.roots_map(scope, PROMISES_SLOT);
|
||||
let name = v8_string(scope, name).expect("registry name fits in a V8 string");
|
||||
let _ = map.set(scope, name.into(), record.into());
|
||||
}
|
||||
|
||||
pub(super) fn remove_pending_promise_root(&self, scope: &mut v8::PinScope<'_, '_>, name: &str) {
|
||||
let map = self.roots_map(scope, PROMISES_SLOT);
|
||||
let name = v8_string(scope, name).expect("registry name fits in a V8 string");
|
||||
let _ = map.delete(scope, name.into());
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,12 @@ impl PageScriptHost {
|
||||
&mut self,
|
||||
realm_token: RuntimeObservableContextToken,
|
||||
) {
|
||||
for store in std::iter::once(&mut self.custom_elements)
|
||||
.chain(self.child_custom_elements.values_mut())
|
||||
.chain(self.scoped_custom_elements.values_mut())
|
||||
{
|
||||
store.retire_execution_state_for_realm(realm_token);
|
||||
}
|
||||
let timers = self.cancel_timers_for_context_token(realm_token);
|
||||
let bindings = self.retire_runtime_binding_context_token(realm_token);
|
||||
let images = self.retire_image_decode_requests_for_context_token(realm_token);
|
||||
@@ -213,10 +219,16 @@ impl PageScriptHost {
|
||||
// these LocalDOMWindow/ExecutionContext-owned services when the frame
|
||||
// is detached while ordinary retained Document/Node values remain
|
||||
// usable.
|
||||
drop(std::mem::take(&mut self.custom_elements));
|
||||
self.child_custom_elements.clear();
|
||||
self.scoped_custom_elements.clear();
|
||||
self.foreign_custom_elements.clear();
|
||||
// Release execution-owned registry roots while preserving weak native
|
||||
// metadata. A retained JS registry traces its old values after close;
|
||||
// it must neither lose them nor resume installing new definitions.
|
||||
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();
|
||||
}
|
||||
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));
|
||||
|
||||
@@ -4,6 +4,44 @@ mod split30_registry_native_owner;
|
||||
use super::*;
|
||||
use crate::RendererPopupActivationSource;
|
||||
|
||||
#[tokio::test]
|
||||
async fn retained_popup_registries_preserve_definitions_without_resuming_definition_installation() {
|
||||
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-retirement.test/").unwrap(),
|
||||
"<!doctype html><body></body>",
|
||||
RendererTopLevelNavigationDispatch::DelegateToBrowser,
|
||||
)
|
||||
.await;
|
||||
let (reply, _) = page
|
||||
.run_async_command(RendererPageCommand::EvaluateExpression {
|
||||
expression: include_str!("custom_element_registry_retirement.js").to_owned(),
|
||||
await_promise: true,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else {
|
||||
panic!("retirement probe must return all observations");
|
||||
};
|
||||
let result: serde_json::Value = serde_json::from_str(&result).unwrap();
|
||||
let rows = result["rows"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
for row in rows {
|
||||
for (name, value) in row.as_object().unwrap() {
|
||||
if name != "case" {
|
||||
assert_eq!(value, true, "{}: {name}", row["case"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
page.close_async().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn document_registry_validation_uses_native_owner_identity() {
|
||||
let runtime = JsRuntime::initialize();
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
(async () => {
|
||||
const rows = [];
|
||||
const methods = CustomElementRegistry.prototype;
|
||||
for (const kind of ['global', 'scoped']) {
|
||||
const popup = open('about:blank');
|
||||
try {
|
||||
const registry = kind === 'global' ? popup.customElements : new popup.CustomElementRegistry();
|
||||
const name = `retirement-${kind}-before`;
|
||||
const lateName = `retirement-${kind}-after`;
|
||||
const Constructor = class extends popup.HTMLElement {};
|
||||
let fulfilled;
|
||||
let lateFulfilled = false;
|
||||
const pending = methods.whenDefined.call(registry, lateName);
|
||||
pending.then(() => { lateFulfilled = true; });
|
||||
methods.define.call(registry, name, Constructor);
|
||||
methods.whenDefined.call(registry, name).then(value => { fulfilled = value; });
|
||||
await Promise.resolve();
|
||||
rows.push({case: `${kind}-before-close`,
|
||||
get: methods.get.call(registry, name) === Constructor,
|
||||
getName: methods.getName.call(registry, Constructor) === name,
|
||||
whenDefined: fulfilled === Constructor,
|
||||
samePending: methods.whenDefined.call(registry, lateName) === pending,
|
||||
});
|
||||
|
||||
popup.close();
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
let conversions = 0;
|
||||
let prototypeReads = 0;
|
||||
const LateConstructor = new Proxy(class {}, {get(target, key, receiver) {
|
||||
if (key === 'prototype') ++prototypeReads;
|
||||
return Reflect.get(target, key, receiver);
|
||||
}});
|
||||
methods.define.call(registry, {toString() { ++conversions; return lateName; }}, LateConstructor);
|
||||
fulfilled = undefined;
|
||||
methods.whenDefined.call(registry, name).then(value => { fulfilled = value; });
|
||||
await Promise.resolve();
|
||||
rows.push({case: `${kind}-after-close`,
|
||||
get: methods.get.call(registry, name) === Constructor,
|
||||
getName: methods.getName.call(registry, Constructor) === name,
|
||||
whenDefined: fulfilled === Constructor,
|
||||
samePending: methods.whenDefined.call(registry, lateName) === pending,
|
||||
lateDefinitionAbsent: methods.get.call(registry, lateName) === undefined,
|
||||
latePromisePending: !lateFulfilled,
|
||||
argumentsConverted: conversions === 1,
|
||||
constructorReadOnce: prototypeReads === 1,
|
||||
});
|
||||
} finally { popup.close(); }
|
||||
}
|
||||
return JSON.stringify({rows});
|
||||
})()
|
||||
+23
@@ -1,5 +1,28 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn inactive_registry_methods_bind_recreated_native_stores_without_installing_new_definitions() {
|
||||
let mut vm = new_storage_test_vm("https://inactive-registry-calls.test/");
|
||||
// eval() returns the Promise. Store the observations through a separate
|
||||
// reaction so the standalone VM still owns the microtask checkpoint.
|
||||
vm.eval(&format!(
|
||||
"globalThis.inactiveRegistryRows = null; ({}).then(value => {{ inactiveRegistryRows = value; }});",
|
||||
include_str!("inactive_registry_calls.js")
|
||||
))
|
||||
.unwrap();
|
||||
let result: serde_json::Value =
|
||||
serde_json::from_str(&vm.eval("inactiveRegistryRows").unwrap()).unwrap();
|
||||
let rows = result["rows"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
for row in rows {
|
||||
for (name, value) in row.as_object().unwrap() {
|
||||
if name != "case" {
|
||||
assert_eq!(value, true, "{}: {name}", row["case"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn inactive_document_test_vm(loaded_srcdoc: bool) -> StandaloneScriptVmHarness {
|
||||
let mut vm = new_storage_test_vm("https://inactive-document-registry.test/");
|
||||
vm.eval(
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
(async () => {
|
||||
const rows = [];
|
||||
const root = document.documentElement || document.appendChild(document.createElement('html'));
|
||||
const body = document.body || root.appendChild(document.createElement('body'));
|
||||
for (const kind of ['global', 'scoped']) {
|
||||
const frame = document.createElement('iframe');
|
||||
body.appendChild(frame);
|
||||
const owner = frame.contentWindow;
|
||||
const registry = kind === 'global' ? owner.customElements : new owner.CustomElementRegistry();
|
||||
const Constructor = class extends owner.HTMLElement {};
|
||||
frame.remove();
|
||||
const name = `detached-${kind}-late`;
|
||||
const methods = CustomElementRegistry.prototype;
|
||||
let resolved = false;
|
||||
const pending = methods.whenDefined.call(registry, name);
|
||||
pending.then(() => { resolved = true; });
|
||||
methods.define.call(registry, name, Constructor);
|
||||
await Promise.resolve();
|
||||
rows.push({case: kind,
|
||||
promise: Object.prototype.toString.call(pending) === '[object Promise]',
|
||||
samePending: methods.whenDefined.call(registry, name) === pending,
|
||||
noLateDefinition: methods.get.call(registry, name) === undefined,
|
||||
pending: !resolved,
|
||||
});
|
||||
}
|
||||
return JSON.stringify({rows});
|
||||
})()
|
||||
@@ -44,8 +44,6 @@ const RAW_GLOBAL_FUNCTION_ALLOWLIST: &[(&str, usize)] = &[
|
||||
// page-supplied abort listeners remain in the typed EventTarget registry.
|
||||
("abort_signal_route.rs", 1),
|
||||
("custom_elements/construction.rs", 1),
|
||||
("custom_elements/definition.rs", 10),
|
||||
("custom_elements/definition_callbacks.rs", 1),
|
||||
("host/timers.rs", 1),
|
||||
("native_bridge/history_queue.rs", 3),
|
||||
("script_vm/frame_script_jobs.rs", 3),
|
||||
|
||||
Reference in New Issue
Block a user