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