wasmtime/runtime/component/func.rs
1use crate::component::instance::Instance;
2use crate::component::matching::InstanceType;
3use crate::component::storage::storage_as_slice;
4use crate::component::types::ComponentFunc;
5use crate::component::values::Val;
6use crate::prelude::*;
7use crate::runtime::vm::component::{ComponentInstance, InstanceFlags};
8use crate::runtime::vm::{Export, SendSyncPtr, UncaughtException, VMFuncRef};
9use crate::store::StoreOpaque;
10use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
11use core::mem::{self, MaybeUninit};
12use core::ptr::NonNull;
13use wasmtime_environ::component::{
14 CanonicalOptions, ExportIndex, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, OptionsIndex,
15 TypeFuncIndex, TypeTuple,
16};
17
18mod host;
19mod options;
20mod typed;
21pub use self::host::*;
22pub use self::options::*;
23pub use self::typed::*;
24
25/// A WebAssembly component function which can be called.
26///
27/// This type is the dual of [`wasmtime::Func`](crate::Func) for component
28/// functions. An instance of [`Func`] represents a component function from a
29/// component [`Instance`](crate::component::Instance). Like with
30/// [`wasmtime::Func`](crate::Func) it's possible to call functions either
31/// synchronously or asynchronously and either typed or untyped.
32#[derive(Copy, Clone, Debug)]
33#[repr(C)] // here for the C API.
34pub struct Func {
35 instance: Instance,
36
37 /// The export index of this lifted function within its component.
38 index: ExportIndex,
39
40 /// The resolved core `VMFuncRef` for this lifted function, whose lifetime
41 /// is bound to the `Store` this `Func` belongs to.
42 ///
43 /// Note that this field has an `unsafe_*` prefix to discourage use of it.
44 /// This is only safe to read/use if the store that owns `instance`
45 /// (identified by `instance.id().store_id()`) is in scope. Use the
46 /// `self.lifted_core_func()` method instead of this field to perform this
47 /// check.
48 unsafe_func_ref: SendSyncPtr<VMFuncRef>,
49}
50
51// Double-check that the C representation in `component/func.h` matches our
52// in-Rust representation here in terms of size/alignment/etc.
53const _: () = {
54 #[repr(C)]
55 struct T(u64, u32);
56 #[repr(C)]
57 struct C(T, u32, *mut u8);
58 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Func>());
59 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Func>());
60 assert!(core::mem::offset_of!(Func, instance) == 0);
61};
62
63impl Func {
64 pub(crate) fn from_lifted_func(
65 store: &mut StoreOpaque,
66 instance: Instance,
67 index: ExportIndex,
68 ) -> Func {
69 let (component, store) = instance.component_and_store_mut(store);
70 let (_ty, def, _options) = component.export_lifted_function(index);
71 let unsafe_func_ref = match instance.lookup_vmdef(store, def) {
72 Export::Function(f) => f.vm_func_ref(store),
73 _ => unreachable!(),
74 }
75 .into();
76
77 Func {
78 instance,
79 index,
80 unsafe_func_ref,
81 }
82 }
83
84 /// Attempt to cast this [`Func`] to a statically typed [`TypedFunc`] with
85 /// the provided `Params` and `Return`.
86 ///
87 /// This function will perform a type-check at runtime that the [`Func`]
88 /// takes `Params` as parameters and returns `Return`. If the type-check
89 /// passes then a [`TypedFunc`] will be returned which can be used to
90 /// invoke the function in an efficient, statically-typed, and ergonomic
91 /// manner.
92 ///
93 /// The `Params` type parameter here is a tuple of the parameters to the
94 /// function. A function which takes no arguments should use `()`, a
95 /// function with one argument should use `(T,)`, etc. Note that all
96 /// `Params` must also implement the [`Lower`] trait since they're going
97 /// into wasm.
98 ///
99 /// The `Return` type parameter is the return value of this function. A
100 /// return value of `()` means that there's no return (similar to a Rust
101 /// unit return) and otherwise a type `T` can be specified. Note that the
102 /// `Return` must also implement the [`Lift`] trait since it's coming from
103 /// wasm.
104 ///
105 /// Types specified here must implement the [`ComponentType`] trait. This
106 /// trait is implemented for built-in types to Rust such as integer
107 /// primitives, floats, `Option<T>`, `Result<T, E>`, strings, `Vec<T>`, and
108 /// more. As parameters you'll be passing native Rust types.
109 ///
110 /// See the documentation for [`ComponentType`] for more information about
111 /// supported types.
112 ///
113 /// # Errors
114 ///
115 /// If the function does not actually take `Params` as its parameters or
116 /// return `Return` then an error will be returned.
117 ///
118 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
119 /// memory allocation fails. See the `OutOfMemory` type's documentation for
120 /// details on Wasmtime's out-of-memory handling.
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<()>) -> wasmtime::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<()>) -> wasmtime::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<()>) -> wasmtime::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<&ComponentInstance>,
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<&ComponentInstance>,
192 ) -> Result<()>
193 where
194 Params: ComponentNamedList + Lower,
195 Return: ComponentNamedList + Lift,
196 {
197 let cx = InstanceType::new(instance.unwrap_or_else(|| self.instance.id().get(store)));
198 let ty = &cx.types[self.ty_index(store)];
199
200 Params::typecheck(&InterfaceType::Tuple(ty.params), &cx)
201 .context("type mismatch with parameters")?;
202 Return::typecheck(&InterfaceType::Tuple(ty.results), &cx)
203 .context("type mismatch with results")?;
204
205 Ok(())
206 }
207
208 /// Get the type of this function.
209 pub fn ty(&self, store: impl AsContext) -> ComponentFunc {
210 let store = store.as_context().0;
211 let cx = InstanceType::new(self.instance.id().get(store));
212 let ty = self.ty_index(store);
213 ComponentFunc::from(ty, &cx)
214 }
215
216 fn ty_index(&self, store: &StoreOpaque) -> TypeFuncIndex {
217 let instance = self.instance.id().get(store);
218 let (ty, _, _) = instance.component().export_lifted_function(self.index);
219 ty
220 }
221
222 /// Invokes this function with the `params` given and returns the result.
223 ///
224 /// The `params` provided must match the parameters that this function takes
225 /// in terms of their types and the number of parameters. Results will be
226 /// written to the `results` slice provided if the call completes
227 /// successfully. The initial types of the values in `results` are ignored
228 /// and values are overwritten to write the result. It's required that the
229 /// size of `results` exactly matches the number of results that this
230 /// function produces.
231 ///
232 /// This will also call the corresponding `post-return` function, if any.
233 ///
234 /// For more detailed information see the documentation of
235 /// [`TypedFunc::call`].
236 ///
237 /// # Errors
238 ///
239 /// Returns an error in situations including but not limited to:
240 ///
241 /// * `params` is not the right size or if the values have the wrong type
242 /// * `results` is not the right size
243 /// * A trap occurs while executing the function
244 /// * The function calls a host function which returns an error
245 /// * The `store` used requires the use of [`Func::call_async`] instead. See
246 /// [store documentation](crate#async) for more information.
247 /// * The call is recursive from within e.g. a `call_async` invocation.
248 /// * If the function is async-typed or async-lifted, in which case either
249 /// [`Self::call_async`] or [`Self::call_concurrent`] must be used.
250 ///
251 /// See [`TypedFunc::call`] for more information in addition to
252 /// [`wasmtime::Func::call`](crate::Func::call).
253 ///
254 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
255 /// memory allocation fails. See the `OutOfMemory` type's documentation for
256 /// details on Wasmtime's out-of-memory handling.
257 ///
258 /// # Panics
259 ///
260 /// Panics if `store` does not own this function.
261 pub fn call(
262 &self,
263 mut store: impl AsContextMut,
264 params: &[Val],
265 results: &mut [Val],
266 ) -> Result<()> {
267 let mut store = store.as_context_mut();
268 store.0.validate_sync_call()?;
269 self.call_impl(store.as_context_mut(), params, results)?;
270 Ok(())
271 }
272
273 /// Exactly like [`Self::call`] except for use on async stores.
274 ///
275 /// # Errors
276 ///
277 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
278 /// memory allocation fails. See the `OutOfMemory` type's documentation for
279 /// details on Wasmtime's out-of-memory handling.
280 ///
281 /// # Panics
282 ///
283 /// Panics if `store` does not own this function.
284 #[cfg(feature = "async")]
285 pub async fn call_async(
286 &self,
287 mut store: impl AsContextMut<Data: Send>,
288 params: &[Val],
289 results: &mut [Val],
290 ) -> Result<()> {
291 let mut store = store.as_context_mut();
292
293 #[cfg(feature = "component-model-async")]
294 if store.0.concurrency_support() {
295 return store
296 .run_concurrent_trap_on_idle(async |store| {
297 self.call_concurrent(store, params, results).await
298 })
299 .await?;
300 }
301
302 store
303 .on_fiber(|store| self.call_impl(store, params, results))
304 .await?
305 }
306
307 pub(crate) fn check_params_results<T>(
308 &self,
309 store: StoreContextMut<T>,
310 params: &[Val],
311 results: &mut [Val],
312 ) -> Result<()> {
313 let ty = self.ty(&store);
314 if ty.params().len() != params.len() {
315 bail!(
316 "expected {} argument(s), got {}",
317 ty.params().len(),
318 params.len(),
319 );
320 }
321
322 if ty.results().len() != results.len() {
323 bail!(
324 "expected {} result(s), got {}",
325 ty.results().len(),
326 results.len(),
327 );
328 }
329
330 Ok(())
331 }
332
333 fn call_impl(
334 &self,
335 mut store: impl AsContextMut,
336 params: &[Val],
337 results: &mut [Val],
338 ) -> Result<()> {
339 let mut store = store.as_context_mut();
340
341 self.check_params_results(store.as_context_mut(), params, results)?;
342
343 if self.is_async(store.0) {
344 bail!(
345 "cannot synchronously call an async function; \
346 use `call_async` or `call_concurrent` instead"
347 );
348 }
349
350 // SAFETY: the chosen representations of type parameters to `call_raw`
351 // here should be generally safe to work with:
352 //
353 // * parameters use `MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>`
354 // which represents the maximal possible number of parameters that can
355 // be passed to lifted component functions. This is modeled with
356 // `MaybeUninit` to represent how it all starts as uninitialized and
357 // thus can't be safely read during lowering.
358 //
359 // * results are modeled as `[ValRaw; MAX_FLAT_RESULTS]` which
360 // represents the maximal size of values that can be returned. Note
361 // that if the function doesn't actually have a return value then the
362 // `ValRaw` inside the array will have undefined contents. That is
363 // safe in Rust, however, due to `ValRaw` being a `union`. The
364 // contents should dynamically not be read due to the type of the
365 // function used here matching the actual lift.
366 let result = unsafe {
367 self.call_raw(
368 store.as_context_mut(),
369 |cx, ty, dst: &mut MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>| {
370 // SAFETY: it's safe to assume that
371 // `MaybeUninit<array-of-maybe-uninit>` is initialized because
372 // each individual element is still considered uninitialized.
373 let dst: &mut [MaybeUninit<ValRaw>] = dst.assume_init_mut();
374 Self::lower_args(cx, params, ty, dst)
375 },
376 |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| {
377 let max_flat = MAX_FLAT_RESULTS;
378 for (result, slot) in
379 Self::lift_results(cx, results_ty, src, max_flat)?.zip(results)
380 {
381 *slot = result?;
382 }
383 Ok(())
384 },
385 )
386 };
387
388 if result.is_err() {
389 store.0.set_trapped();
390 }
391
392 result
393 }
394
395 #[inline]
396 pub(crate) fn lifted_core_func(&self, store: &StoreOpaque) -> NonNull<VMFuncRef> {
397 self.instance.id().assert_belongs_to(store.id());
398 self.unsafe_func_ref.as_non_null()
399 }
400
401 /// Returns whether this function is async-typed or async-lifted, either of
402 /// which means it can't be called synchronously.
403 pub(crate) fn is_async(&self, store: &StoreOpaque) -> bool {
404 let instance = self.instance.id().get(store);
405 let component = instance.component();
406 let (ty, _def, options) = component.export_lifted_function(self.index);
407 component.types()[ty].async_ || component.env_component().options[options].async_
408 }
409
410 pub(crate) fn abi_info<'a>(
411 &self,
412 store: &'a StoreOpaque,
413 ) -> (
414 OptionsIndex,
415 InstanceFlags,
416 TypeFuncIndex,
417 &'a CanonicalOptions,
418 ) {
419 let vminstance = self.instance.id().get(store);
420 let component = vminstance.component();
421 let (ty, _def, options_index) = component.export_lifted_function(self.index);
422 let raw_options = &component.env_component().options[options_index];
423 (
424 options_index,
425 vminstance.instance_flags(raw_options.instance),
426 ty,
427 raw_options,
428 )
429 }
430
431 /// Invokes the underlying wasm function, lowering arguments and lifting the
432 /// result.
433 ///
434 /// The `lower` function and `lift` function provided here are what actually
435 /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types
436 /// are what will be allocated on the stack for this function call. They
437 /// should be appropriately sized for the lowering/lifting operation
438 /// happening.
439 ///
440 /// # Safety
441 ///
442 /// The safety of this function relies on the correct definitions of the
443 /// `LowerParams` and `LowerReturn` type. They must match the type of `self`
444 /// for the params/results that are going to be produced. Additionally
445 /// these types must be representable with a sequence of `ValRaw` values.
446 unsafe fn call_raw<T, Return, LowerParams, LowerReturn>(
447 &self,
448 mut store: StoreContextMut<'_, T>,
449 lower: impl FnOnce(
450 &mut LowerContext<'_, T>,
451 InterfaceType,
452 &mut MaybeUninit<LowerParams>,
453 ) -> Result<()>,
454 lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>,
455 ) -> Result<Return>
456 where
457 LowerParams: Copy,
458 LowerReturn: Copy,
459 {
460 let export = self.lifted_core_func(store.0);
461
462 let (options_idx, flags, ty, raw_options) = self.abi_info(store.0);
463 let post_return = raw_options
464 .post_return
465 .map(|i| self.instance.id().get(store.0).runtime_post_return(i));
466 let instance = self.instance.runtime_instance(raw_options.instance);
467 let async_ = raw_options.async_;
468
469 store.0.enter_guest_sync_call(async_, instance)?;
470
471 #[repr(C)]
472 union Union<Params: Copy, Return: Copy> {
473 params: Params,
474 ret: Return,
475 }
476
477 let space = &mut MaybeUninit::<Union<LowerParams, LowerReturn>>::uninit();
478
479 // Double-check the size/alignment of `space`, just in case.
480 //
481 // Note that this alone is not enough to guarantee the validity of the
482 // `unsafe` block below, but it's definitely required. In any case LLVM
483 // should be able to trivially see through these assertions and remove
484 // them in release mode.
485 let val_size = mem::size_of::<ValRaw>();
486 let val_align = mem::align_of::<ValRaw>();
487 assert!(mem::size_of_val(space) % val_size == 0);
488 assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0);
489 assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0);
490 assert!(mem::align_of_val(space) == val_align);
491 assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align);
492 assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align);
493
494 Func::with_lower_context(
495 self.instance,
496 store.as_context_mut(),
497 options_idx,
498 ty,
499 |cx, ty| lower(cx, ty, map_maybe_uninit!(space.params)),
500 )?;
501
502 // SAFETY: We are providing the guarantee that all the inputs are valid.
503 // The various pointers passed in for the function are all valid since
504 // they're coming from our store, and the `params_and_results` should
505 // have the correct layout for the core wasm function we're calling.
506 // Note that this latter point relies on the correctness of this module
507 // and `ComponentType` implementations, hence `ComponentType` being an
508 // `unsafe` trait.
509 unsafe {
510 crate::Func::call_unchecked_raw(
511 &mut store,
512 export,
513 NonNull::new(core::ptr::slice_from_raw_parts_mut(
514 space.as_mut_ptr().cast(),
515 mem::size_of_val(space) / mem::size_of::<ValRaw>(),
516 ))
517 .unwrap(),
518 UncaughtException::Trap,
519 )?;
520 }
521
522 // Validate that the task, after returning, has no more active borrows
523 // as they're required to have been dropped by this point.
524 store
525 .0
526 .component_resource_tables(Some(self.instance))?
527 .validate_scope_exit()?;
528
529 // SAFETY: We're relying on the correctness of the structure of
530 // `LowerReturn` and the type-checking performed to acquire the
531 // `TypedFunc` to make this safe. It should be the case that
532 // `LowerReturn` is the exact representation of the return value when
533 // interpreted as `[ValRaw]`, and additionally they should have the
534 // correct types for the function we just called (which filled in the
535 // return values).
536 let ret: &LowerReturn = unsafe { map_maybe_uninit!(space.ret).assume_init_ref() };
537
538 let val = Func::with_lift_context(self.instance, store.0, options_idx, ty, |cx, ty| {
539 lift(cx, ty, ret)
540 })?;
541
542 // SAFETY: it's a contract of this function that `LowerReturn` is an
543 // appropriate representation of the result of this function.
544 let ret_slice = unsafe { storage_as_slice(ret) };
545 let post_return_arg = match ret_slice.len() {
546 0 => ValRaw::i32(0),
547 1 => ret_slice[0],
548 _ => unreachable!(),
549 };
550
551 // SAFETY: `post_return` and `flags` were resolved from this function's
552 // own canonical options above, and `store` is the store this call is
553 // running in.
554 unsafe {
555 call_post_return(&mut store, post_return, post_return_arg, flags)?;
556 }
557 store.0.exit_guest_sync_call()?;
558
559 Ok(val)
560 }
561
562 #[doc(hidden)]
563 #[deprecated(note = "no longer needs to be called; this function has no effect")]
564 pub fn post_return(&self, _store: impl AsContextMut) -> Result<()> {
565 Ok(())
566 }
567
568 #[doc(hidden)]
569 #[deprecated(note = "no longer needs to be called; this function has no effect")]
570 #[cfg(feature = "async")]
571 pub async fn post_return_async(&self, _store: impl AsContextMut<Data: Send>) -> Result<()> {
572 Ok(())
573 }
574
575 pub(crate) fn lower_args<T>(
576 cx: &mut LowerContext<'_, T>,
577 params: &[Val],
578 params_ty: InterfaceType,
579 dst: &mut [MaybeUninit<ValRaw>],
580 ) -> Result<()> {
581 let params_ty = match params_ty {
582 InterfaceType::Tuple(i) => &cx.types[i],
583 _ => unreachable!(),
584 };
585 if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() {
586 let dst = &mut dst.iter_mut();
587
588 params
589 .iter()
590 .zip(params_ty.types.iter())
591 .try_for_each(|(param, ty)| param.lower(cx, *ty, dst))
592 } else {
593 Self::store_args(cx, ¶ms_ty, params, dst)
594 }
595 }
596
597 fn store_args<T>(
598 cx: &mut LowerContext<'_, T>,
599 params_ty: &TypeTuple,
600 args: &[Val],
601 dst: &mut [MaybeUninit<ValRaw>],
602 ) -> Result<()> {
603 let size = usize::try_from(params_ty.abi.size32).unwrap();
604 let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?;
605 let mut offset = ptr;
606 for (ty, arg) in params_ty.types.iter().zip(args) {
607 let abi = cx.types.canonical_abi(ty);
608 arg.store(cx, *ty, abi.next_field32_size(&mut offset))?;
609 }
610
611 dst[0].write(ValRaw::i64(ptr as i64));
612
613 Ok(())
614 }
615
616 pub(crate) fn lift_results<'a, 'b>(
617 cx: &'a mut LiftContext<'b>,
618 results_ty: InterfaceType,
619 src: &'a [ValRaw],
620 max_flat: usize,
621 ) -> Result<Box<dyn Iterator<Item = Result<Val>> + 'a>> {
622 let results_ty = match results_ty {
623 InterfaceType::Tuple(i) => &cx.types[i],
624 _ => unreachable!(),
625 };
626 if results_ty.abi.flat_count(max_flat).is_some() {
627 let mut flat = src.iter();
628 Ok(try_new::<Box<_>>(
629 results_ty
630 .types
631 .iter()
632 .map(move |ty| Val::lift(cx, *ty, &mut flat)),
633 )?)
634 } else {
635 let iter = Self::load_results(cx, results_ty, &mut src.iter())?;
636 Ok(try_new::<Box<_>>(iter)?)
637 }
638 }
639
640 fn load_results<'a, 'b>(
641 cx: &'a mut LiftContext<'b>,
642 results_ty: &'a TypeTuple,
643 src: &mut core::slice::Iter<'_, ValRaw>,
644 ) -> Result<impl Iterator<Item = Result<Val>> + use<'a, 'b>> {
645 // FIXME(#4311): needs to read an i64 for memory64
646 let ptr = usize::try_from(src.next().unwrap().get_u32())?;
647 if ptr % usize::try_from(results_ty.abi.align32)? != 0 {
648 bail!("return pointer not aligned");
649 }
650
651 let bytes = cx
652 .memory()
653 .get(ptr..)
654 .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap()))
655 .ok_or_else(|| crate::format_err!("pointer out of bounds of memory"))?;
656
657 let mut offset = 0;
658 Ok(results_ty.types.iter().map(move |ty| {
659 let abi = cx.types.canonical_abi(ty);
660 let offset = abi.next_field32_size(&mut offset);
661 Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])
662 }))
663 }
664
665 #[cfg(feature = "component-model-async")]
666 pub(crate) fn instance(self) -> Instance {
667 self.instance
668 }
669
670 /// Creates a `LowerContext` using the provided configuration values and runs
671 /// the given `lower` closure within it.
672 ///
673 /// The `lower` closure provided should perform the actual lowering and
674 /// return the result of the lowering operation which is then returned from
675 /// this function as well.
676 pub(crate) fn with_lower_context<T>(
677 instance: Instance,
678 mut store: StoreContextMut<T>,
679 options: OptionsIndex,
680 ty: TypeFuncIndex,
681 lower: impl FnOnce(&mut LowerContext<T>, InterfaceType) -> Result<()>,
682 ) -> Result<()> {
683 let mut cx = LowerContext::new(store.as_context_mut(), options, instance);
684 let param_ty = InterfaceType::Tuple(cx.types[ty].params);
685 lower(&mut cx, param_ty)
686 }
687
688 /// Creates a `LiftContext` using the provided configuration values and runs
689 /// the given `lift` closure within it.
690 ///
691 /// The closure `lift` provided should actually perform the lift itself and
692 /// the result of that closure is returned from this function call as well.
693 pub(crate) fn with_lift_context<R>(
694 instance: Instance,
695 store: &mut StoreOpaque,
696 options: OptionsIndex,
697 ty: TypeFuncIndex,
698 lift: impl FnOnce(&mut LiftContext, InterfaceType) -> Result<R>,
699 ) -> Result<R> {
700 let mut cx = LiftContext::new(store, options, instance)?;
701 let ty = InterfaceType::Tuple(cx.types[ty].results);
702 lift(&mut cx, ty)
703 }
704}
705
706pub(crate) unsafe fn call_post_return(
707 mut store: impl AsContextMut,
708 func: Option<NonNull<VMFuncRef>>,
709 arg: ValRaw,
710 mut flags: InstanceFlags,
711) -> Result<()> {
712 unsafe {
713 // Post return functions are forbidden from calling imports or
714 // intrinsics.
715 flags.set_may_leave(false);
716
717 // If the function actually had a `post-return` configured in its
718 // canonical options that's executed here.
719 if let Some(func) = func {
720 crate::Func::call_unchecked_raw(
721 &mut store.as_context_mut(),
722 func,
723 core::slice::from_ref(&arg).into(),
724 UncaughtException::Trap,
725 )?;
726 }
727
728 // And finally if everything completed successfully then the "may
729 // leave" flags is set to `true` again here which enables further
730 // use of the component.
731 flags.set_may_leave(true);
732 }
733
734 Ok(())
735}