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, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS,
15     RuntimeComponentInstanceIndex, TypeFuncIndex, TypeTuple,
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(
298         &self,
299         mut store: impl AsContextMut<Data: Send>,
300         params: &[Val],
301         results: &mut [Val],
302     ) -> Result<()> {
303         let mut store = store.as_context_mut();
304         assert!(
305             store.0.async_support(),
306             "cannot use `call_async` without enabling async support in the config"
307         );
308         store
309             .on_fiber(|store| self.call_impl(store, params, results))
310             .await?
311     }
312 
313     fn call_impl(
314         &self,
315         mut store: impl AsContextMut,
316         params: &[Val],
317         results: &mut [Val],
318     ) -> Result<()> {
319         let store = &mut store.as_context_mut();
320 
321         let param_tys = self.params(&store);
322         let result_tys = self.results(&store);
323 
324         if param_tys.len() != params.len() {
325             bail!(
326                 "expected {} argument(s), got {}",
327                 param_tys.len(),
328                 params.len()
329             );
330         }
331         if result_tys.len() != results.len() {
332             bail!(
333                 "expected {} results(s), got {}",
334                 result_tys.len(),
335                 results.len()
336             );
337         }
338 
339         self.call_raw(
340             store,
341             params,
342             |cx, params, params_ty, dst: &mut MaybeUninit<[ValRaw; MAX_FLAT_PARAMS]>| {
343                 let params_ty = match params_ty {
344                     InterfaceType::Tuple(i) => &cx.types[i],
345                     _ => unreachable!(),
346                 };
347                 if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() {
348                     let dst = &mut unsafe {
349                         mem::transmute::<_, &mut [MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>(dst)
350                     }
351                     .iter_mut();
352 
353                     params
354                         .iter()
355                         .zip(params_ty.types.iter())
356                         .try_for_each(|(param, ty)| param.lower(cx, *ty, dst))
357                 } else {
358                     self.store_args(cx, &params_ty, params, dst)
359                 }
360             },
361             |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| {
362                 let results_ty = match results_ty {
363                     InterfaceType::Tuple(i) => &cx.types[i],
364                     _ => unreachable!(),
365                 };
366                 if results_ty.abi.flat_count(MAX_FLAT_RESULTS).is_some() {
367                     let mut flat = src.iter();
368                     for (ty, slot) in results_ty.types.iter().zip(results) {
369                         *slot = Val::lift(cx, *ty, &mut flat)?;
370                     }
371                     Ok(())
372                 } else {
373                     Self::load_results(cx, results_ty, results, &mut src.iter())
374                 }
375             },
376         )
377     }
378 
379     /// Invokes the underlying wasm function, lowering arguments and lifting the
380     /// result.
381     ///
382     /// The `lower` function and `lift` function provided here are what actually
383     /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types
384     /// are what will be allocated on the stack for this function call. They
385     /// should be appropriately sized for the lowering/lifting operation
386     /// happening.
387     fn call_raw<T, Params: ?Sized, Return, LowerParams, LowerReturn>(
388         &self,
389         store: &mut StoreContextMut<'_, T>,
390         params: &Params,
391         lower: impl FnOnce(
392             &mut LowerContext<'_, T>,
393             &Params,
394             InterfaceType,
395             &mut MaybeUninit<LowerParams>,
396         ) -> Result<()>,
397         lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>,
398     ) -> Result<Return>
399     where
400         LowerParams: Copy,
401         LowerReturn: Copy,
402     {
403         let FuncData {
404             export,
405             options,
406             instance,
407             component_instance,
408             ty,
409             ..
410         } = store.0[self.0];
411 
412         let space = &mut MaybeUninit::<ParamsAndResults<LowerParams, LowerReturn>>::uninit();
413 
414         // Double-check the size/alignment of `space`, just in case.
415         //
416         // Note that this alone is not enough to guarantee the validity of the
417         // `unsafe` block below, but it's definitely required. In any case LLVM
418         // should be able to trivially see through these assertions and remove
419         // them in release mode.
420         let val_size = mem::size_of::<ValRaw>();
421         let val_align = mem::align_of::<ValRaw>();
422         assert!(mem::size_of_val(space) % val_size == 0);
423         assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0);
424         assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0);
425         assert!(mem::align_of_val(space) == val_align);
426         assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align);
427         assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align);
428 
429         let instance = store.0[instance.0].as_ref().unwrap();
430         let types = instance.component_types().clone();
431         let mut flags = instance.instance().instance_flags(component_instance);
432 
433         unsafe {
434             // Test the "may enter" flag which is a "lock" on this instance.
435             // This is immediately set to `false` afterwards and note that
436             // there's no on-cleanup setting this flag back to true. That's an
437             // intentional design aspect where if anything goes wrong internally
438             // from this point on the instance is considered "poisoned" and can
439             // never be entered again. The only time this flag is set to `true`
440             // again is after post-return logic has completed successfully.
441             if !flags.may_enter() {
442                 bail!(crate::Trap::CannotEnterComponent);
443             }
444             flags.set_may_enter(false);
445 
446             debug_assert!(flags.may_leave());
447             flags.set_may_leave(false);
448             let instance_ptr = instance.instance_ptr();
449             let mut cx = LowerContext::new(store.as_context_mut(), &options, &types, instance_ptr);
450             cx.enter_call();
451             let result = lower(
452                 &mut cx,
453                 params,
454                 InterfaceType::Tuple(types[ty].params),
455                 map_maybe_uninit!(space.params),
456             );
457             flags.set_may_leave(true);
458             result?;
459 
460             // This is unsafe as we are providing the guarantee that all the
461             // inputs are valid. The various pointers passed in for the function
462             // are all valid since they're coming from our store, and the
463             // `params_and_results` should have the correct layout for the core
464             // wasm function we're calling. Note that this latter point relies
465             // on the correctness of this module and `ComponentType`
466             // implementations, hence `ComponentType` being an `unsafe` trait.
467             crate::Func::call_unchecked_raw(
468                 store,
469                 export.func_ref,
470                 NonNull::new(core::ptr::slice_from_raw_parts_mut(
471                     space.as_mut_ptr().cast(),
472                     mem::size_of_val(space) / mem::size_of::<ValRaw>(),
473                 ))
474                 .unwrap(),
475             )?;
476 
477             // Note that `.assume_init_ref()` here is unsafe but we're relying
478             // on the correctness of the structure of `LowerReturn` and the
479             // type-checking performed to acquire the `TypedFunc` to make this
480             // safe. It should be the case that `LowerReturn` is the exact
481             // representation of the return value when interpreted as
482             // `[ValRaw]`, and additionally they should have the correct types
483             // for the function we just called (which filled in the return
484             // values).
485             let ret = map_maybe_uninit!(space.ret).assume_init_ref();
486 
487             // Lift the result into the host while managing post-return state
488             // here as well.
489             //
490             // After a successful lift the return value of the function, which
491             // is currently required to be 0 or 1 values according to the
492             // canonical ABI, is saved within the `Store`'s `FuncData`. This'll
493             // later get used in post-return.
494             flags.set_needs_post_return(true);
495             let val = lift(
496                 &mut LiftContext::new(store.0, &options, &types, instance_ptr),
497                 InterfaceType::Tuple(types[ty].results),
498                 ret,
499             )?;
500             let ret_slice = storage_as_slice(ret);
501             let data = &mut store.0[self.0];
502             assert!(data.post_return_arg.is_none());
503             match ret_slice.len() {
504                 0 => data.post_return_arg = Some(ValRaw::i32(0)),
505                 1 => data.post_return_arg = Some(ret_slice[0]),
506                 _ => unreachable!(),
507             }
508             return Ok(val);
509         }
510     }
511 
512     /// Invokes the `post-return` canonical ABI option, if specified, after a
513     /// [`Func::call`] has finished.
514     ///
515     /// This function is a required method call after a [`Func::call`] completes
516     /// successfully. After the embedder has finished processing the return
517     /// value then this function must be invoked.
518     ///
519     /// # Errors
520     ///
521     /// This function will return an error in the case of a WebAssembly trap
522     /// happening during the execution of the `post-return` function, if
523     /// specified.
524     ///
525     /// # Panics
526     ///
527     /// This function will panic if it's not called under the correct
528     /// conditions. This can only be called after a previous invocation of
529     /// [`Func::call`] completes successfully, and this function can only
530     /// be called for the same [`Func`] that was `call`'d.
531     ///
532     /// If this function is called when [`Func::call`] was not previously
533     /// called, then it will panic. If a different [`Func`] for the same
534     /// component instance was invoked then this function will also panic
535     /// because the `post-return` needs to happen for the other function.
536     ///
537     /// Panics if this is called on a function in an asynchronous store.
538     /// This only works with functions defined within a synchronous store.
539     #[inline]
540     pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> {
541         let store = store.as_context_mut();
542         assert!(
543             !store.0.async_support(),
544             "must use `post_return_async` when async support is enabled on the config"
545         );
546         self.post_return_impl(store)
547     }
548 
549     /// Exactly like [`Self::post_return`] except for use on async stores.
550     ///
551     /// # Panics
552     ///
553     /// Panics if this is called on a function in a synchronous store. This
554     /// only works with functions defined within an asynchronous store.
555     #[cfg(feature = "async")]
556     pub async fn post_return_async(&self, mut store: impl AsContextMut<Data: Send>) -> Result<()> {
557         let mut store = store.as_context_mut();
558         assert!(
559             store.0.async_support(),
560             "cannot use `call_async` without enabling async support in the config"
561         );
562         // Future optimization opportunity: conditionally use a fiber here since
563         // some func's post_return will not need the async context (i.e. end up
564         // calling async host functionality)
565         store.on_fiber(|store| self.post_return_impl(store)).await?
566     }
567 
568     fn post_return_impl(&self, mut store: impl AsContextMut) -> Result<()> {
569         let mut store = store.as_context_mut();
570         let data = &mut store.0[self.0];
571         let instance = data.instance;
572         let post_return = data.post_return;
573         let component_instance = data.component_instance;
574         let post_return_arg = data.post_return_arg.take();
575         let instance = store.0[instance.0].as_ref().unwrap().instance_ptr();
576 
577         unsafe {
578             let mut flags = (*instance).instance_flags(component_instance);
579 
580             // First assert that the instance is in a "needs post return" state.
581             // This will ensure that the previous action on the instance was a
582             // function call above. This flag is only set after a component
583             // function returns so this also can't be called (as expected)
584             // during a host import for example.
585             //
586             // Note, though, that this assert is not sufficient because it just
587             // means some function on this instance needs its post-return
588             // called. We need a precise post-return for a particular function
589             // which is the second assert here (the `.expect`). That will assert
590             // that this function itself needs to have its post-return called.
591             //
592             // The theory at least is that these two asserts ensure component
593             // model semantics are upheld where the host properly calls
594             // `post_return` on the right function despite the call being a
595             // separate step in the API.
596             assert!(
597                 flags.needs_post_return(),
598                 "post_return can only be called after a function has previously been called",
599             );
600             let post_return_arg = post_return_arg.expect("calling post_return on wrong function");
601 
602             // This is a sanity-check assert which shouldn't ever trip.
603             assert!(!flags.may_enter());
604 
605             // Unset the "needs post return" flag now that post-return is being
606             // processed. This will cause future invocations of this method to
607             // panic, even if the function call below traps.
608             flags.set_needs_post_return(false);
609 
610             // If the function actually had a `post-return` configured in its
611             // canonical options that's executed here.
612             //
613             // Note that if this traps (returns an error) this function
614             // intentionally leaves the instance in a "poisoned" state where it
615             // can no longer be entered because `may_enter` is `false`.
616             if let Some(func) = post_return {
617                 crate::Func::call_unchecked_raw(
618                     &mut store,
619                     func.func_ref,
620                     NonNull::new(core::ptr::slice_from_raw_parts(&post_return_arg, 1).cast_mut())
621                         .unwrap(),
622                 )?;
623             }
624 
625             // And finally if everything completed successfully then the "may
626             // enter" flag is set to `true` again here which enables further use
627             // of the component.
628             flags.set_may_enter(true);
629 
630             let (calls, host_table, _) = store.0.component_resource_state();
631             ResourceTables {
632                 calls,
633                 host_table: Some(host_table),
634                 guest: Some((*instance).guest_tables()),
635             }
636             .exit_call()?;
637         }
638         Ok(())
639     }
640 
641     fn store_args<T>(
642         &self,
643         cx: &mut LowerContext<'_, T>,
644         params_ty: &TypeTuple,
645         args: &[Val],
646         dst: &mut MaybeUninit<[ValRaw; MAX_FLAT_PARAMS]>,
647     ) -> Result<()> {
648         let size = usize::try_from(params_ty.abi.size32).unwrap();
649         let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?;
650         let mut offset = ptr;
651         for (ty, arg) in params_ty.types.iter().zip(args) {
652             let abi = cx.types.canonical_abi(ty);
653             arg.store(cx, *ty, abi.next_field32_size(&mut offset))?;
654         }
655 
656         map_maybe_uninit!(dst[0]).write(ValRaw::i64(ptr as i64));
657 
658         Ok(())
659     }
660 
661     fn load_results(
662         cx: &mut LiftContext<'_>,
663         results_ty: &TypeTuple,
664         results: &mut [Val],
665         src: &mut core::slice::Iter<'_, ValRaw>,
666     ) -> Result<()> {
667         // FIXME(#4311): needs to read an i64 for memory64
668         let ptr = usize::try_from(src.next().unwrap().get_u32())?;
669         if ptr % usize::try_from(results_ty.abi.align32)? != 0 {
670             bail!("return pointer not aligned");
671         }
672 
673         let bytes = cx
674             .memory()
675             .get(ptr..)
676             .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap()))
677             .ok_or_else(|| anyhow::anyhow!("pointer out of bounds of memory"))?;
678 
679         let mut offset = 0;
680         for (ty, slot) in results_ty.types.iter().zip(results) {
681             let abi = cx.types.canonical_abi(ty);
682             let offset = abi.next_field32_size(&mut offset);
683             *slot = Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])?;
684         }
685         Ok(())
686     }
687 }
688