diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 89af0e1a20..ad1bdbabc7 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -202,7 +202,7 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe /// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; - let names = interp.own_keys(o)?; + let names = interp.ecma_own_keys(o)?; names_array(interp, names) } diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 529226671c..8e9b9a1f53 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -304,7 +304,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 subclass && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { + if !boundary && subclass && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 30eb8b40cf..deb59fe3bd 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1671,7 +1671,7 @@ impl Interp { _ => return internal("not a declarative environment"), }, Resolved::Obj { object, with_this } => { - let own = self.get_own_property(object, &name)?.is_some(); + let own = !with_this && object == self.global && self.get_own_property(object, &name)?.is_some(); let deleted = self.delete(object, &name, false)?; // A global variable whose own property is deleted through the global environment // no longer stops a `let` or `const` of its name (ECMA-262 2015 section 8.1.1.4.7). @@ -1824,21 +1824,21 @@ impl Interp { Ok(self.lookup_on(id, k)?.1) } - pub(crate) fn lookup_for_set(&self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn lookup_for_set(&self, id: ObjId, k: &[u16]) -> JsResult { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { if self.is_proxy(o) { - return Ok(Some(Lookup::Proxy(o))); + return Ok(SetLookup::Proxy(o)); } if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { - return Ok(None); + return Ok(SetLookup::ReadOnly); } if let Some(p) = self.ordinary_own_property(o, k)? { - return Ok(Some(Lookup::Found(p))); + return Ok(SetLookup::Found(p)); } if crate::builtins::binary::typed_key(self, o, k).is_some() { - break; + return Ok(SetLookup::Ignored); } cur = self.object(o)?.proto; steps += 1; @@ -1846,7 +1846,7 @@ impl Interp { return internal("prototype chain too long"); } } - Ok(Some(Lookup::Missing)) + Ok(SetLookup::Missing) } /// [`Self::lookup`], with the object the search stopped at: the one that has the property, or @@ -2281,6 +2281,18 @@ impl Interp { Ok(out) } + pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult> { + let mut keys = self.own_keys(id)?; + if !self.is_proxy(id) { + if matches!(self.object(id)?.class, Class::Array { .. }) { + let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; + keys.insert(0, length); + } + keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); + } + Ok(keys) + } + /// Runs `f` with `values` kept reachable for any collection it starts. pub(crate) fn rooted(&mut self, values: &[Value], f: impl FnOnce(&mut Self) -> JsResult) -> JsResult { let mark = self.temp_roots.len(); @@ -2327,21 +2339,20 @@ impl Interp { } let proto = self.object(id)?.proto; let lookup = match proto { - Some(p) => match self.lookup_for_set(p, &k)? { - Some(found) => Some(found), - None => return self.reject(throw, &k, "a module namespace object is read-only"), - }, - None => None, + Some(p) => self.lookup_for_set(p, &k)?, + None => SetLookup::Missing, }; let inherited = match lookup { - Some(Lookup::Proxy(p)) => { + SetLookup::ReadOnly => return self.reject(throw, &k, "a module namespace object is read-only"), + SetLookup::Ignored => return Ok(()), + SetLookup::Proxy(p) => { if !self.set_with_receiver(p, k.clone(), v, &Value::Object(id))? { return self.reject(throw, &k, "the proxy did not set it"); } return Ok(()); } - Some(Lookup::Found(prop)) => Some(prop), - Some(Lookup::Missing) | None => None, + SetLookup::Found(prop) => Some(prop), + SetLookup::Missing => None, }; match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), @@ -3192,9 +3203,8 @@ impl Interp { } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its - /// `ownKeys` trap, whether each is enumerable with its `getOwnPropertyDescriptor` trap and the - /// next object with its `getPrototypeOf` trap, which `temp_roots[slot]` keeps reachable. A name - /// whose descriptor trap gives `undefined` does not hide the same name further up the chain. + /// `ownKeys` trap and the next object with its `getPrototypeOf` trap, which + /// `temp_roots[slot]` keeps reachable. Descriptors are checked when iteration reaches each name. fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { let mut seen = std::collections::HashSet::new(); let mut held = HeldBytes::new(self); @@ -3210,12 +3220,9 @@ impl Interp { if seen.contains(&k) { continue; } - let Some(p) = self.get_own_property(o, &k)? else { continue }; held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); - if p.enumerable() { - out.push(k); - } + out.push(k); } cur = self.get_prototype_of(o)?; if let Some(root) = self.temp_roots.get_mut(slot) { @@ -4981,6 +4988,14 @@ pub(crate) enum Lookup { Missing, } +pub(crate) enum SetLookup { + Found(Prop), + Proxy(ObjId), + Missing, + ReadOnly, + Ignored, +} + /// What a proxy's [[Call]] or [[Construct]] did. pub(crate) enum ProxyCall { /// The proxy has no trap for it: the target is called or constructed instead. diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 9a70abf4d4..f812193c13 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -124,7 +124,9 @@ //! //! With [`Options::es2015`], the realm also has `Proxy`, with `Proxy.revocable`, and `Reflect`, as //! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5, -//! ). PROXYKEYS +//! ), with string property names: a trap is given only +//! string keys, `Reflect.ownKeys` lists only string keys, and a Symbol key read through a proxy +//! goes to its target without a trap. #![forbid(unsafe_code)] pub mod ast; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 65eb8e079a..354aa391e5 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -19,7 +19,7 @@ use crate::builtins::object::{from_desc, to_desc}; use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; -use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, Interp, JsResult, KEY_ENTRY_BYTES, Lookup, ProxyCall, merge_desc, same_value}; +use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. @@ -244,6 +244,9 @@ impl Interp { return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); } let target_prop = i.own_property(target, k)?; + if let Some(prop) = &target_prop { + i.temp_roots.extend(desc_values(&prop_desc(prop))); + } if matches!(result, Value::Undefined) { let Some(current) = target_prop else { return Ok(None) }; if !current.configurable() { @@ -403,7 +406,7 @@ impl Interp { /// unit of fuel and counts against the heap limit while the list is built. pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult> { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.own_keys(target) }; + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; let mut held = HeldBytes::new(i); let keys = i.trap_key_list(&result, &mut held)?; @@ -503,11 +506,13 @@ impl Interp { return Ok(true); } } - let Some(found) = self.lookup_for_set(o, &k)? else { return Ok(false) }; + let found = self.lookup_for_set(o, &k)?; let own = match found { - Lookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), - Lookup::Found(prop) => prop, - Lookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, + SetLookup::ReadOnly => return Ok(false), + SetLookup::Ignored => return Ok(true), + SetLookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), + SetLookup::Found(prop) => prop, + SetLookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, }; match own { Prop::Accessor { set: Some(s), .. } => { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index d3facca9c5..eac8c9c645 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -861,3 +861,117 @@ fn a_super_assignment_runs_the_set_trap_of_a_proxy_on_the_chain() { seen.join() === 'x' && !o.hasOwnProperty('x')", ); } + +#[test] +fn reflect_construct_allows_distinct_new_targets_for_collections_and_typed_arrays() { + truth( + "function Custom() {} Custom.prototype = { custom: true }; + var m = Reflect.construct(Map, [], Custom), s = Reflect.construct(Set, [], Custom); + Map.prototype.set.call(m, 'x', 7); Set.prototype.add.call(s, 8); + var u = Reflect.construct(Uint8Array, [2], Custom); u[1] = 9; + var proxied = Reflect.construct(new Proxy(Map, {}), [], Custom); + Object.getPrototypeOf(m) === Custom.prototype && Map.prototype.get.call(m, 'x') === 7 && + Object.getPrototypeOf(s) === Custom.prototype && Set.prototype.has.call(s, 8) && + Object.getPrototypeOf(u) === Custom.prototype && u[1] === 9 && + Object.getPrototypeOf(proxied) === Custom.prototype && + type_error(function () { class M extends Map {} new M(); }) && + type_error(function () { class U extends Uint8Array {} new U(1); })", + ); +} + +#[test] +fn for_in_checks_proxy_descriptors_only_when_each_candidate_is_reached() { + truth( + "var calls = [], seen = [], first = true; + var p = new Proxy({}, { + ownKeys: function () { return ['x', 'y']; }, + getOwnPropertyDescriptor: function (t, k) { + calls.push(k); + if (!first) return undefined; + first = false; + return { value: 1, enumerable: true, configurable: true }; + } + }); + for (var k in p) { seen.push(k); calls.push('body'); } + seen.join() === 'x' && calls.join() === 'x,body,y'", + ); +} + +#[test] +fn reflect_own_keys_orders_indices_and_preserves_proxy_trap_order() { + truth( + "var a = []; a[2] = 2; a[1] = 1; a.label = 'a'; + var o = {}; o.z = 0; o[10] = 10; o[2] = 2; o['01'] = 1; o['4294967295'] = 3; o.a = 4; + var p = new Proxy(a, { ownKeys: function () { return ['label', '2', 'length', '1']; } }); + Reflect.ownKeys(a).join() === '1,2,length,label' && + Reflect.ownKeys(o).join() === '2,10,z,01,4294967295,a' && + Reflect.ownKeys(new Proxy(a, {})).join() === '1,2,length,label' && + Reflect.ownKeys(p).join() === 'label,2,length,1' && + Reflect.ownKeys(new Proxy(p, {})).join() === 'label,2,length,1'", + ); +} + +#[test] +fn deleting_a_with_binding_does_not_read_its_descriptor() { + truth( + "var deleted = false, result = false; + var p = new Proxy({}, { + has: function (t, k) { return k === 'x'; }, + getOwnPropertyDescriptor: function () { throw new Error('descriptor'); }, + deleteProperty: function (t, k) { deleted = k === 'x'; return true; } + }); + with (p) { result = delete x; } + result && deleted", + ); +} + +#[test] +fn target_descriptor_values_stay_reachable_after_a_nested_proxy_is_revoked() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, Prop, key}; + use crate::value::Value; + + fn descriptor_alive(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + let marker = key("savedDescriptorMarker"); + Ok(Value::Bool(interp.heap.object_ids().iter().any(|&id| interp.heap.object(id).is_some_and(|o| o.props.get(&marker).is_some())))) + } + + for field in ["value", "get", "set"] { + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "descriptorAlive", descriptor_alive, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("descriptorAlive"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var pair, alive = false; + (function () {{ + var saved = function () {{}}; saved.savedDescriptorMarker = true; + var t = {{}}; Object.defineProperty(t, 'x', {{ {field}: saved, configurable: true }}); + pair = Proxy.revocable(t, {{ isExtensible: function () {{ pair.revoke(); return true; }} }}); + }})(); + var p = new Proxy(pair.proxy, {{ getOwnPropertyDescriptor: function () {{ return {{ + get enumerable() {{ var junk = [{{}}, {{}}]; alive = descriptorAlive(); return false; }}, configurable: true + }}; }} }}); + Reflect.getOwnPropertyDescriptor(p, 'x'); alive" + ); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let result = realm.run(&src); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(result, Ok(JsValue::Bool(true)), "{field}"); + assert!(realm.interp().heap.collections > 0); + } +} + +#[test] +fn typed_array_prototypes_ignore_invalid_numeric_indices_during_assignment() { + truth( + "var a = new Uint8Array(1), o = Object.create(a), r = {}, converted = false; + var value = { valueOf: function () { converted = true; return 9; } }; + var ok = Reflect.set(o, '2', value) && Reflect.set(o, '-0', 9) && Reflect.set(o, 'NaN', 9) && + Reflect.set(o, 'Infinity', 9) && Reflect.set(o, '0.5', 9) && Reflect.set(o, '2', 9, r); + o[3] = 9; + ok && !converted && !o.hasOwnProperty('2') && !o.hasOwnProperty('-0') && !o.hasOwnProperty('NaN') && + !o.hasOwnProperty('Infinity') && !o.hasOwnProperty('0.5') && !o.hasOwnProperty('3') && !r.hasOwnProperty('2') && + Reflect.set(o, '0', 7) && o.hasOwnProperty('0') && o[0] === 7 && a[0] === 0 && + Reflect.set(o, 'label', 8) && o.label === 8", + ); +} diff --git a/docs/mcp.md b/docs/mcp.md index ea987f0db5..8a368ddcdf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2840,7 +2840,16 @@ a trap result that breaks one of the proxy invariants, or any operation on a rev 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 `.js` run and keeps them for later `.jsx` runs. An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads -the proxy's `prototype` for the constructed object. `Object.freeze`, `Object.seal`, `Object.isFrozen` +the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor +as `newTarget` for `Map`, `Set` and typed arrays and uses its `prototype` for the new object. +`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, +then other strings in insertion order; an array's `length` precedes its other non-index strings. +A proxy's `ownKeys` trap determines its key order. A `for-in` loop checks each proxy candidate's descriptor +when iteration reaches that name. 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 +reachable during proxy callbacks, including callbacks that revoke a nested target proxy. +`Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype +without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. `Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace object before it finds the property. `Reflect.getOwnPropertyDescriptor`