1 use crate::component::RuntimeInstance;
2 use crate::component::instance::Instance;
3 use crate::component::matching::InstanceType;
4 use crate::component::storage::storage_as_slice;
5 use crate::component::types::ComponentFunc;
6 use crate::component::values::Val;
7 use crate::prelude::*;
8 use crate::runtime::vm::component::{ComponentInstance, InstanceFlags, ResourceTables};
9 use crate::runtime::vm::{Export, VMFuncRef};
10 use crate::store::StoreOpaque;
11 use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
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, OptionsIndex,
16     TypeFuncIndex, 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<()>) -> wasmtime::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<()>) -> wasmtime::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<()>) -> wasmtime::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_index(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 type of this function.
181     pub fn ty(&self, store: impl AsContext) -> ComponentFunc {
182         self.ty_(store.as_context().0)
183     }
184 
185     fn ty_(&self, store: &StoreOpaque) -> ComponentFunc {
186         let cx = InstanceType::new(self.instance.id().get(store));
187         let ty = self.ty_index(store);
188         ComponentFunc::from(ty, &cx)
189     }
190 
191     fn ty_index(&self, store: &StoreOpaque) -> TypeFuncIndex {
192         let instance = self.instance.id().get(store);
193         let (ty, _, _) = instance.component().export_lifted_function(self.index);
194         ty
195     }
196 
197     /// Invokes this function with the `params` given and returns the result.
198     ///
199     /// The `params` provided must match the parameters that this function takes
200     /// in terms of their types and the number of parameters. Results will be
201     /// written to the `results` slice provided if the call completes
202     /// successfully. The initial types of the values in `results` are ignored
203     /// and values are overwritten to write the result. It's required that the
204     /// size of `results` exactly matches the number of results that this
205     /// function produces.
206     ///
207     /// Note that after a function is invoked the embedder needs to invoke
208     /// [`Func::post_return`] to execute any final cleanup required by the
209     /// guest. This function call is required to either call the function again
210     /// or to call another function.
211     ///
212     /// For more detailed information see the documentation of
213     /// [`TypedFunc::call`].
214     ///
215     /// # Errors
216     ///
217     /// Returns an error in situations including but not limited to:
218     ///
219     /// * `params` is not the right size or if the values have the wrong type
220     /// * `results` is not the right size
221     /// * A trap occurs while executing the function
222     /// * The function calls a host function which returns an error
223     ///
224     /// See [`TypedFunc::call`] for more information in addition to
225     /// [`wasmtime::Func::call`](crate::Func::call).
226     ///
227     /// # Panics
228     ///
229     /// Panics if this is called on a function in an asynchronous store. This
230     /// only works with functions defined within a synchronous store. Also
231     /// panics if `store` does not own this function.
232     pub fn call(
233         &self,
234         mut store: impl AsContextMut,
235         params: &[Val],
236         results: &mut [Val],
237     ) -> Result<()> {
238         let mut store = store.as_context_mut();
239         assert!(
240             !store.0.async_support(),
241             "must use `call_async` when async support is enabled on the config"
242         );
243         self.call_impl(&mut store.as_context_mut(), params, results)
244     }
245 
246     /// Exactly like [`Self::call`] except for use on async stores.
247     ///
248     /// Note that after this [`Func::post_return_async`] will be used instead of
249     /// the synchronous version at [`Func::post_return`].
250     ///
251     /// # Panics
252     ///
253     /// Panics if this is called on a function in a synchronous store. This
254     /// only works with functions defined within an asynchronous store. Also
255     /// panics if `store` does not own this function.
256     #[cfg(feature = "async")]
257     pub async fn call_async(
258         &self,
259         mut store: impl AsContextMut<Data: Send>,
260         params: &[Val],
261         results: &mut [Val],
262     ) -> Result<()> {
263         let store = store.as_context_mut();
264 
265         #[cfg(feature = "component-model-async")]
266         {
267             store
268                 .run_concurrent_trap_on_idle(async |store| {
269                     self.call_concurrent_dynamic(store, params, results, false)
270                         .await
271                         .map(drop)
272                 })
273                 .await?
274         }
275         #[cfg(not(feature = "component-model-async"))]
276         {
277             assert!(
278                 store.0.async_support(),
279                 "cannot use `call_async` without enabling async support in the config"
280             );
281             let mut store = store;
282             store
283                 .on_fiber(|store| self.call_impl(store, params, results))
284                 .await?
285         }
286     }
287 
288     fn check_params_results<T>(
289         &self,
290         store: StoreContextMut<T>,
291         params: &[Val],
292         results: &mut [Val],
293     ) -> Result<()> {
294         let ty = self.ty(&store);
295         if ty.params().len() != params.len() {
296             bail!(
297                 "expected {} argument(s), got {}",
298                 ty.params().len(),
299                 params.len(),
300             );
301         }
302 
303         if ty.results().len() != results.len() {
304             bail!(
305                 "expected {} result(s), got {}",
306                 ty.results().len(),
307                 results.len(),
308             );
309         }
310 
311         Ok(())
312     }
313 
314     /// Start a concurrent call to this function.
315     ///
316     /// Concurrency is achieved by relying on the [`Accessor`] argument, which
317     /// can be obtained by calling [`StoreContextMut::run_concurrent`].
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     /// This returns a [`TaskExit`] representing the completion of the guest
327     /// task and any transitive subtasks it might create.
328     ///
329     /// # Progress
330     ///
331     /// For the wasm task being created in `call_concurrent` to make progress it
332     /// must be run within the scope of [`run_concurrent`]. If there are no
333     /// active calls to [`run_concurrent`] then the wasm task will appear as
334     /// stalled. This is typically not a concern as an [`Accessor`] is bound
335     /// by default to a scope of [`run_concurrent`].
336     ///
337     /// One situation in which this can arise, for example, is that if a
338     /// [`run_concurrent`] computation finishes its async closure before all
339     /// wasm tasks have completed, then there will be no scope of
340     /// [`run_concurrent`] anywhere. In this situation the wasm tasks that have
341     /// not yet completed will not make progress until [`run_concurrent`] is
342     /// called again.
343     ///
344     /// Embedders will need to ensure that this future is `await`'d within the
345     /// scope of [`run_concurrent`] to ensure that the value can be produced
346     /// during the `await` call.
347     ///
348     /// # Cancellation
349     ///
350     /// Cancelling an async task created via `call_concurrent`, at this time, is
351     /// only possible by dropping the store that the computation runs within.
352     /// With [#11833] implemented then it will be possible to request
353     /// cancellation of a task, but that is not yet implemented. Hard-cancelling
354     /// a task will only ever be possible by dropping the entire store and it is
355     /// not possible to remove just one task from a store.
356     ///
357     /// This async function behaves more like a "spawn" than a normal Rust async
358     /// function. When this function is invoked then metadata for the function
359     /// call is recorded in the store connected to the `accessor` argument and
360     /// the wasm invocation is from then on connected to the store. If the
361     /// future created by this function is dropped it does not cancel the
362     /// in-progress execution of the wasm task. Dropping the future
363     /// relinquishes the host's ability to learn about the result of the task
364     /// but the task will still progress and invoke callbacks and such until
365     /// completion.
366     ///
367     /// [`run_concurrent`]: crate::Store::run_concurrent
368     /// [#11833]: https://github.com/bytecodealliance/wasmtime/issues/11833
369     /// [`Accessor`]: crate::component::Accessor
370     ///
371     /// # Panics
372     ///
373     /// Panics if the store that the [`Accessor`] is derived from does not own
374     /// this function.
375     ///
376     /// # Example
377     ///
378     /// Using [`StoreContextMut::run_concurrent`] to get an [`Accessor`]:
379     ///
380     /// ```
381     /// # use {
382     /// #   wasmtime::{
383     /// #     error::{Result},
384     /// #     component::{Component, Linker, ResourceTable},
385     /// #     Config, Engine, Store
386     /// #   },
387     /// # };
388     /// #
389     /// # struct Ctx { table: ResourceTable }
390     /// #
391     /// # async fn foo() -> Result<()> {
392     /// # let mut config = Config::new();
393     /// # let engine = Engine::new(&config)?;
394     /// # let mut store = Store::new(&engine, Ctx { table: ResourceTable::new() });
395     /// # let mut linker = Linker::new(&engine);
396     /// # let component = Component::new(&engine, "")?;
397     /// # let instance = linker.instantiate_async(&mut store, &component).await?;
398     /// let my_func = instance.get_func(&mut store, "my_func").unwrap();
399     /// store.run_concurrent(async |accessor| -> wasmtime::Result<_> {
400     ///    my_func.call_concurrent(accessor, &[], &mut Vec::new()).await?;
401     ///    Ok(())
402     /// }).await??;
403     /// # Ok(())
404     /// # }
405     /// ```
406     #[cfg(feature = "component-model-async")]
407     pub async fn call_concurrent(
408         self,
409         accessor: impl AsAccessor<Data: Send>,
410         params: &[Val],
411         results: &mut [Val],
412     ) -> Result<TaskExit> {
413         self.call_concurrent_dynamic(accessor, params, results, true)
414             .await
415     }
416 
417     /// Internal helper function for `call_async` and `call_concurrent`.
418     #[cfg(feature = "component-model-async")]
419     async fn call_concurrent_dynamic(
420         self,
421         accessor: impl AsAccessor<Data: Send>,
422         params: &[Val],
423         results: &mut [Val],
424         call_post_return_automatically: bool,
425     ) -> Result<TaskExit> {
426         let result = accessor.as_accessor().with(|mut store| {
427             assert!(
428                 store.as_context_mut().0.async_support(),
429                 "cannot use `call_concurrent` when async support is not enabled on the config"
430             );
431             self.check_params_results(store.as_context_mut(), params, results)?;
432             let prepared = self.prepare_call_dynamic(
433                 store.as_context_mut(),
434                 params.to_vec(),
435                 call_post_return_automatically,
436             )?;
437             concurrent::queue_call(store.as_context_mut(), prepared)
438         })?;
439 
440         let (run_results, rx) = result.await?;
441         assert_eq!(run_results.len(), results.len());
442         for (result, slot) in run_results.into_iter().zip(results) {
443             *slot = result;
444         }
445         Ok(TaskExit(rx))
446     }
447 
448     /// Calls `concurrent::prepare_call` with monomorphized functions for
449     /// lowering the parameters and lifting the result.
450     #[cfg(feature = "component-model-async")]
451     fn prepare_call_dynamic<'a, T: Send + 'static>(
452         self,
453         mut store: StoreContextMut<'a, T>,
454         params: Vec<Val>,
455         call_post_return_automatically: bool,
456     ) -> Result<PreparedCall<Vec<Val>>> {
457         let store = store.as_context_mut();
458 
459         concurrent::prepare_call(
460             store,
461             self,
462             MAX_FLAT_PARAMS,
463             false,
464             call_post_return_automatically,
465             move |func, store, params_out| {
466                 func.with_lower_context(store, call_post_return_automatically, |cx, ty| {
467                     Self::lower_args(cx, &params, ty, params_out)
468                 })
469             },
470             move |func, store, results| {
471                 let max_flat = if func.abi_async(store) {
472                     MAX_FLAT_PARAMS
473                 } else {
474                     MAX_FLAT_RESULTS
475                 };
476                 let results = func.with_lift_context(store, |cx, ty| {
477                     Self::lift_results(cx, ty, results, max_flat)?.collect::<Result<Vec<_>>>()
478                 })?;
479                 Ok(Box::new(results))
480             },
481         )
482     }
483 
484     fn call_impl(
485         &self,
486         mut store: impl AsContextMut,
487         params: &[Val],
488         results: &mut [Val],
489     ) -> Result<()> {
490         let mut store = store.as_context_mut();
491 
492         self.check_params_results(store.as_context_mut(), params, results)?;
493 
494         if self.abi_async(store.0) {
495             unreachable!(
496                 "async-lifted exports should have failed validation \
497                  when `component-model-async` feature disabled"
498             );
499         }
500 
501         // SAFETY: the chosen representations of type parameters to `call_raw`
502         // here should be generally safe to work with:
503         //
504         // * parameters use `MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>`
505         //   which represents the maximal possible number of parameters that can
506         //   be passed to lifted component functions. This is modeled with
507         //   `MaybeUninit` to represent how it all starts as uninitialized and
508         //   thus can't be safely read during lowering.
509         //
510         // * results are modeled as `[ValRaw; MAX_FLAT_RESULTS]` which
511         //   represents the maximal size of values that can be returned. Note
512         //   that if the function doesn't actually have a return value then the
513         //   `ValRaw` inside the array will have undefined contents. That is
514         //   safe in Rust, however, due to `ValRaw` being a `union`. The
515         //   contents should dynamically not be read due to the type of the
516         //   function used here matching the actual lift.
517         unsafe {
518             self.call_raw(
519                 store,
520                 |cx, ty, dst: &mut MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>| {
521                     // SAFETY: it's safe to assume that
522                     // `MaybeUninit<array-of-maybe-uninit>` is initialized because
523                     // each individual element is still considered uninitialized.
524                     let dst: &mut [MaybeUninit<ValRaw>] = dst.assume_init_mut();
525                     Self::lower_args(cx, params, ty, dst)
526                 },
527                 |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| {
528                     let max_flat = MAX_FLAT_RESULTS;
529                     for (result, slot) in
530                         Self::lift_results(cx, results_ty, src, max_flat)?.zip(results)
531                     {
532                         *slot = result?;
533                     }
534                     Ok(())
535                 },
536             )
537         }
538     }
539 
540     pub(crate) fn lifted_core_func(&self, store: &mut StoreOpaque) -> NonNull<VMFuncRef> {
541         let def = {
542             let instance = self.instance.id().get(store);
543             let (_ty, def, _options) = instance.component().export_lifted_function(self.index);
544             def.clone()
545         };
546         match self.instance.lookup_vmdef(store, &def) {
547             Export::Function(f) => f.vm_func_ref(store),
548             _ => unreachable!(),
549         }
550     }
551 
552     pub(crate) fn post_return_core_func(&self, store: &StoreOpaque) -> Option<NonNull<VMFuncRef>> {
553         let instance = self.instance.id().get(store);
554         let component = instance.component();
555         let (_ty, _def, options) = component.export_lifted_function(self.index);
556         let post_return = component.env_component().options[options].post_return;
557         post_return.map(|i| instance.runtime_post_return(i))
558     }
559 
560     pub(crate) fn abi_async(&self, store: &StoreOpaque) -> bool {
561         let instance = self.instance.id().get(store);
562         let component = instance.component();
563         let (_ty, _def, options) = component.export_lifted_function(self.index);
564         component.env_component().options[options].async_
565     }
566 
567     pub(crate) fn abi_info<'a>(
568         &self,
569         store: &'a StoreOpaque,
570     ) -> (
571         OptionsIndex,
572         InstanceFlags,
573         TypeFuncIndex,
574         &'a CanonicalOptions,
575     ) {
576         let vminstance = self.instance.id().get(store);
577         let component = vminstance.component();
578         let (ty, _def, options_index) = component.export_lifted_function(self.index);
579         let raw_options = &component.env_component().options[options_index];
580         (
581             options_index,
582             vminstance.instance_flags(raw_options.instance),
583             ty,
584             raw_options,
585         )
586     }
587 
588     /// Invokes the underlying wasm function, lowering arguments and lifting the
589     /// result.
590     ///
591     /// The `lower` function and `lift` function provided here are what actually
592     /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types
593     /// are what will be allocated on the stack for this function call. They
594     /// should be appropriately sized for the lowering/lifting operation
595     /// happening.
596     ///
597     /// # Safety
598     ///
599     /// The safety of this function relies on the correct definitions of the
600     /// `LowerParams` and `LowerReturn` type. They must match the type of `self`
601     /// for the params/results that are going to be produced. Additionally
602     /// these types must be representable with a sequence of `ValRaw` values.
603     unsafe fn call_raw<T, Return, LowerParams, LowerReturn>(
604         &self,
605         mut store: StoreContextMut<'_, T>,
606         lower: impl FnOnce(
607             &mut LowerContext<'_, T>,
608             InterfaceType,
609             &mut MaybeUninit<LowerParams>,
610         ) -> Result<()>,
611         lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>,
612     ) -> Result<Return>
613     where
614         LowerParams: Copy,
615         LowerReturn: Copy,
616     {
617         let export = self.lifted_core_func(store.0);
618         let (_options, _flags, _ty, raw_options) = self.abi_info(store.0);
619         let instance = RuntimeInstance {
620             instance: self.instance.id().instance(),
621             index: raw_options.instance,
622         };
623 
624         if !store.0.may_enter(instance) {
625             bail!(crate::Trap::CannotEnterComponent);
626         }
627 
628         #[repr(C)]
629         union Union<Params: Copy, Return: Copy> {
630             params: Params,
631             ret: Return,
632         }
633 
634         let space = &mut MaybeUninit::<Union<LowerParams, LowerReturn>>::uninit();
635 
636         // Double-check the size/alignment of `space`, just in case.
637         //
638         // Note that this alone is not enough to guarantee the validity of the
639         // `unsafe` block below, but it's definitely required. In any case LLVM
640         // should be able to trivially see through these assertions and remove
641         // them in release mode.
642         let val_size = mem::size_of::<ValRaw>();
643         let val_align = mem::align_of::<ValRaw>();
644         assert!(mem::size_of_val(space) % val_size == 0);
645         assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0);
646         assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0);
647         assert!(mem::align_of_val(space) == val_align);
648         assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align);
649         assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align);
650 
651         self.with_lower_context(store.as_context_mut(), false, |cx, ty| {
652             cx.enter_call();
653             lower(cx, ty, map_maybe_uninit!(space.params))
654         })?;
655 
656         // SAFETY: We are providing the guarantee that all the inputs are valid.
657         // The various pointers passed in for the function are all valid since
658         // they're coming from our store, and the `params_and_results` should
659         // have the correct layout for the core wasm function we're calling.
660         // Note that this latter point relies on the correctness of this module
661         // and `ComponentType` implementations, hence `ComponentType` being an
662         // `unsafe` trait.
663         unsafe {
664             crate::Func::call_unchecked_raw(
665                 &mut store,
666                 export,
667                 NonNull::new(core::ptr::slice_from_raw_parts_mut(
668                     space.as_mut_ptr().cast(),
669                     mem::size_of_val(space) / mem::size_of::<ValRaw>(),
670                 ))
671                 .unwrap(),
672             )?;
673         }
674 
675         // SAFETY: We're relying on the correctness of the structure of
676         // `LowerReturn` and the type-checking performed to acquire the
677         // `TypedFunc` to make this safe. It should be the case that
678         // `LowerReturn` is the exact representation of the return value when
679         // interpreted as `[ValRaw]`, and additionally they should have the
680         // correct types for the function we just called (which filled in the
681         // return values).
682         let ret: &LowerReturn = unsafe { map_maybe_uninit!(space.ret).assume_init_ref() };
683 
684         // Lift the result into the host while managing post-return state
685         // here as well.
686         //
687         // After a successful lift the return value of the function, which
688         // is currently required to be 0 or 1 values according to the
689         // canonical ABI, is saved within the `Store`'s `FuncData`. This'll
690         // later get used in post-return.
691         // flags.set_needs_post_return(true);
692         let val = self.with_lift_context(store.0, |cx, ty| lift(cx, ty, ret))?;
693 
694         // SAFETY: it's a contract of this function that `LowerReturn` is an
695         // appropriate representation of the result of this function.
696         let ret_slice = unsafe { storage_as_slice(ret) };
697 
698         self.instance.id().get_mut(store.0).post_return_arg_set(
699             self.index,
700             match ret_slice.len() {
701                 0 => ValRaw::i32(0),
702                 1 => ret_slice[0],
703                 _ => unreachable!(),
704             },
705         );
706         return Ok(val);
707     }
708 
709     /// Invokes the `post-return` canonical ABI option, if specified, after a
710     /// [`Func::call`] has finished.
711     ///
712     /// This function is a required method call after a [`Func::call`] completes
713     /// successfully. After the embedder has finished processing the return
714     /// value then this function must be invoked.
715     ///
716     /// # Errors
717     ///
718     /// This function will return an error in the case of a WebAssembly trap
719     /// happening during the execution of the `post-return` function, if
720     /// specified.
721     ///
722     /// # Panics
723     ///
724     /// This function will panic if it's not called under the correct
725     /// conditions. This can only be called after a previous invocation of
726     /// [`Func::call`] completes successfully, and this function can only
727     /// be called for the same [`Func`] that was `call`'d.
728     ///
729     /// If this function is called when [`Func::call`] was not previously
730     /// called, then it will panic. If a different [`Func`] for the same
731     /// component instance was invoked then this function will also panic
732     /// because the `post-return` needs to happen for the other function.
733     ///
734     /// Panics if this is called on a function in an asynchronous store.
735     /// This only works with functions defined within a synchronous store.
736     #[inline]
737     pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> {
738         let store = store.as_context_mut();
739         assert!(
740             !store.0.async_support(),
741             "must use `post_return_async` when async support is enabled on the config"
742         );
743         self.post_return_impl(store)
744     }
745 
746     /// Exactly like [`Self::post_return`] except for use on async stores.
747     ///
748     /// # Panics
749     ///
750     /// Panics if this is called on a function in a synchronous store. This
751     /// only works with functions defined within an asynchronous store.
752     #[cfg(feature = "async")]
753     pub async fn post_return_async(&self, mut store: impl AsContextMut<Data: Send>) -> Result<()> {
754         let mut store = store.as_context_mut();
755         assert!(
756             store.0.async_support(),
757             "cannot use `post_return_async` without enabling async support in the config"
758         );
759         // Future optimization opportunity: conditionally use a fiber here since
760         // some func's post_return will not need the async context (i.e. end up
761         // calling async host functionality)
762         store.on_fiber(|store| self.post_return_impl(store)).await?
763     }
764 
765     fn post_return_impl(&self, mut store: impl AsContextMut) -> Result<()> {
766         let mut store = store.as_context_mut();
767 
768         let index = self.index;
769         let vminstance = self.instance.id().get(store.0);
770         let component = vminstance.component();
771         let (_ty, _def, options) = component.export_lifted_function(index);
772         let post_return = self.post_return_core_func(store.0);
773         let mut flags =
774             vminstance.instance_flags(component.env_component().options[options].instance);
775         let mut instance = self.instance.id().get_mut(store.0);
776         let post_return_arg = instance.as_mut().post_return_arg_take(index);
777 
778         unsafe {
779             // First assert that the instance is in a "needs post return" state.
780             // This will ensure that the previous action on the instance was a
781             // function call above. This flag is only set after a component
782             // function returns so this also can't be called (as expected)
783             // during a host import for example.
784             //
785             // Note, though, that this assert is not sufficient because it just
786             // means some function on this instance needs its post-return
787             // called. We need a precise post-return for a particular function
788             // which is the second assert here (the `.expect`). That will assert
789             // that this function itself needs to have its post-return called.
790             //
791             // The theory at least is that these two asserts ensure component
792             // model semantics are upheld where the host properly calls
793             // `post_return` on the right function despite the call being a
794             // separate step in the API.
795             assert!(
796                 flags.needs_post_return(),
797                 "post_return can only be called after a function has previously been called",
798             );
799             let post_return_arg = post_return_arg.expect("calling post_return on wrong function");
800 
801             // Unset the "needs post return" flag now that post-return is being
802             // processed. This will cause future invocations of this method to
803             // panic, even if the function call below traps.
804             flags.set_needs_post_return(false);
805 
806             // Post return functions are forbidden from calling imports or
807             // intrinsics.
808             flags.set_may_leave(false);
809 
810             // If the function actually had a `post-return` configured in its
811             // canonical options that's executed here.
812             if let Some(func) = post_return {
813                 crate::Func::call_unchecked_raw(
814                     &mut store,
815                     func,
816                     NonNull::new(core::ptr::slice_from_raw_parts(&post_return_arg, 1).cast_mut())
817                         .unwrap(),
818                 )?;
819             }
820 
821             // And finally if everything completed successfully then the "may
822             // leave" flags is set to `true` again here which enables further
823             // use of the component.
824             flags.set_may_leave(true);
825 
826             let (calls, host_table, _, instance) = store
827                 .0
828                 .component_resource_state_with_instance(self.instance);
829             ResourceTables {
830                 host_table: Some(host_table),
831                 calls,
832                 guest: Some(instance.instance_states()),
833             }
834             .exit_call()?;
835         }
836         Ok(())
837     }
838 
839     fn lower_args<T>(
840         cx: &mut LowerContext<'_, T>,
841         params: &[Val],
842         params_ty: InterfaceType,
843         dst: &mut [MaybeUninit<ValRaw>],
844     ) -> Result<()> {
845         let params_ty = match params_ty {
846             InterfaceType::Tuple(i) => &cx.types[i],
847             _ => unreachable!(),
848         };
849         if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() {
850             let dst = &mut dst.iter_mut();
851 
852             params
853                 .iter()
854                 .zip(params_ty.types.iter())
855                 .try_for_each(|(param, ty)| param.lower(cx, *ty, dst))
856         } else {
857             Self::store_args(cx, &params_ty, params, dst)
858         }
859     }
860 
861     fn store_args<T>(
862         cx: &mut LowerContext<'_, T>,
863         params_ty: &TypeTuple,
864         args: &[Val],
865         dst: &mut [MaybeUninit<ValRaw>],
866     ) -> Result<()> {
867         let size = usize::try_from(params_ty.abi.size32).unwrap();
868         let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?;
869         let mut offset = ptr;
870         for (ty, arg) in params_ty.types.iter().zip(args) {
871             let abi = cx.types.canonical_abi(ty);
872             arg.store(cx, *ty, abi.next_field32_size(&mut offset))?;
873         }
874 
875         dst[0].write(ValRaw::i64(ptr as i64));
876 
877         Ok(())
878     }
879 
880     fn lift_results<'a, 'b>(
881         cx: &'a mut LiftContext<'b>,
882         results_ty: InterfaceType,
883         src: &'a [ValRaw],
884         max_flat: usize,
885     ) -> Result<Box<dyn Iterator<Item = Result<Val>> + 'a>> {
886         let results_ty = match results_ty {
887             InterfaceType::Tuple(i) => &cx.types[i],
888             _ => unreachable!(),
889         };
890         if results_ty.abi.flat_count(max_flat).is_some() {
891             let mut flat = src.iter();
892             Ok(Box::new(
893                 results_ty
894                     .types
895                     .iter()
896                     .map(move |ty| Val::lift(cx, *ty, &mut flat)),
897             ))
898         } else {
899             let iter = Self::load_results(cx, results_ty, &mut src.iter())?;
900             Ok(Box::new(iter))
901         }
902     }
903 
904     fn load_results<'a, 'b>(
905         cx: &'a mut LiftContext<'b>,
906         results_ty: &'a TypeTuple,
907         src: &mut core::slice::Iter<'_, ValRaw>,
908     ) -> Result<impl Iterator<Item = Result<Val>> + use<'a, 'b>> {
909         // FIXME(#4311): needs to read an i64 for memory64
910         let ptr = usize::try_from(src.next().unwrap().get_u32())?;
911         if ptr % usize::try_from(results_ty.abi.align32)? != 0 {
912             bail!("return pointer not aligned");
913         }
914 
915         let bytes = cx
916             .memory()
917             .get(ptr..)
918             .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap()))
919             .ok_or_else(|| crate::format_err!("pointer out of bounds of memory"))?;
920 
921         let mut offset = 0;
922         Ok(results_ty.types.iter().map(move |ty| {
923             let abi = cx.types.canonical_abi(ty);
924             let offset = abi.next_field32_size(&mut offset);
925             Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])
926         }))
927     }
928 
929     #[cfg(feature = "component-model-async")]
930     pub(crate) fn instance(self) -> Instance {
931         self.instance
932     }
933 
934     #[cfg(feature = "component-model-async")]
935     pub(crate) fn index(self) -> ExportIndex {
936         self.index
937     }
938 
939     /// Creates a `LowerContext` using the configuration values of this lifted
940     /// function.
941     ///
942     /// The `lower` closure provided should perform the actual lowering and
943     /// return the result of the lowering operation which is then returned from
944     /// this function as well.
945     fn with_lower_context<T>(
946         self,
947         mut store: StoreContextMut<T>,
948         call_post_return_automatically: bool,
949         lower: impl FnOnce(&mut LowerContext<T>, InterfaceType) -> Result<()>,
950     ) -> Result<()> {
951         let (options_idx, mut flags, ty, options) = self.abi_info(store.0);
952         let async_ = options.async_;
953 
954         // Perform the actual lowering, where while this is running the
955         // component is forbidden from calling imports.
956         unsafe {
957             debug_assert!(flags.may_leave());
958             flags.set_may_leave(false);
959         }
960         let mut cx = LowerContext::new(store.as_context_mut(), options_idx, self.instance);
961         let param_ty = InterfaceType::Tuple(cx.types[ty].params);
962         let result = lower(&mut cx, param_ty);
963         unsafe { flags.set_may_leave(true) };
964         result?;
965 
966         // If needed, flag a post-return call being required as we're about to
967         // enter wasm and afterwards need a post-return.
968         unsafe {
969             if !(call_post_return_automatically && async_) {
970                 flags.set_needs_post_return(true);
971             }
972         }
973 
974         Ok(())
975     }
976 
977     /// Creates a `LiftContext` using the configuration values with this lifted
978     /// function.
979     ///
980     /// The closure `lift` provided should actually perform the lift itself and
981     /// the result of that closure is returned from this function call as well.
982     fn with_lift_context<R>(
983         self,
984         store: &mut StoreOpaque,
985         lift: impl FnOnce(&mut LiftContext, InterfaceType) -> Result<R>,
986     ) -> Result<R> {
987         let (options, _flags, ty, _) = self.abi_info(store);
988         let mut cx = LiftContext::new(store, options, self.instance);
989         let ty = InterfaceType::Tuple(cx.types[ty].results);
990         lift(&mut cx, ty)
991     }
992 }
993 
994 /// Represents the completion of a task created using
995 /// `[Typed]Func::call_concurrent`.
996 ///
997 /// In general, a guest task may continue running after returning a value.
998 /// Moreover, any given guest task may create its own subtasks before or after
999 /// returning and may exit before some or all of those subtasks have finished
1000 /// running.  In that case, the still-running subtasks will be "reparented" to
1001 /// the nearest surviving caller, which may be the original host call.  The
1002 /// future returned by `TaskExit::block` will resolve once all transitive
1003 /// subtasks created directly or indirectly by the original call to
1004 /// `Instance::call_concurrent` have exited.
1005 #[cfg(feature = "component-model-async")]
1006 pub struct TaskExit(futures::channel::oneshot::Receiver<()>);
1007 
1008 #[cfg(feature = "component-model-async")]
1009 impl TaskExit {
1010     /// Returns a future which will resolve once all transitive subtasks created
1011     /// directly or indirectly by the original call to
1012     /// `Instance::call_concurrent` have exited.
1013     pub async fn block(self, accessor: impl AsAccessor<Data: Send>) {
1014         // The current implementation makes no use of `accessor`, but future
1015         // implementations might (e.g. by using a more efficient mechanism than
1016         // a oneshot channel).
1017         _ = accessor;
1018 
1019         // We don't care whether the sender sent us a value or was dropped
1020         // first; either one counts as a notification, so we ignore the result
1021         // once the future resolves:
1022         _ = self.0.await;
1023     }
1024 }
1025