From 6b8c10999d7e25cf116cd0762378ebbd6c6de62b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:00:34 -0800 Subject: [PATCH 1/3] 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. --- crates/js/src/es2015_tests.rs | 101 ++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 77 ++++++++++++++++++++------ crates/js/tests/test262.rs | 24 +++++++- 3 files changed, 182 insertions(+), 20 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index d717ba2090..0173fb2d6c 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -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::>().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 diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 1030101bab..dc0e678e91 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -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 = 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 { + 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 { 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(()), diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index d9713de57f..32790b3125 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -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();"])); From 2f465a09c34fa67ddb3caeda889f05202f9837d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:03:49 -0800 Subject: [PATCH 2/3] Docs: ES2015 test262 counts include the tests that do not tokenize The ES2015 subset now runs the tests whose sources the token reader rejects, 151 more runs, so the evidence line gives 533 of 708 other runs and lists the forms that the runs that do not parse use. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 98cb315cc1..144b20bd1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,7 +1079,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From d61d494bea19b4b2417ff6b805358dde4edddb2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:09:51 -0800 Subject: [PATCH 3/3] JavaScript: declarations and spread checks stay within the heap and fuel limits - A function body, after default parameters or plain ones, and eval code check the heap for their function declarations and variables after their `let` and `const` environment is made, so the estimate stays within the limit while the declarations are bound. - Looking for an index getter before spreading a long array takes a unit of fuel for each property it inspects, as well as for each object. - An index accessor with only a setter no longer delays the check of an array of length 4294967295 when spread begins, since reading the elements does not run it. - The eval test with `with` now gives the `with` object an `x`, and the function case declares its own `var x`, so a function closing over the wrong environment fails it. --- crates/js/src/es2015_tests.rs | 77 ++++++++++++++++++++++++++++++++++- crates/js/src/interp.rs | 28 ++++++++++--- 2 files changed, 98 insertions(+), 7 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 0173fb2d6c..0b168ad5dc 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -190,8 +190,12 @@ fn a_function_eval_declares_on_the_global_object_sees_global_lexical_bindings() 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))); + // The `with` object's `x` would be read if the function closed over the eval's lexical + // environment. + assert_eq!(realm.run("with ({ x: 99 }) { eval('function read() { return x; }'); } read()"), Ok(JsValue::Number(7.0))); + // In a function, the variable environment is the function's own, which holds its `var x`. + let local = "function g() { var x = 8; with ({ x: 99 }) { eval('function inner() { return x; }'); } return inner(); } g()"; + assert_eq!(realm.run(local), Ok(JsValue::Number(8.0))); } #[test] @@ -519,6 +523,32 @@ fn an_array_s_spread_is_checked_against_the_elements_it_reads() { throws("[0, ...{ length: 4294967295 }];", "RangeError"); } +#[test] +fn an_index_setter_without_a_getter_does_not_delay_the_spread_s_check() { + // A setter does not run when the elements are read, so the array is still checked when + // spread begins, on its own and on its prototype. + for setter in ["a", "Array.prototype"] { + let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() }); + let src = format!("var a = []; a.length = 4294967295; Object.defineProperty({setter}, 0, {{ set: function () {{}} }}); [...a]"); + let long = realm.run(&src); + assert!(is_thrown(&long, "RangeError"), "{setter}: {long:?}"); + } +} + +#[test] +fn looking_for_index_getters_takes_fuel_for_each_property() { + // Each attempt to spread the long array looks at every one of its 10,000 elements, so each + // takes at least that much fuel. + let fuel = 10_000_000; + let mut realm = Realm::with_options(es_options(), Limits { fuel, ..Limits::default() }); + let setup = "var a = []; for (var i = 0; i < 10000; i++) a[i] = i; a.length = 4294967295; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let attempt = "var ok = false; try { [...a]; } catch (e) { ok = e instanceof RangeError; } ok"; + assert_eq!(realm.run(attempt), Ok(JsValue::Bool(true))); + let used = fuel - realm.interp().fuel; + assert!(used >= 10_000, "{used}"); +} + #[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 @@ -631,6 +661,49 @@ fn a_body_after_default_parameters_checks_the_heap_before_its_scope_is_made() { assert!(stopped > 0, "no count reached the heap limit"); } +#[test] +fn declarations_are_checked_after_the_let_and_const_names_take_their_room() { + // The `let` names and the variables each fit in the heap, but not always together. Each run + // stops for lack of fuel at a different point, before a collection could correct the + // estimate, and the estimate is within the limit at every one of them: in a body after + // default parameters, in a plain function's body and in eval code. + let names = |prefix: &str| (0..100).map(|i| format!("{prefix}{i:0>60}")).collect::>().join(", "); + let (lets, vars) = (names("l"), names("v")); + let bodies = [ + format!("function f(a = 0) {{ let {lets}; var {vars}; return 1; }} 0"), + format!("function f() {{ let {lets}; var {vars}; return 1; }} 0"), + format!("function f() {{ eval('let {lets}; var {vars};'); return 1; }} 0"), + ]; + for setup in &bodies { + 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; + assert_eq!(measure.run("f()"), Ok(JsValue::Number(1.0))); + let fuel = Limits::default().fuel - measure.interp().fuel; + for extra in (0..100).map(|k| k * 2048) { + 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; + } + // The declarations are made in the last 600 units of fuel, after any parsing, and + // the estimate stays past the limit for as many units as variables made after it + // passed, so every fourth stop there finds it. + for f in (fuel.saturating_sub(600).max(1)..=fuel).step_by(4) { + realm.interp().collect_garbage(); + realm.set_limits(Limits { heap_bytes, fuel: f, ..Limits::default() }); + let at = &setup[..24]; + match realm.run("f()") { + Ok(v) => assert_eq!(v, JsValue::Number(1.0), "{at}: {heap_bytes}, {f}"), + Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(LimitKind::Heap | LimitKind::Fuel)), "{at}: {heap_bytes}, {f}: {e:?}"), + } + assert!(realm.interp().heap.bytes <= heap_bytes, "{at}: {heap_bytes}, {f}: {}", realm.interp().heap.bytes); + } + } + } +} + #[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 diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index dc0e678e91..80386ce379 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2285,13 +2285,15 @@ impl Interp { 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))?; + self.reserve_heap(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) }); self.frame_mut()?.var_env = var_env; let lex = self.top_env(&code, var_env)?; self.frame_mut()?.env = lex; + // The declarations are checked after the `let` and `const` environment has taken its room. + self.reserve_heap(declaration_bytes(&code))?; 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") }; @@ -2432,16 +2434,23 @@ impl Interp { } /// 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. + /// from has an accessor property with a getter and an index name. Each object, and each + /// property inspected, takes a unit of fuel. fn has_index_getter(&mut self, o: ObjId) -> JsResult { let mut cur = Some(o); while let Some(id) = cur { - self.use_fuel()?; + // The scan stops where the fuel would run out. + let budget = usize::try_from(self.fuel).unwrap_or(usize::MAX); let object = self.object(id)?; - if object.props.iter().any(|(k, p)| matches!(p, Prop::Accessor { .. }) && array_index(k).is_some()) { + let found = + object.props.iter().take(budget).position(|(k, p)| matches!(p, Prop::Accessor { get: Some(_), .. }) && array_index(k).is_some()); + let inspected = found.map_or(object.props.len(), |i| i + 1); + let proto = object.proto; + crate::regexp_vm::use_fuel_n(self, (inspected as u64).saturating_add(1))?; + if found.is_some() { return Ok(true); } - cur = object.proto; + cur = proto; } Ok(false) } @@ -2921,6 +2930,9 @@ impl Interp { let has = |interp: &Self, name: &[u16]| matches!(interp.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.contains(name)); let lex = self.top_env(code, env)?; self.temp_envs.push(lex); + // The call reserved room for the declarations before the `let` and `const` environment + // took some of it. + self.reserve_heap(declaration_bytes(code))?; 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") }; @@ -3343,6 +3355,12 @@ impl Interp { Some(i) => self.block_env(code, i, env)?, None => env, }; + // The caller reserved room for the declarations before the `let` and `const` names took + // some of it. Their environment stays reachable if the check collects. + self.temp_envs.push(lex); + let r = self.reserve_heap(declaration_bytes(code)); + self.temp_envs.pop(); + r?; // Functions close over the code's own environment with ES2015's scoping, and over its // 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'