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::p1::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#[cfg(all(feature = "component-model", feature = "wasi"))]
101impl wasmtime_wasi::WasiView for WasmtimeStoreData {
102    fn ctx(&mut self) -> wasmtime_wasi::WasiCtxView<'_> {
103        self.wasi.as_mut().unwrap().ctx()
104    }
105}
106
107#[unsafe(no_mangle)]
108pub extern "C" fn wasmtime_store_new(
109    engine: &wasm_engine_t,
110    data: *mut c_void,
111    finalizer: Option<extern "C" fn(*mut c_void)>,
112) -> Box<wasmtime_store_t> {
113    Box::new(wasmtime_store_t {
114        store: Store::new(
115            &engine.engine,
116            WasmtimeStoreData {
117                foreign: ForeignData { data, finalizer },
118                #[cfg(feature = "wasi")]
119                wasi: None,
120                hostcall_val_storage: Vec::new(),
121                wasm_val_storage: Vec::new(),
122                store_limits: StoreLimits::default(),
123            },
124        ),
125    })
126}
127
128pub type wasmtime_update_deadline_kind_t = u8;
129pub const WASMTIME_UPDATE_DEADLINE_CONTINUE: wasmtime_update_deadline_kind_t = 0;
130pub const WASMTIME_UPDATE_DEADLINE_YIELD: wasmtime_update_deadline_kind_t = 1;
131
132#[unsafe(no_mangle)]
133pub extern "C" fn wasmtime_store_epoch_deadline_callback(
134    store: &mut wasmtime_store_t,
135    func: extern "C" fn(
136        WasmtimeStoreContextMut<'_>,
137        *mut c_void,
138        *mut u64,
139        *mut wasmtime_update_deadline_kind_t,
140    ) -> Option<Box<wasmtime_error_t>>,
141    data: *mut c_void,
142    finalizer: Option<extern "C" fn(*mut c_void)>,
143) {
144    let foreign = crate::ForeignData { data, finalizer };
145    store.store.epoch_deadline_callback(move |mut store_ctx| {
146        let _ = &foreign; // Move foreign into this closure
147        let mut delta: u64 = 0;
148        let mut kind = WASMTIME_UPDATE_DEADLINE_CONTINUE;
149        let result = (func)(
150            store_ctx.as_context_mut(),
151            foreign.data,
152            &mut delta as *mut u64,
153            &mut kind as *mut wasmtime_update_deadline_kind_t,
154        );
155        match result {
156            Some(err) => Err((*err).into()),
157            None if kind == WASMTIME_UPDATE_DEADLINE_CONTINUE => {
158                Ok(UpdateDeadline::Continue(delta))
159            }
160            #[cfg(feature = "async")]
161            None if kind == WASMTIME_UPDATE_DEADLINE_YIELD => Ok(UpdateDeadline::Yield(delta)),
162            _ => panic!("unknown wasmtime_update_deadline_kind_t: {kind}"),
163        }
164    });
165}
166
167#[unsafe(no_mangle)]
168pub extern "C" fn wasmtime_store_context(
169    store: &mut wasmtime_store_t,
170) -> WasmtimeStoreContextMut<'_> {
171    store.store.as_context_mut()
172}
173
174#[unsafe(no_mangle)]
175pub extern "C" fn wasmtime_store_limiter(
176    store: &mut wasmtime_store_t,
177    memory_size: i64,
178    table_elements: i64,
179    instances: i64,
180    tables: i64,
181    memories: i64,
182) {
183    let mut limiter = StoreLimitsBuilder::new();
184    if memory_size >= 0 {
185        limiter = limiter.memory_size(memory_size as usize);
186    }
187    if table_elements >= 0 {
188        limiter = limiter.table_elements(table_elements as usize);
189    }
190    if instances >= 0 {
191        limiter = limiter.instances(instances as usize);
192    }
193    if tables >= 0 {
194        limiter = limiter.tables(tables as usize);
195    }
196    if memories >= 0 {
197        limiter = limiter.memories(memories as usize);
198    }
199    store.store.data_mut().store_limits = limiter.build();
200    store.store.limiter(|data| &mut data.store_limits);
201}
202
203#[unsafe(no_mangle)]
204pub extern "C" fn wasmtime_context_get_data(store: WasmtimeStoreContext<'_>) -> *mut c_void {
205    store.data().foreign.data
206}
207
208#[unsafe(no_mangle)]
209pub extern "C" fn wasmtime_context_set_data(
210    mut store: WasmtimeStoreContextMut<'_>,
211    data: *mut c_void,
212) {
213    store.data_mut().foreign.data = data;
214}
215
216#[cfg(feature = "wasi")]
217#[unsafe(no_mangle)]
218pub extern "C" fn wasmtime_context_set_wasi(
219    mut context: WasmtimeStoreContextMut<'_>,
220    wasi: Box<crate::wasi_config_t>,
221) -> Option<Box<wasmtime_error_t>> {
222    crate::handle_result(wasi.into_wasi_ctx(), |wasi| {
223        context.data_mut().wasi = Some(wasi);
224    })
225}
226
227#[unsafe(no_mangle)]
228pub extern "C" fn wasmtime_context_gc(mut context: WasmtimeStoreContextMut<'_>) {
229    context.gc(None);
230}
231
232#[unsafe(no_mangle)]
233pub extern "C" fn wasmtime_context_set_fuel(
234    mut store: WasmtimeStoreContextMut<'_>,
235    fuel: u64,
236) -> Option<Box<wasmtime_error_t>> {
237    crate::handle_result(store.set_fuel(fuel), |()| {})
238}
239
240#[unsafe(no_mangle)]
241pub extern "C" fn wasmtime_context_get_fuel(
242    store: WasmtimeStoreContext<'_>,
243    fuel: &mut u64,
244) -> Option<Box<wasmtime_error_t>> {
245    crate::handle_result(store.get_fuel(), |amt| {
246        *fuel = amt;
247    })
248}
249
250#[unsafe(no_mangle)]
251pub extern "C" fn wasmtime_context_set_epoch_deadline(
252    mut store: WasmtimeStoreContextMut<'_>,
253    ticks_beyond_current: u64,
254) {
255    store.set_epoch_deadline(ticks_beyond_current);
256}