1//! Provide limited protection for multithreaded access to the R API.
2use crate::*;
3use extendr_ffi::{
4 R_MakeUnwindCont, R_UnwindProtect, Rboolean, Rf_error, Rf_protect, Rf_unprotect,
5};
6use std::cell::Cell;
7use std::sync::Mutex;
89/// A global lock, that should represent the global lock on the R-API.
10/// It is not tied to an actual instance of R.
11static R_API_LOCK: Mutex<()> = Mutex::new(());
1213thread_local! {
14static THREAD_HAS_LOCK: Cell<bool> = Cell::new(false);
15}
1617/// Run `f` while ensuring that `f` runs in a single-threaded manner.
18///
19/// This is intended for single-threaded access of the R's C-API.
20/// It is possible to have nested calls of `single_threaded` without deadlocking.
21///
22/// Note: This will fail badly if the called function `f` panics or calls `Rf_error`.
23pub fn single_threaded<F, R>(f: F) -> R
24where
25F: FnOnce() -> R,
26{
27let has_lock = THREAD_HAS_LOCK.with(|x| x.get());
2829// acquire R-API lock
30let _guard = if !has_lock {
31Some(R_API_LOCK.lock().unwrap())
32 } else {
33None
34};
3536// this thread now has the lock
37THREAD_HAS_LOCK.with(|x| x.set(true));
3839let result = f();
4041// release the R-API lock
42if _guard.is_some() {
43 THREAD_HAS_LOCK.with(|x| x.set(false));
44 }
4546 result
47}
4849/// This function is used by the wrapper logic to catch
50/// panics on return.
51///
52#[doc(hidden)]
53pub fn handle_panic<F, R>(err_str: &str, f: F) -> R
54where
55F: FnOnce() -> R,
56 F: std::panic::UnwindSafe,
57{
58match std::panic::catch_unwind(f) {
59Ok(res) => res,
60Err(_) => {
61let err_str = CString::new(err_str).unwrap();
62unsafe { Rf_error(err_str.as_ptr()) }
63 }
64 }
65}
6667static mut R_ERROR_BUF: Option<std::ffi::CString> = None;
6869pub fn throw_r_error<S: AsRef<str>>(s: S) -> ! {
70let s = s.as_ref();
71unsafe {
72 R_ERROR_BUF = Some(std::ffi::CString::new(s).unwrap());
73 Rf_error(R_ERROR_BUF.as_ref().unwrap().as_ptr());
74 };
75}
7677/// Wrap an R function such as `Rf_findFunction` and convert errors and panics into results.
78/// ```ignore
79/// use extendr_api::prelude::*;
80/// test! {
81/// let res = catch_r_error(|| unsafe {
82/// throw_r_error("bad things!");
83/// std::ptr::null_mut()
84/// });
85/// assert_eq!(res.is_ok(), false);
86/// }
87/// ```
88pub fn catch_r_error<F>(f: F) -> Result<SEXP>
89where
90F: FnOnce() -> SEXP + Copy,
91 F: std::panic::UnwindSafe,
92{
93use std::os::raw;
9495unsafe extern "C" fn do_call<F>(data: *mut raw::c_void) -> SEXP
96where
97F: FnOnce() -> SEXP + Copy,
98 {
99let data = data as *const ();
100let f: &F = &*(data as *const F);
101 f()
102 }
103104unsafe extern "C" fn do_cleanup(_: *mut raw::c_void, jump: Rboolean) {
105if jump != Rboolean::FALSE {
106panic!("R has thrown an error.");
107 }
108 }
109110 single_threaded(|| unsafe {
111let fun_ptr = do_call::<F> as *const ();
112let clean_ptr = do_cleanup as *const ();
113let x = false;
114let fun = std::mem::transmute(fun_ptr);
115let cleanfun = std::mem::transmute(clean_ptr);
116let data = &f as *const _ as _;
117let cleandata = &x as *const _ as _;
118let cont = R_MakeUnwindCont();
119 Rf_protect(cont);
120121// Note that catch_unwind does not work for 32 bit windows targets.
122let res = match std::panic::catch_unwind(|| {
123 R_UnwindProtect(fun, data, cleanfun, cleandata, cont)
124 }) {
125Ok(res) => Ok(res),
126Err(_) => Err("Error in protected R code".into()),
127 };
128 Rf_unprotect(1);
129 res
130 })
131}