Skip to main content

miniextendr_api/
allocator.rs

1//! R-backed global allocator for Rust.
2//!
3//! Allocations are backed by R RAWSXP objects and protected from GC via
4//! `R_PreserveObject`/`R_ReleaseObject` (R's precious list).
5//!
6//! # Protection Strategy
7//!
8//! This allocator uses `R_PreserveObject` directly because:
9//! - Allocations may need to survive across multiple `.Call` invocations
10//! - The SEXP (RAWSXP) is its own handle — zero Rust-side bookkeeping
11//! - LIFO release pattern (recently allocated = first freed) means O(1) release
12//!   in practice (R's precious list scans from head)
13//!
14//! See the [crate-level documentation](crate#gc-protection-strategies) for an
15//! overview of miniextendr's protection mechanisms.
16//!
17//! # Layout
18//!
19//! Layout inside the RAWSXP (bytes):
20//!   \[optional leading pad\]\[Header\]\[user bytes...\]
21//!
22//! We always return a pointer aligned to at least:
23//!   `max(requested_align, align_of::<Header>())`
24//! so the `Header` placed immediately before the user pointer is always aligned.
25//!
26//! # ⚠️ Warning: longjmp Risk
27//!
28//! R's `Rf_allocVector` can longjmp on allocation failure instead of returning
29//! NULL. If this happens, Rust destructors will NOT run, potentially causing:
30//! - Resource leaks (files, locks, etc.)
31//! - Corrupted state if allocation happens mid-operation
32//!
33//! This allocator is best suited for:
34//! - Short-lived operations within a single R API call
35//! - Contexts where `R_UnwindProtect` is active (e.g., inside a `#[miniextendr]` body)
36//!
37//! For long-lived allocations or critical cleanup requirements, consider using
38//! Rust's standard allocator instead.
39
40use crate::sys::{R_PreserveObject_unchecked, R_ReleaseObject_unchecked};
41use crate::{SEXP, SEXPTYPE, SexpExt, with_r_thread};
42use core::{
43    alloc::{GlobalAlloc, Layout},
44    mem, ptr,
45};
46
47// region: Header and constants
48
49/// Metadata stored immediately before the returned user pointer.
50#[repr(C)]
51#[derive(#[automatically_derived]impl ::core::marker::Copy for Header { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Header {
}
#[automatically_derived]impl ::core::clone::Clone for Header {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<SEXP>;
        *self
    }
}Clone)]
52struct Header {
53    /// The RAWSXP itself, preserved via R_PreserveObject.
54    sexp: SEXP,
55}
56
57const HEADER_SIZE: usize = mem::size_of::<Header>();
58const HEADER_ALIGN: usize = mem::align_of::<Header>();
59// endregion
60
61// region: RAllocator
62
63/// R-backed global allocator.
64///
65/// All allocations are backed by R RAWSXP objects and protected from
66/// garbage collection. The allocator stores metadata before the returned
67/// pointer to enable proper deallocation.
68///
69/// **Note:** This should NOT be used as `#[global_allocator]` in R package
70/// library crates, as it would be invoked during compilation/build time when
71/// R isn't available. Instead, use it explicitly in standalone binaries that
72/// embed R, or use arena-style allocation APIs.
73///
74/// # Thread Safety
75///
76/// This allocator is usable on R's main thread only: every call goes through
77/// [`with_r_thread`], which panics on spawned or Rayon threads.
78#[derive(#[automatically_derived]impl ::core::fmt::Debug for RAllocator {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "RAllocator")
    }
}Debug)]
79pub struct RAllocator;
80
81unsafe impl GlobalAlloc for RAllocator {
82    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
83        with_r_thread(|| unsafe { alloc_main_thread(layout) })
84    }
85
86    unsafe fn dealloc(&self, data: *mut u8, _layout: Layout) {
87        if data.is_null() {
88            return;
89        }
90        with_r_thread(|| unsafe { dealloc_main_thread(data) });
91    }
92
93    unsafe fn realloc(&self, old: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
94        // Handle null input (acts like alloc)
95        if old.is_null() {
96            let Ok(new_layout) = Layout::from_size_align(new_size, layout.align()) else {
97                return ptr::null_mut();
98            };
99            return unsafe { self.alloc(new_layout) };
100        }
101
102        // Handle zero size (acts like dealloc)
103        if new_size == 0 {
104            unsafe { self.dealloc(old, layout) };
105            return ptr::null_mut();
106        }
107
108        with_r_thread(|| unsafe {
109            realloc_main_thread(old, layout.size(), layout.align(), new_size)
110        })
111    }
112
113    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
114        let p = unsafe { self.alloc(layout) };
115        if !p.is_null() {
116            unsafe { ptr::write_bytes(p, 0, layout.size()) };
117        }
118        p
119    }
120}
121// endregion
122
123// region: Main-thread helpers
124
125/// Allocate memory on the R main thread.
126///
127/// # Safety
128///
129/// Must be called from R's main thread.
130unsafe fn alloc_main_thread(layout: Layout) -> *mut u8 {
131    // ZST allocations: return null since we can't meaningfully track them
132    // (dangling pointer would crash in dealloc when we try to read the header)
133    if layout.size() == 0 {
134        return ptr::null_mut();
135    }
136
137    let align = layout.align().max(HEADER_ALIGN);
138
139    // Calculate total size needed with overflow checking
140    let total = {
141        let Some(align_minus_1) = align.checked_sub(1) else {
142            return ptr::null_mut();
143        };
144        let Some(temp) = HEADER_SIZE.checked_add(align_minus_1) else {
145            return ptr::null_mut();
146        };
147        let Some(total) = temp.checked_add(layout.size()) else {
148            return ptr::null_mut();
149        };
150        total
151    };
152
153    let total_isize: isize = match total.try_into() {
154        Ok(n) => n,
155        Err(_) => return ptr::null_mut(),
156    };
157
158    // NOTE: Rf_allocVector can longjmp on failure instead of returning NULL.
159    // Inside a `#[miniextendr]` body, R_UnwindProtect catches it. Outside of
160    // that context, Rust destructors may be skipped.
161    // Use _unchecked since `with_r_thread` checked for R's main thread.
162    // RAWSXP literal is the source of truth (#882): this is an opaque R-managed
163    // byte arena used as a `*mut u8` allocation, not a typed vector — there is no
164    // `T: RNativeType` element to derive the tag from.
165    let sexp = unsafe { crate::sys::Rf_allocVector_unchecked(SEXPTYPE::RAWSXP, total_isize) };
166    if sexp.is_null_ptr() {
167        return ptr::null_mut();
168    }
169
170    // Protect from GC (must stay valid until dealloc()).
171    // Uses R_PreserveObject — LIFO means recently allocated objects are found fast on release.
172    unsafe { R_PreserveObject_unchecked(sexp) };
173
174    // Use _unchecked since we're guaranteed to be on R main thread.
175    let raw_base = unsafe { crate::sys::RAW_unchecked(sexp) }.cast::<u8>();
176
177    // Calculate header and data pointers with alignment
178    let after_header = unsafe { raw_base.add(HEADER_SIZE) };
179    let pad = after_header.align_offset(align);
180    if pad == usize::MAX {
181        // Alignment failed (extremely unlikely)
182        unsafe { R_ReleaseObject_unchecked(sexp) };
183        return ptr::null_mut();
184    }
185
186    let data = unsafe { after_header.add(pad) };
187    let header = unsafe { data.sub(HEADER_SIZE) }.cast::<Header>();
188
189    unsafe { header.write(Header { sexp }) };
190
191    if true {
    {
        match (&data.align_offset(layout.align()), &0) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(data.align_offset(layout.align()), 0);
192    data
193}
194
195/// Deallocate memory on the R main thread.
196///
197/// # Safety
198///
199/// Must be called from R's main thread.
200/// The pointer must have been allocated by this allocator.
201unsafe fn dealloc_main_thread(data: *mut u8) {
202    let header = unsafe { data.sub(HEADER_SIZE) }.cast::<Header>();
203    let sexp = unsafe { (*header).sexp };
204    unsafe { R_ReleaseObject_unchecked(sexp) };
205}
206
207/// Reallocate memory on the R main thread.
208///
209/// # Safety
210///
211/// Must be called from R's main thread.
212/// The old pointer must have been allocated by this allocator.
213unsafe fn realloc_main_thread(
214    old: *mut u8,
215    old_size: usize,
216    align: usize,
217    new_size: usize,
218) -> *mut u8 {
219    // Recover RAWSXP from header (stored directly, no DLL cell indirection).
220    // Use _unchecked since `with_r_thread` checked for R's main thread.
221    let header = unsafe { old.sub(HEADER_SIZE) }.cast::<Header>();
222    let sexp = unsafe { (*header).sexp };
223
224    // Check if existing allocation has capacity
225    let raw_base = unsafe { crate::sys::RAW_unchecked(sexp) }.cast::<u8>();
226    let cap: usize = match unsafe { sexp.xlength_unchecked() }.try_into() {
227        Ok(n) => n,
228        Err(_) => return ptr::null_mut(),
229    };
230
231    let used = unsafe { old.cast_const().offset_from(raw_base.cast_const()) };
232    let Ok(used_usize) = usize::try_from(used) else {
233        // Should be impossible if `old` came from this allocator, but don't UB.
234        return ptr::null_mut();
235    };
236    let available = cap.saturating_sub(used_usize);
237
238    if new_size <= available {
239        return old; // Reuse existing allocation
240    }
241
242    // Need new allocation
243    let Ok(new_layout) = Layout::from_size_align(new_size, align) else {
244        return ptr::null_mut();
245    };
246
247    let new_ptr = unsafe { alloc_main_thread(new_layout) };
248    if new_ptr.is_null() {
249        // On realloc failure, the old allocation must remain valid.
250        return ptr::null_mut();
251    }
252
253    unsafe { ptr::copy_nonoverlapping(old, new_ptr, old_size.min(new_size)) };
254    unsafe { R_ReleaseObject_unchecked(sexp) }; // Free old allocation
255
256    new_ptr
257}
258// endregion