Merge pull request #10582 from dotCooCoo/fix/for-in-fresh-prototype-proxy

Scripts: for-in visits a name when a getPrototypeOf trap returns a new proxy each time
This commit is contained in:
.CooCoo
2026-12-02 11:14:59 -08:00
committed by GitHub
4 changed files with 191 additions and 37 deletions
+6 -5
View File
@@ -215,9 +215,8 @@ pub(crate) struct ArgMap {
#[derive(Clone, Debug)]
pub(crate) struct ForIn {
pub(crate) keys: Vec<Key>,
/// The proxies whose `ownKeys` trap returned a listed name, each with the positions in `keys`
/// of the names it returned.
pub(crate) listed: Vec<Listed>,
/// Each proxy on the chain maps to the positions in `keys` of the names its `ownKeys` trap returned.
pub(crate) listed: HashMap<ObjId, Listed>,
pub(crate) pos: usize,
pub(crate) object: Option<ObjId>,
}
@@ -227,7 +226,8 @@ pub(crate) struct ForIn {
/// name's position is here.
#[derive(Clone, Debug)]
pub(crate) struct Listed {
pub(crate) proxy: ObjId,
/// The proxy returned by this proxy's prototype lookup, if any.
pub(crate) prototype: Option<ObjId>,
pub(crate) positions: Vec<u32>,
}
@@ -1191,7 +1191,8 @@ 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));
work.extend(state.listed.iter().map(|l| l.proxy.0));
work.extend(state.listed.keys().map(|o| o.0));
work.extend(state.listed.values().filter_map(|l| l.prototype.map(|o| o.0)));
strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
strings.bytes += crate::interp::listed_bytes(&state.listed);
}
+58 -30
View File
@@ -18,6 +18,7 @@
//! keeps its operands on the operand stack until it is done, so everything it holds is reachable
//! from the roots when a nested run collects.
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -575,11 +576,11 @@ pub(crate) const KEY_ENTRY_BYTES: usize = 32;
pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::<u32>();
/// The bytes of a `for-in` loop's record of one proxy that listed names, without its positions.
const LISTED_ENTRY_BYTES: usize = std::mem::size_of::<Listed>();
const LISTED_ENTRY_BYTES: usize = std::mem::size_of::<(ObjId, Listed)>() + KEY_ENTRY_BYTES;
/// The bytes of a `for-in` loop's records of the proxies that listed its names.
pub(crate) fn listed_bytes(listed: &[Listed]) -> usize {
listed.iter().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum()
pub(crate) fn listed_bytes(listed: &HashMap<ObjId, Listed>) -> usize {
listed.values().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum()
}
/// The most units of a computed property name an error about a property of `null` or `undefined`
@@ -3332,29 +3333,28 @@ 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.
///
/// The second list holds each proxy whose `ownKeys` trap returned a listed name, with the
/// positions of the names it returned.
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec<Key>, Vec<Listed>)> {
/// The map records each proxy's listed positions and the proxy returned by its prototype lookup.
/// Listing roots remain until `op_for_in_start` installs the iterator.
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec<Key>, HashMap<ObjId, Listed>)> {
if self.options.e4x && self.is_xml(&Value::Object(id)) {
return Ok((self.xml_enumerate(id)?, Vec::new()));
return Ok((self.xml_enumerate(id)?, HashMap::new()));
}
let slot = self.temp_roots.len();
self.temp_roots.push(Value::Undefined);
let r = self.enumerable_keys_from(id, slot);
self.temp_roots.truncate(slot);
r
self.enumerable_keys_from(id, slot)
}
/// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its
/// `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>, Vec<Listed>)> {
fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec<Key>, HashMap<ObjId, Listed>)> {
// Each name met on the chain, with its position in `out` when it is listed.
let mut seen: std::collections::HashMap<Key, Option<u32>> = std::collections::HashMap::new();
let mut held = HeldBytes::new(self);
let mut out: Vec<Key> = Vec::new();
let mut listed: Vec<Listed> = Vec::new();
let mut listed = HashMap::new();
let mut proxy_positions: std::collections::HashSet<(ObjId, u32)> = std::collections::HashSet::new();
let next_pos = |out: &Vec<Key>| u32::try_from(out.len()).unwrap_or(u32::MAX);
let mut cur = Some(id);
while let Some(o) = cur {
@@ -3362,6 +3362,7 @@ impl Interp {
if let Some(root) = self.temp_roots.get_mut(slot) {
*root = Value::Object(o);
}
self.temp_roots.push(Value::Object(o));
let keys = self.own_keys(o)?;
let mut positions = Vec::new();
for k in keys {
@@ -3377,18 +3378,20 @@ impl Interp {
}
};
// A name an earlier object has but does not list is not listed again.
if let Some(pos) = pos {
held.add(self, SOURCE_ENTRY_BYTES)?;
// A proxy met again on the chain records each position once.
if let Some(pos) = pos.filter(|&pos| !proxy_positions.contains(&(o, pos))) {
held.add(self, SOURCE_ENTRY_BYTES.saturating_add(KEY_ENTRY_BYTES))?;
proxy_positions.insert((o, pos));
positions.push(pos);
}
}
if !positions.is_empty() {
held.add(self, LISTED_ENTRY_BYTES)?;
positions.sort_unstable();
positions.dedup();
listed.push(Listed { proxy: o, positions });
}
held.add(self, LISTED_ENTRY_BYTES)?;
cur = self.get_prototype_of(o)?;
let prototype = cur.filter(|&p| self.is_proxy(p));
// A proxy met again on the chain keeps the names its earlier visits listed.
let entry = listed.entry(o).or_insert_with(|| Listed { prototype, positions: Vec::new() });
entry.prototype = prototype;
entry.positions.append(&mut positions);
if let Some(root) = self.temp_roots.get_mut(slot) {
*root = cur.map_or(Value::Undefined, Value::Object);
}
@@ -3439,18 +3442,30 @@ impl Interp {
}
cur = obj.proto;
}
// Sorted once after the walk, for the iterator's binary search.
for entry in listed.values_mut() {
entry.positions.sort_unstable();
entry.positions.dedup();
entry.positions.shrink_to_fit();
}
Ok((out, listed))
}
fn op_for_in_start(&mut self) -> JsResult<()> {
let saved = self.temp_roots.len();
let r = self.op_for_in_start_rooted();
self.temp_roots.truncate(saved);
r
}
fn op_for_in_start_rooted(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let ((keys, listed), object) = if v.is_nullish() {
((Vec::new(), Vec::new()), None)
((Vec::new(), HashMap::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
// listed or their bytes reserved must not free it.
let saved = self.temp_roots.len();
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.
@@ -3460,7 +3475,6 @@ impl Interp {
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
Ok((keys, listed))
});
self.temp_roots.truncate(saved);
(keys?, Some(o))
};
let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, listed, pos: 0, object })), None));
@@ -3493,8 +3507,9 @@ impl Interp {
///
/// `pos` is the position of `k` in the names of the loop `iter`. A proxy is asked through its
/// `getOwnPropertyDescriptor` trap only when its `ownKeys` trap returned `k` while the names
/// were listed, wherever it sits on the chain now; any other proxy cannot hide an inherited
/// name. A typed array without the element `k` names does not hide its prototypes' `k`.
/// were listed, or when the same prototype lookup returns a fresh proxy of that target.
/// Recorded proxies can move on the chain; any other proxy cannot hide an inherited name.
/// A typed array without the element `k` names does not hide its prototypes' `k`.
fn for_in_still_has(&mut self, iter: ObjId, o: ObjId, k: &Key, pos: u32) -> JsResult<bool> {
// One root slot holds the proxy the walk has reached, then the prototype it gave.
let mark = self.temp_roots.len();
@@ -3506,13 +3521,18 @@ impl Interp {
fn for_in_still_has_rooted(&mut self, iter: ObjId, mut cur: ObjId, k: &Key, pos: u32, slot: usize) -> JsResult<bool> {
let mut steps = 0usize;
let mut candidate = None;
loop {
if self.is_proxy(cur) {
if let Some(root) = self.temp_roots.get_mut(slot) {
*root = Value::Object(cur);
}
self.use_fuel()?;
if self.for_in_listed_by(iter, cur, pos)?
let source = self.for_in_listing_proxy(iter, cur, candidate)?;
let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") };
let listed = source.and_then(|p| state.listed.get(&p));
candidate = listed.and_then(|l| l.prototype);
if listed.is_some_and(|l| l.positions.binary_search(&pos).is_ok())
&& let Some(prop) = self.get_own_property(cur, k)?
{
return Ok(prop.enumerable());
@@ -3524,6 +3544,7 @@ impl Interp {
cur = next;
continue;
}
candidate = None;
if let Some(prop) = self.ordinary_own_property(cur, k)? {
return Ok(prop.enumerable());
}
@@ -3536,11 +3557,18 @@ impl Interp {
}
}
/// Whether the `ownKeys` trap of `proxy` returned the name at `pos` when the loop `iter`
/// listed its names.
fn for_in_listed_by(&self, iter: ObjId, proxy: ObjId, pos: u32) -> JsResult<bool> {
/// Finds a recorded proxy by identity or by the preceding proxy's recorded prototype lookup.
fn for_in_listing_proxy(&self, iter: ObjId, proxy: ObjId, candidate: Option<ObjId>) -> JsResult<Option<ObjId>> {
let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") };
Ok(state.listed.iter().any(|l| l.proxy == proxy && l.positions.binary_search(&pos).is_ok()))
if state.listed.contains_key(&proxy) {
return Ok(Some(proxy));
}
let target = |p: ObjId| match self.heap.object(p).map(|o| &o.class) {
Some(Class::Proxy(d)) => d.target,
_ => None,
};
let Some(own) = target(proxy) else { return Ok(None) };
Ok(candidate.filter(|&p| target(p) == Some(own)))
}
// ---- calls ----
+125
View File
@@ -1854,6 +1854,131 @@ fn for_in_asks_only_the_proxies_that_listed_a_name() {
);
}
#[test]
fn for_in_visits_a_name_from_a_prototype_trap_that_returns_a_new_proxy_each_time() {
// Each [[GetPrototypeOf]] gives a new proxy of `t`: the one asked before each name is not the
// one whose ownKeys listed it.
truth_collecting(
"var t = { a: 1, b: 2 };
var o = new Proxy({}, { ownKeys: function () { return []; }, getPrototypeOf: function () { return new Proxy(t, {}); } });
var seen = [];
for (var name in o) seen.push(name);
seen.join() === 'a,b'",
);
// A non-enumerable descriptor from such a proxy still does not hide a name further on.
truth(
"var c = { x: 1 };
var o = new Proxy({}, {
ownKeys: function () { return []; },
getPrototypeOf: function () {
return new Proxy({}, {
ownKeys: function () { return []; },
getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; },
getPrototypeOf: function () { return c; }
});
}
});
var seen = [];
for (var name in o) seen.push(name);
seen.join() === 'x'",
);
// Two proxies of one target on the chain: the one that listed nothing does not decide for the
// one that listed `x`.
truth(
"var t = {};
var b = new Proxy(t, {
ownKeys: function () { return ['x']; },
getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; }
});
var a = new Proxy(t, {
ownKeys: function () { return []; },
getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; },
getPrototypeOf: function () { return b; }
});
var seen = [];
for (var name in a) seen.push(name);
seen.join() === 'x'",
);
}
#[test]
fn for_in_keeps_the_names_a_proxy_listed_before_it_returns_itself_as_its_prototype() {
// The first visit lists `x`; the proxy is its own prototype once, and the second visit lists
// nothing. The name from the first visit is still visited.
truth(
"var keysCalls = 0, protoCalls = 0;
var p = new Proxy({}, {
ownKeys: function () { return keysCalls++ === 0 ? ['x'] : []; },
getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; },
getPrototypeOf: function () { return protoCalls++ === 0 ? p : null; }
});
var seen = [];
for (var name in p) seen.push(name);
seen.join() === 'x'",
);
}
#[test]
fn for_in_matches_nested_fresh_wrappers_to_their_prototype_lookups() {
truth_collecting(
"var t = { a: 1, b: 2 }, middle = {};
var handler = {
ownKeys: function () { return []; },
getPrototypeOf: function () { return new Proxy(t, {}); }
};
var o = new Proxy({}, {
ownKeys: function () { return []; },
getPrototypeOf: function () { return new Proxy(middle, handler); }
});
var seen = [];
for (var name in o) seen.push(name);
seen.join() === 'a,b'",
);
}
#[test]
fn for_in_does_not_ask_an_inserted_proxy_of_a_listing_proxys_target() {
truth_collecting(
"var t = { a: 1, b: 2 }, reads = 0;
var listed = new Proxy(t, {});
var o = Object.create(listed), seen = [];
for (var name in o) {
seen.push(name);
if (name === 'a') {
Object.setPrototypeOf(o, new Proxy(t, {
getOwnPropertyDescriptor: function () {
reads++;
return { value: 0, enumerable: false, configurable: true };
},
getPrototypeOf: function () { return listed; }
}));
}
}
seen.join() === 'a,b' && reads === 0",
);
}
#[test]
fn for_in_walks_many_empty_proxies_before_inherited_names() {
truth(
"var base = {}, depth = 256, count = 32, walks = 0, reads = 0;
for (var i = 0; i < count; i++) base['key' + i] = i;
function wrap(next) {
return new Proxy({}, {
ownKeys: function () { return []; },
getOwnPropertyDescriptor: function () { reads++; return undefined; },
getPrototypeOf: function () { walks++; return next; }
});
}
var o = base;
for (var j = 0; j < depth; j++) o = wrap(o);
var seen = [];
for (var name in o) seen.push(name);
seen.length === count && seen.every(function (name, index) { return name === 'key' + index; }) &&
reads === 0 && walks === depth * (count + 1)",
);
}
#[test]
fn for_in_reaches_a_name_past_a_typed_array_without_that_element() {
truth(
+2 -2
View File
@@ -2924,8 +2924,8 @@ the same key twice (two Symbols are the same key only when they are the same Sym
result is checked against the target's non-configurable keys of both kinds. A `for-in` prototype walk keeps the current proxy reachable
through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain.
A `for-in` loop checks each proxy candidate's descriptor
when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, wherever they sit
on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate
when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, or a new proxy of
the same target that the same `getPrototypeOf` trap returns in its place (such a trap may return a new proxy on each call), wherever they sit on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate
names are rejected; a later getter's exception takes precedence over the duplicate-name error.
Deleting a binding in a `with` scope calls the proxy's `deleteProperty`
trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay