Skip to main content

wasmtime/runtime/component/
instance.rs

1use crate::component::func::HostFunc;
2use crate::component::matching::InstanceType;
3use crate::component::store::{ComponentInstanceId, StoreComponentInstanceId};
4use crate::component::{
5    Component, ComponentExportIndex, ComponentNamedList, Func, Lift, Lower, ResourceType,
6    TypedFunc, types::ComponentItem,
7};
8use crate::component::{ExportLookup, RuntimeInstance};
9use crate::instance::OwnedImports;
10use crate::linker::DefinitionType;
11use crate::prelude::*;
12use crate::runtime::vm::VMTypedResource;
13use crate::runtime::vm::component::{ComponentInstance, TypedResourceIndex};
14use crate::runtime::vm::{self, UncaughtException, VMFuncRef, VMStore};
15use crate::store::{AsStoreOpaque, Asyncness, StoreOpaque};
16use crate::{AsContext, AsContextMut, Engine, Module, StoreContextMut};
17use alloc::sync::Arc;
18use core::marker;
19use core::pin::Pin;
20use core::ptr::NonNull;
21use wasmtime_environ::{EngineOrModuleTypeIndex, component::*};
22use wasmtime_environ::{EntityIndex, 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)]
40pub 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.
46const _: () = {
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
54impl 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(&self, mut store: impl AsContextMut, name: impl ExportLookup) -> Option<Func> {
157        let store = store.as_context_mut().0;
158        let instance = self.id.get(store);
159        let component = instance.component();
160
161        // Validate that `name` exists within `self.`
162        let index = name.lookup(component, None)?;
163
164        // Validate that `index` is indeed a lifted function.
165        match &component.env_component().export_items[index] {
166            Export::LiftedFunction { .. } => {}
167            _ => return None,
168        }
169
170        // And package up the indices!
171        Some(Func::from_lifted_func(store, *self, index))
172    }
173
174    /// Looks up an exported [`Func`] value by name and with its type.
175    ///
176    /// This function is a convenience wrapper over [`Instance::get_func`] and
177    /// [`Func::typed`]. For more information see the linked documentation.
178    ///
179    /// Returns an error if `name` isn't a function export or if the export's
180    /// type did not match `Params` or `Results`
181    ///
182    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
183    /// memory allocation fails. See the `OutOfMemory` type's documentation for
184    /// details on Wasmtime's out-of-memory handling.
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 ExportLookup,
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(|| format_err!("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 ExportLookup,
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 ExportLookup,
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 ExportLookup,
353    ) -> Option<(&'a ComponentInstance, &'a Export)> {
354        let data = self.id().get(store);
355        let index = name.lookup(data.component(), None)?;
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        store
385            .component_resource_tables(Some(self))?
386            .resource_new(VMTypedResource::component(ty, rep))
387    }
388
389    /// Implementation of the `resource.rep` intrinsic for `i32`
390    /// representations.
391    pub(crate) fn resource_rep32(
392        self,
393        store: &mut StoreOpaque,
394        ty: TypeResourceTableIndex,
395        index: u32,
396    ) -> Result<u32> {
397        store
398            .component_resource_tables(Some(self))?
399            .resource_rep(TypedResourceIndex::Component { ty, index })
400    }
401
402    /// Implementation of the `resource.drop` intrinsic.
403    pub(crate) fn resource_drop(
404        self,
405        store: &mut StoreOpaque,
406        ty: TypeResourceTableIndex,
407        index: u32,
408    ) -> Result<Option<u32>> {
409        store
410            .component_resource_tables(Some(self))?
411            .resource_drop(TypedResourceIndex::Component { ty, index })
412    }
413
414    pub(crate) fn resource_transfer_own(
415        self,
416        store: &mut StoreOpaque,
417        index: u32,
418        src: TypeResourceTableIndex,
419        dst: TypeResourceTableIndex,
420    ) -> Result<u32> {
421        let mut tables = store.component_resource_tables(Some(self))?;
422        let rep = tables.resource_lift_own(TypedResourceIndex::Component { ty: src, index })?;
423        tables.resource_lower_own(VMTypedResource::component(dst, rep))
424    }
425
426    pub(crate) fn resource_transfer_borrow(
427        self,
428        store: &mut StoreOpaque,
429        index: u32,
430        src: TypeResourceTableIndex,
431        dst: TypeResourceTableIndex,
432    ) -> Result<u32> {
433        debug_assert!(
434            !self.id().get(store).resource_owned_by_own_instance(dst),
435            "should have used `resource.transfer-borrow-to-owner` instead",
436        );
437        // No lazy-lend path here: the `resource_lower_borrow` below needs a
438        // materialized scope for its `borrow_count`, so the thread has to be
439        // forced anyway.
440        let mut tables = store.component_resource_tables(Some(self))?;
441        let rep = tables.resource_lift_borrow(TypedResourceIndex::Component { ty: src, index })?;
442        tables.resource_lower_borrow(VMTypedResource::component(dst, rep))
443    }
444
445    /// Variant of `resource_transfer_borrow` for when the destination instance
446    /// owns the resource, and so receives the representation directly.
447    pub(crate) fn resource_transfer_borrow_to_owner(
448        self,
449        store: &mut StoreOpaque,
450        index: u32,
451        src: TypeResourceTableIndex,
452    ) -> Result<u32> {
453        store
454            .resource_lift_borrow_maybe_lazy(self, TypedResourceIndex::Component { ty: src, index })
455    }
456
457    pub(crate) fn lookup_vmdef(&self, store: &mut StoreOpaque, def: &CoreDef) -> vm::Export {
458        lookup_vmdef(store, self.id.instance(), def)
459    }
460
461    pub(crate) fn options<'a>(
462        &self,
463        store: &'a StoreOpaque,
464        options: OptionsIndex,
465    ) -> &'a CanonicalOptions {
466        &self.id.get(store).component().env_component().options[options]
467    }
468
469    fn options_memory_raw(
470        &self,
471        store: &StoreOpaque,
472        options: OptionsIndex,
473    ) -> Option<NonNull<vm::VMMemoryDefinition>> {
474        let instance = self.id.get(store);
475        let options = &instance.component().env_component().options[options];
476        let memory = match options.data_model {
477            CanonicalOptionsDataModel::Gc { .. } => return None,
478            CanonicalOptionsDataModel::LinearMemory(o) => match o.memory {
479                Some(m) => m,
480                None => return None,
481            },
482        };
483
484        Some(instance.runtime_memory(memory))
485    }
486
487    pub(crate) fn options_memory<'a>(
488        &self,
489        store: &'a StoreOpaque,
490        options: OptionsIndex,
491    ) -> &'a [u8] {
492        let memory = match self.options_memory_raw(store, options) {
493            Some(m) => m,
494            None => return &[],
495        };
496        // SAFETY: we're borrowing the entire `StoreOpaque` which owns the
497        // memory allocation to return the result of memory. That means that the
498        // lifetime connection here should be safe and the actual ptr/length are
499        // trusted parts of the runtime here.
500        unsafe {
501            let memory = memory.as_ref();
502            core::slice::from_raw_parts(memory.base.as_ptr(), memory.current_length())
503        }
504    }
505
506    pub(crate) fn options_memory_mut<'a>(
507        &self,
508        store: &'a mut StoreOpaque,
509        options: OptionsIndex,
510    ) -> &'a mut [u8] {
511        let memory = match self.options_memory_raw(store, options) {
512            Some(m) => m,
513            None => return &mut [],
514        };
515        // SAFETY: See `options_memory` comment above, and note that this is
516        // taking `&mut StoreOpaque` to thread the lifetime through instead.
517        unsafe {
518            let memory = memory.as_ref();
519            core::slice::from_raw_parts_mut(memory.base.as_ptr(), memory.current_length())
520        }
521    }
522
523    /// The `len` bytes at `offset` of the options' memory, if in bounds.
524    pub(crate) fn options_memory_range_mut<'a>(
525        &self,
526        store: &'a mut StoreOpaque,
527        options: OptionsIndex,
528        offset: usize,
529        len: usize,
530    ) -> Option<&'a mut [u8]> {
531        let end = offset.checked_add(len)?;
532        self.options_memory_mut(store, options).get_mut(offset..end)
533    }
534
535    /// Helper function to simultaneously get a borrow to this instance's
536    /// component as well as the store that this component is contained within.
537    ///
538    /// Note that this function signature is not possible with safe Rust, so
539    /// this is using `unsafe` internally.
540    pub(crate) fn component_and_store_mut<'a, S>(
541        &self,
542        store: &'a mut S,
543    ) -> (&'a Component, &'a mut S)
544    where
545        S: AsStoreOpaque,
546    {
547        let store_opaque = store.as_store_opaque();
548        let instance = self.id.get_mut(store_opaque);
549        let component = instance.component();
550
551        // SAFETY: the goal of this function is to derive a pointer from
552        // `&mut S`, here `&Component`, and then return both so they can both be
553        // used at the same time. In general this is not safe operation since
554        // the original mutable pointer could be mutated or overwritten which
555        // would invalidate the derived pointer.
556        //
557        // In this case though we have a few guarantees which should make this
558        // safe:
559        //
560        // * Embedders never have the ability to overwrite a `StoreOpaque`. For
561        //   example the closest thing of `StoreContextMut` wraps up the
562        //   reference internally so it's inaccessible to the outside world.
563        //   This means that while mutations can still happen it's not possible
564        //   to overwrite a `StoreOpaque` directly.
565        //
566        // * Components are referred to by `vm::ComponentInstance` which holds a
567        //   strong reference. All `ComponentInstance` structures are allocated
568        //   within the store and unconditionally live as long as the entire
569        //   store itself. This means that there's no worry of the rooting
570        //   container going away or otherwise getting deallocated.
571        //
572        // * The `ComponentInstance` container has an invariant that after
573        //   creation the component used to create it cannot be changed. This is
574        //   enforced through `Pin<&mut ComponentInstance>` which disallows
575        //   mutable access to the `component` field, instead only allowing
576        //   read-only access.
577        //
578        // Putting all of this together it's not possible for a component,
579        // within a component instance, within a store, to be deallocated or mutated while
580        // a store is in use. Consequently it should be safe to simultaneously
581        // have a borrow to both at the same time, even if the store has a
582        // mutable borrow itself.
583        unsafe {
584            let component: *const Component = component;
585            (&*component, store)
586        }
587    }
588
589    pub(crate) fn runtime_instance(&self, index: RuntimeComponentInstanceIndex) -> RuntimeInstance {
590        RuntimeInstance {
591            instance: self.id.instance(),
592            index,
593        }
594    }
595
596    #[cfg(feature = "component-model-async")]
597    pub(crate) fn from_runtime_instance(store: &StoreOpaque, instance: RuntimeInstance) -> Self {
598        let id = StoreComponentInstanceId::new(store.id(), instance.instance);
599        Instance { id }
600    }
601}
602
603/// Translates a `CoreDef`, a definition of a core wasm item, to an
604/// [`Export`] which is the runtime core wasm definition.
605pub(crate) fn lookup_vmdef(
606    store: &mut StoreOpaque,
607    id: ComponentInstanceId,
608    def: &CoreDef,
609) -> vm::Export {
610    match def {
611        CoreDef::Export(e) => lookup_vmexport(store, id, e),
612        CoreDef::Trampoline(idx) => {
613            let funcref = store
614                .store_data_mut()
615                .component_instance_mut(id)
616                .trampoline_func_ref(*idx);
617            // SAFETY: the `funcref` is owned by `store` and is valid within
618            // that store, so it's safe to create a `Func`.
619            vm::Export::Function(unsafe { crate::Func::from_vm_func_ref(store.id(), funcref) })
620        }
621        CoreDef::InstanceFlags(idx) => {
622            let id = StoreComponentInstanceId::new(store.id(), id);
623            vm::Export::Global(crate::Global::from_component_flags(id, *idx))
624        }
625        CoreDef::UnsafeIntrinsic(intrinsic) => {
626            let funcref = store
627                .store_data_mut()
628                .component_instance_mut(id)
629                .unsafe_intrinsic_func_ref(*intrinsic);
630            // SAFETY: as above, the `funcref` is owned by `store` and is valid
631            // within that store, so it's safe to create a `Func`.
632            vm::Export::Function(unsafe { crate::Func::from_vm_func_ref(store.id(), funcref) })
633        }
634    }
635}
636
637/// Translates a `CoreExport<T>`, an export of some core instance within
638/// this component, to the actual runtime definition of that item.
639pub(crate) fn lookup_vmexport<T>(
640    store: &mut StoreOpaque,
641    id: ComponentInstanceId,
642    item: &CoreExport<T>,
643) -> vm::Export
644where
645    T: Copy + Into<EntityIndex>,
646{
647    let store_id = store.id();
648    let id = store
649        .store_data_mut()
650        .component_instance_mut(id)
651        .instance(item.instance);
652    let (instance, registry) = store.instance_and_module_registry_mut(id);
653    let idx = match &item.item {
654        ExportItem::Index(idx) => (*idx).into(),
655
656        // FIXME: ideally at runtime we don't actually do any name lookups
657        // here. This will only happen when the host supplies an imported
658        // module so while the structure can't be known at compile time we
659        // do know at `InstancePre` time, for example, what all the host
660        // imports are. In theory we should be able to, as part of
661        // `InstancePre` construction, perform all name=>index mappings
662        // during that phase so the actual instantiation of an `InstancePre`
663        // skips all string lookups. This should probably only be
664        // investigated if this becomes a performance issue though.
665        ExportItem::Name(name) => {
666            let module = instance.env_module();
667            let name = module.strings.get_atom(name).unwrap();
668            module.exports[&name]
669        }
670    };
671    // SAFETY: the `store_id` owns this instance and all exports contained
672    // within.
673    unsafe { instance.get_export_by_index_mut(registry, store_id, idx) }
674}
675
676struct Instantiator<'a> {
677    component: &'a Component,
678    id: ComponentInstanceId,
679    core_imports: OwnedImports,
680    imports: &'a PrimaryMap<RuntimeImportIndex, RuntimeImport>,
681}
682
683pub(crate) enum RuntimeImport {
684    Func(Arc<HostFunc>),
685    Module(Module),
686    Resource {
687        ty: ResourceType,
688
689        // A strong reference to the host function that represents the
690        // destructor for this resource. At this time all resources here are
691        // host-defined resources. Note that this is itself never read because
692        // the funcref below points to it.
693        //
694        // Also note that the `Arc` here is used to support the same host
695        // function being used across multiple instances simultaneously. Or
696        // otherwise this makes `InstancePre::instantiate` possible to create
697        // separate instances all sharing the same host function.
698        dtor: Arc<crate::func::HostFunc>,
699
700        // A raw function which is filled out (including `wasm_call`) which
701        // points to the internals of the `_dtor` field. This is read and
702        // possibly executed by wasm.
703        dtor_funcref: VMFuncRef,
704    },
705}
706
707pub type ImportedResources = TryPrimaryMap<ResourceIndex, ResourceType>;
708
709impl<'a> Instantiator<'a> {
710    fn new(
711        component: &'a Component,
712        store: &mut StoreOpaque,
713        imports: &'a Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
714    ) -> Result<Instantiator<'a>> {
715        let env_component = component.env_component();
716        let (modules, engine, breakpoints) = store.modules_and_engine_and_breakpoints_mut();
717        modules.register_component(component, engine, breakpoints)?;
718        let imported_resources: ImportedResources =
719            TryPrimaryMap::with_capacity(env_component.imported_resources.len())?;
720
721        let instance = ComponentInstance::new(
722            store.store_data().components.next_component_instance_id(),
723            component,
724            try_new::<Arc<_>>(imported_resources)?,
725            imports,
726            store.traitobj(),
727        )?;
728        let id = store.store_data_mut().push_component_instance(instance)?;
729
730        Ok(Instantiator {
731            component,
732            imports,
733            core_imports: OwnedImports::empty(),
734            id,
735        })
736    }
737
738    async fn run<T>(
739        &mut self,
740        store: &mut StoreContextMut<'_, T>,
741        asyncness: Asyncness,
742    ) -> Result<()> {
743        let env_component = self.component.env_component();
744
745        // Before all initializers are processed configure all destructors for
746        // host-defined resources. No initializer will correspond to these and
747        // it's required to happen before they're needed, so execute this first.
748        for (idx, import) in env_component.imported_resources.iter() {
749            let (ty, func_ref) = match &self.imports[*import] {
750                RuntimeImport::Resource {
751                    ty, dtor_funcref, ..
752                } => (*ty, NonNull::from(dtor_funcref)),
753                _ => unreachable!(),
754            };
755            let i = self.instance_resource_types_mut(store.0).push(ty)?;
756            assert_eq!(i, idx);
757            self.instance_mut(store.0)
758                .set_resource_destructor(idx, Some(func_ref));
759        }
760
761        // Next configure all `VMFuncRef`s for trampolines that this component
762        // will require. These functions won't actually get used until their
763        // associated state has been initialized through the global initializers
764        // below, but the funcrefs can all be configured here.
765        for (idx, sig) in env_component.trampolines.iter() {
766            let ptrs = self.component.trampoline_ptrs(idx);
767            let signature = match self.component.signatures().shared_type(*sig) {
768                Some(s) => s,
769                None => panic!("found unregistered signature: {sig:?}"),
770            };
771
772            self.instance_mut(store.0).set_trampoline(
773                idx,
774                ptrs.wasm_call,
775                ptrs.array_call,
776                signature,
777            );
778        }
779
780        // Initialize the unsafe intrinsics used by this component, if any.
781        for (i, module_ty) in env_component
782            .unsafe_intrinsics
783            .iter()
784            .enumerate()
785            .filter_map(|(i, ty)| ty.expand().map(|ty| (i, ty)))
786        {
787            let i = u32::try_from(i).unwrap();
788            let intrinsic = UnsafeIntrinsic::from_u32(i);
789            let ptrs = self.component.unsafe_intrinsic_ptrs(intrinsic).expect(
790                "should have intrinsic pointers given that we assigned the intrinsic a type",
791            );
792            let shared_ty = self
793                .component
794                .signatures()
795                .shared_type(module_ty)
796                .expect("should have a shared type");
797            self.instance_mut(store.0).set_intrinsic(
798                intrinsic,
799                ptrs.wasm_call,
800                ptrs.array_call,
801                shared_ty,
802            );
803        }
804
805        for initializer in env_component.initializers.iter() {
806            match initializer {
807                GlobalInitializer::InstantiateModule(m, component_instance) => {
808                    let instance = self.id;
809                    let module;
810                    let imports = match m {
811                        // Since upvars are statically know we know that the
812                        // `args` list is already in the right order.
813                        InstantiateModule::Static(idx, args) => {
814                            module = self.component.static_module(*idx);
815                            self.build_imports(store.0, module, args.iter())?
816                        }
817
818                        // With imports, unlike upvars, we need to do runtime
819                        // lookups with strings to determine the order of the
820                        // imports since it's whatever the actual module
821                        // requires.
822                        //
823                        // FIXME: see the note in `ExportItem::Name` handling
824                        // above for how we ideally shouldn't do string lookup
825                        // here.
826                        InstantiateModule::Import(idx, args) => {
827                            module = match &self.imports[*idx] {
828                                RuntimeImport::Module(m) => m,
829                                _ => unreachable!(),
830                            };
831                            let args = module
832                                .imports()
833                                .map(|import| &args[import.module()][import.name()]);
834                            self.build_imports(store.0, module, args)?
835                        }
836                    };
837
838                    let callee =
839                        component_instance.map(|index| RuntimeInstance { instance, index });
840
841                    // Note that the unsafety here should be ok because the
842                    // validity of the component means that type-checks have
843                    // already been performed. This means that the unsafety due
844                    // to imports having the wrong type should not happen here.
845                    //
846                    // Also note we are calling `new_raw` followed by
847                    // `start_raw` and will run the latter on a fiber if
848                    // required per `asyncness`.
849
850                    let (mut instance, needs_startup) = {
851                        let (mut limiter, store) = store.0.resource_limiter_and_store_opaque();
852                        unsafe {
853                            crate::Instance::new_raw(
854                                store,
855                                limiter.as_mut(),
856                                module,
857                                imports.as_ref(),
858                            )
859                            .await?
860                        }
861                    };
862
863                    if needs_startup {
864                        if asyncness == Asyncness::No {
865                            start_raw(store, instance, callee)?;
866                        } else {
867                            #[cfg(feature = "async")]
868                            {
869                                #[cfg(feature = "component-model-async")]
870                                {
871                                    if store.0.concurrency_support() {
872                                        // With concurrency support enabled, we must
873                                        // run the start function inside the store's
874                                        // event loop in case it calls async
875                                        // functions or intrinsics, creates and
876                                        // resumes threads, etc.
877                                        instance = store.start_instance(instance, callee).await?;
878                                    } else {
879                                        store
880                                            .on_fiber(|store| start_raw(store, instance, callee))
881                                            .await??;
882                                    }
883                                }
884                                #[cfg(not(feature = "component-model-async"))]
885                                {
886                                    _ = &mut instance;
887                                    store
888                                        .on_fiber(|store| start_raw(store, instance, callee))
889                                        .await??;
890                                }
891                            }
892                            #[cfg(not(feature = "async"))]
893                            {
894                                _ = &mut instance;
895                                unreachable!();
896                            }
897                        }
898                    }
899
900                    self.instance_mut(store.0).push_instance_id(instance.id())?;
901                }
902
903                GlobalInitializer::LowerImport { import, index } => {
904                    let func = match &self.imports[*import] {
905                        RuntimeImport::Func(func) => func,
906                        _ => unreachable!(),
907                    };
908                    self.instance_mut(store.0)
909                        .set_lowering(*index, func.lowering());
910                }
911
912                GlobalInitializer::ExtractTable(table) => self.extract_table(store.0, table),
913
914                GlobalInitializer::ExtractMemory(mem) => self.extract_memory(store.0, mem),
915
916                GlobalInitializer::ExtractRealloc(realloc) => {
917                    self.extract_realloc(store.0, realloc)
918                }
919
920                GlobalInitializer::ExtractCallback(callback) => {
921                    self.extract_callback(store.0, callback)
922                }
923
924                GlobalInitializer::ExtractPostReturn(post_return) => {
925                    self.extract_post_return(store.0, post_return)
926                }
927
928                GlobalInitializer::Resource(r) => self.resource(store.0, r)?,
929            }
930        }
931        Ok(())
932    }
933
934    fn resource(&mut self, store: &mut StoreOpaque, resource: &Resource) -> Result<()> {
935        let dtor = resource
936            .dtor
937            .as_ref()
938            .map(|dtor| lookup_vmdef(store, self.id, dtor));
939        let dtor = dtor.map(|export| match export {
940            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
941            _ => unreachable!(),
942        });
943        let index = self
944            .component
945            .env_component()
946            .resource_index(resource.index);
947        let instance = self.instance(store);
948        let ty = ResourceType::guest(store.id(), instance, resource.index);
949        self.instance_mut(store)
950            .set_resource_destructor(index, dtor);
951        let i = self.instance_resource_types_mut(store).push(ty)?;
952        debug_assert_eq!(i, index);
953        Ok(())
954    }
955
956    fn extract_memory(&mut self, store: &mut StoreOpaque, memory: &ExtractMemory) {
957        let import = match lookup_vmexport(store, self.id, &memory.export) {
958            crate::runtime::vm::Export::Memory(memory) => memory.vmimport(store),
959            crate::runtime::vm::Export::SharedMemory(_, import) => import,
960            _ => unreachable!(),
961        };
962        self.instance_mut(store)
963            .set_runtime_memory(memory.index, import.from.as_non_null());
964    }
965
966    fn extract_realloc(&mut self, store: &mut StoreOpaque, realloc: &ExtractRealloc) {
967        let func_ref = match lookup_vmdef(store, self.id, &realloc.def) {
968            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
969            _ => unreachable!(),
970        };
971        self.instance_mut(store)
972            .set_runtime_realloc(realloc.index, func_ref);
973    }
974
975    fn extract_callback(&mut self, store: &mut StoreOpaque, callback: &ExtractCallback) {
976        let func_ref = match lookup_vmdef(store, self.id, &callback.def) {
977            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
978            _ => unreachable!(),
979        };
980        self.instance_mut(store)
981            .set_runtime_callback(callback.index, func_ref);
982    }
983
984    fn extract_post_return(&mut self, store: &mut StoreOpaque, post_return: &ExtractPostReturn) {
985        let func_ref = match lookup_vmdef(store, self.id, &post_return.def) {
986            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
987            _ => unreachable!(),
988        };
989        self.instance_mut(store)
990            .set_runtime_post_return(post_return.index, func_ref);
991    }
992
993    fn extract_table(&mut self, store: &mut StoreOpaque, table: &ExtractTable) {
994        let export = match lookup_vmexport(store, self.id, &table.export) {
995            crate::runtime::vm::Export::Table(t) => t,
996            _ => unreachable!(),
997        };
998        let import = export.vmimport(store);
999        self.instance_mut(store)
1000            .set_runtime_table(table.index, import);
1001    }
1002
1003    fn build_imports<'b>(
1004        &mut self,
1005        store: &mut StoreOpaque,
1006        module: &Module,
1007        args: impl Iterator<Item = &'b CoreDef>,
1008    ) -> Result<&OwnedImports, OutOfMemory> {
1009        self.core_imports.clear();
1010        self.core_imports.reserve(module)?;
1011        let mut imports = module.compiled_module().module().imports();
1012
1013        for arg in args {
1014            // The general idea of Wasmtime is that at runtime type-checks for
1015            // core wasm instantiations internally within a component are
1016            // unnecessary and superfluous. Naturally though mistakes may be
1017            // made, so double-check this property of wasmtime in debug mode.
1018
1019            if cfg!(debug_assertions) {
1020                let (imp_module, imp_name, expected) = imports.next().unwrap();
1021                self.assert_type_matches(store, module, arg, imp_module, imp_name, expected);
1022            }
1023
1024            // The unsafety here should be ok since the `export` is loaded
1025            // directly from an instance which should only give us valid export
1026            // items.
1027            let export = lookup_vmdef(store, self.id, arg);
1028            self.core_imports.push_export(store, &export)?;
1029        }
1030        debug_assert!(imports.next().is_none());
1031
1032        Ok(&self.core_imports)
1033    }
1034
1035    fn assert_type_matches(
1036        &self,
1037        store: &mut StoreOpaque,
1038        module: &Module,
1039        arg: &CoreDef,
1040        imp_module: &str,
1041        imp_name: &str,
1042        expected: EntityType,
1043    ) {
1044        let export = lookup_vmdef(store, self.id, arg);
1045
1046        // If this value is a core wasm function then the type check is inlined
1047        // here. This can otherwise fail `Extern::from_wasmtime_export` because
1048        // there's no guarantee that there exists a trampoline for `f` so this
1049        // can't fall through to the case below
1050        if let crate::runtime::vm::Export::Function(f) = &export {
1051            let expected = match expected.unwrap_func() {
1052                EngineOrModuleTypeIndex::Engine(e) => Some(e),
1053                EngineOrModuleTypeIndex::Module(m) => module.signatures().shared_type(m),
1054                EngineOrModuleTypeIndex::RecGroup(_) => unreachable!(),
1055            };
1056            let actual = unsafe { f.vm_func_ref(store).as_ref().type_index };
1057            assert!(
1058                expected.is_some_and(|e| store.engine().signatures().is_subtype(actual, e)),
1059                "type mismatch for import {imp_module:?} {imp_name:?}!!!\n\n\
1060                 expected {:#?}\n\n\
1061                 found {:#?}",
1062                expected.and_then(|e| store.engine().signatures().borrow(e)),
1063                store.engine().signatures().borrow(actual)
1064            );
1065            return;
1066        }
1067
1068        let val = crate::Extern::from_wasmtime_export(export, store.engine());
1069        let ty = DefinitionType::from(store, &val);
1070        crate::types::matching::MatchCx::new(module.engine())
1071            .definition(&expected, &ty)
1072            .expect("unexpected typecheck failure");
1073    }
1074
1075    /// Convenience helper to return the `&ComponentInstance` that's being
1076    /// instantiated.
1077    fn instance<'b>(&self, store: &'b StoreOpaque) -> &'b ComponentInstance {
1078        store.store_data().component_instance(self.id)
1079    }
1080
1081    /// Same as [`Self::instance`], but for mutability.
1082    fn instance_mut<'b>(&self, store: &'b mut StoreOpaque) -> Pin<&'b mut ComponentInstance> {
1083        store.store_data_mut().component_instance_mut(self.id)
1084    }
1085
1086    // NB: This method is only intended to be called during the instantiation
1087    // process because the `Arc::get_mut` here is fallible and won't generally
1088    // succeed once the instance has been handed to the embedder. Before that
1089    // though it should be guaranteed that the single owning reference currently
1090    // lives within the `ComponentInstance` that's being built.
1091    fn instance_resource_types_mut<'b>(
1092        &self,
1093        store: &'b mut StoreOpaque,
1094    ) -> &'b mut ImportedResources {
1095        Arc::get_mut(self.instance_mut(store).resource_types_mut()).unwrap()
1096    }
1097}
1098
1099/// Runs the start function of the core wasm `instance`.
1100///
1101/// If `callee` is specified then the start function is run as a sync-lifted
1102/// call into that component instance.
1103pub(crate) fn start_raw<T>(
1104    store: &mut StoreContextMut<'_, T>,
1105    instance: crate::Instance,
1106    callee: Option<RuntimeInstance>,
1107) -> Result<()> {
1108    if let Some(callee) = callee {
1109        store.0.enter_guest_sync_call(false, callee)?;
1110    }
1111    instance.start_raw(store, UncaughtException::Trap)?;
1112    if callee.is_some() {
1113        store.0.exit_guest_sync_call()?;
1114    }
1115    Ok(())
1116}
1117
1118/// A "pre-instantiated" [`Instance`] which has all of its arguments already
1119/// supplied and is ready to instantiate.
1120///
1121/// This structure represents an efficient form of instantiation where import
1122/// type-checking and import lookup has all been resolved by the time that this
1123/// type is created. This type is primarily created through the
1124/// [`Linker::instantiate_pre`](crate::component::Linker::instantiate_pre)
1125/// method.
1126pub struct InstancePre<T: 'static> {
1127    component: Component,
1128    imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
1129    resource_types: Arc<TryPrimaryMap<ResourceIndex, ResourceType>>,
1130    asyncness: Asyncness,
1131    _marker: marker::PhantomData<fn() -> T>,
1132}
1133
1134// `InstancePre`'s clone does not require `T: Clone`
1135impl<T: 'static> Clone for InstancePre<T> {
1136    fn clone(&self) -> Self {
1137        Self {
1138            component: self.component.clone(),
1139            imports: self.imports.clone(),
1140            resource_types: self.resource_types.clone(),
1141            asyncness: self.asyncness,
1142            _marker: self._marker,
1143        }
1144    }
1145}
1146
1147impl<T: 'static> InstancePre<T> {
1148    /// This function is `unsafe` since there's no guarantee that the
1149    /// `RuntimeImport` items provided are guaranteed to work with the `T` of
1150    /// the store.
1151    ///
1152    /// Additionally there is no static guarantee that the `imports` provided
1153    /// satisfy the imports of the `component` provided.
1154    pub(crate) unsafe fn new_unchecked(
1155        component: Component,
1156        imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
1157        resource_types: Arc<TryPrimaryMap<ResourceIndex, ResourceType>>,
1158    ) -> InstancePre<T> {
1159        let mut asyncness = Asyncness::No;
1160        for (_, import) in imports.iter() {
1161            asyncness = asyncness
1162                | match import {
1163                    RuntimeImport::Func(f) => f.asyncness(),
1164                    RuntimeImport::Module(_) => Asyncness::No,
1165                    RuntimeImport::Resource { dtor, .. } => dtor.asyncness(),
1166                };
1167        }
1168        InstancePre {
1169            component,
1170            imports,
1171            resource_types,
1172            asyncness,
1173            _marker: marker::PhantomData,
1174        }
1175    }
1176
1177    /// Returns the underlying component that will be instantiated.
1178    pub fn component(&self) -> &Component {
1179        &self.component
1180    }
1181
1182    #[doc(hidden)]
1183    /// Returns the type at which the underlying component will be
1184    /// instantiated. This contains the instantiated type information which
1185    /// was determined by the Linker.
1186    pub fn instance_type(&self) -> InstanceType<'_> {
1187        InstanceType {
1188            types: &self.component.types(),
1189            resources: Some(&self.resource_types),
1190        }
1191    }
1192
1193    /// Returns the underlying engine.
1194    pub fn engine(&self) -> &Engine {
1195        self.component.engine()
1196    }
1197
1198    /// Performs the instantiation process into the store specified.
1199    ///
1200    /// # Errors
1201    ///
1202    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1203    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1204    /// details on Wasmtime's out-of-memory handling.
1205    //
1206    // TODO: needs more docs
1207    pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
1208        let store = store.as_context_mut();
1209
1210        // If this instance requires an async host, set that flag in the store,
1211        // and then afterwards assert nothing else in the store, nor this
1212        // instance, required async.
1213        store.0.set_async_required(self.asyncness);
1214        store.0.validate_sync_call()?;
1215
1216        vm::assert_ready(self._instantiate(store, Asyncness::No))
1217    }
1218    /// Performs the instantiation process into the store specified.
1219    ///
1220    /// Exactly like [`Self::instantiate`] except for use on async stores.
1221    ///
1222    /// # Errors
1223    ///
1224    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1225    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1226    /// details on Wasmtime's out-of-memory handling.
1227    //
1228    // TODO: needs more docs
1229    #[cfg(feature = "async")]
1230    pub async fn instantiate_async(&self, store: impl AsContextMut<Data = T>) -> Result<Instance> {
1231        self._instantiate(store, Asyncness::Yes).await
1232    }
1233
1234    async fn _instantiate(
1235        &self,
1236        mut store: impl AsContextMut<Data = T>,
1237        asyncness: Asyncness,
1238    ) -> Result<Instance> {
1239        let store = store.as_context_mut();
1240        store.0.set_async_required(self.asyncness);
1241        store
1242            .engine()
1243            .allocator()
1244            .increment_component_instance_count()?;
1245
1246        // Helper structure to pair the above increment with a decrement should
1247        // anything fail below.
1248        let mut decrement = DecrementComponentInstanceCountOnDrop {
1249            store,
1250            enabled: true,
1251        };
1252
1253        let mut instantiator =
1254            Instantiator::new(&self.component, decrement.store.0, &self.imports)?;
1255        instantiator.run(&mut decrement.store, asyncness).await?;
1256
1257        let instance = Instance::from_wasmtime(decrement.store.0, instantiator.id);
1258        decrement.store.0.push_component_instance(instance);
1259
1260        // Everything has passed, don't decrement the instance count and let the
1261        // destructor for the `Store` handle that at this point.
1262        decrement.enabled = false;
1263        return Ok(instance);
1264
1265        struct DecrementComponentInstanceCountOnDrop<'a, T: 'static> {
1266            store: StoreContextMut<'a, T>,
1267            enabled: bool,
1268        }
1269
1270        impl<T> Drop for DecrementComponentInstanceCountOnDrop<'_, T> {
1271            fn drop(&mut self) {
1272                if self.enabled {
1273                    self.store
1274                        .engine()
1275                        .allocator()
1276                        .decrement_component_instance_count();
1277                }
1278            }
1279        }
1280    }
1281}