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