Skip to main content

wasmtime/runtime/store/
async_.rs

1#[cfg(feature = "call-hook")]
2use crate::CallHook;
3use crate::fiber::{self};
4use crate::prelude::*;
5#[cfg(feature = "gc")]
6use crate::runtime::vm::VMStore;
7use crate::store::{AsContextMut, Asyncness, ResourceLimiterInner, StoreInner, StoreOpaque};
8use crate::{Store, StoreContextMut};
9
10/// An object that can take callbacks when the runtime enters or exits hostcalls.
11#[cfg(feature = "call-hook")]
12#[async_trait::async_trait]
13pub trait CallHookHandler<T>: Send {
14    /// A callback to run when wasmtime is about to enter a host call, or when about to
15    /// exit the hostcall.
16    async fn handle_call_event(&self, t: crate::StoreHookState<'_, T>, ch: CallHook) -> Result<()>;
17}
18
19impl<T> Store<T> {
20    /// Configures the [`ResourceLimiterAsync`](crate::ResourceLimiterAsync)
21    /// used to limit resource creation within this [`Store`].
22    ///
23    /// This method is an asynchronous variant of the [`Store::limiter`] method
24    /// where the embedder can block the wasm request for more resources with
25    /// host `async` execution of futures.
26    ///
27    /// By using a [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`)
28    /// with a [`Store`], you can no longer use
29    /// [`Memory::new`](`crate::Memory::new`),
30    /// [`Memory::grow`](`crate::Memory::grow`),
31    /// [`Table::new`](`crate::Table::new`), and
32    /// [`Table::grow`](`crate::Table::grow`). Instead, you must use their
33    /// `async` variants: [`Memory::new_async`](`crate::Memory::new_async`),
34    /// [`Memory::grow_async`](`crate::Memory::grow_async`),
35    /// [`Table::new_async`](`crate::Table::new_async`), and
36    /// [`Table::grow_async`](`crate::Table::grow_async`).
37    ///
38    /// Note that this limiter is only used to limit the creation/growth of
39    /// resources in the future, this does not retroactively attempt to apply
40    /// limits to the [`Store`].
41    ///
42    /// After configuring this method it's required that synchronous APIs in
43    /// Wasmtime are no longer used, such as [`Func::call`](crate::Func::call).
44    /// Instead APIs such as [`Func::call_async`](crate::Func::call_async) must
45    /// be used instead.
46    pub fn limiter_async(
47        &mut self,
48        mut limiter: impl (FnMut(&mut T) -> &mut dyn crate::ResourceLimiterAsync)
49        + Send
50        + Sync
51        + 'static,
52    ) {
53        // Apply the limits on instances, tables, and memory given by the limiter:
54        let inner = &mut self.inner;
55        let (instance_limit, table_limit, memory_limit) = {
56            let l = limiter(inner.data_mut());
57            (l.instances(), l.tables(), l.memories())
58        };
59        let innermost = &mut inner.inner;
60        innermost.instance_limit = instance_limit;
61        innermost.table_limit = table_limit;
62        innermost.memory_limit = memory_limit;
63
64        // Save the limiter accessor function:
65        inner.limiter = Some(ResourceLimiterInner::Async(Box::new(limiter)));
66        inner.set_async_required(Asyncness::Yes);
67    }
68
69    /// Configures an async function that runs on calls and returns between
70    /// WebAssembly and host code. For the non-async equivalent of this method,
71    /// see [`Store::call_hook`].
72    ///
73    /// The function is passed a [`CallHook`] argument, which indicates which
74    /// state transition the VM is making.
75    ///
76    /// This function's future may return a [`Trap`]. If a trap is returned
77    /// when an import was called, it is immediately raised as-if the host
78    /// import had returned the trap. If a trap is returned after wasm returns
79    /// to the host then the wasm function's result is ignored and this trap is
80    /// returned instead.
81    ///
82    /// After this function returns a trap, it may be called for subsequent
83    /// returns to host or wasm code as the trap propagates to the root call.
84    ///
85    /// If the future of an async call into WebAssembly, such as
86    /// [`Func::call_async`](crate::Func::call_async), is dropped before it
87    /// completes, the call is cancelled and no further user code runs for it,
88    /// including this hook. The [`CallHook::ReturningFromHost`] and
89    /// [`CallHook::ReturningFromWasm`] events that would otherwise match
90    /// earlier [`CallHook::CallingHost`] and [`CallHook::CallingWasm`] events
91    /// are not delivered for a cancelled call. Embedders that track state
92    /// across these events should reset it when they drop such a future.
93    ///
94    /// [`Trap`]: crate::Trap
95    #[cfg(feature = "call-hook")]
96    pub fn call_hook_async(&mut self, hook: impl CallHookHandler<T> + Send + Sync + 'static) {
97        // Call hooks may change the store as Wasm is entered and exited, at
98        // points that the trace does not represent.
99        self.inner.rr.poison("installing a call hook");
100        self.inner.call_hook = Some(crate::store::CallHookInner::Async(Box::new(hook)));
101        self.inner.set_async_required(Asyncness::Yes);
102    }
103
104    /// Perform garbage collection asynchronously.
105    ///
106    /// Note that it is not required to actively call this function. GC will
107    /// automatically happen according to various internal heuristics. This is
108    /// provided if fine-grained control over the GC is desired.
109    ///
110    /// This method is only available when the `gc` Cargo feature is enabled.
111    #[cfg(feature = "gc")]
112    pub async fn gc_async(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()>
113    where
114        T: Send,
115    {
116        StoreContextMut(&mut self.inner).gc_async(why).await
117    }
118
119    /// Manually grow the GC heap by at least `bytes` bytes.
120    ///
121    /// For more information, see the documentation of [`Store::gc_heap_grow`].
122    #[cfg(feature = "gc")]
123    pub async fn gc_heap_grow_async(&mut self, bytes: u64) -> Result<()> {
124        StoreContextMut(&mut self.inner)
125            .gc_heap_grow_async(bytes)
126            .await
127    }
128
129    /// Configures epoch-deadline expiration to yield to the async
130    /// caller and the update the deadline.
131    ///
132    /// When epoch-interruption-instrumented code is executed on this
133    /// store and the epoch deadline is reached before completion,
134    /// with the store configured in this way, execution will yield
135    /// (the future will return `Pending` but re-awake itself for
136    /// later execution) and, upon resuming, the store will be
137    /// configured with an epoch deadline equal to the current epoch
138    /// plus `delta` ticks.
139    ///
140    /// This setting is intended to allow for cooperative timeslicing
141    /// of multiple CPU-bound Wasm guests in different stores, all
142    /// executing under the control of an async executor. To drive
143    /// this, stores should be configured to "yield and update"
144    /// automatically with this function, and some external driver (a
145    /// thread that wakes up periodically, or a timer
146    /// signal/interrupt) should call
147    /// [`Engine::increment_epoch()`](crate::Engine::increment_epoch).
148    ///
149    /// See documentation on
150    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
151    /// for an introduction to epoch-based interruption.
152    #[cfg(target_has_atomic = "64")]
153    pub fn epoch_deadline_async_yield_and_update(&mut self, delta: u64) {
154        self.inner.epoch_deadline_async_yield_and_update(delta);
155    }
156
157    /// Sets the maximum number of simultaneously-live fibers permitted in this
158    /// store.
159    ///
160    /// Async entrypoints in Wasmtime, such as [`Func::call_async`] will
161    /// allocate fibers to execute WebAssembly code on. Fibers are additionally
162    /// used for implementing component model async-related primitives. Fibers
163    /// represent an allocated chunk of the host process's virtual address space
164    /// for use as a temporary native stack. Due to the cost of a fiber
165    /// allocation they're limited by default per-store with the ability for
166    /// embedders to tune limits as desired.
167    ///
168    /// Attempts to exceed this limit will be met with an immediate error. For
169    /// example [`Func::call_async`] will return an error when this limit is
170    /// reached.
171    ///
172    /// The limit counts live fibers, so a fiber returns budget once it
173    /// completes. Lowering it below the current live count does not affect
174    /// existing fibers, only blocks new ones until the count falls back under
175    /// it. A limit of 0 makes every async entry point fail.
176    ///
177    /// The default value for this is 64 fibers.
178    ///
179    /// [`Engine`]: crate::Engine
180    /// [`Func::call_async`]: crate::Func::call_async
181    pub fn set_max_fibers(&mut self, limit: u32) {
182        self.as_context_mut().set_max_fibers(limit)
183    }
184}
185
186impl<'a, T> StoreContextMut<'a, T> {
187    /// See [`Store::set_max_fibers`].
188    pub fn set_max_fibers(&mut self, limit: u32) {
189        self.0.async_state.max_fibers = limit;
190    }
191
192    /// Perform garbage collection of `ExternRef`s.
193    ///
194    /// Same as [`Store::gc`].
195    ///
196    /// This method is only available when the `gc` Cargo feature is enabled.
197    #[cfg(feature = "gc")]
198    pub async fn gc_async(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()>
199    where
200        T: Send + 'static,
201    {
202        let (mut limiter, store) = self.0.resource_limiter_and_store_opaque();
203        store
204            .gc(
205                limiter.as_mut(),
206                None,
207                why.map(|e| e.bytes_needed()),
208                crate::store::Asyncness::Yes,
209            )
210            .await?;
211        Ok(())
212    }
213
214    /// Manually grow the GC heap by at least `bytes` bytes.
215    ///
216    /// For more information, see the documentation of [`Store::gc_heap_grow`].
217    #[cfg(feature = "gc")]
218    pub async fn gc_heap_grow_async(&mut self, bytes: u64) -> Result<()> {
219        let (mut limiter, store) = self.0.resource_limiter_and_store_opaque();
220        store
221            .grow_gc_heap(limiter.as_mut(), bytes, crate::store::Asyncness::Yes)
222            .await
223    }
224
225    /// Configures epoch-deadline expiration to yield to the async
226    /// caller and the update the deadline.
227    ///
228    /// For more information see
229    /// [`Store::epoch_deadline_async_yield_and_update`].
230    #[cfg(target_has_atomic = "64")]
231    pub fn epoch_deadline_async_yield_and_update(&mut self, delta: u64) {
232        self.0.epoch_deadline_async_yield_and_update(delta);
233    }
234}
235
236impl<T> StoreInner<T> {
237    #[cfg(target_has_atomic = "64")]
238    fn epoch_deadline_async_yield_and_update(&mut self, delta: u64) {
239        // All future entrypoints must be async to handle the case that an epoch
240        // changes and a yield is required.
241        self.set_async_required(Asyncness::Yes);
242
243        self.epoch_deadline_behavior = super::EpochDeadlineBehavior::YieldAndUpdate(delta);
244    }
245}
246
247#[doc(hidden)]
248impl StoreOpaque {
249    pub(crate) fn allocate_fiber_stack(&mut self) -> Result<wasmtime_fiber::FiberStack> {
250        if self.async_state.live_fibers >= self.async_state.max_fibers {
251            bail!("store limit of fibers has been reached");
252        }
253        let stack = match self.async_state.last_fiber_stack().take() {
254            Some(stack) => stack,
255            None => self.engine().allocator().allocate_fiber_stack()?,
256        };
257        self.async_state.live_fibers += 1;
258        Ok(stack)
259    }
260
261    pub(crate) fn deallocate_fiber_stack(&mut self, stack: wasmtime_fiber::FiberStack) {
262        self.async_state.live_fibers -= 1;
263        self.flush_fiber_stack();
264        *self.async_state.last_fiber_stack() = Some(stack);
265    }
266
267    /// Releases the last fiber stack to the underlying instance allocator, if
268    /// present.
269    pub fn flush_fiber_stack(&mut self) {
270        if let Some(stack) = self.async_state.last_fiber_stack().take() {
271            unsafe {
272                self.engine.allocator().deallocate_fiber_stack(stack);
273            }
274        }
275    }
276}
277
278impl<T> StoreContextMut<'_, T> {
279    /// Executes a synchronous computation `func` asynchronously on a new fiber.
280    pub(crate) async fn on_fiber<R: Send + Sync>(
281        &mut self,
282        func: impl FnOnce(&mut StoreContextMut<'_, T>) -> R + Send + Sync,
283    ) -> Result<R> {
284        fiber::on_fiber(self.0, |me| func(&mut StoreContextMut(me))).await
285    }
286}