Skip to main content

wasmtime_environ/component/
translate.rs

1use crate::Abi;
2use crate::component::dfg::AbstractInstantiations;
3use crate::component::*;
4use crate::prelude::*;
5use crate::{
6    DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, EngineOrModuleTypeIndex,
7    EntityIndex, FactInlineIntrinsic, FuncKey, ImportPositions, KnownEntity, KnownGlobal,
8    ModuleEnvironment, ModuleInternedTypeIndex, ModuleTranslation, ModuleTypesBuilder, PrimaryMap,
9    ScopeVec, TagIndex, Tunables, TypeConvert, WasmHeapType, WasmResult, WasmValType,
10};
11use core::str::FromStr;
12use cranelift_entity::{EntityRef, SecondaryMap};
13use indexmap::IndexMap;
14use std::collections::{HashMap, HashSet};
15use std::mem;
16use wasmparser::component_types::{
17    AliasableResourceId, ComponentCoreModuleTypeId, ComponentCoreTypeId, ComponentDefinedTypeId,
18    ComponentEntityType, ComponentFuncTypeId, ComponentInstanceTypeId, ComponentValType,
19};
20use wasmparser::types::Types;
21use wasmparser::{Chunk, ComponentExternName, Encoding, Parser, Payload, Validator};
22
23mod adapt;
24pub use self::adapt::*;
25mod inline;
26
27/// Structure used to translate a component and parse it.
28pub struct Translator<'a, 'data> {
29    /// The current component being translated.
30    ///
31    /// This will get swapped out as translation traverses the body of a
32    /// component and a sub-component is entered or left.
33    result: Translation<'data>,
34
35    /// Current state of parsing a binary component. Note that like `result`
36    /// this will change as the component is traversed.
37    parser: Parser,
38
39    /// Stack of lexical scopes that are in-progress but not finished yet.
40    ///
41    /// This is pushed to whenever a component is entered and popped from
42    /// whenever a component is left. Each lexical scope also contains
43    /// information about the variables that it is currently required to close
44    /// over which is threaded into the current in-progress translation of
45    /// the sub-component which pushed a scope here.
46    lexical_scopes: Vec<LexicalScope<'data>>,
47
48    /// The validator in use to verify that the raw input binary is a valid
49    /// component.
50    validator: &'a mut Validator,
51
52    /// Type information shared for the entire component.
53    ///
54    /// This builder is also used for all core wasm modules found to intern
55    /// signatures across all modules.
56    types: PreInliningComponentTypes<'a>,
57
58    /// The compiler configuration provided by the embedder.
59    tunables: &'a Tunables,
60
61    /// Auxiliary location to push generated adapter modules onto.
62    scope_vec: &'data ScopeVec<u8>,
63
64    /// Completely translated core wasm modules that have been found so far.
65    ///
66    /// Note that this translation only involves learning about type
67    /// information and functions are not actually compiled here.
68    static_modules: PrimaryMap<StaticModuleIndex, ModuleTranslation<'data>>,
69
70    /// Completely translated components that have been found so far.
71    ///
72    /// As frames are popped from `lexical_scopes` their completed component
73    /// will be pushed onto this list.
74    static_components: PrimaryMap<StaticComponentIndex, Translation<'data>>,
75
76    /// The top-level import name for Wasmtime's unsafe intrinsics, if any.
77    unsafe_intrinsics_import: Option<&'a str>,
78}
79
80/// Representation of the syntactic scope of a component meaning where it is
81/// and what its state is at in the binary format.
82///
83/// These scopes are pushed and popped when a sub-component starts being
84/// parsed and finishes being parsed. The main purpose of this frame is to
85/// have a `ClosedOverVars` field which encapsulates data that is inherited
86/// from the scope specified into the component being translated just beneath
87/// it.
88///
89/// This structure exists to implement outer aliases to components and modules.
90/// When a component or module is closed over then that means it needs to be
91/// inherited in a sense to the component which actually had the alias. This is
92/// achieved with a deceptively simple scheme where each parent of the
93/// component with the alias will inherit the component from the desired
94/// location.
95///
96/// For example with a component structure that looks like:
97///
98/// ```wasm
99/// (component $A
100///     (core module $M)
101///     (component $B
102///         (component $C
103///             (alias outer $A $M (core module))
104///         )
105///     )
106/// )
107/// ```
108///
109/// here the `C` component is closing over `M` located in the root component
110/// `A`. When `C` is being translated the `lexical_scopes` field will look like
111/// `[A, B]`. When the alias is encountered (for module index 0) this will
112/// place a `ClosedOverModule::Local(0)` entry into the `closure_args` field of
113/// `A`'s frame. This will in turn give a `ModuleUpvarIndex` which is then
114/// inserted into `closure_args` in `B`'s frame. This produces yet another
115/// `ModuleUpvarIndex` which is finally inserted into `C`'s module index space
116/// via `LocalInitializer::AliasModuleUpvar` with the last index.
117///
118/// All of these upvar indices and such are interpreted in the "inline" phase
119/// of compilation and not at runtime. This means that when `A` is being
120/// instantiated one of its initializers will be
121/// `LocalInitializer::ComponentStatic`. This starts to create `B` and the
122/// variables captured for `B` are listed as local module 0, or `M`. This list
123/// is then preserved in the definition of the component `B` and later reused
124/// by `C` again to finally get access to the closed over component.
125///
126/// Effectively the scopes are managed hierarchically where a reference to an
127/// outer variable automatically injects references into all parents up to
128/// where the reference is. This variable scopes are the processed during
129/// inlining where a component definition is a reference to the static
130/// component information (`Translation`) plus closed over variables
131/// (`ComponentClosure` during inlining).
132struct LexicalScope<'data> {
133    /// Current state of translating the `translation` below.
134    parser: Parser,
135    /// Current state of the component's translation as found so far.
136    translation: Translation<'data>,
137    /// List of captures that `translation` will need to process to create the
138    /// sub-component which is directly beneath this lexical scope.
139    closure_args: ClosedOverVars,
140}
141
142/// A "local" translation of a component.
143///
144/// This structure is used as a sort of in-progress translation of a component.
145/// This is not `Component` which is the final form as consumed by Wasmtime
146/// at runtime. Instead this is a fairly simple representation of a component
147/// where almost everything is ordered as a list of initializers. The binary
148/// format is translated to a list of initializers here which is later processed
149/// during "inlining" to produce a final component with the final set of
150/// initializers.
151#[derive(Default)]
152struct Translation<'data> {
153    /// Instructions which form this component.
154    ///
155    /// There is one initializer for all members of each index space, and all
156    /// index spaces are incrementally built here as the initializer list is
157    /// processed.
158    initializers: Vec<LocalInitializer<'data>>,
159
160    /// The list of exports from this component, as pairs of names and an
161    /// index into an index space of what's being exported.
162    exports: IndexMap<&'data str, (ComponentItem, wasmparser::ComponentExternName<'data>)>,
163
164    /// Type information produced by `wasmparser` for this component.
165    ///
166    /// This type information is available after the translation of the entire
167    /// component has finished, e.g. for the `inline` pass, but beforehand this
168    /// is set to `None`.
169    types: Option<Types>,
170}
171
172// NB: the type information contained in `LocalInitializer` should always point
173// to `wasmparser`'s type information, not Wasmtime's. Component types cannot be
174// fully determined due to resources until instantiations are known which is
175// tracked during the inlining phase. This means that all type information below
176// is straight from `wasmparser`'s passes.
177enum LocalInitializer<'data> {
178    // imports
179    Import(ComponentExternName<'data>, ComponentEntityType),
180
181    // An import of an intrinsic for compile-time builtins.
182    IntrinsicsImport,
183
184    // canonical function sections
185    Lower {
186        func: ComponentFuncIndex,
187        lower_ty: ComponentFuncTypeId,
188        options: LocalCanonicalOptions,
189    },
190    Lift(ComponentFuncTypeId, FuncIndex, LocalCanonicalOptions),
191
192    // resources
193    Resource(AliasableResourceId, WasmValType, Option<FuncIndex>),
194    ResourceNew(AliasableResourceId, ModuleInternedTypeIndex),
195    ResourceRep(AliasableResourceId, ModuleInternedTypeIndex),
196    ResourceDrop(AliasableResourceId, ModuleInternedTypeIndex),
197
198    BackpressureInc {
199        func: ModuleInternedTypeIndex,
200    },
201    BackpressureDec {
202        func: ModuleInternedTypeIndex,
203    },
204    TaskReturn {
205        result: Option<ComponentValType>,
206        options: LocalCanonicalOptions,
207    },
208    TaskCancel {
209        func: ModuleInternedTypeIndex,
210    },
211    WaitableSetNew {
212        func: ModuleInternedTypeIndex,
213    },
214    WaitableSetWait {
215        options: LocalCanonicalOptions,
216    },
217    WaitableSetPoll {
218        options: LocalCanonicalOptions,
219    },
220    WaitableSetDrop {
221        func: ModuleInternedTypeIndex,
222    },
223    WaitableJoin {
224        func: ModuleInternedTypeIndex,
225    },
226    SubtaskDrop {
227        func: ModuleInternedTypeIndex,
228    },
229    SubtaskCancel {
230        func: ModuleInternedTypeIndex,
231        async_: bool,
232    },
233    StreamNew {
234        ty: ComponentDefinedTypeId,
235        func: ModuleInternedTypeIndex,
236    },
237    StreamRead {
238        ty: ComponentDefinedTypeId,
239        options: LocalCanonicalOptions,
240    },
241    StreamWrite {
242        ty: ComponentDefinedTypeId,
243        options: LocalCanonicalOptions,
244    },
245    StreamCancelRead {
246        ty: ComponentDefinedTypeId,
247        func: ModuleInternedTypeIndex,
248        async_: bool,
249    },
250    StreamCancelWrite {
251        ty: ComponentDefinedTypeId,
252        func: ModuleInternedTypeIndex,
253        async_: bool,
254    },
255    StreamDropReadable {
256        ty: ComponentDefinedTypeId,
257        func: ModuleInternedTypeIndex,
258    },
259    StreamDropWritable {
260        ty: ComponentDefinedTypeId,
261        func: ModuleInternedTypeIndex,
262    },
263    FutureNew {
264        ty: ComponentDefinedTypeId,
265        func: ModuleInternedTypeIndex,
266    },
267    FutureRead {
268        ty: ComponentDefinedTypeId,
269        options: LocalCanonicalOptions,
270    },
271    FutureWrite {
272        ty: ComponentDefinedTypeId,
273        options: LocalCanonicalOptions,
274    },
275    FutureCancelRead {
276        ty: ComponentDefinedTypeId,
277        func: ModuleInternedTypeIndex,
278        async_: bool,
279    },
280    FutureCancelWrite {
281        ty: ComponentDefinedTypeId,
282        func: ModuleInternedTypeIndex,
283        async_: bool,
284    },
285    FutureDropReadable {
286        ty: ComponentDefinedTypeId,
287        func: ModuleInternedTypeIndex,
288    },
289    FutureDropWritable {
290        ty: ComponentDefinedTypeId,
291        func: ModuleInternedTypeIndex,
292    },
293    ErrorContextNew {
294        options: LocalCanonicalOptions,
295    },
296    ErrorContextDebugMessage {
297        options: LocalCanonicalOptions,
298    },
299    ErrorContextDrop {
300        func: ModuleInternedTypeIndex,
301    },
302    ContextGet {
303        func: ModuleInternedTypeIndex,
304        i: u32,
305    },
306    ContextSet {
307        func: ModuleInternedTypeIndex,
308        i: u32,
309    },
310    ThreadIndex {
311        func: ModuleInternedTypeIndex,
312    },
313    ThreadNewIndirect {
314        func: ModuleInternedTypeIndex,
315        start_func_ty: ModuleInternedTypeIndex,
316        start_func_table_index: TableIndex,
317    },
318    ThreadResumeLater {
319        func: ModuleInternedTypeIndex,
320    },
321    ThreadSuspend {
322        func: ModuleInternedTypeIndex,
323    },
324    ThreadYield {
325        func: ModuleInternedTypeIndex,
326    },
327    ThreadSuspendThenResume {
328        func: ModuleInternedTypeIndex,
329    },
330    ThreadYieldThenResume {
331        func: ModuleInternedTypeIndex,
332    },
333    ThreadSuspendThenPromote {
334        func: ModuleInternedTypeIndex,
335    },
336    ThreadYieldThenPromote {
337        func: ModuleInternedTypeIndex,
338    },
339
340    // core wasm modules
341    ModuleStatic(StaticModuleIndex, ComponentCoreModuleTypeId),
342
343    // core wasm module instances
344    ModuleInstantiate(ModuleIndex, HashMap<&'data str, ModuleInstanceIndex>),
345    ModuleSynthetic(HashMap<&'data str, EntityIndex>),
346
347    // components
348    ComponentStatic(StaticComponentIndex, ClosedOverVars),
349
350    // component instances
351    ComponentInstantiate(
352        ComponentIndex,
353        HashMap<&'data str, ComponentItem>,
354        ComponentInstanceTypeId,
355    ),
356    ComponentSynthetic(HashMap<&'data str, ComponentItem>, ComponentInstanceTypeId),
357
358    // alias section
359    AliasExportFunc(ModuleInstanceIndex, &'data str),
360    AliasExportTable(ModuleInstanceIndex, &'data str),
361    AliasExportGlobal(ModuleInstanceIndex, &'data str),
362    AliasExportMemory(ModuleInstanceIndex, &'data str),
363    AliasExportTag(ModuleInstanceIndex, &'data str),
364    AliasComponentExport(ComponentInstanceIndex, &'data str),
365    AliasModule(ClosedOverModule),
366    AliasComponent(ClosedOverComponent),
367
368    // export section
369    Export(ComponentItem),
370}
371
372/// The "closure environment" of components themselves.
373///
374/// For more information see `LexicalScope`.
375#[derive(Default)]
376struct ClosedOverVars {
377    components: PrimaryMap<ComponentUpvarIndex, ClosedOverComponent>,
378    modules: PrimaryMap<ModuleUpvarIndex, ClosedOverModule>,
379}
380
381/// Description how a component is closed over when the closure variables for
382/// a component are being created.
383///
384/// For more information see `LexicalScope`.
385enum ClosedOverComponent {
386    /// A closed over component is coming from the local component's index
387    /// space, meaning a previously defined component is being captured.
388    Local(ComponentIndex),
389    /// A closed over component is coming from our own component's list of
390    /// upvars. This list was passed to us by our enclosing component, which
391    /// will eventually have bottomed out in closing over a `Local` component
392    /// index for some parent component.
393    Upvar(ComponentUpvarIndex),
394}
395
396/// Same as `ClosedOverComponent`, but for modules.
397enum ClosedOverModule {
398    Local(ModuleIndex),
399    Upvar(ModuleUpvarIndex),
400}
401
402/// The data model for objects that are not unboxed in locals.
403#[derive(Debug, Clone, Hash, Eq, PartialEq)]
404pub enum LocalDataModel {
405    /// Data is stored in GC objects.
406    Gc {},
407
408    /// Data is stored in a linear memory.
409    LinearMemory {
410        /// An optional memory definition supplied.
411        memory: Option<MemoryIndex>,
412        /// An optional definition of `realloc` to used.
413        realloc: Option<FuncIndex>,
414    },
415}
416
417/// Representation of canonical ABI options.
418struct LocalCanonicalOptions {
419    string_encoding: StringEncoding,
420    post_return: Option<FuncIndex>,
421    async_: bool,
422    callback: Option<FuncIndex>,
423    /// The type index of the core GC types signature.
424    core_type: ModuleInternedTypeIndex,
425    data_model: LocalDataModel,
426}
427
428enum Action {
429    KeepGoing,
430    Skip(usize),
431    Done,
432}
433
434impl<'a, 'data> Translator<'a, 'data> {
435    /// Creates a new translation state ready to translate a component.
436    pub fn new(
437        tunables: &'a Tunables,
438        validator: &'a mut Validator,
439        types: &'a mut ComponentTypesBuilder,
440        scope_vec: &'data ScopeVec<u8>,
441    ) -> Self {
442        let mut parser = Parser::new(0);
443        parser.set_features(*validator.features());
444        Self {
445            result: Translation::default(),
446            tunables,
447            validator,
448            types: PreInliningComponentTypes::new(types),
449            parser,
450            lexical_scopes: Vec::new(),
451            static_components: Default::default(),
452            static_modules: Default::default(),
453            scope_vec,
454            unsafe_intrinsics_import: None,
455        }
456    }
457
458    /// Expose Wasmtime's unsafe intrinsics under the given top-level import
459    /// name.
460    pub fn expose_unsafe_intrinsics(&mut self, name: &'a str) -> &mut Self {
461        assert!(self.unsafe_intrinsics_import.is_none());
462        self.unsafe_intrinsics_import = Some(name);
463        self
464    }
465
466    /// Translates the binary `component`.
467    ///
468    /// This is the workhorse of compilation which will parse all of
469    /// `component` and create type information for Wasmtime and such. The
470    /// `component` does not have to be valid and it will be validated during
471    /// compilation.
472    ///
473    /// The result of this function is a tuple of the final component's
474    /// description plus a list of core wasm modules found within the
475    /// component. The component's description actually erases internal
476    /// components, instances, etc, as much as it can. Instead `Component`
477    /// retains a flat list of initializers (no nesting) which was created
478    /// as part of compilation from the nested structure of the original
479    /// component.
480    ///
481    /// The list of core wasm modules found is provided to allow compiling
482    /// modules externally in parallel. Additionally initializers in
483    /// `Component` may refer to the modules in the map returned by index.
484    ///
485    /// # Errors
486    ///
487    /// This function will return an error if the `component` provided is
488    /// invalid.
489    pub fn translate(
490        mut self,
491        component: &'data [u8],
492    ) -> Result<(
493        ComponentTranslation,
494        PrimaryMap<StaticModuleIndex, ModuleTranslation<'data>>,
495    )> {
496        // First up wasmparser is used to actually perform the translation and
497        // validation of this component. This will produce a list of core wasm
498        // modules in addition to components which are found during the
499        // translation process. When doing this only a `Translation` is created
500        // which is a simple representation of a component.
501        let mut remaining = component;
502        loop {
503            let payload = match self.parser.parse(remaining, true)? {
504                Chunk::Parsed { payload, consumed } => {
505                    remaining = &remaining[consumed..];
506                    payload
507                }
508                Chunk::NeedMoreData(_) => unreachable!(),
509            };
510
511            match self.translate_payload(payload, component)? {
512                Action::KeepGoing => {}
513                Action::Skip(n) => remaining = &remaining[n..],
514                Action::Done => break,
515            }
516        }
517        assert!(remaining.is_empty());
518        assert!(self.lexical_scopes.is_empty());
519
520        // ... after translation initially finishes the next pass is performed
521        // which we're calling "inlining". This will "instantiate" the root
522        // component, following nested component instantiations, creating a
523        // global list of initializers along the way. This phase uses the simple
524        // initializers in each component to track dataflow of host imports and
525        // internal references to items throughout a component at compile-time.
526        // The produce initializers in the final `Component` are intended to be
527        // much simpler than the original component and more efficient for
528        // Wasmtime to process at runtime as well (e.g. no string lookups as
529        // most everything is done through indices instead).
530        let mut component = inline::run(
531            self.types.types_mut_for_inlining(),
532            &self.result,
533            &self.static_modules,
534            &self.static_components,
535        )?;
536
537        // Now that inlining has finished and the dataflow graph is complete,
538        // determine which fused adapters can skip their
539        // `{enter,exit}-sync-call` calls.
540        component.transparent_adapters = transparent_adapters(&component, self.types.types());
541
542        self.partition_adapter_modules(&mut component)?;
543
544        analyze_same_vmctx_imports(&component, &mut self.static_modules);
545
546        let translation =
547            component.finish(self.types.types_mut_for_inlining(), self.result.types_ref())?;
548
549        self.analyze_imports(&translation);
550
551        Ok((translation, self.static_modules))
552    }
553
554    /// Record everything we statically know about each module's imports.
555    ///
556    /// See `ModuleTranslation::known_imported_functions` and
557    /// `ModuleTranslation::known_imported_globals` for how we can optimize
558    /// lowering based on this information.
559    fn analyze_imports(&mut self, translation: &ComponentTranslation) {
560        // First, abstract interpret the initializers to create a map from each
561        // static module to its abstract set of instantiations.
562        let mut instantiations = SecondaryMap::<StaticModuleIndex, AbstractInstantiations>::new();
563        let mut instances = StaticInstances::new(&self.static_modules);
564        for init in &translation.component.initializers {
565            match init {
566                GlobalInitializer::InstantiateModule(instantiation, _) => match instantiation {
567                    InstantiateModule::Static(module, args) => {
568                        instantiations[*module].join(AbstractInstantiations::One(&*args));
569                        instances.push(Some((*module, &args[..])));
570                    }
571                    _ => {
572                        instances.push(None);
573                    }
574                },
575                _ => continue,
576            }
577        }
578
579        // Second, make sure to mark exported modules as instantiated many
580        // times, since they could be linked with who-knows-what at runtime.
581        for item in translation.component.export_items.values() {
582            if let Export::ModuleStatic { index, .. } = item {
583                instantiations[*index].join(AbstractInstantiations::Many)
584            }
585        }
586
587        // Third, find the globals, memories, and tables whose identity is not
588        // statically known to everything that can access them. Note that this
589        // is a property of the whole component and not of a single module's
590        // instantiations; see `ModuleTranslation::known_imported_globals` for
591        // details.
592        let ambiguous = ambiguous_entities(translation, &instantiations, &instances);
593
594        // Fourth, record which of each module's own defined entities all of
595        // their importers agree on, which lets those modules use a precise alias
596        // region for them even when they are exported.
597        for (module, translation) in self.static_modules.iter_mut() {
598            for i in 0..translation.module.num_defined_globals() {
599                let index = DefinedGlobalIndex::new(i);
600                let global = translation.module.global_index(index);
601                if !ambiguous
602                    .entities
603                    .contains(&(module, EntityIndex::Global(global)))
604                {
605                    translation.globals_known_to_importers.insert(index);
606                }
607            }
608            for i in 0..translation.module.num_defined_memories() {
609                let index = DefinedMemoryIndex::new(i);
610                let memory = translation.module.memory_index(index);
611                if !ambiguous
612                    .entities
613                    .contains(&(module, EntityIndex::Memory(memory)))
614                {
615                    translation.memories_known_to_importers.insert(index);
616                }
617            }
618            for i in 0..translation.module.num_defined_tables() {
619                let index = DefinedTableIndex::new(i);
620                let table = translation.module.table_index(index);
621                if !ambiguous
622                    .entities
623                    .contains(&(module, EntityIndex::Table(table)))
624                {
625                    translation.tables_known_to_importers.insert(index);
626                }
627            }
628        }
629
630        // Finally, iterate over our instantiations and record statically-known
631        // imports: function imports so that they can get translated into direct
632        // calls (and eventually get inlined) rather than indirect calls through
633        // the imports table; and global, memory, and table imports so that they
634        // can get precise alias regions instead of the conservative regions
635        // shared by everything that crosses a module boundary.
636        for (module, instantiations) in instantiations.iter() {
637            let args = match instantiations {
638                dfg::AbstractInstantiations::Many | dfg::AbstractInstantiations::None => continue,
639                dfg::AbstractInstantiations::One(args) => args,
640            };
641
642            for (i, arg) in args.iter().enumerate() {
643                // Record that this global, memory, or table import is always the
644                // same defined entity, when we know that and when everything
645                // else that imports that entity knows it too.
646                macro_rules! record_known_entity {
647                    ($variant:ident, $imported:expr, $defined_index:ident, $known:ident, $wrap:expr) => {{
648                        let Some((arg_module, EntityIndex::$variant(arg_entity))) =
649                            unambiguous_entity(&instances, &ambiguous.entities, arg)
650                        else {
651                            continue;
652                        };
653                        let index = self.static_modules[arg_module]
654                            .module
655                            .$defined_index(arg_entity)
656                            .expect(
657                                "`resolve_core_export` only returns entities that their module \
658                                 defines",
659                            );
660                        assert!(self.static_modules[module].$known[$imported].is_none());
661                        self.static_modules[module].$known[$imported] = Some($wrap(KnownEntity {
662                            module: arg_module,
663                            index,
664                        }));
665                    }};
666                }
667
668                match self.static_modules[module].module.import_index(i).unwrap() {
669                    EntityIndex::Function(imported_func) => {
670                        debug_assert!(
671                            self.static_modules[module]
672                                .module
673                                .defined_func_index(imported_func)
674                                .is_none()
675                        );
676
677                        let known_func = match arg {
678                            CoreDef::InstanceFlags(_) => {
679                                unreachable!("instance flags are not a function")
680                            }
681
682                            // We could in theory inline these trampolines, so it
683                            // could potentially make sense to record that we
684                            // know this imported function is this particular
685                            // trampoline. However, everything else is based
686                            // around (module, defined-function) pairs and these
687                            // trampolines don't fit that paradigm. Also,
688                            // inlining trampolines gets really tricky when we
689                            // consider the stack pointer, frame pointer, and
690                            // return address note-taking that they do for the
691                            // purposes of stack walking. We could, with enough
692                            // effort, turn them into direct calls even though we
693                            // probably wouldn't ever inline them, but it just
694                            // doesn't seem worth the effort.
695                            //
696                            // That said, a couple of adapter trampolines are
697                            // lowered inline during translation. We record these
698                            // here so `FuncEnvironment` recognizes them. All
699                            // other trampolines remain indirect calls.
700                            CoreDef::Trampoline(index) => match translation.trampolines[*index] {
701                                Trampoline::EnterSyncCall => {
702                                    FactInlineIntrinsic::EnterSyncCall.into()
703                                }
704                                Trampoline::ExitSyncCall => {
705                                    FactInlineIntrinsic::ExitSyncCall.into()
706                                }
707                                Trampoline::Trap(trap) => FactInlineIntrinsic::Trap(trap).into(),
708                                Trampoline::ResourceTransferBorrowToOwner { ty } => {
709                                    let instance =
710                                        self.types.types()[ty].unwrap_concrete_instance();
711                                    FactInlineIntrinsic::from(
712                                        FactComponentIntrinsic::ResourceTransferBorrowToOwner {
713                                            ty,
714                                            instance,
715                                        },
716                                    )
717                                    .into()
718                                }
719                                Trampoline::LowerImport { .. } => {
720                                    // Uncaught exceptions become traps at component boundaries
721                                    self.static_modules[module]
722                                        .imported_funcs_never_throw
723                                        .insert(imported_func);
724
725                                    continue;
726                                }
727                                _ => continue,
728                            },
729
730                            // This import is a compile-time builtin intrinsic,
731                            // we should inline its implementation during
732                            // function translation.
733                            CoreDef::UnsafeIntrinsic(i) => {
734                                FuncKey::UnsafeIntrinsic(Abi::Wasm, *i).into()
735                            }
736
737                            // This imported function is an export from another
738                            // instance, a perfect candidate for becoming an
739                            // inlinable direct call!
740                            CoreDef::Export(export) => {
741                                let Some((arg_module, arg_entity)) =
742                                    resolve_core_export(&instances, export)
743                                else {
744                                    // Either an instance of a dynamic module that
745                                    // is not part of this component, or a
746                                    // re-export chain that bottoms out in
747                                    // something that isn't a defined function
748                                    // (for example a re-export of a trampoline;
749                                    // note that we only match trampolines and
750                                    // intrinsics as *direct* arguments above).
751                                    // Either way we have to do an indirect call.
752                                    continue;
753                                };
754
755                                let EntityIndex::Function(arg_func) = arg_entity else {
756                                    unreachable!("function imports must be functions")
757                                };
758
759                                let arg_module_def_func = self.static_modules[arg_module]
760                                    .module
761                                    .defined_func_index(arg_func)
762                                    .expect(
763                                        "`resolve_core_export` only returns entities that their \
764                                         module defines",
765                                    );
766
767                                FuncKey::DefinedWasmFunction(arg_module, arg_module_def_func).into()
768                            }
769                        };
770
771                        assert!(
772                            self.static_modules[module].known_imported_functions[imported_func]
773                                .is_none()
774                        );
775                        self.static_modules[module].known_imported_functions[imported_func] =
776                            Some(known_func);
777                    }
778
779                    // Note that a global import is not necessarily satisfied by a
780                    // wasm global: it can also be one of the component-model
781                    // flags that live in the `VMComponentContext`, and those get
782                    // their own alias regions rather than a defined-global one.
783                    EntityIndex::Global(imported_global) => match component_flags(arg) {
784                        Some(flags) => {
785                            if ambiguous.flags.contains(&flags) {
786                                continue;
787                            }
788                            assert!(
789                                self.static_modules[module].known_imported_globals[imported_global]
790                                    .is_none()
791                            );
792                            self.static_modules[module].known_imported_globals[imported_global] =
793                                Some(flags);
794                        }
795                        None => record_known_entity!(
796                            Global,
797                            imported_global,
798                            defined_global_index,
799                            known_imported_globals,
800                            KnownGlobal::Defined
801                        ),
802                    },
803
804                    EntityIndex::Memory(imported_memory) => record_known_entity!(
805                        Memory,
806                        imported_memory,
807                        defined_memory_index,
808                        known_imported_memories,
809                        core::convert::identity
810                    ),
811
812                    EntityIndex::Table(imported_table) => record_known_entity!(
813                        Table,
814                        imported_table,
815                        defined_table_index,
816                        known_imported_tables,
817                        core::convert::identity
818                    ),
819
820                    // Tags don't have alias regions of their own.
821                    EntityIndex::Tag(_) => {}
822                }
823            }
824        }
825    }
826
827    fn translate_payload(
828        &mut self,
829        payload: Payload<'data>,
830        component: &'data [u8],
831    ) -> Result<Action> {
832        match payload {
833            Payload::Version {
834                num,
835                encoding,
836                range,
837            } => {
838                self.validator.version(num, encoding, &range)?;
839
840                match encoding {
841                    Encoding::Component => {}
842                    Encoding::Module => {
843                        bail!("attempted to parse a wasm module with a component parser");
844                    }
845                }
846            }
847
848            Payload::End(offset) => {
849                assert!(self.result.types.is_none());
850                self.result.types = Some(self.validator.end(offset)?);
851
852                // Exit the current lexical scope. If there is no parent (no
853                // frame currently on the stack) then translation is finished.
854                // Otherwise that means that a nested component has been
855                // completed and is recorded as such.
856                let LexicalScope {
857                    parser,
858                    translation,
859                    closure_args,
860                } = match self.lexical_scopes.pop() {
861                    Some(frame) => frame,
862                    None => return Ok(Action::Done),
863                };
864                self.parser = parser;
865                let component = mem::replace(&mut self.result, translation);
866                let static_idx = self.static_components.push(component);
867                self.result
868                    .initializers
869                    .push(LocalInitializer::ComponentStatic(static_idx, closure_args));
870            }
871
872            // When we see a type section the types are validated and then
873            // translated into Wasmtime's representation. Each active type
874            // definition is recorded in the `ComponentTypesBuilder` tables, or
875            // this component's active scope.
876            //
877            // Note that the push/pop of the component types scope happens above
878            // in `Version` and `End` since multiple type sections can appear
879            // within a component.
880            Payload::ComponentTypeSection(s) => {
881                let mut component_type_index =
882                    self.validator.types(0).unwrap().component_type_count();
883                self.validator.component_type_section(&s)?;
884
885                // Look for resource types and if a local resource is defined
886                // then an initializer is added to define that resource type and
887                // reference its destructor.
888                let types = self.validator.types(0).unwrap();
889                for ty in s {
890                    match ty? {
891                        wasmparser::ComponentType::Resource { rep, dtor } => {
892                            let rep = self.types.convert_valtype(rep)?;
893                            let id = types
894                                .component_any_type_at(component_type_index)
895                                .unwrap_resource();
896                            let dtor = dtor.map(FuncIndex::from_u32);
897                            self.result
898                                .initializers
899                                .push(LocalInitializer::Resource(id, rep, dtor));
900                        }
901
902                        // no extra processing needed
903                        wasmparser::ComponentType::Defined(_)
904                        | wasmparser::ComponentType::Func(_)
905                        | wasmparser::ComponentType::Instance(_)
906                        | wasmparser::ComponentType::Component(_) => {}
907                    }
908
909                    component_type_index += 1;
910                }
911            }
912
913            // Core types defined at the component level, such as the type of a
914            // `thread.new-indirect` start function, are interned as they're
915            // defined, just like in a core module. This ensures that all rec
916            // groups that a rec group refers to are interned before it is.
917            Payload::CoreTypeSection(s) => {
918                let mut index = self
919                    .validator
920                    .types(0)
921                    .unwrap()
922                    .core_type_count_in_component();
923                self.validator.core_type_section(&s)?;
924                let types = self.validator.types(0).unwrap();
925                let count = types.core_type_count_in_component();
926                while index < count {
927                    match types.core_type_at_in_component(index) {
928                        // The current type index is always the first type of
929                        // its rec group, so intern the group and then skip
930                        // past the rest of its types.
931                        ComponentCoreTypeId::Sub(id) => {
932                            let group_id = types.rec_group_id_of(id);
933                            self.types
934                                .module_types_builder()
935                                .intern_rec_group(types, group_id)?;
936                            index +=
937                                u32::try_from(types.rec_group_elements(group_id).len()).unwrap();
938                        }
939                        ComponentCoreTypeId::Module(_) => index += 1,
940                    }
941                }
942            }
943
944            // Processing the import section at this point is relatively simple
945            // which is to simply record the name of the import and the type
946            // information associated with it.
947            Payload::ComponentImportSection(s) => {
948                self.validator.component_import_section(&s)?;
949                for import in s {
950                    let import = import?;
951                    let types = self.validator.types(0).unwrap();
952                    let ty = types
953                        .component_item_for_import(import.name.name)
954                        .unwrap()
955                        .ty;
956
957                    if self.is_unsafe_intrinsics_import(import.name.name) {
958                        self.check_unsafe_intrinsics_import(import.name.name, ty)?;
959                        self.result
960                            .initializers
961                            .push(LocalInitializer::IntrinsicsImport);
962                    } else {
963                        self.result
964                            .initializers
965                            .push(LocalInitializer::Import(import.name, ty));
966                    }
967                }
968            }
969
970            // Entries in the canonical section will get initializers recorded
971            // with the listed options for lifting/lowering.
972            Payload::ComponentCanonicalSection(s) => {
973                let types = self.validator.types(0).unwrap();
974                let mut core_func_index = types.function_count();
975                self.validator.component_canonical_section(&s)?;
976                for func in s {
977                    let init = match func? {
978                        wasmparser::CanonicalFunction::Lift {
979                            type_index,
980                            core_func_index,
981                            options,
982                        } => {
983                            let ty = self
984                                .validator
985                                .types(0)
986                                .unwrap()
987                                .component_any_type_at(type_index)
988                                .unwrap_func();
989
990                            let func = FuncIndex::from_u32(core_func_index);
991                            let options = self.canonical_options(&options, core_func_index)?;
992                            LocalInitializer::Lift(ty, func, options)
993                        }
994                        wasmparser::CanonicalFunction::Lower {
995                            func_index,
996                            options,
997                        } => {
998                            let lower_ty = self
999                                .validator
1000                                .types(0)
1001                                .unwrap()
1002                                .component_function_at(func_index);
1003                            let func = ComponentFuncIndex::from_u32(func_index);
1004                            let options = self.canonical_options(&options, core_func_index)?;
1005                            core_func_index += 1;
1006                            LocalInitializer::Lower {
1007                                func,
1008                                options,
1009                                lower_ty,
1010                            }
1011                        }
1012                        wasmparser::CanonicalFunction::ResourceNew { resource } => {
1013                            let resource = self
1014                                .validator
1015                                .types(0)
1016                                .unwrap()
1017                                .component_any_type_at(resource)
1018                                .unwrap_resource();
1019                            let ty = self.core_func_signature(core_func_index)?;
1020                            core_func_index += 1;
1021                            LocalInitializer::ResourceNew(resource, ty)
1022                        }
1023                        wasmparser::CanonicalFunction::ResourceDrop { resource } => {
1024                            let resource = self
1025                                .validator
1026                                .types(0)
1027                                .unwrap()
1028                                .component_any_type_at(resource)
1029                                .unwrap_resource();
1030                            let ty = self.core_func_signature(core_func_index)?;
1031                            core_func_index += 1;
1032                            LocalInitializer::ResourceDrop(resource, ty)
1033                        }
1034                        wasmparser::CanonicalFunction::ResourceRep { resource } => {
1035                            let resource = self
1036                                .validator
1037                                .types(0)
1038                                .unwrap()
1039                                .component_any_type_at(resource)
1040                                .unwrap_resource();
1041                            let ty = self.core_func_signature(core_func_index)?;
1042                            core_func_index += 1;
1043                            LocalInitializer::ResourceRep(resource, ty)
1044                        }
1045                        wasmparser::CanonicalFunction::ThreadSpawnRef { .. }
1046                        | wasmparser::CanonicalFunction::ThreadSpawnIndirect { .. }
1047                        | wasmparser::CanonicalFunction::ThreadAvailableParallelism => {
1048                            bail!("unsupported intrinsic")
1049                        }
1050                        wasmparser::CanonicalFunction::BackpressureInc => {
1051                            let core_type = self.core_func_signature(core_func_index)?;
1052                            core_func_index += 1;
1053                            LocalInitializer::BackpressureInc { func: core_type }
1054                        }
1055                        wasmparser::CanonicalFunction::BackpressureDec => {
1056                            let core_type = self.core_func_signature(core_func_index)?;
1057                            core_func_index += 1;
1058                            LocalInitializer::BackpressureDec { func: core_type }
1059                        }
1060
1061                        wasmparser::CanonicalFunction::TaskReturn { result, options } => {
1062                            let result = result.map(|ty| match ty {
1063                                wasmparser::ComponentValType::Primitive(ty) => {
1064                                    ComponentValType::Primitive(ty)
1065                                }
1066                                wasmparser::ComponentValType::Type(ty) => ComponentValType::Type(
1067                                    self.validator
1068                                        .types(0)
1069                                        .unwrap()
1070                                        .component_defined_type_at(ty),
1071                                ),
1072                            });
1073                            let options = self.canonical_options(&options, core_func_index)?;
1074                            core_func_index += 1;
1075                            LocalInitializer::TaskReturn { result, options }
1076                        }
1077                        wasmparser::CanonicalFunction::TaskCancel => {
1078                            let func = self.core_func_signature(core_func_index)?;
1079                            core_func_index += 1;
1080                            LocalInitializer::TaskCancel { func }
1081                        }
1082                        wasmparser::CanonicalFunction::WaitableSetNew => {
1083                            let func = self.core_func_signature(core_func_index)?;
1084                            core_func_index += 1;
1085                            LocalInitializer::WaitableSetNew { func }
1086                        }
1087                        wasmparser::CanonicalFunction::WaitableSetWait { memory } => {
1088                            let core_type = self.core_func_signature(core_func_index)?;
1089                            core_func_index += 1;
1090                            LocalInitializer::WaitableSetWait {
1091                                options: LocalCanonicalOptions {
1092                                    core_type,
1093                                    async_: false,
1094                                    data_model: LocalDataModel::LinearMemory {
1095                                        memory: Some(MemoryIndex::from_u32(memory)),
1096                                        realloc: None,
1097                                    },
1098                                    post_return: None,
1099                                    callback: None,
1100                                    string_encoding: StringEncoding::Utf8,
1101                                },
1102                            }
1103                        }
1104                        wasmparser::CanonicalFunction::WaitableSetPoll { memory } => {
1105                            let core_type = self.core_func_signature(core_func_index)?;
1106                            core_func_index += 1;
1107                            LocalInitializer::WaitableSetPoll {
1108                                options: LocalCanonicalOptions {
1109                                    core_type,
1110                                    async_: false,
1111                                    data_model: LocalDataModel::LinearMemory {
1112                                        memory: Some(MemoryIndex::from_u32(memory)),
1113                                        realloc: None,
1114                                    },
1115                                    post_return: None,
1116                                    callback: None,
1117                                    string_encoding: StringEncoding::Utf8,
1118                                },
1119                            }
1120                        }
1121                        wasmparser::CanonicalFunction::WaitableSetDrop => {
1122                            let func = self.core_func_signature(core_func_index)?;
1123                            core_func_index += 1;
1124                            LocalInitializer::WaitableSetDrop { func }
1125                        }
1126                        wasmparser::CanonicalFunction::WaitableJoin => {
1127                            let func = self.core_func_signature(core_func_index)?;
1128                            core_func_index += 1;
1129                            LocalInitializer::WaitableJoin { func }
1130                        }
1131                        wasmparser::CanonicalFunction::SubtaskDrop => {
1132                            let func = self.core_func_signature(core_func_index)?;
1133                            core_func_index += 1;
1134                            LocalInitializer::SubtaskDrop { func }
1135                        }
1136                        wasmparser::CanonicalFunction::SubtaskCancel { async_ } => {
1137                            let func = self.core_func_signature(core_func_index)?;
1138                            core_func_index += 1;
1139                            LocalInitializer::SubtaskCancel { func, async_ }
1140                        }
1141                        wasmparser::CanonicalFunction::StreamNew { ty } => {
1142                            let ty = self
1143                                .validator
1144                                .types(0)
1145                                .unwrap()
1146                                .component_defined_type_at(ty);
1147                            let func = self.core_func_signature(core_func_index)?;
1148                            core_func_index += 1;
1149                            LocalInitializer::StreamNew { ty, func }
1150                        }
1151                        wasmparser::CanonicalFunction::StreamRead { ty, options } => {
1152                            let ty = self
1153                                .validator
1154                                .types(0)
1155                                .unwrap()
1156                                .component_defined_type_at(ty);
1157                            let options = self.canonical_options(&options, core_func_index)?;
1158                            core_func_index += 1;
1159                            LocalInitializer::StreamRead { ty, options }
1160                        }
1161                        wasmparser::CanonicalFunction::StreamWrite { ty, options } => {
1162                            let ty = self
1163                                .validator
1164                                .types(0)
1165                                .unwrap()
1166                                .component_defined_type_at(ty);
1167                            let options = self.canonical_options(&options, core_func_index)?;
1168                            core_func_index += 1;
1169                            LocalInitializer::StreamWrite { ty, options }
1170                        }
1171                        wasmparser::CanonicalFunction::StreamCancelRead { ty, async_ } => {
1172                            let ty = self
1173                                .validator
1174                                .types(0)
1175                                .unwrap()
1176                                .component_defined_type_at(ty);
1177                            let func = self.core_func_signature(core_func_index)?;
1178                            core_func_index += 1;
1179                            LocalInitializer::StreamCancelRead { ty, func, async_ }
1180                        }
1181                        wasmparser::CanonicalFunction::StreamCancelWrite { ty, async_ } => {
1182                            let ty = self
1183                                .validator
1184                                .types(0)
1185                                .unwrap()
1186                                .component_defined_type_at(ty);
1187                            let func = self.core_func_signature(core_func_index)?;
1188                            core_func_index += 1;
1189                            LocalInitializer::StreamCancelWrite { ty, func, async_ }
1190                        }
1191                        wasmparser::CanonicalFunction::StreamDropReadable { ty } => {
1192                            let ty = self
1193                                .validator
1194                                .types(0)
1195                                .unwrap()
1196                                .component_defined_type_at(ty);
1197                            let func = self.core_func_signature(core_func_index)?;
1198                            core_func_index += 1;
1199                            LocalInitializer::StreamDropReadable { ty, func }
1200                        }
1201                        wasmparser::CanonicalFunction::StreamDropWritable { ty } => {
1202                            let ty = self
1203                                .validator
1204                                .types(0)
1205                                .unwrap()
1206                                .component_defined_type_at(ty);
1207                            let func = self.core_func_signature(core_func_index)?;
1208                            core_func_index += 1;
1209                            LocalInitializer::StreamDropWritable { ty, func }
1210                        }
1211                        wasmparser::CanonicalFunction::FutureNew { ty } => {
1212                            let ty = self
1213                                .validator
1214                                .types(0)
1215                                .unwrap()
1216                                .component_defined_type_at(ty);
1217                            let func = self.core_func_signature(core_func_index)?;
1218                            core_func_index += 1;
1219                            LocalInitializer::FutureNew { ty, func }
1220                        }
1221                        wasmparser::CanonicalFunction::FutureRead { ty, options } => {
1222                            let ty = self
1223                                .validator
1224                                .types(0)
1225                                .unwrap()
1226                                .component_defined_type_at(ty);
1227                            let options = self.canonical_options(&options, core_func_index)?;
1228                            core_func_index += 1;
1229                            LocalInitializer::FutureRead { ty, options }
1230                        }
1231                        wasmparser::CanonicalFunction::FutureWrite { ty, options } => {
1232                            let ty = self
1233                                .validator
1234                                .types(0)
1235                                .unwrap()
1236                                .component_defined_type_at(ty);
1237                            let options = self.canonical_options(&options, core_func_index)?;
1238                            core_func_index += 1;
1239                            LocalInitializer::FutureWrite { ty, options }
1240                        }
1241                        wasmparser::CanonicalFunction::FutureCancelRead { ty, async_ } => {
1242                            let ty = self
1243                                .validator
1244                                .types(0)
1245                                .unwrap()
1246                                .component_defined_type_at(ty);
1247                            let func = self.core_func_signature(core_func_index)?;
1248                            core_func_index += 1;
1249                            LocalInitializer::FutureCancelRead { ty, func, async_ }
1250                        }
1251                        wasmparser::CanonicalFunction::FutureCancelWrite { ty, async_ } => {
1252                            let ty = self
1253                                .validator
1254                                .types(0)
1255                                .unwrap()
1256                                .component_defined_type_at(ty);
1257                            let func = self.core_func_signature(core_func_index)?;
1258                            core_func_index += 1;
1259                            LocalInitializer::FutureCancelWrite { ty, func, async_ }
1260                        }
1261                        wasmparser::CanonicalFunction::FutureDropReadable { ty } => {
1262                            let ty = self
1263                                .validator
1264                                .types(0)
1265                                .unwrap()
1266                                .component_defined_type_at(ty);
1267                            let func = self.core_func_signature(core_func_index)?;
1268                            core_func_index += 1;
1269                            LocalInitializer::FutureDropReadable { ty, func }
1270                        }
1271                        wasmparser::CanonicalFunction::FutureDropWritable { ty } => {
1272                            let ty = self
1273                                .validator
1274                                .types(0)
1275                                .unwrap()
1276                                .component_defined_type_at(ty);
1277                            let func = self.core_func_signature(core_func_index)?;
1278                            core_func_index += 1;
1279                            LocalInitializer::FutureDropWritable { ty, func }
1280                        }
1281                        wasmparser::CanonicalFunction::ErrorContextNew { options } => {
1282                            let options = self.canonical_options(&options, core_func_index)?;
1283                            core_func_index += 1;
1284                            LocalInitializer::ErrorContextNew { options }
1285                        }
1286                        wasmparser::CanonicalFunction::ErrorContextDebugMessage { options } => {
1287                            let options = self.canonical_options(&options, core_func_index)?;
1288                            core_func_index += 1;
1289                            LocalInitializer::ErrorContextDebugMessage { options }
1290                        }
1291                        wasmparser::CanonicalFunction::ErrorContextDrop => {
1292                            let func = self.core_func_signature(core_func_index)?;
1293                            core_func_index += 1;
1294                            LocalInitializer::ErrorContextDrop { func }
1295                        }
1296                        wasmparser::CanonicalFunction::ContextGet { slot, ty } => {
1297                            if ty != wasmparser::ValType::I32 {
1298                                bail!("unsupported context.get type: {ty:?}");
1299                            }
1300                            let func = self.core_func_signature(core_func_index)?;
1301                            core_func_index += 1;
1302                            LocalInitializer::ContextGet { i: slot, func }
1303                        }
1304                        wasmparser::CanonicalFunction::ContextSet { slot, ty } => {
1305                            if ty != wasmparser::ValType::I32 {
1306                                bail!("unsupported context.set type: {ty:?}");
1307                            }
1308                            let func = self.core_func_signature(core_func_index)?;
1309                            core_func_index += 1;
1310                            LocalInitializer::ContextSet { i: slot, func }
1311                        }
1312                        wasmparser::CanonicalFunction::ThreadIndex => {
1313                            let func = self.core_func_signature(core_func_index)?;
1314                            core_func_index += 1;
1315                            LocalInitializer::ThreadIndex { func }
1316                        }
1317                        wasmparser::CanonicalFunction::ThreadNewIndirect {
1318                            func_ty_index,
1319                            table_index,
1320                        } => {
1321                            let func = self.core_func_signature(core_func_index)?;
1322                            core_func_index += 1;
1323                            let types = self.validator.types(0).unwrap();
1324                            let start_func_ty =
1325                                types.core_type_at_in_component(func_ty_index).unwrap_sub();
1326                            let start_func_ty = self
1327                                .types
1328                                .module_types_builder()
1329                                .intern_type(types, start_func_ty)?;
1330                            LocalInitializer::ThreadNewIndirect {
1331                                func,
1332                                start_func_ty,
1333                                start_func_table_index: TableIndex::from_u32(table_index),
1334                            }
1335                        }
1336                        wasmparser::CanonicalFunction::ThreadResumeLater => {
1337                            let func = self.core_func_signature(core_func_index)?;
1338                            core_func_index += 1;
1339                            LocalInitializer::ThreadResumeLater { func }
1340                        }
1341                        wasmparser::CanonicalFunction::ThreadSuspend => {
1342                            let func = self.core_func_signature(core_func_index)?;
1343                            core_func_index += 1;
1344                            LocalInitializer::ThreadSuspend { func }
1345                        }
1346                        wasmparser::CanonicalFunction::ThreadYield => {
1347                            let func = self.core_func_signature(core_func_index)?;
1348                            core_func_index += 1;
1349                            LocalInitializer::ThreadYield { func }
1350                        }
1351                        wasmparser::CanonicalFunction::ThreadSuspendThenResume => {
1352                            let func = self.core_func_signature(core_func_index)?;
1353                            core_func_index += 1;
1354                            LocalInitializer::ThreadSuspendThenResume { func }
1355                        }
1356                        wasmparser::CanonicalFunction::ThreadYieldThenResume => {
1357                            let func = self.core_func_signature(core_func_index)?;
1358                            core_func_index += 1;
1359                            LocalInitializer::ThreadYieldThenResume { func }
1360                        }
1361                        wasmparser::CanonicalFunction::ThreadSuspendThenPromote => {
1362                            let func = self.core_func_signature(core_func_index)?;
1363                            core_func_index += 1;
1364                            LocalInitializer::ThreadSuspendThenPromote { func }
1365                        }
1366                        wasmparser::CanonicalFunction::ThreadYieldThenPromote => {
1367                            let func = self.core_func_signature(core_func_index)?;
1368                            core_func_index += 1;
1369                            LocalInitializer::ThreadYieldThenPromote { func }
1370                        }
1371                        wasmparser::CanonicalFunction::StreamForward { .. } => {
1372                            bail!("unimplemented stream.forward")
1373                        }
1374                        wasmparser::CanonicalFunction::FutureForward { .. } => {
1375                            bail!("unimplemented stream.forward")
1376                        }
1377                    };
1378                    self.result.initializers.push(init);
1379                }
1380            }
1381
1382            // Core wasm modules are translated inline directly here with the
1383            // `ModuleEnvironment` from core wasm compilation. This will return
1384            // to the caller the size of the module so it knows how many bytes
1385            // of the input are skipped.
1386            //
1387            // Note that this is just initial type translation of the core wasm
1388            // module and actual function compilation is deferred until this
1389            // entire process has completed.
1390            Payload::ModuleSection {
1391                parser,
1392                unchecked_range,
1393            } => {
1394                let index = self.validator.types(0).unwrap().module_count();
1395                self.validator.module_section(&unchecked_range)?;
1396                let static_module_index = self.static_modules.next_key();
1397                let mut translation = ModuleEnvironment::new(
1398                    self.tunables,
1399                    self.validator,
1400                    self.types.module_types_builder(),
1401                    static_module_index,
1402                )
1403                .translate(
1404                    parser,
1405                    component
1406                        .get(unchecked_range.start as usize..unchecked_range.end as usize)
1407                        .ok_or_else(|| {
1408                            format_err!(
1409                                "section range {}..{} is out of bounds (bound = {})",
1410                                unchecked_range.start,
1411                                unchecked_range.end,
1412                                component.len()
1413                            )
1414                            .context("wasm component contains an invalid module section")
1415                        })?,
1416                )?;
1417
1418                translation.wasm_module_offset = unchecked_range.start;
1419                let static_module_index2 = self.static_modules.push(translation);
1420                assert_eq!(static_module_index, static_module_index2);
1421                let types = self.validator.types(0).unwrap();
1422                let ty = types.module_at(index);
1423                self.result
1424                    .initializers
1425                    .push(LocalInitializer::ModuleStatic(static_module_index, ty));
1426                return Ok(Action::Skip(
1427                    (unchecked_range.end - unchecked_range.start) as usize,
1428                ));
1429            }
1430
1431            // When a sub-component is found then the current translation state
1432            // is pushed onto the `lexical_scopes` stack. This will subsequently
1433            // get popped as part of `Payload::End` processing above.
1434            //
1435            // Note that the set of closure args for this new lexical scope
1436            // starts empty since it will only get populated if translation of
1437            // the nested component ends up aliasing some outer module or
1438            // component.
1439            Payload::ComponentSection {
1440                parser,
1441                unchecked_range,
1442            } => {
1443                self.validator.component_section(&unchecked_range)?;
1444                self.lexical_scopes.push(LexicalScope {
1445                    parser: mem::replace(&mut self.parser, parser),
1446                    translation: mem::take(&mut self.result),
1447                    closure_args: ClosedOverVars::default(),
1448                });
1449            }
1450
1451            // Both core wasm instances and component instances record
1452            // initializers of what form of instantiation is performed which
1453            // largely just records the arguments given from wasmparser into a
1454            // `HashMap` for processing later during inlining.
1455            Payload::InstanceSection(s) => {
1456                self.validator.instance_section(&s)?;
1457                for instance in s {
1458                    let init = match instance? {
1459                        wasmparser::Instance::Instantiate { module_index, args } => {
1460                            let index = ModuleIndex::from_u32(module_index);
1461                            self.instantiate_module(index, &args)
1462                        }
1463                        wasmparser::Instance::FromExports(exports) => {
1464                            self.instantiate_module_from_exports(&exports)
1465                        }
1466                    };
1467                    self.result.initializers.push(init);
1468                }
1469            }
1470            Payload::ComponentInstanceSection(s) => {
1471                let mut index = self.validator.types(0).unwrap().component_instance_count();
1472                self.validator.component_instance_section(&s)?;
1473                for instance in s {
1474                    let types = self.validator.types(0).unwrap();
1475                    let ty = types.component_instance_at(index);
1476                    let init = match instance? {
1477                        wasmparser::ComponentInstance::Instantiate {
1478                            component_index,
1479                            args,
1480                        } => {
1481                            let index = ComponentIndex::from_u32(component_index);
1482                            self.instantiate_component(index, &args, ty)?
1483                        }
1484                        wasmparser::ComponentInstance::FromExports(exports) => {
1485                            self.instantiate_component_from_exports(&exports, ty)?
1486                        }
1487                    };
1488                    self.result.initializers.push(init);
1489                    index += 1;
1490                }
1491            }
1492
1493            // Exports don't actually fill out the `initializers` array but
1494            // instead fill out the one other field in a `Translation`, the
1495            // `exports` field (as one might imagine). This for now simply
1496            // records the index of what's exported and that's tracked further
1497            // later during inlining.
1498            Payload::ComponentExportSection(s) => {
1499                self.validator.component_export_section(&s)?;
1500                for export in s {
1501                    let export = export?;
1502                    let item = self.kind_to_item(export.kind, export.index)?;
1503                    let prev = self
1504                        .result
1505                        .exports
1506                        .insert(export.name.name, (item, export.name));
1507                    assert!(prev.is_none());
1508                    self.result
1509                        .initializers
1510                        .push(LocalInitializer::Export(item));
1511                }
1512            }
1513
1514            Payload::ComponentStartSection { start, range } => {
1515                self.validator.component_start_section(&start, &range)?;
1516                unimplemented!("component start section");
1517            }
1518
1519            // Aliases of instance exports (either core or component) will be
1520            // recorded as an initializer of the appropriate type with outer
1521            // aliases handled specially via upvars and type processing.
1522            Payload::ComponentAliasSection(s) => {
1523                self.validator.component_alias_section(&s)?;
1524                for alias in s {
1525                    let init = match alias? {
1526                        wasmparser::ComponentAlias::InstanceExport {
1527                            kind: _,
1528                            instance_index,
1529                            name,
1530                        } => {
1531                            let instance = ComponentInstanceIndex::from_u32(instance_index);
1532                            LocalInitializer::AliasComponentExport(instance, name)
1533                        }
1534                        wasmparser::ComponentAlias::Outer { kind, count, index } => {
1535                            self.alias_component_outer(kind, count, index);
1536                            continue;
1537                        }
1538                        wasmparser::ComponentAlias::CoreInstanceExport {
1539                            kind,
1540                            instance_index,
1541                            name,
1542                        } => {
1543                            let instance = ModuleInstanceIndex::from_u32(instance_index);
1544                            self.alias_module_instance_export(kind, instance, name)
1545                        }
1546                    };
1547                    self.result.initializers.push(init);
1548                }
1549            }
1550
1551            // All custom sections are ignored by Wasmtime at this time.
1552            //
1553            // FIXME(WebAssembly/component-model#14): probably want to specify
1554            // and parse a `name` section here.
1555            Payload::CustomSection { .. } => {}
1556
1557            // Anything else is either not reachable since we never enable the
1558            // feature in Wasmtime or we do enable it and it's a bug we don't
1559            // implement it, so let validation take care of most errors here and
1560            // if it gets past validation provide a helpful error message to
1561            // debug.
1562            other => {
1563                self.validator.payload(&other)?;
1564                panic!("unimplemented section {other:?}");
1565            }
1566        }
1567
1568        Ok(Action::KeepGoing)
1569    }
1570
1571    fn instantiate_module(
1572        &mut self,
1573        module: ModuleIndex,
1574        raw_args: &[wasmparser::InstantiationArg<'data>],
1575    ) -> LocalInitializer<'data> {
1576        let mut args = HashMap::with_capacity(raw_args.len());
1577        for arg in raw_args {
1578            match arg.kind {
1579                wasmparser::InstantiationArgKind::Instance => {
1580                    let idx = ModuleInstanceIndex::from_u32(arg.index);
1581                    args.insert(arg.name, idx);
1582                }
1583            }
1584        }
1585        LocalInitializer::ModuleInstantiate(module, args)
1586    }
1587
1588    /// Creates a synthetic module from the list of items currently in the
1589    /// module and their given names.
1590    fn instantiate_module_from_exports(
1591        &mut self,
1592        exports: &[wasmparser::Export<'data>],
1593    ) -> LocalInitializer<'data> {
1594        let mut map = HashMap::with_capacity(exports.len());
1595        for export in exports {
1596            let idx = match export.kind {
1597                wasmparser::ExternalKind::Func | wasmparser::ExternalKind::FuncExact => {
1598                    let index = FuncIndex::from_u32(export.index);
1599                    EntityIndex::Function(index)
1600                }
1601                wasmparser::ExternalKind::Table => {
1602                    let index = TableIndex::from_u32(export.index);
1603                    EntityIndex::Table(index)
1604                }
1605                wasmparser::ExternalKind::Memory => {
1606                    let index = MemoryIndex::from_u32(export.index);
1607                    EntityIndex::Memory(index)
1608                }
1609                wasmparser::ExternalKind::Global => {
1610                    let index = GlobalIndex::from_u32(export.index);
1611                    EntityIndex::Global(index)
1612                }
1613                wasmparser::ExternalKind::Tag => {
1614                    let index = TagIndex::from_u32(export.index);
1615                    EntityIndex::Tag(index)
1616                }
1617            };
1618            map.insert(export.name, idx);
1619        }
1620        LocalInitializer::ModuleSynthetic(map)
1621    }
1622
1623    fn instantiate_component(
1624        &mut self,
1625        component: ComponentIndex,
1626        raw_args: &[wasmparser::ComponentInstantiationArg<'data>],
1627        ty: ComponentInstanceTypeId,
1628    ) -> Result<LocalInitializer<'data>> {
1629        let mut args = HashMap::with_capacity(raw_args.len());
1630        for arg in raw_args {
1631            let idx = self.kind_to_item(arg.kind, arg.index)?;
1632            args.insert(arg.name, idx);
1633        }
1634
1635        Ok(LocalInitializer::ComponentInstantiate(component, args, ty))
1636    }
1637
1638    /// Creates a synthetic module from the list of items currently in the
1639    /// module and their given names.
1640    fn instantiate_component_from_exports(
1641        &mut self,
1642        exports: &[wasmparser::ComponentExport<'data>],
1643        ty: ComponentInstanceTypeId,
1644    ) -> Result<LocalInitializer<'data>> {
1645        let mut map = HashMap::with_capacity(exports.len());
1646        for export in exports {
1647            let idx = self.kind_to_item(export.kind, export.index)?;
1648            map.insert(export.name.name, idx);
1649        }
1650
1651        Ok(LocalInitializer::ComponentSynthetic(map, ty))
1652    }
1653
1654    fn kind_to_item(
1655        &mut self,
1656        kind: wasmparser::ComponentExternalKind,
1657        index: u32,
1658    ) -> Result<ComponentItem> {
1659        Ok(match kind {
1660            wasmparser::ComponentExternalKind::Func => {
1661                let index = ComponentFuncIndex::from_u32(index);
1662                ComponentItem::Func(index)
1663            }
1664            wasmparser::ComponentExternalKind::Module => {
1665                let index = ModuleIndex::from_u32(index);
1666                ComponentItem::Module(index)
1667            }
1668            wasmparser::ComponentExternalKind::Instance => {
1669                let index = ComponentInstanceIndex::from_u32(index);
1670                ComponentItem::ComponentInstance(index)
1671            }
1672            wasmparser::ComponentExternalKind::Component => {
1673                let index = ComponentIndex::from_u32(index);
1674                ComponentItem::Component(index)
1675            }
1676            wasmparser::ComponentExternalKind::Value => {
1677                unimplemented!("component values");
1678            }
1679            wasmparser::ComponentExternalKind::Type => {
1680                let types = self.validator.types(0).unwrap();
1681                let ty = types.component_any_type_at(index);
1682                ComponentItem::Type(ty)
1683            }
1684        })
1685    }
1686
1687    fn alias_module_instance_export(
1688        &mut self,
1689        kind: wasmparser::ExternalKind,
1690        instance: ModuleInstanceIndex,
1691        name: &'data str,
1692    ) -> LocalInitializer<'data> {
1693        match kind {
1694            wasmparser::ExternalKind::Func | wasmparser::ExternalKind::FuncExact => {
1695                LocalInitializer::AliasExportFunc(instance, name)
1696            }
1697            wasmparser::ExternalKind::Memory => LocalInitializer::AliasExportMemory(instance, name),
1698            wasmparser::ExternalKind::Table => LocalInitializer::AliasExportTable(instance, name),
1699            wasmparser::ExternalKind::Global => LocalInitializer::AliasExportGlobal(instance, name),
1700            wasmparser::ExternalKind::Tag => LocalInitializer::AliasExportTag(instance, name),
1701        }
1702    }
1703
1704    fn alias_component_outer(
1705        &mut self,
1706        kind: wasmparser::ComponentOuterAliasKind,
1707        count: u32,
1708        index: u32,
1709    ) {
1710        match kind {
1711            wasmparser::ComponentOuterAliasKind::CoreType
1712            | wasmparser::ComponentOuterAliasKind::Type => {}
1713
1714            // For more information about the implementation of outer aliases
1715            // see the documentation of `LexicalScope`. Otherwise though the
1716            // main idea here is that the data to close over starts as `Local`
1717            // and then transitions to `Upvar` as its inserted into the parents
1718            // in order from target we're aliasing back to the current
1719            // component.
1720            wasmparser::ComponentOuterAliasKind::CoreModule => {
1721                let index = ModuleIndex::from_u32(index);
1722                let mut module = ClosedOverModule::Local(index);
1723                let depth = self.lexical_scopes.len() - (count as usize);
1724                for frame in self.lexical_scopes[depth..].iter_mut() {
1725                    module = ClosedOverModule::Upvar(frame.closure_args.modules.push(module));
1726                }
1727
1728                // If the `module` is still `Local` then the `depth` was 0 and
1729                // it's an alias into our own space. Otherwise it's switched to
1730                // an upvar and will index into the upvar space. Either way
1731                // it's just plumbed directly into the initializer.
1732                self.result
1733                    .initializers
1734                    .push(LocalInitializer::AliasModule(module));
1735            }
1736            wasmparser::ComponentOuterAliasKind::Component => {
1737                let index = ComponentIndex::from_u32(index);
1738                let mut component = ClosedOverComponent::Local(index);
1739                let depth = self.lexical_scopes.len() - (count as usize);
1740                for frame in self.lexical_scopes[depth..].iter_mut() {
1741                    component =
1742                        ClosedOverComponent::Upvar(frame.closure_args.components.push(component));
1743                }
1744
1745                self.result
1746                    .initializers
1747                    .push(LocalInitializer::AliasComponent(component));
1748            }
1749        }
1750    }
1751
1752    fn canonical_options(
1753        &mut self,
1754        opts: &[wasmparser::CanonicalOption],
1755        core_func_index: u32,
1756    ) -> WasmResult<LocalCanonicalOptions> {
1757        let core_type = self.core_func_signature(core_func_index)?;
1758
1759        let mut string_encoding = StringEncoding::Utf8;
1760        let mut post_return = None;
1761        let mut async_ = false;
1762        let mut callback = None;
1763        let mut memory = None;
1764        let mut realloc = None;
1765        let mut gc = false;
1766
1767        for opt in opts {
1768            match opt {
1769                wasmparser::CanonicalOption::UTF8 => {
1770                    string_encoding = StringEncoding::Utf8;
1771                }
1772                wasmparser::CanonicalOption::UTF16 => {
1773                    string_encoding = StringEncoding::Utf16;
1774                }
1775                wasmparser::CanonicalOption::CompactUTF16 => {
1776                    string_encoding = StringEncoding::CompactUtf16;
1777                }
1778                wasmparser::CanonicalOption::Memory(idx) => {
1779                    let idx = MemoryIndex::from_u32(*idx);
1780                    memory = Some(idx);
1781                }
1782                wasmparser::CanonicalOption::Realloc(idx) => {
1783                    let idx = FuncIndex::from_u32(*idx);
1784                    realloc = Some(idx);
1785                }
1786                wasmparser::CanonicalOption::PostReturn(idx) => {
1787                    let idx = FuncIndex::from_u32(*idx);
1788                    post_return = Some(idx);
1789                }
1790                wasmparser::CanonicalOption::Async => async_ = true,
1791                wasmparser::CanonicalOption::Callback(idx) => {
1792                    let idx = FuncIndex::from_u32(*idx);
1793                    callback = Some(idx);
1794                }
1795                wasmparser::CanonicalOption::CoreType(idx) => {
1796                    if cfg!(debug_assertions) {
1797                        let types = self.validator.types(0).unwrap();
1798                        let core_ty_id = types.core_type_at_in_component(*idx).unwrap_sub();
1799                        let interned = self
1800                            .types
1801                            .module_types_builder()
1802                            .intern_type(types, core_ty_id)?;
1803                        debug_assert_eq!(interned, core_type);
1804                    }
1805                }
1806                wasmparser::CanonicalOption::Gc => {
1807                    gc = true;
1808                }
1809            }
1810        }
1811
1812        Ok(LocalCanonicalOptions {
1813            string_encoding,
1814            post_return,
1815            async_,
1816            callback,
1817            core_type,
1818            data_model: if gc {
1819                LocalDataModel::Gc {}
1820            } else {
1821                LocalDataModel::LinearMemory { memory, realloc }
1822            },
1823        })
1824    }
1825
1826    /// Get the interned type index for the `index`th core function.
1827    fn core_func_signature(&mut self, index: u32) -> WasmResult<ModuleInternedTypeIndex> {
1828        let types = self.validator.types(0).unwrap();
1829        let id = types.core_function_at(index);
1830        self.types.module_types_builder().intern_type(types, id)
1831    }
1832
1833    fn is_unsafe_intrinsics_import(&self, import: &str) -> bool {
1834        self.lexical_scopes.is_empty()
1835            && self
1836                .unsafe_intrinsics_import
1837                .is_some_and(|name| import == name)
1838    }
1839
1840    fn check_unsafe_intrinsics_import(&self, import: &str, ty: ComponentEntityType) -> Result<()> {
1841        let types = &self.validator.types(0).unwrap();
1842
1843        let ComponentEntityType::Instance(instance_ty) = ty else {
1844            bail!("bad unsafe intrinsics import: import `{import}` must be an instance import")
1845        };
1846        let instance_ty = &types[instance_ty];
1847
1848        ensure!(
1849            instance_ty.defined_resources.is_empty(),
1850            "bad unsafe intrinsics import: import `{import}` cannot define any resources"
1851        );
1852
1853        for (name, ty) in &instance_ty.exports {
1854            let ComponentEntityType::Func(func_ty) = ty.ty else {
1855                bail!(
1856                    "bad unsafe intrinsics import: imported instance `{import}` must \
1857                     only export functions"
1858                )
1859            };
1860            let func_ty = &types[func_ty];
1861
1862            fn ty_eq(a: &InterfaceType, b: &wasmparser::component_types::ComponentValType) -> bool {
1863                use wasmparser::{PrimitiveValType as P, component_types::ComponentValType as C};
1864                match (a, b) {
1865                    (InterfaceType::U8, C::Primitive(P::U8)) => true,
1866                    (InterfaceType::U8, _) => false,
1867
1868                    (InterfaceType::U16, C::Primitive(P::U16)) => true,
1869                    (InterfaceType::U16, _) => false,
1870
1871                    (InterfaceType::U32, C::Primitive(P::U32)) => true,
1872                    (InterfaceType::U32, _) => false,
1873
1874                    (InterfaceType::U64, C::Primitive(P::U64)) => true,
1875                    (InterfaceType::U64, _) => false,
1876
1877                    (ty, _) => unreachable!("no unsafe intrinsics use {ty:?}"),
1878                }
1879            }
1880
1881            fn check_types<'a>(
1882                expected: impl ExactSizeIterator<Item = &'a InterfaceType>,
1883                actual: impl ExactSizeIterator<Item = &'a wasmparser::component_types::ComponentValType>,
1884                kind: &str,
1885                import: &str,
1886                name: &str,
1887            ) -> Result<()> {
1888                let expected_len = expected.len();
1889                let actual_len = actual.len();
1890                ensure!(
1891                    expected_len == actual_len,
1892                    "bad unsafe intrinsics import at `{import}`: function `{name}` must have \
1893                     {expected_len} {kind}, found {actual_len}"
1894                );
1895
1896                for (i, (actual_ty, expected_ty)) in actual.zip(expected).enumerate() {
1897                    ensure!(
1898                        ty_eq(expected_ty, actual_ty),
1899                        "bad unsafe intrinsics import at `{import}`: {kind}[{i}] for function \
1900                         `{name}` must be `{expected_ty:?}`, found `{actual_ty:?}`"
1901                    );
1902                }
1903                Ok(())
1904            }
1905
1906            let intrinsic = UnsafeIntrinsic::from_str(name)
1907                .with_context(|| format!("bad unsafe intrinsics import at `{import}`"))?;
1908
1909            check_types(
1910                intrinsic.component_params().iter(),
1911                func_ty.params.iter().map(|(_name, ty)| ty),
1912                "parameters",
1913                &import,
1914                &name,
1915            )?;
1916            check_types(
1917                intrinsic.component_results().iter(),
1918                func_ty.result.iter(),
1919                "results",
1920                &import,
1921                &name,
1922            )?;
1923        }
1924
1925        Ok(())
1926    }
1927}
1928
1929impl Translation<'_> {
1930    fn types_ref(&self) -> wasmparser::types::TypesRef<'_> {
1931        self.types.as_ref().unwrap().as_ref()
1932    }
1933}
1934
1935/// A small helper module which wraps a `ComponentTypesBuilder` and attempts
1936/// to disallow access to mutable access to the builder before the inlining
1937/// pass.
1938///
1939/// Type information in this translation pass must be preserved at the
1940/// wasmparser layer of abstraction rather than being lowered into Wasmtime's
1941/// own type system. Only during inlining are types fully assigned because
1942/// that's when resource types become available as it's known which instance
1943/// defines which resource, or more concretely the same component instantiated
1944/// twice will produce two unique resource types unlike one as seen by
1945/// wasmparser within the component.
1946mod pre_inlining {
1947    use super::*;
1948
1949    pub struct PreInliningComponentTypes<'a> {
1950        types: &'a mut ComponentTypesBuilder,
1951    }
1952
1953    impl<'a> PreInliningComponentTypes<'a> {
1954        pub fn new(types: &'a mut ComponentTypesBuilder) -> Self {
1955            Self { types }
1956        }
1957
1958        pub fn module_types_builder(&mut self) -> &mut ModuleTypesBuilder {
1959            self.types.module_types_builder_mut()
1960        }
1961
1962        pub fn types(&self) -> &ComponentTypesBuilder {
1963            self.types
1964        }
1965
1966        // NB: this should in theory only be used for the `inline` phase of
1967        // translation.
1968        pub fn types_mut_for_inlining(&mut self) -> &mut ComponentTypesBuilder {
1969            self.types
1970        }
1971    }
1972
1973    impl TypeConvert for PreInliningComponentTypes<'_> {
1974        fn lookup_heap_type(&self, index: wasmparser::UnpackedIndex) -> WasmHeapType {
1975            self.types.lookup_heap_type(index)
1976        }
1977
1978        fn lookup_type_index(&self, index: wasmparser::UnpackedIndex) -> EngineOrModuleTypeIndex {
1979            self.types.lookup_type_index(index)
1980        }
1981    }
1982}
1983use pre_inlining::PreInliningComponentTypes;
1984
1985/// A map from each runtime instance to the static module it is an instance of,
1986/// along with the definition that each of its arguments resolves to, when we
1987/// statically know them.
1988struct StaticInstances {
1989    /// The position of each import of each static module.
1990    import_positions: PrimaryMap<StaticModuleIndex, ImportPositions>,
1991
1992    /// Each instance's module and what each of its arguments resolves to, by
1993    /// import position, as computed by `resolve_core_export`.
1994    ///
1995    /// `None` for instances of modules that are not part of this component,
1996    /// and whose shape we therefore cannot see into.
1997    instances: PrimaryMap<
1998        RuntimeInstanceIndex,
1999        Option<(
2000            StaticModuleIndex,
2001            Vec<Option<(StaticModuleIndex, EntityIndex)>>,
2002        )>,
2003    >,
2004}
2005
2006impl StaticInstances {
2007    fn new(static_modules: &PrimaryMap<StaticModuleIndex, ModuleTranslation<'_>>) -> Self {
2008        StaticInstances {
2009            import_positions: static_modules
2010                .values()
2011                .map(|translation| translation.module.import_positions())
2012                .collect(),
2013            instances: PrimaryMap::new(),
2014        }
2015    }
2016
2017    /// Push the next runtime instance.
2018    ///
2019    /// It must be an instance of the given static module with the given
2020    /// arguments, or `None` for an instance of a module that is not part of
2021    /// this component.
2022    fn push(&mut self, instance: Option<(StaticModuleIndex, &[CoreDef])>) {
2023        let instance = instance.map(|(module, args)| {
2024            let next = self.instances.next_key();
2025            let args = args
2026                .iter()
2027                .map(|arg| match arg {
2028                    CoreDef::Export(export) => {
2029                        // An instantiation's arguments are always exports of
2030                        // instances created before the instance being
2031                        // instantiated.
2032                        assert!(export.instance < next);
2033                        resolve_core_export(self, export)
2034                    }
2035
2036                    CoreDef::InstanceFlags(_)
2037                    | CoreDef::Trampoline(_)
2038                    | CoreDef::UnsafeIntrinsic(_) => None,
2039                })
2040                .collect();
2041            (module, args)
2042        });
2043        self.instances.push(instance);
2044    }
2045}
2046
2047/// Every entity whose identity is not statically known to everything that can
2048/// access it.
2049#[derive(Default)]
2050struct Ambiguous {
2051    /// Globals, memories, and tables defined by a static module in this
2052    /// component.
2053    entities: HashSet<(StaticModuleIndex, EntityIndex)>,
2054
2055    /// Component-model flags living in the `VMComponentContext`. Only ever
2056    /// contains the non-`KnownGlobal::Defined` variants.
2057    flags: HashSet<KnownGlobal>,
2058}
2059
2060/// Get the component-model flag that a `CoreDef` names, if it names one.
2061fn component_flags(def: &CoreDef) -> Option<KnownGlobal> {
2062    match def {
2063        CoreDef::InstanceFlags(instance) => Some(KnownGlobal::ComponentInstanceFlags(*instance)),
2064        CoreDef::Export(_) | CoreDef::Trampoline(_) | CoreDef::UnsafeIntrinsic(_) => None,
2065    }
2066}
2067
2068/// Resolve a `CoreExport` to the static module that *defines* it and the entity
2069/// index it refers to within that module, when we can see through it statically.
2070///
2071/// A module may import an entity and then re-export it, in which case the
2072/// export names an index in the re-exporting module's *imported* index space.
2073/// We follow those chains all the way back to the module that actually defines
2074/// the entity, so that the returned pair is a canonical identity for it: every
2075/// reference to the same entity resolves to the same `(module, entity)` pair, no
2076/// matter how many modules it was laundered through along the way. That is
2077/// load-bearing for alias regions, where naming the same bytes with two
2078/// different keys is a miscompile.
2079///
2080/// Therefore a returned `Some((module, entity))` always satisfies
2081/// `!static_modules[module].module.is_imported(entity)`.
2082fn resolve_core_export(
2083    instances: &StaticInstances,
2084    export: &CoreExport<EntityIndex>,
2085) -> Option<(StaticModuleIndex, EntityIndex)> {
2086    let (module, args) = instances.instances[export.instance].as_ref()?;
2087
2088    let ExportItem::Index(index) = export.item else {
2089        // Names are only used for instances of modules whose shape we don't
2090        // statically know, which we already filtered out.
2091        unreachable!()
2092    };
2093
2094    match instances.import_positions[*module].get(index) {
2095        // The common case: this instance's module defines the entity itself,
2096        // so we've bottomed out at its canonical identity.
2097        None => Some((*module, index)),
2098
2099        // Otherwise this is a re-export of one of the module's imports, which
2100        // resolves to the same thing as whichever argument satisfied that
2101        // import. `StaticInstances::push` already resolved that argument all
2102        // the way back to its definition.
2103        Some(position) => args[position],
2104    }
2105}
2106
2107/// Same as `resolve_core_export`, but for a `CoreDef` that must additionally be
2108/// unambiguous.
2109fn unambiguous_entity(
2110    instances: &StaticInstances,
2111    ambiguous: &HashSet<(StaticModuleIndex, EntityIndex)>,
2112    def: &CoreDef,
2113) -> Option<(StaticModuleIndex, EntityIndex)> {
2114    let CoreDef::Export(export) = def else {
2115        return None;
2116    };
2117    let entity = resolve_core_export(instances, export)?;
2118    if ambiguous.contains(&entity) {
2119        return None;
2120    }
2121    Some(entity)
2122}
2123
2124/// Find every core wasm entity in this component whose identity is *not*
2125/// statically known to every module that may import it.
2126///
2127/// An entity is unambiguous when every argument it flows into belongs to a
2128/// module that we only ever instantiate with that same entity:
2129///
2130/// * An argument to a module that we may instantiate differently elsewhere is
2131///   ambiguous because that module cannot statically know which one of these
2132///   entities it was given at runtime.
2133///
2134/// * An argument to an imported module is ambiguous because that module is
2135///   compiled separately from this component, and it may re-export the entity
2136///   back to us under a name we cannot see through, which we may then hand to a
2137///   module whose imports we do otherwise know.
2138///
2139/// Note that ambiguity is never partial: if a module importing an entity has to
2140/// conservatively tag its accesses with that entity's public alias region, then
2141/// the module defining the entity must do the same, or else inlining one of
2142/// them into the other would access the same bytes through two different alias
2143/// regions, which is invalid.
2144///
2145/// Entities in the returned set are identified by the module that *defines*
2146/// them, as resolved by `resolve_core_export`. That is what makes the previous
2147/// paragraph work through re-exports: marking a module's re-export of an import
2148/// as ambiguous poisons the definition it ultimately refers to, and therefore
2149/// every other module that can reach that definition, and not just the
2150/// re-exporter.
2151fn ambiguous_entities(
2152    translation: &ComponentTranslation,
2153    instantiations: &SecondaryMap<StaticModuleIndex, dfg::AbstractInstantiations<'_>>,
2154    instances: &StaticInstances,
2155) -> Ambiguous {
2156    let mut ambiguous = Ambiguous::default();
2157
2158    let mut mark = |def: &CoreDef| match def {
2159        CoreDef::Export(export) => {
2160            if let Some(entity) = resolve_core_export(instances, export) {
2161                ambiguous.entities.insert(entity);
2162            }
2163        }
2164
2165        CoreDef::InstanceFlags(_) => {
2166            ambiguous.flags.insert(component_flags(def).unwrap());
2167        }
2168
2169        // Neither of these is an entity that gets an alias region keyed by a
2170        // defining module and index.
2171        CoreDef::Trampoline(_) | CoreDef::UnsafeIntrinsic(_) => {}
2172    };
2173
2174    for init in &translation.component.initializers {
2175        match init {
2176            GlobalInitializer::InstantiateModule(instantiation, _) => match instantiation {
2177                InstantiateModule::Static(module, args) => {
2178                    // Arguments to modules that we only instantiate one way are
2179                    // exactly the references that keep an entity unambiguous, so
2180                    // they are the one case we do not mark here. Everything else
2181                    // gets whichever of a number of different entities it was
2182                    // handed at runtime, and so has to be conservative.
2183                    if !matches!(instantiations[*module], dfg::AbstractInstantiations::One(_)) {
2184                        for arg in args.iter() {
2185                            mark(arg);
2186                        }
2187                    }
2188                }
2189
2190                // We cannot see through an imported module's exports, so an
2191                // entity we pass into one and that comes back out to a module
2192                // whose imports we do know would be accessed via two different
2193                // alias regions.
2194                InstantiateModule::Import(_, args) => {
2195                    for arg in args.values().flat_map(|args| args.values()) {
2196                        mark(arg);
2197                    }
2198                }
2199            },
2200
2201            // The remaining initializers do not involve the global/table/memory
2202            // alias regions.
2203            GlobalInitializer::ExtractMemory(_)
2204            | GlobalInitializer::ExtractTable(_)
2205            | GlobalInitializer::ExtractRealloc(_)
2206            | GlobalInitializer::ExtractCallback(_)
2207            | GlobalInitializer::ExtractPostReturn(_)
2208            | GlobalInitializer::Resource(_)
2209            | GlobalInitializer::LowerImport { .. } => {}
2210        }
2211    }
2212
2213    ambiguous
2214}