Skip to main content

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