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