#![allow(clippy::expect_used)]
use core::cell::RefCell;
use core::hint::black_box;
use criterion::BenchmarkId;
use criterion::Criterion;
use criterion::Throughput;
use criterion::criterion_group;
use criterion::criterion_main;
use polyplug::runtime_store::RuntimeStore;
use polyplug_abi::AbiError;
use polyplug_abi::AbiErrorCode;
use polyplug_abi::Array;
use polyplug_abi::DispatchMechanisms;
use polyplug_abi::DispatchType;
use polyplug_abi::GuestContractHandle;
use polyplug_abi::GuestContractInstance;
use polyplug_abi::GuestContractInterface;
use polyplug_abi::HostApi;
use polyplug_abi::NativeDispatch;
use polyplug_abi::PluginDescriptor;
use polyplug_abi::StringView;
use polyplug_abi::ffi::polyplug_host_alloc;
use polyplug_abi::ffi::polyplug_host_free;
use polyplug_abi::types::Version;
use polyplug_utils::BundleId;
use polyplug_utils::GuestContractId;
const TEST_PLUGIN_SO: &str = env!("TEST_PLUGIN_SO");
thread_local! {
static BENCH_REGISTRY: RefCell<Option<RuntimeStore>> = RefCell::new(Some(RuntimeStore::new()));
static LAST_CONTRACT_ID: core::cell::Cell<u64> = const { core::cell::Cell::new(0) };
}
unsafe extern "C" fn bench_register_callback(
_this: *const HostApi,
descriptor: *const PluginDescriptor,
interface: *const GuestContractInterface,
out_err: *mut AbiError,
) {
if descriptor.is_null() || interface.is_null() {
if !out_err.is_null() {
unsafe {
out_err.write(AbiError {
code: AbiErrorCode::Generic as u32,
message: StringView::null(),
})
};
}
return;
}
let desc: &PluginDescriptor = unsafe { &*descriptor };
let iface: &GuestContractInterface = unsafe { &*interface };
let contract_name: &str = unsafe {
let bytes: &[u8] =
core::slice::from_raw_parts(desc.contract_name.ptr, desc.contract_name.len);
core::str::from_utf8_unchecked(bytes) };
let result: Result<GuestContractHandle, _> =
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
let borrowed = cell.borrow();
let registry = borrowed.as_ref().expect("registry not initialized");
unsafe {
registry.register_guest_contract(
*desc,
interface,
contract_name.to_owned(),
BundleId::from_u64(iface.contract_id.id()),
)
}
});
let err: AbiError = match result {
Ok(_) => {
LAST_CONTRACT_ID.with(|cell| cell.set(iface.contract_id.id()));
AbiError::ok()
}
Err(_) => AbiError {
code: AbiErrorCode::Generic as u32,
message: StringView::null(),
},
};
if !out_err.is_null() {
unsafe { out_err.write(err) };
}
}
unsafe extern "C" fn bench_find_guest_contract(
_this: *const HostApi,
contract_id: u64,
min_version: u32,
) -> GuestContractHandle {
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
let registry = cell.borrow();
let reg = registry.as_ref().expect("registry not initialized");
reg.find(GuestContractId::from_u64(contract_id), min_version)
.unwrap_or_else(|_| GuestContractHandle::null())
})
}
unsafe extern "C" fn bench_find_all_guest_contracts(
_this: *const HostApi,
_contract_id: u64,
_min_version: u32,
) -> Array<GuestContractHandle> {
Array::empty()
}
unsafe extern "C" fn bench_resolve_guest_contract(
_this: *const HostApi,
handle: GuestContractHandle,
) -> *const GuestContractInterface {
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
cell.borrow()
.as_ref()
.expect("registry not initialized")
.resolve_guest_contract(handle)
.unwrap_or(core::ptr::null())
})
}
unsafe extern "C" fn bench_get_host_contract(
_this: *const HostApi,
_contract_id: u64,
_min_version: u32,
) -> polyplug_abi::HostContractInstance {
polyplug_abi::HostContractInstance::null()
}
unsafe extern "C" fn bench_resolve_host_contract_interface(
_this: *const HostApi,
_contract_id: u64,
_min_version: u32,
) -> *const polyplug_abi::HostContractInterface {
core::ptr::null()
}
unsafe extern "C" fn bench_list_bundles(_this: *const HostApi) -> Array<BundleId> {
Array::empty()
}
unsafe extern "C" fn bench_get_dependencies(
_this: *const HostApi,
) -> Array<polyplug_abi::DependencyInfo> {
Array::empty()
}
unsafe extern "C" fn bench_alloc(_this: *const HostApi, size: usize, align: usize) -> *mut u8 {
polyplug_host_alloc(size, align)
}
unsafe extern "C" fn bench_free(_this: *const HostApi, ptr: *mut u8, size: usize, align: usize) {
unsafe { polyplug_host_free(ptr, size, align) };
}
unsafe extern "C" fn bench_load_bundle(
_this: *const HostApi,
_path: *const u8,
_path_len: usize,
out_err: *mut AbiError,
) {
if !out_err.is_null() {
unsafe {
out_err.write(AbiError {
code: AbiErrorCode::Generic as u32,
message: StringView::null(),
})
};
}
}
unsafe extern "C" fn bench_reload_bundle(
_this: *const HostApi,
_path: *const u8,
_path_len: usize,
out_err: *mut AbiError,
) {
if !out_err.is_null() {
unsafe {
out_err.write(AbiError {
code: AbiErrorCode::Generic as u32,
message: StringView::null(),
})
};
}
}
unsafe extern "C" fn bench_register_host_contract(
_this: *const HostApi,
_interface: *const polyplug_abi::HostContractInterface,
out_err: *mut AbiError,
) {
if !out_err.is_null() {
unsafe {
out_err.write(AbiError {
code: AbiErrorCode::Generic as u32,
message: StringView::null(),
})
};
}
}
unsafe extern "C" fn bench_register_loader(
_this: *const HostApi,
_loader_ptr: *mut core::ffi::c_void,
out_err: *mut AbiError,
) {
if !out_err.is_null() {
unsafe {
out_err.write(AbiError {
code: AbiErrorCode::Generic as u32,
message: StringView::null(),
})
};
}
}
unsafe extern "C" fn bench_get_last_error(
_this: *const HostApi,
_buf: *mut u8,
_buf_len: usize,
) -> usize {
0
}
unsafe extern "C" fn bench_get_error_len(_this: *const HostApi) -> usize {
0
}
unsafe extern "C" fn bench_unload_bundle(
_this: *const HostApi,
_bundle_id: BundleId,
out_err: *mut AbiError,
) {
if !out_err.is_null() {
unsafe { out_err.write(AbiError::ok()) };
}
}
fn build_host_interface() -> HostApi {
HostApi {
runtime: core::ptr::null_mut(),
register_guest_contract: bench_register_callback,
alloc: bench_alloc,
free: bench_free,
find_guest_contract: bench_find_guest_contract,
find_all_guest_contracts: bench_find_all_guest_contracts,
resolve_guest_contract: bench_resolve_guest_contract,
get_host_contract: bench_get_host_contract,
resolve_host_contract_interface: bench_resolve_host_contract_interface,
list_bundles: bench_list_bundles,
get_dependencies: bench_get_dependencies,
load_bundle: bench_load_bundle,
reload_bundle: bench_reload_bundle,
register_host_contract: bench_register_host_contract,
register_loader: bench_register_loader,
get_last_error: bench_get_last_error,
get_error_len: bench_get_error_len,
unload_bundle: bench_unload_bundle,
log: stub_host_log,
create_guest_instance: stub_create_guest_instance,
destroy_guest_instance: stub_destroy_guest_instance,
revision_counter: stub_revision_counter,
reserved: core::ptr::null(),
}
}
fn load_and_init_plugin(host_interface: &HostApi) -> (libloading::Library, u64) {
let library: libloading::Library =
unsafe { libloading::Library::new(TEST_PLUGIN_SO).expect("failed to load plugin") };
let init_fn: libloading::Symbol<
'_,
unsafe extern "C" fn(*const HostApi, *const polyplug_abi::BundleInitContext) -> AbiError,
> = unsafe {
library
.get(b"polyplug_init\0")
.expect("polyplug_init not found")
};
let plugin_ctx: polyplug_abi::BundleInitContext = polyplug_abi::BundleInitContext {
bundle_path: StringView::null(),
bundle_id: 0,
};
let result: AbiError = unsafe {
init_fn(
host_interface as *const HostApi,
&plugin_ctx as *const polyplug_abi::BundleInitContext,
)
};
assert!(
result.is_ok(),
"polyplug_init failed for {}",
TEST_PLUGIN_SO
);
let contract_id: u64 = LAST_CONTRACT_ID.with(|cell| cell.get());
assert_ne!(contract_id, 0, "plugin contract_id was not captured");
(library, contract_id)
}
fn bench_ffi_resolve_plugin(c: &mut Criterion) {
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
*cell.borrow_mut() = Some(RuntimeStore::new());
});
let host_interface: HostApi = build_host_interface();
let (library, contract_id): (libloading::Library, u64) = load_and_init_plugin(&host_interface);
let handle: GuestContractHandle = unsafe {
(host_interface.find_guest_contract)(&host_interface as *const HostApi, contract_id, 0)
};
let mut group: criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> =
c.benchmark_group("ffi");
group.throughput(Throughput::Elements(1));
group.bench_function(
BenchmarkId::new("resolve_plugin", "direct_interface"),
|b| {
b.iter(|| {
let interface_ptr: *const GuestContractInterface = unsafe {
(host_interface.resolve_guest_contract)(
black_box(&host_interface as *const HostApi),
black_box(handle),
)
};
black_box(interface_ptr);
});
},
);
group.finish();
core::mem::forget(library);
}
fn bench_ffi_resolve_null_handle(c: &mut Criterion) {
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
*cell.borrow_mut() = Some(RuntimeStore::new());
});
let host_interface: HostApi = build_host_interface();
let (library, _contract_id): (libloading::Library, u64) = load_and_init_plugin(&host_interface);
let null_handle: GuestContractHandle = GuestContractHandle::null();
let mut group: criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> =
c.benchmark_group("ffi");
group.throughput(Throughput::Elements(1));
group.bench_function(BenchmarkId::new("resolve_plugin", "null_handle"), |b| {
b.iter(|| {
let interface_ptr: *const GuestContractInterface = unsafe {
(host_interface.resolve_guest_contract)(
black_box(&host_interface as *const HostApi),
black_box(null_handle),
)
};
black_box(interface_ptr);
});
});
group.finish();
core::mem::forget(library);
}
unsafe extern "C" fn sweep_create_instance(
_loader_data: polyplug_abi::dispatch::VmLoaderData,
_host: *const HostApi,
_args: *const (),
out_instance: *mut GuestContractInstance,
) {
if !out_instance.is_null() {
unsafe { out_instance.write(GuestContractInstance::null()) };
}
}
unsafe extern "C" fn sweep_destroy_instance(
_loader_data: polyplug_abi::dispatch::VmLoaderData,
_host: *const HostApi,
_instance: GuestContractInstance,
) {
}
fn leak_sweep_interface(contract_id: u64) -> &'static GuestContractInterface {
Box::leak(Box::new(GuestContractInterface {
contract_id: GuestContractId::from_u64(contract_id),
contract_version: Version {
major: 1,
minor: 0,
patch: 0,
},
dispatch_type: DispatchType::Native,
create_instance: sweep_create_instance,
destroy_instance: sweep_destroy_instance,
dispatch: DispatchMechanisms {
native: NativeDispatch {
function_count: 0,
functions: core::ptr::null(),
},
},
}))
}
fn bench_ffi_resolve_registry_sweep(c: &mut Criterion) {
let host_interface: HostApi = build_host_interface();
let sizes: [u64; 3] = [10, 100, 1000];
let mut group: criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> =
c.benchmark_group("ffi");
group.throughput(Throughput::Elements(1));
for &size in &sizes {
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
*cell.borrow_mut() = Some(RuntimeStore::new());
});
let base_id: u64 = 0x5000_0000_0000_0000_u64;
for i in 0..size {
let interface: &'static GuestContractInterface = leak_sweep_interface(base_id + i);
let descriptor: PluginDescriptor = PluginDescriptor {
name: StringView::from_static(b"sweep_plugin"),
contract_name: StringView::from_static(b"sweep.contract"),
version: Version {
major: 1,
minor: 0,
patch: 0,
},
};
BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
let borrowed = cell.borrow();
let registry: &RuntimeStore = borrowed.as_ref().expect("registry not initialized");
unsafe {
registry
.register_guest_contract(
descriptor,
interface,
format!("sweep.contract.{}", i),
BundleId::from_u64(i),
)
.expect("registration should succeed");
}
});
}
let middle_id: u64 = base_id + size / 2;
let handle: GuestContractHandle = unsafe {
(host_interface.find_guest_contract)(&host_interface as *const HostApi, middle_id, 0)
};
group.bench_with_input(
BenchmarkId::new("resolve_plugin", format!("registry_{}", size)),
&handle,
|b, &handle| {
b.iter(|| {
let interface_ptr: *const GuestContractInterface = unsafe {
(host_interface.resolve_guest_contract)(
black_box(&host_interface as *const HostApi),
black_box(handle),
)
};
black_box(interface_ptr);
});
},
);
}
group.finish();
}
criterion_group!(
benches,
bench_ffi_resolve_plugin,
bench_ffi_resolve_null_handle,
bench_ffi_resolve_registry_sweep,
);
criterion_main!(benches);
unsafe extern "C" fn stub_host_log(
_this: *const polyplug_abi::HostApi,
_level: u32,
_scope: polyplug_abi::StringView,
_message: polyplug_abi::StringView,
) {
}
unsafe extern "C" fn stub_create_guest_instance(
_this: *const polyplug_abi::HostApi,
_interface: *const polyplug_abi::GuestContractInterface,
_args: *const core::ffi::c_void,
out_instance: *mut polyplug_abi::GuestContractInstance,
) {
if !out_instance.is_null() {
unsafe { out_instance.write(polyplug_abi::GuestContractInstance::null()) };
}
}
unsafe extern "C" fn stub_destroy_guest_instance(
_this: *const polyplug_abi::HostApi,
_interface: *const polyplug_abi::GuestContractInterface,
_instance: polyplug_abi::GuestContractInstance,
) {
}
unsafe extern "C" fn stub_revision_counter(_this: *const polyplug_abi::HostApi) -> *const u64 {
core::ptr::null()
}