1 use crate::component::RuntimeInstance; 2 use crate::component::instance::Instance; 3 use crate::component::matching::InstanceType; 4 use crate::component::storage::storage_as_slice; 5 use crate::component::types::ComponentFunc; 6 use crate::component::values::Val; 7 use crate::prelude::*; 8 use crate::runtime::vm::component::{ComponentInstance, InstanceFlags, ResourceTables}; 9 use crate::runtime::vm::{Export, VMFuncRef}; 10 use crate::store::StoreOpaque; 11 use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw}; 12 use core::mem::{self, MaybeUninit}; 13 use core::ptr::NonNull; 14 use wasmtime_environ::component::{ 15 CanonicalOptions, ExportIndex, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, OptionsIndex, 16 TypeFuncIndex, TypeTuple, 17 }; 18 19 #[cfg(feature = "component-model-async")] 20 use crate::component::concurrent::{self, AsAccessor, PreparedCall}; 21 22 mod host; 23 mod options; 24 mod typed; 25 pub use self::host::*; 26 pub use self::options::*; 27 pub use self::typed::*; 28 29 /// A WebAssembly component function which can be called. 30 /// 31 /// This type is the dual of [`wasmtime::Func`](crate::Func) for component 32 /// functions. An instance of [`Func`] represents a component function from a 33 /// component [`Instance`](crate::component::Instance). Like with 34 /// [`wasmtime::Func`](crate::Func) it's possible to call functions either 35 /// synchronously or asynchronously and either typed or untyped. 36 #[derive(Copy, Clone, Debug)] 37 #[repr(C)] // here for the C API. 38 pub struct Func { 39 instance: Instance, 40 index: ExportIndex, 41 } 42 43 // Double-check that the C representation in `component/instance.h` matches our 44 // in-Rust representation here in terms of size/alignment/etc. 45 const _: () = { 46 #[repr(C)] 47 struct T(u64, u32); 48 #[repr(C)] 49 struct C(T, u32); 50 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Func>()); 51 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Func>()); 52 assert!(core::mem::offset_of!(Func, instance) == 0); 53 }; 54 55 impl Func { 56 pub(crate) fn from_lifted_func(instance: Instance, index: ExportIndex) -> Func { 57 Func { instance, index } 58 } 59 60 /// Attempt to cast this [`Func`] to a statically typed [`TypedFunc`] with 61 /// the provided `Params` and `Return`. 62 /// 63 /// This function will perform a type-check at runtime that the [`Func`] 64 /// takes `Params` as parameters and returns `Return`. If the type-check 65 /// passes then a [`TypedFunc`] will be returned which can be used to 66 /// invoke the function in an efficient, statically-typed, and ergonomic 67 /// manner. 68 /// 69 /// The `Params` type parameter here is a tuple of the parameters to the 70 /// function. A function which takes no arguments should use `()`, a 71 /// function with one argument should use `(T,)`, etc. Note that all 72 /// `Params` must also implement the [`Lower`] trait since they're going 73 /// into wasm. 74 /// 75 /// The `Return` type parameter is the return value of this function. A 76 /// return value of `()` means that there's no return (similar to a Rust 77 /// unit return) and otherwise a type `T` can be specified. Note that the 78 /// `Return` must also implement the [`Lift`] trait since it's coming from 79 /// wasm. 80 /// 81 /// Types specified here must implement the [`ComponentType`] trait. This 82 /// trait is implemented for built-in types to Rust such as integer 83 /// primitives, floats, `Option<T>`, `Result<T, E>`, strings, `Vec<T>`, and 84 /// more. As parameters you'll be passing native Rust types. 85 /// 86 /// See the documentation for [`ComponentType`] for more information about 87 /// supported types. 88 /// 89 /// # Errors 90 /// 91 /// If the function does not actually take `Params` as its parameters or 92 /// return `Return` then an error will be returned. 93 /// 94 /// # Panics 95 /// 96 /// This function will panic if `self` is not owned by the `store` 97 /// specified. 98 /// 99 /// # Examples 100 /// 101 /// Calling a function which takes no parameters and has no return value: 102 /// 103 /// ``` 104 /// # use wasmtime::component::Func; 105 /// # use wasmtime::Store; 106 /// # fn foo(func: &Func, store: &mut Store<()>) -> wasmtime::Result<()> { 107 /// let typed = func.typed::<(), ()>(&store)?; 108 /// typed.call(store, ())?; 109 /// # Ok(()) 110 /// # } 111 /// ``` 112 /// 113 /// Calling a function which takes one string parameter and returns a 114 /// string: 115 /// 116 /// ``` 117 /// # use wasmtime::component::Func; 118 /// # use wasmtime::Store; 119 /// # fn foo(func: &Func, mut store: Store<()>) -> wasmtime::Result<()> { 120 /// let typed = func.typed::<(&str,), (String,)>(&store)?; 121 /// let ret = typed.call(&mut store, ("Hello, ",))?.0; 122 /// println!("returned string was: {}", ret); 123 /// # Ok(()) 124 /// # } 125 /// ``` 126 /// 127 /// Calling a function which takes multiple parameters and returns a boolean: 128 /// 129 /// ``` 130 /// # use wasmtime::component::Func; 131 /// # use wasmtime::Store; 132 /// # fn foo(func: &Func, mut store: Store<()>) -> wasmtime::Result<()> { 133 /// let typed = func.typed::<(u32, Option<&str>, &[u8]), (bool,)>(&store)?; 134 /// let ok: bool = typed.call(&mut store, (1, Some("hello"), b"bytes!"))?.0; 135 /// println!("return value was: {ok}"); 136 /// # Ok(()) 137 /// # } 138 /// ``` 139 pub fn typed<Params, Return>(&self, store: impl AsContext) -> Result<TypedFunc<Params, Return>> 140 where 141 Params: ComponentNamedList + Lower, 142 Return: ComponentNamedList + Lift, 143 { 144 self._typed(store.as_context().0, None) 145 } 146 147 pub(crate) fn _typed<Params, Return>( 148 &self, 149 store: &StoreOpaque, 150 instance: Option<&ComponentInstance>, 151 ) -> Result<TypedFunc<Params, Return>> 152 where 153 Params: ComponentNamedList + Lower, 154 Return: ComponentNamedList + Lift, 155 { 156 self.typecheck::<Params, Return>(store, instance)?; 157 unsafe { Ok(TypedFunc::new_unchecked(*self)) } 158 } 159 160 fn typecheck<Params, Return>( 161 &self, 162 store: &StoreOpaque, 163 instance: Option<&ComponentInstance>, 164 ) -> Result<()> 165 where 166 Params: ComponentNamedList + Lower, 167 Return: ComponentNamedList + Lift, 168 { 169 let cx = InstanceType::new(instance.unwrap_or_else(|| self.instance.id().get(store))); 170 let ty = &cx.types[self.ty_index(store)]; 171 172 Params::typecheck(&InterfaceType::Tuple(ty.params), &cx) 173 .context("type mismatch with parameters")?; 174 Return::typecheck(&InterfaceType::Tuple(ty.results), &cx) 175 .context("type mismatch with results")?; 176 177 Ok(()) 178 } 179 180 /// Get the type of this function. 181 pub fn ty(&self, store: impl AsContext) -> ComponentFunc { 182 self.ty_(store.as_context().0) 183 } 184 185 fn ty_(&self, store: &StoreOpaque) -> ComponentFunc { 186 let cx = InstanceType::new(self.instance.id().get(store)); 187 let ty = self.ty_index(store); 188 ComponentFunc::from(ty, &cx) 189 } 190 191 fn ty_index(&self, store: &StoreOpaque) -> TypeFuncIndex { 192 let instance = self.instance.id().get(store); 193 let (ty, _, _) = instance.component().export_lifted_function(self.index); 194 ty 195 } 196 197 /// Invokes this function with the `params` given and returns the result. 198 /// 199 /// The `params` provided must match the parameters that this function takes 200 /// in terms of their types and the number of parameters. Results will be 201 /// written to the `results` slice provided if the call completes 202 /// successfully. The initial types of the values in `results` are ignored 203 /// and values are overwritten to write the result. It's required that the 204 /// size of `results` exactly matches the number of results that this 205 /// function produces. 206 /// 207 /// Note that after a function is invoked the embedder needs to invoke 208 /// [`Func::post_return`] to execute any final cleanup required by the 209 /// guest. This function call is required to either call the function again 210 /// or to call another function. 211 /// 212 /// For more detailed information see the documentation of 213 /// [`TypedFunc::call`]. 214 /// 215 /// # Errors 216 /// 217 /// Returns an error in situations including but not limited to: 218 /// 219 /// * `params` is not the right size or if the values have the wrong type 220 /// * `results` is not the right size 221 /// * A trap occurs while executing the function 222 /// * The function calls a host function which returns an error 223 /// 224 /// See [`TypedFunc::call`] for more information in addition to 225 /// [`wasmtime::Func::call`](crate::Func::call). 226 /// 227 /// # Panics 228 /// 229 /// Panics if this is called on a function in an asynchronous store. This 230 /// only works with functions defined within a synchronous store. Also 231 /// panics if `store` does not own this function. 232 pub fn call( 233 &self, 234 mut store: impl AsContextMut, 235 params: &[Val], 236 results: &mut [Val], 237 ) -> Result<()> { 238 let mut store = store.as_context_mut(); 239 assert!( 240 !store.0.async_support(), 241 "must use `call_async` when async support is enabled on the config" 242 ); 243 self.call_impl(&mut store.as_context_mut(), params, results) 244 } 245 246 /// Exactly like [`Self::call`] except for use on async stores. 247 /// 248 /// Note that after this [`Func::post_return_async`] will be used instead of 249 /// the synchronous version at [`Func::post_return`]. 250 /// 251 /// # Panics 252 /// 253 /// Panics if this is called on a function in a synchronous store. This 254 /// only works with functions defined within an asynchronous store. Also 255 /// panics if `store` does not own this function. 256 #[cfg(feature = "async")] 257 pub async fn call_async( 258 &self, 259 mut store: impl AsContextMut<Data: Send>, 260 params: &[Val], 261 results: &mut [Val], 262 ) -> Result<()> { 263 let store = store.as_context_mut(); 264 265 #[cfg(feature = "component-model-async")] 266 if store.0.cm_concurrency_enabled() { 267 return store 268 .run_concurrent_trap_on_idle(async |store| { 269 self.call_concurrent_dynamic(store, params, results, false) 270 .await 271 .map(drop) 272 }) 273 .await?; 274 } 275 276 assert!( 277 store.0.async_support(), 278 "cannot use `call_async` without enabling async support in the config" 279 ); 280 let mut store = store; 281 store 282 .on_fiber(|store| self.call_impl(store, params, results)) 283 .await? 284 } 285 286 fn check_params_results<T>( 287 &self, 288 store: StoreContextMut<T>, 289 params: &[Val], 290 results: &mut [Val], 291 ) -> Result<()> { 292 let ty = self.ty(&store); 293 if ty.params().len() != params.len() { 294 bail!( 295 "expected {} argument(s), got {}", 296 ty.params().len(), 297 params.len(), 298 ); 299 } 300 301 if ty.results().len() != results.len() { 302 bail!( 303 "expected {} result(s), got {}", 304 ty.results().len(), 305 results.len(), 306 ); 307 } 308 309 Ok(()) 310 } 311 312 /// Start a concurrent call to this function. 313 /// 314 /// Concurrency is achieved by relying on the [`Accessor`] argument, which 315 /// can be obtained by calling [`StoreContextMut::run_concurrent`]. 316 /// 317 /// Unlike [`Self::call`] and [`Self::call_async`] (both of which require 318 /// exclusive access to the store until the completion of the call), calls 319 /// made using this method may run concurrently with other calls to the same 320 /// instance. In addition, the runtime will call the `post-return` function 321 /// (if any) automatically when the guest task completes -- no need to 322 /// explicitly call `Func::post_return` afterward. 323 /// 324 /// This returns a [`TaskExit`] representing the completion of the guest 325 /// task and any transitive subtasks it might create. 326 /// 327 /// # Progress 328 /// 329 /// For the wasm task being created in `call_concurrent` to make progress it 330 /// must be run within the scope of [`run_concurrent`]. If there are no 331 /// active calls to [`run_concurrent`] then the wasm task will appear as 332 /// stalled. This is typically not a concern as an [`Accessor`] is bound 333 /// by default to a scope of [`run_concurrent`]. 334 /// 335 /// One situation in which this can arise, for example, is that if a 336 /// [`run_concurrent`] computation finishes its async closure before all 337 /// wasm tasks have completed, then there will be no scope of 338 /// [`run_concurrent`] anywhere. In this situation the wasm tasks that have 339 /// not yet completed will not make progress until [`run_concurrent`] is 340 /// called again. 341 /// 342 /// Embedders will need to ensure that this future is `await`'d within the 343 /// scope of [`run_concurrent`] to ensure that the value can be produced 344 /// during the `await` call. 345 /// 346 /// # Cancellation 347 /// 348 /// Cancelling an async task created via `call_concurrent`, at this time, is 349 /// only possible by dropping the store that the computation runs within. 350 /// With [#11833] implemented then it will be possible to request 351 /// cancellation of a task, but that is not yet implemented. Hard-cancelling 352 /// a task will only ever be possible by dropping the entire store and it is 353 /// not possible to remove just one task from a store. 354 /// 355 /// This async function behaves more like a "spawn" than a normal Rust async 356 /// function. When this function is invoked then metadata for the function 357 /// call is recorded in the store connected to the `accessor` argument and 358 /// the wasm invocation is from then on connected to the store. If the 359 /// future created by this function is dropped it does not cancel the 360 /// in-progress execution of the wasm task. Dropping the future 361 /// relinquishes the host's ability to learn about the result of the task 362 /// but the task will still progress and invoke callbacks and such until 363 /// completion. 364 /// 365 /// [`run_concurrent`]: crate::Store::run_concurrent 366 /// [#11833]: https://github.com/bytecodealliance/wasmtime/issues/11833 367 /// [`Accessor`]: crate::component::Accessor 368 /// 369 /// # Panics 370 /// 371 /// Panics if the store that the [`Accessor`] is derived from does not own 372 /// this function. 373 /// 374 /// # Example 375 /// 376 /// Using [`StoreContextMut::run_concurrent`] to get an [`Accessor`]: 377 /// 378 /// ``` 379 /// # use { 380 /// # wasmtime::{ 381 /// # error::{Result}, 382 /// # component::{Component, Linker, ResourceTable}, 383 /// # Config, Engine, Store 384 /// # }, 385 /// # }; 386 /// # 387 /// # struct Ctx { table: ResourceTable } 388 /// # 389 /// # async fn foo() -> Result<()> { 390 /// # let mut config = Config::new(); 391 /// # let engine = Engine::new(&config)?; 392 /// # let mut store = Store::new(&engine, Ctx { table: ResourceTable::new() }); 393 /// # let mut linker = Linker::new(&engine); 394 /// # let component = Component::new(&engine, "")?; 395 /// # let instance = linker.instantiate_async(&mut store, &component).await?; 396 /// let my_func = instance.get_func(&mut store, "my_func").unwrap(); 397 /// store.run_concurrent(async |accessor| -> wasmtime::Result<_> { 398 /// my_func.call_concurrent(accessor, &[], &mut Vec::new()).await?; 399 /// Ok(()) 400 /// }).await??; 401 /// # Ok(()) 402 /// # } 403 /// ``` 404 #[cfg(feature = "component-model-async")] 405 pub async fn call_concurrent( 406 self, 407 accessor: impl AsAccessor<Data: Send>, 408 params: &[Val], 409 results: &mut [Val], 410 ) -> Result<TaskExit> { 411 self.call_concurrent_dynamic(accessor, params, results, true) 412 .await 413 } 414 415 /// Internal helper function for `call_async` and `call_concurrent`. 416 #[cfg(feature = "component-model-async")] 417 async fn call_concurrent_dynamic( 418 self, 419 accessor: impl AsAccessor<Data: Send>, 420 params: &[Val], 421 results: &mut [Val], 422 call_post_return_automatically: bool, 423 ) -> Result<TaskExit> { 424 let result = accessor.as_accessor().with(|mut store| { 425 assert!( 426 store.as_context_mut().0.async_support(), 427 "cannot use `call_concurrent` when async support is not enabled on the config" 428 ); 429 self.check_params_results(store.as_context_mut(), params, results)?; 430 let prepared = self.prepare_call_dynamic( 431 store.as_context_mut(), 432 params.to_vec(), 433 call_post_return_automatically, 434 )?; 435 concurrent::queue_call(store.as_context_mut(), prepared) 436 })?; 437 438 let (run_results, rx) = result.await?; 439 assert_eq!(run_results.len(), results.len()); 440 for (result, slot) in run_results.into_iter().zip(results) { 441 *slot = result; 442 } 443 Ok(TaskExit(rx)) 444 } 445 446 /// Calls `concurrent::prepare_call` with monomorphized functions for 447 /// lowering the parameters and lifting the result. 448 #[cfg(feature = "component-model-async")] 449 fn prepare_call_dynamic<'a, T: Send + 'static>( 450 self, 451 mut store: StoreContextMut<'a, T>, 452 params: Vec<Val>, 453 call_post_return_automatically: bool, 454 ) -> Result<PreparedCall<Vec<Val>>> { 455 let store = store.as_context_mut(); 456 457 concurrent::prepare_call( 458 store, 459 self, 460 MAX_FLAT_PARAMS, 461 false, 462 call_post_return_automatically, 463 move |func, store, params_out| { 464 func.with_lower_context(store, call_post_return_automatically, |cx, ty| { 465 Self::lower_args(cx, ¶ms, ty, params_out) 466 }) 467 }, 468 move |func, store, results| { 469 let max_flat = if func.abi_async(store) { 470 MAX_FLAT_PARAMS 471 } else { 472 MAX_FLAT_RESULTS 473 }; 474 let results = func.with_lift_context(store, |cx, ty| { 475 Self::lift_results(cx, ty, results, max_flat)?.collect::<Result<Vec<_>>>() 476 })?; 477 Ok(Box::new(results)) 478 }, 479 ) 480 } 481 482 fn call_impl( 483 &self, 484 mut store: impl AsContextMut, 485 params: &[Val], 486 results: &mut [Val], 487 ) -> Result<()> { 488 let mut store = store.as_context_mut(); 489 490 self.check_params_results(store.as_context_mut(), params, results)?; 491 492 if self.abi_async(store.0) { 493 unreachable!( 494 "async-lifted exports should have failed validation \ 495 when `component-model-async` feature disabled" 496 ); 497 } 498 499 // SAFETY: the chosen representations of type parameters to `call_raw` 500 // here should be generally safe to work with: 501 // 502 // * parameters use `MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>` 503 // which represents the maximal possible number of parameters that can 504 // be passed to lifted component functions. This is modeled with 505 // `MaybeUninit` to represent how it all starts as uninitialized and 506 // thus can't be safely read during lowering. 507 // 508 // * results are modeled as `[ValRaw; MAX_FLAT_RESULTS]` which 509 // represents the maximal size of values that can be returned. Note 510 // that if the function doesn't actually have a return value then the 511 // `ValRaw` inside the array will have undefined contents. That is 512 // safe in Rust, however, due to `ValRaw` being a `union`. The 513 // contents should dynamically not be read due to the type of the 514 // function used here matching the actual lift. 515 unsafe { 516 self.call_raw( 517 store, 518 |cx, ty, dst: &mut MaybeUninit<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>| { 519 // SAFETY: it's safe to assume that 520 // `MaybeUninit<array-of-maybe-uninit>` is initialized because 521 // each individual element is still considered uninitialized. 522 let dst: &mut [MaybeUninit<ValRaw>] = dst.assume_init_mut(); 523 Self::lower_args(cx, params, ty, dst) 524 }, 525 |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| { 526 let max_flat = MAX_FLAT_RESULTS; 527 for (result, slot) in 528 Self::lift_results(cx, results_ty, src, max_flat)?.zip(results) 529 { 530 *slot = result?; 531 } 532 Ok(()) 533 }, 534 ) 535 } 536 } 537 538 pub(crate) fn lifted_core_func(&self, store: &mut StoreOpaque) -> NonNull<VMFuncRef> { 539 let def = { 540 let instance = self.instance.id().get(store); 541 let (_ty, def, _options) = instance.component().export_lifted_function(self.index); 542 def.clone() 543 }; 544 match self.instance.lookup_vmdef(store, &def) { 545 Export::Function(f) => f.vm_func_ref(store), 546 _ => unreachable!(), 547 } 548 } 549 550 pub(crate) fn post_return_core_func(&self, store: &StoreOpaque) -> Option<NonNull<VMFuncRef>> { 551 let instance = self.instance.id().get(store); 552 let component = instance.component(); 553 let (_ty, _def, options) = component.export_lifted_function(self.index); 554 let post_return = component.env_component().options[options].post_return; 555 post_return.map(|i| instance.runtime_post_return(i)) 556 } 557 558 pub(crate) fn abi_async(&self, store: &StoreOpaque) -> bool { 559 let instance = self.instance.id().get(store); 560 let component = instance.component(); 561 let (_ty, _def, options) = component.export_lifted_function(self.index); 562 component.env_component().options[options].async_ 563 } 564 565 pub(crate) fn abi_info<'a>( 566 &self, 567 store: &'a StoreOpaque, 568 ) -> ( 569 OptionsIndex, 570 InstanceFlags, 571 TypeFuncIndex, 572 &'a CanonicalOptions, 573 ) { 574 let vminstance = self.instance.id().get(store); 575 let component = vminstance.component(); 576 let (ty, _def, options_index) = component.export_lifted_function(self.index); 577 let raw_options = &component.env_component().options[options_index]; 578 ( 579 options_index, 580 vminstance.instance_flags(raw_options.instance), 581 ty, 582 raw_options, 583 ) 584 } 585 586 /// Invokes the underlying wasm function, lowering arguments and lifting the 587 /// result. 588 /// 589 /// The `lower` function and `lift` function provided here are what actually 590 /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types 591 /// are what will be allocated on the stack for this function call. They 592 /// should be appropriately sized for the lowering/lifting operation 593 /// happening. 594 /// 595 /// # Safety 596 /// 597 /// The safety of this function relies on the correct definitions of the 598 /// `LowerParams` and `LowerReturn` type. They must match the type of `self` 599 /// for the params/results that are going to be produced. Additionally 600 /// these types must be representable with a sequence of `ValRaw` values. 601 unsafe fn call_raw<T, Return, LowerParams, LowerReturn>( 602 &self, 603 mut store: StoreContextMut<'_, T>, 604 lower: impl FnOnce( 605 &mut LowerContext<'_, T>, 606 InterfaceType, 607 &mut MaybeUninit<LowerParams>, 608 ) -> Result<()>, 609 lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>, 610 ) -> Result<Return> 611 where 612 LowerParams: Copy, 613 LowerReturn: Copy, 614 { 615 let export = self.lifted_core_func(store.0); 616 let (_options, _flags, _ty, raw_options) = self.abi_info(store.0); 617 let instance = RuntimeInstance { 618 instance: self.instance.id().instance(), 619 index: raw_options.instance, 620 }; 621 622 if !store.0.may_enter(instance) { 623 bail!(crate::Trap::CannotEnterComponent); 624 } 625 626 #[repr(C)] 627 union Union<Params: Copy, Return: Copy> { 628 params: Params, 629 ret: Return, 630 } 631 632 let space = &mut MaybeUninit::<Union<LowerParams, LowerReturn>>::uninit(); 633 634 // Double-check the size/alignment of `space`, just in case. 635 // 636 // Note that this alone is not enough to guarantee the validity of the 637 // `unsafe` block below, but it's definitely required. In any case LLVM 638 // should be able to trivially see through these assertions and remove 639 // them in release mode. 640 let val_size = mem::size_of::<ValRaw>(); 641 let val_align = mem::align_of::<ValRaw>(); 642 assert!(mem::size_of_val(space) % val_size == 0); 643 assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0); 644 assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0); 645 assert!(mem::align_of_val(space) == val_align); 646 assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align); 647 assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align); 648 649 self.with_lower_context(store.as_context_mut(), false, |cx, ty| { 650 cx.enter_call(); 651 lower(cx, ty, map_maybe_uninit!(space.params)) 652 })?; 653 654 // SAFETY: We are providing the guarantee that all the inputs are valid. 655 // The various pointers passed in for the function are all valid since 656 // they're coming from our store, and the `params_and_results` should 657 // have the correct layout for the core wasm function we're calling. 658 // Note that this latter point relies on the correctness of this module 659 // and `ComponentType` implementations, hence `ComponentType` being an 660 // `unsafe` trait. 661 unsafe { 662 crate::Func::call_unchecked_raw( 663 &mut store, 664 export, 665 NonNull::new(core::ptr::slice_from_raw_parts_mut( 666 space.as_mut_ptr().cast(), 667 mem::size_of_val(space) / mem::size_of::<ValRaw>(), 668 )) 669 .unwrap(), 670 )?; 671 } 672 673 // SAFETY: We're relying on the correctness of the structure of 674 // `LowerReturn` and the type-checking performed to acquire the 675 // `TypedFunc` to make this safe. It should be the case that 676 // `LowerReturn` is the exact representation of the return value when 677 // interpreted as `[ValRaw]`, and additionally they should have the 678 // correct types for the function we just called (which filled in the 679 // return values). 680 let ret: &LowerReturn = unsafe { map_maybe_uninit!(space.ret).assume_init_ref() }; 681 682 // Lift the result into the host while managing post-return state 683 // here as well. 684 // 685 // After a successful lift the return value of the function, which 686 // is currently required to be 0 or 1 values according to the 687 // canonical ABI, is saved within the `Store`'s `FuncData`. This'll 688 // later get used in post-return. 689 // flags.set_needs_post_return(true); 690 let val = self.with_lift_context(store.0, |cx, ty| lift(cx, ty, ret))?; 691 692 // SAFETY: it's a contract of this function that `LowerReturn` is an 693 // appropriate representation of the result of this function. 694 let ret_slice = unsafe { storage_as_slice(ret) }; 695 696 self.instance.id().get_mut(store.0).post_return_arg_set( 697 self.index, 698 match ret_slice.len() { 699 0 => ValRaw::i32(0), 700 1 => ret_slice[0], 701 _ => unreachable!(), 702 }, 703 ); 704 return Ok(val); 705 } 706 707 /// Invokes the `post-return` canonical ABI option, if specified, after a 708 /// [`Func::call`] has finished. 709 /// 710 /// This function is a required method call after a [`Func::call`] completes 711 /// successfully. After the embedder has finished processing the return 712 /// value then this function must be invoked. 713 /// 714 /// # Errors 715 /// 716 /// This function will return an error in the case of a WebAssembly trap 717 /// happening during the execution of the `post-return` function, if 718 /// specified. 719 /// 720 /// # Panics 721 /// 722 /// This function will panic if it's not called under the correct 723 /// conditions. This can only be called after a previous invocation of 724 /// [`Func::call`] completes successfully, and this function can only 725 /// be called for the same [`Func`] that was `call`'d. 726 /// 727 /// If this function is called when [`Func::call`] was not previously 728 /// called, then it will panic. If a different [`Func`] for the same 729 /// component instance was invoked then this function will also panic 730 /// because the `post-return` needs to happen for the other function. 731 /// 732 /// Panics if this is called on a function in an asynchronous store. 733 /// This only works with functions defined within a synchronous store. 734 #[inline] 735 pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> { 736 let store = store.as_context_mut(); 737 assert!( 738 !store.0.async_support(), 739 "must use `post_return_async` when async support is enabled on the config" 740 ); 741 self.post_return_impl(store) 742 } 743 744 /// Exactly like [`Self::post_return`] except for use on async stores. 745 /// 746 /// # Panics 747 /// 748 /// Panics if this is called on a function in a synchronous store. This 749 /// only works with functions defined within an asynchronous store. 750 #[cfg(feature = "async")] 751 pub async fn post_return_async(&self, mut store: impl AsContextMut<Data: Send>) -> Result<()> { 752 let mut store = store.as_context_mut(); 753 assert!( 754 store.0.async_support(), 755 "cannot use `post_return_async` without enabling async support in the config" 756 ); 757 // Future optimization opportunity: conditionally use a fiber here since 758 // some func's post_return will not need the async context (i.e. end up 759 // calling async host functionality) 760 store.on_fiber(|store| self.post_return_impl(store)).await? 761 } 762 763 fn post_return_impl(&self, mut store: impl AsContextMut) -> Result<()> { 764 let mut store = store.as_context_mut(); 765 766 let index = self.index; 767 let vminstance = self.instance.id().get(store.0); 768 let component = vminstance.component(); 769 let (_ty, _def, options) = component.export_lifted_function(index); 770 let post_return = self.post_return_core_func(store.0); 771 let mut flags = 772 vminstance.instance_flags(component.env_component().options[options].instance); 773 let mut instance = self.instance.id().get_mut(store.0); 774 let post_return_arg = instance.as_mut().post_return_arg_take(index); 775 776 unsafe { 777 // First assert that the instance is in a "needs post return" state. 778 // This will ensure that the previous action on the instance was a 779 // function call above. This flag is only set after a component 780 // function returns so this also can't be called (as expected) 781 // during a host import for example. 782 // 783 // Note, though, that this assert is not sufficient because it just 784 // means some function on this instance needs its post-return 785 // called. We need a precise post-return for a particular function 786 // which is the second assert here (the `.expect`). That will assert 787 // that this function itself needs to have its post-return called. 788 // 789 // The theory at least is that these two asserts ensure component 790 // model semantics are upheld where the host properly calls 791 // `post_return` on the right function despite the call being a 792 // separate step in the API. 793 assert!( 794 flags.needs_post_return(), 795 "post_return can only be called after a function has previously been called", 796 ); 797 let post_return_arg = post_return_arg.expect("calling post_return on wrong function"); 798 799 // Unset the "needs post return" flag now that post-return is being 800 // processed. This will cause future invocations of this method to 801 // panic, even if the function call below traps. 802 flags.set_needs_post_return(false); 803 804 // Post return functions are forbidden from calling imports or 805 // intrinsics. 806 flags.set_may_leave(false); 807 808 // If the function actually had a `post-return` configured in its 809 // canonical options that's executed here. 810 if let Some(func) = post_return { 811 crate::Func::call_unchecked_raw( 812 &mut store, 813 func, 814 NonNull::new(core::ptr::slice_from_raw_parts(&post_return_arg, 1).cast_mut()) 815 .unwrap(), 816 )?; 817 } 818 819 // And finally if everything completed successfully then the "may 820 // leave" flags is set to `true` again here which enables further 821 // use of the component. 822 flags.set_may_leave(true); 823 824 let (calls, host_table, _, instance) = store 825 .0 826 .component_resource_state_with_instance(self.instance); 827 ResourceTables { 828 host_table: Some(host_table), 829 calls, 830 guest: Some(instance.instance_states()), 831 } 832 .exit_call()?; 833 } 834 Ok(()) 835 } 836 837 fn lower_args<T>( 838 cx: &mut LowerContext<'_, T>, 839 params: &[Val], 840 params_ty: InterfaceType, 841 dst: &mut [MaybeUninit<ValRaw>], 842 ) -> Result<()> { 843 let params_ty = match params_ty { 844 InterfaceType::Tuple(i) => &cx.types[i], 845 _ => unreachable!(), 846 }; 847 if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() { 848 let dst = &mut dst.iter_mut(); 849 850 params 851 .iter() 852 .zip(params_ty.types.iter()) 853 .try_for_each(|(param, ty)| param.lower(cx, *ty, dst)) 854 } else { 855 Self::store_args(cx, ¶ms_ty, params, dst) 856 } 857 } 858 859 fn store_args<T>( 860 cx: &mut LowerContext<'_, T>, 861 params_ty: &TypeTuple, 862 args: &[Val], 863 dst: &mut [MaybeUninit<ValRaw>], 864 ) -> Result<()> { 865 let size = usize::try_from(params_ty.abi.size32).unwrap(); 866 let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?; 867 let mut offset = ptr; 868 for (ty, arg) in params_ty.types.iter().zip(args) { 869 let abi = cx.types.canonical_abi(ty); 870 arg.store(cx, *ty, abi.next_field32_size(&mut offset))?; 871 } 872 873 dst[0].write(ValRaw::i64(ptr as i64)); 874 875 Ok(()) 876 } 877 878 fn lift_results<'a, 'b>( 879 cx: &'a mut LiftContext<'b>, 880 results_ty: InterfaceType, 881 src: &'a [ValRaw], 882 max_flat: usize, 883 ) -> Result<Box<dyn Iterator<Item = Result<Val>> + 'a>> { 884 let results_ty = match results_ty { 885 InterfaceType::Tuple(i) => &cx.types[i], 886 _ => unreachable!(), 887 }; 888 if results_ty.abi.flat_count(max_flat).is_some() { 889 let mut flat = src.iter(); 890 Ok(Box::new( 891 results_ty 892 .types 893 .iter() 894 .map(move |ty| Val::lift(cx, *ty, &mut flat)), 895 )) 896 } else { 897 let iter = Self::load_results(cx, results_ty, &mut src.iter())?; 898 Ok(Box::new(iter)) 899 } 900 } 901 902 fn load_results<'a, 'b>( 903 cx: &'a mut LiftContext<'b>, 904 results_ty: &'a TypeTuple, 905 src: &mut core::slice::Iter<'_, ValRaw>, 906 ) -> Result<impl Iterator<Item = Result<Val>> + use<'a, 'b>> { 907 // FIXME(#4311): needs to read an i64 for memory64 908 let ptr = usize::try_from(src.next().unwrap().get_u32())?; 909 if ptr % usize::try_from(results_ty.abi.align32)? != 0 { 910 bail!("return pointer not aligned"); 911 } 912 913 let bytes = cx 914 .memory() 915 .get(ptr..) 916 .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap())) 917 .ok_or_else(|| crate::format_err!("pointer out of bounds of memory"))?; 918 919 let mut offset = 0; 920 Ok(results_ty.types.iter().map(move |ty| { 921 let abi = cx.types.canonical_abi(ty); 922 let offset = abi.next_field32_size(&mut offset); 923 Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize]) 924 })) 925 } 926 927 #[cfg(feature = "component-model-async")] 928 pub(crate) fn instance(self) -> Instance { 929 self.instance 930 } 931 932 #[cfg(feature = "component-model-async")] 933 pub(crate) fn index(self) -> ExportIndex { 934 self.index 935 } 936 937 /// Creates a `LowerContext` using the configuration values of this lifted 938 /// function. 939 /// 940 /// The `lower` closure provided should perform the actual lowering and 941 /// return the result of the lowering operation which is then returned from 942 /// this function as well. 943 fn with_lower_context<T>( 944 self, 945 mut store: StoreContextMut<T>, 946 call_post_return_automatically: bool, 947 lower: impl FnOnce(&mut LowerContext<T>, InterfaceType) -> Result<()>, 948 ) -> Result<()> { 949 let (options_idx, mut flags, ty, options) = self.abi_info(store.0); 950 let async_ = options.async_; 951 952 // Perform the actual lowering, where while this is running the 953 // component is forbidden from calling imports. 954 unsafe { 955 debug_assert!(flags.may_leave()); 956 flags.set_may_leave(false); 957 } 958 let mut cx = LowerContext::new(store.as_context_mut(), options_idx, self.instance); 959 let param_ty = InterfaceType::Tuple(cx.types[ty].params); 960 let result = lower(&mut cx, param_ty); 961 unsafe { flags.set_may_leave(true) }; 962 result?; 963 964 // If needed, flag a post-return call being required as we're about to 965 // enter wasm and afterwards need a post-return. 966 unsafe { 967 if !(call_post_return_automatically && async_) { 968 flags.set_needs_post_return(true); 969 } 970 } 971 972 Ok(()) 973 } 974 975 /// Creates a `LiftContext` using the configuration values with this lifted 976 /// function. 977 /// 978 /// The closure `lift` provided should actually perform the lift itself and 979 /// the result of that closure is returned from this function call as well. 980 fn with_lift_context<R>( 981 self, 982 store: &mut StoreOpaque, 983 lift: impl FnOnce(&mut LiftContext, InterfaceType) -> Result<R>, 984 ) -> Result<R> { 985 let (options, _flags, ty, _) = self.abi_info(store); 986 let mut cx = LiftContext::new(store, options, self.instance); 987 let ty = InterfaceType::Tuple(cx.types[ty].results); 988 lift(&mut cx, ty) 989 } 990 } 991 992 /// Represents the completion of a task created using 993 /// `[Typed]Func::call_concurrent`. 994 /// 995 /// In general, a guest task may continue running after returning a value. 996 /// Moreover, any given guest task may create its own subtasks before or after 997 /// returning and may exit before some or all of those subtasks have finished 998 /// running. In that case, the still-running subtasks will be "reparented" to 999 /// the nearest surviving caller, which may be the original host call. The 1000 /// future returned by `TaskExit::block` will resolve once all transitive 1001 /// subtasks created directly or indirectly by the original call to 1002 /// `Instance::call_concurrent` have exited. 1003 #[cfg(feature = "component-model-async")] 1004 pub struct TaskExit(futures::channel::oneshot::Receiver<()>); 1005 1006 #[cfg(feature = "component-model-async")] 1007 impl TaskExit { 1008 /// Returns a future which will resolve once all transitive subtasks created 1009 /// directly or indirectly by the original call to 1010 /// `Instance::call_concurrent` have exited. 1011 pub async fn block(self, accessor: impl AsAccessor<Data: Send>) { 1012 // The current implementation makes no use of `accessor`, but future 1013 // implementations might (e.g. by using a more efficient mechanism than 1014 // a oneshot channel). 1015 _ = accessor; 1016 1017 // We don't care whether the sender sent us a value or was dropped 1018 // first; either one counts as a notification, so we ignore the result 1019 // once the future resolves: 1020 _ = self.0.await; 1021 } 1022 } 1023