JavaScript: spread and default parameters stay within the heap limit

- Spreading an array checks the room in the result as each element is
  read, so a getter that shrinks an array of length 4294967295 gives the
  elements it reads. An array no getter reads, and any other object, is
  still checked against its length when spread begins.
- Spread counts each element's index name, and each character of a
  string, against the heap as it reads them.
- A function with default or rest parameters checks the heap again before
  its body's environment and declarations are made, since the parameters'
  values may have used the room the call reserved.
- Without the ES2015 option, a function that eval code declares on the
  global object closes over the global scope, so it sees the scripts'
  `let` and `const` names, as functions of global code do.
- With the ES2015 option, a global `var` whose name the global object
  only inherits gets its own property.
- The test262 ES2015 subset runs a test whose source does not tokenize,
  so the error counts as a failure instead of a skip.
This commit is contained in:
dotCooCoo
2026-11-22 11:00:34 -08:00
parent 15fefc9930
commit 6b8c10999d
3 changed files with 182 additions and 20 deletions
+101
View File
@@ -183,6 +183,32 @@ fn functions_from_earlier_runs_see_later_global_lexical_bindings() {
assert_eq!(realm.run("function later() { return x; } later() + read()"), Ok(JsValue::Number(14.0)));
}
#[test]
fn a_function_eval_declares_on_the_global_object_sees_global_lexical_bindings() {
// Without the option, eval code's functions close over its variable environment; on the
// global object that is the global scope, which holds the scripts' `let` and `const` names.
let mut realm = es();
assert_eq!(realm.run("let x = 7; 0"), Ok(JsValue::Number(0.0)));
realm.set_es2015(false);
assert_eq!(realm.run("with ({}) { eval('function read() { return x; }'); } read()"), Ok(JsValue::Number(7.0)));
assert_eq!(realm.run("function g() { eval('function inner() { return x; }'); return inner(); } g()"), Ok(JsValue::Number(7.0)));
}
#[test]
fn a_global_var_makes_its_own_property_over_an_inherited_one() {
// ECMA-262 2015 section 8.1.1.4.17 reads the global object's own property, so `var` makes a
// new one even when the global object inherits the name.
let mut realm = es();
assert_eq!(realm.run("Object.prototype.inherited = 1; Object.prototype.viaEval = 2; 0"), Ok(JsValue::Number(0.0)));
let own = "var inherited; (0, eval)('var viaEval'); this.hasOwnProperty('inherited') && inherited === undefined \
&& this.hasOwnProperty('viaEval') && viaEval === undefined";
assert_eq!(realm.run(own), Ok(JsValue::Bool(true)));
// Without the option, the inherited property counts as declared (ECMA-262 5.1 section 10.5).
let mut realm = Realm::new();
assert_eq!(realm.run("Object.prototype.inherited = 1; 0"), Ok(JsValue::Number(0.0)));
assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true)));
}
#[test]
fn a_global_function_that_cannot_be_declared_declares_nothing() {
let mut realm = es();
@@ -474,6 +500,52 @@ fn spread_reads_an_array_s_length_again_before_each_element() {
truth("var o = { length: 2, get 0() { o.length = 1; return 'v'; }, 1: 'w' }; [...o].join() === 'v,w'");
}
#[test]
fn an_array_s_spread_is_checked_against_the_elements_it_reads() {
// The array starts at the longest length, and its first element's getter shrinks it, so
// only one element is read and the result fits.
let shrink = "var a = []; a.length = 4294967295; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 7; } }); \
var b = [...a]; b.length === 1 && b[0] === 7";
truth(shrink);
let then_more = "var a = []; a.length = 4294967295; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 7; } }); \
var b = [...a, ...[1, 2]]; b.join() === '7,1,2'";
truth(then_more);
// An array no getter reads is checked when spread begins, without reading its elements.
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let long = realm.run("var a = []; a.length = 4294967295; [...a]");
assert!(is_thrown(&long, "RangeError"), "{long:?}");
// An object that is not an array is still checked against the length it has when spread
// begins.
throws("[0, ...{ length: 4294967295 }];", "RangeError");
}
#[test]
fn spread_counts_each_index_name_against_the_heap() {
// The elements' properties, with their index names and a string's characters, fit in the
// heap or the run ends with the heap limit, at every limit in the range.
for spread in ["[...a]", "[...s]"] {
let setup = "var a = Array(4000); var s = new Array(4001).join('x'); 0";
let mut measure = Realm::with_options(es_options(), Limits::default());
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
measure.interp().collect_garbage();
let base = measure.interp().heap.bytes;
for extra in (0..640usize).map(|k| k * 1024) {
let heap_bytes = base + extra;
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
if realm.run(setup).is_err() {
continue;
}
match realm.run(&format!("var b = {spread}; b.length")) {
Ok(v) => assert_eq!(v, JsValue::Number(4000.0), "{spread} at {heap_bytes}"),
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread} at {heap_bytes}: {e:?}"),
}
// A collection counts what is live, without the bytes the spread held while it ran.
realm.interp().collect_garbage();
assert!(realm.interp().heap.bytes <= heap_bytes, "{spread}: {} > {heap_bytes}", realm.interp().heap.bytes);
}
}
}
#[test]
fn spreading_other_values_is_a_type_error() {
throws("[...1];", "TypeError");
@@ -530,6 +602,35 @@ fn a_rest_parameter_checks_the_heap_before_its_array_is_made() {
assert!(realm.interp().heap.bytes <= heap_bytes, "{} > {heap_bytes}", realm.interp().heap.bytes);
}
#[test]
fn a_body_after_default_parameters_checks_the_heap_before_its_scope_is_made() {
// The default value fills the heap a little more each run, so at some count the room left
// after it is smaller than the body's long variable names need. The call then ends with the
// heap limit before the heap estimate passes it.
let vars = (0..200).map(|i| format!("v{i:0>60}")).collect::<Vec<_>>().join(", ");
let setup = format!(
"var keep = []; function fill(k) {{ for (var i = 0; i < k; i++) keep.push(i); }} function f(a = fill(count)) {{ var {vars}; return 1; }} 0"
);
let mut measure = Realm::with_options(es_options(), Limits::default());
assert_eq!(measure.run(&setup), Ok(JsValue::Number(0.0)));
measure.interp().collect_garbage();
let heap_bytes = measure.interp().heap.bytes + (256 << 10);
let mut stopped = 0;
for count in (0..4000).step_by(20) {
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0)));
match realm.run(&format!("var count = {count}; f()")) {
Ok(v) => assert_eq!(v, JsValue::Number(1.0), "{count}"),
Err(e) => {
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{count}: {e:?}");
stopped += 1;
}
}
assert!(realm.interp().heap.bytes <= heap_bytes, "{count}: {} > {heap_bytes}", realm.interp().heap.bytes);
}
assert!(stopped > 0, "no count reached the heap limit");
}
#[test]
fn new_scopes_survive_collections_while_they_are_made() {
// Heaps just big enough make the collector run while function bodies and blocks set up their
+60 -17
View File
@@ -436,6 +436,14 @@ fn binding_bytes(len: usize) -> usize {
PROP_BYTES + string_bytes(len)
}
/// The estimated bytes of the element property that spread adds at index `start + i`, its index
/// name included.
fn element_bytes(start: u32, i: usize) -> usize {
let index = u64::from(start).saturating_add(i as u64);
let digits = index.checked_ilog10().map_or(1, |d| d as usize + 1);
binding_bytes(digits)
}
/// At least the bytes that a function object made from `code` adds to the heap: the function,
/// its prototype object, their properties and the environment holding a function expression's
/// own name.
@@ -2275,6 +2283,9 @@ impl Interp {
fn op_body_env(&mut self) -> JsResult<()> {
let frame = self.frame()?;
let (code, params) = (frame.code.clone(), frame.env);
// The parameters' values may have filled the room the call reserved, so the body's
// environment and declarations are checked against the heap again.
self.reserve_heap(declaration_bytes(&code).saturating_add(ENV_BYTES))?;
// Each new environment is in the frame, where the collector finds it, before the next
// allocation.
let var_env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(params) });
@@ -2323,8 +2334,8 @@ impl Interp {
/// index (holes read as `undefined`), with its length read again before each one as its
/// iterator reads it, a string's or a `String` object's characters by code point, and an
/// object with a `length` by index. Any other value is a `TypeError`. Each element takes a
/// unit of fuel, and a concatenated string's flattened copy is counted against the heap before
/// it is made.
/// unit of fuel and is counted against the heap as it is read, with its index name and a
/// string's character, and a concatenated string's flattened copy is counted before it is made.
fn op_array_spread(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") };
@@ -2336,6 +2347,12 @@ impl Interp {
},
_ => None,
};
let current = match &self.object(a)?.class {
Class::Array { length, .. } => *length,
_ => return internal("spread into something that is not an array"),
};
// The most elements the array has room for.
let room = u32::MAX.saturating_sub(current);
let items: Vec<Value> = match boxed.as_ref().unwrap_or(&v) {
Value::String(s) => {
let units = crate::string_builtins::flat_charged(self, s)?;
@@ -2344,9 +2361,9 @@ impl Interp {
let mut i = 0;
while let Some(&u) = units.get(i) {
self.use_fuel()?;
held.add(self, PROP_BYTES)?;
let pair = (0xD800..0xDC00).contains(&u) && units.get(i + 1).is_some_and(|n| (0xDC00..0xE000).contains(n));
let len = if pair { 2 } else { 1 };
held.add(self, element_bytes(current, out.len()).saturating_add(string_bytes(len)))?;
out.push(Value::String(Str::from_units(units.get(i..i + len).unwrap_or_default().to_vec())));
i += len;
}
@@ -2357,16 +2374,15 @@ impl Interp {
let len = self.get_from(o, &key("length"), &v)?;
// ToLength (ECMA-262 2015 section 7.1.15): a negative or NaN length reads nothing.
let n = crate::string_builtins::to_integer(self.to_number(&len)?).max(0.0);
let current = match &self.object(a)?.class {
Class::Array { length, .. } => *length,
_ => return internal("spread into something that is not an array"),
};
let Some(n) = u32::MAX.checked_sub(current).filter(|room| n < f64::from(*room)).map(|_| n as u32) else {
return Err(self.throw(ErrorType::Range, "array literal too long"));
};
// An array's iterator reads its length again before each element (ECMA-262 2015
// section 22.1.5.2.1), so a getter that shrinks or grows the array changes the count.
// section 22.1.5.2.1), so a getter that shrinks or grows the array changes the count,
// and the room is checked as each element is read. Any other object, and an array
// whose elements no getter reads, is checked against the length it has now.
let array = matches!(self.object(o)?.class, Class::Array { .. });
if n >= f64::from(room) && !(array && self.has_index_getter(o)?) {
return Err(self.throw(ErrorType::Range, "array literal too long"));
}
let n = n as u32;
// The elements read so far stay reachable while a getter runs.
// The list is counted against the heap limit as it grows.
let mark = self.temp_roots.len();
@@ -2381,8 +2397,11 @@ impl Interp {
if i >= end {
return Ok(());
}
if i.saturating_add(1) >= room {
return Err(self.throw(ErrorType::Range, "array literal too long"));
}
self.use_fuel()?;
held.add(self, PROP_BYTES)?;
held.add(self, element_bytes(current, i as usize))?;
let item = self.get_from(o, &index_key(i), &v)?;
self.temp_roots.push(item);
i += 1;
@@ -2412,6 +2431,21 @@ impl Interp {
self.pop().map(drop)
}
/// Whether reading the elements of `o` by index can run code: `o` or an object it inherits
/// from has an accessor property with an index name. Each object takes a unit of fuel.
fn has_index_getter(&mut self, o: ObjId) -> JsResult<bool> {
let mut cur = Some(o);
while let Some(id) = cur {
self.use_fuel()?;
let object = self.object(id)?;
if object.props.iter().any(|(k, p)| matches!(p, Prop::Accessor { .. }) && array_index(k).is_some()) {
return Ok(true);
}
cur = object.proto;
}
Ok(false)
}
/// Takes the array of a call's or `new`'s arguments off the stack and pushes its elements.
fn unpack_args(&mut self) -> JsResult<u32> {
let Value::Object(a) = self.peek(0)? else { return internal("arguments are not an array") };
@@ -3310,11 +3344,17 @@ impl Interp {
None => env,
};
// Functions close over the code's own environment with ES2015's scoping, and over its
// variable environment otherwise (ECMA-262 5.1 section 13). Global code's functions close
// over the global scope in either language, which sees the global object's names too.
let global = var_env == self.global_env && lex == self.global_lex;
let scope = if self.options.es2015 || global { lex } else { var_env };
// variable environment otherwise (ECMA-262 5.1 section 13). When that is the global
// object's, they close over the global scope inside it, which also holds the scripts'
// `let` and `const` names, as global code's functions do in either language.
let on_global = var_env == self.global_env;
let scope = if self.options.es2015 {
lex
} else if on_global {
self.global_lex
} else {
var_env
};
for (name, fi) in &code.fun_decls {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
@@ -3376,7 +3416,10 @@ impl Interp {
}
Some(Env::Obj { object, .. }) => {
let object = *object;
let declared = self.has_property(object, name)?;
// ECMA-262 2015 section 8.1.1.4.17 reads the object's own property, so a name it
// only inherits gets a new own property; section 10.5 of the 5.1 edition reads the
// inherited one as well.
let declared = if self.options.es2015 { self.get_own_property(object, name)?.is_some() } else { self.has_property(object, name)? };
let flags = WRITABLE | ENUMERABLE | configurable;
match value {
None if declared => Ok(()),
+21 -3
View File
@@ -415,12 +415,17 @@ fn needs_missing_builtin(sources: &[&str], missing: &HashSet<&str>) -> bool {
needs_missing_builtin_in(sources, missing, &Options::default())
}
/// [`needs_missing_builtin`] for sources read with `options`.
/// [`needs_missing_builtin`] for sources read with `options`. With [`Options::es2015`], a source
/// that does not tokenize is left out of the check rather than skipping the test, so the run
/// counts the tokenizer's error as a failure.
fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: &Options) -> bool {
let mut lists = Vec::with_capacity(sources.len());
for source in sources {
let Ok(tokens) = tokenize(source, options) else { return true };
lists.push(tokens);
match tokenize(source, options) {
Ok(tokens) => lists.push(tokens),
Err(_) if options.es2015 => {}
Err(_) => return true,
}
}
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
lists.iter().flatten().any(|t| match &t.kind {
@@ -860,6 +865,19 @@ fn a_missing_name_in_a_message_string_does_not_skip() {
assert!(!skips(&["var x = 1;", r#"function check(v) { if (!v) throw new Test262Error("no Symbol"); }"#]));
}
#[test]
fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() {
// The ES5 runs skip a test whose ES2015 syntax they cannot read. In the ES2015 subset, a
// source that does not tokenize is run, so the tokenizer's error is counted as a failure.
let missing: HashSet<&str> = ["Map"].into_iter().collect();
let modern = Options { es2015: true, ..Options::default() };
let unreadable = "var s = `never closed";
assert!(needs_missing_builtin(&[unreadable], &missing));
assert!(!needs_missing_builtin_in(&[unreadable], &missing, &modern));
// A missing built-in in another source still skips.
assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern));
}
#[test]
fn a_missing_name_in_code_skips() {
assert!(skips(&["var m = new Map();"]));