From e03cf7c5f7e0ef09a5c1881821ad5b6d24e65e73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 17:45:16 -0800 Subject: [PATCH] JavaScript: defining a new property checks the heap limit first Object.defineProperty, Object.defineProperties and Object.create added each new property without checking the heap limit, so one call could take the heap estimate past the limit before the run stopped. The property's size is now reserved before it is added, with the object and the descriptor's values kept reachable while a collection runs. --- crates/js/src/builtins_tests.rs | 15 +++++++++++++++ crates/js/src/interp.rs | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index f031c70dc5..ff4dcbf6df 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -306,6 +306,21 @@ fn keys_built_ins_make_count_toward_the_heap_limit() { assert_eq!(realm.run("b.sort(); JSON.stringify({}, a); JSON.stringify({}, [s, s, s]); b.length"), Ok(JsValue::Number(64.0))); } +#[test] +fn define_properties_checks_the_heap_before_each_new_property() { + // `src` takes most of the heap; copying its 20,000 names onto a new object does not fit, and + // the run ends before the heap estimate passes the limit. + let setup = "var d = {value: 1}; var src = {}; for (var i = 0; i < 20000; i++) src['k' + i] = d; 0"; + let mut measure = small(Limits::default()); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + measure.interp().collect_garbage(); + let heap_bytes = measure.interp().heap.bytes + (1 << 20); + let mut realm = small(Limits { heap_bytes, ..Limits::default() }); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + assert_eq!(limit(&mut realm, "var o = Object.defineProperties({}, src); 0"), LimitKind::Heap); + assert!(realm.interp().heap.bytes <= heap_bytes, "{} > {heap_bytes}", realm.interp().heap.bytes); +} + #[test] fn values_built_ins_hold_survive_collections() { // A small heap makes the callbacks' garbage start collections while the results are built. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 57adbbb9b5..1a60bc8a60 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1073,6 +1073,11 @@ impl Interp { if !o.extensible { return self.reject_bool(throw, &k, "the object is not extensible"); } + // The object and the descriptor's values stay rooted while the heap is checked. + let mut roots = vec![Value::Object(id)]; + roots.extend(desc.value.iter().cloned()); + roots.extend(desc.get.flatten().into_iter().chain(desc.set.flatten()).map(Value::Object)); + self.rooted(&roots, |i| i.reserve_heap(binding_bytes(k.len())))?; let flags = desc.flags_or(0); let prop = if desc.is_accessor() { Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & !WRITABLE }