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