dyn-loader 0.3.0

Dynamic library loader with dyn-fat-pointer-bridge for loading trait objects from .so/.dylib plugins. IMPORTANT: strictly align the Rust compiler version across all libs and executables to guarantee ABI compatibility.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! # cdyn — COM-style C function-table loading (ABI-stable)
//!
//! Load Copy-sized vtable/descriptor structs from dynamic libraries using
//! plain C function tables — no Rust trait objects, no named-based access,
//! purely positional dispatch. This is the COM+-like emulated vtable system
//! (formerly the separate `cdyn-loader` crate).
//!
//! Unlike [`crate::dyn_mod`], this mode is ABI-stable across languages:
//! the C++ SDK (`cdyn-loader-sdks/cpp`) and Zig SDK (`cdyn-loader-sdks/zig`)
//! build plugins that match these layouts exactly.
//!
//! ## Usage
//!
//! ```ignore
//! #[repr(C)]
//! struct MyVtable {
//!     add: unsafe extern "C" fn(i32, i32) -> i32,
//!     name: unsafe extern "C" fn() -> *const std::ffi::c_char,
//! }
//!
//! let plugin = unsafe { VTablePlugin::<MyVtable>::load("libmy.so", b"my_get_vtable\0")? };
//! let n = unsafe { (plugin.vtable().add)(1, 2) };
//! ```

use std::ffi::c_char;
use std::marker::PhantomData;
use std::path::Path;

use anyhow::{Context, Result};

use crate::DynLib;
use crate::dyn_mod::{AbiStableDynRef, PluginEntryPoint};

// ---------------------------------------------------------------------------
// VTablePlugin — simpler vtable-based loading (Copy types only)
// ---------------------------------------------------------------------------

/// Load a Copy-sized vtable/descriptor struct from a dynamic library.
pub struct VTablePlugin<T: Copy> {
    _lib: DynLib,
    vtable: T,
}

impl<T: Copy> VTablePlugin<T> {
    /// Load a vtable struct from a dynamic library.
    ///
    /// # Safety
    ///
    /// - The target file must be a valid dynamic library.
    /// - The symbol must refer to a static vtable-compatible value of type `T`.
    pub unsafe fn load(path: &Path, symbol: &[u8]) -> Result<Self> {
        let lib = unsafe { DynLib::load(path) }?;
        unsafe { Self::from_lib(lib, symbol) }
    }

    /// # Safety
    ///
    /// The symbol must refer to a static vtable-compatible value of type `T`.
    pub unsafe fn from_lib(lib: DynLib, symbol: &[u8]) -> Result<Self> {
        let getter: unsafe extern "C" fn() -> *const T = unsafe { lib.symbol(symbol) }?;
        let vtable = unsafe { getter() };
        let vtable = unsafe { vtable.as_ref() }
            .copied()
            .ok_or_else(|| anyhow::anyhow!("vtable getter returned null"))?;
        Ok(Self { _lib: lib, vtable })
    }

    pub fn vtable(&self) -> &T {
        &self.vtable
    }
}

// ---------------------------------------------------------------------------
// C++ math module VTable ABI — matches cpp/math_module/include/math_vtable.h
// ---------------------------------------------------------------------------

/// Opaque handle for a C++ MathSession
pub type MathSession = *mut std::ffi::c_void;

/// Descriptor for a generated math function (matches C++ GeneratedFunction)
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GeneratedFunction {
    pub name: *const c_char,
    pub signature: *const c_char,
    pub arg_count: u32,
    pub id: u32,
}

/// Vtable struct matching C++ MathModuleVtable layout exactly
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct MathModuleVtable {
    // Session lifecycle
    pub create_session: unsafe extern "C" fn() -> MathSession,
    pub destroy_session: unsafe extern "C" fn(MathSession),

    // Math operations (lazy — only "generated" if called)
    pub add_i32: unsafe extern "C" fn(MathSession, i32, i32) -> i32,
    pub add_i64: unsafe extern "C" fn(MathSession, i64, i64) -> i64,
    pub add_f64: unsafe extern "C" fn(MathSession, f64, f64) -> f64,
    pub mul_i32: unsafe extern "C" fn(MathSession, i32, i32) -> i32,
    pub mul_f64: unsafe extern "C" fn(MathSession, f64, f64) -> f64,
    pub pi: unsafe extern "C" fn(MathSession) -> f64,
    pub tau: unsafe extern "C" fn(MathSession) -> f64,

    // Code-generation introspection
    pub generated_count: unsafe extern "C" fn(MathSession) -> u32,
    pub generated_at: unsafe extern "C" fn(MathSession, u32) -> GeneratedFunction,

    // Module info
    pub module_name: unsafe extern "C" fn() -> *const c_char,
    pub module_version: unsafe extern "C" fn() -> u32,
}

// SAFETY: MathModuleVtable contains only function pointers and is safe to Send/Sync
unsafe impl Send for MathModuleVtable {}
unsafe impl Sync for MathModuleVtable {}

#[cfg(test)]
mod cdyn_handle_tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    // A minimal "foreign-style" plugin simulated in-process:
    // static instance + atomic ref-count + vtable of thunks — exactly the
    // pattern the C++ CdynExposed / Zig CdynPlugin generate.
    static INSTANCE: u64 = 0xdead_beef;
    static REFCOUNT: AtomicU32 = AtomicU32::new(0);

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct TestVtable {
        get_value: unsafe extern "C" fn(ctx: *mut std::ffi::c_void) -> u64,
    }

    unsafe extern "C" fn test_get_value(ctx: *mut std::ffi::c_void) -> u64 {
        // simulate thunk: ctx -> instance
        let _ = ctx;
        INSTANCE
    }

    unsafe extern "C" fn test_retain(_: AbiStableDynRef__FatPtr) {
        REFCOUNT.fetch_add(1, Ordering::SeqCst);
    }

    unsafe extern "C" fn test_release(_: AbiStableDynRef__FatPtr) {
        let prev = REFCOUNT.fetch_sub(1, Ordering::SeqCst);
        assert!(prev > 0, "release called more times than retain");
    }

    // alias so the fns match the RetainFn/ReleaseFn signatures
    type AbiStableDynRef__FatPtr = crate::dyn_mod::AbiDynFatPtr;

    static TEST_VTABLE: TestVtable = TestVtable { get_value: test_get_value };

    #[test]
    fn cdyn_handle_retain_release_roundtrip() {
        REFCOUNT.store(1, Ordering::SeqCst); // plugin starts with 1 ref

        let raw = AbiStableDynRef {
            object: crate::dyn_mod::AbiDynFatPtr {
                data: &INSTANCE as *const u64 as *const std::ffi::c_void,
                vtable: &TEST_VTABLE as *const TestVtable as *const std::ffi::c_void,
            },
            retain: test_retain,
            release: test_release,
        };

        // from_raw (unowned lib)
        let h1 = unsafe { CdynHandle::<TestVtable>::from_raw(raw) };
        assert_eq!(REFCOUNT.load(Ordering::SeqCst), 1);

        // clone → retain
        let h2 = h1.clone();
        assert_eq!(REFCOUNT.load(Ordering::SeqCst), 2);

        // vtable call through the handle
        unsafe {
            let vt = h1.vtable();
            assert_eq!((vt.get_value)(h1.ctx()), INSTANCE);
        }
        // same vtable pointer via h2
        assert_eq!(h1.as_raw().object.vtable, h2.as_raw().object.vtable);

        // drop → release
        drop(h2);
        assert_eq!(REFCOUNT.load(Ordering::SeqCst), 1);
        drop(h1);
        assert_eq!(REFCOUNT.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn cdyn_handle_into_raw_skips_release() {
        REFCOUNT.store(1, Ordering::SeqCst);
        let raw = AbiStableDynRef {
            object: crate::dyn_mod::AbiDynFatPtr {
                data: &INSTANCE as *const u64 as *const std::ffi::c_void,
                vtable: &TEST_VTABLE as *const TestVtable as *const std::ffi::c_void,
            },
            retain: test_retain,
            release: test_release,
        };
        let h = unsafe { CdynHandle::<TestVtable>::from_raw(raw) };
        let raw2 = h.into_raw(); // must NOT call release
        drop(raw2); // plain Copy struct, no Drop
        assert_eq!(REFCOUNT.load(Ordering::SeqCst), 1); // unchanged
        // give the ref back to the "plugin" to balance counts
        REFCOUNT.fetch_sub(1, Ordering::SeqCst);
    }
}

// ---------------------------------------------------------------------------
// CdynHandle — cross-language ref-counted smart handle
// ---------------------------------------------------------------------------

/// Ref-counted handle to a **foreign** plugin object exposed through a
/// `*_get_dyn` style entry point returning an [`AbiStableDynRef`].
///
/// This is the Rust-side counterpart of the C++ SDK's `CdynExposed` /
/// `CdynPlugin` and the Zig SDK's `CdynPlugin(PluginType)`:
///
/// - [`clone`](Clone::clone) → calls the plugin's `retain`
/// - [`drop`](Drop) → calls the plugin's `release`
/// - [`ctx`](Self::ctx) → the instance pointer (first arg of every vtable method)
/// - [`vtable`](Self::vtable) → `&T` reconstructed from the packed vtable pointer
///
/// `T` is the C-layout vtable struct (`#[repr(C)]`, `Copy`) — e.g.
/// [`MathModuleVtable`] or your own. The vtable is **not** copied; it is
/// referenced through the pointer packed inside the dyn ref (it points into
/// the plugin's static storage, valid while the library stays loaded).
///
/// # Example
///
/// ```ignore
/// // C++ plugin built with: CDYN_EXPOSE_CLASS(MathPlugin, MathModuleVtable, math)
/// // exports: math_get_vtable() and math_get_dyn()
/// let handle = unsafe { CdynHandle::<MathModuleVtable>::load(&path, b"math_get_dyn\0")? };
/// let vt = unsafe { handle.vtable() };
/// let session = unsafe { (vt.create_session)() };
/// let sum = unsafe { (vt.add_i32)(session, 1, 2) };
/// unsafe { (vt.destroy_session)(session) };
/// // handle drop → plugin release()
/// ```
pub struct CdynHandle<T: Copy> {
    _lib: DynLib,
    raw: AbiStableDynRef,
    _marker: PhantomData<T>,
}

impl<T: Copy> CdynHandle<T> {
    /// Load a foreign plugin object via its dyn entry point.
    ///
    /// # Safety
    ///
    /// - The target file must be a valid dynamic library.
    /// - The entry must return a valid `AbiStableDynRef` whose vtable pointer
    ///   refers to a `T`-layout vtable.
    pub unsafe fn load(path: &Path, dyn_entry: &[u8]) -> Result<Self> {
        let lib = unsafe { DynLib::load(path) }?;
        unsafe { Self::from_lib(lib, dyn_entry) }
    }

    /// Load from an already-loaded library.
    ///
    /// # Safety
    ///
    /// The entry must return a valid `AbiStableDynRef` whose vtable pointer
    /// refers to a `T`-layout vtable.
    pub unsafe fn from_lib(lib: DynLib, dyn_entry: &[u8]) -> Result<Self> {
        let entry: PluginDynEntryPoint =
            unsafe { lib.symbol(dyn_entry) }.with_context(|| {
                format!("dyn entry '{}' not found", crate::helpers::display_symbol(dyn_entry))
            })?;
        let raw = unsafe { entry() };
        if raw.is_null() {
            anyhow::bail!("dyn entry returned null AbiStableDynRef");
        }
        Ok(Self {
            _lib: lib,
            raw,
            _marker: PhantomData,
        })
    }

    /// Reconstruct from a raw [`AbiStableDynRef`] obtained elsewhere.
    ///
    /// The handle does not own the originating library; the caller must keep
    /// it loaded (e.g. hold another [`DynPlugin`](crate::DynPlugin) or
    /// [`DynLib`](crate::DynLib)) for as long as this handle lives.
    ///
    /// # Safety
    ///
    /// `raw` must be a live ref produced by a compatible plugin.
    pub unsafe fn from_raw(raw: AbiStableDynRef) -> Self {
        Self {
            _lib: DynLib::unowned(),
            raw,
            _marker: PhantomData,
        }
    }

    /// Instance context pointer — pass as the first argument of vtable methods.
    pub fn ctx(&self) -> *mut std::ffi::c_void {
        self.raw.object.data as *mut std::ffi::c_void
    }

    /// The vtable, reconstructed from the pointer packed inside the dyn ref.
    ///
    /// # Safety
    ///
    /// `T` must be the exact vtable type the plugin used when building the ref.
    pub unsafe fn vtable(&self) -> &T {
        unsafe { &*(self.raw.object.vtable as *const T) }
    }

    /// Raw ABI ref (for passing back across the boundary).
    pub fn as_raw(&self) -> &AbiStableDynRef {
        &self.raw
    }

    /// Consume without calling `release` (ownership handed back to the plugin).
    pub fn into_raw(self) -> AbiStableDynRef {
        let mut this = std::mem::ManuallyDrop::new(self);
        // Detach the library handle so Drop won't run for it either.
        let lib = unsafe { std::ptr::read(&this._lib) };
        std::mem::forget(lib);
        this.raw
    }
}

/// Type of the dyn entry point that foreign plugins export
/// (C++ `CDYN_EXPORT AbiStableDynRef name_get_dyn()`, Zig `declareDynEntry`).
pub type PluginDynEntryPoint = PluginEntryPoint;

// SAFETY: CdynHandle manages the plugin's own ref-count via retain/release;
// thread-safety follows the plugin's guarantees (same policy as SafeArcDyn).
unsafe impl<T: Copy + Send> Send for CdynHandle<T> {}
unsafe impl<T: Copy + Sync> Sync for CdynHandle<T> {}

impl<T: Copy> Clone for CdynHandle<T> {
    fn clone(&self) -> Self {
        unsafe { (self.raw.retain)(self.raw.object) };
        Self {
            _lib: self._lib.clone(),
            raw: self.raw,
            _marker: PhantomData,
        }
    }
}

impl<T: Copy> Drop for CdynHandle<T> {
    fn drop(&mut self) {
        unsafe { (self.raw.release)(self.raw.object) };
    }
}

#[cfg(test)]
mod cpp_math_tests {
    use super::*;
    use std::ffi::CStr;
    use std::path::PathBuf;

    fn math_module_path() -> PathBuf {
        // Relative from crate root (rust/crates/dyn-loader) to cpp build output
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.push("../../cpp/build/math_module");
        p.push("libmath_module.so");
        p
    }

    #[test]
    fn load_cpp_math_module_via_vtable() {
        let path = math_module_path();
        if !path.exists() {
            eprintln!("SKIP: {} not found — build cpp/ first", path.display());
            return;
        }

        let plugin =
            unsafe { VTablePlugin::<MathModuleVtable>::load(&path, b"math_module_get_vtable\0") }
                .expect("failed to load math_module");
        let vt = plugin.vtable();

        // Module info
        unsafe {
            let name = CStr::from_ptr((vt.module_name)());
            assert_eq!(name.to_str().unwrap(), "core-ast-math");
            assert_eq!((vt.module_version)(), 1);
        }

        // Create session
        let session = unsafe { (vt.create_session)() };
        assert!(!session.is_null());

        // No functions generated yet
        assert_eq!(unsafe { (vt.generated_count)(session) }, 0);

        // Call add_i32 — marks it as "used"
        let result = unsafe { (vt.add_i32)(session, 10, 20) };
        assert_eq!(result, 30);
        assert_eq!(unsafe { (vt.generated_count)(session) }, 1);

        // Call mul_f64 — marks it as "used"
        let result = unsafe { (vt.mul_f64)(session, 3.0, 7.0) };
        assert!((result - 21.0).abs() < 1e-10);
        assert_eq!(unsafe { (vt.generated_count)(session) }, 2);

        // Call pi
        let pi_val = unsafe { (vt.pi)(session) };
        assert!((pi_val - std::f64::consts::PI).abs() < 1e-10);
        assert_eq!(unsafe { (vt.generated_count)(session) }, 3);

        // Introspect generated functions
        let func0 = unsafe { (vt.generated_at)(session, 0) };
        let func0_name = unsafe { CStr::from_ptr(func0.name) }.to_str().unwrap();
        assert_eq!(func0_name, "add_i32");

        let func1 = unsafe { (vt.generated_at)(session, 1) };
        let func1_name = unsafe { CStr::from_ptr(func1.name) }.to_str().unwrap();
        assert_eq!(func1_name, "mul_f64");

        let func2 = unsafe { (vt.generated_at)(session, 2) };
        let func2_name = unsafe { CStr::from_ptr(func2.name) }.to_str().unwrap();
        assert_eq!(func2_name, "pi");

        // Call add_i32 again — should NOT add duplicate
        let _ = unsafe { (vt.add_i32)(session, 1, 2) };
        assert_eq!(unsafe { (vt.generated_count)(session) }, 3);

        // Destroy session
        unsafe { (vt.destroy_session)(session) };
    }
}