Truly independent web browser
LibJS: Fail a regex literal check out of stack at the recursion limit
Shannon Boothd88043f66a65
diff --git a/Libraries/LibJS/Parser/Rust/src/base.rs b/Libraries/LibJS/Parser/Rust/src/base.rsindex 6e27fa1610e..a8bc61c1812 100644--- a/Libraries/LibJS/Parser/Rust/src/base.rs+++ b/Libraries/LibJS/Parser/Rust/src/base.rs@@ -231,8 +231,16 @@ pub(crate) struct FunctionState {}/// How the parser checks a regular expression literal with the regex engine of the runtime that embeds it, so that an-/// invalid one becomes an early error. Gives the message of the error, written into the zone, if it is invalid.-pub type ValidateRegex = for<'z> fn(zone: &'z Zone, pattern: &[u16], flags: &[u16]) -> Result<(), &'z str>;+/// invalid one becomes an early error.+pub type ValidateRegex = for<'z> fn(zone: &'z Zone, pattern: &[u16], flags: &[u16]) -> Result<(), RegexCheckError<'z>>;++/// Why a regular expression literal did not pass [`ValidateRegex`].+pub enum RegexCheckError<'z> {+ /// The literal is invalid, with the message of the error written into the zone.+ Invalid(&'z str),+ /// The stack that is left does not hold the check.+ OutOfStack,+}/// The first syntax error, at a source offset, with its message in the work zone or in the program.pub struct PendingError<'z> {diff --git a/Libraries/LibJS/Parser/Rust/src/lexer.rs b/Libraries/LibJS/Parser/Rust/src/lexer.rsindex c7d79286213..11e41632d19 100644--- a/Libraries/LibJS/Parser/Rust/src/lexer.rs+++ b/Libraries/LibJS/Parser/Rust/src/lexer.rs@@ -9,6 +9,8 @@//! source, and only code that gets compiled reads it again.use super::base::Parser;+use super::base::RECURSION_LIMIT_MESSAGE;+use super::base::RegexCheckError;use super::token::*;use super::unit::*;@@ -916,7 +918,11 @@ impl<'a: 'k, 'k, U: Unit> Parser<'a, 'k, U> {if !self.is_reparsing() {let pattern: &[u16] =zone.alloc_slice_from_iter((start + 1..self.regex_body_end as usize).map(|i| self.at(i) as u16));- if let Err(message) = (self.validate_regex)(zone, pattern, flags) {+ if let Err(error) = (self.validate_regex)(zone, pattern, flags) {+ let message = match error {+ RegexCheckError::Invalid(message) => message,+ RegexCheckError::OutOfStack => RECURSION_LIMIT_MESSAGE,+ };self.fail(start as u32, message);return;}diff --git a/Libraries/LibJS/Rust/src/frontend_host.rs b/Libraries/LibJS/Rust/src/frontend_host.rsindex b1bb4977421..b6f4ef9f332 100644--- a/Libraries/LibJS/Rust/src/frontend_host.rs+++ b/Libraries/LibJS/Rust/src/frontend_host.rs@@ -7,9 +7,11 @@//! The functions the Rust frontend (Libraries/LibJS/Rust) calls on the runtime that embeds it, through host.rs.use libregex_rust::ast::Flags;+use libregex_rust::parser::Error as ParseError;use libregex_rust::regex::Regex;use num_bigint::BigInt;+use crate::host::RegexError;use crate::runtime::big_int_algorithms;use crate::runtime::regexp_object::parse_regex_pattern;use crate::runtime::value::number_to_string;@@ -21,11 +23,11 @@ pub fn number_to_utf16(value: f64) -> Vec<u16> {}/// Compiles a regular expression literal, so that the frontend can report an invalid one as an early error.-pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), String> {+pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), RegexError> {let has_flag = |flag: u8| flags.contains(&u16::from(flag));let parsed_pattern = parse_regex_pattern(pattern, has_flag(b'u'), has_flag(b'v'))- .map_err(|error| format!("RegExp compile error: {}", error.error))?;+ .map_err(|error| RegexError::Invalid(format!("RegExp compile error: {}", error.error)))?;let compile_flags = Flags {global: has_flag(b'g'),@@ -42,8 +44,10 @@ pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), String> {let pattern_characters = char::decode_utf16(parsed_pattern.iter().copied()).map(|character| character.unwrap_or(char::REPLACEMENT_CHARACTER)).collect();- Regex::compile_chars(pattern_characters, compile_flags)- .map_err(|error| format!("RegExp compile error: {error}"))?;+ Regex::compile_chars(pattern_characters, compile_flags).map_err(|error| match error {+ ParseError::TooDeeplyNested => RegexError::OutOfStack,+ error => RegexError::Invalid(format!("RegExp compile error: {error}")),+ })?;Ok(())}diff --git a/Libraries/LibJS/Rust/src/host.rs b/Libraries/LibJS/Rust/src/host.rsindex 87261636884..ca8cb4877b5 100644--- a/Libraries/LibJS/Rust/src/host.rs+++ b/Libraries/LibJS/Rust/src/host.rs@@ -24,9 +24,17 @@ pub fn js_number_to_utf16(value: f64) -> Utf16String {Utf16String::from_utf16(&implementation::number_to_utf16(value))}+/// Why a regex pattern+flags did not pass the check of the host's regex engine.+pub enum RegexError {+ /// The pattern or flags are invalid, with the message of the error.+ Invalid(String),+ /// The stack that is left does not hold the check.+ OutOfStack,+}+/// Check a regex pattern+flags with the host's regex engine, so that an invalid-/// one becomes an early error. Returns the error message if it is invalid.-pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), String> {+/// one becomes an early error.+pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), RegexError> {implementation::validate_regex(pattern, flags)}diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rsindex ee8bdf15675..f0492f74442 100644--- a/Libraries/LibJS/Rust/src/parser/mod.rs+++ b/Libraries/LibJS/Rust/src/parser/mod.rs@@ -32,6 +32,7 @@ use crate::ast::ProgramType;use crate::ast::ScopeTable;use crate::ast::SyntaxTree;use crate::ast::TreeView;+use crate::host::RegexError;use crate::source_text::SourceText;use crate::u32_from_usize;use crate::work_zone::with_work_zone;@@ -40,6 +41,7 @@ use ak::ZoneVec;use base::Mode;use base::OutOfStack;use base::Parser;+use base::RegexCheckError;use base::SOURCE_PADDING;use columns::Ast;use columns::AstColumns;@@ -140,9 +142,12 @@ pub struct ScriptData {}/// Checks a regular expression literal with the regex engine of the runtime, for the parser (see `ValidateRegex`).-fn validate_regex<'z>(zone: &'z Zone, pattern: &[u16], flags: &[u16]) -> Result<(), &'z str> {- crate::host::validate_regex(pattern, flags).map_err(|message| {- core::str::from_utf8(zone.alloc_slice_copy(message.as_bytes())).expect("a copy of a string is one")+fn validate_regex<'z>(zone: &'z Zone, pattern: &[u16], flags: &[u16]) -> Result<(), RegexCheckError<'z>> {+ crate::host::validate_regex(pattern, flags).map_err(|error| match error {+ RegexError::Invalid(message) => RegexCheckError::Invalid(+ core::str::from_utf8(zone.alloc_slice_copy(message.as_bytes())).expect("a copy of a string is one"),+ ),+ RegexError::OutOfStack => RegexCheckError::OutOfStack,})}diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rsindex 18af4db1f46..0fb965f81d0 100644--- a/Libraries/LibJS/Rust/src/test_host.rs+++ b/Libraries/LibJS/Rust/src/test_host.rs@@ -14,7 +14,7 @@ use std::sync::atomic::AtomicU32;use num_bigint::BigInt;-pub fn validate_regex(_pattern: &[u16], _flags: &[u16]) -> Result<(), String> {+pub fn validate_regex(_pattern: &[u16], _flags: &[u16]) -> Result<(), crate::host::RegexError> {Ok(())}diff --git a/Tests/LibJS/Runtime/regexp-literal-reparse-near-stack-limit.js b/Tests/LibJS/Runtime/regexp-literal-reparse-near-stack-limit.jsindex ea5daf5baf9..9339480535d 100644--- a/Tests/LibJS/Runtime/regexp-literal-reparse-near-stack-limit.js+++ b/Tests/LibJS/Runtime/regexp-literal-reparse-near-stack-limit.js@@ -13,21 +13,22 @@ test("regular expression literals reparsed near the call stack size limit", () =});test("regular expression literals at the deepest nesting that the stack allows", () => {- function parses(depth) {- try {- (0, eval)(`(/${"(".repeat(depth)}x${")".repeat(depth)}/)`);- return true;- } catch {- return false;- }- }// The search tries the depth right above the deepest one that parses, which has the least stack to spare.- let low = 1;- let high = 1 << 16;+ // NB: How deep a literal parses depends on the frames above the eval, so each depth is tried only once.+ let low = 0;+ let high = 1 << 20;+ let errorAtHigh;while (low + 1 < high) {const middle = (low + high) >> 1;- if (parses(middle)) low = middle;- else high = middle;+ try {+ (0, eval)(`(/${"(".repeat(middle)}x${")".repeat(middle)}/)`);+ low = middle;+ } catch (error) {+ high = middle;+ errorAtHigh = error;+ }}- expect(parses(low)).toBeTrue();+ expect(low).toBeGreaterThan(0);+ expect(errorAtHigh).toBeInstanceOf(SyntaxError);+ expect(errorAtHigh.message.includes("Maximum parser recursion depth exceeded")).toBeTrue();});