Skip to main content

wasmtime/runtime/component/
component.rs

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