ark_api_ffi/entrypoints/
core.rs

1//! Core entrypoints shared by all module types
2
3use bytemuck::Pod;
4use bytemuck::Zeroable;
5
6/// `ark_initialize` - Initialize module
7///
8/// This gets called once when a module is started and enables the module to prepare its state and resources.
9/// If something goes wrong, the module can communicate that by panicking, and then it will be unloaded.
10///
11/// # Example
12///
13/// ```
14/// #[no_mangle]
15/// pub unsafe fn ark_initialize() {
16/// }
17/// ```
18pub type InitializeFn = fn();
19
20/// `ark_alloc` - Allocate a raw buffer in the module
21///
22/// This is called from the host to be able to allocate and write memory
23/// in a module that it then can pass in as a pointer when calling other
24/// entrypoint functions in the module
25///
26/// # Example
27///
28/// ```
29/// #[no_mangle]
30/// pub unsafe fn ark_alloc(size: usize, alignment: usize) -> *mut u8 {
31///     std::ptr::null_mut()
32/// }
33/// ```
34pub type AllocFn = fn(size: u32, alignment: u32) -> *mut u8;
35
36/// `ark_free` - Free a raw buffer in the module
37///
38/// This is intended to be used on memory allocated with `ark_alloc`
39///
40/// # Example
41///
42/// ```
43/// #[no_mangle]
44/// pub unsafe fn ark_free(ptr: *mut u8, size: usize, alignment: usize) {
45/// }
46/// ```
47pub type FreeFn = fn(ptr: *mut u8, size: u32, alignment: u32);
48
49/// `ark_register_panic_hook` - Register module specific panic hook
50///
51/// This gets called once when a module is started (or possibly by tests), and
52/// enables the module to catch panics and report them back to the host.
53pub type RegisterPanicHookFn = fn();
54
55/// Type for the data pointed to by the return value of `ark_get_alloc_stats`.
56#[derive(Debug, Copy, Clone, Default, Pod, Zeroable)]
57#[repr(C)]
58pub struct AllocStats {
59    // These are all cumulative.
60    pub cumul_alloc_count: u64,
61    pub cumul_alloc_size: u64,
62    pub cumul_free_count: u64,
63    pub cumul_free_size: u64,
64}
65
66// Utilities to compute some common stats from the cumulative sums.
67impl AllocStats {
68    pub fn current_allocated_size(&self) -> usize {
69        (self.cumul_alloc_size - self.cumul_free_size) as usize
70    }
71
72    pub fn current_allocation_count(&self) -> usize {
73        (self.cumul_alloc_count - self.cumul_free_count) as usize
74    }
75}
76
77/// `ark_get_alloc_stats` - Returns a pointer into Wasm memory to an instance of the `AllocStats` data structure.
78///
79/// `AllocStats` counts allocations and frees, so the host can get an idea of current
80/// memory use in a module.
81pub type GetAllocStatsFn = fn() -> u32;
82
83pub const INITIALIZE: &str = "ark_initialize";
84pub const ALLOC: &str = "ark_alloc";
85pub const FREE: &str = "ark_free";
86pub const REGISTER_PANIC_HOOK: &str = "ark_register_panic_hook";
87pub const GET_ALLOC_STATS: &str = "ark_get_alloc_stats";