1 use crate::component::instance::Instance;
2 use crate::component::matching::InstanceType;
3 use crate::component::storage::storage_as_slice;
4 use crate::component::types::Type;
5 use crate::component::values::Val;
6 use crate::prelude::*;
7 use crate::runtime::vm::component::{ComponentInstance, InstanceFlags, ResourceTables};
8 use crate::runtime::vm::{Export, VMFuncRef};
9 use crate::store::StoreOpaque;
10 use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
11 use core::mem::{self, MaybeUninit};
12 use core::ptr::NonNull;
13 use wasmtime_environ::component::{
14     CanonicalOptions, CanonicalOptionsDataModel, ExportIndex, InterfaceType, MAX_FLAT_PARAMS,
15     MAX_FLAT_RESULTS, TypeFuncIndex, TypeTuple,
16 };
17 
18 #[cfg(feature = "component-model-async")]
19 use crate::component::concurrent::{self, PreparedCall};
20 #[cfg(feature = "component-model-async")]
21 use core::future::Future;
22 #[cfg(feature = "component-model-async")]
23 use core::pin::Pin;
24 
25 mod host;
26 mod options;
27 mod typed;
28 pub use self::host::*;
29 pub use self::options::*;
30 pub use self::typed::*;
31 
32 /// A WebAssembly component function which can be called.
33 ///
34 /// This type is the dual of [`wasmtime::Func`](crate::Func) for component
35 /// functions. An instance of [`Func`] represents a component function from a
36 /// component [`Instance`](crate::component::Instance). Like with
37 /// [`wasmtime::Func`](crate::Func) it's possible to call functions either
38 /// synchronously or asynchronously and either typed or untyped.
39 #[derive(Copy, Clone, Debug)]
40 #[repr(C)] // here for the C API.
41 pub struct Func {
42     instance: Instance,
43     index: ExportIndex,
44 }
45 
46 // Double-check that the C representation in `component/instance.h` matches our
47 // in-Rust representation here in terms of size/alignment/etc.
48 const _: () = {
49     #[repr(C)]
50     struct T(u64, u32);
51     #[repr(C)]
52     struct C(T, u32);
53     assert!(core::mem::size_of::<C>() == core::mem::size_of::<Func>());
54     assert!(core::mem::align_of::<C>() == core::mem::align_of::<Func>());
55     assert!(core::mem::offset_of!(Func, instance) == 0);
56 };
57 
58 impl Func {
59     pub(crate) fn from_lifted_func(instance: Instance, index: ExportIndex) -> Func {
60         Func { instance, index }
61     }
62 
63     /// Attempt to cast this [`Func`] to a statically typed [`TypedFunc`] with
64     /// the provided `Params` and `Return`.
65     ///
66     /// This function will perform a type-check at runtime that the [`Func`]
67     /// takes `Params` as parameters and returns `Return`. If the type-check
68     /// passes then a [`TypedFunc`] will be returned which can be used to
69     /// invoke the function in an efficient, statically-typed, and ergonomic
70     /// manner.
71     ///
72     /// The `Params` type parameter here is a tuple of the parameters to the
73     /// function. A function which takes no arguments should use `()`, a
74     /// function with one argument should use `(T,)`, etc. Note that all
75     /// `Params` must also implement the [`Lower`] trait since they're going
76     /// into wasm.
77     ///
78     /// The `Return` type parameter is the return value of this function. A
79     /// return value of `()` means that there's no return (similar to a Rust
80     /// unit return) and otherwise a type `T` can be specified. Note that the
81     /// `Return` must also implement the [`Lift`] trait since it's coming from
82     /// wasm.
83     ///
84     /// Types specified here must implement the [`ComponentType`] trait. This
85     /// trait is implemented for built-in types to Rust such as integer
86     /// primitives, floats, `Option<T>`, `Result<T, E>`, strings, `Vec<T>`, and
87     /// more. As parameters you'll be passing native Rust types.
88     ///
89     /// See the documentation for [`ComponentType`] for more information about
90     /// supported types.
91     ///
92     /// # Errors
93     ///
94     /// If the function does not actually take `Params` as its parameters or
95     /// return `Return` then an error will be returned.
96     ///
97     /// # Panics
98     ///
99     /// This function will panic if `self` is not owned by the `store`
100     /// specified.
101     ///
102     /// # Examples
103     ///
104     /// Calling a function which takes no parameters and has no return value:
105     ///
106     /// ```
107     /// # use wasmtime::component::Func;
108     /// # use wasmtime::Store;
109     /// # fn foo(func: &Func, store: &mut Store<()>) -> anyhow::Result<()> {
110     /// let typed = func.typed::<(), ()>(&store)?;
111     /// typed.call(store, ())?;
112     /// # Ok(())
113     /// # }
114     /// ```
115     ///
116     /// Calling a function which takes one string parameter and returns a
117     /// string:
118     ///
119     /// ```
120     /// # use wasmtime::component::Func;
121     /// # use wasmtime::Store;
122     /// # fn foo(func: &Func, mut store: Store<()>) -> anyhow::Result<()> {
123     /// let typed = func.typed::<(&str,), (String,)>(&store)?;
124     /// let ret = typed.call(&mut store, ("Hello, ",))?.0;
125     /// println!("returned string was: {}", ret);
126     /// # Ok(())
127     /// # }
128     /// ```
129     ///
130     /// Calling a function which takes multiple parameters and returns a boolean:
131     ///
132     /// ```
133     /// # use wasmtime::component::Func;
134     /// # use wasmtime::Store;
135     /// # fn foo(func: &Func, mut store: Store<()>) -> anyhow::Result<()> {
136     /// let typed = func.typed::<(u32, Option<&str>, &[u8]), (bool,)>(&store)?;
137     /// let ok: bool = typed.call(&mut store, (1, Some("hello"), b"bytes!"))?.0;
138     /// println!("return value was: {ok}");
139     /// # Ok(())
140     /// # }
141     /// ```
142     pub fn typed<Params, Return>(&self, store: impl AsContext) -> Result<TypedFunc<Params, Return>>
143     where
144         Params: ComponentNamedList + Lower,
145         Return: ComponentNamedList + Lift,
146     {
147         self._typed(store.as_context().0, None)
148     }
149 
150     pub(crate) fn _typed<Params, Return>(
151         &self,
152         store: &StoreOpaque,
153         instance: Option<&ComponentInstance>,
154     ) -> Result<TypedFunc<Params, Return>>
155     where
156         Params: ComponentNamedList + Lower,
157         Return: ComponentNamedList + Lift,
158     {
159         self.typecheck::<Params, Return>(store, instance)?;
160         unsafe { Ok(TypedFunc::new_unchecked(*self)) }
161     }
162 
163     fn typecheck<Params, Return>(
164         &self,
165         store: &StoreOpaque,
166         instance: Option<&ComponentInstance>,
167     ) -> Result<()>
168     where
169         Params: ComponentNamedList + Lower,
170         Return: ComponentNamedList + Lift,
171     {
172         let cx = InstanceType::new(instance.unwrap_or_else(|| self.instance.id().get(store)));
173         let ty = &cx.types[self.ty(store)];
174 
175         Params::typecheck(&InterfaceType::Tuple(ty.params), &cx)
176             .context("type mismatch with parameters")?;
177         Return::typecheck(&InterfaceType::Tuple(ty.results), &cx)
178             .context("type mismatch with results")?;
179 
180         Ok(())
181     }
182 
183     /// Get the parameter names and types for this function.
184     pub fn params(&self, store: impl AsContext) -> Box<[(String, Type)]> {
185         let store = store.as_context();
186         let instance = self.instance.id().get(store.0);
187         let types = instance.component().types();
188         let func_ty = &types[self.ty(store.0)];
189         types[func_ty.params]
190             .types
191             .iter()
192             .zip(&func_ty.param_names)
193             .map(|(ty, name)| (name.clone(), Type::from(ty, &InstanceType::new(instance))))
194             .collect()
195     }
196 
197     /// Get the result types for this function.
198     pub fn results(&self, store: impl AsContext) -> Box<[Type]> {
199         let store = store.as_context();
200         let instance = self.instance.id().get(store.0);
201         let types = instance.component().types();
202         let ty = self.ty(store.0);
203         types[types[ty].results]
204             .types
205             .iter()
206             .map(|ty| Type::from(ty, &InstanceType::new(instance)))
207             .collect()
208     }
209 
210     fn ty(&self, store: &StoreOpaque) -> TypeFuncIndex {
211         let instance = self.instance.id().get(store);
212         let (ty, _, _) = instance.component().export_lifted_function(self.index);
213         ty
214     }
215 
216     /// Invokes this function with the `params` given and returns the result.
217     ///
218     /// The `params` provided must match the parameters that this function takes
219     /// in terms of their types and the number of parameters. Results will be
220     /// written to the `results` slice provided if the call completes
221     /// successfully. The initial types of the values in `results` are ignored
222     /// and values are overwritten to write the result. It's required that the
223     /// size of `results` exactly matches the number of results that this
224     /// function produces.
225     ///
226     /// Note that after a function is invoked the embedder needs to invoke
227     /// [`Func::post_return`] to execute any final cleanup required by the
228     /// guest. This function call is required to either call the function again
229     /// or to call another function.
230     ///
231     /// For more detailed information see the documentation of
232     /// [`TypedFunc::call`].
233     ///
234     /// # Errors
235     ///
236     /// Returns an error in situations including but not limited to:
237     ///
238     /// * `params` is not the right size or if the values have the wrong type
239     /// * `results` is not the right size
240     /// * A trap occurs while executing the function
241     /// * The function calls a host function which returns an error
242     ///
243     /// See [`TypedFunc::call`] for more information in addition to
244     /// [`wasmtime::Func::call`](crate::Func::call).
245     ///
246     /// # Panics
247     ///
248     /// Panics if this is called on a function in an asynchronous store. This
249     /// only works with functions defined within a synchronous store. Also
250     /// panics if `store` does not own this function.
251     pub fn call(
252         &self,
253         mut store: impl AsContextMut,
254         params: &[Val],
255         results: &mut [Val],
256     ) -> Result<()> {
257         let mut store = store.as_context_mut();
258         assert!(
259             !store.0.async_support(),
260             "must use `call_async` when async support is enabled on the config"
261         );
262         self.call_impl(&mut store.as_context_mut(), params, results)
263     }
264 
265     /// Exactly like [`Self::call`] except for use on async stores.
266     ///
267     /// Note that after this [`Func::post_return_async`] will be used instead of
268     /// the synchronous version at [`Func::post_return`].
269     ///
270     /// # Panics
271     ///
272     /// Panics if this is called on a function in a synchronous store. This
273     /// only works with functions defined within an asynchronous store. Also
274     /// panics if `store` does not own this function.
275     #[cfg(feature = "async")]
276     pub async fn call_async(
277         &self,
278         mut store: impl AsContextMut<Data: Send>,
279         params: &[Val],
280         results: &mut [Val],
281     ) -> Result<()> {
282         let mut store = store.as_context_mut();
283         assert!(
284             store.0.async_support(),
285             "cannot use `call_async` without enabling async support in the config"
286         );
287         store
288             .on_fiber(|store| self.call_impl(store, params, results))
289             .await?
290     }
291 
292     fn check_param_count<T>(&self, store: StoreContextMut<T>, count: usize) -> Result<()> {
293         let param_tys = self.params(&store);
294         if param_tys.len() != count {
295             bail!("expected {} argument(s), got {count}", param_tys.len());
296         }
297 
298         Ok(())
299     }
300 
301     /// Start a concurrent call to this function.
302     ///
303     /// Unlike [`Self::call`] and [`Self::call_async`] (both of which require
304     /// exclusive access to the store until the completion of the call), calls
305     /// made using this method may run concurrently with other calls to the same
306     /// instance.
307     ///
308     /// Note that the `Future` returned by this method will panic if polled or
309     /// `.await`ed outside of the event loop of the component instance this
310     /// function belongs to; use `Instance::run`, `Instance::run_with`, or
311     /// `Instance::spawn` to poll it from within the event loop.  See
312     /// [`Instance::run`] for examples.
313     #[cfg(feature = "component-model-async")]
314     pub fn call_concurrent<T: Send + 'static>(
315         self,
316         mut store: impl AsContextMut<Data = T>,
317         params: Vec<Val>,
318     ) -> Pin<Box<dyn Future<Output = Result<Vec<Val>>> + Send + 'static>> {
319         let mut store = store.as_context_mut();
320         assert!(
321             store.0.async_support(),
322             "cannot use `call_concurrent` when async support is not enabled on the config"
323         );
324 
325         let result = (|| {
326             self.check_param_count(store.as_context_mut(), params.len())?;
327             let prepared = self.prepare_call_dynamic(store.as_context_mut(), params)?;
328             concurrent::queue_call(store, prepared)
329         })();
330 
331         Box::pin(async move { result?.await })
332     }
333 
334     /// Calls `concurrent::prepare_call` with monomorphized functions for
335     /// lowering the parameters and lifting the result.
336     #[cfg(feature = "component-model-async")]
337     fn prepare_call_dynamic<'a, T: Send + 'static>(
338         self,
339         mut store: StoreContextMut<'a, T>,
340         params: Vec<Val>,
341     ) -> Result<PreparedCall<Vec<Val>>> {
342         let store = store.as_context_mut();
343 
344         concurrent::prepare_call(
345             store,
346             move |func, store, params_out| {
347                 func.with_lower_context(store, |cx, ty| {
348                     Self::lower_args(cx, &params, ty, params_out)
349                 })
350             },
351             move |func, store, results| {
352                 let max_flat = if func.abi_async(store) {
353                     MAX_FLAT_PARAMS
354                 } else {
355                     MAX_FLAT_RESULTS
356                 };
357                 let results = func.with_lift_context(store, |cx, ty| {
358                     Self::lift_results(cx, ty, results, max_flat)?.collect::<Result<Vec<_>>>()
359                 })?;
360                 Ok(Box::new(results))
361             },
362             self,
363             MAX_FLAT_PARAMS,
364         )
365     }
366 
367     fn call_impl(
368         &self,
369         mut store: impl AsContextMut,
370         params: &[Val],
371         results: &mut [Val],
372     ) -> Result<()> {
373         let mut store = store.as_context_mut();
374 
375         self.check_param_count(store.as_context_mut(), params.len())?;
376 
377         let result_tys = self.results(&store);
378 
379         if result_tys.len() != results.len() {
380             bail!(
381                 "expected {} result(s), got {}",
382                 result_tys.len(),
383                 results.len()
384             );
385         }
386 
387         if self.abi_async(store.0) {
388             unreachable!(
389                 "async-lifted exports should have failed validation \
390                  when `component-model-async` feature disabled"
391             );
392         }
393 
394         // SAFETY: the chosen representations of type parameters to `call_raw`
395         // here should be generally safe to work with:
396         //
397         // * parameters use `MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>`
398         //   which represents the maximal possible number of parameters that can
399         //   be passed to lifted component functions. This is modeled with
400         //   `MaybeUninit` to represent how it all starts as uninitialized and
401         //   thus can't be safely read during lowering.
402         //
403         // * results are modeled as `[ValRaw; MAX_FLAT_RESULTS]` which
404         //   represents the maximal size of values that can be returned. Note
405         //   that if the function doesn't actually have a return value then the
406         //   `ValRaw` inside the array will have undefined contents. That is
407         //   safe in Rust, however, due to `ValRaw` being a `union`. The
408         //   contents should dynamically not be read due to the type of the
409         //   function used here matching the actual lift.
410         unsafe {
411             self.call_raw(
412                 store,
413                 |cx, ty, dst: &mut MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>| {
414                     // SAFETY: it's safe to assume that
415                     // `MaybeUninit<array-of-maybe-uninit>` is initialized because
416                     // each individual element is still considered uninitialized.
417                     let dst: &mut [MaybeUninit<ValRaw>] = dst.assume_init_mut();
418                     Self::lower_args(cx, params, ty, dst)
419                 },
420                 |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| {
421                     let max_flat = MAX_FLAT_RESULTS;
422                     for (result, slot) in
423                         Self::lift_results(cx, results_ty, src, max_flat)?.zip(results)
424                     {
425                         *slot = result?;
426                     }
427                     Ok(())
428                 },
429             )
430         }
431     }
432 
433     pub(crate) fn lifted_core_func(&self, store: &mut StoreOpaque) -> NonNull<VMFuncRef> {
434         let def = {
435             let instance = self.instance.id().get(store);
436             let (_ty, def, _options) = instance.component().export_lifted_function(self.index);
437             def.clone()
438         };
439         match self.instance.lookup_vmdef(store, &def) {
440             Export::Function(f) => f.func_ref,
441             _ => unreachable!(),
442         }
443     }
444 
445     pub(crate) fn post_return_core_func(&self, store: &StoreOpaque) -> Option<NonNull<VMFuncRef>> {
446         let instance = self.instance.id().get(store);
447         let (_ty, _def, options) = instance.component().export_lifted_function(self.index);
448         options.post_return.map(|i| instance.runtime_post_return(i))
449     }
450 
451     pub(crate) fn abi_async(&self, store: &StoreOpaque) -> bool {
452         let instance = self.instance.id().get(store);
453         let (_ty, _def, options) = instance.component().export_lifted_function(self.index);
454         options.async_
455     }
456 
457     pub(crate) fn abi_info<'a>(
458         &self,
459         store: &'a StoreOpaque,
460     ) -> (Options, InstanceFlags, TypeFuncIndex, &'a CanonicalOptions) {
461         let vminstance = self.instance.id().get(store);
462         let (ty, _def, raw_options) = vminstance.component().export_lifted_function(self.index);
463         let mem_opts = match raw_options.data_model {
464             CanonicalOptionsDataModel::Gc {} => todo!("CM+GC"),
465             CanonicalOptionsDataModel::LinearMemory(opts) => opts,
466         };
467         let memory = mem_opts
468             .memory
469             .map(|i| NonNull::new(vminstance.runtime_memory(i)).unwrap());
470         let realloc = mem_opts.realloc.map(|i| vminstance.runtime_realloc(i));
471         let flags = vminstance.instance_flags(raw_options.instance);
472         let callback = raw_options.callback.map(|i| vminstance.runtime_callback(i));
473         let options = unsafe {
474             Options::new(
475                 store.id(),
476                 memory,
477                 realloc,
478                 raw_options.string_encoding,
479                 raw_options.async_,
480                 callback,
481             )
482         };
483         (options, flags, ty, raw_options)
484     }
485 
486     /// Invokes the underlying wasm function, lowering arguments and lifting the
487     /// result.
488     ///
489     /// The `lower` function and `lift` function provided here are what actually
490     /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types
491     /// are what will be allocated on the stack for this function call. They
492     /// should be appropriately sized for the lowering/lifting operation
493     /// happening.
494     ///
495     /// # Safety
496     ///
497     /// The safety of this function relies on the correct definitions of the
498     /// `LowerParams` and `LowerReturn` type. They must match the type of `self`
499     /// for the params/results that are going to be produced. Additionally
500     /// these types must be representable with a sequence of `ValRaw` values.
501     unsafe fn call_raw<T, Return, LowerParams, LowerReturn>(
502         &self,
503         mut store: StoreContextMut<'_, T>,
504         lower: impl FnOnce(
505             &mut LowerContext<'_, T>,
506             InterfaceType,
507             &mut MaybeUninit<LowerParams>,
508         ) -> Result<()>,
509         lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>,
510     ) -> Result<Return>
511     where
512         LowerParams: Copy,
513         LowerReturn: Copy,
514     {
515         let export = self.lifted_core_func(store.0);
516 
517         #[repr(C)]
518         union Union<Params: Copy, Return: Copy> {
519             params: Params,
520             ret: Return,
521         }
522 
523         let space = &mut MaybeUninit::<Union<LowerParams, LowerReturn>>::uninit();
524 
525         // Double-check the size/alignment of `space`, just in case.
526         //
527         // Note that this alone is not enough to guarantee the validity of the
528         // `unsafe` block below, but it's definitely required. In any case LLVM
529         // should be able to trivially see through these assertions and remove
530         // them in release mode.
531         let val_size = mem::size_of::<ValRaw>();
532         let val_align = mem::align_of::<ValRaw>();
533         assert!(mem::size_of_val(space) % val_size == 0);
534         assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0);
535         assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0);
536         assert!(mem::align_of_val(space) == val_align);
537         assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align);
538         assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align);
539 
540         self.with_lower_context(store.as_context_mut(), |cx, ty| {
541             cx.enter_call();
542             lower(cx, ty, map_maybe_uninit!(space.params))
543         })?;
544 
545         // SAFETY: We are providing the guarantee that all the inputs are valid.
546         // The various pointers passed in for the function are all valid since
547         // they're coming from our store, and the `params_and_results` should
548         // have the correct layout for the core wasm function we're calling.
549         // Note that this latter point relies on the correctness of this module
550         // and `ComponentType` implementations, hence `ComponentType` being an
551         // `unsafe` trait.
552         unsafe {
553             crate::Func::call_unchecked_raw(
554                 &mut store,
555                 export,
556                 NonNull::new(core::ptr::slice_from_raw_parts_mut(
557                     space.as_mut_ptr().cast(),
558                     mem::size_of_val(space) / mem::size_of::<ValRaw>(),
559                 ))
560                 .unwrap(),
561             )?;
562         }
563 
564         // SAFETY: We're relying on the correctness of the structure of
565         // `LowerReturn` and the type-checking performed to acquire the
566         // `TypedFunc` to make this safe. It should be the case that
567         // `LowerReturn` is the exact representation of the return value when
568         // interpreted as `[ValRaw]`, and additionally they should have the
569         // correct types for the function we just called (which filled in the
570         // return values).
571         let ret: &LowerReturn = unsafe { map_maybe_uninit!(space.ret).assume_init_ref() };
572 
573         // Lift the result into the host while managing post-return state
574         // here as well.
575         //
576         // After a successful lift the return value of the function, which
577         // is currently required to be 0 or 1 values according to the
578         // canonical ABI, is saved within the `Store`'s `FuncData`. This'll
579         // later get used in post-return.
580         // flags.set_needs_post_return(true);
581         let val = self.with_lift_context(store.0, |cx, ty| lift(cx, ty, ret))?;
582 
583         // SAFETY: it's a contract of this function that `LowerReturn` is an
584         // appropriate representation of the result of this function.
585         let ret_slice = unsafe { storage_as_slice(ret) };
586 
587         self.instance.id().get_mut(store.0).post_return_arg_set(
588             self.index,
589             match ret_slice.len() {
590                 0 => ValRaw::i32(0),
591                 1 => ret_slice[0],
592                 _ => unreachable!(),
593             },
594         );
595         return Ok(val);
596     }
597 
598     /// Invokes the `post-return` canonical ABI option, if specified, after a
599     /// [`Func::call`] has finished.
600     ///
601     /// This function is a required method call after a [`Func::call`] completes
602     /// successfully. After the embedder has finished processing the return
603     /// value then this function must be invoked.
604     ///
605     /// # Errors
606     ///
607     /// This function will return an error in the case of a WebAssembly trap
608     /// happening during the execution of the `post-return` function, if
609     /// specified.
610     ///
611     /// # Panics
612     ///
613     /// This function will panic if it's not called under the correct
614     /// conditions. This can only be called after a previous invocation of
615     /// [`Func::call`] completes successfully, and this function can only
616     /// be called for the same [`Func`] that was `call`'d.
617     ///
618     /// If this function is called when [`Func::call`] was not previously
619     /// called, then it will panic. If a different [`Func`] for the same
620     /// component instance was invoked then this function will also panic
621     /// because the `post-return` needs to happen for the other function.
622     ///
623     /// Panics if this is called on a function in an asynchronous store.
624     /// This only works with functions defined within a synchronous store.
625     #[inline]
626     pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> {
627         let store = store.as_context_mut();
628         assert!(
629             !store.0.async_support(),
630             "must use `post_return_async` when async support is enabled on the config"
631         );
632         self.post_return_impl(store)
633     }
634 
635     /// Exactly like [`Self::post_return`] except for use on async stores.
636     ///
637     /// # Panics
638     ///
639     /// Panics if this is called on a function in a synchronous store. This
640     /// only works with functions defined within an asynchronous store.
641     #[cfg(feature = "async")]
642     pub async fn post_return_async(&self, mut store: impl AsContextMut<Data: Send>) -> Result<()> {
643         let mut store = store.as_context_mut();
644         assert!(
645             store.0.async_support(),
646             "cannot use `post_return_async` without enabling async support in the config"
647         );
648         // Future optimization opportunity: conditionally use a fiber here since
649         // some func's post_return will not need the async context (i.e. end up
650         // calling async host functionality)
651         store.on_fiber(|store| self.post_return_impl(store)).await?
652     }
653 
654     fn post_return_impl(&self, mut store: impl AsContextMut) -> Result<()> {
655         let mut store = store.as_context_mut();
656 
657         let index = self.index;
658         let vminstance = self.instance.id().get(store.0);
659         let (_ty, _def, options) = vminstance.component().export_lifted_function(index);
660         let post_return = self.post_return_core_func(store.0);
661         let mut flags = vminstance.instance_flags(options.instance);
662         let mut instance = self.instance.id().get_mut(store.0);
663         let post_return_arg = instance.as_mut().post_return_arg_take(index);
664 
665         unsafe {
666             // First assert that the instance is in a "needs post return" state.
667             // This will ensure that the previous action on the instance was a
668             // function call above. This flag is only set after a component
669             // function returns so this also can't be called (as expected)
670             // during a host import for example.
671             //
672             // Note, though, that this assert is not sufficient because it just
673             // means some function on this instance needs its post-return
674             // called. We need a precise post-return for a particular function
675             // which is the second assert here (the `.expect`). That will assert
676             // that this function itself needs to have its post-return called.
677             //
678             // The theory at least is that these two asserts ensure component
679             // model semantics are upheld where the host properly calls
680             // `post_return` on the right function despite the call being a
681             // separate step in the API.
682             assert!(
683                 flags.needs_post_return(),
684                 "post_return can only be called after a function has previously been called",
685             );
686             let post_return_arg = post_return_arg.expect("calling post_return on wrong function");
687 
688             // This is a sanity-check assert which shouldn't ever trip.
689             assert!(!flags.may_enter());
690 
691             // Unset the "needs post return" flag now that post-return is being
692             // processed. This will cause future invocations of this method to
693             // panic, even if the function call below traps.
694             flags.set_needs_post_return(false);
695 
696             // If the function actually had a `post-return` configured in its
697             // canonical options that's executed here.
698             //
699             // Note that if this traps (returns an error) this function
700             // intentionally leaves the instance in a "poisoned" state where it
701             // can no longer be entered because `may_enter` is `false`.
702             if let Some(func) = post_return {
703                 crate::Func::call_unchecked_raw(
704                     &mut store,
705                     func,
706                     NonNull::new(core::ptr::slice_from_raw_parts(&post_return_arg, 1).cast_mut())
707                         .unwrap(),
708                 )?;
709             }
710 
711             // And finally if everything completed successfully then the "may
712             // enter" flag is set to `true` again here which enables further use
713             // of the component.
714             flags.set_may_enter(true);
715 
716             let (calls, host_table, _, instance) = store
717                 .0
718                 .component_resource_state_with_instance(self.instance);
719             ResourceTables {
720                 host_table: Some(host_table),
721                 calls,
722                 guest: Some(instance.guest_tables()),
723             }
724             .exit_call()?;
725         }
726         Ok(())
727     }
728 
729     fn lower_args<T>(
730         cx: &mut LowerContext<'_, T>,
731         params: &[Val],
732         params_ty: InterfaceType,
733         dst: &mut [MaybeUninit<ValRaw>],
734     ) -> Result<()> {
735         let params_ty = match params_ty {
736             InterfaceType::Tuple(i) => &cx.types[i],
737             _ => unreachable!(),
738         };
739         if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() {
740             let dst = &mut dst.iter_mut();
741 
742             params
743                 .iter()
744                 .zip(params_ty.types.iter())
745                 .try_for_each(|(param, ty)| param.lower(cx, *ty, dst))
746         } else {
747             Self::store_args(cx, &params_ty, params, dst)
748         }
749     }
750 
751     fn store_args<T>(
752         cx: &mut LowerContext<'_, T>,
753         params_ty: &TypeTuple,
754         args: &[Val],
755         dst: &mut [MaybeUninit<ValRaw>],
756     ) -> Result<()> {
757         let size = usize::try_from(params_ty.abi.size32).unwrap();
758         let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?;
759         let mut offset = ptr;
760         for (ty, arg) in params_ty.types.iter().zip(args) {
761             let abi = cx.types.canonical_abi(ty);
762             arg.store(cx, *ty, abi.next_field32_size(&mut offset))?;
763         }
764 
765         dst[0].write(ValRaw::i64(ptr as i64));
766 
767         Ok(())
768     }
769 
770     fn lift_results<'a, 'b>(
771         cx: &'a mut LiftContext<'b>,
772         results_ty: InterfaceType,
773         src: &'a [ValRaw],
774         max_flat: usize,
775     ) -> Result<Box<dyn Iterator<Item = Result<Val>> + 'a>> {
776         let results_ty = match results_ty {
777             InterfaceType::Tuple(i) => &cx.types[i],
778             _ => unreachable!(),
779         };
780         if results_ty.abi.flat_count(max_flat).is_some() {
781             let mut flat = src.iter();
782             Ok(Box::new(
783                 results_ty
784                     .types
785                     .iter()
786                     .map(move |ty| Val::lift(cx, *ty, &mut flat)),
787             ))
788         } else {
789             let iter = Self::load_results(cx, results_ty, &mut src.iter())?;
790             Ok(Box::new(iter))
791         }
792     }
793 
794     fn load_results<'a, 'b>(
795         cx: &'a mut LiftContext<'b>,
796         results_ty: &'a TypeTuple,
797         src: &mut core::slice::Iter<'_, ValRaw>,
798     ) -> Result<impl Iterator<Item = Result<Val>> + use<'a, 'b>> {
799         // FIXME(#4311): needs to read an i64 for memory64
800         let ptr = usize::try_from(src.next().unwrap().get_u32())?;
801         if ptr % usize::try_from(results_ty.abi.align32)? != 0 {
802             bail!("return pointer not aligned");
803         }
804 
805         let bytes = cx
806             .memory()
807             .get(ptr..)
808             .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap()))
809             .ok_or_else(|| anyhow::anyhow!("pointer out of bounds of memory"))?;
810 
811         let mut offset = 0;
812         Ok(results_ty.types.iter().map(move |ty| {
813             let abi = cx.types.canonical_abi(ty);
814             let offset = abi.next_field32_size(&mut offset);
815             Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])
816         }))
817     }
818 
819     /// Creates a `LowerContext` using the configuration values of this lifted
820     /// function.
821     ///
822     /// The `lower` closure provided should perform the actual lowering and
823     /// return the result of the lowering operation which is then returned from
824     /// this function as well.
825     fn with_lower_context<T>(
826         self,
827         mut store: StoreContextMut<T>,
828         lower: impl FnOnce(&mut LowerContext<T>, InterfaceType) -> Result<()>,
829     ) -> Result<()> {
830         let types = self.instance.id().get(store.0).component().types().clone();
831         let (options, mut flags, ty, _) = self.abi_info(store.0);
832 
833         // Test the "may enter" flag which is a "lock" on this instance.
834         // This is immediately set to `false` afterwards and note that
835         // there's no on-cleanup setting this flag back to true. That's an
836         // intentional design aspect where if anything goes wrong internally
837         // from this point on the instance is considered "poisoned" and can
838         // never be entered again. The only time this flag is set to `true`
839         // again is after post-return logic has completed successfully.
840         unsafe {
841             if !flags.may_enter() {
842                 bail!(crate::Trap::CannotEnterComponent);
843             }
844             flags.set_may_enter(false);
845         }
846 
847         // Perform the actual lowering, where while this is running the
848         // component is forbidden from calling imports.
849         unsafe {
850             debug_assert!(flags.may_leave());
851             flags.set_may_leave(false);
852         }
853         let mut cx = LowerContext::new(store.as_context_mut(), &options, &types, self.instance);
854         let result = lower(&mut cx, InterfaceType::Tuple(types[ty].params));
855         unsafe { flags.set_may_leave(true) };
856         result?;
857 
858         // If this is an async function then we're allowed to reenter the
859         // component at this point, and otherwise flag a post-return call being
860         // required as we're about to enter wasm and afterwards need a
861         // post-return.
862         unsafe {
863             if options.async_() {
864                 flags.set_may_enter(true);
865             } else {
866                 flags.set_needs_post_return(true);
867             }
868         }
869 
870         Ok(())
871     }
872 
873     /// Creates a `LiftContext` using the configuration values with this lifted
874     /// function.
875     ///
876     /// The closure `lift` provided should actually perform the lift itself and
877     /// the result of that closure is returned from this function call as well.
878     fn with_lift_context<R>(
879         self,
880         store: &mut StoreOpaque,
881         lift: impl FnOnce(&mut LiftContext, InterfaceType) -> Result<R>,
882     ) -> Result<R> {
883         let (options, _flags, ty, _) = self.abi_info(store);
884         let types = self.instance.id().get(store).component().types().clone();
885         lift(
886             &mut LiftContext::new(store, &options, &types, self.instance),
887             InterfaceType::Tuple(types[ty].results),
888         )
889     }
890 }
891