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