Skip to main content

miniextendr_api/
thread.rs

1//! R's main thread, and advanced controls for R's process-global C-stack
2//! bounds.
3//!
4//! # R's main thread
5//!
6//! R's C API may only be called on R's main thread: the thread that loaded the
7//! package and ran [`miniextendr_runtime_init`] from `R_init_<pkg>`. Every
8//! generated `.Call` entry point, ALTREP callback and connection callback runs
9//! there.
10//!
11//! - [`is_r_main_thread`] — whether the current thread is R's main thread.
12//! - [`with_r_thread`] — run a closure that calls R, after checking that this
13//!   is R's main thread. The checked FFI bindings in [`crate::sys`] go through
14//!   it, so an R call from a Rayon or `std::thread` thread panics with a clear
15//!   message instead of reaching R.
16//!
17//! Inside a [`with_r_thread`] body the check has been made: the
18//! `*_unchecked` variants in [`crate::sys`] are fine there (the lint
19//! **MXL301** recognises the body, alongside ALTREP callbacks and
20//! [`crate::unwind_protect::with_r_unwind_protect`] bodies).
21//!
22//! Threads the package spawns stay pure Rust: compute there, then hand the
23//! results to R on the main thread (see `rayon_bridge` for the pattern).
24//!
25//! # R API calls remain main-thread-only
26//!
27//! R's stack checking mechanism causes segfaults when R API functions are
28//! called from threads other than the main R thread. This module also exposes
29//! legacy tools that disable that one check, but doing so does **not** make
30//! R's API safe on a secondary thread.
31//!
32//! R's global state, garbage collector, and error signaling are not made
33//! thread-safe by changing `R_CStackLimit`. Writing R Extensions requires
34//! package R API calls to stay on R's main thread and specifically says packages
35//! must not change these variables to call stack-checking internals on a
36//! secondary thread. Do not use this module as an off-main R bridge in package
37//! code. The misleading package-facing surface is tracked for removal or
38//! relocation in #1352.
39//!
40//! `StackCheckGuard` is gated behind the `nonapi` feature because it
41//! mutates `R_CStackStart` / `R_CStackLimit` / `R_CStackDir`, none of which
42//! are part of R's public C API. The lint **MXL301** currently recognizes this
43//! guard as an unchecked-FFI context, but that only reflects the existing API;
44//! it does not override R's main-thread contract.
45//!
46//! # Don't use `Rf_error` here either
47//!
48//! A longjmp from a non-main thread is undefined behaviour even with the
49//! stack check disabled. Panic, capture the message in your guard's
50//! fallback (see [`crate::ffi_guard::guarded_ffi_call_with_fallback`]), and
51//! surface the failure to the main thread before letting R see it. The lint
52//! **MXL300** rejects direct `Rf_error` calls in user code.
53//!
54//! # Cross references
55//!
56//! - [`crate::sys`] — checked vs `*_unchecked` FFI surface.
57//! - [`crate::ffi_guard`] — guard taxonomy across boundaries.
58//!
59//! # Background
60//!
61//! R tracks three variables for stack overflow detection (all non-API):
62//! - `R_CStackStart` - top of the main thread's stack
63//! - `R_CStackLimit` - stack size limit
64//! - `R_CStackDir` - stack growth direction
65//!
66//! When R API functions check the stack, they compare the current stack pointer
67//! against these bounds. On a different thread, the stack is completely different,
68//! causing false stack overflow detection.
69//!
70//! # Solution
71//!
72//! Setting `R_CStackLimit` to `usize::MAX` disables R's own stack-address
73//! check. The OS still enforces its real stack limit, but all other R threading
74//! invariants remain unchanged.
75//!
76//! # Example
77//!
78//! ```ignore
79//! use miniextendr_api::thread::StackCheckGuard;
80//!
81//! // Advanced embedded-host bookkeeping only; not package R API access.
82//! let _guard = StackCheckGuard::disable();
83//! assert!(miniextendr_api::thread::is_stack_checking_disabled());
84//! ```
85//!
86//! # Feature Gate
87//!
88//! The stack-check controls require the `nonapi` feature because they access
89//! non-API R internals (`R_CStackLimit`, `R_CStackStart`, `R_CStackDir`).
90
91use std::sync::OnceLock;
92use std::thread::ThreadId;
93
94// region: R's main thread
95
96static R_MAIN_THREAD_ID: OnceLock<ThreadId> = OnceLock::new();
97
98/// Check if the current thread is R's main thread.
99///
100/// Returns `true` if called from the main R thread, `false` otherwise.
101/// Before `miniextendr_runtime_init()` is called, always returns `false`.
102#[inline(always)]
103pub fn is_r_main_thread() -> bool {
104    R_MAIN_THREAD_ID
105        .get()
106        .is_some_and(|&id| id == std::thread::current().id())
107}
108
109/// Run a closure that calls R's C API, after checking that this is R's main
110/// thread.
111///
112/// On R's main thread, runs `f` and returns its value. R's C API may not be
113/// called from any other thread, so this has nowhere to send the closure:
114/// called from a Rayon or `std::thread` thread it panics instead. Inside
115/// the closure the `*_unchecked` FFI variants are fine (lint **MXL301**).
116///
117/// # Panics
118///
119/// - If `miniextendr_runtime_init()` hasn't been called yet
120/// - If called from a thread other than R's main thread
121///
122/// # Example
123///
124/// ```ignore
125/// use miniextendr_api::with_r_thread;
126///
127/// let sexp = with_r_thread(|| unsafe {
128///     miniextendr_api::sys::Rf_ScalarInteger_unchecked(1)
129/// });
130/// ```
131#[inline]
132pub fn with_r_thread<F, R>(f: F) -> R
133where
134    F: FnOnce() -> R,
135{
136    assert_runtime_initialized();
137    if !is_r_main_thread() {
138        {
    ::core::panicking::panic_fmt(format_args!("R\'s C API was called from a thread other than R\'s main thread.\n\nR API calls can only happen on R\'s main thread. Keep code on other threads (Rayon, std::thread) pure Rust: collect its results and convert them to R objects after the parallel section returns."));
};panic!(
139            "R's C API was called from a thread other than R's main thread.\n\
140             \n\
141             R API calls can only happen on R's main thread. Keep code on other \
142             threads (Rayon, std::thread) pure Rust: collect its results and convert \
143             them to R objects after the parallel section returns."
144        );
145    }
146    f()
147}
148
149/// Initialize the miniextendr runtime: record the calling thread as R's main
150/// thread, and open there the channels that bring it the deferred conditions
151/// queued on other threads and the R exits dropped on them.
152///
153/// Must be called from R's main thread, typically from `R_init_<pkgname>`.
154/// Idempotent: later calls keep the first thread.
155#[doc(hidden)]
156#[unsafe(no_mangle)]
157pub extern "C-unwind" fn miniextendr_runtime_init() {
158    let _ = R_MAIN_THREAD_ID.set(std::thread::current().id());
159    crate::deferred_condition::open_channel();
160    crate::unwind_protect::open_abandoned_channel();
161}
162
163/// Shut the miniextendr runtime down: uninstall the process panic hook this
164/// DLL registered (see `backtrace::miniextendr_panic_hook_uninstall`).
165///
166/// Called from `R_unload_<pkg>` (generated by `miniextendr_init!`), before
167/// `library.dynam.unload` unmaps the DLL's code. Idempotent.
168#[doc(hidden)]
169#[unsafe(no_mangle)]
170pub extern "C-unwind" fn miniextendr_runtime_shutdown() {
171    crate::backtrace::miniextendr_panic_hook_uninstall();
172}
173
174/// Panic if the runtime hasn't been initialized.
175fn assert_runtime_initialized() {
176    if R_MAIN_THREAD_ID.get().is_none() {
177        {
    ::core::panicking::panic_fmt(format_args!("miniextendr_runtime_init() must be called before using R FFI APIs.\n\nThis is typically done in R_init_<pkgname>() via:\n\nvoid R_init_pkgname(DllInfo *dll) {{\nminiextendr_runtime_init();\nR_registerRoutines(dll, NULL, CallEntries, NULL, NULL);\n}}\n\nIf you\'re embedding R in Rust, call miniextendr_runtime_init() from the main thread before any R API calls."));
};panic!(
178            "miniextendr_runtime_init() must be called before using R FFI APIs.\n\
179             \n\
180             This is typically done in R_init_<pkgname>() via:\n\
181             \n\
182             void R_init_pkgname(DllInfo *dll) {{\n\
183             miniextendr_runtime_init();\n\
184             R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);\n\
185             }}\n\
186             \n\
187             If you're embedding R in Rust, call miniextendr_runtime_init() from the main thread \
188             before any R API calls."
189        );
190    }
191}
192// endregion
193
194// region: C-stack bounds (nonapi)
195
196#[cfg(feature = "nonapi")]
197use crate::sys::nonapi_stack::{
198    get_r_cstack_dir, get_r_cstack_limit, get_r_cstack_start, set_r_cstack_limit,
199};
200
201#[cfg(feature = "nonapi")]
202use std::sync::atomic::{AtomicUsize, Ordering};
203
204/// Global refcount for active stack check guards.
205/// When count > 0, stack checking is disabled.
206#[cfg(feature = "nonapi")]
207static STACK_GUARD_COUNT: AtomicUsize = AtomicUsize::new(0);
208
209/// Original R_CStackLimit value before any guards were created.
210/// Only valid when STACK_GUARD_COUNT > 0.
211#[cfg(feature = "nonapi")]
212static ORIGINAL_STACK_LIMIT: AtomicUsize = AtomicUsize::new(0);
213
214/// RAII guard that disables R's process-global stack check and restores it on drop.
215///
216/// This does not make R API calls safe on a secondary thread. R package code
217/// must keep R API work on the main thread and should not use this guard.
218///
219/// Multiple guards can be active concurrently. Stack checking is only restored
220/// when the last guard is dropped.
221///
222/// # Example
223///
224/// ```ignore
225/// let _guard = StackCheckGuard::disable();
226/// assert!(miniextendr_api::thread::is_stack_checking_disabled());
227/// // Original process-global limit is restored when `_guard` is dropped.
228/// ```
229#[cfg(feature = "nonapi")]
230pub struct StackCheckGuard {
231    // Unit struct - state is in global atomics
232    _private: (),
233}
234
235#[cfg(feature = "nonapi")]
236impl StackCheckGuard {
237    /// Disable R's stack checking and return a guard that restores it on drop.
238    ///
239    /// Multiple guards can be created concurrently (even from different threads).
240    /// Stack checking is only restored when the last guard is dropped.
241    ///
242    /// # Process-global contract
243    ///
244    /// The caller must own the relevant embedded-R lifecycle, ensure R is
245    /// initialized, and prevent conflicting access to the stack globals. This
246    /// is not a supported way for an R package to call R from another thread.
247    #[must_use]
248    pub fn disable() -> Self {
249        // Atomically increment guard count and save original limit if we're the first
250        let prev_count = STACK_GUARD_COUNT.fetch_add(1, Ordering::SeqCst);
251        if prev_count == 0 {
252            // We're the first guard - save the original limit
253            let original = get_r_cstack_limit();
254            ORIGINAL_STACK_LIMIT.store(original, Ordering::SeqCst);
255            // Disable stack checking
256            unsafe {
257                set_r_cstack_limit(usize::MAX);
258            }
259        }
260        Self { _private: () }
261    }
262
263    /// Get the original limit value that will be restored (for debugging).
264    pub fn original_limit() -> usize {
265        ORIGINAL_STACK_LIMIT.load(Ordering::SeqCst)
266    }
267
268    /// Get the current number of active guards (for debugging).
269    pub fn active_count() -> usize {
270        STACK_GUARD_COUNT.load(Ordering::SeqCst)
271    }
272}
273
274#[cfg(feature = "nonapi")]
275impl Drop for StackCheckGuard {
276    fn drop(&mut self) {
277        // Atomically decrement guard count and restore limit if we're the last
278        let prev_count = STACK_GUARD_COUNT.fetch_sub(1, Ordering::SeqCst);
279        if prev_count == 1 {
280            // We were the last guard - restore the original limit
281            let original = ORIGINAL_STACK_LIMIT.load(Ordering::SeqCst);
282            unsafe {
283                set_r_cstack_limit(original);
284            }
285        }
286    }
287}
288
289/// Check if stack checking is currently disabled.
290///
291/// Returns `true` if `R_CStackLimit` is set to `usize::MAX`.
292#[cfg(feature = "nonapi")]
293pub fn is_stack_checking_disabled() -> bool {
294    get_r_cstack_limit() == usize::MAX
295}
296
297/// Get the current stack checking configuration (for debugging).
298///
299/// Returns `(start, limit, direction)`.
300#[cfg(feature = "nonapi")]
301pub fn get_stack_config() -> (usize, usize, i32) {
302    (
303        get_r_cstack_start(),
304        get_r_cstack_limit(),
305        get_r_cstack_dir(),
306    )
307}
308
309/// Disable stack checking permanently for the current session.
310///
311/// Unlike [`StackCheckGuard`], this does not restore the original value.
312/// This is only for an embedding host that owns the complete R process
313/// lifecycle. It must not be used by an R package to enable secondary-thread
314/// R API calls.
315///
316/// # Process-global contract
317///
318/// Call at most once during controlled embedded-R initialization, with no
319/// concurrent access to the stack globals.
320#[cfg(feature = "nonapi")]
321pub fn disable_stack_checking_permanently() {
322    unsafe {
323        set_r_cstack_limit(usize::MAX);
324    }
325    // Pin the saved limit to `usize::MAX` so a later `StackCheckGuard` drop can't
326    // silently re-enable checking. If a guard is already active, `ORIGINAL_STACK_LIMIT`
327    // holds the real pre-disable limit, and the last guard's drop would restore it —
328    // undoing the "permanent" disable. Overwriting it with `usize::MAX` makes that
329    // restore a no-op, so the disable stays durable regardless of guard ordering.
330    ORIGINAL_STACK_LIMIT.store(usize::MAX, Ordering::SeqCst);
331}
332
333/// Execute a closure with stack checking disabled.
334///
335/// This is a convenience wrapper around [`StackCheckGuard`].
336///
337/// This helper does not authorize R API calls from a secondary thread.
338#[cfg(feature = "nonapi")]
339pub fn with_stack_checking_disabled<F, R>(f: F) -> R
340where
341    F: FnOnce() -> R,
342{
343    let _guard = StackCheckGuard::disable();
344    f()
345}
346// endregion
347
348// region: Thread spawning with legacy R-sized stacks
349
350/// Default stack size for the legacy R-sized thread builder (8 MiB).
351///
352/// R doesn't enforce a specific stack size - it uses whatever the OS provides:
353/// - **Unix**: Typically 8 MiB from `ulimit -s`
354/// - **Windows**: 64 MiB for the main thread (since R 4.2)
355///
356/// Rust's default thread stack is only 2 MiB. The legacy builder reserves
357/// 8 MiB to match common R-hosting configurations; this sizing choice does not
358/// make R API access from the spawned thread supported.
359pub const DEFAULT_R_STACK_SIZE: usize = 8 * 1024 * 1024;
360
361/// Stack size matching Windows R (64 MiB).
362///
363/// Use this for a deep pure-Rust workload that needs a reservation comparable
364/// to Windows R's main thread. It does not authorize R API calls on the spawned
365/// thread. Windows R uses 64 MiB for its main thread since R 4.2.
366///
367/// # Why larger than [`DEFAULT_R_STACK_SIZE`]
368///
369/// This is 8x the [`DEFAULT_R_STACK_SIZE`] used on other platforms. Two factors
370/// motivate the larger reservation on Windows:
371///
372/// - Newly spawned Windows threads get a comparatively small *committed* stack by
373///   default, and the OS does not grow a thread stack the way `ulimit -s` allows
374///   on typical Unix configurations — so the size we ask for up front is closer to
375///   the size we actually get.
376/// - R's own choice of 64 MiB for its Windows main thread (since R 4.2) provides
377///   a conservative reference point for stack-heavy native workloads.
378///
379/// This is a conservative reservation, not a precise measurement of any single
380/// Rust call's stack frame.
381#[cfg(windows)]
382pub const WINDOWS_R_STACK_SIZE: usize = 64 * 1024 * 1024;
383
384/// Spawn a thread with the legacy R-oriented stack configuration.
385///
386/// This function:
387/// 1. Sets a stack size appropriate for R (8 MiB by default)
388/// 2. With `nonapi`, disables R's process-global stack check via `StackCheckGuard`
389/// 3. Restores stack checking when the thread completes
390///
391/// This does **not** make R API calls safe on the spawned thread. Keep package
392/// R calls on the main thread; this misleading surface is tracked in #1352.
393///
394/// # Example
395///
396/// ```ignore
397/// use miniextendr_api::thread::spawn_with_r;
398///
399/// let handle = spawn_with_r(|| expensive_pure_rust_computation())?;
400///
401/// let result = handle.join().unwrap();
402/// ```
403///
404/// # Errors
405///
406/// Returns an error if the thread cannot be spawned (e.g., resource exhaustion).
407#[cfg(feature = "nonapi")]
408pub fn spawn_with_r<F, T>(f: F) -> std::io::Result<std::thread::JoinHandle<T>>
409where
410    F: FnOnce() -> T + Send + 'static,
411    T: Send + 'static,
412{
413    RThreadBuilder::new().spawn(f)
414}
415
416/// Builder for spawning pure-Rust threads with a legacy R-sized stack.
417///
418/// This builder is always available and configures threads with stack sizes
419/// suitable for stack-heavy Rust workloads (8 MiB default, vs Rust's 2 MiB default).
420///
421/// When the `nonapi` feature is enabled, spawned threads also automatically
422/// disable R's stack checking via `StackCheckGuard`. That changes only the
423/// stack-address check and does not make R API calls from the thread safe.
424///
425/// # Example
426///
427/// ```ignore
428/// use miniextendr_api::thread::RThreadBuilder;
429///
430/// let handle = RThreadBuilder::new()
431///     .stack_size(16 * 1024 * 1024)  // 16 MiB
432///     .name("r-worker".to_string())
433///     .spawn(expensive_pure_rust_computation)?;
434/// ```
435pub struct RThreadBuilder {
436    stack_size: usize,
437    name: Option<String>,
438}
439
440impl Default for RThreadBuilder {
441    fn default() -> Self {
442        Self::new()
443    }
444}
445
446impl RThreadBuilder {
447    /// Create a new builder with default settings.
448    ///
449    /// Default stack size is [`DEFAULT_R_STACK_SIZE`] (8 MiB).
450    #[must_use]
451    pub fn new() -> Self {
452        Self {
453            stack_size: DEFAULT_R_STACK_SIZE,
454            name: None,
455        }
456    }
457
458    /// Set the stack size for the thread.
459    ///
460    /// The default is 8 MiB, matching the legacy R-sized configuration rather
461    /// than Rust's typical 2 MiB spawned-thread default.
462    #[must_use]
463    pub fn stack_size(mut self, size: usize) -> Self {
464        self.stack_size = size;
465        self
466    }
467
468    /// Set the name for the thread (for debugging).
469    #[must_use]
470    pub fn name(mut self, name: String) -> Self {
471        self.name = Some(name);
472        self
473    }
474
475    /// Spawn the thread with the configured settings.
476    ///
477    /// With `nonapi` feature: automatically disables R's stack checking.
478    /// Without `nonapi` feature: just spawns with the configured stack size.
479    pub fn spawn<F, T>(self, f: F) -> std::io::Result<std::thread::JoinHandle<T>>
480    where
481        F: FnOnce() -> T + Send + 'static,
482        T: Send + 'static,
483    {
484        let mut builder = std::thread::Builder::new().stack_size(self.stack_size);
485
486        if let Some(name) = self.name {
487            builder = builder.name(name);
488        }
489
490        #[cfg(feature = "nonapi")]
491        {
492            builder.spawn(move || {
493                let _guard = StackCheckGuard::disable();
494                f()
495            })
496        }
497
498        #[cfg(not(feature = "nonapi"))]
499        {
500            builder.spawn(f)
501        }
502    }
503
504    /// Spawn and immediately join, returning the result.
505    ///
506    /// Convenience method for synchronously joining a configured thread.
507    ///
508    /// # Example
509    ///
510    /// ```ignore
511    /// let result = RThreadBuilder::new().spawn_join(|| 40 + 2).unwrap();
512    /// ```
513    pub fn spawn_join<F, T>(self, f: F) -> std::thread::Result<T>
514    where
515        F: FnOnce() -> T + Send + 'static,
516        T: Send + 'static,
517    {
518        self.spawn(f)
519            .map_err(|e| Box::new(e) as Box<dyn std::any::Any + Send>)?
520            .join()
521    }
522}
523
524/// Spawn a scoped thread with the legacy R-oriented stack configuration.
525///
526/// Like [`spawn_with_r`] but uses scoped threads, allowing the closure to
527/// borrow from the enclosing scope.
528///
529/// # Example
530///
531/// ```ignore
532/// use miniextendr_api::thread::scope_with_r;
533///
534/// let data = vec![1, 2, 3];
535///
536/// std::thread::scope(|s| {
537///     scope_with_r(s, |_| {
538///         // Can borrow `data` here!
539///         println!("data len: {}", data.len());
540///         // Keep the scoped work Rust-only; R API calls remain main-thread-only.
541///     });
542/// });
543/// ```
544#[cfg(feature = "nonapi")]
545pub fn scope_with_r<'scope, 'env, F, T>(
546    scope: &'scope std::thread::Scope<'scope, 'env>,
547    f: F,
548) -> std::thread::ScopedJoinHandle<'scope, T>
549where
550    F: FnOnce(&'scope std::thread::Scope<'scope, 'env>) -> T + Send + 'scope,
551    T: Send + 'scope,
552{
553    // Note: scoped threads don't support custom stack sizes in std
554    // This is a known limitation. For custom stack sizes, use spawn_with_r.
555    scope.spawn(move || {
556        let _guard = StackCheckGuard::disable();
557        f(scope)
558    })
559}
560
561// endregion
562
563#[cfg(test)]
564mod tests;