Skip to main content

miniextendr_api/
init.rs

1//! Package initialization for miniextendr R packages.
2//!
3//! [`package_init`] consolidates all initialization steps that were previously
4//! scattered across `entrypoint.c.in`. The `miniextendr_init!` proc macro
5//! generates the `R_init_*` entry point that calls this function.
6//!
7//! # Usage
8//!
9//! In your crate's `lib.rs`:
10//!
11//! ```ignore
12//! miniextendr_init!(mypkg);
13//! ```
14//!
15//! This expands to an `extern "C-unwind" fn R_init_mypkg(dll)` that calls
16//! [`package_init`] with the appropriate package name.
17
18use crate::Rboolean;
19use crate::sys::{DllInfo, R_forceSymbols, R_useDynamicSymbols};
20use std::ffi::CStr;
21
22/// Env var the Makevars wrapper-gen recipe sets before `dyn.load`ing the
23/// freshly-built shared object to generate `R/*-wrappers.R`.
24///
25/// Loading the installed `.so`/`.dll` runs `R_init_<pkg>` on every platform, but
26/// during wrapper-gen that image is `dyn.unload`ed immediately afterwards. So when
27/// this var is present, init takes a minimal path: [`package_init`] skips the
28/// panic hook / locale / ALTREP+mx_abi setup, and [`miniextendr_register_routines`]
29/// skips ALTREP *class* registration — none of which must plant a pointer into an
30/// about-to-be-unloaded image (doing so risks the "malloc unsorted double linked
31/// list" heap corruption that macOS hides but Linux R aborts on).
32///
33/// SINGLE SOURCE OF TRUTH: both read-sites go through [`wrapper_gen_mode`] so the
34/// name can't drift between them. Presence-based — any value (even empty) enables
35/// it — so it MUST NOT leak into a real package-load environment, or the package
36/// loads silently degraded (no panic hook, no ALTREP classes, no mx_abi).
37///
38/// [`miniextendr_register_routines`]: crate::registry::miniextendr_register_routines
39pub(crate) const WRAPPER_GEN_ENV: &str = "MINIEXTENDR_WRAPPER_GEN";
40
41/// `true` when the package was loaded purely for wrapper generation — see
42/// [`WRAPPER_GEN_ENV`].
43pub(crate) fn wrapper_gen_mode() -> bool {
44    std::env::var_os(WRAPPER_GEN_ENV).is_some()
45}
46
47/// Initialize a miniextendr R package.
48///
49/// This performs all initialization steps in the correct order:
50///
51/// 1. Record main thread ID
52/// 2. Enter R unwind protection and install the panic hook
53/// 3. Set ALTREP package name
54/// 4. Register mx_abi C-callables for cross-package trait dispatch
55/// 5. Register all `#[miniextendr]` routines and ALTREP classes
56/// 6. Lock down dynamic symbols
57///
58/// The package loads in any locale: string conversions translate per string
59/// (`from_r::try_charsxp_to_str`).
60///
61/// # Safety
62///
63/// Must be called from R's main thread during `R_init_*`.
64/// `dll` must be a valid pointer provided by R.
65/// `pkg_name` must be a valid null-terminated C string that lives for the
66/// duration of the R session (typically a string literal).
67pub unsafe fn package_init(dll: *mut DllInfo, pkg_name: &CStr) {
68    // The guard's checked R calls need the runtime's main-thread identity.
69    // Runtime initialization is pure Rust; the generated R_init entry point
70    // catches a panic here before it can escape into R.
71    crate::miniextendr_runtime_init();
72
73    crate::unwind_protect::with_r_unwind_protect_or_raise(
74        || unsafe {
75            // When loaded purely for wrapper generation (Makevars dyn.load()s the
76            // installed .so/.dll, which runs this init), skip full init. Only routine
77            // registration is needed so .Call(miniextendr_write_wrappers) works.
78            // See WRAPPER_GEN_ENV. The env var is set by Makevars before dyn.load().
79            let wrapper_gen = wrapper_gen_mode();
80
81            if !wrapper_gen {
82                // 2. Install panic hook for better error messages
83                // Skipped during wrapper-gen: on Windows, set_hook during DLL init
84                // can fail with "failed to initiate panic, error 5" because the
85                // panic infrastructure isn't fully available during DLL loading.
86                crate::backtrace::miniextendr_panic_hook();
87
88                // 2b. Install R console logger (if log feature enabled)
89                #[cfg(feature = "log")]
90                crate::optionals::log_impl::install_r_logger();
91
92                // 3. Set ALTREP package name and DllInfo
93                crate::miniextendr_set_altrep_pkg_name(pkg_name.as_ptr());
94                crate::set_altrep_dll_info(dll);
95
96                // 4. Register mx_abi C-callables
97                crate::mx_abi::mx_abi_register(pkg_name);
98            }
99
100            // 5. Register .Call routines (and ALTREP classes, unless wrapper-gen)
101            crate::registry::miniextendr_register_routines(dll);
102
103            // 6. Lock down dynamic symbols
104            R_useDynamicSymbols(dll, Rboolean::FALSE);
105            R_forceSymbols(dll, Rboolean::TRUE);
106        },
107        None,
108    );
109}