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 anyhow::{bail, Context, Result}; 12 use core::mem::{self, MaybeUninit}; 13 use core::ptr::NonNull; 14 use wasmtime_environ::component::{ 15 CanonicalOptions, ComponentTypes, CoreDef, InterfaceType, RuntimeComponentInstanceIndex, 16 TypeFuncIndex, TypeTuple, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, 17 }; 18 19 /// A helper macro to safely map `MaybeUninit<T>` to `MaybeUninit<U>` where `U` 20 /// is a field projection within `T`. 21 /// 22 /// This is intended to be invoked as: 23 /// 24 /// ```ignore 25 /// struct MyType { 26 /// field: u32, 27 /// } 28 /// 29 /// let initial: &mut MaybeUninit<MyType> = ...; 30 /// let field: &mut MaybeUninit<u32> = map_maybe_uninit!(initial.field); 31 /// ``` 32 /// 33 /// Note that array accesses are also supported: 34 /// 35 /// ```ignore 36 /// 37 /// let initial: &mut MaybeUninit<[u32; 2]> = ...; 38 /// let element: &mut MaybeUninit<u32> = map_maybe_uninit!(initial[1]); 39 /// ``` 40 #[doc(hidden)] 41 #[macro_export] 42 macro_rules! map_maybe_uninit { 43 ($maybe_uninit:ident $($field:tt)*) => ({ 44 #[allow(unused_unsafe)] 45 { 46 unsafe { 47 use $crate::component::__internal::MaybeUninitExt; 48 49 let m: &mut core::mem::MaybeUninit<_> = $maybe_uninit; 50 // Note the usage of `addr_of_mut!` here which is an attempt to "stay 51 // safe" here where we never accidentally create `&mut T` where `T` is 52 // actually uninitialized, hopefully appeasing the Rust unsafe 53 // guidelines gods. 54 m.map(|p| core::ptr::addr_of_mut!((*p)$($field)*)) 55 } 56 } 57 }) 58 } 59 60 #[doc(hidden)] 61 pub trait MaybeUninitExt<T> { 62 /// Maps `MaybeUninit<T>` to `MaybeUninit<U>` using the closure provided. 63 /// 64 /// Note that this is `unsafe` as there is no guarantee that `U` comes from 65 /// `T`. 66 unsafe fn map<U>(&mut self, f: impl FnOnce(*mut T) -> *mut U) -> &mut MaybeUninit<U>; 67 } 68 69 impl<T> MaybeUninitExt<T> for MaybeUninit<T> { 70 unsafe fn map<U>(&mut self, f: impl FnOnce(*mut T) -> *mut U) -> &mut MaybeUninit<U> { 71 let new_ptr = f(self.as_mut_ptr()); 72 core::mem::transmute::<*mut U, &mut MaybeUninit<U>>(new_ptr) 73 } 74 } 75 76 mod host; 77 mod options; 78 mod typed; 79 pub use self::host::*; 80 pub use self::options::*; 81 pub use self::typed::*; 82 83 #[repr(C)] 84 union ParamsAndResults<Params: Copy, Return: Copy> { 85 params: Params, 86 ret: Return, 87 } 88 89 /// A WebAssembly component function which can be called. 90 /// 91 /// This type is the dual of [`wasmtime::Func`](crate::Func) for component 92 /// functions. An instance of [`Func`] represents a component function from a 93 /// component [`Instance`](crate::component::Instance). Like with 94 /// [`wasmtime::Func`](crate::Func) it's possible to call functions either 95 /// synchronously or asynchronously and either typed or untyped. 96 #[derive(Copy, Clone, Debug)] 97 pub struct Func(Stored<FuncData>); 98 99 #[doc(hidden)] 100 pub struct FuncData { 101 export: ExportFunction, 102 ty: TypeFuncIndex, 103 types: Arc<ComponentTypes>, 104 options: Options, 105 instance: Instance, 106 component_instance: RuntimeComponentInstanceIndex, 107 post_return: Option<ExportFunction>, 108 post_return_arg: Option<ValRaw>, 109 } 110 111 impl Func { 112 pub(crate) fn from_lifted_func( 113 store: &mut StoreOpaque, 114 instance: &Instance, 115 data: &InstanceData, 116 ty: TypeFuncIndex, 117 func: &CoreDef, 118 options: &CanonicalOptions, 119 ) -> Func { 120 let export = match data.lookup_def(store, func) { 121 Export::Function(f) => f, 122 _ => unreachable!(), 123 }; 124 let memory = options 125 .memory 126 .map(|i| NonNull::new(data.instance().runtime_memory(i)).unwrap()); 127 let realloc = options.realloc.map(|i| data.instance().runtime_realloc(i)); 128 let post_return = options.post_return.map(|i| { 129 let func_ref = data.instance().runtime_post_return(i); 130 ExportFunction { func_ref } 131 }); 132 let component_instance = options.instance; 133 let options = unsafe { Options::new(store.id(), memory, realloc, options.string_encoding) }; 134 Func(store.store_data_mut().insert(FuncData { 135 export, 136 options, 137 ty, 138 types: data.component_types().clone(), 139 instance: *instance, 140 component_instance, 141 post_return, 142 post_return_arg: None, 143 })) 144 } 145 146 /// Attempt to cast this [`Func`] to a statically typed [`TypedFunc`] with 147 /// the provided `Params` and `Return`. 148 /// 149 /// This function will perform a type-check at runtime that the [`Func`] 150 /// takes `Params` as parameters and returns `Return`. If the type-check 151 /// passes then a [`TypedFunc`] will be returned which can be used to 152 /// invoke the function in an efficient, statically-typed, and ergonomic 153 /// manner. 154 /// 155 /// The `Params` type parameter here is a tuple of the parameters to the 156 /// function. A function which takes no arguments should use `()`, a 157 /// function with one argument should use `(T,)`, etc. Note that all 158 /// `Params` must also implement the [`Lower`] trait since they're going 159 /// into wasm. 160 /// 161 /// The `Return` type parameter is the return value of this function. A 162 /// return value of `()` means that there's no return (similar to a Rust 163 /// unit return) and otherwise a type `T` can be specified. Note that the 164 /// `Return` must also implement the [`Lift`] trait since it's coming from 165 /// wasm. 166 /// 167 /// Types specified here must implement the [`ComponentType`] trait. This 168 /// trait is implemented for built-in types to Rust such as integer 169 /// primitives, floats, `Option<T>`, `Result<T, E>`, strings, `Vec<T>`, and 170 /// more. As parameters you'll be passing native Rust types. 171 /// 172 /// See the documentation for [`ComponentType`] for more information about 173 /// supported types. 174 /// 175 /// # Errors 176 /// 177 /// If the function does not actually take `Params` as its parameters or 178 /// return `Return` then an error will be returned. 179 /// 180 /// # Panics 181 /// 182 /// This function will panic if `self` is not owned by the `store` 183 /// specified. 184 /// 185 /// # Examples 186 /// 187 /// Calling a function which takes no parameters and has no return value: 188 /// 189 /// ``` 190 /// # use wasmtime::component::Func; 191 /// # use wasmtime::Store; 192 /// # fn foo(func: &Func, store: &mut Store<()>) -> anyhow::Result<()> { 193 /// let typed = func.typed::<(), ()>(&store)?; 194 /// typed.call(store, ())?; 195 /// # Ok(()) 196 /// # } 197 /// ``` 198 /// 199 /// Calling a function which takes one string parameter and returns a 200 /// string: 201 /// 202 /// ``` 203 /// # use wasmtime::component::Func; 204 /// # use wasmtime::Store; 205 /// # fn foo(func: &Func, mut store: Store<()>) -> anyhow::Result<()> { 206 /// let typed = func.typed::<(&str,), (String,)>(&store)?; 207 /// let ret = typed.call(&mut store, ("Hello, ",))?.0; 208 /// println!("returned string was: {}", ret); 209 /// # Ok(()) 210 /// # } 211 /// ``` 212 /// 213 /// Calling a function which takes multiple parameters and returns a boolean: 214 /// 215 /// ``` 216 /// # use wasmtime::component::Func; 217 /// # use wasmtime::Store; 218 /// # fn foo(func: &Func, mut store: Store<()>) -> anyhow::Result<()> { 219 /// let typed = func.typed::<(u32, Option<&str>, &[u8]), (bool,)>(&store)?; 220 /// let ok: bool = typed.call(&mut store, (1, Some("hello"), b"bytes!"))?.0; 221 /// println!("return value was: {ok}"); 222 /// # Ok(()) 223 /// # } 224 /// ``` 225 pub fn typed<Params, Return>(&self, store: impl AsContext) -> Result<TypedFunc<Params, Return>> 226 where 227 Params: ComponentNamedList + Lower, 228 Return: ComponentNamedList + Lift, 229 { 230 self._typed(store.as_context().0, None) 231 } 232 233 pub(crate) fn _typed<Params, Return>( 234 &self, 235 store: &StoreOpaque, 236 instance: Option<&InstanceData>, 237 ) -> Result<TypedFunc<Params, Return>> 238 where 239 Params: ComponentNamedList + Lower, 240 Return: ComponentNamedList + Lift, 241 { 242 self.typecheck::<Params, Return>(store, instance)?; 243 unsafe { Ok(TypedFunc::new_unchecked(*self)) } 244 } 245 246 fn typecheck<Params, Return>( 247 &self, 248 store: &StoreOpaque, 249 instance: Option<&InstanceData>, 250 ) -> Result<()> 251 where 252 Params: ComponentNamedList + Lower, 253 Return: ComponentNamedList + Lift, 254 { 255 let data = &store[self.0]; 256 let cx = instance 257 .unwrap_or_else(|| &store[data.instance.0].as_ref().unwrap()) 258 .ty(); 259 let ty = &cx.types[data.ty]; 260 261 Params::typecheck(&InterfaceType::Tuple(ty.params), &cx) 262 .context("type mismatch with parameters")?; 263 Return::typecheck(&InterfaceType::Tuple(ty.results), &cx) 264 .context("type mismatch with results")?; 265 266 Ok(()) 267 } 268 269 /// Get the parameter types for this function. 270 pub fn params(&self, store: impl AsContext) -> Box<[Type]> { 271 let store = store.as_context(); 272 let data = &store[self.0]; 273 let instance = store[data.instance.0].as_ref().unwrap(); 274 data.types[data.types[data.ty].params] 275 .types 276 .iter() 277 .map(|ty| Type::from(ty, &instance.ty())) 278 .collect() 279 } 280 281 /// Get the result types for this function. 282 pub fn results(&self, store: impl AsContext) -> Box<[Type]> { 283 let store = store.as_context(); 284 let data = &store[self.0]; 285 let instance = store[data.instance.0].as_ref().unwrap(); 286 data.types[data.types[data.ty].results] 287 .types 288 .iter() 289 .map(|ty| Type::from(ty, &instance.ty())) 290 .collect() 291 } 292 293 /// Invokes this function with the `params` given and returns the result. 294 /// 295 /// The `params` provided must match the parameters that this function takes 296 /// in terms of their types and the number of parameters. Results will be 297 /// written to the `results` slice provided if the call completes 298 /// successfully. The initial types of the values in `results` are ignored 299 /// and values are overwritten to write the result. It's required that the 300 /// size of `results` exactly matches the number of results that this 301 /// function produces. 302 /// 303 /// Note that after a function is invoked the embedder needs to invoke 304 /// [`Func::post_return`] to execute any final cleanup required by the 305 /// guest. This function call is required to either call the function again 306 /// or to call another function. 307 /// 308 /// For more detailed information see the documentation of 309 /// [`TypedFunc::call`]. 310 /// 311 /// # Errors 312 /// 313 /// Returns an error in situations including but not limited to: 314 /// 315 /// * `params` is not the right size or if the values have the wrong type 316 /// * `results` is not the right size 317 /// * A trap occurs while executing the function 318 /// * The function calls a host function which returns an error 319 /// 320 /// See [`TypedFunc::call`] for more information in addition to 321 /// [`wasmtime::Func::call`](crate::Func::call). 322 /// 323 /// # Panics 324 /// 325 /// Panics if this is called on a function in an asyncronous store. This 326 /// only works with functions defined within a synchronous store. Also 327 /// panics if `store` does not own this function. 328 pub fn call( 329 &self, 330 mut store: impl AsContextMut, 331 params: &[Val], 332 results: &mut [Val], 333 ) -> Result<()> { 334 let mut store = store.as_context_mut(); 335 assert!( 336 !store.0.async_support(), 337 "must use `call_async` when async support is enabled on the config" 338 ); 339 self.call_impl(&mut store.as_context_mut(), params, results) 340 } 341 342 /// Exactly like [`Self::call`] except for use on async stores. 343 /// 344 /// Note that after this [`Func::post_return_async`] will be used instead of 345 /// the synchronous version at [`Func::post_return`]. 346 /// 347 /// # Panics 348 /// 349 /// Panics if this is called on a function in a synchronous store. This 350 /// only works with functions defined within an asynchronous store. Also 351 /// panics if `store` does not own this function. 352 #[cfg(feature = "async")] 353 pub async fn call_async<T>( 354 &self, 355 mut store: impl AsContextMut<Data = T>, 356 params: &[Val], 357 results: &mut [Val], 358 ) -> Result<()> 359 where 360 T: Send, 361 { 362 let mut store = store.as_context_mut(); 363 assert!( 364 store.0.async_support(), 365 "cannot use `call_async` without enabling async support in the config" 366 ); 367 store 368 .on_fiber(|store| self.call_impl(store, params, results)) 369 .await? 370 } 371 372 fn call_impl( 373 &self, 374 mut store: impl AsContextMut, 375 params: &[Val], 376 results: &mut [Val], 377 ) -> Result<()> { 378 let store = &mut store.as_context_mut(); 379 380 let param_tys = self.params(&store); 381 let result_tys = self.results(&store); 382 383 if param_tys.len() != params.len() { 384 bail!( 385 "expected {} argument(s), got {}", 386 param_tys.len(), 387 params.len() 388 ); 389 } 390 if result_tys.len() != results.len() { 391 bail!( 392 "expected {} results(s), got {}", 393 result_tys.len(), 394 results.len() 395 ); 396 } 397 398 self.call_raw( 399 store, 400 params, 401 |cx, params, params_ty, dst: &mut MaybeUninit<[ValRaw; MAX_FLAT_PARAMS]>| { 402 let params_ty = match params_ty { 403 InterfaceType::Tuple(i) => &cx.types[i], 404 _ => unreachable!(), 405 }; 406 if params_ty.abi.flat_count(MAX_FLAT_PARAMS).is_some() { 407 let dst = &mut unsafe { 408 mem::transmute::<_, &mut [MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>(dst) 409 } 410 .iter_mut(); 411 412 params 413 .iter() 414 .zip(params_ty.types.iter()) 415 .try_for_each(|(param, ty)| param.lower(cx, *ty, dst)) 416 } else { 417 self.store_args(cx, ¶ms_ty, params, dst) 418 } 419 }, 420 |cx, results_ty, src: &[ValRaw; MAX_FLAT_RESULTS]| { 421 let results_ty = match results_ty { 422 InterfaceType::Tuple(i) => &cx.types[i], 423 _ => unreachable!(), 424 }; 425 if results_ty.abi.flat_count(MAX_FLAT_RESULTS).is_some() { 426 let mut flat = src.iter(); 427 for (ty, slot) in results_ty.types.iter().zip(results) { 428 *slot = Val::lift(cx, *ty, &mut flat)?; 429 } 430 Ok(()) 431 } else { 432 Self::load_results(cx, results_ty, results, &mut src.iter()) 433 } 434 }, 435 ) 436 } 437 438 /// Invokes the underlying wasm function, lowering arguments and lifting the 439 /// result. 440 /// 441 /// The `lower` function and `lift` function provided here are what actually 442 /// do the lowering and lifting. The `LowerParams` and `LowerReturn` types 443 /// are what will be allocated on the stack for this function call. They 444 /// should be appropriately sized for the lowering/lifting operation 445 /// happening. 446 fn call_raw<T, Params: ?Sized, Return, LowerParams, LowerReturn>( 447 &self, 448 store: &mut StoreContextMut<'_, T>, 449 params: &Params, 450 lower: impl FnOnce( 451 &mut LowerContext<'_, T>, 452 &Params, 453 InterfaceType, 454 &mut MaybeUninit<LowerParams>, 455 ) -> Result<()>, 456 lift: impl FnOnce(&mut LiftContext<'_>, InterfaceType, &LowerReturn) -> Result<Return>, 457 ) -> Result<Return> 458 where 459 LowerParams: Copy, 460 LowerReturn: Copy, 461 { 462 let FuncData { 463 export, 464 options, 465 instance, 466 component_instance, 467 ty, 468 .. 469 } = store.0[self.0]; 470 471 let space = &mut MaybeUninit::<ParamsAndResults<LowerParams, LowerReturn>>::uninit(); 472 473 // Double-check the size/alignemnt of `space`, just in case. 474 // 475 // Note that this alone is not enough to guarantee the validity of the 476 // `unsafe` block below, but it's definitely required. In any case LLVM 477 // should be able to trivially see through these assertions and remove 478 // them in release mode. 479 let val_size = mem::size_of::<ValRaw>(); 480 let val_align = mem::align_of::<ValRaw>(); 481 assert!(mem::size_of_val(space) % val_size == 0); 482 assert!(mem::size_of_val(map_maybe_uninit!(space.params)) % val_size == 0); 483 assert!(mem::size_of_val(map_maybe_uninit!(space.ret)) % val_size == 0); 484 assert!(mem::align_of_val(space) == val_align); 485 assert!(mem::align_of_val(map_maybe_uninit!(space.params)) == val_align); 486 assert!(mem::align_of_val(map_maybe_uninit!(space.ret)) == val_align); 487 488 let instance = store.0[instance.0].as_ref().unwrap(); 489 let types = instance.component_types().clone(); 490 let mut flags = instance.instance().instance_flags(component_instance); 491 492 unsafe { 493 // Test the "may enter" flag which is a "lock" on this instance. 494 // This is immediately set to `false` afterwards and note that 495 // there's no on-cleanup setting this flag back to true. That's an 496 // intentional design aspect where if anything goes wrong internally 497 // from this point on the instance is considered "poisoned" and can 498 // never be entered again. The only time this flag is set to `true` 499 // again is after post-return logic has completed successfully. 500 if !flags.may_enter() { 501 bail!(crate::Trap::CannotEnterComponent); 502 } 503 flags.set_may_enter(false); 504 505 debug_assert!(flags.may_leave()); 506 flags.set_may_leave(false); 507 let instance_ptr = instance.instance_ptr(); 508 let mut cx = LowerContext::new(store.as_context_mut(), &options, &types, instance_ptr); 509 cx.enter_call(); 510 let result = lower( 511 &mut cx, 512 params, 513 InterfaceType::Tuple(types[ty].params), 514 map_maybe_uninit!(space.params), 515 ); 516 flags.set_may_leave(true); 517 result?; 518 519 // This is unsafe as we are providing the guarantee that all the 520 // inputs are valid. The various pointers passed in for the function 521 // are all valid since they're coming from our store, and the 522 // `params_and_results` should have the correct layout for the core 523 // wasm function we're calling. Note that this latter point relies 524 // on the correctness of this module and `ComponentType` 525 // implementations, hence `ComponentType` being an `unsafe` trait. 526 crate::Func::call_unchecked_raw( 527 store, 528 export.func_ref, 529 space.as_mut_ptr().cast(), 530 mem::size_of_val(space) / mem::size_of::<ValRaw>(), 531 )?; 532 533 // Note that `.assume_init_ref()` here is unsafe but we're relying 534 // on the correctness of the structure of `LowerReturn` and the 535 // type-checking performed to acquire the `TypedFunc` to make this 536 // safe. It should be the case that `LowerReturn` is the exact 537 // representation of the return value when interpreted as 538 // `[ValRaw]`, and additionally they should have the correct types 539 // for the function we just called (which filled in the return 540 // values). 541 let ret = map_maybe_uninit!(space.ret).assume_init_ref(); 542 543 // Lift the result into the host while managing post-return state 544 // here as well. 545 // 546 // After a successful lift the return value of the function, which 547 // is currently required to be 0 or 1 values according to the 548 // canonical ABI, is saved within the `Store`'s `FuncData`. This'll 549 // later get used in post-return. 550 flags.set_needs_post_return(true); 551 let val = lift( 552 &mut LiftContext::new(store.0, &options, &types, instance_ptr), 553 InterfaceType::Tuple(types[ty].results), 554 ret, 555 )?; 556 let ret_slice = storage_as_slice(ret); 557 let data = &mut store.0[self.0]; 558 assert!(data.post_return_arg.is_none()); 559 match ret_slice.len() { 560 0 => data.post_return_arg = Some(ValRaw::i32(0)), 561 1 => data.post_return_arg = Some(ret_slice[0]), 562 _ => unreachable!(), 563 } 564 return Ok(val); 565 } 566 } 567 568 /// Invokes the `post-return` canonical ABI option, if specified, after a 569 /// [`Func::call`] has finished. 570 /// 571 /// This function is a required method call after a [`Func::call`] completes 572 /// successfully. After the embedder has finished processing the return 573 /// value then this function must be invoked. 574 /// 575 /// # Errors 576 /// 577 /// This function will return an error in the case of a WebAssembly trap 578 /// happening during the execution of the `post-return` function, if 579 /// specified. 580 /// 581 /// # Panics 582 /// 583 /// This function will panic if it's not called under the correct 584 /// conditions. This can only be called after a previous invocation of 585 /// [`Func::call`] completes successfully, and this function can only 586 /// be called for the same [`Func`] that was `call`'d. 587 /// 588 /// If this function is called when [`Func::call`] was not previously 589 /// called, then it will panic. If a different [`Func`] for the same 590 /// component instance was invoked then this function will also panic 591 /// because the `post-return` needs to happen for the other function. 592 /// 593 /// Panics if this is called on a function in an asynchronous store. 594 /// This only works with functions defined within a synchronous store. 595 #[inline] 596 pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> { 597 let store = store.as_context_mut(); 598 assert!( 599 !store.0.async_support(), 600 "must use `post_return_async` when async support is enabled on the config" 601 ); 602 self.post_return_impl(store) 603 } 604 605 /// Exactly like [`Self::post_return`] except for use on async stores. 606 /// 607 /// # Panics 608 /// 609 /// Panics if this is called on a function in a synchronous store. This 610 /// only works with functions defined within an asynchronous store. 611 #[cfg(feature = "async")] 612 pub async fn post_return_async<T: Send>( 613 &self, 614 mut store: impl AsContextMut<Data = T>, 615 ) -> Result<()> { 616 let mut store = store.as_context_mut(); 617 assert!( 618 store.0.async_support(), 619 "cannot use `call_async` without enabling async support in the config" 620 ); 621 // Future optimization opportunity: conditionally use a fiber here since 622 // some func's post_return will not need the async context (i.e. end up 623 // calling async host functionality) 624 store.on_fiber(|store| self.post_return_impl(store)).await? 625 } 626 627 fn post_return_impl(&self, mut store: impl AsContextMut) -> Result<()> { 628 let mut store = store.as_context_mut(); 629 let data = &mut store.0[self.0]; 630 let instance = data.instance; 631 let post_return = data.post_return; 632 let component_instance = data.component_instance; 633 let post_return_arg = data.post_return_arg.take(); 634 let instance = store.0[instance.0].as_ref().unwrap().instance_ptr(); 635 636 unsafe { 637 let mut flags = (*instance).instance_flags(component_instance); 638 639 // First assert that the instance is in a "needs post return" state. 640 // This will ensure that the previous action on the instance was a 641 // function call above. This flag is only set after a component 642 // function returns so this also can't be called (as expected) 643 // during a host import for example. 644 // 645 // Note, though, that this assert is not sufficient because it just 646 // means some function on this instance needs its post-return 647 // called. We need a precise post-return for a particular function 648 // which is the second assert here (the `.expect`). That will assert 649 // that this function itself needs to have its post-return called. 650 // 651 // The theory at least is that these two asserts ensure component 652 // model semantics are upheld where the host properly calls 653 // `post_return` on the right function despite the call being a 654 // separate step in the API. 655 assert!( 656 flags.needs_post_return(), 657 "post_return can only be called after a function has previously been called", 658 ); 659 let post_return_arg = post_return_arg.expect("calling post_return on wrong function"); 660 661 // This is a sanity-check assert which shouldn't ever trip. 662 assert!(!flags.may_enter()); 663 664 // Unset the "needs post return" flag now that post-return is being 665 // processed. This will cause future invocations of this method to 666 // panic, even if the function call below traps. 667 flags.set_needs_post_return(false); 668 669 // If the function actually had a `post-return` configured in its 670 // canonical options that's executed here. 671 // 672 // Note that if this traps (returns an error) this function 673 // intentionally leaves the instance in a "poisoned" state where it 674 // can no longer be entered because `may_enter` is `false`. 675 if let Some(func) = post_return { 676 crate::Func::call_unchecked_raw( 677 &mut store, 678 func.func_ref, 679 &post_return_arg as *const ValRaw as *mut ValRaw, 680 1, 681 )?; 682 } 683 684 // And finally if everything completed successfully then the "may 685 // enter" flag is set to `true` again here which enables further use 686 // of the component. 687 flags.set_may_enter(true); 688 689 let (calls, host_table, _) = store.0.component_resource_state(); 690 ResourceTables { 691 calls, 692 host_table: Some(host_table), 693 tables: Some((*instance).component_resource_tables()), 694 } 695 .exit_call()?; 696 } 697 Ok(()) 698 } 699 700 fn store_args<T>( 701 &self, 702 cx: &mut LowerContext<'_, T>, 703 params_ty: &TypeTuple, 704 args: &[Val], 705 dst: &mut MaybeUninit<[ValRaw; MAX_FLAT_PARAMS]>, 706 ) -> Result<()> { 707 let size = usize::try_from(params_ty.abi.size32).unwrap(); 708 let ptr = cx.realloc(0, 0, params_ty.abi.align32, size)?; 709 let mut offset = ptr; 710 for (ty, arg) in params_ty.types.iter().zip(args) { 711 let abi = cx.types.canonical_abi(ty); 712 arg.store(cx, *ty, abi.next_field32_size(&mut offset))?; 713 } 714 715 map_maybe_uninit!(dst[0]).write(ValRaw::i64(ptr as i64)); 716 717 Ok(()) 718 } 719 720 fn load_results( 721 cx: &mut LiftContext<'_>, 722 results_ty: &TypeTuple, 723 results: &mut [Val], 724 src: &mut core::slice::Iter<'_, ValRaw>, 725 ) -> Result<()> { 726 // FIXME: needs to read an i64 for memory64 727 let ptr = usize::try_from(src.next().unwrap().get_u32()).err2anyhow()?; 728 if ptr % usize::try_from(results_ty.abi.align32).err2anyhow()? != 0 { 729 bail!("return pointer not aligned"); 730 } 731 732 let bytes = cx 733 .memory() 734 .get(ptr..) 735 .and_then(|b| b.get(..usize::try_from(results_ty.abi.size32).unwrap())) 736 .ok_or_else(|| anyhow::anyhow!("pointer out of bounds of memory"))?; 737 738 let mut offset = 0; 739 for (ty, slot) in results_ty.types.iter().zip(results) { 740 let abi = cx.types.canonical_abi(ty); 741 let offset = abi.next_field32_size(&mut offset); 742 *slot = Val::load(cx, *ty, &bytes[offset..][..abi.size32 as usize])?; 743 } 744 Ok(()) 745 } 746 } 747