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