From f3b3cbfe67d6641d2aed904a7ce9a63bdd0c607d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:16:56 -0800 Subject: [PATCH] JavaScript: proxies keep revocation, namespace and collection rules, and key lists stay counted A revoked proxy no longer gives its own Symbol properties, the reflect extension reads proxies without running traps, key lists a proxy gives stay counted against the heap while callers use them, has through a proxy of a host collection asks the collection, a proxy's invariant checks keep a namespace's uninitialized-export errors, and a binary constructor checks its arguments before it reads newTarget's prototype. Trap arguments stay rooted while a trap runs. --- crates/js/src/builtins/binary.rs | 54 +++++++++- crates/js/src/builtins/json.rs | 8 +- crates/js/src/builtins/object.rs | 20 ++-- crates/js/src/builtins/reflect.rs | 2 +- crates/js/src/class_ops.rs | 10 +- crates/js/src/interp.rs | 52 +++++++-- crates/js/src/proxy.rs | 34 +++--- crates/js/src/proxy_tests.rs | 169 ++++++++++++++++++++++++++++++ crates/js/src/reflect.rs | 3 + crates/js/src/symbol.rs | 5 +- docs/mcp.md | 17 ++- 11 files changed, 330 insertions(+), 44 deletions(-) diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index b18a0cda67..5a48799007 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -429,8 +429,48 @@ fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing if !constructing { return Err(interp.type_error("ArrayBuffer must be called with new")); } + array_buffer_with_target(interp, args, None) +} + +fn array_buffer_with_target(interp: &mut Interp, args: &[Value], new_target: Option) -> JsResult { let len = to_index(interp, &arg(args, 0), "the length")?; - new_buffer(interp, len, 0).map(Value::Object) + let fallback = interp.intrinsics.es2015.array_buffer_proto; + let proto = match new_target { + Some(nt) => interp.prototype_from(nt, fallback)?, + None => fallback, + }; + interp.rooted(&[Value::Object(proto)], |i| { + let buffer = new_buffer(i, len, 0)?; + i.object_mut(buffer)?.proto = Some(proto); + Ok(Value::Object(buffer)) + }) +} + +pub(crate) fn defers_prototype(interp: &Interp, intrinsic: Option, args: &[Value]) -> bool { + let i = &interp.intrinsics.es2015; + intrinsic.is_some_and(|p| { + p == i.array_buffer_proto || p == i.data_view_proto || (i.typed_protos.contains(&p) && !matches!(arg(args, 0), Value::Object(_))) + }) +} + +pub(crate) fn construct_with_target(interp: &mut Interp, intrinsic: Option, args: &[Value], new_target: ObjId) -> JsResult { + let i = &interp.intrinsics.es2015; + if intrinsic == Some(i.array_buffer_proto) { + return array_buffer_with_target(interp, args, Some(new_target)); + } + if intrinsic == Some(i.data_view_proto) { + return data_view_with_target(interp, args, Some(new_target)); + } + let elem = Elem::ALL.into_iter().find(|e| intrinsic == Some(typed_proto(interp, *e))); + let Some(elem) = elem else { return Err(Abrupt::Internal("not a binary constructor".into())) }; + let len = to_index(interp, &arg(args, 0), "the length")?; + let fallback = typed_proto(interp, elem); + let proto = interp.prototype_from(new_target, fallback)?; + interp.rooted(&[Value::Object(proto)], |i| { + let view = new_typed(i, elem, len)?; + i.object_mut(view)?.proto = Some(proto); + Ok(Value::Object(view)) + }) } /// `ArrayBuffer.isView` (section 24.1.3.1). @@ -516,6 +556,10 @@ fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: b if !constructing { return Err(interp.type_error("DataView must be called with new")); } + data_view_with_target(interp, args, None) +} + +fn data_view_with_target(interp: &mut Interp, args: &[Value], new_target: Option) -> JsResult { let buffer = match arg(args, 0).as_object() { Some(o) if bytes(interp, o).is_some() => o, _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), @@ -532,8 +576,12 @@ fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: b if offset.saturating_add(view_len) > len { return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); } - interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; - let proto = interp.intrinsics.es2015.data_view_proto; + let fallback = interp.intrinsics.es2015.data_view_proto; + let proto = match new_target { + Some(nt) => interp.prototype_from(nt, fallback)?, + None => fallback, + }; + interp.rooted(&[Value::Object(buffer), Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) } diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index f0b5daf9e3..8e4d027574 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -415,6 +415,7 @@ enum Item { struct Writing { obj: ObjId, keys: Vec, + _held_keys: Option, array: bool, next: usize, count: usize, @@ -630,6 +631,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J } // A proxy whose target is an array is written as one (ECMA-262 2020 section 24.5.2.1). let array = interp.is_array(&Value::Object(o))?; + let mut held_keys = None; let keys = if array { let len = length_of(interp, o)?; // Every element is written as at least `null` and a comma, so a length that cannot fit @@ -647,8 +649,10 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J } else if let Some(list) = &settings.properties { list.clone() } else { + let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + held_keys = Some(held); let mut keys = Vec::new(); - for k in interp.own_keys(o)? { + for k in names { if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) { keys.push(k); } @@ -659,7 +663,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J let stepback = w.indent.len(); w.indent.extend_from_slice(&settings.gap); w.out.push_str(interp, if array { "[" } else { "{" })?; - w.stack.push(Writing { obj: o, keys, array, next: 0, count: 0, stepback }); + w.stack.push(Writing { obj: o, keys, _held_keys: held_keys, array, next: 0, count: 0, stepback }); Ok(()) } diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index a598dd5f6a..599519c0e0 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -135,7 +135,7 @@ fn descriptor_object(interp: &mut Interp, prop: &Prop) -> JsResult { } /// An array of the names, kept reachable while it is filled. -pub(crate) fn names_array(interp: &mut Interp, names: Vec) -> JsResult { +pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator) -> JsResult { let a = new_array(interp, 0)?; interp.rooted(&[Value::Object(a)], |interp| { for (i, k) in names.into_iter().enumerate() { @@ -148,10 +148,11 @@ pub(crate) fn names_array(interp: &mut Interp, names: Vec) -> JsResult JsResult> { - let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { + let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let mut keys: Vec = names.into_iter().map(PropKey::Str).collect(); keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); - Ok(keys) + Ok((keys, held)) } /// `Object.getPrototypeOf` (section 15.2.3.2). @@ -224,7 +225,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - let keys = own_prop_keys(interp, p)?; + let (keys, _held) = own_prop_keys(interp, p)?; // A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted // until they are defined on `o`. for k in &keys { @@ -263,7 +264,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let what = if freeze { "frozen" } else { "sealed" }; return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); } - let keys = own_prop_keys(interp, o)?; + let (keys, _held) = own_prop_keys(interp, o)?; check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; @@ -311,7 +312,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { if interp.is_extensible(o)? { return Ok(Value::Bool(false)); } - let keys = own_prop_keys(interp, o)?; + let (keys, _held) = own_prop_keys(interp, o)?; check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; @@ -357,13 +358,14 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { + let crate::interp::HeldKeys { keys, held } = interp.own_keys(o)?; let mut names = Vec::new(); - for k in interp.own_keys(o)? { + for k in keys { interp.use_fuel()?; if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) { names.push(k); } } - names_array(interp, names) + names_array(interp, crate::interp::HeldKeys { keys: names, held }) }) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index ad1bdbabc7..3f649a3673 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -190,7 +190,7 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// `Reflect.has(target, propertyKey)` (section 26.1.8). fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "has")?; - interp.with_key(&arg(args, 1), |interp, k| interp.has_property(o, &k)).map(Value::Bool) + interp.with_key(&arg(args, 1), |interp, k| interp.has_property_indexed(o, &k)).map(Value::Bool) } /// `Reflect.isExtensible(target)` (section 26.1.9). diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 8e9b9a1f53..c691db98bd 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -176,7 +176,7 @@ impl Interp { } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). - fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { + pub(crate) fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? { Value::Object(p) => Ok(p), _ => Ok(fallback), @@ -317,11 +317,15 @@ impl Interp { let fallback = self.intrinsics.object_proto; let proto = self.prototype_from(nt, fallback)?; Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))) + } else if subclass && crate::builtins::binary::defers_prototype(self, intrinsic, &args) { + let held = self.held_bytes; + let r = crate::builtins::binary::construct_with_target(self, intrinsic, &args, nt); + self.held_bytes = held; + r? } else { // `Number`, `String`, `Date` and `Function` convert their arguments before // `prototype` is read (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so - // a conversion that throws reads nothing from `new.target`; the others read it - // first. + // a conversion that throws reads nothing from `new.target`. let converts_first = { let i = &self.intrinsics; intrinsic.is_some_and(|p| [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p)) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index deb59fe3bd..24daab16cc 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -483,6 +483,47 @@ impl Drop for HeldBytes { } } +pub(crate) struct HeldKeys { + pub(crate) keys: Vec, + pub(crate) held: HeldBytes, +} + +impl std::ops::Deref for HeldKeys { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.keys + } +} + +impl std::ops::DerefMut for HeldKeys { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.keys + } +} + +pub(crate) struct HeldKeyIter { + keys: std::vec::IntoIter, + _held: HeldBytes, +} + +impl Iterator for HeldKeyIter { + type Item = Key; + + fn next(&mut self) -> Option { + self.keys.next() + } +} + +impl IntoIterator for HeldKeys { + type Item = Key; + type IntoIter = HeldKeyIter; + + fn into_iter(self) -> Self::IntoIter { + HeldKeyIter { keys: self.keys.into_iter(), _held: self.held } + } +} + /// The least heap size a collection waits for. const MIN_GC_BYTES: usize = 1 << 20; @@ -2248,7 +2289,7 @@ impl Interp { /// `length` first, then the rest in the order they were added, which is the order `for-in` /// visits them, then an array's `length`. Each name takes a unit of fuel, and the heap for the /// list is checked first. A proxy's names come from its `ownKeys` trap. - pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { + pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { return self.proxy_own_keys(id); } @@ -2262,7 +2303,8 @@ impl Interp { let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); - self.reserve_heap(index_keys_bytes(string_len).saturating_add(count.saturating_mul(KEY_ENTRY_BYTES)))?; + let mut held = HeldBytes::new(self); + held.add(self, index_keys_bytes(string_len).saturating_add(count.saturating_mul(KEY_ENTRY_BYTES)))?; let mut out = Vec::with_capacity(count); for i in 0..string_len { self.use_fuel()?; @@ -2278,10 +2320,10 @@ impl Interp { if is_array { out.push(key("length")); } - Ok(out) + Ok(HeldKeys { keys: out, held }) } - pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult> { + 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 { .. }) { @@ -3213,8 +3255,6 @@ impl Interp { while let Some(o) = cur { if self.is_proxy(o) { let keys = self.own_keys(o)?; - let mut listed = HeldBytes::new(self); - listed.add(self, keys.iter().fold(0usize, |bytes, k| bytes.saturating_add(string_bytes(k.len()) + KEY_ENTRY_BYTES)))?; for k in keys { self.use_fuel()?; if seen.contains(&k) { diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 354aa391e5..bbde3c6933 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, ProxyCall, SetLookup, merge_desc, same_value}; +use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, 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. @@ -112,7 +112,11 @@ impl Interp { /// Calls the trap with the handler as `this`, keeping its result rooted. fn call_trap(&mut self, trap: &Value, handler: ObjId, args: &[Value]) -> JsResult { - let v = self.call(trap, &Value::Object(handler), args)?; + let mark = self.temp_roots.len(); + self.temp_roots.extend(args.iter().cloned()); + let result = self.call(trap, &Value::Object(handler), args); + self.temp_roots.truncate(mark); + let v = result?; self.temp_roots.push(v.clone()); Ok(v) } @@ -296,7 +300,7 @@ impl Interp { if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() { return Ok(false); } - let target_prop = i.get_own_property(target, k)?; + let target_prop = i.own_property(target, k)?; let extensible = i.is_extensible(target)?; let setting_config_false = desc.configurable == Some(false); let Some(current) = target_prop else { @@ -328,10 +332,10 @@ impl Interp { /// [[HasProperty]] of a proxy (section 9.5.7). pub(crate) fn proxy_has(&mut self, p: ObjId, k: &Key) -> JsResult { self.proxy_op(p, "test a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property(target, k) }; + let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property_indexed(target, k) }; let name = i.key_value(k)?; let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy(); - if !found && let Some(current) = i.get_own_property(target, k)? { + if !found && let Some(current) = i.own_property(target, k)? { if !current.configurable() { return Err(i.invariant("has", "hid a non-configurable property of its target")); } @@ -349,7 +353,7 @@ impl Interp { let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) }; let name = i.key_value(k)?; let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; - match i.get_own_property(target, k)? { + match i.own_property(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) } @@ -369,7 +373,7 @@ impl Interp { if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() { return Ok(false); } - match i.get_own_property(target, k)? { + match i.own_property(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(v, &value) => { Err(i.invariant("set", "set a value other than its target's non-configurable, read-only property")) } @@ -389,7 +393,7 @@ impl Interp { if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() { return Ok(false); } - let Some(current) = i.get_own_property(target, k)? else { return Ok(true) }; + let Some(current) = i.own_property(target, k)? else { return Ok(true) }; if !current.configurable() { return Err(i.invariant("deleteProperty", "deleted a non-configurable property of its target")); } @@ -403,15 +407,15 @@ impl Interp { /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable /// name of the target, and of a non-extensible target exactly its names. Each name takes a - /// 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> { + /// unit of fuel and counts against the heap limit until the caller drops the list. + 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.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)?; i.check_own_keys(target, &keys)?; - Ok(keys) + Ok(HeldKeys { keys, held }) }) } @@ -449,12 +453,12 @@ impl Interp { let target_keys = self.own_keys(target)?; let mut fixed = Vec::new(); let mut configurable = Vec::new(); - for k in target_keys { + for k in target_keys.iter() { self.use_fuel()?; - if self.get_own_property(target, &k)?.is_some_and(|p| !p.configurable()) { - fixed.push(k); + if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k.clone()); } else { - configurable.push(k); + configurable.push(k.clone()); } } if extensible && fixed.is_empty() { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index eac8c9c645..dac40b6c6b 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -975,3 +975,172 @@ fn typed_array_prototypes_ignore_invalid_numeric_indices_during_assignment() { Reflect.set(o, 'label', 8) && o.label === 8", ); } + +#[test] +fn proxy_key_lists_stay_charged_during_nested_descriptor_callbacks() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, Prop, key}; + use crate::value::Value; + + fn live_bytes(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + interp.collect_garbage(); + Ok(Value::Number(f64::from(u32::try_from(interp.heap.bytes).unwrap()))) + } + + for operation in ["Object.keys(p)", "JSON.stringify(p)"] { + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "liveBytes", live_bytes, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("liveBytes"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var name = 'x'; while (name.length < 65536) name += name; + var names = [name], depth = 0, retained = 0; + var inner = new Proxy({{}}, {{ + ownKeys: function () {{ return names; }}, + getOwnPropertyDescriptor: function () {{ + depth++; + if (depth < 3) {{ {operation}; }} else {{ retained = liveBytes(); }} + depth--; + return {{ configurable: true, enumerable: false }}; + }} + }}); + var p = new Proxy(inner, {{}}), baseline = liveBytes(); + {operation}; + retained - baseline > 5 * name.length * 2" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)), "{operation}"); + } +} + +#[test] +fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var calls = 0; + var p = new Proxy({{}}, {{ + ownKeys: function () {{ calls++; return {{ length: 10001 }}; }}, + getOwnPropertyDescriptor: function () {{ calls++; throw 1; }} + }}); + var getter = Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get; + type_error(function () {{ p.reflect; }}) && type_error(function () {{ getter.call(p); }}) && 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| { + assert_eq!(args.get(2), Some(&Data::Bool(true))); + Ok(match args.get(1) { + Some(Data::Number(n)) if *n == 0.0 => Data::Bool(true), + Some(Data::String(s)) if s == "named" => Data::Bool(true), + _ => Data::Undefined, + }) + }); + let class = crate::HostClass { name: "Indexed".into(), parent: None, members: vec![], info: vec![], index: Some(index), construct: None }; + let mut realm = es(); + realm.define_host_classes(vec![class], vec![("indexed".into(), crate::host_ref("Indexed", &[1.0]))]).unwrap(); + assert_eq!( + realm.run( + "var p = new Proxy(new Proxy(indexed, {}), {}); + var ok = [indexed, p].every(function (t) { + return 0 in t && 'named' in t && !(1 in t) && !('missing' in t) && + Reflect.has(t, 0) && Reflect.has(t, 'named') && !Reflect.has(t, 1) && !Reflect.has(t, 'missing'); + }); + var calls = 0; + var trapped = new Proxy(indexed, { has: function () { calls++; return false; } }); + ok && !Reflect.has(trapped, 0) && calls === 1", + ), + Ok(JsValue::Bool(true)) + ); +} + +#[test] +fn binary_constructors_validate_arguments_before_reading_new_target_prototype() { + truth( + "var reads = 0, proto = {}; + var nt = new Proxy(function () {}, { get: function () { reads++; return proto; } }); + var constructors = [ArrayBuffer, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, + Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + var ok = constructors.every(function (C) { + try { Reflect.construct(C, [-1], nt); } catch (e) { return e instanceof RangeError && reads === 0; } + 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; } + return false; + }); + var a = Reflect.construct(ArrayBuffer, [2], nt), u = Reflect.construct(Uint8Array, ['2'], nt); + var d = Reflect.construct(DataView, [buffer, 1, 2], nt); + ok && reads === 3 && Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(u) === proto && + Object.getPrototypeOf(d) === proto && Uint8Array.prototype.join.call(u) === '0,0'", + ); + truth( + "var log = [], proto = {}; + var nt = new Proxy(function () {}, { get: function () { log.push('prototype'); return proto; } }); + var length = { valueOf: function () { log.push('length'); return 2; } }; + var offset = { valueOf: function () { log.push('offset'); return 1; } }; + Reflect.construct(ArrayBuffer, [length], nt); + Reflect.construct(DataView, [new ArrayBuffer(4), offset, length], nt); + log.join() === 'length,prototype,offset,length,prototype'", + ); +} + +#[test] +fn proxy_invariants_preserve_namespace_initialization_errors() { + let mut realm = es(); + assert!(realm.run("var out = [];").is_ok()); + let mut load = |_: &str, specifier: &str| -> Result { + let (key, source) = if specifier == "main" { + ("main.mjs", None) + } else { + ( + "cycle.mjs", + Some( + "import * as ns from 'main'; + var p = new Proxy(ns, { + get: function () { return 9; }, set: function () { return true; }, + has: function () { return false; }, deleteProperty: function () { return true; }, + defineProperty: function () { return true; }, ownKeys: function () { return ['x']; } + }); + [function () { p.x; }, function () { p.x = 9; }, function () { 'x' in p; }, + function () { delete p.x; }, function () { Reflect.defineProperty(p, 'x', { value: 9 }); }, + function () { Reflect.ownKeys(p); }].forEach(function (f) { + try { f(); out.push(false); } catch (e) { out.push(e instanceof ReferenceError); } + });" + .into(), + ), + ) + }; + Ok(crate::LoadedModule { key: key.into(), source }) + }; + assert_eq!( + realm.run_module("main.mjs", "import './cycle.mjs'; export let x = 1;", crate::ModuleLimits::default(), &mut load), + Ok(JsValue::Undefined) + ); + assert_eq!(realm.run("out.join()"), Ok(JsValue::String("true,true,true,true,true,true".into()))); +} + +#[test] +fn revoked_proxies_reject_symbol_operations_on_their_own_properties() { + truth( + "var s = Symbol('saved'), missing = Symbol('missing'), pair = Proxy.revocable({}, {}), p = pair.proxy; + p[s] = 7; + var child = Object.create(p); + var ok = p[s] === 7 && s in p && Object.getOwnPropertyDescriptor(p, s).value === 7; + pair.revoke(); + ok && [function () { p[s]; }, function () { p[missing]; }, function () { child[s]; }, + function () { s in p; }, function () { p[s] = 8; }, function () { p[missing] = 8; }, + function () { delete p[s]; }, function () { delete p[missing]; }, + function () { Object.getOwnPropertyDescriptor(p, s); }, + function () { Object.defineProperty(p, s, { value: 8 }); }, + function () { Object.defineProperty(p, missing, { value: 8 }); }, + function () { Object.getOwnPropertySymbols(p); }].every(type_error)", + ); +} diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 79cac25cc0..62c63c6bb0 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -100,6 +100,9 @@ fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult (interp.symbols.objects.map_or(interp.intrinsics.object_proto, |o| o.symbol_proto), Some("Symbol")), Value::Object(o) => (*o, None), }; + if interp.is_proxy(id) { + return Err(interp.type_error("reflect does not support proxy objects")); + } let (name, properties, methods) = match interp.host_class_members(id)? { Some((name, members)) if primitive.is_none() => { let (properties, methods) = host_infos(interp, &members)?; diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index bbac60d461..e90652ec00 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -315,7 +315,8 @@ impl Interp { self.reject(true, &name, why) } - pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { + self.symbol_lookup_target(id)?; Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } @@ -364,6 +365,7 @@ impl Interp { /// Adds or replaces an own property directly, keeping the heap estimate. pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { + self.symbol_lookup_target(id)?; let o = self.object_mut(id)?; if o.syms.get_or_insert_with(Box::default).insert(k, prop) { self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); @@ -488,6 +490,7 @@ impl Interp { /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and /// the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { + self.symbol_lookup_target(id)?; let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index bb5f85d641..1aba1d1294 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2853,14 +2853,22 @@ counts against the call depth. A generator function called in an engine that `#t throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has 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 property names. 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 and the names retained during a `for-in` prototype walk count against the heap limit, and -a trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A +and 26.2), with string property names. 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, +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 `.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. `Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set` and typed arrays and uses its `prototype` for the new object. +`ArrayBuffer` and typed arrays constructed from primitive lengths convert the length before reading +`newTarget.prototype`. `DataView` validates its buffer, byte offset and byte length before reading that prototype. +A failure during conversion or validation throws before the prototype getter runs. `Reflect.has` and an empty-handler proxy's +membership checks use host collection indexers, including numeric indices and named items. +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 +and symbol enumeration on a revoked proxy also throw `TypeError`. `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 @@ -2872,7 +2880,8 @@ without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Ob 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` -and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. +and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant +checks that read a target descriptor also throw `ReferenceError` for an uninitialized namespace export. The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; both properties are nonwritable, nonenumerable and configurable. A `.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there