use std::ffi::c_void;
use std::marker::PhantomData;
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result};
use crate::DynLib;
use crate::helpers::display_symbol;
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AbiDynFatPtr {
pub data: *const c_void,
pub vtable: *const c_void,
}
impl AbiDynFatPtr {
pub const fn null() -> Self {
Self {
data: std::ptr::null(),
vtable: std::ptr::null(),
}
}
pub fn is_null(self) -> bool {
self.data.is_null() || self.vtable.is_null()
}
}
unsafe impl Send for AbiDynFatPtr {}
unsafe impl Sync for AbiDynFatPtr {}
pub type RetainFn = unsafe extern "C" fn(AbiDynFatPtr);
pub type ReleaseFn = unsafe extern "C" fn(AbiDynFatPtr);
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct AbiStableDynRef {
pub object: AbiDynFatPtr,
pub retain: RetainFn,
pub release: ReleaseFn,
}
impl AbiStableDynRef {
pub const fn null() -> Self {
Self {
object: AbiDynFatPtr::null(),
retain: retain_noop,
release: release_noop,
}
}
pub fn is_null(self) -> bool {
self.object.is_null()
}
}
unsafe impl Send for AbiStableDynRef {}
unsafe impl Sync for AbiStableDynRef {}
unsafe extern "C" fn retain_noop(_: AbiDynFatPtr) {}
unsafe extern "C" fn release_noop(_: AbiDynFatPtr) {}
pub unsafe fn pack_fat_ptr<T: ?Sized>(ptr: *const T) -> AbiDynFatPtr {
unsafe { std::mem::transmute_copy(&ptr) }
}
pub unsafe fn unpack_fat_ptr<T: ?Sized>(ptr: AbiDynFatPtr) -> *const T {
unsafe { std::mem::transmute_copy(&ptr) }
}
unsafe extern "C" fn retain_arc<T: ?Sized>(ptr: AbiDynFatPtr) {
let raw: *const T = unsafe { unpack_fat_ptr(ptr) };
unsafe { Arc::increment_strong_count(raw) };
}
unsafe extern "C" fn release_arc<T: ?Sized>(ptr: AbiDynFatPtr) {
let raw: *const T = unsafe { unpack_fat_ptr(ptr) };
unsafe { drop(Arc::from_raw(raw)) };
}
#[repr(transparent)]
pub struct SafeArcDyn<T: ?Sized> {
raw: AbiStableDynRef,
_marker: PhantomData<*const T>,
}
impl<T: ?Sized> SafeArcDyn<T> {
pub fn from_arc(value: Arc<T>) -> Self {
let raw = Arc::into_raw(value);
Self {
raw: AbiStableDynRef {
object: unsafe { pack_fat_ptr(raw) },
retain: retain_arc::<T>,
release: release_arc::<T>,
},
_marker: PhantomData,
}
}
pub fn into_abi(self) -> AbiStableDynRef {
let raw = self.raw;
std::mem::forget(self); raw
}
pub unsafe fn from_abi(raw: AbiStableDynRef) -> Self {
Self {
raw,
_marker: PhantomData,
}
}
pub unsafe fn trait_ref(&self) -> &T {
unsafe { &*unpack_fat_ptr::<T>(self.raw.object) }
}
}
unsafe impl<T: ?Sized + Send> Send for SafeArcDyn<T> {}
unsafe impl<T: ?Sized + Sync> Sync for SafeArcDyn<T> {}
impl<T: ?Sized> Clone for SafeArcDyn<T> {
fn clone(&self) -> Self {
unsafe { (self.raw.retain)(self.raw.object) };
Self {
raw: self.raw,
_marker: PhantomData,
}
}
}
impl<T: ?Sized> Drop for SafeArcDyn<T> {
fn drop(&mut self) {
unsafe { (self.raw.release)(self.raw.object) };
}
}
pub struct DynPlugin<T: ?Sized> {
_lib: DynLib,
plugin: SafeArcDyn<T>,
}
pub type PluginEntryPoint = unsafe extern "C" fn() -> AbiStableDynRef;
impl<T: ?Sized> DynPlugin<T> {
pub unsafe fn load(path: &Path, entry_symbol: &[u8]) -> Result<Self> {
let lib = unsafe { DynLib::load(path) }?;
unsafe { Self::from_lib(lib, entry_symbol) }
}
pub unsafe fn from_lib(lib: DynLib, entry_symbol: &[u8]) -> Result<Self> {
let entry: PluginEntryPoint = unsafe { lib.symbol(entry_symbol) }
.with_context(|| format!("entry point '{}' not found", display_symbol(entry_symbol)))?;
let abi_ref = unsafe { entry() };
if abi_ref.is_null() {
anyhow::bail!("entry point returned null AbiStableDynRef");
}
let plugin = unsafe { SafeArcDyn::<T>::from_abi(abi_ref) };
Ok(Self { _lib: lib, plugin })
}
pub fn trait_ref(&self) -> &T {
unsafe { self.plugin.trait_ref() }
}
pub fn clone_handle(&self) -> SafeArcDyn<T> {
self.plugin.clone()
}
}
unsafe impl<T: ?Sized + Send> Send for DynPlugin<T> {}
unsafe impl<T: ?Sized + Sync> Sync for DynPlugin<T> {}
#[cfg(test)]
mod tests {
use super::*;
trait Demo: Send + Sync {
fn value(&self) -> i32;
}
struct DemoValue(i32);
impl Demo for DemoValue {
fn value(&self) -> i32 {
self.0
}
}
#[test]
fn safe_arc_dyn_round_trip() {
let arc: Arc<dyn Demo> = Arc::new(DemoValue(42));
let wrapped = SafeArcDyn::from_arc(arc);
let abi = wrapped.into_abi();
let restored = unsafe { SafeArcDyn::<dyn Demo>::from_abi(abi) };
assert_eq!(unsafe { restored.trait_ref() }.value(), 42);
}
#[test]
fn safe_arc_dyn_clone() {
let arc: Arc<dyn Demo> = Arc::new(DemoValue(7));
let wrapped = SafeArcDyn::from_arc(arc);
let cloned = wrapped.clone();
assert_eq!(unsafe { wrapped.trait_ref() }.value(), 7);
assert_eq!(unsafe { cloned.trait_ref() }.value(), 7);
drop(wrapped);
assert_eq!(unsafe { cloned.trait_ref() }.value(), 7);
}
}