1 use crate::component::instance::{Instance, InstanceData};
2 use crate::component::storage::storage_as_slice;
3 use crate::component::types::Type;
4 use crate::component::values::Val;
5 use crate::prelude::*;
6 use crate::runtime::vm::component::ResourceTables;
7 use crate::runtime::vm::{Export, ExportFunction};
8 use crate::store::{StoreOpaque, Stored};
9 use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
10 use alloc::sync::Arc;
11 use core::mem::{self, MaybeUninit};
12 use core::ptr::NonNull;
13 use wasmtime_environ::component::{
14     CanonicalOptions, ComponentTypes, CoreDef, InterfaceType, RuntimeComponentInstanceIndex,
15     TypeFuncIndex, TypeTuple, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS,
16 };
17 
18 mod host;
19 mod options;
20 mod typed;
21 pub use self::host::*;
22 pub use self::options::*;
23 pub use self::typed::*;
24 
25 #[repr(C)]
26 union ParamsAndResults<Params: Copy, Return: Copy> {
27     params: Params,
28     ret: Return,
29 }
30 
31 /// A WebAssembly component function which can be called.
32 ///
33 /// This type is the dual of [`wasmtime::Func`](crate::Func) for component
34 /// functions. An instance of [`Func`] represents a component function from a
35 /// component [`Instance`](crate::component::Instance). Like with
36 /// [`wasmtime::Func`](crate::Func) it's possible to call functions either
37 /// synchronously or asynchronously and either typed or untyped.
38 #[derive(Copy, Clone, Debug)]
39 pub struct Func(Stored<FuncData>);
40 
41 #[doc(hidden)]
42 pub struct FuncData {
43     export: ExportFunction,
44     ty: TypeFuncIndex,
45     types: Arc<ComponentTypes>,
46     options: Options,
47     instance: Instance,
48     component_instance: RuntimeComponentInstanceIndex,
49     post_return: Option<ExportFunction>,
50     post_return_arg: Option<ValRaw>,
51 }
52 
53 impl Func {
54     pub(crate) fn from_lifted_func(
55         store: &mut StoreOpaque,
56         instance: &Instance,
57         data: &InstanceData,
58         ty: TypeFuncIndex,
59         func: &CoreDef,
60         options: &CanonicalOptions,
61     ) -> Func {
62         let export = match data.lookup_def(store, func) {
63             Export::Function(f) => f,
64             _ => unreachable!(),
65         };
66         let memory = options
67             .memory
68             .map(|i| NonNull::new(data.instance().runtime_memory(i)).unwrap());
69         let realloc = options.realloc.map(|i| data.instance().runtime_realloc(i));
70         let post_return = options.post_return.map(|i| {
71             let func_ref = data.instance().runtime_post_return(i);
72             ExportFunction { func_ref }
73         });
74         let component_instance = options.instance;
75         let options = unsafe { Options::new(store.id(), memory, realloc, options.string_encoding) };
76         Func(store.store_data_mut().insert(FuncData {
77             export,
78             options,
79             ty,
80             types: data.component_types().clone(),
81             instance: *instance,
82             component_instance,
83             post_return,
84             post_return_arg: None,
85         }))
86     }
87 
88     /// Attempt to cast this [`Func`] to a statically typed [`TypedFunc`] with
89     /// the provided `Params` and `Return`.
90     ///
91     /// This function will perform a type-check at runtime that the [`Func`]
92     /// takes `Params` as parameters and returns `Return`. If the type-check
93     /// passes then a [`TypedFunc`] will be returned which can be used to
94     /// invoke the function in an efficient, statically-typed, and ergonomic
95     /// manner.
96     ///
97     /// The `Params` type parameter here is a tuple of the parameters to the
98     /// function. A function which takes no arguments should use `()`, a
99     /// function with one argument should use `(T,)`, etc. Note that all
100     /// `Params` must also implement the [`Lower`] trait since they're going
101     /// into wasm.
102     ///
103     /// The `Return` type parameter is the return value of this function. A
104     /// return value of `()` means that there's no return (similar to a Rust
105     /// unit return) and otherwise a type `T` can be specified. Note that the
106     /// `Return` must also implement the [`Lift`] trait since it's coming from
107     /// wasm.
108     ///
109     /// Types specified here must implement the [`ComponentType`] trait. This
110     /// trait is implemented for built-in types to Rust such as integer
111     /// primitives, floats, `Option<T>`, `Result<T, E>`, strings, `Vec<T>`, and
112     /// more. As parameters you'll be passing native Rust types.
113     ///
114     /// See the documentation for [`ComponentType`] for more information about
115     /// supported types.
116     ///
117     /// # Errors
118     ///
119     /// If the function does not actually take `Params` as its parameters or
120     /// return `Return` then an error will be returned.
121     ///
122     /// # Panics
123     ///
124     /// This function will panic if `self` is not owned by the `store`
125     /// specified.
126     ///
127     /// # Examples
128     ///
129     /// Calling a function which takes no parameters and has no return value:
130     ///
131     /// ```
132     /// # use wasmtime::component::Func;
133     /// # use wasmtime::Store;
134     /// # fn foo(func: &Func, store: &mut Store<()>) -> anyhow::Result<()> {
135     /// let typed = func.typed::<(), ()>(&store)?;
136     /// typed.call(store, ())?;
137     /// # Ok(())
138     /// # }
139     /// ```
140     ///
141     /// Calling a function which takes one string parameter and returns a
142     /// string:
143     ///
144     /// ```
145     /// # use wasmtime::component::Func;
146     /// # use wasmtime::Store;
147     /// # fn foo(func: &Func, mut store: Store<()>) -> anyhow::Result<()> {
148     /// let typed = func.typed::<(&str,), (String,)>(&store)?;
149     /// let ret = typed.call(&mut store, ("Hello, ",))?.0;
150     /// println!("returned string was: {}", ret);
151     /// # Ok(())
152     /// # }
153     /// ```
154     ///
155     /// Calling a function which takes multiple parameters and returns a boolean:
156     ///
157     /// ```
158     /// # use wasmtime::component::Func;
159     /// # use wasmtime::Store;
160     /// # fn foo(func: &Func, mut store: Store<()>) -> anyhow::Result<()> {
161     /// let typed = func.typed::<(u32, Option<&str>, &[u8]), (bool,)>(&store)?;
162     /// let ok: bool = typed.call(&mut store, (1, Some("hello"), b"bytes!"))?.0;
163     /// println!("return value was: {ok}");
164     /// # Ok(())
165     /// # }
166     /// ```
167     pub fn typed<Params, Return>(&self, store: impl AsContext) -> Result<TypedFunc<Params, Return>>
168     where
169         Params: ComponentNamedList + Lower,
170         Return: ComponentNamedList + Lift,
171     {
172         self._typed(store.as_context().0, None)
173     }
174 
175     pub(crate) fn _typed<Params, Return>(
176         &self,
177         store: &StoreOpaque,
178         instance: Option<&InstanceData>,
179     ) -> Result<TypedFunc<Params, Return>>
180     where
181         Params: ComponentNamedList + Lower,
182         Return: ComponentNamedList + Lift,
183     {
184         self.typecheck::<Params, Return>(store, instance)?;
185         unsafe { Ok(TypedFunc::new_unchecked(*self)) }
186     }
187 
188     fn typecheck<Params, Return>(
189         &self,
190         store: &StoreOpaque,
191         instance: Option<&InstanceData>,
192     ) -> Result<()>
193     where
194         Params: ComponentNamedList + Lower,
195         Return: ComponentNamedList + Lift,
196     {
197         let data = &store[self.0];
198         let cx = instance
199             .unwrap_or_else(|| &store[data.instance.0].as_ref().unwrap())
200             .ty();
201         let ty = &cx.types[data.ty];
202 
203         Params::typecheck(&InterfaceType::Tuple(ty.params), &cx)
204             .context("type mismatch with parameters")?;
205         Return::typecheck(&InterfaceType::Tuple(ty.results), &cx)
206             .context("type mismatch with results")?;
207 
208         Ok(())
209     }
210 
211     /// Get the parameter names and types for this function.
212     pub fn params(&self, store: impl AsContext) -> Box<[(String, Type)]> {
213         let store = store.as_context();
214         let data = &store[self.0];
215         let instance = store[data.instance.0].as_ref().unwrap();
216         let func_ty = &data.types[data.ty];
217         data.types[func_ty.params]
218             .types
219             .iter()
220             .zip(&func_ty.param_names)
221             .map(|(ty, name)| (name.clone(), Type::from(ty, &instance.ty())))
222             .collect()
223     }
224 
225     /// Get the result types for this function.
226     pub fn results(&self, store: impl AsContext) -> Box<[Type]> {
227         let store = store.as_context();
228         let data = &store[self.0];
229         let instance = store[data.instance.0].as_ref().unwrap();
230         data.types[data.types[data.ty].results]
231             .types
232             .iter()
233             .map(|ty| Type::from(ty, &instance.ty()))
234             .collect()
235     }
236 
237     /// Invokes this function with the `params` given and returns the result.
238     ///
239     /// The `params` provided must match the parameters that this function takes
240     /// in terms of their types and the number of parameters. Results will be
241     /// written to the `results` slice provided if the call completes
242     /// successfully. The initial types of the values in `results` are ignored
243     /// and values are overwritten to write the result. It's required that the
244     /// size of `results` exactly matches the number of results that this
245     /// function produces.
246     ///
247     /// Note that after a function is invoked the embedder needs to invoke
248     /// [`Func::post_return`] to execute any final cleanup required by the
249     /// guest. This function call is required to either call the function again
250     /// or to call another function.
251     ///
252     /// For more detailed information see the documentation of
253     /// [`TypedFunc::call`].
254     ///
255     /// # Errors
256     ///
257     /// Returns an error in situations including but not limited to:
258     ///
259     /// * `params` is not the right size or if the values have the wrong type
260     /// * `results` is not the right size
261     /// * A trap occurs while executing the function
262     /// * The function calls a host function which returns an error
263     ///
264     /// See [`TypedFunc::call`] for more information in addition to
265     /// [`wasmtime::Func::call`](crate::Func::call).
266     ///
267     /// # Panics
268     ///
269     /// Panics if this is called on a function in an asynchronous store. This
270     /// only works with functions defined within a synchronous store. Also
271     /// panics if `store` does not own this function.
272     pub fn call(
273         &self,
274         mut store: impl AsContextMut,
275         params: &[Val],
276         results: &mut [Val],
277     ) -> Result<()> {
278         let mut store = store.as_context_mut();
279         assert!(
280             !store.0.async_support(),
281             "must use `call_async` when async support is enabled on the config"
282         );
283         self.call_impl(&mut store.as_context_mut(), params, results)
284     }
285 
286     /// Exactly like [`Self::call`] except for use on async stores.
287     ///
288     /// Note that after this [`Func::post_return_async`] will be used instead of
289     /// the synchronous version at [`Func::post_return`].
290     ///
291     /// # Panics
292     ///
293     /// Panics if this is called on a function in a synchronous store. This
294     /// only works with functions defined within an asynchronous store. Also
295     /// panics if `store` does not own this function.
296     #[cfg(feature = "async")]
297     pub async fn call_async<T>(
298         &self,
299         mut store: impl AsContextMut<Data = T>,
300         params: &[Val],
301         results: &mut [Val],
302     ) -> Result<()>
303     where
304         T: Send,
305     {
306         let mut store = store.as_context_mut();
307         assert!(
308             store.0.async_support(),
309             "cannot use `call_async` without enabling async support in the config"
310         );
311         store
312             .on_fiber(|store| self.call_impl(store, params, results))
313             .await?
314     }
315 
316     fn call_impl(
317         &self,
318         mut store: impl AsContextMut,
319         params: &[Val],
320         results: &mut [Val],
321     ) -> Result<()> {
322         let store = &mut store.as_context_mut();
323 
324         let param_tys = self.params(&store);
325         let result_tys = self.results(&store);
326 
327         if param_tys.len() != params.len() {
328             bail!(
329                 "expected {} argument(s), got {}",
330                 param_tys.len(),
331                 params.len()
332             );
333         }
334         if result_tys.len() != results.len() {
335             bail!(
336                 "expected {} results(s), got {}",
337                 result_tys.len(),
338                 results.len()
339             );
340         }
341 
342         self.call_raw(
343             store,
344             params,
345             |cx, params, params_ty, dst: &mut MaybeUninit<[ValRaw; MAX_FLAT_PARAMS]>| {
346                 let params_ty = match params_ty {
347                     InterfaceType::Tuple(i) => &cx.types[i],
348                     _ => unreachable!(),
349                 };
350                 if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() {
351                     let dst = &mut unsafe {
352                         mem::transmute::<_, &mut [MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>(dst)
353                     }
354                     .iter_mut();
355 
356                     params
357                         .iter()
358                         .zip(params_ty.types.iter())
359                         .try_for_each(|(param, ty)| param.lower(cx, *ty, dst))
360                 } else {
361                     self.store_args(cx, &params_ty, params, dst)
362                 }
363             },
364             |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| {
365                 let results_ty = match results_ty {
366                     InterfaceType::Tuple(i) => &cx.types[i],
367                     _ => unreachable!(),
368                 };
369                 if results_ty.abi.flat_count(MAX_FLAT_RESULTS).is_some() {
370                     let mut flat = src.iter();
371                     for (ty, slot) in results_ty.types.iter().zip(results) {
372                         *slot = Val::lift(cx, *ty, &mut flat)?;
373                     }
374                     Ok(())
375                 } else {
376                     Self::load_results(cx, results_ty, results, &mut src.iter())
377                 }
378             },
379         )
380     }
381 
382     /// Invokes the underlying wasm function, lowering arguments and lifting the
383     /// result.
384     ///
385     /// The `lower` function and `lift` function provided here are what actually
386     /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types
387     /// are what will be allocated on the stack for this function call. They
388     /// should be appropriately sized for the lowering/lifting operation
389     /// happening.
390     fn call_raw<T, Params: ?Sized, Return, LowerParams, LowerReturn>(
391         &self,
392         store: &mut StoreContextMut<'_, T>,
393         params: &Params,
394         lower: impl FnOnce(
395             &mut LowerContext<'_, T>,
396             &Params,
397             InterfaceType,
398             &mut MaybeUninit<LowerParams>,
399         ) -> Result<()>,
400         lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>,
401     ) -> Result<Return>
402     where
403         LowerParams: Copy,
404         LowerReturn: Copy,
405     {
406         let FuncData {
407             export,
408             options,
409             instance,
410             component_instance,
411             ty,
412             ..
413         } = store.0[self.0];
414 
415         let space = &mut MaybeUninit::<ParamsAndResults<LowerParams, LowerReturn>>::uninit();
416 
417         // Double-check the size/alignment of `space`, just in case.
418         //
419         // Note that this alone is not enough to guarantee the validity of the
420         // `unsafe` block below, but it's definitely required. In any case LLVM
421         // should be able to trivially see through these assertions and remove
422         // them in release mode.
423         let val_size = mem::size_of::<ValRaw>();
424         let val_align = mem::align_of::<ValRaw>();
425         assert!(mem::size_of_val(space) % val_size == 0);
426         assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0);
427         assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0);
428         assert!(mem::align_of_val(space) == val_align);
429         assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align);
430         assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align);
431 
432         let instance = store.0[instance.0].as_ref().unwrap();
433         let types = instance.component_types().clone();
434         let mut flags = instance.instance().instance_flags(component_instance);
435 
436         unsafe {
437             // Test the "may enter" flag which is a "lock" on this instance.
438             // This is immediately set to `false` afterwards and note that
439             // there's no on-cleanup setting this flag back to true. That's an
440             // intentional design aspect where if anything goes wrong internally
441             // from this point on the instance is considered "poisoned" and can
442             // never be entered again. The only time this flag is set to `true`
443             // again is after post-return logic has completed successfully.
444             if !flags.may_enter() {
445                 bail!(crate::Trap::CannotEnterComponent);
446             }
447             flags.set_may_enter(false);
448 
449             debug_assert!(flags.may_leave());
450             flags.set_may_leave(false);
451             let instance_ptr = instance.instance_ptr();
452             let mut cx = LowerContext::new(store.as_context_mut(), &options, &types, instance_ptr);
453             cx.enter_call();
454             let result = lower(
455                 &mut cx,
456                 params,
457                 InterfaceType::Tuple(types[ty].params),
458                 map_maybe_uninit!(space.params),
459             );
460             flags.set_may_leave(true);
461             result?;
462 
463             // This is unsafe as we are providing the guarantee that all the
464             // inputs are valid. The various pointers passed in for the function
465             // are all valid since they're coming from our store, and the
466             // `params_and_results` should have the correct layout for the core
467             // wasm function we're calling. Note that this latter point relies
468             // on the correctness of this module and `ComponentType`
469             // implementations, hence `ComponentType` being an `unsafe` trait.
470             crate::Func::call_unchecked_raw(
471                 store,
472                 export.func_ref,
473                 core::ptr::slice_from_raw_parts_mut(
474                     space.as_mut_ptr().cast(),
475                     mem::size_of_val(space) / mem::size_of::<ValRaw>(),
476                 ),
477             )?;
478 
479             // Note that `.assume_init_ref()` here is unsafe but we're relying
480             // on the correctness of the structure of `LowerReturn` and the
481             // type-checking performed to acquire the `TypedFunc` to make this
482             // safe. It should be the case that `LowerReturn` is the exact
483             // representation of the return value when interpreted as
484             // `[ValRaw]`, and additionally they should have the correct types
485             // for the function we just called (which filled in the return
486             // values).
487             let ret = map_maybe_uninit!(space.ret).assume_init_ref();
488 
489             // Lift the result into the host while managing post-return state
490             // here as well.
491             //
492             // After a successful lift the return value of the function, which
493             // is currently required to be 0 or 1 values according to the
494             // canonical ABI, is saved within the `Store`'s `FuncData`. This'll
495             // later get used in post-return.
496             flags.set_needs_post_return(true);
497             let val = lift(
498                 &mut LiftContext::new(store.0, &options, &types, instance_ptr),
499                 InterfaceType::Tuple(types[ty].results),
500                 ret,
501             )?;
502             let ret_slice = storage_as_slice(ret);
503             let data = &mut store.0[self.0];
504             assert!(data.post_return_arg.is_none());
505             match ret_slice.len() {
506                 0 => data.post_return_arg = Some(ValRaw::i32(0)),
507                 1 => data.post_return_arg = Some(ret_slice[0]),
508                 _ => unreachable!(),
509             }
510             return Ok(val);
511         }
512     }
513 
514     /// Invokes the `post-return` canonical ABI option, if specified, after a
515     /// [`Func::call`] has finished.
516     ///
517     /// This function is a required method call after a [`Func::call`] completes
518     /// successfully. After the embedder has finished processing the return
519     /// value then this function must be invoked.
520     ///
521     /// # Errors
522     ///
523     /// This function will return an error in the case of a WebAssembly trap
524     /// happening during the execution of the `post-return` function, if
525     /// specified.
526     ///
527     /// # Panics
528     ///
529     /// This function will panic if it's not called under the correct
530     /// conditions. This can only be called after a previous invocation of
531     /// [`Func::call`] completes successfully, and this function can only
532     /// be called for the same [`Func`] that was `call`'d.
533     ///
534     /// If this function is called when [`Func::call`] was not previously
535     /// called, then it will panic. If a different [`Func`] for the same
536     /// component instance was invoked then this function will also panic
537     /// because the `post-return` needs to happen for the other function.
538     ///
539     /// Panics if this is called on a function in an asynchronous store.
540     /// This only works with functions defined within a synchronous store.
541     #[inline]
542     pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> {
543         let store = store.as_context_mut();
544         assert!(
545             !store.0.async_support(),
546             "must use `post_return_async` when async support is enabled on the config"
547         );
548         self.post_return_impl(store)
549     }
550 
551     /// Exactly like [`Self::post_return`] except for use on async stores.
552     ///
553     /// # Panics
554     ///
555     /// Panics if this is called on a function in a synchronous store. This
556     /// only works with functions defined within an asynchronous store.
557     #[cfg(feature = "async")]
558     pub async fn post_return_async<T: Send>(
559         &self,
560         mut store: impl AsContextMut<Data = T>,
561     ) -> Result<()> {
562         let mut store = store.as_context_mut();
563         assert!(
564             store.0.async_support(),
565             "cannot use `call_async` without enabling async support in the config"
566         );
567         // Future optimization opportunity: conditionally use a fiber here since
568         // some func's post_return will not need the async context (i.e. end up
569         // calling async host functionality)
570         store.on_fiber(|store| self.post_return_impl(store)).await?
571     }
572 
573     fn post_return_impl(&self, mut store: impl AsContextMut) -> Result<()> {
574         let mut store = store.as_context_mut();
575         let data = &mut store.0[self.0];
576         let instance = data.instance;
577         let post_return = data.post_return;
578         let component_instance = data.component_instance;
579         let post_return_arg = data.post_return_arg.take();
580         let instance = store.0[instance.0].as_ref().unwrap().instance_ptr();
581 
582         unsafe {
583             let mut flags = (*instance).instance_flags(component_instance);
584 
585             // First assert that the instance is in a "needs post return" state.
586             // This will ensure that the previous action on the instance was a
587             // function call above. This flag is only set after a component
588             // function returns so this also can't be called (as expected)
589             // during a host import for example.
590             //
591             // Note, though, that this assert is not sufficient because it just
592             // means some function on this instance needs its post-return
593             // called. We need a precise post-return for a particular function
594             // which is the second assert here (the `.expect`). That will assert
595             // that this function itself needs to have its post-return called.
596             //
597             // The theory at least is that these two asserts ensure component
598             // model semantics are upheld where the host properly calls
599             // `post_return` on the right function despite the call being a
600             // separate step in the API.
601             assert!(
602                 flags.needs_post_return(),
603                 "post_return can only be called after a function has previously been called",
604             );
605             let post_return_arg = post_return_arg.expect("calling post_return on wrong function");
606 
607             // This is a sanity-check assert which shouldn't ever trip.
608             assert!(!flags.may_enter());
609 
610             // Unset the "needs post return" flag now that post-return is being
611             // processed. This will cause future invocations of this method to
612             // panic, even if the function call below traps.
613             flags.set_needs_post_return(false);
614 
615             // If the function actually had a `post-return` configured in its
616             // canonical options that's executed here.
617             //
618             // Note that if this traps (returns an error) this function
619             // intentionally leaves the instance in a "poisoned" state where it
620             // can no longer be entered because `may_enter` is `false`.
621             if let Some(func) = post_return {
622                 crate::Func::call_unchecked_raw(
623                     &mut store,
624                     func.func_ref,
625                     core::ptr::slice_from_raw_parts(&post_return_arg, 1).cast_mut(),
626                 )?;
627             }
628 
629             // And finally if everything completed successfully then the "may
630             // enter" flag is set to `true` again here which enables further use
631             // of the component.
632             flags.set_may_enter(true);
633 
634             let (calls, host_table, _) = store.0.component_resource_state();
635             ResourceTables {
636                 calls,
637                 host_table: Some(host_table),
638                 tables: Some((*instance).component_resource_tables()),
639             }
640             .exit_call()?;
641         }
642         Ok(())
643     }
644 
645     fn store_args<T>(
646         &self,
647         cx: &mut LowerContext<'_, T>,
648         params_ty: &TypeTuple,
649         args: &[Val],
650         dst: &mut MaybeUninit<[ValRaw; MAX_FLAT_PARAMS]>,
651     ) -> Result<()> {
652         let size = usize::try_from(params_ty.abi.size32).unwrap();
653         let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?;
654         let mut offset = ptr;
655         for (ty, arg) in params_ty.types.iter().zip(args) {
656             let abi = cx.types.canonical_abi(ty);
657             arg.store(cx, *ty, abi.next_field32_size(&mut offset))?;
658         }
659 
660         map_maybe_uninit!(dst[0]).write(ValRaw::i64(ptr as i64));
661 
662         Ok(())
663     }
664 
665     fn load_results(
666         cx: &mut LiftContext<'_>,
667         results_ty: &TypeTuple,
668         results: &mut [Val],
669         src: &mut core::slice::Iter<'_, ValRaw>,
670     ) -> Result<()> {
671         // FIXME: needs to read an i64 for memory64
672         let ptr = usize::try_from(src.next().unwrap().get_u32()).err2anyhow()?;
673         if ptr % usize::try_from(results_ty.abi.align32).err2anyhow()? != 0 {
674             bail!("return pointer not aligned");
675         }
676 
677         let bytes = cx
678             .memory()
679             .get(ptr..)
680             .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap()))
681             .ok_or_else(|| anyhow::anyhow!("pointer out of bounds of memory"))?;
682 
683         let mut offset = 0;
684         for (ty, slot) in results_ty.types.iter().zip(results) {
685             let abi = cx.types.canonical_abi(ty);
686             let offset = abi.next_field32_size(&mut offset);
687             *slot = Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])?;
688         }
689         Ok(())
690     }
691 }
692