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