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
70/// Visitor used by [`Trace`] implementations.
71///
72/// The collector drives this; user code only calls [`Tracer::visit`] (usually
73/// through `#[derive]`-style impls for containers).
74pub struct Tracer<'a> {
75 out: &'a mut Vec<NonNull<Header>>,
76}
77
78impl Tracer<'_> {
79 /// Record that `gc` is owned by the object currently being traced.
80 #[inline]
81 pub fn visit<T: Trace + 'static>(&mut self, gc: &Gc<T>) {
82 self.out.push(gc.header());
83 }
84}
85
86macro_rules! trace_noop {
87 ($($t:ty),* $(,)?) => {$(
88 impl Trace for $t {
89 #[inline]
90 fn trace(&self, _tracer: &mut Tracer) {}
91 }
92 )*};
93}
94
95trace_noop!(
96 (),
97 bool,
98 char,
99 i8,
100 i16,
101 i32,
102 i64,
103 i128,
104 isize,
105 u8,
106 u16,
107 u32,
108 u64,
109 u128,
110 usize,
111 f32,
112 f64,
113 String,
114 &'static str,
115);
116
117impl<T: Trace + ?Sized> Trace for &T {
118 #[inline]
119 fn trace(&self, tracer: &mut Tracer) {
120 (**self).trace(tracer);
121 }
122}
123
124impl<T: Trace + ?Sized> Trace for Box<T> {
125 #[inline]
126 fn trace(&self, tracer: &mut Tracer) {
127 (**self).trace(tracer);
128 }
129}
130
131impl<T: Trace> Trace for Option<T> {
132 #[inline]
133 fn trace(&self, tracer: &mut Tracer) {
134 if let Some(v) = self {
135 v.trace(tracer);
136 }
137 }
138}
139
140impl<T: Trace> Trace for Vec<T> {
141 #[inline]
142 fn trace(&self, tracer: &mut Tracer) {
143 for v in self {
144 v.trace(tracer);
145 }
146 }
147}
148
149impl<T: Trace, const N: usize> Trace for [T; N] {
150 #[inline]
151 fn trace(&self, tracer: &mut Tracer) {
152 for v in self {
153 v.trace(tracer);
154 }
155 }
156}
157
158impl<T: Trace, U: Trace> Trace for (T, U) {
159 #[inline]
160 fn trace(&self, tracer: &mut Tracer) {
161 self.0.trace(tracer);
162 self.1.trace(tracer);
163 }
164}
165
166impl<T: Trace> Trace for std::rc::Rc<T> {
167 #[inline]
168 fn trace(&self, tracer: &mut Tracer) {
169 (**self).trace(tracer);
170 }
171}
172
173impl<T: Trace> Trace for RefCell<T> {
174 #[inline]
175 fn trace(&self, tracer: &mut Tracer) {
176 // A cell that is mutably borrowed while the collector runs would make
177 // tracing panic; skipping the edge is the safe degradation (worst case:
178 // we fail to reclaim a cycle, never a use-after-free).
179 if let Ok(v) = self.try_borrow() {
180 v.trace(tracer);
181 }
182 }
183}
184
185impl<T: Trace> Trace for Cell<T>
186where
187 T: Copy,
188{
189 #[inline]
190 fn trace(&self, tracer: &mut Tracer) {
191 self.get().trace(tracer);
192 }
193}
194
195// ---------------------------------------------------------------------------
196// Header / box
197// ---------------------------------------------------------------------------
198
199/// Type-erased box header. Every `GcBox<T>` starts with one, so a
200/// `NonNull<Header>` can identify, trace and free any box without knowing `T`.
201struct Header {
202 strong: Cell<usize>,
203 weak: Cell<usize>,
204 /// Scratch space for the collector: `strong` minus internal edges.
205 gc_refs: Cell<isize>,
206 marked: Cell<bool>,
207 /// Index into [`Heap::boxes`], `usize::MAX` when not registered.
208 slot: Cell<usize>,
209 heap: NonNull<Heap>,
210 trace_fn: unsafe fn(NonNull<Header>, &mut Tracer),
211 drop_fn: unsafe fn(NonNull<Header>),
212 size: usize,
213 align: usize,
214}
215
216#[repr(C)]
217struct GcBox<T: Trace + 'static> {
218 header: Header,
219 value: UnsafeCell<Option<T>>,
220}
221
222unsafe fn trace_impl<T: Trace + 'static>(h: NonNull<Header>, tracer: &mut Tracer) {
223 let b = h.cast::<GcBox<T>>();
224 // SAFETY: `h` came from a `GcBox<T>` allocation and the value is only
225 // mutated by `drop_impl` / construction, never while tracing.
226 let value = unsafe { &*(*b.as_ptr()).value.get() };
227 if let Some(v) = value {
228 v.trace(tracer);
229 }
230}
231
232unsafe fn drop_impl<T: Trace + 'static>(h: NonNull<Header>) {
233 let b = h.cast::<GcBox<T>>();
234 // Take the value out before dropping it so that re-entrant `Gc` releases
235 // (this drop can free other boxes) never observe a borrowed cell.
236 // SAFETY: `h` came from a `GcBox<T>` allocation; the value is dropped once.
237 let taken = unsafe { (*b.as_ptr()).value.get().as_mut() }.and_then(Option::take);
238 drop(taken);
239}
240
241// ---------------------------------------------------------------------------
242// Heap
243// ---------------------------------------------------------------------------
244
245/// Statistics returned by [`Heap::collect`].
246#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
247pub struct CollectStats {
248 /// Boxes registered before the collection.
249 pub before: usize,
250 /// Boxes reclaimed by this collection.
251 pub collected: usize,
252 /// Boxes still alive afterwards.
253 pub after: usize,
254 /// Collection passes performed (always 1 today; kept for API stability).
255 pub passes: usize,
256}
257
258/// Owns the live-object registry for one JavaScript runtime.
259pub struct Heap {
260 boxes: RefCell<Vec<Option<NonNull<Header>>>>,
261 free_slots: RefCell<Vec<usize>>,
262 live: Cell<usize>,
263 allocated: Cell<usize>,
264 threshold: Cell<usize>,
265}
266
267impl Default for Heap {
268 fn default() -> Self {
269 Self::new()
270 }
271}
272
273impl Heap {
274 /// Create an empty heap. Runs the collector only when asked
275 /// (see [`Heap::set_threshold`]).
276 pub fn new() -> Heap {
277 Heap {
278 boxes: RefCell::new(Vec::new()),
279 free_slots: RefCell::new(Vec::new()),
280 live: Cell::new(0),
281 allocated: Cell::new(0),
282 threshold: Cell::new(usize::MAX),
283 }
284 }
285
286 /// Trigger a collection automatically when more than `n` boxes are live.
287 /// `usize::MAX` disables automatic collection (the default).
288 pub fn set_threshold(&self, n: usize) {
289 self.threshold.set(n);
290 }
291
292 /// Current automatic-collection threshold.
293 pub fn threshold(&self) -> usize {
294 self.threshold.get()
295 }
296
297 /// Number of live boxes.
298 pub fn live_count(&self) -> usize {
299 self.live.get()
300 }
301
302 /// Approximate number of bytes held by live boxes (excluding external
303 /// allocations made by the values themselves).
304 pub fn allocated_bytes(&self) -> usize {
305 self.allocated.get()
306 }
307
308 fn register(&self, h: NonNull<Header>) {
309 let mut boxes = self.boxes.borrow_mut();
310 let slot = match self.free_slots.borrow_mut().pop() {
311 Some(slot) => {
312 boxes[slot] = Some(h);
313 slot
314 }
315 None => {
316 boxes.push(Some(h));
317 boxes.len() - 1
318 }
319 };
320 // SAFETY: `h` points at a live box we just allocated.
321 let header = unsafe { h.as_ref() };
322 header.slot.set(slot);
323 self.live.set(self.live.get() + 1);
324 self.allocated.set(self.allocated.get() + header.size);
325 }
326
327 fn deregister(&self, h: NonNull<Header>) {
328 // SAFETY: `h` points at a live box (we are on its release path).
329 let header = unsafe { h.as_ref() };
330 let slot = header.slot.get();
331 if slot == usize::MAX {
332 return;
333 }
334 header.slot.set(usize::MAX);
335 {
336 let mut boxes = self.boxes.borrow_mut();
337 boxes[slot] = None;
338 }
339 self.free_slots.borrow_mut().push(slot);
340 self.live.set(self.live.get() - 1);
341 self.allocated.set(self.allocated.get() - header.size);
342 }
343
344 /// Run the cycle collector.
345 ///
346 /// Objects that are only reachable from garbage are dropped and freed;
347 /// everything reachable from a handle living outside the heap survives.
348 pub fn collect(&self) -> CollectStats {
349 let snapshot: Vec<NonNull<Header>> =
350 self.boxes.borrow().iter().flatten().copied().collect();
351 let before = snapshot.len();
352 if before == 0 {
353 return CollectStats {
354 before: 0,
355 collected: 0,
356 after: 0,
357 passes: 1,
358 };
359 }
360
361 // 1. gc_refs = strong.
362 for &h in &snapshot {
363 // SAFETY: every pointer in the snapshot came from a registered box
364 // that cannot be freed while we hold no handles to it... see note
365 // below: no user code runs between snapshot and marking, and boxes
366 // are only freed once their strong count reaches zero, which cannot
367 // happen without user code.
368 let header = unsafe { h.as_ref() };
369 header.gc_refs.set(header.strong.get() as isize);
370 header.marked.set(false);
371 }
372
373 // 2. Subtract internal edges.
374 let mut buf: Vec<NonNull<Header>> = Vec::new();
375 for &h in &snapshot {
376 buf.clear();
377 // SAFETY: see above; `trace` is a pure read of the graph.
378 unsafe { trace_children(h, &mut buf) };
379 for &child in &buf {
380 // SAFETY: children are live boxes (they are referenced by a
381 // live box, so their strong count is >= 1).
382 let child = unsafe { child.as_ref() };
383 child.gc_refs.set(child.gc_refs.get() - 1);
384 }
385 }
386
387 // 3. Mark from roots (`gc_refs > 0` == referenced from outside the heap).
388 let mut stack: Vec<NonNull<Header>> = Vec::new();
389 for &h in &snapshot {
390 // SAFETY: see above.
391 let header = unsafe { h.as_ref() };
392 if header.gc_refs.get() > 0 && !header.marked.get() {
393 header.marked.set(true);
394 stack.push(h);
395 }
396 }
397 while let Some(h) = stack.pop() {
398 buf.clear();
399 // SAFETY: see above.
400 unsafe { trace_children(h, &mut buf) };
401 for &child in &buf {
402 // SAFETY: see above.
403 let header = unsafe { child.as_ref() };
404 if !header.marked.get() {
405 header.marked.set(true);
406 stack.push(child);
407 }
408 }
409 }
410
411 // 4. Drop the unmarked boxes. Bump every one of them first so that
412 // releasing handles inside them cannot free a box we are still
413 // iterating over.
414 let dead: Vec<NonNull<Header>> = snapshot
415 .iter()
416 .copied()
417 .filter(|h| {
418 // SAFETY: see above.
419 !unsafe { h.as_ref() }.marked.get()
420 })
421 .collect();
422
423 for &h in &dead {
424 // SAFETY: see above.
425 let header = unsafe { h.as_ref() };
426 header.strong.set(header.strong.get() + 1);
427 }
428 for &h in &dead {
429 // SAFETY: `drop_fn` only touches this box's own value.
430 unsafe { (h.as_ref().drop_fn)(h) };
431 // The value is gone, so the object left the object graph; do it now
432 // so that a (later) collection never sees a value-less box.
433 self.deregister(h);
434 }
435 for &h in &dead {
436 // SAFETY: see above.
437 let header = unsafe { h.as_ref() };
438 let strong = header.strong.get();
439 header.strong.set(strong - 1);
440 if strong == 1 && header.weak.get() == 0 {
441 // SAFETY: no strong or weak references remain.
442 unsafe { dealloc_box(h) };
443 }
444 }
445
446 let after = self.live_count();
447 CollectStats {
448 before,
449 collected: before - after,
450 after,
451 passes: 1,
452 }
453 }
454}
455
456/// # Safety
457/// `h` must point at a live box.
458unsafe fn trace_children(h: NonNull<Header>, out: &mut Vec<NonNull<Header>>) {
459 // SAFETY: caller guarantees `h` is live; `trace_fn` only reads the value.
460 let trace_fn = unsafe { h.as_ref().trace_fn };
461 let mut tracer = Tracer { out };
462 // SAFETY: as above.
463 unsafe { trace_fn(h, &mut tracer) };
464}
465
466/// # Safety
467/// `h` must point at a box that has already been deregistered and whose strong
468/// and weak counts both reached zero.
469unsafe fn dealloc_box(h: NonNull<Header>) {
470 // SAFETY: caller guarantees the header is still allocated.
471 let (size, align) = {
472 let header = unsafe { h.as_ref() };
473 (header.size, header.align)
474 };
475 // SAFETY: the allocation was made with this exact layout.
476 unsafe {
477 dealloc(
478 h.as_ptr() as *mut u8,
479 Layout::from_size_align_unchecked(size, align),
480 )
481 };
482}
483
484// ---------------------------------------------------------------------------
485// Gc
486// ---------------------------------------------------------------------------
487
488/// A strong, reference-counted handle to a heap value.
489///
490/// `Gc<T>` is a pointer-sized handle: cloning is cheap, [`Deref`] gives `&T`,
491/// and the value is released as soon as the last handle is gone (cycles need
492/// [`Heap::collect`]).
493pub struct Gc<T: Trace + 'static> {
494 ptr: NonNull<GcBox<T>>,
495}
496
497impl<T: Trace + 'static> Gc<T> {
498 /// Allocate `value` on `heap` and return a handle to it.
499 pub fn new(heap: &Heap, value: T) -> Gc<T> {
500 let boxed = Box::new(GcBox {
501 header: Header {
502 strong: Cell::new(1),
503 weak: Cell::new(0),
504 gc_refs: Cell::new(1),
505 marked: Cell::new(false),
506 slot: Cell::new(usize::MAX),
507 heap: NonNull::from(heap),
508 trace_fn: trace_impl::<T>,
509 drop_fn: drop_impl::<T>,
510 size: std::mem::size_of::<GcBox<T>>(),
511 align: std::mem::align_of::<GcBox<T>>(),
512 },
513 value: UnsafeCell::new(Some(value)),
514 });
515 // SAFETY: `Box::into_raw` never returns null.
516 let ptr = unsafe { NonNull::new_unchecked(Box::into_raw(boxed)) };
517 let gc = Gc { ptr };
518 heap.register(gc.header());
519 if heap.live_count() > heap.threshold() {
520 heap.collect();
521 }
522 gc
523 }
524
525 /// The heap this value lives on.
526 pub fn heap(&self) -> &Heap {
527 // SAFETY: the heap outlives the box (documented contract).
528 unsafe { self.ptr.as_ref().header.heap.as_ref() }
529 }
530
531 /// Number of strong handles (including internal edges).
532 pub fn strong_count(&self) -> usize {
533 // SAFETY: the handle keeps the box alive.
534 unsafe { self.ptr.as_ref().header.strong.get() }
535 }
536
537 /// Whether two handles point at the same box.
538 pub fn ptr_eq(&self, other: &Gc<T>) -> bool {
539 self.ptr == other.ptr
540 }
541
542 /// Create a non-owning handle.
543 pub fn downgrade(&self) -> WeakGc<T> {
544 // SAFETY: the handle keeps the box alive.
545 let header = unsafe { &self.ptr.as_ref().header };
546 header.weak.set(header.weak.get() + 1);
547 WeakGc { ptr: self.ptr }
548 }
549
550 #[inline]
551 fn header(&self) -> NonNull<Header> {
552 // SAFETY: `Header` is the first field of `GcBox<T>` (`#[repr(C)]`).
553 unsafe { NonNull::new_unchecked(self.ptr.as_ptr().cast::<Header>()) }
554 }
555}
556
557impl<T: Trace + 'static> Clone for Gc<T> {
558 fn clone(&self) -> Gc<T> {
559 // SAFETY: the handle keeps the box alive.
560 let header = unsafe { &self.ptr.as_ref().header };
561 header.strong.set(header.strong.get() + 1);
562 Gc { ptr: self.ptr }
563 }
564}
565
566impl<T: Trace + 'static> Drop for Gc<T> {
567 fn drop(&mut self) {
568 dec_strong(self.header());
569 }
570}
571
572impl<T: Trace + 'static> Deref for Gc<T> {
573 type Target = T;
574
575 fn deref(&self) -> &T {
576 // SAFETY: the handle keeps the box and its value alive.
577 unsafe {
578 (*self.ptr.as_ptr())
579 .value
580 .get()
581 .as_ref()
582 .expect("UnsafeCell pointer is never null")
583 .as_ref()
584 .expect("Gc value accessed after it was dropped")
585 }
586 }
587}
588
589impl<T: Trace + 'static> fmt::Debug for Gc<T> {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 write!(
592 f,
593 "Gc({:p}, strong={})",
594 self.ptr.as_ptr(),
595 self.strong_count()
596 )
597 }
598}
599
600impl<T: Trace + 'static> Trace for Gc<T> {
601 #[inline]
602 fn trace(&self, tracer: &mut Tracer) {
603 tracer.visit(self);
604 }
605}
606
607/// # Safety
608/// `h` must point at a live box.
609fn dec_strong(h: NonNull<Header>) {
610 // SAFETY: caller guarantees liveness; a handle owns one strong reference.
611 let header = unsafe { h.as_ref() };
612 let strong = header.strong.get();
613 debug_assert!(strong > 0, "Gc strong count underflow");
614 header.strong.set(strong - 1);
615 if strong == 1 {
616 // SAFETY: we just dropped the last reference.
617 unsafe { release(h) };
618 }
619}
620
621/// # Safety
622/// `h` must point at a box whose strong count just reached zero.
623unsafe fn release(h: NonNull<Header>) {
624 // SAFETY: caller guarantees the strong count is zero; dropping the value may
625 // free other boxes but never this one (we still own its allocation).
626 unsafe { (h.as_ref().drop_fn)(h) };
627 // SAFETY: header is still valid (the allocation is ours until we free it).
628 let header = unsafe { h.as_ref() };
629 // A box without a value is no longer part of the object graph, so the
630 // collector must not see it; weak handles may still point at the header.
631 // SAFETY: the heap outlives its boxes (documented contract).
632 unsafe { header.heap.as_ref() }.deregister(h);
633 if header.weak.get() == 0 {
634 // SAFETY: no strong or weak references remain.
635 unsafe { dealloc_box(h) };
636 }
637}
638
639// ---------------------------------------------------------------------------
640// WeakGc
641// ---------------------------------------------------------------------------
642
643/// A non-owning handle to a heap value.
644///
645/// Keeps the box header (but not the value) alive, so [`WeakGc::upgrade`] can
646/// tell whether the value is still there. Weak handles are not traced: they do
647/// not keep anything alive and they do not take part in cycle detection, which
648/// is what `WeakRef`/`WeakMap` need.
649pub struct WeakGc<T: Trace + 'static> {
650 ptr: NonNull<GcBox<T>>,
651}
652
653impl<T: Trace + 'static> WeakGc<T> {
654 /// Try to obtain a strong handle.
655 pub fn upgrade(&self) -> Option<Gc<T>> {
656 // SAFETY: the weak handle keeps the box allocation alive.
657 let header = unsafe { &self.ptr.as_ref().header };
658 if header.strong.get() == 0 {
659 None
660 } else {
661 header.strong.set(header.strong.get() + 1);
662 Some(Gc { ptr: self.ptr })
663 }
664 }
665
666 /// Whether the value has been released.
667 pub fn is_expired(&self) -> bool {
668 // SAFETY: the weak handle keeps the box allocation alive.
669 unsafe { self.ptr.as_ref() }.header.strong.get() == 0
670 }
671}
672
673impl<T: Trace + 'static> Clone for WeakGc<T> {
674 fn clone(&self) -> WeakGc<T> {
675 // SAFETY: the weak handle keeps the box allocation alive.
676 let header = unsafe { &self.ptr.as_ref().header };
677 header.weak.set(header.weak.get() + 1);
678 WeakGc { ptr: self.ptr }
679 }
680}
681
682impl<T: Trace + 'static> Drop for WeakGc<T> {
683 fn drop(&mut self) {
684 // SAFETY: this weak handle owns one weak reference.
685 let header = unsafe { &self.ptr.as_ref().header };
686 let weak = header.weak.get();
687 debug_assert!(weak > 0, "WeakGc weak count underflow");
688 header.weak.set(weak - 1);
689 if weak == 1 && header.strong.get() == 0 {
690 // SAFETY: the header keeps its address until both counts are zero,
691 // and the last reference of either kind just went away.
692 let h = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().cast::<Header>()) };
693 unsafe { dealloc_box(h) };
694 }
695 }
696}
697
698impl<T: Trace + 'static> fmt::Debug for WeakGc<T> {
699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700 write!(
701 f,
702 "WeakGc({:p}, expired={})",
703 self.ptr.as_ptr(),
704 self.is_expired()
705 )
706 }
707}
708
709impl<T: Trace + 'static> Trace for WeakGc<T> {
710 #[inline]
711 fn trace(&self, _tracer: &mut Tracer) {}
712}