Skip to content

Truly independent web browser

LibWasm: Give GC objects tighter cells

Andreas Kling4562f73464ca
diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rs
index dff2a245fa5..850ffce04d5 100644
--- a/Libraries/LibWasm/Engine/src/runtime/gc.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs
@@ -19,10 +19,10 @@ use super::heap::{
use super::{Store, TagAddress, Value};
pub use crate::abi::EXCEPTION_CELL_SIZE;
use crate::abi::{
- EXCEPTION_KINDS_OFFSET, EXCEPTION_LENGTH_OFFSET, EXCEPTION_PAYLOAD_OFFSET, EXCEPTION_TAG_OFFSET,
- OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET, RTT_KIND_ARRAY, RTT_KIND_FUNCTION,
- RTT_KIND_STRUCT, Rtt, STORAGE_32, STORAGE_64, STORAGE_FUNCTION_REFERENCE, STORAGE_I8, STORAGE_I16,
- STORAGE_REFERENCE, STORAGE_V128,
+ ARRAY_INLINE_DATA_OFFSET, EXCEPTION_KINDS_OFFSET, EXCEPTION_LENGTH_OFFSET, EXCEPTION_PAYLOAD_OFFSET,
+ EXCEPTION_TAG_OFFSET, MAX_INLINE_DATA_SIZE, OBJECT_DATA_OFFSET, OBJECT_LENGTH_OFFSET, RTT_KIND_ARRAY,
+ RTT_KIND_FUNCTION, RTT_KIND_STRUCT, Rtt, STORAGE_32, STORAGE_64, STORAGE_FUNCTION_REFERENCE, STORAGE_I8,
+ STORAGE_I16, STORAGE_REFERENCE, STORAGE_V128, STRUCT_INLINE_DATA_OFFSET,
};
use crate::types::{CompositeType, HeapType, StorageType, SubType, ValType, struct_layout};
use core::ffi::c_void;
@@ -174,35 +174,46 @@ pub(super) unsafe extern "C" fn rtt_destroy(cell: *mut c_void) {
/// Allocate a zeroed object of the type `rtt` with `data_size` bytes of data and, for an array, `length` elements.
/// Returns zero if the data is too large, or if there is no memory for it.
-pub fn allocate_object(heap: &Heap, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {
+///
+/// # Safety
+///
+/// `rtt` must be the runtime type of a struct or array type of the heap's store.
+pub unsafe fn allocate_object(heap: &Heap, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {
if data_size > MAX_OBJECT_DATA_SIZE {
return 0;
}
- let (cell, data) = match object_size_class(data_size as usize) {
- Some(class) => {
- let cell = heap.allocate_cell(CellType::Object(class));
- (cell, unsafe { cell.add(OBJECT_INLINE_DATA_OFFSET) })
- }
- None => {
- // The data lives outside the heap, after a word that holds the number of words after it. It counts towards
- // the next collection before the cell is allocated, which may collect.
- let words = data_size.div_ceil(8) as usize;
- let mut block = Vec::new();
- if block.try_reserve_exact(words + 1).is_err() {
- return 0;
- }
- block.resize(words + 1, 0u64);
- heap.did_allocate_external_memory((words + 1) * 8);
- let block = Box::leak(block.into_boxed_slice());
- block[0] = words as u64;
- let data = unsafe { block.as_mut_ptr().add(1) }.cast::<u8>();
- (heap.allocate_cell(CellType::Object(0)), data)
+ let is_array = unsafe { (*rtt).kind } == RTT_KIND_ARRAY;
+ let inline_data_offset = if is_array {
+ ARRAY_INLINE_DATA_OFFSET
+ } else {
+ STRUCT_INLINE_DATA_OFFSET
+ };
+ let (cell, data) = if data_size as usize <= MAX_INLINE_DATA_SIZE {
+ let class = object_size_class(inline_data_offset + data_size as usize);
+ let cell = heap.allocate_cell(CellType::Object(class));
+ (cell, unsafe { cell.add(inline_data_offset) })
+ } else {
+ // The data lives outside the heap, after a word that holds the number of words after it. It counts towards
+ // the next collection before the cell is allocated, which may collect.
+ let words = data_size.div_ceil(8) as usize;
+ let mut block = Vec::new();
+ if block.try_reserve_exact(words + 1).is_err() {
+ return 0;
}
+ block.resize(words + 1, 0u64);
+ heap.did_allocate_external_memory((words + 1) * 8);
+ let block = Box::leak(block.into_boxed_slice());
+ block[0] = words as u64;
+ let data = unsafe { block.as_mut_ptr().add(1) }.cast::<u8>();
+ let cell = heap.allocate_cell(CellType::Object(object_size_class(inline_data_offset)));
+ (cell, data)
};
unsafe {
write(cell, 0, rtt as u64);
write(cell, OBJECT_DATA_OFFSET, data as u64);
- write(cell, OBJECT_LENGTH_OFFSET, length);
+ if is_array {
+ write(cell, OBJECT_LENGTH_OFFSET, length);
+ }
}
cell as u64
}
@@ -211,7 +222,11 @@ pub fn allocate_object(heap: &Heap, rtt: *const Rtt, data_size: u64, length: u64
unsafe fn out_of_line_data(cell: *const c_void) -> Option<(*mut u64, usize)> {
unsafe {
let data: *mut u64 = read(cell, OBJECT_DATA_OFFSET);
- if data.cast::<u8>().cast_const() == cell.cast::<u8>().add(OBJECT_INLINE_DATA_OFFSET) {
+ // NB: The object's type may be gone already while the heap is destroyed, so this cannot ask whether it is an
+ // array. Data outside the heap is never right after the cell header.
+ let data_address = data.cast::<u8>().cast_const();
+ let cell = cell.cast::<u8>();
+ if data_address == cell.add(STRUCT_INLINE_DATA_OFFSET) || data_address == cell.add(ARRAY_INLINE_DATA_OFFSET) {
return None;
}
let block = data.sub(1);
@@ -433,8 +448,12 @@ impl Store {
}
/// Allocate a zeroed object of `data_size` bytes whose type is `rtt`, or return zero if it is too large.
- pub fn allocate_object(&mut self, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {
- allocate_object(&self.heap, rtt, data_size, length)
+ ///
+ /// # Safety
+ ///
+ /// `rtt` must be the runtime type of a struct or array type of the store.
+ pub unsafe fn allocate_object(&mut self, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {
+ unsafe { allocate_object(&self.heap, rtt, data_size, length) }
}
/// Allocate a struct of the type `identity` with the given field values, or return zero if there is no memory
@@ -442,7 +461,7 @@ impl Store {
pub fn allocate_struct(&mut self, identity: u32, fields: &[Value]) -> u64 {
let rtt: *const Rtt = self.rtt(identity);
let size = u64::from(unsafe { (*rtt).size });
- let object = self.allocate_object(rtt, size, 0);
+ let object = unsafe { self.allocate_object(rtt, size, 0) };
if object == 0 {
return 0;
}
@@ -461,7 +480,7 @@ impl Store {
pub fn allocate_array(&mut self, identity: u32, values: &[Value]) -> u64 {
let rtt: *const Rtt = self.rtt(identity);
let (element_size, kind) = unsafe { (u64::from((*rtt).size), *(*rtt).field_kinds) };
- let object = self.allocate_object(rtt, values.len() as u64 * element_size, values.len() as u64);
+ let object = unsafe { self.allocate_object(rtt, values.len() as u64 * element_size, values.len() as u64) };
if object == 0 {
return 0;
}
@@ -477,7 +496,7 @@ impl Store {
pub fn allocate_filled_array(&mut self, identity: u32, value: Value, length: u32) -> u64 {
let rtt: *const Rtt = self.rtt(identity);
let (element_size, kind) = unsafe { (u64::from((*rtt).size), *(*rtt).field_kinds) };
- let object = self.allocate_object(rtt, u64::from(length) * element_size, u64::from(length));
+ let object = unsafe { self.allocate_object(rtt, u64::from(length) * element_size, u64::from(length)) };
if object == 0 {
return 0;
}
diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rs
index b29c8577c4d..0676c4ddb6a 100644
--- a/Libraries/LibWasm/Engine/src/runtime/heap.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs
@@ -185,11 +185,14 @@ pub enum CellType {
Entity(usize),
}
-pub use crate::abi::OBJECT_DATA_SIZE_CLASSES;
-
-/// The size class of objects with `size` bytes of data, or None if the data does not fit inline.
-pub fn object_size_class(size: usize) -> Option<usize> {
- OBJECT_DATA_SIZE_CLASSES.iter().position(|&class| class >= size)
+pub use crate::abi::OBJECT_CELL_SIZE_CLASSES;
+
+/// The size class of object cells of at least `size` bytes, which is at most the largest class.
+pub fn object_size_class(size: usize) -> usize {
+ OBJECT_CELL_SIZE_CLASSES
+ .iter()
+ .position(|&class| class >= size)
+ .expect("object cells are at most the largest class")
}
/// The allocators of the runtime's cell types, which LibGC requires to outlive every heap, so there is one set of
@@ -260,7 +263,12 @@ fn type_info(cell_type: CellType) -> (&'static CellTypeInfo, &'static str) {
};
let info = Box::leak(Box::new(CellTypeInfo {
cell_size: cell_size(cell_type) as u32,
- alignment: 16,
+ // NB: Objects come in sizes 8 bytes apart, and their fields are aligned to at most 8 bytes.
+ alignment: if matches!(cell_type, CellType::Object(_)) {
+ 8
+ } else {
+ 16
+ },
kind: CELL_KIND_OTHER,
visit_edges,
finalize: None,
@@ -278,7 +286,7 @@ impl Allocators {
unsafe { (interface.gc_allocator_create)(info, name.as_ptr().cast(), name.len(), core::ptr::null()) }
};
Self {
- objects: (0..OBJECT_DATA_SIZE_CLASSES.len())
+ objects: (0..OBJECT_CELL_SIZE_CLASSES.len())
.map(|class| create(CellType::Object(class)))
.collect(),
rtt: create(CellType::Rtt),
@@ -304,7 +312,7 @@ impl Allocators {
/// The size of a cell of a type.
pub fn cell_size(cell_type: CellType) -> usize {
match cell_type {
- CellType::Object(class) => crate::abi::OBJECT_INLINE_DATA_OFFSET + OBJECT_DATA_SIZE_CLASSES[class],
+ CellType::Object(class) => OBJECT_CELL_SIZE_CLASSES[class],
CellType::Rtt => CELL_HEADER_SIZE + size_of::<crate::abi::Rtt>().next_multiple_of(16),
CellType::Exception => super::gc::EXCEPTION_CELL_SIZE,
CellType::StoreRoot => 32,
diff --git a/Libraries/LibWasm/JIT/src/builder/gc.rs b/Libraries/LibWasm/JIT/src/builder/gc.rs
index 1502a25f09a..d7be4905953 100644
--- a/Libraries/LibWasm/JIT/src/builder/gc.rs
+++ b/Libraries/LibWasm/JIT/src/builder/gc.rs
@@ -7,10 +7,10 @@
//! The GC instructions (the `0xFB` prefix): structs, arrays, i31 references, and tests and casts of references.
//!
//! Objects are cells of the runtime's heap (see `abi::Rtt`): the Rtt first, the data's address at OBJECT_DATA_OFFSET
-//! and an array's length at OBJECT_LENGTH_OFFSET. Data of up to `MAX_INLINE_DATA_SIZE` bytes is inline at
-//! OBJECT_INLINE_DATA_OFFSET, so a struct's fields are at constant offsets from the object where the struct is small
-//! enough and its type is final. Fields take `StorageType::object_field_size()` bytes, at the offsets `struct_layout`
-//! gives them: the runtime's layout, which `abi` and `types` define for both.
+//! and an array's length at OBJECT_LENGTH_OFFSET. Data of up to `MAX_INLINE_DATA_SIZE` bytes is inline, at
+//! STRUCT_INLINE_DATA_OFFSET or ARRAY_INLINE_DATA_OFFSET, so a struct's fields are at constant offsets from the object
+//! where the struct is small enough and its type is final. Fields take `StorageType::object_field_size()` bytes, at
+//! the offsets `struct_layout` gives them: the runtime's layout, which `abi` and `types` define for both.
//!
//! GC references in compiled frames need nothing special: the collector scans the stack conservatively and recognizes
//! pointers into cells, and every allocation is a call of the runtime, around which values live in stack slots or in
@@ -22,8 +22,8 @@ use super::Builder;
use crate::ir::{Func, HeapTest, Helper, LoadKind, Node, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Type, Value};
use libwasm_module::Module;
use libwasm_module::abi::{
- InstanceData, MAX_INLINE_DATA_SIZE, OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET,
- TRAP_MEMORY_OUT_OF_BOUNDS, TRAP_NULL_REFERENCE, TRAP_TABLE_OUT_OF_BOUNDS,
+ ARRAY_INLINE_DATA_OFFSET, InstanceData, MAX_INLINE_DATA_SIZE, OBJECT_DATA_OFFSET, OBJECT_LENGTH_OFFSET,
+ STRUCT_INLINE_DATA_OFFSET, TRAP_MEMORY_OUT_OF_BOUNDS, TRAP_NULL_REFERENCE, TRAP_TABLE_OUT_OF_BOUNDS,
};
use libwasm_module::opcode::gc::*;
use libwasm_module::opcode::simd::I64X2_EXTRACT_LANE;
@@ -94,11 +94,11 @@ impl Builder {
Some(self.field_offset(module, type_index, count))
}
- /// Where the data of an object with `size` bytes of it is: the object and the offset of its inline data, or the
- /// address of its data.
- fn object_data(func: &mut Func, object: Value, size: Option<u32>) -> (Value, u32) {
+ /// Where the data of an object with `size` bytes of it is, with `inline_data_offset` where it would be inline: the
+ /// object and the offset of its inline data, or the address of its data.
+ fn object_data(func: &mut Func, object: Value, size: Option<u32>, inline_data_offset: usize) -> (Value, u32) {
if size.is_some_and(|size| size as usize <= MAX_INLINE_DATA_SIZE) {
- return (object, OBJECT_INLINE_DATA_OFFSET as u32);
+ return (object, inline_data_offset as u32);
}
let data = Self::append(
func,
@@ -251,7 +251,7 @@ impl Builder {
let zero = self.constant(func, Type::I64, 0);
let object = self.allocate(func, first, size_value, zero);
if !values.is_empty() {
- let (base, data_offset) = Self::object_data(func, object, Some(size));
+ let (base, data_offset) = Self::object_data(func, object, Some(size), STRUCT_INLINE_DATA_OFFSET);
for (index, &value) in values.iter().enumerate() {
if self.is_zero(func, value) {
continue;
@@ -267,7 +267,7 @@ impl Builder {
let object = func.resolve(self.pop());
Self::check_null(func, object);
let size = self.struct_data_size(module, first);
- let (base, data_offset) = Self::object_data(func, object, size);
+ let (base, data_offset) = Self::object_data(func, object, size, STRUCT_INLINE_DATA_OFFSET);
let offset = data_offset + self.field_offset(module, first, second);
let storage = struct_fields(module, first)[second as usize].storage;
let value = self.load_field(func, base, offset, storage, sub_opcode == STRUCT_GET_S);
@@ -278,7 +278,7 @@ impl Builder {
let object = func.resolve(self.pop());
Self::check_null(func, object);
let size = self.struct_data_size(module, first);
- let (base, data_offset) = Self::object_data(func, object, size);
+ let (base, data_offset) = Self::object_data(func, object, size, STRUCT_INLINE_DATA_OFFSET);
let offset = data_offset + self.field_offset(module, first, second);
let storage = struct_fields(module, first)[second as usize].storage;
self.store_at(func, size_log2(storage), base, offset, value);
@@ -311,7 +311,7 @@ impl Builder {
let size = self.constant(func, Type::I64, u64::from(data_size));
let length = self.constant(func, Type::I64, u64::from(second));
let array = self.allocate(func, first, size, length);
- let (base, data_offset) = Self::object_data(func, array, Some(data_size));
+ let (base, data_offset) = Self::object_data(func, array, Some(data_size), ARRAY_INLINE_DATA_OFFSET);
for (index, &value) in values.iter().enumerate() {
if self.is_zero(func, value) {
continue;
diff --git a/Libraries/LibWasm/Module/src/abi.rs b/Libraries/LibWasm/Module/src/abi.rs
index b074cc01d91..c960a052dbb 100644
--- a/Libraries/LibWasm/Module/src/abi.rs
+++ b/Libraries/LibWasm/Module/src/abi.rs
@@ -220,7 +220,9 @@ pub struct ExecutionContext {
///
/// A GC object is a cell that starts with the address of its type's Rtt, followed by the cell header LibGC owns, the
/// address of its data (OBJECT_DATA_OFFSET), and an array's length (OBJECT_LENGTH_OFFSET). The data is a struct's
-/// fields or an array's elements, inline at OBJECT_INLINE_DATA_OFFSET if they fit there and outside the heap otherwise.
+/// fields or an array's elements. Up to MAX_INLINE_DATA_SIZE bytes of it are inline, right after the address for a
+/// struct (STRUCT_INLINE_DATA_OFFSET) and after the length for an array (ARRAY_INLINE_DATA_OFFSET), and larger data is
+/// outside the heap.
#[repr(C)]
pub struct Rtt {
pub kind: u32,
@@ -256,16 +258,50 @@ pub const STORAGE_FUNCTION_REFERENCE: u8 = 6;
pub const OBJECT_DATA_OFFSET: usize = 16;
pub const OBJECT_LENGTH_OFFSET: usize = 24;
-pub const OBJECT_INLINE_DATA_OFFSET: usize = 32;
-
-/// The sizes of the data a GC object can keep inline, the size classes of the runtime's heap. Larger data is
-/// allocated outside of the heap.
-pub const OBJECT_DATA_SIZE_CLASSES: [usize; 17] = [
- 0, 16, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096,
-];
+pub const STRUCT_INLINE_DATA_OFFSET: usize = 24;
+pub const ARRAY_INLINE_DATA_OFFSET: usize = 32;
/// The most data an object keeps inline.
-pub const MAX_INLINE_DATA_SIZE: usize = OBJECT_DATA_SIZE_CLASSES[OBJECT_DATA_SIZE_CLASSES.len() - 1];
+pub const MAX_INLINE_DATA_SIZE: usize = 4096;
+
+/// The sizes of the cells of GC objects, the size classes of the runtime's heap: every 8 bytes up to 128, then about a
+/// quarter apart, up to the cell of an array with the most inline data.
+pub const OBJECT_CELL_SIZE_CLASSES: [usize; 34] = [
+ 24,
+ 32,
+ 40,
+ 48,
+ 56,
+ 64,
+ 72,
+ 80,
+ 88,
+ 96,
+ 104,
+ 112,
+ 120,
+ 128,
+ 144,
+ 160,
+ 176,
+ 192,
+ 224,
+ 256,
+ 288,
+ 320,
+ 384,
+ 448,
+ 512,
+ 640,
+ 768,
+ 1024,
+ 1280,
+ 1536,
+ 2048,
+ 2560,
+ 3072,
+ ARRAY_INLINE_DATA_OFFSET + MAX_INLINE_DATA_SIZE,
+];
// NB: The bytes a field or element takes in an object's data are `StorageType::object_field_size()`, and the offsets of
// a struct's fields come from `struct_layout()` (types.rs).