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, 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 def = {
70 let vminstance = instance.id().get(store);
71 let (_ty, def, _options) = vminstance.component().export_lifted_function(index);
72 def.clone()
73 };
74 let unsafe_func_ref = match instance.lookup_vmdef(store, &def) {
75 Export::Function(f) => f.vm_func_ref(store),
76 _ => unreachable!(),
77 }
78 .into();
79
80 Func {
81 instance,
82 index,
83 unsafe_func_ref,
84 }
85 }
86
87 /// Attempt to cast this [`Func`] to a statically typed [`TypedFunc`] with
88 /// the provided `Params` and `Return`.
89 ///
90 /// This function will perform a type-check at runtime that the [`Func`]
91 /// takes `Params` as parameters and returns `Return`. If the type-check
92 /// passes then a [`TypedFunc`] will be returned which can be used to
93 /// invoke the function in an efficient, statically-typed, and ergonomic
94 /// manner.
95 ///
96 /// The `Params` type parameter here is a tuple of the parameters to the
97 /// function. A function which takes no arguments should use `()`, a
98 /// function with one argument should use `(T,)`, etc. Note that all
99 /// `Params` must also implement the [`Lower`] trait since they're going
100 /// into wasm.
101 ///
102 /// The `Return` type parameter is the return value of this function. A
103 /// return value of `()` means that there's no return (similar to a Rust
104 /// unit return) and otherwise a type `T` can be specified. Note that the
105 /// `Return` must also implement the [`Lift`] trait since it's coming from
106 /// wasm.
107 ///
108 /// Types specified here must implement the [`ComponentType`] trait. This
109 /// trait is implemented for built-in types to Rust such as integer
110 /// primitives, floats, `Option<T>`, `Result<T, E>`, strings, `Vec<T>`, and
111 /// more. As parameters you'll be passing native Rust types.
112 ///
113 /// See the documentation for [`ComponentType`] for more information about
114 /// supported types.
115 ///
116 /// # Errors
117 ///
118 /// If the function does not actually take `Params` as its parameters or
119 /// return `Return` then an error will be returned.
120 ///
121 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
122 /// memory allocation fails. See the `OutOfMemory` type's documentation for
123 /// details on Wasmtime's out-of-memory handling.
124 ///
125 /// # Panics
126 ///
127 /// This function will panic if `self` is not owned by the `store`
128 /// specified.
129 ///
130 /// # Examples
131 ///
132 /// Calling a function which takes no parameters and has no return value:
133 ///
134 /// ```
135 /// # use wasmtime::component::Func;
136 /// # use wasmtime::Store;
137 /// # fn foo(func: &Func, store: &mut Store<()>) -> wasmtime::Result<()> {
138 /// let typed = func.typed::<(), ()>(&store)?;
139 /// typed.call(store, ())?;
140 /// # Ok(())
141 /// # }
142 /// ```
143 ///
144 /// Calling a function which takes one string parameter and returns a
145 /// string:
146 ///
147 /// ```
148 /// # use wasmtime::component::Func;
149 /// # use wasmtime::Store;
150 /// # fn foo(func: &Func, mut store: Store<()>) -> wasmtime::Result<()> {
151 /// let typed = func.typed::<(&str,), (String,)>(&store)?;
152 /// let ret = typed.call(&mut store, ("Hello, ",))?.0;
153 /// println!("returned string was: {}", ret);
154 /// # Ok(())
155 /// # }
156 /// ```
157 ///
158 /// Calling a function which takes multiple parameters and returns a boolean:
159 ///
160 /// ```
161 /// # use wasmtime::component::Func;
162 /// # use wasmtime::Store;
163 /// # fn foo(func: &Func, mut store: Store<()>) -> wasmtime::Result<()> {
164 /// let typed = func.typed::<(u32, Option<&str>, &[u8]), (bool,)>(&store)?;
165 /// let ok: bool = typed.call(&mut store, (1, Some("hello"), b"bytes!"))?.0;
166 /// println!("return value was: {ok}");
167 /// # Ok(())
168 /// # }
169 /// ```
170 pub fn typed<Params, Return>(&self, store: impl AsContext) -> Result<TypedFunc<Params, Return>>
171 where
172 Params: ComponentNamedList + Lower,
173 Return: ComponentNamedList + Lift,
174 {
175 self._typed(store.as_context().0, None)
176 }
177
178 pub(crate) fn _typed<Params, Return>(
179 &self,
180 store: &StoreOpaque,
181 instance: Option<&ComponentInstance>,
182 ) -> Result<TypedFunc<Params, Return>>
183 where
184 Params: ComponentNamedList + Lower,
185 Return: ComponentNamedList + Lift,
186 {
187 self.typecheck::<Params, Return>(store, instance)?;
188 unsafe { Ok(TypedFunc::new_unchecked(*self)) }
189 }
190
191 fn typecheck<Params, Return>(
192 &self,
193 store: &StoreOpaque,
194 instance: Option<&ComponentInstance>,
195 ) -> Result<()>
196 where
197 Params: ComponentNamedList + Lower,
198 Return: ComponentNamedList + Lift,
199 {
200 let cx = InstanceType::new(instance.unwrap_or_else(|| self.instance.id().get(store)));
201 let ty = &cx.types[self.ty_index(store)];
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 type of this function.
212 pub fn ty(&self, store: impl AsContext) -> ComponentFunc {
213 let store = store.as_context().0;
214 let cx = InstanceType::new(self.instance.id().get(store));
215 let ty = self.ty_index(store);
216 ComponentFunc::from(ty, &cx)
217 }
218
219 fn ty_index(&self, store: &StoreOpaque) -> TypeFuncIndex {
220 let instance = self.instance.id().get(store);
221 let (ty, _, _) = instance.component().export_lifted_function(self.index);
222 ty
223 }
224
225 /// Invokes this function with the `params` given and returns the result.
226 ///
227 /// The `params` provided must match the parameters that this function takes
228 /// in terms of their types and the number of parameters. Results will be
229 /// written to the `results` slice provided if the call completes
230 /// successfully. The initial types of the values in `results` are ignored
231 /// and values are overwritten to write the result. It's required that the
232 /// size of `results` exactly matches the number of results that this
233 /// function produces.
234 ///
235 /// This will also call the corresponding `post-return` function, if any.
236 ///
237 /// For more detailed information see the documentation of
238 /// [`TypedFunc::call`].
239 ///
240 /// # Errors
241 ///
242 /// Returns an error in situations including but not limited to:
243 ///
244 /// * `params` is not the right size or if the values have the wrong type
245 /// * `results` is not the right size
246 /// * A trap occurs while executing the function
247 /// * The function calls a host function which returns an error
248 /// * The `store` used requires the use of [`Func::call_async`] instead. See
249 /// [store documentation](crate#async) for more information.
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 let call = self.start_call_concurrent(&mut store, params, results)?;
296 return store
297 .run_concurrent_trap_on_idle(async |store| {
298 self.finish_call_concurrent(store, call).await
299 })
300 .await?;
301 }
302
303 store
304 .on_fiber(|store| self.call_impl(store, params, results))
305 .await?
306 }
307
308 pub(crate) fn check_params_results<T>(
309 &self,
310 store: StoreContextMut<T>,
311 params: &[Val],
312 results: &mut [Val],
313 ) -> Result<()> {
314 let ty = self.ty(&store);
315 if ty.params().len() != params.len() {
316 bail!(
317 "expected {} argument(s), got {}",
318 ty.params().len(),
319 params.len(),
320 );
321 }
322
323 if ty.results().len() != results.len() {
324 bail!(
325 "expected {} result(s), got {}",
326 ty.results().len(),
327 results.len(),
328 );
329 }
330
331 Ok(())
332 }
333
334 fn call_impl(
335 &self,
336 mut store: impl AsContextMut,
337 params: &[Val],
338 results: &mut [Val],
339 ) -> Result<()> {
340 let mut store = store.as_context_mut();
341
342 self.check_params_results(store.as_context_mut(), params, results)?;
343
344 if self.abi_async(store.0) {
345 unreachable!(
346 "async-lifted exports should have failed validation \
347 when `component-model-async` feature disabled"
348 );
349 }
350
351 // SAFETY: the chosen representations of type parameters to `call_raw`
352 // here should be generally safe to work with:
353 //
354 // * parameters use `MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>`
355 // which represents the maximal possible number of parameters that can
356 // be passed to lifted component functions. This is modeled with
357 // `MaybeUninit` to represent how it all starts as uninitialized and
358 // thus can't be safely read during lowering.
359 //
360 // * results are modeled as `[ValRaw; MAX_FLAT_RESULTS]` which
361 // represents the maximal size of values that can be returned. Note
362 // that if the function doesn't actually have a return value then the
363 // `ValRaw` inside the array will have undefined contents. That is
364 // safe in Rust, however, due to `ValRaw` being a `union`. The
365 // contents should dynamically not be read due to the type of the
366 // function used here matching the actual lift.
367 unsafe {
368 self.call_raw(
369 store.as_context_mut(),
370 |cx, ty, dst: &mut MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>| {
371 // SAFETY: it's safe to assume that
372 // `MaybeUninit<array-of-maybe-uninit>` is initialized because
373 // each individual element is still considered uninitialized.
374 let dst: &mut [MaybeUninit<ValRaw>] = dst.assume_init_mut();
375 Self::lower_args(cx, params, ty, dst)
376 },
377 |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| {
378 let max_flat = MAX_FLAT_RESULTS;
379 for (result, slot) in
380 Self::lift_results(cx, results_ty, src, max_flat)?.zip(results)
381 {
382 *slot = result?;
383 }
384 Ok(())
385 },
386 )?;
387 }
388
389 Ok(())
390 }
391
392 #[inline]
393 pub(crate) fn lifted_core_func(&self, store: &StoreOpaque) -> NonNull<VMFuncRef> {
394 self.instance.id().assert_belongs_to(store.id());
395 self.unsafe_func_ref.as_non_null()
396 }
397
398 pub(crate) fn abi_async(&self, store: &StoreOpaque) -> bool {
399 let instance = self.instance.id().get(store);
400 let component = instance.component();
401 let (_ty, _def, options) = component.export_lifted_function(self.index);
402 component.env_component().options[options].async_
403 }
404
405 pub(crate) fn abi_info<'a>(
406 &self,
407 store: &'a StoreOpaque,
408 ) -> (
409 OptionsIndex,
410 InstanceFlags,
411 TypeFuncIndex,
412 &'a CanonicalOptions,
413 ) {
414 let vminstance = self.instance.id().get(store);
415 let component = vminstance.component();
416 let (ty, _def, options_index) = component.export_lifted_function(self.index);
417 let raw_options = &component.env_component().options[options_index];
418 (
419 options_index,
420 vminstance.instance_flags(raw_options.instance),
421 ty,
422 raw_options,
423 )
424 }
425
426 /// Invokes the underlying wasm function, lowering arguments and lifting the
427 /// result.
428 ///
429 /// The `lower` function and `lift` function provided here are what actually
430 /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types
431 /// are what will be allocated on the stack for this function call. They
432 /// should be appropriately sized for the lowering/lifting operation
433 /// happening.
434 ///
435 /// # Safety
436 ///
437 /// The safety of this function relies on the correct definitions of the
438 /// `LowerParams` and `LowerReturn` type. They must match the type of `self`
439 /// for the params/results that are going to be produced. Additionally
440 /// these types must be representable with a sequence of `ValRaw` values.
441 unsafe fn call_raw<T, Return, LowerParams, LowerReturn>(
442 &self,
443 mut store: StoreContextMut<'_, T>,
444 lower: impl FnOnce(
445 &mut LowerContext<'_, T>,
446 InterfaceType,
447 &mut MaybeUninit<LowerParams>,
448 ) -> Result<()>,
449 lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>,
450 ) -> Result<Return>
451 where
452 LowerParams: Copy,
453 LowerReturn: Copy,
454 {
455 let export = self.lifted_core_func(store.0);
456
457 let (options_idx, flags, ty, raw_options) = self.abi_info(store.0);
458 let post_return = raw_options
459 .post_return
460 .map(|i| self.instance.id().get(store.0).runtime_post_return(i));
461 let instance = self.instance.runtime_instance(raw_options.instance);
462 let async_ = raw_options.async_;
463
464 if !store.0.may_enter(instance)? {
465 bail!(crate::Trap::CannotEnterComponent);
466 }
467
468 store.0.enter_guest_sync_call(None, async_, instance)?;
469
470 #[repr(C)]
471 union Union<Params: Copy, Return: Copy> {
472 params: Params,
473 ret: Return,
474 }
475
476 let space = &mut MaybeUninit::<Union<LowerParams, LowerReturn>>::uninit();
477
478 // Double-check the size/alignment of `space`, just in case.
479 //
480 // Note that this alone is not enough to guarantee the validity of the
481 // `unsafe` block below, but it's definitely required. In any case LLVM
482 // should be able to trivially see through these assertions and remove
483 // them in release mode.
484 let val_size = mem::size_of::<ValRaw>();
485 let val_align = mem::align_of::<ValRaw>();
486 assert!(mem::size_of_val(space) % val_size == 0);
487 assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0);
488 assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0);
489 assert!(mem::align_of_val(space) == val_align);
490 assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align);
491 assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align);
492
493 Func::with_lower_context(
494 self.instance,
495 store.as_context_mut(),
496 options_idx,
497 flags,
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 )?;
519 }
520
521 // Validate that the task, after returning, has no more active borrows
522 // as they're required to have been dropped by this point.
523 store
524 .0
525 .component_resource_tables(Some(self.instance))?
526 .validate_scope_exit()?;
527
528 // SAFETY: We're relying on the correctness of the structure of
529 // `LowerReturn` and the type-checking performed to acquire the
530 // `TypedFunc` to make this safe. It should be the case that
531 // `LowerReturn` is the exact representation of the return value when
532 // interpreted as `[ValRaw]`, and additionally they should have the
533 // correct types for the function we just called (which filled in the
534 // return values).
535 let ret: &LowerReturn = unsafe { map_maybe_uninit!(space.ret).assume_init_ref() };
536
537 let val = Func::with_lift_context(self.instance, store.0, options_idx, ty, |cx, ty| {
538 lift(cx, ty, ret)
539 })?;
540
541 // SAFETY: it's a contract of this function that `LowerReturn` is an
542 // appropriate representation of the result of this function.
543 let ret_slice = unsafe { storage_as_slice(ret) };
544 let post_return_arg = match ret_slice.len() {
545 0 => ValRaw::i32(0),
546 1 => ret_slice[0],
547 _ => unreachable!(),
548 };
549
550 // SAFETY: `post_return` and `flags` were resolved from this function's
551 // own canonical options above, and `store` is the store this call is
552 // running in.
553 unsafe {
554 call_post_return(&mut store, post_return, post_return_arg, flags)?;
555 }
556 store.0.exit_guest_sync_call()?;
557
558 Ok(val)
559 }
560
561 #[doc(hidden)]
562 #[deprecated(note = "no longer needs to be called; this function has no effect")]
563 pub fn post_return(&self, _store: impl AsContextMut) -> Result<()> {
564 Ok(())
565 }
566
567 #[doc(hidden)]
568 #[deprecated(note = "no longer needs to be called; this function has no effect")]
569 #[cfg(feature = "async")]
570 pub async fn post_return_async(&self, _store: impl AsContextMut<Data: Send>) -> Result<()> {
571 Ok(())
572 }
573
574 pub(crate) fn lower_args<T>(
575 cx: &mut LowerContext<'_, T>,
576 params: &[Val],
577 params_ty: InterfaceType,
578 dst: &mut [MaybeUninit<ValRaw>],
579 ) -> Result<()> {
580 let params_ty = match params_ty {
581 InterfaceType::Tuple(i) => &cx.types[i],
582 _ => unreachable!(),
583 };
584 if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() {
585 let dst = &mut dst.iter_mut();
586
587 params
588 .iter()
589 .zip(params_ty.types.iter())
590 .try_for_each(|(param, ty)| param.lower(cx, *ty, dst))
591 } else {
592 Self::store_args(cx, ¶ms_ty, params, dst)
593 }
594 }
595
596 fn store_args<T>(
597 cx: &mut LowerContext<'_, T>,
598 params_ty: &TypeTuple,
599 args: &[Val],
600 dst: &mut [MaybeUninit<ValRaw>],
601 ) -> Result<()> {
602 let size = usize::try_from(params_ty.abi.size32).unwrap();
603 let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?;
604 let mut offset = ptr;
605 for (ty, arg) in params_ty.types.iter().zip(args) {
606 let abi = cx.types.canonical_abi(ty);
607 arg.store(cx, *ty, abi.next_field32_size(&mut offset))?;
608 }
609
610 dst[0].write(ValRaw::i64(ptr as i64));
611
612 Ok(())
613 }
614
615 pub(crate) fn lift_results<'a, 'b>(
616 cx: &'a mut LiftContext<'b>,
617 results_ty: InterfaceType,
618 src: &'a [ValRaw],
619 max_flat: usize,
620 ) -> Result<Box<dyn Iterator<Item = Result<Val>> + 'a>> {
621 let results_ty = match results_ty {
622 InterfaceType::Tuple(i) => &cx.types[i],
623 _ => unreachable!(),
624 };
625 if results_ty.abi.flat_count(max_flat).is_some() {
626 let mut flat = src.iter();
627 Ok(try_new::<Box<_>>(
628 results_ty
629 .types
630 .iter()
631 .map(move |ty| Val::lift(cx, *ty, &mut flat)),
632 )?)
633 } else {
634 let iter = Self::load_results(cx, results_ty, &mut src.iter())?;
635 Ok(try_new::<Box<_>>(iter)?)
636 }
637 }
638
639 fn load_results<'a, 'b>(
640 cx: &'a mut LiftContext<'b>,
641 results_ty: &'a TypeTuple,
642 src: &mut core::slice::Iter<'_, ValRaw>,
643 ) -> Result<impl Iterator<Item = Result<Val>> + use<'a, 'b>> {
644 // FIXME(#4311): needs to read an i64 for memory64
645 let ptr = usize::try_from(src.next().unwrap().get_u32())?;
646 if ptr % usize::try_from(results_ty.abi.align32)? != 0 {
647 bail!("return pointer not aligned");
648 }
649
650 let bytes = cx
651 .memory()
652 .get(ptr..)
653 .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap()))
654 .ok_or_else(|| crate::format_err!("pointer out of bounds of memory"))?;
655
656 let mut offset = 0;
657 Ok(results_ty.types.iter().map(move |ty| {
658 let abi = cx.types.canonical_abi(ty);
659 let offset = abi.next_field32_size(&mut offset);
660 Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])
661 }))
662 }
663
664 #[cfg(feature = "component-model-async")]
665 pub(crate) fn instance(self) -> Instance {
666 self.instance
667 }
668
669 /// Creates a `LowerContext` using the provided configuration values and runs
670 /// the given `lower` closure within it.
671 ///
672 /// The `lower` closure provided should perform the actual lowering and
673 /// return the result of the lowering operation which is then returned from
674 /// this function as well.
675 pub(crate) fn with_lower_context<T>(
676 instance: Instance,
677 mut store: StoreContextMut<T>,
678 options: OptionsIndex,
679 mut flags: InstanceFlags,
680 ty: TypeFuncIndex,
681 lower: impl FnOnce(&mut LowerContext<T>, InterfaceType) -> Result<()>,
682 ) -> Result<()> {
683 // Perform the actual lowering, where while this is running the
684 // component is forbidden from calling imports.
685 unsafe {
686 debug_assert!(flags.may_leave());
687 flags.set_may_leave(false);
688 }
689 let mut cx = LowerContext::new(store.as_context_mut(), options, instance);
690 let param_ty = InterfaceType::Tuple(cx.types[ty].params);
691 let result = lower(&mut cx, param_ty);
692 unsafe { flags.set_may_leave(true) };
693 result
694 }
695
696 /// Creates a `LiftContext` using the provided configuration values and runs
697 /// the given `lift` closure within it.
698 ///
699 /// The closure `lift` provided should actually perform the lift itself and
700 /// the result of that closure is returned from this function call as well.
701 pub(crate) fn with_lift_context<R>(
702 instance: Instance,
703 store: &mut StoreOpaque,
704 options: OptionsIndex,
705 ty: TypeFuncIndex,
706 lift: impl FnOnce(&mut LiftContext, InterfaceType) -> Result<R>,
707 ) -> Result<R> {
708 let mut cx = LiftContext::new(store, options, instance)?;
709 let ty = InterfaceType::Tuple(cx.types[ty].results);
710 lift(&mut cx, ty)
711 }
712}
713
714pub(crate) unsafe fn call_post_return(
715 mut store: impl AsContextMut,
716 func: Option<NonNull<VMFuncRef>>,
717 arg: ValRaw,
718 mut flags: InstanceFlags,
719) -> Result<()> {
720 unsafe {
721 // Post return functions are forbidden from calling imports or
722 // intrinsics.
723 flags.set_may_leave(false);
724
725 // If the function actually had a `post-return` configured in its
726 // canonical options that's executed here.
727 if let Some(func) = func {
728 crate::Func::call_unchecked_raw(
729 &mut store.as_context_mut(),
730 func,
731 core::slice::from_ref(&arg).into(),
732 )?;
733 }
734
735 // And finally if everything completed successfully then the "may
736 // leave" flags is set to `true` again here which enables further
737 // use of the component.
738 flags.set_may_leave(true);
739 }
740
741 Ok(())
742}