fix(realms): unwrap bound function and Proxy targets

Bound functions wrapping foreign proxies can have a creation context that differs from the underlying target realm. Expose V8 GetBoundFunction and follow both internal target chains when resolving a callable realm, including revoked-Proxy errors without executing property traps.

Cover mixed chains, prototype mutation, revoked proxies, all eight Wasm constructors, and DOMParser prototype fallback with unchanged document ownership and getter counts.

Validation: cargo fmt --all; strict workspace/all-targets/all-features Clippy; full nextest (18,417 passed, 13 skipped); CLI build; 17/17 selected WPT passed. The Wasm NewTarget realm WPT improves from 112/120 to 120/120 subtests.
This commit is contained in:
ldm0
2026-11-24 14:30:19 +08:00
parent 4059bc2be2
commit ef02af6d9b
7 changed files with 174 additions and 12 deletions
@@ -974,6 +974,23 @@ fn child_webassembly_constructors_use_newtarget_child_realm_default_prototype()
bytes,
new ProxyOther(bindOther.call(freshNewTarget(NaN)), {})
),
boundProxyInterfaces: [
["Module", bytes],
["Instance", new WebAssembly.Module(bytes)],
["Memory", { initial: 0 }],
["Table", { element: "anyfunc", initial: 0 }],
["Global", { value: "i32" }],
["CompileError"], ["LinkError"], ["RuntimeError"]
].every(([name, argument]) => usesNewTargetDefaultPrototype(
name, argument, bindOther.call(new ProxyOther(freshNewTarget(false), {}))
)),
moduleMixedBoundProxy: usesNewTargetDefaultPrototype(
"Module",
bytes,
bindOther.call(new ProxyOther(
bindOther.call(new ProxyOther(freshNewTarget(null), {})), {}
))
),
memoryProxy: usesNewTargetDefaultPrototype(
"Memory",
{ initial: 0 },
@@ -994,7 +1011,7 @@ fn child_webassembly_constructors_use_newtarget_child_realm_default_prototype()
assert_eq!(
result,
r#"{"namespaceIsSeparate":true,"constructorFunctionPrototype":true,"moduleDirect":true,"moduleBound":true,"moduleProxy":true,"moduleProxyBound":true,"memoryProxy":true,"compileErrorDirect":true,"moduleTopRealm":true,"moduleIntrinsicSurvivesNamespaceReplacement":true}"#
r#"{"namespaceIsSeparate":true,"constructorFunctionPrototype":true,"moduleDirect":true,"moduleBound":true,"moduleProxy":true,"moduleProxyBound":true,"boundProxyInterfaces":true,"moduleMixedBoundProxy":true,"memoryProxy":true,"compileErrorDirect":true,"moduleTopRealm":true,"moduleIntrinsicSurvivesNamespaceReplacement":true}"#
);
}
#[test]
@@ -189,6 +189,21 @@ fn dom_parser_non_object_new_target_prototype_uses_new_target_realm_default() {
const ProxyTop = new child.Proxy(new Function(), {});
ProxyTop.prototype = 7;
const BoundProxyChild = Function.prototype.bind.call(ProxyChild);
BoundProxyChild.prototype = 7;
const BoundProxyTop = child.Function.prototype.bind.call(ProxyTop);
BoundProxyTop.prototype = 7;
let boundGetterCount = 0;
const GetterBoundProxyChild = new Proxy(BoundProxyChild, {
get(target, property, receiver) {
if (property === 'prototype') {
boundGetterCount += 1;
return 7;
}
return Reflect.get(target, property, receiver);
}
});
let getterCount = 0;
const GetterProxyChild = new Proxy(new child.Function(), {
get(target, property, receiver) {
@@ -249,7 +264,23 @@ fn dom_parser_non_object_new_target_prototype_uses_new_target_realm_default() {
child.DOMParser.prototype,
topUrl
),
getterCount
boundProxyChild: check(
Reflect.construct(DOMParser, [], BoundProxyChild),
child.DOMParser.prototype,
topUrl
),
boundProxyTop: check(
Reflect.construct(child.DOMParser, [], BoundProxyTop),
DOMParser.prototype,
childUrl
),
getterBoundProxyChild: check(
Reflect.construct(DOMParser, [], GetterBoundProxyChild),
child.DOMParser.prototype,
topUrl
),
getterCount,
boundGetterCount
});
})()
"#,
@@ -258,7 +289,7 @@ fn dom_parser_non_object_new_target_prototype_uses_new_target_realm_default() {
assert_eq!(
result,
r#"{"directTop":[true,true],"directChild":[true,true],"boundChild":[true,true],"boundTop":[true,true],"proxyChild":[true,true],"proxyTop":[true,true],"getterProxyChild":[true,true],"getterCount":1}"#
r#"{"directTop":[true,true],"directChild":[true,true],"boundChild":[true,true],"boundTop":[true,true],"proxyChild":[true,true],"proxyTop":[true,true],"getterProxyChild":[true,true],"boundProxyChild":[true,true],"boundProxyTop":[true,true],"getterBoundProxyChild":[true,true],"getterCount":1,"boundGetterCount":1}"#
);
}
+75
View File
@@ -1069,6 +1069,81 @@ mod tests {
options.into()
}
#[test]
fn callable_realm_follows_mixed_bound_and_proxy_targets_without_traps() {
ensure_v8();
let mut isolate = v8::Isolate::new(v8::CreateParams::default());
let scope = pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let target_context = v8::Context::new(scope, Default::default());
let target = {
let scope = &mut v8::ContextScope::new(scope, target_context);
let code = super::v8str(scope, "(function Target() { throw 'called'; })");
v8::Script::compile(scope, code, None)
.unwrap()
.run(scope)
.unwrap()
};
let wrapper_context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, wrapper_context);
let global = wrapper_context.global(scope);
global
.set(scope, super::v8str(scope, "target").into(), target)
.unwrap();
let code = super::v8str(
scope,
r#"
(() => {
let armed = false;
const handler = {
get(target, key, receiver) {
if (armed) throw new Error('unexpected property read');
return Reflect.get(target, key, receiver);
},
getPrototypeOf(target) {
if (armed) throw new Error('unexpected prototype read');
return Reflect.getPrototypeOf(target);
}
};
const proxy = new Proxy(target, handler);
const bound = Function.prototype.bind.call(proxy);
const mixed = Function.prototype.bind.call(new Proxy(bound, handler));
Object.setPrototypeOf(bound, null);
const revocable = Proxy.revocable(target, {});
const revokedBound = Function.prototype.bind.call(revocable.proxy);
revocable.revoke();
armed = true;
return [target, proxy, bound, mixed, new Proxy(mixed, handler), revokedBound];
})()
"#,
);
let values = v8::Script::compile(scope, code, None)
.unwrap()
.run(scope)
.unwrap();
let values = v8::Local::<v8::Array>::try_from(values).unwrap();
for index in 0..5 {
let value = values.get_index(scope, index).unwrap();
assert_eq!(
super::callable_relevant_context(scope, value),
Some(target_context)
);
}
let revoked = values.get_index(scope, 5).unwrap();
let scope = pin!(v8::TryCatch::new(scope));
let scope = &mut scope.init();
assert!(super::callable_relevant_context(scope, revoked).is_none());
let exception = scope.exception().unwrap();
let exception = v8::Local::<v8::Object>::try_from(exception).unwrap();
let expected = super::global_constructor_prototype(scope, "TypeError").unwrap();
assert!(
exception
.get_prototype(scope)
.unwrap()
.strict_equals(expected.into())
);
}
#[test]
fn utf16_string_helpers_use_code_unit_offsets() {
let value = "a\u{1f306}b";
+22 -9
View File
@@ -246,16 +246,29 @@ pub fn callable_relevant_context<'s>(
scope: &mut v8::PinScope<'s, '_>,
mut callable: v8::Local<'s, v8::Value>,
) -> Option<v8::Local<'s, v8::Context>> {
// V8's GetFunctionRealm unwraps Proxy chains. Bound functions are created
// in their target function's context, so their creation context already
// identifies the target realm through the public embedding API.
while callable.is_proxy() {
let proxy = v8::Local::<v8::Proxy>::try_from(callable).ok()?;
callable = proxy.get_target(scope);
// GetFunctionRealm follows both bound targets and Proxy targets. A bound
// Proxy's creation context need not be the underlying function's realm.
// Read internal targets without invoking author-defined property traps.
loop {
if let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(callable) {
if proxy.is_revoked() {
throw_type_error(scope, "Cannot determine the realm of a revoked Proxy");
return None;
}
callable = proxy.get_target(scope);
continue;
}
if let Ok(function) = v8::Local::<v8::Function>::try_from(callable) {
let target = function.get_bound_function(scope);
if !target.is_undefined() {
callable = target;
continue;
}
}
return v8::Local::<v8::Object>::try_from(callable)
.ok()?
.get_creation_context(scope);
}
v8::Local::<v8::Object>::try_from(callable)
.ok()?
.get_creation_context(scope)
}
pub fn new_target_realm_constructor_prototype<'s>(
+2
View File
@@ -27,6 +27,8 @@ Moli extensions:
and Web IDL bindings.
- `src/context_ext.cc` exposes global detachment and backup-incumbent-context
support used by Moli's browsing-context lifecycle.
- `src/function_ext.cc` exposes bound-function targets so Moli can resolve the
function realm through mixed bound-function and Proxy chains.
- `src/inspector_context_ext.cc` and `src/inspector_session_ext.cc` expose the
inspector context/session operations required by Moli's CDP implementation.
- `src/module_ext.cc` exposes the synthetic-module export hook used to write
+10
View File
@@ -56,6 +56,7 @@ unsafe extern "C" {
argv: *const *const Value,
) -> *const Object;
fn v8__Function__GetName(this: *const Function) -> *const Value;
fn v8__Function__GetBoundFunction(this: *const Function) -> *const Value;
fn v8__Function__SetName(this: *const Function, name: *const String);
fn v8__Function__GetScriptColumnNumber(this: *const Function) -> int;
fn v8__Function__GetScriptLineNumber(this: *const Function) -> int;
@@ -1097,6 +1098,15 @@ impl Function {
unsafe { scope.cast_local(|_| v8__Function__GetName(self)).unwrap() }
}
/// Returns the target of a bound function, or undefined for other functions.
#[inline(always)]
pub fn get_bound_function<'s>(
&self,
scope: &PinScope<'s, '_>,
) -> Local<'s, Value> {
unsafe { scope.cast_local(|_| v8__Function__GetBoundFunction(self)).unwrap() }
}
#[inline(always)]
pub fn set_name(&self, name: Local<String>) {
unsafe { v8__Function__SetName(self, &*name) }
+14
View File
@@ -0,0 +1,14 @@
// Copyright 2026 the Moli authors. MIT license.
#include "support.h"
#include "v8-function.h"
using namespace support;
extern "C" {
const v8::Value* v8__Function__GetBoundFunction(const v8::Function& self) {
return local_to_ptr(ptr_to_local(&self)->GetBoundFunction());
}
} // extern "C"