Skip to content

Commit c9c78db

Browse files
authored
Bound AST nesting so deep source raises instead of crashing (#8827)
* Bound AST nesting so deep source raises instead of crashing Deeply nested source exhausted the native stack and killed the process with SIGSEGV, which no Python-level `except` can catch. The parser grows its own stack when it runs low on one, so it returns trees deeper than the passes after it can walk. Those passes recurse without a limit of their own, and the symbol table, which does apply one, runs last. `compile(..., PyCF_ONLY_AST)` returns before reaching it at all. Apply that same limit to the tree right after it is parsed, and count bracket nesting before parsing rather than after, as CPython's tokenizer does. Checking afterwards built the tree first, and one nested that deep exhausts the stack when it is dropped. Fixes #7655 Assisted-by: Claude Code:Opus 5 * Return Result from too_deeply_nested_error Lets the four call sites use `?` instead of matching on `Some` and returning the error by hand, which drops 11 lines. `Result` is already `#[must_use]`, so the attribute on the function goes away with it. Assisted-by: Claude Code:Opus 5 * Return Result from pre_parse_source_error too Same shape as the previous commit, for the other check this PR adds, so the two are consistent with each other. Assisted-by: Claude Code:Opus 5 * Drop exceeds_max_nesting for the check beside it The escape-warning pass needs the bracket check but had no `SourceFile` to build a `CompileError` from, so it got a `bool` wrapper of its own. Building the `SourceFile` there lets it call `pre_parse_source_error` instead, which is shaped like the other checks in that file, and costs nothing measurable. Assisted-by: Claude Code:Opus 5
1 parent 100dac0 commit c9c78db

4 files changed

Lines changed: 169 additions & 4 deletions

File tree

‎crates/compiler/src/lib.rs‎

Lines changed: 93 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6796,6 +6796,17 @@ pub fn leading_byte_order_mark_error(source_file: &SourceFile) -> Option<Compile
67966796
})
67976797
}
67986798

6799+
/// Source-level errors raised before parsing, as CPython's tokenizer does.
6800+
///
6801+
/// Checking after the parse would build the tree first, and one nested that
6802+
/// deep exhausts the native stack when it is dropped.
6803+
pub fn pre_parse_source_error(source_file: &SourceFile) -> Result<(), CompileError> {
6804+
match too_many_nested_parentheses_error(source_file.source_text()) {
6805+
Some(error) => Err(CompileError::from_source_error(source_file, error)),
6806+
None => Ok(()),
6807+
}
6808+
}
6809+
67996810
fn post_parse_source_error(
68006811
source_file: &SourceFile,
68016812
tokens: &Tokens,
@@ -6804,9 +6815,6 @@ fn post_parse_source_error(
68046815
if let Some(error) = leading_byte_order_mark_error(source_file) {
68056816
return Some(error);
68066817
}
6807-
if let Some(error) = too_many_nested_parentheses_error(source_file.source_text()) {
6808-
return Some(CompileError::from_source_error(source_file, error));
6809-
}
68106818
if let Some(error) = too_many_nested_interpolated_strings(source_file.source_text()) {
68116819
return Some(CompileError::from_source_error(source_file, error));
68126820
}
@@ -6837,6 +6845,82 @@ fn is_compound_stmt(stmt: &ast::Stmt) -> bool {
68376845
)
68386846
}
68396847

6848+
/// Rejects an AST nested deeper than `limit`.
6849+
///
6850+
/// The parser grows its own stack, so it returns trees deeper than the passes
6851+
/// after it can walk, and each of those recurses without a limit of its own.
6852+
/// The symbol table applies the same limit, but `compile(..., PyCF_ONLY_AST)`
6853+
/// returns before reaching it.
6854+
pub fn too_deeply_nested_error(
6855+
ast: &ast::Mod,
6856+
source_file: &SourceFile,
6857+
limit: usize,
6858+
) -> Result<(), CompileError> {
6859+
use ast::visitor::Visitor;
6860+
6861+
struct DepthChecker {
6862+
depth: usize,
6863+
limit: usize,
6864+
too_deep: Option<ruff_text_size::TextRange>,
6865+
}
6866+
6867+
impl DepthChecker {
6868+
fn descend(&mut self, range: ruff_text_size::TextRange, walk: impl FnOnce(&mut Self)) {
6869+
if self.too_deep.is_some() {
6870+
return;
6871+
}
6872+
if self.depth >= self.limit {
6873+
self.too_deep = Some(range);
6874+
return;
6875+
}
6876+
self.depth += 1;
6877+
walk(self);
6878+
self.depth -= 1;
6879+
}
6880+
}
6881+
6882+
impl<'a> Visitor<'a> for DepthChecker {
6883+
fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
6884+
self.descend(stmt.range(), |checker| {
6885+
ast::visitor::walk_stmt(checker, stmt);
6886+
});
6887+
}
6888+
6889+
fn visit_expr(&mut self, expr: &'a ast::Expr) {
6890+
self.descend(expr.range(), |checker| {
6891+
ast::visitor::walk_expr(checker, expr);
6892+
});
6893+
}
6894+
6895+
fn visit_pattern(&mut self, pattern: &'a ast::Pattern) {
6896+
self.descend(pattern.range(), |checker| {
6897+
ast::visitor::walk_pattern(checker, pattern);
6898+
});
6899+
}
6900+
}
6901+
6902+
let mut checker = DepthChecker {
6903+
depth: 0,
6904+
limit,
6905+
too_deep: None,
6906+
};
6907+
match ast {
6908+
ast::Mod::Module(module) => checker.visit_body(&module.body),
6909+
ast::Mod::Expression(expression) => checker.visit_expr(&expression.body),
6910+
}
6911+
6912+
let Some(range) = checker.too_deep else {
6913+
return Ok(());
6914+
};
6915+
let (location, end_location) = source_locations(source_file, range.start(), range.end());
6916+
Err(CompileError::Codegen(codegen::error::CodegenError {
6917+
location: Some(location),
6918+
end_location: Some(end_location),
6919+
error: codegen::error::CodegenErrorType::RecursionError,
6920+
source_path: source_file.name().to_owned(),
6921+
}))
6922+
}
6923+
68406924
/// Syntax the reference grammar has no rule for, but that this parser accepts.
68416925
///
68426926
/// A bare generator expression is one: `f(x for x in y)` is the `primary
@@ -7192,6 +7276,7 @@ fn _compile_with_syntax_warning_handler<'a>(
71927276
opts.future_features
71937277
.contains(core::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL),
71947278
);
7279+
pre_parse_source_error(&source_file)?;
71957280
let parsed = parser::parse(barry_source.source(), parser_options);
71967281
if let Some(error) = barry_source.diagnostic(parsed.as_ref().err(), &source_file) {
71977282
return Err(error);
@@ -7213,6 +7298,7 @@ fn _compile_with_syntax_warning_handler<'a>(
72137298
return Err(error);
72147299
}
72157300
let ast = parsed.into_syntax();
7301+
too_deeply_nested_error(&ast, &source_file, opts.recursion_limit)?;
72167302
if let Some(error) = unsupported_grammar_error(&ast, &source_file) {
72177303
return Err(error);
72187304
}
@@ -7493,6 +7579,7 @@ pub fn _compile_symtable(
74937579
prepare_barry_as_flufl_source(source_file.source_text(), parser_options.clone(), false);
74947580
let res = match mode {
74957581
Mode::Exec | Mode::Single | Mode::BlockExpr => {
7582+
pre_parse_source_error(&source_file)?;
74967583
let parsed = ruff_python_parser::parse(barry_source.source(), parser_options);
74977584
if let Some(error) = barry_source.diagnostic(parsed.as_ref().err(), &source_file) {
74987585
return Err(error);
@@ -7505,6 +7592,7 @@ pub fn _compile_symtable(
75057592
return Err(error);
75067593
}
75077594
let ast = ast.into_syntax();
7595+
too_deeply_nested_error(&ast, &source_file, CompileOpts::default().recursion_limit)?;
75087596
if let Some(error) = unsupported_grammar_error(&ast, &source_file) {
75097597
return Err(error);
75107598
}
@@ -7519,6 +7607,7 @@ pub fn _compile_symtable(
75197607
symboltable::SymbolTable::scan_program(&ast, source_file.clone())
75207608
}
75217609
Mode::Eval => {
7610+
pre_parse_source_error(&source_file)?;
75227611
let parsed = ruff_python_parser::parse(barry_source.source(), parser_options);
75237612
if let Some(error) = barry_source.diagnostic(parsed.as_ref().err(), &source_file) {
75247613
return Err(error);
@@ -7531,6 +7620,7 @@ pub fn _compile_symtable(
75317620
return Err(error);
75327621
}
75337622
let ast = ast.into_syntax();
7623+
too_deeply_nested_error(&ast, &source_file, CompileOpts::default().recursion_limit)?;
75347624
if let Some(error) = unsupported_grammar_error(&ast, &source_file) {
75357625
return Err(error);
75367626
}

‎crates/vm/src/stdlib/_ast.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1813,6 +1813,7 @@ pub(crate) fn parse(
18131813
options.clone(),
18141814
explicit_future_features.contains(crate::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL),
18151815
);
1816+
rustpython_compiler::pre_parse_source_error(&source_file)?;
18161817
let parsed = parser::parse_unchecked(barry_source.source(), options);
18171818
let type_comment_source =
18181819
type_comments.then(|| TypeCommentSource::new(source, parsed.tokens()));
@@ -1881,6 +1882,11 @@ pub(crate) fn parse(
18811882
return Err(error);
18821883
}
18831884
let mut top = parsed.into_syntax();
1885+
rustpython_compiler::too_deeply_nested_error(
1886+
&top,
1887+
&source_file,
1888+
rustpython_compiler::CompileOpts::default().recursion_limit,
1889+
)?;
18841890
if let Some(error) = rustpython_compiler::unsupported_grammar_error(&top, &source_file) {
18851891
return Err(error);
18861892
}

‎crates/vm/src/vm/compile.rs‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,10 @@ mod escape_warnings {
13811381
filename: &'a str,
13821382
vm: &'a VirtualMachine,
13831383
error: Option<CompileWarningError>,
1384+
/// This pass runs before the compile that rejects an over-nested
1385+
/// tree, so it has to stop itself.
1386+
depth: usize,
1387+
depth_limit: usize,
13841388
}
13851389

13861390
impl<'a> EscapeWarningVisitor<'a> {
@@ -1525,7 +1529,13 @@ mod escape_warnings {
15251529
}
15261530
}
15271531
}
1528-
_ => ast::visitor::walk_expr(self, expr),
1532+
_ => {
1533+
if self.depth < self.depth_limit {
1534+
self.depth += 1;
1535+
ast::visitor::walk_expr(self, expr);
1536+
self.depth -= 1;
1537+
}
1538+
}
15291539
}
15301540
}
15311541
}
@@ -1548,6 +1558,12 @@ mod escape_warnings {
15481558
source: &str,
15491559
filename: &str,
15501560
) -> Result<(), CompileWarningError> {
1561+
// The compile that follows rejects this source; parsing it here
1562+
// would build a tree that exhausts the stack when dropped.
1563+
let source_file = compiler::core::SourceFileBuilder::new(filename, source).finish();
1564+
if compiler::pre_parse_source_error(&source_file).is_err() {
1565+
return Ok(());
1566+
}
15511567
let Ok(parsed) =
15521568
ruff_python_parser::parse(source, ruff_python_parser::Mode::Module.into())
15531569
else {
@@ -1559,6 +1575,8 @@ mod escape_warnings {
15591575
filename,
15601576
vm: self,
15611577
error: None,
1578+
depth: 0,
1579+
depth_limit: compiler::CompileOpts::default().recursion_limit,
15621580
};
15631581
match &ast {
15641582
ast::Mod::Module(module) => {
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import ast
2+
3+
from testutils import assert_raises
4+
5+
# Deeply nested source used to exhaust the native stack, killing the process
6+
# with a signal no `except` here could catch. What is asserted below is mostly
7+
# that this file finishes at all: reaching the end means each case raised a
8+
# Python exception instead of taking the interpreter down.
9+
#
10+
# Two limits keep that from happening, and each has to apply before a tree that
11+
# deep is built. The parser grows its own stack when it runs low on one, and a
12+
# tree it returns costs stack both to walk and to drop, so checking afterwards
13+
# is already too late.
14+
15+
16+
def nested_binop(depth):
17+
return "x" + "+1" * depth
18+
19+
20+
def nested_brackets(depth):
21+
return "[" * depth + "1" + "]" * depth
22+
23+
24+
# Brackets are counted in the source text before it is parsed, the way CPython
25+
# counts them in its tokenizer, so no tree is built for these at all.
26+
assert_raises(SyntaxError, compile, nested_brackets(200000), "<test>", "exec")
27+
assert_raises(SyntaxError, ast.parse, nested_brackets(200000))
28+
assert_raises(SyntaxError, compile, nested_brackets(5000), "<test>", "exec")
29+
assert_raises(SyntaxError, ast.parse, nested_brackets(5000))
30+
31+
# Nesting that reaches the parser is bounded by the compiler's recursion limit,
32+
# applied to the tree it returns. CPython bounds the same walks by how much
33+
# stack is left rather than by a count, so it accepts depths rejected here;
34+
# either outcome is fine, crashing is not.
35+
try:
36+
compile(nested_binop(20000), "<test>", "exec")
37+
except RecursionError:
38+
pass
39+
40+
# `compile(..., PyCF_ONLY_AST)`, which `ast.parse` uses, returns before the
41+
# symbol table runs, so it used to reach the limit of no pass at all.
42+
try:
43+
ast.parse(nested_binop(5000))
44+
except RecursionError:
45+
pass
46+
47+
# Nesting within both limits still compiles and runs.
48+
assert compile(nested_binop(100), "<test>", "exec")
49+
assert compile(nested_brackets(100), "<test>", "exec")
50+
assert ast.parse(nested_binop(100))
51+
assert eval(compile(nested_binop(100), "<test>", "eval"), {"x": 0}) == 100

0 commit comments

Comments
 (0)