ureeves_wasmtime/runtime/component/
component.rs

1use crate::component::matching::InstanceType;
2use crate::component::types;
3use crate::component::InstanceExportLookup;
4use crate::prelude::*;
5use crate::runtime::vm::component::ComponentRuntimeInfo;
6use crate::runtime::vm::{
7    CompiledModuleId, VMArrayCallFunction, VMFuncRef, VMFunctionBody, VMWasmCallFunction,
8};
9use crate::{
10    code::CodeObject, code_memory::CodeMemory, type_registry::TypeCollection, Engine, Module,
11    ResourcesRequired,
12};
13use crate::{FuncType, ValType};
14use alloc::sync::Arc;
15use core::any::Any;
16use core::mem;
17use core::ops::Range;
18use core::ptr::NonNull;
19#[cfg(feature = "std")]
20use std::path::Path;
21use wasmtime_environ::component::{
22    AllCallFunc, CompiledComponentInfo, ComponentArtifacts, ComponentTypes, Export, ExportIndex,
23    GlobalInitializer, InstantiateModule, NameMapNoIntern, StaticModuleIndex, TrampolineIndex,
24    TypeComponentIndex, TypeDef, VMComponentOffsets,
25};
26use wasmtime_environ::{FunctionLoc, HostPtr, ObjectKind, PrimaryMap};
27
28/// A compiled WebAssembly Component.
29///
30/// This structure represents a compiled component that is ready to be
31/// instantiated. This owns a region of virtual memory which contains executable
32/// code compiled from a WebAssembly binary originally. This is the analog of
33/// [`Module`](crate::Module) in the component embedding API.
34///
35/// A [`Component`] can be turned into an
36/// [`Instance`](crate::component::Instance) through a
37/// [`Linker`](crate::component::Linker). [`Component`]s are safe to share
38/// across threads. The compilation model of a component is the same as that of
39/// [a module](crate::Module) which is to say:
40///
41/// * Compilation happens synchronously during [`Component::new`].
42/// * The result of compilation can be saved into storage with
43///   [`Component::serialize`].
44/// * A previously compiled artifact can be parsed with
45///   [`Component::deserialize`].
46/// * No compilation happens at runtime for a component — everything is done
47///   by the time [`Component::new`] returns.
48///
49/// ## Components and `Clone`
50///
51/// Using `clone` on a `Component` is a cheap operation. It will not create an
52/// entirely new component, but rather just a new reference to the existing
53/// component. In other words it's a shallow copy, not a deep copy.
54///
55/// ## Examples
56///
57/// For example usage see the documentation of [`Module`](crate::Module) as
58/// [`Component`] has the same high-level API.
59#[derive(Clone)]
60pub struct Component {
61    inner: Arc<ComponentInner>,
62}
63
64struct ComponentInner {
65    /// Unique id for this component within this process.
66    ///
67    /// Note that this is repurposing ids for modules intentionally as there
68    /// shouldn't be an issue overlapping them.
69    id: CompiledModuleId,
70
71    /// The engine that this component belongs to.
72    engine: Engine,
73
74    /// Component type index
75    ty: TypeComponentIndex,
76
77    /// Core wasm modules that the component defined internally, indexed by the
78    /// compile-time-assigned `ModuleUpvarIndex`.
79    static_modules: PrimaryMap<StaticModuleIndex, Module>,
80
81    /// Code-related information such as the compiled artifact, type
82    /// information, etc.
83    ///
84    /// Note that the `Arc` here is used to share this allocation with internal
85    /// modules.
86    code: Arc<CodeObject>,
87
88    /// Metadata produced during compilation.
89    info: CompiledComponentInfo,
90
91    /// A cached handle to the `wasmtime::FuncType` for the canonical ABI's
92    /// `realloc`, to avoid the need to look up types in the registry and take
93    /// locks when calling `realloc` via `TypedFunc::call_raw`.
94    realloc_func_type: Arc<dyn Any + Send + Sync>,
95}
96
97pub(crate) struct AllCallFuncPointers {
98    pub wasm_call: NonNull<VMWasmCallFunction>,
99    pub array_call: VMArrayCallFunction,
100}
101
102impl Component {
103    /// Compiles a new WebAssembly component from the in-memory list of bytes
104    /// provided.
105    ///
106    /// The `bytes` provided can either be the binary or text format of a
107    /// [WebAssembly component]. Note that the text format requires the `wat`
108    /// feature of this crate to be enabled. This API does not support
109    /// streaming compilation.
110    ///
111    /// This function will synchronously validate the entire component,
112    /// including all core modules, and then compile all components, modules,
113    /// etc., found within the provided bytes.
114    ///
115    /// [WebAssembly component]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md
116    ///
117    /// # Errors
118    ///
119    /// This function may fail and return an error. Errors may include
120    /// situations such as:
121    ///
122    /// * The binary provided could not be decoded because it's not a valid
123    ///   WebAssembly binary
124    /// * The WebAssembly binary may not validate (e.g. contains type errors)
125    /// * Implementation-specific limits were exceeded with a valid binary (for
126    ///   example too many locals)
127    /// * The wasm binary may use features that are not enabled in the
128    ///   configuration of `engine`
129    /// * If the `wat` feature is enabled and the input is text, then it may be
130    ///   rejected if it fails to parse.
131    ///
132    /// The error returned should contain full information about why compilation
133    /// failed.
134    ///
135    /// # Examples
136    ///
137    /// The `new` function can be invoked with a in-memory array of bytes:
138    ///
139    /// ```no_run
140    /// # use wasmtime::*;
141    /// # use wasmtime::component::Component;
142    /// # fn main() -> anyhow::Result<()> {
143    /// # let engine = Engine::default();
144    /// # let wasm_bytes: Vec<u8> = Vec::new();
145    /// let component = Component::new(&engine, &wasm_bytes)?;
146    /// # Ok(())
147    /// # }
148    /// ```
149    ///
150    /// Or you can also pass in a string to be parsed as the wasm text
151    /// format:
152    ///
153    /// ```
154    /// # use wasmtime::*;
155    /// # use wasmtime::component::Component;
156    /// # fn main() -> anyhow::Result<()> {
157    /// # let engine = Engine::default();
158    /// let component = Component::new(&engine, "(component (core module))")?;
159    /// # Ok(())
160    /// # }
161    #[cfg(any(feature = "cranelift", feature = "winch"))]
162    pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> {
163        crate::CodeBuilder::new(engine)
164            .wasm_binary_or_text(bytes.as_ref(), None)?
165            .compile_component()
166    }
167
168    /// Compiles a new WebAssembly component from a wasm file on disk pointed
169    /// to by `file`.
170    ///
171    /// This is a convenience function for reading the contents of `file` on
172    /// disk and then calling [`Component::new`].
173    #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))]
174    pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Component> {
175        crate::CodeBuilder::new(engine)
176            .wasm_binary_or_text_file(file.as_ref())?
177            .compile_component()
178    }
179
180    /// Compiles a new WebAssembly component from the in-memory wasm image
181    /// provided.
182    ///
183    /// This function is the same as [`Component::new`] except that it does not
184    /// accept the text format of WebAssembly. Even if the `wat` feature
185    /// is enabled an error will be returned here if `binary` is the text
186    /// format.
187    ///
188    /// For more information on semantics and errors see [`Component::new`].
189    #[cfg(any(feature = "cranelift", feature = "winch"))]
190    pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Component> {
191        crate::CodeBuilder::new(engine)
192            .wasm_binary(binary, None)?
193            .compile_component()
194    }
195
196    /// Same as [`Module::deserialize`], but for components.
197    ///
198    /// Note that the bytes referenced here must contain contents previously
199    /// produced by [`Engine::precompile_component`] or
200    /// [`Component::serialize`].
201    ///
202    /// For more information see the [`Module::deserialize`] method.
203    ///
204    /// # Unsafety
205    ///
206    /// The unsafety of this method is the same as that of the
207    /// [`Module::deserialize`] method.
208    ///
209    /// [`Module::deserialize`]: crate::Module::deserialize
210    pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> {
211        let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Component)?;
212        Component::from_parts(engine, code, None)
213    }
214
215    /// Same as [`Module::deserialize_file`], but for components.
216    ///
217    /// Note that the file referenced here must contain contents previously
218    /// produced by [`Engine::precompile_component`] or
219    /// [`Component::serialize`].
220    ///
221    /// For more information see the [`Module::deserialize_file`] method.
222    ///
223    /// # Unsafety
224    ///
225    /// The unsafety of this method is the same as that of the
226    /// [`Module::deserialize_file`] method.
227    ///
228    /// [`Module::deserialize_file`]: crate::Module::deserialize_file
229    #[cfg(feature = "std")]
230    pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component> {
231        let code = engine.load_code_file(path.as_ref(), ObjectKind::Component)?;
232        Component::from_parts(engine, code, None)
233    }
234
235    /// Returns the type of this component as a [`types::Component`].
236    ///
237    /// This method enables runtime introspection of the type of a component
238    /// before instantiation, if necessary.
239    ///
240    /// ## Component types and Resources
241    ///
242    /// An important point to note here is that the precise type of imports and
243    /// exports of a component change when it is instantiated with respect to
244    /// resources. For example a [`Component`] represents an un-instantiated
245    /// component meaning that its imported resources are represented as abstract
246    /// resource types. These abstract types are not equal to any other
247    /// component's types.
248    ///
249    /// For example:
250    ///
251    /// ```
252    /// # use wasmtime::Engine;
253    /// # use wasmtime::component::Component;
254    /// # use wasmtime::component::types::ComponentItem;
255    /// # fn main() -> wasmtime::Result<()> {
256    /// # let engine = Engine::default();
257    /// let a = Component::new(&engine, r#"
258    ///     (component (import "x" (type (sub resource))))
259    /// "#)?;
260    /// let b = Component::new(&engine, r#"
261    ///     (component (import "x" (type (sub resource))))
262    /// "#)?;
263    ///
264    /// let (_, a_ty) = a.component_type().imports(&engine).next().unwrap();
265    /// let (_, b_ty) = b.component_type().imports(&engine).next().unwrap();
266    ///
267    /// let a_ty = match a_ty {
268    ///     ComponentItem::Resource(ty) => ty,
269    ///     _ => unreachable!(),
270    /// };
271    /// let b_ty = match b_ty {
272    ///     ComponentItem::Resource(ty) => ty,
273    ///     _ => unreachable!(),
274    /// };
275    /// assert!(a_ty != b_ty);
276    /// # Ok(())
277    /// # }
278    /// ```
279    ///
280    /// Additionally, however, these abstract types are "substituted" during
281    /// instantiation meaning that a component type will appear to have changed
282    /// once it is instantiated.
283    ///
284    /// ```
285    /// # use wasmtime::{Engine, Store};
286    /// # use wasmtime::component::{Component, Linker, ResourceType};
287    /// # use wasmtime::component::types::ComponentItem;
288    /// # fn main() -> wasmtime::Result<()> {
289    /// # let engine = Engine::default();
290    /// // Here this component imports a resource and then exports it as-is
291    /// // which means that the export is equal to the import.
292    /// let a = Component::new(&engine, r#"
293    ///     (component
294    ///         (import "x" (type $x (sub resource)))
295    ///         (export "x" (type $x))
296    ///     )
297    /// "#)?;
298    ///
299    /// let (_, import) = a.component_type().imports(&engine).next().unwrap();
300    /// let (_, export) = a.component_type().exports(&engine).next().unwrap();
301    ///
302    /// let import = match import {
303    ///     ComponentItem::Resource(ty) => ty,
304    ///     _ => unreachable!(),
305    /// };
306    /// let export = match export {
307    ///     ComponentItem::Resource(ty) => ty,
308    ///     _ => unreachable!(),
309    /// };
310    /// assert_eq!(import, export);
311    ///
312    /// // However after instantiation the resource type "changes"
313    /// let mut store = Store::new(&engine, ());
314    /// let mut linker = Linker::new(&engine);
315    /// linker.root().resource("x", ResourceType::host::<()>(), |_, _| Ok(()))?;
316    /// let instance = linker.instantiate(&mut store, &a)?;
317    /// let instance_ty = instance.get_resource(&mut store, "x").unwrap();
318    ///
319    /// // Here `instance_ty` is not the same as either `import` or `export`,
320    /// // but it is equal to what we provided as an import.
321    /// assert!(instance_ty != import);
322    /// assert!(instance_ty != export);
323    /// assert!(instance_ty == ResourceType::host::<()>());
324    /// # Ok(())
325    /// # }
326    /// ```
327    ///
328    /// Finally, each instantiation of an exported resource from a component is
329    /// considered "fresh" for all instantiations meaning that different
330    /// instantiations will have different exported resource types:
331    ///
332    /// ```
333    /// # use wasmtime::{Engine, Store};
334    /// # use wasmtime::component::{Component, Linker};
335    /// # fn main() -> wasmtime::Result<()> {
336    /// # let engine = Engine::default();
337    /// let a = Component::new(&engine, r#"
338    ///     (component
339    ///         (type $x (resource (rep i32)))
340    ///         (export "x" (type $x))
341    ///     )
342    /// "#)?;
343    ///
344    /// let mut store = Store::new(&engine, ());
345    /// let linker = Linker::new(&engine);
346    /// let instance1 = linker.instantiate(&mut store, &a)?;
347    /// let instance2 = linker.instantiate(&mut store, &a)?;
348    ///
349    /// let x1 = instance1.get_resource(&mut store, "x").unwrap();
350    /// let x2 = instance2.get_resource(&mut store, "x").unwrap();
351    ///
352    /// // Despite these two resources being the same export of the same
353    /// // component they come from two different instances meaning that their
354    /// // types will be unique.
355    /// assert!(x1 != x2);
356    /// # Ok(())
357    /// # }
358    /// ```
359    pub fn component_type(&self) -> types::Component {
360        self.with_uninstantiated_instance_type(|ty| types::Component::from(self.inner.ty, ty))
361    }
362
363    fn with_uninstantiated_instance_type<R>(&self, f: impl FnOnce(&InstanceType<'_>) -> R) -> R {
364        let resources = Arc::new(PrimaryMap::new());
365        f(&InstanceType {
366            types: self.types(),
367            resources: &resources,
368        })
369    }
370
371    /// Final assembly step for a component from its in-memory representation.
372    ///
373    /// If the `artifacts` are specified as `None` here then they will be
374    /// deserialized from `code_memory`.
375    pub(crate) fn from_parts(
376        engine: &Engine,
377        code_memory: Arc<CodeMemory>,
378        artifacts: Option<ComponentArtifacts>,
379    ) -> Result<Component> {
380        let ComponentArtifacts {
381            ty,
382            info,
383            types,
384            static_modules,
385        } = match artifacts {
386            Some(artifacts) => artifacts,
387            None => postcard::from_bytes(code_memory.wasmtime_info()).err2anyhow()?,
388        };
389
390        // Validate that the component can be used with the current instance
391        // allocator.
392        engine.allocator().validate_component(
393            &info.component,
394            &VMComponentOffsets::new(HostPtr, &info.component),
395            &|module_index| &static_modules[module_index].module,
396        )?;
397
398        // Create a signature registration with the `Engine` for all trampolines
399        // and core wasm types found within this component, both for the
400        // component and for all included core wasm modules.
401        let signatures = TypeCollection::new_for_module(engine, types.module_types());
402
403        // Assemble the `CodeObject` artifact which is shared by all core wasm
404        // modules as well as the final component.
405        let types = Arc::new(types);
406        let code = Arc::new(CodeObject::new(code_memory, signatures, types.into()));
407
408        // Convert all information about static core wasm modules into actual
409        // `Module` instances by converting each `CompiledModuleInfo`, the
410        // `types` type information, and the code memory to a runtime object.
411        let static_modules = static_modules
412            .into_iter()
413            .map(|(_, info)| Module::from_parts_raw(engine, code.clone(), info, false))
414            .collect::<Result<_>>()?;
415
416        let realloc_func_type = Arc::new(FuncType::new(
417            engine,
418            [ValType::I32, ValType::I32, ValType::I32, ValType::I32],
419            [ValType::I32],
420        )) as _;
421
422        Ok(Component {
423            inner: Arc::new(ComponentInner {
424                id: CompiledModuleId::new(),
425                engine: engine.clone(),
426                ty,
427                static_modules,
428                code,
429                info,
430                realloc_func_type,
431            }),
432        })
433    }
434
435    pub(crate) fn ty(&self) -> TypeComponentIndex {
436        self.inner.ty
437    }
438
439    pub(crate) fn env_component(&self) -> &wasmtime_environ::component::Component {
440        &self.inner.info.component
441    }
442
443    pub(crate) fn static_module(&self, idx: StaticModuleIndex) -> &Module {
444        &self.inner.static_modules[idx]
445    }
446
447    #[inline]
448    pub(crate) fn types(&self) -> &Arc<ComponentTypes> {
449        self.inner.component_types()
450    }
451
452    pub(crate) fn signatures(&self) -> &TypeCollection {
453        self.inner.code.signatures()
454    }
455
456    pub(crate) fn text(&self) -> &[u8] {
457        self.inner.code.code_memory().text()
458    }
459
460    pub(crate) fn trampoline_ptrs(&self, index: TrampolineIndex) -> AllCallFuncPointers {
461        let AllCallFunc {
462            wasm_call,
463            array_call,
464        } = &self.inner.info.trampolines[index];
465        AllCallFuncPointers {
466            wasm_call: self.func(wasm_call).cast(),
467            array_call: unsafe {
468                mem::transmute::<NonNull<VMFunctionBody>, VMArrayCallFunction>(
469                    self.func(array_call),
470                )
471            },
472        }
473    }
474
475    fn func(&self, loc: &FunctionLoc) -> NonNull<VMFunctionBody> {
476        let text = self.text();
477        let trampoline = &text[loc.start as usize..][..loc.length as usize];
478        NonNull::new(trampoline.as_ptr() as *mut VMFunctionBody).unwrap()
479    }
480
481    pub(crate) fn code_object(&self) -> &Arc<CodeObject> {
482        &self.inner.code
483    }
484
485    /// Same as [`Module::serialize`], except for a component.
486    ///
487    /// Note that the artifact produced here must be passed to
488    /// [`Component::deserialize`] and is not compatible for use with
489    /// [`Module`].
490    ///
491    /// [`Module::serialize`]: crate::Module::serialize
492    /// [`Module`]: crate::Module
493    pub fn serialize(&self) -> Result<Vec<u8>> {
494        Ok(self.code_object().code_memory().mmap().to_vec())
495    }
496
497    pub(crate) fn runtime_info(&self) -> Arc<dyn ComponentRuntimeInfo> {
498        self.inner.clone()
499    }
500
501    /// Creates a new `VMFuncRef` with all fields filled out for the destructor
502    /// specified.
503    ///
504    /// The `dtor`'s own `VMFuncRef` won't have `wasm_call` filled out but this
505    /// component may have `resource_drop_wasm_to_native_trampoline` filled out
506    /// if necessary in which case it's filled in here.
507    pub(crate) fn resource_drop_func_ref(&self, dtor: &crate::func::HostFunc) -> VMFuncRef {
508        // Host functions never have their `wasm_call` filled in at this time.
509        assert!(dtor.func_ref().wasm_call.is_none());
510
511        // Note that if `resource_drop_wasm_to_native_trampoline` is not present
512        // then this can't be called by the component, so it's ok to leave it
513        // blank.
514        let wasm_call = self
515            .inner
516            .info
517            .resource_drop_wasm_to_array_trampoline
518            .as_ref()
519            .map(|i| self.func(i).cast());
520        VMFuncRef {
521            wasm_call,
522            ..*dtor.func_ref()
523        }
524    }
525
526    /// Returns a summary of the resources required to instantiate this
527    /// [`Component`][crate::component::Component].
528    ///
529    /// Note that when a component imports and instantiates another component or
530    /// core module, we cannot determine ahead of time how many resources
531    /// instantiating this component will require, and therefore this method
532    /// will return `None` in these scenarios.
533    ///
534    /// Potential uses of the returned information:
535    ///
536    /// * Determining whether your pooling allocator configuration supports
537    ///   instantiating this component.
538    ///
539    /// * Deciding how many of which `Component` you want to instantiate within
540    ///   a fixed amount of resources, e.g. determining whether to create 5
541    ///   instances of component X or 10 instances of component Y.
542    ///
543    /// # Example
544    ///
545    /// ```
546    /// # fn main() -> wasmtime::Result<()> {
547    /// use wasmtime::{Config, Engine, component::Component};
548    ///
549    /// let mut config = Config::new();
550    /// config.wasm_multi_memory(true);
551    /// config.wasm_component_model(true);
552    /// let engine = Engine::new(&config)?;
553    ///
554    /// let component = Component::new(&engine, &r#"
555    ///     (component
556    ///         ;; Define a core module that uses two memories.
557    ///         (core module $m
558    ///             (memory 1)
559    ///             (memory 6)
560    ///         )
561    ///
562    ///         ;; Instantiate that core module three times.
563    ///         (core instance $i1 (instantiate (module $m)))
564    ///         (core instance $i2 (instantiate (module $m)))
565    ///         (core instance $i3 (instantiate (module $m)))
566    ///     )
567    /// "#)?;
568    ///
569    /// let resources = component.resources_required()
570    ///     .expect("this component does not import any core modules or instances");
571    ///
572    /// // Instantiating the component will require allocating two memories per
573    /// // core instance, and there are three instances, so six total memories.
574    /// assert_eq!(resources.num_memories, 6);
575    /// assert_eq!(resources.max_initial_memory_size, Some(6));
576    ///
577    /// // The component doesn't need any tables.
578    /// assert_eq!(resources.num_tables, 0);
579    /// assert_eq!(resources.max_initial_table_size, None);
580    /// # Ok(()) }
581    /// ```
582    pub fn resources_required(&self) -> Option<ResourcesRequired> {
583        let mut resources = ResourcesRequired {
584            num_memories: 0,
585            max_initial_memory_size: None,
586            num_tables: 0,
587            max_initial_table_size: None,
588        };
589        for init in &self.env_component().initializers {
590            match init {
591                GlobalInitializer::InstantiateModule(inst) => match inst {
592                    InstantiateModule::Static(index, _) => {
593                        let module = self.static_module(*index);
594                        resources.add(&module.resources_required());
595                    }
596                    InstantiateModule::Import(_, _) => {
597                        // We can't statically determine the resources required
598                        // to instantiate this component.
599                        return None;
600                    }
601                },
602                GlobalInitializer::LowerImport { .. }
603                | GlobalInitializer::ExtractMemory(_)
604                | GlobalInitializer::ExtractRealloc(_)
605                | GlobalInitializer::ExtractPostReturn(_)
606                | GlobalInitializer::Resource(_) => {}
607            }
608        }
609        Some(resources)
610    }
611
612    /// Returns the range, in the host's address space, that this module's
613    /// compiled code resides at.
614    ///
615    /// For more information see
616    /// [`Module::image_range`](crate::Module::image_range).
617    pub fn image_range(&self) -> Range<*const u8> {
618        self.inner.code.code_memory().mmap().image_range()
619    }
620
621    /// Force initialization of copy-on-write images to happen here-and-now
622    /// instead of when they're requested during first instantiation.
623    ///
624    /// When [copy-on-write memory
625    /// initialization](crate::Config::memory_init_cow) is enabled then Wasmtime
626    /// will lazily create the initialization image for a component. This method
627    /// can be used to explicitly dictate when this initialization happens.
628    ///
629    /// Note that this largely only matters on Linux when memfd is used.
630    /// Otherwise the copy-on-write image typically comes from disk and in that
631    /// situation the creation of the image is trivial as the image is always
632    /// sourced from disk. On Linux, though, when memfd is used a memfd is
633    /// created and the initialization image is written to it.
634    ///
635    /// Also note that this method is not required to be called, it's available
636    /// as a performance optimization if required but is otherwise handled
637    /// automatically.
638    pub fn initialize_copy_on_write_image(&self) -> Result<()> {
639        for (_, module) in self.inner.static_modules.iter() {
640            module.initialize_copy_on_write_image()?;
641        }
642        Ok(())
643    }
644
645    /// Looks up a specific export of this component by `name` optionally nested
646    /// within the `instance` provided.
647    ///
648    /// This method is primarily used to acquire a [`ComponentExportIndex`]
649    /// which can be used with [`Instance`](crate::component::Instance) when
650    /// looking up exports. Export lookup with [`ComponentExportIndex`] can
651    /// skip string lookups at runtime and instead use a more efficient
652    /// index-based lookup.
653    ///
654    /// This method takes a few arguments:
655    ///
656    /// * `engine` - the engine that was used to compile this component.
657    /// * `instance` - an optional "parent instance" for the export being looked
658    ///   up. If this is `None` then the export is looked up on the root of the
659    ///   component itself, and otherwise the export is looked up on the
660    ///   `instance` specified. Note that `instance` must have come from a
661    ///   previous invocation of this method.
662    /// * `name` - the name of the export that's being looked up.
663    ///
664    /// If the export is located then two values are returned: a
665    /// [`types::ComponentItem`] which enables introspection about the type of
666    /// the export and a [`ComponentExportIndex`]. The index returned notably
667    /// implements the [`InstanceExportLookup`] trait which enables using it
668    /// with [`Instance::get_func`](crate::component::Instance::get_func) for
669    /// example.
670    ///
671    /// # Examples
672    ///
673    /// ```
674    /// use wasmtime::{Engine, Store};
675    /// use wasmtime::component::{Component, Linker};
676    /// use wasmtime::component::types::ComponentItem;
677    ///
678    /// # fn main() -> wasmtime::Result<()> {
679    /// let engine = Engine::default();
680    /// let component = Component::new(
681    ///     &engine,
682    ///     r#"
683    ///         (component
684    ///             (core module $m
685    ///                 (func (export "f"))
686    ///             )
687    ///             (core instance $i (instantiate $m))
688    ///             (func (export "f")
689    ///                 (canon lift (core func $i "f")))
690    ///         )
691    ///     "#,
692    /// )?;
693    ///
694    /// // Perform a lookup of the function "f" before instantiaton.
695    /// let (ty, export) = component.export_index(None, "f").unwrap();
696    /// assert!(matches!(ty, ComponentItem::ComponentFunc(_)));
697    ///
698    /// // After instantiation use `export` to lookup the function in question
699    /// // which notably does not do a string lookup at runtime.
700    /// let mut store = Store::new(&engine, ());
701    /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
702    /// let func = instance.get_typed_func::<(), ()>(&mut store, &export)?;
703    /// // ...
704    /// # Ok(())
705    /// # }
706    /// ```
707    pub fn export_index(
708        &self,
709        instance: Option<&ComponentExportIndex>,
710        name: &str,
711    ) -> Option<(types::ComponentItem, ComponentExportIndex)> {
712        let info = self.env_component();
713        let index = self.lookup_export_index(instance, name)?;
714        let ty = match info.export_items[index] {
715            Export::Instance { ty, .. } => TypeDef::ComponentInstance(ty),
716            Export::LiftedFunction { ty, .. } => TypeDef::ComponentFunc(ty),
717            Export::ModuleStatic { ty, .. } | Export::ModuleImport { ty, .. } => {
718                TypeDef::Module(ty)
719            }
720            Export::Type(ty) => ty,
721        };
722        let item = self.with_uninstantiated_instance_type(|instance| {
723            types::ComponentItem::from(&self.inner.engine, &ty, instance)
724        });
725        Some((
726            item,
727            ComponentExportIndex {
728                id: self.inner.id,
729                index,
730            },
731        ))
732    }
733
734    pub(crate) fn lookup_export_index(
735        &self,
736        instance: Option<&ComponentExportIndex>,
737        name: &str,
738    ) -> Option<ExportIndex> {
739        let info = self.env_component();
740        let exports = match instance {
741            Some(idx) => {
742                if idx.id != self.inner.id {
743                    return None;
744                }
745                match &info.export_items[idx.index] {
746                    Export::Instance { exports, .. } => exports,
747                    _ => return None,
748                }
749            }
750            None => &info.exports,
751        };
752        exports.get(name, &NameMapNoIntern).copied()
753    }
754
755    pub(crate) fn id(&self) -> CompiledModuleId {
756        self.inner.id
757    }
758
759    /// Returns the [`Engine`] that this [`Component`] was compiled by.
760    pub fn engine(&self) -> &Engine {
761        &self.inner.engine
762    }
763}
764
765/// A value which represents a known export of a component.
766///
767/// This is the return value of [`Component::export_index`] and implements the
768/// [`InstanceExportLookup`] trait to work with lookups like
769/// [`Instance::get_func`](crate::component::Instance::get_func).
770#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
771pub struct ComponentExportIndex {
772    pub(crate) id: CompiledModuleId,
773    pub(crate) index: ExportIndex,
774}
775
776impl InstanceExportLookup for ComponentExportIndex {
777    fn lookup(&self, component: &Component) -> Option<ExportIndex> {
778        if component.inner.id == self.id {
779            Some(self.index)
780        } else {
781            None
782        }
783    }
784}
785
786impl ComponentRuntimeInfo for ComponentInner {
787    fn component(&self) -> &wasmtime_environ::component::Component {
788        &self.info.component
789    }
790
791    fn component_types(&self) -> &Arc<ComponentTypes> {
792        match self.code.types() {
793            crate::code::Types::Component(types) => types,
794            // The only creator of a `Component` is itself which uses the other
795            // variant, so this shouldn't be possible.
796            crate::code::Types::Module(_) => unreachable!(),
797        }
798    }
799
800    fn realloc_func_type(&self) -> &Arc<dyn Any + Send + Sync> {
801        &self.realloc_func_type
802    }
803}
804
805#[cfg(test)]
806mod tests {
807    use crate::component::Component;
808    use crate::{Config, Engine};
809    use wasmtime_environ::MemoryInitialization;
810
811    #[test]
812    fn cow_on_by_default() {
813        let mut config = Config::new();
814        config.wasm_component_model(true);
815        let engine = Engine::new(&config).unwrap();
816        let component = Component::new(
817            &engine,
818            r#"
819                (component
820                    (core module
821                        (memory 1)
822                        (data (i32.const 100) "abcd")
823                    )
824                )
825            "#,
826        )
827        .unwrap();
828
829        for (_, module) in component.inner.static_modules.iter() {
830            let init = &module.env_module().memory_initialization;
831            assert!(matches!(init, MemoryInitialization::Static { .. }));
832        }
833    }
834}