Skip to main content

Crate zplugin

Crate zplugin 

Source
Expand description

§zplugin

Define a Rust trait, implement it in a cdylib, and call it through a typed host proxy. zplugin uses a frozen target-platform C ABI, cached function tables, and explicit library lifetimes. The default runtime is no_std, needs no allocator, and has zero third-party runtime dependencies. Its native system loader is shared with the Project Z zsys crate through the allocation-free dylib feature.

The same interface also generates C/C++ headers; Zig imports a module translated from those headers. Additive extension records support checked structs/enums, owned resources, callbacks, and cross-library tasks that the Rust host can .await.

For untrusted plugins, enable the separate wasm backend: validated Wasm32 bytecode, no host imports, finite execution fuel, and bounded guest memory. Native .so/.dylib/.dll loading still requires trusted code.

Rust 1.95 or newer; edition 2024. Development toolchain: 1.100.0, the stable release published on 2026-11-12. Native loading targets Linux, macOS, and Windows; see the 0.3.0 delivery record for tested machines and compiler combinations. This is a library of primitives, with no background watcher, executor, transport, or plugin discovery service. Native loading, the optional Wasm host and the allocator-free Wasm guest SDK share the Rust 1.95 baseline required by zsys. Older release evidence remains linked above; new platform verification belongs to this version’s CI run.

§Install

Shared interface crate:

[dependencies]
zplugin = { version = "0.3.1", features = ["macros"] }

Plugin and host crates can enable std independently. The interface itself may remain no_std. The optional procedural macro depends on syn, quote, and proc-macro2 at compile time; these are not linked into the runtime.

§Define an interface

#[zplugin::interface(id = "example.calculator", version = 1)]
pub trait Calculator {
    fn add(&mut self, a: u64, b: u64) -> Result<u64, zplugin::Error>;
    fn copy(&self, input: &[u8], output: &mut [u8]) -> Result<u64, zplugin::Error>;
}

The macro generates CalculatorApi, CalculatorBinding, CalculatorProxy, and CalculatorExport<T>. Argument names may change; method order, names, receiver kind, types, and results define the frozen interface. Change its version when changing that contract.

§Implement a plugin

Use the shared interface crate as a dependency and configure the plugin:

[lib]
crate-type = ["cdylib"]

[dependencies]
zplugin = { version = "0.3.1", features = ["std", "macros"] }
calculator-api = { path = "../calculator-api" }
ⓘ
use calculator_api::{Calculator, CalculatorExport};
use zplugin::{Error, Result};

struct Implementation;
impl Calculator for Implementation {
    fn add(&mut self, a: u64, b: u64) -> Result<u64> {
        Ok(a.wrapping_add(b))
    }
    fn copy(&self, input: &[u8], output: &mut [u8]) -> Result<u64> {
        if output.len() < input.len() { return Err(Error::BufferTooSmall); }
        output[..input.len()].copy_from_slice(input);
        Ok(input.len() as u64)
    }
}
fn create() -> Result<Implementation> { Ok(Implementation) }

zplugin::export!(CalculatorExport<Implementation>,
    constructor = create, version = (1, 0, 0), unload = pinned);

The pinned policy keeps the image resident until process exit. To opt into cooperative unloading, implement the unsafe zplugin::export::UnloadSafe contract for the implementation, use unload = cooperative, and select the same policy when loading. The complete runnable example contains that implementation.

§Load and call

ⓘ
use calculator_api::CalculatorApi;
use zplugin::{Plugin, UnloadPolicy};

// SAFETY: this file and its dependencies are trusted, and obey the v1 ABI.
let library = unsafe { Plugin::load_path("./libcalculator.so", UnloadPolicy::Pinned)? };
let mut calculator = CalculatorApi::create(&library)?;
assert_eq!(calculator.add(20, 22)?, 42);
let mut output = [0; 64];
let count = calculator.copy(b"hello", &mut output)?;
assert_eq!(&output[..count as usize], b"hello");

Use .dylib on macOS and .dll on Windows. load_path preserves native Unicode paths. Without std, Plugin::load(&CStr) is available; on Windows its narrow path uses the ANSI code page, and Plugin::load_wide accepts UTF-16 without alloc.

The proxy borrows its library, so Rust rejects dropping that library first. For an independent owning proxy, enable alloc, put the plugin in Rc<Plugin>, and call CalculatorApi::wrap(Plugin::create_owned(&library, CalculatorApi::SPEC)?). Cloning occurs when acquiring resources; ordinary calls do not clone a lease.

§Run the complete example

The repository includes separate interface, plugin, and host crates:

cargo build --release -p demo-plugin
cargo run --release -p demo-host -- target/release/libdemo_plugin.so --self-test

On macOS substitute libdemo_plugin.dylib; on Windows use demo_plugin.dll. See examples/README.md for the directory structure, full Cargo configuration, explicit snapshot/restore, and owned outputs.

§Supported boundaries

Rust interface typeBoundary representation
u8/u16/u32/u64, i8/i16/i32/i64, f32/f64Fixed-width C ABI scalar
&[u8], &mut [u8]Pointer and native size_t length; one call only
&strValidated UTF-8 view; one call only
Result<T, zplugin::Error> / zplugin::Result<T>Signed status plus initialized success output
() or scalar successNo output or fixed-width result record
zplugin::OwnedBytes successBuffer, origin release callback, independent library lease
Plugin objectOpaque plugin allocation and matching destroy function
#[zplugin::abi_type] struct or enumRecursive C-layout record or checked tag/payload; independent of Rust layout
zplugin::OwnedResource successVersioned opaque resource with call/release table and independent library lease
zplugin::CallbackRef<'_> inputBorrowed callback with explicit retain/invoke/release protocol
zplugin::OwnedTask<T> successTask handle with poll/cancel/release; host receives Task<T>: Future with alloc

Unsupported signatures produce compile errors: generics, direct async fn, default methods, associated types, conditional methods, usize/isize, bool/char, 128-bit integers, unannotated structs, native String/Vec/Box/Arc, and native Future layouts. Stable values require Copy + Clone; reference, owned, generic and array fields are excluded. Task outputs use AbiValue, including nested structs/enums and unit. Plugin internals may use ordinary Rust facilities and dependencies.

§Asynchronous and cross-language plugins

The interface declares a task factory, so borrowed input ends at the factory call:

#[zplugin::interface(id = "example.jobs", version = 1)]
pub trait Jobs {
    fn start(&mut self, input: u64) -> zplugin::Result<zplugin::OwnedTask<u64>>;
}

struct Worker;
impl Jobs for Worker {
    fn start(&mut self, input: u64) -> zplugin::Result<zplugin::OwnedTask<u64>> {
        Ok(zplugin::OwnedTask::new(async move { Ok(input.wrapping_add(1)) }))
    }
}

The generated host proxy returns a lease-owning Task<u64>: use jobs.start(41)?.await?, or cancel() for cooperative cancellation. Polling, cancelling and destruction stay on the creating thread; retained wakers support concurrent notification. No native Future or Waker layout crosses the boundary. The plugin manages any runtime it needs. Dropping a future does not implicitly shut down an external executor; cooperative unloading requires workers and callback return paths to be fully joined/drained.

JobsApi::write_c_header(&mut writer) emits the exact argument layouts, method signatures and descriptor helpers. C11 and C++17 include the header; Zig uses its automatically translated module. The generator itself writes through core::fmt::Write without needing an allocator.

python3 scripts/async.py
python3 scripts/foreign.py --install-zig

See the async three-crate example, the complete C/C++/Zig example, and the extension protocol and ownership rules.

§Features

FeatureAdditional capabilityRuntime dependency
default: noneABI, native loader, borrowed instances, manual resource/factory contractscore and Project Z zsys/dylib
allocFactories, Rc leases, owned bytes/resources, closure callbacks, Future/Waker adaptersRust allocator
stdNative paths, error integration, panic containmentstd, implies alloc
macrosTrait-to-ABI generationCompilation-only macro crate
hot-reloadBounded generations and request leasesalloc
wasmImport-free, fuel-metered Wasm32 sandbox; separate byte-buffer protocolalloc + Wasmi 2.0 and its dependencies; Rust 1.95+

For allocator-free plugins, implement the public ABI with application-owned object storage. export::Object<T> and the entrypoint guards also work without an allocator. Convenience export! factories deliberately require alloc.

§Untrusted Wasm plugins

The host opts in explicitly; the default native runtime depends only on Project Z zsys:

[dependencies]
zplugin = { version = "0.3.1", features = ["wasm"] }
ⓘ
use zplugin::wasm::{Interface, Limits, Plugin};

let interface = Interface { id: 0x7a70_6c75_6769_6e01, version: 1 };
// bytes is an untrusted binary Wasm module; this API is safe to call.
let mut plugin = Plugin::new(&bytes, interface, Limits::default())?;
let mut output = [0; 64];
let written = plugin.call(1, b"hello", &mut output)?;
assert_eq!(&output[..written], b"HELLO");

Implement wasm_guest::Guest, export it with export_wasm!, and compile for wasm32-unknown-unknown. The complete guest and host run with:

rustup target add wasm32-unknown-unknown
python3 scripts/wasm.py

Wasm calls use numeric operations and bounded byte buffers. Input/output are copied across the memory boundary; native trait proxies, handles, callbacks, and async tasks are not forwarded into the sandbox. No WASI, filesystem, network, environment, clock or process capabilities are granted. Module imports and start sections are rejected. A trap exhausts/invalidates that instance, not the native host’s call stack; subsequent use returns Poisoned.

This is an in-process Wasm sandbox whose isolation depends on the engine. Guest-memory limits do not cap process RSS, and fuel is not a compilation-time deadline. Use additional OS process isolation for strict total-memory/time bounds or protection against engine vulnerabilities. See protocol, policy and evidence. Reproducible sandbox timings and allocation measurements are in the 0.3.0 Wasm performance report.

§Multiple interfaces and hot switching

export_interfaces! exports independently versioned interfaces through one entry:

ⓘ
zplugin::export_interfaces!(version = (1, 0, 0), unload = cooperative;
    CalculatorExport<Implementation> => create,
    SnapshotExport<State> => create_state,
);

With hot-reload, hot::Generations::new(plugin, maximum_retired) tracks the current image and old generations. current() acquires a request/session lease. reload or reload_path loads an independent image, runs your creation/restore closure, and switches only on success. Old objects continue using their old code. Use an explicitly versioned byte snapshot for state migration. collect() asks unreferenced cooperative generations to retire; Busy generations remain and count toward the limit. No timeout forces an unload.

§Safety and performance

Loading trusted native code remains unsafe: initializers and methods execute with the host’s privileges. ABI checks detect incompatible metadata; native code must still honor memory validity, ownership, and unwind contracts. Proxies are neither Send nor Sync; all calls, including shared trait methods, require a mutable proxy. Same-object raw reentry returns Busy before a second borrow.

Under std and an unwind-enabled plugin build, adapters catch Rust panics on the plugin side and poison that instance. panic=abort, foreign exceptions, and native crashes retain their process-level behavior. C++ plugins contain their own exceptions before returning; the C++ example includes that boundary. Task/callback extensions use independent size/version-prefixed tables. Failed resource cleanup prevents cooperative unloading, including a future or callback capture destructor that panics.

Steady native borrowed calls use cached function pointers without forced allocation, serialization, symbol lookup, or per-call reference counting. Actual comparisons against inline/noinline calls, cached C pointers and cached libloading symbols are in the 0.2.0 performance report, including three raw runs, task initialization, reused/changed wakers, and worker shutdown. An inline static call remains a distinct, cheaper baseline for tiny functions.

§Validation and release

python3 scripts/check.py
python3 scripts/check.py --cross-version
python3 scripts/legacy.py
python3 scripts/foreign.py --install-zig
python3 scripts/wasm.py
python3 tools/bench/run.py docs/benchmarks/v0.2.0
python3 tools/bench/extensions.py

CI runs actual hosts and dynamic libraries on Linux, macOS, and Windows, plus Rust 1.95.0/stable, core-only embedded/WASM compilation, negative macro fixtures, and release transaction tests. Wasm also runs on all three native host platforms, with Rust 1.95 MSRV/no_std checks and independently built guest/host pairs. The manual release workflow supports patch/minor/major/custom, dry_run, exact-commit validation, dependency-ordered publication, and recovery after a partial upload. It uses the step-scoped CARGO_REGISTRY_TOKEN secret. See release operations.

Further detail: ABI and ownership, validation evidence, changelog. Licensed MIT OR Apache-2.0.

Native plugin primitives with a frozen C ABI and explicit library lifetimes.

The default feature set needs neither std nor an allocator. Enable macros for generated interfaces, alloc for owned library leases and plugin factories, std for path conveniences and panic containment, and hot-reload for generations. Native loading is unsafe: native code must obey ABI and ownership contracts. The separate wasm feature provides an import-free, fuel-metered sandbox for untrusted WebAssembly, with an optional Wasmi runtime dependency. All features require Rust 1.95; the native system loader is shared through Project Z zsys. wasm_guest and export_wasm! are allocator-free and need no engine feature.

Re-exports§

pub use callback::Callback;
pub use callback::CallbackRef;
pub use resource::OwnedResource;
pub use resource::Resource;
pub use resource::ResourceHandler;
pub use task::OwnedTask;
pub use task::Task;
pub use value::AbiValue;

Modules§

abi
Protocol v1. All pointers refer to the current process and target C ABI.
bindings
C declarations shared by generated interfaces and usable from C++ or Zig’s C translation tool. Generation writes to core::fmt::Write; it needs no heap.
callback
Same-thread reverse callbacks with explicit retain, invoke, and release.
export
Plugin-side adapters. Raw entrypoints require valid pointers and one thread.
hot
Request-boundary generations. Existing leases continue using their original code.
loader
Project Z native loader, backed by zsys. Images remain pinned until closed.
resource
Plugin-owned opaque resources with explicit type, version, and release paths.
task
Owned cross-library tasks. A Rust Future and Waker never cross the C ABI.
value
Fixed-layout values with checked conversion at the native boundary.
wasm
Opt-in sandbox for untrusted Wasm32 plugins (requires Rust 1.86 and alloc).
wasm_guest
Allocator-free guest SDK for the separate zplugin Wasm byte-buffer ABI v1.

Macros§

export
Export one generated interface. The constructor returns Result<Implementation>. The cooperative form requires an explicit unsafe UnloadSafe implementation.
export_interfaces
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.
export_wasm
Export a no-allocator Wasm plugin with fixed, disjoint scratch buffers.

Structs§

Binding
A fully checked interface; symbol lookup and signature checks are complete.
Buffer
Host-side returned bytes. Release runs before its independent library lease drops.
Instance
A plugin-owned object. Drop calls its original destroy before releasing its lease.
InterfaceSpec
OwnedBytes
Plugin-side owned bytes. Its v1 representation carries the origin allocator’s release.
Plugin
A validated descriptor and owning library. It is neither Send nor Sync.

Enums§

Error
Errors are Rust values locally; the wire contains only an i32 status.
UnloadPolicy

Functions§

status_result
Convert any nonzero status without constructing an unchecked Rust enum.

Type Aliases§

Result

Attribute Macros§

abi_type
Define an explicitly versioned struct or enum with a checked C representation.
interface
Define a frozen interface, its export adapter, and its typed host proxy.