1 use crate::component::func::HostFunc;
2 use crate::component::matching::InstanceType;
3 use crate::component::store::{ComponentInstanceId, StoreComponentInstanceId};
4 use crate::component::{
5     Component, ComponentExportIndex, ComponentNamedList, Func, Lift, Lower, ResourceType,
6     TypedFunc, types::ComponentItem,
7 };
8 use crate::instance::OwnedImports;
9 use crate::linker::DefinitionType;
10 use crate::prelude::*;
11 use crate::runtime::vm::VMFuncRef;
12 use crate::runtime::vm::component::{ComponentInstance, OwnedComponentInstance};
13 use crate::store::StoreOpaque;
14 use crate::{AsContext, AsContextMut, Engine, Module, StoreContextMut};
15 use alloc::sync::Arc;
16 use core::marker;
17 use core::ptr::NonNull;
18 use wasmtime_environ::{EngineOrModuleTypeIndex, component::*};
19 use wasmtime_environ::{EntityType, PrimaryMap};
20 
21 /// An instantiated component.
22 ///
23 /// This type represents an instantiated [`Component`](super::Component).
24 /// Instances have exports which can be accessed through functions such as
25 /// [`Instance::get_func`] or [`Instance::get_export`]. Instances are owned by a
26 /// [`Store`](crate::Store) and all methods require a handle to the store.
27 ///
28 /// Component instances are created through
29 /// [`Linker::instantiate`](super::Linker::instantiate) and its family of
30 /// methods.
31 ///
32 /// This type is similar to the core wasm version
33 /// [`wasmtime::Instance`](crate::Instance) except that it represents an
34 /// instantiated component instead of an instantiated module.
35 #[derive(Copy, Clone, Debug)]
36 #[repr(transparent)]
37 pub struct Instance {
38     id: StoreComponentInstanceId,
39 }
40 
41 // Double-check that the C representation in `component/instance.h` matches our
42 // in-Rust representation here in terms of size/alignment/etc.
43 const _: () = {
44     #[repr(C)]
45     struct C(u64, u32);
46     assert!(core::mem::size_of::<C>() == core::mem::size_of::<Instance>());
47     assert!(core::mem::align_of::<C>() == core::mem::align_of::<Instance>());
48     assert!(core::mem::offset_of!(Instance, id) == 0);
49 };
50 
51 impl Instance {
52     /// Creates a raw `Instance` from the internal identifiers within the store.
53     ///
54     /// # Safety
55     ///
56     /// The safety of this function relies on `id` belonging to the instance
57     /// within `store`.
58     pub(crate) unsafe fn from_wasmtime(store: &StoreOpaque, id: ComponentInstanceId) -> Instance {
59         Instance {
60             id: StoreComponentInstanceId::new(store.id(), id),
61         }
62     }
63 
64     /// Looks up an exported function by name within this [`Instance`].
65     ///
66     /// The `store` argument provided must be the store that this instance
67     /// lives within and the `name` argument is the lookup key by which to find
68     /// the exported function. If the function is found then `Some` is returned
69     /// and otherwise `None` is returned.
70     ///
71     /// The `name` here can be a string such as `&str` or it can be a
72     /// [`ComponentExportIndex`] which is loaded prior from a [`Component`].
73     ///
74     /// # Panics
75     ///
76     /// Panics if `store` does not own this instance.
77     ///
78     /// # Examples
79     ///
80     /// Looking up a function which is exported from the root of a component:
81     ///
82     /// ```
83     /// use wasmtime::{Engine, Store};
84     /// use wasmtime::component::{Component, Linker};
85     ///
86     /// # fn main() -> wasmtime::Result<()> {
87     /// let engine = Engine::default();
88     /// let component = Component::new(
89     ///     &engine,
90     ///     r#"
91     ///         (component
92     ///             (core module $m
93     ///                 (func (export "f"))
94     ///             )
95     ///             (core instance $i (instantiate $m))
96     ///             (func (export "f")
97     ///                 (canon lift (core func $i "f")))
98     ///         )
99     ///     "#,
100     /// )?;
101     ///
102     /// // Look up the function by name
103     /// let mut store = Store::new(&engine, ());
104     /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
105     /// let func = instance.get_func(&mut store, "f").unwrap();
106     ///
107     /// // The function can also be looked up by an index via a precomputed index.
108     /// let export = component.get_export_index(None, "f").unwrap();
109     /// let func = instance.get_func(&mut store, &export).unwrap();
110     /// # Ok(())
111     /// # }
112     /// ```
113     ///
114     /// Looking up a function which is exported from a nested instance:
115     ///
116     /// ```
117     /// use wasmtime::{Engine, Store};
118     /// use wasmtime::component::{Component, Linker};
119     ///
120     /// # fn main() -> wasmtime::Result<()> {
121     /// let engine = Engine::default();
122     /// let component = Component::new(
123     ///     &engine,
124     ///     r#"
125     ///         (component
126     ///             (core module $m
127     ///                 (func (export "f"))
128     ///             )
129     ///             (core instance $i (instantiate $m))
130     ///             (func $f
131     ///                 (canon lift (core func $i "f")))
132     ///
133     ///             (instance $i
134     ///                 (export "f" (func $f)))
135     ///             (export "i" (instance $i))
136     ///         )
137     ///     "#,
138     /// )?;
139     ///
140     /// // First look up the exported instance, then use that to lookup the
141     /// // exported function.
142     /// let instance_index = component.get_export_index(None, "i").unwrap();
143     /// let func_index = component.get_export_index(Some(&instance_index), "f").unwrap();
144     ///
145     /// // Then use `func_index` at runtime.
146     /// let mut store = Store::new(&engine, ());
147     /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
148     /// let func = instance.get_func(&mut store, &func_index).unwrap();
149     ///
150     /// // Alternatively the `instance` can be used directly in conjunction with
151     /// // the `get_export_index` method.
152     /// let instance_index = instance.get_export_index(&mut store, None, "i").unwrap();
153     /// let func_index = instance.get_export_index(&mut store, Some(&instance_index), "f").unwrap();
154     /// let func = instance.get_func(&mut store, &func_index).unwrap();
155     /// # Ok(())
156     /// # }
157     /// ```
158     pub fn get_func(
159         &self,
160         mut store: impl AsContextMut,
161         name: impl InstanceExportLookup,
162     ) -> Option<Func> {
163         let store = store.as_context_mut().0;
164         let instance = &store[self.id];
165         let component = instance.component();
166 
167         // Validate that `name` exists within `self.`
168         let index = name.lookup(component)?;
169 
170         // Validate that `index` is indeed a lifted function.
171         match &component.env_component().export_items[index] {
172             Export::LiftedFunction { .. } => {}
173             _ => return None,
174         }
175 
176         // And package up the indices!
177         Some(Func::from_lifted_func(*self, index))
178     }
179 
180     /// Looks up an exported [`Func`] value by name and with its type.
181     ///
182     /// This function is a convenience wrapper over [`Instance::get_func`] and
183     /// [`Func::typed`]. For more information see the linked documentation.
184     ///
185     /// Returns an error if `name` isn't a function export or if the export's
186     /// type did not match `Params` or `Results`
187     ///
188     /// # Panics
189     ///
190     /// Panics if `store` does not own this instance.
191     pub fn get_typed_func<Params, Results>(
192         &self,
193         mut store: impl AsContextMut,
194         name: impl InstanceExportLookup,
195     ) -> Result<TypedFunc<Params, Results>>
196     where
197         Params: ComponentNamedList + Lower,
198         Results: ComponentNamedList + Lift,
199     {
200         let f = self
201             .get_func(store.as_context_mut(), name)
202             .ok_or_else(|| anyhow!("failed to find function export"))?;
203         Ok(f.typed::<Params, Results>(store)
204             .with_context(|| format!("failed to convert function to given type"))?)
205     }
206 
207     /// Looks up an exported module by name within this [`Instance`].
208     ///
209     /// The `store` argument provided must be the store that this instance
210     /// lives within and the `name` argument is the lookup key by which to find
211     /// the exported module. If the module is found then `Some` is returned
212     /// and otherwise `None` is returned.
213     ///
214     /// The `name` here can be a string such as `&str` or it can be a
215     /// [`ComponentExportIndex`] which is loaded prior from a [`Component`].
216     ///
217     /// For some examples see [`Instance::get_func`] for loading values from a
218     /// component.
219     ///
220     /// # Panics
221     ///
222     /// Panics if `store` does not own this instance.
223     pub fn get_module(
224         &self,
225         mut store: impl AsContextMut,
226         name: impl InstanceExportLookup,
227     ) -> Option<Module> {
228         let store = store.as_context_mut().0;
229         let (instance, export) = self.lookup_export(store, name)?;
230         match export {
231             Export::ModuleStatic { index, .. } => {
232                 Some(instance.component().static_module(*index).clone())
233             }
234             Export::ModuleImport { import, .. } => match instance.runtime_import(*import) {
235                 RuntimeImport::Module(m) => Some(m.clone()),
236                 _ => unreachable!(),
237             },
238             _ => None,
239         }
240     }
241 
242     /// Looks up an exported resource type by name within this [`Instance`].
243     ///
244     /// The `store` argument provided must be the store that this instance
245     /// lives within and the `name` argument is the lookup key by which to find
246     /// the exported resource. If the resource is found then `Some` is returned
247     /// and otherwise `None` is returned.
248     ///
249     /// The `name` here can be a string such as `&str` or it can be a
250     /// [`ComponentExportIndex`] which is loaded prior from a [`Component`].
251     ///
252     /// For some examples see [`Instance::get_func`] for loading values from a
253     /// component.
254     ///
255     /// # Panics
256     ///
257     /// Panics if `store` does not own this instance.
258     pub fn get_resource(
259         &self,
260         mut store: impl AsContextMut,
261         name: impl InstanceExportLookup,
262     ) -> Option<ResourceType> {
263         let store = store.as_context_mut().0;
264         let (instance, export) = self.lookup_export(store, name)?;
265         match export {
266             Export::Type(TypeDef::Resource(id)) => {
267                 Some(InstanceType::new(instance).resource_type(*id))
268             }
269             Export::Type(_)
270             | Export::LiftedFunction { .. }
271             | Export::ModuleStatic { .. }
272             | Export::ModuleImport { .. }
273             | Export::Instance { .. } => None,
274         }
275     }
276 
277     /// A methods similar to [`Component::get_export`] except for this
278     /// instance.
279     ///
280     /// This method will lookup the `name` provided within the `instance`
281     /// provided and return a [`ComponentItem`] describing the export,
282     /// and [`ComponentExportIndex`] which can be passed other `get_*`
283     /// functions like [`Instance::get_func`].
284     ///
285     /// The [`ComponentItem`] is more expensive to compute than the
286     /// [`ComponentExportIndex`]. If you are not consuming the
287     /// [`ComponentItem`], use [`Instance::get_export_index`] instead.
288     ///
289     /// # Panics
290     ///
291     /// Panics if `store` does not own this instance.
292     pub fn get_export(
293         &self,
294         mut store: impl AsContextMut,
295         instance: Option<&ComponentExportIndex>,
296         name: &str,
297     ) -> Option<(ComponentItem, ComponentExportIndex)> {
298         self._get_export(store.as_context_mut().0, instance, name)
299     }
300 
301     fn _get_export(
302         &self,
303         store: &StoreOpaque,
304         instance: Option<&ComponentExportIndex>,
305         name: &str,
306     ) -> Option<(ComponentItem, ComponentExportIndex)> {
307         let data = &store[self.id()];
308         let component = data.component();
309         let index = component.lookup_export_index(instance, name)?;
310         let item = ComponentItem::from_export(
311             &store.engine(),
312             &component.env_component().export_items[index],
313             &InstanceType::new(data),
314         );
315         Some((
316             item,
317             ComponentExportIndex {
318                 id: data.component().id(),
319                 index,
320             },
321         ))
322     }
323 
324     /// A methods similar to [`Component::get_export_index`] except for this
325     /// instance.
326     ///
327     /// This method will lookup the `name` provided within the `instance`
328     /// provided and return a [`ComponentExportIndex`] which can be passed
329     /// other `get_*` functions like [`Instance::get_func`].
330     ///
331     /// If you need the [`ComponentItem`] corresponding to this export, use
332     /// the [`Instance::get_export`] instead.
333     ///
334     /// # Panics
335     ///
336     /// Panics if `store` does not own this instance.
337     pub fn get_export_index(
338         &self,
339         mut store: impl AsContextMut,
340         instance: Option<&ComponentExportIndex>,
341         name: &str,
342     ) -> Option<ComponentExportIndex> {
343         let data = &store.as_context_mut()[self.id()];
344         let index = data.component().lookup_export_index(instance, name)?;
345         Some(ComponentExportIndex {
346             id: data.component().id(),
347             index,
348         })
349     }
350 
351     fn lookup_export<'a>(
352         &self,
353         store: &'a StoreOpaque,
354         name: impl InstanceExportLookup,
355     ) -> Option<(&'a ComponentInstance, &'a Export)> {
356         let data = &store[self.id()];
357         let index = name.lookup(data.component())?;
358         Some((data, &data.component().env_component().export_items[index]))
359     }
360 
361     /// Returns the [`InstancePre`] that was used to create this instance.
362     pub fn instance_pre<T>(&self, store: impl AsContext<Data = T>) -> InstancePre<T> {
363         // This indexing operation asserts the Store owns the Instance.
364         // Therefore, the InstancePre<T> must match the Store<T>.
365         let data = &store.as_context()[self.id()];
366 
367         // SAFETY: calling this method safely here relies on matching the `T`
368         // in `InstancePre<T>` to the store itself, which is happening in the
369         // type signature just above by ensuring the store's data is `T` which
370         // matches the return value.
371         unsafe { data.instance_pre() }
372     }
373 
374     /// Returns the VM/runtime state for this instance as belonging to the
375     /// store provided.
376     pub(crate) fn instance_ptr(&self, store: &StoreOpaque) -> NonNull<ComponentInstance> {
377         self.id.assert_belongs_to(store.id());
378         store.component_instance_ptr(self.id.instance())
379     }
380 
381     pub(crate) fn id(&self) -> StoreComponentInstanceId {
382         self.id
383     }
384 }
385 
386 /// Trait used to lookup the export of a component instance.
387 ///
388 /// This trait is used as an implementation detail of [`Instance::get_func`]
389 /// and related `get_*` methods. Notable implementors of this trait are:
390 ///
391 /// * `str`
392 /// * `String`
393 /// * [`ComponentExportIndex`]
394 ///
395 /// Note that this is intended to be a `wasmtime`-sealed trait so it shouldn't
396 /// need to be implemented externally.
397 pub trait InstanceExportLookup {
398     #[doc(hidden)]
399     fn lookup(&self, component: &Component) -> Option<ExportIndex>;
400 }
401 
402 impl<T> InstanceExportLookup for &T
403 where
404     T: InstanceExportLookup + ?Sized,
405 {
406     fn lookup(&self, component: &Component) -> Option<ExportIndex> {
407         T::lookup(self, component)
408     }
409 }
410 
411 impl InstanceExportLookup for str {
412     fn lookup(&self, component: &Component) -> Option<ExportIndex> {
413         component
414             .env_component()
415             .exports
416             .get(self, &NameMapNoIntern)
417             .copied()
418     }
419 }
420 
421 impl InstanceExportLookup for String {
422     fn lookup(&self, component: &Component) -> Option<ExportIndex> {
423         str::lookup(self, component)
424     }
425 }
426 
427 struct Instantiator<'a> {
428     component: &'a Component,
429     id: ComponentInstanceId,
430     core_imports: OwnedImports,
431     imports: &'a PrimaryMap<RuntimeImportIndex, RuntimeImport>,
432 }
433 
434 pub(crate) enum RuntimeImport {
435     Func(Arc<HostFunc>),
436     Module(Module),
437     Resource {
438         ty: ResourceType,
439 
440         // A strong reference to the host function that represents the
441         // destructor for this resource. At this time all resources here are
442         // host-defined resources. Note that this is itself never read because
443         // the funcref below points to it.
444         //
445         // Also note that the `Arc` here is used to support the same host
446         // function being used across multiple instances simultaneously. Or
447         // otherwise this makes `InstancePre::instantiate` possible to create
448         // separate instances all sharing the same host function.
449         _dtor: Arc<crate::func::HostFunc>,
450 
451         // A raw function which is filled out (including `wasm_call`) which
452         // points to the internals of the `_dtor` field. This is read and
453         // possibly executed by wasm.
454         dtor_funcref: VMFuncRef,
455     },
456 }
457 
458 pub type ImportedResources = PrimaryMap<ResourceIndex, ResourceType>;
459 
460 impl<'a> Instantiator<'a> {
461     fn new(
462         component: &'a Component,
463         store: &mut StoreOpaque,
464         imports: &'a Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
465     ) -> Instantiator<'a> {
466         let env_component = component.env_component();
467         store.modules_mut().register_component(component);
468         let imported_resources: ImportedResources =
469             PrimaryMap::with_capacity(env_component.imported_resources.len());
470 
471         let instance = OwnedComponentInstance::new(
472             store.store_data().components.next_component_instance_id(),
473             component,
474             Arc::new(imported_resources),
475             imports,
476             store.traitobj(),
477         );
478         let id = store.store_data_mut().push_component_instance(instance);
479 
480         Instantiator {
481             component,
482             imports,
483             core_imports: OwnedImports::empty(),
484             id,
485         }
486     }
487 
488     fn run<T>(&mut self, store: &mut StoreContextMut<'_, T>) -> Result<()> {
489         let env_component = self.component.env_component();
490 
491         // Before all initializers are processed configure all destructors for
492         // host-defined resources. No initializer will correspond to these and
493         // it's required to happen before they're needed, so execute this first.
494         for (idx, import) in env_component.imported_resources.iter() {
495             let (ty, func_ref) = match &self.imports[*import] {
496                 RuntimeImport::Resource {
497                     ty, dtor_funcref, ..
498                 } => (*ty, NonNull::from(dtor_funcref)),
499                 _ => unreachable!(),
500             };
501             let i = self.instance_resource_types_mut(store.0).push(ty);
502             assert_eq!(i, idx);
503             self.instance_mut(store.0)
504                 .set_resource_destructor(idx, Some(func_ref));
505         }
506 
507         // Next configure all `VMFuncRef`s for trampolines that this component
508         // will require. These functions won't actually get used until their
509         // associated state has been initialized through the global initializers
510         // below, but the funcrefs can all be configured here.
511         for (idx, sig) in env_component.trampolines.iter() {
512             let ptrs = self.component.trampoline_ptrs(idx);
513             let signature = match self.component.signatures().shared_type(*sig) {
514                 Some(s) => s,
515                 None => panic!("found unregistered signature: {sig:?}"),
516             };
517 
518             self.instance_mut(store.0).set_trampoline(
519                 idx,
520                 ptrs.wasm_call,
521                 ptrs.array_call,
522                 signature,
523             );
524         }
525 
526         for initializer in env_component.initializers.iter() {
527             match initializer {
528                 GlobalInitializer::InstantiateModule(m) => {
529                     let module;
530                     let imports = match m {
531                         // Since upvars are statically know we know that the
532                         // `args` list is already in the right order.
533                         InstantiateModule::Static(idx, args) => {
534                             module = self.component.static_module(*idx);
535                             self.build_imports(store.0, module, args.iter())
536                         }
537 
538                         // With imports, unlike upvars, we need to do runtime
539                         // lookups with strings to determine the order of the
540                         // imports since it's whatever the actual module
541                         // requires.
542                         //
543                         // FIXME: see the note in `ExportItem::Name` handling
544                         // above for how we ideally shouldn't do string lookup
545                         // here.
546                         InstantiateModule::Import(idx, args) => {
547                             module = match &self.imports[*idx] {
548                                 RuntimeImport::Module(m) => m,
549                                 _ => unreachable!(),
550                             };
551                             let args = module
552                                 .imports()
553                                 .map(|import| &args[import.module()][import.name()]);
554                             self.build_imports(store.0, module, args)
555                         }
556                     };
557 
558                     // Note that the unsafety here should be ok because the
559                     // validity of the component means that type-checks have
560                     // already been performed. This means that the unsafety due
561                     // to imports having the wrong type should not happen here.
562                     //
563                     // Also note we are calling new_started_impl because we have
564                     // already checked for asyncness and are running on a fiber
565                     // if required.
566 
567                     let i = unsafe {
568                         crate::Instance::new_started_impl(store, module, imports.as_ref())?
569                     };
570                     self.instance_mut(store.0).push_instance_id(i.id());
571                 }
572 
573                 GlobalInitializer::LowerImport { import, index } => {
574                     let func = match &self.imports[*import] {
575                         RuntimeImport::Func(func) => func,
576                         _ => unreachable!(),
577                     };
578                     self.instance_mut(store.0)
579                         .set_lowering(*index, func.lowering());
580                 }
581 
582                 GlobalInitializer::ExtractTable(table) => self.extract_table(store.0, table),
583 
584                 GlobalInitializer::ExtractMemory(mem) => self.extract_memory(store.0, mem),
585 
586                 GlobalInitializer::ExtractRealloc(realloc) => {
587                     self.extract_realloc(store.0, realloc)
588                 }
589 
590                 GlobalInitializer::ExtractCallback(callback) => {
591                     self.extract_callback(store.0, callback)
592                 }
593 
594                 GlobalInitializer::ExtractPostReturn(post_return) => {
595                     self.extract_post_return(store.0, post_return)
596                 }
597 
598                 GlobalInitializer::Resource(r) => self.resource(store.0, r),
599             }
600         }
601         Ok(())
602     }
603 
604     fn resource(&mut self, store: &mut StoreOpaque, resource: &Resource) {
605         let instance = self.instance(store);
606         let dtor = resource
607             .dtor
608             .as_ref()
609             .map(|dtor| instance.lookup_def(store, dtor));
610         let dtor = dtor.map(|export| match export {
611             crate::runtime::vm::Export::Function(f) => f.func_ref,
612             _ => unreachable!(),
613         });
614         let index = self
615             .component
616             .env_component()
617             .resource_index(resource.index);
618         let ty = ResourceType::guest(store.id(), instance, resource.index);
619         self.instance_mut(store)
620             .set_resource_destructor(index, dtor);
621         let i = self.instance_resource_types_mut(store).push(ty);
622         debug_assert_eq!(i, index);
623     }
624 
625     fn extract_memory(&mut self, store: &mut StoreOpaque, memory: &ExtractMemory) {
626         let mem = match self.instance(store).lookup_export(store, &memory.export) {
627             crate::runtime::vm::Export::Memory(m) => m,
628             _ => unreachable!(),
629         };
630         self.instance_mut(store)
631             .set_runtime_memory(memory.index, mem.definition);
632     }
633 
634     fn extract_realloc(&mut self, store: &mut StoreOpaque, realloc: &ExtractRealloc) {
635         let func_ref = match self.instance(store).lookup_def(store, &realloc.def) {
636             crate::runtime::vm::Export::Function(f) => f.func_ref,
637             _ => unreachable!(),
638         };
639         self.instance_mut(store)
640             .set_runtime_realloc(realloc.index, func_ref);
641     }
642 
643     fn extract_callback(&mut self, store: &mut StoreOpaque, callback: &ExtractCallback) {
644         let func_ref = match self.instance(store).lookup_def(store, &callback.def) {
645             crate::runtime::vm::Export::Function(f) => f.func_ref,
646             _ => unreachable!(),
647         };
648         self.instance_mut(store)
649             .set_runtime_callback(callback.index, func_ref);
650     }
651 
652     fn extract_post_return(&mut self, store: &mut StoreOpaque, post_return: &ExtractPostReturn) {
653         let func_ref = match self.instance(store).lookup_def(store, &post_return.def) {
654             crate::runtime::vm::Export::Function(f) => f.func_ref,
655             _ => unreachable!(),
656         };
657         self.instance_mut(store)
658             .set_runtime_post_return(post_return.index, func_ref);
659     }
660 
661     fn extract_table(&mut self, store: &mut StoreOpaque, table: &ExtractTable) {
662         let export = match self.instance(store).lookup_export(store, &table.export) {
663             crate::runtime::vm::Export::Table(t) => t,
664             _ => unreachable!(),
665         };
666         self.instance_mut(store).set_runtime_table(
667             table.index,
668             export.definition,
669             export.vmctx,
670             export.index,
671         );
672     }
673 
674     fn build_imports<'b>(
675         &mut self,
676         store: &StoreOpaque,
677         module: &Module,
678         args: impl Iterator<Item = &'b CoreDef>,
679     ) -> &OwnedImports {
680         self.core_imports.clear();
681         self.core_imports.reserve(module);
682         let mut imports = module.compiled_module().module().imports();
683 
684         for arg in args {
685             // The general idea of Wasmtime is that at runtime type-checks for
686             // core wasm instantiations internally within a component are
687             // unnecessary and superfluous. Naturally though mistakes may be
688             // made, so double-check this property of wasmtime in debug mode.
689 
690             if cfg!(debug_assertions) {
691                 let (imp_module, imp_name, expected) = imports.next().unwrap();
692                 self.assert_type_matches(store, module, arg, imp_module, imp_name, expected);
693             }
694 
695             // The unsafety here should be ok since the `export` is loaded
696             // directly from an instance which should only give us valid export
697             // items.
698             let export = self.instance(store).lookup_def(store, arg);
699             unsafe {
700                 self.core_imports.push_export(&export);
701             }
702         }
703         debug_assert!(imports.next().is_none());
704 
705         &self.core_imports
706     }
707 
708     fn assert_type_matches(
709         &self,
710         store: &StoreOpaque,
711         module: &Module,
712         arg: &CoreDef,
713         imp_module: &str,
714         imp_name: &str,
715         expected: EntityType,
716     ) {
717         let export = self.instance(store).lookup_def(store, arg);
718 
719         // If this value is a core wasm function then the type check is inlined
720         // here. This can otherwise fail `Extern::from_wasmtime_export` because
721         // there's no guarantee that there exists a trampoline for `f` so this
722         // can't fall through to the case below
723         if let crate::runtime::vm::Export::Function(f) = &export {
724             let expected = match expected.unwrap_func() {
725                 EngineOrModuleTypeIndex::Engine(e) => Some(e),
726                 EngineOrModuleTypeIndex::Module(m) => module.signatures().shared_type(m),
727                 EngineOrModuleTypeIndex::RecGroup(_) => unreachable!(),
728             };
729             let actual = unsafe { f.func_ref.as_ref().type_index };
730             assert_eq!(
731                 expected,
732                 Some(actual),
733                 "type mismatch for import {imp_module:?} {imp_name:?}!!!\n\n\
734                  expected {:#?}\n\n\
735                  found {:#?}",
736                 expected.and_then(|e| store.engine().signatures().borrow(e)),
737                 store.engine().signatures().borrow(actual)
738             );
739             return;
740         }
741 
742         let val = unsafe { crate::Extern::from_wasmtime_export(export, store) };
743         let ty = DefinitionType::from(store, &val);
744         crate::types::matching::MatchCx::new(module.engine())
745             .definition(&expected, &ty)
746             .expect("unexpected typecheck failure");
747     }
748 
749     /// Convenience helper to return the `&ComponentInstance` that's being
750     /// instantiated.
751     fn instance<'b>(&self, store: &'b StoreOpaque) -> &'b ComponentInstance {
752         store.store_data().component_instance(self.id)
753     }
754 
755     /// Same as [`Self::instance`], but for mutability.
756     fn instance_mut<'b>(&self, store: &'b mut StoreOpaque) -> &'b mut ComponentInstance {
757         store.store_data_mut().component_instance_mut(self.id)
758     }
759 
760     // NB: This method is only intended to be called during the instantiation
761     // process because the `Arc::get_mut` here is fallible and won't generally
762     // succeed once the instance has been handed to the embedder. Before that
763     // though it should be guaranteed that the single owning reference currently
764     // lives within the `ComponentInstance` that's being built.
765     fn instance_resource_types_mut<'b>(
766         &self,
767         store: &'b mut StoreOpaque,
768     ) -> &'b mut ImportedResources {
769         Arc::get_mut(self.instance_mut(store).resource_types_mut()).unwrap()
770     }
771 }
772 
773 /// A "pre-instantiated" [`Instance`] which has all of its arguments already
774 /// supplied and is ready to instantiate.
775 ///
776 /// This structure represents an efficient form of instantiation where import
777 /// type-checking and import lookup has all been resolved by the time that this
778 /// type is created. This type is primarily created through the
779 /// [`Linker::instantiate_pre`](crate::component::Linker::instantiate_pre)
780 /// method.
781 pub struct InstancePre<T: 'static> {
782     component: Component,
783     imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
784     resource_types: Arc<PrimaryMap<ResourceIndex, ResourceType>>,
785     _marker: marker::PhantomData<fn() -> T>,
786 }
787 
788 // `InstancePre`'s clone does not require `T: Clone`
789 impl<T: 'static> Clone for InstancePre<T> {
790     fn clone(&self) -> Self {
791         Self {
792             component: self.component.clone(),
793             imports: self.imports.clone(),
794             resource_types: self.resource_types.clone(),
795             _marker: self._marker,
796         }
797     }
798 }
799 
800 impl<T: 'static> InstancePre<T> {
801     /// This function is `unsafe` since there's no guarantee that the
802     /// `RuntimeImport` items provided are guaranteed to work with the `T` of
803     /// the store.
804     ///
805     /// Additionally there is no static guarantee that the `imports` provided
806     /// satisfy the imports of the `component` provided.
807     pub(crate) unsafe fn new_unchecked(
808         component: Component,
809         imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
810         resource_types: Arc<PrimaryMap<ResourceIndex, ResourceType>>,
811     ) -> InstancePre<T> {
812         InstancePre {
813             component,
814             imports,
815             resource_types,
816             _marker: marker::PhantomData,
817         }
818     }
819 
820     /// Returns the underlying component that will be instantiated.
821     pub fn component(&self) -> &Component {
822         &self.component
823     }
824 
825     #[doc(hidden)]
826     /// Returns the type at which the underlying component will be
827     /// instantiated. This contains the instantiated type information which
828     /// was determined by the Linker.
829     pub fn instance_type(&self) -> InstanceType<'_> {
830         InstanceType {
831             types: &self.component.types(),
832             resources: &self.resource_types,
833         }
834     }
835 
836     /// Returns the underlying engine.
837     pub fn engine(&self) -> &Engine {
838         self.component.engine()
839     }
840 
841     /// Performs the instantiation process into the store specified.
842     //
843     // TODO: needs more docs
844     pub fn instantiate(&self, store: impl AsContextMut<Data = T>) -> Result<Instance> {
845         assert!(
846             !store.as_context().async_support(),
847             "must use async instantiation when async support is enabled"
848         );
849         self.instantiate_impl(store)
850     }
851     /// Performs the instantiation process into the store specified.
852     ///
853     /// Exactly like [`Self::instantiate`] except for use on async stores.
854     //
855     // TODO: needs more docs
856     #[cfg(feature = "async")]
857     pub async fn instantiate_async(
858         &self,
859         mut store: impl AsContextMut<Data = T>,
860     ) -> Result<Instance>
861     where
862         T: Send,
863     {
864         let mut store = store.as_context_mut();
865         assert!(
866             store.0.async_support(),
867             "must use sync instantiation when async support is disabled"
868         );
869         store.on_fiber(|store| self.instantiate_impl(store)).await?
870     }
871 
872     fn instantiate_impl(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
873         let mut store = store.as_context_mut();
874         store
875             .engine()
876             .allocator()
877             .increment_component_instance_count()?;
878         let mut instantiator = Instantiator::new(&self.component, store.0, &self.imports);
879         instantiator.run(&mut store).map_err(|e| {
880             store
881                 .engine()
882                 .allocator()
883                 .decrement_component_instance_count();
884             e
885         })?;
886         // SAFETY: `from_wasmtime` requires that `id` belongs to the store
887         // provided, and it was just inserted above so the condition should be
888         // satisfied.
889         let instance = unsafe { Instance::from_wasmtime(store.0, instantiator.id) };
890         store.0.push_component_instance(instance);
891         Ok(instance)
892     }
893 }
894