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