diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index a6d8babc9e..e5027df1c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let (keys, held) = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok((list, held)) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 20338eeca2..a3655d2b17 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1757,6 +1757,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); } +#[test] +fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0; + var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }}); + find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + #[test] fn transparent_proxy_and_reflect_membership_use_host_indexers() { let index: HostFunction = Rc::new(|args| { @@ -2036,6 +2049,14 @@ fn json_proxy_replacer_lengths_use_to_length() { ); } +#[test] +fn json_replacer_lists_charge_only_the_names_they_keep() { + // A long, sparse replacer array keeps one name, so only that name counts against the heap. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'"; + assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true))); +} + #[test] fn json_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { @@ -2061,13 +2082,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { ), LimitKind::Fuel ); + // A replacer list's length alone is not charged to the heap; the names it keeps are. let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run( + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } }); + JSON.stringify({ a: 1 }, p) === '{}'" + ), + Ok(JsValue::Bool(true)) + ); assert_eq!( limit( - "var p = new Proxy([], { get: function (t, k) { - if (k === 'length') return 1000000; - throw new Error('element read'); - } }); JSON.stringify({}, p)", + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } }); + JSON.stringify({}, p)", limits, ), LimitKind::Heap @@ -2116,6 +2143,41 @@ fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { ); } +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = [], extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads.push(String(k)); + if (k === s) Object.defineProperty(t, u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + // The descriptor of `s`, read first, makes `u` non-configurable before `u` is read, so the + // outer trap that leaves `u` out breaks the invariant. + var threw = type_error(function () { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a', s]; } })); }); + var ok = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', u, 'a']; } })); + threw && reads.slice(0, 4).join() === 'Symbol(s),a,Symbol(u),b' && extensible === 2 && ok.length === 3", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + #[test] fn own_keys_consumers_keep_interleaved_trap_keys() { truth( diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 62c63c6bb0..2949ccba0c 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult flat_charged(interp, &s)?, Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?, _ => continue, diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..4e380d9057 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2902,7 +2902,8 @@ A conversion or syntax error throws before that prototype getter runs. membership checks use host collection indexers, including numeric indices and named items. `JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys -or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped. +or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped, +and each distinct name a replacer array keeps counts against it until the call returns. Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before @@ -2911,7 +2912,8 @@ the maximum safe integer. Reviver traversal keys count against the heap limit un In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating -its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations +its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without +calling proxy traps, so a proxy receiver throws `TypeError`. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, `defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation