wasmtime_environ/component/
info.rs

1// General runtime type-information about a component.
2//
3// Compared to the `Module` structure for core wasm this type is pretty
4// significantly different. The core wasm `Module` corresponds roughly 1-to-1
5// with the structure of the wasm module itself, but instead a `Component` is
6// more of a "compiled" representation where the original structure is thrown
7// away in favor of a more optimized representation. The considerations for this
8// are:
9//
10// * This representation of a `Component` avoids the need to create a
11//   `PrimaryMap` of some form for each of the index spaces within a component.
12//   This is less so an issue about allocations and more so that this information
13//   generally just isn't needed any time after instantiation. Avoiding creating
14//   these altogether helps components be lighter weight at runtime and
15//   additionally accelerates instantiation.
16//
17// * Components can have arbitrary nesting and internally do instantiations via
18//   string-based matching. At instantiation-time, though, we want to do as few
19//   string-lookups in hash maps as much as we can since they're significantly
20//   slower than index-based lookups. Furthermore while the imports of a
21//   component are not statically known the rest of the structure of the
22//   component is statically known which enables the ability to track precisely
23//   what matches up where and do all the string lookups at compile time instead
24//   of instantiation time.
25//
26// * Finally by performing this sort of dataflow analysis we are capable of
27//   identifying what adapters need trampolines for compilation or fusion. For
28//   example this tracks when host functions are lowered which enables us to
29//   enumerate what trampolines are required to enter into a component.
30//   Additionally (eventually) this will track all of the "fused" adapter
31//   functions where a function from one component instance is lifted and then
32//   lowered into another component instance. Altogether this enables Wasmtime's
33//   AOT-compilation where the artifact from compilation is suitable for use in
34//   running the component without the support of a compiler at runtime.
35//
36// Note, however, that the current design of `Component` has fundamental
37// limitations which it was not designed for. For example there is no feasible
38// way to implement either importing or exporting a component itself from the
39// root component. Currently we rely on the ability to have static knowledge of
40// what's coming from the host which at this point can only be either functions
41// or core wasm modules. Additionally one flat list of initializers for a
42// component are produced instead of initializers-per-component which would
43// otherwise be required to export a component from a component.
44//
45// For now this tradeoff is made as it aligns well with the intended use case
46// for components in an embedding. This may need to be revisited though if the
47// requirements of embeddings change over time.
48
49use crate::component::*;
50use crate::prelude::*;
51use crate::{EntityIndex, ModuleInternedTypeIndex, PrimaryMap, WasmValType};
52use serde_derive::{Deserialize, Serialize};
53
54/// Metadata as a result of compiling a component.
55pub struct ComponentTranslation {
56    /// Serializable information that will be emitted into the final artifact.
57    pub component: Component,
58
59    /// Metadata about required trampolines and what they're supposed to do.
60    pub trampolines: PrimaryMap<TrampolineIndex, Trampoline>,
61}
62
63/// Run-time-type-information about a `Component`, its structure, and how to
64/// instantiate it.
65///
66/// This type is intended to mirror the `Module` type in this crate which
67/// provides all the runtime information about the structure of a module and
68/// how it works.
69///
70/// NB: Lots of the component model is not yet implemented in the runtime so
71/// this is going to undergo a lot of churn.
72#[derive(Default, Debug, Serialize, Deserialize)]
73pub struct Component {
74    /// A list of typed values that this component imports.
75    ///
76    /// Note that each name is given an `ImportIndex` here for the next map to
77    /// refer back to.
78    pub import_types: PrimaryMap<ImportIndex, (String, TypeDef)>,
79
80    /// A list of "flattened" imports that are used by this instance.
81    ///
82    /// This import map represents extracting imports, as necessary, from the
83    /// general imported types by this component. The flattening here refers to
84    /// extracting items from instances. Currently the flat imports are either a
85    /// host function or a core wasm module.
86    ///
87    /// For example if `ImportIndex(0)` pointed to an instance then this import
88    /// map represent extracting names from that map, for example extracting an
89    /// exported module or an exported function.
90    ///
91    /// Each import item is keyed by a `RuntimeImportIndex` which is referred to
92    /// by types below whenever something refers to an import. The value for
93    /// each `RuntimeImportIndex` in this map is the `ImportIndex` for where
94    /// this items comes from (which can be associated with a name above in the
95    /// `import_types` array) as well as the list of export names if
96    /// `ImportIndex` refers to an instance. The export names array represents
97    /// recursively fetching names within an instance.
98    //
99    // TODO: this is probably a lot of `String` storage and may be something
100    // that needs optimization in the future. For example instead of lots of
101    // different `String` allocations this could instead be a pointer/length
102    // into one large string allocation for the entire component. Alternatively
103    // strings could otherwise be globally intern'd via some other mechanism to
104    // avoid `Linker`-specific intern-ing plus intern-ing here. Unsure what the
105    // best route is or whether such an optimization is even necessary here.
106    pub imports: PrimaryMap<RuntimeImportIndex, (ImportIndex, Vec<String>)>,
107
108    /// This component's own root exports from the component itself.
109    pub exports: NameMap<String, ExportIndex>,
110
111    /// All exports of this component and exported instances of this component.
112    ///
113    /// This is indexed by `ExportIndex` for fast lookup and `Export::Instance`
114    /// will refer back into this list.
115    pub export_items: PrimaryMap<ExportIndex, Export>,
116
117    /// Initializers that must be processed when instantiating this component.
118    ///
119    /// This list of initializers does not correspond directly to the component
120    /// itself. The general goal with this is that the recursive nature of
121    /// components is "flattened" with an array like this which is a linear
122    /// sequence of instructions of how to instantiate a component. This will
123    /// have instantiations, for example, in addition to entries which
124    /// initialize `VMComponentContext` fields with previously instantiated
125    /// instances.
126    pub initializers: Vec<GlobalInitializer>,
127
128    /// The number of runtime instances (maximum `RuntimeInstanceIndex`) created
129    /// when instantiating this component.
130    pub num_runtime_instances: u32,
131
132    /// Same as `num_runtime_instances`, but for `RuntimeComponentInstanceIndex`
133    /// instead.
134    pub num_runtime_component_instances: u32,
135
136    /// The number of runtime memories (maximum `RuntimeMemoryIndex`) needed to
137    /// instantiate this component.
138    ///
139    /// Note that this many memories will be stored in the `VMComponentContext`
140    /// and each memory is intended to be unique (e.g. the same memory isn't
141    /// stored in two different locations).
142    pub num_runtime_memories: u32,
143
144    /// The number of runtime tables (maximum `RuntimeTableIndex`) needed to
145    /// instantiate this component. See notes on `num_runtime_memories`.
146    pub num_runtime_tables: u32,
147
148    /// The number of runtime reallocs (maximum `RuntimeReallocIndex`) needed to
149    /// instantiate this component.
150    ///
151    /// Note that this many function pointers will be stored in the
152    /// `VMComponentContext`.
153    pub num_runtime_reallocs: u32,
154
155    /// The number of runtime async callbacks (maximum `RuntimeCallbackIndex`)
156    /// needed to instantiate this component.
157    pub num_runtime_callbacks: u32,
158
159    /// Same as `num_runtime_reallocs`, but for post-return functions.
160    pub num_runtime_post_returns: u32,
161
162    /// WebAssembly type signature of all trampolines.
163    pub trampolines: PrimaryMap<TrampolineIndex, ModuleInternedTypeIndex>,
164
165    /// The number of lowered host functions (maximum `LoweredIndex`) needed to
166    /// instantiate this component.
167    pub num_lowerings: u32,
168
169    /// Maximal number of tables required at runtime for resource-related
170    /// information in this component.
171    pub num_resource_tables: usize,
172
173    /// Total number of resources both imported and defined within this
174    /// component.
175    pub num_resources: u32,
176
177    /// Maximal number of tables required at runtime for future-related
178    /// information in this component.
179    pub num_future_tables: usize,
180
181    /// Maximal number of tables required at runtime for stream-related
182    /// information in this component.
183    pub num_stream_tables: usize,
184
185    /// Maximal number of tables required at runtime for error-context-related
186    /// information in this component.
187    pub num_error_context_tables: usize,
188
189    /// Metadata about imported resources and where they are within the runtime
190    /// imports array.
191    ///
192    /// This map is only as large as the number of imported resources.
193    pub imported_resources: PrimaryMap<ResourceIndex, RuntimeImportIndex>,
194
195    /// Metadata about which component instances defined each resource within
196    /// this component.
197    ///
198    /// This is used to determine which set of instance flags are inspected when
199    /// testing reentrance.
200    pub defined_resource_instances: PrimaryMap<DefinedResourceIndex, RuntimeComponentInstanceIndex>,
201}
202
203impl Component {
204    /// Attempts to convert a resource index into a defined index.
205    ///
206    /// Returns `None` if `idx` is for an imported resource in this component or
207    /// `Some` if it's a locally defined resource.
208    pub fn defined_resource_index(&self, idx: ResourceIndex) -> Option<DefinedResourceIndex> {
209        let idx = idx
210            .as_u32()
211            .checked_sub(self.imported_resources.len() as u32)?;
212        Some(DefinedResourceIndex::from_u32(idx))
213    }
214
215    /// Converts a defined resource index to a component-local resource index
216    /// which includes all imports.
217    pub fn resource_index(&self, idx: DefinedResourceIndex) -> ResourceIndex {
218        ResourceIndex::from_u32(self.imported_resources.len() as u32 + idx.as_u32())
219    }
220}
221
222/// GlobalInitializer instructions to get processed when instantiating a
223/// component.
224///
225/// The variants of this enum are processed during the instantiation phase of a
226/// component in-order from front-to-back. These are otherwise emitted as a
227/// component is parsed and read and translated.
228//
229// FIXME(#2639) if processing this list is ever a bottleneck we could
230// theoretically use cranelift to compile an initialization function which
231// performs all of these duties for us and skips the overhead of interpreting
232// all of these instructions.
233#[derive(Debug, Serialize, Deserialize)]
234pub enum GlobalInitializer {
235    /// A core wasm module is being instantiated.
236    ///
237    /// This will result in a new core wasm instance being created, which may
238    /// involve running the `start` function of the instance as well if it's
239    /// specified. This largely delegates to the same standard instantiation
240    /// process as the rest of the core wasm machinery already uses.
241    InstantiateModule(InstantiateModule),
242
243    /// A host function is being lowered, creating a core wasm function.
244    ///
245    /// This initializer entry is intended to be used to fill out the
246    /// `VMComponentContext` and information about this lowering such as the
247    /// cranelift-compiled trampoline function pointer, the host function
248    /// pointer the trampoline calls, and the canonical ABI options.
249    LowerImport {
250        /// The index of the lowered function that's being created.
251        ///
252        /// This is guaranteed to be the `n`th `LowerImport` instruction
253        /// if the index is `n`.
254        index: LoweredIndex,
255
256        /// The index of the imported host function that is being lowered.
257        ///
258        /// It's guaranteed that this `RuntimeImportIndex` points to a function.
259        import: RuntimeImportIndex,
260    },
261
262    /// A core wasm linear memory is going to be saved into the
263    /// `VMComponentContext`.
264    ///
265    /// This instruction indicates that a core wasm linear memory needs to be
266    /// extracted from the `export` and stored into the `VMComponentContext` at
267    /// the `index` specified. This lowering is then used in the future by
268    /// pointers from `CanonicalOptions`.
269    ExtractMemory(ExtractMemory),
270
271    /// Same as `ExtractMemory`, except it's extracting a function pointer to be
272    /// used as a `realloc` function.
273    ExtractRealloc(ExtractRealloc),
274
275    /// Same as `ExtractMemory`, except it's extracting a function pointer to be
276    /// used as an async `callback` function.
277    ExtractCallback(ExtractCallback),
278
279    /// Same as `ExtractMemory`, except it's extracting a function pointer to be
280    /// used as a `post-return` function.
281    ExtractPostReturn(ExtractPostReturn),
282
283    /// A core wasm table is going to be saved into the `VMComponentContext`.
284    ///
285    /// This instruction indicates that s core wasm table needs to be extracted
286    /// from its `export` and stored into the `VMComponentContext` at the
287    /// `index` specified. During this extraction, we will also capture the
288    /// table's containing instance pointer to access the table at runtime. This
289    /// extraction is useful for `thread.spawn_indirect`.
290    ExtractTable(ExtractTable),
291
292    /// Declares a new defined resource within this component.
293    ///
294    /// Contains information about the destructor, for example.
295    Resource(Resource),
296}
297
298/// Metadata for extraction of a memory; contains what's being extracted (the
299/// memory at `export`) and where it's going (the `index` within a
300/// `VMComponentContext`).
301#[derive(Debug, Serialize, Deserialize)]
302pub struct ExtractMemory {
303    /// The index of the memory being defined.
304    pub index: RuntimeMemoryIndex,
305    /// Where this memory is being extracted from.
306    pub export: CoreExport<MemoryIndex>,
307}
308
309/// Same as `ExtractMemory` but for the `realloc` canonical option.
310#[derive(Debug, Serialize, Deserialize)]
311pub struct ExtractRealloc {
312    /// The index of the realloc being defined.
313    pub index: RuntimeReallocIndex,
314    /// Where this realloc is being extracted from.
315    pub def: CoreDef,
316}
317
318/// Same as `ExtractMemory` but for the `callback` canonical option.
319#[derive(Debug, Serialize, Deserialize)]
320pub struct ExtractCallback {
321    /// The index of the callback being defined.
322    pub index: RuntimeCallbackIndex,
323    /// Where this callback is being extracted from.
324    pub def: CoreDef,
325}
326
327/// Same as `ExtractMemory` but for the `post-return` canonical option.
328#[derive(Debug, Serialize, Deserialize)]
329pub struct ExtractPostReturn {
330    /// The index of the post-return being defined.
331    pub index: RuntimePostReturnIndex,
332    /// Where this post-return is being extracted from.
333    pub def: CoreDef,
334}
335
336/// Metadata for extraction of a table.
337#[derive(Debug, Serialize, Deserialize)]
338pub struct ExtractTable {
339    /// The index of the table being defined in a `VMComponentContext`.
340    pub index: RuntimeTableIndex,
341    /// Where this table is being extracted from.
342    pub export: CoreExport<TableIndex>,
343}
344
345/// Different methods of instantiating a core wasm module.
346#[derive(Debug, Serialize, Deserialize)]
347pub enum InstantiateModule {
348    /// A module defined within this component is being instantiated.
349    ///
350    /// Note that this is distinct from the case of imported modules because the
351    /// order of imports required is statically known and can be pre-calculated
352    /// to avoid string lookups related to names at runtime, represented by the
353    /// flat list of arguments here.
354    Static(StaticModuleIndex, Box<[CoreDef]>),
355
356    /// An imported module is being instantiated.
357    ///
358    /// This is similar to `Upvar` but notably the imports are provided as a
359    /// two-level named map since import resolution order needs to happen at
360    /// runtime.
361    Import(
362        RuntimeImportIndex,
363        IndexMap<String, IndexMap<String, CoreDef>>,
364    ),
365}
366
367/// Definition of a core wasm item and where it can come from within a
368/// component.
369///
370/// Note that this is sort of a result of data-flow-like analysis on a component
371/// during compile time of the component itself. References to core wasm items
372/// are "compiled" to either referring to a previous instance or to some sort of
373/// lowered host import.
374#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
375pub enum CoreDef {
376    /// This item refers to an export of a previously instantiated core wasm
377    /// instance.
378    Export(CoreExport<EntityIndex>),
379    /// This is a reference to a wasm global which represents the
380    /// runtime-managed flags for a wasm instance.
381    InstanceFlags(RuntimeComponentInstanceIndex),
382    /// This is a reference to a Cranelift-generated trampoline which is
383    /// described in the `trampolines` array.
384    Trampoline(TrampolineIndex),
385}
386
387impl<T> From<CoreExport<T>> for CoreDef
388where
389    EntityIndex: From<T>,
390{
391    fn from(export: CoreExport<T>) -> CoreDef {
392        CoreDef::Export(export.map_index(|i| i.into()))
393    }
394}
395
396/// Identifier of an exported item from a core WebAssembly module instance.
397///
398/// Note that the `T` here is the index type for exports which can be
399/// identified by index. The `T` is monomorphized with types like
400/// [`EntityIndex`] or [`FuncIndex`].
401#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
402pub struct CoreExport<T> {
403    /// The instance that this item is located within.
404    ///
405    /// Note that this is intended to index the `instances` map within a
406    /// component. It's validated ahead of time that all instance pointers
407    /// refer only to previously-created instances.
408    pub instance: RuntimeInstanceIndex,
409
410    /// The item that this export is referencing, either by name or by index.
411    pub item: ExportItem<T>,
412}
413
414impl<T> CoreExport<T> {
415    /// Maps the index type `T` to another type `U` if this export item indeed
416    /// refers to an index `T`.
417    pub fn map_index<U>(self, f: impl FnOnce(T) -> U) -> CoreExport<U> {
418        CoreExport {
419            instance: self.instance,
420            item: match self.item {
421                ExportItem::Index(i) => ExportItem::Index(f(i)),
422                ExportItem::Name(s) => ExportItem::Name(s),
423            },
424        }
425    }
426}
427
428/// An index at which to find an item within a runtime instance.
429#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
430pub enum ExportItem<T> {
431    /// An exact index that the target can be found at.
432    ///
433    /// This is used where possible to avoid name lookups at runtime during the
434    /// instantiation process. This can only be used on instances where the
435    /// module was statically known at compile time, however.
436    Index(T),
437
438    /// An item which is identified by a name, so at runtime we need to
439    /// perform a name lookup to determine the index that the item is located
440    /// at.
441    ///
442    /// This is used for instantiations of imported modules, for example, since
443    /// the precise shape of the module is not known.
444    Name(String),
445}
446
447/// Possible exports from a component.
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub enum Export {
450    /// A lifted function being exported which is an adaptation of a core wasm
451    /// function.
452    LiftedFunction {
453        /// The component function type of the function being created.
454        ty: TypeFuncIndex,
455        /// Which core WebAssembly export is being lifted.
456        func: CoreDef,
457        /// Any options, if present, associated with this lifting.
458        options: CanonicalOptions,
459    },
460    /// A module defined within this component is exported.
461    ModuleStatic {
462        /// The type of this module
463        ty: TypeModuleIndex,
464        /// Which module this is referring to.
465        index: StaticModuleIndex,
466    },
467    /// A module imported into this component is exported.
468    ModuleImport {
469        /// Module type index
470        ty: TypeModuleIndex,
471        /// Module runtime import index
472        import: RuntimeImportIndex,
473    },
474    /// A nested instance is being exported which has recursively defined
475    /// `Export` items.
476    Instance {
477        /// Instance type index, if such is assigned
478        ty: TypeComponentInstanceIndex,
479        /// Instance export map
480        exports: NameMap<String, ExportIndex>,
481    },
482    /// An exported type from a component or instance, currently only
483    /// informational.
484    Type(TypeDef),
485}
486
487/// Canonical ABI options associated with a lifted or lowered function.
488#[derive(Debug, Clone, Serialize, Deserialize)]
489pub struct CanonicalOptions {
490    /// The component instance that this bundle was associated with.
491    pub instance: RuntimeComponentInstanceIndex,
492
493    /// The encoding used for strings.
494    pub string_encoding: StringEncoding,
495
496    /// The memory used by these options, if specified.
497    pub memory: Option<RuntimeMemoryIndex>,
498
499    /// The realloc function used by these options, if specified.
500    pub realloc: Option<RuntimeReallocIndex>,
501
502    /// The async callback function used by these options, if specified.
503    pub callback: Option<RuntimeCallbackIndex>,
504
505    /// The post-return function used by these options, if specified.
506    pub post_return: Option<RuntimePostReturnIndex>,
507
508    /// Whether to use the async ABI for lifting or lowering.
509    pub async_: bool,
510}
511
512/// Possible encodings of strings within the component model.
513#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
514#[expect(missing_docs, reason = "self-describing variants")]
515pub enum StringEncoding {
516    Utf8,
517    Utf16,
518    CompactUtf16,
519}
520
521impl StringEncoding {
522    /// Decodes the `u8` provided back into a `StringEncoding`, if it's valid.
523    pub fn from_u8(val: u8) -> Option<StringEncoding> {
524        if val == StringEncoding::Utf8 as u8 {
525            return Some(StringEncoding::Utf8);
526        }
527        if val == StringEncoding::Utf16 as u8 {
528            return Some(StringEncoding::Utf16);
529        }
530        if val == StringEncoding::CompactUtf16 as u8 {
531            return Some(StringEncoding::CompactUtf16);
532        }
533        None
534    }
535}
536
537/// Possible transcoding operations that must be provided by the host.
538///
539/// Note that each transcoding operation may have a unique signature depending
540/// on the precise operation.
541#[expect(missing_docs, reason = "self-describing variants")]
542#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
543pub enum Transcode {
544    Copy(FixedEncoding),
545    Latin1ToUtf16,
546    Latin1ToUtf8,
547    Utf16ToCompactProbablyUtf16,
548    Utf16ToCompactUtf16,
549    Utf16ToLatin1,
550    Utf16ToUtf8,
551    Utf8ToCompactUtf16,
552    Utf8ToLatin1,
553    Utf8ToUtf16,
554}
555
556impl Transcode {
557    /// Get this transcoding's symbol fragment.
558    pub fn symbol_fragment(&self) -> &'static str {
559        match self {
560            Transcode::Copy(x) => match x {
561                FixedEncoding::Utf8 => "copy_utf8",
562                FixedEncoding::Utf16 => "copy_utf16",
563                FixedEncoding::Latin1 => "copy_latin1",
564            },
565            Transcode::Latin1ToUtf16 => "latin1_to_utf16",
566            Transcode::Latin1ToUtf8 => "latin1_to_utf8",
567            Transcode::Utf16ToCompactProbablyUtf16 => "utf16_to_compact_probably_utf16",
568            Transcode::Utf16ToCompactUtf16 => "utf16_to_compact_utf16",
569            Transcode::Utf16ToLatin1 => "utf16_to_latin1",
570            Transcode::Utf16ToUtf8 => "utf16_to_utf8",
571            Transcode::Utf8ToCompactUtf16 => "utf8_to_compact_utf16",
572            Transcode::Utf8ToLatin1 => "utf8_to_latin1",
573            Transcode::Utf8ToUtf16 => "utf8_to_utf16",
574        }
575    }
576
577    /// Returns a human-readable description for this transcoding operation.
578    pub fn desc(&self) -> &'static str {
579        match self {
580            Transcode::Copy(FixedEncoding::Utf8) => "utf8-to-utf8",
581            Transcode::Copy(FixedEncoding::Utf16) => "utf16-to-utf16",
582            Transcode::Copy(FixedEncoding::Latin1) => "latin1-to-latin1",
583            Transcode::Latin1ToUtf16 => "latin1-to-utf16",
584            Transcode::Latin1ToUtf8 => "latin1-to-utf8",
585            Transcode::Utf16ToCompactProbablyUtf16 => "utf16-to-compact-probably-utf16",
586            Transcode::Utf16ToCompactUtf16 => "utf16-to-compact-utf16",
587            Transcode::Utf16ToLatin1 => "utf16-to-latin1",
588            Transcode::Utf16ToUtf8 => "utf16-to-utf8",
589            Transcode::Utf8ToCompactUtf16 => "utf8-to-compact-utf16",
590            Transcode::Utf8ToLatin1 => "utf8-to-latin1",
591            Transcode::Utf8ToUtf16 => "utf8-to-utf16",
592        }
593    }
594}
595
596#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
597#[expect(missing_docs, reason = "self-describing variants")]
598pub enum FixedEncoding {
599    Utf8,
600    Utf16,
601    Latin1,
602}
603
604impl FixedEncoding {
605    /// Returns the byte width of unit loads/stores for this encoding, for
606    /// example the unit length is multiplied by this return value to get the
607    /// byte width of a string.
608    pub fn width(&self) -> u8 {
609        match self {
610            FixedEncoding::Utf8 => 1,
611            FixedEncoding::Utf16 => 2,
612            FixedEncoding::Latin1 => 1,
613        }
614    }
615}
616
617/// Description of a new resource declared in a `GlobalInitializer::Resource`
618/// variant.
619///
620/// This will have the effect of initializing runtime state for this resource,
621/// namely the destructor is fetched and stored.
622#[derive(Debug, Serialize, Deserialize)]
623pub struct Resource {
624    /// The local index of the resource being defined.
625    pub index: DefinedResourceIndex,
626    /// Core wasm representation of this resource.
627    pub rep: WasmValType,
628    /// Optionally-specified destructor and where it comes from.
629    pub dtor: Option<CoreDef>,
630    /// Which component instance this resource logically belongs to.
631    pub instance: RuntimeComponentInstanceIndex,
632}
633
634/// A list of all possible trampolines that may be required to compile a
635/// component completely.
636///
637/// These trampolines are used often as core wasm definitions and require
638/// Cranelift support to generate these functions. Each trampoline serves a
639/// different purpose for implementing bits and pieces of the component model.
640///
641/// All trampolines have a core wasm function signature associated with them
642/// which is stored in the `Component::trampolines` array.
643///
644/// Note that this type does not implement `Serialize` or `Deserialize` and
645/// that's intentional as this isn't stored in the final compilation artifact.
646pub enum Trampoline {
647    /// Description of a lowered import used in conjunction with
648    /// `GlobalInitializer::LowerImport`.
649    LowerImport {
650        /// The runtime lowering state that this trampoline will access.
651        index: LoweredIndex,
652
653        /// The type of the function that is being lowered, as perceived by the
654        /// component doing the lowering.
655        lower_ty: TypeFuncIndex,
656
657        /// The canonical ABI options used when lowering this function specified
658        /// in the original component.
659        options: CanonicalOptions,
660    },
661
662    /// Information about a string transcoding function required by an adapter
663    /// module.
664    ///
665    /// A transcoder is used when strings are passed between adapter modules,
666    /// optionally changing string encodings at the same time. The transcoder is
667    /// implemented in a few different layers:
668    ///
669    /// * Each generated adapter module has some glue around invoking the
670    ///   transcoder represented by this item. This involves bounds-checks and
671    ///   handling `realloc` for example.
672    /// * Each transcoder gets a cranelift-generated trampoline which has the
673    ///   appropriate signature for the adapter module in question. Existence of
674    ///   this initializer indicates that this should be compiled by Cranelift.
675    /// * The cranelift-generated trampoline will invoke a "transcoder libcall"
676    ///   which is implemented natively in Rust that has a signature independent
677    ///   of memory64 configuration options for example.
678    Transcoder {
679        /// The transcoding operation being performed.
680        op: Transcode,
681        /// The linear memory that the string is being read from.
682        from: RuntimeMemoryIndex,
683        /// Whether or not the source linear memory is 64-bit or not.
684        from64: bool,
685        /// The linear memory that the string is being written to.
686        to: RuntimeMemoryIndex,
687        /// Whether or not the destination linear memory is 64-bit or not.
688        to64: bool,
689    },
690
691    /// A small adapter which simply traps, used for degenerate lift/lower
692    /// combinations.
693    AlwaysTrap,
694
695    /// A `resource.new` intrinsic which will inject a new resource into the
696    /// table specified.
697    ResourceNew(TypeResourceTableIndex),
698
699    /// Same as `ResourceNew`, but for the `resource.rep` intrinsic.
700    ResourceRep(TypeResourceTableIndex),
701
702    /// Same as `ResourceNew`, but for the `resource.drop` intrinsic.
703    ResourceDrop(TypeResourceTableIndex),
704
705    /// A `backpressure.set` intrinsic, which tells the host to enable or
706    /// disable backpressure for the caller's instance.
707    BackpressureSet {
708        /// The specific component instance which is calling the intrinsic.
709        instance: RuntimeComponentInstanceIndex,
710    },
711
712    /// A `task.return` intrinsic, which returns a result to the caller of a
713    /// lifted export function.  This allows the callee to continue executing
714    /// after returning a result.
715    TaskReturn {
716        /// Tuple representing the result types this intrinsic accepts.
717        results: TypeTupleIndex,
718
719        /// The canonical ABI options specified for this intrinsic.
720        options: CanonicalOptions,
721    },
722
723    /// A `waitable-set.new` intrinsic.
724    WaitableSetNew {
725        /// The specific component instance which is calling the intrinsic.
726        instance: RuntimeComponentInstanceIndex,
727    },
728
729    /// A `waitable-set.wait` intrinsic, which waits for at least one
730    /// outstanding async task/stream/future to make progress, returning the
731    /// first such event.
732    WaitableSetWait {
733        /// The specific component instance which is calling the intrinsic.
734        instance: RuntimeComponentInstanceIndex,
735        /// If `true`, indicates the caller instance maybe reentered.
736        async_: bool,
737        /// Memory to use when storing the event.
738        memory: RuntimeMemoryIndex,
739    },
740
741    /// A `waitable-set.poll` intrinsic, which checks whether any outstanding
742    /// async task/stream/future has made progress.  Unlike `task.wait`, this
743    /// does not block and may return nothing if no such event has occurred.
744    WaitableSetPoll {
745        /// The specific component instance which is calling the intrinsic.
746        instance: RuntimeComponentInstanceIndex,
747        /// If `true`, indicates the caller instance maybe reentered.
748        async_: bool,
749        /// Memory to use when storing the event.
750        memory: RuntimeMemoryIndex,
751    },
752
753    /// A `waitable-set.drop` intrinsic.
754    WaitableSetDrop {
755        /// The specific component instance which is calling the intrinsic.
756        instance: RuntimeComponentInstanceIndex,
757    },
758
759    /// A `waitable.join` intrinsic.
760    WaitableJoin {
761        /// The specific component instance which is calling the intrinsic.
762        instance: RuntimeComponentInstanceIndex,
763    },
764
765    /// A `yield` intrinsic, which yields control to the host so that other
766    /// tasks are able to make progress, if any.
767    Yield {
768        /// If `true`, indicates the caller instance maybe reentered.
769        async_: bool,
770    },
771
772    /// A `subtask.drop` intrinsic to drop a specified task which has completed.
773    SubtaskDrop {
774        /// The specific component instance which is calling the intrinsic.
775        instance: RuntimeComponentInstanceIndex,
776    },
777
778    /// A `stream.new` intrinsic to create a new `stream` handle of the
779    /// specified type.
780    StreamNew {
781        /// The table index for the specific `stream` type and caller instance.
782        ty: TypeStreamTableIndex,
783    },
784
785    /// A `stream.read` intrinsic to read from a `stream` of the specified type.
786    StreamRead {
787        /// The table index for the specific `stream` type and caller instance.
788        ty: TypeStreamTableIndex,
789
790        /// Any options (e.g. string encoding) to use when storing values to
791        /// memory.
792        options: CanonicalOptions,
793    },
794
795    /// A `stream.write` intrinsic to write to a `stream` of the specified type.
796    StreamWrite {
797        /// The table index for the specific `stream` type and caller instance.
798        ty: TypeStreamTableIndex,
799        /// Any options (e.g. string encoding) to use when storing values to
800        /// memory.
801        options: CanonicalOptions,
802    },
803
804    /// A `stream.cancel-read` intrinsic to cancel an in-progress read from a
805    /// `stream` of the specified type.
806    StreamCancelRead {
807        /// The table index for the specific `stream` type and caller instance.
808        ty: TypeStreamTableIndex,
809        /// If `false`, block until cancellation completes rather than return
810        /// `BLOCKED`.
811        async_: bool,
812    },
813
814    /// A `stream.cancel-write` intrinsic to cancel an in-progress write from a
815    /// `stream` of the specified type.
816    StreamCancelWrite {
817        /// The table index for the specific `stream` type and caller instance.
818        ty: TypeStreamTableIndex,
819        /// If `false`, block until cancellation completes rather than return
820        /// `BLOCKED`.
821        async_: bool,
822    },
823
824    /// A `stream.close-readable` intrinsic to close the readable end of a
825    /// `stream` of the specified type.
826    StreamCloseReadable {
827        /// The table index for the specific `stream` type and caller instance.
828        ty: TypeStreamTableIndex,
829    },
830
831    /// A `stream.close-writable` intrinsic to close the writable end of a
832    /// `stream` of the specified type.
833    StreamCloseWritable {
834        /// The table index for the specific `stream` type and caller instance.
835        ty: TypeStreamTableIndex,
836    },
837
838    /// A `future.new` intrinsic to create a new `future` handle of the
839    /// specified type.
840    FutureNew {
841        /// The table index for the specific `future` type and caller instance.
842        ty: TypeFutureTableIndex,
843    },
844
845    /// A `future.read` intrinsic to read from a `future` of the specified type.
846    FutureRead {
847        /// The table index for the specific `future` type and caller instance.
848        ty: TypeFutureTableIndex,
849
850        /// Any options (e.g. string encoding) to use when storing values to
851        /// memory.
852        options: CanonicalOptions,
853    },
854
855    /// A `future.write` intrinsic to write to a `future` of the specified type.
856    FutureWrite {
857        /// The table index for the specific `future` type and caller instance.
858        ty: TypeFutureTableIndex,
859        /// Any options (e.g. string encoding) to use when storing values to
860        /// memory.
861        options: CanonicalOptions,
862    },
863
864    /// A `future.cancel-read` intrinsic to cancel an in-progress read from a
865    /// `future` of the specified type.
866    FutureCancelRead {
867        /// The table index for the specific `future` type and caller instance.
868        ty: TypeFutureTableIndex,
869        /// If `false`, block until cancellation completes rather than return
870        /// `BLOCKED`.
871        async_: bool,
872    },
873
874    /// A `future.cancel-write` intrinsic to cancel an in-progress write from a
875    /// `future` of the specified type.
876    FutureCancelWrite {
877        /// The table index for the specific `future` type and caller instance.
878        ty: TypeFutureTableIndex,
879        /// If `false`, block until cancellation completes rather than return
880        /// `BLOCKED`.
881        async_: bool,
882    },
883
884    /// A `future.close-readable` intrinsic to close the readable end of a
885    /// `future` of the specified type.
886    FutureCloseReadable {
887        /// The table index for the specific `future` type and caller instance.
888        ty: TypeFutureTableIndex,
889    },
890
891    /// A `future.close-writable` intrinsic to close the writable end of a
892    /// `future` of the specified type.
893    FutureCloseWritable {
894        /// The table index for the specific `future` type and caller instance.
895        ty: TypeFutureTableIndex,
896    },
897
898    /// A `error-context.new` intrinsic to create a new `error-context` with a
899    /// specified debug message.
900    ErrorContextNew {
901        /// The table index for the `error-context` type in the caller instance.
902        ty: TypeComponentLocalErrorContextTableIndex,
903        /// String encoding, memory, etc. to use when loading debug message.
904        options: CanonicalOptions,
905    },
906
907    /// A `error-context.debug-message` intrinsic to get the debug message for a
908    /// specified `error-context`.
909    ///
910    /// Note that the debug message might not necessarily match what was passed
911    /// to `error.new`.
912    ErrorContextDebugMessage {
913        /// The table index for the `error-context` type in the caller instance.
914        ty: TypeComponentLocalErrorContextTableIndex,
915        /// String encoding, memory, etc. to use when storing debug message.
916        options: CanonicalOptions,
917    },
918
919    /// A `error-context.drop` intrinsic to drop a specified `error-context`.
920    ErrorContextDrop {
921        /// The table index for the `error-context` type in the caller instance.
922        ty: TypeComponentLocalErrorContextTableIndex,
923    },
924
925    /// An intrinsic used by FACT-generated modules which will transfer an owned
926    /// resource from one table to another. Used in component-to-component
927    /// adapter trampolines.
928    ResourceTransferOwn,
929
930    /// Same as `ResourceTransferOwn` but for borrows.
931    ResourceTransferBorrow,
932
933    /// An intrinsic used by FACT-generated modules which indicates that a call
934    /// is being entered and resource-related metadata needs to be configured.
935    ///
936    /// Note that this is currently only invoked when borrowed resources are
937    /// detected, otherwise this is "optimized out".
938    ResourceEnterCall,
939
940    /// Same as `ResourceEnterCall` except for when exiting a call.
941    ResourceExitCall,
942
943    /// An intrinsic used by FACT-generated modules to begin a call involving a
944    /// sync-lowered import and async-lifted export.
945    SyncEnterCall,
946
947    /// An intrinsic used by FACT-generated modules to complete a call involving
948    /// a sync-lowered import and async-lifted export.
949    SyncExitCall {
950        /// The callee's callback function, if any.
951        callback: Option<RuntimeCallbackIndex>,
952    },
953
954    /// An intrinsic used by FACT-generated modules to begin a call involving an
955    /// async-lowered import function.
956    AsyncEnterCall,
957
958    /// An intrinsic used by FACT-generated modules to complete a call involving
959    /// an async-lowered import function.
960    ///
961    /// Note that `AsyncEnterCall` and `AsyncExitCall` could theoretically be
962    /// combined into a single `AsyncCall` intrinsic, but we separate them to
963    /// allow the FACT-generated module to optionally call the callee directly
964    /// without an intermediate host stack frame.
965    AsyncExitCall {
966        /// The callee's callback, if any.
967        callback: Option<RuntimeCallbackIndex>,
968
969        /// The callee's post-return function, if any.
970        post_return: Option<RuntimePostReturnIndex>,
971    },
972
973    /// An intrinisic used by FACT-generated modules to (partially or entirely) transfer
974    /// ownership of a `future`.
975    ///
976    /// Transfering a `future` can either mean giving away the readable end
977    /// while retaining the writable end or only the former, depending on the
978    /// ownership status of the `future`.
979    FutureTransfer,
980
981    /// An intrinisic used by FACT-generated modules to (partially or entirely) transfer
982    /// ownership of a `stream`.
983    ///
984    /// Transfering a `stream` can either mean giving away the readable end
985    /// while retaining the writable end or only the former, depending on the
986    /// ownership status of the `stream`.
987    StreamTransfer,
988
989    /// An intrinisic used by FACT-generated modules to (partially or entirely) transfer
990    /// ownership of an `error-context`.
991    ///
992    /// Unlike futures, streams, and resource handles, `error-context` handles
993    /// are reference counted, meaning that sharing the handle with another
994    /// component does not invalidate the handle in the original component.
995    ErrorContextTransfer,
996}
997
998impl Trampoline {
999    /// Returns the name to use for the symbol of this trampoline in the final
1000    /// compiled artifact
1001    pub fn symbol_name(&self) -> String {
1002        use Trampoline::*;
1003        match self {
1004            LowerImport { index, .. } => {
1005                format!("component-lower-import[{}]", index.as_u32())
1006            }
1007            Transcoder {
1008                op, from64, to64, ..
1009            } => {
1010                let op = op.symbol_fragment();
1011                let from = if *from64 { "64" } else { "32" };
1012                let to = if *to64 { "64" } else { "32" };
1013                format!("component-transcode-{op}-m{from}-m{to}")
1014            }
1015            AlwaysTrap => format!("component-always-trap"),
1016            ResourceNew(i) => format!("component-resource-new[{}]", i.as_u32()),
1017            ResourceRep(i) => format!("component-resource-rep[{}]", i.as_u32()),
1018            ResourceDrop(i) => format!("component-resource-drop[{}]", i.as_u32()),
1019            BackpressureSet { .. } => format!("backpressure-set"),
1020            TaskReturn { .. } => format!("task-return"),
1021            WaitableSetNew { .. } => format!("waitable-set-new"),
1022            WaitableSetWait { .. } => format!("waitable-set-wait"),
1023            WaitableSetPoll { .. } => format!("waitable-set-poll"),
1024            WaitableSetDrop { .. } => format!("waitable-set-drop"),
1025            WaitableJoin { .. } => format!("waitable-join"),
1026            Yield { .. } => format!("yield"),
1027            SubtaskDrop { .. } => format!("subtask-drop"),
1028            StreamNew { .. } => format!("stream-new"),
1029            StreamRead { .. } => format!("stream-read"),
1030            StreamWrite { .. } => format!("stream-write"),
1031            StreamCancelRead { .. } => format!("stream-cancel-read"),
1032            StreamCancelWrite { .. } => format!("stream-cancel-write"),
1033            StreamCloseReadable { .. } => format!("stream-close-readable"),
1034            StreamCloseWritable { .. } => format!("stream-close-writable"),
1035            FutureNew { .. } => format!("future-new"),
1036            FutureRead { .. } => format!("future-read"),
1037            FutureWrite { .. } => format!("future-write"),
1038            FutureCancelRead { .. } => format!("future-cancel-read"),
1039            FutureCancelWrite { .. } => format!("future-cancel-write"),
1040            FutureCloseReadable { .. } => format!("future-close-readable"),
1041            FutureCloseWritable { .. } => format!("future-close-writable"),
1042            ErrorContextNew { .. } => format!("error-context-new"),
1043            ErrorContextDebugMessage { .. } => format!("error-context-debug-message"),
1044            ErrorContextDrop { .. } => format!("error-context-drop"),
1045            ResourceTransferOwn => format!("component-resource-transfer-own"),
1046            ResourceTransferBorrow => format!("component-resource-transfer-borrow"),
1047            ResourceEnterCall => format!("component-resource-enter-call"),
1048            ResourceExitCall => format!("component-resource-exit-call"),
1049            SyncEnterCall => format!("component-sync-enter-call"),
1050            SyncExitCall { .. } => format!("component-sync-exit-call"),
1051            AsyncEnterCall => format!("component-async-enter-call"),
1052            AsyncExitCall { .. } => format!("component-async-exit-call"),
1053            FutureTransfer => format!("future-transfer"),
1054            StreamTransfer => format!("stream-transfer"),
1055            ErrorContextTransfer => format!("error-context-transfer"),
1056        }
1057    }
1058}