1 use crate::prelude::*; 2 use crate::runtime::Uninhabited; 3 use crate::runtime::vm::{ 4 InterpreterRef, SendSyncPtr, StoreBox, VMArrayCallHostFuncContext, VMCommonStackInformation, 5 VMContext, VMFuncRef, VMFunctionImport, VMOpaqueContext, VMStoreContext, 6 }; 7 use crate::store::{AutoAssertNoGc, StoreId, StoreOpaque}; 8 use crate::type_registry::RegisteredType; 9 use crate::{ 10 AsContext, AsContextMut, CallHook, Engine, Extern, FuncType, Instance, ModuleExport, Ref, 11 StoreContext, StoreContextMut, Val, ValRaw, ValType, 12 }; 13 use alloc::sync::Arc; 14 use core::ffi::c_void; 15 #[cfg(feature = "async")] 16 use core::future::Future; 17 use core::mem::{self, MaybeUninit}; 18 use core::ptr::NonNull; 19 use wasmtime_environ::VMSharedTypeIndex; 20 21 /// A reference to the abstract `nofunc` heap value. 22 /// 23 /// The are no instances of `(ref nofunc)`: it is an uninhabited type. 24 /// 25 /// There is precisely one instance of `(ref null nofunc)`, aka `nullfuncref`: 26 /// the null reference. 27 /// 28 /// This `NoFunc` Rust type's sole purpose is for use with [`Func::wrap`]- and 29 /// [`Func::typed`]-style APIs for statically typing a function as taking or 30 /// returning a `(ref null nofunc)` (aka `Option<NoFunc>`) which is always 31 /// `None`. 32 /// 33 /// # Example 34 /// 35 /// ``` 36 /// # use wasmtime::*; 37 /// # fn _foo() -> Result<()> { 38 /// let mut config = Config::new(); 39 /// config.wasm_function_references(true); 40 /// let engine = Engine::new(&config)?; 41 /// 42 /// let module = Module::new( 43 /// &engine, 44 /// r#" 45 /// (module 46 /// (func (export "f") (param (ref null nofunc)) 47 /// ;; If the reference is null, return. 48 /// local.get 0 49 /// ref.is_null nofunc 50 /// br_if 0 51 /// 52 /// ;; If the reference was not null (which is impossible) 53 /// ;; then raise a trap. 54 /// unreachable 55 /// ) 56 /// ) 57 /// "#, 58 /// )?; 59 /// 60 /// let mut store = Store::new(&engine, ()); 61 /// let instance = Instance::new(&mut store, &module, &[])?; 62 /// let f = instance.get_func(&mut store, "f").unwrap(); 63 /// 64 /// // We can cast a `(ref null nofunc)`-taking function into a typed function that 65 /// // takes an `Option<NoFunc>` via the `Func::typed` method. 66 /// let f = f.typed::<Option<NoFunc>, ()>(&store)?; 67 /// 68 /// // We can call the typed function, passing the null `nofunc` reference. 69 /// let result = f.call(&mut store, NoFunc::null()); 70 /// 71 /// // The function should not have trapped, because the reference we gave it was 72 /// // null (as it had to be, since `NoFunc` is uninhabited). 73 /// assert!(result.is_ok()); 74 /// # Ok(()) 75 /// # } 76 /// ``` 77 #[derive(Copy, Clone, Debug, PartialEq, Eq)] 78 pub struct NoFunc { 79 _inner: Uninhabited, 80 } 81 82 impl NoFunc { 83 /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference. 84 #[inline] 85 pub fn null() -> Option<NoFunc> { 86 None 87 } 88 89 /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a 90 /// [`Ref`]. 91 #[inline] 92 pub fn null_ref() -> Ref { 93 Ref::Func(None) 94 } 95 96 /// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a 97 /// [`Val`]. 98 #[inline] 99 pub fn null_val() -> Val { 100 Val::FuncRef(None) 101 } 102 } 103 104 /// A WebAssembly function which can be called. 105 /// 106 /// This type typically represents an exported function from a WebAssembly 107 /// module instance. In this case a [`Func`] belongs to an [`Instance`] and is 108 /// loaded from there. A [`Func`] may also represent a host function as well in 109 /// some cases, too. 110 /// 111 /// Functions can be called in a few different ways, either synchronous or async 112 /// and either typed or untyped (more on this below). Note that host functions 113 /// are normally inserted directly into a [`Linker`](crate::Linker) rather than 114 /// using this directly, but both options are available. 115 /// 116 /// # `Func` and `async` 117 /// 118 /// Functions from the perspective of WebAssembly are always synchronous. You 119 /// might have an `async` function in Rust, however, which you'd like to make 120 /// available from WebAssembly. Wasmtime supports asynchronously calling 121 /// WebAssembly through native stack switching. You can get some more 122 /// information about [asynchronous configs](crate::Config::async_support), but 123 /// from the perspective of `Func` it's important to know that whether or not 124 /// your [`Store`](crate::Store) is asynchronous will dictate whether you call 125 /// functions through [`Func::call`] or [`Func::call_async`] (or the typed 126 /// wrappers such as [`TypedFunc::call`] vs [`TypedFunc::call_async`]). 127 /// 128 /// # To `Func::call` or to `Func::typed().call()` 129 /// 130 /// There's a 2x2 matrix of methods to call [`Func`]. Invocations can either be 131 /// asynchronous or synchronous. They can also be statically typed or not. 132 /// Whether or not an invocation is asynchronous is indicated via the method 133 /// being `async` and [`call_async`](Func::call_async) being the entry point. 134 /// Otherwise for statically typed or not your options are: 135 /// 136 /// * Dynamically typed - if you don't statically know the signature of the 137 /// function that you're calling you'll be using [`Func::call`] or 138 /// [`Func::call_async`]. These functions take a variable-length slice of 139 /// "boxed" arguments in their [`Val`] representation. Additionally the 140 /// results are returned as an owned slice of [`Val`]. These methods are not 141 /// optimized due to the dynamic type checks that must occur, in addition to 142 /// some dynamic allocations for where to put all the arguments. While this 143 /// allows you to call all possible wasm function signatures, if you're 144 /// looking for a speedier alternative you can also use... 145 /// 146 /// * Statically typed - if you statically know the type signature of the wasm 147 /// function you're calling, then you'll want to use the [`Func::typed`] 148 /// method to acquire an instance of [`TypedFunc`]. This structure is static proof 149 /// that the underlying wasm function has the ascripted type, and type 150 /// validation is only done once up-front. The [`TypedFunc::call`] and 151 /// [`TypedFunc::call_async`] methods are much more efficient than [`Func::call`] 152 /// and [`Func::call_async`] because the type signature is statically known. 153 /// This eschews runtime checks as much as possible to get into wasm as fast 154 /// as possible. 155 /// 156 /// # Examples 157 /// 158 /// One way to get a `Func` is from an [`Instance`] after you've instantiated 159 /// it: 160 /// 161 /// ``` 162 /// # use wasmtime::*; 163 /// # fn main() -> anyhow::Result<()> { 164 /// let engine = Engine::default(); 165 /// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?; 166 /// let mut store = Store::new(&engine, ()); 167 /// let instance = Instance::new(&mut store, &module, &[])?; 168 /// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function"); 169 /// 170 /// // Work with `foo` as a `Func` at this point, such as calling it 171 /// // dynamically... 172 /// match foo.call(&mut store, &[], &mut []) { 173 /// Ok(()) => { /* ... */ } 174 /// Err(trap) => { 175 /// panic!("execution of `foo` resulted in a wasm trap: {}", trap); 176 /// } 177 /// } 178 /// foo.call(&mut store, &[], &mut [])?; 179 /// 180 /// // ... or we can make a static assertion about its signature and call it. 181 /// // Our first call here can fail if the signatures don't match, and then the 182 /// // second call can fail if the function traps (like the `match` above). 183 /// let foo = foo.typed::<(), ()>(&store)?; 184 /// foo.call(&mut store, ())?; 185 /// # Ok(()) 186 /// # } 187 /// ``` 188 /// 189 /// You can also use the [`wrap` function](Func::wrap) to create a 190 /// `Func` 191 /// 192 /// ``` 193 /// # use wasmtime::*; 194 /// # fn main() -> anyhow::Result<()> { 195 /// let mut store = Store::<()>::default(); 196 /// 197 /// // Create a custom `Func` which can execute arbitrary code inside of the 198 /// // closure. 199 /// let add = Func::wrap(&mut store, |a: i32, b: i32| -> i32 { a + b }); 200 /// 201 /// // Next we can hook that up to a wasm module which uses it. 202 /// let module = Module::new( 203 /// store.engine(), 204 /// r#" 205 /// (module 206 /// (import "" "" (func $add (param i32 i32) (result i32))) 207 /// (func (export "call_add_twice") (result i32) 208 /// i32.const 1 209 /// i32.const 2 210 /// call $add 211 /// i32.const 3 212 /// i32.const 4 213 /// call $add 214 /// i32.add)) 215 /// "#, 216 /// )?; 217 /// let instance = Instance::new(&mut store, &module, &[add.into()])?; 218 /// let call_add_twice = instance.get_typed_func::<(), i32>(&mut store, "call_add_twice")?; 219 /// 220 /// assert_eq!(call_add_twice.call(&mut store, ())?, 10); 221 /// # Ok(()) 222 /// # } 223 /// ``` 224 /// 225 /// Or you could also create an entirely dynamic `Func`! 226 /// 227 /// ``` 228 /// # use wasmtime::*; 229 /// # fn main() -> anyhow::Result<()> { 230 /// let mut store = Store::<()>::default(); 231 /// 232 /// // Here we need to define the type signature of our `Double` function and 233 /// // then wrap it up in a `Func` 234 /// let double_type = wasmtime::FuncType::new( 235 /// store.engine(), 236 /// [wasmtime::ValType::I32].iter().cloned(), 237 /// [wasmtime::ValType::I32].iter().cloned(), 238 /// ); 239 /// let double = Func::new(&mut store, double_type, |_, params, results| { 240 /// let mut value = params[0].unwrap_i32(); 241 /// value *= 2; 242 /// results[0] = value.into(); 243 /// Ok(()) 244 /// }); 245 /// 246 /// let module = Module::new( 247 /// store.engine(), 248 /// r#" 249 /// (module 250 /// (import "" "" (func $double (param i32) (result i32))) 251 /// (func $start 252 /// i32.const 1 253 /// call $double 254 /// drop) 255 /// (start $start)) 256 /// "#, 257 /// )?; 258 /// let instance = Instance::new(&mut store, &module, &[double.into()])?; 259 /// // .. work with `instance` if necessary 260 /// # Ok(()) 261 /// # } 262 /// ``` 263 #[derive(Copy, Clone, Debug)] 264 #[repr(C)] // here for the C API 265 pub struct Func { 266 /// The store that the below pointer belongs to. 267 /// 268 /// It's only safe to look at the contents of the pointer below when the 269 /// `StoreOpaque` matching this id is in-scope. 270 store: StoreId, 271 272 /// The raw `VMFuncRef`, whose lifetime is bound to the store this func 273 /// belongs to. 274 /// 275 /// Note that this field has an `unsafe_*` prefix to discourage use of it. 276 /// This is only safe to read/use if `self.store` is validated to belong to 277 /// an ambiently provided `StoreOpaque` or similar. Use the 278 /// `self.func_ref()` method instead of this field to perform this check. 279 unsafe_func_ref: SendSyncPtr<VMFuncRef>, 280 } 281 282 // Double-check that the C representation in `extern.h` matches our in-Rust 283 // representation here in terms of size/alignment/etc. 284 const _: () = { 285 #[repr(C)] 286 struct C(u64, *mut u8); 287 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Func>()); 288 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Func>()); 289 assert!(core::mem::offset_of!(Func, store) == 0); 290 }; 291 292 macro_rules! for_each_function_signature { 293 ($mac:ident) => { 294 $mac!(0); 295 $mac!(1 A1); 296 $mac!(2 A1 A2); 297 $mac!(3 A1 A2 A3); 298 $mac!(4 A1 A2 A3 A4); 299 $mac!(5 A1 A2 A3 A4 A5); 300 $mac!(6 A1 A2 A3 A4 A5 A6); 301 $mac!(7 A1 A2 A3 A4 A5 A6 A7); 302 $mac!(8 A1 A2 A3 A4 A5 A6 A7 A8); 303 $mac!(9 A1 A2 A3 A4 A5 A6 A7 A8 A9); 304 $mac!(10 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10); 305 $mac!(11 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11); 306 $mac!(12 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12); 307 $mac!(13 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13); 308 $mac!(14 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14); 309 $mac!(15 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15); 310 $mac!(16 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16); 311 $mac!(17 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17); 312 }; 313 } 314 315 mod typed; 316 use crate::runtime::vm::VMStackChain; 317 pub use typed::*; 318 319 impl Func { 320 /// Creates a new `Func` with the given arguments, typically to create a 321 /// host-defined function to pass as an import to a module. 322 /// 323 /// * `store` - the store in which to create this [`Func`], which will own 324 /// the return value. 325 /// 326 /// * `ty` - the signature of this function, used to indicate what the 327 /// inputs and outputs are. 328 /// 329 /// * `func` - the native code invoked whenever this `Func` will be called. 330 /// This closure is provided a [`Caller`] as its first argument to learn 331 /// information about the caller, and then it's passed a list of 332 /// parameters as a slice along with a mutable slice of where to write 333 /// results. 334 /// 335 /// Note that the implementation of `func` must adhere to the `ty` signature 336 /// given, error or traps may occur if it does not respect the `ty` 337 /// signature. For example if the function type declares that it returns one 338 /// i32 but the `func` closures does not write anything into the results 339 /// slice then a trap may be generated. 340 /// 341 /// Additionally note that this is quite a dynamic function since signatures 342 /// are not statically known. For a more performant and ergonomic `Func` 343 /// it's recommended to use [`Func::wrap`] if you can because with 344 /// statically known signatures Wasmtime can optimize the implementation 345 /// much more. 346 /// 347 /// For more information about `Send + Sync + 'static` requirements on the 348 /// `func`, see [`Func::wrap`](#why-send--sync--static). 349 /// 350 /// # Errors 351 /// 352 /// The host-provided function here returns a 353 /// [`Result<()>`](anyhow::Result). If the function returns `Ok(())` then 354 /// that indicates that the host function completed successfully and wrote 355 /// the result into the `&mut [Val]` argument. 356 /// 357 /// If the function returns `Err(e)`, however, then this is equivalent to 358 /// the host function triggering a trap for wasm. WebAssembly execution is 359 /// immediately halted and the original caller of [`Func::call`], for 360 /// example, will receive the error returned here (possibly with 361 /// [`WasmBacktrace`](crate::WasmBacktrace) context information attached). 362 /// 363 /// For more information about errors in Wasmtime see the [`Trap`] 364 /// documentation. 365 /// 366 /// [`Trap`]: crate::Trap 367 /// 368 /// # Panics 369 /// 370 /// Panics if the given function type is not associated with this store's 371 /// engine. 372 pub fn new<T: 'static>( 373 store: impl AsContextMut<Data = T>, 374 ty: FuncType, 375 func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static, 376 ) -> Self { 377 assert!(ty.comes_from_same_engine(store.as_context().engine())); 378 let ty_clone = ty.clone(); 379 unsafe { 380 Func::new_unchecked(store, ty, move |caller, values| { 381 Func::invoke_host_func_for_wasm(caller, &ty_clone, values, &func) 382 }) 383 } 384 } 385 386 /// Creates a new [`Func`] with the given arguments, although has fewer 387 /// runtime checks than [`Func::new`]. 388 /// 389 /// This function takes a callback of a different signature than 390 /// [`Func::new`], instead receiving a raw pointer with a list of [`ValRaw`] 391 /// structures. These values have no type information associated with them 392 /// so it's up to the caller to provide a function that will correctly 393 /// interpret the list of values as those coming from the `ty` specified. 394 /// 395 /// If you're calling this from Rust it's recommended to either instead use 396 /// [`Func::new`] or [`Func::wrap`]. The [`Func::wrap`] API, in particular, 397 /// is both safer and faster than this API. 398 /// 399 /// # Errors 400 /// 401 /// See [`Func::new`] for the behavior of returning an error from the host 402 /// function provided here. 403 /// 404 /// # Unsafety 405 /// 406 /// This function is not safe because it's not known at compile time that 407 /// the `func` provided correctly interprets the argument types provided to 408 /// it, or that the results it produces will be of the correct type. 409 /// 410 /// # Panics 411 /// 412 /// Panics if the given function type is not associated with this store's 413 /// engine. 414 pub unsafe fn new_unchecked<T: 'static>( 415 mut store: impl AsContextMut<Data = T>, 416 ty: FuncType, 417 func: impl Fn(Caller<'_, T>, &mut [ValRaw]) -> Result<()> + Send + Sync + 'static, 418 ) -> Self { 419 assert!(ty.comes_from_same_engine(store.as_context().engine())); 420 let store = store.as_context_mut().0; 421 let host = HostFunc::new_unchecked(store.engine(), ty, func); 422 host.into_func(store) 423 } 424 425 /// Creates a new host-defined WebAssembly function which, when called, 426 /// will run the asynchronous computation defined by `func` to completion 427 /// and then return the result to WebAssembly. 428 /// 429 /// This function is the asynchronous analogue of [`Func::new`] and much of 430 /// that documentation applies to this as well. The key difference is that 431 /// `func` returns a future instead of simply a `Result`. Note that the 432 /// returned future can close over any of the arguments, but it cannot close 433 /// over the state of the closure itself. It's recommended to store any 434 /// necessary async state in the `T` of the [`Store<T>`](crate::Store) which 435 /// can be accessed through [`Caller::data`] or [`Caller::data_mut`]. 436 /// 437 /// For more information on `Send + Sync + 'static`, see 438 /// [`Func::wrap`](#why-send--sync--static). 439 /// 440 /// # Panics 441 /// 442 /// This function will panic if `store` is not associated with an [async 443 /// config](crate::Config::async_support). 444 /// 445 /// Panics if the given function type is not associated with this store's 446 /// engine. 447 /// 448 /// # Errors 449 /// 450 /// See [`Func::new`] for the behavior of returning an error from the host 451 /// function provided here. 452 /// 453 /// # Examples 454 /// 455 /// ``` 456 /// # use wasmtime::*; 457 /// # fn main() -> anyhow::Result<()> { 458 /// // Simulate some application-specific state as well as asynchronous 459 /// // functions to query that state. 460 /// struct MyDatabase { 461 /// // ... 462 /// } 463 /// 464 /// impl MyDatabase { 465 /// async fn get_row_count(&self) -> u32 { 466 /// // ... 467 /// # 100 468 /// } 469 /// } 470 /// 471 /// let my_database = MyDatabase { 472 /// // ... 473 /// }; 474 /// 475 /// // Using `new_async` we can hook up into calling our async 476 /// // `get_row_count` function. 477 /// let engine = Engine::new(Config::new().async_support(true))?; 478 /// let mut store = Store::new(&engine, MyDatabase { 479 /// // ... 480 /// }); 481 /// let get_row_count_type = wasmtime::FuncType::new( 482 /// &engine, 483 /// None, 484 /// Some(wasmtime::ValType::I32), 485 /// ); 486 /// let get = Func::new_async(&mut store, get_row_count_type, |caller, _params, results| { 487 /// Box::new(async move { 488 /// let count = caller.data().get_row_count().await; 489 /// results[0] = Val::I32(count as i32); 490 /// Ok(()) 491 /// }) 492 /// }); 493 /// // ... 494 /// # Ok(()) 495 /// # } 496 /// ``` 497 #[cfg(all(feature = "async", feature = "cranelift"))] 498 pub fn new_async<T, F>(store: impl AsContextMut<Data = T>, ty: FuncType, func: F) -> Func 499 where 500 F: for<'a> Fn( 501 Caller<'a, T>, 502 &'a [Val], 503 &'a mut [Val], 504 ) -> Box<dyn Future<Output = Result<()>> + Send + 'a> 505 + Send 506 + Sync 507 + 'static, 508 T: 'static, 509 { 510 assert!( 511 store.as_context().async_support(), 512 "cannot use `new_async` without enabling async support in the config" 513 ); 514 assert!(ty.comes_from_same_engine(store.as_context().engine())); 515 return Func::new( 516 store, 517 ty, 518 move |Caller { store, caller }, params, results| { 519 store.with_blocking(|store, cx| { 520 cx.block_on(core::pin::Pin::from(func( 521 Caller { store, caller }, 522 params, 523 results, 524 ))) 525 })? 526 }, 527 ); 528 } 529 530 /// Creates a new `Func` from a store and a funcref within that store. 531 /// 532 /// # Safety 533 /// 534 /// The safety of this function requires that `func_ref` is a valid function 535 /// pointer owned by `store`. 536 pub(crate) unsafe fn from_vm_func_ref(store: StoreId, func_ref: NonNull<VMFuncRef>) -> Func { 537 debug_assert!(func_ref.as_ref().type_index != VMSharedTypeIndex::default()); 538 Func { 539 store, 540 unsafe_func_ref: func_ref.into(), 541 } 542 } 543 544 /// Creates a new `Func` from the given Rust closure. 545 /// 546 /// This function will create a new `Func` which, when called, will 547 /// execute the given Rust closure. Unlike [`Func::new`] the target 548 /// function being called is known statically so the type signature can 549 /// be inferred. Rust types will map to WebAssembly types as follows: 550 /// 551 /// | Rust Argument Type | WebAssembly Type | 552 /// |-----------------------------------|-------------------------------------------| 553 /// | `i32` | `i32` | 554 /// | `u32` | `i32` | 555 /// | `i64` | `i64` | 556 /// | `u64` | `i64` | 557 /// | `f32` | `f32` | 558 /// | `f64` | `f64` | 559 /// | `V128` on x86-64 and aarch64 only | `v128` | 560 /// | `Option<Func>` | `funcref` aka `(ref null func)` | 561 /// | `Func` | `(ref func)` | 562 /// | `Option<Nofunc>` | `nullfuncref` aka `(ref null nofunc)` | 563 /// | `NoFunc` | `(ref nofunc)` | 564 /// | `Option<Rooted<ExternRef>>` | `externref` aka `(ref null extern)` | 565 /// | `Rooted<ExternRef>` | `(ref extern)` | 566 /// | `Option<NoExtern>` | `nullexternref` aka `(ref null noextern)` | 567 /// | `NoExtern` | `(ref noextern)` | 568 /// | `Option<Rooted<AnyRef>>` | `anyref` aka `(ref null any)` | 569 /// | `Rooted<AnyRef>` | `(ref any)` | 570 /// | `Option<Rooted<EqRef>>` | `eqref` aka `(ref null eq)` | 571 /// | `Rooted<EqRef>` | `(ref eq)` | 572 /// | `Option<I31>` | `i31ref` aka `(ref null i31)` | 573 /// | `I31` | `(ref i31)` | 574 /// | `Option<Rooted<StructRef>>` | `(ref null struct)` | 575 /// | `Rooted<StructRef>` | `(ref struct)` | 576 /// | `Option<Rooted<ArrayRef>>` | `(ref null array)` | 577 /// | `Rooted<ArrayRef>` | `(ref array)` | 578 /// | `Option<NoneRef>` | `nullref` aka `(ref null none)` | 579 /// | `NoneRef` | `(ref none)` | 580 /// 581 /// Note that anywhere a `Rooted<T>` appears, a `ManuallyRooted<T>` may also 582 /// be used. 583 /// 584 /// Any of the Rust types can be returned from the closure as well, in 585 /// addition to some extra types 586 /// 587 /// | Rust Return Type | WebAssembly Return Type | Meaning | 588 /// |-------------------|-------------------------|-----------------------| 589 /// | `()` | nothing | no return value | 590 /// | `T` | `T` | a single return value | 591 /// | `(T1, T2, ...)` | `T1 T2 ...` | multiple returns | 592 /// 593 /// Note that all return types can also be wrapped in `Result<_>` to 594 /// indicate that the host function can generate a trap as well as possibly 595 /// returning a value. 596 /// 597 /// Finally you can also optionally take [`Caller`] as the first argument of 598 /// your closure. If inserted then you're able to inspect the caller's 599 /// state, for example the [`Memory`](crate::Memory) it has exported so you 600 /// can read what pointers point to. 601 /// 602 /// Note that when using this API, the intention is to create as thin of a 603 /// layer as possible for when WebAssembly calls the function provided. With 604 /// sufficient inlining and optimization the WebAssembly will call straight 605 /// into `func` provided, with no extra fluff entailed. 606 /// 607 /// # Why `Send + Sync + 'static`? 608 /// 609 /// All host functions defined in a [`Store`](crate::Store) (including 610 /// those from [`Func::new`] and other constructors) require that the 611 /// `func` provided is `Send + Sync + 'static`. Additionally host functions 612 /// always are `Fn` as opposed to `FnMut` or `FnOnce`. This can at-a-glance 613 /// feel restrictive since the closure cannot close over as many types as 614 /// before. The reason for this, though, is to ensure that 615 /// [`Store<T>`](crate::Store) can implement both the `Send` and `Sync` 616 /// traits. 617 /// 618 /// Fear not, however, because this isn't as restrictive as it seems! Host 619 /// functions are provided a [`Caller<'_, T>`](crate::Caller) argument which 620 /// allows access to the host-defined data within the 621 /// [`Store`](crate::Store). The `T` type is not required to be any of 622 /// `Send`, `Sync`, or `'static`! This means that you can store whatever 623 /// you'd like in `T` and have it accessible by all host functions. 624 /// Additionally mutable access to `T` is allowed through 625 /// [`Caller::data_mut`]. 626 /// 627 /// Most host-defined [`Func`] values provide closures that end up not 628 /// actually closing over any values. These zero-sized types will use the 629 /// context from [`Caller`] for host-defined information. 630 /// 631 /// # Errors 632 /// 633 /// The closure provided here to `wrap` can optionally return a 634 /// [`Result<T>`](anyhow::Result). Returning `Ok(t)` represents the host 635 /// function successfully completing with the `t` result. Returning 636 /// `Err(e)`, however, is equivalent to raising a custom wasm trap. 637 /// Execution of WebAssembly does not resume and the stack is unwound to the 638 /// original caller of the function where the error is returned. 639 /// 640 /// For more information about errors in Wasmtime see the [`Trap`] 641 /// documentation. 642 /// 643 /// [`Trap`]: crate::Trap 644 /// 645 /// # Examples 646 /// 647 /// First up we can see how simple wasm imports can be implemented, such 648 /// as a function that adds its two arguments and returns the result. 649 /// 650 /// ``` 651 /// # use wasmtime::*; 652 /// # fn main() -> anyhow::Result<()> { 653 /// # let mut store = Store::<()>::default(); 654 /// let add = Func::wrap(&mut store, |a: i32, b: i32| a + b); 655 /// let module = Module::new( 656 /// store.engine(), 657 /// r#" 658 /// (module 659 /// (import "" "" (func $add (param i32 i32) (result i32))) 660 /// (func (export "foo") (param i32 i32) (result i32) 661 /// local.get 0 662 /// local.get 1 663 /// call $add)) 664 /// "#, 665 /// )?; 666 /// let instance = Instance::new(&mut store, &module, &[add.into()])?; 667 /// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?; 668 /// assert_eq!(foo.call(&mut store, (1, 2))?, 3); 669 /// # Ok(()) 670 /// # } 671 /// ``` 672 /// 673 /// We can also do the same thing, but generate a trap if the addition 674 /// overflows: 675 /// 676 /// ``` 677 /// # use wasmtime::*; 678 /// # fn main() -> anyhow::Result<()> { 679 /// # let mut store = Store::<()>::default(); 680 /// let add = Func::wrap(&mut store, |a: i32, b: i32| { 681 /// match a.checked_add(b) { 682 /// Some(i) => Ok(i), 683 /// None => anyhow::bail!("overflow"), 684 /// } 685 /// }); 686 /// let module = Module::new( 687 /// store.engine(), 688 /// r#" 689 /// (module 690 /// (import "" "" (func $add (param i32 i32) (result i32))) 691 /// (func (export "foo") (param i32 i32) (result i32) 692 /// local.get 0 693 /// local.get 1 694 /// call $add)) 695 /// "#, 696 /// )?; 697 /// let instance = Instance::new(&mut store, &module, &[add.into()])?; 698 /// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?; 699 /// assert_eq!(foo.call(&mut store, (1, 2))?, 3); 700 /// assert!(foo.call(&mut store, (i32::max_value(), 1)).is_err()); 701 /// # Ok(()) 702 /// # } 703 /// ``` 704 /// 705 /// And don't forget all the wasm types are supported! 706 /// 707 /// ``` 708 /// # use wasmtime::*; 709 /// # fn main() -> anyhow::Result<()> { 710 /// # let mut store = Store::<()>::default(); 711 /// let debug = Func::wrap(&mut store, |a: i32, b: u32, c: f32, d: i64, e: u64, f: f64| { 712 /// 713 /// println!("a={}", a); 714 /// println!("b={}", b); 715 /// println!("c={}", c); 716 /// println!("d={}", d); 717 /// println!("e={}", e); 718 /// println!("f={}", f); 719 /// }); 720 /// let module = Module::new( 721 /// store.engine(), 722 /// r#" 723 /// (module 724 /// (import "" "" (func $debug (param i32 i32 f32 i64 i64 f64))) 725 /// (func (export "foo") 726 /// i32.const -1 727 /// i32.const 1 728 /// f32.const 2 729 /// i64.const -3 730 /// i64.const 3 731 /// f64.const 4 732 /// call $debug)) 733 /// "#, 734 /// )?; 735 /// let instance = Instance::new(&mut store, &module, &[debug.into()])?; 736 /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?; 737 /// foo.call(&mut store, ())?; 738 /// # Ok(()) 739 /// # } 740 /// ``` 741 /// 742 /// Finally if you want to get really fancy you can also implement 743 /// imports that read/write wasm module's memory 744 /// 745 /// ``` 746 /// use std::str; 747 /// 748 /// # use wasmtime::*; 749 /// # fn main() -> anyhow::Result<()> { 750 /// # let mut store = Store::default(); 751 /// let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| { 752 /// let mem = match caller.get_export("memory") { 753 /// Some(Extern::Memory(mem)) => mem, 754 /// _ => anyhow::bail!("failed to find host memory"), 755 /// }; 756 /// let data = mem.data(&caller) 757 /// .get(ptr as u32 as usize..) 758 /// .and_then(|arr| arr.get(..len as u32 as usize)); 759 /// let string = match data { 760 /// Some(data) => match str::from_utf8(data) { 761 /// Ok(s) => s, 762 /// Err(_) => anyhow::bail!("invalid utf-8"), 763 /// }, 764 /// None => anyhow::bail!("pointer/length out of bounds"), 765 /// }; 766 /// assert_eq!(string, "Hello, world!"); 767 /// println!("{}", string); 768 /// Ok(()) 769 /// }); 770 /// let module = Module::new( 771 /// store.engine(), 772 /// r#" 773 /// (module 774 /// (import "" "" (func $log_str (param i32 i32))) 775 /// (func (export "foo") 776 /// i32.const 4 ;; ptr 777 /// i32.const 13 ;; len 778 /// call $log_str) 779 /// (memory (export "memory") 1) 780 /// (data (i32.const 4) "Hello, world!")) 781 /// "#, 782 /// )?; 783 /// let instance = Instance::new(&mut store, &module, &[log_str.into()])?; 784 /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?; 785 /// foo.call(&mut store, ())?; 786 /// # Ok(()) 787 /// # } 788 /// ``` 789 pub fn wrap<T, Params, Results>( 790 mut store: impl AsContextMut<Data = T>, 791 func: impl IntoFunc<T, Params, Results>, 792 ) -> Func 793 where 794 T: 'static, 795 { 796 let store = store.as_context_mut().0; 797 // part of this unsafety is about matching the `T` to a `Store<T>`, 798 // which is done through the `AsContextMut` bound above. 799 unsafe { 800 let host = HostFunc::wrap(store.engine(), func); 801 host.into_func(store) 802 } 803 } 804 805 #[cfg(feature = "async")] 806 fn wrap_inner<F, T, Params, Results>(mut store: impl AsContextMut<Data = T>, func: F) -> Func 807 where 808 F: Fn(Caller<'_, T>, Params) -> Results + Send + Sync + 'static, 809 Params: WasmTyList, 810 Results: WasmRet, 811 T: 'static, 812 { 813 let store = store.as_context_mut().0; 814 // part of this unsafety is about matching the `T` to a `Store<T>`, 815 // which is done through the `AsContextMut` bound above. 816 unsafe { 817 let host = HostFunc::wrap_inner(store.engine(), func); 818 host.into_func(store) 819 } 820 } 821 822 /// Same as [`Func::wrap`], except the closure asynchronously produces the 823 /// result and the arguments are passed within a tuple. For more information 824 /// see the [`Func`] documentation. 825 /// 826 /// # Panics 827 /// 828 /// This function will panic if called with a non-asynchronous store. 829 #[cfg(feature = "async")] 830 pub fn wrap_async<T, F, P, R>(store: impl AsContextMut<Data = T>, func: F) -> Func 831 where 832 F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a> 833 + Send 834 + Sync 835 + 'static, 836 P: WasmTyList, 837 R: WasmRet, 838 T: 'static, 839 { 840 assert!( 841 store.as_context().async_support(), 842 concat!("cannot use `wrap_async` without enabling async support on the config") 843 ); 844 Func::wrap_inner(store, move |Caller { store, caller }, args| { 845 match store.block_on(|store| func(Caller { store, caller }, args).into()) { 846 Ok(ret) => ret.into_fallible(), 847 Err(e) => R::fallible_from_error(e), 848 } 849 }) 850 } 851 852 /// Returns the underlying wasm type that this `Func` has. 853 /// 854 /// # Panics 855 /// 856 /// Panics if `store` does not own this function. 857 pub fn ty(&self, store: impl AsContext) -> FuncType { 858 self.load_ty(&store.as_context().0) 859 } 860 861 /// Forcibly loads the type of this function from the `Engine`. 862 /// 863 /// Note that this is a somewhat expensive method since it requires taking a 864 /// lock as well as cloning a type. 865 pub(crate) fn load_ty(&self, store: &StoreOpaque) -> FuncType { 866 FuncType::from_shared_type_index(store.engine(), self.type_index(store)) 867 } 868 869 /// Does this function match the given type? 870 /// 871 /// That is, is this function's type a subtype of the given type? 872 /// 873 /// # Panics 874 /// 875 /// Panics if this function is not associated with the given store or if the 876 /// function type is not associated with the store's engine. 877 pub fn matches_ty(&self, store: impl AsContext, func_ty: &FuncType) -> bool { 878 self._matches_ty(store.as_context().0, func_ty) 879 } 880 881 pub(crate) fn _matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> bool { 882 let actual_ty = self.load_ty(store); 883 actual_ty.matches(func_ty) 884 } 885 886 pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> Result<()> { 887 if !self.comes_from_same_store(store) { 888 bail!("function used with wrong store"); 889 } 890 if self._matches_ty(store, func_ty) { 891 Ok(()) 892 } else { 893 let actual_ty = self.load_ty(store); 894 bail!("type mismatch: expected {func_ty}, found {actual_ty}") 895 } 896 } 897 898 pub(crate) fn type_index(&self, data: &StoreOpaque) -> VMSharedTypeIndex { 899 unsafe { self.vm_func_ref(data).as_ref().type_index } 900 } 901 902 /// Invokes this function with the `params` given and writes returned values 903 /// to `results`. 904 /// 905 /// The `params` here must match the type signature of this `Func`, or an 906 /// error will occur. Additionally `results` must have the same 907 /// length as the number of results for this function. Calling this function 908 /// will synchronously execute the WebAssembly function referenced to get 909 /// the results. 910 /// 911 /// This function will return `Ok(())` if execution completed without a trap 912 /// or error of any kind. In this situation the results will be written to 913 /// the provided `results` array. 914 /// 915 /// # Errors 916 /// 917 /// Any error which occurs throughout the execution of the function will be 918 /// returned as `Err(e)`. The [`Error`](anyhow::Error) type can be inspected 919 /// for the precise error cause such as: 920 /// 921 /// * [`Trap`] - indicates that a wasm trap happened and execution was 922 /// halted. 923 /// * [`WasmBacktrace`] - optionally included on errors for backtrace 924 /// information of the trap/error. 925 /// * Other string-based errors to indicate issues such as type errors with 926 /// `params`. 927 /// * Any host-originating error originally returned from a function defined 928 /// via [`Func::new`], for example. 929 /// 930 /// Errors typically indicate that execution of WebAssembly was halted 931 /// mid-way and did not complete after the error condition happened. 932 /// 933 /// [`Trap`]: crate::Trap 934 /// 935 /// # Panics 936 /// 937 /// This function will panic if called on a function belonging to an async 938 /// store. Asynchronous stores must always use `call_async`. Also panics if 939 /// `store` does not own this function. 940 /// 941 /// [`WasmBacktrace`]: crate::WasmBacktrace 942 pub fn call( 943 &self, 944 mut store: impl AsContextMut, 945 params: &[Val], 946 results: &mut [Val], 947 ) -> Result<()> { 948 assert!( 949 !store.as_context().async_support(), 950 "must use `call_async` when async support is enabled on the config", 951 ); 952 let mut store = store.as_context_mut(); 953 954 self.call_impl_check_args(&mut store, params, results)?; 955 956 unsafe { self.call_impl_do_call(&mut store, params, results) } 957 } 958 959 /// Invokes this function in an "unchecked" fashion, reading parameters and 960 /// writing results to `params_and_returns`. 961 /// 962 /// This function is the same as [`Func::call`] except that the arguments 963 /// and results both use a different representation. If possible it's 964 /// recommended to use [`Func::call`] if safety isn't necessary or to use 965 /// [`Func::typed`] in conjunction with [`TypedFunc::call`] since that's 966 /// both safer and faster than this method of invoking a function. 967 /// 968 /// Note that if this function takes `externref` arguments then it will 969 /// **not** automatically GC unlike the [`Func::call`] and 970 /// [`TypedFunc::call`] functions. This means that if this function is 971 /// invoked many times with new `ExternRef` values and no other GC happens 972 /// via any other means then no values will get collected. 973 /// 974 /// # Errors 975 /// 976 /// For more information about errors see the [`Func::call`] documentation. 977 /// 978 /// # Unsafety 979 /// 980 /// This function is unsafe because the `params_and_returns` argument is not 981 /// validated at all. It must uphold invariants such as: 982 /// 983 /// * It's a valid pointer to an array 984 /// * It has enough space to store all parameters 985 /// * It has enough space to store all results (not at the same time as 986 /// parameters) 987 /// * Parameters are initially written to the array and have the correct 988 /// types and such. 989 /// * Reference types like `externref` and `funcref` are valid at the 990 /// time of this call and for the `store` specified. 991 /// 992 /// These invariants are all upheld for you with [`Func::call`] and 993 /// [`TypedFunc::call`]. 994 pub unsafe fn call_unchecked( 995 &self, 996 mut store: impl AsContextMut, 997 params_and_returns: *mut [ValRaw], 998 ) -> Result<()> { 999 let mut store = store.as_context_mut(); 1000 let func_ref = self.vm_func_ref(store.0); 1001 let params_and_returns = NonNull::new(params_and_returns).unwrap_or(NonNull::from(&mut [])); 1002 Self::call_unchecked_raw(&mut store, func_ref, params_and_returns) 1003 } 1004 1005 pub(crate) unsafe fn call_unchecked_raw<T>( 1006 store: &mut StoreContextMut<'_, T>, 1007 func_ref: NonNull<VMFuncRef>, 1008 params_and_returns: NonNull<[ValRaw]>, 1009 ) -> Result<()> { 1010 invoke_wasm_and_catch_traps(store, |caller, vm| { 1011 VMFuncRef::array_call(func_ref, vm, caller, params_and_returns) 1012 }) 1013 } 1014 1015 /// Converts the raw representation of a `funcref` into an `Option<Func>` 1016 /// 1017 /// This is intended to be used in conjunction with [`Func::new_unchecked`], 1018 /// [`Func::call_unchecked`], and [`ValRaw`] with its `funcref` field. 1019 /// 1020 /// # Unsafety 1021 /// 1022 /// This function is not safe because `raw` is not validated at all. The 1023 /// caller must guarantee that `raw` is owned by the `store` provided and is 1024 /// valid within the `store`. 1025 pub unsafe fn from_raw(mut store: impl AsContextMut, raw: *mut c_void) -> Option<Func> { 1026 Self::_from_raw(store.as_context_mut().0, raw) 1027 } 1028 1029 pub(crate) unsafe fn _from_raw(store: &mut StoreOpaque, raw: *mut c_void) -> Option<Func> { 1030 Some(Func::from_vm_func_ref( 1031 store.id(), 1032 NonNull::new(raw.cast())?, 1033 )) 1034 } 1035 1036 /// Extracts the raw value of this `Func`, which is owned by `store`. 1037 /// 1038 /// This function returns a value that's suitable for writing into the 1039 /// `funcref` field of the [`ValRaw`] structure. 1040 /// 1041 /// # Unsafety 1042 /// 1043 /// The returned value is only valid for as long as the store is alive and 1044 /// this function is properly rooted within it. Additionally this function 1045 /// should not be liberally used since it's a very low-level knob. 1046 pub unsafe fn to_raw(&self, mut store: impl AsContextMut) -> *mut c_void { 1047 self.vm_func_ref(store.as_context_mut().0).as_ptr().cast() 1048 } 1049 1050 /// Invokes this function with the `params` given, returning the results 1051 /// asynchronously. 1052 /// 1053 /// This function is the same as [`Func::call`] except that it is 1054 /// asynchronous. This is only compatible with stores associated with an 1055 /// [asynchronous config](crate::Config::async_support). 1056 /// 1057 /// It's important to note that the execution of WebAssembly will happen 1058 /// synchronously in the `poll` method of the future returned from this 1059 /// function. Wasmtime does not manage its own thread pool or similar to 1060 /// execute WebAssembly in. Future `poll` methods are generally expected to 1061 /// resolve quickly, so it's recommended that you run or poll this future 1062 /// in a "blocking context". 1063 /// 1064 /// For more information see the documentation on [asynchronous 1065 /// configs](crate::Config::async_support). 1066 /// 1067 /// # Errors 1068 /// 1069 /// For more information on errors see the [`Func::call`] documentation. 1070 /// 1071 /// # Panics 1072 /// 1073 /// Panics if this is called on a function in a synchronous store. This 1074 /// only works with functions defined within an asynchronous store. Also 1075 /// panics if `store` does not own this function. 1076 #[cfg(feature = "async")] 1077 pub async fn call_async( 1078 &self, 1079 mut store: impl AsContextMut<Data: Send>, 1080 params: &[Val], 1081 results: &mut [Val], 1082 ) -> Result<()> { 1083 let mut store = store.as_context_mut(); 1084 assert!( 1085 store.0.async_support(), 1086 "cannot use `call_async` without enabling async support in the config", 1087 ); 1088 1089 self.call_impl_check_args(&mut store, params, results)?; 1090 1091 let result = store 1092 .on_fiber(|store| unsafe { self.call_impl_do_call(store, params, results) }) 1093 .await??; 1094 Ok(result) 1095 } 1096 1097 /// Perform dynamic checks that the arguments given to us match 1098 /// the signature of this function and are appropriate to pass to this 1099 /// function. 1100 /// 1101 /// This involves checking to make sure we have the right number and types 1102 /// of arguments as well as making sure everything is from the same `Store`. 1103 /// 1104 /// This must be called just before `call_impl_do_call`. 1105 fn call_impl_check_args<T>( 1106 &self, 1107 store: &mut StoreContextMut<'_, T>, 1108 params: &[Val], 1109 results: &mut [Val], 1110 ) -> Result<()> { 1111 let ty = self.load_ty(store.0); 1112 if ty.params().len() != params.len() { 1113 bail!( 1114 "expected {} arguments, got {}", 1115 ty.params().len(), 1116 params.len() 1117 ); 1118 } 1119 if ty.results().len() != results.len() { 1120 bail!( 1121 "expected {} results, got {}", 1122 ty.results().len(), 1123 results.len() 1124 ); 1125 } 1126 1127 for (ty, arg) in ty.params().zip(params) { 1128 arg.ensure_matches_ty(store.0, &ty) 1129 .context("argument type mismatch")?; 1130 if !arg.comes_from_same_store(store.0) { 1131 bail!("cross-`Store` values are not currently supported"); 1132 } 1133 } 1134 1135 Ok(()) 1136 } 1137 1138 /// Do the actual call into Wasm. 1139 /// 1140 /// # Safety 1141 /// 1142 /// You must have type checked the arguments by calling 1143 /// `call_impl_check_args` immediately before calling this function. It is 1144 /// only safe to call this function if that one did not return an error. 1145 unsafe fn call_impl_do_call<T>( 1146 &self, 1147 store: &mut StoreContextMut<'_, T>, 1148 params: &[Val], 1149 results: &mut [Val], 1150 ) -> Result<()> { 1151 // Store the argument values into `values_vec`. 1152 let ty = self.load_ty(store.0); 1153 let values_vec_size = params.len().max(ty.results().len()); 1154 let mut values_vec = store.0.take_wasm_val_raw_storage(); 1155 debug_assert!(values_vec.is_empty()); 1156 values_vec.resize_with(values_vec_size, || ValRaw::v128(0)); 1157 for (arg, slot) in params.iter().cloned().zip(&mut values_vec) { 1158 unsafe { 1159 *slot = arg.to_raw(&mut *store)?; 1160 } 1161 } 1162 1163 unsafe { 1164 self.call_unchecked( 1165 &mut *store, 1166 core::ptr::slice_from_raw_parts_mut(values_vec.as_mut_ptr(), values_vec_size), 1167 )?; 1168 } 1169 1170 for ((i, slot), val) in results.iter_mut().enumerate().zip(&values_vec) { 1171 let ty = ty.results().nth(i).unwrap(); 1172 *slot = unsafe { Val::from_raw(&mut *store, *val, ty) }; 1173 } 1174 values_vec.truncate(0); 1175 store.0.save_wasm_val_raw_storage(values_vec); 1176 Ok(()) 1177 } 1178 1179 #[inline] 1180 pub(crate) fn vm_func_ref(&self, store: &StoreOpaque) -> NonNull<VMFuncRef> { 1181 self.store.assert_belongs_to(store.id()); 1182 self.unsafe_func_ref.as_non_null() 1183 } 1184 1185 pub(crate) fn vmimport(&self, store: &StoreOpaque) -> VMFunctionImport { 1186 unsafe { 1187 let f = self.vm_func_ref(store); 1188 VMFunctionImport { 1189 // Note that this is a load-bearing `unwrap` here, but is 1190 // never expected to trip at runtime. The general problem is 1191 // that host functions do not have a `wasm_call` function so 1192 // the `VMFuncRef` type has an optional pointer there. This is 1193 // only able to be filled out when a function is "paired" with 1194 // a module where trampolines are present to fill out 1195 // `wasm_call` pointers. 1196 // 1197 // This pairing of modules doesn't happen explicitly but is 1198 // instead managed lazily throughout Wasmtime. Specifically the 1199 // way this works is one of: 1200 // 1201 // * When a host function is created the store's list of 1202 // modules are searched for a wasm trampoline. If not found 1203 // the `wasm_call` field is left blank. 1204 // 1205 // * When a module instantiation happens, which uses this 1206 // function, the module will be used to fill any outstanding 1207 // holes that it has trampolines for. 1208 // 1209 // This means that by the time we get to this point any 1210 // relevant holes should be filled out. Thus if this panic 1211 // actually triggers then it's indicative of a missing `fill` 1212 // call somewhere else. 1213 wasm_call: f.as_ref().wasm_call.unwrap(), 1214 array_call: f.as_ref().array_call, 1215 vmctx: f.as_ref().vmctx, 1216 } 1217 } 1218 } 1219 1220 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool { 1221 self.store == store.id() 1222 } 1223 1224 fn invoke_host_func_for_wasm<T>( 1225 mut caller: Caller<'_, T>, 1226 ty: &FuncType, 1227 values_vec: &mut [ValRaw], 1228 func: &dyn Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()>, 1229 ) -> Result<()> { 1230 // Translate the raw JIT arguments in `values_vec` into a `Val` which 1231 // we'll be passing as a slice. The storage for our slice-of-`Val` we'll 1232 // be taking from the `Store`. We preserve our slice back into the 1233 // `Store` after the hostcall, ideally amortizing the cost of allocating 1234 // the storage across wasm->host calls. 1235 // 1236 // Note that we have a dynamic guarantee that `values_vec` is the 1237 // appropriate length to both read all arguments from as well as store 1238 // all results into. 1239 let mut val_vec = caller.store.0.take_hostcall_val_storage(); 1240 debug_assert!(val_vec.is_empty()); 1241 let nparams = ty.params().len(); 1242 val_vec.reserve(nparams + ty.results().len()); 1243 for (i, ty) in ty.params().enumerate() { 1244 val_vec.push(unsafe { Val::from_raw(&mut caller.store, values_vec[i], ty) }) 1245 } 1246 1247 val_vec.extend((0..ty.results().len()).map(|_| Val::null_func_ref())); 1248 let (params, results) = val_vec.split_at_mut(nparams); 1249 func(caller.sub_caller(), params, results)?; 1250 1251 // Unlike our arguments we need to dynamically check that the return 1252 // values produced are correct. There could be a bug in `func` that 1253 // produces the wrong number, wrong types, or wrong stores of 1254 // values, and we need to catch that here. 1255 for (i, (ret, ty)) in results.iter().zip(ty.results()).enumerate() { 1256 ret.ensure_matches_ty(caller.store.0, &ty) 1257 .context("function attempted to return an incompatible value")?; 1258 unsafe { 1259 values_vec[i] = ret.to_raw(&mut caller.store)?; 1260 } 1261 } 1262 1263 // Restore our `val_vec` back into the store so it's usable for the next 1264 // hostcall to reuse our own storage. 1265 val_vec.truncate(0); 1266 caller.store.0.save_hostcall_val_storage(val_vec); 1267 Ok(()) 1268 } 1269 1270 /// Attempts to extract a typed object from this `Func` through which the 1271 /// function can be called. 1272 /// 1273 /// This function serves as an alternative to [`Func::call`] and 1274 /// [`Func::call_async`]. This method performs a static type check (using 1275 /// the `Params` and `Results` type parameters on the underlying wasm 1276 /// function. If the type check passes then a `TypedFunc` object is returned, 1277 /// otherwise an error is returned describing the typecheck failure. 1278 /// 1279 /// The purpose of this relative to [`Func::call`] is that it's much more 1280 /// efficient when used to invoke WebAssembly functions. With the types 1281 /// statically known far less setup/teardown is required when invoking 1282 /// WebAssembly. If speed is desired then this function is recommended to be 1283 /// used instead of [`Func::call`] (which is more general, hence its 1284 /// slowdown). 1285 /// 1286 /// The `Params` type parameter is used to describe the parameters of the 1287 /// WebAssembly function. This can either be a single type (like `i32`), or 1288 /// a tuple of types representing the list of parameters (like `(i32, f32, 1289 /// f64)`). Additionally you can use `()` to represent that the function has 1290 /// no parameters. 1291 /// 1292 /// The `Results` type parameter is used to describe the results of the 1293 /// function. This behaves the same way as `Params`, but just for the 1294 /// results of the function. 1295 /// 1296 /// # Translating Between WebAssembly and Rust Types 1297 /// 1298 /// Translation between Rust types and WebAssembly types looks like: 1299 /// 1300 /// | WebAssembly | Rust | 1301 /// |-------------------------------------------|---------------------------------------| 1302 /// | `i32` | `i32` or `u32` | 1303 /// | `i64` | `i64` or `u64` | 1304 /// | `f32` | `f32` | 1305 /// | `f64` | `f64` | 1306 /// | `externref` aka `(ref null extern)` | `Option<Rooted<ExternRef>>` | 1307 /// | `(ref extern)` | `Rooted<ExternRef>` | 1308 /// | `nullexternref` aka `(ref null noextern)` | `Option<NoExtern>` | 1309 /// | `(ref noextern)` | `NoExtern` | 1310 /// | `anyref` aka `(ref null any)` | `Option<Rooted<AnyRef>>` | 1311 /// | `(ref any)` | `Rooted<AnyRef>` | 1312 /// | `eqref` aka `(ref null eq)` | `Option<Rooted<EqRef>>` | 1313 /// | `(ref eq)` | `Rooted<EqRef>` | 1314 /// | `i31ref` aka `(ref null i31)` | `Option<I31>` | 1315 /// | `(ref i31)` | `I31` | 1316 /// | `structref` aka `(ref null struct)` | `Option<Rooted<StructRef>>` | 1317 /// | `(ref struct)` | `Rooted<StructRef>` | 1318 /// | `arrayref` aka `(ref null array)` | `Option<Rooted<ArrayRef>>` | 1319 /// | `(ref array)` | `Rooted<ArrayRef>` | 1320 /// | `nullref` aka `(ref null none)` | `Option<NoneRef>` | 1321 /// | `(ref none)` | `NoneRef` | 1322 /// | `funcref` aka `(ref null func)` | `Option<Func>` | 1323 /// | `(ref func)` | `Func` | 1324 /// | `(ref null <func type index>)` | `Option<Func>` | 1325 /// | `(ref <func type index>)` | `Func` | 1326 /// | `nullfuncref` aka `(ref null nofunc)` | `Option<NoFunc>` | 1327 /// | `(ref nofunc)` | `NoFunc` | 1328 /// | `v128` | `V128` on `x86-64` and `aarch64` only | 1329 /// 1330 /// (Note that this mapping is the same as that of [`Func::wrap`], and that 1331 /// anywhere a `Rooted<T>` appears, a `ManuallyRooted<T>` may also appear). 1332 /// 1333 /// Note that once the [`TypedFunc`] return value is acquired you'll use either 1334 /// [`TypedFunc::call`] or [`TypedFunc::call_async`] as necessary to actually invoke 1335 /// the function. This method does not invoke any WebAssembly code, it 1336 /// simply performs a typecheck before returning the [`TypedFunc`] value. 1337 /// 1338 /// This method also has a convenience wrapper as 1339 /// [`Instance::get_typed_func`](crate::Instance::get_typed_func) to 1340 /// directly get a typed function value from an 1341 /// [`Instance`](crate::Instance). 1342 /// 1343 /// ## Subtyping 1344 /// 1345 /// For result types, you can always use a supertype of the WebAssembly 1346 /// function's actual declared result type. For example, if the WebAssembly 1347 /// function was declared with type `(func (result nullfuncref))` you could 1348 /// successfully call `f.typed::<(), Option<Func>>()` because `Option<Func>` 1349 /// corresponds to `funcref`, which is a supertype of `nullfuncref`. 1350 /// 1351 /// For parameter types, you can always use a subtype of the WebAssembly 1352 /// function's actual declared parameter type. For example, if the 1353 /// WebAssembly function was declared with type `(func (param (ref null 1354 /// func)))` you could successfully call `f.typed::<Func, ()>()` because 1355 /// `Func` corresponds to `(ref func)`, which is a subtype of `(ref null 1356 /// func)`. 1357 /// 1358 /// Additionally, for functions which take a reference to a concrete type as 1359 /// a parameter, you can also use the concrete type's supertype. Consider a 1360 /// WebAssembly function that takes a reference to a function with a 1361 /// concrete type: `(ref null <func type index>)`. In this scenario, there 1362 /// is no static `wasmtime::Foo` Rust type that corresponds to that 1363 /// particular Wasm-defined concrete reference type because Wasm modules are 1364 /// loaded dynamically at runtime. You *could* do `f.typed::<Option<NoFunc>, 1365 /// ()>()`, and while that is correctly typed and valid, it is often overly 1366 /// restrictive. The only value you could call the resulting typed function 1367 /// with is the null function reference, but we'd like to call it with 1368 /// non-null function references that happen to be of the correct 1369 /// type. Therefore, `f.typed<Option<Func>, ()>()` is also allowed in this 1370 /// case, even though `Option<Func>` represents `(ref null func)` which is 1371 /// the supertype, not subtype, of `(ref null <func type index>)`. This does 1372 /// imply some minimal dynamic type checks in this case, but it is supported 1373 /// for better ergonomics, to enable passing non-null references into the 1374 /// function. 1375 /// 1376 /// # Errors 1377 /// 1378 /// This function will return an error if `Params` or `Results` does not 1379 /// match the native type of this WebAssembly function. 1380 /// 1381 /// # Panics 1382 /// 1383 /// This method will panic if `store` does not own this function. 1384 /// 1385 /// # Examples 1386 /// 1387 /// An end-to-end example of calling a function which takes no parameters 1388 /// and has no results: 1389 /// 1390 /// ``` 1391 /// # use wasmtime::*; 1392 /// # fn main() -> anyhow::Result<()> { 1393 /// let engine = Engine::default(); 1394 /// let mut store = Store::new(&engine, ()); 1395 /// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?; 1396 /// let instance = Instance::new(&mut store, &module, &[])?; 1397 /// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function"); 1398 /// 1399 /// // Note that this call can fail due to the typecheck not passing, but 1400 /// // in our case we statically know the module so we know this should 1401 /// // pass. 1402 /// let typed = foo.typed::<(), ()>(&store)?; 1403 /// 1404 /// // Note that this can fail if the wasm traps at runtime. 1405 /// typed.call(&mut store, ())?; 1406 /// # Ok(()) 1407 /// # } 1408 /// ``` 1409 /// 1410 /// You can also pass in multiple parameters and get a result back 1411 /// 1412 /// ``` 1413 /// # use wasmtime::*; 1414 /// # fn foo(add: &Func, mut store: Store<()>) -> anyhow::Result<()> { 1415 /// let typed = add.typed::<(i32, i64), f32>(&store)?; 1416 /// assert_eq!(typed.call(&mut store, (1, 2))?, 3.0); 1417 /// # Ok(()) 1418 /// # } 1419 /// ``` 1420 /// 1421 /// and similarly if a function has multiple results you can bind that too 1422 /// 1423 /// ``` 1424 /// # use wasmtime::*; 1425 /// # fn foo(add_with_overflow: &Func, mut store: Store<()>) -> anyhow::Result<()> { 1426 /// let typed = add_with_overflow.typed::<(u32, u32), (u32, i32)>(&store)?; 1427 /// let (result, overflow) = typed.call(&mut store, (u32::max_value(), 2))?; 1428 /// assert_eq!(result, 1); 1429 /// assert_eq!(overflow, 1); 1430 /// # Ok(()) 1431 /// # } 1432 /// ``` 1433 pub fn typed<Params, Results>( 1434 &self, 1435 store: impl AsContext, 1436 ) -> Result<TypedFunc<Params, Results>> 1437 where 1438 Params: WasmParams, 1439 Results: WasmResults, 1440 { 1441 // Type-check that the params/results are all valid 1442 let store = store.as_context().0; 1443 let ty = self.load_ty(store); 1444 Params::typecheck(store.engine(), ty.params(), TypeCheckPosition::Param) 1445 .context("type mismatch with parameters")?; 1446 Results::typecheck(store.engine(), ty.results(), TypeCheckPosition::Result) 1447 .context("type mismatch with results")?; 1448 1449 // and then we can construct the typed version of this function 1450 // (unsafely), which should be safe since we just did the type check above. 1451 unsafe { Ok(TypedFunc::_new_unchecked(store, *self)) } 1452 } 1453 1454 /// Get a stable hash key for this function. 1455 /// 1456 /// Even if the same underlying function is added to the `StoreData` 1457 /// multiple times and becomes multiple `wasmtime::Func`s, this hash key 1458 /// will be consistent across all of these functions. 1459 #[cfg_attr( 1460 not(test), 1461 expect(dead_code, reason = "Not used yet, but added for consistency") 1462 )] 1463 pub(crate) fn hash_key(&self, store: &mut StoreOpaque) -> impl core::hash::Hash + Eq + use<> { 1464 self.vm_func_ref(store).as_ptr().addr() 1465 } 1466 } 1467 1468 /// Prepares for entrance into WebAssembly. 1469 /// 1470 /// This function will set up context such that `closure` is allowed to call a 1471 /// raw trampoline or a raw WebAssembly function. This *must* be called to do 1472 /// things like catch traps and set up GC properly. 1473 /// 1474 /// The `closure` provided receives a default "caller" `VMContext` parameter it 1475 /// can pass to the called wasm function, if desired. 1476 pub(crate) fn invoke_wasm_and_catch_traps<T>( 1477 store: &mut StoreContextMut<'_, T>, 1478 closure: impl FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool, 1479 ) -> Result<()> { 1480 unsafe { 1481 // The `enter_wasm` call below will reset the store context's 1482 // `stack_chain` to a new `InitialStack`, pointing to the 1483 // stack-allocated `initial_stack_csi`. 1484 let mut initial_stack_csi = VMCommonStackInformation::running_default(); 1485 // Stores some state of the runtime just before entering Wasm. Will be 1486 // restored upon exiting Wasm. Note that the `CallThreadState` that is 1487 // created by the `catch_traps` call below will store a pointer to this 1488 // stack-allocated `previous_runtime_state`. 1489 let mut previous_runtime_state = 1490 EntryStoreContext::enter_wasm(store, &mut initial_stack_csi); 1491 1492 if let Err(trap) = store.0.call_hook(CallHook::CallingWasm) { 1493 // `previous_runtime_state` implicitly dropped here 1494 return Err(trap); 1495 } 1496 let result = crate::runtime::vm::catch_traps(store, &mut previous_runtime_state, closure); 1497 core::mem::drop(previous_runtime_state); 1498 store.0.call_hook(CallHook::ReturningFromWasm)?; 1499 result.map_err(|t| crate::trap::from_runtime_box(store.0, t)) 1500 } 1501 } 1502 1503 /// This type helps managing the state of the runtime when entering and exiting 1504 /// Wasm. To this end, it contains a subset of the data in `VMStoreContext`. 1505 /// Upon entering Wasm, it updates various runtime fields and their 1506 /// original values saved in this struct. Upon exiting Wasm, the previous values 1507 /// are restored. 1508 pub(crate) struct EntryStoreContext { 1509 /// If set, contains value of `stack_limit` field to restore in 1510 /// `VMStoreContext` when exiting Wasm. 1511 pub stack_limit: Option<usize>, 1512 /// Contains value of `last_wasm_exit_pc` field to restore in 1513 /// `VMStoreContext` when exiting Wasm. 1514 pub last_wasm_exit_pc: usize, 1515 /// Contains value of `last_wasm_exit_fp` field to restore in 1516 /// `VMStoreContext` when exiting Wasm. 1517 pub last_wasm_exit_fp: usize, 1518 /// Contains value of `last_wasm_entry_fp` field to restore in 1519 /// `VMStoreContext` when exiting Wasm. 1520 pub last_wasm_entry_fp: usize, 1521 /// Contains value of `stack_chain` field to restore in 1522 /// `VMStoreContext` when exiting Wasm. 1523 pub stack_chain: VMStackChain, 1524 1525 /// We need a pointer to the runtime limits, so we can update them from 1526 /// `drop`/`exit_wasm`. 1527 vm_store_context: *const VMStoreContext, 1528 } 1529 1530 impl EntryStoreContext { 1531 /// This function is called to update and save state when 1532 /// WebAssembly is entered within the `Store`. 1533 /// 1534 /// This updates various fields such as: 1535 /// 1536 /// * The stack limit. This is what ensures that we limit the stack space 1537 /// allocated by WebAssembly code and it's relative to the initial stack 1538 /// pointer that called into wasm. 1539 /// 1540 /// It also saves the different last_wasm_* values in the `VMStoreContext`. 1541 pub fn enter_wasm<T>( 1542 store: &mut StoreContextMut<'_, T>, 1543 initial_stack_information: *mut VMCommonStackInformation, 1544 ) -> Self { 1545 let stack_limit; 1546 1547 // If this is a recursive call, e.g. our stack limit is already set, then 1548 // we may be able to skip this function. 1549 // 1550 // For synchronous stores there's nothing else to do because all wasm calls 1551 // happen synchronously and on the same stack. This means that the previous 1552 // stack limit will suffice for the next recursive call. 1553 // 1554 // For asynchronous stores then each call happens on a separate native 1555 // stack. This means that the previous stack limit is no longer relevant 1556 // because we're on a separate stack. 1557 if unsafe { *store.0.vm_store_context().stack_limit.get() } != usize::MAX 1558 && !store.0.async_support() 1559 { 1560 stack_limit = None; 1561 } 1562 // Ignore this stack pointer business on miri since we can't execute wasm 1563 // anyway and the concept of a stack pointer on miri is a bit nebulous 1564 // regardless. 1565 else if cfg!(miri) { 1566 stack_limit = None; 1567 } else { 1568 // When Cranelift has support for the host then we might be running native 1569 // compiled code meaning we need to read the actual stack pointer. If 1570 // Cranelift can't be used though then we're guaranteed to be running pulley 1571 // in which case this stack pointer isn't actually used as Pulley has custom 1572 // mechanisms for stack overflow. 1573 #[cfg(has_host_compiler_backend)] 1574 let stack_pointer = crate::runtime::vm::get_stack_pointer(); 1575 #[cfg(not(has_host_compiler_backend))] 1576 let stack_pointer = { 1577 use wasmtime_environ::TripleExt; 1578 debug_assert!(store.engine().target().is_pulley()); 1579 usize::MAX 1580 }; 1581 1582 // Determine the stack pointer where, after which, any wasm code will 1583 // immediately trap. This is checked on the entry to all wasm functions. 1584 // 1585 // Note that this isn't 100% precise. We are requested to give wasm 1586 // `max_wasm_stack` bytes, but what we're actually doing is giving wasm 1587 // probably a little less than `max_wasm_stack` because we're 1588 // calculating the limit relative to this function's approximate stack 1589 // pointer. Wasm will be executed on a frame beneath this one (or next 1590 // to it). In any case it's expected to be at most a few hundred bytes 1591 // of slop one way or another. When wasm is typically given a MB or so 1592 // (a million bytes) the slop shouldn't matter too much. 1593 // 1594 // After we've got the stack limit then we store it into the `stack_limit` 1595 // variable. 1596 let wasm_stack_limit = stack_pointer 1597 .checked_sub(store.engine().config().max_wasm_stack) 1598 .unwrap(); 1599 let prev_stack = unsafe { 1600 mem::replace( 1601 &mut *store.0.vm_store_context().stack_limit.get(), 1602 wasm_stack_limit, 1603 ) 1604 }; 1605 stack_limit = Some(prev_stack); 1606 } 1607 1608 unsafe { 1609 let last_wasm_exit_pc = *store.0.vm_store_context().last_wasm_exit_pc.get(); 1610 let last_wasm_exit_fp = *store.0.vm_store_context().last_wasm_exit_fp.get(); 1611 let last_wasm_entry_fp = *store.0.vm_store_context().last_wasm_entry_fp.get(); 1612 1613 let stack_chain = (*store.0.vm_store_context().stack_chain.get()).clone(); 1614 1615 let new_stack_chain = VMStackChain::InitialStack(initial_stack_information); 1616 *store.0.vm_store_context().stack_chain.get() = new_stack_chain; 1617 1618 let vm_store_context = store.0.vm_store_context(); 1619 1620 Self { 1621 stack_limit, 1622 last_wasm_exit_pc, 1623 last_wasm_exit_fp, 1624 last_wasm_entry_fp, 1625 stack_chain, 1626 vm_store_context, 1627 } 1628 } 1629 } 1630 1631 /// This function restores the values stored in this struct. We invoke this 1632 /// function through this type's `Drop` implementation. This ensures that we 1633 /// even restore the values if we unwind the stack (e.g., because we are 1634 /// panicking out of a Wasm execution). 1635 #[inline] 1636 fn exit_wasm(&mut self) { 1637 unsafe { 1638 if let Some(limit) = self.stack_limit { 1639 *(&*self.vm_store_context).stack_limit.get() = limit; 1640 } 1641 1642 *(*self.vm_store_context).last_wasm_exit_fp.get() = self.last_wasm_exit_fp; 1643 *(*self.vm_store_context).last_wasm_exit_pc.get() = self.last_wasm_exit_pc; 1644 *(*self.vm_store_context).last_wasm_entry_fp.get() = self.last_wasm_entry_fp; 1645 *(*self.vm_store_context).stack_chain.get() = self.stack_chain.clone(); 1646 } 1647 } 1648 } 1649 1650 impl Drop for EntryStoreContext { 1651 #[inline] 1652 fn drop(&mut self) { 1653 self.exit_wasm(); 1654 } 1655 } 1656 1657 /// A trait implemented for types which can be returned from closures passed to 1658 /// [`Func::wrap`] and friends. 1659 /// 1660 /// This trait should not be implemented by user types. This trait may change at 1661 /// any time internally. The types which implement this trait, however, are 1662 /// stable over time. 1663 /// 1664 /// For more information see [`Func::wrap`] 1665 pub unsafe trait WasmRet { 1666 // Same as `WasmTy::compatible_with_store`. 1667 #[doc(hidden)] 1668 fn compatible_with_store(&self, store: &StoreOpaque) -> bool; 1669 1670 /// Stores this return value into the `ptr` specified using the rooted 1671 /// `store`. 1672 /// 1673 /// Traps are communicated through the `Result<_>` return value. 1674 /// 1675 /// # Unsafety 1676 /// 1677 /// This method is unsafe as `ptr` must have the correct length to store 1678 /// this result. This property is only checked in debug mode, not in release 1679 /// mode. 1680 #[doc(hidden)] 1681 unsafe fn store( 1682 self, 1683 store: &mut AutoAssertNoGc<'_>, 1684 ptr: &mut [MaybeUninit<ValRaw>], 1685 ) -> Result<()>; 1686 1687 #[doc(hidden)] 1688 fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType; 1689 #[doc(hidden)] 1690 fn may_gc() -> bool; 1691 1692 // Utilities used to convert an instance of this type to a `Result` 1693 // explicitly, used when wrapping async functions which always bottom-out 1694 // in a function that returns a trap because futures can be cancelled. 1695 #[doc(hidden)] 1696 type Fallible: WasmRet; 1697 #[doc(hidden)] 1698 fn into_fallible(self) -> Self::Fallible; 1699 #[doc(hidden)] 1700 fn fallible_from_error(error: Error) -> Self::Fallible; 1701 } 1702 1703 unsafe impl<T> WasmRet for T 1704 where 1705 T: WasmTy, 1706 { 1707 type Fallible = Result<T>; 1708 1709 fn compatible_with_store(&self, store: &StoreOpaque) -> bool { 1710 <Self as WasmTy>::compatible_with_store(self, store) 1711 } 1712 1713 unsafe fn store( 1714 self, 1715 store: &mut AutoAssertNoGc<'_>, 1716 ptr: &mut [MaybeUninit<ValRaw>], 1717 ) -> Result<()> { 1718 debug_assert!(ptr.len() > 0); 1719 <Self as WasmTy>::store(self, store, ptr.get_unchecked_mut(0)) 1720 } 1721 1722 fn may_gc() -> bool { 1723 T::may_gc() 1724 } 1725 1726 fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType { 1727 FuncType::new(engine, params, Some(<Self as WasmTy>::valtype())) 1728 } 1729 1730 fn into_fallible(self) -> Result<T> { 1731 Ok(self) 1732 } 1733 1734 fn fallible_from_error(error: Error) -> Result<T> { 1735 Err(error) 1736 } 1737 } 1738 1739 unsafe impl<T> WasmRet for Result<T> 1740 where 1741 T: WasmRet, 1742 { 1743 type Fallible = Self; 1744 1745 fn compatible_with_store(&self, store: &StoreOpaque) -> bool { 1746 match self { 1747 Ok(x) => <T as WasmRet>::compatible_with_store(x, store), 1748 Err(_) => true, 1749 } 1750 } 1751 1752 unsafe fn store( 1753 self, 1754 store: &mut AutoAssertNoGc<'_>, 1755 ptr: &mut [MaybeUninit<ValRaw>], 1756 ) -> Result<()> { 1757 self.and_then(|val| val.store(store, ptr)) 1758 } 1759 1760 fn may_gc() -> bool { 1761 T::may_gc() 1762 } 1763 1764 fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType { 1765 T::func_type(engine, params) 1766 } 1767 1768 fn into_fallible(self) -> Result<T> { 1769 self 1770 } 1771 1772 fn fallible_from_error(error: Error) -> Result<T> { 1773 Err(error) 1774 } 1775 } 1776 1777 macro_rules! impl_wasm_host_results { 1778 ($n:tt $($t:ident)*) => ( 1779 #[allow(non_snake_case, reason = "macro-generated code")] 1780 unsafe impl<$($t),*> WasmRet for ($($t,)*) 1781 where 1782 $($t: WasmTy,)* 1783 { 1784 type Fallible = Result<Self>; 1785 1786 #[inline] 1787 fn compatible_with_store(&self, _store: &StoreOpaque) -> bool { 1788 let ($($t,)*) = self; 1789 $( $t.compatible_with_store(_store) && )* true 1790 } 1791 1792 #[inline] 1793 unsafe fn store( 1794 self, 1795 _store: &mut AutoAssertNoGc<'_>, 1796 _ptr: &mut [MaybeUninit<ValRaw>], 1797 ) -> Result<()> { 1798 let ($($t,)*) = self; 1799 let mut _cur = 0; 1800 $( 1801 debug_assert!(_cur < _ptr.len()); 1802 let val = _ptr.get_unchecked_mut(_cur); 1803 _cur += 1; 1804 WasmTy::store($t, _store, val)?; 1805 )* 1806 Ok(()) 1807 } 1808 1809 #[doc(hidden)] 1810 fn may_gc() -> bool { 1811 $( $t::may_gc() || )* false 1812 } 1813 1814 fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType { 1815 FuncType::new( 1816 engine, 1817 params, 1818 IntoIterator::into_iter([$($t::valtype(),)*]), 1819 ) 1820 } 1821 1822 #[inline] 1823 fn into_fallible(self) -> Result<Self> { 1824 Ok(self) 1825 } 1826 1827 #[inline] 1828 fn fallible_from_error(error: Error) -> Result<Self> { 1829 Err(error) 1830 } 1831 } 1832 ) 1833 } 1834 1835 for_each_function_signature!(impl_wasm_host_results); 1836 1837 /// Internal trait implemented for all arguments that can be passed to 1838 /// [`Func::wrap`] and [`Linker::func_wrap`](crate::Linker::func_wrap). 1839 /// 1840 /// This trait should not be implemented by external users, it's only intended 1841 /// as an implementation detail of this crate. 1842 pub trait IntoFunc<T, Params, Results>: Send + Sync + 'static { 1843 /// Convert this function into a `VM{Array,Native}CallHostFuncContext` and 1844 /// internal `VMFuncRef`. 1845 #[doc(hidden)] 1846 fn into_func(self, engine: &Engine) -> HostContext; 1847 } 1848 1849 macro_rules! impl_into_func { 1850 ($num:tt $arg:ident) => { 1851 // Implement for functions without a leading `&Caller` parameter, 1852 // delegating to the implementation below which does have the leading 1853 // `Caller` parameter. 1854 #[expect(non_snake_case, reason = "macro-generated code")] 1855 impl<T, F, $arg, R> IntoFunc<T, $arg, R> for F 1856 where 1857 F: Fn($arg) -> R + Send + Sync + 'static, 1858 $arg: WasmTy, 1859 R: WasmRet, 1860 T: 'static, 1861 { 1862 fn into_func(self, engine: &Engine) -> HostContext { 1863 let f = move |_: Caller<'_, T>, $arg: $arg| { 1864 self($arg) 1865 }; 1866 1867 f.into_func(engine) 1868 } 1869 } 1870 1871 #[expect(non_snake_case, reason = "macro-generated code")] 1872 impl<T, F, $arg, R> IntoFunc<T, (Caller<'_, T>, $arg), R> for F 1873 where 1874 F: Fn(Caller<'_, T>, $arg) -> R + Send + Sync + 'static, 1875 $arg: WasmTy, 1876 R: WasmRet, 1877 T: 'static, 1878 { 1879 fn into_func(self, engine: &Engine) -> HostContext { 1880 HostContext::from_closure(engine, move |caller: Caller<'_, T>, ($arg,)| { 1881 self(caller, $arg) 1882 }) 1883 } 1884 } 1885 }; 1886 ($num:tt $($args:ident)*) => { 1887 // Implement for functions without a leading `&Caller` parameter, 1888 // delegating to the implementation below which does have the leading 1889 // `Caller` parameter. 1890 #[allow(non_snake_case, reason = "macro-generated code")] 1891 impl<T, F, $($args,)* R> IntoFunc<T, ($($args,)*), R> for F 1892 where 1893 F: Fn($($args),*) -> R + Send + Sync + 'static, 1894 $($args: WasmTy,)* 1895 R: WasmRet, 1896 T: 'static, 1897 { 1898 fn into_func(self, engine: &Engine) -> HostContext { 1899 let f = move |_: Caller<'_, T>, $($args:$args),*| { 1900 self($($args),*) 1901 }; 1902 1903 f.into_func(engine) 1904 } 1905 } 1906 1907 #[allow(non_snake_case, reason = "macro-generated code")] 1908 impl<T, F, $($args,)* R> IntoFunc<T, (Caller<'_, T>, $($args,)*), R> for F 1909 where 1910 F: Fn(Caller<'_, T>, $($args),*) -> R + Send + Sync + 'static, 1911 $($args: WasmTy,)* 1912 R: WasmRet, 1913 T: 'static, 1914 { 1915 fn into_func(self, engine: &Engine) -> HostContext { 1916 HostContext::from_closure(engine, move |caller: Caller<'_, T>, ( $( $args ),* )| { 1917 self(caller, $( $args ),* ) 1918 }) 1919 } 1920 } 1921 } 1922 } 1923 1924 for_each_function_signature!(impl_into_func); 1925 1926 /// Trait implemented for various tuples made up of types which implement 1927 /// [`WasmTy`] that can be passed to [`Func::wrap_inner`] and 1928 /// [`HostContext::from_closure`]. 1929 pub unsafe trait WasmTyList { 1930 /// Get the value type that each Type in the list represents. 1931 fn valtypes() -> impl Iterator<Item = ValType>; 1932 1933 // Load a version of `Self` from the `values` provided. 1934 // 1935 // # Safety 1936 // 1937 // This function is unsafe as it's up to the caller to ensure that `values` are 1938 // valid for this given type. 1939 #[doc(hidden)] 1940 unsafe fn load(store: &mut AutoAssertNoGc<'_>, values: &mut [MaybeUninit<ValRaw>]) -> Self; 1941 1942 #[doc(hidden)] 1943 fn may_gc() -> bool; 1944 } 1945 1946 macro_rules! impl_wasm_ty_list { 1947 ($num:tt $($args:ident)*) => ( 1948 #[allow(non_snake_case, reason = "macro-generated code")] 1949 unsafe impl<$($args),*> WasmTyList for ($($args,)*) 1950 where 1951 $($args: WasmTy,)* 1952 { 1953 fn valtypes() -> impl Iterator<Item = ValType> { 1954 IntoIterator::into_iter([$($args::valtype(),)*]) 1955 } 1956 1957 unsafe fn load(_store: &mut AutoAssertNoGc<'_>, _values: &mut [MaybeUninit<ValRaw>]) -> Self { 1958 let mut _cur = 0; 1959 ($({ 1960 debug_assert!(_cur < _values.len()); 1961 let ptr = _values.get_unchecked(_cur).assume_init_ref(); 1962 _cur += 1; 1963 $args::load(_store, ptr) 1964 },)*) 1965 } 1966 1967 fn may_gc() -> bool { 1968 $( $args::may_gc() || )* false 1969 } 1970 } 1971 ); 1972 } 1973 1974 for_each_function_signature!(impl_wasm_ty_list); 1975 1976 /// A structure representing the caller's context when creating a function 1977 /// via [`Func::wrap`]. 1978 /// 1979 /// This structure can be taken as the first parameter of a closure passed to 1980 /// [`Func::wrap`] or other constructors, and serves two purposes: 1981 /// 1982 /// * First consumers can use [`Caller<'_, T>`](crate::Caller) to get access to 1983 /// [`StoreContextMut<'_, T>`](crate::StoreContextMut) and/or get access to 1984 /// `T` itself. This means that the [`Caller`] type can serve as a proxy to 1985 /// the original [`Store`](crate::Store) itself and is used to satisfy 1986 /// [`AsContext`] and [`AsContextMut`] bounds. 1987 /// 1988 /// * Second a [`Caller`] can be used as the name implies, learning about the 1989 /// caller's context, namely it's exported memory and exported functions. This 1990 /// allows functions which take pointers as arguments to easily read the 1991 /// memory the pointers point into, or if a function is expected to call 1992 /// malloc in the wasm module to reserve space for the output you can do that. 1993 /// 1994 /// Host functions which want access to [`Store`](crate::Store)-level state are 1995 /// recommended to use this type. 1996 pub struct Caller<'a, T: 'static> { 1997 pub(crate) store: StoreContextMut<'a, T>, 1998 caller: Instance, 1999 } 2000 2001 impl<T> Caller<'_, T> { 2002 #[cfg(feature = "async")] 2003 pub(crate) fn new(store: StoreContextMut<'_, T>, caller: Instance) -> Caller<'_, T> { 2004 Caller { store, caller } 2005 } 2006 2007 #[cfg(feature = "async")] 2008 pub(crate) fn caller(&self) -> Instance { 2009 self.caller 2010 } 2011 2012 unsafe fn with<F, R>(caller: NonNull<VMContext>, f: F) -> R 2013 where 2014 // The closure must be valid for any `Caller` it is given; it doesn't 2015 // get to choose the `Caller`'s lifetime. 2016 F: for<'a> FnOnce(Caller<'a, T>) -> R, 2017 // And the return value must not borrow from the caller/store. 2018 R: 'static, 2019 { 2020 crate::runtime::vm::InstanceAndStore::from_vmctx(caller, |pair| { 2021 let (instance, store) = pair.unpack_mut(); 2022 let mut store = store.unchecked_context_mut::<T>(); 2023 let caller = Instance::from_wasmtime(instance.id(), store.0); 2024 2025 let (gc_lifo_scope, ret) = { 2026 let gc_lifo_scope = store.0.gc_roots().enter_lifo_scope(); 2027 2028 let ret = f(Caller { 2029 store: store.as_context_mut(), 2030 caller, 2031 }); 2032 2033 (gc_lifo_scope, ret) 2034 }; 2035 2036 // Safe to recreate a mutable borrow of the store because `ret` 2037 // cannot be borrowing from the store. 2038 store.0.exit_gc_lifo_scope(gc_lifo_scope); 2039 2040 ret 2041 }) 2042 } 2043 2044 fn sub_caller(&mut self) -> Caller<'_, T> { 2045 Caller { 2046 store: self.store.as_context_mut(), 2047 caller: self.caller, 2048 } 2049 } 2050 2051 /// Looks up an export from the caller's module by the `name` given. 2052 /// 2053 /// This is a low-level function that's typically used to implement passing 2054 /// of pointers or indices between core Wasm instances, where the callee 2055 /// needs to consult the caller's exports to perform memory management and 2056 /// resolve the references. 2057 /// 2058 /// For comparison, in components, the component model handles translating 2059 /// arguments from one component instance to another and managing memory, so 2060 /// that callees don't need to be aware of their callers, which promotes 2061 /// virtualizability of APIs. 2062 /// 2063 /// # Return 2064 /// 2065 /// If an export with the `name` provided was found, then it is returned as an 2066 /// `Extern`. There are a number of situations, however, where the export may not 2067 /// be available: 2068 /// 2069 /// * The caller instance may not have an export named `name` 2070 /// * There may not be a caller available, for example if `Func` was called 2071 /// directly from host code. 2072 /// 2073 /// It's recommended to take care when calling this API and gracefully 2074 /// handling a `None` return value. 2075 pub fn get_export(&mut self, name: &str) -> Option<Extern> { 2076 // All instances created have a `host_state` with a pointer pointing 2077 // back to themselves. If this caller doesn't have that `host_state` 2078 // then it probably means it was a host-created object like `Func::new` 2079 // which doesn't have any exports we want to return anyway. 2080 self.caller.get_export(&mut self.store, name) 2081 } 2082 2083 /// Looks up an exported [`Extern`] value by a [`ModuleExport`] value. 2084 /// 2085 /// This is similar to [`Self::get_export`] but uses a [`ModuleExport`] value to avoid 2086 /// string lookups where possible. [`ModuleExport`]s can be obtained by calling 2087 /// [`Module::get_export_index`] on the [`Module`] that an instance was instantiated with. 2088 /// 2089 /// This method will search the module for an export with a matching entity index and return 2090 /// the value, if found. 2091 /// 2092 /// Returns `None` if there was no export with a matching entity index. 2093 /// # Panics 2094 /// 2095 /// Panics if `store` does not own this instance. 2096 /// 2097 /// # Usage 2098 /// ``` 2099 /// use std::str; 2100 /// 2101 /// # use wasmtime::*; 2102 /// # fn main() -> anyhow::Result<()> { 2103 /// # let mut store = Store::default(); 2104 /// 2105 /// let module = Module::new( 2106 /// store.engine(), 2107 /// r#" 2108 /// (module 2109 /// (import "" "" (func $log_str (param i32 i32))) 2110 /// (func (export "foo") 2111 /// i32.const 4 ;; ptr 2112 /// i32.const 13 ;; len 2113 /// call $log_str) 2114 /// (memory (export "memory") 1) 2115 /// (data (i32.const 4) "Hello, world!")) 2116 /// "#, 2117 /// )?; 2118 /// 2119 /// let Some(module_export) = module.get_export_index("memory") else { 2120 /// anyhow::bail!("failed to find `memory` export in module"); 2121 /// }; 2122 /// 2123 /// let log_str = Func::wrap(&mut store, move |mut caller: Caller<'_, ()>, ptr: i32, len: i32| { 2124 /// let mem = match caller.get_module_export(&module_export) { 2125 /// Some(Extern::Memory(mem)) => mem, 2126 /// _ => anyhow::bail!("failed to find host memory"), 2127 /// }; 2128 /// let data = mem.data(&caller) 2129 /// .get(ptr as u32 as usize..) 2130 /// .and_then(|arr| arr.get(..len as u32 as usize)); 2131 /// let string = match data { 2132 /// Some(data) => match str::from_utf8(data) { 2133 /// Ok(s) => s, 2134 /// Err(_) => anyhow::bail!("invalid utf-8"), 2135 /// }, 2136 /// None => anyhow::bail!("pointer/length out of bounds"), 2137 /// }; 2138 /// assert_eq!(string, "Hello, world!"); 2139 /// println!("{}", string); 2140 /// Ok(()) 2141 /// }); 2142 /// let instance = Instance::new(&mut store, &module, &[log_str.into()])?; 2143 /// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?; 2144 /// foo.call(&mut store, ())?; 2145 /// # Ok(()) 2146 /// # } 2147 /// ``` 2148 pub fn get_module_export(&mut self, export: &ModuleExport) -> Option<Extern> { 2149 self.caller.get_module_export(&mut self.store, export) 2150 } 2151 2152 /// Access the underlying data owned by this `Store`. 2153 /// 2154 /// Same as [`Store::data`](crate::Store::data) 2155 pub fn data(&self) -> &T { 2156 self.store.data() 2157 } 2158 2159 /// Access the underlying data owned by this `Store`. 2160 /// 2161 /// Same as [`Store::data_mut`](crate::Store::data_mut) 2162 pub fn data_mut(&mut self) -> &mut T { 2163 self.store.data_mut() 2164 } 2165 2166 /// Returns the underlying [`Engine`] this store is connected to. 2167 pub fn engine(&self) -> &Engine { 2168 self.store.engine() 2169 } 2170 2171 /// Perform garbage collection. 2172 /// 2173 /// Same as [`Store::gc`](crate::Store::gc). 2174 #[cfg(feature = "gc")] 2175 pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) { 2176 self.store.gc(why); 2177 } 2178 2179 /// Perform garbage collection asynchronously. 2180 /// 2181 /// Same as [`Store::gc_async`](crate::Store::gc_async). 2182 #[cfg(all(feature = "async", feature = "gc"))] 2183 pub async fn gc_async(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> 2184 where 2185 T: Send + 'static, 2186 { 2187 self.store.gc_async(why).await 2188 } 2189 2190 /// Returns the remaining fuel in the store. 2191 /// 2192 /// For more information see [`Store::get_fuel`](crate::Store::get_fuel) 2193 pub fn get_fuel(&self) -> Result<u64> { 2194 self.store.get_fuel() 2195 } 2196 2197 /// Set the amount of fuel in this store to be consumed when executing wasm code. 2198 /// 2199 /// For more information see [`Store::set_fuel`](crate::Store::set_fuel) 2200 pub fn set_fuel(&mut self, fuel: u64) -> Result<()> { 2201 self.store.set_fuel(fuel) 2202 } 2203 2204 /// Configures this `Store` to yield while executing futures every N units of fuel. 2205 /// 2206 /// For more information see 2207 /// [`Store::fuel_async_yield_interval`](crate::Store::fuel_async_yield_interval) 2208 pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> { 2209 self.store.fuel_async_yield_interval(interval) 2210 } 2211 } 2212 2213 impl<T: 'static> AsContext for Caller<'_, T> { 2214 type Data = T; 2215 fn as_context(&self) -> StoreContext<'_, T> { 2216 self.store.as_context() 2217 } 2218 } 2219 2220 impl<T: 'static> AsContextMut for Caller<'_, T> { 2221 fn as_context_mut(&mut self) -> StoreContextMut<'_, T> { 2222 self.store.as_context_mut() 2223 } 2224 } 2225 2226 // State stored inside a `VMArrayCallHostFuncContext`. 2227 struct HostFuncState<F> { 2228 // The actual host function. 2229 func: F, 2230 2231 // NB: We have to keep our `VMSharedTypeIndex` registered in the engine for 2232 // as long as this function exists. 2233 _ty: RegisteredType, 2234 } 2235 2236 #[doc(hidden)] 2237 pub enum HostContext { 2238 Array(StoreBox<VMArrayCallHostFuncContext>), 2239 } 2240 2241 impl From<StoreBox<VMArrayCallHostFuncContext>> for HostContext { 2242 fn from(ctx: StoreBox<VMArrayCallHostFuncContext>) -> Self { 2243 HostContext::Array(ctx) 2244 } 2245 } 2246 2247 impl HostContext { 2248 fn from_closure<F, T, P, R>(engine: &Engine, func: F) -> Self 2249 where 2250 F: Fn(Caller<'_, T>, P) -> R + Send + Sync + 'static, 2251 P: WasmTyList, 2252 R: WasmRet, 2253 T: 'static, 2254 { 2255 let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes())); 2256 let type_index = ty.type_index(); 2257 2258 let array_call = Self::array_call_trampoline::<T, F, P, R>; 2259 2260 let ctx = unsafe { 2261 VMArrayCallHostFuncContext::new( 2262 array_call, 2263 type_index, 2264 Box::new(HostFuncState { 2265 func, 2266 _ty: ty.into_registered_type(), 2267 }), 2268 ) 2269 }; 2270 2271 ctx.into() 2272 } 2273 2274 unsafe extern "C" fn array_call_trampoline<T, F, P, R>( 2275 callee_vmctx: NonNull<VMOpaqueContext>, 2276 caller_vmctx: NonNull<VMContext>, 2277 args: NonNull<ValRaw>, 2278 args_len: usize, 2279 ) -> bool 2280 where 2281 F: Fn(Caller<'_, T>, P) -> R + 'static, 2282 P: WasmTyList, 2283 R: WasmRet, 2284 T: 'static, 2285 { 2286 // Note that this function is intentionally scoped into a 2287 // separate closure. Handling traps and panics will involve 2288 // longjmp-ing from this function which means we won't run 2289 // destructors. As a result anything requiring a destructor 2290 // should be part of this closure, and the long-jmp-ing 2291 // happens after the closure in handling the result. 2292 let run = move |mut caller: Caller<'_, T>| { 2293 let mut args = 2294 NonNull::slice_from_raw_parts(args.cast::<MaybeUninit<ValRaw>>(), args_len); 2295 let vmctx = VMArrayCallHostFuncContext::from_opaque(callee_vmctx); 2296 let state = vmctx.as_ref().host_state(); 2297 2298 // Double-check ourselves in debug mode, but we control 2299 // the `Any` here so an unsafe downcast should also 2300 // work. 2301 debug_assert!(state.is::<HostFuncState<F>>()); 2302 let state = &*(state as *const _ as *const HostFuncState<F>); 2303 let func = &state.func; 2304 2305 let ret = 'ret: { 2306 if let Err(trap) = caller.store.0.call_hook(CallHook::CallingHost) { 2307 break 'ret R::fallible_from_error(trap); 2308 } 2309 2310 let mut store = if P::may_gc() { 2311 AutoAssertNoGc::new(caller.store.0) 2312 } else { 2313 unsafe { AutoAssertNoGc::disabled(caller.store.0) } 2314 }; 2315 let params = P::load(&mut store, args.as_mut()); 2316 let _ = &mut store; 2317 drop(store); 2318 2319 let r = func(caller.sub_caller(), params); 2320 2321 if let Err(trap) = caller.store.0.call_hook(CallHook::ReturningFromHost) { 2322 break 'ret R::fallible_from_error(trap); 2323 } 2324 r.into_fallible() 2325 }; 2326 2327 if !ret.compatible_with_store(caller.store.0) { 2328 bail!("host function attempted to return cross-`Store` value to Wasm") 2329 } else { 2330 let mut store = if R::may_gc() { 2331 AutoAssertNoGc::new(caller.store.0) 2332 } else { 2333 unsafe { AutoAssertNoGc::disabled(caller.store.0) } 2334 }; 2335 let ret = ret.store(&mut store, args.as_mut())?; 2336 Ok(ret) 2337 } 2338 }; 2339 2340 // With nothing else on the stack move `run` into this 2341 // closure and then run it as part of `Caller::with`. 2342 crate::runtime::vm::catch_unwind_and_record_trap(move || Caller::with(caller_vmctx, run)) 2343 } 2344 } 2345 2346 /// Representation of a host-defined function. 2347 /// 2348 /// This is used for `Func::new` but also for `Linker`-defined functions. For 2349 /// `Func::new` this is stored within a `Store`, and for `Linker`-defined 2350 /// functions they wrap this up in `Arc` to enable shared ownership of this 2351 /// across many stores. 2352 /// 2353 /// Technically this structure needs a `<T>` type parameter to connect to the 2354 /// `Store<T>` itself, but that's an unsafe contract of using this for now 2355 /// rather than part of the struct type (to avoid `Func<T>` in the API). 2356 pub(crate) struct HostFunc { 2357 ctx: HostContext, 2358 2359 // Stored to unregister this function's signature with the engine when this 2360 // is dropped. 2361 engine: Engine, 2362 } 2363 2364 impl core::fmt::Debug for HostFunc { 2365 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 2366 f.debug_struct("HostFunc").finish_non_exhaustive() 2367 } 2368 } 2369 2370 impl HostFunc { 2371 /// Analog of [`Func::new`] 2372 /// 2373 /// # Panics 2374 /// 2375 /// Panics if the given function type is not associated with the given 2376 /// engine. 2377 pub fn new<T>( 2378 engine: &Engine, 2379 ty: FuncType, 2380 func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static, 2381 ) -> Self 2382 where 2383 T: 'static, 2384 { 2385 assert!(ty.comes_from_same_engine(engine)); 2386 let ty_clone = ty.clone(); 2387 unsafe { 2388 HostFunc::new_unchecked(engine, ty, move |caller, values| { 2389 Func::invoke_host_func_for_wasm(caller, &ty_clone, values, &func) 2390 }) 2391 } 2392 } 2393 2394 /// Analog of [`Func::new_unchecked`] 2395 /// 2396 /// # Panics 2397 /// 2398 /// Panics if the given function type is not associated with the given 2399 /// engine. 2400 pub unsafe fn new_unchecked<T>( 2401 engine: &Engine, 2402 ty: FuncType, 2403 func: impl Fn(Caller<'_, T>, &mut [ValRaw]) -> Result<()> + Send + Sync + 'static, 2404 ) -> Self 2405 where 2406 T: 'static, 2407 { 2408 assert!(ty.comes_from_same_engine(engine)); 2409 let func = move |caller_vmctx, values: &mut [ValRaw]| { 2410 Caller::<T>::with(caller_vmctx, |mut caller| { 2411 caller.store.0.call_hook(CallHook::CallingHost)?; 2412 let result = func(caller.sub_caller(), values)?; 2413 caller.store.0.call_hook(CallHook::ReturningFromHost)?; 2414 Ok(result) 2415 }) 2416 }; 2417 let ctx = crate::trampoline::create_array_call_function(&ty, func) 2418 .expect("failed to create function"); 2419 HostFunc::_new(engine, ctx.into()) 2420 } 2421 2422 /// Analog of [`Func::wrap_inner`] 2423 #[cfg(any(feature = "component-model", feature = "async"))] 2424 pub fn wrap_inner<F, T, Params, Results>(engine: &Engine, func: F) -> Self 2425 where 2426 F: Fn(Caller<'_, T>, Params) -> Results + Send + Sync + 'static, 2427 Params: WasmTyList, 2428 Results: WasmRet, 2429 T: 'static, 2430 { 2431 let ctx = HostContext::from_closure(engine, func); 2432 HostFunc::_new(engine, ctx) 2433 } 2434 2435 /// Analog of [`Func::wrap`] 2436 pub fn wrap<T, Params, Results>( 2437 engine: &Engine, 2438 func: impl IntoFunc<T, Params, Results>, 2439 ) -> Self 2440 where 2441 T: 'static, 2442 { 2443 let ctx = func.into_func(engine); 2444 HostFunc::_new(engine, ctx) 2445 } 2446 2447 /// Requires that this function's signature is already registered within 2448 /// `Engine`. This happens automatically during the above two constructors. 2449 fn _new(engine: &Engine, ctx: HostContext) -> Self { 2450 HostFunc { 2451 ctx, 2452 engine: engine.clone(), 2453 } 2454 } 2455 2456 /// Inserts this `HostFunc` into a `Store`, returning the `Func` pointing to 2457 /// it. 2458 /// 2459 /// # Unsafety 2460 /// 2461 /// Can only be inserted into stores with a matching `T` relative to when 2462 /// this `HostFunc` was first created. 2463 pub unsafe fn to_func(self: &Arc<Self>, store: &mut StoreOpaque) -> Func { 2464 self.validate_store(store); 2465 let (funcrefs, modules) = store.func_refs_and_modules(); 2466 let funcref = funcrefs.push_arc_host(self.clone(), modules); 2467 Func::from_vm_func_ref(store.id(), funcref) 2468 } 2469 2470 /// Inserts this `HostFunc` into a `Store`, returning the `Func` pointing to 2471 /// it. 2472 /// 2473 /// This function is similar to, but not equivalent, to `HostFunc::to_func`. 2474 /// Notably this function requires that the `Arc<Self>` pointer is otherwise 2475 /// rooted within the `StoreOpaque` via another means. When in doubt use 2476 /// `to_func` above as it's safer. 2477 /// 2478 /// # Unsafety 2479 /// 2480 /// Can only be inserted into stores with a matching `T` relative to when 2481 /// this `HostFunc` was first created. 2482 /// 2483 /// Additionally the `&Arc<Self>` is not cloned in this function. Instead a 2484 /// raw pointer to `Self` is stored within the `Store` for this function. 2485 /// The caller must arrange for the `Arc<Self>` to be "rooted" in the store 2486 /// provided via another means, probably by pushing to 2487 /// `StoreOpaque::rooted_host_funcs`. 2488 /// 2489 /// Similarly, the caller must arrange for `rooted_func_ref` to be rooted in 2490 /// the same store. 2491 pub unsafe fn to_func_store_rooted( 2492 self: &Arc<Self>, 2493 store: &mut StoreOpaque, 2494 rooted_func_ref: Option<NonNull<VMFuncRef>>, 2495 ) -> Func { 2496 self.validate_store(store); 2497 2498 match rooted_func_ref { 2499 Some(funcref) => { 2500 debug_assert!(funcref.as_ref().wasm_call.is_some()); 2501 Func::from_vm_func_ref(store.id(), funcref) 2502 } 2503 None => { 2504 debug_assert!(self.func_ref().wasm_call.is_some()); 2505 Func::from_vm_func_ref(store.id(), self.func_ref().into()) 2506 } 2507 } 2508 } 2509 2510 /// Same as [`HostFunc::to_func`], different ownership. 2511 unsafe fn into_func(self, store: &mut StoreOpaque) -> Func { 2512 self.validate_store(store); 2513 let (funcrefs, modules) = store.func_refs_and_modules(); 2514 let funcref = funcrefs.push_box_host(Box::new(self), modules); 2515 Func::from_vm_func_ref(store.id(), funcref) 2516 } 2517 2518 fn validate_store(&self, store: &mut StoreOpaque) { 2519 // This assert is required to ensure that we can indeed safely insert 2520 // `self` into the `store` provided, otherwise the type information we 2521 // have listed won't be correct. This is possible to hit with the public 2522 // API of Wasmtime, and should be documented in relevant functions. 2523 assert!( 2524 Engine::same(&self.engine, store.engine()), 2525 "cannot use a store with a different engine than a linker was created with", 2526 ); 2527 } 2528 2529 pub(crate) fn sig_index(&self) -> VMSharedTypeIndex { 2530 self.func_ref().type_index 2531 } 2532 2533 pub(crate) fn func_ref(&self) -> &VMFuncRef { 2534 match &self.ctx { 2535 HostContext::Array(ctx) => unsafe { ctx.get().as_ref().func_ref() }, 2536 } 2537 } 2538 2539 pub(crate) fn host_ctx(&self) -> &HostContext { 2540 &self.ctx 2541 } 2542 } 2543 2544 #[cfg(test)] 2545 mod tests { 2546 use super::*; 2547 use crate::{Module, Store}; 2548 2549 #[test] 2550 #[cfg_attr(miri, ignore)] 2551 fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> { 2552 let mut store = Store::<()>::default(); 2553 let module = Module::new( 2554 store.engine(), 2555 r#" 2556 (module 2557 (func (export "f") 2558 nop 2559 ) 2560 ) 2561 "#, 2562 )?; 2563 let instance = Instance::new(&mut store, &module, &[])?; 2564 2565 // Each time we `get_func`, we call `Func::from_wasmtime` which adds a 2566 // new entry to `StoreData`, so `f1` and `f2` will have different 2567 // indices into `StoreData`. 2568 let f1 = instance.get_func(&mut store, "f").unwrap(); 2569 let f2 = instance.get_func(&mut store, "f").unwrap(); 2570 2571 // But their hash keys are the same. 2572 assert!( 2573 f1.hash_key(&mut store.as_context_mut().0) 2574 == f2.hash_key(&mut store.as_context_mut().0) 2575 ); 2576 2577 // But the hash keys are different from different funcs. 2578 let instance2 = Instance::new(&mut store, &module, &[])?; 2579 let f3 = instance2.get_func(&mut store, "f").unwrap(); 2580 assert!( 2581 f1.hash_key(&mut store.as_context_mut().0) 2582 != f3.hash_key(&mut store.as_context_mut().0) 2583 ); 2584 2585 Ok(()) 2586 } 2587 } 2588