wasmtime_c_api/
store.rs

1use crate::{ForeignData, wasm_engine_t, wasmtime_error_t, wasmtime_val_t};
2use std::cell::UnsafeCell;
3use std::ffi::c_void;
4use std::sync::Arc;
5use wasmtime::{
6    AsContext, AsContextMut, Caller, Store, StoreContext, StoreContextMut, StoreLimits,
7    StoreLimitsBuilder, UpdateDeadline, Val,
8};
9
10// Store-related type aliases for `wasm.h` APIs. Not for use with `wasmtime.h`
11// APIs!
12pub type WasmStoreData = ();
13pub type WasmStore = Store<WasmStoreData>;
14pub type WasmStoreContext<'a> = StoreContext<'a, WasmStoreData>;
15pub type WasmStoreContextMut<'a> = StoreContextMut<'a, WasmStoreData>;
16
17/// This representation of a `Store` is used to implement the `wasm.h` API (and
18/// *not* the `wasmtime.h` API!)
19///
20/// This is stored alongside `Func` and such for `wasm.h` so each object is
21/// independently owned. The usage of `Arc` here is mostly to just get it to be
22/// safe to drop across multiple threads, but otherwise acquiring the `context`
23/// values from this struct is considered unsafe due to it being unknown how the
24/// aliasing is working on the C side of things.
25///
26/// The aliasing requirements are documented in the C API `wasm.h` itself (at
27/// least Wasmtime's implementation).
28#[derive(Clone)]
29pub struct WasmStoreRef {
30    store: Arc<UnsafeCell<WasmStore>>,
31}
32
33impl WasmStoreRef {
34    pub unsafe fn context(&self) -> WasmStoreContext<'_> {
35        (*self.store.get()).as_context()
36    }
37
38    pub unsafe fn context_mut(&mut self) -> WasmStoreContextMut<'_> {
39        (*self.store.get()).as_context_mut()
40    }
41}
42
43#[repr(C)]
44#[derive(Clone)]
45pub struct wasm_store_t {
46    pub(crate) store: WasmStoreRef,
47}
48
49wasmtime_c_api_macros::declare_own!(wasm_store_t);
50
51#[unsafe(no_mangle)]
52pub extern "C" fn wasm_store_new(engine: &wasm_engine_t) -> Box<wasm_store_t> {
53    let engine = &engine.engine;
54    let store = Store::new(engine, ());
55    Box::new(wasm_store_t {
56        store: WasmStoreRef {
57            store: Arc::new(UnsafeCell::new(store)),
58        },
59    })
60}
61
62// Store-related type aliases for `wasmtime.h` APIs. Not for use with `wasm.h`
63// APIs!
64pub type WasmtimeStore = Store<WasmtimeStoreData>;
65pub type WasmtimeStoreContext<'a> = StoreContext<'a, WasmtimeStoreData>;
66pub type WasmtimeStoreContextMut<'a> = StoreContextMut<'a, WasmtimeStoreData>;
67pub type WasmtimeCaller<'a> = Caller<'a, WasmtimeStoreData>;
68
69/// Representation of a `Store` for `wasmtime.h` This notably tries to move more
70/// burden of aliasing on the caller rather than internally, allowing for a more
71/// raw representation of contexts and such that requires less `unsafe` in the
72/// implementation.
73///
74/// Note that this notably carries `WasmtimeStoreData` as a payload which allows
75/// storing foreign data and configuring WASI as well.
76#[repr(C)]
77pub struct wasmtime_store_t {
78    pub(crate) store: WasmtimeStore,
79}
80
81wasmtime_c_api_macros::declare_own!(wasmtime_store_t);
82
83pub struct WasmtimeStoreData {
84    foreign: crate::ForeignData,
85    #[cfg(feature = "wasi")]
86    pub(crate) wasi: Option<wasmtime_wasi::preview1::WasiP1Ctx>,
87
88    /// Temporary storage for usage during a wasm->host call to store values
89    /// in a slice we pass to the C API.
90    pub hostcall_val_storage: Vec<wasmtime_val_t>,
91
92    /// Temporary storage for usage during host->wasm calls, same as above but
93    /// for a different direction.
94    pub wasm_val_storage: Vec<Val>,
95
96    /// Limits for the store.
97    pub store_limits: StoreLimits,
98}
99
100#[unsafe(no_mangle)]
101pub extern "C" fn wasmtime_store_new(
102    engine: &wasm_engine_t,
103    data: *mut c_void,
104    finalizer: Option<extern "C" fn(*mut c_void)>,
105) -> Box<wasmtime_store_t> {
106    Box::new(wasmtime_store_t {
107        store: Store::new(
108            &engine.engine,
109            WasmtimeStoreData {
110                foreign: ForeignData { data, finalizer },
111                #[cfg(feature = "wasi")]
112                wasi: None,
113                hostcall_val_storage: Vec::new(),
114                wasm_val_storage: Vec::new(),
115                store_limits: StoreLimits::default(),
116            },
117        ),
118    })
119}
120
121pub type wasmtime_update_deadline_kind_t = u8;
122pub const WASMTIME_UPDATE_DEADLINE_CONTINUE: wasmtime_update_deadline_kind_t = 0;
123pub const WASMTIME_UPDATE_DEADLINE_YIELD: wasmtime_update_deadline_kind_t = 1;
124
125#[unsafe(no_mangle)]
126pub extern "C" fn wasmtime_store_epoch_deadline_callback(
127    store: &mut wasmtime_store_t,
128    func: extern "C" fn(
129        WasmtimeStoreContextMut<'_>,
130        *mut c_void,
131        *mut u64,
132        *mut wasmtime_update_deadline_kind_t,
133    ) -> Option<Box<wasmtime_error_t>>,
134    data: *mut c_void,
135    finalizer: Option<extern "C" fn(*mut c_void)>,
136) {
137    let foreign = crate::ForeignData { data, finalizer };
138    store.store.epoch_deadline_callback(move |mut store_ctx| {
139        let _ = &foreign; // Move foreign into this closure
140        let mut delta: u64 = 0;
141        let mut kind = WASMTIME_UPDATE_DEADLINE_CONTINUE;
142        let result = (func)(
143            store_ctx.as_context_mut(),
144            foreign.data,
145            &mut delta as *mut u64,
146            &mut kind as *mut wasmtime_update_deadline_kind_t,
147        );
148        match result {
149            Some(err) => Err((*err).into()),
150            None if kind == WASMTIME_UPDATE_DEADLINE_CONTINUE => {
151                Ok(UpdateDeadline::Continue(delta))
152            }
153            #[cfg(feature = "async")]
154            None if kind == WASMTIME_UPDATE_DEADLINE_YIELD => Ok(UpdateDeadline::Yield(delta)),
155            _ => panic!("unknown wasmtime_update_deadline_kind_t: {kind}"),
156        }
157    });
158}
159
160#[unsafe(no_mangle)]
161pub extern "C" fn wasmtime_store_context(
162    store: &mut wasmtime_store_t,
163) -> WasmtimeStoreContextMut<'_> {
164    store.store.as_context_mut()
165}
166
167#[unsafe(no_mangle)]
168pub extern "C" fn wasmtime_store_limiter(
169    store: &mut wasmtime_store_t,
170    memory_size: i64,
171    table_elements: i64,
172    instances: i64,
173    tables: i64,
174    memories: i64,
175) {
176    let mut limiter = StoreLimitsBuilder::new();
177    if memory_size >= 0 {
178        limiter = limiter.memory_size(memory_size as usize);
179    }
180    if table_elements >= 0 {
181        limiter = limiter.table_elements(table_elements as usize);
182    }
183    if instances >= 0 {
184        limiter = limiter.instances(instances as usize);
185    }
186    if tables >= 0 {
187        limiter = limiter.tables(tables as usize);
188    }
189    if memories >= 0 {
190        limiter = limiter.memories(memories as usize);
191    }
192    store.store.data_mut().store_limits = limiter.build();
193    store.store.limiter(|data| &mut data.store_limits);
194}
195
196#[unsafe(no_mangle)]
197pub extern "C" fn wasmtime_context_get_data(store: WasmtimeStoreContext<'_>) -> *mut c_void {
198    store.data().foreign.data
199}
200
201#[unsafe(no_mangle)]
202pub extern "C" fn wasmtime_context_set_data(
203    mut store: WasmtimeStoreContextMut<'_>,
204    data: *mut c_void,
205) {
206    store.data_mut().foreign.data = data;
207}
208
209#[cfg(feature = "wasi")]
210#[unsafe(no_mangle)]
211pub extern "C" fn wasmtime_context_set_wasi(
212    mut context: WasmtimeStoreContextMut<'_>,
213    wasi: Box<crate::wasi_config_t>,
214) -> Option<Box<wasmtime_error_t>> {
215    crate::handle_result(wasi.into_wasi_ctx(), |wasi| {
216        context.data_mut().wasi = Some(wasi);
217    })
218}
219
220#[unsafe(no_mangle)]
221pub extern "C" fn wasmtime_context_gc(mut context: WasmtimeStoreContextMut<'_>) {
222    context.gc(None);
223}
224
225#[unsafe(no_mangle)]
226pub extern "C" fn wasmtime_context_set_fuel(
227    mut store: WasmtimeStoreContextMut<'_>,
228    fuel: u64,
229) -> Option<Box<wasmtime_error_t>> {
230    crate::handle_result(store.set_fuel(fuel), |()| {})
231}
232
233#[unsafe(no_mangle)]
234pub extern "C" fn wasmtime_context_get_fuel(
235    store: WasmtimeStoreContext<'_>,
236    fuel: &mut u64,
237) -> Option<Box<wasmtime_error_t>> {
238    crate::handle_result(store.get_fuel(), |amt| {
239        *fuel = amt;
240    })
241}
242
243#[unsafe(no_mangle)]
244pub extern "C" fn wasmtime_context_set_epoch_deadline(
245    mut store: WasmtimeStoreContextMut<'_>,
246    ticks_beyond_current: u64,
247) {
248    store.set_epoch_deadline(ticks_beyond_current);
249}