Skip to content

Truly independent web browser

LibJS: Don't run out of stack going through a tree after its parse

Shannon Booth8f1cd7d13b82
diff --git a/Libraries/LibJS/Parser/Rust/src/base.rs b/Libraries/LibJS/Parser/Rust/src/base.rs
index 6189c2ff00c..9ebf0b6c5e1 100644
--- a/Libraries/LibJS/Parser/Rust/src/base.rs
+++ b/Libraries/LibJS/Parser/Rust/src/base.rs
@@ -2557,8 +2557,7 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {
}
}
- /// Every recursive path of the parser goes through this, and through leave() on the way back. The limit on the
- /// depth also protects what walks the tree later, which recursion here reaches as deep as it reached here.
+ /// Every recursive path of the parser goes through this, and through leave() on the way back.
#[inline(always)]
pub(crate) fn enter(&mut self) -> bool {
let marker = 0u8;
diff --git a/Libraries/LibJS/Parser/Rust/src/resolve.rs b/Libraries/LibJS/Parser/Rust/src/resolve.rs
index 63e4deb3134..0cfa71d8dfe 100644
--- a/Libraries/LibJS/Parser/Rust/src/resolve.rs
+++ b/Libraries/LibJS/Parser/Rust/src/resolve.rs
@@ -436,6 +436,14 @@ impl ScriptView<'_> {
pub struct ResolveOptions {
pub initiated_by_eval: bool,
pub suppress_globals: bool,
+ /// The lowest address that the stack may reach on the way through the tree.
+ pub stack_limit: usize,
+}
+
+/// The tree nests more deeply than the stack that is left can follow, at `position` in the source.
+#[derive(Clone, Copy, Debug)]
+pub struct TooDeep {
+ pub position: u32,
}
/// The scope table that a resolver fills in.
@@ -483,10 +491,13 @@ struct Resolver<'t, 'z> {
is_module: bool,
initiated_by_eval: bool,
suppress_globals: bool,
+ stack_limit: usize,
+ /// Where the stack ran out, after which nothing of the tree gets walked.
+ too_deep: Option<TooDeep>,
}
impl<'t, 'z> Resolver<'t, 'z> {
- fn new(zone: &'z Zone, tree: &'t TreeView<'t>, script: ScriptView<'t>) -> Self {
+ fn new(zone: &'z Zone, tree: &'t TreeView<'t>, script: ScriptView<'t>, options: &ResolveOptions) -> Self {
// NB: Each function that the tree does not hold leaves a reference behind for each name that it captures and
// one more, see `note_free_names_of_function()`. This counts those of every function in the script, which
// is enough for nearly all trees.
@@ -515,8 +526,10 @@ impl<'t, 'z> Resolver<'t, 'z> {
chain_links: ZoneVec::new_in(zone),
loop_depth: 0,
is_module: script.is_module,
- initiated_by_eval: false,
- suppress_globals: false,
+ initiated_by_eval: options.initiated_by_eval,
+ suppress_globals: options.suppress_globals,
+ stack_limit: options.stack_limit,
+ too_deep: None,
tree,
script,
}
@@ -555,12 +568,13 @@ pub fn resolve_program<'z>(
tree: &TreeView<'_>,
script: &ScriptView<'_>,
options: &ResolveOptions,
-) -> Resolved<'z> {
- let mut resolver = Resolver::new(zone, tree, *script);
- resolver.initiated_by_eval = options.initiated_by_eval;
- resolver.suppress_globals = options.suppress_globals;
+) -> Result<Resolved<'z>, TooDeep> {
+ let mut resolver = Resolver::new(zone, tree, *script, options);
resolver.program(tree.root);
- resolver.finish()
+ match resolver.too_deep {
+ Some(too_deep) => Err(too_deep),
+ None => Ok(resolver.finish()),
+ }
}
impl<'t, 'z> Resolver<'t, 'z> {
@@ -1007,11 +1021,13 @@ impl<'t, 'z> Resolver<'t, 'z> {
}
/// The name of the function that a statement declares, labelled or not.
- fn declared_function_name(&self, statement: u32) -> Option<Name> {
- match self.tag(statement) {
- tag::FUNCTION_DECL => Some(Name(self.b(statement))),
- tag::LABELED => self.declared_function_name(self.b(statement)),
- _ => None,
+ fn declared_function_name(&self, mut statement: u32) -> Option<Name> {
+ loop {
+ match self.tag(statement) {
+ tag::FUNCTION_DECL => return Some(Name(self.b(statement))),
+ tag::LABELED => statement = self.b(statement),
+ _ => return None,
+ }
}
}
@@ -1058,6 +1074,19 @@ impl<'t, 'z> Resolver<'t, 'z> {
// === Programs ===
+ /// Whether the stack has no room for what nests in `node`, noting where it first ran out. The parser nests less
+ /// deeply for each level than a walk of its tree does, so a tree that it could build may be too deep here.
+ #[inline(always)]
+ fn out_of_stack(&mut self, node: u32) -> bool {
+ let marker = 0u8;
+ if (&raw const marker as usize) < self.stack_limit && self.too_deep.is_none() {
+ self.too_deep = Some(TooDeep {
+ position: self.pos(node),
+ });
+ }
+ self.too_deep.is_some()
+ }
+
fn program(&mut self, root: u32) {
self.push_frame(FrameKind::Program, self.b(root));
let list = self.list(self.a(root));
@@ -1083,6 +1112,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
}
fn statement(&mut self, node: u32) {
+ if self.out_of_stack(node) {
+ return;
+ }
let (a, b) = (self.a(node), self.b(node));
match self.tag(node) {
tag::EMPTY | tag::DEBUGGER | tag::BREAK | tag::CONTINUE | tag::IMPORT => {}
@@ -1406,7 +1438,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
});
} else {
self.pattern(target, PatternMode::Binding, &mut bound);
- has_parameter_expressions |= self.tree.pattern_contains_expression(target);
+ if self.too_deep.is_none() {
+ has_parameter_expressions |= self.tree.pattern_contains_expression(target);
+ }
}
if default != 0 {
self.expression(default);
@@ -1511,6 +1545,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
/// Makes room for the names that an assignment target refers to as an expression, which come before the names
/// that only it as a pattern refers to.
fn note_names_in_expression(&mut self, node: u32) {
+ if self.out_of_stack(node) {
+ return;
+ }
let start = self.chain_links.len();
let mut first = node;
while Self::continues_chain_in_target(self.tag(first)) {
@@ -1609,6 +1646,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
}
fn pattern(&mut self, node: u32, mode: PatternMode, bound: &mut ZoneVec<'_, BoundName>) {
+ if self.out_of_stack(node) {
+ return;
+ }
let is_array = self.tag(node) == tag::ARRAY_PATTERN;
for &item in self.list(self.a(node)) {
self.pattern_entry(item, is_array, mode, bound);
@@ -1681,6 +1721,9 @@ impl<'t, 'z> Resolver<'t, 'z> {
/// Walks an expression. The parser makes chains like `a + b + c`, `a.b.c` and `a()()` in a loop, which puts no limit
/// on their length, so that they get a loop here as well. What is left is as deep as the recursion of the parser was.
fn expression(&mut self, node: u32) {
+ if self.out_of_stack(node) {
+ return;
+ }
let start = self.chain_links.len();
let mut first = node;
while self.continues_chain(first) {
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 2f9987cf181..9630a0c0006 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -3028,10 +3028,13 @@ impl<'a> Statement<'a> {
// https://tc39.es/ecma262/#sec-static-semantics-lexicallyscopeddeclarations
// LabelledItem : FunctionDeclaration
// 1. Return « |FunctionDeclaration| ».
- match self.kind() {
- StatementKind::FunctionDeclaration(function) => Some(function),
- StatementKind::Labelled(data) => data.item.function_declaration_for_labelled_item(),
- _ => None,
+ let mut statement = *self;
+ loop {
+ match statement.kind() {
+ StatementKind::FunctionDeclaration(function) => return Some(function),
+ StatementKind::Labelled(data) => statement = data.item,
+ _ => return None,
+ }
}
}
}
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index e627fda0bb2..f94cf66cfe2 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -494,104 +494,102 @@ pub(crate) fn module_environment_scope(scope: &ast::Scope) -> Arc<bytecode::code
)
}
-/// Recursively collect var declared names for module scope.
+// 8.2.8 Static Semantics: VarDeclaredNames, https://tc39.es/ecma262/#sec-static-semantics-vardeclarednames
+/// Collects the VarDeclaredNames of a ModuleItem.
pub(crate) fn collect_module_var_names(statement: &ast::Statement, f: &mut dyn FnMut(Utf16View<'_>)) {
- match statement.kind() {
- StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {
- for declarator in &declaration.declarations {
- for_each_bound_name(&declarator.target, f);
- }
- }
- StatementKind::Export(export_data) => {
- if let Some(statement) = export_data.statement {
- collect_module_var_names(&statement, f);
- }
- }
- _ => {
- for_each_child_statement(statement, &mut |child| {
- collect_module_var_names(child, f);
- });
+ // ModuleItem : ExportDeclaration
+ // 1. If ExportDeclaration is export VariableStatement, return the BoundNames of ExportDeclaration.
+ // 2. Return a new empty List.
+ if let StatementKind::Export(export_data) = statement.kind() {
+ if let Some(statement) = export_data.statement {
+ collect_var_declared_names(statement, f);
}
+ return;
}
+ collect_var_declared_names(*statement, f);
}
-/// Recursively collect var-declared names from a statement and all nested
-/// statements, excluding function/class bodies (which create new var scopes).
-pub(crate) fn collect_var_names_recursive(statement: &ast::Statement, push_name: &mut dyn FnMut(Utf16View<'_>)) {
- match statement.kind() {
- StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {
- for declarator in &declaration.declarations {
- for_each_bound_name(&declarator.target, push_name);
+// 8.2.8 Static Semantics: VarDeclaredNames, https://tc39.es/ecma262/#sec-static-semantics-vardeclarednames
+/// Collects the VarDeclaredNames of a statement, in the order of the source.
+pub(crate) fn collect_var_declared_names(mut statement: ast::Statement<'_>, push_name: &mut dyn FnMut(Utf16View<'_>)) {
+ // NB: The VarDeclaredNames of a statement are those of the statements in it, which are a list here in place of
+ // recursion: statements nest as deeply as the parser allows, which is more than the stack may have room for.
+ let mut pending = Vec::new();
+ loop {
+ match statement.kind() {
+ // VariableStatement : var VariableDeclarationList ;
+ // 1. Return the BoundNames of VariableDeclarationList.
+ StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {
+ for declarator in &declaration.declarations {
+ for_each_bound_name(&declarator.target, push_name);
+ }
+ }
+ _ => {
+ let start = pending.len();
+ child_statements(statement, &mut pending);
+ pending[start..].reverse();
}
}
- _ => {
- for_each_child_statement(statement, &mut |child| {
- collect_var_names_recursive(child, push_name);
- });
- }
+ let Some(next) = pending.pop() else {
+ return;
+ };
+ statement = next;
}
}
-/// Visit each child statement of a statement, excluding function/class bodies
-/// (which create new var scopes). This enables recursive var-declaration walking.
-fn for_each_child_statement(statement: &ast::Statement, f: &mut dyn FnMut(&ast::Statement)) {
+/// Appends the child statements of a statement, excluding function/class bodies
+/// (which create new var scopes), as VarDeclaredNames goes through them.
+fn child_statements<'a>(statement: ast::Statement<'a>, children: &mut Vec<ast::Statement<'a>>) {
match statement.kind() {
StatementKind::Block(scope) => {
- for child in &scope.children {
- f(&child);
- }
+ children.extend(&scope.children);
}
StatementKind::If(data) => {
- f(&data.consequent);
- if let Some(alternate) = &data.alternate {
- f(alternate);
- }
+ children.push(data.consequent);
+ children.extend(data.alternate);
}
StatementKind::While(data) => {
- f(&data.body);
+ children.push(data.body);
}
StatementKind::DoWhile(data) => {
- f(&data.body);
+ children.push(data.body);
}
StatementKind::With(data) => {
- f(&data.body);
+ children.push(data.body);
}
StatementKind::For(data) => {
if let Some(ast::ForInit::Declaration(declaration)) = &data.init {
- f(declaration);
+ children.push(*declaration);
}
- f(&data.body);
+ children.push(data.body);
}
StatementKind::ForInOf(data) => {
if let ast::ForInOfLhs::Declaration(declaration) = &data.lhs {
- f(declaration);
+ children.push(*declaration);
}
- f(&data.body);
+ children.push(data.body);
}
StatementKind::Switch(data) => {
for case in &data.cases {
- for child in &case.scope.children {
- f(&child);
- }
+ children.extend(&case.scope.children);
}
}
StatementKind::Try(data) => {
- f(&data.block);
+ children.push(data.block);
if let Some(handler) = &data.handler {
- f(&handler.body);
- }
- if let Some(finalizer) = &data.finalizer {
- f(finalizer);
+ children.push(handler.body);
}
+ children.extend(data.finalizer);
}
StatementKind::Labelled(data) => {
- f(&data.item);
+ children.push(data.item);
}
// Don't recurse into function/class bodies (new var scopes)
_ => {}
}
}
+// 8.2.1 Static Semantics: BoundNames, https://tc39.es/ecma262/#sec-static-semantics-boundnames
pub(crate) fn for_each_bound_name(target: &ast::VariableDeclaratorTarget, f: &mut dyn FnMut(Utf16View<'_>)) {
match target {
ast::VariableDeclaratorTarget::Identifier(identifier) => f(identifier.text()),
@@ -601,8 +599,16 @@ pub(crate) fn for_each_bound_name(target: &ast::VariableDeclaratorTarget, f: &mu
}
}
+// 8.2.1 Static Semantics: BoundNames, https://tc39.es/ecma262/#sec-static-semantics-boundnames
fn for_each_bound_name_in_pattern(pattern: &ast::BindingPattern, f: &mut dyn FnMut(Utf16View<'_>)) {
- for entry in &pattern.entries {
+ // NB: The BoundNames of a pattern are those of the patterns in it, which are a list here in place of recursion:
+ // patterns nest as deeply as the parser allows, which is more than the stack may have room for.
+ let mut pending = vec![pattern.entries.iter()];
+ while let Some(entries) = pending.last_mut() {
+ let Some(entry) = entries.next() else {
+ pending.pop();
+ continue;
+ };
match &entry.alias {
None => {
if let Some(ast::BindingEntryName::Identifier(identifier)) = &entry.name {
@@ -611,7 +617,7 @@ fn for_each_bound_name_in_pattern(pattern: &ast::BindingPattern, f: &mut dyn FnM
}
Some(ast::BindingEntryAlias::Identifier(identifier)) => f(identifier.text()),
Some(ast::BindingEntryAlias::BindingPattern(inner)) => {
- for_each_bound_name_in_pattern(inner, f);
+ pending.push(inner.entries.iter());
}
Some(ast::BindingEntryAlias::MemberExpression(_)) => {}
}
@@ -1562,7 +1568,7 @@ fn collect_var_scoped_declarations(tree: &SyntaxTree<'_>) -> VarScopedDeclaratio
// Var names (var declarations at any nesting level + top-level function declarations)
let mut var_names = Vec::new();
for child in &scope.children {
- collect_var_names_recursive(&child, &mut |name| var_names.push(name.into()));
+ collect_var_declared_names(child, &mut |name| var_names.push(name.into()));
if let Some(function) = child.function_declaration_for_labelled_item()
&& let Some(name) = function.name
{
@@ -1604,7 +1610,7 @@ fn collect_var_scoped_declarations(tree: &SyntaxTree<'_>) -> VarScopedDeclaratio
// Var-scoped names (var VariableDeclaration names, excluding function declarations)
let mut var_scoped_names = Vec::new();
for child in &scope.children {
- collect_var_names_recursive(&child, &mut |name| var_scoped_names.push(name.into()));
+ collect_var_declared_names(child, &mut |name| var_scoped_names.push(name.into()));
}
let mut lexical_bindings = Vec::new();
diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rs
index e5569196606..ba7cf4f970d 100644
--- a/Libraries/LibJS/Rust/src/parser/mod.rs
+++ b/Libraries/LibJS/Rust/src/parser/mod.rs
@@ -590,6 +590,7 @@ fn parse_code_units<'z, U: Unit + Default, R>(
return Ok(None);
}
let lines = LineTable::new(zone, units, options.initial_line_number);
+ let stack_limit = parser.stack_limit;
let index = core::mem::replace(&mut parser.index, FunctionIndexBuilder::with_capacity(zone, 0)).finish();
let top_level_rows = parser
.parse_top_level_rows(
@@ -643,8 +644,20 @@ fn parse_code_units<'z, U: Unit + Default, R>(
&resolve::ResolveOptions {
initiated_by_eval: options.initiated_by_eval,
suppress_globals: options.suppress_globals,
+ stack_limit,
},
);
+ let resolved = match resolved {
+ Ok(resolved) => resolved,
+ Err(too_deep) => {
+ let position = script.positions.lines.position(too_deep.position);
+ return Err(vec![ParseError {
+ message: base::RECURSION_LIMIT_MESSAGE.to_owned(),
+ line: position.line,
+ column: position.column,
+ }]);
+ }
+ };
let tree = SyntaxTree {
script,
source: source.clone(),
diff --git a/Tests/LibJS/Runtime/eval-near-stack-limit.js b/Tests/LibJS/Runtime/eval-near-stack-limit.js
new file mode 100644
index 00000000000..a8b6c8084c0
--- /dev/null
+++ b/Tests/LibJS/Runtime/eval-near-stack-limit.js
@@ -0,0 +1,27 @@
+test("eval of nested code near the call stack size limit", () => {
+ const sources = [
+ "try{".repeat(100) + "1" + "}finally{}".repeat(100),
+ "{".repeat(150) + "1" + "}".repeat(150),
+ "if (1) ".repeat(150) + "1;",
+ "var a; " + "a = ".repeat(150) + "1",
+ "var " + "[".repeat(150) + "a" + "]".repeat(150) + " = [];",
+ Array.from({ length: 1900 }, (_, i) => `l${i}:`).join("") + ";",
+ ];
+ let levels = 0;
+ function recurse() {
+ try {
+ Reflect.apply(recurse, null, []);
+ } catch {}
+ if (levels++ > 1000) return;
+ for (const source of sources) {
+ try {
+ eval(source);
+ } catch {}
+ try {
+ (0, eval)(source);
+ } catch {}
+ }
+ }
+ recurse();
+ expect(sources.slice(0, 4).map(source => (0, eval)(source))).toEqual([1, 1, 1, 1]);
+});