Skip to main content

cljrs_runtime/env/
gc_roots.rs

1#[cfg(not(feature = "no-gc"))]
2use crate::env::dynamics;
3use crate::env::env::Env;
4use crate::env::env::GlobalEnv;
5use crate::env::error::{EvalError, EvalResult};
6use std::cell::RefCell;
7
8// ── Stop-the-world reclaim hooks (JIT code unloading, cold-IR sweep) ────────
9//
10// Reclamation of execution-engine caches runs only at a stop-the-world
11// safepoint, when every mutator thread is parked and active JIT frames can be
12// scanned safely.  GC collection is the existing STW point, so interested
13// tiers install hooks here that run at the tail of every collection while the
14// STW guard is still held.  Current registrants: the compiler's JIT code cache
15// (`cljrs_compiler::jit::code_cache`, superseded native modules) and this
16// crate's lowering worker (idle Tier-1 IR, Phase 10.7).
17
18type StwReclaimHook = Box<dyn Fn() + Send + Sync + 'static>;
19static STW_RECLAIM_HOOKS: std::sync::RwLock<Vec<StwReclaimHook>> =
20    std::sync::RwLock::new(Vec::new());
21
22/// Register a stop-the-world reclaim hook.  Multiple hooks may be registered;
23/// each runs at every STW point, in registration order.
24///
25/// Hooks run inside the STW guard after each collection, so they may assume
26/// all other mutator threads are parked.
27pub fn set_stw_reclaim_hook(f: impl Fn() + Send + Sync + 'static) {
28    STW_RECLAIM_HOOKS.write().unwrap().push(Box::new(f));
29}
30
31/// Run the STW reclaim hooks, if any.  Caller must hold the STW guard.
32#[cfg(not(feature = "no-gc"))]
33fn run_stw_reclaim() {
34    for hook in STW_RECLAIM_HOOKS.read().unwrap().iter() {
35        hook();
36    }
37}
38
39// ── Thread-local Env root registry ──────────────────────────────────────────
40//
41// When the interpreter enters a function call, the caller's Env stays on the
42// Rust stack but the callee creates a fresh Env.  If GC triggers inside the
43// callee, only the callee's Env is passed to `gc_safepoint`.  To keep the
44// caller's local bindings alive we maintain a thread-local stack of pointers
45// to all active Envs on this thread's call stack.
46//
47// SAFETY: the raw pointers are valid during STW collection because:
48// - The collecting thread's own Envs are in earlier (still-live) stack frames.
49// - Other threads are parked at safepoints; their stacks (and Envs) are frozen.
50
51thread_local! {
52    static ENV_ROOTS: RefCell<Vec<*const Env>> = const { RefCell::new(Vec::new()) };
53    /// Shadow stack of Value pointers on the Rust call stack that need to
54    /// survive GC.  Each entry is a `(ptr, count)` pair pointing to a
55    /// contiguous slice of Values (e.g., a Vec's backing storage or a single
56    /// Value on the stack).
57    static VALUE_ROOTS: RefCell<Vec<(*const cljrs_value::Value, usize)>> =
58        const { RefCell::new(Vec::new()) };
59    /// Shadow stack for `Option<Value>` slices (e.g., the IR interpreter's
60    /// register file).  Each entry is `(ptr, count)` pointing to a fixed-size
61    /// heap slice whose address will not change for the lifetime of the entry.
62    static OPTION_VALUE_ROOTS: RefCell<Vec<(*const Option<cljrs_value::Value>, usize)>> =
63        const { RefCell::new(Vec::new()) };
64}
65cljrs_gc::mutator_slot!("cljrs-runtime/ENV_ROOTS", refcell ENV_ROOTS: Vec<*const Env>, trace trace_saved_envs);
66cljrs_gc::mutator_slot!("cljrs-runtime/VALUE_ROOTS", refcell VALUE_ROOTS: Vec<(*const cljrs_value::Value, usize)>, trace trace_saved_values);
67cljrs_gc::mutator_slot!(
68    "cljrs-runtime/OPTION_VALUE_ROOTS",
69    refcell OPTION_VALUE_ROOTS: Vec<(*const Option<cljrs_value::Value>, usize)>, trace trace_saved_options
70);
71
72// SAFETY: detached states are traced only while the owning fiber's stack
73// remains allocated. Root guards are removed during unwind before stack reuse.
74fn trace_saved_envs(roots: &Vec<*const Env>, visitor: &mut cljrs_gc::MarkVisitor) {
75    for &env in roots {
76        trace_env_roots(unsafe { &*env }, visitor);
77    }
78}
79fn trace_saved_values(
80    roots: &Vec<(*const cljrs_value::Value, usize)>,
81    visitor: &mut cljrs_gc::MarkVisitor,
82) {
83    use cljrs_gc::Trace;
84    for &(ptr, len) in roots {
85        for value in unsafe { std::slice::from_raw_parts(ptr, len) } {
86            value.trace(visitor);
87        }
88    }
89}
90fn trace_saved_options(
91    roots: &Vec<(*const Option<cljrs_value::Value>, usize)>,
92    visitor: &mut cljrs_gc::MarkVisitor,
93) {
94    use cljrs_gc::Trace;
95    for &(ptr, len) in roots {
96        for value in unsafe { std::slice::from_raw_parts(ptr, len) }
97            .iter()
98            .flatten()
99        {
100            value.trace(visitor);
101        }
102    }
103}
104
105/// RAII guard that pops the Env pointer on drop.
106pub struct EnvRootGuard;
107
108impl Drop for EnvRootGuard {
109    fn drop(&mut self) {
110        ENV_ROOTS.with(|roots| {
111            roots.borrow_mut().pop();
112        });
113    }
114}
115
116/// RAII guard that removes its own entry from the value shadow stack on drop.
117///
118/// The entry is removed by identity rather than popped: async tasks on one
119/// `LocalSet` share this thread's stack and can hold guards across `await`s,
120/// so guards need not drop in LIFO order.
121pub struct ValueRootGuard {
122    entry: Option<(*const cljrs_value::Value, usize)>,
123}
124
125impl Drop for ValueRootGuard {
126    fn drop(&mut self) {
127        if let Some(entry) = self.entry {
128            VALUE_ROOTS.with(|roots| {
129                let mut roots = roots.borrow_mut();
130                if let Some(i) = roots.iter().rposition(|e| *e == entry) {
131                    roots.remove(i);
132                }
133            });
134        }
135    }
136}
137
138/// Register an Env as a GC root for the duration of its use.
139/// Returns a guard that unregisters on drop.
140pub fn push_env_root(env: &Env) -> EnvRootGuard {
141    ENV_ROOTS.with(|roots| {
142        roots.borrow_mut().push(env as *const Env);
143    });
144    EnvRootGuard
145}
146
147/// Register a single Value as a GC root.
148pub fn root_value(val: &cljrs_value::Value) -> ValueRootGuard {
149    let entry = (val as *const cljrs_value::Value, 1);
150    VALUE_ROOTS.with(|roots| roots.borrow_mut().push(entry));
151    ValueRootGuard { entry: Some(entry) }
152}
153
154/// Register a slice of Values as GC roots (e.g., a Vec<Value>).
155pub fn root_values(vals: &[cljrs_value::Value]) -> ValueRootGuard {
156    if vals.is_empty() {
157        return ValueRootGuard { entry: None };
158    }
159    let entry = (vals.as_ptr(), vals.len());
160    VALUE_ROOTS.with(|roots| roots.borrow_mut().push(entry));
161    ValueRootGuard { entry: Some(entry) }
162}
163
164/// RAII guard that pops one entry from the option-value shadow stack on drop.
165pub struct OptionValueRootGuard {
166    pushed: bool,
167}
168
169impl Drop for OptionValueRootGuard {
170    fn drop(&mut self) {
171        if self.pushed {
172            OPTION_VALUE_ROOTS.with(|roots| {
173                roots.borrow_mut().pop();
174            });
175        }
176    }
177}
178
179/// Register a slice of `Option<Value>` as GC roots.
180///
181/// The caller **must** ensure the slice's heap address is stable for the
182/// lifetime of the returned guard — use `Box<[Option<Value>]>` rather than
183/// a `Vec` that could reallocate.
184pub fn root_option_values(vals: &[Option<cljrs_value::Value>]) -> OptionValueRootGuard {
185    if vals.is_empty() {
186        return OptionValueRootGuard { pushed: false };
187    }
188    OPTION_VALUE_ROOTS.with(|roots| {
189        roots.borrow_mut().push((vals.as_ptr(), vals.len()));
190    });
191    OptionValueRootGuard { pushed: true }
192}
193
194/// Force an immediate GC collection, bypassing the memory-pressure threshold.
195///
196/// Unlike `gc_safepoint`, this always initiates collection regardless of
197/// `gc_requested()`. Use this after removing namespaces from globals to ensure
198/// their closures and form-trees are freed before the next namespace is loaded.
199///
200/// Under `no-gc` this is a no-op.
201#[cfg(feature = "no-gc")]
202pub fn force_collect(_env: &Env) {}
203
204#[cfg(not(feature = "no-gc"))]
205pub fn force_collect(env: &Env) {
206    let Some(_stw_guard) = cljrs_gc::begin_stw() else {
207        // Another thread is already collecting — just wait for it.
208        cljrs_gc::safepoint();
209        return;
210    };
211
212    cljrs_gc::HEAP.collect(|visitor| {
213        cljrs_gc::HEAP.trace_registered_roots(visitor);
214        trace_env_roots(env, visitor);
215        trace_thread_env_roots(visitor);
216        trace_value_roots(visitor);
217        trace_option_value_roots(visitor);
218        dynamics::trace_current(visitor);
219        crate::env::monitor::trace_current(visitor);
220        cljrs_value::collections::trace_snapshots(visitor);
221        crate::env::taps::trace_roots(visitor);
222        cljrs_gc::trace_thread_alloc_roots(visitor);
223    });
224    // Reclaim superseded JIT code while the world is still stopped.
225    run_stw_reclaim();
226}
227
228/// Interpreter-level GC safepoint.
229///
230/// Under GC mode it either parks (if collection is in progress) or initiates
231/// a collection (if memory pressure was signalled).  Then, in both modes, it
232/// resolves a pending memory fault: an allocation that strict admission
233/// refused but that could not fail (`GcPtr::new`).  The fault is dropped if
234/// committed memory is back within the hard limit and returned as
235/// [`EvalError::MemoryLimitExceeded`] otherwise.  Under `no-gc` there is no
236/// collection; region scopes release their memory as they exit.
237#[cfg(feature = "no-gc")]
238pub fn gc_safepoint(_env: &Env) -> EvalResult<()> {
239    check_memory_fault()
240}
241
242#[cfg(not(feature = "no-gc"))]
243pub fn gc_safepoint(env: &Env) -> EvalResult<()> {
244    // Fast path: no GC activity and no pending fault.
245    if !cljrs_gc::governor::runtime_fault_possible()
246        && !cljrs_gc::gc_requested()
247        && !cljrs_gc::CONFIG_CANCELLATION.in_progress()
248    {
249        return Ok(());
250    }
251    collect_at_safepoint(env);
252    check_memory_fault()
253}
254
255/// Turn the thread's pending memory fault, if it survives
256/// [`cljrs_gc::resolve_runtime_fault`], into an evaluation error.
257pub fn check_memory_fault() -> EvalResult<()> {
258    match cljrs_gc::resolve_runtime_fault() {
259        Some(fault) => Err(EvalError::MemoryLimitExceeded(fault)),
260        None => Ok(()),
261    }
262}
263
264#[cfg(not(feature = "no-gc"))]
265fn collect_at_safepoint(env: &Env) {
266    if !cljrs_gc::gc_requested() && !cljrs_gc::CONFIG_CANCELLATION.in_progress() {
267        return;
268    }
269
270    // If a GC is already in progress (another thread is collecting), just park.
271    if cljrs_gc::CONFIG_CANCELLATION.in_progress() {
272        cljrs_gc::safepoint();
273        return;
274    }
275
276    // A GC was requested (memory pressure). Try to become the collector.
277    if !cljrs_gc::take_gc_request() {
278        // Another thread took the request; if collection started, park.
279        cljrs_gc::safepoint();
280        return;
281    }
282
283    // We won the request. Initiate STW collection.
284    let Some(_stw_guard) = cljrs_gc::begin_stw() else {
285        // Race: another thread started collecting between our take and begin.
286        cljrs_gc::safepoint();
287        return;
288    };
289
290    // All other threads are now parked. Collect with registered roots
291    // plus ALL of this thread's active environments and dynamic bindings.
292    cljrs_gc::HEAP.collect(|visitor| {
293        // Trace globally registered roots (GlobalEnv, etc.)
294        cljrs_gc::HEAP.trace_registered_roots(visitor);
295        // Trace the current (innermost) env
296        trace_env_roots(env, visitor);
297        // Trace all caller Envs registered on this thread's stack
298        trace_thread_env_roots(visitor);
299        // Trace values on the Rust call stack (shadow stack)
300        trace_value_roots(visitor);
301        // Trace Option<Value> slices (e.g. IR interpreter register files)
302        trace_option_value_roots(visitor);
303        // Trace dynamic variable bindings on this thread
304        dynamics::trace_current(visitor);
305        crate::env::monitor::trace_current(visitor);
306        cljrs_value::collections::trace_snapshots(visitor);
307        // Trace the global tap system (functions and queued values)
308        crate::env::taps::trace_roots(visitor);
309        // Trace in-flight allocations from this thread's alloc root frames
310        cljrs_gc::trace_thread_alloc_roots(visitor);
311    });
312    // Reclaim superseded JIT code while the world is still stopped.
313    run_stw_reclaim();
314    // _stw_guard drop clears in_progress, waking parked threads.
315}
316
317// ── GC-only root tracing helpers ─────────────────────────────────────────────
318
319/// Trace all GcPtr values reachable from an Env's local frames.
320fn trace_env_roots(env: &Env, visitor: &mut cljrs_gc::MarkVisitor) {
321    use cljrs_gc::Trace;
322    // Trace local frame bindings
323    for frame in &env.frames {
324        for (_name, val) in &frame.bindings {
325            val.trace(visitor);
326        }
327    }
328    // Trace the globals (namespaces, vars) — these are also registered
329    // as root tracers, but it's safe to trace twice (idempotent marking).
330    trace_globals(&env.globals, visitor);
331}
332
333/// Trace all Values registered in the thread-local value shadow stack.
334#[cfg(not(feature = "no-gc"))]
335fn trace_value_roots(visitor: &mut cljrs_gc::MarkVisitor) {
336    use cljrs_gc::Trace;
337    VALUE_ROOTS.with(|roots| {
338        for &(ptr, count) in roots.borrow().iter() {
339            // SAFETY: pointers are valid — they point to Values on this thread's
340            // still-live stack frames or heap-allocated Vecs whose owners are
341            // on still-live stack frames.
342            let slice = unsafe { std::slice::from_raw_parts(ptr, count) };
343            for val in slice {
344                val.trace(visitor);
345            }
346        }
347    });
348}
349
350/// Trace all Option<Value> slices registered in the thread-local shadow stack.
351///
352/// Used for the IR interpreter's register file (a `Box<[Option<Value>]>`).
353#[cfg(not(feature = "no-gc"))]
354fn trace_option_value_roots(visitor: &mut cljrs_gc::MarkVisitor) {
355    use cljrs_gc::Trace;
356    OPTION_VALUE_ROOTS.with(|roots| {
357        for &(ptr, count) in roots.borrow().iter() {
358            // SAFETY: the slice is a Box<[Option<Value>]> owned by an active
359            // stack frame; the address is stable for the guard's lifetime.
360            let slice = unsafe { std::slice::from_raw_parts(ptr, count) };
361            for val in slice.iter().flatten() {
362                val.trace(visitor);
363            }
364        }
365    });
366}
367
368/// Trace all Envs registered in the thread-local root stack.
369#[cfg(not(feature = "no-gc"))]
370fn trace_thread_env_roots(visitor: &mut cljrs_gc::MarkVisitor) {
371    use cljrs_gc::Trace;
372    ENV_ROOTS.with(|roots| {
373        for env_ptr in roots.borrow().iter() {
374            // SAFETY: pointers are valid — they point to Envs on this thread's
375            // still-live stack frames (we are the collector, so our stack is active).
376            let env = unsafe { &**env_ptr };
377            for frame in &env.frames {
378                for (_name, val) in &frame.bindings {
379                    val.trace(visitor);
380                }
381            }
382        }
383    });
384}
385
386/// Trace all namespaces and their contents.
387pub(crate) fn trace_globals(globals: &GlobalEnv, visitor: &mut cljrs_gc::MarkVisitor) {
388    use cljrs_gc::{GcVisitor as _, Trace};
389    let namespaces = globals.namespaces.read().unwrap();
390    for ns_ptr in namespaces.values() {
391        visitor.visit(ns_ptr);
392    }
393    drop(namespaces);
394    // Values resolved at a pinned commit may live only in the version cache
395    // (e.g. native HEAD fallbacks) — without this they would be collected.
396    let version_cache = globals.version_cache.lock().unwrap();
397    for val in version_cache.values() {
398        val.trace(visitor);
399    }
400}
401
402/// Service a pending GC request from an async (LocalSet) context.
403///
404/// Safe to call from within a Tokio `LocalSet` task at any cooperative yield
405/// point: when this executes, no other tasks are polling, so thread-local root
406/// stacks (ENV_ROOTS, VALUE_ROOTS, ALLOC_ROOTS) fully describe all GcPtrs held
407/// by suspended tasks and can be scanned safely.
408///
409/// Under `no-gc` this is a no-op.
410#[cfg(feature = "no-gc")]
411pub fn async_gc_collect() {}
412
413#[cfg(not(feature = "no-gc"))]
414pub fn async_gc_collect() {
415    if !cljrs_gc::gc_requested() && !cljrs_gc::CONFIG_CANCELLATION.in_progress() {
416        return;
417    }
418    if cljrs_gc::CONFIG_CANCELLATION.in_progress() {
419        cljrs_gc::safepoint();
420        return;
421    }
422    if !cljrs_gc::take_gc_request() {
423        cljrs_gc::safepoint();
424        return;
425    }
426    let Some(_stw_guard) = cljrs_gc::begin_stw() else {
427        cljrs_gc::safepoint();
428        return;
429    };
430    cljrs_gc::HEAP.collect(|visitor| {
431        cljrs_gc::HEAP.trace_registered_roots(visitor);
432        trace_thread_env_roots(visitor);
433        trace_value_roots(visitor);
434        trace_option_value_roots(visitor);
435        dynamics::trace_current(visitor);
436        crate::env::monitor::trace_current(visitor);
437        cljrs_value::collections::trace_snapshots(visitor);
438        crate::env::taps::trace_roots(visitor);
439        cljrs_gc::trace_thread_alloc_roots(visitor);
440    });
441    // Reclaim superseded JIT code while the world is still stopped.
442    run_stw_reclaim();
443}