Files
moli/moli-renderer-v8/src/script_vm/execution_contexts.rs
T
ldm0 c178aebd83 fix(renderer): reconcile native Window lifecycle with protocol Page ownership
Use the canonical Window.document and Location objects across related Pages, retain producer identity and inherited about-document settings, and preserve the Page dispatch policy for cross-document history traversal. Route stop and close through exact Document owner actions and apply them through ordered protocol target lanes. Keep unload reentry checks and bootstrap output ordering. Window.opener=null preserves its accessor as specified; adjust the two conflicting protocol expectations while keeping the renderer regression. Register the main realm owner before native HistoryEntry bootstrap so inherited origins remain in committed history; replace an initial-empty entry consistently in both navigate events and Location seeds. Empty URL reuse can retain a focus activation with navigation_requested=false while preserving every document/history/load assertion. The renderer enum producer and exhaustive protocol consumer change together. Formatting, strict workspace Clippy and the complete nextest suite passed against unchanged final source with 32 workers and zero retries.
2026-11-22 02:01:59 +08:00

1299 lines
53 KiB
Rust

use super::*;
use moli_inspector_json::InspectorJson;
impl ScriptVm {
pub(super) fn child_frame_realm_context_ptr(
&self,
realm_id: FrameRealmId,
) -> Result<*const v8::Global<v8::Context>> {
self.child_frame_realm_store
.context_for_owner_realm_id(realm_id)
.map(|realm| &realm.context as *const _)
.ok_or_else(|| anyhow!("unknown child frame owner realm `{realm_id:?}`"))
}
pub(super) fn child_frame_realm_context_ptr_for_execution_context_id(
&self,
execution_context_id: i64,
) -> Result<*const v8::Global<v8::Context>> {
let realm_id = self
.child_frame_realm_store
.owner_realm_id_for_context_id(execution_context_id)
.ok_or_else(|| anyhow!("unknown child frame realm `{execution_context_id}`"))?;
self.child_frame_realm_context_ptr(realm_id)
}
pub(super) fn inspector_window_dispatch_scope_for_target(
&self,
target: InspectorWindowDispatchTarget,
) -> Option<InspectorWindowDispatchScope> {
let execution_context_id = match target {
InspectorWindowDispatchTarget::DefaultTop => {
return Some(InspectorWindowDispatchScope {
context_ptr: self.current_main_world()?.context_ptr(),
child_handle: None,
});
}
InspectorWindowDispatchTarget::ExecutionContext(execution_context_id) => {
execution_context_id
}
InspectorWindowDispatchTarget::UniqueContext(unique_id) => {
self.runtime_realm_inventory()
.into_iter()
.find(|realm| realm.realm_id.as_deref() == Some(unique_id.as_str()))?
.context_id
}
};
if self.runtime_observable_default_execution_context_id() == Some(execution_context_id) {
return Some(InspectorWindowDispatchScope {
context_ptr: self.current_main_world()?.context_ptr(),
child_handle: None,
});
}
if let Some(realm) = self.child_frame_realm_store.get(&execution_context_id) {
return Some(InspectorWindowDispatchScope {
context_ptr: &realm.context as *const _,
child_handle: Some(realm.child_handle),
});
}
let isolated_context_id = self
.page_isolated_world_contexts
.execution_context_id_for_inspector_context(execution_context_id)?;
let world = self
.page_isolated_world_contexts
.context(isolated_context_id)?;
Some(InspectorWindowDispatchScope {
context_ptr: &world.context as *const _,
child_handle: world.child_handle,
})
}
pub(super) fn frame_realm_context_ptr(
&self,
realm_id: FrameRealmId,
) -> Result<*const v8::Global<v8::Context>> {
if realm_id.0 == 0 {
return self
.current_main_world()
.map(WindowRealmRuntime::context_ptr)
.ok_or_else(|| anyhow!("main world is not initialized"));
}
self.child_frame_realm_context_ptr(realm_id)
}
pub(super) fn child_frame_owner_realm_id_for_execution_context_id(
&self,
execution_context_id: i64,
) -> Result<FrameRealmId> {
let context = self
.child_frame_realm_store
.get(&execution_context_id)
.ok_or_else(|| anyhow!("unknown child frame realm `{execution_context_id}`"))?;
if !self.child_default_context_is_live(context) {
return Err(anyhow!(
"child frame realm `{execution_context_id}` belongs to a retired owner"
));
}
Ok(context.owner_realm_id)
}
#[cfg(feature = "devtools")]
pub(super) fn with_child_frame_realm_context_scope<T>(
&mut self,
execution_context_id: i64,
op: impl FnOnce(&mut v8::PinScope<'_, '_>, *mut PageScriptHost) -> Result<T>,
) -> Result<T> {
let realm_id =
self.child_frame_owner_realm_id_for_execution_context_id(execution_context_id)?;
self.with_frame_realm_scope(realm_id, op)
}
pub(super) fn child_frame_source_script_job_for_execution_context_id(
&self,
execution_context_id: i64,
kind: FrameScriptJobKind,
source: String,
) -> Result<FrameScriptJob> {
let context = self
.child_frame_realm_store
.get(&execution_context_id)
.ok_or_else(|| anyhow!("unknown child frame realm `{execution_context_id}`"))?;
self._context_host
.borrow()
.frame_owner_child_source_script_job(context.child_handle, kind, source)
.ok_or_else(|| {
anyhow!(
"child frame realm `{execution_context_id}` has no current FrameScriptJob owner"
)
})
}
pub(super) fn exec_child_frame_source_script_job_for_execution_context_id(
&mut self,
execution_context_id: i64,
kind: FrameScriptJobKind,
source: &str,
) -> Result<()> {
let job = self.child_frame_source_script_job_for_execution_context_id(
execution_context_id,
kind,
source.to_owned(),
)?;
self.exec_frame_script_job(job)
}
pub(crate) fn default_execution_context_id(&self) -> Option<i64> {
self.page_inspector.default_execution_context_id()
}
pub(crate) fn default_or_initial_execution_context_id(&self) -> Option<i64> {
self.page_inspector
.default_execution_context_id()
.or_else(|| self.page_inspector.initial_default_execution_context_id())
}
pub(super) fn runtime_observable_default_execution_context_id(&self) -> Option<i64> {
// Creation-time console output can be observed before Runtime.enable has
// materialized the session-visible default context id. The renderer
// still owns the initial V8 context identity, so source items can be
// emitted immediately instead of being parked as contextless messages.
self.page_inspector
.default_execution_context_id()
.or_else(|| self.page_inspector.initial_default_execution_context_id())
}
pub(super) fn runtime_observable_default_execution_context_realm_id(&self) -> Option<String> {
self.page_inspector
.default_execution_context_realm_id()
.or_else(|| {
self.page_inspector
.initial_default_execution_context_realm_id()
})
}
pub(crate) fn root_frame_id(&self) -> Option<&str> {
self.root_frame_id.as_deref()
}
pub(super) fn default_runtime_realm_info(&self) -> Option<RendererRuntimeRealmInfo> {
let context_id = self.runtime_observable_default_execution_context_id()?;
let document_url = self.document_runtime.document_url();
Some(RendererRuntimeRealmInfo {
context_id,
realm_id: self.runtime_observable_default_execution_context_realm_id(),
frame_id: self.root_frame_id.clone(),
origin: moli_url::origin_ascii_serialization(document_url),
name: document_url.as_str().to_owned(),
is_default: true,
context_type: "default".to_owned(),
grant_universal_access: None,
})
}
pub(crate) fn runtime_realm_inventory(&self) -> Vec<RendererRuntimeRealmInfo> {
let mut realms = Vec::new();
realms.extend(self.default_runtime_realm_info());
let mut isolated_context_ids = self
.page_isolated_world_contexts
.execution_context_ids()
.collect::<Vec<_>>();
isolated_context_ids.sort_unstable();
realms.extend(
isolated_context_ids
.into_iter()
.filter_map(|context_id| self.isolated_world_runtime_realm_info(context_id)),
);
realms.extend(self.live_child_default_runtime_realm_inventory());
realms
}
pub(super) fn runtime_inspector_messages_from_v8_messages<T: Into<InspectorJson>>(
&self,
messages: impl IntoIterator<Item = T>,
) -> Vec<RendererRuntimeInspectorMessage> {
messages
.into_iter()
.map(RendererRuntimeInspectorMessage::from_v8_inspector_message)
.collect()
}
pub(crate) fn has_isolated_execution_context_id(&self, execution_context_id: i64) -> bool {
self.page_isolated_world_contexts
.has_execution_context_id(execution_context_id)
}
pub(crate) fn has_isolated_world_named(&self, name: &str) -> bool {
self.page_isolated_world_contexts
.has_world_for_scope(None, name)
}
pub(crate) fn has_isolated_world_named_for_frame(&self, frame_id: &str, name: &str) -> bool {
self.page_isolated_world_contexts
.has_world_for_scope(Some(frame_id), name)
}
#[cfg(feature = "devtools")]
pub(crate) fn has_isolated_world_for_owner(
&self,
devtools_session: Option<&DevToolsSessionKey>,
frame_id: Option<&str>,
name: &str,
) -> bool {
self.page_isolated_world_contexts
.execution_context_id_for_scope(devtools_session, frame_id, name)
.is_some()
}
#[cfg(feature = "devtools")]
pub(crate) fn inspector_execution_context_id_for_isolated_context(
&self,
execution_context_id: i64,
) -> Option<i64> {
self.page_isolated_world_contexts
.inspector_execution_context_id(execution_context_id)
}
#[cfg(feature = "devtools")]
pub(crate) fn isolated_execution_context_id_for_inspector_context(
&self,
execution_context_id: i64,
) -> Option<i64> {
self.page_isolated_world_contexts
.execution_context_id_for_inspector_context(execution_context_id)
}
pub(crate) fn child_default_frame_id_for_execution_context_id(
&self,
execution_context_id: i64,
) -> Option<String> {
let context = self.child_frame_realm_store.get(&execution_context_id)?;
self.child_default_context_is_live(context)
.then(|| context.frame_id.clone())
}
pub(crate) fn child_default_execution_context_id_for_frame_id(
&self,
frame_id: &str,
) -> Option<i64> {
self.live_child_default_contexts()
.find_map(|(execution_context_id, context)| {
(context.frame_id == frame_id).then_some(execution_context_id)
})
}
pub(crate) fn child_browsing_context_module_request_initiator_url(
&self,
child_handle: crate::document_runtime::DomHandle,
) -> Option<Url> {
self._context_host
.borrow()
.child_browsing_context_request_initiator_url(child_handle)
}
pub(super) fn isolated_world_runtime_realm_info(
&self,
context_id: i64,
) -> Option<RendererRuntimeRealmInfo> {
let world = self.page_isolated_world_contexts.context(context_id)?;
let origin = world
.child_handle
.and_then(|handle| {
self._context_host
.borrow()
.child_browsing_context_current_url(handle)
})
.unwrap_or_else(|| self.document_runtime.document_url().clone());
Some(RendererRuntimeRealmInfo {
context_id,
realm_id: world.inspector_execution_context_realm_id.clone(),
frame_id: world
.frame_id
.clone()
.or_else(|| self.root_frame_id.clone()),
origin: moli_url::origin_ascii_serialization(&origin),
name: world.name.clone(),
is_default: false,
context_type: "isolated".to_owned(),
grant_universal_access: Some(world.grant_universal_access),
})
}
pub(crate) fn live_child_default_runtime_realm_inventory(
&self,
) -> Vec<RendererRuntimeRealmInfo> {
self.live_child_default_contexts()
.map(|(context_id, context)| {
let document_url = self
._context_host
.borrow()
.child_browsing_context_current_url(context.child_handle)
.unwrap_or_else(|| self.document_runtime.document_url().clone());
RendererRuntimeRealmInfo {
context_id,
realm_id: context.inspector_execution_context_realm_id.clone(),
frame_id: Some(context.frame_id.clone()),
origin: moli_url::origin_ascii_serialization(&document_url),
name: document_url.as_str().to_owned(),
is_default: true,
context_type: "default".to_owned(),
grant_universal_access: None,
}
})
.collect()
}
pub(super) fn live_child_default_contexts(
&self,
) -> impl Iterator<Item = (i64, &ChildFrameRealmRecord)> + '_ {
self.child_frame_realm_store
.iter_by_execution_context_id()
.filter(|(_, context)| self.child_default_context_is_live(context))
}
fn child_default_context_is_live(&self, context: &ChildFrameRealmRecord) -> bool {
let host = self._context_host.borrow();
host.child_browsing_context_is_live(context.child_handle)
&& host
.frame_owner_current_child_snapshot_for_realm(context.owner_realm_id)
.is_some_and(|snapshot| {
snapshot.owner_handle == context.child_handle
&& snapshot.frame_id.0 == context.frame_id
&& snapshot.local_window_id == context.local_window_id
})
}
pub(super) fn create_new_child_default_world(
&mut self,
frame_id: &str,
child_handle: DomHandle,
) -> Result<ChildFrameRealmRecord> {
let current_owner = self
._context_host
.borrow()
.current_child_document_task_owner(child_handle)
.ok_or_else(|| anyhow!("child frame `{frame_id}` has no current LocalWindow owner"))?;
let prebootstrapped = self
.prebootstrapped_child_default_contexts
.borrow_mut()
.remove(&child_handle);
let prebootstrapped = match prebootstrapped {
Some(context) if context.local_window_id == current_owner.local_window_id => {
Some(context)
}
Some(context) => {
self.retire_prebootstrapped_child_default_context(child_handle, context)?;
// Cancellation can synchronously install a successor realm or
// detach the frame. Resolve both owner and pending context anew.
return self.create_new_child_default_world(frame_id, child_handle);
}
None => None,
};
let context_host = self._context_host.clone();
let runtime = if let Some(prebootstrapped) = prebootstrapped {
prebootstrapped.runtime
} else {
self.renderer_document_isolate
.with_entered_renderer_document_isolate_and_bootstrap(
|isolate, isolate_bootstrap| {
ScriptVmContextBootstrap::new_child_default(
isolate,
isolate_bootstrap,
context_host,
self.resource_owner_id,
&self.promise_reject_dispatch,
self.indexed_db_manager.clone(),
Some(self.storage_bucket_store.clone()),
child_handle,
current_owner,
)
},
)?
.into_runtime()
};
let document_url = self
._context_host
.borrow()
.child_browsing_context_current_url(child_handle)
.unwrap_or_else(|| self.document_runtime.document_url().clone());
let renderer_document_isolate = self.renderer_document_isolate.clone();
let inspector_document_isolate = renderer_document_isolate.clone();
let page_inspector = &mut self.page_inspector;
let (inspector_context, inspector_context_registration_id) = renderer_document_isolate
.with_entered_renderer_document_isolate_and_inspector_mut(|isolate, inspector| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let local_context = v8::Local::new(scope, &runtime.context);
let registered_context = v8::Global::new(scope.as_ref(), local_context);
page_inspector.attach_child_default_context(
inspector_document_isolate,
inspector,
local_context,
registered_context,
&document_url,
frame_id,
)
})?;
let owner_realm_id = self
._context_host
.borrow_mut()
.bind_child_default_execution_context_id(
child_handle,
current_owner,
inspector_context.id,
);
let Some(owner_realm_id) = owner_realm_id else {
assert!(
self.page_inspector
.destroy_context_registration(inspector_context_registration_id),
"failed child realm materialization must release its Inspector registration"
);
return Err(anyhow!(
"child frame `{frame_id}` has no current FrameOwnerStore record for FrameRealm materialization"
));
};
Ok(ChildFrameRealmRecord {
frame_id: frame_id.to_owned(),
child_handle,
local_window_id: current_owner.local_window_id,
owner_realm_id,
runtime,
inspector_execution_context_id: inspector_context.id,
inspector_execution_context_realm_id: inspector_context.unique_id,
inspector_context_registration_id,
})
}
pub(super) fn retire_child_default_context_for_window(
&mut self,
child_handle: DomHandle,
local_window_id: crate::frame_owner_model::LocalWindowId,
) {
if let Some(execution_context_id) = self
.child_frame_realm_store
.context_id_for_local_window_id(local_window_id)
{
self.destroy_child_default_context(execution_context_id);
return;
}
// A Window may have been exposed synchronously before the owner task
// promoted it. Remove just the pending context for the retired Window.
let retired = {
let mut contexts = self.prebootstrapped_child_default_contexts.borrow_mut();
if contexts
.get(&child_handle)
.is_some_and(|context| context.local_window_id == local_window_id)
{
contexts.remove(&child_handle)
} else {
None
}
};
if let Some(context) = retired
&& let Err(error) =
self.retire_prebootstrapped_child_default_context(child_handle, context)
{
tracing::warn!(%error, ?child_handle, ?local_window_id, "failed to retire prebootstrapped child context");
}
}
fn retire_prebootstrapped_child_default_context(
&mut self,
child_handle: DomHandle,
mut context: crate::native_bridge::PrebootstrappedChildDefaultContext,
) -> Result<()> {
self.clear_context_wrapper_cache_for_context_ptr(&context.context, false);
self.cancel_history_traversals_for_retiring_window(
crate::native_bridge::WindowExecutionContextOwner::Frame(context.local_window_id),
);
let reuses_window_proxy = {
let mut host = self._context_host.borrow_mut();
host.retire_window_realm_resources(context.runtime_observable_context_token);
host.retire_window_execution_contexts_for_context_token(
context.runtime_observable_context_token,
Some(self.resource_owner_id),
);
host.child_window_proxy_frame_is_current(child_handle, &context.frame_id)
};
let result = if reuses_window_proxy {
self.renderer_document_isolate
.with_entered_renderer_document_isolate(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
v8::Local::new(scope, &context.context).detach_global();
Ok(())
})
} else {
Ok(())
};
context.runtime.mark_closed();
result
}
pub(super) fn destroy_child_default_context(&mut self, execution_context_id: i64) {
let Some(mut context) = self.child_frame_realm_store.remove(&execution_context_id) else {
return;
};
let context_ptr: *const v8::Global<v8::Context> = &context.context as *const _;
self.clear_context_wrapper_cache_for_context_ptr(context_ptr, false);
self.cancel_history_traversals_for_retiring_window(
crate::native_bridge::WindowExecutionContextOwner::Frame(context.local_window_id),
);
{
let mut host = self._context_host.borrow_mut();
host.clear_child_default_execution_context_if_matches(
context.child_handle,
context.owner_realm_id,
execution_context_id,
);
host.retire_window_realm_resources(context.runtime_observable_context_token);
host.retire_window_execution_contexts_for_context_token(
context.runtime_observable_context_token,
Some(self.resource_owner_id),
);
}
assert!(
self.page_inspector
.destroy_context_registration(context.inspector_context_registration_id),
"child default context must retain its document-owned Inspector registration"
);
let context_host = self._context_host.clone();
let proxy_cleanup_result = self
.renderer_document_isolate
.with_entered_renderer_document_isolate(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let local_context = unsafe { v8::Local::new(scope, &*context_ptr) };
let host_ptr = (*context_host).as_ptr();
let host = unsafe { &mut *host_ptr };
let reuses_window_proxy = host
.child_window_proxy_frame_is_current(context.child_handle, &context.frame_id);
// Navigation within the same frame reuses its WindowProxy.
// Removal (including remove/reinsert of the same element)
// creates a different browsing context. Keep the old proxy
// attached to its retained Window so its constructors remain
// callable after execution authority has been retired.
if reuses_window_proxy {
local_context.detach_global();
if !host.preserve_child_window_proxy_between_realms(scope, context.child_handle)
{
anyhow::bail!("failed to park the live child WindowProxy between realms");
}
}
Ok(reuses_window_proxy)
});
match proxy_cleanup_result {
Err(error) => tracing::warn!(
%error,
execution_context_id,
child_handle = context.child_handle.index(),
owner_realm_id = ?context.owner_realm_id,
"failed to finalize retired child WindowProxy"
),
Ok(reuses_window_proxy) => tracing::debug!(
execution_context_id,
child_handle = context.child_handle.index(),
owner_realm_id = ?context.owner_realm_id,
reuses_window_proxy,
"finalized retired child WindowProxy"
),
}
context.runtime.mark_closed();
}
pub(super) fn destroy_isolated_world_context(&mut self, execution_context_id: i64) {
let Some(mut context) = self
.page_isolated_world_contexts
.remove_context(execution_context_id)
else {
return;
};
let reuses_window_proxy = context
.child_handle
.zip(context.frame_id.as_deref())
.is_some_and(|(child_handle, frame_id)| {
let host = self._context_host.borrow();
host.child_window_proxy_frame_is_current(child_handle, frame_id)
&& host
.current_child_document_task_owner(child_handle)
.is_some_and(|owner| {
owner.local_window_id != context.document_owner.local_window_id
})
});
self._context_host
.borrow_mut()
.retire_window_realm_resources(context.runtime_observable_context_token);
{
let mut contexts = self.prebootstrapped_child_default_contexts.borrow_mut();
contexts.forget_isolated_context(context.runtime_observable_context_token);
if !reuses_window_proxy {
contexts
.forget_isolated_proxy_for_context(context.runtime_observable_context_token);
}
}
assert!(
self.page_inspector
.destroy_context_registration(context.inspector_context_registration_id),
"isolated context must retain its document-owned Inspector registration"
);
let context_ptr: *const v8::Global<v8::Context> = &context.context as *const _;
self.clear_context_wrapper_cache_for_context_ptr(context_ptr, false);
// V8 Inspector consumes the still-identifiable realm while processing
// `context_destroyed` (including Runtime lifecycle projection for
// named child worlds). Only after that notification may the strict
// realm locator become stale. Isolated worlds have no owner-indexed
// default-world binding, so retire only this token's registry entry.
let retired_window_execution_context_realm_count = self
._context_host
.borrow_mut()
.retire_isolated_window_execution_context(
context.runtime_observable_context_token,
self.resource_owner_id,
);
if reuses_window_proxy {
let detached = self
.renderer_document_isolate
.with_entered_renderer_document_isolate(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let context = unsafe { v8::Local::new(scope, &*context_ptr) };
context.detach_global();
Ok(())
});
if let Err(error) = detached {
tracing::warn!(%error, execution_context_id, "failed to detach a retired isolated WindowProxy");
}
}
tracing::debug!(
execution_context_id,
context_token = ?context.runtime_observable_context_token,
retired_window_execution_context_realm_count,
"retired isolated-world Runtime binding context"
);
context.runtime.mark_closed();
}
pub(super) fn retire_isolated_worlds_for_document_owner(
&mut self,
owner: FrameDocumentTaskOwner,
) -> usize {
let stale_context_ids = self
.page_isolated_world_contexts
.contexts_with_ids()
.filter_map(|(context_id, world)| (world.document_owner == owner).then_some(context_id))
.collect::<Vec<_>>();
let retired_count = stale_context_ids.len();
for context_id in stale_context_ids {
self.destroy_isolated_world_context(context_id);
}
retired_count
}
#[cfg(feature = "devtools")]
pub(super) fn retire_isolated_worlds_for_devtools_session(
&mut self,
devtools_session: &DevToolsSessionKey,
) -> usize {
let context_ids = self
.page_isolated_world_contexts
.execution_context_ids_for_devtools_session(devtools_session);
let retired_count = context_ids.len();
for context_id in context_ids {
self.destroy_isolated_world_context(context_id);
}
self.prebootstrapped_child_default_contexts
.borrow_mut()
.forget_isolated_proxies_for_session(devtools_session);
self.renderer_document_isolate
.with_renderer_document_isolate_mut(|isolate| {
crate::native_bridge::IsolatedWindowWorld::forget_session(
isolate,
devtools_session,
);
});
retired_count
}
pub(super) fn rebind_isolated_worlds_for_document_owner_transition(
&mut self,
retired_owner: FrameDocumentTaskOwner,
current_owner: FrameDocumentTaskOwner,
) -> usize {
let targets = self
.page_isolated_world_contexts
.contexts_with_ids()
.filter_map(|(execution_context_id, world)| {
(world.document_owner == retired_owner).then_some((
execution_context_id,
world.child_handle,
world.runtime_observable_context_token,
))
})
.collect::<Vec<_>>();
let mut rebound_count = 0;
for (execution_context_id, child_handle, realm_token) in targets {
let rebound = if let Some(child_handle) = child_handle {
let Some(context_ptr) = self
.page_isolated_world_contexts
.context(execution_context_id)
.map(|world| &world.context as *const v8::Global<v8::Context>)
else {
continue;
};
let context_host = self._context_host.clone();
let result = self
.renderer_document_isolate
.with_entered_renderer_document_isolate(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let context = unsafe { v8::Local::new(scope, &*context_ptr) };
let child_scope = &mut v8::ContextScope::new(scope, context);
let global = context.global(child_scope);
context_host
.borrow_mut()
.rebind_child_window_realm_document_state(
child_scope,
global,
child_handle,
retired_owner,
current_owner,
realm_token,
)
});
if let Err(error) = result {
tracing::warn!(
execution_context_id,
?child_handle,
?retired_owner,
?current_owner,
%error,
"failed closed while rebinding isolated-world document state"
);
false
} else {
true
}
} else {
true
};
if !rebound {
continue;
}
if let Some(world) = self
.page_isolated_world_contexts
.context_mut(execution_context_id)
&& world.document_owner == retired_owner
{
world.document_owner = current_owner;
rebound_count += 1;
}
}
rebound_count
}
pub(super) fn create_new_isolated_world(
&mut self,
devtools_session: Option<DevToolsSessionKey>,
name: &str,
grant_universal_access: bool,
frame_id: Option<String>,
child_handle: Option<DomHandle>,
) -> Result<i64> {
self.ensure_main_world()?;
let document_owner = match child_handle {
Some(child_handle) => self
._context_host
.borrow()
.current_child_document_task_owner(child_handle)
.ok_or_else(|| {
anyhow!(
"cannot create isolated world for child without a current document owner"
)
})?,
None => self
.current_main_document_task_owner()
.ok_or_else(|| anyhow!("cannot create isolated world without a main document"))?,
};
let access_policy = if grant_universal_access {
crate::native_bridge::WindowExecutionContextAccessPolicy::Universal
} else {
crate::native_bridge::WindowExecutionContextAccessPolicy::EnforceWebOrigin
};
let context_host = self._context_host.clone();
let context_bootstrap = self
.renderer_document_isolate
.with_entered_renderer_document_isolate_and_bootstrap(
|isolate, isolate_bootstrap| {
let world_definition = crate::native_bridge::IsolatedWindowWorld::ensure_named(
isolate,
name,
devtools_session.clone(),
)?;
ScriptVmContextBootstrap::new_isolated(
isolate,
isolate_bootstrap,
context_host,
self.resource_owner_id,
&self.promise_reject_dispatch,
self.indexed_db_manager.clone(),
Some(self.storage_bucket_store.clone()),
child_handle,
document_owner,
world_definition,
access_policy,
)
},
)?;
let runtime_observable_context_token = context_bootstrap.runtime_observable_context_token;
let runtime = context_bootstrap.into_runtime();
let renderer_document_isolate = self.renderer_document_isolate.clone();
let inspector_document_isolate = renderer_document_isolate.clone();
let page_inspector = &mut self.page_inspector;
let inspector_frame_id = frame_id.as_deref().or(self.root_frame_id.as_deref());
let inspector_context = renderer_document_isolate
.with_entered_renderer_document_isolate_and_inspector_mut(|isolate, inspector| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let local_context = v8::Local::new(scope, &runtime.context);
let registered_context = v8::Global::new(scope.as_ref(), local_context);
page_inspector.attach_isolated_context(
inspector_document_isolate,
inspector,
local_context,
registered_context,
None,
name,
grant_universal_access,
inspector_frame_id,
)
})?;
let (inspector_context, inspector_context_registration_id) = inspector_context
.ok_or_else(|| anyhow!("V8 inspector did not report isolated execution context id"))?;
let execution_context_id = inspector_context.id;
assert!(
!self
.page_isolated_world_contexts
.has_execution_context_id(execution_context_id),
"new isolated world reused a live execution context id"
);
let replaced_context = self.page_isolated_world_contexts.insert_context(
execution_context_id,
PageIsolatedWorldContext {
explicit: true,
name: name.to_owned(),
devtools_session,
grant_universal_access,
frame_id,
child_handle,
document_owner,
runtime,
inspector_execution_context_id: Some(inspector_context.id),
inspector_execution_context_realm_id: inspector_context.unique_id,
inspector_context_registration_id,
},
);
debug_assert!(replaced_context.is_none());
let isolated_dispatch_scope = child_handle
.map(crate::native_bridge::OwnerDispatchScope::Child)
.unwrap_or(crate::native_bridge::OwnerDispatchScope::Top);
let isolated_execution_context_owner =
crate::native_bridge::WindowExecutionContextOwner::Frame(
document_owner.local_window_id,
);
if !self
._context_host
.borrow_mut()
.register_window_execution_context_realm(
isolated_execution_context_owner,
isolated_dispatch_scope,
runtime_observable_context_token,
if grant_universal_access {
crate::native_bridge::WindowExecutionContextAccessPolicy::Universal
} else {
crate::native_bridge::WindowExecutionContextAccessPolicy::EnforceWebOrigin
},
)
{
let context = self
.page_isolated_world_contexts
.remove_context(execution_context_id);
if let Some(context) = context {
self.page_inspector
.destroy_context_registration(context.inspector_context_registration_id);
}
return Err(anyhow!(
"failed to register isolated Window execution-context realm"
));
}
if let Some(child_handle) = child_handle {
let context_ptr = self
.page_isolated_world_contexts
.context(execution_context_id)
.map(|world| &world.context as *const v8::Global<v8::Context>)
.ok_or_else(|| {
anyhow!("unknown isolated execution context `{execution_context_id}`")
})?;
let context_host = self._context_host.clone();
self.renderer_document_isolate
.with_entered_renderer_document_isolate(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let context = unsafe { v8::Local::new(scope, &*context_ptr) };
let child_scope = &mut v8::ContextScope::new(scope, context);
context_host
.borrow_mut()
.bind_child_window_indexed_db_factory_after_context_registration(
child_scope,
child_handle,
);
Ok(())
})?;
}
Ok(execution_context_id)
}
/// Publish native bootstrap results after leaving the outer V8 body. This
/// does not complete a task, run a checkpoint, or invoke page callbacks.
pub(super) fn publish_prebootstrapped_isolated_window_contexts(&mut self) -> Result<()> {
let pending = self
.prebootstrapped_child_default_contexts
.borrow_mut()
.take_pending_isolated();
for pending in pending {
let runtime = pending.runtime;
let realm_is_current = self
.renderer_document_isolate
.with_entered_renderer_document_isolate(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let context = v8::Local::new(scope, &runtime.context);
let host = self._context_host.borrow();
Ok(host
.window_execution_context_identity_for_access_check(context)
.is_some_and(|identity| {
identity.realm_token() == runtime.runtime_observable_context_token
&& host.window_execution_context_identity_is_current(identity)
}))
})?;
if !realm_is_current {
// An alias can be read and its Window navigated/detached in the
// same JS body. Runtime Drop closes this unpublished member.
continue;
}
let grant_universal_access = pending.access_policy
== crate::native_bridge::WindowExecutionContextAccessPolicy::Universal;
let renderer_isolate = self.renderer_document_isolate.clone();
let inspector_isolate = renderer_isolate.clone();
let inspector_frame_id = pending
.frame_id
.as_deref()
.or(self.root_frame_id.as_deref());
let inspector = &mut self.page_inspector;
let attached = renderer_isolate
.with_entered_renderer_document_isolate_and_inspector_mut(|isolate, backend| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let context = v8::Local::new(scope, &runtime.context);
let registered = v8::Global::new(scope, context);
inspector.attach_isolated_context(
inspector_isolate,
backend,
context,
registered,
None,
&pending.world.name,
grant_universal_access,
inspector_frame_id,
)
})?;
let (context, registration) = attached.ok_or_else(|| {
anyhow!("V8 Inspector did not publish a target-Window isolated Context")
})?;
assert!(
!self
.page_isolated_world_contexts
.has_execution_context_id(context.id),
"new target-Window Context reused a live execution context id"
);
self.page_isolated_world_contexts.insert_context(
context.id,
PageIsolatedWorldContext {
explicit: false,
name: pending.world.name.clone(),
devtools_session: pending.world.devtools_session.clone(),
grant_universal_access,
frame_id: pending.frame_id,
child_handle: pending.child_handle,
document_owner: pending.document_owner,
runtime,
inspector_execution_context_id: Some(context.id),
inspector_execution_context_realm_id: context.unique_id,
inspector_context_registration_id: registration,
},
);
}
Ok(())
}
#[cfg(feature = "devtools")]
pub(crate) fn ensure_isolated_worlds_attached_to_inspector(&mut self) -> Result<()> {
self.publish_prebootstrapped_isolated_window_contexts()?;
let pending_ids = self
.page_isolated_world_contexts
.pending_inspector_attachment_ids();
for execution_context_id in pending_ids {
let context_ptr: *const v8::Global<v8::Context> = self
.page_isolated_world_contexts
.context(execution_context_id)
.map(|world| &world.context as *const _)
.ok_or_else(|| {
anyhow!("unknown isolated execution context `{execution_context_id}`")
})?;
let (name, grant_universal_access, frame_id, replaced_registration_id) = self
.page_isolated_world_contexts
.context(execution_context_id)
.map(|world| {
(
world.name.clone(),
world.grant_universal_access,
world.frame_id.clone(),
world.inspector_context_registration_id,
)
})
.ok_or_else(|| {
anyhow!("unknown isolated execution context `{execution_context_id}`")
})?;
let inspector_frame_id = frame_id.as_deref().or(self.root_frame_id.as_deref());
let renderer_document_isolate = self.renderer_document_isolate.clone();
let inspector_document_isolate = renderer_document_isolate.clone();
let page_inspector = &mut self.page_inspector;
let inspector_context = renderer_document_isolate
.with_entered_renderer_document_isolate_and_inspector_mut(
|isolate, inspector| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let local_context = unsafe { v8::Local::new(scope, &*context_ptr) };
let registered_context = v8::Global::new(scope.as_ref(), local_context);
page_inspector.attach_isolated_context(
inspector_document_isolate,
inspector,
local_context,
registered_context,
Some(replaced_registration_id),
&name,
grant_universal_access,
inspector_frame_id,
)
},
)?;
if let Some((inspector_context, registration_id)) = inspector_context {
if let Some(world) = self
.page_isolated_world_contexts
.context_mut(execution_context_id)
{
world.inspector_context_registration_id = registration_id;
}
self.page_isolated_world_contexts
.set_inspector_execution_context_id(
execution_context_id,
inspector_context.id,
inspector_context.unique_id,
);
}
}
Ok(())
}
pub(crate) fn create_isolated_world(
&mut self,
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
self.ensure_isolated_world_for_owner(None, name, grant_universal_access)
}
#[cfg(feature = "devtools")]
pub(crate) fn create_isolated_world_for_frame(
&mut self,
frame_id: &str,
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
self.ensure_isolated_world_for_frame_owner(None, frame_id, name, grant_universal_access)
}
pub(crate) fn ensure_isolated_world_for_owner(
&mut self,
devtools_session: Option<&DevToolsSessionKey>,
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
self.publish_prebootstrapped_isolated_window_contexts()?;
if let Some(execution_context_id) = self
.page_isolated_world_contexts
.execution_context_id_for_scope(devtools_session, None, name)
{
let owner_is_current = self
.page_isolated_world_contexts
.context(execution_context_id)
.is_some_and(|world| {
self._context_host
.borrow()
.document_task_owner_is_current(world.document_owner)
});
if !owner_is_current {
return Err(anyhow!(
"isolated world `{name}` belongs to a retired main document"
));
}
let member = self
.page_isolated_world_contexts
.context_mut(execution_context_id)
.unwrap();
if !member.explicit {
member.explicit = true;
}
return Ok(execution_context_id);
}
self.create_new_isolated_world(
devtools_session.cloned(),
name,
grant_universal_access,
None,
None,
)
}
pub(crate) fn ensure_isolated_world_for_frame_owner(
&mut self,
devtools_session: Option<&DevToolsSessionKey>,
frame_id: &str,
name: &str,
grant_universal_access: bool,
) -> Result<i64> {
self.publish_prebootstrapped_isolated_window_contexts()?;
if let Some(execution_context_id) = self
.page_isolated_world_contexts
.execution_context_id_for_scope(devtools_session, Some(frame_id), name)
{
let owner_is_current = self
.page_isolated_world_contexts
.context(execution_context_id)
.is_some_and(|world| {
self._context_host
.borrow()
.document_task_owner_is_current(world.document_owner)
});
if owner_is_current {
let member = self
.page_isolated_world_contexts
.context_mut(execution_context_id)
.unwrap();
if !member.explicit {
member.explicit = true;
}
return Ok(execution_context_id);
}
self.destroy_isolated_world_context(execution_context_id);
}
let child_handle = self
._context_host
.borrow()
.child_browsing_context_handle_by_frame_id(frame_id)
.ok_or_else(|| anyhow!("no live child browsing context for frame `{frame_id}`"))?;
self.create_new_isolated_world(
devtools_session.cloned(),
name,
grant_universal_access,
Some(frame_id.to_owned()),
Some(child_handle),
)
}
pub(crate) fn install_runtime_binding(
&mut self,
name: &str,
execution_context_name: Option<&str>,
execution_context_id: Option<i64>,
) -> Result<()> {
if let Some(execution_context_id) = execution_context_id {
return self.install_runtime_binding_in_execution_context(execution_context_id, name);
}
let Some(execution_context_name) = execution_context_name else {
return self.install_runtime_binding_in_default_context(name);
};
let matching_context_ids = self
.page_isolated_world_contexts
.execution_context_ids_for_name(execution_context_name);
if matching_context_ids.is_empty() {
return Ok(());
}
for execution_context_id in matching_context_ids {
self.install_runtime_binding_in_isolated_context(execution_context_id, name)?;
}
Ok(())
}
#[cfg(feature = "devtools")]
pub(crate) fn remove_runtime_binding(&mut self, name: &str) -> Result<()> {
self.remove_runtime_binding_from_default_context(name)?;
let isolated_context_ids = self
.page_isolated_world_contexts
.execution_context_ids()
.collect::<Vec<_>>();
for execution_context_id in isolated_context_ids {
self.remove_runtime_binding_from_isolated_context(execution_context_id, name)?;
}
self.remove_runtime_binding_from_child_default_contexts(name)?;
Ok(())
}
#[cfg(feature = "devtools")]
pub(crate) fn remove_default_runtime_binding(&mut self, name: &str) -> Result<()> {
self.remove_runtime_binding_from_default_context(name)
}
#[cfg(feature = "devtools")]
pub(crate) fn run_document_start_script_now(
&mut self,
script: &DocumentStartScript,
) -> Result<Option<(i64, bool)>> {
match script.world_name.as_deref() {
Some(world_name) => {
let created = self
.page_isolated_world_contexts
.execution_context_id_for_scope(
script.devtools_session.as_ref(),
None,
world_name,
)
.is_none();
let execution_context_id = self.ensure_isolated_world_for_owner(
script.devtools_session.as_ref(),
world_name,
false,
)?;
self.exec_in_execution_context(execution_context_id, &script.source)?;
Ok(Some((execution_context_id, created)))
}
None => {
self.exec_runtime_turn(&script.source, None)?;
Ok(None)
}
}
}
#[cfg(feature = "devtools")]
pub(crate) fn run_document_start_script_in_execution_context(
&mut self,
execution_context_id: i64,
script: &DocumentStartScript,
) -> Result<()> {
self.exec_in_execution_context(execution_context_id, &script.source)
}
}