From e5a1f339c3607546f1d5074be03e918a72b89dfe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:44:02 -0800 Subject: [PATCH 1/3] JavaScript: spreading a string counts its flattened copy against the heap Spreading a concatenated string (`[...s]`, `f(...s)`) flattened it before any limit was checked, so a script could make the host build the whole copy before the per-element fuel and heap accounting ran. The spread now flattens through the same counted helper the string built-ins use, which ends the run with the heap limit before the copy is made. --- crates/js/src/es2015_tests.rs | 17 +++++++++++++++++ crates/js/src/interp.rs | 5 +++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 3e27c3925a..7117dae281 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -364,6 +364,23 @@ fn spread_and_templates_stay_within_the_limits() { throws("var a = []; a.length = 4294967294; [0, ...a];", "RangeError"); } +#[test] +fn spreading_a_rope_counts_its_flattened_length_first() { + // `mk` returns a rope whose left half is a flat string of about half the heap, held by + // nothing else. Its flattened copy is the other half, so the two don't fit together. Making + // the left half takes about 16,400 fuel, and the elements read before the heap fills would + // take more than the rest, so only the check before the copy ends the run with the heap limit. + let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \ + function mk() { var a = f('a'); a[0]; return a + 'b'; }"; + let limits = Limits { heap_bytes: 4 * 262_146, fuel: 20_000, ..Limits::default() }; + for spread in ["[...mk()]", "Math.max(...mk())"] { + let e = Realm::with_options(es_options(), limits.clone()).run(&format!("{build} {spread}; 0")).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread}: {e:?}"); + } + let made = Realm::with_options(es_options(), limits).run(&format!("{build} mk(); 0")); + assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel"); +} + #[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 7a44fed2fe..10f3216c67 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2292,13 +2292,14 @@ impl Interp { /// Appends the elements of the value on top to the array under it: an array's elements by /// index (holes read as `undefined`), a string'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. + /// 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. 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") }; let items: Vec = match &v { Value::String(s) => { - let units = s.flat(); + let units = crate::string_builtins::flat_charged(self, s)?; let mut out = Vec::new(); let mut held = HeldBytes::new(self); let mut i = 0; From 4447e02955a41164396b1fb081ddec0c32fd2ff6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:52:01 -0800 Subject: [PATCH 2/3] JavaScript: a rest parameter checks the heap before its array is made A call to a function with a rest parameter built the array of its extra arguments without reserving room for it, so `f.apply(null, big)` could push the heap estimate past the limit. The call now counts the rest array, its binding and one property per extra argument in the room it reserves before the function's environment is made. --- crates/js/src/es2015_tests.rs | 17 +++++++++++++++++ crates/js/src/interp.rs | 10 +++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 7117dae281..dc9f4fefce 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -381,6 +381,23 @@ fn spreading_a_rope_counts_its_flattened_length_first() { assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel"); } +#[test] +fn a_rest_parameter_checks_the_heap_before_its_array_is_made() { + // The 20,000 arguments fit in the room left over, and the rest array of them does not, so + // the call ends with the heap limit before the heap estimate passes it. + let setup = "function f(...r) { return r.length; } var big = Array(20000); 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 + (512 << 10); + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("f.apply(null, Array(10))"), Ok(JsValue::Number(10.0))); + let e = realm.run("f.apply(null, big)").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}"); + assert!(realm.interp().heap.bytes <= heap_bytes, "{} > {heap_bytes}", 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 10f3216c67..3a90e06e00 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2727,7 +2727,15 @@ impl Interp { let params = code.params.iter().fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len()))); let arguments = if code.uses_arguments { OBJECT_BYTES.saturating_add(args.len().saturating_add(4).saturating_mul(binding_bytes(10))) } else { 0 }; - let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments); + // The array a rest parameter gets: its binding and one property for each extra argument. + let rest = match &code.rest { + Some(name) => { + let extra = args.len().saturating_sub(code.params.len()); + OBJECT_BYTES.saturating_add(binding_bytes(name.len())).saturating_add(extra.saturating_mul(binding_bytes(10))) + } + None => 0, + }; + let need = declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(params).saturating_add(arguments).saturating_add(rest); if self.heap.bytes.saturating_add(need) > self.limits.heap_bytes { let mark = self.temp_roots.len(); self.temp_roots.push(Value::Object(callee)); From 33bcf63381f46008527c8fd73ddb5ed786b87b49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:13:14 -0800 Subject: [PATCH 3/3] JavaScript: a global function declaration reads the global object's own property With ES2015 scripts, a function declaration was judged by a property the global object inherits, so a fixed property on Object.prototype stopped `function name() {}`. The check now reads the global object's own property, as ECMA-262 2015 section 8.1.1.4.16 does, and declares nothing when the global object is not extensible and has no property of that name. Indirect eval code makes the same check for all of its functions before it declares any of them, and a function declaration never adds a property to a global object that is not extensible. --- crates/js/src/es2015_tests.rs | 31 ++++++++++++++++++++++ crates/js/src/interp.rs | 50 ++++++++++++++++++++++++----------- 2 files changed, 66 insertions(+), 15 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index dc9f4fefce..32a6caa1ee 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -169,6 +169,37 @@ fn a_global_function_that_cannot_be_declared_declares_nothing() { assert_eq!(realm.run("let retained = 2; retained"), Ok(JsValue::Number(2.0))); } +#[test] +fn a_global_function_is_judged_by_the_global_objects_own_property() { + // ECMA-262 2015 sections 8.1.1.4.16 and 8.1.1.4.18 read the global object's own property, so + // a fixed property the global object inherits does not stop the declaration. + let mut realm = es(); + let setup = "Object.defineProperty(Object.prototype, 'fixed', { value: 1 }); \ + Object.defineProperty(Object.prototype, 'getter', { get: function () { return 1; } }); 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("function fixed() { return 2; } function getter() { return 3; } fixed() + getter()"), Ok(JsValue::Number(5.0))); + let own = "var d = Object.getOwnPropertyDescriptor(this, 'fixed'); d.writable && d.enumerable && !d.configurable && ({}).fixed === 1"; + assert_eq!(realm.run(own), Ok(JsValue::Bool(true))); + // A global object that is not extensible takes no new function, inherited name or not, and + // a function declared next to one it cannot take is not declared either. + let mut realm = es(); + assert_eq!(realm.run(&format!("{setup}; var kept = 1; Object.preventExtensions(this); 0")), Ok(JsValue::Number(0.0))); + for decl in [ + "function fixed() {}", + "function fresh() {}", + "(0, eval)('function fixed() {}')", + "(0, eval)('function fresh() {}')", + "(0, eval)('function kept() {} function fresh() {}')", + ] { + let failed = realm.run(decl); + assert!( + matches!(&failed, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")), + "{decl}: {failed:?}" + ); + } + assert_eq!(realm.run("this.hasOwnProperty('fixed') || this.hasOwnProperty('fresh') || kept !== 1"), Ok(JsValue::Bool(false))); +} + #[test] fn eval_code_keeps_its_let_and_const_to_itself() { truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'"); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3a90e06e00..a79328cf60 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3145,20 +3145,7 @@ impl Interp { } } if self.options.es2015 { - // The test `declare` makes for a function in an object environment (section 15.1.8, - // step 8, CanDeclareGlobalFunction). - for (name, _) in &code.fun_decls { - let replaceable = match self.find_property(global, name)? { - None => true, - Some(p) if p.configurable() => true, - Some(Prop::Data { flags, .. }) => flags & (WRITABLE | ENUMERABLE) == WRITABLE | ENUMERABLE, - Some(_) => false, - }; - if !replaceable { - let ident = String::from_utf16_lossy(name); - return Err(self.type_error(&format!("cannot declare function {ident}"))); - } - } + self.check_global_functions(code)?; } for (name, constant) in lets { let b = Binding::lexical(*constant); @@ -3167,6 +3154,27 @@ impl Interp { Ok(()) } + /// The test `declare` makes for a function in an object environment, on the global object's + /// own property, for every function `code` declares before any is (ECMA-262 2015 sections + /// 15.1.8, step 8, and 18.2.1.2, step 8, CanDeclareGlobalFunction): a function that cannot + /// replace its property is a `TypeError`. + fn check_global_functions(&mut self, code: &Code) -> JsResult<()> { + let global = self.global; + for (name, _) in &code.fun_decls { + let replaceable = match self.get_own_property(global, name)? { + None => self.object(global)?.extensible, + Some(p) if p.configurable() => true, + Some(Prop::Data { flags, .. }) => flags & (WRITABLE | ENUMERABLE) == WRITABLE | ENUMERABLE, + Some(_) => false, + }; + if !replaceable { + let ident = String::from_utf16_lossy(name); + return Err(self.type_error(&format!("cannot declare function {ident}"))); + } + } + Ok(()) + } + fn push_code_frame(&mut self, code: Rc, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> { if self.frames.len() >= self.limits.frames { return Err(Abrupt::Limit(LimitKind::Frames)); @@ -3198,6 +3206,9 @@ impl Interp { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict && self.options.es2015 { self.check_eval_vars(code, env, var_env)?; + if var_env == self.global_env { + self.check_global_functions(code)?; + } } let lex = match code.top_scope { _ if !is_eval && env == self.global_lex => { @@ -3273,7 +3284,16 @@ impl Interp { None if declared => Ok(()), None => self.define(object, name.clone(), Prop::Data { value: Value::Undefined, flags }), Some(v) => { - let existing = self.find_property(object, name)?; + // ECMA-262 2015 section 8.1.1.4.18 reads the object's own property, and + // section 10.5 of the 5.1 edition the property it inherits as well. + let existing = if self.options.es2015 { self.get_own_property(object, name)? } else { self.find_property(object, name)? }; + // A new own property needs an extensible object (ECMA-262 2015 section + // 8.1.1.4.16; section 8.12.9 of the 5.1 edition, step 3). + let defines = existing.as_ref().is_none_or(Prop::configurable); + if defines && !self.object(object)?.extensible && self.get_own_property(object, name)?.is_none() { + let ident = String::from_utf16_lossy(name); + return Err(self.type_error(&format!("cannot declare function {ident}"))); + } match existing { None => self.define(object, name.clone(), Prop::Data { value: v, flags }), Some(p) if p.configurable() => self.define(object, name.clone(), Prop::Data { value: v, flags }),