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