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));