Truly independent web browser
LibJS: Keep the tables of an executable in one block of memory
Andreas Kling86c0670f7977
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex e9f65e9f3f1..19d2a359993 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -30,7 +30,7 @@ use crate::gc::weak::SweptAfterCollection;use crate::interpreter::vm::Vm;use crate::jit::InterpreterTier;use crate::jit::code::ExecutableJitState;-use crate::layout::buffer::{InterpreterBuffer, ThinSlice};+use crate::layout::buffer::{BlockSlice, InterpreterBuffer, ThinSlice};use crate::layout::cell::{CellHeader, CellHeaderTail, Gc};use crate::layout::executable::ExecutableHead;use crate::layout::feedback::ExecutableFeedbackHead;@@ -55,6 +55,7 @@ use crate::runtime::property_key::PropertyKey;use crate::runtime::shape::ShapeKey;use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;use crate::runtime::value::number_to_string;+use crate::slice_block::{SliceBlock, SliceBlockBuilder};use crate::source_code::SourceCode;use crate::source_range::{Position, SourceRange};use crate::utf16::Utf16View;@@ -1195,8 +1196,8 @@ pub struct Executable {pub head: ExecutableHead,/// What this executable runs, which other executables of the same code share.code: Arc<ExecutableData>,- environment_shape_caches: ThinSlice<NullableMember<EnvironmentShape>>,- object_shape_caches: ThinSlice<ObjectShapeCache>,+ environment_shape_caches: BlockSlice<NullableMember<EnvironmentShape>>,+ object_shape_caches: BlockSlice<ObjectShapeCache>,/// How many feedback slots of each kind the bytecode indexes into.feedback_slot_counts: FeedbackSlotCounts,/// What the interpreter observed running the bytecode, for the optimizing JIT. Only executables that left the@@ -1215,13 +1216,15 @@ pub struct Executable {has_dumped_feedback: Cell<bool>,pub is_strict_mode: bool,/// The property keys, made once, since turning a string into a property key checks whether it is an array index.- property_keys: ThinSlice<PropertyKey>,+ property_keys: BlockSlice<PropertyKey>,/// The functions the bytecode creates, which NewFunction and NewClass refer to by index.- shared_function_data: ThinSlice<Gc<SharedFunctionInstanceData>>,+ shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,/// The name of the function the executable is the body of, given when the function is first compiled. Empty for/// other code.name: FlyStringSlot,pub source_code: Option<Rc<SourceCode>>,+ /// The memory of the slices above, which get dropped before it.+ tables: SliceBlock,}// NB: Every function that was called has these bytes.@@ -1315,24 +1318,21 @@ impl Executable {/// for as long as the executable, which is what makes the address of the bytecode good to hand out.fn new_with_code(code: Arc<ExecutableData>,- constants: ThinSlice<Value>,- property_keys: ThinSlice<PropertyKey>,+ mut tables: SliceBlockBuilder,+ constants: BlockSlice<Value>,+ property_keys: BlockSlice<PropertyKey>,+ shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,_defer_gc: &DeferGc<'_>,) -> Self {let cache_counts = &code.cache_counts;- let property_lookup_caches: ThinSlice<PropertyLookupCache> = (0..cache_counts.property_lookup)- .map(|_| PropertyLookupCache::new())- .collect();- let global_variable_caches: ThinSlice<GlobalVariableCache> = (0..cache_counts.global_variable)- .map(|_| GlobalVariableCache::default())- .collect();- let environment_coordinate_caches: ThinSlice<Cell<EnvironmentCoordinate>> = (0..cache_counts- .environment_coordinate)- .map(|_| Cell::new(EnvironmentCoordinate::invalid()))- .collect();- let environment_shape_caches = (0..cache_counts.environment_shape)- .map(|_| NullableMember::null())- .collect();+ let property_lookup_caches =+ tables.slice((0..cache_counts.property_lookup).map(|_| PropertyLookupCache::new()));+ let global_variable_caches =+ tables.slice((0..cache_counts.global_variable).map(|_| GlobalVariableCache::default()));+ let environment_coordinate_caches =+ tables.slice((0..cache_counts.environment_coordinate).map(|_| Cell::new(EnvironmentCoordinate::invalid())));+ let environment_shape_caches =+ tables.slice((0..cache_counts.environment_shape).map(|_| NullableMember::null()));let number_of_locals = u32::try_from(code.local_variable_metadata.len()).expect("local count fits in u32");let registers_and_locals_count = code.number_of_registers + number_of_locals;let constant_count = u32::try_from(constants.len()).expect("constant count fits in u32");@@ -1353,9 +1353,7 @@ impl Executable {// The interpreter only reads the caches, which slow paths update through their cells.environment_coordinate_caches,};- let object_shape_caches = (0..cache_counts.object_shape)- .map(|_| ObjectShapeCache::default())- .collect();+ let object_shape_caches = tables.slice((0..cache_counts.object_shape).map(|_| ObjectShapeCache::default()));let feedback_slot_counts = FeedbackSlotCounts {arith: cache_counts.arith_feedback,value: cache_counts.value_feedback,@@ -1379,9 +1377,10 @@ impl Executable {has_dumped_feedback: Cell::new(false),is_strict_mode: code.is_strict,property_keys,- shared_function_data: ThinSlice::empty(),+ shared_function_data,name: FlyStringSlot::new(None),source_code: None,+ tables: tables.finish(),code,}}@@ -1394,21 +1393,18 @@ impl Executable {source_code: Option<&Rc<SourceCode>>,) -> Gc<Executable> {let executable = DeferGc::scope(vm, |_| {+ let mut tables = SliceBlock::builder(Self::size_of_tables(&data));let is_strict = data.is_strict;- let shared_function_data: ThinSlice<Gc<SharedFunctionInstanceData>> = data- .shared_function_data- .iter()- .map(|pending| {- SharedFunctionInstanceData::create_from_pending_shared_function_data(- vm,- pending,- is_strict,- source_code,- )- })- .collect();+ let shared_function_data = tables.slice(data.shared_function_data.iter().map(|pending| {+ SharedFunctionInstanceData::create_from_pending_shared_function_data(+ vm,+ pending,+ is_strict,+ source_code,+ )+ }));vm.heap()- .allocate(|defer_gc| Self::build(vm, data, shared_function_data, source_code, defer_gc))+ .allocate(|defer_gc| Self::build(vm, data, tables, shared_function_data, source_code, defer_gc))});vm.register_executable(executable);@@ -1419,10 +1415,24 @@ impl Executable {executable}+ /// The bytes of the tables that an executable of `code` has from the start.+ fn size_of_tables(code: &ExecutableData) -> usize {+ let cache_counts = &code.cache_counts;+ SliceBlock::room_for::<Gc<SharedFunctionInstanceData>>(code.shared_function_data.len())+ + SliceBlock::room_for::<PropertyKey>(code.property_key_table.len())+ + SliceBlock::room_for::<Value>(code.constants.len())+ + SliceBlock::room_for::<PropertyLookupCache>(cache_counts.property_lookup as usize)+ + SliceBlock::room_for::<GlobalVariableCache>(cache_counts.global_variable as usize)+ + SliceBlock::room_for::<Cell<EnvironmentCoordinate>>(cache_counts.environment_coordinate as usize)+ + SliceBlock::room_for::<NullableMember<EnvironmentShape>>(cache_counts.environment_shape as usize)+ + SliceBlock::room_for::<ObjectShapeCache>(cache_counts.object_shape as usize)+ }+fn build(vm: &Vm,mut data: Arc<ExecutableData>,- shared_function_data: ThinSlice<Gc<SharedFunctionInstanceData>>,+ mut tables: SliceBlockBuilder,+ shared_function_data: BlockSlice<Gc<SharedFunctionInstanceData>>,source_code: Option<&Rc<SourceCode>>,defer_gc: &DeferGc<'_>,) -> Executable {@@ -1431,29 +1441,26 @@ impl Executable {.iter().map(|blueprint| ClassBlueprint::create(vm, blueprint, source_code, defer_gc)).collect();- let property_keys: ThinSlice<PropertyKey> = match Arc::get_mut(&mut data) {- Some(code) => std::mem::take(&mut code.property_key_table)- .into_vec()- .into_iter()- .map(PropertyKey::from)- .collect(),- None => data.property_key_table.iter().cloned().map(PropertyKey::from).collect(),+ let property_keys = match Arc::get_mut(&mut data) {+ Some(code) => tables.slice(+ std::mem::take(&mut code.property_key_table)+ .into_vec()+ .into_iter()+ .map(PropertyKey::from),+ ),+ None => tables.slice(data.property_key_table.iter().cloned().map(PropertyKey::from)),};- let constants: ThinSlice<Value> = data- .constants- .iter()- .map(|constant| constant_value(vm, constant))- .collect();+ let constants = tables.slice(data.constants.iter().map(|constant| constant_value(vm, constant)));let template_object_caches: ThinSlice<Gc<TemplateObjectCache>> = (0..data.cache_counts.template_object).map(|_| TemplateObjectCache::create(vm)).collect();let object_property_iterator_caches = data.cache_counts.object_property_iterator;- let mut executable = Self::new_with_code(data, constants, property_keys, defer_gc);+ let mut executable =+ Self::new_with_code(data, tables, constants, property_keys, shared_function_data, defer_gc);if let Some(code) = Arc::get_mut(&mut executable.code) {code.release_link_inputs();}- executable.shared_function_data = shared_function_data;if !class_blueprints.is_empty() {executable.rare_data_mut().class_blueprints = class_blueprints;}diff --git a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rsindex e0df2e80e78..b0b8ec5fc32 100644--- a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs+++ b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs@@ -14,7 +14,8 @@ use core::cell::Cell;use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};use super::visitor::{Trace, Visitor};-use crate::layout::buffer::{InterpreterBuffer, ThinSlice};+use crate::layout::buffer::{BlockSlice, InterpreterBuffer, ThinSlice};+use crate::slice_block::THIN_SLICE_HEADER_SIZE;/// Mirrors AK::Vector's growth policy.fn padded_capacity(capacity: usize) -> usize {@@ -155,8 +156,6 @@ unsafe impl<T: Copy + Trace> Trace for InterpreterBuffer<T> {}}-const THIN_SLICE_HEADER_SIZE: usize = size_of::<usize>();-impl<T> ThinSlice<T> {const fn layout_for(length: usize) -> Layout {const { assert!(size_of::<T>() != 0 && align_of::<T>() <= THIN_SLICE_HEADER_SIZE) };@@ -287,3 +286,10 @@ unsafe impl<T: Trace> Trace for ThinSlice<T> {T::trace_slice(self.as_slice(), visitor);}}++// SAFETY: Visits every element.+unsafe impl<T: Trace> Trace for BlockSlice<T> {+ fn trace(&self, visitor: &mut Visitor) {+ T::trace_slice(self.as_slice(), visitor);+ }+}diff --git a/Libraries/LibJS/Rust/src/layout/buffer.rs b/Libraries/LibJS/Rust/src/layout/buffer.rsindex 4509c085041..4a5e37e7462 100644--- a/Libraries/LibJS/Rust/src/layout/buffer.rs+++ b/Libraries/LibJS/Rust/src/layout/buffer.rs@@ -47,3 +47,33 @@ impl<T> Default for ThinSlice<T> {Self::empty()}}++/// A [`ThinSlice`] that lives in a block of memory with other slices. Dropping it drops its elements and leaves the memory+/// to the block, so whatever holds both has to drop the slice first.+#[repr(transparent)]+pub struct BlockSlice<T> {+ pub data: *mut T,+ _elements: PhantomData<T>,+}++const _: () = assert!(size_of::<BlockSlice<u8>>() == 8);++impl<T> BlockSlice<T> {+ pub const fn empty() -> Self {+ Self::from_data(core::ptr::null_mut())+ }++ /// `data` must be null, or point at elements that have their length in front of them and that this slice owns.+ pub(crate) const fn from_data(data: *mut T) -> Self {+ Self {+ data,+ _elements: PhantomData,+ }+ }+}++impl<T> Default for BlockSlice<T> {+ fn default() -> Self {+ Self::empty()+ }+}diff --git a/Libraries/LibJS/Rust/src/layout/executable.rs b/Libraries/LibJS/Rust/src/layout/executable.rsindex a1b350c0b40..56ad363a3e0 100644--- a/Libraries/LibJS/Rust/src/layout/executable.rs+++ b/Libraries/LibJS/Rust/src/layout/executable.rs@@ -6,7 +6,7 @@use core::cell::Cell;-use super::buffer::ThinSlice;+use super::buffer::BlockSlice;use super::cell::CellHeaderTail;use super::feedback::ExecutableFeedbackHead;use super::property_lookup_cache::{EnvironmentCoordinate, GlobalVariableCache, PropertyLookupCache};@@ -36,10 +36,10 @@ pub struct ExecutableHead {pub jit_compile_state: Cell<u8>,/// Where the profiling interpreter records feedback for the optimizing JIT.pub feedback: ExecutableFeedbackHead,- pub constants: ThinSlice<Value>,- pub property_lookup_caches: ThinSlice<PropertyLookupCache>,- pub global_variable_caches: ThinSlice<GlobalVariableCache>,- pub environment_coordinate_caches: ThinSlice<Cell<EnvironmentCoordinate>>,+ pub constants: BlockSlice<Value>,+ pub property_lookup_caches: BlockSlice<PropertyLookupCache>,+ pub global_variable_caches: BlockSlice<GlobalVariableCache>,+ pub environment_coordinate_caches: BlockSlice<Cell<EnvironmentCoordinate>>,}const _: () = assert!(size_of::<ExecutableHead>() == 96);diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rsindex cf9a4bf629f..589243f54af 100644--- a/Libraries/LibJS/Rust/src/lib.rs+++ b/Libraries/LibJS/Rust/src/lib.rs@@ -143,6 +143,7 @@ pub mod runtime;pub mod script;#[cfg(not(test))]pub mod simdjson;+pub mod slice_block;#[cfg(not(test))]pub mod source_code;#[cfg(not(test))]diff --git a/Libraries/LibJS/Rust/src/slice_block.rs b/Libraries/LibJS/Rust/src/slice_block.rsnew file mode 100644index 00000000000..8a43f373299--- /dev/null+++ b/Libraries/LibJS/Rust/src/slice_block.rs@@ -0,0 +1,181 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Slices that share one block of memory.++use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};++use crate::layout::buffer::BlockSlice;++pub(crate) const THIN_SLICE_HEADER_SIZE: usize = size_of::<usize>();++/// The memory of slices that get made together and go away together, which takes one trip to the allocator instead of+/// one for each. The size of the block is in a word in front of the slices.+pub struct SliceBlock {+ memory: *mut u8,+}++// SAFETY: A block is memory that nothing else knows of, and it does nothing with the slices in it.+unsafe impl Send for SliceBlock {}+// SAFETY: As above, and a shared block has no operations.+unsafe impl Sync for SliceBlock {}++impl SliceBlock {+ pub const fn empty() -> Self {+ Self {+ memory: core::ptr::null_mut(),+ }+ }++ /// How much of a block a slice of `length` elements takes.+ pub const fn room_for<T>(length: usize) -> usize {+ const { assert!(size_of::<T>() != 0 && align_of::<T>() <= THIN_SLICE_HEADER_SIZE) };+ if length == 0 {+ return 0;+ }+ assert!(length <= isize::MAX as usize / size_of::<T>(), "a slice fits in memory");+ THIN_SLICE_HEADER_SIZE + (length * size_of::<T>()).next_multiple_of(THIN_SLICE_HEADER_SIZE)+ }++ const fn layout_for(size: usize) -> Layout {+ // SAFETY: The size fits in memory, since it is the sum of what slices take, and the alignment is a power of two.+ unsafe { Layout::from_size_align_unchecked(THIN_SLICE_HEADER_SIZE + size, THIN_SLICE_HEADER_SIZE) }+ }++ /// A block with `size` bytes for slices to be put in.+ pub fn builder(size: usize) -> SliceBlockBuilder {+ if size == 0 {+ return SliceBlockBuilder {+ block: Self::empty(),+ free: core::ptr::null_mut(),+ remaining: 0,+ };+ }+ let layout = Self::layout_for(size);+ // SAFETY: The layout has a non-zero size, with room for the size of the block in front of the slices.+ unsafe {+ let memory = alloc(layout);+ if memory.is_null() {+ handle_alloc_error(layout);+ }+ memory.cast::<usize>().write(size);+ SliceBlockBuilder {+ block: Self { memory },+ free: memory.add(THIN_SLICE_HEADER_SIZE),+ remaining: size,+ }+ }+ }+}++impl Default for SliceBlock {+ fn default() -> Self {+ Self::empty()+ }+}++impl Drop for SliceBlock {+ fn drop(&mut self) {+ if self.memory.is_null() {+ return;+ }+ // SAFETY: The size is where builder() put it, and that made the allocation with this layout.+ unsafe {+ let layout = Self::layout_for(self.memory.cast::<usize>().read());+ dealloc(self.memory, layout);+ }+ }+}++/// A block on its way, which slices get put into one at a time.+pub struct SliceBlockBuilder {+ block: SliceBlock,+ free: *mut u8,+ remaining: usize,+}++impl SliceBlockBuilder {+ /// Moves `elements` into the block. It has to have been made with room for them.+ pub fn slice<T>(&mut self, elements: impl ExactSizeIterator<Item = T>) -> BlockSlice<T> {+ let length = elements.len();+ let room = SliceBlock::room_for::<T>(length);+ assert!(room <= self.remaining, "a block has room for what goes in it");+ if length == 0 {+ return BlockSlice::empty();+ }+ // SAFETY: There is room for the length and for `length` elements, aligned for both, since everything in a block+ // takes a multiple of the size of the length.+ unsafe {+ self.free.cast::<usize>().write(length);+ let data = self.free.add(THIN_SLICE_HEADER_SIZE).cast::<T>();+ let mut written = 0;+ for element in elements.take(length) {+ data.add(written).write(element);+ written += 1;+ }+ assert_eq!(written, length, "an iterator yields as much as it says");+ self.free = self.free.add(room);+ self.remaining -= room;+ BlockSlice::from_data(data)+ }+ }++ /// The block, for as long as the slices in it live.+ pub fn finish(self) -> SliceBlock {+ self.block+ }+}++impl<T> BlockSlice<T> {+ pub fn as_slice(&self) -> &[T] {+ if self.data.is_null() {+ return &[];+ }+ // SAFETY: A non-null slice has its length in front of its initialized elements, which it owns.+ unsafe { ak::slice_from_raw_parts(self.data, self.data.cast::<usize>().sub(1).read()) }+ }++ pub fn as_mut_slice(&mut self) -> &mut [T] {+ if self.data.is_null() {+ return &mut [];+ }+ // SAFETY: A non-null slice has its length in front of its initialized elements, which it owns.+ unsafe { ak::slice_from_raw_parts_mut(self.data, self.data.cast::<usize>().sub(1).read()) }+ }+}++impl<T> core::ops::Deref for BlockSlice<T> {+ type Target = [T];++ fn deref(&self) -> &[T] {+ self.as_slice()+ }+}++impl<T> core::ops::DerefMut for BlockSlice<T> {+ fn deref_mut(&mut self) -> &mut [T] {+ self.as_mut_slice()+ }+}++impl<'a, T> IntoIterator for &'a BlockSlice<T> {+ type Item = &'a T;+ type IntoIter = core::slice::Iter<'a, T>;++ fn into_iter(self) -> Self::IntoIter {+ self.as_slice().iter()+ }+}++impl<T> Drop for BlockSlice<T> {+ fn drop(&mut self) {+ if core::mem::needs_drop::<T>() {+ let elements = core::ptr::from_mut(self.as_mut_slice());+ // SAFETY: The elements are initialized and nothing uses them after this.+ unsafe { core::ptr::drop_in_place(elements) };+ }+ }+}