Skip to main content

canic_memory/runtime/
mod.rs

1pub mod registry;
2
3use std::cell::{Cell, RefCell};
4
5// -----------------------------------------------------------------------------
6// CANIC_EAGER_TLS
7// -----------------------------------------------------------------------------
8// Internal registry of "TLS touch" functions.
9//
10// Each function must be a plain `fn()` pointer (not a closure). When invoked,
11// the function must perform a `.with(|_| {})` on a thread_local! static.
12// This guarantees that the TLS slot is *initialized eagerly*, not lazily, so
13// stable memory pages or other backing buffers are allocated in a deterministic
14// order before any canister entry points are executed.
15//
16// These functions are registered by the `eager_static!` macro via
17// `defer_tls_initializer()`, and run once during process startup by
18// `init_eager_tls()`.
19// -----------------------------------------------------------------------------
20
21thread_local! {
22    static CANIC_EAGER_TLS: RefCell<Vec<fn()>> = const {
23        RefCell::new(Vec::new())
24    };
25    static CANIC_EAGER_TLS_RUNNING: Cell<bool> = const { Cell::new(false) };
26}
27
28/// Run all deferred TLS initializers and clear the registry.
29///
30/// This drains the internal queue of initializer functions and invokes
31/// each *exactly once*. The use of `std::mem::take` ensures:
32///
33/// - the vector is fully emptied before we run any initializers
34/// - we drop the borrow before calling user code (prevents borrow panics)
35/// - functions cannot be re-run accidentally
36/// - reentrant modifications of the queue become visible *after* this call
37///
38/// This should be invoked before any IC canister lifecycle hooks (init, update,
39/// heartbeat, etc.) so that thread-local caches are in a fully-initialized state
40/// before the canister performs memory-dependent work.
41pub fn init_eager_tls() {
42    struct RunningGuard;
43
44    impl Drop for RunningGuard {
45        fn drop(&mut self) {
46            CANIC_EAGER_TLS_RUNNING.with(|running| running.set(false));
47        }
48    }
49
50    CANIC_EAGER_TLS_RUNNING.with(|running| running.set(true));
51    let _running_guard = RunningGuard;
52
53    let funcs = CANIC_EAGER_TLS.with(|v| {
54        let mut v = v.borrow_mut();
55        std::mem::take(&mut *v)
56    });
57
58    debug_assert!(
59        CANIC_EAGER_TLS.with(|v| v.borrow().is_empty()),
60        "CANIC_EAGER_TLS was modified during init_eager_tls() execution"
61    );
62
63    for f in funcs {
64        f();
65    }
66}
67
68#[must_use]
69pub fn is_eager_tls_initializing() -> bool {
70    CANIC_EAGER_TLS_RUNNING.with(Cell::get)
71}
72
73#[must_use]
74pub fn is_memory_bootstrap_ready() -> bool {
75    is_eager_tls_initializing() || registry::MemoryRegistryRuntime::is_initialized()
76}
77
78pub fn assert_memory_bootstrap_ready(label: &str, id: u8) {
79    if is_memory_bootstrap_ready() {
80        return;
81    }
82
83    panic!(
84        "stable memory slot '{label}' (id {id}) accessed before memory bootstrap; call init_eager_tls() and MemoryRegistryRuntime::init(...) first"
85    );
86}
87
88/// Register a TLS initializer function for eager execution.
89///
90/// This is called by the `eager_static!` macro. The function pointer `f`
91/// must be a zero-argument function (`fn()`) that performs a `.with(|_| {})`
92/// on the thread-local static it is meant to initialize.
93pub fn defer_tls_initializer(f: fn()) {
94    CANIC_EAGER_TLS.with_borrow_mut(|v| v.push(f));
95}
96
97///
98/// TESTS
99///
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use std::cell::Cell;
105
106    thread_local! {
107        static COUNT: Cell<u32> = const { Cell::new(0) };
108    }
109
110    fn bump() {
111        COUNT.with(|c| c.set(c.get() + 1));
112    }
113
114    #[test]
115    fn init_eager_tls_runs_and_clears_queue() {
116        COUNT.with(|c| c.set(0));
117        CANIC_EAGER_TLS.with(|v| v.borrow_mut().push(bump));
118        init_eager_tls();
119        let first = COUNT.with(Cell::get);
120        assert_eq!(first, 1);
121
122        // second call sees empty queue
123        init_eager_tls();
124        let second = COUNT.with(Cell::get);
125        assert_eq!(second, 1);
126    }
127}