1 use crate::component::RuntimeInstance; 2 use crate::component::func::HostFunc; 3 use crate::component::matching::InstanceType; 4 use crate::component::store::{ComponentInstanceId, StoreComponentInstanceId}; 5 use crate::component::{ 6 Component, ComponentExportIndex, ComponentNamedList, Func, Lift, Lower, ResourceType, 7 TypedFunc, types::ComponentItem, 8 }; 9 use crate::instance::OwnedImports; 10 use crate::linker::DefinitionType; 11 use crate::prelude::*; 12 use crate::runtime::vm::component::{ 13 CallContexts, ComponentInstance, ResourceTables, TypedResource, TypedResourceIndex, 14 }; 15 use crate::runtime::vm::{self, VMFuncRef}; 16 use crate::store::{AsStoreOpaque, Asyncness, StoreOpaque}; 17 use crate::{AsContext, AsContextMut, Engine, Module, StoreContextMut}; 18 use alloc::sync::Arc; 19 use core::marker; 20 use core::pin::Pin; 21 use core::ptr::NonNull; 22 use wasmtime_environ::{EngineOrModuleTypeIndex, component::*}; 23 use wasmtime_environ::{EntityIndex, EntityType, PrimaryMap}; 24 25 /// An instantiated component. 26 /// 27 /// This type represents an instantiated [`Component`](super::Component). 28 /// Instances have exports which can be accessed through functions such as 29 /// [`Instance::get_func`] or [`Instance::get_export`]. Instances are owned by a 30 /// [`Store`](crate::Store) and all methods require a handle to the store. 31 /// 32 /// Component instances are created through 33 /// [`Linker::instantiate`](super::Linker::instantiate) and its family of 34 /// methods. 35 /// 36 /// This type is similar to the core wasm version 37 /// [`wasmtime::Instance`](crate::Instance) except that it represents an 38 /// instantiated component instead of an instantiated module. 39 #[derive(Copy, Clone, Debug)] 40 #[repr(transparent)] 41 pub struct Instance { 42 id: StoreComponentInstanceId, 43 } 44 45 // Double-check that the C representation in `component/instance.h` matches our 46 // in-Rust representation here in terms of size/alignment/etc. 47 const _: () = { 48 #[repr(C)] 49 struct C(u64, u32); 50 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Instance>()); 51 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Instance>()); 52 assert!(core::mem::offset_of!(Instance, id) == 0); 53 }; 54 55 impl Instance { 56 /// Creates a raw `Instance` from the internal identifiers within the store. 57 pub(crate) fn from_wasmtime(store: &StoreOpaque, id: ComponentInstanceId) -> Instance { 58 Instance { 59 id: StoreComponentInstanceId::new(store.id(), id), 60 } 61 } 62 63 /// Looks up an exported function by name within this [`Instance`]. 64 /// 65 /// The `store` argument provided must be the store that this instance 66 /// lives within and the `name` argument is the lookup key by which to find 67 /// the exported function. If the function is found then `Some` is returned 68 /// and otherwise `None` is returned. 69 /// 70 /// The `name` here can be a string such as `&str` or it can be a 71 /// [`ComponentExportIndex`] which is loaded prior from a [`Component`]. 72 /// 73 /// # Panics 74 /// 75 /// Panics if `store` does not own this instance. 76 /// 77 /// # Examples 78 /// 79 /// Looking up a function which is exported from the root of a component: 80 /// 81 /// ``` 82 /// use wasmtime::{Engine, Store}; 83 /// use wasmtime::component::{Component, Linker}; 84 /// 85 /// # fn main() -> wasmtime::Result<()> { 86 /// let engine = Engine::default(); 87 /// let component = Component::new( 88 /// &engine, 89 /// r#" 90 /// (component 91 /// (core module $m 92 /// (func (export "f")) 93 /// ) 94 /// (core instance $i (instantiate $m)) 95 /// (func (export "f") 96 /// (canon lift (core func $i "f"))) 97 /// ) 98 /// "#, 99 /// )?; 100 /// 101 /// // Look up the function by name 102 /// let mut store = Store::new(&engine, ()); 103 /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?; 104 /// let func = instance.get_func(&mut store, "f").unwrap(); 105 /// 106 /// // The function can also be looked up by an index via a precomputed index. 107 /// let export = component.get_export_index(None, "f").unwrap(); 108 /// let func = instance.get_func(&mut store, &export).unwrap(); 109 /// # Ok(()) 110 /// # } 111 /// ``` 112 /// 113 /// Looking up a function which is exported from a nested instance: 114 /// 115 /// ``` 116 /// use wasmtime::{Engine, Store}; 117 /// use wasmtime::component::{Component, Linker}; 118 /// 119 /// # fn main() -> wasmtime::Result<()> { 120 /// let engine = Engine::default(); 121 /// let component = Component::new( 122 /// &engine, 123 /// r#" 124 /// (component 125 /// (core module $m 126 /// (func (export "f")) 127 /// ) 128 /// (core instance $i (instantiate $m)) 129 /// (func $f 130 /// (canon lift (core func $i "f"))) 131 /// 132 /// (instance $i 133 /// (export "f" (func $f))) 134 /// (export "i" (instance $i)) 135 /// ) 136 /// "#, 137 /// )?; 138 /// 139 /// // First look up the exported instance, then use that to lookup the 140 /// // exported function. 141 /// let instance_index = component.get_export_index(None, "i").unwrap(); 142 /// let func_index = component.get_export_index(Some(&instance_index), "f").unwrap(); 143 /// 144 /// // Then use `func_index` at runtime. 145 /// let mut store = Store::new(&engine, ()); 146 /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?; 147 /// let func = instance.get_func(&mut store, &func_index).unwrap(); 148 /// 149 /// // Alternatively the `instance` can be used directly in conjunction with 150 /// // the `get_export_index` method. 151 /// let instance_index = instance.get_export_index(&mut store, None, "i").unwrap(); 152 /// let func_index = instance.get_export_index(&mut store, Some(&instance_index), "f").unwrap(); 153 /// let func = instance.get_func(&mut store, &func_index).unwrap(); 154 /// # Ok(()) 155 /// # } 156 /// ``` 157 pub fn get_func( 158 &self, 159 mut store: impl AsContextMut, 160 name: impl InstanceExportLookup, 161 ) -> Option<Func> { 162 let store = store.as_context_mut().0; 163 let instance = self.id.get(store); 164 let component = instance.component(); 165 166 // Validate that `name` exists within `self.` 167 let index = name.lookup(component)?; 168 169 // Validate that `index` is indeed a lifted function. 170 match &component.env_component().export_items[index] { 171 Export::LiftedFunction { .. } => {} 172 _ => return None, 173 } 174 175 // And package up the indices! 176 Some(Func::from_lifted_func(*self, index)) 177 } 178 179 /// Looks up an exported [`Func`] value by name and with its type. 180 /// 181 /// This function is a convenience wrapper over [`Instance::get_func`] and 182 /// [`Func::typed`]. For more information see the linked documentation. 183 /// 184 /// Returns an error if `name` isn't a function export or if the export's 185 /// type did not match `Params` or `Results` 186 /// 187 /// # Panics 188 /// 189 /// Panics if `store` does not own this instance. 190 pub fn get_typed_func<Params, Results>( 191 &self, 192 mut store: impl AsContextMut, 193 name: impl InstanceExportLookup, 194 ) -> Result<TypedFunc<Params, Results>> 195 where 196 Params: ComponentNamedList + Lower, 197 Results: ComponentNamedList + Lift, 198 { 199 let f = self 200 .get_func(store.as_context_mut(), name) 201 .ok_or_else(|| format_err!("failed to find function export"))?; 202 Ok(f.typed::<Params, Results>(store) 203 .with_context(|| format!("failed to convert function to given type"))?) 204 } 205 206 /// Looks up an exported module by name within this [`Instance`]. 207 /// 208 /// The `store` argument provided must be the store that this instance 209 /// lives within and the `name` argument is the lookup key by which to find 210 /// the exported module. If the module is found then `Some` is returned 211 /// and otherwise `None` is returned. 212 /// 213 /// The `name` here can be a string such as `&str` or it can be a 214 /// [`ComponentExportIndex`] which is loaded prior from a [`Component`]. 215 /// 216 /// For some examples see [`Instance::get_func`] for loading values from a 217 /// component. 218 /// 219 /// # Panics 220 /// 221 /// Panics if `store` does not own this instance. 222 pub fn get_module( 223 &self, 224 mut store: impl AsContextMut, 225 name: impl InstanceExportLookup, 226 ) -> Option<Module> { 227 let store = store.as_context_mut().0; 228 let (instance, export) = self.lookup_export(store, name)?; 229 match export { 230 Export::ModuleStatic { index, .. } => { 231 Some(instance.component().static_module(*index).clone()) 232 } 233 Export::ModuleImport { import, .. } => match instance.runtime_import(*import) { 234 RuntimeImport::Module(m) => Some(m.clone()), 235 _ => unreachable!(), 236 }, 237 _ => None, 238 } 239 } 240 241 /// Looks up an exported resource type by name within this [`Instance`]. 242 /// 243 /// The `store` argument provided must be the store that this instance 244 /// lives within and the `name` argument is the lookup key by which to find 245 /// the exported resource. If the resource is found then `Some` is returned 246 /// and otherwise `None` is returned. 247 /// 248 /// The `name` here can be a string such as `&str` or it can be a 249 /// [`ComponentExportIndex`] which is loaded prior from a [`Component`]. 250 /// 251 /// For some examples see [`Instance::get_func`] for loading values from a 252 /// component. 253 /// 254 /// # Panics 255 /// 256 /// Panics if `store` does not own this instance. 257 pub fn get_resource( 258 &self, 259 mut store: impl AsContextMut, 260 name: impl InstanceExportLookup, 261 ) -> Option<ResourceType> { 262 let store = store.as_context_mut().0; 263 let (instance, export) = self.lookup_export(store, name)?; 264 match export { 265 Export::Type(TypeDef::Resource(id)) => { 266 Some(InstanceType::new(instance).resource_type(*id)) 267 } 268 Export::Type(_) 269 | Export::LiftedFunction { .. } 270 | Export::ModuleStatic { .. } 271 | Export::ModuleImport { .. } 272 | Export::Instance { .. } => None, 273 } 274 } 275 276 /// A methods similar to [`Component::get_export`] except for this 277 /// instance. 278 /// 279 /// This method will lookup the `name` provided within the `instance` 280 /// provided and return a [`ComponentItem`] describing the export, 281 /// and [`ComponentExportIndex`] which can be passed other `get_*` 282 /// functions like [`Instance::get_func`]. 283 /// 284 /// The [`ComponentItem`] is more expensive to compute than the 285 /// [`ComponentExportIndex`]. If you are not consuming the 286 /// [`ComponentItem`], use [`Instance::get_export_index`] instead. 287 /// 288 /// # Panics 289 /// 290 /// Panics if `store` does not own this instance. 291 pub fn get_export( 292 &self, 293 mut store: impl AsContextMut, 294 instance: Option<&ComponentExportIndex>, 295 name: &str, 296 ) -> Option<(ComponentItem, ComponentExportIndex)> { 297 self._get_export(store.as_context_mut().0, instance, name) 298 } 299 300 fn _get_export( 301 &self, 302 store: &StoreOpaque, 303 instance: Option<&ComponentExportIndex>, 304 name: &str, 305 ) -> Option<(ComponentItem, ComponentExportIndex)> { 306 let data = self.id().get(store); 307 let component = data.component(); 308 let index = component.lookup_export_index(instance, name)?; 309 let item = ComponentItem::from_export( 310 &store.engine(), 311 &component.env_component().export_items[index], 312 &InstanceType::new(data), 313 ); 314 Some(( 315 item, 316 ComponentExportIndex { 317 id: data.component().id(), 318 index, 319 }, 320 )) 321 } 322 323 /// A methods similar to [`Component::get_export_index`] except for this 324 /// instance. 325 /// 326 /// This method will lookup the `name` provided within the `instance` 327 /// provided and return a [`ComponentExportIndex`] which can be passed 328 /// other `get_*` functions like [`Instance::get_func`]. 329 /// 330 /// If you need the [`ComponentItem`] corresponding to this export, use 331 /// the [`Instance::get_export`] instead. 332 /// 333 /// # Panics 334 /// 335 /// Panics if `store` does not own this instance. 336 pub fn get_export_index( 337 &self, 338 mut store: impl AsContextMut, 339 instance: Option<&ComponentExportIndex>, 340 name: &str, 341 ) -> Option<ComponentExportIndex> { 342 let data = self.id().get(store.as_context_mut().0); 343 let index = data.component().lookup_export_index(instance, name)?; 344 Some(ComponentExportIndex { 345 id: data.component().id(), 346 index, 347 }) 348 } 349 350 fn lookup_export<'a>( 351 &self, 352 store: &'a StoreOpaque, 353 name: impl InstanceExportLookup, 354 ) -> Option<(&'a ComponentInstance, &'a Export)> { 355 let data = self.id().get(store); 356 let index = name.lookup(data.component())?; 357 Some((data, &data.component().env_component().export_items[index])) 358 } 359 360 /// Returns the [`InstancePre`] that was used to create this instance. 361 pub fn instance_pre<T>(&self, store: impl AsContext<Data = T>) -> InstancePre<T> { 362 // This indexing operation asserts the Store owns the Instance. 363 // Therefore, the InstancePre<T> must match the Store<T>. 364 let data = self.id().get(store.as_context().0); 365 366 // SAFETY: calling this method safely here relies on matching the `T` 367 // in `InstancePre<T>` to the store itself, which is happening in the 368 // type signature just above by ensuring the store's data is `T` which 369 // matches the return value. 370 unsafe { data.instance_pre() } 371 } 372 373 pub(crate) fn id(&self) -> StoreComponentInstanceId { 374 self.id 375 } 376 377 /// Implementation of the `resource.new` intrinsic for `i32` 378 /// representations. 379 pub(crate) fn resource_new32( 380 self, 381 store: &mut StoreOpaque, 382 ty: TypeResourceTableIndex, 383 rep: u32, 384 ) -> Result<u32> { 385 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 386 resource_tables(calls, instance).resource_new(TypedResource::Component { ty, rep }) 387 } 388 389 /// Implementation of the `resource.rep` intrinsic for `i32` 390 /// representations. 391 pub(crate) fn resource_rep32( 392 self, 393 store: &mut StoreOpaque, 394 ty: TypeResourceTableIndex, 395 index: u32, 396 ) -> Result<u32> { 397 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 398 resource_tables(calls, instance).resource_rep(TypedResourceIndex::Component { ty, index }) 399 } 400 401 /// Implementation of the `resource.drop` intrinsic. 402 pub(crate) fn resource_drop( 403 self, 404 store: &mut StoreOpaque, 405 ty: TypeResourceTableIndex, 406 index: u32, 407 ) -> Result<Option<u32>> { 408 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 409 resource_tables(calls, instance).resource_drop(TypedResourceIndex::Component { ty, index }) 410 } 411 412 pub(crate) fn resource_transfer_own( 413 self, 414 store: &mut StoreOpaque, 415 index: u32, 416 src: TypeResourceTableIndex, 417 dst: TypeResourceTableIndex, 418 ) -> Result<u32> { 419 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 420 let mut tables = resource_tables(calls, instance); 421 let rep = tables.resource_lift_own(TypedResourceIndex::Component { ty: src, index })?; 422 tables.resource_lower_own(TypedResource::Component { ty: dst, rep }) 423 } 424 425 pub(crate) fn resource_transfer_borrow( 426 self, 427 store: &mut StoreOpaque, 428 index: u32, 429 src: TypeResourceTableIndex, 430 dst: TypeResourceTableIndex, 431 ) -> Result<u32> { 432 let dst_owns_resource = self.id().get(store).resource_owned_by_own_instance(dst); 433 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 434 let mut tables = resource_tables(calls, instance); 435 let rep = tables.resource_lift_borrow(TypedResourceIndex::Component { ty: src, index })?; 436 // Implement `lower_borrow`'s special case here where if a borrow's 437 // resource type is owned by `dst` then the destination receives the 438 // representation directly rather than a handle to the representation. 439 // 440 // This can perhaps become a different libcall in the future to avoid 441 // this check at runtime since we know at compile time whether the 442 // destination type owns the resource, but that's left as a future 443 // refactoring if truly necessary. 444 if dst_owns_resource { 445 return Ok(rep); 446 } 447 tables.resource_lower_borrow(TypedResource::Component { ty: dst, rep }) 448 } 449 450 pub(crate) fn resource_enter_call(self, store: &mut StoreOpaque) { 451 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 452 resource_tables(calls, instance).enter_call() 453 } 454 455 pub(crate) fn resource_exit_call(self, store: &mut StoreOpaque) -> Result<()> { 456 let (calls, _, _, instance) = store.component_resource_state_with_instance(self); 457 resource_tables(calls, instance).exit_call() 458 } 459 460 pub(crate) fn lookup_vmdef(&self, store: &mut StoreOpaque, def: &CoreDef) -> vm::Export { 461 lookup_vmdef(store, self.id.instance(), def) 462 } 463 464 pub(crate) fn options<'a>( 465 &self, 466 store: &'a StoreOpaque, 467 options: OptionsIndex, 468 ) -> &'a CanonicalOptions { 469 &self.id.get(store).component().env_component().options[options] 470 } 471 472 fn options_memory_raw( 473 &self, 474 store: &StoreOpaque, 475 options: OptionsIndex, 476 ) -> Option<NonNull<vm::VMMemoryDefinition>> { 477 let instance = self.id.get(store); 478 let options = &instance.component().env_component().options[options]; 479 let memory = match options.data_model { 480 CanonicalOptionsDataModel::Gc { .. } => return None, 481 CanonicalOptionsDataModel::LinearMemory(o) => match o.memory { 482 Some(m) => m, 483 None => return None, 484 }, 485 }; 486 487 Some(instance.runtime_memory(memory)) 488 } 489 490 pub(crate) fn options_memory<'a>( 491 &self, 492 store: &'a StoreOpaque, 493 options: OptionsIndex, 494 ) -> &'a [u8] { 495 let memory = match self.options_memory_raw(store, options) { 496 Some(m) => m, 497 None => return &[], 498 }; 499 // SAFETY: we're borrowing the entire `StoreOpaque` which owns the 500 // memory allocation to return the result of memory. That means that the 501 // lifetime connection here should be safe and the actual ptr/length are 502 // trusted parts of the runtime here. 503 unsafe { 504 let memory = memory.as_ref(); 505 core::slice::from_raw_parts(memory.base.as_ptr(), memory.current_length()) 506 } 507 } 508 509 pub(crate) fn options_memory_mut<'a>( 510 &self, 511 store: &'a mut StoreOpaque, 512 options: OptionsIndex, 513 ) -> &'a mut [u8] { 514 let memory = match self.options_memory_raw(store, options) { 515 Some(m) => m, 516 None => return &mut [], 517 }; 518 // SAFETY: See `options_memory` comment above, and note that this is 519 // taking `&mut StoreOpaque` to thread the lifetime through instead. 520 unsafe { 521 let memory = memory.as_ref(); 522 core::slice::from_raw_parts_mut(memory.base.as_ptr(), memory.current_length()) 523 } 524 } 525 526 /// Helper function to simultaneously get a borrow to this instance's 527 /// component as well as the store that this component is contained within. 528 /// 529 /// Note that this function signature is not possible with safe Rust, so 530 /// this is using `unsafe` internally. 531 pub(crate) fn component_and_store_mut<'a, S>( 532 &self, 533 store: &'a mut S, 534 ) -> (&'a Component, &'a mut S) 535 where 536 S: AsStoreOpaque, 537 { 538 let store_opaque = store.as_store_opaque(); 539 let instance = self.id.get_mut(store_opaque); 540 let component = instance.component(); 541 542 // SAFETY: the goal of this function is to derive a pointer from 543 // `&mut S`, here `&Component`, and then return both so they can both be 544 // used at the same time. In general this is not safe operation since 545 // the original mutable pointer could be mutated or overwritten which 546 // would invalidate the derived pointer. 547 // 548 // In this case though we have a few guarantees which should make this 549 // safe: 550 // 551 // * Embedders never have the ability to overwrite a `StoreOpaque`. For 552 // example the closest thing of `StoreContextMut` wraps up the 553 // reference internally so it's inaccessible to the outside world. 554 // This means that while mutations can still happen it's not possible 555 // to overwrite a `StoreOpaque` directly. 556 // 557 // * Components are referred to by `vm::ComponentInstance` which holds a 558 // strong reference. All `ComponentInstance` structures are allocated 559 // within the store and unconditionally live as long as the entire 560 // store itself. This means that there's no worry of the rooting 561 // container going away or otherwise getting deallocated. 562 // 563 // * The `ComponentInstance` container has an invariant that after 564 // creation the component used to create it cannot be changed. This is 565 // enforced through `Pin<&mut ComponentInstance>` which disallows 566 // mutable access to the `component` field, instead only allowing 567 // read-only access. 568 // 569 // Putting all of this together it's not possible for a component, 570 // within a component instance, within a store, to be deallocated or mutated while 571 // a store is in use. Consequently it should be safe to simultaneously 572 // have a borrow to both at the same time, even if the store has a 573 // mutable borrow itself. 574 unsafe { 575 let component: *const Component = component; 576 (&*component, store) 577 } 578 } 579 } 580 581 /// Translates a `CoreDef`, a definition of a core wasm item, to an 582 /// [`Export`] which is the runtime core wasm definition. 583 pub(crate) fn lookup_vmdef( 584 store: &mut StoreOpaque, 585 id: ComponentInstanceId, 586 def: &CoreDef, 587 ) -> vm::Export { 588 match def { 589 CoreDef::Export(e) => lookup_vmexport(store, id, e), 590 CoreDef::Trampoline(idx) => { 591 let funcref = store 592 .store_data_mut() 593 .component_instance_mut(id) 594 .trampoline_func_ref(*idx); 595 // SAFETY: the `funcref` is owned by `store` and is valid within 596 // that store, so it's safe to create a `Func`. 597 vm::Export::Function(unsafe { crate::Func::from_vm_func_ref(store.id(), funcref) }) 598 } 599 CoreDef::InstanceFlags(idx) => { 600 let id = StoreComponentInstanceId::new(store.id(), id); 601 vm::Export::Global(crate::Global::from_component_flags(id, *idx)) 602 } 603 CoreDef::UnsafeIntrinsic(intrinsic) => { 604 let funcref = store 605 .store_data_mut() 606 .component_instance_mut(id) 607 .unsafe_intrinsic_func_ref(*intrinsic); 608 // SAFETY: as above, the `funcref` is owned by `store` and is valid 609 // within that store, so it's safe to create a `Func`. 610 vm::Export::Function(unsafe { crate::Func::from_vm_func_ref(store.id(), funcref) }) 611 } 612 CoreDef::TaskMayBlock => vm::Export::Global(crate::Global::from_task_may_block( 613 StoreComponentInstanceId::new(store.id(), id), 614 )), 615 } 616 } 617 618 /// Translates a `CoreExport<T>`, an export of some core instance within 619 /// this component, to the actual runtime definition of that item. 620 pub(crate) fn lookup_vmexport<T>( 621 store: &mut StoreOpaque, 622 id: ComponentInstanceId, 623 item: &CoreExport<T>, 624 ) -> vm::Export 625 where 626 T: Copy + Into<EntityIndex>, 627 { 628 let store_id = store.id(); 629 let id = store 630 .store_data_mut() 631 .component_instance_mut(id) 632 .instance(item.instance); 633 let (instance, registry) = store.instance_and_module_registry_mut(id); 634 let idx = match &item.item { 635 ExportItem::Index(idx) => (*idx).into(), 636 637 // FIXME: ideally at runtime we don't actually do any name lookups 638 // here. This will only happen when the host supplies an imported 639 // module so while the structure can't be known at compile time we 640 // do know at `InstancePre` time, for example, what all the host 641 // imports are. In theory we should be able to, as part of 642 // `InstancePre` construction, perform all name=>index mappings 643 // during that phase so the actual instantiation of an `InstancePre` 644 // skips all string lookups. This should probably only be 645 // investigated if this becomes a performance issue though. 646 ExportItem::Name(name) => instance.env_module().exports[name], 647 }; 648 // SAFETY: the `store_id` owns this instance and all exports contained 649 // within. 650 unsafe { instance.get_export_by_index_mut(registry, store_id, idx) } 651 } 652 653 fn resource_tables<'a>( 654 calls: &'a mut CallContexts, 655 instance: Pin<&'a mut ComponentInstance>, 656 ) -> ResourceTables<'a> { 657 ResourceTables { 658 host_table: None, 659 calls, 660 guest: Some(instance.instance_states()), 661 } 662 } 663 664 /// Trait used to lookup the export of a component instance. 665 /// 666 /// This trait is used as an implementation detail of [`Instance::get_func`] 667 /// and related `get_*` methods. Notable implementors of this trait are: 668 /// 669 /// * `str` 670 /// * `String` 671 /// * [`ComponentExportIndex`] 672 /// 673 /// Note that this is intended to be a `wasmtime`-sealed trait so it shouldn't 674 /// need to be implemented externally. 675 pub trait InstanceExportLookup { 676 #[doc(hidden)] 677 fn lookup(&self, component: &Component) -> Option<ExportIndex>; 678 } 679 680 impl<T> InstanceExportLookup for &T 681 where 682 T: InstanceExportLookup + ?Sized, 683 { 684 fn lookup(&self, component: &Component) -> Option<ExportIndex> { 685 T::lookup(self, component) 686 } 687 } 688 689 impl InstanceExportLookup for str { 690 fn lookup(&self, component: &Component) -> Option<ExportIndex> { 691 component 692 .env_component() 693 .exports 694 .get(self, &NameMapNoIntern) 695 .copied() 696 } 697 } 698 699 impl InstanceExportLookup for String { 700 fn lookup(&self, component: &Component) -> Option<ExportIndex> { 701 str::lookup(self, component) 702 } 703 } 704 705 struct Instantiator<'a> { 706 component: &'a Component, 707 id: ComponentInstanceId, 708 core_imports: OwnedImports, 709 imports: &'a PrimaryMap<RuntimeImportIndex, RuntimeImport>, 710 } 711 712 pub(crate) enum RuntimeImport { 713 Func(Arc<HostFunc>), 714 Module(Module), 715 Resource { 716 ty: ResourceType, 717 718 // A strong reference to the host function that represents the 719 // destructor for this resource. At this time all resources here are 720 // host-defined resources. Note that this is itself never read because 721 // the funcref below points to it. 722 // 723 // Also note that the `Arc` here is used to support the same host 724 // function being used across multiple instances simultaneously. Or 725 // otherwise this makes `InstancePre::instantiate` possible to create 726 // separate instances all sharing the same host function. 727 dtor: Arc<crate::func::HostFunc>, 728 729 // A raw function which is filled out (including `wasm_call`) which 730 // points to the internals of the `_dtor` field. This is read and 731 // possibly executed by wasm. 732 dtor_funcref: VMFuncRef, 733 }, 734 } 735 736 pub type ImportedResources = PrimaryMap<ResourceIndex, ResourceType>; 737 738 impl<'a> Instantiator<'a> { 739 fn new( 740 component: &'a Component, 741 store: &mut StoreOpaque, 742 imports: &'a Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>, 743 ) -> Result<Instantiator<'a>> { 744 let env_component = component.env_component(); 745 store.register_component(component)?; 746 let imported_resources: ImportedResources = 747 PrimaryMap::with_capacity(env_component.imported_resources.len()); 748 749 let instance = ComponentInstance::new( 750 store.store_data().components.next_component_instance_id(), 751 component, 752 Arc::new(imported_resources), 753 imports, 754 store.traitobj(), 755 )?; 756 let id = store.store_data_mut().push_component_instance(instance); 757 758 Ok(Instantiator { 759 component, 760 imports, 761 core_imports: OwnedImports::empty(), 762 id, 763 }) 764 } 765 766 async fn run<T>( 767 &mut self, 768 store: &mut StoreContextMut<'_, T>, 769 asyncness: Asyncness, 770 ) -> Result<()> { 771 let env_component = self.component.env_component(); 772 773 // Before all initializers are processed configure all destructors for 774 // host-defined resources. No initializer will correspond to these and 775 // it's required to happen before they're needed, so execute this first. 776 for (idx, import) in env_component.imported_resources.iter() { 777 let (ty, func_ref) = match &self.imports[*import] { 778 RuntimeImport::Resource { 779 ty, dtor_funcref, .. 780 } => (*ty, NonNull::from(dtor_funcref)), 781 _ => unreachable!(), 782 }; 783 let i = self.instance_resource_types_mut(store.0).push(ty); 784 assert_eq!(i, idx); 785 self.instance_mut(store.0) 786 .set_resource_destructor(idx, Some(func_ref)); 787 } 788 789 // Next configure all `VMFuncRef`s for trampolines that this component 790 // will require. These functions won't actually get used until their 791 // associated state has been initialized through the global initializers 792 // below, but the funcrefs can all be configured here. 793 for (idx, sig) in env_component.trampolines.iter() { 794 let ptrs = self.component.trampoline_ptrs(idx); 795 let signature = match self.component.signatures().shared_type(*sig) { 796 Some(s) => s, 797 None => panic!("found unregistered signature: {sig:?}"), 798 }; 799 800 self.instance_mut(store.0).set_trampoline( 801 idx, 802 ptrs.wasm_call, 803 ptrs.array_call, 804 signature, 805 ); 806 } 807 808 // Initialize the unsafe intrinsics used by this component, if any. 809 for (i, module_ty) in env_component 810 .unsafe_intrinsics 811 .iter() 812 .enumerate() 813 .filter_map(|(i, ty)| ty.expand().map(|ty| (i, ty))) 814 { 815 let i = u32::try_from(i).unwrap(); 816 let intrinsic = UnsafeIntrinsic::from_u32(i); 817 let ptrs = self.component.unsafe_intrinsic_ptrs(intrinsic).expect( 818 "should have intrinsic pointers given that we assigned the intrinsic a type", 819 ); 820 let shared_ty = self 821 .component 822 .signatures() 823 .shared_type(module_ty) 824 .expect("should have a shared type"); 825 self.instance_mut(store.0).set_intrinsic( 826 intrinsic, 827 ptrs.wasm_call, 828 ptrs.array_call, 829 shared_ty, 830 ); 831 } 832 833 for initializer in env_component.initializers.iter() { 834 match initializer { 835 GlobalInitializer::InstantiateModule(m, component_instance) => { 836 let instance = self.id; 837 let module; 838 let imports = match m { 839 // Since upvars are statically know we know that the 840 // `args` list is already in the right order. 841 InstantiateModule::Static(idx, args) => { 842 module = self.component.static_module(*idx); 843 self.build_imports(store.0, module, args.iter()) 844 } 845 846 // With imports, unlike upvars, we need to do runtime 847 // lookups with strings to determine the order of the 848 // imports since it's whatever the actual module 849 // requires. 850 // 851 // FIXME: see the note in `ExportItem::Name` handling 852 // above for how we ideally shouldn't do string lookup 853 // here. 854 InstantiateModule::Import(idx, args) => { 855 module = match &self.imports[*idx] { 856 RuntimeImport::Module(m) => m, 857 _ => unreachable!(), 858 }; 859 let args = module 860 .imports() 861 .map(|import| &args[import.module()][import.name()]); 862 self.build_imports(store.0, module, args) 863 } 864 }; 865 866 let exit = if let Some(component_instance) = *component_instance 867 && store.0.concurrency_support() 868 { 869 store.0.enter_sync_call( 870 None, 871 false, 872 RuntimeInstance { 873 instance, 874 index: component_instance, 875 }, 876 )?; 877 true 878 } else { 879 false 880 }; 881 882 // Note that the unsafety here should be ok because the 883 // validity of the component means that type-checks have 884 // already been performed. This means that the unsafety due 885 // to imports having the wrong type should not happen here. 886 // 887 // Also note we are calling new_started_impl because we have 888 // already checked for asyncness and are running on a fiber 889 // if required. 890 891 let i = unsafe { 892 crate::Instance::new_started(store, module, imports.as_ref(), asyncness) 893 .await? 894 }; 895 896 if exit { 897 store.0.exit_sync_call(false)?; 898 } 899 900 self.instance_mut(store.0).push_instance_id(i.id()); 901 } 902 903 GlobalInitializer::LowerImport { import, index } => { 904 let func = match &self.imports[*import] { 905 RuntimeImport::Func(func) => func, 906 _ => unreachable!(), 907 }; 908 self.instance_mut(store.0) 909 .set_lowering(*index, func.lowering()); 910 } 911 912 GlobalInitializer::ExtractTable(table) => self.extract_table(store.0, table), 913 914 GlobalInitializer::ExtractMemory(mem) => self.extract_memory(store.0, mem), 915 916 GlobalInitializer::ExtractRealloc(realloc) => { 917 self.extract_realloc(store.0, realloc) 918 } 919 920 GlobalInitializer::ExtractCallback(callback) => { 921 self.extract_callback(store.0, callback) 922 } 923 924 GlobalInitializer::ExtractPostReturn(post_return) => { 925 self.extract_post_return(store.0, post_return) 926 } 927 928 GlobalInitializer::Resource(r) => self.resource(store.0, r), 929 } 930 } 931 Ok(()) 932 } 933 934 fn resource(&mut self, store: &mut StoreOpaque, resource: &Resource) { 935 let dtor = resource 936 .dtor 937 .as_ref() 938 .map(|dtor| lookup_vmdef(store, self.id, dtor)); 939 let dtor = dtor.map(|export| match export { 940 crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store), 941 _ => unreachable!(), 942 }); 943 let index = self 944 .component 945 .env_component() 946 .resource_index(resource.index); 947 let instance = self.instance(store); 948 let ty = ResourceType::guest(store.id(), instance, resource.index); 949 self.instance_mut(store) 950 .set_resource_destructor(index, dtor); 951 let i = self.instance_resource_types_mut(store).push(ty); 952 debug_assert_eq!(i, index); 953 } 954 955 fn extract_memory(&mut self, store: &mut StoreOpaque, memory: &ExtractMemory) { 956 let import = match lookup_vmexport(store, self.id, &memory.export) { 957 crate::runtime::vm::Export::Memory(memory) => memory.vmimport(store), 958 crate::runtime::vm::Export::SharedMemory(_, import) => import, 959 _ => unreachable!(), 960 }; 961 self.instance_mut(store) 962 .set_runtime_memory(memory.index, import.from.as_non_null()); 963 } 964 965 fn extract_realloc(&mut self, store: &mut StoreOpaque, realloc: &ExtractRealloc) { 966 let func_ref = match lookup_vmdef(store, self.id, &realloc.def) { 967 crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store), 968 _ => unreachable!(), 969 }; 970 self.instance_mut(store) 971 .set_runtime_realloc(realloc.index, func_ref); 972 } 973 974 fn extract_callback(&mut self, store: &mut StoreOpaque, callback: &ExtractCallback) { 975 let func_ref = match lookup_vmdef(store, self.id, &callback.def) { 976 crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store), 977 _ => unreachable!(), 978 }; 979 self.instance_mut(store) 980 .set_runtime_callback(callback.index, func_ref); 981 } 982 983 fn extract_post_return(&mut self, store: &mut StoreOpaque, post_return: &ExtractPostReturn) { 984 let func_ref = match lookup_vmdef(store, self.id, &post_return.def) { 985 crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store), 986 _ => unreachable!(), 987 }; 988 self.instance_mut(store) 989 .set_runtime_post_return(post_return.index, func_ref); 990 } 991 992 fn extract_table(&mut self, store: &mut StoreOpaque, table: &ExtractTable) { 993 let export = match lookup_vmexport(store, self.id, &table.export) { 994 crate::runtime::vm::Export::Table(t) => t, 995 _ => unreachable!(), 996 }; 997 let import = export.vmimport(store); 998 self.instance_mut(store) 999 .set_runtime_table(table.index, import); 1000 } 1001 1002 fn build_imports<'b>( 1003 &mut self, 1004 store: &mut StoreOpaque, 1005 module: &Module, 1006 args: impl Iterator<Item = &'b CoreDef>, 1007 ) -> &OwnedImports { 1008 self.core_imports.clear(); 1009 self.core_imports.reserve(module); 1010 let mut imports = module.compiled_module().module().imports(); 1011 1012 for arg in args { 1013 // The general idea of Wasmtime is that at runtime type-checks for 1014 // core wasm instantiations internally within a component are 1015 // unnecessary and superfluous. Naturally though mistakes may be 1016 // made, so double-check this property of wasmtime in debug mode. 1017 1018 if cfg!(debug_assertions) { 1019 let (imp_module, imp_name, expected) = imports.next().unwrap(); 1020 self.assert_type_matches(store, module, arg, imp_module, imp_name, expected); 1021 } 1022 1023 // The unsafety here should be ok since the `export` is loaded 1024 // directly from an instance which should only give us valid export 1025 // items. 1026 let export = lookup_vmdef(store, self.id, arg); 1027 self.core_imports.push_export(store, &export); 1028 } 1029 debug_assert!(imports.next().is_none()); 1030 1031 &self.core_imports 1032 } 1033 1034 fn assert_type_matches( 1035 &self, 1036 store: &mut StoreOpaque, 1037 module: &Module, 1038 arg: &CoreDef, 1039 imp_module: &str, 1040 imp_name: &str, 1041 expected: EntityType, 1042 ) { 1043 let export = lookup_vmdef(store, self.id, arg); 1044 1045 // If this value is a core wasm function then the type check is inlined 1046 // here. This can otherwise fail `Extern::from_wasmtime_export` because 1047 // there's no guarantee that there exists a trampoline for `f` so this 1048 // can't fall through to the case below 1049 if let crate::runtime::vm::Export::Function(f) = &export { 1050 let expected = match expected.unwrap_func() { 1051 EngineOrModuleTypeIndex::Engine(e) => Some(e), 1052 EngineOrModuleTypeIndex::Module(m) => module.signatures().shared_type(m), 1053 EngineOrModuleTypeIndex::RecGroup(_) => unreachable!(), 1054 }; 1055 let actual = unsafe { f.vm_func_ref(store).as_ref().type_index }; 1056 assert_eq!( 1057 expected, 1058 Some(actual), 1059 "type mismatch for import {imp_module:?} {imp_name:?}!!!\n\n\ 1060 expected {:#?}\n\n\ 1061 found {:#?}", 1062 expected.and_then(|e| store.engine().signatures().borrow(e)), 1063 store.engine().signatures().borrow(actual) 1064 ); 1065 return; 1066 } 1067 1068 let val = crate::Extern::from_wasmtime_export(export, store); 1069 let ty = DefinitionType::from(store, &val); 1070 crate::types::matching::MatchCx::new(module.engine()) 1071 .definition(&expected, &ty) 1072 .expect("unexpected typecheck failure"); 1073 } 1074 1075 /// Convenience helper to return the `&ComponentInstance` that's being 1076 /// instantiated. 1077 fn instance<'b>(&self, store: &'b StoreOpaque) -> &'b ComponentInstance { 1078 store.store_data().component_instance(self.id) 1079 } 1080 1081 /// Same as [`Self::instance`], but for mutability. 1082 fn instance_mut<'b>(&self, store: &'b mut StoreOpaque) -> Pin<&'b mut ComponentInstance> { 1083 store.store_data_mut().component_instance_mut(self.id) 1084 } 1085 1086 // NB: This method is only intended to be called during the instantiation 1087 // process because the `Arc::get_mut` here is fallible and won't generally 1088 // succeed once the instance has been handed to the embedder. Before that 1089 // though it should be guaranteed that the single owning reference currently 1090 // lives within the `ComponentInstance` that's being built. 1091 fn instance_resource_types_mut<'b>( 1092 &self, 1093 store: &'b mut StoreOpaque, 1094 ) -> &'b mut ImportedResources { 1095 Arc::get_mut(self.instance_mut(store).resource_types_mut()).unwrap() 1096 } 1097 } 1098 1099 /// A "pre-instantiated" [`Instance`] which has all of its arguments already 1100 /// supplied and is ready to instantiate. 1101 /// 1102 /// This structure represents an efficient form of instantiation where import 1103 /// type-checking and import lookup has all been resolved by the time that this 1104 /// type is created. This type is primarily created through the 1105 /// [`Linker::instantiate_pre`](crate::component::Linker::instantiate_pre) 1106 /// method. 1107 pub struct InstancePre<T: 'static> { 1108 component: Component, 1109 imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>, 1110 resource_types: Arc<PrimaryMap<ResourceIndex, ResourceType>>, 1111 asyncness: Asyncness, 1112 _marker: marker::PhantomData<fn() -> T>, 1113 } 1114 1115 // `InstancePre`'s clone does not require `T: Clone` 1116 impl<T: 'static> Clone for InstancePre<T> { 1117 fn clone(&self) -> Self { 1118 Self { 1119 component: self.component.clone(), 1120 imports: self.imports.clone(), 1121 resource_types: self.resource_types.clone(), 1122 asyncness: self.asyncness, 1123 _marker: self._marker, 1124 } 1125 } 1126 } 1127 1128 impl<T: 'static> InstancePre<T> { 1129 /// This function is `unsafe` since there's no guarantee that the 1130 /// `RuntimeImport` items provided are guaranteed to work with the `T` of 1131 /// the store. 1132 /// 1133 /// Additionally there is no static guarantee that the `imports` provided 1134 /// satisfy the imports of the `component` provided. 1135 pub(crate) unsafe fn new_unchecked( 1136 component: Component, 1137 imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>, 1138 resource_types: Arc<PrimaryMap<ResourceIndex, ResourceType>>, 1139 ) -> InstancePre<T> { 1140 let mut asyncness = Asyncness::No; 1141 for (_, import) in imports.iter() { 1142 asyncness = asyncness 1143 | match import { 1144 RuntimeImport::Func(f) => f.asyncness(), 1145 RuntimeImport::Module(_) => Asyncness::No, 1146 RuntimeImport::Resource { dtor, .. } => dtor.asyncness(), 1147 }; 1148 } 1149 InstancePre { 1150 component, 1151 imports, 1152 resource_types, 1153 asyncness, 1154 _marker: marker::PhantomData, 1155 } 1156 } 1157 1158 /// Returns the underlying component that will be instantiated. 1159 pub fn component(&self) -> &Component { 1160 &self.component 1161 } 1162 1163 #[doc(hidden)] 1164 /// Returns the type at which the underlying component will be 1165 /// instantiated. This contains the instantiated type information which 1166 /// was determined by the Linker. 1167 pub fn instance_type(&self) -> InstanceType<'_> { 1168 InstanceType { 1169 types: &self.component.types(), 1170 resources: &self.resource_types, 1171 } 1172 } 1173 1174 /// Returns the underlying engine. 1175 pub fn engine(&self) -> &Engine { 1176 self.component.engine() 1177 } 1178 1179 /// Performs the instantiation process into the store specified. 1180 // 1181 // TODO: needs more docs 1182 pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> { 1183 let store = store.as_context_mut(); 1184 1185 // If this instance requires an async host, set that flag in the store, 1186 // and then afterwards assert nothing else in the store, nor this 1187 // instance, required async. 1188 store.0.set_async_required(self.asyncness); 1189 store.0.validate_sync_call()?; 1190 1191 vm::assert_ready(self._instantiate(store, Asyncness::No)) 1192 } 1193 /// Performs the instantiation process into the store specified. 1194 /// 1195 /// Exactly like [`Self::instantiate`] except for use on async stores. 1196 // 1197 // TODO: needs more docs 1198 #[cfg(feature = "async")] 1199 pub async fn instantiate_async(&self, store: impl AsContextMut<Data = T>) -> Result<Instance> { 1200 self._instantiate(store, Asyncness::Yes).await 1201 } 1202 1203 async fn _instantiate( 1204 &self, 1205 mut store: impl AsContextMut<Data = T>, 1206 asyncness: Asyncness, 1207 ) -> Result<Instance> { 1208 let mut store = store.as_context_mut(); 1209 store.0.set_async_required(self.asyncness); 1210 store 1211 .engine() 1212 .allocator() 1213 .increment_component_instance_count()?; 1214 let mut instantiator = Instantiator::new(&self.component, store.0, &self.imports)?; 1215 instantiator.run(&mut store, asyncness).await.map_err(|e| { 1216 store 1217 .engine() 1218 .allocator() 1219 .decrement_component_instance_count(); 1220 e 1221 })?; 1222 1223 let instance = Instance::from_wasmtime(store.0, instantiator.id); 1224 store.0.push_component_instance(instance); 1225 Ok(instance) 1226 } 1227 } 1228