Skip to content

Truly independent web browser

LibJS: Own copied bytecode cache blobs without a C callback

Andreas Kling8d524aff7b23
diff --git a/Libraries/LibJS/Rust/src/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode_cache.rs
index 1834c66b9ed..fbb3bef98e9 100644
--- a/Libraries/LibJS/Rust/src/bytecode_cache.rs
+++ b/Libraries/LibJS/Rust/src/bytecode_cache.rs
@@ -113,11 +113,26 @@ pub fn serialize_compiled_program(
pub type FreeBytecodeCacheBlobOwner = unsafe extern "C" fn(*mut c_void);
-/// An embedder's handle on the bytes of a bytecode cache blob.
-pub struct ForeignBytecodeCacheBlobOwner {
- pub owner: *mut c_void,
- /// Releases a handle once nothing decoded from the bytes needs them anymore.
- pub free_owner: FreeBytecodeCacheBlobOwner,
+/// What keeps the bytes of a bytecode cache blob alive.
+pub enum BytecodeCacheBlobOwner {
+ /// An embedder's handle on the bytes, which `free_owner` releases once nothing decoded from them needs them
+ /// anymore.
+ Foreign {
+ owner: *mut c_void,
+ free_owner: FreeBytecodeCacheBlobOwner,
+ },
+ /// A copy of bytes that were not aligned for running in place. A Vec, unlike a Box, can be moved while the bytes
+ /// are borrowed.
+ Aligned(Vec<u64>),
+}
+
+impl Drop for BytecodeCacheBlobOwner {
+ fn drop(&mut self) {
+ if let Self::Foreign { owner, free_owner } = self {
+ // SAFETY: The embedder's release function takes the owner it handed over, once.
+ unsafe { free_owner(*owner) };
+ }
+ }
}
/// Decodes a blob that [`serialize_compiled_program()`] wrote for `expected_runtime` and a program of
@@ -128,13 +143,13 @@ pub struct ForeignBytecodeCacheBlobOwner {
/// program type or source, and for a malformed one.
///
/// # Safety
-/// `bytes` must stay alive and unchanged until `owner.free_owner` is called with `owner.owner`.
+/// `bytes` must stay alive and unchanged until `owner` is dropped.
pub unsafe fn decode_blob(
bytes: &[u8],
expected_program_type: ast::ProgramType,
expected_source_hash: &[u8; SOURCE_HASH_SIZE],
expected_runtime: BytecodeCacheRuntime,
- owner: ForeignBytecodeCacheBlobOwner,
+ owner: BytecodeCacheBlobOwner,
) -> Option<DecodedCacheBlob> {
let mut decoder = Decoder::new(bytes, Some(owner));
let blob = CacheBlob::decode(
@@ -189,16 +204,7 @@ impl Encoder {
struct ForeignBytecodeCacheBlob {
data: *const u8,
length: usize,
- owner: *mut c_void,
- free_owner: FreeBytecodeCacheBlobOwner,
-}
-
-impl Drop for ForeignBytecodeCacheBlob {
- fn drop(&mut self) {
- unsafe {
- (self.free_owner)(self.owner);
- }
- }
+ _owner: BytecodeCacheBlobOwner,
}
struct Decoder<'a> {
@@ -208,13 +214,12 @@ struct Decoder<'a> {
}
impl<'a> Decoder<'a> {
- fn new(bytes: &'a [u8], owner: Option<ForeignBytecodeCacheBlobOwner>) -> Self {
+ fn new(bytes: &'a [u8], owner: Option<BytecodeCacheBlobOwner>) -> Self {
let foreign_blob = owner.map(|owner| {
Rc::new(ForeignBytecodeCacheBlob {
data: bytes.as_ptr(),
length: bytes.len(),
- owner: owner.owner,
- free_owner: owner.free_owner,
+ _owner: owner,
})
});
Self {
@@ -3108,7 +3113,7 @@ mod tests {
}
/// Copies `bytes` into storage of the returned owner, which adds one to `releases` when it is released.
- fn test_blob(bytes: &[u8], releases: &Rc<Cell<usize>>) -> (&'static [u8], ForeignBytecodeCacheBlobOwner) {
+ fn test_blob(bytes: &[u8], releases: &Rc<Cell<usize>>) -> (&'static [u8], BytecodeCacheBlobOwner) {
let mut storage = Box::new(TestBlobStorage {
words: vec![0u64; bytes.len().div_ceil(size_of::<u64>())],
releases: releases.clone(),
@@ -3119,7 +3124,7 @@ mod tests {
}
// SAFETY: The owner keeps the words alive until the decoded blob releases it.
let view = unsafe { std::slice::from_raw_parts(storage.words.as_ptr().cast::<u8>(), bytes.len()) };
- let owner = ForeignBytecodeCacheBlobOwner {
+ let owner = BytecodeCacheBlobOwner::Foreign {
owner: Box::into_raw(storage).cast(),
free_owner: release_test_blob,
};
diff --git a/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rs b/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rs
index 73279c7496b..78541eaea31 100644
--- a/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rs
+++ b/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rs
@@ -19,9 +19,7 @@ use core::ffi::c_void;
use std::rc::Rc;
use crate::bytecode::bytecode_cache::DecodedBytecodeCache;
-use crate::bytecode_cache::{
- BytecodeCacheRuntime, ForeignBytecodeCacheBlobOwner, decode_blob, serialize_compiled_program,
-};
+use crate::bytecode_cache::{BytecodeCacheBlobOwner, BytecodeCacheRuntime, decode_blob, serialize_compiled_program};
use crate::compile::FunctionPrecompileMode;
use crate::embedding::abi_types::{
JSByteSink, JSRealm, JSSourceCode, JSUtf16View, cell_from_abi, cell_into_abi, vm_from_abi,
@@ -126,18 +124,8 @@ pub unsafe extern "C" fn js_bytecode_cache_serialize(
unsafe { append(sink.context, blob.as_ptr(), blob.len()) }
}
-/// The bytes of a blob that was not aligned for running in place, copied to storage that is.
-struct AlignedBlobBytes {
- words: Box<[u64]>,
-}
-
const _: () = assert!(align_of::<u64>() == JS_BYTECODE_CACHE_BLOB_ALIGNMENT);
-unsafe extern "C" fn release_aligned_blob_bytes(owner: *mut c_void) {
- // SAFETY: The owner is the boxed copy that decode() handed over, which is released once.
- drop(unsafe { Box::from_raw(owner.cast::<AlignedBlobBytes>()) });
-}
-
/// Decodes the blob in `bytes`, whose owner it takes over, releasing the owner if it rejects the blob.
///
/// # Safety
@@ -167,29 +155,26 @@ unsafe fn decode(
return None;
}
let program_type = program_type_from_abi(program_type);
+ // SAFETY: The caller passes bytes that stay alive and unchanged until the owner is released.
+ let bytes = unsafe { core::slice::from_raw_parts(bytes, length) };
- let (bytes, owner) = if bytes.addr().is_multiple_of(JS_BYTECODE_CACHE_BLOB_ALIGNMENT) {
- // SAFETY: The caller passes bytes that stay alive and unchanged until the owner is released.
- let bytes = unsafe { core::slice::from_raw_parts(bytes, length) };
- let owner = ForeignBytecodeCacheBlobOwner {
+ let (bytes, owner) = if bytes.as_ptr().addr().is_multiple_of(JS_BYTECODE_CACHE_BLOB_ALIGNMENT) {
+ let owner = BytecodeCacheBlobOwner::Foreign {
owner: owner.owner,
free_owner: release,
};
(bytes, owner)
} else {
- let mut copy = Box::new(AlignedBlobBytes {
- words: vec![0; length.div_ceil(size_of::<u64>())].into_boxed_slice(),
- });
- // SAFETY: The caller passes `length` readable bytes, and the words have room for them.
- unsafe { core::ptr::copy_nonoverlapping(bytes, copy.words.as_mut_ptr().cast::<u8>(), length) };
+ let mut words = vec![0; length.div_ceil(size_of::<u64>())];
+ for (word, chunk) in words.iter_mut().zip(bytes.chunks(size_of::<u64>())) {
+ let mut word_bytes = [0; size_of::<u64>()];
+ word_bytes[..chunk.len()].copy_from_slice(chunk);
+ *word = u64::from_ne_bytes(word_bytes);
+ }
release_owner();
- // SAFETY: The copy, which the owner below releases, keeps its words alive and unchanged.
- let bytes = unsafe { core::slice::from_raw_parts(copy.words.as_ptr().cast::<u8>(), length) };
- let owner = ForeignBytecodeCacheBlobOwner {
- owner: Box::into_raw(copy).cast(),
- free_owner: release_aligned_blob_bytes,
- };
- (bytes, owner)
+ // SAFETY: The words, which the owner below keeps, stay alive and unchanged.
+ let bytes = unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), length) };
+ (bytes, BytecodeCacheBlobOwner::Aligned(words))
};
// SAFETY: The owner keeps the bytes alive and unchanged until it is released.
let blob = unsafe { decode_blob(bytes, program_type, source_hash, BytecodeCacheRuntime::Rust, owner) }?;