JavaScript: proxy checks follow GetFunctionRealm, subclass order and for-in sources

- A non-object `prototype` on `new.target` walks its bound and proxy chain
  (GetFunctionRealm), so a get trap that revokes the proxy throws a
  TypeError instead of running the constructor.
- A subclassable built-in such as Number no longer unwraps a revoked
  `new.target` before its own argument conversion runs.
- for-in records how many proxies came before the object that first listed
  each name, and the recheck does not ask those proxies for a descriptor, so
  a proxy that did not list a name cannot hide an inherited enumerable one.
- Names from an ownKeys trap take fuel for their code units, and so do the
  names the ownKeys invariant check hashes.
- The DataView argument test expects TypeError for a non-buffer and
  RangeError for a bad offset or length.
This commit is contained in:
dotCooCoo committed 2026-12-01 09:06:27 -08:00
1 parent d74312bedc
commit b3c1a31cfa
6 files changed
+164 -23

No files matched your search

+24 -2
View File
@@ -176,10 +176,32 @@ impl Interp {
}
/// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14).
/// Before falling back it runs GetFunctionRealm (section 7.3.22) on `new.target`, which
/// throws a `TypeError` for a revoked proxy in its bound or proxy chain.
pub(crate) fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult<ObjId> {
match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? {
Value::Object(p) => Ok(p),
_ => Ok(fallback),
_ => {
self.function_realm(new_target)?;
Ok(fallback)
}
}
}
/// GetFunctionRealm (section 7.3.22). There is one realm, so this only walks the bound
/// and proxy chain of `f` and throws a `TypeError` when it reaches a revoked proxy.
/// Each hop takes a unit of fuel.
fn function_realm(&mut self, mut f: ObjId) -> JsResult<()> {
loop {
let next = match self.symbol_lookup_target(f)? {
Some(t) => t,
None => match self.func_of(&Value::Object(f)) {
Some(Func::Bound { target, .. }) => target,
_ => return Ok(()),
},
};
self.use_fuel()?;
f = next;
}
}
@@ -313,7 +335,7 @@ impl Interp {
Some(Func::Native { f: native, constructor: true, name, .. }) => {
// `Proxy` does not read `new.target` (section 26.2.1.1).
let subclass = nt != callee && name != "Proxy";
if !boundary && subclass && !forwarding && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? {
if !boundary && subclass && !forwarding && !self.subclassable(callee)? && self.unwrapped_proxy_target(nt)? != callee {
return Err(self.type_error("this built-in cannot be subclassed"));
}
let intrinsic = match self.get_own_property(callee, &key("prototype"))? {
+4
View File
@@ -215,6 +215,9 @@ pub(crate) struct ArgMap {
#[derive(Clone, Debug)]
pub(crate) struct ForIn {
pub(crate) keys: Vec<Key>,
/// For each name, how many proxies came before the object that first listed it on the
/// chain; empty when no name came after a proxy. A missing entry counts as 0.
pub(crate) starts: Vec<u32>,
pub(crate) pos: usize,
pub(crate) object: Option<ObjId>,
}
@@ -1180,6 +1183,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
Class::ForIn(state) => {
work.extend(state.object.iter().map(|o| o.0));
strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
strings.bytes += state.starts.len() * crate::interp::SOURCE_ENTRY_BYTES;
}
Class::Symbol(s) => strings.add_symbol(s),
Class::IterRecord(r) => {
+52 -15
View File
@@ -571,6 +571,9 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16;
/// The estimated bytes of a name's entries in the list and the set `for-in` builds.
pub(crate) const KEY_ENTRY_BYTES: usize = 32;
/// The bytes of one entry in the list of proxy counts `for-in` keeps for each name.
pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::<u32>();
/// The most units of a computed property name an error about a property of `null` or `undefined`
/// names; a longer name is left out of the message.
const NAMED_KEY_UNITS: usize = 256;
@@ -3298,9 +3301,12 @@ impl Interp {
///
/// For a String object, the heap budget for all its index names is checked before any is
/// built. Each index name and each property visited takes a unit of fuel.
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<Vec<Key>> {
///
/// The second list holds, for each name, how many proxies came before the object that
/// listed it. It is empty or shorter than the names when the missing entries are 0.
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec<Key>, Vec<u32>)> {
if self.options.e4x && self.is_xml(&Value::Object(id)) {
return self.xml_enumerate(id);
return Ok((self.xml_enumerate(id)?, Vec::new()));
}
let slot = self.temp_roots.len();
self.temp_roots.push(Value::Undefined);
@@ -3313,12 +3319,15 @@ impl Interp {
/// `ownKeys` trap and the next object with its `getPrototypeOf` trap.
/// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype.
/// Descriptors are checked when iteration reaches each name.
fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<Vec<Key>> {
fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec<Key>, Vec<u32>)> {
let mut seen = std::collections::HashSet::new();
let mut held = HeldBytes::new(self);
let mut out = Vec::new();
let mut starts: Vec<u32> = Vec::new();
let mut proxies = 0u32;
let mut cur = Some(id);
while let Some(o) = cur {
let before = out.len();
if self.is_proxy(o) {
if let Some(root) = self.temp_roots.get_mut(slot) {
*root = Value::Object(o);
@@ -3333,6 +3342,8 @@ impl Interp {
seen.insert(k.clone());
out.push(k);
}
self.note_listed(&mut starts, &mut held, before, out.len(), proxies)?;
proxies = proxies.saturating_add(1);
cur = self.get_prototype_of(o)?;
if let Some(root) = self.temp_roots.get_mut(slot) {
*root = cur.map_or(Value::Undefined, Value::Object);
@@ -3379,14 +3390,28 @@ impl Interp {
}
}
cur = obj.proto;
self.note_listed(&mut starts, &mut held, before, out.len(), proxies)?;
}
Ok(out)
Ok((out, starts))
}
/// Records that the names from `before` to `len` came after `proxies` proxies, counting
/// the new entries. Nothing is recorded when `proxies` is 0 or no name was added, since a
/// missing entry counts as 0.
fn note_listed(&mut self, starts: &mut Vec<u32>, held: &mut HeldBytes, before: usize, len: usize, proxies: u32) -> JsResult<()> {
if proxies == 0 || len == before {
return Ok(());
}
held.add(self, len.saturating_sub(starts.len()).saturating_mul(SOURCE_ENTRY_BYTES))?;
starts.resize(before, 0);
starts.resize(len, proxies);
Ok(())
}
fn op_for_in_start(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let (keys, object) = if v.is_nullish() {
(Vec::new(), None)
let ((keys, starts), object) = if v.is_nullish() {
((Vec::new(), Vec::new()), None)
} else {
let o = self.to_object(&v)?;
// A wrapper made by ToObject is not on the stack; a collection while the names are
@@ -3395,16 +3420,16 @@ impl Interp {
self.temp_roots.push(Value::Object(o));
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
let keys = self.enumerable_keys(o).and_then(|keys| {
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
let keys = self.enumerable_keys(o).and_then(|(keys, starts)| {
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>() + starts.len() * SOURCE_ENTRY_BYTES;
self.reserve_heap(bytes)?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
Ok(keys)
Ok((keys, starts))
});
self.temp_roots.truncate(saved);
(keys?, Some(o))
};
let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, pos: 0, object })), None));
let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, starts, pos: 0, object })), None));
self.replace(1, Value::Object(iter))
}
@@ -3413,10 +3438,15 @@ impl Interp {
loop {
let Class::ForIn(state) = &mut self.object_mut(iter)?.class else { return internal("not a for-in iterator") };
let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) };
let skip = state.starts.get(state.pos).copied().unwrap_or(0);
state.pos += 1;
let object = state.object;
let Some(o) = object else { continue };
let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k)? };
let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) {
self.scope_has(o, &k)?
} else {
self.for_in_still_has(o, &k, skip)?
};
if visit {
return self.push(Value::String(Str::from_rc(k)));
}
@@ -3429,16 +3459,21 @@ impl Interp {
/// the objects that follow it are searched. A name deleted or made non-enumerable after the
/// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is
/// not asked. Each proxy on the chain takes a unit of fuel.
fn for_in_still_has(&mut self, o: ObjId, k: &Key) -> JsResult<bool> {
///
/// `skip` is how many proxies came before the object that first listed `k`. Those proxies
/// did not list `k`, so the first `skip` proxies the walk reaches are not asked through
/// their `getOwnPropertyDescriptor` trap and cannot hide an inherited name.
fn for_in_still_has(&mut self, o: ObjId, k: &Key, skip: u32) -> JsResult<bool> {
// One root slot holds the prototype the walk has reached; each hop replaces it.
let mark = self.temp_roots.len();
self.temp_roots.push(Value::Undefined);
let r = self.for_in_still_has_rooted(o, k, mark);
let r = self.for_in_still_has_rooted(o, k, skip, mark);
self.temp_roots.truncate(mark);
r
}
fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, slot: usize) -> JsResult<bool> {
fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, skip: u32, slot: usize) -> JsResult<bool> {
let mut passed = 0u32;
loop {
let p = match self.lookup(cur, k)? {
Lookup::Found(prop) => return Ok(prop.enumerable()),
@@ -3446,7 +3481,9 @@ impl Interp {
Lookup::Proxy(p) => p,
};
self.use_fuel()?;
if let Some(prop) = self.get_own_property(p, k)? {
let asked = passed >= skip;
passed = passed.saturating_add(1);
if asked && let Some(prop) = self.get_own_property(p, k)? {
return Ok(prop.enumerable());
}
let Some(next) = self.get_prototype_of(p)? else { return Ok(false) };
+16
View File
@@ -477,6 +477,8 @@ impl Interp {
match v {
Value::String(s) => {
held.add(self, string_bytes(s.len()).saturating_add(3 * KEY_ENTRY_BYTES))?;
// Flattening and hashing the name read every code unit of it.
crate::string_builtins::charge_units(self, s.len())?;
let k = s.flat();
if !seen.insert(k.clone()) && duplicate.is_none() {
duplicate = Some(PropKey::Str(k.clone()));
@@ -530,9 +532,14 @@ impl Interp {
if extensible && fixed.is_empty() {
return Ok(());
}
// Building the set and each lookup in it hash every code unit of the name.
for k in keys {
crate::string_builtins::charge_units(self, k.len())?;
}
let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect();
let mut unchecked_syms: HashSet<usize> = syms.iter().map(Sym::addr).collect();
for k in &fixed {
charge_lookup(self, k)?;
if !take(&mut unchecked, &mut unchecked_syms, k) {
let name = self.pk_name(k)?;
return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target")));
@@ -542,6 +549,7 @@ impl Interp {
return Ok(());
}
for k in &configurable {
charge_lookup(self, k)?;
if !take(&mut unchecked, &mut unchecked_syms, k) {
let name = self.pk_name(k)?;
return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target")));
@@ -768,6 +776,14 @@ fn pk_root(k: &PropKey) -> Value {
}
}
/// Takes the fuel for hashing the name `k` to look it up; a Symbol is looked up by address.
fn charge_lookup(interp: &mut Interp, k: &PropKey) -> JsResult<()> {
match k {
PropKey::Str(name) => crate::string_builtins::charge_units(interp, name.len()),
PropKey::Sym(_) => Ok(()),
}
}
/// Removes `k` from the keys a trap gave that are not yet matched: whether it was there.
fn take(names: &mut HashSet<&[u16]>, syms: &mut HashSet<usize>, k: &PropKey) -> bool {
match k {
+66 -5
View File
@@ -1743,11 +1743,11 @@ fn binary_constructors_validate_arguments_before_reading_new_target_prototype()
return false;
});
var buffer = new ArrayBuffer(4);
ok = ok && [function () { Reflect.construct(DataView, [{}], nt); },
function () { Reflect.construct(DataView, [buffer, -1], nt); },
function () { Reflect.construct(DataView, [buffer, 5], nt); },
function () { Reflect.construct(DataView, [buffer, 0, 5], nt); }].every(function (f) {
try { f(); } catch (e) { return (e instanceof RangeError || e instanceof TypeError) && reads === 0; }
ok = ok && [[TypeError, function () { Reflect.construct(DataView, [{}], nt); }],
[RangeError, function () { Reflect.construct(DataView, [buffer, -1], nt); }],
[RangeError, function () { Reflect.construct(DataView, [buffer, 5], nt); }],
[RangeError, function () { Reflect.construct(DataView, [buffer, 0, 5], nt); }]].every(function (c) {
try { c[1](); } catch (e) { return e instanceof c[0] && reads === 0; }
return false;
});
var a = Reflect.construct(ArrayBuffer, [2], nt), u = Reflect.construct(Uint8Array, ['2'], nt);
@@ -1766,6 +1766,67 @@ fn binary_constructors_validate_arguments_before_reading_new_target_prototype()
);
}
#[test]
fn a_new_target_revoked_while_its_prototype_is_read_is_a_type_error() {
type_errors(&[
"var r = Proxy.revocable(function () {}, { get: function () { r.revoke(); return 1; } });
var ran = false;
Reflect.construct(function () { ran = true; }, [], r.proxy);",
"var r = Proxy.revocable(function () {}, { get: function () { r.revoke(); return 1; } });
Reflect.construct(Array, [], r.proxy);",
]);
truth(
"var proto = {};
var r = Proxy.revocable(function () {}, { get: function () { r.revoke(); return proto; } });
Object.getPrototypeOf(Reflect.construct(function () {}, [], r.proxy)) === proto",
);
}
#[test]
fn long_names_from_an_own_keys_trap_take_fuel_by_length() {
let src = "var k = 'x'; while (k.length < 262144) k += k;
var p = new Proxy({}, { ownKeys: function () { return [k]; } });
for (var i = 0; i < 20; i++) Reflect.ownKeys(p);";
assert_eq!(limit(src, Limits { fuel: 200_000, ..Limits::default() }), LimitKind::Fuel);
}
#[test]
fn for_in_over_a_proxy_visits_an_inherited_name_the_proxy_did_not_list() {
truth(
"var proto = { x: 1 };
var p = new Proxy(Object.create(proto), {
ownKeys: function () { return []; },
getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; },
getPrototypeOf: function () { return proto; }
});
var seen = [];
for (var name in p) seen.push(name);
seen.join() === 'x'",
);
truth(
"var b = new Proxy({ x: 1 }, {});
var a = new Proxy(Object.create(b), {
ownKeys: function () { return ['x']; },
getOwnPropertyDescriptor: function () { return undefined; },
getPrototypeOf: function () { return b; }
});
var seen = [];
for (var name in a) seen.push(name);
seen.join() === 'x'",
);
}
#[test]
fn a_subclassable_built_in_does_not_unwrap_a_revoked_new_target() {
truth(
"class C extends Number { constructor(v) { r.revoke(); super(v); } }
var r = Proxy.revocable(C, {});
var thrown = {}, caught;
try { Reflect.construct(C, [{ valueOf: function () { throw thrown; } }], r.proxy); } catch (e) { caught = e; }
caught === thrown",
);
}
#[test]
fn proxy_invariants_preserve_namespace_initialization_errors() {
let mut realm = es();
+2 -1
View File
@@ -2862,7 +2862,8 @@ and a run with `module: true` also have the
globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1
and 26.2), with string and Symbol property keys. A trap is a script call: it takes fuel and counts against the limit on nested calls.
The copy of the property name it is given, key lists retained by enumeration callers, and the names retained during
a `for-in` prototype walk count against the heap limit. A trap result that breaks one of the proxy invariants,
a `for-in` prototype walk count against the heap limit. Each name an `ownKeys` trap returns takes fuel for its
UTF-16 code units, as does each name the proxy invariants check. A trap result that breaks one of the proxy invariants,
or any operation on a revoked proxy, throws a `TypeError`. A
proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets
`Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs.