Skip to content

Truly independent web browser

LibRegex+LibJS: Give up on matches once the VM is interrupted

Andreas Kling6d1dcab8ae1c
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 94cf4f075df..39a3ff8b79f 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -780,6 +780,9 @@ impl Vm {
.keyed_property_lookup_cache_entries
.set(vm.keyed_property_lookup_cache.entries_for_interpreter());
vm.update_dispatch_tables();
+ if options.become_thread_default_heap {
+ libregex_rust::vm::set_interrupt_flag_of_this_thread(&raw const vm.interrupt_requested);
+ }
let context = storage.cast();
// SAFETY: The VM stays at this address until it is dropped, and it destroys the heap before anything else.
let heap = unsafe { Heap::new(gather_roots, context, options.become_thread_default_heap) };
@@ -2148,6 +2151,9 @@ impl Vm {
impl Drop for Vm {
fn drop(&mut self) {
+ if self.options.become_thread_default_heap {
+ libregex_rust::vm::set_interrupt_flag_of_this_thread(core::ptr::null());
+ }
// The debugger holds weak references to executables, which go away with the heap.
drop(self.debugger.take());
// So do these caches of shapes. A weak reference that outlives the heap also keeps its weak block allocated.
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
index b95d14ba460..4f5374500fc 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_regex.rs
@@ -28,7 +28,7 @@ impl MatchResult {
match result {
VmResult::Match => Self::Match,
VmResult::NoMatch => Self::NoMatch,
- VmResult::LimitExceeded => Self::LimitExceeded,
+ VmResult::LimitExceeded | VmResult::Interrupted => Self::LimitExceeded,
}
}
}
diff --git a/Libraries/LibRegex/Rust/src/ffi.rs b/Libraries/LibRegex/Rust/src/ffi.rs
index b301d333499..566f9646cd7 100644
--- a/Libraries/LibRegex/Rust/src/ffi.rs
+++ b/Libraries/LibRegex/Rust/src/ffi.rs
@@ -147,7 +147,7 @@ fn exec_into_internal<I: crate::vm::Input>(
match regex.0.exec_into_input(input, start_pos, out) {
VmResult::Match => 1,
VmResult::NoMatch => 0,
- VmResult::LimitExceeded => -1,
+ VmResult::LimitExceeded | VmResult::Interrupted => -1,
}
}
@@ -157,7 +157,7 @@ fn test_internal<I: crate::vm::Input>(regex: &RustRegex, input: I, start_pos: us
match regex.0.test_input(input, start_pos) {
VmResult::Match => 1,
VmResult::NoMatch => 0,
- VmResult::LimitExceeded => -1,
+ VmResult::LimitExceeded | VmResult::Interrupted => -1,
}
}
diff --git a/Libraries/LibRegex/Rust/src/vm.rs b/Libraries/LibRegex/Rust/src/vm.rs
index 121807a91f7..78d472dadb0 100644
--- a/Libraries/LibRegex/Rust/src/vm.rs
+++ b/Libraries/LibRegex/Rust/src/vm.rs
@@ -12,17 +12,42 @@
//! Spec:
//! - <https://tc39.es/ecma262/#sec-pattern-semantics>
//! - <https://tc39.es/ecma262/#sec-regexpbuiltinexec>
+use core::cell::Cell;
+use core::sync::atomic::{AtomicBool, Ordering};
+
use crate::bytecode::*;
/// Maximum number of steps before aborting (prevents ReDoS).
const MATCH_LIMIT: u64 = 10_000_000;
+/// How many steps a match runs between looks at the interrupt flag of its thread.
+const INTERRUPT_POLL_INTERVAL: u64 = 1 << 20;
+
+thread_local! {
+ static INTERRUPT_FLAG: Cell<*const AtomicBool> = const { Cell::new(core::ptr::null()) };
+}
+
+/// Makes matches on this thread give up as if they reached their limit once `flag` is set. MATCH_LIMIT only limits one
+/// start position, so without this a catastrophic pattern can keep going for as long as its input is long. `flag` may be
+/// null, and otherwise must stay valid until it is replaced.
+pub fn set_interrupt_flag_of_this_thread(flag: *const AtomicBool) {
+ INTERRUPT_FLAG.set(flag);
+}
+
+fn is_interrupted() -> bool {
+ let flag = INTERRUPT_FLAG.get();
+ // SAFETY: The flag stays valid until it is replaced.
+ !flag.is_null() && unsafe { &*flag }.load(Ordering::Relaxed)
+}
+
/// Tri-state result from a single VM execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VmResult {
Match,
NoMatch,
LimitExceeded,
+ /// Like LimitExceeded, but the search ends here instead of going on at the next start position.
+ Interrupted,
}
pub trait Input: Copy {
@@ -566,7 +591,7 @@ pub fn find_all_with_scratch<I: Input>(
count += 1;
pos = next_search_position(match_start, match_end);
}
- VmResult::LimitExceeded => return -2,
+ VmResult::LimitExceeded | VmResult::Interrupted => return -2,
VmResult::NoMatch => {
pos = candidate_pos + 1;
}
@@ -587,7 +612,7 @@ pub fn find_all_with_scratch<I: Input>(
}
return -1;
}
- VmResult::LimitExceeded => return -2,
+ VmResult::LimitExceeded | VmResult::Interrupted => return -2,
VmResult::NoMatch => return 0,
}
}
@@ -613,7 +638,7 @@ pub fn find_all_with_scratch<I: Input>(
count += 1;
pos = next_search_position(match_start, match_end);
}
- VmResult::LimitExceeded => return -2,
+ VmResult::LimitExceeded | VmResult::Interrupted => return -2,
VmResult::NoMatch => {
pos = candidate_pos + 1;
}
@@ -638,7 +663,7 @@ pub fn find_all_with_scratch<I: Input>(
count += 1;
pos = next_search_position(match_start, match_end);
}
- VmResult::LimitExceeded => return -2,
+ VmResult::LimitExceeded | VmResult::Interrupted => return -2,
VmResult::NoMatch => {
pos = candidate_pos + 1;
}
@@ -735,6 +760,7 @@ fn execute_into_impl<I: Input>(
return VmResult::Match;
}
VmResult::LimitExceeded => hit_limit = true,
+ VmResult::Interrupted => return VmResult::Interrupted,
VmResult::NoMatch => {}
}
pos = candidate_pos + 1;
@@ -762,6 +788,7 @@ fn execute_into_impl<I: Input>(
return VmResult::Match;
}
VmResult::LimitExceeded => hit_limit = true,
+ VmResult::Interrupted => return VmResult::Interrupted,
VmResult::NoMatch => {}
}
pos = candidate_pos + 1;
@@ -784,6 +811,7 @@ fn execute_into_impl<I: Input>(
return VmResult::Match;
}
VmResult::LimitExceeded => hit_limit = true,
+ VmResult::Interrupted => return VmResult::Interrupted,
VmResult::NoMatch => {}
}
pos = candidate_pos + 1;
@@ -1400,7 +1428,14 @@ struct Vm<'a, I: Input> {
/// The old values of the registers written so far, most recent last. A saved state records the length of this
/// trail, and backtracking to it undoes the writes after that point, so saving a state costs nothing per register.
register_trail: &'a mut Vec<RegisterUndo>,
+ /// The steps so far, across all start positions.
steps: u64,
+ /// Where the steps reach MATCH_LIMIT for the current start position.
+ step_limit: u64,
+ /// Where the steps next look at the interrupt flag.
+ next_interrupt_poll: u64,
+ /// The sooner of the two above, so that a step has one comparison to make.
+ next_checkpoint: u64,
modifiers: ActiveModifiers,
modifier_stack: &'a mut Vec<ActiveModifiers>,
/// The changes to the modifier stack so far, most recent last. A saved state records the length of this trail, and
@@ -1433,6 +1468,9 @@ impl<'a, I: Input> Vm<'a, I> {
backtrack_stack: &mut scratch.backtrack_stack,
register_trail: &mut scratch.register_trail,
steps: 0,
+ step_limit: MATCH_LIMIT,
+ next_interrupt_poll: INTERRUPT_POLL_INTERVAL,
+ next_checkpoint: INTERRUPT_POLL_INTERVAL.min(MATCH_LIMIT),
modifiers: ActiveModifiers {
ignore_case: program.ignore_case,
multiline: program.multiline,
@@ -1465,7 +1503,8 @@ impl<'a, I: Input> Vm<'a, I> {
self.registers.fill(-1);
self.backtrack_stack.clear();
self.register_trail.clear();
- self.steps = 0;
+ self.step_limit = self.steps + MATCH_LIMIT;
+ self.next_checkpoint = self.next_interrupt_poll.min(self.step_limit);
self.modifiers = ActiveModifiers {
ignore_case: self.program.ignore_case,
multiline: self.program.multiline,
@@ -1478,6 +1517,20 @@ impl<'a, I: Input> Vm<'a, I> {
self.lookaround_depth = 0;
}
+ /// Decides how a match goes on at `next_checkpoint`: it does not if the result says so.
+ #[cold]
+ fn reach_checkpoint(&mut self) -> Option<VmResult> {
+ if self.steps >= self.step_limit {
+ return Some(VmResult::LimitExceeded);
+ }
+ if is_interrupted() {
+ return Some(VmResult::Interrupted);
+ }
+ self.next_interrupt_poll = self.steps + INTERRUPT_POLL_INTERVAL;
+ self.next_checkpoint = self.next_interrupt_poll.min(self.step_limit);
+ None
+ }
+
fn run(&mut self) -> VmResult {
// Use the fast path for non-Unicode, forward-only patterns.
if !self.program.unicode && !self.backward {
@@ -1495,8 +1548,10 @@ impl<'a, I: Input> Vm<'a, I> {
let input_len = input.len();
'vm_loop: loop {
self.steps += 1;
- if self.steps >= MATCH_LIMIT {
- return VmResult::LimitExceeded;
+ if self.steps >= self.next_checkpoint
+ && let Some(result) = self.reach_checkpoint()
+ {
+ return result;
}
let pc = self.pc as usize;
@@ -1867,8 +1922,10 @@ impl<'a, I: Input> Vm<'a, I> {
let num_instructions = instructions.len();
'vm_loop: loop {
self.steps += 1;
- if self.steps >= MATCH_LIMIT {
- return VmResult::LimitExceeded;
+ if self.steps >= self.next_checkpoint
+ && let Some(result) = self.reach_checkpoint()
+ {
+ return result;
}
let pc = self.pc as usize;
@@ -2333,8 +2390,8 @@ impl<'a, I: Input> Vm<'a, I> {
self.pos = saved_pos;
self.backtrack_stack.truncate(saved_bt_len);
- if body_result == VmResult::LimitExceeded {
- return Some(VmResult::LimitExceeded);
+ if matches!(body_result, VmResult::LimitExceeded | VmResult::Interrupted) {
+ return Some(body_result);
}
let body_matched = body_result == VmResult::Match;
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 7c26e8d0e87..62100139f27 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -35,6 +35,7 @@ ALLOWED = {
"Libraries/LibJS/Flap/src/low_ir/lowering.rs:LABELS": "per-thread scratch buffer; a second copy costs memory, never an answer",
"Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs:FEATURES": "immutable CPU/OS feature cache; each copy computes the same supported instructions",
"Libraries/LibJS/JIT/Rust/src/codegen/tests.rs:REGION": "the fake heap region of JIT unit tests, in the cargo test binary that has no runtime",
+ "Libraries/LibRegex/Rust/src/vm.rs:INTERRUPT_FLAG": "per-thread, and only libjs_rust's copy sets it; the copy of LibURL's crate has no VM to interrupt, so it only ever sees null",
"Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_LISTS": "per-thread allocation pool; a second copy costs memory, never an answer",
"Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_VALUES": "per-thread allocation pool; a second copy costs memory, never an answer",
}