use crate::{Error, Result, abi};
#[cfg(feature = "alloc")]
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::{
cell::{Cell, UnsafeCell},
ffi::c_void,
};
pub unsafe trait ExportInterface {
type Implementation;
const ID: &'static str;
const VERSION: u32;
const METHODS: &'static [abi::Method];
}
pub unsafe trait UnloadSafe {}
pub trait Factory {
type Object;
fn create() -> Result<Self::Object>;
}
pub struct Object<T> {
busy: Cell<bool>,
poisoned: Cell<bool>,
value: UnsafeCell<T>,
}
impl<T> Object<T> {
pub const fn new(value: T) -> Self {
Self {
busy: Cell::new(false),
poisoned: Cell::new(false),
value: UnsafeCell::new(value),
}
}
}
pub fn check_pointer<T>(ptr: *const T) -> Result<()> {
if ptr.is_null() || !(ptr as usize).is_multiple_of(core::mem::align_of::<T>()) {
Err(Error::InvalidArgument)
} else {
Ok(())
}
}
#[derive(Clone, Copy)]
pub struct Borrow {
pub ptr: *const u8,
pub len: usize,
pub mutable: bool,
}
pub fn validate_borrows(ranges: &[Borrow]) -> Result<()> {
for (i, a) in ranges.iter().enumerate() {
abi::validate_range(a.ptr, a.len)?;
for b in &ranges[..i] {
if a.len != 0
&& b.len != 0
&& (a.mutable || b.mutable)
&& (a.ptr as usize) < (b.ptr as usize) + b.len
&& (b.ptr as usize) < (a.ptr as usize) + a.len
{
return Err(Error::InvalidArgument);
}
}
}
Ok(())
}
pub(crate) fn catch<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
#[cfg(feature = "std")]
{
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(result) => result,
Err(payload) => {
if let Err(nested) =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(payload)))
{
core::mem::forget(nested);
}
Err(Error::Panicked)
}
}
}
#[cfg(not(feature = "std"))]
f()
}
pub fn guard(f: impl FnOnce() -> Result<()>) -> i32 {
catch(f).map_or_else(Error::status, |()| 0)
}
pub unsafe fn with_object<T, R>(
object: *mut c_void,
f: impl FnOnce(&mut T) -> Result<R>,
) -> Result<R> {
let ptr = object.cast::<Object<T>>();
check_pointer(ptr)?;
let object = unsafe { &*ptr };
if object.poisoned.get() {
return Err(Error::Poisoned);
}
if object.busy.replace(true) {
return Err(Error::Busy);
}
struct Reset<'a>(&'a Cell<bool>);
impl Drop for Reset<'_> {
fn drop(&mut self) {
self.0.set(false);
}
}
let _reset = Reset(&object.busy);
let result = catch(|| f(unsafe { &mut *object.value.get() }));
if matches!(result, Err(Error::Panicked)) {
object.poisoned.set(true);
}
result
}
#[cfg(feature = "alloc")]
static ACTIVE: AtomicUsize = AtomicUsize::new(0);
#[cfg(feature = "alloc")]
static FAILED_CLEANUP: AtomicBool = AtomicBool::new(false);
#[cfg(feature = "alloc")]
pub(crate) fn resource_failed() {
FAILED_CLEANUP.store(true, Ordering::Release);
}
#[cfg(feature = "alloc")]
pub(crate) fn resource_acquired() {
ACTIVE.fetch_add(1, Ordering::Relaxed);
}
#[cfg(feature = "alloc")]
pub(crate) fn resource_released() {
ACTIVE.fetch_sub(1, Ordering::Release);
}
#[cfg(feature = "alloc")]
unsafe extern "C" fn create<F: Factory>(out: *mut *mut c_void) -> i32 {
guard(|| {
check_pointer(out)?;
unsafe {
out.write(core::ptr::null_mut());
}
let value = F::create()?;
let object = alloc::boxed::Box::new(Object::new(value));
resource_acquired();
unsafe {
out.write(alloc::boxed::Box::into_raw(object).cast());
}
Ok(())
})
}
#[cfg(feature = "alloc")]
pub(crate) unsafe extern "C" fn destroy<T>(ptr: *mut c_void) -> i32 {
guard(|| {
let ptr = ptr.cast::<Object<T>>();
check_pointer(ptr)?;
let object = unsafe { &*ptr };
if object.busy.replace(true) {
return Err(Error::Busy);
}
let result = catch(|| {
unsafe {
drop(alloc::boxed::Box::from_raw(ptr));
}
Ok(())
});
if result.is_err() {
resource_failed();
}
resource_released();
result
})
}
#[cfg(feature = "alloc")]
unsafe extern "C" fn quiesce() -> i32 {
if ACTIVE.load(Ordering::Acquire) == 0 && !FAILED_CLEANUP.load(Ordering::Acquire) {
0
} else {
Error::Busy.status()
}
}
#[cfg(feature = "alloc")]
pub struct Registration<I, F>(PhantomData<(I, F)>);
#[cfg(feature = "alloc")]
impl<I: ExportInterface, F: Factory<Object = I::Implementation>> Registration<I, F> {
const INTERFACE: abi::InterfaceDescriptor = abi::InterfaceDescriptor {
size: core::mem::size_of::<abi::InterfaceDescriptor>() as u32,
version: I::VERSION,
id: abi::Bytes::from_static(I::ID.as_bytes()),
method_count: I::METHODS.len() as u32,
methods: I::METHODS.as_ptr(),
create: Some(create::<F>),
destroy: Some(destroy::<I::Implementation>),
};
const INTERFACES: [*const abi::InterfaceDescriptor; 1] = [&Self::INTERFACE];
pub const fn interface() -> &'static abi::InterfaceDescriptor {
&Self::INTERFACE
}
pub const fn pinned(version: abi::Version) -> abi::PluginDescriptor {
abi::PluginDescriptor {
header: abi::Header {
magic: abi::MAGIC,
major: abi::ABI_MAJOR,
minor: abi::ABI_MINOR,
size: core::mem::size_of::<abi::PluginDescriptor>() as u32,
},
plugin_version: version,
flags: 0,
interface_count: 1,
interfaces: Self::INTERFACES.as_ptr(),
quiesce: None,
}
}
pub const fn cooperative(version: abi::Version) -> abi::PluginDescriptor
where
I::Implementation: UnloadSafe,
{
let mut descriptor = Self::pinned(version);
descriptor.flags = abi::COOPERATIVE;
descriptor.quiesce = Some(quiesce);
descriptor
}
}
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! export {
($adapter:ty, constructor = $constructor:path, version = ($major:expr, $minor:expr, $patch:expr), unload = $policy:ident $(,)?) => {
const _: () = {
struct ZpluginFactory;
impl $crate::export::Factory for ZpluginFactory {
type Object = <$adapter as $crate::export::ExportInterface>::Implementation;
fn create() -> $crate::Result<Self::Object> {
$constructor()
}
}
static DESCRIPTOR: $crate::abi::PluginDescriptor =
$crate::export::Registration::<$adapter, ZpluginFactory>::$policy(
$crate::abi::Version {
major: $major,
minor: $minor,
patch: $patch,
},
);
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zplugin_entry_v1() -> *const $crate::abi::Header {
&DESCRIPTOR.header
}
};
};
}
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! export_interfaces {
(version = ($major:expr, $minor:expr, $patch:expr), unload = $policy:ident;
$first:ty => $first_constructor:path $(, $adapter:ty => $constructor:path)* $(,)?) => {
const _: () = {
const VERSION: $crate::abi::Version = $crate::abi::Version {
major: $major,
minor: $minor,
patch: $patch,
};
struct ZpluginFirstFactory;
impl $crate::export::Factory for ZpluginFirstFactory {
type Object = <$first as $crate::export::ExportInterface>::Implementation;
fn create() -> $crate::Result<Self::Object> {
$first_constructor()
}
}
const INTERFACES: &[*const $crate::abi::InterfaceDescriptor] = &[
$crate::export::Registration::<$first, ZpluginFirstFactory>::interface(),
$({
struct ZpluginFactory;
impl $crate::export::Factory for ZpluginFactory {
type Object = <$adapter as $crate::export::ExportInterface>::Implementation;
fn create() -> $crate::Result<Self::Object> {
$constructor()
}
}
let _ = $crate::export::Registration::<$adapter, ZpluginFactory>::$policy(VERSION);
$crate::export::Registration::<$adapter, ZpluginFactory>::interface()
}),*
];
static DESCRIPTOR: $crate::abi::PluginDescriptor = {
let mut descriptor =
$crate::export::Registration::<$first, ZpluginFirstFactory>::$policy(VERSION);
descriptor.interface_count = INTERFACES.len() as u32;
descriptor.interfaces = INTERFACES.as_ptr();
descriptor
};
#[unsafe(no_mangle)]
pub unsafe extern "C" fn zplugin_entry_v1() -> *const $crate::abi::Header {
&DESCRIPTOR.header
}
};
};
}