Preface
This book explains how paragc works, from the first alloc to a heap shared
by several processes. It is written for two kinds of readers:
- Users who embed paragc in a Rust program (a language runtime such as j8, a database, a graph library) and want to know what each API promises and what it costs.
- Contributors who want to change the collector and need the invariants that hold it together.
paragc is a tracing garbage collector with an Immix-style mark-region heap. Many threads allocate at once, collections
mark and sweep on every core, and nothing in it takes a lock. On Linux, the crossheap feature adds heaps that live in
shared memory: other processes map them, read and write their objects, and find objects by a signature.
How to read it
| Part | What it covers |
|---|---|
| Garbage collection | What a garbage collector is and the concepts every collector is built from; the first collectors (1960 onwards); the JVM’s collectors; cppgc, V8’s C++ heap; and how paragc descends from them |
| Getting started | What paragc is, a first program, the handle types and why they carry brands |
| The private heap | The in-process heap: layout, allocation, marking, sweeping, concurrent work, evacuation, young collections, reference counting, weak references |
| Between heaps | Direct references from one private heap into another, and collecting cycles that span them |
| Cross-heap | Heaps on shared memory: address space, file layout, objects without code, processes that die at any moment, weak references and signatures across processes, promotion of private objects into a cross-heap |
| Quality and roadmap | Tests, Miri, benchmarks, code rules, known limits and what comes next |
Every page states the current behaviour of the code on main. When a page and the code disagree, the code wins; please
open an issue or use the edit link at the top of the page.
Versions
This edition describes paragc 0.6.1:
- 0.6.0 added cross-heap weak references, signatures, the mailbox, shrinking and promotion;
- 0.6.1 added tail allocation.
The crate is on crates.io and its API reference is on docs.rs.
What a garbage collector is
A program allocates memory for its data: a list node, a string, an object. At some point the data is no longer needed and the memory should be reused. Someone has to decide when.
- In C, the programmer decides:
mallocgives memory,freegives it back. Free too early and the program reads memory that now belongs to something else (use-after-free). Forget to free and memory leaks. Free twice and the allocator’s own bookkeeping breaks. - In Rust, the compiler decides for most data: every value has one owner, and the value is dropped when the owner goes
out of scope. This works as long as the data forms a tree. Graphs with cycles, or data shared without a clear owner,
need
Rc/Arc(reference counting) or an arena, each with its own limits. - A garbage collector (GC) decides at run time, by looking at the data itself. Memory that the program can no longer reach is garbage; the collector finds it and reuses it. The program only allocates and never frees.
The program is called the mutator: from the collector’s point of view, all it does is change (mutate) the graph of objects. The collector is the other party, which reclaims what the mutator can no longer use.
Reachability
A collector cannot know which objects the program will use in the future; that is undecidable in general. It uses a safe approximation instead: an object is live if the program could still reach it.
- Roots are the places the program reads directly: local variables on the stacks, registers, globals, and, in a
library like paragc, handles the program explicitly registers (
Root). - An object is reachable if a chain of pointers leads to it from a root.
- Everything else is garbage. No chain of pointers leads to it, so the program cannot touch it again, and reusing its memory is safe.
Reachable objects may still never be used again. That memory is a leak a GC cannot fix, but it is never a crash.
The two families: tracing and reference counting
| Tracing | Reference counting | |
|---|---|---|
| Idea | from time to time, start at the roots, follow every pointer, and mark what you reach; the rest is garbage | every object counts the pointers to it; at zero it is garbage |
| Work is proportional to | live data (marking) and heap size (sweeping) | the number of pointer writes |
| Cycles | collected naturally | never reach zero: leak unless another mechanism handles them |
| When memory comes back | at the next collection | immediately when the count drops |
| Cost on the mutator | small (barriers only for some designs) | every pointer write updates two counts |
Real collectors mix the two. CPython counts references and traces for cycles. LXR, which paragc follows, counts references for old objects and traces now and then.
Tracing collectors: what happens to the garbage
After marking, a tracing collector has three choices.
| Algorithm | What it does | Pros | Cons |
|---|---|---|---|
| Mark-sweep | walk the heap and put every unmarked object on a free list | objects never move | fragmentation; allocation searches free lists |
| Mark-compact | slide live objects together at one end of the heap | no fragmentation; bump allocation | several passes over the heap; every pointer must be updated |
| Copying (semispace) | copy live objects into an empty space while tracing; the old space is wholly free | one pass, work proportional to live data only; bump allocation | half the memory sits empty; long-lived objects get copied again and again |
| Mark-region (Immix) | free memory in units of fixed-size lines inside blocks; copy only when a block is sparse | bump allocation into free lines; little copying | an object can leave a partly used line unusable |
Allocation
- Free-list allocation searches lists of free chunks by size: flexible but slow, and it fragments.
- Bump allocation keeps a pointer and a limit and moves the pointer forward: a compare and an add. It needs contiguous free space, which is why compacting, copying and region collectors are fast to allocate from.
- Thread-local allocation buffers (TLABs): each thread bumps inside its own chunk, so allocation needs no synchronization at all.
When the collector runs
| Style | Meaning |
|---|---|
| Stop-the-world | all mutator threads stop while the collector works. Simplest; the stop is a pause |
| Parallel | the collector uses several threads during a pause. The pause is shorter; the mutators are still stopped |
| Incremental | the collector works in small slices interleaved with the mutator, one thread at a time |
| Concurrent | the collector runs on other threads while the mutators keep running |
Stopping the mutators safely needs safepoints: places in the program where every thread’s roots are known. Runtimes like the JVM poll at loop back-edges and calls. paragc avoids them: Rust’s borrow checker proves that no mutator is inside the heap when a stop-the-world collection runs.
Tri-color marking and barriers
Dijkstra and his colleagues described tracing with three colors:
- white: not reached yet (garbage, if it stays white);
- grey: reached, but its pointers have not been scanned;
- black: reached and fully scanned.
Marking ends when nothing is grey. When the mutator runs during marking (incremental or concurrent), it can hide an object: it stores a pointer to a white object into a black one and deletes the only other path. The collector would never see it and would free a live object. Barriers prevent this. A barrier is a few instructions the compiler or library runs on every pointer write (write barrier) or read (read barrier):
| Barrier | What it does |
|---|---|
| Insertion (Dijkstra) | when a pointer is stored, shade the new target grey |
| Deletion / snapshot at the beginning (Yuasa) | when a pointer is overwritten, shade the old target grey. Everything reachable when marking began survives |
| Read barrier (Baker, Brooks, load barriers) | when a pointer is loaded, make sure it points at the current copy of a moved object |
Objects allocated during marking are usually made black right away (black allocation).
Generations
The weak generational hypothesis says that most objects die young. A generational collector:
- splits the heap into a young generation (the nursery) and one or more old generations;
- collects the young generation often and cheaply (a minor or young collection), and the whole heap rarely (a major or full collection);
- moves objects that survive a few young collections into the old generation (promotion).
A young collection does not trace the old generation, so it must know about pointers from old objects to young ones. The write barrier records them in a remembered set, or marks the containing chunk of memory dirty in a card table.
Precise or conservative
- A precise (exact) collector knows exactly which words are pointers: the compiler emits stack maps, or the library keeps handles. It can move objects, because it can update every pointer.
- A conservative collector treats any word that looks like a pointer into the heap as one, typically on the stack, where it lacks type information. It cannot move an object that such a word points at, since that word might really be an integer.
Moving or not
Moving objects (copying, compacting, evacuating) removes fragmentation and allows bump allocation, but it changes addresses. Everything that holds an address must be updated, and nobody outside the collector’s knowledge may keep a raw address across a collection. Non-moving collectors are simpler to embed, especially in C++, where raw pointers are everywhere.
Finalization and weak references
- A finalizer (destructor) runs when the collector frees an object: to close a file, release a lock, free native memory. The collector decides when, and in no particular order, so a finalizer must not depend on other collected objects.
- A weak reference points at an object without keeping it alive. After a collection it either still points at the object or is cleared. Caches and observer lists use them.
What a collector is judged on
| Measure | Question |
|---|---|
| Throughput | what fraction of time goes to the program rather than the collector? |
| Latency | how long are the pauses, and how often? |
| Footprint | how much memory beyond the live data does it need? |
| Mutator overhead | what do barriers and allocation cost the program? |
| Scalability | does it use all the cores, for allocation and for collection? |
No design wins on all five. Every collector in the next chapters makes a different trade between them.
The first garbage collectors
Garbage collection is almost as old as high-level programming. Most of the ideas used today were invented between 1960 and 1990.
1960: Lisp and mark-sweep
John McCarthy’s Lisp, described in Recursive Functions of Symbolic Expressions and Their Computation by Machine (1960), built all data from cons cells and gave the programmer no way to free them. When the free list ran out, the system:
- started from the program’s registers and variables;
- followed every
carandcdrpointer, setting a mark bit in each cell it reached; - swept through all of memory, putting every unmarked cell back on the free list.
That is mark-sweep, the first garbage collector, implemented on the IBM 704. It stopped the program for the whole collection. The paper called the process “reclamation”; the name “garbage collection” came soon after.
1960: reference counting
In the same year George Collins published A Method for Overlapping and Erasure of Lists. Each cell counts the pointers
to it, and a cell whose count reaches zero is freed at once, together with whatever only it pointed to. No pause, but
every pointer change costs work, and cycles are never freed. Reference counting has lived on ever since: in Smalltalk-80,
Objective-C and Swift (ARC), CPython, C++ shared_ptr and Rust’s Rc/Arc.
1963–1970: copying collectors
- Marvin Minsky (1963) collected a Lisp heap by copying the live cells out to secondary storage and back.
- Robert Fenichel and Jerome Yochelson (1969) split memory into two semispaces. Allocation fills one; a collection copies everything reachable into the other, and the roles swap.
- C. J. Cheney (1970) made the copy breadth-first and non-recursive: the to-space itself serves as the queue of objects still to scan, so no stack is needed.
Copying collection touches only live objects and leaves free memory in one piece, so allocation becomes a pointer bump. The price is half the memory standing idle.
1970s: compaction
Mark-compact algorithms slide live objects to one end of the heap without a second space. The LISP 2 algorithm computes new addresses in one pass, updates pointers in a second and moves objects in a third. Jonkers (1979) and others reduced the passes with pointer threading. Compaction keeps allocation fast without the semispace’s memory cost.
1975–1978: collecting while the program runs
- Guy Steele (1975) and Edsger Dijkstra, Leslie Lamport and colleagues (On-the-Fly Garbage Collection, 1978) described collectors that run concurrently with the program. Dijkstra’s paper introduced the tri-color abstraction and the insertion write barrier.
- Henry Baker (1978) made copying incremental and real-time: the collector copies a little on each allocation, and a read barrier makes sure the program only ever sees the new copy of an object.
- Taiichi Yuasa (1990) published the deletion barrier that underlies snapshot-at-the-beginning marking.
1983–1984: generations
Henry Lieberman and Carl Hewitt (1983) observed that most objects die young and proposed collecting recent objects more often. David Ungar’s Generation Scavenging (1984), in Berkeley Smalltalk, made it practical: a small nursery is copied often, survivors are promoted, and a remembered set records old-to-young pointers. Almost every production collector since has been generational.
1988: conservative collection for C
Hans Boehm, Alan Demers and Mark Weiser built a collector for C and C++ programs that were never designed for one. It scans stacks, registers and data segments conservatively: any word that looks like a heap address keeps that object alive. It never moves objects. The Boehm GC is still used by GNU Guile, Mono (in the past), Inkscape and many language runtimes.
1990s–2000s: towards the modern design
- Parallel collectors used several threads during the pause, with work stealing to balance load (Endo et al., 1997; Flood et al., 2001).
- Mostly concurrent mark-sweep (Boehm et al., 1991; Printezis & Detlefs, 2000) became the basis of the JVM’s CMS.
- Region-based heaps let a collector reclaim or evacuate parts of the heap independently. They lead to G1 in the JVM.
- Immix (Stephen Blackburn and Kathryn McKinley, 2008) introduced the mark-region heap: blocks cut into lines, bump allocation into free lines, and opportunistic copying of sparse blocks. paragc’s heap is an Immix heap.
- LXR (Wenyu Zhao, Stephen Blackburn and Kathryn McKinley, 2022) combined Immix with reference counting for old objects and occasional concurrent tracing, and showed low latency without giving up throughput. paragc follows its first three stages.
The textbook
Richard Jones, Antony Hosking and Eliot Moss, The Garbage Collection Handbook (2nd edition, 2023), covers all of the above in depth and is the standard reference.
The JVM’s collectors
The Java Virtual Machine is where garbage collection was industrialised. A JVM runs many threads, allocates at enormous rates, and serves both batch jobs that want throughput and servers that want short pauses. Instead of one collector, HotSpot (OpenJDK’s JVM) offers several, chosen with a command-line flag. Together they show the whole design space.
Common machinery
| Mechanism | What it is |
|---|---|
| Precise roots | the JIT emits stack maps; at a safepoint every pointer on every stack is known |
| Safepoints | compiled code polls at loop back-edges and method returns; a collection stops all threads at safepoints |
| TLABs | each thread bump-allocates in its own thread-local allocation buffer inside the young generation |
| Card table | the old generation is divided into 512-byte cards; the write barrier dirties a card when a pointer is stored into it, so young collections only scan dirty cards |
| Generations | a young generation (Eden + two survivor spaces, copied) and an old generation |
Serial
One thread does everything while all mutators stop. The young generation is copied (Eden and one survivor space into the other survivor space or the old generation); the old generation is mark-compacted. It is the right choice for small heaps and single-core machines, and it still runs in containers with little CPU.
Parallel (the throughput collector)
The same algorithms as Serial, but the pause uses every core, with work stealing. It gives the best total throughput, at the cost of pauses that grow with the heap. It was the default collector up to JDK 8.
CMS: Concurrent Mark Sweep
CMS (JDK 1.4) marked the old generation concurrently with the program, using an incremental-update write barrier, with short pauses at the start (initial mark) and end (remark), and then swept concurrently. It never compacted the old generation, so it suffered from fragmentation and had to fall back to a long full collection when allocation failed. It was deprecated in JDK 9 and removed in JDK 14.
G1: Garbage First
G1 (experimental in JDK 6u14, default since JDK 9) splits the heap into equal regions (1–32 MiB).
- Regions take the role of Eden, survivor or old as needed; humongous objects take runs of regions.
- Each region has a remembered set of incoming pointers, so any set of regions can be evacuated on its own.
- Marking is concurrent with snapshot-at-the-beginning (SATB) barriers.
- Each pause evacuates a collection set: all young regions plus the old regions with the most garbage (hence the
name), chosen to fit a pause-time goal (
-XX:MaxGCPauseMillis, 200 ms by default). - Compaction happens incrementally by evacuation, so fragmentation stays under control.
G1 is a balance between throughput and latency, and it is the default for most workloads.
ZGC
ZGC (experimental in JDK 11, production in JDK 15, generational since JDK 21) aims for pauses under a millisecond, independent of heap size, up to multi-terabyte heaps.
- Coloured pointers: metadata bits inside each 64-bit reference record its marking and relocation state.
- Load barriers: every pointer loaded from the heap is checked. If it is stale, the barrier fixes it on the spot by finding or making the relocated copy.
- Marking, relocation and reference updating are all concurrent. Pauses only handle roots, and their length does not depend on heap size.
Shenandoah
Shenandoah (Red Hat, JDK 12) also evacuates concurrently with the program. It started with Brooks forwarding pointers (an extra word per object pointing at its current copy) and moved to load-reference barriers like ZGC. It became generational in recent releases.
Epsilon
Epsilon (JDK 11) allocates and never collects. It exists for performance testing and for very short-lived programs.
What the JVM teaches
- There is no single best collector; throughput, latency and footprint pull in different directions.
- Generations, TLABs, card tables and remembered sets are the standard toolkit.
- Low pause times need concurrent moving, which needs read barriers on every load. The JIT can afford those because it compiles every access.
paragc borrows the toolkit: TLAB-style buffers, remembered sets, SATB marking, parallel work stealing. It does not borrow read barriers. It is a library, not a JIT, and cannot instrument every pointer load, so it only moves objects while the mutators are stopped.
cppgc: V8’s C++ heap
A JVM controls the language, the compiler and the runtime, so it can put barriers and stack maps everywhere. A garbage collector for C++ cannot. The code is written by people, pointers are raw, and the stack is whatever the C++ compiler made of it. cppgc, also known as Oilpan, is the best-known modern answer, and the closest relative of paragc.
Where it comes from
Chrome’s rendering engine, Blink, used reference counting for its DOM objects, and cycles between C++ DOM nodes and JavaScript wrappers leaked. Around 2013 the Blink team built Oilpan, a tracing garbage collector for Blink’s C++ objects. In 2020 it moved into V8 as the standalone library cppgc, so other embedders could use it too. Today Blink’s DOM, the V8 JavaScript heap and cppgc’s C++ heap form one unified heap, traced together.
The programming model
class Node final : public cppgc::GarbageCollected<Node> {
public:
void Trace(cppgc::Visitor* visitor) const {
visitor->Trace(next_);
}
private:
cppgc::Member<Node> next_;
};
auto* node = cppgc::MakeGarbageCollected<Node>(heap->GetAllocationHandle());
cppgc::Persistent<Node> root(node);
| cppgc | Role | paragc counterpart |
|---|---|---|
GarbageCollected<T> | base class of heap objects | #[derive(Trace)] |
Trace(Visitor*) | written by hand, reports each pointer field | generated by the derive |
Member<T> | pointer field inside a heap object, with a write barrier | Slot<'gc, T> |
WeakMember<T> | weak field | Weak inside an object |
Persistent<T> | root held from outside the heap | Root<B> |
WeakPersistent<T> | weak root | Weak<B> |
raw T* on the stack | found by conservative stack scanning | Gc<'gc, T>, safe only inside mutate |
How it collects
- Mark-sweep with free-list allocation in size-class pages, plus bump allocation in linear allocation buffers. Ordinary objects do not move.
- Conservative stack scanning: any word on a thread’s stack that points into the heap keeps that object alive. This is what lets C++ code hold raw pointers in local variables safely, and it is also why objects cannot move freely.
- Incremental and concurrent marking with write barriers on
Memberstores, and concurrent sweeping. - Compaction only for backing stores: the buffers behind Blink’s vectors and hash tables can be compacted, because cppgc knows every slot that points at them.
- Pre-finalizers run before sweeping, while every object is still intact, for cleanup that must touch other heap objects. Ordinary destructors run during sweeping, in no particular order.
- A young generation (minor collections with a remembered set) exists behind a build flag and needs the caged heap: all objects in one large reservation, so a pointer can be checked against the heap with a mask.
What cppgc teaches
- A C++ collector has to tolerate raw pointers on the stack, so it scans conservatively, and that limits moving.
- Hand-written
Tracemethods are a frequent source of bugs: forgetting a field means a live object gets freed. - One unified heap across languages (C++ and JS) removes the leaks that two separate collectors with cross-references produce.
Where paragc differs
| cppgc | paragc | |
|---|---|---|
| Stack | scanned conservatively | not scanned; Gc handles are confined to mutate by Rust lifetimes |
| Stop-the-world | needs every thread at a known point | &mut Heap: the borrow checker proves nobody is inside |
| Moving | ordinary objects never move | evacuation and young copying, because no unknown raw pointers exist |
| Tracing code | hand-written Trace | derived; Drop on traced types rejected at compile time |
| Allocation threads | per-thread heaps | one heap, many threads bump-allocating at once |
| Young objects | optional minor GC | sticky-mark young collections and reference counting by default |
| Sharing between processes | none | cross-heaps on shared memory (Linux) |
Rust gives paragc what cppgc has to buy with conservative scanning: the compiler knows when no pointer can be outside the collector’s view.
From there to paragc
paragc is assembled from ideas in the previous chapters, plus one that only Rust allows. This page maps each part of paragc to where it comes from; the rest of the book explains each part in detail.
What paragc takes
| Idea | Origin | In paragc |
|---|---|---|
| Tracing from roots | McCarthy, 1960 | every collection marks from Roots, entries and remembered slots |
| Tri-color marking, SATB barrier | Dijkstra et al. 1978; Yuasa 1990 | concurrent marking with a deletion barrier on Slot writes and black allocation (Concurrent) |
| Bump allocation in thread-local buffers | copying collectors; JVM TLABs | Tlab, one per thread in mutate (Allocation) |
| Mark-region heap: blocks and lines | Immix, 2008 | 32 KiB blocks, 256 B lines, overflow allocation (Layout) |
| Opportunistic evacuation | Immix | sparse blocks copied while marking (Evacuation) |
| Generations, remembered sets | Lieberman & Hewitt; Ungar | sticky-mark young collections, slot logging (Young collections) |
| Parallel marking with work stealing | Endo, Flood et al.; JVM Parallel and G1 | crossbeam deques per worker (Marking) |
| Reference counting for old objects, background release | Collins 1960; LXR 2022 | 6-bit counts settled at young collections, decrements on the pool (Reference counting) |
| Weak references | Lisp weak pointers; Java WeakReference | Weak, cleared in every pause (Weak references) |
| A collector as a library for a host language | Boehm GC, cppgc | a Rust crate; j8 builds its JS heap on it |
What paragc adds
The borrow checker as the stop-the-world. JVMs need safepoints and stack maps. cppgc needs conservative stack scanning. paragc needs neither:
- a
Gc<'gc, T>cannot leave themutatecall it came from, so outsidemutateno unregistered pointer exists; - a stop-the-world collection takes
&mut Heap, so the compiler proves nomutateis running.
That is why paragc can move objects (evacuation, young copying) without read barriers and without conservative pinning, as a plain library.
No locks anywhere. Many mutators allocate at once from one heap. Blocks, roots, weak references and work queues are lock-free structures, and the thread pool is woken with one atomic word.
Heaps in shared memory, across processes. No collector in the previous chapters lets several processes use one heap at once. paragc’s cross-heaps do:
- objects without code pointers, collected by pointer maps;
- offsets that mean the same thing in every process;
- crash recovery when a process dies mid-collection;
- weak references and signatures that never make one process wait for another;
- promotion of a private heap’s survivors into a cross-heap.
The rest of the book starts from the user’s side (Quick start), then goes through the private heap, references between heaps, and the cross-heap.
What paragc is
paragc is a tracing garbage collector for Rust programs that share one heap across many threads.
- Objects live in 32 KiB blocks cut into 256-byte lines, the layout of Immix (Blackburn & McKinley, 2008).
- Threads bump-allocate into free lines on their own.
- A collection marks and sweeps on every core.
What sets it apart
| Many mutators | Heap::mutate(&self) runs on any number of threads at once. Each thread allocates from its own buffer (Tlab) and claims whole blocks with one atomic operation. |
| Exclusive by borrowing | Heap::collect(&mut self) cannot overlap a mutate, because the borrow checker forbids it. That borrow is the stop-the-world: there is no safepoint protocol and no lock. |
| Concurrent marking | Heap::mark_concurrently(&self) marks while mutators keep running. A snapshot-at-the-beginning barrier on Slot writes keeps it correct, and new objects are allocated black. |
| Concurrent sweeping | Heap::finish_marking only finishes marking. Mutators sweep a block themselves when they need one, and sweep_concurrently sweeps the rest on the pool. |
| Evacuation | A stop-the-world collection copies live objects out of sparse blocks while it marks (Immix defragmentation). |
| Young collections | collect_young traces only objects allocated since the last collection and compacts the survivors. |
| Reference counting | Old objects carry a small count, settled at young collections and released in the background (the LXR design). Full tracing only runs every few rounds, for cycles. |
| Weak references | Weak<B> does not keep its target alive; every kind of collection clears or moves it. |
| References between heaps | Far points straight from one private heap into another; collect_group reclaims cycles across them. |
| Cross-heap (Linux) | A CrossHeap lives in a shared-memory file. Several processes map it and use it at once, a killed process never blocks the others, and objects can be signed and found from another process. |
Where it is used
paragc is the heap of the j8 JavaScript engine. In j8:
- every JS object, string and closure is a paragc object;
- one isolate owns one
Heap; - with the
crossheapfeature, the isolate attaches a cross-heap as its old generation. JS values that survive a turn are promoted there, so another process can read them by signature.
What it is not
- Not a conservative collector. paragc does not scan stacks. Every object that must survive a collection is
reachable from a
Root. Inside amutate,Gchandles are safe because no collection can run. - Not
no_std. It needs threads,mmapand atomics fromstd. - Not a drop-in
Rcreplacement. Objects are reached through branded handles. Types implementTrace(usually with#[derive(Trace)]), and a type withGcfields must not implementDrop.
Quick start
[dependencies]
paragc = "0.6"
A singly linked list, kept by a root and summed after a collection:
#![allow(unused)]
fn main() {
use paragc::{Gc, Heap, Root, Trace, brand};
#[derive(Trace)]
struct Node<'gc> {
value: u64,
next: Option<Gc<'gc, Node<'gc>>>,
}
// A root handle has no 'gc; the brand puts it back on when you read it
brand!(NodeB = for<'gc> Node<'gc>);
let mut heap = Heap::default();
let list: Root<NodeB> = heap.mutate(|m| {
let mut head = None;
for value in 0..1000 {
head = Some(m.alloc(Node { value, next: head }));
}
m.root(head.unwrap())
});
heap.collect();
let sum = heap.mutate(|m| {
let mut sum = 0;
let mut cur = Some(m.get(&list));
while let Some(n) = cur {
sum += n.value;
cur = n.next;
}
sum
});
assert_eq!(sum, 999 * 1000 / 2);
}
What happens here:
heap.mutate(|m| ...)enters the heap.mis aMutator<'gc>, and everyGc<'gc, T>it hands out is tied to this one call by the'gcbrand.m.alloc(value)movesvalueinto the heap and returns aGc.m.root(gc)turns aGcinto aRoot<NodeB>. A root carries no lifetime, so it can leave the closure, be stored anywhere and be sent to other threads.heap.collect()takes&mut Heap, so nomutatecan be running. It marks from the roots and frees everything else.m.get(&root)brings the object back as aGcin a newmutate.
Mutable edges
Gc fields are fixed once the object is built. A field that changes is a Slot:
#![allow(unused)]
fn main() {
use paragc::{Slot, Trace};
#[derive(Trace)]
struct Cell<'gc> {
value: Slot<'gc, Node<'gc>>,
}
heap.mutate(|m| {
let cell = m.alloc(Cell { value: None.into() });
let node = m.alloc(Node { value: 1, next: None });
cell.value.set(m, Some(node)); // the write barrier sees the Mutator
assert_eq!(cell.value.get().map(|n| n.value), Some(1));
});
}
Slot::set takes the Mutator because the write barrier needs it. The barrier:
- logs old-to-young edges for young collections;
- keeps reference counts;
- marks the overwritten value during concurrent marking.
Choosing a collection
| Call | Use it when |
|---|---|
collect_if_needed() | Between units of work. It decides between nothing, a young collection and a full one. |
collect_young() | You know most new objects are already garbage. |
collect() | You want everything unreachable gone now. |
mark_concurrently() then finish_marking() | Pauses must stay short while mutators keep running. |
shrink() | The program is idle and memory should go back to the system. |
Threads
Heap is Sync. Wrap it in an Arc and call mutate from as many threads as you like. A collection (&mut self)
waits until every one of them has left. Collector threads are a pool owned by the heap: they start at the first
collection and park between collections.
Handles and brands
paragc’s handle types differ in how long they are valid and whether they keep their target alive.
| Handle | Lifetime | Keeps alive | Where it can live |
|---|---|---|---|
Gc<'gc, T> | one mutate | while the mutate runs (no collection can start) | locals, fields of heap objects |
Slot<'gc, T> | field of a heap object | yes, as an edge | inside heap objects |
WordSlot<'gc> | field of a heap object | yes, when the word is a pointer | inside heap objects |
Root<B> | none | yes | anywhere, any thread |
Weak<B> | none | no | anywhere, any thread |
Far<'a, B> | brand of the holder heap | yes, registered in the target heap | inside objects of the holder heap |
Why brands
A Gc is a bare pointer (#[repr(transparent)] over NonNull<T>). It is only safe while no collection can move or free
its target, which is exactly the duration of one mutate. The closure passed to mutate is generic over 'gc
(for<'gc> FnOnce(&Mutator<'gc>) -> R), so:
- a
Gc<'gc, T>cannot be returned out of the closure, becauseRcannot name'gc; - a
Gcfrom one heap cannot be stored in another heap’s object, because the two brands differ.
brand! declares a type that maps a lifetime back onto a heap type:
#![allow(unused)]
fn main() {
brand!(NodeB = for<'gc> Node<'gc>);
}
Root<NodeB> stores no lifetime; m.get(&root) returns Gc<'gc, Node<'gc>> for the current mutate.
Raw pointers
Gc::as_ptr and Gc::from_raw convert to and from a raw data pointer taken in the same mutate, for NaN-boxing and
similar tricks. The collector cannot see a raw address stored in an object. A type that stores raw addresses must:
- report them in
Trace::tracethroughTracer::edge; - pass them to
Tracer::relocateinTrace::relocateand write the new address back.
WordSlot covers the common case of a NaN-boxed 64-bit word (see Weak references and word slots).
Trace
#[derive(Trace)] generates:
trace, which reports every field that holds an edge;relocate, which rewrites those fields after evacuation;NO_EDGES, true when no field can hold an edge. Objects of such types are never pushed on the mark stack.
The derive refuses types that implement Drop. Destructors run in no particular order, so a Drop could see objects
that were already destroyed. #[trace(unsafe_drop)] opts out when the destructor touches no Gc.
Heap types must be Send + Sync: objects are traced and dropped on collector threads.
Blocks, lines and headers
Sizes
| Constant | Value | Meaning |
|---|---|---|
BLOCK | 32 KiB | unit the heap hands out; aligned to its size |
LINE | 256 B | unit of reuse inside a block (128 lines per block) |
GRANULE | 8 B | allocation alignment; object sizes are whole granules |
LARGE | 16 KiB | objects above half a block are allocated on their own |
LARGE_MMAP | 64 KiB | large objects from here up get their own mmap |
HEADER | 24 B | private object header |
Because blocks are aligned to 32 KiB, masking the low 15 bits of any object address gives its block.
The block header
Each block keeps, outside its data area:
- line marks: one
u32epoch per line. A line is free when its mark is older than the last finished epoch, so clearing marks is never needed; a new collection just uses a newer epoch; - the object-start bitmap: one bit per granule, set at the first granule of every object. Sweeping and cross-heap lookups walk it to find objects;
- a state (free, being allocated into, recyclable, full, swept) and counters used by evacuation.
An allocation buffer collects the start bits of the objects it allocates in one bitmap word and publishes them with a
single atomic OR. It does that when it moves to another word, adopts another block, or when the mutate returns.
Nobody reads those bits earlier: the buffer owns its blocks until the next collection.
Where blocks come from
On Linux:
- each heap maps 2 MiB chunks itself and cuts them into aligned blocks;
- a returned block first goes to a warm pool and keeps its memory, because the next round probably needs as many blocks;
- only when the warm pool is full is the block
madvise(MADV_DONTNEED)ed, giving its memory back; its address then goes to a cold pool for reuse. Warm blocks are handed out first; - the chunks are unmapped when the heap is dropped.
paragc bypasses glibc here: aligned allocations cost extra, and memory freed to glibc is not returned to the system.
On macOS, Windows and under Miri, blocks come from the global allocator.
The object header
A private object starts with a 24-byte Header:
| Field | Bits | Meaning |
|---|---|---|
| mark | 32 | epoch of the last collection that marked it; FORWARDED / BUSY bits during evacuation |
| info | 32 | size in granules (24 bits), reference count (6 bits), parity bit, large bit |
| visit | 64 | unsafe fn(*mut u8, &mut Tracer) for the type: traces or relocates its edges |
| drop | 64 | Option<unsafe fn(*mut u8)>, the destructor; after a move it holds the forwarding address |
The first two words (Core) are shared with cross-heap objects, whose 16-byte PHeader has a type number and a birth
stamp instead of function pointers. Blocks, lines, sweeping and marking therefore use the same code for both heaps.
A single object’s data can be at most 128 MiB (24 bits of granules).
Bit layouts
Every word paragc and j8 put in memory, bit by bit.
A private object
An object is a 24-byte header, the data, and an optional tail. The total is rounded up to 8 bytes:
(HEADER + size_of::<T>() + tail).next_multiple_of(8).
offset 0 mark u32 bits 0–29 epoch of the last mark (0 = young; ceiling MAX_EPOCH = 2^30 − 1)
bit 30 BUSY: a collector thread claimed it and is copying it
bit 31 FORWARDED: moved; the new address is in the drop word
offset 4 info u32 bits 0–23 size in granules, header included (× 8 bytes; at most 128 MiB)
bits 24–29 reference count (sticks at 63)
bit 30 count parity (which generation of counts this one belongs to)
bit 31 large object
offset 8 visit fn traces, relocates or answers the type question (see Marking)
offset 16 drop fn? destructor, or none; after a move, the forwarding address
offset 24 data T, then the tail
mark and info together are Core, the part blocks, lines and sweeping look at.
A cross-heap object
The header is 16 bytes and has no code pointers:
offset 0 mark u32 as above
offset 4 info u32 as above (so the block code is shared)
offset 8 ty u32 index in the heap's type table; collection follows that type's pointer map
offset 12 stamp u32 birth stamp: SplitMix64 of the heap's incarnation and the allocation epoch
offset 16 data
When a private object is promoted, its 24-byte header is replaced by a 16-byte one, and the data and tail are copied unchanged.
Block metadata
For every 32 KiB block:
| Table | Size | Meaning |
|---|---|---|
| line marks | 128 × u32 = 512 B | epoch per 256-byte line; a line is free when its mark is older than the last finished epoch |
| start bitmap | 4096 bits = 512 B | one bit per 8-byte granule, set at the first granule of each object |
Edges and words
| Thing | Layout |
|---|---|
Gc<'gc, T> | one pointer to the data (after the header) |
Slot<'gc, T> | two words: the current value, and the value last counted for reference counting |
WordSlot<'gc> | two words. A value word ≥ WORD_POINTER_MIN (0xFFF8 << 48) is a pointer: top 16 bits are the user’s tag (kept through moves), low 48 bits the data address. Any other word is plain data |
CrossHeapSlot | one u64: offset from the start of the cross-heap region, the same in every process |
CrossHeapWeak | one u64: high 37 bits are the offset ÷ 8 (a 1 TiB region needs 40 bits, minus 3 for alignment), low 27 bits the stamp |
Signature | 32 bytes: the weak word (8), the heap incarnation (8), the type key (16) |
j8’s JS values
A JS Value is one 64-bit word, NaN-boxed:
- a double is stored as is (NaNs are canonicalised to
0x7FF8_0000_0000_0000); - every other value is
0xFFF0 << 48 | (tag + 1) << 48 | payload.
| Top 16 bits | Kind | Payload |
|---|---|---|
0xFFF1 | undefined | – |
0xFFF2 | null | – |
0xFFF3 | boolean | 0 or 1 |
0xFFF5 | uninitialised binding (TDZ) | – |
0xFFF6 | lazy value | index |
0xFFF8 | string | address of a JsStr |
0xFFF9 | symbol | address |
0xFFFA | bigint | address |
0xFFFB | object | address of an Object |
0xFFFC | accessor pair | address |
0xFFFD | context (closure environment) | address |
Every kind that points into the heap has a top half ≥ 0xFFF8, which is exactly the range WordSlot treats as a
pointer. A JS value stored in a WordSlot (j8’s ValueCell) is therefore an edge the collector traces, counts and
relocates, and the tag survives the move.
Example: a JS string
JsStr is 32 bytes of fields followed by its text in the tail:
private header 24 B
JsStr 32 B buf 8 none: the text is in my tail; some: a view into another string's buffer
len 4 UTF-8 bytes
units 4 UTF-16 code units (equal to len exactly when the text is ASCII)
start 4 start in the buffer (views)
cap 4 tail capacity for UTF-8 (spare room for appending)
used 4 bytes of the buffer claimed so far (atomic; appending claims with a CAS)
pad 4
tail cap B UTF-8, then (non-ASCII only) padding to 2 and units × u16 of UTF-16
A 40-byte ASCII string is 24 + 32 + 40 = 96 bytes = 12 granules, and the low 24 bits of info hold 12. Promoted into a
cross-heap, the same string is 16 + 32 + 40 = 88 bytes.
Allocation
The thread-local buffer
Each thread in a mutate allocates through a Tlab: a cursor and a limit inside one block. An allocation that fits
bumps the cursor and writes the header; nothing else is shared.
When the current run of free lines is too small, the buffer tries, in order:
- the next run of free lines in the same block (a line is free when its mark is older than the last finished epoch);
- a recyclable block, one that the last sweep found with free lines;
- an empty block;
- a new block from the segment pool.
Taking a block is one atomic operation on a lock-free list.
Overflow allocation
Objects larger than a line that do not fit the current run go to a second cursor, the overflow cursor (Immix
overflow allocation). It looks at up to OVERFLOW_TRIES (8) available blocks for a run long enough, otherwise it opens
a fresh block. The current run stays in place for small objects, so a medium object never throws away a good hole.
Large objects
An object above LARGE (16 KiB) is allocated on its own:
- up to 64 KiB, from runs of blocks;
- from 64 KiB, with its own
mmap.
Large objects are never moved. Sweeping frees them whole.
Black allocation
During concurrent marking, a new object gets the current marking epoch, and its lines are marked as well. It is allocated “black”, so the marker never has to scan it. Its address goes to a list, so that its edges are counted at the end of marking.
Allocating with a tail
Mutator::alloc_tail(value, tail, fill) allocates an object followed by tail bytes of plain data:
- the tail starts right after
T(atsize_of::<T>()from the data pointer), andfillwrites all of it before the object can be reached; - the collector never looks inside the tail, but copies it with the object when the object moves or is promoted, because the header size covers it;
- the type keeps the tail’s length itself.
j8 stores the bytes of every JS string this way. alloc_shared_tail is the same for shareable objects (see
Promotion).
Buffers across collections
A buffer remembers the heap and the collection count it belongs to. After a collection it starts over, because the sweep may have reclassified its block.
Marking and the thread pool
Epochs
Marks are epochs, not bits. Each collection takes a new epoch number. An object is marked in this round when its mark word equals the current epoch, and a line is live when its mark is the last finished epoch. Nothing ever has to be cleared between collections.
Parallel marking
- The roots are spread over the workers.
- A worker reaching an object swaps the epoch into its mark word. Whoever swaps first owns the object. It marks the
lines the object spans and pushes the object on its own deque. Types without edges (
NO_EDGES) are never pushed. - A worker pops an object and calls its
visitfunction in tracing mode; each edge goes back to step 2.
Each worker has a crossbeam work-stealing deque. A worker that runs dry steals in batches from the others.
Termination. A worker whose deque is empty and that cannot steal counts itself idle and keeps trying. When every worker is idle at once, marking is complete.
Deep structures never touch the call stack: a million-node chain is a million deque pushes, not a million frames.
The pool
The pool starts at the first collection and lives as long as the heap.
- A collection is handed out by bumping one atomic word that holds a generation number and the number of participants. Only that many workers are unparked.
- Idle workers back off, then park.
- A panic on a worker is caught and raised again on the thread that called the collection.
The tracer modes
The same visit function serves several purposes, selected by the Tracer:
| Mode | What visit does |
|---|---|
| tracing | calls Trace::trace; each edge is marked and pushed |
| relocating | calls Trace::relocate; each edge is rewritten to its forwarding address |
| asking (cross-heap) | answers whether the type is shareable and, if so, its type number in the cross-heap |
The asking mode lets the collector learn about a type from the object alone, without a type registry in the private heap.
Sweeping
Sweeping turns the marks into free space and runs destructors.
The parallel sweep
Workers claim blocks in batches of 16. For each block, a worker:
- walks the object-start bitmap;
- for every object whose mark is not the current epoch, runs its destructor (unless it was moved; see Evacuation) and clears its start bit;
- classifies the block as empty, recyclable (some free lines) or full.
Empty blocks beyond what the last round used are returned to the system (MADV_DONTNEED); the rest stay as spares.
Destructors and threads
By default, destructors run in parallel on every collector thread. Heap::set_parallel_drop(false) runs them only on
the thread that called the collection or sweep_concurrently. Finding the dead and recomputing lines stay parallel.
Turn parallel drop off when destructors free memory that the mutator thread allocated: frees from other threads make the
allocator contend.
Lazy and concurrent sweeping
finish_marking only finishes marking. It hands every block and large object to the sweeper and returns. From then on:
- a mutator that needs a block first takes a swept one. Failing that, it claims an unswept block and sweeps it on the spot (lazy sweeping);
sweep_concurrentlysweeps everything left on the pool and waits for blocks others are still sweeping.
Claiming is an atomic cursor, so each block is swept exactly once, by whoever claims it, before it is handed out. New objects carry the last finished epoch, so an allocation made during sweeping is never taken for dead.
collect is finish_marking followed by sweep_concurrently.
Shrinking
Heap::shrink, called when the program is idle:
- runs a full collection;
- keeps no empty blocks;
madvises away the whole pages of free lines inside recyclable blocks.
Live objects are untouched, and the freed lines can be allocated into again afterwards.
Concurrent marking and sweeping
With concurrent marking, the only pauses are a short handshake at the start and draining the grey queue at the end.
Start: the handshake
Heap::mark_concurrently(&self):
- finishes the previous sweep. The sweep judges objects by “mark ≠ that epoch”, so it must end before marking stamps live objects with a newer epoch;
- raises the request bit in the gate word. The top bit is the request; the low bits count threads inside
mutate; - waits until no mutator is inside. paragc does not scan stacks, so the snapshot must be taken while no mutator holds
an unrooted
Gc; - marks the roots grey and drops the request.
Marking then runs on the pool while mutators continue.
During marking
- Snapshot at the beginning. Writing a
Slotmarks the value it overwrites and pushes it to the heap’s grey queue. Every object reachable at the handshake is therefore found, even if a mutator unlinks it. - Black allocation. New objects get the marking epoch and their lines are marked.
- Read barrier for weak references.
upgrademarks and greys its target. Otherwise an object that was only weakly reachable at the snapshot could be taken out and stored under a black object, and be missed. - Line reuse. A line is free only when its mark is older than the last finished epoch, so lines that the marker has just stamped are never handed out.
End: the pause
finish_marking(&mut self) drains the grey queue in parallel, finishes reference counting (see below), clears dead weak
references and hands the blocks to the sweeper. sweep_concurrently then sweeps while mutators run.
Recounting
Concurrent marking also rebuilds reference counts:
- the handshake flips the count parity and drops the slots logged before it;
- markers count every edge they scan;
- a marker that recounts a slot rereads it afterwards, and logs it itself if a mutator wrote it in between;
- objects allocated black are queued and their edges counted at the finish;
- logged slots are then settled.
Counts are trusted again as soon as the finish returns.
Limits
- Concurrent marking never moves objects, so mutators need no read barrier for moved objects.
- Never call
mark_concurrentlyfrom inside amutateon the same heap: it would wait for itself to leave. - While a cross-heap is attached, concurrent marking is not supported.
Evacuation
A stop-the-world collection can move live objects out of sparse blocks while it marks: Immix’s opportunistic defragmentation. Marking, copying and rewriting edges are one pass.
Choosing blocks
- Candidates: blocks that have not been allocated into since they were swept and that hold less than half a block of
live data (
EVACUATE_LIVE). They are taken sparsest first, at least 4, with no upper cap. - Copy targets: every other swept block.
- Early full collections:
collect_if_neededruns a full collection early once blocks exceed “live data + one round of allowed allocation” by 1.5×.
Copying
While marking, the first worker that reaches an object in a candidate block:
- claims it by setting
BUSYin its mark word; - copies it into its own copy buffer. The new copy is marked and gets its start bit and line marks;
- writes the forwarding address into the old header (the
dropword) and setsFORWARDED.
Other workers that reach the old copy either wait for BUSY to clear or follow the forwarding address.
Rewriting edges
- Every edge is rewritten through
Trace::relocate. - Root slots are rewritten with a CAS, so a handle that another thread drops at the same time stays dropped.
- Weak references follow moved targets.
- The sweep clears the old copies’ start bits without running their destructors.
What is never moved
- Large objects.
- Anything during concurrent marking.
- Targets of
Farreferences from other heaps: their blocks drop out of evacuation before marking starts. See Far references. - Objects that young collections in
SkipRememberedmode promote in place. See Young collections.
Consequence for users
Gc::as_ptr may differ from one mutate to the next. Code must not keep raw addresses across a collection, except
through Trace::relocate.
Young collections
Most objects die young. Heap::collect_young traces only the objects allocated since the last collection.
Sticky mark bits
There is no separate nursery. An object marked with the last finished epoch is old; a new object starts with mark 0 and is young. A young collection marks with that same epoch:
- an old object it reaches already carries the epoch, so the trace stops there;
- a young object it reaches gets the epoch and becomes old (it is promoted).
The remembered set
An edge from an old object to a young one can only come from a Slot write. Outside concurrent marking, the write
barrier logs the slot of an old object whenever the value written is young.
- Slots of young objects are not logged: a young collection reaches them through the object itself.
- During concurrent marking every new object is black and survives as old, so nothing is logged.
- Every collection clears the log.
A young collection marks from the roots and from the logged slots. It sweeps only the blocks allocated into since their last sweep.
Moving survivors
Surviving young objects move into compact blocks. Heap::set_young_evacuation chooses how:
| Mode | Behaviour |
|---|---|
SkipRemembered (default) | Objects that an old object (a remembered slot) or another heap’s Far points at directly are promoted in place. The rest move; only young objects and roots point at them, and those are all relocated. Old objects are never written. |
Full | Remembered slots are rewritten too, so every young survivor can move. Use it only when old objects keep the address nowhere but in a Slot. |
Off | Nothing moves; survivors are promoted in place. |
A rule that follows from this
Young collections never scan old objects. A structure that indexes objects by address must itself be young while it points at young objects: when it changes, move it into a fresh object.
Scheduling
collect_if_needed runs young collections and a full collection every few rounds:
- every 16 young collections while reference counts are trusted (
YOUNG_PER_FULL_RC); - every 4 otherwise (
YOUNG_PER_FULL).
With a cross-heap attached, young evacuation is forced to Full, because promotion moves every shareable survivor (see
Promotion).
Reference counting
Old objects carry a small reference count. Most old garbage is freed by its count, in the background, and full tracing only runs every few rounds for cycles and overflowed counts. This follows LXR (Zhao, Blackburn & McKinley, 2022), stages one to three.
What is counted
RC(x) is the number of edges to x from old objects. Edges from a young object are counted when that object is promoted.
The count lives in the header’s info word:
- 6 bits, which stick when they reach the maximum;
- a parity bit. A stop-the-world full collection flips it and recounts every edge exactly while it marks; a count with the wrong parity is from the previous generation and starts again from 1.
Maintaining counts
A Slot is two words: the value, and the value it last counted.
- An old object’s slot is logged on its first write in a round.
- A young collection settles it: +1 for the new value, −1 for the value last counted.
- Roots are counted lazily (deferred root counting): +1 for each current root, −1 for the previous round’s roots.
- Decrements run after all increments.
An old object reaching zero:
- has its edges decremented;
- is finalized;
- has its start bit cleared.
The lines of the affected blocks are then recomputed.
Background release
The pause (finish_young) only settles increments and pushes the decrements onto a queue. collect_young is
finish_young + sweep_concurrently. On the pool:
- workers pop decrements;
- whoever brings a count to zero finalizes the object, clears its start bit, queues decrements for its edges and records the block as dirty;
- objects at zero have no counted references, and every root and promoted young object was counted, so mutators cannot reach them.
Dirty blocks get their lines recomputed from the old objects left at the start of the next pause. Every collection first finishes pending decrements, so a recount never flips the parity under them.
Cycles and weak targets
- Cycles never reach zero; the periodic full collection reclaims them.
- An object with a weak reference gets a stuck count. Release runs in the background, too late to clear weak references first, so only tracing may free such an object.
Single worker
With one marking worker nobody else touches the counts, so the recount uses plain loads and stores instead of locked atomic read-modify-writes.
Weak references and word slots
Weak<B>
A Weak<B> is like a Root<B>: it has no lifetime and can be stored anywhere. Unlike a root, it does not keep its
target alive.
#![allow(unused)]
fn main() {
let weak = heap.mutate(|m| m.weak::<NodeB>(m.alloc(Node { value: 1, next: None })));
heap.collect();
assert!(weak.is_cleared());
assert!(heap.mutate(|m| m.upgrade(&weak).is_none()));
}
How it works:
- Each
Weakowns a slot in the heap’s weak table, which is not a root set. - In every pause (full, young, the end of concurrent marking, group collections), after marking and evacuation and
before sweeping, the table is walked:
- a moved target gets its new address;
- an unmarked target is cleared, by CAS, so that a handle dropped at the same moment is not revived.
- During
mutate, the table only points at live objects.Mutator::upgradegives anOption<Gc>, andWeak::is_clearedworks outsidemutate. - Live targets of weak references get a stuck reference count (see Reference counting). A young object with only weak references is cleared by the next young collection, an old one by the next full collection.
Weak references can also be stored inside heap objects; they go with their holder.
WordSlot
A WordSlot<'gc> holds a u64 that the user encodes, such as a NaN-boxed JS value:
- words at or above
WORD_POINTER_MIN(0xFFF8 << 48) are pointers. Their low 48 bits are an object’s data address, and their top 16 bits are the user’s tag, kept as is through evacuation; - every other word is plain data.
WordSlot has the same barriers, counting and relocation as Slot. word_pointer decodes a word. A tagged word must
point at a live object of the same heap.
Far references and group collection
Several private heaps can live in one process: one per isolate, one per subsystem. Far<'a, B> lets an object in one
heap point straight at an object in another, with no copy and no indirection.
Creating and reading
#![allow(unused)]
fn main() {
// inside both heaps' mutate
let far = Far::new(&holder_m, &target_m, target_gc);
let holder = holder_m.alloc(Holder { far });
// later, reading needs the target heap's Mutator
let t = holder.far.get(&target_m);
}
- A
Faris branded with the holder heap, so it can only be stored in that heap’s objects. - Reading takes the target heap’s
Mutator. Holding that mutator proves the target heap is open and that no collection of it is running. - A
Farnever changes. To point elsewhere, put it in an object behind aSlotand replace that object.
Entries: how the target heap sees it
Creating a Far claims a slot in the target heap’s root table, which also records the holder heap. Finalizing the
object that holds the Far (by sweep or by reference count) returns the slot.
- Collecting the target heap alone treats these entries as roots. Young collections, reference counting and concurrent marking need nothing new.
- Entries are pinned. Before an evacuating collection marks anything, the blocks holding entry targets drop out of
evacuation and become copy targets instead. A
Fartherefore never needs rewriting.
Cycles across heaps: collect_group
A cycle A → B → A survives collecting A alone and B alone, because each side is an entry root in the other.
Heap::collect_group(&mut [&mut Heap]) (and CrossHeap::collect_group for cross-heaps) collects several heaps together:
- entries held from inside the group are not roots;
- each heap marks from its own roots;
- a traced
Farhands its target to the target heap, seeded with that heap’s epoch; - the heaps take turns until no heap has grey objects left;
- entries held inside the group whose target stayed unmarked belong to dead holders and are cleared, so a later collection never seeds a freed object.
Group collections do not evacuate.
Dropping order
Far holds an Arc of the target heap’s root table, so dropping the target heap first and the holder later is safe.
Once the target heap is gone, its mutator cannot be obtained, so get can no longer be called.
Cross-heap overview
A cross-heap (CrossHeap) is a heap that lives in a shared-memory file. Every process that can open the file maps
the heap and uses it: it can allocate, read, write and collect.
[dependencies]
paragc = { version = "0.6", features = ["crossheap"] }
The feature exists only on Linux. On macOS and Windows it compiles to nothing, and only the private heap is there.
build.rs emits cfg(crossheap) when the feature is on and the target is Linux, and every cross-heap item is gated on
that cfg.
Two kinds of heap, two scopes of sharing
| shared between threads | shared between processes | |
|---|---|---|
private heap (Heap) | ✓ | ✗ |
cross-heap (CrossHeap) | ✓ | ✓, for every process that can open its file |
| From → to | private heap | cross-heap |
|---|---|---|
| private heap | ✓ direct pointer (Far between heaps) | ✓ CrossHeapRoot, or an absolute address once promoted |
| cross-heap | ✗ (other processes cannot see private memory) | ✓ CrossHeapSlot, CrossHeapRef, CrossHeapWeak |
Because nothing in a cross-heap points into a private heap, private and cross-heaps never form cycles.
Pieces
| Piece | Page |
|---|---|
| Where heaps are mapped; the file layout; how the file grows and shrinks | Address space and file layout |
Objects without code: #[derive(Shared)], type numbers, pointer maps, handles | Objects, types and pointer maps |
| Several processes in one heap; dying at any moment; heap numbers, owners, restarts | Processes, crashes and lifetime |
| References that never hold anything up; signatures another process can resolve; posting objects to the owner | Weak references, signatures and the mailbox |
| A cross-heap as the old generation of a private heap | Promotion |
Trust
Every process that maps a heap can read all of it and corrupt it. Processes that share a heap trust each other; the permission check is the file’s permission. A signature from an untrusted party is only read, though, and a forged one never crashes the reader.
The goal behind it
j8 runtimes in different processes exchange JS values without copying. A process sends a 32-byte signature; the receiver, or a broker such as dowin, maps the sender’s heap, finds the object and reads it, or passes the signature on.
Sharing a JS object, step by step
This page follows one JS object from the process that creates it, through a broker, to another process, and shows which parts of a j8 object can make the trip today. The example is the goal behind cross-heaps: an acdes process sends a JS object to dowin, and dowin forwards it to another acdes without copying.
The steps
- Allocate. JS allocates the object in the isolate’s private heap. If its type is shareable (
alloc_shared), it is still an ordinary young object at a private address. Nothing decides at allocation time which heap it will live in, so allocation stays lazy. - Mark it for sharing. The host calls
scope.shares.share(mc, gc), which records a ticket and moves nothing. - Promote at the end of the turn. j8 never collects in the middle of running JS. When
Isolate::enterreturns, j8 runs one young collection if anything is pending. Shareable survivors, tails included, are copied into the attached cross-heap:- the cross-heap sits at 64 TiB + 16 GiB × heap number, the same address in every process;
- the old place gets a forwarding address, and every private slot, root and weak reference is moved to the new one.
- Sign.
sign_promotedproduces the 32-byte signature: offset and stamp, heap incarnation, type key. - Send to the broker. The signature and the heap file’s descriptor go over a Unix socket. dowin opens the heap with
open_fd, which maps it at the same window, and callsresolve. That checks the block, the start bit, the stamp and the type key, and hands back a pointer into shared memory. dowin reads the object in place. - Forward. dowin passes the same signature, and the descriptor if needed, to the other acdes, which repeats step 5. Nobody copied the object.
Still missing:
- the dowin side is not written yet;
- j8’s test uses an anonymous cross-heap, which other processes cannot open. Real use needs a file heap and its descriptor.
Where the parts of a j8 object live
| Part | Where | Shareable today |
|---|---|---|
Object shell (prototype, call target, class bits) | GC heap | depends on the rows below |
Props.inline (first 4 property values) | inside the object, one NaN-boxed word each | ✓ |
Props.store (properties 5 and up) | GC heap | ✓ |
Props.shape | a raw pointer to malloc’d memory, invisible to the collector | ✗ |
Props.anchor, a prototype’s shape_root | GC objects holding an Arc<Shape> | ✗ (they have a destructor) |
the Shape itself: property names, attributes, transitions, hash index | Arc outside the heap; names are SmallStr (short ones inline, long ones Arc<str>) | ✗ |
| dictionary-mode properties | GC objects holding Vec and HashMap | ✗ |
| strings | GC heap, text in the object’s tail | ✓ |
| functions | bytecode and FunctionInfo outside the heap | ✗ |
| host objects | Box<dyn Any> | ✗; the owner acts for others through the mailbox |
A shape is the object’s layout: which property name sits in which slot, with which attributes. Objects with the same properties added in the same order share one shape.
Why shapes are outside the heap
- Identity is the address, and paragc moves objects. The executor’s inline caches compare shape addresses, and
the JIT bakes them into machine code (
CheckShape). paragc’s young collections and evacuation change object addresses. A malloc’dArcnever moves, so its address is a stable identity. - A shape is a shared cache that grows. Adding a property appends a child to the shape tree, lock-free, through
&self(Chain,Prefix). A shape with many properties builds a hash index lazily (OnceBox<HashMap>). Both need growable malloc’d memory, at moments where no allocation context (mc) is at hand. As GC objects they would needBoxes and destructors, and types with destructors cannot be shared. - The GC still decides when they die. A prototype’s
shape_root, and theanchorof an object whose shape is not in its prototype’s tree, are GC objects that hold theArc. When they die the count drops and the shapes go. - History (inferred). When j8 moved its heap to paragc (11-17, eb308d0), shapes kept their earlier
Arc-based design. Sharing across processes was not a requirement then.
What that means for sharing
When an object is promoted into a cross-heap, its values and strings arrive intact, but Props.shape still points into
the sending process’s malloc heap. Another process sees the values in each slot without knowing which property name each
slot belongs to. The Anchor also carries a destructor, so it cannot be promoted at all. That is why stage 3 of the
cross-process work, shapes, has to come before ordinary objects can be shared. The candidate designs are listed in
Limits and open problems.
Address space and file layout
The address region and windows
CrossHeapSpace::reserve takes a range of addresses, not memory (PROT_NONE + MAP_NORESERVE):
- 64 windows × 16 GiB = 1 TiB, aligned to its own size;
- cross-heap number k is always mapped at window k;
- a process maps only the heaps it opened.
A pointer inside a cross-heap is an offset from the start of the region, so the same value names the same object in every process, even across heaps. The base is found from any address in the region by masking the low bits.
The fixed region
CrossHeapSpace::reserve_fixed reserves the region at FIXED_BASE = 64 TiB with MAP_FIXED_NOREPLACE. Every process
that does so maps heap k at the same absolute address, so plain absolute pointers (Gc, Slot) inside cross-heap
objects are valid everywhere. Promotion depends on this (see Promotion). A process can hold the fixed
region only once at a time.
Inside a window
Every part sits at a fixed offset, so any process finds it without following a pointer:
offset 0 superblock (one page): identity, owner, counters, stack heads, the attachment table at 1024
type table (1024 entries: type key → type number, pointer map position)
pointer maps (64 K offsets)
entry table (one entry per 16 KiB of window)
block table (state of every block)
blocks (32 KiB each, handed out from a cursor)
The superblock holds a magic number (paragcP5), the owner, a random incarnation, the persist and dead flags, the
mailbox head, the mail count, the owner_only flag, and how far each part has been extended.
Starting empty, growing on use
- A new heap’s file is one page long: only the superblock.
- Every part is extended with
fallocatewhen it is first used.fallocateonly ever grows the file, so threads and processes can race on it safely. - On tmpfs,
fallocatetakes memory right away, so memory is used up to the file length. The rest of the window costs nothing. - A process entering
mutatecompares its mapped length with the superblock and maps more when needed: one comparison, no system call in the common case.
Giving memory back
Sweeping keeps empty blocks as spares, up to the amount allocated since the last collection. The rest are punched out:
- file heaps:
fallocate(PUNCH_HOLE | KEEP_SIZE); - anonymous heaps:
madvise(MADV_REMOVE).
Runs of adjacent blocks are punched in one call. All-zero block metadata is a valid empty block, so punched blocks stay
on the free stack and are reused like any other. CrossHeap::shrink keeps no spares.
Opening a heap
| Call | Use |
|---|---|
space.create(path, threads) | a new heap in a file; its number is claimed in the file’s directory |
space.create_anonymous(threads) | a new heap with no file (anonymous shared memory), usable only inside this process; for tests, Miri and an isolate’s own old generation |
space.open(path, threads) | an existing heap by path |
space.open_fd(fd, threads) | an existing heap from a file descriptor passed over a Unix socket (SCM_RIGHTS); no path needed |
heap.fd() | the descriptor to pass (file heaps only) |
Objects, types and pointer maps
Objects in a cross-heap can be read and collected by processes that never linked the code of their type, so they carry no function pointers.
Shareable types: #[derive(Shared)]
#![allow(unused)]
fn main() {
use paragc::{CrossHeapSlot, Shared, cross_heap_brand};
#[repr(C)]
#[derive(Shared)]
struct Node<'p> {
value: u64,
next: CrossHeapSlot<'p, Node<'p>>,
}
cross_heap_brand!(NodeB = for<'p> Node<'p>);
}
#[repr(C)]is required, so the layout agrees across processes and binaries.- Fields may be plain data,
CrossHeapSlot,CrossHeapRef,CrossHeapWeak, nestedSharedtypes and fixed-size arrays. Promotion adds absolute-address edges:Gc,Option<Gc>,Slot,WordSlot. - No destructor:
CrossHeapMutator::allocchecks it at compile time. - The derive generates a pointer map: the offset of every pointer field, through nested types and arrays.
The type table
The first allocation of a type registers it in the heap’s type table:
- the type key is a hash of the type name, its size and its pointer map;
- the entry records the type number, the size, and where the pointer map is stored.
A process that looks up a handle checks the type key, so a handle of the wrong type is refused rather than misread.
The header
A cross-heap object has a 16-byte PHeader:
| Field | Meaning |
|---|---|
| mark, info | the same two words as a private header, so blocks, lines and sweeping are shared code |
| type | the type number |
| stamp | the birth stamp (see Weak references and signatures) |
Collection follows the pointer map of the type number; it never calls code.
Handles
| Handle | Valid | Stores |
|---|---|---|
CrossHeapGc<'p, T> | inside one CrossHeap::mutate | an absolute address in this mapping |
CrossHeapSlot<'p, T> | field of a cross-heap object | an offset from the region start, the same in every mapping |
CrossHeapRoot<B> | anywhere; in private heaps too | an entry number; holds the object alive |
CrossHeapRef<'a, B> | field of an object in heap A, pointing into heap B | the target’s offset and B’s incarnation; registers an entry in B |
CrossHeapWeak<B> | anywhere | one word: offset and stamp; holds nothing |
get and set on a CrossHeapSlot take the CrossHeapMutator, which knows this mapping’s base address.
Entries
The entry table is the cross-heap’s root set. Each entry records the target’s offset and its holder:
- an attachment slot, meaning a process;
HEAP_HOLDER | k, meaning another cross-heap;- 0, meaning nobody: a persistent root.
CrossHeapRoot::index is the entry number, valid in every mapping. CrossHeapMutator::find turns an entry number back
into a handle after checking the type key; this is how another process picks up an object handed to it.
Large objects
Objects above 16 KiB take a run of fresh blocks. When such an object dies, its blocks become ordinary blocks again.
Collection
CrossHeap::collect:
- marks in parallel from the entry table, reading each object’s pointer map, and sweeps in parallel;
- never moves objects. Other processes hold offsets and weak words, which must stay valid;
- keeps free blocks and free entries on lock-free stacks inside the file, with tagged heads against ABA.
Cross-heaps have no concurrent marking, young collections, reference counting or evacuation: collect is
stop-the-world and waits for every live process’s mutators to leave.
Processes, crashes and lifetime
A process may be killed at any instruction, including in the middle of a collection. The rules on this page keep the heap readable and keep the other processes running.
The attachment table
Every mapping takes one of 32 slots in the superblock page (at offset 1024). A slot holds:
- the process id;
- the process start time, read from
/proc/<pid>/stat. A reused pid is never mistaken for the old process, and zombies count as dead; - the number of its threads inside
mutate; - the number of its threads waiting at the door.
The handshake
A collection request is one word holding the collector’s slot (0 means none).
- A mutator increments its count and then checks the request.
- A collector raises the request and then checks every count.
- All of these are sequentially consistent, so at least one side sees the other.
Waiting is a futex on the shared word (not process-private). Waiters wake every 10 ms to check whether the other process is still alive. A collector that was waited on by stalled mutators lets them in before taking the next collection, so back-to-back collections cannot starve mutators.
Crash recovery
- A dead mutator is not waited for. The next collector releases every entry its slot held and frees the slot, but never the slot that still owns the request: a newcomer reusing it would look like a live collector.
- A dead collector is taken over by whoever sees the request owned by a dead process, a mutator at the door or another collector. The collection is redone from scratch with an epoch newer than the one the dead collector started, because its marks must not count for this round. Sweeping again is harmless, since it only ran after marking had finished.
- Every step leaves the heap readable:
- an object is written before its start bit (or a large object’s block kinds) is published;
- a large object’s tail blocks are freed before its head, so an interrupted free is redone and skips the work already done;
- the collector extends the block and entry tables up to their counters before reading them, in case a process died between bumping a counter and growing the file.
A process that dies may leave a few blocks or entries unusable (killed between taking one and recording it). Nothing it left is ever read as an object.
Owners and lifetime
A cross-heap belongs to the process that created it. The superblock records the owner (pid and start time) and a random incarnation.
- When the owner exits or is killed, the heap dies with it unless
CrossHeap::persistwas called. Whoever notices first marks it dead and deletes the file and its marker. Memory goes back once every mapping is dropped. - Other processes see
is_alive() == false, andtry_mutatereturnsHeapDead. Their handles stay safe to use and to drop. - A
CrossHeapRefstores its target heap’s incarnation. Once a dead heap’s number is reused, the reference readsNoneand collections do not follow it. CrossHeapRoot::persistmakes a root that belongs to no process. It is found again by entry number and returned withCrossHeapMutator::release.
Heap numbers
Numbers are claimed per directory through .paragc-<k> marker files. Every decision is taken under the marker’s
flock, re-checked against the path after locking, so a half-created heap is never mistaken for a stale one and
simultaneous creators get distinct numbers.
Several heaps at once: avoiding deadlock
Collectors and mutators take heaps like ordered locks:
- a group collection takes each heap in heap-number order and drains it before taking the next;
CrossHeap::mutate_withenters two heaps lowest number first.
A mutator nesting in that order never waits on a heap that a collector holds while the collector waits on it. Nesting in the other order still works: a collector that cannot drain within 50 ms releases what it holds, pauses for a random, doubling interval (capped at 200 ms) and retries.
Who collects
Any attached process can call collect or collect_group, except on a heap marked owner-only. A cross-heap attached
to a private heap as its old generation is owner-only (see Promotion).
Weak references, signatures and the mailbox
These three mechanisms carry a reference across processes without making any process wait for another.
Birth stamps
Every cross-heap object header has a 32-bit birth stamp: a SplitMix64 mix of the heap’s incarnation and the allocation epoch. Two objects that occupy the same address at different times almost certainly have different stamps.
CrossHeapWeak
A CrossHeapWeak<B> is one word: the object’s offset (in 8-byte units) in the high bits and its stamp in the low 27 bits.
- It registers nothing in the target heap and keeps nothing alive.
- No collection looks at it, so across processes it holds up no one.
Reading it inside the target heap’s mutate checks, in order:
- the block was opened, and its table entry has memory behind it;
- the start bit is set at that offset, or the offset is the start of a large object’s first block;
- the stamp matches.
If any check fails the result is None. This covers a dead object, a new object in the same place, and a heap number
reused by a new heap. Stamps collide with a probability of about 2⁻²⁷.
Signatures
A Signature is 32 bytes: the weak word, the heap’s incarnation and the type key. It is the thing one process sends to
another.
#![allow(unused)]
fn main() {
// sender
let sig: Signature = cross.mutate(|cm| cm.sign(obj));
let bytes: [u8; SIGNATURE_BYTES] = sig.into();
send(&bytes, cross.fd()); // e.g. over a Unix socket with SCM_RIGHTS
// receiver
let sig = Signature::from(&bytes);
let heap = space.open_fd(fd, threads)?;
let value = heap.mutate(|cm| cm.resolve::<NodeB>(&sig).map(|n| n.value));
}
| Call | Use |
|---|---|
sign(gc) | sign an object in a cross-heap |
sign_promoted(gc) | sign a promoted object straight from a private Gc, with no brand |
resolve::<B>(&sig) | the object, if it is alive and of type B |
verify(&sig) | check a signature without knowing the type |
A signature from an untrusted party is only read. A forged or stale one gives None and never crashes the reader.
The mailbox: the owner acts for others
Some resources cannot be shared: file descriptors, Boxes, anything private to the owner’s process. Another process
asks the owner to act instead:
CrossHeapMutator::post(obj)takes an entry owned by no process, so the request survives the poster’s death;- it pushes the entry on the mailbox stack in the superblock;
- it bumps the mail count, a futex word, and wakes the owner.
The owner polls CrossHeap::mail(), the count received so far, or sleeps in wait_mail(seen, timeout) until it changes. It must not wait inside the heap’s own mutate, or collections would wait for it forever. take_mail takes everything, oldest
first; find gets each object, and release returns its entry when done.
Shrinking and descriptors
CrossHeap::shrink runs a collection that keeps no spare blocks, which brings the file’s real usage down after a burst
of garbage. CrossHeap::fd gives the file descriptor to pass to another process. The receiver needs no path, and the
heap is mapped at the same window number in every process.
Promotion: a cross-heap as the old generation
Allocating every shareable object directly in a cross-heap would mean deciding at allocation time which heap an object goes to. Promotion avoids that. Objects are allocated in the private heap as usual, and those that survive a young collection move into a cross-heap attached as the old generation. Allocation stays lazy, and short-lived objects never touch shared memory.
Setting it up
#![allow(unused)]
fn main() {
let space = CrossHeapSpace::reserve_fixed()?; // the fixed region, at 64 TiB
let cross = space.create(path, threads)?; // or create_anonymous for in-process use
let mut heap = Heap::new(threads);
heap.attach_cross_heap(&cross)?;
}
- The cross-heap must be in the fixed region, so absolute addresses stored in its objects are valid in every process that also reserved it.
- The cross-heap becomes owner-only: other processes and
collect_groupleave it alone. Only this private heap collects it. - With a cross-heap attached, young evacuation is forced to
Full, and concurrent marking is not supported.
Shareable private objects
#![allow(unused)]
fn main() {
#[repr(C)]
#[derive(Trace, Shared)]
struct Node<'gc> {
value: u64,
next: Slot<'gc, Node<'gc>>,
}
heap.mutate(|m| m.alloc_shared(Node { value: 1, next: None.into() }));
}
Mutator::alloc_shared (and alloc_shared_tail) takes a type that is both Trace and Shared, without Drop. Its
Gc, Option<Gc>, Slot and WordSlot fields are recorded in the pointer map as absolute-address edges (WORD_EDGE,
PTR_EDGE).
What a young collection does
When a worker reaches a young object during a young collection:
- it asks the object’s
visitfunction, in asking mode, whether the type is shareable and what its type number in the cross-heap is. The type is registered there on first use; - if the type is shareable, the worker claims the object, copies it with its own promotion buffer into the cross-heap,
writes the
PHeader(type number and birth stamp), and forwards the old header to the new place; - slots, roots and weak references in the private heap are relocated to the new address, as for any move.
A promoted object’s edges are traced too. Its targets must be shareable; a non-shareable target reached from a promoted
object panics (in_shared).
The private heap skips cross-heap addresses everywhere: marking, reference counting, the remembered set, the write barrier, root and weak tables.
Writing a private object into a cross-heap object
A cross-heap object can be written after promotion, for example promoted.next.set(m, Some(fresh)) where fresh is
still young. The barrier:
- records the slot in the remembered set;
- sets
promotion_pending.
Until the next young collection, the slot holds a private address. Other processes treat an address outside the region as
empty. The next young collection promotes fresh and rewrites the slot through the remembered set. A host checks
Heap::promotion_pending() when a unit of work ends and runs a young collection if it is set.
Collecting
Heap::collect:
- runs a young collection, so every shareable survivor is promoted;
- runs a full private mark;
- collects the cross-heap with extra roots: the cross-heap edges the private mark found, and the root-table entries pointing into the cross-heap;
- clears private weak references whose cross-heap target died.
CrossHeap::collect on an owner-only heap does nothing.
Handing an object to another process
#![allow(unused)]
fn main() {
let sig = heap.mutate(|m| cross.mutate(|cm| cm.sign_promoted(m.get(&root))));
}
sign_promoted returns None for an object that is still private. A signature keeps nothing alive. If the owner drops
the object and collects, the signature resolves to None.
How j8 uses it
With j8’s crossheap feature, an Isolate takes a cross-heap (attach_cross_heap):
scope.shares.share(mc, gc)records an object to share and returns a ticket;- j8 never collects in the middle of running JS. At the end of
Isolate::enter, if anything is pending, it runs one young collection and then signs the recorded objects; take_signatureshands out (ticket, signature) pairs.
JS strings are shareable: their bytes, and the UTF-16 units of non-ASCII text, live in the object’s tail.
Testing and Miri
Test files
| File | Covers |
|---|---|
tests/gc.rs | the private heap: survival, finalization counts, threads, large objects, deep structures, concurrent marking and sweeping, evacuation, young collections, reference counting, shrinking, serial drop |
tests/weak.rs | weak references through every kind of collection, the read barrier during concurrent marking |
tests/word.rs | WordSlot through full, young and concurrent collections |
tests/far.rs | Far, pinning, group collections, cross-heap cycles of private heaps |
tests/cross_heap.rs | cross-heaps in one process: pointer maps, large objects, two mappings, CrossHeapRef, group collections, weak references, signatures, mailbox, shrink, promotion, tails (needs --features crossheap) |
tests/processes.rs | several processes on one heap: killed mutators, killed collectors, random kills, restarts, heap numbers, 8 processes with half killed (needs --features crossheap) |
The README’s verification table lists every test and what it checks.
Running them
cargo test --test gc -- --exact <name>
cargo test --features crossheap --test cross_heap
cargo test --features crossheap --test processes
promotion_into_attached_cross_heap runs several scenarios inside one test, because a process can hold the fixed region
only once at a time and tests in one file run on parallel threads.
Miri
Every test also runs under Miri, with both Stacked Borrows and Tree Borrows (scaled down under cfg(miri)):
MIRIFLAGS="-Zmiri-permissive-provenance -Zmiri-ignore-leaks" cargo +nightly miri test --test gc -- --exact <name>
MIRIFLAGS="-Zmiri-permissive-provenance -Zmiri-ignore-leaks -Zmiri-tree-borrows" cargo +nightly miri test --test gc -- --exact <name>
- Miri cannot map files. Under Miri the cross-heap region is an ordinary allocation (4 windows of 16 MiB); the tests without a file run on it, and the file tests are skipped.
-Zmiri-ignore-leaksis needed because crossbeam-epoch’s global collector still holds deferred garbage at exit.- At 4 collector threads Stacked Borrows reports a violation inside crossbeam-epoch itself, so tests use 2 under Miri. A few concurrent tests still hit it under Stacked Borrows and are clean under Tree Borrows.
Known flaky test
gc::background_release_while_mutating can fail in release builds; it passes in debug builds. The failure predates
0.6.0.
Benchmarks
paragc against cppgc (V8’s Oilpan), gc-arena, gc (rust-gc) and dumpster on a 16-core machine. The numbers are
wall-clock milliseconds, best of 5. Setup, workloads and every configuration are in
benches/benchmark.md.
| paragc | cppgc | gc-arena | dumpster | gc | |
|---|---|---|---|---|---|
| Pause, 1M live + 1M dead, 1 thread | 20.2 | 44.2 | 16.3 | 16.3 | 90.2 |
| Pause, 16 threads | 4.2 | 44.9 | – | – | – |
| Pause, concurrent marking + sweeping, 1 thread | 0.02 | – | – | – | – |
| GCBench, 1 thread | 50.3 | 121.0 | 118.0 | 97.8 | 294.6 |
| GCBench, 4 threads | 54.3 | 94.2 | – | – | – |
| Many mutators, 16 threads | 9.0 | – | – | 343.5 | – |
| Fragmentation (~80 MB live), RSS after / peak MB | 111 / 416 | 445 / 1894 | – | – | – |
How to read them:
- On a single thread, gc-arena and dumpster pause for less time. paragc’s full collection also rebuilds reference counts.
- With threads, and in throughput, paragc leads.
- cppgc’s forced full collection marks on one thread even with every parallel flag on, and pays an FFI call per allocation and per edge in this harness.
The comparison benchmarks depend on large libraries such as V8, so benches/ is a workspace of its own.
Code conventions
No locks
paragc takes no locks, not even inside collections. Shared state changes through atomics, lock-free stacks with tagged
heads, append-only segmented vectors and futex waits. The work-stealing deques and backoff come from crossbeam; the
append-only vector and the push-only list are paragc’s own (src/sync.rs).
Exclusion by borrowing
Operations that need the world stopped take &mut Heap. The borrow checker is the safepoint protocol. New code should
keep it that way rather than add runtime coordination for private heaps.
Source layout
The source is flat; similar things live together:
| File | Contents |
|---|---|
layout.rs | blocks, lines, headers, the cross-heap window layout and superblock |
heap.rs | Heap, Mutator, Tlab, collections, CrossHeap, CrossHeapMutator, promotion |
mark.rs | Tracer, the work-stealing crew, the copier, the cross-heap marker |
sweep.rs | sweeping and large objects |
handle.rs | Gc, Slot, WordSlot, Root, Weak, Far, cross-heap handles, Signature, Shared |
shm.rs | the cross-heap address region, windows, heap numbers, process liveness (Linux) |
sync.rs | lock-free building blocks and futex waits |
Cross-heap items are gated on cfg(crossheap), set by build.rs only on Linux with the crossheap feature.
Style
- Code, comments, messages and docs in English; READMEs in English (default) and Chinese.
cargo clippy --all-targetsis clean withpedantic, with and without--features crossheap.- Named constants, never bare numbers, for sizes, thresholds and bit fields.
- Every
unsafeblock states its safety argument in a// SAFETY:comment.
Releases
The repository’s main is protected: every change goes through a pull request on GitHub (0x00-Community/paragc).
Versions are published to crates.io (paragc and paragc-macros, same version) and tagged vX.Y.Z.
Limits and open problems
This page lists what paragc does not do yet and the places where its design is under strain. Read it before relying on cross-heaps.
The private heap
- No stack scanning. Every object that must survive a collection is reachable from a
Root,Faror entry. - 128 MiB per object. The header stores the size in 24 bits of granules.
Slotis two words: the value and the value last counted for reference counting.- Concurrent young collections do not exist. A young collection is a pause, short as it is.
- Address-indexed structures must stay young while they point at young objects (see Young collections).
- One flaky test:
gc::background_release_while_mutatingin release builds.
Cross-heaps
- Stop-the-world only. A cross-heap has no concurrent marking, young collections, reference counting or evacuation.
collectwaits for every live process’s mutators to leave, so a process that is alive but stuck insidemutatestalls collection. Only dead processes are skipped. - No compaction. Cross-heap objects never move, so fragmentation is only reduced by reusing lines and punching empty blocks.
- 64 windows. Heap numbers are window numbers in a 1 TiB region, so one directory holds at most 64 live cross-heaps, and every heap is at most 16 GiB.
CrossHeapRefregistrations are only returned by group collections. Code that rewrites them often should run group collections.- Trust. Every process that maps a heap can read and corrupt all of it. There is no per-object protection and no locking. Concurrent writers from several processes get no consistency guarantees; this is a deliberate choice, with thread semantics expected to come from the language above.
- Dead processes can leave a few blocks or entries unusable, if they were killed between taking one and recording it.
- Stamps collide with probability about 2⁻²⁷, so a stale weak reference or signature can very rarely resolve to a new object of the same type at the same address.
Promotion
- The fixed region is per process.
reserve_fixedmaps 1 TiB at 64 TiB withMAP_FIXED_NOREPLACE. If something else already sits there, it fails, and a process can hold it only once. - Concurrent marking is off while a cross-heap is attached, and young evacuation is forced to
Full. A runtime that promotes gives up paragc’s shortest pauses. - Promotion panics on a non-shareable edge. A shareable object that reaches a non-shareable one through a traced edge makes the collector panic. That is a programming error, but it surfaces in the collector rather than at the write.
- The owner-only cross-heap grows until a full collection. Young collections promote into it but never free in it.
Only
Heap::collectreclaims cross-heap garbage, so a runtime that mostly runs young collections must still schedule full ones. - Anonymous cross-heaps are private.
create_anonymousis visible only inside its process. A runtime that wants other processes to read its objects must create a file heap and pass its descriptor. - A short window of invisibility. A private object written into a cross-heap slot stays private, and reads as empty elsewhere, until the next young collection.
The object model above paragc (j8)
Sharing a JS value means the receiver must understand the object’s layout, not just its bytes. In j8 today:
| Part of a JS object | Where it lives | Shareable |
|---|---|---|
| strings | GC heap, bytes in the object’s tail | ✓ (since j8 #49) |
| shapes (property names, attributes, transitions) | Arc<Shape> outside the heap; objects keep a raw *const Shape | ✗ |
| property values (inline slots, the store) | GC heap | only once their shape is shareable |
| dictionary-mode properties | GC objects holding Vec and HashMap | ✗ |
| functions | bytecode and FunctionInfo outside the heap | ✗ |
| host objects | Box<dyn Any> | ✗; the owner acts for others through the mailbox |
Shapes are the hard part. Shape identity is a memory address:
- the executor’s inline caches compare shape addresses and keep
Arc<Shape>to stay valid; - the JIT bakes shape addresses into machine code (
CheckShape).
A shape that is an ordinary moving GC object would break both. The candidate designs:
- Immortal shapes in a fixed place. Shapes live in an append-only area inside the fixed region, never move and are
never freed. Caches and the JIT stay as they are, and
Arcrefcounting goes away. The cost is that shape memory only grows; objects with more than 64 properties already switch to dictionary mode. - Shapes as moving GC objects. Memory is reclaimed, but inline caches must hold traced references and the JIT must either stop baking addresses or recompile when shapes move.
- A second, shareable description made at promotion. The hot path is unchanged, but every object carries one more word, and later property additions must be kept in sync on both sides.
This decision is open; it blocks stage 3 of cross-process objects in j8.
Roadmap
Done
| Version | What |
|---|---|
| up to 0.4 | parallel stop-the-world collection and a persistent pool; concurrent marking; concurrent and lazy sweeping; opportunistic evacuation; young collections; reference counting with background release; tracing every 16 young collections; concurrent recount; Far and group collections |
| 0.5 | cross-heaps on shared memory with several processes and crash recovery; CrossHeapRef and group collections across cross-heaps; heap numbers and restarts; heap lifetime tied to the owner; WordSlot and Weak |
| 0.6.0 | the crossheap feature (Linux only); the Public* API renamed to CrossHeap*; CrossHeapWeak, birth stamps and signatures; open_fd; the mailbox; shrinking cross-heaps; promotion into an attached cross-heap with owner-only collection; deferred promotion of private objects written into cross-heap slots; sign_promoted |
| 0.6.1 | alloc_tail / alloc_shared_tail |
Next
- Cross-process JS objects in j8, stage by stage:
- an isolate takes a cross-heap and signs shared objects when a turn ends (done);
- strings in the GC heap (done);
- shapes: see Limits and open problems;
- ordinary objects and arrays;
- functions, with bytecode in the cross-heap;
- host objects, through the owner and the mailbox.
- Cross-heaps with concurrent marking, young collections and reference counting, so a large shared old generation does not mean long pauses.
- Concurrent marking with a cross-heap attached.
- A concurrent young collection, and a one-word
Slot.
Glossary
| Term | Meaning |
|---|---|
| block | 32 KiB aligned unit of heap memory |
| line | 256 B unit of reuse inside a block |
| granule | 8 B, the allocation alignment |
| epoch | the number a collection writes into mark words and line marks; never cleared |
| mutate | Heap::mutate, a call during which the thread may allocate and use Gc handles |
| brand | the 'gc lifetime tying a Gc to one mutate; also the brand! type mapping it back |
| root | Root<B>, a handle with no lifetime that keeps its object alive |
| entry | a root-table slot claimed for a reference from outside the heap (Far, cross-heap entries) |
| tlab | thread-local allocation buffer |
| overflow cursor | second allocation cursor for medium objects that do not fit the current run |
| black allocation | giving new objects the marking epoch during concurrent marking |
| SATB | snapshot at the beginning: the write barrier marks overwritten values during concurrent marking |
| evacuation | copying live objects out of sparse blocks while marking |
| forwarding address | the new address left in an old header after a move |
| young / old | not yet / already marked with the last finished epoch (sticky mark bits) |
| remembered set | slots of old objects that were written with young values |
| promotion | a young object becoming old: in place, by move, or into an attached cross-heap |
| RC | reference count of edges from old objects |
| parity | the bit that tells current counts from the previous generation’s |
Far | a direct reference from one private heap into another |
| group collection | collecting several heaps together to reclaim cycles across them |
| cross-heap | a heap in a shared-memory file, usable by several processes |
| region / window | the reserved address range for cross-heaps / one heap’s 16 GiB slice of it |
| fixed region | the region at 64 TiB, the same address in every process |
| superblock | the first page of a cross-heap |
| attachment | a process’s slot in a cross-heap’s superblock |
| incarnation | a random identity a cross-heap gets at creation |
| birth stamp | 32-bit tag in a cross-heap header from the incarnation and the allocation epoch |
| type key | hash of a shareable type’s name, size and pointer map |
| pointer map | offsets of the pointer fields of a shareable type |
| signature | 32 bytes (weak word, incarnation, type key) that identify a cross-heap object to another process |
| owner-only | a cross-heap only its owner may collect (an attached old generation) |
| mailbox | a stack in the superblock where other processes post objects for the owner to act on |