mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 11:23:43 +01:00
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.
This commit is contained in:
1 parent
2f465a09c3
commit
d61d494bea
2 files changed
+98
-7
No files matched your search
@@ -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::<Vec<_>>().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
|
||||
|
||||
+23
-5
@@ -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<bool> {
|
||||
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'
|
||||
|
||||
Reference in new issue
Block a user