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