zplugin 0.1.0

Zero-dependency no_std native plugin ABI, loader, and generated Rust interfaces
Documentation
//! Plugin-side adapters. Raw entrypoints require valid pointers and one thread.
use crate::{Error, Result, abi};
#[cfg(feature = "alloc")]
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use core::sync::atomic::{AtomicUsize, Ordering};
use core::{
    cell::{Cell, UnsafeCell},
    ffi::c_void,
};

/// Type-level description generated by the interface macro.
/// # Safety
/// Every method must match its exact signature and the protocol's buffer,
/// object, panic and ownership rules. Metadata must remain immutable.
pub unsafe trait ExportInterface {
    type Implementation;
    const ID: &'static str;
    const VERSION: u32;
    const METHODS: &'static [abi::Method];
}

/// A promise that releasing the last object also retires all plugin activity.
/// # Safety
/// No thread, task, callback, TLS destructor, atexit hook, or escaped code/data
/// reference may need this library after its last object/resource is released.
/// Object destructors must join/cancel/unregister all such activity. Library
/// initializers and finalizers must obey the same contract.
pub unsafe trait UnloadSafe {}

pub trait Factory {
    type Object;
    fn create() -> Result<Self::Object>;
}

/// Object memory is owned by the plugin. A Cell guard precedes any mutable borrow.
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),
        }
    }
}

/// Validate structural pointer conditions; memory mapping is a caller obligation.
pub fn check_pointer<T>(ptr: *const T) -> Result<()> {
    if ptr.is_null() || (ptr as usize) % core::mem::align_of::<T>() != 0 {
        Err(Error::InvalidArgument)
    } else {
        Ok(())
    }
}

#[derive(Clone, Copy)]
pub struct Borrow {
    pub ptr: *const u8,
    pub len: usize,
    pub mutable: bool,
}

/// Reject malformed or overlapping mutable ranges before constructing references.
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) => {
                // Normal payloads are released. A payload's destructor can itself
                // panic; catch that too and forget only the pathological 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()
}

/// Catch unwind-enabled panics on the plugin side of the C boundary.
pub fn guard(f: impl FnOnce() -> Result<()>) -> i32 {
    catch(f).map_or_else(Error::status, |()| 0)
}

/// # Safety
/// `object` must point to a live Object<T>, created in this library, and used on
/// its creating thread. Reentry is rejected before creating a mutable reference.
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)?;
    // SAFETY: guaranteed by the entrypoint caller; shared access touches only Cells.
    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);
    // SAFETY: this thread holds the busy guard and there is no existing T borrow.
    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")]
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)?;
        // SAFETY: entrypoint callers provide writable, aligned output storage.
        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")]
unsafe extern "C" fn destroy<T>(ptr: *mut c_void) -> i32 {
    guard(|| {
        let ptr = ptr.cast::<Object<T>>();
        check_pointer(ptr)?;
        // SAFETY: destroy is called once, on this object's creating thread.
        let object = unsafe { &*ptr };
        if object.busy.replace(true) {
            return Err(Error::Busy);
        }
        let result = catch(|| {
            // SAFETY: no active borrow remains; Box's drop glue also releases its
            // allocation if T's destructor unwinds. The object is never retried.
            unsafe {
                drop(alloc::boxed::Box::from_raw(ptr));
            }
            Ok(())
        });
        resource_released();
        result
    })
}

#[cfg(feature = "alloc")]
unsafe extern "C" fn quiesce() -> i32 {
    if ACTIVE.load(Ordering::Acquire) == 0 {
        0
    } else {
        Error::Busy.status()
    }
}

/// Builds static descriptors without allocating during entry or interface discovery.
#[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];

    /// Immutable interface metadata, for composing independent extension interfaces.
    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
    }
}

/// Export one generated interface. The constructor returns `Result<Implementation>`.
/// The cooperative form requires an explicit unsafe `UnloadSafe` implementation.
#[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
            }
        };
    };
}

/// Export several independently versioned interfaces through one v1 entrypoint.
/// Each constructor returns its implementation, and the cooperative policy
/// requires every implementation to satisfy the unsafe `UnloadSafe` contract.
/// Interface IDs must be distinct; extending a frozen table requires a new ID
/// or a new interface version rather than changing an existing signature.
///
/// ```
/// # #[cfg(feature = "macros")]
/// # mod example {
/// # #[zplugin::interface(id = "example.counter", version = 1)]
/// # trait Counter { fn count(&self) -> zplugin::Result<u64>; }
/// # struct CounterObject;
/// # impl Counter for CounterObject { fn count(&self) -> zplugin::Result<u64> { Ok(0) } }
/// # unsafe impl zplugin::export::UnloadSafe for CounterObject {}
/// # fn create_counter() -> zplugin::Result<CounterObject> { Ok(CounterObject) }
/// # #[zplugin::interface(id = "example.snapshot", version = 1)]
/// # trait Snapshot { fn version(&self) -> zplugin::Result<u32>; }
/// # struct SnapshotObject;
/// # impl Snapshot for SnapshotObject { fn version(&self) -> zplugin::Result<u32> { Ok(1) } }
/// # unsafe impl zplugin::export::UnloadSafe for SnapshotObject {}
/// # fn create_snapshot() -> zplugin::Result<SnapshotObject> { Ok(SnapshotObject) }
/// zplugin::export_interfaces!(version = (1, 0, 0), unload = cooperative;
///     CounterExport<CounterObject> => create_counter,
///     SnapshotExport<SnapshotObject> => create_snapshot,
/// );
/// # }
/// ```
#[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()
                        }
                    }
                    // Calling the selected policy also checks UnloadSafe for every
                    // additional interface, not just the first one in the table.
                    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
            }
        };
    };
}