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