Skip to main content

js_gc/
lib.rs

1//! `quickjs-gc` — reference counting with cycle collection.
2//!
3//! QuickJS frees memory by reference counting and removes reference cycles with a
4//! periodic collector (see `JS_RunGC` / `JS_SetGCThreshold` in the C API). Its
5//! observable behaviour — an object is released as soon as the last reference
6//! goes away, finalizers run at that moment, and cycles are reclaimed only when
7//! the collector runs — is part of the semantics we have to reproduce, so we use
8//! the same algorithm instead of a tracing GC.
9//!
10//! This crate provides:
11//!
12//! * [`Heap`] — one per [`Runtime`]-equivalent; owns the registry of live boxes,
13//!   the allocation accounting and the collector.
14//! * [`Gc<T>`] — a strong, reference-counted handle. Cheap to clone, derefs to
15//!   `T`, releases the value deterministically when the last handle dies.
16//! * [`WeakGc<T>`] — a non-owning handle that does not keep the value alive and
17//!   does not participate in cycle detection (used by `WeakRef`, `WeakMap` and
18//!   `FinalizationRegistry`).
19//! * [`Trace`] — implemented by every type that can own `Gc` handles, so the
20//!   collector can walk the object graph.
21//!
22//! # The collector
23//!
24//! `Heap::collect` implements trial deletion (Bacon–Rajan "synchronous cycle
25//! collection"):
26//!
27//! 1. Every live box starts with `gc_refs = strong_count`.
28//! 2. Every internal edge (a `Gc` field inside another box) decrements the
29//!    child's `gc_refs`. After this pass `gc_refs > 0` means "at least one
30//!    reference lives outside the heap", i.e. the box is a root.
31//! 3. Mark everything reachable from the roots.
32//! 4. Unmarked boxes are only reachable from garbage: their values are dropped
33//!    (which releases the handles they hold) and the boxes themselves are freed
34//!    once their strong count reaches zero.
35//!
36//! # Contract
37//!
38//! * A [`Heap`] must outlive every [`Gc`] created from it. Dropping a heap with
39//!   live boxes leaks them; it is not undefined behaviour.
40//! * [`Trace::trace`] must not mutate the object graph, allocate, or panic:
41//!   it runs while the collector holds a snapshot of the heap.
42//! * `Gc<T>`/`WeakGc<T>` are `!Send + !Sync`: a heap is single threaded, which
43//!   matches a QuickJS `JSRuntime` (`JS_SetSharedArrayBufferFunctions` is the
44//!   only cross-thread escape hatch and it is handled in `js-value`).
45
46#![deny(unsafe_op_in_unsafe_fn)]
47#![warn(missing_docs)]
48
49use std::alloc::{Layout, dealloc};
50use std::cell::{Cell, RefCell, UnsafeCell};
51use std::fmt;
52use std::ops::Deref;
53use std::ptr::NonNull;
54
55// ---------------------------------------------------------------------------
56// Trace / Tracer
57// ---------------------------------------------------------------------------
58
59/// Types that may own [`Gc`] handles.
60///
61/// Implementations must visit *every* `Gc` field, directly or through another
62/// type that implements `Trace`. Missing an edge makes the collector treat the
63/// object as unreachable from that side, which only costs memory (a cycle that
64/// is never reclaimed), never safety — but it is still a bug.
65pub trait Trace {
66    /// Report every `Gc` owned by `self` to `tracer`.
67    fn trace(&self, tracer: &mut Tracer);
68
69    /// Bytes this value owns *outside* its own box: a string's buffer, an array's element
70    /// vector, a buffer's bytes.
71    ///
72    /// Without this, a memory limit would be counting the box a container lives in and
73    /// missing everything inside it — `var a = []; for (;;) a.push(1.5)` allocates one box
74    /// and then gigabytes of element slots, so the limit would never trip. The default is
75    /// zero, which is right for everything that is only a box: numbers, symbols, cells,
76    /// compiled code.
77    ///
78    /// Read in three places, all of them at allocation boundaries rather than in a loop: on
79    /// allocation (added), on free (subtracted, so nothing leaks out of the accounting) and
80    /// when a container grows or shrinks in place (adjusted by the container itself).
81    fn external_bytes(&self) -> usize {
82        0
83    }
84}
85
86/// Visitor used by [`Trace`] implementations.
87///
88/// The collector drives this; user code only calls [`Tracer::visit`] (usually
89/// through `#[derive]`-style impls for containers).
90pub struct Tracer<'a> {
91    out: &'a mut Vec<NonNull<Header>>,
92}
93
94impl Tracer<'_> {
95    /// Record that `gc` is owned by the object currently being traced.
96    #[inline]
97    pub fn visit<T: Trace + 'static>(&mut self, gc: &Gc<T>) {
98        self.out.push(gc.header());
99    }
100}
101
102macro_rules! trace_noop {
103    ($($t:ty),* $(,)?) => {$(
104        impl Trace for $t {
105            #[inline]
106            fn trace(&self, _tracer: &mut Tracer) {}
107        }
108    )*};
109}
110
111trace_noop!(
112    (),
113    bool,
114    char,
115    i8,
116    i16,
117    i32,
118    i64,
119    i128,
120    isize,
121    u8,
122    u16,
123    u32,
124    u64,
125    u128,
126    usize,
127    f32,
128    f64,
129    String,
130    &'static str,
131);
132
133impl<T: Trace + ?Sized> Trace for &T {
134    #[inline]
135    fn trace(&self, tracer: &mut Tracer) {
136        (**self).trace(tracer);
137    }
138
139    /// Forwarded, and not for symmetry: without this, `value.external_bytes()` inside
140    /// [`payload_impl`] — where `value: &T` — resolves to *this* impl and answers the
141    /// default 0, silently. A 2 MB string then reported 0 bytes and the memory limit did
142    /// not exist. Every blanket impl below forwards for the same reason.
143    #[inline]
144    fn external_bytes(&self) -> usize {
145        (**self).external_bytes()
146    }
147}
148
149impl<T: Trace + ?Sized> Trace for Box<T> {
150    #[inline]
151    fn trace(&self, tracer: &mut Tracer) {
152        (**self).trace(tracer);
153    }
154
155    #[inline]
156    fn external_bytes(&self) -> usize {
157        (**self).external_bytes()
158    }
159}
160
161impl<T: Trace> Trace for Option<T> {
162    #[inline]
163    fn trace(&self, tracer: &mut Tracer) {
164        if let Some(v) = self {
165            v.trace(tracer);
166        }
167    }
168}
169
170impl<T: Trace> Trace for Vec<T> {
171    #[inline]
172    fn trace(&self, tracer: &mut Tracer) {
173        for v in self {
174            v.trace(tracer);
175        }
176    }
177}
178
179impl<T: Trace, const N: usize> Trace for [T; N] {
180    #[inline]
181    fn trace(&self, tracer: &mut Tracer) {
182        for v in self {
183            v.trace(tracer);
184        }
185    }
186}
187
188impl<T: Trace, U: Trace> Trace for (T, U) {
189    #[inline]
190    fn trace(&self, tracer: &mut Tracer) {
191        self.0.trace(tracer);
192        self.1.trace(tracer);
193    }
194}
195
196impl<T: Trace> Trace for std::rc::Rc<T> {
197    #[inline]
198    fn trace(&self, tracer: &mut Tracer) {
199        (**self).trace(tracer);
200    }
201}
202
203impl<T: Trace> Trace for RefCell<T> {
204    #[inline]
205    fn trace(&self, tracer: &mut Tracer) {
206        // A cell that is mutably borrowed while the collector runs would make
207        // tracing panic; skipping the edge is the safe degradation (worst case:
208        // we fail to reclaim a cycle, never a use-after-free).
209        if let Ok(v) = self.try_borrow() {
210            v.trace(tracer);
211        }
212    }
213}
214
215impl<T: Trace> Trace for Cell<T>
216where
217    T: Copy,
218{
219    #[inline]
220    fn trace(&self, tracer: &mut Tracer) {
221        self.get().trace(tracer);
222    }
223}
224
225// ---------------------------------------------------------------------------
226// Header / box
227// ---------------------------------------------------------------------------
228
229/// Type-erased box header. Every `GcBox<T>` starts with one, so a
230/// `NonNull<Header>` can identify, trace and free any box without knowing `T`.
231struct Header {
232    strong: Cell<usize>,
233    weak: Cell<usize>,
234    /// Scratch space for the collector: `strong` minus internal edges.
235    gc_refs: Cell<isize>,
236    marked: Cell<bool>,
237    /// Index into [`Heap::boxes`], `usize::MAX` when not registered.
238    slot: Cell<usize>,
239    heap: NonNull<Heap>,
240    trace_fn: unsafe fn(NonNull<Header>, &mut Tracer),
241    drop_fn: unsafe fn(NonNull<Header>),
242    /// [`Trace::external_bytes`] for the concrete type, so the heap can subtract a box's
243    /// payload on the free path without knowing what it is.
244    payload_fn: unsafe fn(NonNull<Header>) -> usize,
245    size: usize,
246    align: usize,
247}
248
249#[repr(C)]
250struct GcBox<T: Trace + 'static> {
251    header: Header,
252    value: UnsafeCell<Option<T>>,
253}
254
255unsafe fn trace_impl<T: Trace + 'static>(h: NonNull<Header>, tracer: &mut Tracer) {
256    let b = h.cast::<GcBox<T>>();
257    // SAFETY: `h` came from a `GcBox<T>` allocation and the value is only
258    // mutated by `drop_impl` / construction, never while tracing.
259    let value = unsafe { &*(*b.as_ptr()).value.get() };
260    if let Some(v) = value {
261        v.trace(tracer);
262    }
263}
264
265unsafe fn drop_impl<T: Trace + 'static>(h: NonNull<Header>) {
266    let b = h.cast::<GcBox<T>>();
267    // Take the value out before dropping it so that re-entrant `Gc` releases
268    // (this drop can free other boxes) never observe a borrowed cell.
269    // SAFETY: `h` came from a `GcBox<T>` allocation; the value is dropped once.
270    let taken = unsafe { (*b.as_ptr()).value.get().as_mut() }.and_then(Option::take);
271    drop(taken);
272}
273
274/// [`Trace::external_bytes`] for `T`, reached through a box header.
275///
276/// Takes a header rather than a `&T` because the heap has to subtract a box's payload on
277/// the free path, where all it has is the header — the value has no type any more.
278///
279/// # Safety
280///
281/// `h` must be a live `GcBox<T>` that has not yet had its value taken.
282unsafe fn payload_impl<T: Trace + 'static>(h: NonNull<Header>) -> usize {
283    let b = h.cast::<GcBox<T>>();
284    // The deref-and-match matters: `Option<&Option<T>>::as_ref` would bind `value` to
285    // `&Option<T>`, and `Trace::external_bytes` on *that* answers the default 0 — silently,
286    // because `Option<T>` is traceable too. The measurement then reported nothing and the
287    // memory limit did not exist.
288    //
289    // SAFETY: the caller guarantees the box is live and still holds its value.
290    match unsafe { &*(*b.as_ptr()).value.get() } {
291        Some(value) => Trace::external_bytes(value),
292        None => 0,
293    }
294}
295
296// ---------------------------------------------------------------------------
297// Heap
298// ---------------------------------------------------------------------------
299
300/// Statistics returned by [`Heap::collect`].
301#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
302pub struct CollectStats {
303    /// Boxes registered before the collection.
304    pub before: usize,
305    /// Boxes reclaimed by this collection.
306    pub collected: usize,
307    /// Boxes still alive afterwards.
308    pub after: usize,
309    /// Collection passes performed (always 1 today; kept for API stability).
310    pub passes: usize,
311}
312
313/// Owns the live-object registry for one JavaScript runtime.
314pub struct Heap {
315    boxes: RefCell<Vec<Option<NonNull<Header>>>>,
316    free_slots: RefCell<Vec<usize>>,
317    live: Cell<usize>,
318    allocated: Cell<usize>,
319    threshold: Cell<usize>,
320    /// The memory limit in bytes, or `None` for "no limit".
321    ///
322    /// A `Cell` because a limit is set once by the host and read on every allocation, and
323    /// because [`Heap::fits`] may need to collect, which takes `&self`.
324    memory_limit: Cell<Option<usize>>,
325}
326
327impl Default for Heap {
328    fn default() -> Self {
329        Self::new()
330    }
331}
332
333impl Heap {
334    /// Create an empty heap. Runs the collector only when asked
335    /// (see [`Heap::set_threshold`]).
336    pub fn new() -> Heap {
337        Heap {
338            boxes: RefCell::new(Vec::new()),
339            free_slots: RefCell::new(Vec::new()),
340            live: Cell::new(0),
341            allocated: Cell::new(0),
342            threshold: Cell::new(usize::MAX),
343            memory_limit: Cell::new(None),
344        }
345    }
346
347    /// Cap the heap at `limit` bytes of GC-managed objects, or remove the cap with `None`.
348    ///
349    /// This is what `qjs --memory-limit` sets. It is checked by [`Heap::fits`], which the
350    /// engine calls before an allocation whose size it can predict (`new Array(n)`,
351    /// `s.repeat(n)`) and at its own checkpoints.
352    pub fn set_memory_limit(&self, limit: Option<usize>) {
353        self.memory_limit.set(limit);
354    }
355
356    /// The current limit, if any.
357    pub fn memory_limit(&self) -> Option<usize> {
358        self.memory_limit.get()
359    }
360
361    /// Measure what the heap really holds: every live box plus its payload.
362    ///
363    /// O(live boxes), so it is not something to do per instruction — but it is the only
364    /// number that cannot drift, and the engine calls it on a schedule (see
365    /// `Interp::check_memory`) rather than tracking every mutation. Tracking would mean a
366    /// `&Heap` threaded through every array and map mutator in the engine, and one forgotten
367    /// call site would make the limit quietly wrong; measuring cannot forget.
368    pub fn measure_used(&self) -> usize {
369        let boxes = self.boxes.borrow();
370        let mut total = 0;
371        for &h in boxes.iter().flatten() {
372            // SAFETY: `boxes` only ever holds live, registered boxes, and a registered box
373            // still holds its value.
374            let header = unsafe { h.as_ref() };
375            total += header.size + unsafe { (header.payload_fn)(h) };
376        }
377        total
378    }
379
380    /// Whether `payload` more bytes fit under the limit.
381    ///
382    /// `payload` is what the caller is *about to hold* — the length of a string it is
383    /// building, the element vector a container is growing into — not the increment.
384    /// Passing the increment would check every push against a fresh budget and never trip.
385    ///
386    /// A failed check collects once and asks again. That is not politeness: a script that
387    /// fills the limit, catches the error and drops the reference must be able to carry on,
388    /// and the reference behaves that way (`js_malloc` triggers a GC and retries).
389    pub fn fits(&self, payload: usize) -> bool {
390        let Some(limit) = self.memory_limit.get() else {
391            return true;
392        };
393        if self.allocated.get().saturating_add(payload) <= limit {
394            return true;
395        }
396        self.collect();
397        self.allocated.get().saturating_add(payload) <= limit
398    }
399
400    /// Bytes the heap accounts for: live boxes plus the payloads they reported.
401    pub fn used_bytes(&self) -> usize {
402        self.allocated.get()
403    }
404
405    /// Record that a live box grew or shrank by `delta` bytes of payload.
406    ///
407    /// Containers call this when they change in place — `a.push(x)` grows an element vector
408    /// without allocating a box — so that the running total stays equal to what
409    /// [`Trace::external_bytes`] will report when the box is freed. The two must agree
410    /// exactly, or the subtraction at free time would leave the counter permanently wrong.
411    pub fn adjust_payload(&self, delta: isize) {
412        let current = self.allocated.get() as isize;
413        let next = current.saturating_add(delta);
414        self.allocated.set(next.max(0) as usize);
415    }
416
417    /// Subtract the payload of a box that is about to be dropped.
418    ///
419    /// Separated from [`Heap::deregister`] because of ordering: on the reference-counting
420    /// path the value is dropped *before* deregistering, and once the value is gone its
421    /// payload cannot be measured any more.
422    ///
423    /// # Safety
424    ///
425    /// `h` must be a live box whose value has not been taken.
426    unsafe fn release_payload(&self, h: NonNull<Header>) {
427        let payload = unsafe { (h.as_ref().payload_fn)(h) };
428        self.allocated
429            .set(self.allocated.get().saturating_sub(payload));
430    }
431
432    /// Whether the heap is over its limit right now, collecting first if it might be.
433    ///
434    /// The interpreter asks this at its checkpoints — a call, a backward branch — which is
435    /// as often as it can cheaply ask, and often enough that a loop allocating an object per
436    /// iteration stops within a few allocations of the limit.
437    pub fn over_limit(&self) -> bool {
438        !self.fits(0)
439    }
440
441    /// Trigger a collection automatically when more than `n` boxes are live.
442    /// `usize::MAX` disables automatic collection (the default).
443    pub fn set_threshold(&self, n: usize) {
444        self.threshold.set(n);
445    }
446
447    /// Current automatic-collection threshold.
448    pub fn threshold(&self) -> usize {
449        self.threshold.get()
450    }
451
452    /// Number of live boxes.
453    pub fn live_count(&self) -> usize {
454        self.live.get()
455    }
456
457    /// Approximate number of bytes held by live boxes (excluding external
458    /// allocations made by the values themselves).
459    pub fn allocated_bytes(&self) -> usize {
460        self.allocated.get()
461    }
462
463    fn register(&self, h: NonNull<Header>) {
464        let mut boxes = self.boxes.borrow_mut();
465        let slot = match self.free_slots.borrow_mut().pop() {
466            Some(slot) => {
467                boxes[slot] = Some(h);
468                slot
469            }
470            None => {
471                boxes.push(Some(h));
472                boxes.len() - 1
473            }
474        };
475        // SAFETY: `h` points at a live box we just allocated.
476        let header = unsafe { h.as_ref() };
477        header.slot.set(slot);
478        self.live.set(self.live.get() + 1);
479        // The payload is counted from the start, not when it first changes: a string's
480        // bytes never change, and they are the whole reason the counter exists.
481        // SAFETY: the box is live and holds its value.
482        let payload = unsafe { (header.payload_fn)(h) };
483        self.allocated
484            .set(self.allocated.get() + header.size + payload);
485    }
486
487    fn deregister(&self, h: NonNull<Header>) {
488        // SAFETY: `h` points at a live box (we are on its release path).
489        let header = unsafe { h.as_ref() };
490        let slot = header.slot.get();
491        if slot == usize::MAX {
492            return;
493        }
494
495        header.slot.set(usize::MAX);
496        {
497            let mut boxes = self.boxes.borrow_mut();
498            boxes[slot] = None;
499        }
500        self.free_slots.borrow_mut().push(slot);
501        self.live.set(self.live.get() - 1);
502        // Saturating, not `-`: the counter is maintained by the containers that grow their
503        // payload in place, and a container that reports a shrink it never reported as a
504        // growth would take the counter below zero and abort the process *during* a drop —
505        // the worst place for a panic, because it runs while other boxes are being
506        // released. Drifting low costs a limit that is slightly generous; drifting into a
507        // panic costs the program. `payload_accounting_returns_to_zero` in the tests is
508        // what keeps the drift from going unnoticed.
509        self.allocated
510            .set(self.allocated.get().saturating_sub(header.size));
511    }
512
513    /// Run the cycle collector.
514    ///
515    /// Objects that are only reachable from garbage are dropped and freed;
516    /// everything reachable from a handle living outside the heap survives.
517    pub fn collect(&self) -> CollectStats {
518        let snapshot: Vec<NonNull<Header>> =
519            self.boxes.borrow().iter().flatten().copied().collect();
520        let before = snapshot.len();
521        if before == 0 {
522            return CollectStats {
523                before: 0,
524                collected: 0,
525                after: 0,
526                passes: 1,
527            };
528        }
529
530        // 1. gc_refs = strong.
531        for &h in &snapshot {
532            // SAFETY: every pointer in the snapshot came from a registered box
533            // that cannot be freed while we hold no handles to it... see note
534            // below: no user code runs between snapshot and marking, and boxes
535            // are only freed once their strong count reaches zero, which cannot
536            // happen without user code.
537            let header = unsafe { h.as_ref() };
538            header.gc_refs.set(header.strong.get() as isize);
539            header.marked.set(false);
540        }
541
542        // 2. Subtract internal edges.
543        let mut buf: Vec<NonNull<Header>> = Vec::new();
544        for &h in &snapshot {
545            buf.clear();
546            // SAFETY: see above; `trace` is a pure read of the graph.
547            unsafe { trace_children(h, &mut buf) };
548            for &child in &buf {
549                // SAFETY: children are live boxes (they are referenced by a
550                // live box, so their strong count is >= 1).
551                let child = unsafe { child.as_ref() };
552                child.gc_refs.set(child.gc_refs.get() - 1);
553            }
554        }
555
556        // 3. Mark from roots (`gc_refs > 0` == referenced from outside the heap).
557        let mut stack: Vec<NonNull<Header>> = Vec::new();
558        for &h in &snapshot {
559            // SAFETY: see above.
560            let header = unsafe { h.as_ref() };
561            if header.gc_refs.get() > 0 && !header.marked.get() {
562                header.marked.set(true);
563                stack.push(h);
564            }
565        }
566        while let Some(h) = stack.pop() {
567            buf.clear();
568            // SAFETY: see above.
569            unsafe { trace_children(h, &mut buf) };
570            for &child in &buf {
571                // SAFETY: see above.
572                let header = unsafe { child.as_ref() };
573                if !header.marked.get() {
574                    header.marked.set(true);
575                    stack.push(child);
576                }
577            }
578        }
579
580        // 4. Drop the unmarked boxes. Bump every one of them first so that
581        //    releasing handles inside them cannot free a box we are still
582        //    iterating over.
583        let dead: Vec<NonNull<Header>> = snapshot
584            .iter()
585            .copied()
586            .filter(|h| {
587                // SAFETY: see above.
588                !unsafe { h.as_ref() }.marked.get()
589            })
590            .collect();
591
592        for &h in &dead {
593            // SAFETY: see above.
594            let header = unsafe { h.as_ref() };
595            header.strong.set(header.strong.get() + 1);
596        }
597        for &h in &dead {
598            // The payload goes with the value, and it has to be subtracted before the value
599            // is dropped — afterwards there is nothing left to measure.
600            // SAFETY: the box is live and still holds its value.
601            unsafe { self.release_payload(h) };
602            // SAFETY: `drop_fn` only touches this box's own value.
603            unsafe { (h.as_ref().drop_fn)(h) };
604            // The value is gone, so the object left the object graph; do it now
605            // so that a (later) collection never sees a value-less box.
606            self.deregister(h);
607        }
608        for &h in &dead {
609            // SAFETY: see above.
610            let header = unsafe { h.as_ref() };
611            let strong = header.strong.get();
612            header.strong.set(strong - 1);
613            if strong == 1 && header.weak.get() == 0 {
614                // SAFETY: no strong or weak references remain.
615                unsafe { dealloc_box(h) };
616            }
617        }
618
619        let after = self.live_count();
620        CollectStats {
621            before,
622            collected: before - after,
623            after,
624            passes: 1,
625        }
626    }
627}
628
629/// # Safety
630/// `h` must point at a live box.
631unsafe fn trace_children(h: NonNull<Header>, out: &mut Vec<NonNull<Header>>) {
632    // SAFETY: caller guarantees `h` is live; `trace_fn` only reads the value.
633    let trace_fn = unsafe { h.as_ref().trace_fn };
634    let mut tracer = Tracer { out };
635    // SAFETY: as above.
636    unsafe { trace_fn(h, &mut tracer) };
637}
638
639/// # Safety
640/// `h` must point at a box that has already been deregistered and whose strong
641/// and weak counts both reached zero.
642unsafe fn dealloc_box(h: NonNull<Header>) {
643    // SAFETY: caller guarantees the header is still allocated.
644    let (size, align) = {
645        let header = unsafe { h.as_ref() };
646        (header.size, header.align)
647    };
648    // SAFETY: the allocation was made with this exact layout.
649    unsafe {
650        dealloc(
651            h.as_ptr() as *mut u8,
652            Layout::from_size_align_unchecked(size, align),
653        )
654    };
655}
656
657// ---------------------------------------------------------------------------
658// Gc
659// ---------------------------------------------------------------------------
660
661/// A strong, reference-counted handle to a heap value.
662///
663/// `Gc<T>` is a pointer-sized handle: cloning is cheap, [`Deref`] gives `&T`,
664/// and the value is released as soon as the last handle is gone (cycles need
665/// [`Heap::collect`]).
666pub struct Gc<T: Trace + 'static> {
667    ptr: NonNull<GcBox<T>>,
668}
669
670impl<T: Trace + 'static> Gc<T> {
671    /// Allocate `value` on `heap` and return a handle to it.
672    pub fn new(heap: &Heap, value: T) -> Gc<T> {
673        let boxed = Box::new(GcBox {
674            header: Header {
675                strong: Cell::new(1),
676                weak: Cell::new(0),
677                gc_refs: Cell::new(1),
678                marked: Cell::new(false),
679                slot: Cell::new(usize::MAX),
680                heap: NonNull::from(heap),
681                trace_fn: trace_impl::<T>,
682                drop_fn: drop_impl::<T>,
683                payload_fn: payload_impl::<T>,
684                size: std::mem::size_of::<GcBox<T>>(),
685                align: std::mem::align_of::<GcBox<T>>(),
686            },
687            value: UnsafeCell::new(Some(value)),
688        });
689        // SAFETY: `Box::into_raw` never returns null.
690        let ptr = unsafe { NonNull::new_unchecked(Box::into_raw(boxed)) };
691        let gc = Gc { ptr };
692        heap.register(gc.header());
693        if heap.live_count() > heap.threshold() {
694            heap.collect();
695        }
696        gc
697    }
698
699    /// The heap this value lives on.
700    pub fn heap(&self) -> &Heap {
701        // SAFETY: the heap outlives the box (documented contract).
702        unsafe { self.ptr.as_ref().header.heap.as_ref() }
703    }
704
705    /// Number of strong handles (including internal edges).
706    pub fn strong_count(&self) -> usize {
707        // SAFETY: the handle keeps the box alive.
708        unsafe { self.ptr.as_ref().header.strong.get() }
709    }
710
711    /// Whether two handles point at the same box.
712    pub fn ptr_eq(&self, other: &Gc<T>) -> bool {
713        self.ptr == other.ptr
714    }
715
716    /// Whether this handle points at the box `other` refers to, expired or not.
717    ///
718    /// A `WeakMap` stores weak handles but compares against live keys, so the comparison
719    /// has to span both handle types without upgrading (which would resurrect the key).
720    pub fn upgrades_to(&self, other: &WeakGc<T>) -> bool {
721        self.ptr == other.ptr
722    }
723
724    /// Create a non-owning handle.
725    pub fn downgrade(&self) -> WeakGc<T> {
726        // SAFETY: the handle keeps the box alive.
727        let header = unsafe { &self.ptr.as_ref().header };
728        header.weak.set(header.weak.get() + 1);
729        WeakGc { ptr: self.ptr }
730    }
731
732    #[inline]
733    fn header(&self) -> NonNull<Header> {
734        // SAFETY: `Header` is the first field of `GcBox<T>` (`#[repr(C)]`).
735        unsafe { NonNull::new_unchecked(self.ptr.as_ptr().cast::<Header>()) }
736    }
737}
738
739impl<T: Trace + 'static> Clone for Gc<T> {
740    fn clone(&self) -> Gc<T> {
741        // SAFETY: the handle keeps the box alive.
742        let header = unsafe { &self.ptr.as_ref().header };
743        header.strong.set(header.strong.get() + 1);
744        Gc { ptr: self.ptr }
745    }
746}
747
748impl<T: Trace + 'static> Drop for Gc<T> {
749    fn drop(&mut self) {
750        dec_strong(self.header());
751    }
752}
753
754impl<T: Trace + 'static> Deref for Gc<T> {
755    type Target = T;
756
757    fn deref(&self) -> &T {
758        // SAFETY: the handle keeps the box and its value alive.
759        unsafe {
760            (*self.ptr.as_ptr())
761                .value
762                .get()
763                .as_ref()
764                .expect("UnsafeCell pointer is never null")
765                .as_ref()
766                .expect("Gc value accessed after it was dropped")
767        }
768    }
769}
770
771impl<T: Trace + 'static> fmt::Debug for Gc<T> {
772    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
773        write!(
774            f,
775            "Gc({:p}, strong={})",
776            self.ptr.as_ptr(),
777            self.strong_count()
778        )
779    }
780}
781
782impl<T: Trace + 'static> Trace for Gc<T> {
783    #[inline]
784    fn trace(&self, tracer: &mut Tracer) {
785        tracer.visit(self);
786    }
787
788    /// What the *pointee* owns, which is counted against the pointee's own box.
789    ///
790    /// Forwarded so that `gc.external_bytes()` is not a silent zero, but a container must
791    /// never add this to its own total: it would count the child's payload twice, once here
792    /// and once when the child's box is registered.
793    #[inline]
794    fn external_bytes(&self) -> usize {
795        (**self).external_bytes()
796    }
797}
798
799/// # Safety
800/// `h` must point at a live box.
801fn dec_strong(h: NonNull<Header>) {
802    // SAFETY: caller guarantees liveness; a handle owns one strong reference.
803    let header = unsafe { h.as_ref() };
804    let strong = header.strong.get();
805    debug_assert!(strong > 0, "Gc strong count underflow");
806    header.strong.set(strong - 1);
807    if strong == 1 {
808        // SAFETY: we just dropped the last reference.
809        unsafe { release(h) };
810    }
811}
812
813/// # Safety
814/// `h` must point at a box whose strong count just reached zero.
815unsafe fn release(h: NonNull<Header>) {
816    // Hold the allocation for the duration of the drop by pretending one strong reference
817    // still exists. Dropping the value can release the *last* `WeakGc` that points at this
818    // very box — `Owner { weak: WeakGc<Back> }` inside `Back { owner: Gc<Owner> }` is
819    // exactly that shape — and `WeakGc::drop` frees a box whose strong count is zero. The
820    // header reads below would then touch freed memory.
821    //
822    // The collector's step 4 already does this (it bumps every dead box before dropping
823    // it); this is the same trick on the reference-counting path.
824    let header = unsafe { h.as_ref() };
825    header.strong.set(1);
826    // SAFETY: the value is still there, and the heap outlives its boxes.
827    unsafe {
828        header.heap.as_ref().release_payload(h);
829        (header.drop_fn)(h);
830    }
831    // SAFETY: the allocation was held above, so the header is still ours.
832    let header = unsafe { h.as_ref() };
833    // A box without a value is no longer part of the object graph, so the collector must
834    // not see it; weak handles may still point at the header.
835    // SAFETY: the heap outlives its boxes (documented contract).
836    unsafe { header.heap.as_ref() }.deregister(h);
837    header.strong.set(0);
838    if header.weak.get() == 0 {
839        // SAFETY: no strong or weak references remain.
840        unsafe { dealloc_box(h) };
841    }
842}
843
844// ---------------------------------------------------------------------------
845// WeakGc
846// ---------------------------------------------------------------------------
847
848/// A non-owning handle to a heap value.
849///
850/// Keeps the box header (but not the value) alive, so [`WeakGc::upgrade`] can
851/// tell whether the value is still there. Weak handles are not traced: they do
852/// not keep anything alive and they do not take part in cycle detection, which
853/// is what `WeakRef`/`WeakMap` need.
854pub struct WeakGc<T: Trace + 'static> {
855    ptr: NonNull<GcBox<T>>,
856}
857
858impl<T: Trace + 'static> WeakGc<T> {
859    /// Try to obtain a strong handle.
860    pub fn upgrade(&self) -> Option<Gc<T>> {
861        // SAFETY: the weak handle keeps the box allocation alive.
862        let header = unsafe { &self.ptr.as_ref().header };
863        if header.strong.get() == 0 {
864            None
865        } else {
866            header.strong.set(header.strong.get() + 1);
867            Some(Gc { ptr: self.ptr })
868        }
869    }
870
871    /// Whether the value has been released.
872    pub fn is_expired(&self) -> bool {
873        // SAFETY: the weak handle keeps the box allocation alive.
874        unsafe { self.ptr.as_ref() }.header.strong.get() == 0
875    }
876
877    /// Whether two handles point at the same box, live or expired.
878    ///
879    /// This is the key comparison a `WeakMap` needs: two objects are one key exactly when
880    /// they are one allocation, and comparing addresses answers that without upgrading —
881    /// so an expired entry still compares equal to nothing and can be swept.
882    pub fn ptr_eq(&self, other: &WeakGc<T>) -> bool {
883        self.ptr == other.ptr
884    }
885}
886
887impl<T: Trace + 'static> Clone for WeakGc<T> {
888    fn clone(&self) -> WeakGc<T> {
889        // SAFETY: the weak handle keeps the box allocation alive.
890        let header = unsafe { &self.ptr.as_ref().header };
891        header.weak.set(header.weak.get() + 1);
892        WeakGc { ptr: self.ptr }
893    }
894}
895
896impl<T: Trace + 'static> Drop for WeakGc<T> {
897    fn drop(&mut self) {
898        // SAFETY: this weak handle owns one weak reference.
899        let header = unsafe { &self.ptr.as_ref().header };
900        let weak = header.weak.get();
901        debug_assert!(weak > 0, "WeakGc weak count underflow");
902        header.weak.set(weak - 1);
903        if weak == 1 && header.strong.get() == 0 {
904            // SAFETY: the header keeps its address until both counts are zero,
905            // and the last reference of either kind just went away.
906            let h = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().cast::<Header>()) };
907            unsafe { dealloc_box(h) };
908        }
909    }
910}
911
912impl<T: Trace + 'static> fmt::Debug for WeakGc<T> {
913    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914        write!(
915            f,
916            "WeakGc({:p}, expired={})",
917            self.ptr.as_ptr(),
918            self.is_expired()
919        )
920    }
921}
922
923impl<T: Trace + 'static> Trace for WeakGc<T> {
924    #[inline]
925    fn trace(&self, _tracer: &mut Tracer) {}
926}