wasmtime/runtime/component/
component.rs

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