Truly independent web browser
LibGC+LibJS: Bump-allocate the never-allocated cells of a block
Andreas Kling5a6b5312addc
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cppindex 4ee6bf6757d..051be85e0d5 100644--- a/Libraries/LibGC/CAPI.cpp+++ b/Libraries/LibGC/CAPI.cpp@@ -121,6 +121,9 @@ struct CAPI {.weak_impl_pointer_offset = WeakImpl::value_offset(),.free_cell_next_offset = HeapBlock::freelist_next_offset(),.free_cell_link_mask = HeapBlock::freelist_link_mask,+ .local_cursor_offset = offsetof(CellAllocator::LocalFreeCells, cursor),+ .local_end_offset = offsetof(CellAllocator::LocalFreeCells, end),+ .local_cell_size_offset = offsetof(CellAllocator::LocalFreeCells, cell_size),.heap_allocated_bytes_since_last_gc_offset = offsetof(Heap, m_allocated_bytes_since_last_gc),.heap_gc_bytes_threshold_offset = offsetof(Heap, m_gc_bytes_threshold),.heap_total_allocated_bytes_offset = offsetof(Heap, m_total_allocated_bytes),@@ -147,9 +150,11 @@ struct CAPI {static_assert(sizeof(Heap::m_gc_bytes_threshold) == sizeof(size_t));static_assert(sizeof(Heap::m_total_allocated_bytes) == sizeof(size_t));- // Foreign code reads and writes the head of the list as a plain pointer.+ // Foreign code reads and writes the head of the list, the cursor and the end as plain pointers.static_assert(sizeof(RawPtr<Cell>) == sizeof(Cell*));- static RawPtr<Cell>* local_free_list(Heap& heap, CellAllocatorDescriptorBase& descriptor) { return descriptor.for_heap(heap).local_free_list({}); }+ static_assert(offsetof(CellAllocator::LocalFreeCells, free_list) == 0);+ static_assert(sizeof(FlatPtr) == sizeof(void*));+ static CellAllocator::LocalFreeCells* local_free_cells(Heap& heap, CellAllocatorDescriptorBase& descriptor) { return descriptor.for_heap(heap).local_free_cells({}); }static void set_foreign_context(Heap& heap, void* context) { heap.m_foreign_context = context; }static void* foreign_context(Heap& heap) { return heap.m_foreign_context; }static void defer_gc(Heap& heap) { heap.defer_gc(); }@@ -336,7 +341,7 @@ GCCell** gc_heap_allocator_local_free_list(GCHeap* heap, GCAllocator* allocator)return nullptr;#elseauto& descriptor = *reinterpret_cast<CAPICellAllocator*>(allocator);- return reinterpret_cast<GCCell**>(CAPI::local_free_list(as_heap(heap), descriptor));+ return reinterpret_cast<GCCell**>(CAPI::local_free_cells(as_heap(heap), descriptor));#endif}diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.hindex 2f5acb3ce0b..4e598750a6d 100644--- a/Libraries/LibGC/CAPI.h+++ b/Libraries/LibGC/CAPI.h@@ -85,6 +85,11 @@ typedef struct GCLayout {// For code that allocates cells from local free lists itself, see gc_heap_allocator_local_free_list().uint32_t free_cell_next_offset;uint32_t free_cell_link_mask;+ // Where the cursor, the end and the cell size of the cells an allocator bumps through are, relative to the head+ // of its local free list (see gc_heap_allocator_local_free_list()).+ uint32_t local_cursor_offset;+ uint32_t local_end_offset;+ uint32_t local_cell_size_offset;uint32_t heap_allocated_bytes_since_last_gc_offset;uint32_t heap_gc_bytes_threshold_offset;uint32_t heap_total_allocated_bytes_offset;@@ -134,23 +139,28 @@ GC_API GCCell* gc_heap_allocate_cell(GCHeap*, GCAllocator*, bool* must_mark);// states nothing may observe, and callers can hold on to anything across the growth. Live storage counts once a// collection finds it, through the live cell bytes that set the next threshold.GC_API GCCell* gc_heap_allocate_storage_cell(GCHeap*, GCAllocator*, bool* must_mark);-// Each allocator takes the free cells of one block at a time into a local free list of the heap, so that allocating is-// usually popping that list, and code that allocates cells itself (like the Rust heap) pops it inline:+// Each allocator takes the free cells of one block at a time into the heap, as a local free list of the cells that were+// freed and a range of cells that were never allocated, so that allocating is usually popping that list or bumping+// the cursor of that range, and code that allocates cells itself (like the Rust heap) does either inline:// - The list is a list of dead cells of one block, linked through the word at free_cell_next_offset. Cells are in the// heap region, where anything may have been corrupted, so only the bits of a link under free_cell_link_mask count:// the next cell is at those bits within the block of the cell holding the link, that is, the cell's address with// the bits under free_cell_link_mask replaced by the link's. The list is empty when the bits of its head under-// free_cell_link_mask are all zero (a null head, or the start of a block, where the last link leads). Its cells-// never need marking.+// free_cell_link_mask are all zero (a null head, or the start of a block, where the last link leads).+// - Once the list is empty, cells come from the range: the cursor, the end and the cell size are pointer-sized words+// at local_cursor_offset, local_end_offset and local_cell_size_offset from the head of the list. While the cursor is+// below the end, the cell at the cursor is free, and taking it advances the cursor by the cell size. These words are+// outside the heap region.+// - Cells from the list or the range never need marking.// - Before taking a cell of N bytes (the cell size of the allocator), such code checks that the heap's// allocated_bytes_since_last_gc + N stays within its gc_bytes_threshold, and allocates through the heap otherwise// (which may collect garbage). After taking it, it adds N to allocated_bytes_since_last_gc and total_allocated_bytes;// storage cells (see gc_heap_allocate_storage_cell()) skip the check and add N to total_allocated_bytes only. These// are size_t fields of the heap, at the offsets gc_get_layout() reports.// - It then writes every byte of the cell, as after gc_heap_allocate_cell(), with a clear mark.-// Returns where the head of the allocator's list in the heap is, which stays valid as long as the heap. The list is-// always empty while the heap collects on every allocation. Returns null if cells must always be allocated through the-// heap, as in builds that poison free cells for AddressSanitizer.+// Returns where the head of the allocator's list in the heap is, which stays valid as long as the heap. The list and+// the range are always empty while the heap collects on every allocation. Returns null if cells must always be+// allocated through the heap, as in builds that poison free cells for AddressSanitizer.GC_API GCCell** gc_heap_allocator_local_free_list(GCHeap*, GCAllocator*);// The context that the heap of the cell was created with, as code that only has a cell finds the rest of its runtime.GC_API void* gc_cell_heap_context(GCCell const*);diff --git a/Libraries/LibGC/CellAllocator.cpp b/Libraries/LibGC/CellAllocator.cppindex 0f8a6bd1958..92fbd7a716e 100644--- a/Libraries/LibGC/CellAllocator.cpp+++ b/Libraries/LibGC/CellAllocator.cpp@@ -23,6 +23,7 @@ CellAllocator::CellAllocator(CellAllocatorDescriptorBase& descriptor): m_descriptor(descriptor), m_block_allocator(shared_block_allocator()){+ m_local.cell_size = cell_size();}CellAllocator::~CellAllocator()@@ -51,8 +52,12 @@ CellAllocator& CellAllocatorDescriptorBase::for_heap(Heap& heap)Cell* CellAllocator::allocate_cell_slow(Heap& heap){- VERIFY(HeapBlock::is_end_of_freelist(m_local_free_list.ptr()));- m_local_free_list = nullptr;+ // NB: The local block has no free cells left, and take_free_cells() left it full.+ VERIFY(HeapBlock::is_end_of_freelist(m_local.free_list.ptr()));+ VERIFY(m_local.cursor == m_local.end);+ m_local.free_list = nullptr;+ m_local.cursor = 0;+ m_local.end = 0;m_local_block = nullptr;if (!m_list_node.is_in_list())@@ -92,8 +97,11 @@ Cell* CellAllocator::allocate_cell_slow(Heap& heap)return cell;}- m_local_free_list = block.take_free_cells();- VERIFY(!HeapBlock::is_end_of_freelist(m_local_free_list.ptr()));+ auto free_cells = block.take_free_cells();+ VERIFY(!HeapBlock::is_end_of_freelist(free_cells.free_list.ptr()) || free_cells.lazy_start < free_cells.lazy_end);+ m_local.free_list = free_cells.free_list;+ m_local.cursor = free_cells.lazy_start;+ m_local.end = free_cells.lazy_end;m_full_blocks.append(block);m_local_block = █return allocate_cell(heap);@@ -104,11 +112,13 @@ void CellAllocator::give_back_local_free_list(Badge<Heap>){if (!m_local_block)return;- if (!HeapBlock::is_end_of_freelist(m_local_free_list.ptr())) {- m_local_block->give_back_free_cells(m_local_free_list.ptr());+ if (!HeapBlock::is_end_of_freelist(m_local.free_list.ptr()) || m_local.cursor < m_local.end) {+ m_local_block->give_back_free_cells(m_local.free_list.ptr(), m_local.cursor);m_usable_blocks.append(*m_local_block);}- m_local_free_list = nullptr;+ m_local.free_list = nullptr;+ m_local.cursor = 0;+ m_local.end = 0;m_local_block = nullptr;}diff --git a/Libraries/LibGC/CellAllocator.h b/Libraries/LibGC/CellAllocator.hindex 213ad329932..d873b736fb0 100644--- a/Libraries/LibGC/CellAllocator.h+++ b/Libraries/LibGC/CellAllocator.h@@ -74,34 +74,51 @@ public:size_t cell_size() const { return m_descriptor.cell_size(); }CellTypeInfo const& type_info() const { return m_descriptor.type_info(); }- // Cells come from a list of free cells that the allocator took from one- // of its blocks (the local block) at once, so allocating is usually just- // popping that list.+ // Cells come from the free cells that the allocator took from one of its+ // blocks (the local block) at once, so allocating is usually just popping+ // a list of freed cells, or bumping a cursor over cells that were never+ // allocated.//- // Invariants of the local free list:- // - Its cells are dead and belong to the local block, which is in the- // full block list while it has a local free list.- // - The local block is never pending incremental sweep: the list is filled- // from swept or new blocks only, and handed back to its block whenever a- // collection starts. So cells from it never need marking.+ // Invariants of the local free cells:+ // - They are dead and belong to the local block, which is in the full+ // block list while it has local free cells.+ // - The local block is never pending incremental sweep: they come from+ // swept or new blocks only, and are handed back to their block whenever+ // a collection starts. So cells from them never need marking.// - The list is empty when its head is at the start of a block (or null),// which is where following the link of the last cell leads (see// HeapBlock::follow_freelist_link()).+ // - The cells from the cursor up to the end are cells of the local block+ // that were never allocated, and cell_size apart. There are none when the+ // cursor is at the end.+ struct LocalFreeCells {+ RawPtr<Cell> free_list;+ FlatPtr cursor { 0 };+ FlatPtr end { 0 };+ FlatPtr cell_size { 0 };+ };+ALWAYS_INLINE Cell* allocate_cell(Heap& heap){- if (auto* cell = m_local_free_list.ptr(); !HeapBlock::is_end_of_freelist(cell)) [[likely]] {- m_local_free_list = HeapBlock::next_free_cell(cell);+ if (auto* cell = m_local.free_list.ptr(); !HeapBlock::is_end_of_freelist(cell)) [[likely]] {+ m_local.free_list = HeapBlock::next_free_cell(cell);+ ASAN_UNPOISON_MEMORY_REGION(cell, cell_size());+ return cell;+ }+ if (m_local.cursor < m_local.end) [[likely]] {+ auto* cell = bit_cast<Cell*>(m_local.cursor);+ m_local.cursor += m_local.cell_size;ASAN_UNPOISON_MEMORY_REGION(cell, cell_size());return cell;}return allocate_cell_slow(heap);}- // Hands the local free list back to the local block.+ // Hands the local free cells back to the local block.void give_back_local_free_list(Badge<Heap>);- // For code that pops the local free list itself, see gc_heap_allocator_local_free_list().- RawPtr<Cell>* local_free_list(Badge<CAPI>) { return &m_local_free_list; }+ // For code that allocates from the local free cells itself, see gc_heap_allocator_local_free_list().+ LocalFreeCells* local_free_cells(Badge<CAPI>) { return &m_local; }template<typename Callback>IterationDecision for_each_block(Callback callback)@@ -136,7 +153,7 @@ private:Cell* allocate_cell_slow(Heap&);CellAllocatorDescriptorBase& m_descriptor;- RawPtr<Cell> m_local_free_list;+ LocalFreeCells m_local;HeapBlock* m_local_block { nullptr };BlockAllocator& m_block_allocator;diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 689d723011b..a43a91295eb 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -581,6 +581,11 @@ AK::JsonObject Heap::build_graph(ReadonlySpan<FlatPtr> callee_saved_registers).callee_saved_registers = callee_saved_registers,};+ // NB: While an allocator has a block's never-allocated cells out, the block counts them as cells, and the+ // conservative scan in gather_roots() would take a possible pointer into one for a live cell. Give them back,+ // as a collection does, so that they are the block's lazy region again.+ give_back_local_free_lists();+// An in-progress incremental sweep would leave parts of the heap as freelist// entries while the conservative scan in gather_roots() can still pick up// not-yet-swept (but unreachable) cells whose internal pointers lead to@@ -772,6 +777,10 @@ void Heap::run_post_gc_tasks()void Heap::dump_allocators(){+ // NB: While an allocator has a block's never-allocated cells out, the block counts them as cells. Give them back,+ // so that they are the block's lazy region again and are not counted.+ give_back_local_free_lists();+size_t total_in_committed_blocks = 0;size_t total_waste = 0;for (auto& allocator : m_all_cell_allocators) {diff --git a/Libraries/LibGC/HeapBlock.cpp b/Libraries/LibGC/HeapBlock.cppindex a6d70504bd7..1ac9c05670f 100644--- a/Libraries/LibGC/HeapBlock.cpp+++ b/Libraries/LibGC/HeapBlock.cpp@@ -37,32 +37,37 @@ HeapBlock::HeapBlock(Heap& heap, CellAllocator& cell_allocator)ASAN_POISON_MEMORY_REGION(m_storage, BLOCK_SIZE - sizeof(HeapBlock));}-Cell* HeapBlock::take_free_cells()+HeapBlock::FreeCells HeapBlock::take_free_cells(){- auto head = bit_cast<FlatPtr>(freelist_head());+ FreeCells free_cells {+ .free_list = freelist_head(),+ .lazy_start = bit_cast<FlatPtr>(cell(m_next_lazy_freelist_index)),+ .lazy_end = bit_cast<FlatPtr>(cell(cell_count())),+ };+ // NB: Inline allocators bump through these cells without further checks, so make sure they are within the block.+ VERIFY(free_cells.lazy_start <= free_cells.lazy_end);+ VERIFY(free_cells.lazy_end <= bit_cast<FlatPtr>(this) + BLOCK_SIZE);m_freelist = 0;-- // NB: The lazily initialized cells come first, in address order.- for (size_t index = cell_count(); index-- > m_next_lazy_freelist_index;) {- auto* free_cell = cell(index);- ASAN_UNPOISON_MEMORY_REGION(free_cell, sizeof(FreelistEntry));- auto* freelist_entry = new (free_cell) FreelistEntry();- freelist_entry->set_state(Cell::State::Dead);- freelist_entry->next = head;- head = bit_cast<FlatPtr>(freelist_entry);- }m_next_lazy_freelist_index = cell_count();- return bit_cast<Cell*>(head);+ return free_cells;}-void HeapBlock::give_back_free_cells(Cell* cells)+void HeapBlock::give_back_free_cells(Cell* free_list, FlatPtr lazy_cursor){// NB: take_free_cells() left the block without free cells of its own, and nothing frees cells in a block while// its free cells are out, so the list becomes the block's free list as it is. Its links can only lead into// this block (see follow_freelist_link()).VERIFY(is_end_of_freelist(freelist_head()));- VERIFY(is_end_of_freelist(cells) || is_valid_cell_pointer(cells));- m_freelist = bit_cast<FlatPtr>(cells);+ VERIFY(!has_lazy_freelist());+ VERIFY(is_end_of_freelist(free_list) || is_valid_cell_pointer(free_list));+ m_freelist = bit_cast<FlatPtr>(free_list);++ auto storage = reinterpret_cast<FlatPtr>(m_storage);+ VERIFY(lazy_cursor >= storage);+ VERIFY((lazy_cursor - storage) % m_cell_size == 0);+ auto lazy_index = (lazy_cursor - storage) / m_cell_size;+ VERIFY(lazy_index <= cell_count());+ m_next_lazy_freelist_index = lazy_index;}void HeapBlock::deallocate(Cell* cell)diff --git a/Libraries/LibGC/HeapBlock.h b/Libraries/LibGC/HeapBlock.hindex dd68b6225a6..fa5720c3821 100644--- a/Libraries/LibGC/HeapBlock.h+++ b/Libraries/LibGC/HeapBlock.h@@ -55,12 +55,24 @@ public:// found unmarked.void deallocate(Cell*);- // Takes every free cell of the block as a list linked through- // freelist_next_offset, leaving the block full. The cells are dead.- Cell* take_free_cells();+ // The free cells of a block: the cells that were freed, as a list linked+ // through freelist_next_offset, and the cells that were never allocated,+ // which are the cells from lazy_start up to lazy_end.+ struct FreeCells {+ RawPtr<Cell> free_list;+ FlatPtr lazy_start { 0 };+ FlatPtr lazy_end { 0 };+ };++ // Takes every free cell of the block, leaving the block full. The cells+ // that were never allocated are taken as they are, without writing them.+ FreeCells take_free_cells();- // Gives back a list of free cells taken from this block.- void give_back_free_cells(Cell*);+ // Gives back the free cells of a list taken from this block, and the+ // cells from lazy_cursor up to the end of the block, which must be the+ // part of the never-allocated cells taken from this block that is still+ // unallocated.+ void give_back_free_cells(Cell* free_list, FlatPtr lazy_cursor);// The offset of the link to the next cell in a free cell.static constexpr size_t freelist_next_offset();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rsindex 79ae236967f..e181aa98ad6 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs@@ -5,9 +5,10 @@*///! Allocation in JIT code, per the allocation contract (see-//! `ObjectAllocationInfo`): a cell from the size class's local free list,-//! entirely inline, and a call of the runtime out of line when the list is-//! empty or the heap wants to collect garbage.+//! `ObjectAllocationInfo`): a cell from the size class's local free list or+//! its never-allocated cells, entirely inline, and a call of the runtime out+//! of line when there is no local free cell or the heap wants to collect+//! garbage.use super::Codegen;use super::call::ConstantField;@@ -359,23 +360,27 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.add64_to_memory_imm(&Address::new(heap, total), byte_count(total_bytes));}- /// Pops a cell off the local free list of `allocator` into `cell`, or- /// branches to `slow` if it is empty. Clobbers `temp` and the scratch- /// register.+ /// Takes a local free cell of `allocator` into `cell`, or branches to+ /// `slow` if there is none. Clobbers `temp` and the scratch register.pub(super) fn emit_pop_free_list(&mut self, allocator: u64, cell: Gpr, temp: Gpr, slow: Label) {let scratch = self.pinned.scratch;self.masm.move_imm64(scratch, allocator);self.emit_pop_free_list_of(scratch, cell, temp, slow);}- /// Pops a cell off the local free list of the allocator in `allocator`- /// into `cell`, or branches to `slow` if it is empty. Clobbers `temp`.+ /// Takes a local free cell of the allocator in `allocator` into `cell`:+ /// the head of its local free list, or else its next never-allocated+ /// cell, or branches to `slow` if there is neither. Clobbers `temp`.pub(super) fn emit_pop_free_list_of(&mut self, allocator: Gpr, cell: Gpr, temp: Gpr, slow: Label) {let info = &self.runtime.object_allocation;let head = Address::new(allocator, info.local_free_list_offset as i32);let (next, link_mask) = (info.freelist_next_offset as i32, u64::from(info.freelist_link_mask));+ let cursor = Address::new(allocator, info.local_cursor_offset as i32);+ let end = Address::new(allocator, info.local_end_offset as i32);+ let cell_size = Address::new(allocator, info.local_cell_size_offset as i32);+ let (bump, done) = (self.masm.new_label(), self.masm.new_label());self.masm.load64(cell, &head);- self.masm.branch_test64(Condition::Zero, cell, link_mask, slow);+ self.masm.branch_test64(Condition::Zero, cell, link_mask, bump);// NB: The next cell is the cell's address with the link's bits under// the mask, so it is in the cell's block whatever the link is.self.masm.load64(temp, &Address::new(cell, next));@@ -383,6 +388,30 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.and64_imm(temp, temp, link_mask);self.masm.xor64(temp, temp, cell);self.masm.store64(&head, temp);+ self.masm.jump(done);+ self.masm.bind(bump);+ self.masm.load64(cell, &cursor);+ self.masm.branch64_memory(Condition::BelowOrEqual, &end, cell, slow);+ self.masm.load64(temp, &cell_size);+ self.masm.add64(temp, temp, cell);+ self.masm.store64(&cursor, temp);+ self.masm.bind(done);+ }++ /// Branches to `slow` unless the allocator in `allocator` has a local+ /// free cell. Clobbers `temp`.+ fn emit_branch_if_no_local_free_cell(&mut self, allocator: Gpr, temp: Gpr, slow: Label) {+ let info = &self.runtime.object_allocation;+ let head = Address::new(allocator, info.local_free_list_offset as i32);+ let cursor = Address::new(allocator, info.local_cursor_offset as i32);+ let end = Address::new(allocator, info.local_end_offset as i32);+ let has_cell = self.masm.new_label();+ self.masm.load64(temp, &head);+ self.masm+ .branch_test64(Condition::NonZero, temp, u64::from(info.freelist_link_mask), has_cell);+ self.masm.load64(temp, &cursor);+ self.masm.branch64_memory(Condition::BelowOrEqual, &end, temp, slow);+ self.masm.bind(has_cell);}/// The array of `count` packed elements, all undefined (see@@ -431,13 +460,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// Only the array cell counts towards the next collection.self.emit_check_heap_threshold(info.cell_size, array, temp, entry);- // NB: Both free lists must have a cell before either gives one.+ // NB: Both allocators must have a free cell before either gives one.let storage_size_class = storage_size_class.filter(|_| count != 0);if let Some(size_class) = storage_size_class {self.masm.move_imm64(scratch, size_class.allocator);- self.masm.load64(temp, &at(scratch, objects.local_free_list_offset));- self.masm- .branch_test64(Condition::Zero, temp, u64::from(objects.freelist_link_mask), entry);+ self.emit_branch_if_no_local_free_cell(scratch, temp, entry);}self.emit_pop_free_list(info.allocator, array, temp, entry);if let Some(size_class) = storage_size_class {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex aa796009ffc..17611fe52bb 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -3388,17 +3388,32 @@ mod direct_calls {assert_eq!(machine.vm[3], callee.interpreter_stack.as_ptr() as u64);}+ /// Where a test's local free cell is, if it has one.+ #[derive(Clone, Copy, PartialEq, Eq)]+ enum FreeCell {+ InList,+ NeverAllocated,+ None,+ }+#[test]fn direct_calls_allocate_the_function_environments_of_their_callees() {// A fake heap (allocated, threshold and total bytes), and the- // local free list of one cell, which has room for 12 words and- // two binding values, and links to the next cell with `link`.- let run = |threshold: u64, free_cell: bool, link: u64| {+ // local free cells: a list of one cell, which has room for 12+ // words and two binding values, and links to the next cell with+ // `link`, or else that cell as the only never-allocated cell.+ let run = |threshold: u64, free_cell: FreeCell, link: u64| {let mut callee = Callee::new();let mut heap = vec![100u64, threshold, 1000];let mut block = FakeBlock::new(14, 0x5a5a_5a5a_5a5a_5a5a);block.0[FakeBlock::CELL] = link;- let mut free_list = vec![if free_cell { block.cell().as_ptr() as u64 } else { 0 }];+ // NB: The head of the free list, then the cursor, the end and the cell size of the never-allocated cells.+ let address = block.cell().as_ptr() as u64;+ let mut free_list = match free_cell {+ FreeCell::InList => vec![address, 0, 0, 14 * 8],+ FreeCell::NeverAllocated => vec![0, address, address + 14 * 8, 14 * 8],+ FreeCell::None => vec![0, 0, 0, 14 * 8],+ };let template = crate::snapshot::EnvironmentTemplateSnapshot {allocator: free_list.as_mut_ptr() as u64,cell_size: 14 * 8,@@ -3428,6 +3443,9 @@ mod direct_calls {allocation.local_free_list_offset = 0;allocation.freelist_next_offset = 0;allocation.freelist_link_mask = FakeBlock::LINK_MASK;+ allocation.local_cursor_offset = 8;+ allocation.local_end_offset = 16;+ allocation.local_cell_size_offset = 24;});assert!(compiled.embedded_cells.contains(&CellId(0xcafe)));let mut machine = Machine::new(@@ -3454,29 +3472,39 @@ mod direct_calls {)};- let (result, frames, generic_calls, heap, block, free_list, popped) = run(10_000, true, 0);- assert_eq!((result, generic_calls), (returned(value::int32(99)), 0));- let cell = block.cell();- let address = cell.as_ptr() as u64;- let mut expected = (0..12).map(|index| 0x1000 + index).collect::<Vec<u64>>();- expected[6] = address + 96;- expected[9] = value::TRUE;- assert_eq!(cell[..12], expected[..]);- assert_eq!(heap, [100 + 112, 10_000, 1000 + 112]);- assert_eq!(free_list[0], block.address(), "the end of the free list");- // The callee's lexical and variable environments, and its `this`.- let frame = &frames[0];- assert_eq!((frame[1], frame[12], frame[15]), (address, address, value::TRUE));- assert!(popped);+ for free_cell in [FreeCell::InList, FreeCell::NeverAllocated] {+ let (result, frames, generic_calls, heap, block, free_list, popped) = run(10_000, free_cell, 0);+ assert_eq!((result, generic_calls), (returned(value::int32(99)), 0));+ let cell = block.cell();+ let address = cell.as_ptr() as u64;+ let mut expected = (0..12).map(|index| 0x1000 + index).collect::<Vec<u64>>();+ expected[6] = address + 96;+ expected[9] = value::TRUE;+ assert_eq!(cell[..12], expected[..]);+ assert_eq!(heap, [100 + 112, 10_000, 1000 + 112]);+ if free_cell == FreeCell::InList {+ assert_eq!(free_list[0], block.address(), "the end of the free list");+ } else {+ assert_eq!(free_list[..3], [0, address + 112, address + 112], "the advanced cursor");+ }+ // The callee's lexical and variable environments, and its `this`.+ let frame = &frames[0];+ assert_eq!((frame[1], frame[12], frame[15]), (address, address, value::TRUE));+ assert!(popped);+ }// Whatever a free cell's link was overwritten with, the next cell// is in the cell's block.- let (_, _, _, _, block, free_list, _) = run(10_000, true, 0x7f12_3456_0000_0040);+ let (_, _, _, _, block, free_list, _) = run(10_000, FreeCell::InList, 0x7f12_3456_0000_0040);assert_eq!(free_list[0], block.address() + 0x40, "the next cell");// Without room before the next collection, or without free// cells, the call takes the generic path and frees its frame.- for (threshold, free_cell) in [(150, true), (10_000, false)] {+ for (threshold, free_cell) in [+ (150, FreeCell::InList),+ (150, FreeCell::NeverAllocated),+ (10_000, FreeCell::None),+ ] {let (result, frames, generic_calls, heap, _, _, popped) = run(threshold, free_cell, 0);assert_eq!(result.status, RETURNED);assert_eq!((frames.len(), generic_calls, heap[0]), (0, 1, 100));@@ -3817,11 +3845,17 @@ mod direct_calls {let mut callee = DynamicCallee::new(1, flags);let mut heap = vec![100u64, 10_000, 1000];let block = FakeBlock::new(8, 0x5a5a);- let mut free_list = vec![if case.free_cell {- block.cell().as_ptr() as u64- } else {- 0- }];+ // NB: The head of the free list, then an empty range of never-allocated cells.+ let mut free_list = vec![+ if case.free_cell {+ block.cell().as_ptr() as u64+ } else {+ 0+ },+ 0,+ 0,+ 64,+ ];// The free lists of size classes 0 to 3: the template's size// class 6 masks to 2.let free_lists = vec![0, 0, free_list.as_mut_ptr() as u64, 0];@@ -3860,6 +3894,9 @@ mod direct_calls {allocation.heap_threshold_offset = 8;allocation.heap_total_allocated_bytes_offset = 16;allocation.freelist_link_mask = FakeBlock::LINK_MASK;+ allocation.local_cursor_offset = 8;+ allocation.local_end_offset = 16;+ allocation.local_cell_size_offset = 24;install_call_stub(&mut snapshot.runtime);snapshot.executables[0].feedback.call = vec![CallFeedbackSnapshot {target: Some(CellId(CALL_FUNCTION)),diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 79337135729..8621cac82e9 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -1130,16 +1130,22 @@ pub struct DynamicCallLayout {/// `allocated + cell_size` > the u64 at `heap + heap_threshold_offset`,/// take the slow path (the heap collects garbage there)./// 3. Let `cell` = the pointer at `allocator + local_free_list_offset`. If-/// `cell & freelist_link_mask` is 0, the list is empty: take the slow-/// path (it refills the list).-/// 4. Let `link` = the u64 at `cell + freelist_next_offset`. Store+/// `cell & freelist_link_mask` is 0, the list is empty: go to step 4.+/// Otherwise let `link` = the u64 at `cell + freelist_next_offset`, store/// `(cell & !freelist_link_mask) | (link & freelist_link_mask)`, the next/// cell, which is in the block of `cell` whatever `link` is (cells are in/// the heap region, where anything may have been corrupted), to-/// `allocator + local_free_list_offset`, `allocated + cell_size` to-/// `heap + heap_allocated_bytes_offset`, and add `cell_size` to the u64 at+/// `allocator + local_free_list_offset`, and go to step 5.+/// 4. Let `cell` = the pointer at `allocator + local_cursor_offset`. If it is+/// not below the pointer at `allocator + local_end_offset`, take the slow+/// path (it refills the list and the cursor). Otherwise store `cell` plus+/// the u64 at `allocator + local_cell_size_offset` to+/// `allocator + local_cursor_offset`. These words are outside the heap+/// region.+/// 5. Store `allocated + cell_size` to `heap + heap_allocated_bytes_offset`,+/// and add `cell_size` to the u64 at/// `heap + heap_total_allocated_bytes_offset`.-/// 5. Copy `template` (`8 * template.len()` bytes, the start of every cell) to+/// 6. Copy `template` (`8 * template.len()` bytes, the start of every cell) to/// `cell`. Then store `inline_capacity` (a u8) at/// `cell + inline_capacity_offset`, the shape at `cell + shape_offset`,/// `cell + inline_storage_offset` (the address) at@@ -1149,9 +1155,9 @@ pub struct DynamicCallLayout {/// initialized yet) followed by NaN-boxed `undefined` up to/// `inline_capacity` values.///-/// No garbage can be collected between steps 2 and 5, and the cell needs no-/// marking: local free lists only ever hold cells of blocks that the-/// incremental sweep is done with.+/// No garbage can be collected between steps 2 and 6, and the cell needs no+/// marking: local free lists and never-allocated cells only ever come from+/// blocks that the incremental sweep is done with.////// Slow path: `Object* libjs_jit_allocate_object(VM*, Shape*, u32 reserve)`/// returns a complete object of that shape with every named property@@ -1170,6 +1176,11 @@ pub struct ObjectAllocationInfo {pub local_free_list_offset: u32,pub freelist_next_offset: u32,pub freelist_link_mask: u32,+ /// Where the cursor, the end and the cell size of an allocator's+ /// never-allocated cells are, relative to its `allocator` address.+ pub local_cursor_offset: u32,+ pub local_end_offset: u32,+ pub local_cell_size_offset: u32,/// The bytes every new plain object starts with, as u64 words.pub template: Vec<u64>,pub shape_offset: u32,diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rsindex 536fceb188d..fdf34810e00 100644--- a/Libraries/LibJS/Rust/src/gc/capi.rs+++ b/Libraries/LibJS/Rust/src/gc/capi.rs@@ -59,6 +59,9 @@ pub struct GCLayout {pub weak_impl_pointer_offset: u32,pub free_cell_next_offset: u32,pub free_cell_link_mask: u32,+ pub local_cursor_offset: u32,+ pub local_end_offset: u32,+ pub local_cell_size_offset: u32,pub heap_allocated_bytes_since_last_gc_offset: u32,pub heap_gc_bytes_threshold_offset: u32,pub heap_total_allocated_bytes_offset: u32,diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rsindex 48cfe91540e..2f83c45b23e 100644--- a/Libraries/LibJS/Rust/src/gc/heap.rs+++ b/Libraries/LibJS/Rust/src/gc/heap.rs@@ -49,6 +49,11 @@ pub struct InlineAllocationInfo {pub total_allocated_bytes: NonNull<usize>,pub free_cell_next_offset: usize,pub free_cell_link_mask: usize,+ /// Where an allocator keeps the cursor, the end and the cell size of the never-allocated cells it bumps through+ /// once its local free list is empty, relative to the head of the list.+ pub local_cursor_offset: usize,+ pub local_end_offset: usize,+ pub local_cell_size_offset: usize,}/// An allocator of a heap, with the address of its local free list in the heap, which is null if every cell has to be@@ -163,6 +168,9 @@ impl Heap {total_allocated_bytes: counter(layout.heap_total_allocated_bytes_offset),free_cell_next_offset: layout.free_cell_next_offset as usize,free_cell_link_mask: layout.free_cell_link_mask as usize,+ local_cursor_offset: layout.local_cursor_offset as usize,+ local_end_offset: layout.local_end_offset as usize,+ local_cell_size_offset: layout.local_cell_size_offset as usize,},}}@@ -332,8 +340,9 @@ impl Heap {}}- /// Pops the allocator's local free list, unless LibGC has to collect garbage first or the list is empty, with the- /// bookkeeping gc_heap_allocator_local_free_list() describes. Cells from the list never need marking.+ /// Takes a cell from the allocator's local free list, or else from its never-allocated cells, unless LibGC has to+ /// collect garbage first or there is no local free cell, with the bookkeeping gc_heap_allocator_local_free_list()+ /// describes. These cells never need marking.////// # Safety///@@ -348,13 +357,22 @@ impl Heap {let local_free_list = allocator.local_free_list()?;let info = &self.inline_allocation_info;let link_mask = info.free_cell_link_mask;- // SAFETY: The list and the counters are fields of the live heap, and every cell on the list is a free cell that- // keeps the link to the next one at free_cell_next_offset.+ // SAFETY: The list, the cursor, the end and the counters are fields of the live heap, and every cell on the list+ // is a free cell that keeps the link to the next one at free_cell_next_offset.unsafe {- let cell = local_free_list.read();- if cell.addr() & link_mask == 0 {- return None;- }+ let cursor = local_free_list.byte_add(info.local_cursor_offset).cast::<*mut c_void>();+ let head = local_free_list.read();+ let from_list = head.addr() & link_mask != 0;+ let cell = if from_list {+ head+ } else {+ let cursor_cell = cursor.read();+ let end = local_free_list.byte_add(info.local_end_offset).cast::<usize>().read();+ if cursor_cell.addr() >= end {+ return None;+ }+ cursor_cell+ };let cell = NonNull::new_unchecked(cell);if let AllocationKind::Cell = kind {let allocated_bytes = info.allocated_bytes_since_last_gc.read() + cell_size;@@ -365,13 +383,17 @@ impl Heap {}info.total_allocated_bytes.write(info.total_allocated_bytes.read() + cell_size);- // NB: Only the bits of the link under the mask count, so that the next cell is in the block of this one- // whatever the link was overwritten with.- let link = cell.byte_add(info.free_cell_next_offset).cast::<usize>().read();- local_free_list.write(- cell.as_ptr()- .map_addr(|address| (address & !link_mask) | (link & link_mask)),- );+ if from_list {+ // NB: Only the bits of the link under the mask count, so that the next cell is in the block of this one+ // whatever the link was overwritten with.+ let link = cell.byte_add(info.free_cell_next_offset).cast::<usize>().read();+ local_free_list.write(+ cell.as_ptr()+ .map_addr(|address| (address & !link_mask) | (link & link_mask)),+ );+ } else {+ cursor.write(cell.as_ptr().byte_add(cell_size));+ }Some(cell)}}diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rsindex 2a16c101718..842a0b31887 100644--- a/Libraries/LibJS/Rust/src/jit/allocation.rs+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs@@ -97,6 +97,9 @@ pub fn allocation_infos(vm: &Vm, realm: Gc<Realm>) -> AllocationInfos {local_free_list_offset: 0,freelist_next_offset: offset(inline.free_cell_next_offset),freelist_link_mask: u32::try_from(inline.free_cell_link_mask).expect("links are offsets within a block"),+ local_cursor_offset: offset(inline.local_cursor_offset),+ local_end_offset: offset(inline.local_end_offset),+ local_cell_size_offset: offset(inline.local_cell_size_offset),template: cell_words(object_template, size_of::<Object>()),shape_offset: offset(core::mem::offset_of!(Object, shape)),named_properties_offset: offset(core::mem::offset_of!(Object, named_properties)),diff --git a/Tests/LibGC/TestGCFreeList.cpp b/Tests/LibGC/TestGCFreeList.cppindex e15fdc5b0bf..2e2dac1b7a0 100644--- a/Tests/LibGC/TestGCFreeList.cpp+++ b/Tests/LibGC/TestGCFreeList.cpp@@ -25,25 +25,45 @@ private:GC_DEFINE_ALLOCATOR(FreeListTestCell);+NEVER_INLINE void scrub_stack()+{+ u8 volatile filler[8 * KiB];+ for (size_t i = 0; i < sizeof(filler); ++i)+ filler[i] = 0;+}++NEVER_INLINE void allocate_unreachable_cells(GC::Heap& heap, size_t count)+{+ for (size_t i = 0; i < count; ++i)+ (void)heap.allocate<FreeListTestCell>();+}+}TEST_CASE(a_corrupted_free_cell_link_leads_to_a_cell_of_the_same_block){GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ heap.set_incremental_sweep_enabled(false);- // NB: The first cell comes from a new block, whose free cells the allocator takes in address order.+ // NB: The cells of a new block come in address order.auto first = GC::make_root(heap.allocate<FreeListTestCell>());auto cell_size = GC::HeapBlock::from_cell(first.ptr())->cell_size();auto address_of = [&](size_t index) { return bit_cast<FlatPtr>(first.ptr()) + index * cell_size; };+ allocate_unreachable_cells(heap, 4);+ scrub_stack();++ // The sweep frees the four unreachable cells in address order, so the free list of the block leads from the last+ // of them to the first.+ heap.collect_garbage();- // Overwrite the link of the next free cell with an address outside the heap region that has the offset of the- // fourth cell in its block.+ // Overwrite the link of the cell at the head of the list with an address outside the heap region that has the+ // offset of the second cell after it in its block.auto link_mask = GC::HeapBlock::freelist_link_mask;- auto forged_link = (0x7fff'0000'0000'0000ull & ~link_mask) | (address_of(3) & link_mask);- *bit_cast<FlatPtr*>(address_of(1) + GC::HeapBlock::freelist_next_offset()) = forged_link;+ auto forged_link = (0x7fff'0000'0000'0000ull & ~link_mask) | (address_of(2) & link_mask);+ *bit_cast<FlatPtr*>(address_of(4) + GC::HeapBlock::freelist_next_offset()) = forged_link;auto second = GC::make_root(heap.allocate<FreeListTestCell>());- EXPECT_EQ(bit_cast<FlatPtr>(second.ptr()), address_of(1));+ EXPECT_EQ(bit_cast<FlatPtr>(second.ptr()), address_of(4));auto third = GC::make_root(heap.allocate<FreeListTestCell>());- EXPECT_EQ(bit_cast<FlatPtr>(third.ptr()), address_of(3));+ EXPECT_EQ(bit_cast<FlatPtr>(third.ptr()), address_of(2));}