Skip to content

Truly independent web browser

LibJS: Find a cell's class through its block

Shannon Booth57685380cf27
diff --git a/Libraries/LibJS/Console.cpp b/Libraries/LibJS/Console.cpp
index 95a2e05fa74..d8535e768a4 100644
--- a/Libraries/LibJS/Console.cpp
+++ b/Libraries/LibJS/Console.cpp
@@ -215,7 +215,7 @@ void Console::report_exception(Utf16View name, Utf16View message, ErrorData cons
void Console::report_exception(Utf16View name, Utf16View message, Utf16View filename, u32 line, u32 column, bool in_promise) const
{
- js_console_report_exception_with_location(console_to_abi(*this), utf16_view_to_abi(name), utf16_view_to_abi(message), utf16_view_to_abi(filename), line, column, in_promise);
+ js_console_report_exception_with_location(vm_to_abi(vm()), console_to_abi(*this), utf16_view_to_abi(name), utf16_view_to_abi(message), utf16_view_to_abi(filename), line, column, in_promise);
}
static GC::Ref<EngineConsoleClient> create_engine_console_client(Console& console, ConsoleClient& client)
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs b/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs
index 352a25301e3..d691811f2e9 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/array_iterators.rs
@@ -42,8 +42,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let layout = self.runtime.layout;
let other = self.masm.new_label();
let fail = if invert { target } else { other };
- // NB: Cells start with the pointer to their class.
- self.masm.load64(scratch, &Address::new(object, 0));
+ self.emit_load_class(scratch, object);
self.masm
.branch64_imm(Condition::NotEqual, scratch, layout.array_iterator_class as i64, fail);
self.masm
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs b/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs
index 6c5bf98bf7f..b6bbfda6864 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/environments.rs
@@ -108,7 +108,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
&Address::new(environment, layout.environment_declarative as i32),
);
self.masm.branch_test32(Condition::Zero, scratch, 0xFF, fail);
- self.masm.load64(scratch, &Address::new(environment, 0));
+ self.emit_load_class(scratch, environment);
self.masm.move_imm64(shape, layout.module_environment_class);
self.masm.branch64(Condition::Equal, scratch, shape, fail);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index d6aa66edcfd..635054b8928 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -73,6 +73,7 @@ use crate::asm::GprSet;
use crate::asm::Label;
use crate::asm::MachineFrame;
use crate::asm::PortableMacroAssembler;
+use crate::asm::Scale;
use crate::asm::disassembler;
use crate::bytecode::DecodedInstruction;
use crate::bytecode::EXCEPTION_REGISTER;
@@ -1873,7 +1874,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.bind(walk);
// Only objects with the ordinary [[GetPrototypeOf]] have the
// prototype of their shape.
- self.masm.load64(scratch, &Address::new(object, 0));
+ self.emit_load_class(scratch, object);
self.masm
.load64(scratch, &Address::new(scratch, layout.class_object_methods as i32));
self.masm.branch64_memory_imm(
@@ -2110,6 +2111,24 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.add64_imm(dst, dst, self.runtime.heap_region_base as i64);
}
+ /// `dst = the class of the cell at cell`, which the cell's block holds,
+ /// or the cell keeps after itself if its block is one of an allocator
+ /// that classes share.
+ fn emit_load_class(&mut self, dst: Gpr, cell: Gpr) {
+ assert_ne!(dst, cell, "the cell is read after its block");
+ let layout = self.runtime.layout;
+ let done = self.masm.new_label();
+ self.masm.and64_imm(dst, cell, layout.cell_block_mask);
+ self.masm
+ .load64(dst, &Address::new(dst, layout.block_class_offset as i32));
+ self.masm
+ .branch_test64(Condition::Zero, dst, layout.block_class_tail_tag, done);
+ let cell_size = layout.class_cell_size as i32 - layout.block_class_tail_tag as i32;
+ self.masm.load32(dst, &Address::new(dst, cell_size));
+ self.masm.load64(dst, &Address::indexed(cell, dst, Scale::One, 0));
+ self.masm.bind(done);
+ }
+
/// `dst = heap_region_base + (dst << 3)`, the cell pointer the
/// compressed cell pointer in `dst` (zero-extended, not null) names,
/// which is in the heap region whatever its 32 bits are.
@@ -2331,8 +2350,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
BranchCondition::Float64(_) => unreachable!("float64 comparisons branch above"),
BranchCondition::ArrayIterator => self.emit_branch_on_array_iterator(input, target, invert),
BranchCondition::GeneratorObject => {
- // NB: Cells start with the pointer to their class.
- self.masm.load64(scratch, &Address::new(input, 0));
+ self.emit_load_class(scratch, input);
let class = self.runtime.layout.generator_object_class as i64;
self.masm.branch64_imm(when(Condition::Equal), scratch, class, target);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs
index e4fb36885d7..9d07adfd08e 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs
@@ -542,20 +542,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.move_imm64(output, value::TRUE);
self.masm.jump(done);
self.masm.bind(absent);
- // NB: Plain objects, which start with the virtual table pointer
- // of their class like the template of new plain objects, have
- // the own string-keyed properties of their shapes. Their
- // prototypes may have it, which `in` leaves to the runtime.
- match self.runtime.object_allocation.template.first() {
- Some(&plain_object_vtable) if own => {
- self.emit_unbox_cell(entry, object);
- self.masm.move_imm64(scratch, plain_object_vtable);
- self.masm
- .branch64_memory(Condition::NotEqual, &Address::new(entry, 0), scratch, probe);
- self.masm.move_imm64(output, value::FALSE);
- self.masm.jump(done);
- }
- _ => self.masm.jump(probe),
+ // NB: Plain objects have the own string-keyed properties of their
+ // shapes. Their prototypes may have it, which `in` leaves to
+ // the runtime.
+ let object_class = layout.object_class;
+ if own && object_class != 0 {
+ self.emit_unbox_cell(entry, object);
+ self.emit_load_class(scratch, entry);
+ self.masm
+ .branch64_imm(Condition::NotEqual, scratch, object_class as i64, probe);
+ self.masm.move_imm64(output, value::FALSE);
+ self.masm.jump(done);
+ } else {
+ self.masm.jump(probe);
}
}
self.bind_probe_failure(output, value::EMPTY, failure, done);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
index bdcfe100370..d60444e973c 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
@@ -235,20 +235,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let scratch = self.pinned.scratch;
let layout = self.runtime.layout;
let offsets = self.runtime.offsets;
- // NB: Plain objects start with the virtual table pointer of their
- // class, like the template of new plain objects.
- let Some(&plain_object_vtable) = self.runtime.object_allocation.template.first() else {
+ if layout.object_class == 0 {
self.masm.jump(miss);
return;
- };
+ }
let cacheable = self.masm.new_label();
- self.masm.move_imm64(scratch, plain_object_vtable);
- self.masm
- .branch64_memory(Condition::Equal, &Address::new(object, 0), scratch, cacheable);
- for class in [layout.string_object_class, layout.string_prototype_class] {
+ self.emit_load_class(shape, object);
+ for class in [
+ layout.object_class,
+ layout.string_object_class,
+ layout.string_prototype_class,
+ ] {
self.masm.move_imm64(scratch, class);
- self.masm
- .branch64_memory(Condition::Equal, &Address::new(object, 0), scratch, cacheable);
+ self.masm.branch64(Condition::Equal, shape, scratch, cacheable);
}
let flags =
self.runtime.dynamic_calls.object_flag_is_ecmascript_function | layout.object_flag_has_magical_length;
@@ -261,8 +260,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
if layout.default_is_cacheable_for_property_absence == 0 || layout.class_object_methods == 0 {
self.masm.jump(miss);
} else {
- // NB: Objects start with their class.
- self.masm.load64(shape, &Address::new(object, 0));
self.masm
.load64(shape, &Address::new(shape, layout.class_object_methods as i32));
self.masm
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
index f7db0a797d7..dd1d304e1ff 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
@@ -139,9 +139,9 @@ extern "C" fn marker_record(vm: *mut u64, pc: u32, instruction: *const u8, outpu
static NO_PROPERTY_CACHES: [u64; 16] = [0; 16];
-/// Word 0 of fake plain objects, like the virtual table pointer of real
-/// ones.
-const PLAIN_OBJECT_VTABLE: u64 = 0x7000;
+/// The class of fake plain objects, in their word 0 (see
+/// `cell_block_mask`).
+const PLAIN_OBJECT_CLASS: u64 = 0x7000;
/// Word 0 of fake String objects and of the fake `%String.prototype%`, like
/// the classes of real ones.
@@ -292,7 +292,7 @@ fn marker_runtime() -> RuntimeInfo {
runtime.object_allocation.inline_storage_offset = 64;
runtime.object_allocation.inline_capacity_offset = 40;
runtime.offsets.shape_dictionary_generation = 84;
- runtime.object_allocation.template = vec![PLAIN_OBJECT_VTABLE];
+ runtime.object_allocation.template = vec![PLAIN_OBJECT_CLASS];
runtime.dynamic_calls.object_flag_is_ecmascript_function = FLAG_IS_ECMASCRIPT_FUNCTION;
for opcode in [O::Increment, O::Decrement, O::PostfixIncrement, O::PostfixDecrement] {
set(opcode, marker_record as *const () as u64);
@@ -1190,6 +1190,7 @@ fn fake_object_layout() -> RuntimeLayout {
indexed_storage_kind_holey: HOLEY,
object_flag_is_extensible: FLAG_IS_EXTENSIBLE,
object_flag_has_magical_length: FLAG_HAS_MAGICAL_LENGTH,
+ object_class: PLAIN_OBJECT_CLASS,
string_object_class: STRING_OBJECT_CLASS,
string_prototype_class: STRING_PROTOTYPE_CLASS,
object_flag_may_interfere: FLAG_MAY_INTERFERE,
@@ -1314,6 +1315,12 @@ fn fake_object_layout() -> RuntimeLayout {
property_lookup_cache_entry_type_add_own_property: 1,
property_lookup_cache_entry_type_get_own_property: 3,
property_lookup_cache_entry_type_change_own_property: 2,
+ // NB: Fake cells keep their class in their first word: the mask
+ // keeps every bit, so the block of a fake cell is the cell.
+ cell_block_mask: u64::MAX,
+ block_class_offset: 0,
+ block_class_tail_tag: 1,
+ class_cell_size: 0,
class_object_methods: 8,
object_methods_get_prototype_of: 0,
object_methods_is_cacheable_for_property_absence: 0,
@@ -4161,7 +4168,7 @@ fn get_by_value_through_megamorphic_property_caches() {
fn get_by_id_of_missing_properties_through_property_caches() {
let mut fake = FakeCachedObject::new(&[value::int32(10)]);
fake.set_entry(6, 0, false);
- fake.object[0] = PLAIN_OBJECT_VTABLE;
+ fake.object[0] = PLAIN_OBJECT_CLASS;
assert_eq!(fake.get(fake.value()), value::UNDEFINED);
// Objects of other classes may have properties their shapes do not
// describe: the probe, then the slow path. ECMAScript functions, arrays
@@ -4178,7 +4185,7 @@ fn get_by_id_of_missing_properties_through_property_caches() {
assert_eq!(fake.get(fake.value()), value::UNDEFINED);
}
// Shapes with a prototype need a valid prototype chain.
- fake.object[0] = PLAIN_OBJECT_VTABLE;
+ fake.object[0] = PLAIN_OBJECT_CLASS;
fake.shape[0] = 0x8000;
assert_eq!(fake.get(fake.value()), MARKER);
let mut validity = vec![1u64];
@@ -4300,7 +4307,7 @@ fn get_by_id_of_strings_through_megamorphic_property_caches() {
fn keyed_accesses_of_missing_and_added_properties_through_property_caches() {
const ENTRY_WORDS: usize = 8;
let mut fake = FakeCachedObject::new(&[value::int32(10), value::int32(11), value::EMPTY]);
- fake.object[0] = PLAIN_OBJECT_VTABLE;
+ fake.object[0] = PLAIN_OBJECT_CLASS;
fake.object[1] = u64::from(FLAG_IS_EXTENSIBLE);
let shape = fake.shape.as_ptr() as u64;
let key = u64::from(STRING_TAG) << 48 | 0x5000;
@@ -4355,7 +4362,7 @@ fn keyed_accesses_of_missing_and_added_properties_through_property_caches() {
assert_eq!(get(&fake, other_key), MARKER);
fake.object[0] = 0;
assert_eq!(get(&fake, key), MARKER);
- fake.object[0] = PLAIN_OBJECT_VTABLE;
+ fake.object[0] = PLAIN_OBJECT_CLASS;
// Changes of existing properties.
set_entry(&mut data, 2, 1, 0, shape);
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 6f8706b83b2..1953e0e28ce 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -1663,8 +1663,9 @@ pub struct RuntimeLayout {
pub object_flag_is_extensible: u16,
/// `Object::Flag::HasMagicalLengthProperty`, which only arrays have.
pub object_flag_has_magical_length: u16,
- /// The classes (pointers) of `StringObject`s and of `%String.prototype%`,
- /// which start their cells.
+ /// The classes (pointers) of plain objects, of `StringObject`s and of
+ /// `%String.prototype%`.
+ pub object_class: u64,
pub string_object_class: u64,
pub string_prototype_class: u64,
/// `Object::Flag::MayInterfereWithIndexedPropertyAccess`.
@@ -1914,8 +1915,17 @@ pub struct RuntimeLayout {
pub property_lookup_cache_entry_type_get_own_property: u32,
/// `PropertyLookupCache::Entry::Type::ChangeOwnProperty`.
pub property_lookup_cache_entry_type_change_own_property: u32,
- /// `Class::object_methods`, of the class every cell starts with, or 0 if
- /// JIT code does not walk prototype chains.
+ /// The mask that rounds the address of a cell down to its block, and
+ /// where the block holds the class of its cells. A block of an allocator
+ /// that classes share holds that class with `block_class_tail_tag` set,
+ /// and each cell keeps its own class right after the
+ /// `Class::type_info.cell_size` bytes of that class.
+ pub cell_block_mask: u64,
+ pub block_class_offset: u32,
+ pub block_class_tail_tag: u64,
+ pub class_cell_size: u32,
+ /// `Class::object_methods`, or 0 if JIT code does not walk prototype
+ /// chains.
pub class_object_methods: u32,
/// `ObjectMethods::internal_get_prototype_of`, which is null for objects
/// whose prototype is the prototype of their shape.
diff --git a/Libraries/LibJS/Runtime/ErrorData.h b/Libraries/LibJS/Runtime/ErrorData.h
index f71688c34fe..24a9c977b9f 100644
--- a/Libraries/LibJS/Runtime/ErrorData.h
+++ b/Libraries/LibJS/Runtime/ErrorData.h
@@ -35,9 +35,9 @@ enum CompactTraceback {
};
// The [[ErrorData]] of an Error or of an ErrorDataCell: the call stack it was created on. The runtime keeps it inside
-// the cell that has it, so a reference to an ErrorData is to the runtime's error data, or for the ErrorData that an
-// ErrorDataCell derives from, to the cell itself, which the runtime takes in its place. An Error converts to the
-// ErrorData inside it.
+// the cell that has it, so a reference to an ErrorData is to the runtime's error data, or for the ErrorData of an
+// ErrorDataCell, to the cell itself, which the runtime takes in its place. An Error converts to the ErrorData inside
+// it.
class JS_API ErrorData {
AK_MAKE_NONCOPYABLE(ErrorData);
AK_MAKE_NONMOVABLE(ErrorData);
@@ -54,11 +54,14 @@ protected:
};
// The error data of a host object that is not an Error, such as a DOMException, kept in a cell of its own.
-class JS_API ErrorDataCell final
- : public EngineCell
- , public ErrorData {
+// NB: ErrorDataCell can't derive from ErrorData, as the MSVC ABI places an empty second base after the first one, so
+// the ErrorData would not be at the address of the cell.
+class JS_API ErrorDataCell final : public EngineCell {
public:
static GC::Ref<ErrorDataCell> capture(VM&);
+
+ ErrorData& error_data() { return *reinterpret_cast<ErrorData*>(this); }
+ ErrorData const& error_data() const { return *reinterpret_cast<ErrorData const*>(this); }
};
static_assert(GC::IsForeignCellHandle<ErrorDataCell>);
diff --git a/Libraries/LibJS/Runtime/Object.h b/Libraries/LibJS/Runtime/Object.h
index bc6399b823c..43267a4b067 100644
--- a/Libraries/LibJS/Runtime/Object.h
+++ b/Libraries/LibJS/Runtime/Object.h
@@ -241,12 +241,19 @@ protected:
private:
static_assert(JS_LAYOUT_OBJECT_SHAPE_SIZE == sizeof(u32));
- static_assert(JS_LAYOUT_CELL_CLASS_SIZE == sizeof(void*));
static_assert(JS_LAYOUT_CLASS_ID_SIZE == sizeof(u16));
static_assert(JS_LAYOUT_CLASS_PARENT_SIZE == sizeof(void*));
- // The runtime's class of the object, which the first word of every cell points to.
- u8 const* engine_class() const { return engine_field<u8 const*>(JS_LAYOUT_CELL_CLASS_OFFSET); }
+ // The runtime's class of the object, which the object's block holds, unless the block's class is tagged as one that
+ // classes share an allocator of: then the object keeps its class in its last word.
+ u8 const* engine_class() const
+ {
+ auto const* block = GC::HeapBlockBase::from_cell(GC::as_cell(this));
+ auto const* engine_class = static_cast<u8 const*>(block->foreign_type());
+ if (!(bit_cast<FlatPtr>(engine_class) & JS_LAYOUT_BLOCK_CLASS_TAIL_TAG))
+ return engine_class;
+ return engine_field<u8 const*>(block->type_info().cell_size - sizeof(void*));
+ }
static u16 engine_class_id_of(u8 const* engine_class)
{
diff --git a/Libraries/LibJS/Rust/generate/layout_header.rs b/Libraries/LibJS/Rust/generate/layout_header.rs
index d82bc0ff49b..5d63d347828 100644
--- a/Libraries/LibJS/Rust/generate/layout_header.rs
+++ b/Libraries/LibJS/Rust/generate/layout_header.rs
@@ -286,7 +286,6 @@ pub fn generate() -> LayoutHeader {
let mut w = HeaderWriter::new();
w.section("Cell header, at the start of every cell");
- offset!(w, "CELL_CLASS", CellHeader, class);
offset!(w, "CELL_MARK", CellHeader, mark);
offset!(w, "CELL_STATE", CellHeader, state);
offset!(w, "CELL_KIND", CellHeader, kind);
@@ -294,7 +293,8 @@ pub fn generate() -> LayoutHeader {
w.define(&format!("CELL_KIND_{}", cell_kind_name(kind)), kind as u8);
}
- w.section("Class, which the first word of a cell points to: its id and the class it extends");
+ w.section("Class, which the block of a cell holds: its id and the class it extends");
+ w.define("BLOCK_CLASS_TAIL_TAG", BLOCK_CLASS_TAIL_TAG);
offset!(w, "CLASS_ID", ClassLayout, id);
offset!(w, "CLASS_PARENT", ClassLayout, parent);
diff --git a/Libraries/LibJS/Rust/src/embedding/abi_types.rs b/Libraries/LibJS/Rust/src/embedding/abi_types.rs
index 1d1dd854ecf..a119998d669 100644
--- a/Libraries/LibJS/Rust/src/embedding/abi_types.rs
+++ b/Libraries/LibJS/Rust/src/embedding/abi_types.rs
@@ -28,7 +28,7 @@ use core::ptr::NonNull;
use ak::Utf16String;
-use crate::gc::class::Extends;
+use crate::gc::class::{Extends, GcCell, block_class_pointer_at};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::host_class::{
@@ -40,7 +40,7 @@ use crate::layout::value::Value;
use crate::runtime::big_int::BigInt;
use crate::runtime::completion::{Throw, ThrowCompletionOr};
use crate::runtime::error::ErrorKind;
-use crate::runtime::error_data::{ErrorData, ErrorDataCell};
+use crate::runtime::error_data::{ERROR_DATA_CELL_ERROR_DATA_OFFSET, ErrorData, ErrorDataCell};
use crate::runtime::primitive_string::PrimitiveString;
use crate::runtime::promise_capability::PromiseCapability;
use crate::runtime::property_key::PropertyKey;
@@ -116,15 +116,34 @@ impl CellAbi for JSPromiseCapability {
type Cell = PromiseCapability;
}
+/// The error data of an error data cell goes to the embedder as the cell (see error_data_from_abi).
pub fn error_data_into_abi(error_data: &ErrorData) -> *const JSErrorData {
- core::ptr::from_ref(error_data).cast()
+ let address = core::ptr::from_ref(error_data).cast::<u8>();
+ // SAFETY: Error data lives in a cell.
+ if core::ptr::eq(unsafe { block_class_pointer_at(address) }, ErrorDataCell::CLASS) {
+ return address.wrapping_sub(ERROR_DATA_CELL_ERROR_DATA_OFFSET).cast();
+ }
+ address.cast()
}
+/// The error data that the embedder passes as a JSErrorData: the error data of an Error, or an error data cell, whose
+/// address the C++ ErrorDataCell gives as the address of its ErrorData. Error data in an error data cell reaches the
+/// embedder as the cell (see error_data_into_abi), so an address in a block of error data cells is the address of a
+/// cell.
+///
/// # Safety
///
-/// `error_data` must point to the error data of a cell that stays alive for `'cell`.
+/// `error_data` must be the error data or the error data cell of a cell that stays alive for `'cell`.
pub unsafe fn error_data_from_abi<'cell>(error_data: *const JSErrorData) -> &'cell ErrorData {
assert!(!error_data.is_null(), "the embedder passes error data");
+ // SAFETY: Error data lives in a cell.
+ if core::ptr::eq(
+ unsafe { block_class_pointer_at(error_data.cast()) },
+ ErrorDataCell::CLASS,
+ ) {
+ // SAFETY: The pointer is the address of a live error data cell.
+ return unsafe { &*error_data.cast::<ErrorDataCell>() }.error_data();
+ }
// SAFETY: The caller guarantees that the pointer is to error data, which lives as long as its cell.
unsafe { &*error_data.cast::<ErrorData>() }
}
diff --git a/Libraries/LibJS/Rust/src/embedding/console.rs b/Libraries/LibJS/Rust/src/embedding/console.rs
index 6339b517661..8a2f0063c8c 100644
--- a/Libraries/LibJS/Rust/src/embedding/console.rs
+++ b/Libraries/LibJS/Rust/src/embedding/console.rs
@@ -20,7 +20,7 @@ use crate::layout::cell::Gc;
use crate::layout::host_class::{JSObject, JSVM, JSValue};
use crate::layout::value::Value;
use crate::runtime::console_object::ConsoleObject;
-use crate::runtime::error_data::ErrorData;
+use crate::runtime::error_data::ErrorDataCell;
use crate::runtime::print::{PrintContext, print};
use crate::source_code::SourceCode;
use crate::source_range::{Position, SourceRange};
@@ -181,9 +181,11 @@ pub unsafe extern "C" fn js_console_report_exception(
///
/// # Safety
///
-/// `console` must point to a live console, and the views must be valid for the call. Call on the VM's thread.
+/// `vm` must point to a live VM, `console` to a live console, and the views must be valid for the call. Call on the
+/// VM's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_console_report_exception_with_location(
+ vm: *mut JSVM,
console: *mut JSConsole,
name: JSUtf16View,
message: JSUtf16View,
@@ -192,15 +194,21 @@ pub unsafe extern "C" fn js_console_report_exception_with_location(
column: u32,
in_promise: bool,
) {
+ // SAFETY: The caller passes a live VM.
+ let vm = unsafe { vm_from_abi(vm) };
// SAFETY: The caller passes a live console.
let console = unsafe { console_from_abi(console) };
// SAFETY: The caller guarantees that the views are valid for the call.
let (name, message, filename) = unsafe { (name.as_view(), message.as_view(), filename.as_view()) };
- let error_data = ErrorData::from_source_range(SourceRange {
- code: SourceCode::create(filename.to_utf16_string(), ak::Utf16String::default()),
- start: Position { line, column },
- });
- console.report_exception(name, message, &error_data, in_promise);
+ // Error data has to be in a cell, since error_data_into_abi finds its class through its block.
+ let error_data = ErrorDataCell::from_source_range(
+ vm,
+ SourceRange {
+ code: SourceCode::create(filename.to_utf16_string(), ak::Utf16String::default()),
+ start: Position { line, column },
+ },
+ );
+ console.report_exception(name, message, error_data.error_data(), in_promise);
}
/// The stream a PrintContext writes to, which hands the bytes to the embedder's sink.
diff --git a/Libraries/LibJS/Rust/src/embedding/error.rs b/Libraries/LibJS/Rust/src/embedding/error.rs
index f62c8022fd6..174ad03554d 100644
--- a/Libraries/LibJS/Rust/src/embedding/error.rs
+++ b/Libraries/LibJS/Rust/src/embedding/error.rs
@@ -15,7 +15,7 @@ use crate::embedding::abi_types::{
owned_utf16_string_from_abi, owned_utf16_string_into_abi, value_from_abi, vm_from_abi,
};
use crate::embedding::source_code::source_code_into_abi;
-use crate::gc::class::{Class, GcCell};
+use crate::gc::class::GcCell;
use crate::layout::cell::Gc;
use crate::layout::host_class::{JSCompletion, JSObject, JSVM, JSValue};
use crate::layout::object::Object;
@@ -23,26 +23,6 @@ use crate::runtime::error::Error;
use crate::runtime::error_data::{CompactTraceback, ErrorData, ErrorDataCell};
use crate::utf16::Utf16View;
-/// The error data that the embedder passes as a JSErrorData: an address js_error_data_of gave it, or a JSErrorDataCell
-/// itself, which is where a pointer to the C++ ErrorDataCell points as a pointer to the ErrorData it derives from.
-///
-/// # Safety
-///
-/// `error_data` must be the error data or the error data cell of a live cell.
-unsafe fn error_data_or_error_data_cell_from_abi<'cell>(error_data: *const JSErrorData) -> &'cell ErrorData {
- assert!(!error_data.is_null(), "the embedder passes error data");
- // A cell starts with its class. Error data starts with a part of its traceback's Vec or a cell pointer, neither
- // of which is ever the address of a class.
- // SAFETY: Both start with an initialized word.
- let first_word = unsafe { error_data.cast::<*const Class>().read_unaligned() };
- if core::ptr::eq(first_word, ErrorDataCell::CLASS) {
- // SAFETY: The pointer is the address of a live error data cell.
- return unsafe { &*error_data.cast::<ErrorDataCell>() }.error_data();
- }
- // SAFETY: The caller passes error data of a live cell.
- unsafe { error_data_from_abi(error_data) }
-}
-
/// The error data that the error_data hook of a host class returned for `object`: error data or an error data cell
/// as js_error_data_stack_string takes it, or null for none.
///
@@ -51,7 +31,7 @@ unsafe fn error_data_or_error_data_cell_from_abi<'cell>(error_data: *const JSErr
/// `error_data` must be null or the error data or error data cell of a cell that `object` keeps alive.
pub unsafe fn error_data_from_host_hook(_object: &Object, error_data: *mut c_void) -> Option<&ErrorData> {
// SAFETY: The caller guarantees that the object keeps the error data alive, as long as the object itself.
- (!error_data.is_null()).then(|| unsafe { error_data_or_error_data_cell_from_abi(error_data.cast_const().cast()) })
+ (!error_data.is_null()).then(|| unsafe { error_data_from_abi(error_data.cast_const().cast()) })
}
/// Throws a new error of `kind` whose message is a copy of the code units `message` views, created the way the
@@ -213,7 +193,7 @@ pub unsafe extern "C" fn js_error_data_stack_string(
compact: bool,
) -> JSOwnedUtf16String {
// SAFETY: The caller passes error data of a live cell.
- let error_data = unsafe { error_data_or_error_data_cell_from_abi(error_data) };
+ let error_data = unsafe { error_data_from_abi(error_data) };
let compact = if compact {
CompactTraceback::Yes
} else {
@@ -231,9 +211,7 @@ pub unsafe extern "C" fn js_error_data_stack_string(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_error_data_traceback_length(error_data: *const JSErrorData) -> usize {
// SAFETY: The caller passes error data of a live cell.
- unsafe { error_data_or_error_data_cell_from_abi(error_data) }
- .traceback()
- .len()
+ unsafe { error_data_from_abi(error_data) }.traceback().len()
}
/// A frame of the call stack of an error, as C++ TracebackFrame: the name of the frame's function, and where in its
@@ -264,7 +242,7 @@ pub unsafe extern "C" fn js_error_data_traceback_frame(
out: *mut JSTracebackFrame,
) {
// SAFETY: The caller passes error data of a live cell.
- let error_data = unsafe { error_data_or_error_data_cell_from_abi(error_data) };
+ let error_data = unsafe { error_data_from_abi(error_data) };
let frame = &error_data.traceback()[index];
let (filename, line, column) = frame.source_position();
assert!(!out.is_null(), "the embedder passes an out parameter");
diff --git a/Libraries/LibJS/Rust/src/embedding/host/registry.rs b/Libraries/LibJS/Rust/src/embedding/host/registry.rs
index 183148b2209..f6c5fde8cde 100644
--- a/Libraries/LibJS/Rust/src/embedding/host/registry.rs
+++ b/Libraries/LibJS/Rust/src/embedding/host/registry.rs
@@ -75,7 +75,8 @@ pub fn runtime_class_of_host_class(vm: &Vm, table: &'static JSHostClass) -> &'st
}
/// The runtime class of `table`, which must be of `kind`, and the allocator its objects come from: the class's own,
-/// or with JS_HOST_CLASS_SHARES_ALLOCATOR_WITH_PARENT, that of its nearest ancestor that has one of its own.
+/// or with JS_HOST_CLASS_SHARES_ALLOCATOR_WITH_PARENT, the one that the classes sharing the allocator of its nearest
+/// ancestor without the flag share.
pub fn runtime_class_and_allocator_of_host_class(
vm: &Vm,
table: &'static JSHostClass,
@@ -97,9 +98,13 @@ pub fn runtime_class_and_allocator_of_host_class(
}
let class = runtime_class_of_host_class(vm, table);
- let allocator = vm
- .heap()
- .runtime_class_allocator(runtime_class_of_host_class(vm, table.allocating_class()));
+ let allocating_class = table.allocating_class();
+ let allocator = if core::ptr::eq(allocating_class, table) {
+ vm.heap().runtime_class_allocator(class)
+ } else {
+ vm.heap()
+ .shared_runtime_class_allocator(runtime_class_of_host_class(vm, allocating_class), class)
+ };
vm.host_classes()
.borrow_mut()
.get_mut(&table.identity())
diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rs
index 68dc75bd943..da4ccd888af 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -31,8 +31,8 @@ pub struct CellTypeInfo {
pub class_name: Option<unsafe extern "C" fn(cell: *const c_void, length: *mut usize) -> *const c_char>,
}
-/// The class of a cell, stored in the first word of every cell. It starts with the type info LibGC dispatches
-/// through, so the class of a cell and the type info of the block it lives in are the same address.
+/// The class of a cell, which the block the cell lives in holds (see `class_of`). It starts with the type info LibGC
+/// dispatches through.
#[repr(C)]
pub struct Class {
pub type_info: CellTypeInfo,
@@ -246,8 +246,8 @@ unsafe extern "C" fn destroy<T>(cell: *mut c_void) {
}
unsafe extern "C" fn class_name(cell: *const c_void, length: *mut usize) -> *const c_char {
- // SAFETY: Every Rust cell starts with its class.
- let class = unsafe { cell.cast::<&'static Class>().read() };
+ // SAFETY: LibGC passes a cell of a Rust allocator.
+ let class = unsafe { class_at(cell.cast()) };
// SAFETY: LibGC passes somewhere to store the length.
unsafe { length.write(class.name.len()) };
class.name.as_ptr().cast()
@@ -278,19 +278,64 @@ unsafe impl<T: GcCell> Extends<CellHeader> for T {}
// SAFETY: A header starts with itself.
unsafe impl Extends<CellHeader> for CellHeader {}
+/// A cell's block starts at the cell's address rounded down to a multiple of BLOCK_SIZE, and holds the class of its
+/// cells at BLOCK_CLASS_OFFSET: the foreign type of the allocator that created the block (see Heap::create_allocator).
+/// The block of an allocator that classes share holds the class they extend with BLOCK_CLASS_TAIL_TAG added, and each of
+/// its cells keeps its own class in the word after the cell_size bytes of that class.
+pub const BLOCK_SIZE: usize = 16 * 1024;
+pub const BLOCK_CLASS_OFFSET: usize = 2 * size_of::<usize>();
+pub use crate::layout::cell::BLOCK_CLASS_TAIL_TAG;
+
+/// The class that the block `address` is in holds, without its tag, or null for a block of C++ cells.
+///
+/// # Safety
+///
+/// `address` must be in a live cell.
+pub unsafe fn block_class_pointer_at(address: *const u8) -> *const Class {
+ debug_assert!(is_in_heap_region(address.addr()), "only cells in the heap have a class");
+ let block = address.wrapping_sub(address.addr() & (BLOCK_SIZE - 1));
+ // SAFETY: The caller passes an address in a live cell, whose block is live as well.
+ let class = unsafe { block.add(BLOCK_CLASS_OFFSET).cast::<*const u8>().read() };
+ class.wrapping_sub(class.addr() & BLOCK_CLASS_TAIL_TAG).cast()
+}
+
+/// The class of the cell at `cell`.
+///
+/// # Safety
+///
+/// `cell` must be the address of a live cell of a Rust allocator.
+pub unsafe fn class_at(cell: *const u8) -> &'static Class {
+ debug_assert!(is_in_heap_region(cell.addr()), "only cells in the heap have a class");
+ let block = cell.wrapping_sub(cell.addr() & (BLOCK_SIZE - 1));
+ // SAFETY: The caller passes a live cell of a Rust allocator, whose block holds a class.
+ let class = unsafe { block.add(BLOCK_CLASS_OFFSET).cast::<*const u8>().read() };
+ if class.addr() & BLOCK_CLASS_TAIL_TAG == 0 {
+ // SAFETY: The allocator created the block with the class of its cells, which lives forever.
+ return unsafe { &*class.cast::<Class>() };
+ }
+ // SAFETY: The class that classes share an allocator of lives forever, and each cell of the allocator keeps its own
+ // class right after the bytes of that class.
+ unsafe {
+ let shared = &*class.wrapping_sub(BLOCK_CLASS_TAIL_TAG).cast::<Class>();
+ cell.add(shared.type_info.cell_size as usize)
+ .cast::<&'static Class>()
+ .read()
+ }
+}
+
/// The class a cell was allocated with, which may be a subclass of its static type.
pub fn class_of<T>(cell: crate::layout::cell::Gc<T>) -> &'static Class {
- // SAFETY: Every cell starts with its class.
- unsafe { cell.as_ptr().cast::<&'static Class>().read() }
+ // SAFETY: The cell is live.
+ unsafe { class_at(cell.as_ptr().cast()) }
}
/// The cell as a `Derived`, if it was allocated as one or as a subclass of it.
///
-/// NB: A cell carries the class it is constructed with from the start, and is only ever constructed as part of a
-/// value of that class, so its class tells what the memory around it is.
+/// NB: A cell is only ever allocated by the allocator of its class, so the class its block holds tells what the memory
+/// around it is.
pub fn downcast_ref<Base: GcCell, Derived: GcCell + Extends<Base>>(cell: &Base) -> Option<&Derived> {
- // SAFETY: Every cell starts with its class.
- let class = unsafe { core::ptr::from_ref(cell).cast::<&'static Class>().read() };
+ // SAFETY: The cell is live.
+ let class = unsafe { class_at(core::ptr::from_ref(cell).cast()) };
class
.is_class_of::<Derived>()
// SAFETY: The cell is a Derived or a subclass of it, which starts with a Derived.
@@ -353,14 +398,21 @@ impl<T> crate::layout::cell::Gc<T> {
}
impl CellHeader {
+ /// The header of a cell of `class`, which must also be the class of the allocator the cell comes from.
pub fn for_class(class: &'static Class) -> Self {
Self {
- class,
+ unused: [0; 8],
mark: false.into(),
state: CellState::Live.into(),
kind: class.kind(),
}
}
+
+ /// The class of the cell, which its block holds.
+ pub fn class(&self) -> &'static Class {
+ // SAFETY: A header starts a live cell.
+ unsafe { class_at(core::ptr::from_ref(self).cast()) }
+ }
}
/// Defines the class of a cell type, named after the type and its ClassId. `extends` names the cell types it
diff --git a/Libraries/LibJS/Rust/src/gc/embedder_cell.rs b/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
index bf777880dbf..73156063ffb 100644
--- a/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
+++ b/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
@@ -158,7 +158,7 @@ impl<T: EmbedderValue> EmbedderClass<T> {
/// # Safety
///
/// `cell` must be a live cell that an embedder class allocated, such as the host data of a host object the
- /// embedder created with such a cell, whose first word is therefore its class.
+ /// embedder created with such a cell, whose block therefore holds its class.
pub unsafe fn downcast(&'static self, cell: NonNull<c_void>) -> Option<Gc<EmbedderCell<T>>> {
// SAFETY: The caller passes a live cell of an embedder class.
let cell = unsafe { Gc::<EmbedderCell<T>>::from_non_null(cell.cast()) };
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index c5d00449b8b..95631308249 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -11,7 +11,7 @@ use core::ptr::NonNull;
use std::collections::HashMap;
use super::capi::{self, GCAllocator, GCGatherRootsCallback, GCHeap, GCLayout};
-use super::class::{CellTypeInfo, Class, GcCell};
+use super::class::{BLOCK_CLASS_OFFSET, BLOCK_CLASS_TAIL_TAG, BLOCK_SIZE, CellTypeInfo, Class, GcCell};
use super::class_id::{CLASS_COUNT, ClassId};
use super::defer_gc::DeferGc;
use super::weak::WEAK_IMPL_POINTER_OFFSET;
@@ -28,6 +28,8 @@ pub struct Heap {
/// The allocators of the classes that have no id of their own, the classes derived at run time and the classes
/// of an embedder's cells, by the address of their class.
runtime_class_allocators: RefCell<HashMap<usize, HeapAllocator, foldhash::fast::RandomState>>,
+ /// The allocators that the classes extending a class share, by the address of that class.
+ shared_class_allocators: RefCell<HashMap<usize, SharedClassAllocator, foldhash::fast::RandomState>>,
/// The size classes of each class, by class id, out of line, as few classes have any.
size_class_tables: Box<[OnceCell<SizeClassTable>; CLASS_COUNT]>,
inline_allocation_info: InlineAllocationInfo,
@@ -36,6 +38,13 @@ pub struct Heap {
collect_when_deferrals_end: NonNull<bool>,
}
+/// An allocator that classes extending a class share, whose cells each keep their class in the word after them (see
+/// `class_at`), with the type info of those larger cells, which has to outlive the allocator.
+struct SharedClassAllocator {
+ allocator: HeapAllocator,
+ _type_info: Box<CellTypeInfo>,
+}
+
/// The size classes of a class, with the type infos their blocks dispatch through, which have to outlive the
/// allocators.
struct SizeClassTable {
@@ -80,6 +89,8 @@ impl HeapAllocator {
pub struct RuntimeClassAllocator {
class: &'static Class,
allocator: HeapAllocator,
+ /// Whether the allocator is shared with other classes, so that each cell keeps its class in the word after it.
+ class_in_tail: bool,
}
impl RuntimeClassAllocator {
@@ -169,6 +180,7 @@ impl Heap {
raw,
allocators: [const { Cell::new(None) }; CLASS_COUNT],
runtime_class_allocators: RefCell::default(),
+ shared_class_allocators: RefCell::default(),
size_class_tables: Box::new([const { OnceCell::new() }; CLASS_COUNT]),
inline_allocation_info: InlineAllocationInfo {
allocated_bytes_since_last_gc: counter(layout.heap_allocated_bytes_since_last_gc_offset),
@@ -249,13 +261,32 @@ impl Heap {
let build = |defer_gc: &DeferGc<'_>| {
let cell = build(defer_gc);
// SAFETY: Every cell starts with its header.
- debug_assert!(
- unsafe { (*core::ptr::from_ref(&cell).cast::<CellHeader>()).class }.is_subclass_of(allocator.class)
- );
+ debug_assert!(unsafe { (*core::ptr::from_ref(&cell).cast::<CellHeader>()).kind } == allocator.class.kind());
cell
};
- // SAFETY: The allocator's cells have the size of a T, checked above, and T's alignment, as its class extends T's.
- unsafe { self.allocate_with(allocator.allocator, size_of::<T>(), AllocationKind::Cell, build, |_| {}) }
+ if !allocator.class_in_tail {
+ // SAFETY: The allocator's cells have the size of a T, checked above, and T's alignment, as its class extends
+ // T's.
+ return unsafe {
+ self.allocate_with(allocator.allocator, size_of::<T>(), AllocationKind::Cell, build, |_| {})
+ };
+ }
+ let class = allocator.class;
+ let initialize_tail = |tail: *mut u8| {
+ // SAFETY: A cell of a shared allocator has room for its class right after the T, 8-byte aligned.
+ unsafe { tail.cast::<&'static Class>().write(class) };
+ };
+ // SAFETY: The cells of a shared allocator have the size of a T and a word, and T's alignment, as its class
+ // extends T's.
+ unsafe {
+ self.allocate_with(
+ allocator.allocator,
+ size_of::<T>() + size_of::<&'static Class>(),
+ AllocationKind::Cell,
+ build,
+ initialize_tail,
+ )
+ }
}
/// allocate() into a cell of `size_class`, whose class is the class of the cell or one that it extends, filling the
@@ -307,7 +338,7 @@ impl Heap {
let cell = build(defer_gc);
// SAFETY: Every cell starts with its header.
debug_assert!(
- unsafe { (*core::ptr::from_ref(&cell).cast::<CellHeader>()).class }.is_subclass_of(size_class.class)
+ unsafe { (*core::ptr::from_ref(&cell).cast::<CellHeader>()).kind } == size_class.class.kind()
);
cell
};
@@ -414,7 +445,7 @@ impl Heap {
let header = storage.cast::<CellHeader>();
// SAFETY: Every cell starts with its header.
unsafe {
- debug_assert!((*header.as_ptr()).class.is_subclass_of(T::CLASS));
+ debug_assert!((*header.as_ptr()).class().is_subclass_of(T::CLASS));
(*header.as_ptr()).mark.set(must_mark);
Gc::from_non_null(storage)
}
@@ -478,22 +509,26 @@ impl Heap {
}
}
- /// Creates an allocator of cells of `class` with `type_info`, whose blocks hold the class (see `class_of`).
+ /// Creates an allocator of cells of `class` with `type_info`, whose blocks hold the class (see `class_of`), tagged
+ /// if each cell keeps a class of its own in the word after it.
///
/// # Safety
///
/// The type info must outlive the allocator.
- unsafe fn create_allocator(&self, type_info: *const CellTypeInfo, class: &'static Class) -> HeapAllocator {
+ unsafe fn create_allocator(
+ &self,
+ type_info: *const CellTypeInfo,
+ class: &'static Class,
+ class_in_tail: bool,
+ ) -> HeapAllocator {
let name = class.name;
+ let mut foreign_type = core::ptr::from_ref(class).cast::<u8>();
+ if class_in_tail {
+ foreign_type = foreign_type.wrapping_add(BLOCK_CLASS_TAIL_TAG);
+ }
// SAFETY: The caller keeps the type info alive for as long as the allocator, and the class lives forever.
- let raw = unsafe {
- capi::gc_allocator_create(
- type_info,
- name.as_ptr().cast(),
- name.len(),
- core::ptr::from_ref(class).cast(),
- )
- };
+ let raw =
+ unsafe { capi::gc_allocator_create(type_info, name.as_ptr().cast(), name.len(), foreign_type.cast()) };
let raw = NonNull::new(raw).expect("LibGC creates the allocator");
// SAFETY: The heap and the allocator are live.
let local_free_list = unsafe { capi::gc_heap_allocator_local_free_list(self.raw.as_ptr(), raw.as_ptr()) };
@@ -510,6 +545,47 @@ impl Heap {
RuntimeClassAllocator {
class,
allocator: self.allocator_kept_by_class_address(class),
+ class_in_tail: false,
+ }
+ }
+
+ /// The allocator of `class`, a class derived at run time that shares the allocator of `allocating_class`, a class it
+ /// extends, with the other classes that do: each cell keeps its class in the word after it (see `class_at`).
+ pub fn shared_runtime_class_allocator(
+ &self,
+ allocating_class: &'static Class,
+ class: &'static Class,
+ ) -> RuntimeClassAllocator {
+ assert!(
+ class.is_derived_at_run_time()
+ && class.is_subclass_of(allocating_class)
+ && class.type_info.cell_size == allocating_class.type_info.cell_size
+ && allocating_class.type_info.alignment as usize <= size_of::<&'static Class>(),
+ "{} cannot share the allocator of {}",
+ class.name,
+ allocating_class.name
+ );
+ let allocator = self
+ .shared_class_allocators
+ .borrow_mut()
+ .entry(core::ptr::from_ref(allocating_class) as usize)
+ .or_insert_with(|| {
+ let type_info = Box::new(CellTypeInfo {
+ cell_size: allocating_class.type_info.cell_size + size_of::<&'static Class>() as u32,
+ ..allocating_class.type_info
+ });
+ // SAFETY: The box keeps the type info alive for as long as the allocator.
+ let allocator = unsafe { self.create_allocator(&raw const *type_info, allocating_class, true) };
+ SharedClassAllocator {
+ allocator,
+ _type_info: type_info,
+ }
+ })
+ .allocator;
+ RuntimeClassAllocator {
+ class,
+ allocator,
+ class_in_tail: true,
}
}
@@ -524,6 +600,7 @@ impl Heap {
RuntimeClassAllocator {
class,
allocator: self.allocator_kept_by_class_address(class),
+ class_in_tail: false,
}
}
@@ -533,7 +610,7 @@ impl Heap {
.borrow_mut()
.entry(core::ptr::from_ref(class) as usize)
// SAFETY: The class and its name live as long as the process, so they outlive the allocator.
- .or_insert_with(|| unsafe { self.create_allocator(&raw const class.type_info, class) })
+ .or_insert_with(|| unsafe { self.create_allocator(&raw const class.type_info, class, false) })
}
/// The size classes of `class`, whose cells have `cell_sizes` bytes, in that order, which the first call for the
@@ -584,7 +661,7 @@ impl Heap {
class,
cell_size: type_info.cell_size,
// SAFETY: The heap destroys the allocator before the type info, and the class name is static.
- allocator: unsafe { self.create_allocator(type_info, class) },
+ allocator: unsafe { self.create_allocator(type_info, class, false) },
})
.collect();
SizeClassTable {
@@ -605,7 +682,7 @@ impl Heap {
class.name
);
// SAFETY: The class and its name are static, so they outlive the allocator.
- let allocator = unsafe { self.create_allocator(&raw const class.type_info, class) };
+ let allocator = unsafe { self.create_allocator(&raw const class.type_info, class, false) };
slot.set(Some(allocator));
allocator
}
@@ -687,6 +764,9 @@ impl Drop for Heap {
for allocator in self.runtime_class_allocators.get_mut().values() {
capi::gc_allocator_destroy(allocator.raw.as_ptr());
}
+ for shared in self.shared_class_allocators.get_mut().values() {
+ capi::gc_allocator_destroy(shared.allocator.raw.as_ptr());
+ }
for table in self.size_class_tables.iter().filter_map(OnceCell::get) {
for size_class in &table.allocators {
capi::gc_allocator_destroy(size_class.allocator.raw.as_ptr());
@@ -721,6 +801,12 @@ fn check_layout() -> GCLayout {
layout.cell_kind_offset.into(),
offset_of!(CellHeader, kind) as u64,
);
+ expect("block size", layout.block_size.into(), BLOCK_SIZE as u64);
+ expect(
+ "block foreign type offset",
+ layout.block_foreign_type_offset.into(),
+ BLOCK_CLASS_OFFSET as u64,
+ );
expect(
"cell type info size",
layout.cell_type_info_size.into(),
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 57f846c7a89..f894b8fddde 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -27,7 +27,7 @@ use crate::bytecode::executable::{
MAX_NUMBER_OF_SHAPES_TO_REMEMBER, MEGAMORPHIC_DATA_TAG, MEGAMORPHIC_HASH_MULTIPLIER, MEGAMORPHIC_INDEX_BITS,
MEGAMORPHIC_PRIMARY_ENTRIES_OFFSET, MEGAMORPHIC_SECONDARY_ENTRIES_OFFSET,
};
-use crate::gc::class::{Class, GcCell};
+use crate::gc::class::{BLOCK_CLASS_OFFSET, BLOCK_CLASS_TAIL_TAG, BLOCK_SIZE, Class, GcCell};
use crate::gc::defer_gc::DeferGc;
use crate::interpreter::runtime_functions::runtime_function_addresses;
use crate::interpreter::vm::{
@@ -182,6 +182,7 @@ fn runtime_layout() -> RuntimeLayout {
indexed_storage_kind_holey: IndexedStorageKind::Holey as u8,
object_flag_is_extensible: object_flag::IS_EXTENSIBLE,
object_flag_has_magical_length: object_flag::HAS_MAGICAL_LENGTH_PROPERTY,
+ object_class: core::ptr::from_ref(Object::CLASS) as u64,
string_object_class: core::ptr::from_ref(StringObject::CLASS) as u64,
string_prototype_class: core::ptr::from_ref(StringPrototype::CLASS) as u64,
object_flag_may_interfere: object_flag::MAY_INTERFERE_WITH_INDEXED_PROPERTY_ACCESS,
@@ -344,6 +345,10 @@ fn runtime_layout() -> RuntimeLayout {
property_lookup_cache_entry_type_add_own_property: PropertyLookupCacheEntryType::AddOwnProperty as u32,
property_lookup_cache_entry_type_get_own_property: PropertyLookupCacheEntryType::GetOwnProperty as u32,
property_lookup_cache_entry_type_change_own_property: PropertyLookupCacheEntryType::ChangeOwnProperty as u32,
+ cell_block_mask: !(BLOCK_SIZE as u64 - 1),
+ block_class_offset: offset(BLOCK_CLASS_OFFSET),
+ block_class_tail_tag: BLOCK_CLASS_TAIL_TAG as u64,
+ class_cell_size: offset(offset_of!(Class, type_info.cell_size)),
class_object_methods: offset(offset_of!(Class, object_methods)),
object_methods_get_prototype_of: offset(offset_of!(ObjectMethods, internal_get_prototype_of)),
object_methods_is_cacheable_for_property_absence: offset(offset_of!(
diff --git a/Libraries/LibJS/Rust/src/layout/cell.rs b/Libraries/LibJS/Rust/src/layout/cell.rs
index 0d80f48865b..6b39319f9f2 100644
--- a/Libraries/LibJS/Rust/src/layout/cell.rs
+++ b/Libraries/LibJS/Rust/src/layout/cell.rs
@@ -7,8 +7,6 @@
use core::cell::Cell;
use core::ptr::NonNull;
-use crate::layout_forward::Class;
-
/// A pointer to a garbage-collected cell. Cells are kept alive by being reachable from the heap's roots or from the
/// stack, which the collector scans conservatively, so a `Gc` needs no rooting while it lives in a local.
#[repr(transparent)]
@@ -81,15 +79,19 @@ pub enum CellState {
}
/// The bytes LibGC shares with every cell. The first word is the vtable pointer of a C++ cell, which LibGC never
-/// reads; Rust cells keep their class there. The header is packed so that a cell's own fields can use the bytes that
-/// follow it, the same way C++ cells reuse the base class's tail padding.
+/// reads; the block of a Rust cell holds its class instead (see `class_of`). The header is packed so that a cell's own
+/// fields can use the bytes that follow it, the same way C++ cells reuse the base class's tail padding.
#[repr(C, packed)]
pub struct CellHeader {
- pub class: &'static Class,
+ pub unused: [u8; 8],
pub mark: Cell<bool>,
pub state: Cell<CellState>,
pub kind: CellKind,
}
const _: () = assert!(size_of::<CellHeader>() == 11);
+
+/// Added to the class that the block of an allocator holds when the classes that extend it share the allocator, whose
+/// cells each keep their own class in the word after the cell_size bytes of that class.
+pub const BLOCK_CLASS_TAIL_TAG: usize = 1;
const _: () = assert!(align_of::<CellHeader>() == 1);
diff --git a/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs b/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs
index 720cdeed251..ced14d7e6bd 100644
--- a/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs
+++ b/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs
@@ -77,7 +77,7 @@ impl DisposableResourceStack {
/// The stack a register holds, which must be one.
pub fn from_value(value: Value) -> Gc<DisposableResourceStack> {
assert!(value.is_cell());
- // SAFETY: The value holds a cell, and every cell starts with its class, which is checked below.
+ // SAFETY: The value holds a cell, whose block holds its class, which is checked below.
let stack = unsafe { value.cell::<DisposableResourceStack>() };
assert!(
class_of(stack).is_subclass_of(Self::CLASS),
diff --git a/Libraries/LibJS/Rust/src/runtime/environment.rs b/Libraries/LibJS/Rust/src/runtime/environment.rs
index dfbfaafc04b..1e23b756fd8 100644
--- a/Libraries/LibJS/Rust/src/runtime/environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/environment.rs
@@ -135,7 +135,7 @@ impl Environment {
}
pub fn class(&self) -> &'static Class {
- self.header.class
+ self.header.class()
}
fn methods(&self) -> &'static EnvironmentMethods {
@@ -282,7 +282,7 @@ impl Value {
/// The environment the value holds, which must be one.
pub fn as_environment(self) -> Gc<Environment> {
assert!(self.is_cell());
- // SAFETY: The value holds a cell, and every cell starts with its class, which is checked below.
+ // SAFETY: The value holds a cell, whose block holds its class, which is checked below.
let environment = unsafe { self.cell::<Environment>() };
assert!(
class_of(environment).is_subclass_of(Environment::CLASS),
diff --git a/Libraries/LibJS/Rust/src/runtime/error_data.rs b/Libraries/LibJS/Rust/src/runtime/error_data.rs
index 4c95d720eea..ab11d94bf34 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_data.rs
@@ -239,6 +239,9 @@ pub struct ErrorDataCell {
define_cell!(ErrorDataCell, Other, external_memory_size: external_memory_size);
+/// Where an error data cell keeps its error data.
+pub const ERROR_DATA_CELL_ERROR_DATA_OFFSET: usize = core::mem::offset_of!(ErrorDataCell, error_data);
+
impl ExternalMemorySize for ErrorDataCell {
fn external_memory_size(&self) -> usize {
self.error_data.external_memory_size()
@@ -248,9 +251,18 @@ impl ExternalMemorySize for ErrorDataCell {
impl ErrorDataCell {
/// ErrorDataCell::capture(vm): error data with the call stack of the running execution context.
pub fn capture(vm: &Vm) -> Gc<ErrorDataCell> {
+ Self::create(vm, ErrorData::new(vm))
+ }
+
+ /// Error data for an exception whose source location came from another agent.
+ pub fn from_source_range(vm: &Vm, source_range: SourceRange) -> Gc<ErrorDataCell> {
+ Self::create(vm, ErrorData::from_source_range(source_range))
+ }
+
+ fn create(vm: &Vm, error_data: ErrorData) -> Gc<ErrorDataCell> {
let cell = vm.heap().allocate(|_| Self {
header: CellHeader::for_class(Self::CLASS),
- error_data: ErrorData::new(vm),
+ error_data,
});
vm.heap()
.did_allocate_external_memory(cell.error_data.traceback_storage_size());
diff --git a/Libraries/LibJS/Rust/src/runtime/module.rs b/Libraries/LibJS/Rust/src/runtime/module.rs
index 00e09c528f5..14d9969bc72 100644
--- a/Libraries/LibJS/Rust/src/runtime/module.rs
+++ b/Libraries/LibJS/Rust/src/runtime/module.rs
@@ -240,7 +240,7 @@ impl Module {
}
pub fn class(&self) -> &'static Class {
- self.header.class
+ self.header.class()
}
pub(crate) fn methods(&self) -> &'static ModuleMethods {
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index b64d306c671..a26639ca566 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -774,7 +774,7 @@ impl Object {
}
pub fn class(&self) -> &'static Class {
- self.header.class
+ self.header.class()
}
fn methods(&self) -> &'static ObjectMethods {
diff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
index 6afd7ee1aae..55212ea3c1d 100644
--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
@@ -644,7 +644,7 @@ impl PrimitiveString {
}
fn header_class(&self) -> &'static Class {
- self.header.class
+ self.header.class()
}
pub fn deferred_kind(&self) -> DeferredKind {
diff --git a/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
index 80cf6359c8b..77adae179b9 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
+++ b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
@@ -1552,7 +1552,7 @@ JsonObject current_stack_trace(JS::VM& vm)
{
// The current stack trace is the result of construct a stack trace given a list of stack frames representing the
// callstack of the running execution context.
- return construct_a_stack_trace(JS::ErrorDataCell::capture(vm)->traceback());
+ return construct_a_stack_trace(JS::ErrorDataCell::capture(vm)->error_data().traceback());
}
// https://w3c.github.io/webdriver-bidi/#get-exception-details
diff --git a/Libraries/LibWeb/WebIDL/DOMException.h b/Libraries/LibWeb/WebIDL/DOMException.h
index 2a33c0bad9d..08d1b1292d2 100644
--- a/Libraries/LibWeb/WebIDL/DOMException.h
+++ b/Libraries/LibWeb/WebIDL/DOMException.h
@@ -110,8 +110,8 @@ public:
Utf16FlyString const& message() const { return m_message; }
u16 code() const { return get_legacy_code_for_name(m_name); }
- JS::ErrorDataCell& error_data() { return *m_error_data; }
- JS::ErrorDataCell const& error_data() const { return *m_error_data; }
+ JS::ErrorData& error_data() { return m_error_data->error_data(); }
+ JS::ErrorData const& error_data() const { return m_error_data->error_data(); }
protected:
DOMException(FlyString name, Utf16String const& message);