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::component::{ComponentInstance, TypedResource, TypedResourceIndex};
13use crate::runtime::vm::{self, UncaughtException, VMFuncRef, VMStore};
14use crate::store::{AsStoreOpaque, Asyncness, StoreOpaque};
15use crate::{AsContext, AsContextMut, Engine, Module, StoreContextMut};
16use alloc::sync::Arc;
17use core::marker;
18use core::pin::Pin;
19use core::ptr::NonNull;
20use wasmtime_environ::{EngineOrModuleTypeIndex, component::*};
21use wasmtime_environ::{EntityIndex, EntityType, PrimaryMap};
22
23/// An instantiated component.
24///
25/// This type represents an instantiated [`Component`](super::Component).
26/// Instances have exports which can be accessed through functions such as
27/// [`Instance::get_func`] or [`Instance::get_export`]. Instances are owned by a
28/// [`Store`](crate::Store) and all methods require a handle to the store.
29///
30/// Component instances are created through
31/// [`Linker::instantiate`](super::Linker::instantiate) and its family of
32/// methods.
33///
34/// This type is similar to the core wasm version
35/// [`wasmtime::Instance`](crate::Instance) except that it represents an
36/// instantiated component instead of an instantiated module.
37#[derive(Copy, Clone, Debug)]
38#[repr(transparent)]
39pub struct Instance {
40    id: StoreComponentInstanceId,
41}
42
43// Double-check that the C representation in `component/instance.h` matches our
44// in-Rust representation here in terms of size/alignment/etc.
45const _: () = {
46    #[repr(C)]
47    struct C(u64, u32);
48    assert!(core::mem::size_of::<C>() == core::mem::size_of::<Instance>());
49    assert!(core::mem::align_of::<C>() == core::mem::align_of::<Instance>());
50    assert!(core::mem::offset_of!(Instance, id) == 0);
51};
52
53impl Instance {
54    /// Creates a raw `Instance` from the internal identifiers within the store.
55    pub(crate) fn from_wasmtime(store: &StoreOpaque, id: ComponentInstanceId) -> Instance {
56        Instance {
57            id: StoreComponentInstanceId::new(store.id(), id),
58        }
59    }
60
61    /// Looks up an exported function by name within this [`Instance`].
62    ///
63    /// The `store` argument provided must be the store that this instance
64    /// lives within and the `name` argument is the lookup key by which to find
65    /// the exported function. If the function is found then `Some` is returned
66    /// and otherwise `None` is returned.
67    ///
68    /// The `name` here can be a string such as `&str` or it can be a
69    /// [`ComponentExportIndex`] which is loaded prior from a [`Component`].
70    ///
71    /// # Panics
72    ///
73    /// Panics if `store` does not own this instance.
74    ///
75    /// # Examples
76    ///
77    /// Looking up a function which is exported from the root of a component:
78    ///
79    /// ```
80    /// use wasmtime::{Engine, Store};
81    /// use wasmtime::component::{Component, Linker};
82    ///
83    /// # fn main() -> wasmtime::Result<()> {
84    /// let engine = Engine::default();
85    /// let component = Component::new(
86    ///     &engine,
87    ///     r#"
88    ///         (component
89    ///             (core module $m
90    ///                 (func (export "f"))
91    ///             )
92    ///             (core instance $i (instantiate $m))
93    ///             (func (export "f")
94    ///                 (canon lift (core func $i "f")))
95    ///         )
96    ///     "#,
97    /// )?;
98    ///
99    /// // Look up the function by name
100    /// let mut store = Store::new(&engine, ());
101    /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
102    /// let func = instance.get_func(&mut store, "f").unwrap();
103    ///
104    /// // The function can also be looked up by an index via a precomputed index.
105    /// let export = component.get_export_index(None, "f").unwrap();
106    /// let func = instance.get_func(&mut store, &export).unwrap();
107    /// # Ok(())
108    /// # }
109    /// ```
110    ///
111    /// Looking up a function which is exported from a nested instance:
112    ///
113    /// ```
114    /// use wasmtime::{Engine, Store};
115    /// use wasmtime::component::{Component, Linker};
116    ///
117    /// # fn main() -> wasmtime::Result<()> {
118    /// let engine = Engine::default();
119    /// let component = Component::new(
120    ///     &engine,
121    ///     r#"
122    ///         (component
123    ///             (core module $m
124    ///                 (func (export "f"))
125    ///             )
126    ///             (core instance $i (instantiate $m))
127    ///             (func $f
128    ///                 (canon lift (core func $i "f")))
129    ///
130    ///             (instance $i
131    ///                 (export "f" (func $f)))
132    ///             (export "i" (instance $i))
133    ///         )
134    ///     "#,
135    /// )?;
136    ///
137    /// // First look up the exported instance, then use that to lookup the
138    /// // exported function.
139    /// let instance_index = component.get_export_index(None, "i").unwrap();
140    /// let func_index = component.get_export_index(Some(&instance_index), "f").unwrap();
141    ///
142    /// // Then use `func_index` at runtime.
143    /// let mut store = Store::new(&engine, ());
144    /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
145    /// let func = instance.get_func(&mut store, &func_index).unwrap();
146    ///
147    /// // Alternatively the `instance` can be used directly in conjunction with
148    /// // the `get_export_index` method.
149    /// let instance_index = instance.get_export_index(&mut store, None, "i").unwrap();
150    /// let func_index = instance.get_export_index(&mut store, Some(&instance_index), "f").unwrap();
151    /// let func = instance.get_func(&mut store, &func_index).unwrap();
152    /// # Ok(())
153    /// # }
154    /// ```
155    pub fn get_func(&self, mut store: impl AsContextMut, name: impl ExportLookup) -> Option<Func> {
156        let store = store.as_context_mut().0;
157        let instance = self.id.get(store);
158        let component = instance.component();
159
160        // Validate that `name` exists within `self.`
161        let index = name.lookup(component, None)?;
162
163        // Validate that `index` is indeed a lifted function.
164        match &component.env_component().export_items[index] {
165            Export::LiftedFunction { .. } => {}
166            _ => return None,
167        }
168
169        // And package up the indices!
170        Some(Func::from_lifted_func(store, *self, index))
171    }
172
173    /// Looks up an exported [`Func`] value by name and with its type.
174    ///
175    /// This function is a convenience wrapper over [`Instance::get_func`] and
176    /// [`Func::typed`]. For more information see the linked documentation.
177    ///
178    /// Returns an error if `name` isn't a function export or if the export's
179    /// type did not match `Params` or `Results`
180    ///
181    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
182    /// memory allocation fails. See the `OutOfMemory` type's documentation for
183    /// details on Wasmtime's out-of-memory handling.
184    ///
185    /// # Panics
186    ///
187    /// Panics if `store` does not own this instance.
188    pub fn get_typed_func<Params, Results>(
189        &self,
190        mut store: impl AsContextMut,
191        name: impl ExportLookup,
192    ) -> Result<TypedFunc<Params, Results>>
193    where
194        Params: ComponentNamedList + Lower,
195        Results: ComponentNamedList + Lift,
196    {
197        let f = self
198            .get_func(store.as_context_mut(), name)
199            .ok_or_else(|| format_err!("failed to find function export"))?;
200        Ok(f.typed::<Params, Results>(store)
201            .with_context(|| format!("failed to convert function to given type"))?)
202    }
203
204    /// Looks up an exported module by name within this [`Instance`].
205    ///
206    /// The `store` argument provided must be the store that this instance
207    /// lives within and the `name` argument is the lookup key by which to find
208    /// the exported module. If the module is found then `Some` is returned
209    /// and otherwise `None` is returned.
210    ///
211    /// The `name` here can be a string such as `&str` or it can be a
212    /// [`ComponentExportIndex`] which is loaded prior from a [`Component`].
213    ///
214    /// For some examples see [`Instance::get_func`] for loading values from a
215    /// component.
216    ///
217    /// # Panics
218    ///
219    /// Panics if `store` does not own this instance.
220    pub fn get_module(
221        &self,
222        mut store: impl AsContextMut,
223        name: impl ExportLookup,
224    ) -> Option<Module> {
225        let store = store.as_context_mut().0;
226        let (instance, export) = self.lookup_export(store, name)?;
227        match export {
228            Export::ModuleStatic { index, .. } => {
229                Some(instance.component().static_module(*index).clone())
230            }
231            Export::ModuleImport { import, .. } => match instance.runtime_import(*import) {
232                RuntimeImport::Module(m) => Some(m.clone()),
233                _ => unreachable!(),
234            },
235            _ => None,
236        }
237    }
238
239    /// Looks up an exported resource type by name within this [`Instance`].
240    ///
241    /// The `store` argument provided must be the store that this instance
242    /// lives within and the `name` argument is the lookup key by which to find
243    /// the exported resource. If the resource is found then `Some` is returned
244    /// and otherwise `None` is returned.
245    ///
246    /// The `name` here can be a string such as `&str` or it can be a
247    /// [`ComponentExportIndex`] which is loaded prior from a [`Component`].
248    ///
249    /// For some examples see [`Instance::get_func`] for loading values from a
250    /// component.
251    ///
252    /// # Panics
253    ///
254    /// Panics if `store` does not own this instance.
255    pub fn get_resource(
256        &self,
257        mut store: impl AsContextMut,
258        name: impl ExportLookup,
259    ) -> Option<ResourceType> {
260        let store = store.as_context_mut().0;
261        let (instance, export) = self.lookup_export(store, name)?;
262        match export {
263            Export::Type(TypeDef::Resource(id)) => {
264                Some(InstanceType::new(instance).resource_type(*id))
265            }
266            Export::Type(_)
267            | Export::LiftedFunction { .. }
268            | Export::ModuleStatic { .. }
269            | Export::ModuleImport { .. }
270            | Export::Instance { .. } => None,
271        }
272    }
273
274    /// A methods similar to [`Component::get_export`] except for this
275    /// instance.
276    ///
277    /// This method will lookup the `name` provided within the `instance`
278    /// provided and return a [`ComponentItem`] describing the export,
279    /// and [`ComponentExportIndex`] which can be passed other `get_*`
280    /// functions like [`Instance::get_func`].
281    ///
282    /// The [`ComponentItem`] is more expensive to compute than the
283    /// [`ComponentExportIndex`]. If you are not consuming the
284    /// [`ComponentItem`], use [`Instance::get_export_index`] instead.
285    ///
286    /// # Panics
287    ///
288    /// Panics if `store` does not own this instance.
289    pub fn get_export(
290        &self,
291        mut store: impl AsContextMut,
292        instance: Option<&ComponentExportIndex>,
293        name: &str,
294    ) -> Option<(ComponentItem, ComponentExportIndex)> {
295        self._get_export(store.as_context_mut().0, instance, name)
296    }
297
298    fn _get_export(
299        &self,
300        store: &StoreOpaque,
301        instance: Option<&ComponentExportIndex>,
302        name: &str,
303    ) -> Option<(ComponentItem, ComponentExportIndex)> {
304        let data = self.id().get(store);
305        let component = data.component();
306        let index = component.lookup_export_index(instance, name)?;
307        let item = ComponentItem::from_export(
308            &store.engine(),
309            &component.env_component().export_items[index],
310            &InstanceType::new(data),
311        );
312        Some((
313            item,
314            ComponentExportIndex {
315                id: data.component().id(),
316                index,
317            },
318        ))
319    }
320
321    /// A methods similar to [`Component::get_export_index`] except for this
322    /// instance.
323    ///
324    /// This method will lookup the `name` provided within the `instance`
325    /// provided and return a [`ComponentExportIndex`] which can be passed
326    /// other `get_*` functions like [`Instance::get_func`].
327    ///
328    /// If you need the [`ComponentItem`] corresponding to this export, use
329    /// the [`Instance::get_export`] instead.
330    ///
331    /// # Panics
332    ///
333    /// Panics if `store` does not own this instance.
334    pub fn get_export_index(
335        &self,
336        mut store: impl AsContextMut,
337        instance: Option<&ComponentExportIndex>,
338        name: &str,
339    ) -> Option<ComponentExportIndex> {
340        let data = self.id().get(store.as_context_mut().0);
341        let index = data.component().lookup_export_index(instance, name)?;
342        Some(ComponentExportIndex {
343            id: data.component().id(),
344            index,
345        })
346    }
347
348    fn lookup_export<'a>(
349        &self,
350        store: &'a StoreOpaque,
351        name: impl ExportLookup,
352    ) -> Option<(&'a ComponentInstance, &'a Export)> {
353        let data = self.id().get(store);
354        let index = name.lookup(data.component(), None)?;
355        Some((data, &data.component().env_component().export_items[index]))
356    }
357
358    /// Returns the [`InstancePre`] that was used to create this instance.
359    pub fn instance_pre<T>(&self, store: impl AsContext<Data = T>) -> InstancePre<T> {
360        // This indexing operation asserts the Store owns the Instance.
361        // Therefore, the InstancePre<T> must match the Store<T>.
362        let data = self.id().get(store.as_context().0);
363
364        // SAFETY: calling this method safely here relies on matching the `T`
365        // in `InstancePre<T>` to the store itself, which is happening in the
366        // type signature just above by ensuring the store's data is `T` which
367        // matches the return value.
368        unsafe { data.instance_pre() }
369    }
370
371    pub(crate) fn id(&self) -> StoreComponentInstanceId {
372        self.id
373    }
374
375    /// Implementation of the `resource.new` intrinsic for `i32`
376    /// representations.
377    pub(crate) fn resource_new32(
378        self,
379        store: &mut StoreOpaque,
380        ty: TypeResourceTableIndex,
381        rep: u32,
382    ) -> Result<u32> {
383        store
384            .component_resource_tables(Some(self))?
385            .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        store
397            .component_resource_tables(Some(self))?
398            .resource_rep(TypedResourceIndex::Component { ty, index })
399    }
400
401    /// Implementation of the `resource.drop` intrinsic.
402    pub(crate) fn resource_drop(
403        self,
404        store: &mut StoreOpaque,
405        ty: TypeResourceTableIndex,
406        index: u32,
407    ) -> Result<Option<u32>> {
408        store
409            .component_resource_tables(Some(self))?
410            .resource_drop(TypedResourceIndex::Component { ty, index })
411    }
412
413    pub(crate) fn resource_transfer_own(
414        self,
415        store: &mut StoreOpaque,
416        index: u32,
417        src: TypeResourceTableIndex,
418        dst: TypeResourceTableIndex,
419    ) -> Result<u32> {
420        let mut tables = store.component_resource_tables(Some(self))?;
421        let rep = tables.resource_lift_own(TypedResourceIndex::Component { ty: src, index })?;
422        tables.resource_lower_own(TypedResource::Component { ty: dst, rep })
423    }
424
425    pub(crate) fn resource_transfer_borrow(
426        self,
427        store: &mut StoreOpaque,
428        index: u32,
429        src: TypeResourceTableIndex,
430        dst: TypeResourceTableIndex,
431    ) -> Result<u32> {
432        debug_assert!(
433            !self.id().get(store).resource_owned_by_own_instance(dst),
434            "should have used `resource.transfer-borrow-to-owner` instead",
435        );
436        // No lazy-lend path here: the `resource_lower_borrow` below needs a
437        // materialized scope for its `borrow_count`, so the thread has to be
438        // forced anyway.
439        let mut tables = store.component_resource_tables(Some(self))?;
440        let rep = tables.resource_lift_borrow(TypedResourceIndex::Component { ty: src, index })?;
441        tables.resource_lower_borrow(TypedResource::Component { ty: dst, rep })
442    }
443
444    /// Variant of `resource_transfer_borrow` for when the destination instance
445    /// owns the resource, and so receives the representation directly.
446    pub(crate) fn resource_transfer_borrow_to_owner(
447        self,
448        store: &mut StoreOpaque,
449        index: u32,
450        src: TypeResourceTableIndex,
451    ) -> Result<u32> {
452        store
453            .resource_lift_borrow_maybe_lazy(self, TypedResourceIndex::Component { ty: src, index })
454    }
455
456    pub(crate) fn lookup_vmdef(&self, store: &mut StoreOpaque, def: &CoreDef) -> vm::Export {
457        lookup_vmdef(store, self.id.instance(), def)
458    }
459
460    pub(crate) fn options<'a>(
461        &self,
462        store: &'a StoreOpaque,
463        options: OptionsIndex,
464    ) -> &'a CanonicalOptions {
465        &self.id.get(store).component().env_component().options[options]
466    }
467
468    fn options_memory_raw(
469        &self,
470        store: &StoreOpaque,
471        options: OptionsIndex,
472    ) -> Option<NonNull<vm::VMMemoryDefinition>> {
473        let instance = self.id.get(store);
474        let options = &instance.component().env_component().options[options];
475        let memory = match options.data_model {
476            CanonicalOptionsDataModel::Gc { .. } => return None,
477            CanonicalOptionsDataModel::LinearMemory(o) => match o.memory {
478                Some(m) => m,
479                None => return None,
480            },
481        };
482
483        Some(instance.runtime_memory(memory))
484    }
485
486    pub(crate) fn options_memory<'a>(
487        &self,
488        store: &'a StoreOpaque,
489        options: OptionsIndex,
490    ) -> &'a [u8] {
491        let memory = match self.options_memory_raw(store, options) {
492            Some(m) => m,
493            None => return &[],
494        };
495        // SAFETY: we're borrowing the entire `StoreOpaque` which owns the
496        // memory allocation to return the result of memory. That means that the
497        // lifetime connection here should be safe and the actual ptr/length are
498        // trusted parts of the runtime here.
499        unsafe {
500            let memory = memory.as_ref();
501            core::slice::from_raw_parts(memory.base.as_ptr(), memory.current_length())
502        }
503    }
504
505    pub(crate) fn options_memory_mut<'a>(
506        &self,
507        store: &'a mut StoreOpaque,
508        options: OptionsIndex,
509    ) -> &'a mut [u8] {
510        let memory = match self.options_memory_raw(store, options) {
511            Some(m) => m,
512            None => return &mut [],
513        };
514        // SAFETY: See `options_memory` comment above, and note that this is
515        // taking `&mut StoreOpaque` to thread the lifetime through instead.
516        unsafe {
517            let memory = memory.as_ref();
518            core::slice::from_raw_parts_mut(memory.base.as_ptr(), memory.current_length())
519        }
520    }
521
522    /// Helper function to simultaneously get a borrow to this instance's
523    /// component as well as the store that this component is contained within.
524    ///
525    /// Note that this function signature is not possible with safe Rust, so
526    /// this is using `unsafe` internally.
527    pub(crate) fn component_and_store_mut<'a, S>(
528        &self,
529        store: &'a mut S,
530    ) -> (&'a Component, &'a mut S)
531    where
532        S: AsStoreOpaque,
533    {
534        let store_opaque = store.as_store_opaque();
535        let instance = self.id.get_mut(store_opaque);
536        let component = instance.component();
537
538        // SAFETY: the goal of this function is to derive a pointer from
539        // `&mut S`, here `&Component`, and then return both so they can both be
540        // used at the same time. In general this is not safe operation since
541        // the original mutable pointer could be mutated or overwritten which
542        // would invalidate the derived pointer.
543        //
544        // In this case though we have a few guarantees which should make this
545        // safe:
546        //
547        // * Embedders never have the ability to overwrite a `StoreOpaque`. For
548        //   example the closest thing of `StoreContextMut` wraps up the
549        //   reference internally so it's inaccessible to the outside world.
550        //   This means that while mutations can still happen it's not possible
551        //   to overwrite a `StoreOpaque` directly.
552        //
553        // * Components are referred to by `vm::ComponentInstance` which holds a
554        //   strong reference. All `ComponentInstance` structures are allocated
555        //   within the store and unconditionally live as long as the entire
556        //   store itself. This means that there's no worry of the rooting
557        //   container going away or otherwise getting deallocated.
558        //
559        // * The `ComponentInstance` container has an invariant that after
560        //   creation the component used to create it cannot be changed. This is
561        //   enforced through `Pin<&mut ComponentInstance>` which disallows
562        //   mutable access to the `component` field, instead only allowing
563        //   read-only access.
564        //
565        // Putting all of this together it's not possible for a component,
566        // within a component instance, within a store, to be deallocated or mutated while
567        // a store is in use. Consequently it should be safe to simultaneously
568        // have a borrow to both at the same time, even if the store has a
569        // mutable borrow itself.
570        unsafe {
571            let component: *const Component = component;
572            (&*component, store)
573        }
574    }
575
576    pub(crate) fn runtime_instance(&self, index: RuntimeComponentInstanceIndex) -> RuntimeInstance {
577        RuntimeInstance {
578            instance: self.id.instance(),
579            index,
580        }
581    }
582
583    #[cfg(feature = "component-model-async")]
584    pub(crate) fn from_runtime_instance(store: &StoreOpaque, instance: RuntimeInstance) -> Self {
585        let id = StoreComponentInstanceId::new(store.id(), instance.instance);
586        Instance { id }
587    }
588}
589
590/// Translates a `CoreDef`, a definition of a core wasm item, to an
591/// [`Export`] which is the runtime core wasm definition.
592pub(crate) fn lookup_vmdef(
593    store: &mut StoreOpaque,
594    id: ComponentInstanceId,
595    def: &CoreDef,
596) -> vm::Export {
597    match def {
598        CoreDef::Export(e) => lookup_vmexport(store, id, e),
599        CoreDef::Trampoline(idx) => {
600            let funcref = store
601                .store_data_mut()
602                .component_instance_mut(id)
603                .trampoline_func_ref(*idx);
604            // SAFETY: the `funcref` is owned by `store` and is valid within
605            // that store, so it's safe to create a `Func`.
606            vm::Export::Function(unsafe { crate::Func::from_vm_func_ref(store.id(), funcref) })
607        }
608        CoreDef::InstanceFlags(idx) => {
609            let id = StoreComponentInstanceId::new(store.id(), id);
610            vm::Export::Global(crate::Global::from_component_flags(id, *idx))
611        }
612        CoreDef::UnsafeIntrinsic(intrinsic) => {
613            let funcref = store
614                .store_data_mut()
615                .component_instance_mut(id)
616                .unsafe_intrinsic_func_ref(*intrinsic);
617            // SAFETY: as above, the `funcref` is owned by `store` and is valid
618            // within 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    }
622}
623
624/// Translates a `CoreExport<T>`, an export of some core instance within
625/// this component, to the actual runtime definition of that item.
626pub(crate) fn lookup_vmexport<T>(
627    store: &mut StoreOpaque,
628    id: ComponentInstanceId,
629    item: &CoreExport<T>,
630) -> vm::Export
631where
632    T: Copy + Into<EntityIndex>,
633{
634    let store_id = store.id();
635    let id = store
636        .store_data_mut()
637        .component_instance_mut(id)
638        .instance(item.instance);
639    let (instance, registry) = store.instance_and_module_registry_mut(id);
640    let idx = match &item.item {
641        ExportItem::Index(idx) => (*idx).into(),
642
643        // FIXME: ideally at runtime we don't actually do any name lookups
644        // here. This will only happen when the host supplies an imported
645        // module so while the structure can't be known at compile time we
646        // do know at `InstancePre` time, for example, what all the host
647        // imports are. In theory we should be able to, as part of
648        // `InstancePre` construction, perform all name=>index mappings
649        // during that phase so the actual instantiation of an `InstancePre`
650        // skips all string lookups. This should probably only be
651        // investigated if this becomes a performance issue though.
652        ExportItem::Name(name) => {
653            let module = instance.env_module();
654            let name = module.strings.get_atom(name).unwrap();
655            module.exports[&name]
656        }
657    };
658    // SAFETY: the `store_id` owns this instance and all exports contained
659    // within.
660    unsafe { instance.get_export_by_index_mut(registry, store_id, idx) }
661}
662
663struct Instantiator<'a> {
664    component: &'a Component,
665    id: ComponentInstanceId,
666    core_imports: OwnedImports,
667    imports: &'a PrimaryMap<RuntimeImportIndex, RuntimeImport>,
668}
669
670pub(crate) enum RuntimeImport {
671    Func(Arc<HostFunc>),
672    Module(Module),
673    Resource {
674        ty: ResourceType,
675
676        // A strong reference to the host function that represents the
677        // destructor for this resource. At this time all resources here are
678        // host-defined resources. Note that this is itself never read because
679        // the funcref below points to it.
680        //
681        // Also note that the `Arc` here is used to support the same host
682        // function being used across multiple instances simultaneously. Or
683        // otherwise this makes `InstancePre::instantiate` possible to create
684        // separate instances all sharing the same host function.
685        dtor: Arc<crate::func::HostFunc>,
686
687        // A raw function which is filled out (including `wasm_call`) which
688        // points to the internals of the `_dtor` field. This is read and
689        // possibly executed by wasm.
690        dtor_funcref: VMFuncRef,
691    },
692}
693
694pub type ImportedResources = TryPrimaryMap<ResourceIndex, ResourceType>;
695
696impl<'a> Instantiator<'a> {
697    fn new(
698        component: &'a Component,
699        store: &mut StoreOpaque,
700        imports: &'a Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
701    ) -> Result<Instantiator<'a>> {
702        let env_component = component.env_component();
703        let (modules, engine, breakpoints) = store.modules_and_engine_and_breakpoints_mut();
704        modules.register_component(component, engine, breakpoints)?;
705        let imported_resources: ImportedResources =
706            TryPrimaryMap::with_capacity(env_component.imported_resources.len())?;
707
708        let instance = ComponentInstance::new(
709            store.store_data().components.next_component_instance_id(),
710            component,
711            try_new::<Arc<_>>(imported_resources)?,
712            imports,
713            store.traitobj(),
714        )?;
715        let id = store.store_data_mut().push_component_instance(instance)?;
716
717        Ok(Instantiator {
718            component,
719            imports,
720            core_imports: OwnedImports::empty(),
721            id,
722        })
723    }
724
725    async fn run<T>(
726        &mut self,
727        store: &mut StoreContextMut<'_, T>,
728        asyncness: Asyncness,
729    ) -> Result<()> {
730        let env_component = self.component.env_component();
731
732        // Before all initializers are processed configure all destructors for
733        // host-defined resources. No initializer will correspond to these and
734        // it's required to happen before they're needed, so execute this first.
735        for (idx, import) in env_component.imported_resources.iter() {
736            let (ty, func_ref) = match &self.imports[*import] {
737                RuntimeImport::Resource {
738                    ty, dtor_funcref, ..
739                } => (*ty, NonNull::from(dtor_funcref)),
740                _ => unreachable!(),
741            };
742            let i = self.instance_resource_types_mut(store.0).push(ty)?;
743            assert_eq!(i, idx);
744            self.instance_mut(store.0)
745                .set_resource_destructor(idx, Some(func_ref));
746        }
747
748        // Next configure all `VMFuncRef`s for trampolines that this component
749        // will require. These functions won't actually get used until their
750        // associated state has been initialized through the global initializers
751        // below, but the funcrefs can all be configured here.
752        for (idx, sig) in env_component.trampolines.iter() {
753            let ptrs = self.component.trampoline_ptrs(idx);
754            let signature = match self.component.signatures().shared_type(*sig) {
755                Some(s) => s,
756                None => panic!("found unregistered signature: {sig:?}"),
757            };
758
759            self.instance_mut(store.0).set_trampoline(
760                idx,
761                ptrs.wasm_call,
762                ptrs.array_call,
763                signature,
764            );
765        }
766
767        // Initialize the unsafe intrinsics used by this component, if any.
768        for (i, module_ty) in env_component
769            .unsafe_intrinsics
770            .iter()
771            .enumerate()
772            .filter_map(|(i, ty)| ty.expand().map(|ty| (i, ty)))
773        {
774            let i = u32::try_from(i).unwrap();
775            let intrinsic = UnsafeIntrinsic::from_u32(i);
776            let ptrs = self.component.unsafe_intrinsic_ptrs(intrinsic).expect(
777                "should have intrinsic pointers given that we assigned the intrinsic a type",
778            );
779            let shared_ty = self
780                .component
781                .signatures()
782                .shared_type(module_ty)
783                .expect("should have a shared type");
784            self.instance_mut(store.0).set_intrinsic(
785                intrinsic,
786                ptrs.wasm_call,
787                ptrs.array_call,
788                shared_ty,
789            );
790        }
791
792        for initializer in env_component.initializers.iter() {
793            match initializer {
794                GlobalInitializer::InstantiateModule(m, component_instance) => {
795                    let instance = self.id;
796                    let module;
797                    let imports = match m {
798                        // Since upvars are statically know we know that the
799                        // `args` list is already in the right order.
800                        InstantiateModule::Static(idx, args) => {
801                            module = self.component.static_module(*idx);
802                            self.build_imports(store.0, module, args.iter())?
803                        }
804
805                        // With imports, unlike upvars, we need to do runtime
806                        // lookups with strings to determine the order of the
807                        // imports since it's whatever the actual module
808                        // requires.
809                        //
810                        // FIXME: see the note in `ExportItem::Name` handling
811                        // above for how we ideally shouldn't do string lookup
812                        // here.
813                        InstantiateModule::Import(idx, args) => {
814                            module = match &self.imports[*idx] {
815                                RuntimeImport::Module(m) => m,
816                                _ => unreachable!(),
817                            };
818                            let args = module
819                                .imports()
820                                .map(|import| &args[import.module()][import.name()]);
821                            self.build_imports(store.0, module, args)?
822                        }
823                    };
824
825                    let callee =
826                        component_instance.map(|index| RuntimeInstance { instance, index });
827
828                    // Note that the unsafety here should be ok because the
829                    // validity of the component means that type-checks have
830                    // already been performed. This means that the unsafety due
831                    // to imports having the wrong type should not happen here.
832                    //
833                    // Also note we are calling `new_raw` followed by
834                    // `start_raw` and will run the latter on a fiber if
835                    // required per `asyncness`.
836
837                    let (mut instance, needs_startup) = {
838                        let (mut limiter, store) = store.0.resource_limiter_and_store_opaque();
839                        unsafe {
840                            crate::Instance::new_raw(
841                                store,
842                                limiter.as_mut(),
843                                module,
844                                imports.as_ref(),
845                            )
846                            .await?
847                        }
848                    };
849
850                    if needs_startup {
851                        if asyncness == Asyncness::No {
852                            start_raw(store, instance, callee)?;
853                        } else {
854                            #[cfg(feature = "async")]
855                            {
856                                #[cfg(feature = "component-model-async")]
857                                {
858                                    if store.0.concurrency_support() {
859                                        // With concurrency support enabled, we must
860                                        // run the start function inside the store's
861                                        // event loop in case it calls async
862                                        // functions or intrinsics, creates and
863                                        // resumes threads, etc.
864                                        instance = store.start_instance(instance, callee).await?;
865                                    } else {
866                                        store
867                                            .on_fiber(|store| start_raw(store, instance, callee))
868                                            .await??;
869                                    }
870                                }
871                                #[cfg(not(feature = "component-model-async"))]
872                                {
873                                    _ = &mut instance;
874                                    store
875                                        .on_fiber(|store| start_raw(store, instance, callee))
876                                        .await??;
877                                }
878                            }
879                            #[cfg(not(feature = "async"))]
880                            {
881                                _ = &mut instance;
882                                unreachable!();
883                            }
884                        }
885                    }
886
887                    self.instance_mut(store.0).push_instance_id(instance.id())?;
888                }
889
890                GlobalInitializer::LowerImport { import, index } => {
891                    let func = match &self.imports[*import] {
892                        RuntimeImport::Func(func) => func,
893                        _ => unreachable!(),
894                    };
895                    self.instance_mut(store.0)
896                        .set_lowering(*index, func.lowering());
897                }
898
899                GlobalInitializer::ExtractTable(table) => self.extract_table(store.0, table),
900
901                GlobalInitializer::ExtractMemory(mem) => self.extract_memory(store.0, mem),
902
903                GlobalInitializer::ExtractRealloc(realloc) => {
904                    self.extract_realloc(store.0, realloc)
905                }
906
907                GlobalInitializer::ExtractCallback(callback) => {
908                    self.extract_callback(store.0, callback)
909                }
910
911                GlobalInitializer::ExtractPostReturn(post_return) => {
912                    self.extract_post_return(store.0, post_return)
913                }
914
915                GlobalInitializer::Resource(r) => self.resource(store.0, r)?,
916            }
917        }
918        Ok(())
919    }
920
921    fn resource(&mut self, store: &mut StoreOpaque, resource: &Resource) -> Result<()> {
922        let dtor = resource
923            .dtor
924            .as_ref()
925            .map(|dtor| lookup_vmdef(store, self.id, dtor));
926        let dtor = dtor.map(|export| match export {
927            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
928            _ => unreachable!(),
929        });
930        let index = self
931            .component
932            .env_component()
933            .resource_index(resource.index);
934        let instance = self.instance(store);
935        let ty = ResourceType::guest(store.id(), instance, resource.index);
936        self.instance_mut(store)
937            .set_resource_destructor(index, dtor);
938        let i = self.instance_resource_types_mut(store).push(ty)?;
939        debug_assert_eq!(i, index);
940        Ok(())
941    }
942
943    fn extract_memory(&mut self, store: &mut StoreOpaque, memory: &ExtractMemory) {
944        let import = match lookup_vmexport(store, self.id, &memory.export) {
945            crate::runtime::vm::Export::Memory(memory) => memory.vmimport(store),
946            crate::runtime::vm::Export::SharedMemory(_, import) => import,
947            _ => unreachable!(),
948        };
949        self.instance_mut(store)
950            .set_runtime_memory(memory.index, import.from.as_non_null());
951    }
952
953    fn extract_realloc(&mut self, store: &mut StoreOpaque, realloc: &ExtractRealloc) {
954        let func_ref = match lookup_vmdef(store, self.id, &realloc.def) {
955            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
956            _ => unreachable!(),
957        };
958        self.instance_mut(store)
959            .set_runtime_realloc(realloc.index, func_ref);
960    }
961
962    fn extract_callback(&mut self, store: &mut StoreOpaque, callback: &ExtractCallback) {
963        let func_ref = match lookup_vmdef(store, self.id, &callback.def) {
964            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
965            _ => unreachable!(),
966        };
967        self.instance_mut(store)
968            .set_runtime_callback(callback.index, func_ref);
969    }
970
971    fn extract_post_return(&mut self, store: &mut StoreOpaque, post_return: &ExtractPostReturn) {
972        let func_ref = match lookup_vmdef(store, self.id, &post_return.def) {
973            crate::runtime::vm::Export::Function(f) => f.vm_func_ref(store),
974            _ => unreachable!(),
975        };
976        self.instance_mut(store)
977            .set_runtime_post_return(post_return.index, func_ref);
978    }
979
980    fn extract_table(&mut self, store: &mut StoreOpaque, table: &ExtractTable) {
981        let export = match lookup_vmexport(store, self.id, &table.export) {
982            crate::runtime::vm::Export::Table(t) => t,
983            _ => unreachable!(),
984        };
985        let import = export.vmimport(store);
986        self.instance_mut(store)
987            .set_runtime_table(table.index, import);
988    }
989
990    fn build_imports<'b>(
991        &mut self,
992        store: &mut StoreOpaque,
993        module: &Module,
994        args: impl Iterator<Item = &'b CoreDef>,
995    ) -> Result<&OwnedImports, OutOfMemory> {
996        self.core_imports.clear();
997        self.core_imports.reserve(module)?;
998        let mut imports = module.compiled_module().module().imports();
999
1000        for arg in args {
1001            // The general idea of Wasmtime is that at runtime type-checks for
1002            // core wasm instantiations internally within a component are
1003            // unnecessary and superfluous. Naturally though mistakes may be
1004            // made, so double-check this property of wasmtime in debug mode.
1005
1006            if cfg!(debug_assertions) {
1007                let (imp_module, imp_name, expected) = imports.next().unwrap();
1008                self.assert_type_matches(store, module, arg, imp_module, imp_name, expected);
1009            }
1010
1011            // The unsafety here should be ok since the `export` is loaded
1012            // directly from an instance which should only give us valid export
1013            // items.
1014            let export = lookup_vmdef(store, self.id, arg);
1015            self.core_imports.push_export(store, &export)?;
1016        }
1017        debug_assert!(imports.next().is_none());
1018
1019        Ok(&self.core_imports)
1020    }
1021
1022    fn assert_type_matches(
1023        &self,
1024        store: &mut StoreOpaque,
1025        module: &Module,
1026        arg: &CoreDef,
1027        imp_module: &str,
1028        imp_name: &str,
1029        expected: EntityType,
1030    ) {
1031        let export = lookup_vmdef(store, self.id, arg);
1032
1033        // If this value is a core wasm function then the type check is inlined
1034        // here. This can otherwise fail `Extern::from_wasmtime_export` because
1035        // there's no guarantee that there exists a trampoline for `f` so this
1036        // can't fall through to the case below
1037        if let crate::runtime::vm::Export::Function(f) = &export {
1038            let expected = match expected.unwrap_func() {
1039                EngineOrModuleTypeIndex::Engine(e) => Some(e),
1040                EngineOrModuleTypeIndex::Module(m) => module.signatures().shared_type(m),
1041                EngineOrModuleTypeIndex::RecGroup(_) => unreachable!(),
1042            };
1043            let actual = unsafe { f.vm_func_ref(store).as_ref().type_index };
1044            assert!(
1045                expected.is_some_and(|e| store.engine().signatures().is_subtype(actual, e)),
1046                "type mismatch for import {imp_module:?} {imp_name:?}!!!\n\n\
1047                 expected {:#?}\n\n\
1048                 found {:#?}",
1049                expected.and_then(|e| store.engine().signatures().borrow(e)),
1050                store.engine().signatures().borrow(actual)
1051            );
1052            return;
1053        }
1054
1055        let val = crate::Extern::from_wasmtime_export(export, store.engine());
1056        let ty = DefinitionType::from(store, &val);
1057        crate::types::matching::MatchCx::new(module.engine())
1058            .definition(&expected, &ty)
1059            .expect("unexpected typecheck failure");
1060    }
1061
1062    /// Convenience helper to return the `&ComponentInstance` that's being
1063    /// instantiated.
1064    fn instance<'b>(&self, store: &'b StoreOpaque) -> &'b ComponentInstance {
1065        store.store_data().component_instance(self.id)
1066    }
1067
1068    /// Same as [`Self::instance`], but for mutability.
1069    fn instance_mut<'b>(&self, store: &'b mut StoreOpaque) -> Pin<&'b mut ComponentInstance> {
1070        store.store_data_mut().component_instance_mut(self.id)
1071    }
1072
1073    // NB: This method is only intended to be called during the instantiation
1074    // process because the `Arc::get_mut` here is fallible and won't generally
1075    // succeed once the instance has been handed to the embedder. Before that
1076    // though it should be guaranteed that the single owning reference currently
1077    // lives within the `ComponentInstance` that's being built.
1078    fn instance_resource_types_mut<'b>(
1079        &self,
1080        store: &'b mut StoreOpaque,
1081    ) -> &'b mut ImportedResources {
1082        Arc::get_mut(self.instance_mut(store).resource_types_mut()).unwrap()
1083    }
1084}
1085
1086/// Runs the start function of the core wasm `instance`.
1087///
1088/// If `callee` is specified then the start function is run as a sync-lifted
1089/// call into that component instance.
1090pub(crate) fn start_raw<T>(
1091    store: &mut StoreContextMut<'_, T>,
1092    instance: crate::Instance,
1093    callee: Option<RuntimeInstance>,
1094) -> Result<()> {
1095    if let Some(callee) = callee {
1096        store.0.enter_guest_sync_call(false, callee)?;
1097    }
1098    instance.start_raw(store, UncaughtException::Trap)?;
1099    if callee.is_some() {
1100        store.0.exit_guest_sync_call()?;
1101    }
1102    Ok(())
1103}
1104
1105/// A "pre-instantiated" [`Instance`] which has all of its arguments already
1106/// supplied and is ready to instantiate.
1107///
1108/// This structure represents an efficient form of instantiation where import
1109/// type-checking and import lookup has all been resolved by the time that this
1110/// type is created. This type is primarily created through the
1111/// [`Linker::instantiate_pre`](crate::component::Linker::instantiate_pre)
1112/// method.
1113pub struct InstancePre<T: 'static> {
1114    component: Component,
1115    imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
1116    resource_types: Arc<TryPrimaryMap<ResourceIndex, ResourceType>>,
1117    asyncness: Asyncness,
1118    _marker: marker::PhantomData<fn() -> T>,
1119}
1120
1121// `InstancePre`'s clone does not require `T: Clone`
1122impl<T: 'static> Clone for InstancePre<T> {
1123    fn clone(&self) -> Self {
1124        Self {
1125            component: self.component.clone(),
1126            imports: self.imports.clone(),
1127            resource_types: self.resource_types.clone(),
1128            asyncness: self.asyncness,
1129            _marker: self._marker,
1130        }
1131    }
1132}
1133
1134impl<T: 'static> InstancePre<T> {
1135    /// This function is `unsafe` since there's no guarantee that the
1136    /// `RuntimeImport` items provided are guaranteed to work with the `T` of
1137    /// the store.
1138    ///
1139    /// Additionally there is no static guarantee that the `imports` provided
1140    /// satisfy the imports of the `component` provided.
1141    pub(crate) unsafe fn new_unchecked(
1142        component: Component,
1143        imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
1144        resource_types: Arc<TryPrimaryMap<ResourceIndex, ResourceType>>,
1145    ) -> InstancePre<T> {
1146        let mut asyncness = Asyncness::No;
1147        for (_, import) in imports.iter() {
1148            asyncness = asyncness
1149                | match import {
1150                    RuntimeImport::Func(f) => f.asyncness(),
1151                    RuntimeImport::Module(_) => Asyncness::No,
1152                    RuntimeImport::Resource { dtor, .. } => dtor.asyncness(),
1153                };
1154        }
1155        InstancePre {
1156            component,
1157            imports,
1158            resource_types,
1159            asyncness,
1160            _marker: marker::PhantomData,
1161        }
1162    }
1163
1164    /// Returns the underlying component that will be instantiated.
1165    pub fn component(&self) -> &Component {
1166        &self.component
1167    }
1168
1169    #[doc(hidden)]
1170    /// Returns the type at which the underlying component will be
1171    /// instantiated. This contains the instantiated type information which
1172    /// was determined by the Linker.
1173    pub fn instance_type(&self) -> InstanceType<'_> {
1174        InstanceType {
1175            types: &self.component.types(),
1176            resources: Some(&self.resource_types),
1177        }
1178    }
1179
1180    /// Returns the underlying engine.
1181    pub fn engine(&self) -> &Engine {
1182        self.component.engine()
1183    }
1184
1185    /// Performs the instantiation process into the store specified.
1186    ///
1187    /// # Errors
1188    ///
1189    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1190    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1191    /// details on Wasmtime's out-of-memory handling.
1192    //
1193    // TODO: needs more docs
1194    pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
1195        let store = store.as_context_mut();
1196
1197        // If this instance requires an async host, set that flag in the store,
1198        // and then afterwards assert nothing else in the store, nor this
1199        // instance, required async.
1200        store.0.set_async_required(self.asyncness);
1201        store.0.validate_sync_call()?;
1202
1203        vm::assert_ready(self._instantiate(store, Asyncness::No))
1204    }
1205    /// Performs the instantiation process into the store specified.
1206    ///
1207    /// Exactly like [`Self::instantiate`] except for use on async stores.
1208    ///
1209    /// # Errors
1210    ///
1211    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1212    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1213    /// details on Wasmtime's out-of-memory handling.
1214    //
1215    // TODO: needs more docs
1216    #[cfg(feature = "async")]
1217    pub async fn instantiate_async(&self, store: impl AsContextMut<Data = T>) -> Result<Instance> {
1218        self._instantiate(store, Asyncness::Yes).await
1219    }
1220
1221    async fn _instantiate(
1222        &self,
1223        mut store: impl AsContextMut<Data = T>,
1224        asyncness: Asyncness,
1225    ) -> Result<Instance> {
1226        let store = store.as_context_mut();
1227        store.0.set_async_required(self.asyncness);
1228        store
1229            .engine()
1230            .allocator()
1231            .increment_component_instance_count()?;
1232
1233        // Helper structure to pair the above increment with a decrement should
1234        // anything fail below.
1235        let mut decrement = DecrementComponentInstanceCountOnDrop {
1236            store,
1237            enabled: true,
1238        };
1239
1240        let mut instantiator =
1241            Instantiator::new(&self.component, decrement.store.0, &self.imports)?;
1242        instantiator.run(&mut decrement.store, asyncness).await?;
1243
1244        let instance = Instance::from_wasmtime(decrement.store.0, instantiator.id);
1245        decrement.store.0.push_component_instance(instance);
1246
1247        // Everything has passed, don't decrement the instance count and let the
1248        // destructor for the `Store` handle that at this point.
1249        decrement.enabled = false;
1250        return Ok(instance);
1251
1252        struct DecrementComponentInstanceCountOnDrop<'a, T: 'static> {
1253            store: StoreContextMut<'a, T>,
1254            enabled: bool,
1255        }
1256
1257        impl<T> Drop for DecrementComponentInstanceCountOnDrop<'_, T> {
1258            fn drop(&mut self) {
1259                if self.enabled {
1260                    self.store
1261                        .engine()
1262                        .allocator()
1263                        .decrement_component_instance_count();
1264                }
1265            }
1266        }
1267    }
1268}