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