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