mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
JavaScript: JSON reads proxy array lengths with ToLength and skips host indexers through transparent proxies, and proxies construct bound built-ins
This commit is contained in:
1 parent
0248f7eb74
commit
94cbceb676
6 files changed
+155
-15
No files matched your search
@@ -483,12 +483,16 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult<Se
|
||||
|
||||
/// The property names a replacer array lists, without repeats (section 15.12.3, step 4.b).
|
||||
fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<Vec<Key>> {
|
||||
let len = length_of(interp, r)?;
|
||||
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 list: Vec<Key> = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
let v = interp.get_from(r, &key_of(f64::from(i)), &Value::Object(r))?;
|
||||
let v = interp.get_from(r, &key_of(i as f64), &Value::Object(r))?;
|
||||
let item = match &v {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Number(_) => Some(interp.primitive_to_str(&v)),
|
||||
@@ -633,17 +637,20 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J
|
||||
let array = interp.is_array(&Value::Object(o))?;
|
||||
let mut held_keys = None;
|
||||
let keys = if array {
|
||||
let len = length_of(interp, o)?;
|
||||
let len = super::collections::length_of(interp, o)?;
|
||||
// Every element is written as at least `null` and a comma, so a length that cannot fit
|
||||
// is refused before anything is listed.
|
||||
if u64::from(len).saturating_mul(5) > (interp.limits.heap_bytes / 4) as u64 {
|
||||
if len.saturating_mul(5) > (interp.limits.heap_bytes / 4) as u64 {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Heap));
|
||||
}
|
||||
if len > interp.fuel {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel));
|
||||
}
|
||||
interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?;
|
||||
let mut keys = Vec::with_capacity(len as usize);
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
keys.push(key_of(f64::from(i)));
|
||||
keys.push(key_of(i as f64));
|
||||
}
|
||||
keys
|
||||
} else if let Some(list) = &settings.properties {
|
||||
|
||||
@@ -237,6 +237,7 @@ impl Interp {
|
||||
/// boundary when `boundary` is set. A proxy runs its `construct` trap, or without one
|
||||
/// constructs its target with the same `new.target` (section 9.5.13).
|
||||
fn construct_at(&mut self, start: usize, f: Value, mut args: Vec<Value>, new_target: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let forwarding = new_target.is_none() || new_target == f.as_object();
|
||||
let mut f = f;
|
||||
let mut new_target = new_target;
|
||||
// A bound function constructs its target with its arguments first, and a `new.target`
|
||||
@@ -261,7 +262,7 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) else {
|
||||
break self.construct_function(start, f, args, new_target, boundary);
|
||||
break self.construct_function(start, f, args, new_target, boundary, forwarding);
|
||||
};
|
||||
if let Err(e) = self.use_fuel() {
|
||||
break Err(e);
|
||||
@@ -283,7 +284,15 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The steps of [`Interp::construct_at`] for `f` once it is neither a proxy nor bound.
|
||||
fn construct_function(&mut self, start: usize, f: Value, args: Vec<Value>, new_target: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
fn construct_function(
|
||||
&mut self,
|
||||
start: usize,
|
||||
f: Value,
|
||||
args: Vec<Value>,
|
||||
new_target: Option<ObjId>,
|
||||
boundary: bool,
|
||||
forwarding: bool,
|
||||
) -> JsResult<()> {
|
||||
let Some(callee) = f.as_object() else { return Err(self.type_error("the value is not a constructor")) };
|
||||
let nt = new_target.unwrap_or(callee);
|
||||
match self.func_of(&f) {
|
||||
@@ -304,7 +313,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 && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? {
|
||||
if !boundary && subclass && !forwarding && 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"))? {
|
||||
@@ -372,7 +381,7 @@ impl Interp {
|
||||
// object it gives inherits from the class's prototype. The class's other functions are
|
||||
// not constructors. A constructor called with `new` cannot wait for its result.
|
||||
Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if self.is_host_constructor(callee) => {
|
||||
if nt != callee && self.unwrapped_proxy_target(nt)? != callee {
|
||||
if nt != callee && !forwarding && self.unwrapped_proxy_target(nt)? != callee {
|
||||
return Err(self.type_error("this built-in cannot be subclassed"));
|
||||
}
|
||||
let was = std::mem::replace(&mut self.constructing, true);
|
||||
|
||||
@@ -2017,7 +2017,7 @@ impl Interp {
|
||||
Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Lookup::Found(Prop::Data { value, .. }) => Ok(value),
|
||||
Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, k, receiver),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, k, receiver, true),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2033,7 +2033,7 @@ impl Interp {
|
||||
Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Lookup::Found(Prop::Data { value, .. }) => Ok(value),
|
||||
Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, k, receiver),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, k, receiver, false),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -348,9 +348,11 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// [[Get]] of a proxy (section 9.5.8).
|
||||
pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value) -> JsResult<Value> {
|
||||
pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value, indexed: bool) -> JsResult<Value> {
|
||||
self.proxy_op(p, "read a property of", &[receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) };
|
||||
let Some(trap) = i.proxy_trap(handler, "get")? else {
|
||||
return if indexed { i.get_from(target, k, receiver) } else { i.get_property_only(target, k, receiver) };
|
||||
};
|
||||
let name = i.key_value(k)?;
|
||||
let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?;
|
||||
match i.own_property(target, k)? {
|
||||
|
||||
@@ -1328,3 +1328,120 @@ fn revoked_proxies_reject_symbol_operations_on_their_own_properties() {
|
||||
function () { Object.getOwnPropertySymbols(p); }].every(type_error)",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_proxy_array_lengths_use_to_length() {
|
||||
truth(
|
||||
"var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0;
|
||||
var empty = lengths.every(function (length) {
|
||||
var p = new Proxy([7], { get: function (t, k) {
|
||||
if (k === 'length') return length;
|
||||
if (k === '0') reads++;
|
||||
return t[k];
|
||||
} });
|
||||
return JSON.stringify(new Proxy(p, {})) === '[]';
|
||||
});
|
||||
var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } });
|
||||
empty && reads === 0 && JSON.stringify(p) === '[7]'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_proxy_replacer_lengths_use_to_length() {
|
||||
truth(
|
||||
"var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0;
|
||||
var empty = lengths.every(function (length) {
|
||||
var p = new Proxy(['a'], { get: function (t, k) {
|
||||
if (k === 'length') return length;
|
||||
if (k === '0') reads++;
|
||||
return t[k];
|
||||
} });
|
||||
return JSON.stringify({ a: 7 }, new Proxy(p, {})) === '{}';
|
||||
});
|
||||
var p = new Proxy(['a', 'b'], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } });
|
||||
empty && reads === 0 && JSON.stringify({ a: 7, b: 8 }, p) === '{\"a\":7}'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_proxy_lengths_check_limits_before_reading_elements() {
|
||||
for length in ["4294967296", "Infinity"] {
|
||||
let setup = format!(
|
||||
"var p = new Proxy([], {{ get: function (t, k) {{
|
||||
if (k === 'length') return {length};
|
||||
if (k === 'toJSON') return undefined;
|
||||
throw new Error('element read');
|
||||
}} }});"
|
||||
);
|
||||
assert_eq!(limit(&format!("{setup} JSON.stringify(p)"), Limits::default()), LimitKind::Heap);
|
||||
assert_eq!(limit(&format!("{setup} JSON.stringify({{}}, p)"), Limits::default()), LimitKind::Fuel);
|
||||
}
|
||||
let limits = Limits { fuel: 200_000, ..Limits::default() };
|
||||
assert_eq!(
|
||||
limit(
|
||||
"var p = new Proxy([], { get: function (t, k) {
|
||||
if (k === 'length') return 300000;
|
||||
if (k === 'toJSON') return undefined;
|
||||
throw new Error('element read');
|
||||
} }); JSON.stringify(p)",
|
||||
limits,
|
||||
),
|
||||
LimitKind::Fuel
|
||||
);
|
||||
let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() };
|
||||
assert_eq!(
|
||||
limit(
|
||||
"var p = new Proxy([], { get: function (t, k) {
|
||||
if (k === 'length') return 1000000;
|
||||
throw new Error('element read');
|
||||
} }); JSON.stringify({}, p)",
|
||||
limits,
|
||||
),
|
||||
LimitKind::Heap
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() {
|
||||
truth(
|
||||
"var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {});
|
||||
var a = new P(), b = new Q(), c = Reflect.construct(Q, []);
|
||||
var R = new Proxy(Q.bind(null), {}), d = new R();
|
||||
var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U();
|
||||
Object.defineProperty(B, 'prototype', { value: Map.prototype });
|
||||
a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 &&
|
||||
Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 &&
|
||||
type_error(function () { class Child extends P {} new Child(); })",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() {
|
||||
let calls = Rc::new(RefCell::new(0));
|
||||
let count = calls.clone();
|
||||
let index: HostFunction = Rc::new(move |_| {
|
||||
*count.borrow_mut() += 1;
|
||||
Err(crate::HostError::Error("unknown item".into()))
|
||||
});
|
||||
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 plain = JSON.stringify(indexed);
|
||||
var ok = JSON.stringify(p) === plain;
|
||||
var receiver, reads = 0;
|
||||
var trapped = new Proxy(indexed, { get: function (t, k, r) {
|
||||
if (k === 'toJSON') { reads++; receiver = r; return function () { return this === outer ? 7 : 0; }; }
|
||||
return Reflect.get(t, k, r);
|
||||
} });
|
||||
var outer = new Proxy(trapped, {});
|
||||
ok && JSON.stringify(outer) === '7' && reads === 1 && receiver === outer",
|
||||
),
|
||||
Ok(JsValue::Bool(true))
|
||||
);
|
||||
assert_eq!(*calls.borrow(), 0);
|
||||
assert_eq!(realm.run("var caught = false; try { p.missing; } catch (e) { caught = true; } caught"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(*calls.borrow(), 1);
|
||||
}
|
||||
+7
-2
@@ -2861,8 +2861,9 @@ proxy in a command's params throws a `TypeError` without running its traps. An e
|
||||
`Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs.
|
||||
Existing globals with either name are preserved. If a missing global cannot be added because the global object
|
||||
is nonextensible, sealed or frozen, the run fails with an installation error before the script executes.
|
||||
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
|
||||
An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)`
|
||||
and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object.
|
||||
`Reflect.construct` also accepts a distinct constructor
|
||||
as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object.
|
||||
`Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's
|
||||
`set` or `add` method. A missing or noncallable adder throws `TypeError` before the iterable is read;
|
||||
@@ -2877,6 +2878,10 @@ rejects a missing or noncallable executor with `TypeError` before reading `newTa
|
||||
For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call.
|
||||
`Reflect.has` and an empty-handler proxy's
|
||||
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. Its `toJSON` lookup skips host collection indexers through empty-handler proxies
|
||||
and calls an explicit `get` trap when present.
|
||||
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`.
|
||||
|
||||
Reference in new issue
Block a user