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