diff --git a/rust/README.md b/rust/README.md index 181bf8a4..e9ead4f9 100644 --- a/rust/README.md +++ b/rust/README.md @@ -176,6 +176,14 @@ Known differences: needn't watch the run from outside. Under `ThreadCpu` a stretch's CPU time is measured from when it has run a sixteenth of the slice, so it may run up to that much past it. On wasm32 the clocks are `performance.now()` and `Date.now()` (`web-time`), and `ThreadCpu` counts wall-clock time. +- **Compiling:** the parser recurses once a level of syntax and has no guard of its own, so a program is parsed on a + thread with the stack its nesting needs, by a bound read from its bytes (`nesting.rs`). A program bounded past + `MAX_COMPILE_LEVELS` (65,536; the bound takes each token of the longest item at each depth for a level, so it is + far above the 2,000 levels the compiler takes) is refused before it is parsed: what a hostile source costs to + refuse doesn't grow with its depth. A regular expression literal has its flags and its syntax checked, in time by + its length, and is compiled where the program evaluates it, within that run's limits: a compile takes time by what + a pattern holds, and nothing limits a program's compile. So a literal that is valid syntax and that the regex + compiler refuses (more than 65,535 loops) throws its `SyntaxError` when it is evaluated. - Layout: `crates/psychoscript` (compiler on `oxc_parser`, VM, standard library, host functions, snapshots, and `thread_clock`: a thread's CPU time, read on it or from another thread, for hosts too), `crates/psychoscript-gpu` (GPU canvases: a program's WebGPU batches checked and replayed on a host's `wgpu` device, its `README.md`), diff --git a/rust/crates/psychoscript/src/builtins/regexp.rs b/rust/crates/psychoscript/src/builtins/regexp.rs index c9845c2e..8d1c3c3a 100644 --- a/rust/crates/psychoscript/src/builtins/regexp.rs +++ b/rust/crates/psychoscript/src/builtins/regexp.rs @@ -349,9 +349,11 @@ pub fn new_regexp(vm: &mut Vm, pattern: &str, flags: &str) -> Res { } } -/// Checks a regular expression literal at compile time. +/// Checks a regular expression literal at compile time: its flags and its syntax, which take time by its length. +/// It is not compiled: that takes time by what a pattern holds (0.7 s for 240 KB of `[\S\W]` under `iv`), and a +/// program compiles outside any run, with no limit to end it. The program compiles it where it evaluates it. pub fn validate_literal(pattern: &str, flags: &str) -> Result<(), String> { - match compile(pattern, flags) { + match literal_syntax(pattern, flags) { Ok(_) => Ok(()), Err(CompileError::Flags) => Err(format!("Invalid regular expression flags '{flags}'")), Err(CompileError::Pattern(reason)) => Err(format!( @@ -360,6 +362,23 @@ pub fn validate_literal(pattern: &str, flags: &str) -> Result<(), String> { } } +/// The first error in a literal's flags or in its syntax. +fn literal_syntax(pattern: &str, flags: &str) -> Result<(), CompileError> { + // The flags are checked by a compile of nothing. + compile("", flags)?; + let mode = if flags.contains('v') { + Mode::UnicodeSets + } else if flags.contains('u') { + Mode::Unicode + } else { + Mode::Legacy + }; + match regexp_syntax::check(&crate::strings::units_of(pattern), mode, &EngineUnicode) { + Some(code) => Err(CompileError::Pattern(code.message().into())), + None => Ok(()), + } +} + pub fn as_regexp(vm: &Vm, v: &Value) -> Option { match v { Value::Obj(id) if matches!(vm.heap[*id as usize].kind, Kind::RegExp(_)) => Some(*id), diff --git a/rust/crates/psychoscript/src/builtins/regexp_syntax.rs b/rust/crates/psychoscript/src/builtins/regexp_syntax.rs index 51aa985f..4ea6b24b 100644 --- a/rust/crates/psychoscript/src/builtins/regexp_syntax.rs +++ b/rust/crates/psychoscript/src/builtins/regexp_syntax.rs @@ -3,7 +3,7 @@ //! it. `regress` compiles the pattern afterwards; it accepts a few patterns JavaScriptCore rejects (such as `\b*`) //! and words its errors differently, so the reference's error and wording come from here. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Mode { @@ -116,6 +116,7 @@ pub fn check(pattern: &[u16], mode: Mode, unicode: &dyn Unicode) -> Option parens: Vec::new(), names: Names::new(), forward_names: HashSet::new(), + properties: HashMap::new(), }; p.tokens(); if p.error.is_none() { @@ -154,51 +155,92 @@ enum Paren { } /// Named groups seen so far: a name may repeat only in another alternative. +/// +/// Each alternative, of the pattern and of each group, is a set of the names used in it, and a group that closes +/// joins its sets to the one it is in. A name can't be used while the set of its last use is the one the pattern or +/// a group still open is at; when the last use allows another, so does every earlier one. So a use is one lookup and +/// nothing is copied, where each group and each `|` copied the names so far: 8 s for 15,000 groups after 3,000 +/// names. struct Names { - all: HashSet>, - nested: Vec>>, - active: Vec>>, + /// Each name, with the set its last use is in. + all: HashMap, usize>, + /// What each set was joined to: itself until then. + joined: Vec, + /// For a set not joined to another: whether the pattern or a group still open is at it. + current: Vec, + /// The pattern, then each group still open: the set it is at, and the sets of its earlier alternatives. + open: Vec<(usize, Vec)>, } impl Names { fn new() -> Names { Names { - all: HashSet::new(), - nested: vec![HashSet::new()], - active: vec![HashSet::new()], + all: HashMap::new(), + joined: vec![0], + current: vec![true], + open: vec![(0, Vec::new())], } } - fn next_alternative(&mut self) { - let done = std::mem::take(self.active.last_mut().expect("a scope")); - self.nested.last_mut().expect("a scope").extend(done); - let n = self.active.len(); - if n > 1 { - let outer = self.active[n - 2].clone(); - self.active[n - 1].extend(outer); + /// A new set, for an alternative that starts. + fn set(&mut self) -> usize { + self.joined.push(self.joined.len()); + self.current.push(true); + self.joined.len() - 1 + } + + /// The set that `set` is part of by now. + fn whole(&mut self, mut set: usize) -> usize { + while self.joined[set] != set { + self.joined[set] = self.joined[self.joined[set]]; + set = self.joined[set]; } + set + } + + fn next_alternative(&mut self) { + let next = self.set(); + let Some((at, earlier)) = self.open.last_mut() else { + return; + }; + let done = std::mem::replace(at, next); + earlier.push(done); + let done = self.whole(done); + self.current[done] = false; } fn push(&mut self) { - let top = self.active.last().cloned().unwrap_or_default(); - self.nested.push(HashSet::new()); - self.active.push(top); + let at = self.set(); + self.open.push((at, Vec::new())); } fn pop(&mut self) { - let (Some(mut nested), Some(active)) = (self.nested.pop(), self.active.pop()) else { + if self.open.len() < 2 { + return; + } + let Some((at, mut sets)) = self.open.pop() else { return; }; - nested.extend(active); - if let Some(outer) = self.active.last_mut() { - outer.extend(nested); + sets.push(at); + let outer = self.open.last().map_or(0, |o| o.0); + let outer = self.whole(outer); + for set in sets { + let set = self.whole(set); + self.joined[set] = outer; } } /// Adds a name; false when it is already active in this alternative. fn add(&mut self, name: Vec) -> bool { - self.all.insert(name.clone()); - self.active.last_mut().is_some_and(|a| a.insert(name)) + if let Some(&last) = self.all.get(&name) { + let last = self.whole(last); + if self.current[last] { + return false; + } + } + let at = self.open.last().map_or(0, |o| o.0); + self.all.insert(name, at); + true } } @@ -217,6 +259,9 @@ struct Parser<'a> { parens: Vec, names: Names, forward_names: HashSet>, + /// What `unicode` said of each property expression the pattern has, asked once: the answer can be a compile of + /// the property (0.8 ms for `RGI_Emoji`), and a pattern can name one at every thirteenth unit. + properties: HashMap>, } /// What an escape adds to the construct it is in. @@ -564,7 +609,7 @@ impl Parser<'_> { || self .forward_names .iter() - .any(|n| !self.names.all.contains(n))); + .any(|n| !self.names.all.contains_key(n))); if illegal_forward { if self.unicode_mode() || !self.names.all.is_empty() { self.set(Code::InvalidNamedBackReference); @@ -720,7 +765,7 @@ impl Parser<'_> { return (Token::Atom, Item::Other); } if let Some(name) = name { - if self.names.all.contains(&name) { + if self.names.all.contains_key(&name) { return (Token::Atom, Item::Other); } if self.named_forward_allowed { @@ -928,7 +973,14 @@ impl Parser<'_> { if errors { break; } - let found = self.unicode.property(&text, self.mode); + let found = match self.properties.get(&text) { + Some(found) => *found, + None => { + let found = self.unicode.property(&text, self.mode); + self.properties.insert(text, found); + found + } + }; if found.is_none() { self.set(Code::InvalidUnicodePropertyExpression); } diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index b05e46a0..900f641e 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -29,6 +29,12 @@ pub const COMPILE_STACK_PER_LEVEL: usize = if cfg!(debug_assertions) { pub const RUN_STACK_BUDGET: usize = 512 << 10; /// Room on a thread beyond what its work is measured to need. pub(crate) const THREAD_STACK_BASE: usize = 256 << 10; +/// The most levels, by [`nesting::bound`], a program is parsed with: a deeper one is refused unparsed. The parser +/// has no guard of its own and recurses once a level, so it takes stack, memory and time by a program's depth (1 MiB +/// of `{` took 961 MiB and 0.6 s in a release build), for a program the compiler then refuses past 2,000 levels. +/// The bound counts a level for each token of the longest item at each depth, so this is far above what a program +/// that compiles needs: of 35 minified bundles, up to 1.1 MB, the deepest was bounded at 591. +pub const MAX_COMPILE_LEVELS: usize = 1 << 16; /// A program compiled once to run many times: its bytecode and the strings it interned, which every run starts from /// a copy of, so a run of it is the same as a run of its source. Cheap to clone, and shared across threads. @@ -123,6 +129,13 @@ pub fn compile(code: &str, atoms: &mut Strings) -> Result if need <= RUN_STACK_BUDGET { return compiler::compile(code, atoms); } + if need > MAX_COMPILE_LEVELS.saturating_mul(COMPILE_STACK_PER_LEVEL) { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: "SyntaxError: Program is nested too deeply to compile.".into(), + offset: None, + }); + } #[cfg(target_arch = "wasm32")] { Err(CompileError { diff --git a/rust/crates/psychoscript/tests/compile_bound.rs b/rust/crates/psychoscript/tests/compile_bound.rs new file mode 100644 index 00000000..41202333 --- /dev/null +++ b/rust/crates/psychoscript/tests/compile_bound.rs @@ -0,0 +1,34 @@ +//! A program nested past what the parser is given stack for (`MAX_COMPILE_LEVELS`) is refused before it is parsed, +//! and a regular expression literal is checked when its program compiles, not compiled. + +use psychoscript::{DiagnosticKind, Runtime}; + +/// The parser recurses once a level and has no guard, so each of these took stack and time by its depth to parse +/// (one of them compiled, the others were refused once parsed). Wide is not deep: as many tokens side by side +/// compile as before, and so does a regular expression literal, in time by its length. +#[test] +fn a_program_nested_past_the_bound_is_refused_unparsed() { + let n = 80_000; + for (name, code) in [ + ("brackets left open", "[".repeat(n)), + ("parentheses", "(".repeat(n) + "1" + &")".repeat(n)), + ("prefix operators", "!".repeat(n) + "1"), + ("blocks", "{".repeat(n) + &"}".repeat(n)), + ("template substitutions", "`${".repeat(n)), + ] { + let err = Runtime::make().compile(&code).unwrap_err(); + assert_eq!(err.kind, DiagnosticKind::ParseError, "{name}"); + assert!( + err.message_lossy().contains("nested too deeply"), + "{name}: {}", + err.message_lossy() + ); + } + // The literal has names, which each group after them copied (minutes for these), and more loops than the regex + // compiler takes: its program compiles all the same, since no run has yet set a limit to what a compile costs. + let names: String = (0..3_000).map(|i| format!("(?.)")).collect(); + let literal = format!("/{names}{}{}/", "()".repeat(15_000), "a*".repeat(n)); + for code in [format!("[{}]", "1,".repeat(n)), "x;".repeat(n), literal] { + assert!(Runtime::make().compile(&code).is_ok()); + } +}