Skip to main content

miniextendr_api/
unwind_protect.rs

1//! Safe API for R's `R_UnwindProtect`
2//!
3//! This module provides [`with_r_unwind_protect`] for handling R errors with Rust cleanup.
4//! It automatically runs Rust destructors when R errors occur.
5//!
6//! **Important**: R uses `longjmp` for error handling, which normally bypasses Rust destructors.
7//! Use this API to ensure cleanup happens even when R errors occur.
8//!
9//! ## When to reach for this
10//!
11//! - **Calling R APIs that can error from a body you wrote yourself**
12//!   (custom ALTREP, custom connection trampoline, hand-rolled FFI shim).
13//!   Wrap the R-calling section in [`with_r_unwind_protect`] so Rust
14//!   destructors run if R longjmps.
15//! - **Inside a [`with_r_unwind_protect`] body it is safe to use `*_unchecked`
16//!   variants of the R FFI** — see the [`crate::sys`] module doc. The lint
17//!   **MXL301** recognises this as one of the three contexts where bypassing
18//!   the main-thread assertion is valid (the other two being ALTREP callbacks
19//!   and [`crate::with_r_thread`] bodies).
20//!
21//! ## You probably don't need this from a `#[miniextendr]` body
22//!
23//! The proc-macro already wraps every function and method in a guard that
24//! converts panics into the tagged-condition transport ([`crate::error_value`]).
25//! Returning `Result::Err`, `Option::None`, or calling `panic!()` /
26//! [`crate::error!`] / [`crate::warning!`] / [`crate::message!`] is the
27//! idiomatic path. Direct [`with_r_unwind_protect`] use inside that body is
28//! almost always wrong — you'd be nesting an `R_UnwindProtect` inside another
29//! `R_UnwindProtect`, paying the longjmp-leak cost twice (see "Leaks" below).
30//!
31//! ## Don't use `Rf_error`
32//!
33//! `Rf_error` and `Rf_errorcall` longjmp directly, skipping every Rust
34//! destructor on the stack. The lint **MXL300** forbids them in user code.
35//! Panic instead (or call [`crate::error!`]) and the framework raises the
36//! corresponding R condition for you.
37//!
38//! ## Leaks
39//!
40//! On the R longjmp path (when R unwinds out of the protected body),
41//! `with_r_unwind_protect` leaks ~8 bytes (an `RErrorMarker` + `Box` header)
42//! because the cleanup handler can't reclaim them via
43//! `Box::from_raw`. Regular Rust panics from inside the body don't leak.
44//! This is the cost MXL300 is buying off: every direct `Rf_error()` would
45//! incur the same leak with no observability.
46//!
47//! ## Log drain
48//!
49//! Every call to `with_r_unwind_protect` (and its variants) drains the
50//! cross-thread log queue via the crate-private `drain_log_queue_if_available`
51//! helper before returning or re-raising an R error. This ensures that records
52//! buffered by other threads (Rayon, `std::thread`) are flushed to R's console on every FFI exit —
53//! including error paths.
54//!
55//! ## Cross references
56//!
57//! - [`crate::with_r_thread`] — checks for R's main thread and runs a closure.
58//! - [`crate::ffi_guard`] — unified panic-catching trampoline that consumes
59//!   `with_r_unwind_protect_sourced` for ALTREP `RUnwind` mode.
60//! - [`crate::error_value`] / [`mod@crate::condition`] — panic → R condition
61//!   transport.
62use std::{
63    any::Any,
64    borrow::Cow,
65    cell::{Cell, OnceCell},
66    ffi::c_void,
67    panic::{AssertUnwindSafe, catch_unwind},
68    sync::OnceLock,
69    sync::mpsc::{Receiver, SyncSender, sync_channel},
70};
71
72// region: raise_rust_condition_via_stop — Approach 3 for ALTREP RUnwind path
73
74/// Raise the R condition for a tagged condition value by evaluating the
75/// shared `.miniextendr_raise_condition` helper on it, the helper every
76/// generated R wrapper calls on the value its `.Call()` returns.
77///
78/// This is **Approach 3** from the issue-345 plan: an `Rf_eval` that ends in
79/// `stop(structure(...))`, for contexts with no outer R wrapper to inspect a
80/// tagged SEXP. It is the only viable option for ALTREP callbacks, which are
81/// invoked directly by R's runtime (no `.Call` frame, no R wrapper).
82///
83/// `tagged_value` builds the value (with [`crate::error_value`]'s
84/// constructors). Because the helper raises it, the condition is the one the
85/// wrapper raises for the same value, field for field (#1768): `message`,
86/// `call`, `kind`, then the `data =` fields spliced with `utils::modifyList`,
87/// so a data field named `message`, `call` or `kind` replaces the base field
88/// on both transports (#1315); the classes ahead of the `rust_*` layering.
89/// The copy evaluated here lives in the base namespace, so the caller
90/// resolves `arg_error!`'s class marker in Rust first.
91///
92/// The value must be of an error kind (`stop()` longjmps, so this function
93/// never returns); the helper's warning / message / condition arms return.
94///
95/// ## Nothing Rust-owned survives the longjmp
96///
97/// The longjmp skips every Rust frame above R's, so no destructor runs past
98/// this point. `tagged_value` consumes what it captures (message, classes,
99/// data) and is itself dropped before `Rf_eval`; the SEXPs are rooted with
100/// plain `Rf_protect`, whose stack R resets on the jump, rather than a
101/// drop guard that would never run.
102///
103/// ## MXL300 compliance
104///
105/// This function raises an R error via `Rf_eval(stop(...))`, not via direct
106/// `Rf_error`/`Rf_errorcall`. MXL300 does not flag `Rf_eval`.
107///
108/// # Safety
109///
110/// Must be called from R's main thread in a context where R longjmps are
111/// safe, with no Rust value that needs dropping left on the caller's frames.
112/// In practice, always called from `with_r_unwind_protect_sourced` (ALTREP
113/// `RUnwind` guards, [`with_r_unwind_protect_or_raise`]) after its guarded
114/// closure has returned.
115pub(crate) unsafe fn raise_rust_condition_via_stop(
116    tagged_value: impl FnOnce() -> SEXP,
117    call: Option<SEXP>,
118) -> ! {
119    use crate::sys::{R_BaseEnv, Rf_eval, Rf_lang3, Rf_protect};
120
121    unsafe {
122        let helper = crate::deferred_condition::raise_condition_helper();
123        let tagged = Rf_protect(tagged_value());
124        let expr = Rf_protect(Rf_lang3(helper, tagged, call.unwrap_or(SEXP::nil())));
125        // Longjmps through `stop()`; R pops the protect stack on the way out.
126        Rf_eval(expr, R_BaseEnv);
127    }
128    // Only a non-error tagged value (a bug in the caller) gets here, and
129    // unwinding out of an ALTREP callback would cross R's C frames.
130    std::process::abort()
131}
132
133/// The tagged value of a generic panic, `kind = "panic"`: what
134/// [`with_r_unwind_protect`] returns for one.
135fn panic_condition_value(message: &str, call: Option<SEXP>) -> SEXP {
136    // SAFETY: only called by `raise_rust_condition_via_stop`, on the main thread.
137    unsafe {
138        crate::error_value::make_rust_condition_value(
139            message,
140            crate::error_value::kind::PANIC,
141            None,
142            call,
143        )
144    }
145}
146
147// endregion
148
149use crate::sys::{self, R_ContinueUnwind, R_UnwindProtect_C_unwind};
150use crate::{Rboolean, SEXP};
151
152/// Global continuation token for R_UnwindProtect.
153///
154/// Using a single global token instead of thread-local tokens avoids leaking
155/// one token per thread that uses `with_r_unwind_protect`.
156///
157/// # Safety
158///
159/// The token is created and preserved once during first use. It remains valid
160/// for the entire R session.
161static R_CONTINUATION_TOKEN: OnceLock<SEXP> = OnceLock::new();
162
163/// Get or create the global continuation token.
164fn get_continuation_token() -> SEXP {
165    *R_CONTINUATION_TOKEN.get_or_init(|| {
166        // The continuation token must be created on R's main thread
167        // (R_MakeUnwindCont is an R API call). OnceLock ensures it is
168        // only created once and safely shared.
169        unsafe {
170            let token = sys::R_MakeUnwindCont();
171            sys::R_PreserveObject(token);
172            token
173        }
174    })
175}
176
177/// Extract a message from a panic payload.
178///
179/// Handles `&str`, `String`, `&String` and
180/// [`RCondition`](enum@crate::condition::RCondition) payloads (the condition's
181/// message) consistently. The borrowed variants are returned as
182/// `Cow::Borrowed`, so the common `panic!("literal")` case avoids the heap
183/// allocation that a `String` return would force. Unrecognised payload types
184/// fall back to a `Cow::Borrowed` static string.
185///
186/// Call `.into_owned()` (or `.to_string()`) at sites that need an owned
187/// `String`.
188pub fn panic_payload_to_string(payload: &(dyn Any + Send)) -> Cow<'_, str> {
189    if let Some(&s) = payload.downcast_ref::<&str>() {
190        Cow::Borrowed(s)
191    } else if let Some(s) = payload.downcast_ref::<String>() {
192        Cow::Borrowed(s.as_str())
193    } else if let Some(s) = payload.downcast_ref::<&String>() {
194        Cow::Borrowed(s.as_str())
195    } else if let Some(condition) = payload.downcast_ref::<crate::condition::RCondition>() {
196        Cow::Borrowed(condition.message())
197    } else {
198        Cow::Borrowed("unknown panic")
199    }
200}
201
202/// Stringify a panic payload and fold in the Rust source location the panic
203/// hook recorded on the *current* thread, producing the final R-facing message.
204///
205/// Returns `panic_payload_to_string(payload)` with a `\n(at file:line)` suffix
206/// when [`crate::backtrace::take_last_panic_location`] has a location for this
207/// thread, otherwise the bare message. The location is captured in the process
208/// panic hook (`backtrace.rs`), which fires on the panicking thread — so this
209/// **must be called on the same thread that ran the panicking closure** (R's
210/// main thread for `#[miniextendr]` fns).
211///
212/// Only the *generic panic* path uses this. `error!`/`warning!`/`message!`/
213/// `condition!` (and `Result::Err` / `Option::None`) travel the typed
214/// `RCondition` / tagged-value branches and are deliberately left byte-for-byte
215/// unchanged — they carry no location suffix.
216pub(crate) fn panic_message_with_location(payload: &(dyn Any + Send)) -> String {
217    let msg = panic_payload_to_string(payload);
218    match crate::backtrace::take_last_panic_location() {
219        Some((file, line)) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n(at {1}:{2})", msg, file,
                line))
    })format!("{msg}\n(at {file}:{line})"),
220        None => msg.into_owned(),
221    }
222}
223
224// region: R exits carried as a Rust unwind (#1835)
225
226#[doc = r" The last boundary id handed out on this thread."]
const LAST_BOUNDARY: ::std::thread::LocalKey<Cell<u64>> =
    {
        const __RUST_STD_INTERNAL_INIT: Cell<u64> = { Cell::new(0) };
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<Cell<u64>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::EagerStorage<Cell<u64>> =
                                        ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                    __RUST_STD_INTERNAL_VAL.get()
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL: Cell<u64> =
                                        __RUST_STD_INTERNAL_INIT;
                                    &__RUST_STD_INTERNAL_VAL
                                }
                        }
                    })
        }
    };thread_local! {
227    /// The innermost [`Boundary`] on this thread; `0` outside any.
228    static BOUNDARY: Cell<u64> = const { Cell::new(0) };
229    /// The last boundary id handed out on this thread.
230    static LAST_BOUNDARY: Cell<u64> = const { Cell::new(0) };
231}
232
233/// A miniextendr boundary that resumes R exits ([`RUnwind`]): the innermost on
234/// its thread from [`enter`](Self::enter) until it is dropped or
235/// [`leave`](Self::leave)s.
236///
237/// An exit belongs to the boundary that was innermost when its evaluation
238/// started, and only that boundary may resume it. Its jump target is an R
239/// context on the C stack, alive only while that boundary's call is: an exit
240/// caught with `catch_unwind`, kept, and resumed after the call returned would
241/// jump into a frame that no longer exists. [`resume_if_r_unwind`] refuses it.
242pub(crate) struct Boundary {
243    id: u64,
244    outer: u64,
245}
246
247impl Boundary {
248    /// Become the innermost boundary on this thread.
249    #[inline]
250    pub(crate) fn enter() -> Self {
251        let id = LAST_BOUNDARY.with(|last| {
252            let id = last.get() + 1;
253            last.set(id);
254            id
255        });
256        let outer = BOUNDARY.with(|current| current.replace(id));
257        Boundary { id, outer }
258    }
259
260    /// Make the enclosing boundary the innermost again. Call it before leaving
261    /// by an R jump, which skips `Drop`.
262    #[inline]
263    pub(crate) fn leave(&self) {
264        BOUNDARY.with(|current| current.set(self.outer));
265    }
266}
267
268impl Drop for Boundary {
269    #[inline]
270    fn drop(&mut self) {
271        self.leave();
272    }
273}
274
275/// An R non-local exit that [`call_unwinding`] carries out of its callback
276/// as a Rust unwind: an error, a condition caught by an exiting handler set up
277/// outside the call (`tryCatch(warning = )`), a restart, an interrupt.
278///
279/// The unwind runs the destructors of the Rust frames between the evaluation
280/// and the boundary that catches it. The boundary ([`run_r_unwind_protect`],
281/// the FFI guards) then resumes the exit with
282/// `R_ContinueUnwind`, and R carries on to the context it was jumping to, with
283/// the condition object and call it was jumping with.
284///
285/// The continuation token is private to one evaluation and preserved until
286/// the exit resumes, so R code that a destructor runs during the unwind (a
287/// protected call of its own, which reuses the shared token) cannot overwrite
288/// the pending jump or let the collector reclaim it (#1507).
289pub(crate) struct RUnwind {
290    /// `R_MakeUnwindCont()`, preserved: the jump target and the value R was
291    /// jumping with.
292    token: SEXP,
293    /// The [`Boundary`] that was innermost when the evaluation started.
294    boundary: u64,
295}
296
297impl RUnwind {
298    /// Whether `boundary` may resume this exit: the boundary its evaluation
299    /// ran in, still on the stack.
300    #[inline]
301    pub(crate) fn belongs_to(&self, boundary: &Boundary) -> bool {
302        self.boundary == boundary.id
303    }
304
305    /// Continue the R exit where `R_UnwindProtect` stopped it. Never returns.
306    ///
307    /// # Safety
308    ///
309    /// R's main thread, at the boundary the exit [`belongs_to`](Self::belongs_to),
310    /// after its [`Boundary::leave`], with no Rust value left to drop between
311    /// this call and the R context that owns the frame (the C entry point R
312    /// called).
313    pub(crate) unsafe fn resume(self) -> ! {
314        let token = self.token;
315        std::mem::forget(self);
316        unsafe {
317            // `R_jumpctxt` roots the value it jumps with only after the cleanups
318            // of the contexts it passes have run (it sets `R_ReturnedValue`
319            // after `R_run_onexits`), and those may allocate. The protection
320            // keeps the token, and with it the value, alive until then; the
321            // jump resets the protect stack (`R_restore_globals`), which ends it.
322            sys::Rf_protect(token);
323            sys::R_ReleaseObject(token);
324            R_ContinueUnwind(token)
325        }
326    }
327
328    /// The payload a boundary raises in place of an exit it may not resume
329    /// (see [`Boundary`]). The exit is dropped.
330    pub(crate) fn stray(self: Box<Self>) -> Box<dyn Any + Send> {
331        drop(self);
332        Box::new(
333            "an R exit (an error, a condition handler's exit or a restart) was caught with \
334             `catch_unwind` and resumed outside the call that raised it; it cannot continue",
335        )
336    }
337}
338
339impl Drop for RUnwind {
340    /// Reached when something other than the exit's boundary caught the unwind
341    /// and dropped it, or the boundary refused it ([`RUnwind::stray`]). The R
342    /// exit is abandoned: R carries on from where the evaluation stopped, as
343    /// after `R_tryEval`. Release the token, on R's main thread: dropped on
344    /// another thread (code that moved the caught payload there), it goes to
345    /// the main thread over [`ABANDONED_SENDER`] and the next evaluation
346    /// releases it.
347    ///
348    /// Off the main thread the token is sent with `try_send`, never `send`: the
349    /// main thread may be joining the dropping thread, and a blocking send
350    /// would wait for it forever. When the channel is full (more than
351    /// [`ABANDONED_CAPACITY`] exits dropped off the main thread between two
352    /// evaluations) or not open yet, the token stays preserved, and R keeps
353    /// the value the exit carried: a leak, not a crash.
354    fn drop(&mut self) {
355        if crate::is_r_main_thread() {
356            unsafe { sys::R_ReleaseObject(self.token) }
357        } else if let Some(tx) = ABANDONED_SENDER.get() {
358            let _ = tx.try_send(self.token);
359        }
360    }
361}
362
363/// Capacity of the channel carrying abandoned exits' tokens to R's main thread.
364const ABANDONED_CAPACITY: usize = 64;
365
366/// Sending end of the channel for the tokens of R exits dropped off R's main
367/// thread, where `R_ReleaseObject` would race R. Any thread sends on it.
368static ABANDONED_SENDER: OnceLock<SyncSender<SEXP>> = OnceLock::new();
369
370#[doc =
r" Receiving end of the abandoned-token channel: set on the thread that"]
#[doc = r" opened it (R's main thread), empty on every other thread."]
const ABANDONED_RECEIVER: ::std::thread::LocalKey<OnceCell<Receiver<SEXP>>> =
    {
        const __RUST_STD_INTERNAL_INIT: OnceCell<Receiver<SEXP>> =
            { OnceCell::new() };
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<OnceCell<Receiver<SEXP>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::EagerStorage<OnceCell<Receiver<SEXP>>>
                                        =
                                        ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                    __RUST_STD_INTERNAL_VAL.get()
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL: OnceCell<Receiver<SEXP>> =
                                        __RUST_STD_INTERNAL_INIT;
                                    &__RUST_STD_INTERNAL_VAL
                                }
                        }
                    })
        }
    };thread_local! {
371    /// Receiving end of the abandoned-token channel: set on the thread that
372    /// opened it (R's main thread), empty on every other thread.
373    static ABANDONED_RECEIVER: OnceCell<Receiver<SEXP>> = const { OnceCell::new() };
374}
375
376/// Open the abandoned-token channel and keep its receiving end on the current
377/// thread. [`crate::miniextendr_runtime_init`] calls it on R's main thread;
378/// only the first call opens it.
379pub(crate) fn open_abandoned_channel() {
380    ABANDONED_SENDER.get_or_init(|| {
381        let (tx, rx) = sync_channel(ABANDONED_CAPACITY);
382        ABANDONED_RECEIVER.with(|cell| {
383            cell.get_or_init(|| rx);
384        });
385        tx
386    });
387}
388
389/// Release the tokens of exits dropped off the main thread. An empty channel
390/// is the fast path: `try_iter` stops at once.
391///
392/// # Safety
393///
394/// R's main thread.
395unsafe fn release_abandoned_off_main() {
396    ABANDONED_RECEIVER.with(|cell| {
397        if let Some(rx) = cell.get() {
398            for token in rx.try_iter() {
399                unsafe { sys::R_ReleaseObject(token) };
400            }
401        }
402    });
403}
404
405/// Resume `payload` if it carries an R exit ([`RUnwind`]) that belongs to
406/// `boundary`; return it otherwise, or [`RUnwind::stray`] for an exit from
407/// elsewhere. Conditions deferred since `deferred_mark` belong to the call the
408/// exit abandons and are discarded first, as on the R-error path.
409///
410/// # Safety
411///
412/// As [`RUnwind::resume`]: R's main thread, at `boundary`, with nothing left
413/// to drop above the C entry point.
414pub(crate) unsafe fn resume_if_r_unwind(
415    payload: Box<dyn Any + Send>,
416    deferred_mark: usize,
417    boundary: &Boundary,
418) -> Box<dyn Any + Send> {
419    match payload.downcast::<RUnwind>() {
420        Ok(exit) if exit.belongs_to(boundary) => {
421            crate::deferred_condition::discard(deferred_mark);
422            boundary.leave();
423            unsafe { exit.resume() }
424        }
425        Ok(exit) => exit.stray(),
426        Err(payload) => payload,
427    }
428}
429
430/// Evaluate `expr` in `env` with `Rf_eval`, in the caller's R context: the
431/// condition handlers and restarts established around the `.Call()` stay in
432/// place, unlike under `R_tryEval`, whose `R_ToplevelExec` empties the handler
433/// and restart stacks for the duration. An R exit leaves as [`RUnwind`]
434/// ([`call_unwinding`]).
435///
436/// # Safety
437///
438/// As [`call_unwinding`]; `expr` and `env` are rooted for the call, `env` an
439/// environment. The result is unprotected.
440pub(crate) unsafe fn eval_unwinding(expr: SEXP, env: SEXP) -> SEXP {
441    struct EvalData {
442        expr: SEXP,
443        env: SEXP,
444    }
445
446    unsafe extern "C-unwind" fn eval(data: *mut c_void) -> SEXP {
447        let data = unsafe { &*data.cast::<EvalData>() };
448        unsafe { sys::Rf_eval(data.expr, data.env) }
449    }
450
451    let mut data = EvalData { expr, env };
452    unsafe { call_unwinding(eval, (&raw mut data).cast()) }
453}
454
455/// Call `fun(data)` in its own `R_UnwindProtect`, in the caller's R context,
456/// and return its value.
457///
458/// An R exit from `fun` (an error, an exiting handler of the caller's
459/// `tryCatch()`, a restart, an interrupt) stops at that frame, never jumping
460/// over a Rust frame. Its cleanup turns the exit into a Rust unwind
461/// ([`RUnwind`]); the boundary resumes it.
462///
463/// # Safety
464///
465/// R's main thread, inside a miniextendr boundary (a `#[miniextendr]` body, a
466/// `with_r_unwind_protect*` closure, a guarded callback). `fun` holds nothing
467/// to drop across an R jump (it is called from C), and what `data` points to
468/// outlives the call. The result is unprotected.
469pub(crate) unsafe fn call_unwinding(
470    fun: unsafe extern "C-unwind" fn(*mut c_void) -> SEXP,
471    data: *mut c_void,
472) -> SEXP {
473    struct CallData {
474        fun: unsafe extern "C-unwind" fn(*mut c_void) -> SEXP,
475        data: *mut c_void,
476        token: SEXP,
477        boundary: u64,
478    }
479
480    unsafe extern "C-unwind" fn trampoline(data: *mut c_void) -> SEXP {
481        let data = unsafe { &*data.cast::<CallData>() };
482        // An R exit from here jumps to `R_UnwindProtect`, over no Rust frame
483        // that holds anything to drop.
484        unsafe { (data.fun)(data.data) }
485    }
486
487    unsafe extern "C-unwind" fn cleanup(data: *mut c_void, jump: Rboolean) {
488        if jump != Rboolean::FALSE {
489            let data = unsafe { &*data.cast::<CallData>() };
490            // A boundary the R code entered and an R jump left skipped its
491            // `leave`; this evaluation's boundary is the innermost again.
492            BOUNDARY.with(|current| current.set(data.boundary));
493            // R stopped its jump at our frame and would continue it after this
494            // returns. Carry it out as a Rust unwind instead. `resume_unwind`
495            // skips the panic hook: this is no panic.
496            std::panic::resume_unwind(Box::new(RUnwind {
497                token: data.token,
498                boundary: data.boundary,
499            }));
500        }
501    }
502
503    unsafe {
504        release_abandoned_off_main();
505        let token = sys::R_MakeUnwindCont();
506        sys::R_PreserveObject(token);
507        let boundary = BOUNDARY.with(Cell::get);
508        let mut data = CallData {
509            fun,
510            data,
511            token,
512            boundary,
513        };
514        let value = R_UnwindProtect_C_unwind(
515            Some(trampoline),
516            (&raw mut data).cast(),
517            Some(cleanup),
518            (&raw mut data).cast(),
519            token,
520        );
521        BOUNDARY.with(|current| current.set(boundary));
522        sys::R_ReleaseObject(token);
523        value
524    }
525}
526
527// endregion
528
529// region: Log drain integration
530
531/// Drain the cross-thread log queue if the `log` feature is enabled.
532///
533/// This is called at every exit point of `run_r_unwind_protect` (normal
534/// return, Rust panic, and immediately before `R_ContinueUnwind`) so that
535/// off-main-thread log records always reach R's console before the FFI call
536/// returns or re-raises an R error.
537///
538/// When the `log` feature is disabled this compiles to a no-op; there is
539/// no runtime overhead.
540#[inline]
541fn drain_log_queue_if_available() {
542    #[cfg(feature = "log")]
543    crate::optionals::log_impl::drain_log_queue();
544}
545
546// endregion
547
548/// Core R_UnwindProtect wrapper. Returns `Ok(result)` on success,
549/// `Err(payload)` on Rust panic, or diverges via `R_ContinueUnwind` on R longjmp.
550///
551/// Handles: CallData boxing, trampoline, cleanup handler, continuation token,
552/// `Box::from_raw` reclamation on all non-diverging paths.
553///
554/// Drains the cross-thread log queue (when the `log` feature is enabled) at
555/// each exit point so off-main-thread records reach R's console before the FFI
556/// boundary is crossed.
557fn run_r_unwind_protect<F, R>(f: F) -> Result<R, Box<dyn Any + Send>>
558where
559    F: FnOnce() -> R,
560{
561    /// Marker type for R errors caught by R_UnwindProtect's cleanup handler.
562    struct RErrorMarker;
563
564    struct CallData<F, R> {
565        f: Option<F>,
566        result: Option<R>,
567        panic_payload: Option<Box<dyn Any + Send>>,
568    }
569
570    unsafe extern "C-unwind" fn trampoline<F, R>(data: *mut c_void) -> SEXP
571    where
572        F: FnOnce() -> R,
573    {
574        if !!data.is_null() {
    {
        ::core::panicking::panic_fmt(format_args!("trampoline: data pointer is null"));
    }
};assert!(!data.is_null(), "trampoline: data pointer is null");
575        let data = unsafe { &mut *data.cast::<CallData<F, R>>() };
576        let f = data.f.take().expect("trampoline: closure already consumed");
577
578        match catch_unwind(AssertUnwindSafe(f)) {
579            Ok(result) => {
580                data.result = Some(result);
581                crate::SEXP::nil()
582            }
583            Err(payload) => {
584                data.panic_payload = Some(payload);
585                crate::SEXP::nil()
586            }
587        }
588    }
589
590    unsafe extern "C-unwind" fn cleanup_handler(_data: *mut c_void, jump: Rboolean) {
591        if jump != Rboolean::FALSE {
592            // R is about to longjmp - trigger a Rust panic so we can unwind properly
593            std::panic::panic_any(RErrorMarker);
594        }
595    }
596
597    let deferred_mark = crate::deferred_condition::mark();
598    let boundary = Boundary::enter();
599    unsafe {
600        let token = get_continuation_token();
601
602        let data = Box::into_raw(Box::new(CallData::<F, R> {
603            f: Some(f),
604            result: None,
605            panic_payload: None,
606        }));
607
608        let panic_result = catch_unwind(AssertUnwindSafe(|| {
609            R_UnwindProtect_C_unwind(
610                Some(trampoline::<F, R>),
611                data.cast(),
612                Some(cleanup_handler),
613                std::ptr::null_mut(),
614                token,
615            )
616        }));
617
618        let mut data = Box::from_raw(data);
619
620        match panic_result {
621            Ok(_) => {
622                // Check if trampoline caught a panic
623                if let Some(payload) = data.panic_payload.take() {
624                    drop(data);
625                    // Drain off-main-thread log records before returning the panic
626                    // payload to the caller (which will convert it to an R error).
627                    drain_log_queue_if_available();
628                    // An R exit carried out of `call_unwinding` (#1835): the Rust
629                    // frames it crossed have dropped their values; continue it.
630                    let payload = resume_if_r_unwind(payload, deferred_mark, &boundary);
631                    Err(payload)
632                } else {
633                    // Normal completion - return the result
634                    let result = data
635                        .result
636                        .take()
637                        .expect("result not set after successful completion");
638                    drop(data);
639                    // Drain off-main-thread log records on the normal success path.
640                    drain_log_queue_if_available();
641                    Ok(result)
642                }
643            }
644            Err(payload) => {
645                // Drop data first to run destructors
646                drop(data);
647                // Check if this was an R error or a Rust panic
648                if payload.downcast_ref::<RErrorMarker>().is_some() {
649                    // R error - drain log records before re-raising so off-main
650                    // thread output is not lost even on error exits.
651                    drain_log_queue_if_available();
652                    // No signalling while resuming an R error or exiting handler.
653                    // Conditions from the abandoned call must not survive it.
654                    crate::deferred_condition::discard(deferred_mark);
655                    boundary.leave();
656                    // Continue R's unwind (diverges, never returns)
657                    R_ContinueUnwind(token);
658                } else {
659                    // Rust panic — drain before returning the payload.
660                    drain_log_queue_if_available();
661                    Err(payload)
662                }
663            }
664        }
665    }
666}
667
668/// Execute a closure with R unwind protection, raising any Rust panic as the R
669/// error a generated wrapper would raise for it.
670///
671/// If the closure panics, the panic is caught and converted to an R error
672/// (longjmp) with `rust_*` class layering. If R raises an error (longjmp), all
673/// Rust RAII resources are properly dropped before R continues unwinding.
674///
675/// **This is NOT the user-facing path for `#[miniextendr]` functions.** That
676/// path is [`with_r_unwind_protect`], which returns a tagged SEXP instead of
677/// longjmping (the macro-generated R wrapper raises the structured condition).
678///
679/// This raising-variant exists for guard sites that have no R wrapper between
680/// them and R's runtime:
681/// - ALTREP `RUnwind` guard callbacks (via the crate-private
682///   `with_r_unwind_protect_sourced`)
683/// - FFI guard tests / benchmarks exercising the raw `R_UnwindProtect` mechanism
684///
685/// In those contexts there is no consumer-side R wrapper to inspect a tagged
686/// SEXP. Panics are routed through `raise_rust_condition_via_stop` so they
687/// still receive `rust_*` class layering (issue #345), the same `kind` and
688/// the same fields as the wrapper's condition (#1768). Trait-ABI shims use a
689/// separate SEXP-returning variant ([`with_r_unwind_protect_shim`]) that
690/// re-panics at the View boundary.
691///
692/// # Arguments
693///
694/// * `f` - The closure to execute
695/// * `call` - Optional R call SEXP for better error messages
696///
697/// Deferred conditions are signalled before the outcome is returned or raised.
698/// Any R objects held by the generic return value must remain rooted during
699/// signalling. Return an [`crate::OwnedProtect`] for a freshly allocated SEXP,
700/// then call its `get()` after this guard returns. ALTREP's SEXP trampolines do
701/// this automatically. An R-origin error discards this call's queued conditions.
702pub fn with_r_unwind_protect_or_raise<F, R>(f: F, call: Option<SEXP>) -> R
703where
704    F: FnOnce() -> R,
705{
706    with_r_unwind_protect_sourced(f, call, crate::panic_telemetry::PanicSource::UnwindProtect)
707}
708
709/// Like [`with_r_unwind_protect_or_raise`], but reports panics with a custom
710/// `PanicSource`.
711///
712/// Used by `guarded_altrep_call` so that panics inside ALTREP callbacks with
713/// `AltrepGuard::RUnwind` are still attributed to `PanicSource::Altrep`.
714///
715/// Every outcome is raised through [`raise_rust_condition_via_stop`], which
716/// hands the tagged value [`with_r_unwind_protect`] would return to the R
717/// helper the generated wrappers call, so the condition is the wrapper's, with
718/// its `kind` (#1768). This works even in ALTREP callback context, where there
719/// is no R wrapper to inspect a tagged SEXP (Approach 3 from the issue-345
720/// plan):
721///
722/// - `RCondition::Error` (`error!()`) — `kind = "error"`, its classes ahead of
723///   the `rust_*` layering, its `data =` fields.
724///
725/// - `RCondition::Conversion` (`arg_error!`) — `kind = "conversion"`, with the
726///   crate-class marker replaced in Rust by the classes `miniextendr_init!`
727///   registered: no generated R is there to resolve it.
728///
729/// - A generic panic — `kind = "panic"`, with the `(at file:line)` suffix.
730///
731/// - `Warning`, `Message`, `Condition` — a plain R error with a diagnostic
732///   message and `kind = "panic"`. `warning!()`/`message!()` from ALTREP
733///   context cannot suspend execution for non-fatal signals; documented
734///   limitation.
735pub(crate) fn with_r_unwind_protect_sourced<F, R>(
736    f: F,
737    call: Option<SEXP>,
738    source: crate::panic_telemetry::PanicSource,
739) -> R
740where
741    F: FnOnce() -> R,
742{
743    let deferred_mark = crate::deferred_condition::mark();
744    let outcome = run_r_unwind_protect(f);
745    // Preserve the original panic site before condition handlers can re-enter
746    // Rust and overwrite the panic hook's thread-local location.
747    let panic_message = outcome.as_ref().err().and_then(|payload| {
748        (!payload.is::<crate::condition::RCondition>())
749            .then(|| panic_message_with_location(payload.as_ref()))
750    });
751    let queued = crate::deferred_condition::take_pending(deferred_mark);
752    let (outcome, panic_message) = if queued.is_empty() {
753        (outcome, panic_message)
754    } else {
755        // Move both the outcome and saved panic text INTO this guard: an
756        // exiting R handler must drop all their Rust resources too.
757        // SEXP-bearing outcomes must own their roots.
758        match run_r_unwind_protect(move || {
759            unsafe { crate::deferred_condition::signal_now(queued, call) };
760            (outcome, panic_message)
761        }) {
762            Ok(outcome) => outcome,
763            Err(payload) => (Err(payload), None),
764        }
765    };
766    match outcome {
767        Ok(result) => result,
768        Err(payload) => {
769            // region: RCondition recognition for the raising-variant path
770            if payload.is::<crate::condition::RCondition>() {
771                // Take ownership so the payload's parts move into the tagged
772                // value without cloning — same idiom as `with_r_unwind_protect_shim`.
773                let cond = *payload
774                    .downcast::<crate::condition::RCondition>()
775                    .expect("checked is::<RCondition> above");
776                let error_kind = #[allow(non_exhaustive_omitted_patterns)] match cond {
    crate::condition::RCondition::Error { .. } |
        crate::condition::RCondition::Conversion { .. } => true,
    _ => false,
}matches!(
777                    cond,
778                    crate::condition::RCondition::Error { .. }
779                        | crate::condition::RCondition::Conversion { .. }
780                );
781                // The kind is the one the tagged path writes for this payload.
782                let (kind, mut parts) = cond.into_parts();
783                if error_kind {
784                    // Approach 3 (issue-345): the helper the wrappers use raises
785                    // the value, so `tryCatch(rust_error = h, ...)`,
786                    // `tryCatch(my_class = h, ...)`, `e$kind` and the `data`
787                    // fields (issue #996 path 2) all match the wrapper's
788                    // condition. That copy of the helper cannot resolve an
789                    // `arg_error!`'s class marker (#1740): Rust puts the
790                    // package's registered classes in its place.
791                    parts.class = crate::condition::resolve_conversion_error_class_marker(
792                        parts.class,
793                        crate::condition::crate_conversion_error_class(),
794                    );
795                    crate::panic_telemetry::fire(&parts.message, source);
796                    unsafe {
797                        raise_rust_condition_via_stop(
798                            move || crate::error_value::condition_parts_value(kind, parts, call),
799                            call,
800                        )
801                    }
802                } else {
803                    // warning!/message!/condition! cannot be cleanly raised from an ALTREP
804                    // or connection callback (no mechanism to suspend execution for
805                    // non-fatal signals).
806                    // Documented degradation: a plain R error with a fixed diagnostic,
807                    // raised like the generic-panic branch below (`kind = "panic"`,
808                    // `rust_error` class layering, issue #366): an error reporting the
809                    // original kind would claim to be a warning. The classes and data
810                    // fields are dropped along with the message; the call choice is
811                    // kept (`call = none` drops the guard's call).
812                    let call = parts.call.apply(call);
813                    drop(parts);
814                    let msg = "warning!/message!/condition! from an ALTREP or connection \
815                               callback context cannot be raised as non-fatal signals; use \
816                               error!() instead. This context has no R wrapper to handle \
817                               signal restart.";
818                    crate::panic_telemetry::fire(msg, source);
819                    unsafe {
820                        raise_rust_condition_via_stop(|| panic_condition_value(msg, call), call)
821                    }
822                }
823            } else {
824                // Generic panic — no class layering, plain error string plus the
825                // `(at file:line)` suffix folded from the panic hook (this branch
826                // runs on the panicking thread for the ALTREP/FFI-guard path).
827                // Fire telemetry and raise via Approach 3 with rust_error class so
828                // tryCatch(rust_error = h, ...) matches even for plain panics.
829                let msg =
830                    panic_message.unwrap_or_else(|| panic_message_with_location(payload.as_ref()));
831                // The raise longjmps over this frame: free the payload first.
832                drop(payload);
833                crate::panic_telemetry::fire(&msg, source);
834                unsafe {
835                    raise_rust_condition_via_stop(move || panic_condition_value(&msg, call), call)
836                }
837            }
838            // endregion
839        }
840    }
841}
842
843/// Like [`with_r_unwind_protect`], but tailored for trait-ABI vtable shims.
844///
845/// Same tagged-SEXP behaviour as [`with_r_unwind_protect`], but intended for
846/// shim functions that have no R wrapper of their own. The tagged SEXP is
847/// returned to the View method wrapper, which calls
848/// [`crate::condition::repanic_if_rust_error`] to re-panic with the
849/// reconstructed [`enum@crate::condition::RCondition`]. The outer
850/// `with_r_unwind_protect` in the consumer's C entry point then catches the
851/// re-panic and builds the final tagged SEXP for the consumer's R wrapper.
852///
853/// R-origin errors (longjmp) still pass through via `R_ContinueUnwind` — the
854/// outer guard will catch them.
855///
856/// An `arg_error!` raised by the implementation gets the implementing
857/// package's `conversion_error_class` here, in place of its class marker, as
858/// the shim's own conversion failures do
859/// ([`crate::trait_abi::conversion_error_class`]): the consumer's R helper
860/// would otherwise fill in the consumer's.
861///
862/// # PROTECT note
863///
864/// The returned SEXP is unprotected. The View method wrapper must not call any
865/// R API functions between receiving it and passing it to
866/// `repanic_if_rust_error`. `repanic_if_rust_error` reads the message/kind/class
867/// strings immediately and then panics (or returns), so the SEXP does not need
868/// protection beyond that window.
869pub fn with_r_unwind_protect_shim<F>(f: F) -> SEXP
870where
871    F: FnOnce() -> SEXP,
872{
873    // Conditions queued with `defer_warning` & co. inside the shim are signalled
874    // at this boundary: the consumer's queue is a different static (every
875    // package links its own copy of this crate), so nothing may be left behind.
876    let deferred_mark = crate::deferred_condition::mark();
877    let result = match run_r_unwind_protect(f) {
878        Ok(result) => result,
879        Err(payload) => {
880            // region: RCondition recognition — same as the tagged-SEXP path
881            if payload.is::<crate::condition::RCondition>() {
882                // Take ownership of the payload so the `data` Vec can be moved
883                // into `make_rust_condition_value` (consumed when materialised).
884                // A call-less payload writes the "no call" marker, which
885                // `from_tagged_sexp` reads back on the consumer's side.
886                let cond = *payload
887                    .downcast::<crate::condition::RCondition>()
888                    .expect("checked is::<RCondition> above");
889                let (kind, mut parts) = cond.into_parts();
890                // An `arg_error!` in the implementation takes the implementing
891                // package's classes, as from its own `.Call` wrapper: this
892                // copy of the crate is that package's, while the consumer's R
893                // helper would put the consumer's in place of the marker.
894                parts.class = crate::condition::resolve_conversion_error_class_marker(
895                    parts.class,
896                    crate::condition::crate_conversion_error_class(),
897                );
898                // SAFETY: on the R main thread inside R_UnwindProtect.
899                unsafe { crate::error_value::condition_parts_value(kind, parts, None) }
900            } else {
901                // Generic panic path — fold the hook-captured `(at file:line)` into
902                // the message (this shim runs on the panicking thread).
903                let msg = panic_message_with_location(payload.as_ref());
904                crate::panic_telemetry::fire(
905                    &msg,
906                    crate::panic_telemetry::PanicSource::UnwindProtect,
907                );
908                // SAFETY: on the R main thread inside R_UnwindProtect.
909                unsafe {
910                    crate::error_value::make_rust_condition_value(
911                        &msg,
912                        crate::error_value::kind::PANIC,
913                        None,
914                        None,
915                    )
916                }
917            }
918            // endregion
919        }
920    };
921    // SAFETY: vtable shims run on R's main thread, inside the consumer's `.Call`.
922    unsafe { crate::deferred_condition::finish(deferred_mark, result, None) }
923}
924
925/// Run a closure under `R_UnwindProtect`, returning a tagged condition SEXP on
926/// Rust panics instead of raising an R error.
927///
928/// This is **the** transport for all `#[miniextendr]` functions and methods.
929/// The returned error/condition SEXP is inspected by the generated R wrapper
930/// which raises a proper R condition past the Rust boundary, with `rust_*`
931/// class layering.
932///
933/// Recognises [`enum@crate::condition::RCondition`] payloads (from `error!()`,
934/// `warning!()`, `message!()`, `condition!()`) before falling through to the
935/// generic panic→string path.
936///
937/// R-origin errors (longjmp) still pass through via `R_ContinueUnwind`.
938///
939/// For guard sites that have no R wrapper to inspect a tagged SEXP (ALTREP
940/// `RUnwind` callbacks, FFI guard tests) see [`with_r_unwind_protect_or_raise`];
941/// for trait-ABI vtable shims see [`with_r_unwind_protect_shim`].
942pub fn with_r_unwind_protect<F>(f: F, call: Option<SEXP>) -> SEXP
943where
944    F: FnOnce() -> SEXP,
945{
946    match run_r_unwind_protect(f) {
947        Ok(result) => result,
948        Err(payload) => {
949            // region: RCondition recognition — must come before generic panic path
950            if payload.is::<crate::condition::RCondition>() {
951                // Take ownership so the `data` payload can be moved into
952                // `make_rust_condition_value` (consumed during materialisation).
953                let cond = *payload
954                    .downcast::<crate::condition::RCondition>()
955                    .expect("checked is::<RCondition> above");
956                // No panic telemetry for user-raised conditions — they are intentional.
957                // SAFETY: on the R main thread inside R_UnwindProtect.
958                return unsafe { crate::error_value::rust_condition_value(cond, call) };
959            }
960            // endregion
961
962            // Generic panic path — the primary user-facing route for
963            // `#[miniextendr]` fns running on the main thread. Fold the
964            // hook-captured `(at file:line)` into the message. (The RCondition
965            // branch above is deliberately untouched: error!/warning!/message!/
966            // condition! and Err/None carry no location suffix.)
967            let msg = panic_message_with_location(payload.as_ref());
968            crate::panic_telemetry::fire(&msg, crate::panic_telemetry::PanicSource::UnwindProtect);
969            // SAFETY: on the R main thread inside R_UnwindProtect.
970            unsafe {
971                crate::error_value::make_rust_condition_value(
972                    &msg,
973                    crate::error_value::kind::PANIC,
974                    None,
975                    call,
976                )
977            }
978        }
979    }
980}