Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <LibGC/Export.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
// A C interface to LibGC for cell types that are defined outside of C++.
//
// A foreign cell type describes itself with a GCCellTypeInfo, which LibGC dispatches through exactly as it does for
// C++ cells. The foreign side owns the whole cell: gc_heap_allocate_cell() hands out uninitialized storage, and the
// caller writes every byte of the cell, including the header fields at the offsets reported by gc_get_layout(),
// before anything that can collect garbage runs: another allocation, external memory accounting, undeferring,
// an explicit collection, or a return to the event loop.
//
// The first word of a cell, which holds the vtable pointer of a C++ cell, belongs to the foreign side. LibGC never
// reads it, but -fsanitize=vptr instrumentation of LibGC does, so that sanitizer cannot be used with foreign cells.
//
// Like the rest of LibGC, every heap in a process must be used from the same thread.
#ifdef __cplusplus
extern "C" {
#endif
typedef struct GCHeap GCHeap;
typedef struct GCCell GCCell;
typedef struct GCVisitor GCVisitor;
typedef struct GCAllocator GCAllocator;
typedef struct GCRoot GCRoot;
typedef struct GCWeakImpl GCWeakImpl;
typedef void (*GCCallback)(void* context);
// Called whenever the heap gathers its roots. Every cell passed to root_visitor is kept alive by this collection.
// root_visitor only accepts cells and values, not possible values, and the callback must not allocate.
typedef void (*GCGatherRootsCallback)(void* context, GCVisitor* root_visitor);
enum {
GC_CELL_KIND_OTHER = 0,
GC_CELL_KIND_OBJECT = 1,
GC_CELL_KIND_PRIMITIVE_STRING = 2,
GC_CELL_KIND_SYMBOL = 3,
GC_CELL_KIND_BIGINT = 4,
GC_CELL_KIND_ACCESSOR = 5,
};
enum {
GC_CELL_STATE_LIVE = 0,
GC_CELL_STATE_DEAD = 1,
};
enum {
GC_COLLECTION_TYPE_COLLECT_GARBAGE = 0,
GC_COLLECTION_TYPE_COLLECT_EVERYTHING = 1,
};
// Mirrors GC::CellTypeInfo. visit_edges is required; every other function may be null.
typedef struct GCCellTypeInfo {
uint32_t cell_size;
uint32_t alignment;
uint8_t kind;
void (*visit_edges)(GCCell*, GCVisitor*);
void (*finalize)(GCCell*);
void (*destroy)(GCCell*);
size_t (*external_memory_size)(GCCell const*);
char const* (*class_name)(GCCell const*, size_t* length);
} GCCellTypeInfo;
// Everything a foreign implementation of cells needs to agree on with this build of LibGC.
typedef struct GCLayout {
uint32_t cell_state_offset;
uint32_t cell_kind_offset;
uint32_t min_cell_size;
uint32_t max_cell_size;
uint32_t max_cell_alignment;
uint32_t cell_type_info_size;
uint32_t weak_impl_pointer_offset;
// 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;
// A cell's block starts at the cell's address rounded down to a multiple of block_size, and holds the foreign
// type the cell's allocator was created with at block_foreign_type_offset.
uint32_t block_size;
uint32_t block_foreign_type_offset;
uint64_t heap_region_offset_mask;
uint64_t primitive_storage_cage_offset_mask;
// Where a GCVisitor keeps a pointer to the marker it marks for, which is null in visitors that do not mark. Code that
// visits can hand cells to the marker directly, with gc_marker_visit_cell() and gc_marker_visit_values().
uint32_t visitor_marker_offset;
// Where a cell keeps the state of its identity hash, and the bits of that state (see gc_cell_identity_hash()).
uint32_t identity_hash_state_offset;
uint8_t identity_hash_hashed;
uint8_t identity_hash_moved;
} GCLayout;
// The caller passes the size of its GCLayout, which must match LibGC's, so that a mirror that drifted is caught before
// anything is written to it.
GC_API void gc_get_layout(GCLayout*, size_t layout_size);
// The base of the region all cells are allocated from, which NaN-boxed cell pointers are relative to. Reserves the
// region on first use.
GC_API uintptr_t gc_heap_region_base(void);
GC_API uintptr_t gc_primitive_storage_cage_base(void);
GC_API GCHeap* gc_heap_create(GCGatherRootsCallback, void* context, bool become_thread_default);
// Finalizes and destroys every remaining cell. Roots created with gc_root_create() must be destroyed first. The final
// collection also runs every sweep callback and pending post-GC task, with gc_heap_is_collecting_everything() true,
// so their contexts must stay valid until this returns; nothing they allocate then is destroyed.
GC_API void gc_heap_destroy(GCHeap*);
GC_API void gc_heap_collect_garbage(GCHeap*, int collection_type, bool print_report);
// Collects garbage without scanning the stack, so only the roots the heap knows of keep cells alive, and cells may move.
// The caller must hold no cell that it did not root.
GC_API void gc_heap_collect_garbage_without_scanning_the_stack(GCHeap*);
// Whether LIBGC_MOVE_EVERYTHING is set, see Heap::moves_everything().
GC_API bool gc_heap_moves_everything(void);
// See Heap::set_moves_everything_for_testing().
GC_API void gc_heap_set_moves_everything_for_testing(GCHeap*, bool);
GC_API bool gc_heap_is_collecting_everything(GCHeap const*);
// Whether the heap gathers its roots and marks the live cells for a collection now, rather than for a graph dump.
GC_API bool gc_heap_is_marking_for_collection(GCHeap const*);
// Whether the collection that runs is there to give memory back to the system, for a process that is short of it.
GC_API bool gc_heap_is_returning_memory_to_system(GCHeap const*);
GC_API void gc_heap_defer_gc(GCHeap*);
GC_API void gc_heap_undefer_gc(GCHeap*);
GC_API void gc_heap_deferral_state(GCHeap*, size_t** deferrals, bool** collect_when_deferrals_end);
GC_API bool gc_heap_should_collect_on_every_allocation(GCHeap const*);
GC_API void gc_heap_set_should_collect_on_every_allocation(GCHeap*, bool);
GC_API void gc_heap_set_incremental_sweep_enabled(GCHeap*, bool);
GC_API void gc_heap_uproot_cell(GCHeap*, GCCell*);
// The bounds of the stack of the thread that created the heap; base is the lowest address.
GC_API void gc_heap_stack_bounds(GCHeap const*, uintptr_t* base, uintptr_t* top);
GC_API void gc_heap_enqueue_post_gc_task(GCHeap*, GCCallback, void* context);
// Runs during every collection after marking and finalization and before dead cells are swept, when weak holders can
// drop the cells that did not survive. There is no way to unregister a sweep callback, and it also runs when the heap
// is destroyed.
GC_API void gc_heap_register_sweep_callback(GCHeap*, GCCallback, void* context);
GC_API void gc_heap_did_allocate_external_memory(GCHeap*, size_t);
GC_API void gc_heap_did_free_external_memory(GCHeap*, size_t);
// The type info and the name must outlive the allocator, and the allocator must outlive every heap it allocated from.
// The blocks of the allocator hold foreign_type, which also names the type of the cells for the whole process:
// allocators with the same foreign_type and cell size share a pool of blocks, across all heaps, and blocks never leave
// their pool. Different types must have different ones. An allocator without one has a pool of its own, and must never
// be destroyed.
GC_API GCAllocator* gc_allocator_create(GCCellTypeInfo const*, char const* name, size_t name_length, void const* foreign_type);
GC_API void gc_allocator_destroy(GCAllocator*);
// Cells of allocators created here may be traced on any thread while the collector marks, as long as the thread that
// owns their heap is stopped. This has the cells of an allocator traced only on that thread instead, for types whose
// visit_edges() or external_memory_size() reach state that is not their own. It must be called before the allocator
// allocates a cell.
GC_API void gc_allocator_set_traced_on_owner_thread_only(GCAllocator*);
// Lets collections move the cells of the allocator to other blocks of it, in collections that do not scan the stack. A
// cell moves as a bytewise copy, its old slot is freed without destroying it, and every slot that marking visited
// through gc_marker_visit_member(), gc_marker_visit_values(), gc_marker_visit_owned_values(),
// gc_marker_visit_interior_pointer() or gc_marker_visit_self_pointer() is rewritten. A cell that something visits by
// value, through gc_marker_visit_cell() or as a root, or that gc_marker_pin_cell() pins, stays where it is. So a type
// may only be movable if everything that keeps its address without visiting it as a slot either pins it or forgets it
// (see gc_cell_will_move()). It must be called before the allocator allocates a cell.
GC_API void gc_allocator_set_movable(GCAllocator*);
// Returns uninitialized storage for one cell.
GC_API GCCell* gc_heap_allocate_cell(GCHeap*, GCAllocator*);
// Like gc_heap_allocate_cell(), for cells that other cells keep their storage in instead of malloc memory: it never
// collects garbage, so storage can grow while its owner is between states nothing may observe, and callers can hold on
// to anything across the growth. It still counts towards the next collection, which the next allocation that may
// collect starts.
GC_API GCCell* gc_heap_allocate_storage_cell(GCHeap*, GCAllocator*);
// 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).
// - 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.
// - 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 but add N to both as well. 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().
// 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*);
// The type info the cell's block was allocated with.
GC_API GCCellTypeInfo const* gc_cell_type_info(GCCell const*);
// Whether the last collection marked the cell. Only meaningful from the end of marking until the cell is swept, as in a
// sweep callback.
GC_API bool gc_cell_is_marked(GCCell const*);
// Whether the collection in progress moves the cell once marking is done, as a sweep callback may ask. A cache that keeps
// cells by address without visiting them drops such a cell, as if it died.
GC_API bool gc_cell_will_move(GCCell const*);
// Whether the collection in progress may move cells.
GC_API bool gc_heap_is_moving_cells(GCHeap const*);
// What a slot handed to gc_heap_record_slot() holds.
enum {
// A NaN-boxed value, which may hold a cell.
GC_RECORDED_SLOT_VALUE = 0,
// A raw pointer to the start of a cell, or null.
GC_RECORDED_SLOT_CELL_POINTER = 1,
};
// Has the collection in progress rewrite a slot that marking did not visit through it if its cell moves, as it rewrites
// the slots marking visited. Holders that keep cells without keeping them alive or in place, like weak maps, hand over
// the slots of the cells that survived from a sweep callback, once they forgot those that died. The cell must be marked,
// and nothing may free, move or write the slot until the collection is over. Does nothing if no cell moves.
GC_API void gc_heap_record_slot(GCHeap*, void const* slot, int kind);
// A 32-bit hash of the cell's identity, which stays the same while the cell lives, wherever the collector moves it.
// Hashing a cell for the first time sets the "hashed" bit of the byte at identity_hash_state_offset; while the "moved"
// bit is clear, the hash is the cell's compressed address, so code may compute it inline (see GC::identity_hash()) and
// call this only for cells whose "moved" bit is set.
GC_API uint32_t gc_cell_identity_hash(GCCell const*);
GC_API GCRoot* gc_root_create(GCCell*);
GC_API void gc_root_destroy(GCRoot*);
GC_API GCCell* gc_root_cell(GCRoot const*);
// Weak references are returned with one reference already taken, which the caller releases with
// gc_weak_impl_unref(). The pointer lives at weak_impl_pointer_offset and becomes null once the cell is collected.
GC_API GCWeakImpl* gc_heap_create_weak_impl(GCHeap*, GCCell*);
GC_API GCWeakImpl* gc_weak_impl_null(void);
GC_API void gc_weak_impl_ref(GCWeakImpl*);
GC_API void gc_weak_impl_unref(GCWeakImpl*);
GC_API void gc_visitor_visit_cell(GCVisitor*, GCCell*);
GC_API void gc_visitor_visit_cells(GCVisitor*, GCCell* const*, size_t count);
GC_API void gc_visitor_visit_values(GCVisitor*, uint64_t const*, size_t count);
// Visits a NaN-boxed value that is reachable only while key is, such as a WeakMap entry's. A collection that moves cells
// keeps both where they are.
GC_API void gc_visitor_visit_ephemeron(GCVisitor*, GCCell* key, uint64_t const* value);
// The marker a marking GCVisitor points to (see GCLayout::visitor_marker_offset), which these hand cells to directly.
typedef struct GCMarker GCMarker;
// Visits the cell by value, which keeps it from moving.
GC_API void gc_marker_visit_cell(GCMarker*, GCCell*);
// Visits the values, whose slots a collection that moves cells rewrites if they are in a cell.
GC_API void gc_marker_visit_values(GCMarker*, uint64_t const*, size_t count);
// Visits values in memory that the cell being visited owns outside the heap, whose slots a collection that moves cells
// rewrites where they are, like those in cells. Nothing may free, move or write that memory until the collection is
// over: no finalizer, destructor or sweep callback may touch it.
GC_API void gc_marker_visit_owned_values(GCMarker*, uint64_t const*, size_t count);
// Visits the cell that the compressed pointer in the slot points to, if it is not null. A collection that moves cells
// rewrites the slot if it is in a cell, and keeps the cell where it is otherwise.
GC_API void gc_marker_visit_member(GCMarker*, uint32_t const* slot);
// Visits a cell that the pointer in the slot points into, past its start, like the values of storage a cell keeps.
GC_API void gc_marker_visit_interior_pointer(GCMarker*, uintptr_t const* slot, GCCell* cell);
// Notes a pointer in the slot to somewhere in the cell that holds it, up to one past its end, which a collection that
// moves the cell keeps pointing into the copy.
GC_API void gc_marker_visit_self_pointer(GCMarker*, uintptr_t const* slot);
// Keeps the cell from moving without keeping it alive, for a weak reference that the collector cannot update.
GC_API void gc_marker_pin_cell(GCMarker*, GCCell const*);
// Marks value once key is marked, like gc_visitor_visit_ephemeron(), without keeping either from moving. The holder must
// hand the slots of both to gc_heap_record_slot() if the entry survives the collection.
GC_API void gc_marker_visit_ephemeron_without_pinning(GCMarker*, GCCell* key, GCCell* value);
// Primitive storage holds byte buffers inside the cage that starts at gc_primitive_storage_cage_base(), so that the
// interpreter can reach any of their bytes as a cage offset masked with primitive_storage_cage_offset_mask. Like the
// heap, primitive storage is not thread-safe, and every call must come from the thread that uses the heap.
//
// A handle crosses this interface as one 64-bit word: the generation of its table entry in the high 32 bits and the
// index of that entry in the low 32 bits. Generations start at 1, so GC_PRIMITIVE_STORAGE_NULL_HANDLE never names
// storage. Freeing storage moves its entry to the next generation, after which every function treats the old handle
// as naming no storage.
typedef uint64_t GCPrimitiveStorageHandle;
#define GC_PRIMITIVE_STORAGE_NULL_HANDLE ((GCPrimitiveStorageHandle)0)
#define GC_PRIMITIVE_STORAGE_HANDLE_GENERATION_SHIFT 32
#define GC_PRIMITIVE_STORAGE_INVALID_OFFSET SIZE_MAX
// Where storage is in the cage and how large it is. An owner may keep the layout at hand, since only creating and
// resizing the storage change it.
typedef struct GCPrimitiveStorageLayout {
size_t offset;
size_t size;
size_t capacity;
} GCPrimitiveStorageLayout;
// The functions that create storage write its handle to *out_handle and return true, or write
// GC_PRIMITIVE_STORAGE_NULL_HANDLE and return false when the cage or the system is out of memory. With zero_fill, the
// first size bytes start out zero; without it, their contents are unspecified. The functions that create or resize
// storage also write its new layout to *out_layout when they succeed, unless out_layout is null.
//
// Storage of size bytes, which may share pages with other small storage.
GC_API bool gc_primitive_storage_allocate(size_t size, bool zero_fill, GCPrimitiveStorageHandle* out_handle, GCPrimitiveStorageLayout* out_layout);
// Storage of size bytes in a reservation of its own: capacity bytes followed by guard_size inaccessible bytes, both
// rounded up to whole pages. Only the pages the size covers are committed. Fails if size is greater than capacity.
GC_API bool gc_primitive_storage_reserve(size_t size, size_t capacity, bool zero_fill, size_t guard_size, GCPrimitiveStorageHandle* out_handle, GCPrimitiveStorageLayout* out_layout);
// Maps the first size bytes of the shared memory object behind fd into the cage. The mapping keeps the memory alive by
// itself, so the caller keeps ownership of fd and may close it at any time. Fails if size is 0. Growing the storage
// would replace the mapping with private memory, so shared storage keeps its size.
// The resizing functions return false and leave the storage as it was if the handle names no storage or memory runs
// out. Within the capacity, the storage stays where it is; beyond it, the bytes move to new storage, which changes the
// offset and the data pointer.
GC_API bool gc_primitive_storage_resize(GCPrimitiveStorageHandle, size_t new_size, bool zero_fill, GCPrimitiveStorageLayout* out_layout);
// Grows the capacity to at least new_capacity, moving the storage into a reservation of its own if it has to grow.
GC_API bool gc_primitive_storage_reserve_capacity(GCPrimitiveStorageHandle, size_t new_capacity, GCPrimitiveStorageLayout* out_layout);
// Sets the size and grows the capacity to at least new_capacity, moving the storage at most once. Fails if new_size
// is greater than new_capacity.
GC_API bool gc_primitive_storage_resize_and_reserve(GCPrimitiveStorageHandle, size_t new_size, size_t new_capacity, bool zero_fill, GCPrimitiveStorageLayout* out_layout);
// Does nothing if the handle names no storage.
GC_API void gc_primitive_storage_free(GCPrimitiveStorageHandle);
// For a handle that names no storage, the offset is GC_PRIMITIVE_STORAGE_INVALID_OFFSET, the sizes are 0 and the data
// pointer is null.
GC_API bool gc_primitive_storage_is_valid(GCPrimitiveStorageHandle);
// The offset of the first byte from gc_primitive_storage_cage_base().
GC_API size_t gc_primitive_storage_offset(GCPrimitiveStorageHandle);
GC_API size_t gc_primitive_storage_size(GCPrimitiveStorageHandle);
GC_API size_t gc_primitive_storage_capacity(GCPrimitiveStorageHandle);
// The bytes from the offset on that are backed by memory.
GC_API size_t gc_primitive_storage_committed_size(GCPrimitiveStorageHandle);
GC_API uint8_t* gc_primitive_storage_data(GCPrimitiveStorageHandle);
#ifdef __cplusplus
}
#endif