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