diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index c5a5396dbe..7792e4c56c 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -170,6 +170,33 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() { assert!(restricted.is_err(), "{restricted:?}"); } +#[test] +fn a_script_stopped_at_the_heap_limit_declares_no_global_lexical_name() { + // The `let` names and the variables each fit in the heap at some limits, but not together. + // A run that stops at the heap limit adds none of the names, so the same script runs once the + // limit is raised. + let names = |prefix: &str| (0..100).map(|i| format!("{prefix}{i:0>60}")).collect::>().join(", "); + let src = format!("let {} = 1; var {}; 0", names("l"), names("v")); + let mut measure = Realm::with_options(es_options(), Limits::default()); + measure.interp().collect_garbage(); + let base = measure.interp().heap.bytes; + let mut stopped = 0; + for extra in (0..200).map(|k| k * 512) { + let heap_bytes = base + extra; + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + match realm.run(&src) { + Ok(v) => assert_eq!(v, JsValue::Number(0.0), "{heap_bytes}"), + Err(e) => { + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{heap_bytes}: {e:?}"); + stopped += 1; + realm.set_limits(Limits::default()); + assert_eq!(realm.run(&src), Ok(JsValue::Number(0.0)), "{heap_bytes}: run again"); + } + } + } + assert!(stopped > 0, "no limit stopped the script"); +} + #[test] fn functions_from_earlier_runs_see_later_global_lexical_bindings() { let mut realm = Realm::new(); @@ -579,6 +606,22 @@ fn an_index_setter_without_a_getter_does_not_delay_the_spread_s_check() { } } +#[test] +fn a_prototype_getter_behind_an_own_element_does_not_delay_the_spread_s_check() { + // The array's own element 0 is read instead of the getter on its prototype, so no getter can + // shrink it, and it is checked when spread begins. + let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() }); + let src = "var a = [7]; Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 0; } }); \ + a.length = 4294967295; [...a]"; + let long = realm.run(src); + assert!(is_thrown(&long, "RangeError"), "{long:?}"); + // A getter on the prototype with no own element in front of it is read, and shrinks the array. + let shrink = "var a = []; a.length = 4294967295; \ + Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 7; } }); \ + var b = [...a]; b.length === 1 && b[0] === 7"; + truth(shrink); +} + #[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 @@ -620,6 +663,41 @@ fn spread_counts_each_index_name_against_the_heap() { } } +#[test] +fn spread_stops_at_the_heap_limit_before_the_next_step_runs() { + // With room for about half the elements, the spread stops with the heap limit while it reads + // them. Each run's fuel ends somewhere in the steps just after the spread, so a check made + // only at the next step would end the run for lack of fuel first, with the elements over the + // limit until a collection. + for spread in ["[...a]", "[...s]"] { + let setup = "var a = Array(4000); var s = new Array(4001).join('x'); 0"; + let run = format!("var b = {spread}; 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; + assert_eq!(measure.run(&run), Ok(JsValue::Number(0.0))); + let fuel = Limits::default().fuel - measure.interp().fuel; + measure.interp().collect_garbage(); + let need = measure.interp().heap.bytes - base; + let heap_bytes = base + need / 2; + for f in fuel.saturating_sub(40).max(1)..=fuel { + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)), "{spread}"); + realm.interp().collect_garbage(); + realm.set_limits(Limits { heap_bytes, fuel: f, ..Limits::default() }); + let e = realm.run(&run).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread} at fuel {f}: {e:?}"); + let bytes = realm.interp().settled_heap_bytes(); + assert!(bytes <= heap_bytes, "{spread} at fuel {f}: {bytes} > {heap_bytes}"); + } + // With room for twice the elements, the spread completes. + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: base + need * 2, ..Limits::default() }); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)), "{spread}"); + assert_eq!(realm.run(&format!("var b = {spread}; b.length")), Ok(JsValue::Number(4000.0)), "{spread}"); + } +} + #[test] fn spreading_other_values_is_a_type_error() { throws("[...1];", "TypeError"); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 274b37d9fa..5b296033ef 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -740,6 +740,14 @@ impl Interp { self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened); } + /// The heap's total with the released and flattened bytes taken into account, without a + /// collection. + #[cfg(test)] + pub(crate) fn settled_heap_bytes(&mut self) -> usize { + self.settle_held(); + self.heap.bytes + } + /// Collects garbage now and sets when the next collection runs. #[cfg(test)] pub(crate) fn collect_for_room(&mut self) { @@ -2449,22 +2457,52 @@ 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 a getter and an index name. Each object, and each - /// property inspected, takes a unit of fuel. + /// from has an accessor property with a getter and an index name, and no object before it + /// in the chain has an own property of that name, which an indexed read would find first. + /// Each object, each property inspected and each earlier object a getter is looked up in + /// takes a unit of fuel. fn has_index_getter(&mut self, o: ObjId) -> JsResult { + // The objects already scanned, whose own properties shadow a getter further along. + let mut before: Vec = Vec::new(); let mut cur = Some(o); while let Some(id) = cur { // 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)?; - 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 mut used = 0usize; + let mut found = false; + for (k, p) in object.props.iter() { + if used >= budget { + break; + } + used = used.saturating_add(1); + if !matches!(p, Prop::Accessor { get: Some(_), .. }) || array_index(k).is_none() { + continue; + } + let mut shadowed = false; + for &earlier in &before { + // Where the fuel runs out the scan stops, and the charge below fails. + if used >= budget { + shadowed = true; + break; + } + used = used.saturating_add(1); + if self.get_own_property(earlier, k)?.is_some() { + shadowed = true; + break; + } + } + if !shadowed { + found = true; + break; + } + } let proto = object.proto; - crate::regexp_vm::use_fuel_n(self, (inspected as u64).saturating_add(1))?; - if found.is_some() { + crate::regexp_vm::use_fuel_n(self, (used as u64).saturating_add(1))?; + if found { return Ok(true); } + before.push(id); cur = proto; } Ok(false) @@ -3279,6 +3317,10 @@ impl Interp { self.check_global_functions(code)?; self.check_global_vars(code)?; } + // The room for the names and the declarations is checked before any name is added, so a + // run that stops at the heap limit here adds no name to the global scope. + let names = lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len()))); + self.reserve_heap(names.saturating_add(declaration_bytes(code)))?; for (name, constant) in lets { let b = Binding::lexical(*constant); self.env_insert(lex, name.clone(), b)?; @@ -3382,7 +3424,8 @@ impl Interp { 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. + // some of it (a script's names in the global scope were checked with the declarations + // before they were added). 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();