1 use crate::linker::{Definition, DefinitionType}; 2 use crate::prelude::*; 3 use crate::runtime::vm::{ 4 self, Imports, ModuleRuntimeInfo, VMFuncRef, VMFunctionImport, VMGlobalImport, VMMemoryImport, 5 VMTableImport, VMTagImport, 6 }; 7 use crate::store::{AllocateInstanceKind, InstanceId, StoreInstanceId, StoreOpaque}; 8 use crate::types::matching; 9 use crate::{ 10 AsContextMut, Engine, Export, Extern, Func, Global, Memory, Module, ModuleExport, SharedMemory, 11 StoreContext, StoreContextMut, Table, Tag, TypedFunc, 12 }; 13 use alloc::sync::Arc; 14 use core::ptr::NonNull; 15 use wasmparser::WasmFeatures; 16 use wasmtime_environ::{ 17 EntityIndex, EntityType, FuncIndex, GlobalIndex, MemoryIndex, PrimaryMap, TableIndex, TagIndex, 18 TypeTrace, 19 }; 20 21 /// An instantiated WebAssembly module. 22 /// 23 /// This type represents the instantiation of a [`Module`]. Once instantiated 24 /// you can access the [`exports`](Instance::exports) which are of type 25 /// [`Extern`] and provide the ability to call functions, set globals, read 26 /// memory, etc. When interacting with any wasm code you'll want to make an 27 /// [`Instance`] to call any code or execute anything. 28 /// 29 /// Instances are owned by a [`Store`](crate::Store) which is passed in at 30 /// creation time. It's recommended to create instances with 31 /// [`Linker::instantiate`](crate::Linker::instantiate) or similar 32 /// [`Linker`](crate::Linker) methods, but a more low-level constructor is also 33 /// available as [`Instance::new`]. 34 #[derive(Copy, Clone, Debug)] 35 #[repr(C)] 36 pub struct Instance { 37 id: StoreInstanceId, 38 } 39 40 // Double-check that the C representation in `instance.h` matches our in-Rust 41 // representation here in terms of size/alignment/etc. 42 const _: () = { 43 #[repr(C)] 44 struct C(u64, usize); 45 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Instance>()); 46 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Instance>()); 47 assert!(core::mem::offset_of!(Instance, id) == 0); 48 }; 49 50 impl Instance { 51 /// Creates a new [`Instance`] from the previously compiled [`Module`] and 52 /// list of `imports` specified. 53 /// 54 /// This method instantiates the `module` provided with the `imports`, 55 /// following the procedure in the [core specification][inst] to 56 /// instantiate. Instantiation can fail for a number of reasons (many 57 /// specified below), but if successful the `start` function will be 58 /// automatically run (if specified in the `module`) and then the 59 /// [`Instance`] will be returned. 60 /// 61 /// Per the WebAssembly spec, instantiation includes running the module's 62 /// start function, if it has one (not to be confused with the `_start` 63 /// function, which is not run). 64 /// 65 /// Note that this is a low-level function that just performs an 66 /// instantiation. See the [`Linker`](crate::Linker) struct for an API which 67 /// provides a convenient way to link imports and provides automatic Command 68 /// and Reactor behavior. 69 /// 70 /// ## Providing Imports 71 /// 72 /// The entries in the list of `imports` are intended to correspond 1:1 73 /// with the list of imports returned by [`Module::imports`]. Before 74 /// calling [`Instance::new`] you'll want to inspect the return value of 75 /// [`Module::imports`] and, for each import type, create an [`Extern`] 76 /// which corresponds to that type. These [`Extern`] values are all then 77 /// collected into a list and passed to this function. 78 /// 79 /// Note that this function is intentionally relatively low level. For an 80 /// easier time passing imports by doing name-based resolution it's 81 /// recommended to instead use the [`Linker`](crate::Linker) type. 82 /// 83 /// ## Errors 84 /// 85 /// This function can fail for a number of reasons, including, but not 86 /// limited to: 87 /// 88 /// * The number of `imports` provided doesn't match the number of imports 89 /// returned by the `module`'s [`Module::imports`] method. 90 /// * The type of any [`Extern`] doesn't match the corresponding 91 /// [`ExternType`] entry that it maps to. 92 /// * The `start` function in the instance, if present, traps. 93 /// * Module/instance resource limits are exceeded. 94 /// 95 /// When instantiation fails it's recommended to inspect the return value to 96 /// see why it failed, or bubble it upwards. If you'd like to specifically 97 /// check for trap errors, you can use `error.downcast::<Trap>()`. For more 98 /// about error handling see the [`Trap`] documentation. 99 /// 100 /// [`Trap`]: crate::Trap 101 /// 102 /// # Panics 103 /// 104 /// This function will panic if called with a store associated with a 105 /// [`asynchronous config`](crate::Config::async_support). This function 106 /// will also panic if any [`Extern`] supplied is not owned by `store`. 107 /// 108 /// [inst]: https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation 109 /// [`ExternType`]: crate::ExternType 110 pub fn new( 111 mut store: impl AsContextMut, 112 module: &Module, 113 imports: &[Extern], 114 ) -> Result<Instance> { 115 let mut store = store.as_context_mut(); 116 let imports = Instance::typecheck_externs(store.0, module, imports)?; 117 // Note that the unsafety here should be satisfied by the call to 118 // `typecheck_externs` above which satisfies the condition that all 119 // the imports are valid for this module. 120 unsafe { Instance::new_started(&mut store, module, imports.as_ref()) } 121 } 122 123 /// Same as [`Instance::new`], except for usage in [asynchronous stores]. 124 /// 125 /// For more details about this function see the documentation on 126 /// [`Instance::new`]. The only difference between these two methods is that 127 /// this one will asynchronously invoke the wasm start function in case it 128 /// calls any imported function which is an asynchronous host function (e.g. 129 /// created with [`Func::new_async`](crate::Func::new_async). 130 /// 131 /// # Panics 132 /// 133 /// This function will panic if called with a store associated with a 134 /// [`synchronous config`](crate::Config::new). This is only compatible with 135 /// stores associated with an [`asynchronous 136 /// config`](crate::Config::async_support). 137 /// 138 /// This function will also panic, like [`Instance::new`], if any [`Extern`] 139 /// specified does not belong to `store`. 140 /// 141 /// # Examples 142 /// 143 /// An example of using this function: 144 /// 145 /// ``` 146 /// use wasmtime::{Result, Store, Engine, Config, Module, Instance}; 147 /// 148 /// #[tokio::main] 149 /// async fn main() -> Result<()> { 150 /// let mut config = Config::new(); 151 /// config.async_support(true); 152 /// let engine = Engine::new(&config)?; 153 /// 154 /// // For this example, a module with no imports is being used hence 155 /// // the empty array to `Instance::new_async`. 156 /// let module = Module::new(&engine, "(module)")?; 157 /// let mut store = Store::new(&engine, ()); 158 /// let instance = Instance::new_async(&mut store, &module, &[]).await?; 159 /// 160 /// // ... use `instance` and exports and such ... 161 /// 162 /// Ok(()) 163 /// } 164 /// ``` 165 /// 166 /// Note, though, that the future returned from this function is only 167 /// `Send` if the store's own data is `Send` meaning that this does not 168 /// compile for example: 169 /// 170 /// ```compile_fail 171 /// use wasmtime::{Result, Store, Engine, Config, Module, Instance}; 172 /// use std::rc::Rc; 173 /// 174 /// #[tokio::main] 175 /// async fn main() -> Result<()> { 176 /// let mut config = Config::new(); 177 /// config.async_support(true); 178 /// let engine = Engine::new(&config)?; 179 /// 180 /// let module = Module::new(&engine, "(module)")?; 181 /// 182 /// // Note that `Rc<()>` is NOT `Send`, which is what many future 183 /// // runtimes require and below will cause a failure. 184 /// let mut store = Store::new(&engine, Rc::new(())); 185 /// 186 /// // Compile failure because `Store<Rc<()>>` is not `Send` 187 /// assert_send(Instance::new_async(&mut store, &module, &[])).await?; 188 /// 189 /// Ok(()) 190 /// } 191 /// 192 /// fn assert_send<T: Send>(t: T) -> T { t } 193 /// ``` 194 #[cfg(feature = "async")] 195 pub async fn new_async( 196 mut store: impl AsContextMut, 197 module: &Module, 198 imports: &[Extern], 199 ) -> Result<Instance> { 200 let mut store = store.as_context_mut(); 201 let imports = Instance::typecheck_externs(store.0, module, imports)?; 202 // See `new` for notes on this unsafety 203 unsafe { Instance::new_started_async(&mut store, module, imports.as_ref()).await } 204 } 205 206 fn typecheck_externs( 207 store: &mut StoreOpaque, 208 module: &Module, 209 imports: &[Extern], 210 ) -> Result<OwnedImports> { 211 for import in imports { 212 if !import.comes_from_same_store(store) { 213 bail!("cross-`Store` instantiation is not currently supported"); 214 } 215 } 216 217 typecheck(module, imports, |cx, ty, item| { 218 let item = DefinitionType::from(store, item); 219 cx.definition(ty, &item) 220 })?; 221 222 // When pushing functions into `OwnedImports` it's required that their 223 // `wasm_call` fields are all filled out. This `module` is guaranteed 224 // to have any trampolines necessary for functions so register the 225 // module with the store and then attempt to fill out any outstanding 226 // holes. 227 // 228 // Note that under normal operation this shouldn't do much as the list 229 // of funcs-with-holes should generally be empty. As a result the 230 // process of filling this out is not super optimized at this point. 231 store.modules_mut().register_module(module); 232 let (funcrefs, modules) = store.func_refs_and_modules(); 233 funcrefs.fill(modules); 234 235 let mut owned_imports = OwnedImports::new(module); 236 for import in imports { 237 owned_imports.push(import, store); 238 } 239 Ok(owned_imports) 240 } 241 242 /// Internal function to create an instance and run the start function. 243 /// 244 /// This function's unsafety is the same as `Instance::new_raw`. 245 pub(crate) unsafe fn new_started<T>( 246 store: &mut StoreContextMut<'_, T>, 247 module: &Module, 248 imports: Imports<'_>, 249 ) -> Result<Instance> { 250 assert!( 251 !store.0.async_support(), 252 "must use async instantiation when async support is enabled", 253 ); 254 255 // SAFETY: the safety contract of `new_started_impl` is the same as this 256 // function. 257 unsafe { Self::new_started_impl(store, module, imports) } 258 } 259 260 /// Internal function to create an instance and run the start function. 261 /// 262 /// ONLY CALL THIS IF YOU HAVE ALREADY CHECKED FOR ASYNCNESS AND HANDLED 263 /// THE FIBER NONSENSE 264 pub(crate) unsafe fn new_started_impl<T>( 265 store: &mut StoreContextMut<'_, T>, 266 module: &Module, 267 imports: Imports<'_>, 268 ) -> Result<Instance> { 269 // SAFETY: the safety contract of `new_raw` is the same as this 270 // function. 271 let (instance, start) = unsafe { Instance::new_raw(store.0, module, imports)? }; 272 if let Some(start) = start { 273 instance.start_raw(store, start)?; 274 } 275 Ok(instance) 276 } 277 278 /// Internal function to create an instance and run the start function. 279 /// 280 /// This function's unsafety is the same as `Instance::new_raw`. 281 #[cfg(feature = "async")] 282 async unsafe fn new_started_async<T>( 283 store: &mut StoreContextMut<'_, T>, 284 module: &Module, 285 imports: Imports<'_>, 286 ) -> Result<Instance> { 287 assert!( 288 store.0.async_support(), 289 "must use sync instantiation when async support is disabled", 290 ); 291 292 store 293 .on_fiber(|store| { 294 // SAFETY: the unsafe contract of `new_started_impl` is the same 295 // as this function. 296 unsafe { Self::new_started_impl(store, module, imports) } 297 }) 298 .await? 299 } 300 301 /// Internal function to create an instance which doesn't have its `start` 302 /// function run yet. 303 /// 304 /// This is not intended to be exposed from Wasmtime, it's intended to 305 /// refactor out common code from `new_started` and `new_started_async`. 306 /// 307 /// Note that this step needs to be run on a fiber in async mode even 308 /// though it doesn't do any blocking work because an async resource 309 /// limiter may need to yield. 310 /// 311 /// # Unsafety 312 /// 313 /// This method is unsafe because it does not type-check the `imports` 314 /// provided. The `imports` provided must be suitable for the module 315 /// provided as well. 316 unsafe fn new_raw( 317 store: &mut StoreOpaque, 318 module: &Module, 319 imports: Imports<'_>, 320 ) -> Result<(Instance, Option<FuncIndex>)> { 321 if !Engine::same(store.engine(), module.engine()) { 322 bail!("cross-`Engine` instantiation is not currently supported"); 323 } 324 store.bump_resource_counts(module)?; 325 326 // Allocate the GC heap, if necessary. 327 if module.env_module().needs_gc_heap { 328 store.ensure_gc_store()?; 329 } 330 331 let compiled_module = module.compiled_module(); 332 333 // Register the module just before instantiation to ensure we keep the module 334 // properly referenced while in use by the store. 335 let module_id = store.modules_mut().register_module(module); 336 337 // The first thing we do is issue an instance allocation request 338 // to the instance allocator. This, on success, will give us an 339 // instance handle. 340 // 341 // SAFETY: this module, by construction, was already validated within 342 // the store. 343 let id = unsafe { 344 store.allocate_instance( 345 AllocateInstanceKind::Module(module_id), 346 &ModuleRuntimeInfo::Module(module.clone()), 347 imports, 348 )? 349 }; 350 351 // Additionally, before we start doing fallible instantiation, we 352 // do one more step which is to insert an `InstanceData` 353 // corresponding to this instance. This `InstanceData` can be used 354 // via `Caller::get_export` if our instance's state "leaks" into 355 // other instances, even if we don't return successfully from this 356 // function. 357 // 358 // We don't actually load all exports from the instance at this 359 // time, instead preferring to lazily load them as they're demanded. 360 // For module/instance exports, though, those aren't actually 361 // stored in the instance handle so we need to immediately handle 362 // those here. 363 let instance = Instance::from_wasmtime(id, store); 364 365 // Now that we've recorded all information we need to about this 366 // instance within a `Store` we can start performing fallible 367 // initialization. Note that we still defer the `start` function to 368 // later since that may need to run asynchronously. 369 // 370 // If this returns an error (or if the start function traps) then 371 // any other initialization which may have succeeded which placed 372 // items from this instance into other instances should be ok when 373 // those items are loaded and run we'll have all the metadata to 374 // look at them. 375 let bulk_memory = store 376 .engine() 377 .features() 378 .contains(WasmFeatures::BULK_MEMORY); 379 380 if store.async_support() { 381 #[cfg(feature = "async")] 382 store.block_on(|store| { 383 let module = compiled_module.module().clone(); 384 Box::pin( 385 async move { vm::initialize_instance(store, id, &module, bulk_memory).await }, 386 ) 387 })??; 388 #[cfg(not(feature = "async"))] 389 unreachable!(); 390 } else { 391 vm::assert_ready(vm::initialize_instance( 392 store, 393 id, 394 compiled_module.module(), 395 bulk_memory, 396 ))?; 397 } 398 399 Ok((instance, compiled_module.module().start_func)) 400 } 401 402 pub(crate) fn from_wasmtime(id: InstanceId, store: &mut StoreOpaque) -> Instance { 403 Instance { 404 id: StoreInstanceId::new(store.id(), id), 405 } 406 } 407 408 fn start_raw<T>(&self, store: &mut StoreContextMut<'_, T>, start: FuncIndex) -> Result<()> { 409 // If a start function is present, invoke it. Make sure we use all the 410 // trap-handling configuration in `store` as well. 411 let store_id = store.0.id(); 412 let mut instance = self.id.get_mut(store.0); 413 // SAFETY: the `store_id` is the id of the store that owns this 414 // instance and any function stored within the instance. 415 let f = unsafe { instance.as_mut().get_exported_func(store_id, start) }; 416 let caller_vmctx = instance.vmctx(); 417 unsafe { 418 let funcref = f.vm_func_ref(store.0); 419 super::func::invoke_wasm_and_catch_traps(store, |_default_caller, vm| { 420 VMFuncRef::array_call(funcref, vm, caller_vmctx, NonNull::from(&mut [])) 421 })?; 422 } 423 Ok(()) 424 } 425 426 /// Get this instance's module. 427 pub fn module<'a, T: 'static>(&self, store: impl Into<StoreContext<'a, T>>) -> &'a Module { 428 self._module(store.into().0) 429 } 430 431 fn _module<'a>(&self, store: &'a StoreOpaque) -> &'a Module { 432 store.module_for_instance(self.id).unwrap() 433 } 434 435 /// Returns the list of exported items from this [`Instance`]. 436 /// 437 /// # Panics 438 /// 439 /// Panics if `store` does not own this instance. 440 pub fn exports<'a, T: 'static>( 441 &'a self, 442 store: impl Into<StoreContextMut<'a, T>>, 443 ) -> impl ExactSizeIterator<Item = Export<'a>> + 'a { 444 self._exports(store.into().0) 445 } 446 447 fn _exports<'a>( 448 &'a self, 449 store: &'a mut StoreOpaque, 450 ) -> impl ExactSizeIterator<Item = Export<'a>> + 'a { 451 let module = store[self.id].env_module().clone(); 452 let mut items = Vec::new(); 453 for (_name, entity) in module.exports.iter() { 454 items.push(self._get_export(store, *entity)); 455 } 456 store[self.id] 457 .env_module() 458 .exports 459 .iter() 460 .zip(items) 461 .map(|((name, _), item)| Export::new(name, item)) 462 } 463 464 /// Looks up an exported [`Extern`] value by name. 465 /// 466 /// This method will search the module for an export named `name` and return 467 /// the value, if found. 468 /// 469 /// Returns `None` if there was no export named `name`. 470 /// 471 /// # Panics 472 /// 473 /// Panics if `store` does not own this instance. 474 /// 475 /// # Why does `get_export` take a mutable context? 476 /// 477 /// This method requires a mutable context because an instance's exports are 478 /// lazily populated, and we cache them as they are accessed. This makes 479 /// instantiating a module faster, but also means this method requires a 480 /// mutable context. 481 pub fn get_export(&self, mut store: impl AsContextMut, name: &str) -> Option<Extern> { 482 let store = store.as_context_mut().0; 483 let entity = *store[self.id].env_module().exports.get(name)?; 484 Some(self._get_export(store, entity)) 485 } 486 487 /// Looks up an exported [`Extern`] value by a [`ModuleExport`] value. 488 /// 489 /// This is similar to [`Instance::get_export`] but uses a [`ModuleExport`] value to avoid 490 /// string lookups where possible. [`ModuleExport`]s can be obtained by calling 491 /// [`Module::get_export_index`] on the [`Module`] that this instance was instantiated with. 492 /// 493 /// This method will search the module for an export with a matching entity index and return 494 /// the value, if found. 495 /// 496 /// Returns `None` if there was no export with a matching entity index. 497 /// 498 /// # Panics 499 /// 500 /// Panics if `store` does not own this instance. 501 pub fn get_module_export( 502 &self, 503 mut store: impl AsContextMut, 504 export: &ModuleExport, 505 ) -> Option<Extern> { 506 let store = store.as_context_mut().0; 507 508 // Verify the `ModuleExport` matches the module used in this instance. 509 if self._module(store).id() != export.module { 510 return None; 511 } 512 513 Some(self._get_export(store, export.entity)) 514 } 515 516 fn _get_export(&self, store: &mut StoreOpaque, entity: EntityIndex) -> Extern { 517 let id = store.id(); 518 // SAFETY: the store `id` owns this instance and all exports contained 519 // within. 520 let export = unsafe { self.id.get_mut(store).get_export_by_index_mut(id, entity) }; 521 unsafe { Extern::from_wasmtime_export(export, store) } 522 } 523 524 /// Looks up an exported [`Func`] value by name. 525 /// 526 /// Returns `None` if there was no export named `name`, or if there was but 527 /// it wasn't a function. 528 /// 529 /// # Panics 530 /// 531 /// Panics if `store` does not own this instance. 532 pub fn get_func(&self, store: impl AsContextMut, name: &str) -> Option<Func> { 533 self.get_export(store, name)?.into_func() 534 } 535 536 /// Looks up an exported [`Func`] value by name and with its type. 537 /// 538 /// This function is a convenience wrapper over [`Instance::get_func`] and 539 /// [`Func::typed`]. For more information see the linked documentation. 540 /// 541 /// Returns an error if `name` isn't a function export or if the export's 542 /// type did not match `Params` or `Results` 543 /// 544 /// # Panics 545 /// 546 /// Panics if `store` does not own this instance. 547 pub fn get_typed_func<Params, Results>( 548 &self, 549 mut store: impl AsContextMut, 550 name: &str, 551 ) -> Result<TypedFunc<Params, Results>> 552 where 553 Params: crate::WasmParams, 554 Results: crate::WasmResults, 555 { 556 let f = self 557 .get_export(store.as_context_mut(), name) 558 .and_then(|f| f.into_func()) 559 .ok_or_else(|| anyhow!("failed to find function export `{}`", name))?; 560 Ok(f.typed::<Params, Results>(store) 561 .with_context(|| format!("failed to convert function `{name}` to given type"))?) 562 } 563 564 /// Looks up an exported [`Table`] value by name. 565 /// 566 /// Returns `None` if there was no export named `name`, or if there was but 567 /// it wasn't a table. 568 /// 569 /// # Panics 570 /// 571 /// Panics if `store` does not own this instance. 572 pub fn get_table(&self, store: impl AsContextMut, name: &str) -> Option<Table> { 573 self.get_export(store, name)?.into_table() 574 } 575 576 /// Looks up an exported [`Memory`] value by name. 577 /// 578 /// Returns `None` if there was no export named `name`, or if there was but 579 /// it wasn't a memory. 580 /// 581 /// # Panics 582 /// 583 /// Panics if `store` does not own this instance. 584 pub fn get_memory(&self, store: impl AsContextMut, name: &str) -> Option<Memory> { 585 self.get_export(store, name)?.into_memory() 586 } 587 588 /// Looks up an exported [`SharedMemory`] value by name. 589 /// 590 /// Returns `None` if there was no export named `name`, or if there was but 591 /// it wasn't a shared memory. 592 /// 593 /// # Panics 594 /// 595 /// Panics if `store` does not own this instance. 596 pub fn get_shared_memory( 597 &self, 598 mut store: impl AsContextMut, 599 name: &str, 600 ) -> Option<SharedMemory> { 601 let mut store = store.as_context_mut(); 602 self.get_export(&mut store, name)?.into_shared_memory() 603 } 604 605 /// Looks up an exported [`Global`] value by name. 606 /// 607 /// Returns `None` if there was no export named `name`, or if there was but 608 /// it wasn't a global. 609 /// 610 /// # Panics 611 /// 612 /// Panics if `store` does not own this instance. 613 pub fn get_global(&self, store: impl AsContextMut, name: &str) -> Option<Global> { 614 self.get_export(store, name)?.into_global() 615 } 616 617 /// Looks up a tag [`Tag`] by name. 618 /// 619 /// Returns `None` if there was no export named `name`, or if there was but 620 /// it wasn't a tag. 621 /// 622 /// # Panics 623 /// 624 /// Panics if `store` does not own this instance. 625 pub fn get_tag(&self, store: impl AsContextMut, name: &str) -> Option<Tag> { 626 self.get_export(store, name)?.into_tag() 627 } 628 629 #[allow( 630 dead_code, 631 reason = "c-api crate does not yet support exnrefs and causes this method to be dead." 632 )] 633 pub(crate) fn id(&self) -> InstanceId { 634 self.id.instance() 635 } 636 637 /// Get all globals within this instance. 638 /// 639 /// Returns both import and defined globals. 640 /// 641 /// Returns both exported and non-exported globals. 642 /// 643 /// Gives access to the full globals space. 644 #[cfg(feature = "coredump")] 645 pub(crate) fn all_globals<'a>( 646 &'a self, 647 store: &'a mut StoreOpaque, 648 ) -> impl ExactSizeIterator<Item = (GlobalIndex, Global)> + 'a { 649 let store_id = store.id(); 650 store[self.id].all_globals(store_id) 651 } 652 653 /// Get all memories within this instance. 654 /// 655 /// Returns both import and defined memories. 656 /// 657 /// Returns both exported and non-exported memories. 658 /// 659 /// Gives access to the full memories space. 660 #[cfg(feature = "coredump")] 661 pub(crate) fn all_memories<'a>( 662 &'a self, 663 store: &'a StoreOpaque, 664 ) -> impl ExactSizeIterator<Item = (MemoryIndex, Memory)> + 'a { 665 let store_id = store.id(); 666 store[self.id].all_memories(store_id) 667 } 668 } 669 670 pub(crate) struct OwnedImports { 671 functions: PrimaryMap<FuncIndex, VMFunctionImport>, 672 tables: PrimaryMap<TableIndex, VMTableImport>, 673 memories: PrimaryMap<MemoryIndex, VMMemoryImport>, 674 globals: PrimaryMap<GlobalIndex, VMGlobalImport>, 675 tags: PrimaryMap<TagIndex, VMTagImport>, 676 } 677 678 impl OwnedImports { 679 fn new(module: &Module) -> OwnedImports { 680 let mut ret = OwnedImports::empty(); 681 ret.reserve(module); 682 return ret; 683 } 684 685 pub(crate) fn empty() -> OwnedImports { 686 OwnedImports { 687 functions: PrimaryMap::new(), 688 tables: PrimaryMap::new(), 689 memories: PrimaryMap::new(), 690 globals: PrimaryMap::new(), 691 tags: PrimaryMap::new(), 692 } 693 } 694 695 pub(crate) fn reserve(&mut self, module: &Module) { 696 let raw = module.compiled_module().module(); 697 self.functions.reserve(raw.num_imported_funcs); 698 self.tables.reserve(raw.num_imported_tables); 699 self.memories.reserve(raw.num_imported_memories); 700 self.globals.reserve(raw.num_imported_globals); 701 self.tags.reserve(raw.num_imported_tags); 702 } 703 704 #[cfg(feature = "component-model")] 705 pub(crate) fn clear(&mut self) { 706 self.functions.clear(); 707 self.tables.clear(); 708 self.memories.clear(); 709 self.globals.clear(); 710 self.tags.clear(); 711 } 712 713 fn push(&mut self, item: &Extern, store: &mut StoreOpaque) { 714 match item { 715 Extern::Func(i) => { 716 self.functions.push(i.vmimport(store)); 717 } 718 Extern::Global(i) => { 719 self.globals.push(i.vmimport(store)); 720 } 721 Extern::Table(i) => { 722 self.tables.push(i.vmimport(store)); 723 } 724 Extern::Memory(i) => { 725 self.memories.push(i.vmimport(store)); 726 } 727 Extern::SharedMemory(i) => { 728 self.memories.push(i.vmimport(store)); 729 } 730 Extern::Tag(i) => { 731 self.tags.push(i.vmimport(store)); 732 } 733 } 734 } 735 736 /// Note that this is unsafe as the validity of `item` is not verified and 737 /// it contains a bunch of raw pointers. 738 #[cfg(feature = "component-model")] 739 pub(crate) fn push_export(&mut self, store: &StoreOpaque, item: &crate::runtime::vm::Export) { 740 match item { 741 crate::runtime::vm::Export::Function(f) => { 742 // SAFETY: the funcref associated with a `Func` is valid to use 743 // under the `store` that owns the function. 744 let f = unsafe { f.vm_func_ref(store).as_ref() }; 745 self.functions.push(VMFunctionImport { 746 wasm_call: f.wasm_call.unwrap(), 747 array_call: f.array_call, 748 vmctx: f.vmctx, 749 }); 750 } 751 crate::runtime::vm::Export::Global(g) => { 752 self.globals.push(g.vmimport(store)); 753 } 754 crate::runtime::vm::Export::Table(t) => { 755 self.tables.push(t.vmimport(store)); 756 } 757 crate::runtime::vm::Export::Memory { memory, .. } => { 758 self.memories.push(memory.vmimport(store)); 759 } 760 crate::runtime::vm::Export::Tag(t) => { 761 self.tags.push(t.vmimport(store)); 762 } 763 } 764 } 765 766 pub(crate) fn as_ref(&self) -> Imports<'_> { 767 Imports { 768 tables: self.tables.values().as_slice(), 769 globals: self.globals.values().as_slice(), 770 memories: self.memories.values().as_slice(), 771 functions: self.functions.values().as_slice(), 772 tags: self.tags.values().as_slice(), 773 } 774 } 775 } 776 777 /// An instance, pre-instantiation, that is ready to be instantiated. 778 /// 779 /// This structure represents an instance *just before* it was instantiated, 780 /// after all type-checking and imports have been resolved. The only thing left 781 /// to do for this instance is to actually run the process of instantiation. 782 /// 783 /// Note that an `InstancePre` may not be tied to any particular [`Store`] if 784 /// none of the imports it closed over are tied to any particular [`Store`]. 785 /// 786 /// This structure is created through the [`Linker::instantiate_pre`] method, 787 /// which also has some more information and examples. 788 /// 789 /// [`Store`]: crate::Store 790 /// [`Linker::instantiate_pre`]: crate::Linker::instantiate_pre 791 pub struct InstancePre<T> { 792 module: Module, 793 794 /// The items which this `InstancePre` use to instantiate the `module` 795 /// provided, passed to `Instance::new_started` after inserting them into a 796 /// `Store`. 797 /// 798 /// Note that this is stored as an `Arc<[T]>` to quickly move a strong 799 /// reference to everything internally into a `Store<T>` without having to 800 /// clone each individual item. 801 items: Arc<[Definition]>, 802 803 /// A count of `Definition::HostFunc` entries in `items` above to 804 /// preallocate space in a `Store` up front for all entries to be inserted. 805 host_funcs: usize, 806 807 /// The `VMFuncRef`s for the functions in `items` that do not 808 /// have a `wasm_call` trampoline. We pre-allocate and pre-patch these 809 /// `VMFuncRef`s so that we don't have to do it at 810 /// instantiation time. 811 /// 812 /// This is an `Arc<[T]>` for the same reason as `items`. 813 func_refs: Arc<[VMFuncRef]>, 814 815 _marker: core::marker::PhantomData<fn() -> T>, 816 } 817 818 /// InstancePre's clone does not require T: Clone 819 impl<T> Clone for InstancePre<T> { 820 fn clone(&self) -> Self { 821 Self { 822 module: self.module.clone(), 823 items: self.items.clone(), 824 host_funcs: self.host_funcs, 825 func_refs: self.func_refs.clone(), 826 _marker: self._marker, 827 } 828 } 829 } 830 831 impl<T: 'static> InstancePre<T> { 832 /// Creates a new `InstancePre` which type-checks the `items` provided and 833 /// on success is ready to instantiate a new instance. 834 /// 835 /// # Unsafety 836 /// 837 /// This method is unsafe as the `T` of the `InstancePre<T>` is not 838 /// guaranteed to be the same as the `T` within the `Store`, the caller must 839 /// verify that. 840 pub(crate) unsafe fn new(module: &Module, items: Vec<Definition>) -> Result<InstancePre<T>> { 841 typecheck(module, &items, |cx, ty, item| cx.definition(ty, &item.ty()))?; 842 843 let mut func_refs = vec![]; 844 let mut host_funcs = 0; 845 for item in &items { 846 match item { 847 Definition::Extern(_, _) => {} 848 Definition::HostFunc(f) => { 849 host_funcs += 1; 850 if f.func_ref().wasm_call.is_none() { 851 // `f` needs its `VMFuncRef::wasm_call` patched with a 852 // Wasm-to-native trampoline. 853 debug_assert!(matches!(f.host_ctx(), crate::HostContext::Array(_))); 854 func_refs.push(VMFuncRef { 855 wasm_call: module 856 .wasm_to_array_trampoline(f.sig_index()) 857 .map(|f| f.into()), 858 ..*f.func_ref() 859 }); 860 } 861 } 862 } 863 } 864 865 Ok(InstancePre { 866 module: module.clone(), 867 items: items.into(), 868 host_funcs, 869 func_refs: func_refs.into(), 870 _marker: core::marker::PhantomData, 871 }) 872 } 873 874 /// Returns a reference to the module that this [`InstancePre`] will be 875 /// instantiating. 876 pub fn module(&self) -> &Module { 877 &self.module 878 } 879 880 /// Instantiates this instance, creating a new instance within the provided 881 /// `store`. 882 /// 883 /// This function will run the actual process of instantiation to 884 /// completion. This will use all of the previously-closed-over items as 885 /// imports to instantiate the module that this was originally created with. 886 /// 887 /// For more information about instantiation see [`Instance::new`]. 888 /// 889 /// # Panics 890 /// 891 /// Panics if any import closed over by this [`InstancePre`] isn't owned by 892 /// `store`, or if `store` has async support enabled. Additionally this 893 /// function will panic if the `store` provided comes from a different 894 /// [`Engine`] than the [`InstancePre`] originally came from. 895 pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> { 896 let mut store = store.as_context_mut(); 897 let imports = pre_instantiate_raw( 898 &mut store.0, 899 &self.module, 900 &self.items, 901 self.host_funcs, 902 &self.func_refs, 903 )?; 904 905 // This unsafety should be handled by the type-checking performed by the 906 // constructor of `InstancePre` to assert that all the imports we're passing 907 // in match the module we're instantiating. 908 unsafe { Instance::new_started(&mut store, &self.module, imports.as_ref()) } 909 } 910 911 /// Creates a new instance, running the start function asynchronously 912 /// instead of inline. 913 /// 914 /// For more information about asynchronous instantiation see the 915 /// documentation on [`Instance::new_async`]. 916 /// 917 /// # Panics 918 /// 919 /// Panics if any import closed over by this [`InstancePre`] isn't owned by 920 /// `store`, or if `store` does not have async support enabled. 921 #[cfg(feature = "async")] 922 pub async fn instantiate_async( 923 &self, 924 mut store: impl AsContextMut<Data = T>, 925 ) -> Result<Instance> { 926 let mut store = store.as_context_mut(); 927 let imports = pre_instantiate_raw( 928 &mut store.0, 929 &self.module, 930 &self.items, 931 self.host_funcs, 932 &self.func_refs, 933 )?; 934 935 // This unsafety should be handled by the type-checking performed by the 936 // constructor of `InstancePre` to assert that all the imports we're passing 937 // in match the module we're instantiating. 938 unsafe { Instance::new_started_async(&mut store, &self.module, imports.as_ref()).await } 939 } 940 } 941 942 /// Helper function shared between 943 /// `InstancePre::{instantiate,instantiate_async}` 944 /// 945 /// This is an out-of-line function to avoid the generic on `InstancePre` and 946 /// get this compiled into the `wasmtime` crate to avoid having it monomorphized 947 /// elsewhere. 948 fn pre_instantiate_raw( 949 store: &mut StoreOpaque, 950 module: &Module, 951 items: &Arc<[Definition]>, 952 host_funcs: usize, 953 func_refs: &Arc<[VMFuncRef]>, 954 ) -> Result<OwnedImports> { 955 // Register this module and use it to fill out any funcref wasm_call holes 956 // we can. For more comments on this see `typecheck_externs`. 957 store.modules_mut().register_module(module); 958 let (funcrefs, modules) = store.func_refs_and_modules(); 959 funcrefs.fill(modules); 960 961 if host_funcs > 0 { 962 // Any linker-defined function of the `Definition::HostFunc` variant 963 // will insert a function into the store automatically as part of 964 // instantiation, so reserve space here to make insertion more efficient 965 // as it won't have to realloc during the instantiation. 966 funcrefs.reserve_storage(host_funcs); 967 968 // The usage of `to_extern_store_rooted` requires that the items are 969 // rooted via another means, which happens here by cloning the list of 970 // items into the store once. This avoids cloning each individual item 971 // below. 972 funcrefs.push_instance_pre_definitions(items.clone()); 973 funcrefs.push_instance_pre_func_refs(func_refs.clone()); 974 } 975 976 let mut func_refs = func_refs.iter().map(|f| NonNull::from(f)); 977 let mut imports = OwnedImports::new(module); 978 for import in items.iter() { 979 if !import.comes_from_same_store(store) { 980 bail!("cross-`Store` instantiation is not currently supported"); 981 } 982 // This unsafety should be encapsulated in the constructor of 983 // `InstancePre` where the `T` of the original item should match the 984 // `T` of the store. Additionally the rooting necessary has happened 985 // above. 986 let item = match import { 987 Definition::Extern(e, _) => e.clone(), 988 Definition::HostFunc(func) => unsafe { 989 func.to_func_store_rooted( 990 store, 991 if func.func_ref().wasm_call.is_none() { 992 Some(func_refs.next().unwrap()) 993 } else { 994 None 995 }, 996 ) 997 .into() 998 }, 999 }; 1000 imports.push(&item, store); 1001 } 1002 1003 Ok(imports) 1004 } 1005 1006 fn typecheck<I>( 1007 module: &Module, 1008 import_args: &[I], 1009 check: impl Fn(&matching::MatchCx<'_>, &EntityType, &I) -> Result<()>, 1010 ) -> Result<()> { 1011 let env_module = module.compiled_module().module(); 1012 let expected_len = env_module.imports().count(); 1013 let actual_len = import_args.len(); 1014 if expected_len != actual_len { 1015 bail!("expected {expected_len} imports, found {actual_len}"); 1016 } 1017 let cx = matching::MatchCx::new(module.engine()); 1018 for ((name, field, expected_ty), actual) in env_module.imports().zip(import_args) { 1019 debug_assert!(expected_ty.is_canonicalized_for_runtime_usage()); 1020 check(&cx, &expected_ty, actual) 1021 .with_context(|| format!("incompatible import type for `{name}::{field}`"))?; 1022 } 1023 Ok(()) 1024 } 1025