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