Truly independent web browser
LibRegex: Stop before nested patterns run out of stack
Shannon Boothe91449b99c52
diff --git a/Libraries/LibRegex/Rust/src/compiler.rs b/Libraries/LibRegex/Rust/src/compiler.rsindex 55d2b379ce9..cdd61f35b80 100644--- a/Libraries/LibRegex/Rust/src/compiler.rs+++ b/Libraries/LibRegex/Rust/src/compiler.rs@@ -14,6 +14,8 @@//! - <https://tc39.es/ecma262/#sec-compilepattern>use crate::ast::*;use crate::bytecode::*;+use crate::parser::Error;+use std::cell::Cell;use std::collections::BTreeSet;/// Resolve a Unicode property name/value pair to an ICU enum ID.@@ -31,9 +33,12 @@ pub fn resolve_property(name: &str, value: Option<&str>) -> Option<ResolvedPrope////// Spec entry point: `CompilePattern`./// <https://tc39.es/ecma262/#sec-compilepattern>-pub fn compile(pattern: &Pattern) -> Program {+pub fn compile(pattern: &Pattern) -> Result<Program, Error> {let mut compiler = Compiler::new(pattern);compiler.compile_pattern(pattern);+ if compiler.ran_out_of_stack.get() {+ return Err(Error::TooDeeplyNested);+ }compiler.program.named_groups = pattern.named_groups.iter()@@ -42,7 +47,7 @@ pub fn compile(pattern: &Pattern) -> Program {index: ng.index,}).collect();- compiler.program+ Ok(compiler.program)}const fn char_range(start: u32, end: u32) -> CharRange {@@ -125,9 +130,19 @@ struct Compiler {next_internal_reg: u32,/// True when compiling a lookbehind body (terms are reversed).backward: bool,+ /// Set when a pass stopped short of a nested group or class because the stack ran low, which fails the compile.+ ran_out_of_stack: Cell<bool>,}impl Compiler {+ /// Whether a pass has to stop short of recursing into a nested group or class, which fails the compile.+ fn is_out_of_stack(&self) -> bool {+ if crate::stack::is_exhausted() {+ self.ran_out_of_stack.set(true);+ }+ self.ran_out_of_stack.get()+ }+/// The code point ranges of a builtin class inside a character class of a pattern without the u and v flags, if/// the class can match it as plain ranges.///@@ -175,6 +190,7 @@ impl Compiler {effective_dot_all: pattern.flags.dot_all,next_internal_reg: register_count,backward: false,+ ran_out_of_stack: Cell::new(false),}}@@ -292,6 +308,9 @@ impl Compiler {}fn class_set_expression_lengths(&self, expr: &ClassSetExpression) -> BTreeSet<usize> {+ if self.is_out_of_stack() {+ return BTreeSet::new();+ }match expr {ClassSetExpression::Union(operands) => operands.iter().fold(BTreeSet::new(), |mut lengths, operand| {lengths.extend(self.class_set_operand_lengths(operand));@@ -418,29 +437,32 @@ impl Compiler {}/// Collect all capture group indices inside an atom (recursively).- fn collect_captures(atom: &Atom, out: &mut Vec<u32>) {+ fn collect_captures(&self, atom: &Atom, out: &mut Vec<u32>) {match atom {Atom::Group(g) => {out.push(g.index);- Self::collect_captures_in_disjunction(&g.body, out);+ self.collect_captures_in_disjunction(&g.body, out);}Atom::NonCapturingGroup(g) => {- Self::collect_captures_in_disjunction(&g.body, out);+ self.collect_captures_in_disjunction(&g.body, out);}Atom::ModifierGroup(mg) => {- Self::collect_captures_in_disjunction(&mg.body, out);+ self.collect_captures_in_disjunction(&mg.body, out);}Atom::Lookaround(la) => {- Self::collect_captures_in_disjunction(&la.body, out);+ self.collect_captures_in_disjunction(&la.body, out);}_ => {}}}- fn collect_captures_in_disjunction(disj: &Disjunction, out: &mut Vec<u32>) {+ fn collect_captures_in_disjunction(&self, disj: &Disjunction, out: &mut Vec<u32>) {+ if self.is_out_of_stack() {+ return;+ }for alt in &disj.alternatives {for term in &alt.terms {- Self::collect_captures(&term.atom, out);+ self.collect_captures(&term.atom, out);}}}@@ -450,7 +472,7 @@ impl Compiler {/// undefined at the start of each quantifier iteration./// <https://tc39.es/ecma262/#sec-runtime-semantics-repeatmatcher-abstract-operation>fn emit_clear_captures(&mut self, atom: &Atom) {- for idx in Self::capture_registers(atom) {+ for idx in self.capture_registers(atom) {self.emit(Instruction::ClearRegister(idx));}}@@ -458,12 +480,12 @@ impl Compiler {/// Collect all capture register indices (start and end) for captures inside an atom./// Returns empty for intrinsically zero-width atoms (lookarounds, assertions)/// since their captures should NOT be cleared on zero-width ProgressCheck.- fn capture_registers(atom: &Atom) -> Vec<u32> {+ fn capture_registers(&self, atom: &Atom) -> Vec<u32> {if matches!(atom, Atom::Lookaround(_) | Atom::Assertion(_)) {return Vec::new();}let mut captures = Vec::new();- Self::collect_captures(atom, &mut captures);+ self.collect_captures(atom, &mut captures);let mut regs = Vec::new();for idx in captures {regs.push(idx * 2);@@ -473,6 +495,9 @@ impl Compiler {}fn disjunction_can_be_zero_width(&self, disjunction: &Disjunction) -> bool {+ if self.is_out_of_stack() {+ return true;+ }disjunction.alternatives.iter()@@ -519,6 +544,9 @@ impl Compiler {/// Lower `Disjunction` to a chain of split/jump choice points./// <https://tc39.es/ecma262/#sec-compilesubpattern>fn compile_disjunction(&mut self, disj: &Disjunction) {+ if self.is_out_of_stack() {+ return;+ }if let Some(term) = self.try_merge_optional_alternatives(disj) {self.compile_term(&term);return;@@ -676,7 +704,7 @@ impl Compiler {if let Some(reg) = progress_reg {self.emit(Instruction::ProgressCheck {reg,- clear_captures: Self::capture_registers(atom),+ clear_captures: self.capture_registers(atom),});}self.emit(Instruction::RepeatCheck {@@ -730,7 +758,7 @@ impl Compiler {if let Some(reg) = progress_reg {self.emit(Instruction::ProgressCheck {reg,- clear_captures: Self::capture_registers(atom),+ clear_captures: self.capture_registers(atom),});}let after = self.current_offset();@@ -752,7 +780,7 @@ impl Compiler {if let Some(reg) = progress_reg {self.emit(Instruction::ProgressCheck {reg,- clear_captures: Self::capture_registers(atom),+ clear_captures: self.capture_registers(atom),});}let after = self.current_offset();@@ -786,7 +814,7 @@ impl Compiler {if can_be_zero_width {self.emit(Instruction::ProgressCheck {reg: progress_reg,- clear_captures: Self::capture_registers(atom),+ clear_captures: self.capture_registers(atom),});}self.emit(Instruction::Jump(loop_start));@@ -808,7 +836,7 @@ impl Compiler {if can_be_zero_width {self.emit(Instruction::ProgressCheck {reg: progress_reg,- clear_captures: Self::capture_registers(atom),+ clear_captures: self.capture_registers(atom),});}self.emit(Instruction::Jump(loop_start));@@ -1126,6 +1154,9 @@ impl Compiler {/// a `LazyLoop`/`GreedyLoop`. Returns `None` for operands that require multi-character/// matching (string literals) or set operations that can't be represented as a simple test.fn try_simple_match_for_operand(operand: &ClassSetOperand) -> Option<SimpleMatch> {+ if crate::stack::is_exhausted() {+ return None;+ }match operand {ClassSetOperand::Char(c) => Some(SimpleMatch::Char(*c)),ClassSetOperand::Range(lo, hi) => Some(SimpleMatch::CharClass {@@ -1332,6 +1363,9 @@ impl Compiler {}fn try_extract_union_ranges(expr: &ClassSetExpression) -> Option<Vec<CharRange>> {+ if crate::stack::is_exhausted() {+ return None;+ }let ClassSetExpression::Union(operands) = expr else {return None;};@@ -1447,6 +1481,9 @@ impl Compiler {}fn compile_class_set_expression_at_length(&mut self, expr: &ClassSetExpression, length: usize) {+ if self.is_out_of_stack() {+ return;+ }match expr {ClassSetExpression::Union(operands) => {let filtered: Vec<&ClassSetOperand> = operandsdiff --git a/Libraries/LibRegex/Rust/src/lib.rs b/Libraries/LibRegex/Rust/src/lib.rsindex ea44fd199d3..2721a61de10 100644--- a/Libraries/LibRegex/Rust/src/lib.rs+++ b/Libraries/LibRegex/Rust/src/lib.rs@@ -19,4 +19,5 @@ pub mod compiler;pub mod ffi;pub mod parser;pub mod regex;+mod stack;pub mod vm;diff --git a/Libraries/LibRegex/Rust/src/parser.rs b/Libraries/LibRegex/Rust/src/parser.rsindex 7d05193aad8..ccfbefdd7fe 100644--- a/Libraries/LibRegex/Rust/src/parser.rs+++ b/Libraries/LibRegex/Rust/src/parser.rs@@ -69,6 +69,7 @@ pub enum Error {QuantifierWithoutAtom,NothingToRepeat,NumberOverflow,+ TooDeeplyNested,}impl std::fmt::Display for Error {@@ -100,6 +101,7 @@ impl std::fmt::Display for Error {Self::QuantifierWithoutAtom => write!(f, "quantifier without atom"),Self::NothingToRepeat => write!(f, "nothing to repeat"),Self::NumberOverflow => write!(f, "number overflow"),+ Self::TooDeeplyNested => write!(f, "pattern is nested too deeply"),}}}@@ -215,6 +217,9 @@ impl Parser {/// been collected./// <https://tc39.es/ecma262/#sec-patterns-static-semantics-early-errors>fn validate_backrefs(disj: &Disjunction, group_names: &std::collections::HashSet<&str>) -> Result<(), Error> {+ if crate::stack::is_exhausted() {+ return Err(Error::TooDeeplyNested);+ }for alt in &disj.alternatives {for term in &alt.terms {match &term.atom {@@ -286,6 +291,9 @@ impl Parser {/// Parse `Disjunction`./// <https://tc39.es/ecma262/#sec-patterns>fn parse_disjunction(&mut self) -> Result<Disjunction, Error> {+ if crate::stack::is_exhausted() {+ return Err(Error::TooDeeplyNested);+ }let inherited = self.alternative_name_stack.last().cloned().unwrap_or_default();self.alternative_name_stack.push(inherited.clone());let mut alternatives = vec![self.parse_alternative()?];@@ -1174,6 +1182,9 @@ impl Parser {/// Parse `CharacterClass`./// <https://tc39.es/ecma262/#sec-compilecharacterclass>fn parse_character_class(&mut self) -> Result<CharacterClass, Error> {+ if crate::stack::is_exhausted() {+ return Err(Error::TooDeeplyNested);+ }self.expect('[')?;let negated = self.eat('^');@@ -1189,7 +1200,7 @@ impl Parser {self.parse_class_set_expression()?};self.in_negated_class = saved_negated;- if negated && Self::class_set_expression_may_contain_strings(&expr) {+ if negated && Self::class_set_expression_may_contain_strings(&expr)? {return Err(Error::InvalidCharacterClass);}self.expect(']')?;@@ -1468,27 +1479,43 @@ impl Parser {/// - Intersection: may contain strings if ALL operands may contain strings/// (i.e., no operand is "purely characters")/// - Subtraction: may contain strings if the leftmost operand may contain strings- fn class_set_expression_may_contain_strings(expr: &ClassSetExpression) -> bool {+ fn class_set_expression_may_contain_strings(expr: &ClassSetExpression) -> Result<bool, Error> {+ if crate::stack::is_exhausted() {+ return Err(Error::TooDeeplyNested);+ }match expr {- ClassSetExpression::Union(operands) => operands.iter().any(Self::class_set_operand_may_contain_strings),+ ClassSetExpression::Union(operands) => {+ for operand in operands {+ if Self::class_set_operand_may_contain_strings(operand)? {+ return Ok(true);+ }+ }+ Ok(false)+ }ClassSetExpression::Intersection(operands) => {- operands.iter().all(Self::class_set_operand_may_contain_strings)+ for operand in operands {+ if !Self::class_set_operand_may_contain_strings(operand)? {+ return Ok(false);+ }+ }+ Ok(true)}- ClassSetExpression::Subtraction(operands) => operands- .first()- .is_some_and(Self::class_set_operand_may_contain_strings),+ ClassSetExpression::Subtraction(operands) => match operands.first() {+ Some(operand) => Self::class_set_operand_may_contain_strings(operand),+ None => Ok(false),+ },}}- fn class_set_operand_may_contain_strings(operand: &ClassSetOperand) -> bool {- match operand {+ fn class_set_operand_may_contain_strings(operand: &ClassSetOperand) -> Result<bool, Error> {+ Ok(match operand {ClassSetOperand::NestedClass(class) => {if class.negated {- return false;+ return Ok(false);}match &class.body {CharacterClassBody::Ranges(_) => false,- CharacterClassBody::UnicodeSet(expr) => Self::class_set_expression_may_contain_strings(expr),+ CharacterClassBody::UnicodeSet(expr) => Self::class_set_expression_may_contain_strings(expr)?,}}ClassSetOperand::UnicodeProperty(property) => {@@ -1496,7 +1523,7 @@ impl Parser {}ClassSetOperand::StringLiteral(chars) => chars.len() != 1,ClassSetOperand::Char(_) | ClassSetOperand::Range(_, _) | ClassSetOperand::BuiltinClass(_) => false,- }+ })}/// Parse one `/v` `ClassSetOperand`.diff --git a/Libraries/LibRegex/Rust/src/regex.rs b/Libraries/LibRegex/Rust/src/regex.rsindex 586d5c3b7a8..9e6383fcc49 100644--- a/Libraries/LibRegex/Rust/src/regex.rs+++ b/Libraries/LibRegex/Rust/src/regex.rs@@ -52,7 +52,7 @@ impl Regex {}fn compile_parsed(parsed: Pattern, flags: Flags) -> Result<Self, parser::Error> {- let mut program = compiler::compile(&parsed);+ let mut program = compiler::compile(&parsed)?;Self::resolve_properties(&mut program);let required_literal_hint = extract_required_literal_hint(&parsed, flags);let hints = vm::analyze_pattern(&program, required_literal_hint);@@ -670,6 +670,12 @@ fn extract_required_literal_hint(pattern: &Pattern, flags: Flags) -> Option<vm::}fn analyze_required_literal_disjunction(disjunction: &Disjunction, flags: Flags) -> RequiredLiteralAnalysis {+ if crate::stack::is_exhausted() {+ return RequiredLiteralAnalysis {+ exact_literal: None,+ guaranteed_runs: Vec::new(),+ };+ }let mut analyses = disjunction.alternatives.iter()diff --git a/Libraries/LibRegex/Rust/src/stack.rs b/Libraries/LibRegex/Rust/src/stack.rsnew file mode 100644index 00000000000..2d82ab877c7--- /dev/null+++ b/Libraries/LibRegex/Rust/src/stack.rs@@ -0,0 +1,20 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A pattern can nest groups and classes deeper than the native stack holds, so each pass that recurses into them+//! checks this first.++/// The stack left below the limit for what a pass does between two checks.+const HEADROOM: usize = 64 * 1024;++/// Whether recursing into one more nested group or class could run this thread out of stack.+pub(crate) fn is_exhausted() -> bool {+ let Some(lowest_address) = ak::stack::lowest_address_of_this_thread() else {+ return false;+ };+ let marker = 0u8;+ (&raw const marker as usize) < lowest_address.saturating_add(HEADROOM)+}diff --git a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.jsindex 4c78ccec838..443cfb5608d 100644--- a/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js+++ b/Tests/LibJS/Runtime/builtins/RegExp/RegExp.js@@ -961,3 +961,42 @@ test("string properties allowed as set operation operands in negated /v mode claRegExp("[^\\p{Emoji_Keycap_Sequence}]", "v");}).toThrowWithMessage(SyntaxError, "RegExp compile error: invalid Unicode property 'Emoji_Keycap_Sequence'");});++test("deeply nested patterns throw instead of overflowing the stack", () => {+ const message = "RegExp compile error: pattern is nested too deeply";+ expect(() => {+ RegExp("(".repeat(100_000) + ")".repeat(100_000));+ }).toThrowWithMessage(SyntaxError, message);+ expect(() => {+ RegExp("(?:".repeat(100_000) + ")".repeat(100_000));+ }).toThrowWithMessage(SyntaxError, message);+ expect(() => {+ RegExp("[".repeat(100_000) + "]".repeat(100_000), "v");+ }).toThrowWithMessage(SyntaxError, message);+});++test("the most deeply nested pattern that compiles also runs", () => {+ // Each pass over a pattern recurses into its nested groups and classes, so each must stop before the stack does.+ for (const [pattern, flags] of [+ [depth => "(".repeat(depth) + "a" + ")".repeat(depth), ""],+ [depth => "(?<=".repeat(depth) + "a" + ")".repeat(depth), ""],+ [depth => "(?:" + "(".repeat(depth) + "a|" + ")".repeat(depth) + ")*", ""],+ [depth => "[".repeat(depth) + "a" + "]".repeat(depth), "v"],+ [depth => "[^".repeat(depth) + "a" + "]".repeat(depth), "v"],+ ]) {+ let deepest;+ let low = 1;+ let high = 100_000;+ while (low + 1 < high) {+ const middle = Math.floor((low + high) / 2);+ try {+ deepest = RegExp(pattern(middle), flags);+ low = middle;+ } catch (error) {+ expect(error.message).toBe("RegExp compile error: pattern is nested too deeply");+ high = middle;+ }+ }+ expect(() => deepest.exec("a")).not.toThrow();+ }+});