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.
3940use crate::sys::{R_PreserveObject_unchecked, R_ReleaseObject_unchecked};
41use crate::{SEXP, SEXPTYPE, SexpExt, with_r_thread};
42use core::{
43 alloc::{GlobalAlloc, Layout},
44mem, ptr,
45};
4647// region: Header and constants
4849/// 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.
54sexp: SEXP,
55}
5657const HEADER_SIZE: usize = mem::size_of::<Header>();
58const HEADER_ALIGN: usize = mem::align_of::<Header>();
59// endregion
6061// region: RAllocator
6263/// 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;
8081unsafe impl GlobalAllocfor RAllocator {
82unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
83with_r_thread(|| unsafe { alloc_main_thread(layout) })
84 }
8586unsafe fn dealloc(&self, data: *mut u8, _layout: Layout) {
87if data.is_null() {
88return;
89 }
90with_r_thread(|| unsafe { dealloc_main_thread(data) });
91 }
9293unsafe fn realloc(&self, old: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
94// Handle null input (acts like alloc)
95if old.is_null() {
96let Ok(new_layout) = Layout::from_size_align(new_size, layout.align()) else {
97return ptr::null_mut();
98 };
99return unsafe { self.alloc(new_layout) };
100 }
101102// Handle zero size (acts like dealloc)
103if new_size == 0 {
104unsafe { self.dealloc(old, layout) };
105return ptr::null_mut();
106 }
107108with_r_thread(|| unsafe {
109realloc_main_thread(old, layout.size(), layout.align(), new_size)
110 })
111 }
112113unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
114let p = unsafe { self.alloc(layout) };
115if !p.is_null() {
116unsafe { ptr::write_bytes(p, 0, layout.size()) };
117 }
118p119 }
120}
121// endregion
122123// region: Main-thread helpers
124125/// 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)
133if layout.size() == 0 {
134return ptr::null_mut();
135 }
136137let align = layout.align().max(HEADER_ALIGN);
138139// Calculate total size needed with overflow checking
140let total = {
141let Some(align_minus_1) = align.checked_sub(1) else {
142return ptr::null_mut();
143 };
144let Some(temp) = HEADER_SIZE.checked_add(align_minus_1) else {
145return ptr::null_mut();
146 };
147let Some(total) = temp.checked_add(layout.size()) else {
148return ptr::null_mut();
149 };
150total151 };
152153let total_isize: isize = match total.try_into() {
154Ok(n) => n,
155Err(_) => return ptr::null_mut(),
156 };
157158// 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.
165let sexp = unsafe { crate::sys::Rf_allocVector_unchecked(SEXPTYPE::RAWSXP, total_isize) };
166if sexp.is_null_ptr() {
167return ptr::null_mut();
168 }
169170// Protect from GC (must stay valid until dealloc()).
171 // Uses R_PreserveObject — LIFO means recently allocated objects are found fast on release.
172unsafe { R_PreserveObject_unchecked(sexp) };
173174// Use _unchecked since we're guaranteed to be on R main thread.
175let raw_base = unsafe { crate::sys::RAW_unchecked(sexp) }.cast::<u8>();
176177// Calculate header and data pointers with alignment
178let after_header = unsafe { raw_base.add(HEADER_SIZE) };
179let pad = after_header.align_offset(align);
180if pad == usize::MAX {
181// Alignment failed (extremely unlikely)
182unsafe { R_ReleaseObject_unchecked(sexp) };
183return ptr::null_mut();
184 }
185186let data = unsafe { after_header.add(pad) };
187let header = unsafe { data.sub(HEADER_SIZE) }.cast::<Header>();
188189unsafe { header.write(Header { sexp }) };
190191if 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);
192data193}
194195/// 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) {
202let header = unsafe { data.sub(HEADER_SIZE) }.cast::<Header>();
203let sexp = unsafe { (*header).sexp };
204unsafe { R_ReleaseObject_unchecked(sexp) };
205}
206207/// 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.
221let header = unsafe { old.sub(HEADER_SIZE) }.cast::<Header>();
222let sexp = unsafe { (*header).sexp };
223224// Check if existing allocation has capacity
225let raw_base = unsafe { crate::sys::RAW_unchecked(sexp) }.cast::<u8>();
226let cap: usize = match unsafe { sexp.xlength_unchecked() }.try_into() {
227Ok(n) => n,
228Err(_) => return ptr::null_mut(),
229 };
230231let used = unsafe { old.cast_const().offset_from(raw_base.cast_const()) };
232let Ok(used_usize) = usize::try_from(used) else {
233// Should be impossible if `old` came from this allocator, but don't UB.
234return ptr::null_mut();
235 };
236let available = cap.saturating_sub(used_usize);
237238if new_size <= available {
239return old; // Reuse existing allocation
240}
241242// Need new allocation
243let Ok(new_layout) = Layout::from_size_align(new_size, align) else {
244return ptr::null_mut();
245 };
246247let new_ptr = unsafe { alloc_main_thread(new_layout) };
248if new_ptr.is_null() {
249// On realloc failure, the old allocation must remain valid.
250return ptr::null_mut();
251 }
252253unsafe { ptr::copy_nonoverlapping(old, new_ptr, old_size.min(new_size)) };
254unsafe { R_ReleaseObject_unchecked(sexp) }; // Free old allocation
255256new_ptr257}
258// endregion