Truly independent web browser
LibJS: Call the frontend's host functions as Rust functions
Andreas Klingf15323e3051e
diff --git a/AK/LsanSuppressions.h b/AK/LsanSuppressions.hindex e975996c975..4049f7d4542 100644--- a/AK/LsanSuppressions.h+++ b/AK/LsanSuppressions.h@@ -16,8 +16,7 @@ char const* __lsan_default_suppressions()// Both Skia and Chromium suppress false positive FontConfig leaks// https://github.com/google/skia/blob/main/tools/LsanSuppressions.cpp#L20// https://chromium.googlesource.com/chromium/src/build/+/master/sanitizers/lsan_suppressions.cc#25- return "leak:FcPatternObjectInsertElt\n"- "leak:rust_compile_regex";+ return "leak:FcPatternObjectInsertElt";}}#endifdiff --git a/Libraries/LibJS/Rust/src/frontend_host.rs b/Libraries/LibJS/Rust/src/frontend_host.rsindex f56031bd600..a535d99dced 100644--- a/Libraries/LibJS/Rust/src/frontend_host.rs+++ b/Libraries/LibJS/Rust/src/frontend_host.rs@@ -4,13 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The functions the Rust frontend (Libraries/LibJS/Rust) calls on the runtime that embeds it: the hooks the parser-//! calls.--use core::alloc::Layout;-use core::ffi::c_void;-use core::{ptr, slice};-use std::alloc::{alloc, dealloc, handle_alloc_error};+//! 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::regex::Regex;@@ -18,101 +12,13 @@ use libregex_rust::regex::Regex;use crate::runtime::regexp_object::parse_regex_pattern;use crate::runtime::value::number_to_string;-/// What the frontend holds for each regular expression literal it compiled: the pattern as ParsePattern rewrote it.-pub struct CompiledRegex {- pub parsed_pattern: Vec<u16>,+/// Number::toString(value), which the frontend uses for numeric property names.+pub fn number_to_utf16(value: f64) -> Vec<u16> {+ number_to_string(value).encode_utf16().collect()}/// Compiles a regular expression literal, so that the frontend can report an invalid one as an early error.-///-/// Returns an owned CompiledRegex for rust_free_compiled_regex to release, or null with an error message in error_out-/// and error_len_out for rust_free_error_string to release.-///-/// # Safety-///-/// pattern_data and flags_data must point to pattern_len and flags_len UTF-16 code units (or may dangle when the-/// length is zero), and error_out and error_len_out must be valid for writes.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_compile_regex(- pattern_data: *const u16,- pattern_len: usize,- flags_data: *const u16,- flags_len: usize,- error_out: *mut *const u16,- error_len_out: *mut usize,-) -> *mut c_void {- // SAFETY: The caller passes valid buffers of these lengths, and out-pointers valid for writes.- unsafe {- error_out.write(ptr::null());- error_len_out.write(0);- let (pattern, flags) = (code_units(pattern_data, pattern_len), code_units(flags_data, flags_len));- match compile_regex(pattern, flags) {- Ok(compiled) => Box::into_raw(Box::new(compiled)).cast(),- Err(message) => {- let (error, error_length) = allocate_error_string(&message);- error_out.write(error);- error_len_out.write(error_length);- ptr::null_mut()- }- }- }-}--/// # Safety-///-/// compiled_regex must be null or a pointer rust_compile_regex returned that has not been freed yet.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_free_compiled_regex(compiled_regex: *mut c_void) {- if !compiled_regex.is_null() {- // SAFETY: rust_compile_regex created this pointer with Box::into_raw.- drop(unsafe { Box::from_raw(compiled_regex.cast::<CompiledRegex>()) });- }-}--/// # Safety-///-/// message must be null or an error message rust_compile_regex stored that has not been freed yet.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_free_error_string(message: *const u16) {- if message.is_null() {- return;- }- // SAFETY: allocate_error_string placed the message right after its length, in an allocation of this layout.- unsafe {- let allocation = message.cast::<u8>().sub(ERROR_STRING_HEADER_SIZE).cast_mut();- let length = allocation.cast::<usize>().read();- dealloc(allocation, error_string_layout(length));- }-}--/// Writes Number::toString(value) into buffer, truncated to buffer_len code units, and returns how many it wrote.-///-/// # Safety-///-/// buffer must be valid for writing buffer_len code units.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_number_to_utf16(value: f64, buffer: *mut u16, buffer_len: usize) -> usize {- let string = number_to_string(value);- let length = string.len().min(buffer_len);- for (index, byte) in string.bytes().take(length).enumerate() {- // SAFETY: index is below buffer_len, for which the caller passes a writable buffer.- unsafe { buffer.add(index).write(u16::from(byte)) };- }- length-}--/// # Safety-///-/// data must point to length code units, or may dangle when length is zero.-unsafe fn code_units<'a>(data: *const u16, length: usize) -> &'a [u16] {- if length == 0 {- return &[];- }- // SAFETY: The caller guarantees the buffer.- unsafe { slice::from_raw_parts(data, length) }-}--fn compile_regex(pattern: &[u16], flags: &[u16]) -> Result<CompiledRegex, String> {+pub fn validate_regex(pattern: &[u16], flags: &[u16]) -> Result<(), String> {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'))@@ -135,33 +41,5 @@ fn compile_regex(pattern: &[u16], flags: &[u16]) -> Result<CompiledRegex, String.collect();Regex::compile_chars(pattern_characters, compile_flags).map_err(|error| format!("RegExp compile error: {error}"))?;-- Ok(CompiledRegex { parsed_pattern })-}--/// Error messages carry their length in front of them, since rust_free_error_string only receives the message.-const ERROR_STRING_HEADER_SIZE: usize = size_of::<usize>();--fn error_string_layout(length: usize) -> Layout {- Layout::from_size_align(- ERROR_STRING_HEADER_SIZE + length * size_of::<u16>(),- align_of::<usize>(),- )- .expect("an error message fits the address space")-}--fn allocate_error_string(message: &str) -> (*const u16, usize) {- let code_units: Vec<u16> = message.encode_utf16().collect();- let layout = error_string_layout(code_units.len());- // SAFETY: The layout has a non-zero size, and the header and message are written within it.- unsafe {- let allocation = alloc(layout);- if allocation.is_null() {- handle_alloc_error(layout);- }- allocation.cast::<usize>().write(code_units.len());- let message_data = allocation.add(ERROR_STRING_HEADER_SIZE).cast::<u16>();- ptr::copy_nonoverlapping(code_units.as_ptr(), message_data, code_units.len());- (message_data, code_units.len())- }+ Ok(())}diff --git a/Libraries/LibJS/Rust/src/host.rs b/Libraries/LibJS/Rust/src/host.rsindex 1f6de69ed96..c9d33cf73a4 100644--- a/Libraries/LibJS/Rust/src/host.rs+++ b/Libraries/LibJS/Rust/src/host.rs@@ -6,60 +6,24 @@//! Functions the parser and codegen import from the runtime that embeds them.//!-//! These four symbols are the frontend's whole host interface, so every runtime-//! that embeds the frontend defines them.--use std::ffi::c_void;+//! The runtime implements them in frontend_host.rs. The cargo test binary, which+//! builds the frontend without the runtime, uses the stand-ins in test_host.rs.use crate::ast::Utf16String;-unsafe extern "C" {- fn rust_free_compiled_regex(ptr: *mut c_void);-- fn rust_compile_regex(- pattern_data: *const u16,- pattern_len: usize,- flags_data: *const u16,- flags_len: usize,- error_out: *mut *const u16,- error_len_out: *mut usize,- ) -> *mut c_void;-- fn rust_free_error_string(str: *const u16);-- fn rust_number_to_utf16(value: f64, buffer: *mut u16, buffer_len: usize) -> usize;--}+#[cfg(not(test))]+use crate::frontend_host as implementation;+#[cfg(test)]+use crate::test_host as implementation;/// Convert a JS number to its UTF-16 string representation using the/// ECMA-262 Number::toString algorithm, which the host implements.pub fn js_number_to_utf16(value: f64) -> Utf16String {- let mut buffer = [0u16; 64];- let len = unsafe { rust_number_to_utf16(value, buffer.as_mut_ptr(), buffer.len()) };- Utf16String(buffer[..len].to_vec())+ Utf16String(implementation::number_to_utf16(value))}/// 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;- let handle = rust_compile_regex(- pattern.as_ptr(),- pattern.len(),- flags.as_ptr(),- flags.len(),- &raw mut error,- &raw mut error_len,- );- if error.is_null() {- 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);- Err(msg)- }- }+ implementation::validate_regex(pattern, flags).map_err(|message| Utf16String(message.encode_utf16().collect()))}diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rsindex 9240fcade9a..1aa9a933f09 100644--- a/Libraries/LibJS/Rust/src/test_host.rs+++ b/Libraries/LibJS/Rust/src/test_host.rs@@ -9,45 +9,20 @@use std::alloc::Layout;use std::collections::HashMap;-use std::ffi::c_void;use std::sync::Mutex;use std::sync::atomic::AtomicU32;-#[unsafe(no_mangle)]-extern "C" fn rust_compile_regex(- _pattern_data: *const u16,- _pattern_len: usize,- _flags_data: *const u16,- _flags_len: usize,- error_out: *mut *const u16,- error_len_out: *mut usize,-) -> *mut c_void {- // SAFETY: The frontend passes valid out-parameters.- unsafe {- *error_out = std::ptr::null();- *error_len_out = 0;- }- std::ptr::null_mut()+pub fn validate_regex(_pattern: &[u16], _flags: &[u16]) -> Result<(), String> {+ Ok(())}-#[unsafe(no_mangle)]-extern "C" fn rust_free_compiled_regex(_ptr: *mut c_void) {}--#[unsafe(no_mangle)]-extern "C" fn rust_free_error_string(_str: *const u16) {}--#[unsafe(no_mangle)]-extern "C" fn rust_number_to_utf16(value: f64, buffer: *mut u16, buffer_len: usize) -> usize {+pub fn number_to_utf16(value: f64) -> Vec<u16> {let text = if value.is_infinite() {if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string()} else {value.to_string()};- let units: Vec<u16> = text.encode_utf16().collect();- assert!(units.len() <= buffer_len);- // SAFETY: The frontend passes a buffer of `buffer_len` code units.- unsafe { std::ptr::copy_nonoverlapping(units.as_ptr(), buffer, units.len()) };- units.len()+ text.encode_utf16().collect()}#[unsafe(no_mangle)]