quickjs-gc 0.10.1

Reference counting with cycle collection for the pure-Rust QuickJS port
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
//! `quickjs-gc` — reference counting with cycle collection.
//!
//! QuickJS frees memory by reference counting and removes reference cycles with a
//! periodic collector (see `JS_RunGC` / `JS_SetGCThreshold` in the C API). Its
//! observable behaviour — an object is released as soon as the last reference
//! goes away, finalizers run at that moment, and cycles are reclaimed only when
//! the collector runs — is part of the semantics we have to reproduce, so we use
//! the same algorithm instead of a tracing GC.
//!
//! This crate provides:
//!
//! * [`Heap`] — one per [`Runtime`]-equivalent; owns the registry of live boxes,
//!   the allocation accounting and the collector.
//! * [`Gc<T>`] — a strong, reference-counted handle. Cheap to clone, derefs to
//!   `T`, releases the value deterministically when the last handle dies.
//! * [`WeakGc<T>`] — a non-owning handle that does not keep the value alive and
//!   does not participate in cycle detection (used by `WeakRef`, `WeakMap` and
//!   `FinalizationRegistry`).
//! * [`Trace`] — implemented by every type that can own `Gc` handles, so the
//!   collector can walk the object graph.
//!
//! # The collector
//!
//! `Heap::collect` implements trial deletion (Bacon–Rajan "synchronous cycle
//! collection"):
//!
//! 1. Every live box starts with `gc_refs = strong_count`.
//! 2. Every internal edge (a `Gc` field inside another box) decrements the
//!    child's `gc_refs`. After this pass `gc_refs > 0` means "at least one
//!    reference lives outside the heap", i.e. the box is a root.
//! 3. Mark everything reachable from the roots.
//! 4. Unmarked boxes are only reachable from garbage: their values are dropped
//!    (which releases the handles they hold) and the boxes themselves are freed
//!    once their strong count reaches zero.
//!
//! # Contract
//!
//! * A [`Heap`] must outlive every [`Gc`] created from it. Dropping a heap with
//!   live boxes leaks them; it is not undefined behaviour.
//! * [`Trace::trace`] must not mutate the object graph, allocate, or panic:
//!   it runs while the collector holds a snapshot of the heap.
//! * `Gc<T>`/`WeakGc<T>` are `!Send + !Sync`: a heap is single threaded, which
//!   matches a QuickJS `JSRuntime` (`JS_SetSharedArrayBufferFunctions` is the
//!   only cross-thread escape hatch and it is handled in `js-value`).

#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]

use std::alloc::{Layout, dealloc};
use std::cell::{Cell, RefCell, UnsafeCell};
use std::fmt;
use std::ops::Deref;
use std::ptr::NonNull;

// ---------------------------------------------------------------------------
// Trace / Tracer
// ---------------------------------------------------------------------------

/// Types that may own [`Gc`] handles.
///
/// Implementations must visit *every* `Gc` field, directly or through another
/// type that implements `Trace`. Missing an edge makes the collector treat the
/// object as unreachable from that side, which only costs memory (a cycle that
/// is never reclaimed), never safety — but it is still a bug.
pub trait Trace {
    /// Report every `Gc` owned by `self` to `tracer`.
    fn trace(&self, tracer: &mut Tracer);

    /// Bytes this value owns *outside* its own box: a string's buffer, an array's element
    /// vector, a buffer's bytes.
    ///
    /// Without this, a memory limit would be counting the box a container lives in and
    /// missing everything inside it — `var a = []; for (;;) a.push(1.5)` allocates one box
    /// and then gigabytes of element slots, so the limit would never trip. The default is
    /// zero, which is right for everything that is only a box: numbers, symbols, cells,
    /// compiled code.
    ///
    /// Read in three places, all of them at allocation boundaries rather than in a loop: on
    /// allocation (added), on free (subtracted, so nothing leaks out of the accounting) and
    /// when a container grows or shrinks in place (adjusted by the container itself).
    fn external_bytes(&self) -> usize {
        0
    }
}

/// Visitor used by [`Trace`] implementations.
///
/// The collector drives this; user code only calls [`Tracer::visit`] (usually
/// through `#[derive]`-style impls for containers).
pub struct Tracer<'a> {
    out: &'a mut Vec<NonNull<Header>>,
}

impl Tracer<'_> {
    /// Record that `gc` is owned by the object currently being traced.
    #[inline]
    pub fn visit<T: Trace + 'static>(&mut self, gc: &Gc<T>) {
        self.out.push(gc.header());
    }
}

macro_rules! trace_noop {
    ($($t:ty),* $(,)?) => {$(
        impl Trace for $t {
            #[inline]
            fn trace(&self, _tracer: &mut Tracer) {}
        }
    )*};
}

trace_noop!(
    (),
    bool,
    char,
    i8,
    i16,
    i32,
    i64,
    i128,
    isize,
    u8,
    u16,
    u32,
    u64,
    u128,
    usize,
    f32,
    f64,
    String,
    &'static str,
);

impl<T: Trace + ?Sized> Trace for &T {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        (**self).trace(tracer);
    }

    /// Forwarded, and not for symmetry: without this, `value.external_bytes()` inside
    /// [`payload_impl`] — where `value: &T` — resolves to *this* impl and answers the
    /// default 0, silently. A 2 MB string then reported 0 bytes and the memory limit did
    /// not exist. Every blanket impl below forwards for the same reason.
    #[inline]
    fn external_bytes(&self) -> usize {
        (**self).external_bytes()
    }
}

impl<T: Trace + ?Sized> Trace for Box<T> {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        (**self).trace(tracer);
    }

    #[inline]
    fn external_bytes(&self) -> usize {
        (**self).external_bytes()
    }
}

impl<T: Trace> Trace for Option<T> {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        if let Some(v) = self {
            v.trace(tracer);
        }
    }
}

impl<T: Trace> Trace for Vec<T> {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        for v in self {
            v.trace(tracer);
        }
    }
}

impl<T: Trace, const N: usize> Trace for [T; N] {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        for v in self {
            v.trace(tracer);
        }
    }
}

impl<T: Trace, U: Trace> Trace for (T, U) {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        self.0.trace(tracer);
        self.1.trace(tracer);
    }
}

impl<T: Trace> Trace for std::rc::Rc<T> {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        (**self).trace(tracer);
    }
}

impl<T: Trace> Trace for RefCell<T> {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        // A cell that is mutably borrowed while the collector runs would make
        // tracing panic; skipping the edge is the safe degradation (worst case:
        // we fail to reclaim a cycle, never a use-after-free).
        if let Ok(v) = self.try_borrow() {
            v.trace(tracer);
        }
    }
}

impl<T: Trace> Trace for Cell<T>
where
    T: Copy,
{
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        self.get().trace(tracer);
    }
}

// ---------------------------------------------------------------------------
// Header / box
// ---------------------------------------------------------------------------

/// Type-erased box header. Every `GcBox<T>` starts with one, so a
/// `NonNull<Header>` can identify, trace and free any box without knowing `T`.
struct Header {
    strong: Cell<usize>,
    weak: Cell<usize>,
    /// Scratch space for the collector: `strong` minus internal edges.
    gc_refs: Cell<isize>,
    marked: Cell<bool>,
    /// Index into [`Heap::boxes`], `usize::MAX` when not registered.
    slot: Cell<usize>,
    heap: NonNull<Heap>,
    trace_fn: unsafe fn(NonNull<Header>, &mut Tracer),
    drop_fn: unsafe fn(NonNull<Header>),
    /// [`Trace::external_bytes`] for the concrete type, so the heap can subtract a box's
    /// payload on the free path without knowing what it is.
    payload_fn: unsafe fn(NonNull<Header>) -> usize,
    size: usize,
    align: usize,
}

#[repr(C)]
struct GcBox<T: Trace + 'static> {
    header: Header,
    value: UnsafeCell<Option<T>>,
}

unsafe fn trace_impl<T: Trace + 'static>(h: NonNull<Header>, tracer: &mut Tracer) {
    let b = h.cast::<GcBox<T>>();
    // SAFETY: `h` came from a `GcBox<T>` allocation and the value is only
    // mutated by `drop_impl` / construction, never while tracing.
    let value = unsafe { &*(*b.as_ptr()).value.get() };
    if let Some(v) = value {
        v.trace(tracer);
    }
}

unsafe fn drop_impl<T: Trace + 'static>(h: NonNull<Header>) {
    let b = h.cast::<GcBox<T>>();
    // Take the value out before dropping it so that re-entrant `Gc` releases
    // (this drop can free other boxes) never observe a borrowed cell.
    // SAFETY: `h` came from a `GcBox<T>` allocation; the value is dropped once.
    let taken = unsafe { (*b.as_ptr()).value.get().as_mut() }.and_then(Option::take);
    drop(taken);
}

/// [`Trace::external_bytes`] for `T`, reached through a box header.
///
/// Takes a header rather than a `&T` because the heap has to subtract a box's payload on
/// the free path, where all it has is the header — the value has no type any more.
///
/// # Safety
///
/// `h` must be a live `GcBox<T>` that has not yet had its value taken.
unsafe fn payload_impl<T: Trace + 'static>(h: NonNull<Header>) -> usize {
    let b = h.cast::<GcBox<T>>();
    // The deref-and-match matters: `Option<&Option<T>>::as_ref` would bind `value` to
    // `&Option<T>`, and `Trace::external_bytes` on *that* answers the default 0 — silently,
    // because `Option<T>` is traceable too. The measurement then reported nothing and the
    // memory limit did not exist.
    //
    // SAFETY: the caller guarantees the box is live and still holds its value.
    match unsafe { &*(*b.as_ptr()).value.get() } {
        Some(value) => Trace::external_bytes(value),
        None => 0,
    }
}

// ---------------------------------------------------------------------------
// Heap
// ---------------------------------------------------------------------------

/// Statistics returned by [`Heap::collect`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CollectStats {
    /// Boxes registered before the collection.
    pub before: usize,
    /// Boxes reclaimed by this collection.
    pub collected: usize,
    /// Boxes still alive afterwards.
    pub after: usize,
    /// Collection passes performed (always 1 today; kept for API stability).
    pub passes: usize,
}

/// Owns the live-object registry for one JavaScript runtime.
pub struct Heap {
    boxes: RefCell<Vec<Option<NonNull<Header>>>>,
    free_slots: RefCell<Vec<usize>>,
    live: Cell<usize>,
    allocated: Cell<usize>,
    threshold: Cell<usize>,
    /// The memory limit in bytes, or `None` for "no limit".
    ///
    /// A `Cell` because a limit is set once by the host and read on every allocation, and
    /// because [`Heap::fits`] may need to collect, which takes `&self`.
    memory_limit: Cell<Option<usize>>,
}

impl Default for Heap {
    fn default() -> Self {
        Self::new()
    }
}

impl Heap {
    /// Create an empty heap. Runs the collector only when asked
    /// (see [`Heap::set_threshold`]).
    pub fn new() -> Heap {
        Heap {
            boxes: RefCell::new(Vec::new()),
            free_slots: RefCell::new(Vec::new()),
            live: Cell::new(0),
            allocated: Cell::new(0),
            threshold: Cell::new(usize::MAX),
            memory_limit: Cell::new(None),
        }
    }

    /// Cap the heap at `limit` bytes of GC-managed objects, or remove the cap with `None`.
    ///
    /// This is what `qjs --memory-limit` sets. It is checked by [`Heap::fits`], which the
    /// engine calls before an allocation whose size it can predict (`new Array(n)`,
    /// `s.repeat(n)`) and at its own checkpoints.
    pub fn set_memory_limit(&self, limit: Option<usize>) {
        self.memory_limit.set(limit);
    }

    /// The current limit, if any.
    pub fn memory_limit(&self) -> Option<usize> {
        self.memory_limit.get()
    }

    /// Measure what the heap really holds: every live box plus its payload.
    ///
    /// O(live boxes), so it is not something to do per instruction — but it is the only
    /// number that cannot drift, and the engine calls it on a schedule (see
    /// `Interp::check_memory`) rather than tracking every mutation. Tracking would mean a
    /// `&Heap` threaded through every array and map mutator in the engine, and one forgotten
    /// call site would make the limit quietly wrong; measuring cannot forget.
    pub fn measure_used(&self) -> usize {
        let boxes = self.boxes.borrow();
        let mut total = 0;
        for &h in boxes.iter().flatten() {
            // SAFETY: `boxes` only ever holds live, registered boxes, and a registered box
            // still holds its value.
            let header = unsafe { h.as_ref() };
            total += header.size + unsafe { (header.payload_fn)(h) };
        }
        total
    }

    /// Whether `payload` more bytes fit under the limit.
    ///
    /// `payload` is what the caller is *about to hold* — the length of a string it is
    /// building, the element vector a container is growing into — not the increment.
    /// Passing the increment would check every push against a fresh budget and never trip.
    ///
    /// A failed check collects once and asks again. That is not politeness: a script that
    /// fills the limit, catches the error and drops the reference must be able to carry on,
    /// and the reference behaves that way (`js_malloc` triggers a GC and retries).
    pub fn fits(&self, payload: usize) -> bool {
        let Some(limit) = self.memory_limit.get() else {
            return true;
        };
        if self.allocated.get().saturating_add(payload) <= limit {
            return true;
        }
        self.collect();
        self.allocated.get().saturating_add(payload) <= limit
    }

    /// Bytes the heap accounts for: live boxes plus the payloads they reported.
    pub fn used_bytes(&self) -> usize {
        self.allocated.get()
    }

    /// Record that a live box grew or shrank by `delta` bytes of payload.
    ///
    /// Containers call this when they change in place — `a.push(x)` grows an element vector
    /// without allocating a box — so that the running total stays equal to what
    /// [`Trace::external_bytes`] will report when the box is freed. The two must agree
    /// exactly, or the subtraction at free time would leave the counter permanently wrong.
    pub fn adjust_payload(&self, delta: isize) {
        let current = self.allocated.get() as isize;
        let next = current.saturating_add(delta);
        self.allocated.set(next.max(0) as usize);
    }

    /// Subtract the payload of a box that is about to be dropped.
    ///
    /// Separated from [`Heap::deregister`] because of ordering: on the reference-counting
    /// path the value is dropped *before* deregistering, and once the value is gone its
    /// payload cannot be measured any more.
    ///
    /// # Safety
    ///
    /// `h` must be a live box whose value has not been taken.
    unsafe fn release_payload(&self, h: NonNull<Header>) {
        let payload = unsafe { (h.as_ref().payload_fn)(h) };
        self.allocated
            .set(self.allocated.get().saturating_sub(payload));
    }

    /// Whether the heap is over its limit right now, collecting first if it might be.
    ///
    /// The interpreter asks this at its checkpoints — a call, a backward branch — which is
    /// as often as it can cheaply ask, and often enough that a loop allocating an object per
    /// iteration stops within a few allocations of the limit.
    pub fn over_limit(&self) -> bool {
        !self.fits(0)
    }

    /// Trigger a collection automatically when more than `n` boxes are live.
    /// `usize::MAX` disables automatic collection (the default).
    pub fn set_threshold(&self, n: usize) {
        self.threshold.set(n);
    }

    /// Current automatic-collection threshold.
    pub fn threshold(&self) -> usize {
        self.threshold.get()
    }

    /// Number of live boxes.
    pub fn live_count(&self) -> usize {
        self.live.get()
    }

    /// Approximate number of bytes held by live boxes (excluding external
    /// allocations made by the values themselves).
    pub fn allocated_bytes(&self) -> usize {
        self.allocated.get()
    }

    fn register(&self, h: NonNull<Header>) {
        let mut boxes = self.boxes.borrow_mut();
        let slot = match self.free_slots.borrow_mut().pop() {
            Some(slot) => {
                boxes[slot] = Some(h);
                slot
            }
            None => {
                boxes.push(Some(h));
                boxes.len() - 1
            }
        };
        // SAFETY: `h` points at a live box we just allocated.
        let header = unsafe { h.as_ref() };
        header.slot.set(slot);
        self.live.set(self.live.get() + 1);
        // The payload is counted from the start, not when it first changes: a string's
        // bytes never change, and they are the whole reason the counter exists.
        // SAFETY: the box is live and holds its value.
        let payload = unsafe { (header.payload_fn)(h) };
        self.allocated
            .set(self.allocated.get() + header.size + payload);
    }

    fn deregister(&self, h: NonNull<Header>) {
        // SAFETY: `h` points at a live box (we are on its release path).
        let header = unsafe { h.as_ref() };
        let slot = header.slot.get();
        if slot == usize::MAX {
            return;
        }

        header.slot.set(usize::MAX);
        {
            let mut boxes = self.boxes.borrow_mut();
            boxes[slot] = None;
        }
        self.free_slots.borrow_mut().push(slot);
        self.live.set(self.live.get() - 1);
        // Saturating, not `-`: the counter is maintained by the containers that grow their
        // payload in place, and a container that reports a shrink it never reported as a
        // growth would take the counter below zero and abort the process *during* a drop —
        // the worst place for a panic, because it runs while other boxes are being
        // released. Drifting low costs a limit that is slightly generous; drifting into a
        // panic costs the program. `payload_accounting_returns_to_zero` in the tests is
        // what keeps the drift from going unnoticed.
        self.allocated
            .set(self.allocated.get().saturating_sub(header.size));
    }

    /// Run the cycle collector.
    ///
    /// Objects that are only reachable from garbage are dropped and freed;
    /// everything reachable from a handle living outside the heap survives.
    pub fn collect(&self) -> CollectStats {
        let snapshot: Vec<NonNull<Header>> =
            self.boxes.borrow().iter().flatten().copied().collect();
        let before = snapshot.len();
        if before == 0 {
            return CollectStats {
                before: 0,
                collected: 0,
                after: 0,
                passes: 1,
            };
        }

        // 1. gc_refs = strong.
        for &h in &snapshot {
            // SAFETY: every pointer in the snapshot came from a registered box
            // that cannot be freed while we hold no handles to it... see note
            // below: no user code runs between snapshot and marking, and boxes
            // are only freed once their strong count reaches zero, which cannot
            // happen without user code.
            let header = unsafe { h.as_ref() };
            header.gc_refs.set(header.strong.get() as isize);
            header.marked.set(false);
        }

        // 2. Subtract internal edges.
        let mut buf: Vec<NonNull<Header>> = Vec::new();
        for &h in &snapshot {
            buf.clear();
            // SAFETY: see above; `trace` is a pure read of the graph.
            unsafe { trace_children(h, &mut buf) };
            for &child in &buf {
                // SAFETY: children are live boxes (they are referenced by a
                // live box, so their strong count is >= 1).
                let child = unsafe { child.as_ref() };
                child.gc_refs.set(child.gc_refs.get() - 1);
            }
        }

        // 3. Mark from roots (`gc_refs > 0` == referenced from outside the heap).
        let mut stack: Vec<NonNull<Header>> = Vec::new();
        for &h in &snapshot {
            // SAFETY: see above.
            let header = unsafe { h.as_ref() };
            if header.gc_refs.get() > 0 && !header.marked.get() {
                header.marked.set(true);
                stack.push(h);
            }
        }
        while let Some(h) = stack.pop() {
            buf.clear();
            // SAFETY: see above.
            unsafe { trace_children(h, &mut buf) };
            for &child in &buf {
                // SAFETY: see above.
                let header = unsafe { child.as_ref() };
                if !header.marked.get() {
                    header.marked.set(true);
                    stack.push(child);
                }
            }
        }

        // 4. Drop the unmarked boxes. Bump every one of them first so that
        //    releasing handles inside them cannot free a box we are still
        //    iterating over.
        let dead: Vec<NonNull<Header>> = snapshot
            .iter()
            .copied()
            .filter(|h| {
                // SAFETY: see above.
                !unsafe { h.as_ref() }.marked.get()
            })
            .collect();

        for &h in &dead {
            // SAFETY: see above.
            let header = unsafe { h.as_ref() };
            header.strong.set(header.strong.get() + 1);
        }
        for &h in &dead {
            // The payload goes with the value, and it has to be subtracted before the value
            // is dropped — afterwards there is nothing left to measure.
            // SAFETY: the box is live and still holds its value.
            unsafe { self.release_payload(h) };
            // SAFETY: `drop_fn` only touches this box's own value.
            unsafe { (h.as_ref().drop_fn)(h) };
            // The value is gone, so the object left the object graph; do it now
            // so that a (later) collection never sees a value-less box.
            self.deregister(h);
        }
        for &h in &dead {
            // SAFETY: see above.
            let header = unsafe { h.as_ref() };
            let strong = header.strong.get();
            header.strong.set(strong - 1);
            if strong == 1 && header.weak.get() == 0 {
                // SAFETY: no strong or weak references remain.
                unsafe { dealloc_box(h) };
            }
        }

        let after = self.live_count();
        CollectStats {
            before,
            collected: before - after,
            after,
            passes: 1,
        }
    }
}

/// # Safety
/// `h` must point at a live box.
unsafe fn trace_children(h: NonNull<Header>, out: &mut Vec<NonNull<Header>>) {
    // SAFETY: caller guarantees `h` is live; `trace_fn` only reads the value.
    let trace_fn = unsafe { h.as_ref().trace_fn };
    let mut tracer = Tracer { out };
    // SAFETY: as above.
    unsafe { trace_fn(h, &mut tracer) };
}

/// # Safety
/// `h` must point at a box that has already been deregistered and whose strong
/// and weak counts both reached zero.
unsafe fn dealloc_box(h: NonNull<Header>) {
    // SAFETY: caller guarantees the header is still allocated.
    let (size, align) = {
        let header = unsafe { h.as_ref() };
        (header.size, header.align)
    };
    // SAFETY: the allocation was made with this exact layout.
    unsafe {
        dealloc(
            h.as_ptr() as *mut u8,
            Layout::from_size_align_unchecked(size, align),
        )
    };
}

// ---------------------------------------------------------------------------
// Gc
// ---------------------------------------------------------------------------

/// A strong, reference-counted handle to a heap value.
///
/// `Gc<T>` is a pointer-sized handle: cloning is cheap, [`Deref`] gives `&T`,
/// and the value is released as soon as the last handle is gone (cycles need
/// [`Heap::collect`]).
pub struct Gc<T: Trace + 'static> {
    ptr: NonNull<GcBox<T>>,
}

impl<T: Trace + 'static> Gc<T> {
    /// Allocate `value` on `heap` and return a handle to it.
    pub fn new(heap: &Heap, value: T) -> Gc<T> {
        let boxed = Box::new(GcBox {
            header: Header {
                strong: Cell::new(1),
                weak: Cell::new(0),
                gc_refs: Cell::new(1),
                marked: Cell::new(false),
                slot: Cell::new(usize::MAX),
                heap: NonNull::from(heap),
                trace_fn: trace_impl::<T>,
                drop_fn: drop_impl::<T>,
                payload_fn: payload_impl::<T>,
                size: std::mem::size_of::<GcBox<T>>(),
                align: std::mem::align_of::<GcBox<T>>(),
            },
            value: UnsafeCell::new(Some(value)),
        });
        // SAFETY: `Box::into_raw` never returns null.
        let ptr = unsafe { NonNull::new_unchecked(Box::into_raw(boxed)) };
        let gc = Gc { ptr };
        heap.register(gc.header());
        if heap.live_count() > heap.threshold() {
            heap.collect();
        }
        gc
    }

    /// The heap this value lives on.
    pub fn heap(&self) -> &Heap {
        // SAFETY: the heap outlives the box (documented contract).
        unsafe { self.ptr.as_ref().header.heap.as_ref() }
    }

    /// Number of strong handles (including internal edges).
    pub fn strong_count(&self) -> usize {
        // SAFETY: the handle keeps the box alive.
        unsafe { self.ptr.as_ref().header.strong.get() }
    }

    /// Whether two handles point at the same box.
    pub fn ptr_eq(&self, other: &Gc<T>) -> bool {
        self.ptr == other.ptr
    }

    /// Whether this handle points at the box `other` refers to, expired or not.
    ///
    /// A `WeakMap` stores weak handles but compares against live keys, so the comparison
    /// has to span both handle types without upgrading (which would resurrect the key).
    pub fn upgrades_to(&self, other: &WeakGc<T>) -> bool {
        self.ptr == other.ptr
    }

    /// Create a non-owning handle.
    pub fn downgrade(&self) -> WeakGc<T> {
        // SAFETY: the handle keeps the box alive.
        let header = unsafe { &self.ptr.as_ref().header };
        header.weak.set(header.weak.get() + 1);
        WeakGc { ptr: self.ptr }
    }

    #[inline]
    fn header(&self) -> NonNull<Header> {
        // SAFETY: `Header` is the first field of `GcBox<T>` (`#[repr(C)]`).
        unsafe { NonNull::new_unchecked(self.ptr.as_ptr().cast::<Header>()) }
    }
}

impl<T: Trace + 'static> Clone for Gc<T> {
    fn clone(&self) -> Gc<T> {
        // SAFETY: the handle keeps the box alive.
        let header = unsafe { &self.ptr.as_ref().header };
        header.strong.set(header.strong.get() + 1);
        Gc { ptr: self.ptr }
    }
}

impl<T: Trace + 'static> Drop for Gc<T> {
    fn drop(&mut self) {
        dec_strong(self.header());
    }
}

impl<T: Trace + 'static> Deref for Gc<T> {
    type Target = T;

    fn deref(&self) -> &T {
        // SAFETY: the handle keeps the box and its value alive.
        unsafe {
            (*self.ptr.as_ptr())
                .value
                .get()
                .as_ref()
                .expect("UnsafeCell pointer is never null")
                .as_ref()
                .expect("Gc value accessed after it was dropped")
        }
    }
}

impl<T: Trace + 'static> fmt::Debug for Gc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Gc({:p}, strong={})",
            self.ptr.as_ptr(),
            self.strong_count()
        )
    }
}

impl<T: Trace + 'static> Trace for Gc<T> {
    #[inline]
    fn trace(&self, tracer: &mut Tracer) {
        tracer.visit(self);
    }

    /// What the *pointee* owns, which is counted against the pointee's own box.
    ///
    /// Forwarded so that `gc.external_bytes()` is not a silent zero, but a container must
    /// never add this to its own total: it would count the child's payload twice, once here
    /// and once when the child's box is registered.
    #[inline]
    fn external_bytes(&self) -> usize {
        (**self).external_bytes()
    }
}

/// # Safety
/// `h` must point at a live box.
fn dec_strong(h: NonNull<Header>) {
    // SAFETY: caller guarantees liveness; a handle owns one strong reference.
    let header = unsafe { h.as_ref() };
    let strong = header.strong.get();
    debug_assert!(strong > 0, "Gc strong count underflow");
    header.strong.set(strong - 1);
    if strong == 1 {
        // SAFETY: we just dropped the last reference.
        unsafe { release(h) };
    }
}

/// # Safety
/// `h` must point at a box whose strong count just reached zero.
unsafe fn release(h: NonNull<Header>) {
    // Hold the allocation for the duration of the drop by pretending one strong reference
    // still exists. Dropping the value can release the *last* `WeakGc` that points at this
    // very box — `Owner { weak: WeakGc<Back> }` inside `Back { owner: Gc<Owner> }` is
    // exactly that shape — and `WeakGc::drop` frees a box whose strong count is zero. The
    // header reads below would then touch freed memory.
    //
    // The collector's step 4 already does this (it bumps every dead box before dropping
    // it); this is the same trick on the reference-counting path.
    let header = unsafe { h.as_ref() };
    header.strong.set(1);
    // SAFETY: the value is still there, and the heap outlives its boxes.
    unsafe {
        header.heap.as_ref().release_payload(h);
        (header.drop_fn)(h);
    }
    // SAFETY: the allocation was held above, so the header is still ours.
    let header = unsafe { h.as_ref() };
    // A box without a value is no longer part of the object graph, so the collector must
    // not see it; weak handles may still point at the header.
    // SAFETY: the heap outlives its boxes (documented contract).
    unsafe { header.heap.as_ref() }.deregister(h);
    header.strong.set(0);
    if header.weak.get() == 0 {
        // SAFETY: no strong or weak references remain.
        unsafe { dealloc_box(h) };
    }
}

// ---------------------------------------------------------------------------
// WeakGc
// ---------------------------------------------------------------------------

/// A non-owning handle to a heap value.
///
/// Keeps the box header (but not the value) alive, so [`WeakGc::upgrade`] can
/// tell whether the value is still there. Weak handles are not traced: they do
/// not keep anything alive and they do not take part in cycle detection, which
/// is what `WeakRef`/`WeakMap` need.
pub struct WeakGc<T: Trace + 'static> {
    ptr: NonNull<GcBox<T>>,
}

impl<T: Trace + 'static> WeakGc<T> {
    /// Try to obtain a strong handle.
    pub fn upgrade(&self) -> Option<Gc<T>> {
        // SAFETY: the weak handle keeps the box allocation alive.
        let header = unsafe { &self.ptr.as_ref().header };
        if header.strong.get() == 0 {
            None
        } else {
            header.strong.set(header.strong.get() + 1);
            Some(Gc { ptr: self.ptr })
        }
    }

    /// Whether the value has been released.
    pub fn is_expired(&self) -> bool {
        // SAFETY: the weak handle keeps the box allocation alive.
        unsafe { self.ptr.as_ref() }.header.strong.get() == 0
    }

    /// Whether two handles point at the same box, live or expired.
    ///
    /// This is the key comparison a `WeakMap` needs: two objects are one key exactly when
    /// they are one allocation, and comparing addresses answers that without upgrading —
    /// so an expired entry still compares equal to nothing and can be swept.
    pub fn ptr_eq(&self, other: &WeakGc<T>) -> bool {
        self.ptr == other.ptr
    }
}

impl<T: Trace + 'static> Clone for WeakGc<T> {
    fn clone(&self) -> WeakGc<T> {
        // SAFETY: the weak handle keeps the box allocation alive.
        let header = unsafe { &self.ptr.as_ref().header };
        header.weak.set(header.weak.get() + 1);
        WeakGc { ptr: self.ptr }
    }
}

impl<T: Trace + 'static> Drop for WeakGc<T> {
    fn drop(&mut self) {
        // SAFETY: this weak handle owns one weak reference.
        let header = unsafe { &self.ptr.as_ref().header };
        let weak = header.weak.get();
        debug_assert!(weak > 0, "WeakGc weak count underflow");
        header.weak.set(weak - 1);
        if weak == 1 && header.strong.get() == 0 {
            // SAFETY: the header keeps its address until both counts are zero,
            // and the last reference of either kind just went away.
            let h = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().cast::<Header>()) };
            unsafe { dealloc_box(h) };
        }
    }
}

impl<T: Trace + 'static> fmt::Debug for WeakGc<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "WeakGc({:p}, expired={})",
            self.ptr.as_ptr(),
            self.is_expired()
        )
    }
}

impl<T: Trace + 'static> Trace for WeakGc<T> {
    #[inline]
    fn trace(&self, _tracer: &mut Tracer) {}
}