Skip to content

Truly independent web browser

LibJS: Stop carrying compiled regexes the frontend only validates

Andreas Kling911d4ebb0adf
diff --git a/Libraries/LibJS/Flap/src/bytecode.rs b/Libraries/LibJS/Flap/src/bytecode.rs
index 2c58c3ae895..9d5c6d23505 100644
--- a/Libraries/LibJS/Flap/src/bytecode.rs
+++ b/Libraries/LibJS/Flap/src/bytecode.rs
@@ -180,7 +180,6 @@ fn bytecode_field_type_matches(field: &crate::metadata::Field, parameter_type: &
| "ObjectPropertyIteratorCacheIndex"
| "ObjectShapeCacheIndex"
| "PropertyKeyTableIndex"
- | "RegexTableIndex"
| "StringTableIndex"
| "TemplateObjectCacheIndex"
| "Optional<IdentifierTableIndex>"
diff --git a/Libraries/LibJS/Flap/src/frontend/parser.rs b/Libraries/LibJS/Flap/src/frontend/parser.rs
index 5a4804ecf26..78c25327637 100644
--- a/Libraries/LibJS/Flap/src/frontend/parser.rs
+++ b/Libraries/LibJS/Flap/src/frontend/parser.rs
@@ -572,7 +572,6 @@ impl<'a> Parser<'a> {
| "ObjectPropertyIteratorCacheIndex"
| "ObjectShapeCacheIndex"
| "PropertyKeyTableIndex"
- | "RegexTableIndex"
| "StringTableIndex"
| "TemplateObjectCacheIndex"
) {
diff --git a/Libraries/LibJS/Flap/src/metadata.rs b/Libraries/LibJS/Flap/src/metadata.rs
index b01ada2446a..322e5294f1b 100644
--- a/Libraries/LibJS/Flap/src/metadata.rs
+++ b/Libraries/LibJS/Flap/src/metadata.rs
@@ -643,7 +643,6 @@ fn try_field_type_info(ty: &str) -> Option<FieldType> {
"PropertyKeyTableIndex" => ("PropertyKeyTableIndex", 4, 4, "u32_newtype"),
"StringTableIndex" => ("StringTableIndex", 4, 4, "u32_newtype"),
"Optional<StringTableIndex>" => ("Option<StringTableIndex>", 4, 4, "optional_u32_newtype"),
- "RegexTableIndex" => ("RegexTableIndex", 4, 4, "u32_newtype"),
"EnvironmentCoordinate" => ("EnvironmentCoordinate", 4, 8, "env_coord"),
"Builtin" => ("u8", 1, 1, "u8"),
"Completion::Type" => ("u32", 4, 4, "u32"),
diff --git a/Libraries/LibJS/Flap/src/rust_bytecode.rs b/Libraries/LibJS/Flap/src/rust_bytecode.rs
index d1cf7dbd415..12b129f5b49 100644
--- a/Libraries/LibJS/Flap/src/rust_bytecode.rs
+++ b/Libraries/LibJS/Flap/src/rust_bytecode.rs
@@ -14,7 +14,7 @@
//!
//! The generated code expects the including module to provide the operand types
//! named by `field_type_info()` (`Operand`, `Label`, `IdentifierTableIndex`,
-//! `PropertyKeyTableIndex`, `StringTableIndex`, `RegexTableIndex`,
+//! `PropertyKeyTableIndex`, `StringTableIndex`,
//! `EnvironmentCoordinate`) with `from_raw` / `optional_from_raw` constructors,
//! plus `read_u16(bytes, at)`, `read_u32(bytes, at)` and `read_u64(bytes, at)` helpers reachable
//! through the `reader` path prefix passed to the field reading functions.
@@ -120,7 +120,6 @@ pub fn read_expr_for_type(ty: &str, offset: &str, reader: &str) -> String {
"Optional<StringTableIndex>" => {
format!("StringTableIndex::optional_from_raw({reader}read_u32(bytes, {offset}))")
}
- "RegexTableIndex" => format!("RegexTableIndex({reader}read_u32(bytes, {offset}))"),
"EnvironmentCoordinate" => format!(
"EnvironmentCoordinate {{ hops: {reader}read_u32(bytes, {offset}), index: {reader}read_u32(bytes, {offset} + 4) }}"
),
diff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flap
index 624e550c85c..2027d9adb32 100644
--- a/Libraries/LibJS/Interpreter/interpreter.flap
+++ b/Libraries/LibJS/Interpreter/interpreter.flap
@@ -4677,8 +4677,7 @@ handler NewPrimitiveArray(
handler NewRegExp(
dst: out Operand,
source_index: StringTableIndex,
- flags_index: StringTableIndex,
- regex_index: RegexTableIndex
+ flags_index: StringTableIndex
) @cold = call_slow_path(new_regexp);
handler NewReferenceError(
diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs
index a8ad3758324..35b810572fa 100644
--- a/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs
+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs
@@ -88,10 +88,6 @@ impl StringTableIndex {
}
}
-/// Index into the executable's regex table.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct RegexTableIndex(pub u32);
-
/// Environment coordinate used by the binding instructions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EnvironmentCoordinate {
diff --git a/Libraries/LibJS/Rust/generate/instructions.rs b/Libraries/LibJS/Rust/generate/instructions.rs
index 09f2d02ca74..2574d23b2da 100644
--- a/Libraries/LibJS/Rust/generate/instructions.rs
+++ b/Libraries/LibJS/Rust/generate/instructions.rs
@@ -575,9 +575,6 @@ fn emit_scalar_field_check(
w,
" validate_property_key_index(read_u32(bytes, at + {offset}), ctx)?;"
)?,
- "RegexTableIndex" => {
- // The regex table is not consulted at runtime; skip range-checking.
- }
"PropertyLookupCacheIndex" => writeln!(
w,
" validate_property_lookup_cache_index(read_u32(bytes, at + {offset}), ctx)?;"
diff --git a/Libraries/LibJS/Rust/generate/ops.rs b/Libraries/LibJS/Rust/generate/ops.rs
index 443210f61ab..f11e9d299bd 100644
--- a/Libraries/LibJS/Rust/generate/ops.rs
+++ b/Libraries/LibJS/Rust/generate/ops.rs
@@ -38,7 +38,7 @@ fn rust_type(ty: &str) -> String {
"Optional<Operand>" => "OptionalOperand".to_string(),
"Label" => "Label".to_string(),
"Optional<Label>" => "OptionalLabel".to_string(),
- "IdentifierTableIndex" | "PropertyKeyTableIndex" | "StringTableIndex" | "RegexTableIndex" => ty.to_string(),
+ "IdentifierTableIndex" | "PropertyKeyTableIndex" | "StringTableIndex" => ty.to_string(),
"Optional<IdentifierTableIndex>" => "OptionalIndex<IdentifierTableIndex>".to_string(),
"Optional<StringTableIndex>" => "OptionalIndex<StringTableIndex>".to_string(),
"EnvironmentCoordinate" => "EnvironmentCoordinate".to_string(),
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rs
index 9d911ab5c35..c42d5202934 100644
--- a/Libraries/LibJS/Rust/src/ast.rs
+++ b/Libraries/LibJS/Rust/src/ast.rs
@@ -22,13 +22,9 @@
//! - `ScopeData` is carried by block-like constructs (Program,
//! BlockStatement, FunctionBody, etc.) and holds scope analysis results.
-use std::ffi::c_void;
-use std::fmt;
use std::ops::Index;
use std::ops::IndexMut;
use std::sync::Arc;
-use std::sync::atomic::AtomicPtr;
-use std::sync::atomic::Ordering;
use crate::fast_hash::HashMap;
@@ -1240,52 +1236,10 @@ pub struct TemplateLiteralData {
// RegExp literal
// =============================================================================
-/// Handle to a compiled regex from the host's regex engine.
-///
-/// Wrapped in `Arc` in `RegExpLiteralData` so that AST clones (e.g. for
-/// class field initializers) share the handle cheaply. The first codegen
-/// path to call `take()` gets the handle; `Drop` frees it if untaken.
-/// Uses `AtomicPtr` so the regex can be safely shared across threads
-/// during background compile of sibling functions.
-pub struct CompiledRegex(AtomicPtr<c_void>);
-
-impl CompiledRegex {
- pub fn new(ptr: *mut c_void) -> Self {
- Self(AtomicPtr::new(ptr))
- }
-
- /// Take ownership of the compiled regex handle, leaving null behind
- /// so the destructor won't free it.
- pub fn take(&self) -> *mut c_void {
- self.0.swap(std::ptr::null_mut(), Ordering::AcqRel)
- }
-
- /// Set the compiled regex handle (used by deferred compilation).
- pub fn set(&self, ptr: *mut c_void) {
- self.0.store(ptr, Ordering::Release);
- }
-}
-
-impl Drop for CompiledRegex {
- fn drop(&mut self) {
- let ptr = *self.0.get_mut();
- if !ptr.is_null() {
- unsafe { crate::host::free_compiled_regex(ptr) };
- }
- }
-}
-
-impl fmt::Debug for CompiledRegex {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "CompiledRegex({:p})", self.0.load(Ordering::Acquire))
- }
-}
-
#[derive(Clone, Debug)]
pub struct RegExpLiteralData {
pub pattern: Utf16String,
pub flags: Utf16String,
- pub compiled_regex: Arc<CompiledRegex>,
}
// =============================================================================
diff --git a/Libraries/LibJS/Rust/src/breakpoint_positions.rs b/Libraries/LibJS/Rust/src/breakpoint_positions.rs
index 2246b6b0b49..afb8a5476e6 100644
--- a/Libraries/LibJS/Rust/src/breakpoint_positions.rs
+++ b/Libraries/LibJS/Rust/src/breakpoint_positions.rs
@@ -35,7 +35,6 @@ pub fn breakpoint_positions_for_source(
let compiled = compile_parsed_program_off_thread(parsed, source.len(), FunctionPrecompileMode::All);
let mut positions = Vec::new();
compiled.for_each_breakpoint_position(|position| positions.push(position));
- compiled.discard();
positions.sort_unstable();
positions.dedup();
positions
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rs
index 25e948276f8..2c958a607d1 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs
@@ -317,14 +317,11 @@ fn generate_expression_inner(
ExpressionKind::RegExpLiteral(data) => {
let source_index = generator.intern_string(&data.pattern);
let flags_index = generator.intern_string(&data.flags);
- let compiled = data.compiled_regex.take();
- let regex_index = generator.intern_regex(compiled);
let dst = choose_dst(generator, preferred_dst);
generator.emit(Instruction::NewRegExp {
dst: dst.operand(),
source_index,
flags_index,
- regex_index,
});
Some(dst)
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/encoding.rs b/Libraries/LibJS/Rust/src/bytecode/encoding.rs
index b1bad921f4a..3eba78da184 100644
--- a/Libraries/LibJS/Rust/src/bytecode/encoding.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/encoding.rs
@@ -72,12 +72,7 @@ macro_rules! define_table_index {
};
}
-define_table_index!(
- IdentifierTableIndex,
- PropertyKeyTableIndex,
- StringTableIndex,
- RegexTableIndex
-);
+define_table_index!(IdentifierTableIndex, PropertyKeyTableIndex, StringTableIndex);
/// A table index that may be absent, encoded with all bits set.
#[repr(transparent)]
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index 7122239ba37..562a7e5d1e9 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -23,7 +23,6 @@ use crate::bytecode::feedback::{ExecutableFeedback, FeedbackSlotCounts};
use crate::bytecode::generator::{ConstantValue, ExceptionHandler};
use crate::bytecode::generator::{LocalVariable, PendingClassBlueprint};
use crate::bytecode_cache::{DecodedBytecodeBytes, DecodedExecutableRecord};
-use crate::frontend_host::rust_free_compiled_regex;
use crate::gc::class::{Finalize, GcCell, define_cell};
use crate::gc::heap::cell_is_dead;
use crate::gc::root::MarkedVec;
@@ -1532,11 +1531,6 @@ impl Executable {
));
}
- // The regexes were only compiled to report early errors; the runtime compiles them again when it runs.
- for regex in data.compiled_regexes {
- // SAFETY: Each handle came from rust_compile_regex and is freed once.
- unsafe { rust_free_compiled_regex(regex.into_raw()) };
- }
let parts = ExecutableParts {
bytecode: ExecutableBytecode::Owned(data.bytecode.into_boxed_slice()),
number_of_registers: data.number_of_registers,
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
index e221da53cea..b371d6aab9e 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
@@ -6,8 +6,6 @@
//! Compiled bytecode together with everything needed to run it, as owned Rust values.
-use std::ffi::c_void;
-
use super::basic_block::SourceMapEntry;
use super::generator::AssembledBytecode;
use super::generator::ConstantValue;
@@ -18,24 +16,6 @@ use super::generator::PendingClassBlueprint;
use super::generator::PendingSharedFunctionData;
use super::operand::PropertyKeyTableIndex;
-/// A regular expression that `host::compile_regex()` compiled for the bytecode, which only the host looks into.
-#[repr(transparent)]
-pub struct CompiledRegexHandle(*mut c_void);
-
-// SAFETY: The frontend never dereferences the handle. It only carries it from the thread that compiled the bytecode to
-// the one that runs it, where the runtime adopts or frees it, and hosts let any thread do that.
-unsafe impl Send for CompiledRegexHandle {}
-
-impl CompiledRegexHandle {
- pub fn new(handle: *mut c_void) -> Self {
- Self(handle)
- }
-
- pub fn into_raw(self) -> *mut c_void {
- self.0
- }
-}
-
/// How many inline cache and feedback slots of each kind the bytecode indexes into.
#[derive(Clone, Copy)]
pub struct ExecutableCacheCounts {
@@ -76,9 +56,6 @@ pub struct ExecutableData {
pub length_identifier: Option<PropertyKeyTableIndex>,
pub shared_function_data: Vec<PendingSharedFunctionData>,
pub class_blueprints: Vec<PendingClassBlueprint>,
- /// Handles from `host::compile_regex()`, owned by this executable until the
- /// runtime adopts them.
- pub compiled_regexes: Vec<CompiledRegexHandle>,
}
impl ExecutableData {
@@ -123,7 +100,6 @@ impl ExecutableData {
length_identifier: generator.length_identifier,
shared_function_data,
class_blueprints: generator.class_blueprints,
- compiled_regexes: generator.compiled_regexes,
}
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/generator.rs b/Libraries/LibJS/Rust/src/bytecode/generator.rs
index d0e0e1caa82..72e432c0a56 100644
--- a/Libraries/LibJS/Rust/src/bytecode/generator.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/generator.rs
@@ -18,7 +18,6 @@ use super::basic_block::BasicBlock;
use super::basic_block::SourceMapEntry;
use super::constant::AbstractOperationKind;
use super::constant::WellKnownSymbolKind;
-use super::executable_data::CompiledRegexHandle;
use super::executable_data::ExecutableData;
use super::instruction::{Instruction, specialize_instruction_sequence};
use super::operand::*;
@@ -340,7 +339,6 @@ pub struct Generator {
identifier_table_index: HashMap<ak::Utf16FlyString, IdentifierTableIndex>,
pub property_key_table: Vec<ak::Utf16FlyString>,
property_key_table_index: HashMap<ak::Utf16FlyString, PropertyKeyTableIndex>,
- pub compiled_regexes: Vec<CompiledRegexHandle>,
// --- Scope/unwind state ---
pub boundaries: Vec<BlockBoundaryType>,
@@ -543,7 +541,6 @@ impl Generator {
identifier_table_index: HashMap::new(),
property_key_table: Vec::new(),
property_key_table_index: HashMap::new(),
- compiled_regexes: Vec::new(),
boundaries: Vec::new(),
continuable_scopes: Vec::new(),
breakable_scopes: Vec::new(),
@@ -879,12 +876,6 @@ impl Generator {
index
}
- pub fn intern_regex(&mut self, compiled: *mut std::ffi::c_void) -> RegexTableIndex {
- let index = u32_from_usize(self.compiled_regexes.len());
- self.compiled_regexes.push(CompiledRegexHandle::new(compiled));
- RegexTableIndex(index)
- }
-
// --- Basic block management ---
/// Create a new basic block and return its label.
diff --git a/Libraries/LibJS/Rust/src/bytecode/operand.rs b/Libraries/LibJS/Rust/src/bytecode/operand.rs
index 46d1d1ba27d..4972e1f9d82 100644
--- a/Libraries/LibJS/Rust/src/bytecode/operand.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/operand.rs
@@ -164,10 +164,6 @@ impl IdentifierTableIndex {
#[derive(Debug, Clone, Copy)]
pub struct PropertyKeyTableIndex(pub u32);
-/// Index into the regex table.
-#[derive(Debug, Clone, Copy)]
-pub struct RegexTableIndex(pub u32);
-
/// Environment coordinate used by environment lookup instructions.
/// Layout: two `u32` fields (hops + index).
#[derive(Debug, Clone, Copy)]
diff --git a/Libraries/LibJS/Rust/src/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode_cache.rs
index 5917e5453ab..1834c66b9ed 100644
--- a/Libraries/LibJS/Rust/src/bytecode_cache.rs
+++ b/Libraries/LibJS/Rust/src/bytecode_cache.rs
@@ -50,7 +50,7 @@ use crate::compile::CompiledProgramBytecode;
use crate::u32_from_usize;
const MAGIC: &[u8; 8] = b"LBJSBC\0\0";
-const FORMAT_VERSION: u32 = 25;
+const FORMAT_VERSION: u32 = 26;
/// The size of the source hash a blob is keyed by.
pub(crate) const SOURCE_HASH_SIZE: usize = 32;
const BYTECODE_ALIGNMENT: usize = 8;
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index 9fae785c065..2c12eba051d 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -30,8 +30,7 @@ use std::collections::HashSet;
// Compile-time assertion: what parse and compile produce travels from a worker
// thread to the main thread, so it must be `Send`. After the StringId and
// ScopeId arena migrations the AST itself contains no `Rc`/`Cell`/`RefCell`
-// values, and compiled regexes are CompiledRegexHandles, so this is naturally
-// satisfied without `unsafe impl Send`.
+// values, so this is naturally satisfied without `unsafe impl Send`.
const _: fn() = || {
fn assert_send<T: Send>() {}
assert_send::<ParsedProgram>();
@@ -599,33 +598,6 @@ impl CompiledProgram {
declarations,
}
}
-
- /// Frees a program that will not run, together with the regular expressions the host compiled for it. Dropping it
- /// instead would leak those, since only the runtime that adopts an executable frees them otherwise.
- pub fn discard(mut self) {
- fn free_executable_regexes(executable: &mut ExecutableData) {
- for regex in executable.compiled_regexes.drain(..) {
- // SAFETY: No runtime adopted the executables of a program that is discarded, so they still own these.
- unsafe { crate::host::free_compiled_regex(regex.into_raw()) };
- }
- for shared_data in &mut executable.shared_function_data {
- if let Some(precompiled) = &mut shared_data.precompiled_function {
- free_executable_regexes(&mut precompiled.executable);
- }
- }
- }
-
- match &mut self.bytecode {
- CompiledProgramBytecode::Program(executable) | CompiledProgramBytecode::AsyncModule(executable) => {
- free_executable_regexes(executable);
- }
- }
- for declaration in &mut self.declaration_functions {
- if let Some(precompiled) = &mut declaration.precompiled_function {
- free_executable_regexes(&mut precompiled.executable);
- }
- }
- }
}
/// Returns the name of the binding that holds the value of `export default <expression>`, if the module has one.
diff --git a/Libraries/LibJS/Rust/src/embedding/compile.rs b/Libraries/LibJS/Rust/src/embedding/compile.rs
index 6732e9800d6..bfc8a7cd230 100644
--- a/Libraries/LibJS/Rust/src/embedding/compile.rs
+++ b/Libraries/LibJS/Rust/src/embedding/compile.rs
@@ -38,7 +38,7 @@ use crate::layout::cell::Gc;
use crate::layout::host_class::{JSModule, JSVM};
use crate::parser_error::ParserError;
use crate::runtime::module::Module;
-use crate::runtime::shared_function_instance_data::{SharedFunctionInstanceData, discard_precompiled_function};
+use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;
use crate::runtime::source_text_module::SourceTextModule;
use crate::script::Script;
use crate::utf16::Utf16View;
@@ -260,7 +260,7 @@ pub unsafe fn compiled_program_from_abi<'a>(compiled: *const JSCompiledProgram)
pub unsafe extern "C" fn js_compile_compiled_program_destroy(compiled: *mut JSCompiledProgram) {
if !compiled.is_null() {
// SAFETY: The caller gives up a live compiled program.
- unsafe { take_compiled_program_from_abi(compiled) }.discard();
+ drop(unsafe { take_compiled_program_from_abi(compiled) });
}
}
@@ -647,12 +647,10 @@ unsafe extern "C" fn install_compiled_lazy_functions(compiled: *mut c_void) {
executable,
awaiting_compilation.callbacks.clone(),
);
- discard_precompiled_function(compiled_function);
continue;
}
// Installing a bytecode cache may have dropped the AST, and its bytecode with it, while the worker compiled.
if !shared_data.has_function_ast() {
- discard_precompiled_function(compiled_function);
continue;
}
shared_data.set_precompiled_bytecode_executable(compiled_function);
diff --git a/Libraries/LibJS/Rust/src/host.rs b/Libraries/LibJS/Rust/src/host.rs
index 3a45af98081..1f6de69ed96 100644
--- a/Libraries/LibJS/Rust/src/host.rs
+++ b/Libraries/LibJS/Rust/src/host.rs
@@ -39,12 +39,9 @@ pub fn js_number_to_utf16(value: f64) -> Utf16String {
Utf16String(buffer[..len].to_vec())
}
-/// Compile a regex pattern+flags using the host's regex engine.
-///
-/// On success, returns an opaque handle to the compiled regex, which must be
-/// released with `free_compiled_regex()` unless an executable adopts it. On
-/// failure, returns the error message.
-pub fn compile_regex(pattern: &[u16], flags: &[u16]) -> Result<*mut c_void, Utf16String> {
+/// 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<(), Utf16String> {
unsafe {
let mut error: *const u16 = std::ptr::null();
let mut error_len = 0usize;
@@ -57,7 +54,8 @@ pub fn compile_regex(pattern: &[u16], flags: &[u16]) -> Result<*mut c_void, Utf1
&raw mut error_len,
);
if error.is_null() {
- Ok(handle)
+ rust_free_compiled_regex(handle);
+ Ok(())
} else {
let msg = Utf16String(std::slice::from_raw_parts(error, error_len).to_vec());
rust_free_error_string(error);
@@ -65,11 +63,3 @@ pub fn compile_regex(pattern: &[u16], flags: &[u16]) -> Result<*mut c_void, Utf1
}
}
}
-
-/// # Safety
-///
-/// `ptr` must identify a compiled regular expression whose ownership has not
-/// been transferred to an executable or released previously.
-pub unsafe fn free_compiled_regex(ptr: *mut c_void) {
- unsafe { rust_free_compiled_regex(ptr) };
-}
diff --git a/Libraries/LibJS/Rust/src/parser/expressions.rs b/Libraries/LibJS/Rust/src/parser/expressions.rs
index 2f0b8178253..62ce1ebda6d 100644
--- a/Libraries/LibJS/Rust/src/parser/expressions.rs
+++ b/Libraries/LibJS/Rust/src/parser/expressions.rs
@@ -7,8 +7,6 @@
//! Expression parsing: primary, secondary (binary/postfix), unary, and
//! precedence climbing.
-use std::sync::Arc;
-
use crate::ast::*;
use crate::lexer::ch;
use crate::parser::Associativity;
@@ -660,19 +658,14 @@ impl Parser<'_> {
Vec::new()
};
self.validate_regex_flags(&flags);
- let compiled_regex = match crate::host::compile_regex(&pattern, &flags) {
- Ok(handle) => Arc::new(CompiledRegex::new(handle)),
- Err(msg) => {
- self.syntax_error_at_position(&String::from_utf16_lossy(&msg), start);
- Arc::new(CompiledRegex::new(std::ptr::null_mut()))
- }
- };
+ if let Err(msg) = crate::host::validate_regex(&pattern, &flags) {
+ self.syntax_error_at_position(&String::from_utf16_lossy(&msg), start);
+ }
self.expression(
start,
ExpressionKind::RegExpLiteral(Box::new(RegExpLiteralData {
pattern: pattern.into(),
flags: flags.into(),
- compiled_regex,
})),
)
}
diff --git a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
index 310f8a66a7b..e05cd5d97b2 100644
--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
@@ -15,12 +15,10 @@ pub use crate::ast::FunctionKind;
use crate::ast::FunctionPayload;
use crate::bytecode::bytecode_cache::materialize_cached_function_executable;
use crate::bytecode::executable::Executable;
-use crate::bytecode::executable_data::ExecutableData;
use crate::bytecode::generator::{FunctionSfdMetadata, PendingSharedFunctionData, PrecompiledFunction};
use crate::bytecode_cache::{DecodedCachedExecutableRecord, DecodedFunctionRecord};
use crate::compile::FunctionPrecompileMode;
use crate::compile::SharedFunctionDescription;
-use crate::frontend_host::rust_free_compiled_regex;
use crate::gc::class::{GcCell, define_cell};
use crate::gc::gc_ref_cell::GcRefCell;
use crate::gc::visitor::{Trace, Visitor};
@@ -141,37 +139,12 @@ pub struct SharedFunctionInstanceDataStorage {
closure_count: Cell<ClosureCount>,
}
-impl Drop for SharedFunctionInstanceDataStorage {
- fn drop(&mut self) {
- if let Some(precompiled) = self.precompiled_bytecode_executable.get_mut().take() {
- discard_precompiled_function(precompiled);
- }
- }
-}
-
/// The most properties that constructions make room for ahead (the largest inline capacity of plain objects).
const MAX_CONSTRUCT_RESERVE: u32 = 16;
/// The last construction that follows the transitions again (see SharedFunctionInstanceData::construct_reserve()).
const MAX_CONSTRUCT_RESERVE_UPDATES: u32 = 1024;
-/// Frees bytecode that the frontend compiled ahead of a call that never came, along with the regular expressions the
-/// host compiled for it and for the functions nested in it, which only an executable created from it frees otherwise.
-pub fn discard_precompiled_function(mut precompiled: Box<PrecompiledFunction>) {
- fn free_compiled_regexes(executable: &mut ExecutableData) {
- for regex in executable.compiled_regexes.drain(..) {
- // SAFETY: No executable was created from this bytecode, so it still owns the regexes, which are freed once.
- unsafe { rust_free_compiled_regex(regex.into_raw()) };
- }
- for nested in &mut executable.shared_function_data {
- if let Some(nested_precompiled) = &mut nested.precompiled_function {
- free_compiled_regexes(&mut nested_precompiled.executable);
- }
- }
- }
- free_compiled_regexes(&mut precompiled.executable);
-}
-
define_cell!(SharedFunctionInstanceData, Other);
// SAFETY: Visits the executable, the call environment template and every cell the storage holds.
@@ -605,9 +578,7 @@ impl SharedFunctionInstanceData {
pub fn clear_non_bytecode_cache_compile_inputs(&self) {
drop(self.storage.rust_function_ast.take());
- if let Some(precompiled) = self.storage.precompiled_bytecode_executable.take() {
- discard_precompiled_function(precompiled);
- }
+ drop(self.storage.precompiled_bytecode_executable.take());
}
/// Whether the function still has the AST it compiles from when it is first called.
diff --git a/Tests/LibJS/Bytecode/expected/regex-literals.txt b/Tests/LibJS/Bytecode/expected/regex-literals.txt
index 4934de45881..94d99eaf133 100644
--- a/Tests/LibJS/Bytecode/expected/regex-literals.txt
+++ b/Tests/LibJS/Bytecode/expected/regex-literals.txt
@@ -1,4 +1,4 @@
-$1e202ea6 regex-literals.js:2:1
+$99fa450e regex-literals.js:2:1
Registers: 7
Blocks: 1
Constants:
@@ -9,25 +9,25 @@ $1e202ea6 regex-literals.js:2:1
block0:
[ 0] Enter
[ 8] NewRegExp dst:reg5, foo,
- [ 20] DynamicInitializeLexicalBinding `a`, src:reg5
- [ 30] NewRegExp dst:reg5, bar, gi
- [ 48] DynamicInitializeLexicalBinding `b`, src:reg5
- [ 58] NewRegExp dst:reg5, baz, i
- [ 70] AddLhsInt32 arith_feedback:0, dst:reg6, lhs:1, rhs:reg5
- [ 80] DynamicInitializeLexicalBinding `c`, src:reg6
- [ 90] GetGlobal value_feedback:0, dst:reg5, `matchDigits`
- [ a0] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, this_value:Undefined, matchDigits, arguments:[String("abc123")]
- [ c8] End value:reg6
+ [ 18] DynamicInitializeLexicalBinding `a`, src:reg5
+ [ 28] NewRegExp dst:reg5, bar, gi
+ [ 38] DynamicInitializeLexicalBinding `b`, src:reg5
+ [ 48] NewRegExp dst:reg5, baz, i
+ [ 58] AddLhsInt32 arith_feedback:0, dst:reg6, lhs:1, rhs:reg5
+ [ 68] DynamicInitializeLexicalBinding `c`, src:reg6
+ [ 78] GetGlobal value_feedback:0, dst:reg5, `matchDigits`
+ [ 88] Call value_feedback:1, call_feedback:0, dst:reg6, callee:reg5, this_value:Undefined, matchDigits, arguments:[String("abc123")]
+ [ b0] End value:reg6
-matchDigits$5149c62f regex-literals.js:8:5
+matchDigits$cfe7cda7 regex-literals.js:8:5
Registers: 9
Blocks: 1
block0:
[ 0] Enter
[ 8] NewRegExp dst:reg6, \d+, g
- [ 20] GetById value_feedback:0, dst:reg7, base:reg6, `test`
- [ 38] Mov dst:reg8, src:arg0
- [ 48] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, <object>.test, arguments:[reg8]
- [ 70] Return value:reg5
+ [ 18] GetById value_feedback:0, dst:reg7, base:reg6, `test`
+ [ 30] Mov dst:reg8, src:arg0
+ [ 40] Call value_feedback:1, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, <object>.test, arguments:[reg8]
+ [ 68] Return value:reg5