wit_component/
encoding.rs

1//! Support for encoding a core wasm module into a component.
2//!
3//! This module, at a high level, is tasked with transforming a core wasm
4//! module into a component. This will process the imports/exports of the core
5//! wasm module and translate between the `wit-parser` AST and the component
6//! model binary format, producing a final component which will import
7//! `*.wit` defined interfaces and export `*.wit` defined interfaces as well
8//! with everything wired up internally according to the canonical ABI and such.
9//!
10//! This doc block here is not currently 100% complete and doesn't cover the
11//! full functionality of this module.
12//!
13//! # Adapter Modules
14//!
15//! One feature of this encoding process which is non-obvious is the support for
16//! "adapter modules". The general idea here is that historical host API
17//! definitions have been around for quite some time, such as
18//! `wasi_snapshot_preview1`, but these host API definitions are not compatible
19//! with the canonical ABI or component model exactly. These APIs, however, can
20//! in most situations be roughly adapted to component-model equivalents. This
21//! is where adapter modules come into play, they're converting from some
22//! arbitrary API/ABI into a component-model using API.
23//!
24//! An adapter module is a separately compiled `*.wasm` blob which will export
25//! functions matching the desired ABI (e.g. exporting functions matching the
26//! `wasi_snapshot_preview1` ABI). The `*.wasm` blob will then import functions
27//! in the canonical ABI and internally adapt the exported functions to the
28//! imported functions. The encoding support in this module is what wires
29//! everything up and makes sure that everything is imported and exported to the
30//! right place. Adapter modules currently always use "indirect lowerings"
31//! meaning that a shim module is created and provided as the imports to the
32//! main core wasm module, and the shim module is "filled in" at a later time
33//! during the instantiation process.
34//!
35//! Adapter modules are not intended to be general purpose and are currently
36//! very restrictive, namely:
37//!
38//! * They must import a linear memory and not define their own linear memory
39//!   otherwise. In other words they import memory and cannot use multi-memory.
40//! * They cannot define any `elem` or `data` segments since otherwise there's
41//!   no knowledge ahead-of-time of where their data or element segments could
42//!   go. This means things like no panics, no indirect calls, etc.
43//! * If the adapter uses a shadow stack, the global that points to it must be a
44//!   mutable `i32` named `__stack_pointer`. This stack is automatically
45//!   allocated with an injected `allocate_stack` function that will either use
46//!   the main module's `cabi_realloc` export (if present) or `memory.grow`. It
47//!   allocates only 64KB of stack space, and there is no protection if that
48//!   overflows.
49//! * If the adapter has a global, mutable `i32` named `allocation_state`, it
50//!   will be used to keep track of stack allocation status and avoid infinite
51//!   recursion if the main module's `cabi_realloc` function calls back into the
52//!   adapter.  `allocate_stack` will check this global on entry; if it is zero,
53//!   it will set it to one, then allocate the stack, and finally set it to two.
54//!   If it is non-zero, `allocate_stack` will do nothing and return immediately
55//!   (because either the stack has already been allocated or is in the process
56//!   of being allocated).  If the adapter does not have an `allocation_state`,
57//!   `allocate_stack` will use `memory.grow` to allocate the stack; it will
58//!   _not_ use the main module's `cabi_realloc` even if it's available.
59//! * If the adapter imports a `cabi_realloc` function, and the main module
60//!   exports one, they'll be linked together via an alias. If the adapter
61//!   imports such a function but the main module does _not_ export one, we'll
62//!   synthesize one based on `memory.grow` (which will trap for any size other
63//!   than 64KB). Note that the main module's `cabi_realloc` function may call
64//!   back into the adapter before the shadow stack has been allocated. In this
65//!   case (when `allocation_state` is zero or one), the adapter should return
66//!   whatever dummy value(s) it can immediately without touching the stack.
67//!
68//! This means that adapter modules are not meant to be written by everyone.
69//! It's assumed that these will be relatively few and far between yet still a
70//! crucial part of the transition process from to the component model since
71//! otherwise there's no way to run a `wasi_snapshot_preview1` module within the
72//! component model.
73
74use crate::metadata::{self, Bindgen, ModuleMetadata};
75use crate::validation::{Export, ExportMap, Import, ImportInstance, ImportMap, PayloadInfo};
76use crate::StringEncoding;
77use anyhow::{anyhow, bail, Context, Result};
78use indexmap::{IndexMap, IndexSet};
79use std::borrow::Cow;
80use std::collections::HashMap;
81use std::hash::Hash;
82use std::mem;
83use wasm_encoder::*;
84use wasmparser::{Validator, WasmFeatures};
85use wit_parser::{
86    abi::{AbiVariant, WasmSignature, WasmType},
87    Function, FunctionKind, InterfaceId, LiveTypes, Resolve, Stability, Type, TypeDefKind, TypeId,
88    TypeOwner, WorldItem, WorldKey,
89};
90
91const INDIRECT_TABLE_NAME: &str = "$imports";
92
93mod wit;
94pub use wit::{encode, encode_world};
95
96mod types;
97use types::{InstanceTypeEncoder, RootTypeEncoder, ValtypeEncoder};
98mod world;
99use world::{ComponentWorld, ImportedInterface, Lowering};
100
101fn to_val_type(ty: &WasmType) -> ValType {
102    match ty {
103        WasmType::I32 => ValType::I32,
104        WasmType::I64 => ValType::I64,
105        WasmType::F32 => ValType::F32,
106        WasmType::F64 => ValType::F64,
107        WasmType::Pointer => ValType::I32,
108        WasmType::PointerOrI64 => ValType::I64,
109        WasmType::Length => ValType::I32,
110    }
111}
112
113bitflags::bitflags! {
114    /// Options in the `canon lower` or `canon lift` required for a particular
115    /// function.
116    #[derive(Copy, Clone, Debug)]
117    pub struct RequiredOptions: u8 {
118        /// A memory must be specified, typically the "main module"'s memory
119        /// export.
120        const MEMORY = 1 << 0;
121        /// A `realloc` function must be specified, typically named
122        /// `cabi_realloc`.
123        const REALLOC = 1 << 1;
124        /// A string encoding must be specified, which is always utf-8 for now
125        /// today.
126        const STRING_ENCODING = 1 << 2;
127        const ASYNC = 1 << 3;
128    }
129}
130
131impl RequiredOptions {
132    fn for_import(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions {
133        let sig = resolve.wasm_signature(abi, func);
134        let mut ret = RequiredOptions::empty();
135        // Lift the params and lower the results for imports
136        ret.add_lift(TypeContents::for_types(
137            resolve,
138            func.params.iter().map(|(_, t)| t),
139        ));
140        ret.add_lower(TypeContents::for_types(resolve, &func.result));
141
142        // If anything is indirect then `memory` will be required to read the
143        // indirect values.
144        if sig.retptr || sig.indirect_params {
145            ret |= RequiredOptions::MEMORY;
146        }
147        if abi == AbiVariant::GuestImportAsync {
148            ret |= RequiredOptions::ASYNC;
149        }
150        ret
151    }
152
153    fn for_export(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions {
154        let sig = resolve.wasm_signature(abi, func);
155        let mut ret = RequiredOptions::empty();
156        // Lower the params and lift the results for exports
157        ret.add_lower(TypeContents::for_types(
158            resolve,
159            func.params.iter().map(|(_, t)| t),
160        ));
161        ret.add_lift(TypeContents::for_types(resolve, &func.result));
162
163        // If anything is indirect then `memory` will be required to read the
164        // indirect values, but if the arguments are indirect then `realloc` is
165        // additionally required to allocate space for the parameters.
166        if sig.retptr || sig.indirect_params {
167            ret |= RequiredOptions::MEMORY;
168            if sig.indirect_params {
169                ret |= RequiredOptions::REALLOC;
170            }
171        }
172        if let AbiVariant::GuestExportAsync | AbiVariant::GuestExportAsyncStackful = abi {
173            ret |= RequiredOptions::ASYNC;
174        }
175        ret
176    }
177
178    fn add_lower(&mut self, types: TypeContents) {
179        // If lists/strings are lowered into wasm then memory is required as
180        // usual but `realloc` is also required to allow the external caller to
181        // allocate space in the destination for the list/string.
182        if types.contains(TypeContents::LIST) {
183            *self |= RequiredOptions::MEMORY | RequiredOptions::REALLOC;
184        }
185        if types.contains(TypeContents::STRING) {
186            *self |= RequiredOptions::MEMORY
187                | RequiredOptions::STRING_ENCODING
188                | RequiredOptions::REALLOC;
189        }
190    }
191
192    fn add_lift(&mut self, types: TypeContents) {
193        // Unlike for `lower` when lifting a string/list all that's needed is
194        // memory, since the string/list already resides in memory `realloc`
195        // isn't needed.
196        if types.contains(TypeContents::LIST) {
197            *self |= RequiredOptions::MEMORY;
198        }
199        if types.contains(TypeContents::STRING) {
200            *self |= RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING;
201        }
202    }
203
204    fn into_iter(
205        self,
206        encoding: StringEncoding,
207        memory_index: Option<u32>,
208        realloc_index: Option<u32>,
209    ) -> Result<impl ExactSizeIterator<Item = CanonicalOption>> {
210        #[derive(Default)]
211        struct Iter {
212            options: [Option<CanonicalOption>; 5],
213            current: usize,
214            count: usize,
215        }
216
217        impl Iter {
218            fn push(&mut self, option: CanonicalOption) {
219                assert!(self.count < self.options.len());
220                self.options[self.count] = Some(option);
221                self.count += 1;
222            }
223        }
224
225        impl Iterator for Iter {
226            type Item = CanonicalOption;
227
228            fn next(&mut self) -> Option<Self::Item> {
229                if self.current == self.count {
230                    return None;
231                }
232                let option = self.options[self.current];
233                self.current += 1;
234                option
235            }
236
237            fn size_hint(&self) -> (usize, Option<usize>) {
238                (self.count - self.current, Some(self.count - self.current))
239            }
240        }
241
242        impl ExactSizeIterator for Iter {}
243
244        let mut iter = Iter::default();
245
246        if self.contains(RequiredOptions::MEMORY) {
247            iter.push(CanonicalOption::Memory(memory_index.ok_or_else(|| {
248                anyhow!("module does not export a memory named `memory`")
249            })?));
250        }
251
252        if self.contains(RequiredOptions::REALLOC) {
253            iter.push(CanonicalOption::Realloc(realloc_index.ok_or_else(
254                || anyhow!("module does not export a function named `cabi_realloc`"),
255            )?));
256        }
257
258        if self.contains(RequiredOptions::STRING_ENCODING) {
259            iter.push(encoding.into());
260        }
261
262        if self.contains(RequiredOptions::ASYNC) {
263            iter.push(CanonicalOption::Async);
264        }
265
266        Ok(iter)
267    }
268}
269
270bitflags::bitflags! {
271    /// Flags about what kinds of types are present within the recursive
272    /// structure of a type.
273    struct TypeContents: u8 {
274        const STRING = 1 << 0;
275        const LIST = 1 << 1;
276    }
277}
278
279impl TypeContents {
280    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
281        let mut cur = TypeContents::empty();
282        for ty in types {
283            cur |= Self::for_type(resolve, ty);
284        }
285        cur
286    }
287
288    fn for_optional_types<'a>(
289        resolve: &Resolve,
290        types: impl Iterator<Item = Option<&'a Type>>,
291    ) -> Self {
292        Self::for_types(resolve, types.flatten())
293    }
294
295    fn for_optional_type(resolve: &Resolve, ty: Option<&Type>) -> Self {
296        match ty {
297            Some(ty) => Self::for_type(resolve, ty),
298            None => Self::empty(),
299        }
300    }
301
302    fn for_type(resolve: &Resolve, ty: &Type) -> Self {
303        match ty {
304            Type::Id(id) => match &resolve.types[*id].kind {
305                TypeDefKind::Handle(h) => match h {
306                    wit_parser::Handle::Own(_) => Self::empty(),
307                    wit_parser::Handle::Borrow(_) => Self::empty(),
308                },
309                TypeDefKind::Resource => Self::empty(),
310                TypeDefKind::Record(r) => Self::for_types(resolve, r.fields.iter().map(|f| &f.ty)),
311                TypeDefKind::Tuple(t) => Self::for_types(resolve, t.types.iter()),
312                TypeDefKind::Flags(_) => Self::empty(),
313                TypeDefKind::Option(t) => Self::for_type(resolve, t),
314                TypeDefKind::Result(r) => {
315                    Self::for_optional_type(resolve, r.ok.as_ref())
316                        | Self::for_optional_type(resolve, r.err.as_ref())
317                }
318                TypeDefKind::Variant(v) => {
319                    Self::for_optional_types(resolve, v.cases.iter().map(|c| c.ty.as_ref()))
320                }
321                TypeDefKind::Enum(_) => Self::empty(),
322                TypeDefKind::List(t) => Self::for_type(resolve, t) | Self::LIST,
323                TypeDefKind::Type(t) => Self::for_type(resolve, t),
324                TypeDefKind::Future(_) => Self::empty(),
325                TypeDefKind::Stream(_) => Self::empty(),
326                TypeDefKind::Unknown => unreachable!(),
327            },
328            Type::String => Self::STRING,
329            _ => Self::empty(),
330        }
331    }
332}
333
334/// State relating to encoding a component.
335pub struct EncodingState<'a> {
336    /// The component being encoded.
337    component: ComponentBuilder,
338    /// The index into the core module index space for the inner core module.
339    ///
340    /// If `None`, the core module has not been encoded.
341    module_index: Option<u32>,
342    /// The index into the core instance index space for the inner core module.
343    ///
344    /// If `None`, the core module has not been instantiated.
345    instance_index: Option<u32>,
346    /// The index in the core memory index space for the exported memory.
347    ///
348    /// If `None`, then the memory has not yet been aliased.
349    memory_index: Option<u32>,
350    /// The index of the shim instance used for lowering imports into the core instance.
351    ///
352    /// If `None`, then the shim instance how not yet been encoded.
353    shim_instance_index: Option<u32>,
354    /// The index of the fixups module to instantiate to fill in the lowered imports.
355    ///
356    /// If `None`, then a fixup module has not yet been encoded.
357    fixups_module_index: Option<u32>,
358
359    /// A map of named adapter modules and the index that the module was defined
360    /// at.
361    adapter_modules: IndexMap<&'a str, u32>,
362    /// A map of adapter module instances and the index of their instance.
363    adapter_instances: IndexMap<&'a str, u32>,
364
365    /// Imported instances and what index they were imported as.
366    imported_instances: IndexMap<InterfaceId, u32>,
367    imported_funcs: IndexMap<String, u32>,
368    exported_instances: IndexMap<InterfaceId, u32>,
369
370    /// Maps used when translating types to the component model binary format.
371    /// Note that imports and exports are stored in separate maps since they
372    /// need fresh hierarchies of types in case the same interface is both
373    /// imported and exported.
374    import_type_map: HashMap<TypeId, u32>,
375    import_func_type_map: HashMap<types::FunctionKey<'a>, u32>,
376    export_type_map: HashMap<TypeId, u32>,
377    export_func_type_map: HashMap<types::FunctionKey<'a>, u32>,
378
379    /// Cache of items that have been aliased from core instances.
380    ///
381    /// This is a helper to reduce the number of aliases created by ensuring
382    /// that repeated requests for the same item return the same index of an
383    /// original `core alias` item.
384    aliased_core_items: HashMap<(u32, String), u32>,
385
386    /// Metadata about the world inferred from the input to `ComponentEncoder`.
387    info: &'a ComponentWorld<'a>,
388}
389
390impl<'a> EncodingState<'a> {
391    fn encode_core_modules(&mut self) {
392        assert!(self.module_index.is_none());
393        let idx = self.component.core_module_raw(&self.info.encoder.module);
394        self.module_index = Some(idx);
395
396        for (name, adapter) in self.info.adapters.iter() {
397            let mut add_meta = wasm_metadata::AddMetadata::default();
398            add_meta.name = Some(if adapter.library_info.is_some() {
399                name.to_string()
400            } else {
401                format!("wit-component:adapter:{name}")
402            });
403            let wasm = add_meta
404                .to_wasm(&adapter.wasm)
405                .expect("core wasm can get name added");
406            let idx = self.component.core_module_raw(&wasm);
407            let prev = self.adapter_modules.insert(name, idx);
408            assert!(prev.is_none());
409        }
410    }
411
412    fn root_import_type_encoder(
413        &mut self,
414        interface: Option<InterfaceId>,
415    ) -> RootTypeEncoder<'_, 'a> {
416        RootTypeEncoder {
417            state: self,
418            interface,
419            import_types: true,
420        }
421    }
422
423    fn root_export_type_encoder(
424        &mut self,
425        interface: Option<InterfaceId>,
426    ) -> RootTypeEncoder<'_, 'a> {
427        RootTypeEncoder {
428            state: self,
429            interface,
430            import_types: false,
431        }
432    }
433
434    fn instance_type_encoder(&mut self, interface: InterfaceId) -> InstanceTypeEncoder<'_, 'a> {
435        InstanceTypeEncoder {
436            state: self,
437            interface,
438            type_map: Default::default(),
439            func_type_map: Default::default(),
440            ty: Default::default(),
441        }
442    }
443
444    fn encode_imports(&mut self, name_map: &HashMap<String, String>) -> Result<()> {
445        let mut has_funcs = false;
446        for (name, info) in self.info.import_map.iter() {
447            match name {
448                Some(name) => {
449                    self.encode_interface_import(name_map.get(name).unwrap_or(name), info)?
450                }
451                None => has_funcs = true,
452            }
453        }
454
455        let resolve = &self.info.encoder.metadata.resolve;
456        let world = &resolve.worlds[self.info.encoder.metadata.world];
457
458        // FIXME: ideally this would use the liveness analysis from
459        // world-building to only encode live types, not all type in a world.
460        for (_name, item) in world.imports.iter() {
461            if let WorldItem::Type(ty) = item {
462                self.root_import_type_encoder(None)
463                    .encode_valtype(resolve, &Type::Id(*ty))?;
464            }
465        }
466
467        if has_funcs {
468            let info = &self.info.import_map[&None];
469            self.encode_root_import_funcs(info)?;
470        }
471        Ok(())
472    }
473
474    fn encode_interface_import(&mut self, name: &str, info: &ImportedInterface) -> Result<()> {
475        let resolve = &self.info.encoder.metadata.resolve;
476        let interface_id = info.interface.as_ref().unwrap();
477        let interface_id = *interface_id;
478        let interface = &resolve.interfaces[interface_id];
479        log::trace!("encoding imports for `{name}` as {:?}", interface_id);
480        let mut encoder = self.instance_type_encoder(interface_id);
481
482        // First encode all type information
483        if let Some(live) = encoder.state.info.live_type_imports.get(&interface_id) {
484            for ty in live {
485                log::trace!(
486                    "encoding extra type {ty:?} name={:?}",
487                    resolve.types[*ty].name
488                );
489                encoder.encode_valtype(resolve, &Type::Id(*ty))?;
490            }
491        }
492
493        // Next encode all required functions from this imported interface
494        // into the instance type.
495        for (_, func) in interface.functions.iter() {
496            if !(info
497                .lowerings
498                .contains_key(&(func.name.clone(), AbiVariant::GuestImport))
499                || info
500                    .lowerings
501                    .contains_key(&(func.name.clone(), AbiVariant::GuestImportAsync)))
502            {
503                continue;
504            }
505            log::trace!("encoding function type for `{}`", func.name);
506            let idx = encoder.encode_func_type(resolve, func)?;
507
508            encoder.ty.export(&func.name, ComponentTypeRef::Func(idx));
509        }
510
511        let ty = encoder.ty;
512        // Don't encode empty instance types since they're not
513        // meaningful to the runtime of the component anyway.
514        if ty.is_empty() {
515            return Ok(());
516        }
517        let instance_type_idx = self.component.type_instance(&ty);
518        let instance_idx = self
519            .component
520            .import(name, ComponentTypeRef::Instance(instance_type_idx));
521        let prev = self.imported_instances.insert(interface_id, instance_idx);
522        assert!(prev.is_none());
523        Ok(())
524    }
525
526    fn encode_root_import_funcs(&mut self, info: &ImportedInterface) -> Result<()> {
527        let resolve = &self.info.encoder.metadata.resolve;
528        let world = self.info.encoder.metadata.world;
529        for (name, item) in resolve.worlds[world].imports.iter() {
530            let func = match item {
531                WorldItem::Function(f) => f,
532                WorldItem::Interface { .. } | WorldItem::Type(_) => continue,
533            };
534            let name = resolve.name_world_key(name);
535            if !(info
536                .lowerings
537                .contains_key(&(name.clone(), AbiVariant::GuestImport))
538                || info
539                    .lowerings
540                    .contains_key(&(name.clone(), AbiVariant::GuestImportAsync)))
541            {
542                continue;
543            }
544            log::trace!("encoding function type for `{}`", func.name);
545            let idx = self
546                .root_import_type_encoder(None)
547                .encode_func_type(resolve, func)?;
548            let func_idx = self.component.import(&name, ComponentTypeRef::Func(idx));
549            let prev = self.imported_funcs.insert(name, func_idx);
550            assert!(prev.is_none());
551        }
552        Ok(())
553    }
554
555    fn alias_imported_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
556        let ty = &self.info.encoder.metadata.resolve.types[id];
557        let name = ty.name.as_ref().expect("type must have a name");
558        let instance = self.imported_instances[&interface];
559        self.component
560            .alias_export(instance, name, ComponentExportKind::Type)
561    }
562
563    fn alias_exported_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
564        let ty = &self.info.encoder.metadata.resolve.types[id];
565        let name = ty.name.as_ref().expect("type must have a name");
566        let instance = self.exported_instances[&interface];
567        self.component
568            .alias_export(instance, name, ComponentExportKind::Type)
569    }
570
571    fn encode_core_instantiation(&mut self) -> Result<()> {
572        // Encode a shim instantiation if needed
573        let shims = self.encode_shim_instantiation()?;
574
575        // Next declare any types needed for imported intrinsics. This
576        // populates `export_type_map` and will additionally be used for
577        // imports to modules instantiated below.
578        self.declare_types_for_imported_intrinsics(&shims)?;
579
580        // Next instantiate the main module. This provides the linear memory to
581        // use for all future adapters and enables creating indirect lowerings
582        // at the end.
583        self.instantiate_main_module(&shims)?;
584
585        // Separate the adapters according which should be instantiated before
586        // and after indirect lowerings are encoded.
587        let (before, after) = self
588            .info
589            .adapters
590            .iter()
591            .partition::<Vec<_>, _>(|(_, adapter)| {
592                !matches!(
593                    adapter.library_info,
594                    Some(LibraryInfo {
595                        instantiate_after_shims: true,
596                        ..
597                    })
598                )
599            });
600
601        for (name, _adapter) in before {
602            self.instantiate_adapter_module(&shims, name)?;
603        }
604
605        // With all the relevant core wasm instances in play now the original shim
606        // module, if present, can be filled in with lowerings/adapters/etc.
607        self.encode_indirect_lowerings(&shims)?;
608
609        for (name, _adapter) in after {
610            self.instantiate_adapter_module(&shims, name)?;
611        }
612
613        self.encode_initialize_with_start()?;
614
615        Ok(())
616    }
617
618    fn lookup_resource_index(&mut self, id: TypeId) -> u32 {
619        let resolve = &self.info.encoder.metadata.resolve;
620        let ty = &resolve.types[id];
621        match ty.owner {
622            // If this resource is owned by a world then it's a top-level
623            // resource which means it must have already been translated so
624            // it's available for lookup in `import_type_map`.
625            TypeOwner::World(_) => self.import_type_map[&id],
626            TypeOwner::Interface(i) => {
627                let instance = self.imported_instances[&i];
628                let name = ty.name.as_ref().expect("resources must be named");
629                self.component
630                    .alias_export(instance, name, ComponentExportKind::Type)
631            }
632            TypeOwner::None => panic!("resources must have an owner"),
633        }
634    }
635
636    fn encode_exports(&mut self, module: CustomModule) -> Result<()> {
637        let resolve = &self.info.encoder.metadata.resolve;
638        let exports = match module {
639            CustomModule::Main => &self.info.encoder.main_module_exports,
640            CustomModule::Adapter(name) => &self.info.encoder.adapters[name].required_exports,
641        };
642
643        if exports.is_empty() {
644            return Ok(());
645        }
646
647        let mut interface_func_core_names = IndexMap::new();
648        let mut world_func_core_names = IndexMap::new();
649        for (core_name, export) in self.info.exports_for(module).iter() {
650            match export {
651                Export::WorldFunc(_, name, _) => {
652                    let prev = world_func_core_names.insert(name, core_name);
653                    assert!(prev.is_none());
654                }
655                Export::InterfaceFunc(_, id, name, _) => {
656                    let prev = interface_func_core_names
657                        .entry(id)
658                        .or_insert(IndexMap::new())
659                        .insert(name.as_str(), core_name);
660                    assert!(prev.is_none());
661                }
662                Export::WorldFuncCallback(..)
663                | Export::InterfaceFuncCallback(..)
664                | Export::WorldFuncPostReturn(..)
665                | Export::InterfaceFuncPostReturn(..)
666                | Export::ResourceDtor(..)
667                | Export::Memory
668                | Export::GeneralPurposeRealloc
669                | Export::GeneralPurposeExportRealloc
670                | Export::GeneralPurposeImportRealloc
671                | Export::Initialize
672                | Export::ReallocForAdapter => continue,
673            }
674        }
675
676        let world = &resolve.worlds[self.info.encoder.metadata.world];
677
678        for export_name in exports {
679            let export_string = resolve.name_world_key(export_name);
680            match &world.exports[export_name] {
681                WorldItem::Function(func) => {
682                    let ty = self
683                        .root_import_type_encoder(None)
684                        .encode_func_type(resolve, func)?;
685                    let core_name = world_func_core_names[&func.name];
686                    let idx = self.encode_lift(module, &core_name, export_name, func, ty)?;
687                    self.component
688                        .export(&export_string, ComponentExportKind::Func, idx, None);
689                }
690                WorldItem::Interface { id, .. } => {
691                    let core_names = interface_func_core_names.get(id);
692                    self.encode_interface_export(
693                        &export_string,
694                        module,
695                        export_name,
696                        *id,
697                        core_names,
698                    )?;
699                }
700                WorldItem::Type(_) => unreachable!(),
701            }
702        }
703
704        Ok(())
705    }
706
707    fn encode_interface_export(
708        &mut self,
709        export_name: &str,
710        module: CustomModule<'_>,
711        key: &WorldKey,
712        export: InterfaceId,
713        interface_func_core_names: Option<&IndexMap<&str, &str>>,
714    ) -> Result<()> {
715        log::trace!("encode interface export `{export_name}`");
716        let resolve = &self.info.encoder.metadata.resolve;
717
718        // First execute a `canon lift` for all the functions in this interface
719        // from the core wasm export. This requires type information but notably
720        // not exported type information since we don't want to export this
721        // interface's types from the root of the component. Each lifted
722        // function is saved off into an `imports` array to get imported into
723        // the nested component synthesized below.
724        let mut imports = Vec::new();
725        let mut root = self.root_export_type_encoder(Some(export));
726        for (_, func) in &resolve.interfaces[export].functions {
727            let core_name = interface_func_core_names.unwrap()[func.name.as_str()];
728            let ty = root.encode_func_type(resolve, func)?;
729            let func_index = root.state.encode_lift(module, &core_name, key, func, ty)?;
730            imports.push((
731                import_func_name(func),
732                ComponentExportKind::Func,
733                func_index,
734            ));
735        }
736
737        // Next a nested component is created which will import the functions
738        // above and then reexport them. The purpose of them is to "re-type" the
739        // functions through type ascription on each `func` item.
740        let mut nested = NestedComponentTypeEncoder {
741            component: ComponentBuilder::default(),
742            type_map: Default::default(),
743            func_type_map: Default::default(),
744            export_types: false,
745            interface: export,
746            state: self,
747            imports: IndexMap::new(),
748        };
749
750        // Import all transitively-referenced types from other interfaces into
751        // this component. This temporarily switches the `interface` listed to
752        // the interface of the referred-to-type to generate the import. After
753        // this loop `interface` is rewritten to `export`.
754        //
755        // Each component is a standalone "island" so the necessary type
756        // information needs to be rebuilt within this component. This ensures
757        // that we're able to build a valid component and additionally connect
758        // all the type information to the outer context.
759        let mut types_to_import = LiveTypes::default();
760        types_to_import.add_interface(resolve, export);
761        let exports_used = &nested.state.info.exports_used[&export];
762        for ty in types_to_import.iter() {
763            if let TypeOwner::Interface(owner) = resolve.types[ty].owner {
764                if owner == export {
765                    // Here this deals with the current exported interface which
766                    // is handled below.
767                    continue;
768                }
769
770                // Ensure that `self` has encoded this type before. If so this
771                // is a noop but otherwise it generates the type here.
772                let mut encoder = if exports_used.contains(&owner) {
773                    nested.state.root_export_type_encoder(Some(export))
774                } else {
775                    nested.state.root_import_type_encoder(Some(export))
776                };
777                encoder.encode_valtype(resolve, &Type::Id(ty))?;
778
779                // Next generate the same type but this time within the
780                // component itself. The type generated above (or prior) will be
781                // used to satisfy this type import.
782                nested.interface = owner;
783                nested.encode_valtype(resolve, &Type::Id(ty))?;
784            }
785        }
786        nested.interface = export;
787
788        // Record the map of types imported to their index at where they were
789        // imported. This is used after imports are encoded as exported types
790        // will refer to these.
791        let imported_types = nested.type_map.clone();
792
793        // Handle resource types for this instance specially, namely importing
794        // them into the nested component. This models how the resource is
795        // imported from its definition in the outer component to get reexported
796        // internally. This chiefly avoids creating a second resource which is
797        // not desired in this situation.
798        let mut resources = HashMap::new();
799        for (_name, ty) in resolve.interfaces[export].types.iter() {
800            if !matches!(resolve.types[*ty].kind, TypeDefKind::Resource) {
801                continue;
802            }
803            let idx = match nested.encode_valtype(resolve, &Type::Id(*ty))? {
804                ComponentValType::Type(idx) => idx,
805                _ => unreachable!(),
806            };
807            resources.insert(*ty, idx);
808        }
809
810        // Next import each function of this interface. This will end up
811        // defining local types as necessary or using the types as imported
812        // above.
813        for (_, func) in resolve.interfaces[export].functions.iter() {
814            let ty = nested.encode_func_type(resolve, func)?;
815            nested
816                .component
817                .import(&import_func_name(func), ComponentTypeRef::Func(ty));
818        }
819
820        // Swap the `nested.type_map` which was previously from `TypeId` to
821        // `u32` to instead being from `u32` to `TypeId`. This reverse map is
822        // then used in conjunction with `self.type_map` to satisfy all type
823        // imports of the nested component generated. The type import's index in
824        // the inner component is translated to a `TypeId` via `reverse_map`
825        // which is then translated back to our own index space via `type_map`.
826        let reverse_map = nested
827            .type_map
828            .drain()
829            .map(|p| (p.1, p.0))
830            .collect::<HashMap<_, _>>();
831        for (name, idx) in nested.imports.drain(..) {
832            let id = reverse_map[&idx];
833            let owner = match resolve.types[id].owner {
834                TypeOwner::Interface(id) => id,
835                _ => unreachable!(),
836            };
837            let idx = if owner == export || exports_used.contains(&owner) {
838                log::trace!("consulting exports for {id:?}");
839                nested.state.export_type_map[&id]
840            } else {
841                log::trace!("consulting imports for {id:?}");
842                nested.state.import_type_map[&id]
843            };
844            imports.push((name, ComponentExportKind::Type, idx))
845        }
846
847        // Before encoding exports reset the type map to what all was imported
848        // from foreign interfaces. This will enable any encoded types below to
849        // refer to imports which, after type substitution, will point to the
850        // correct type in the outer component context.
851        nested.type_map = imported_types;
852
853        // Next the component reexports all of its imports, but notably uses the
854        // type ascription feature to change the type of the function. Note that
855        // no structural change is happening to the types here but instead types
856        // are getting proper names and such now that this nested component is a
857        // new type index space. Hence the `export_types = true` flag here which
858        // flows through the type encoding and when types are emitted.
859        nested.export_types = true;
860        nested.func_type_map.clear();
861
862        // To start off all type information is encoded. This will be used by
863        // functions below but notably this also has special handling for
864        // resources. Resources reexport their imported resource type under
865        // the final name which achieves the desired goal of threading through
866        // the original resource without creating a new one.
867        for (_, id) in resolve.interfaces[export].types.iter() {
868            let ty = &resolve.types[*id];
869            match ty.kind {
870                TypeDefKind::Resource => {
871                    let idx = nested.component.export(
872                        ty.name.as_ref().expect("resources must be named"),
873                        ComponentExportKind::Type,
874                        resources[id],
875                        None,
876                    );
877                    nested.type_map.insert(*id, idx);
878                }
879                _ => {
880                    nested.encode_valtype(resolve, &Type::Id(*id))?;
881                }
882            }
883        }
884
885        for (i, (_, func)) in resolve.interfaces[export].functions.iter().enumerate() {
886            let ty = nested.encode_func_type(resolve, func)?;
887            nested.component.export(
888                &func.name,
889                ComponentExportKind::Func,
890                i as u32,
891                Some(ComponentTypeRef::Func(ty)),
892            );
893        }
894
895        // Embed the component within our component and then instantiate it with
896        // the lifted functions. That final instance is then exported under the
897        // appropriate name as the final typed export of this component.
898        let component = nested.component;
899        let component_index = self.component.component(component);
900        let instance_index = self.component.instantiate(component_index, imports);
901        let idx = self.component.export(
902            export_name,
903            ComponentExportKind::Instance,
904            instance_index,
905            None,
906        );
907        let prev = self.exported_instances.insert(export, idx);
908        assert!(prev.is_none());
909
910        // After everything is all said and done remove all the type information
911        // about type exports of this interface. Any entries in the map
912        // currently were used to create the instance above but aren't the
913        // actual copy of the exported type since that comes from the exported
914        // instance itself. Entries will be re-inserted into this map as
915        // necessary via aliases from the exported instance which is the new
916        // source of truth for all these types.
917        for (_name, id) in resolve.interfaces[export].types.iter() {
918            self.export_type_map.remove(id);
919        }
920
921        return Ok(());
922
923        struct NestedComponentTypeEncoder<'state, 'a> {
924            component: ComponentBuilder,
925            type_map: HashMap<TypeId, u32>,
926            func_type_map: HashMap<types::FunctionKey<'a>, u32>,
927            export_types: bool,
928            interface: InterfaceId,
929            state: &'state mut EncodingState<'a>,
930            imports: IndexMap<String, u32>,
931        }
932
933        impl<'a> ValtypeEncoder<'a> for NestedComponentTypeEncoder<'_, 'a> {
934            fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) {
935                self.component.type_defined()
936            }
937            fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) {
938                self.component.type_function()
939            }
940            fn export_type(&mut self, idx: u32, name: &'a str) -> Option<u32> {
941                if self.export_types {
942                    Some(
943                        self.component
944                            .export(name, ComponentExportKind::Type, idx, None),
945                    )
946                } else {
947                    let name = self.unique_import_name(name);
948                    let ret = self
949                        .component
950                        .import(&name, ComponentTypeRef::Type(TypeBounds::Eq(idx)));
951                    self.imports.insert(name, ret);
952                    Some(ret)
953                }
954            }
955            fn export_resource(&mut self, name: &'a str) -> u32 {
956                if self.export_types {
957                    panic!("resources should already be exported")
958                } else {
959                    let name = self.unique_import_name(name);
960                    let ret = self
961                        .component
962                        .import(&name, ComponentTypeRef::Type(TypeBounds::SubResource));
963                    self.imports.insert(name, ret);
964                    ret
965                }
966            }
967            fn import_type(&mut self, _: InterfaceId, _id: TypeId) -> u32 {
968                unreachable!()
969            }
970            fn type_map(&mut self) -> &mut HashMap<TypeId, u32> {
971                &mut self.type_map
972            }
973            fn func_type_map(&mut self) -> &mut HashMap<types::FunctionKey<'a>, u32> {
974                &mut self.func_type_map
975            }
976            fn interface(&self) -> Option<InterfaceId> {
977                Some(self.interface)
978            }
979        }
980
981        impl NestedComponentTypeEncoder<'_, '_> {
982            fn unique_import_name(&mut self, name: &str) -> String {
983                let mut name = format!("import-type-{name}");
984                let mut n = 0;
985                while self.imports.contains_key(&name) {
986                    name = format!("{name}{n}");
987                    n += 1;
988                }
989                name
990            }
991        }
992
993        fn import_func_name(f: &Function) -> String {
994            match f.kind {
995                FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
996                    format!("import-func-{}", f.item_name())
997                }
998
999                // transform `[method]foo.bar` into `import-method-foo-bar` to
1000                // have it be a valid kebab-name which can't conflict with
1001                // anything else.
1002                //
1003                // There's probably a better and more "formal" way to do this
1004                // but quick-and-dirty string manipulation should work well
1005                // enough for now hopefully.
1006                FunctionKind::Method(_)
1007                | FunctionKind::AsyncMethod(_)
1008                | FunctionKind::Static(_)
1009                | FunctionKind::AsyncStatic(_)
1010                | FunctionKind::Constructor(_) => {
1011                    format!(
1012                        "import-{}",
1013                        f.name.replace('[', "").replace([']', '.', ' '], "-")
1014                    )
1015                }
1016            }
1017        }
1018    }
1019
1020    fn encode_lift(
1021        &mut self,
1022        module: CustomModule<'_>,
1023        core_name: &str,
1024        key: &WorldKey,
1025        func: &Function,
1026        ty: u32,
1027    ) -> Result<u32> {
1028        let resolve = &self.info.encoder.metadata.resolve;
1029        let metadata = self.info.module_metadata_for(module);
1030        let instance_index = self.instance_for(module);
1031        let core_func_index = self.core_alias_export(instance_index, core_name, ExportKind::Func);
1032        let exports = self.info.exports_for(module);
1033
1034        let options = RequiredOptions::for_export(
1035            resolve,
1036            func,
1037            exports
1038                .abi(key, func)
1039                .ok_or_else(|| anyhow!("no ABI found for {}", func.name))?,
1040        );
1041
1042        let encoding = metadata
1043            .export_encodings
1044            .get(resolve, key, &func.name)
1045            .unwrap();
1046        let exports = self.info.exports_for(module);
1047        let realloc_index = exports
1048            .export_realloc_for(key, &func.name)
1049            .map(|name| self.core_alias_export(instance_index, name, ExportKind::Func));
1050        let mut options = options
1051            .into_iter(encoding, self.memory_index, realloc_index)?
1052            .collect::<Vec<_>>();
1053
1054        if let Some(post_return) = exports.post_return(key, func) {
1055            let post_return = self.core_alias_export(instance_index, post_return, ExportKind::Func);
1056            options.push(CanonicalOption::PostReturn(post_return));
1057        }
1058        if let Some(callback) = exports.callback(key, func) {
1059            let callback = self.core_alias_export(instance_index, callback, ExportKind::Func);
1060            options.push(CanonicalOption::Callback(callback));
1061        }
1062        let func_index = self.component.lift_func(core_func_index, ty, options);
1063        Ok(func_index)
1064    }
1065
1066    fn encode_shim_instantiation(&mut self) -> Result<Shims<'a>> {
1067        let mut ret = Shims::default();
1068
1069        ret.append_indirect(self.info, CustomModule::Main)
1070            .context("failed to register indirect shims for main module")?;
1071
1072        // For all required adapter modules a shim is created for each required
1073        // function and additionally a set of shims are created for the
1074        // interface imported into the shim module itself.
1075        for (adapter_name, _adapter) in self.info.adapters.iter() {
1076            ret.append_indirect(self.info, CustomModule::Adapter(adapter_name))
1077                .with_context(|| {
1078                    format!("failed to register indirect shims for adapter {adapter_name}")
1079                })?;
1080        }
1081
1082        if ret.shims.is_empty() {
1083            return Ok(ret);
1084        }
1085
1086        assert!(self.shim_instance_index.is_none());
1087        assert!(self.fixups_module_index.is_none());
1088
1089        // This function encodes two modules:
1090        // - A shim module that defines a table and exports functions
1091        //   that indirectly call through the table.
1092        // - A fixup module that imports that table and a set of functions
1093        //   and populates the imported table via active element segments. The
1094        //   fixup module is used to populate the shim's table once the
1095        //   imported functions have been lowered.
1096
1097        let mut types = TypeSection::new();
1098        let mut tables = TableSection::new();
1099        let mut functions = FunctionSection::new();
1100        let mut exports = ExportSection::new();
1101        let mut code = CodeSection::new();
1102        let mut sigs = IndexMap::new();
1103        let mut imports_section = ImportSection::new();
1104        let mut elements = ElementSection::new();
1105        let mut func_indexes = Vec::new();
1106        let mut func_names = NameMap::new();
1107
1108        for (i, shim) in ret.shims.values().enumerate() {
1109            let i = i as u32;
1110            let type_index = *sigs.entry(&shim.sig).or_insert_with(|| {
1111                let index = types.len();
1112                types.ty().function(
1113                    shim.sig.params.iter().map(to_val_type),
1114                    shim.sig.results.iter().map(to_val_type),
1115                );
1116                index
1117            });
1118
1119            functions.function(type_index);
1120            Self::encode_shim_function(type_index, i, &mut code, shim.sig.params.len() as u32);
1121            exports.export(&shim.name, ExportKind::Func, i);
1122
1123            imports_section.import("", &shim.name, EntityType::Function(type_index));
1124            func_indexes.push(i);
1125            func_names.append(i, &shim.debug_name);
1126        }
1127        let mut names = NameSection::new();
1128        names.module("wit-component:shim");
1129        names.functions(&func_names);
1130
1131        let table_type = TableType {
1132            element_type: RefType::FUNCREF,
1133            minimum: ret.shims.len() as u64,
1134            maximum: Some(ret.shims.len() as u64),
1135            table64: false,
1136            shared: false,
1137        };
1138
1139        tables.table(table_type);
1140
1141        exports.export(INDIRECT_TABLE_NAME, ExportKind::Table, 0);
1142        imports_section.import("", INDIRECT_TABLE_NAME, table_type);
1143
1144        elements.active(
1145            None,
1146            &ConstExpr::i32_const(0),
1147            Elements::Functions(func_indexes.into()),
1148        );
1149
1150        let mut shim = Module::new();
1151        shim.section(&types);
1152        shim.section(&functions);
1153        shim.section(&tables);
1154        shim.section(&exports);
1155        shim.section(&code);
1156        shim.section(&RawCustomSection(
1157            &crate::base_producers().raw_custom_section(),
1158        ));
1159        shim.section(&names);
1160
1161        let mut fixups = Module::default();
1162        fixups.section(&types);
1163        fixups.section(&imports_section);
1164        fixups.section(&elements);
1165        fixups.section(&RawCustomSection(
1166            &crate::base_producers().raw_custom_section(),
1167        ));
1168
1169        let mut names = NameSection::new();
1170        names.module("wit-component:fixups");
1171        fixups.section(&names);
1172
1173        let shim_module_index = self.component.core_module(&shim);
1174        self.fixups_module_index = Some(self.component.core_module(&fixups));
1175        self.shim_instance_index = Some(self.component.core_instantiate(shim_module_index, []));
1176
1177        return Ok(ret);
1178    }
1179
1180    fn encode_shim_function(
1181        type_index: u32,
1182        func_index: u32,
1183        code: &mut CodeSection,
1184        param_count: u32,
1185    ) {
1186        let mut func = wasm_encoder::Function::new(std::iter::empty());
1187        for i in 0..param_count {
1188            func.instructions().local_get(i);
1189        }
1190        func.instructions().i32_const(func_index as i32);
1191        func.instructions().call_indirect(0, type_index);
1192        func.instructions().end();
1193        code.function(&func);
1194    }
1195
1196    fn encode_indirect_lowerings(&mut self, shims: &Shims<'_>) -> Result<()> {
1197        if shims.shims.is_empty() {
1198            return Ok(());
1199        }
1200
1201        let shim_instance_index = self
1202            .shim_instance_index
1203            .expect("must have an instantiated shim");
1204
1205        let table_index =
1206            self.core_alias_export(shim_instance_index, INDIRECT_TABLE_NAME, ExportKind::Table);
1207
1208        let resolve = &self.info.encoder.metadata.resolve;
1209
1210        let mut exports = Vec::new();
1211        exports.push((INDIRECT_TABLE_NAME, ExportKind::Table, table_index));
1212
1213        for shim in shims.shims.values() {
1214            let core_func_index = match &shim.kind {
1215                // Indirect lowerings are a `canon lower`'d function with
1216                // options specified from a previously instantiated instance.
1217                // This previous instance could either be the main module or an
1218                // adapter module, which affects the `realloc` option here.
1219                // Currently only one linear memory is supported so the linear
1220                // memory always comes from the main module.
1221                ShimKind::IndirectLowering {
1222                    interface,
1223                    index,
1224                    realloc,
1225                    encoding,
1226                } => {
1227                    let interface = &self.info.import_map[interface];
1228                    let ((name, _), _) = interface.lowerings.get_index(*index).unwrap();
1229                    let func_index = match &interface.interface {
1230                        Some(interface_id) => {
1231                            let instance_index = self.imported_instances[interface_id];
1232                            self.component.alias_export(
1233                                instance_index,
1234                                name,
1235                                ComponentExportKind::Func,
1236                            )
1237                        }
1238                        None => self.imported_funcs[name],
1239                    };
1240
1241                    let realloc = self
1242                        .info
1243                        .exports_for(*realloc)
1244                        .import_realloc_for(interface.interface, name)
1245                        .map(|name| {
1246                            let instance = self.instance_for(*realloc);
1247                            self.core_alias_export(instance, name, ExportKind::Func)
1248                        });
1249
1250                    self.component.lower_func(
1251                        func_index,
1252                        shim.options
1253                            .into_iter(*encoding, self.memory_index, realloc)?,
1254                    )
1255                }
1256
1257                // Adapter shims are defined by an export from an adapter
1258                // instance, so use the specified name here and the previously
1259                // created instances to get the core item that represents the
1260                // shim.
1261                ShimKind::Adapter { adapter, func } => {
1262                    self.core_alias_export(self.adapter_instances[adapter], func, ExportKind::Func)
1263                }
1264
1265                // Resources are required for a module to be instantiated
1266                // meaning that any destructor for the resource must be called
1267                // indirectly due to the otherwise circular dependency between
1268                // the module and the resource itself.
1269                ShimKind::ResourceDtor { module, export } => {
1270                    self.core_alias_export(self.instance_for(*module), export, ExportKind::Func)
1271                }
1272
1273                ShimKind::PayloadFunc {
1274                    for_module,
1275                    info,
1276                    kind,
1277                } => {
1278                    let metadata = self.info.module_metadata_for(*for_module);
1279                    let exports = self.info.exports_for(*for_module);
1280                    let instance_index = self.instance_for(*for_module);
1281                    let (encoding, realloc) = if info.imported {
1282                        (
1283                            metadata
1284                                .import_encodings
1285                                .get(resolve, &info.key, &info.function),
1286                            exports.import_realloc_for(info.interface, &info.function),
1287                        )
1288                    } else {
1289                        (
1290                            metadata
1291                                .export_encodings
1292                                .get(resolve, &info.key, &info.function),
1293                            exports.export_realloc_for(&info.key, &info.function),
1294                        )
1295                    };
1296                    let encoding = encoding.unwrap_or(StringEncoding::UTF8);
1297                    let realloc_index = realloc
1298                        .map(|name| self.core_alias_export(instance_index, name, ExportKind::Func));
1299                    let type_index = self.payload_type_index(info)?;
1300                    let options =
1301                        shim.options
1302                            .into_iter(encoding, self.memory_index, realloc_index)?;
1303
1304                    match kind {
1305                        PayloadFuncKind::FutureWrite => {
1306                            self.component.future_write(type_index, options)
1307                        }
1308                        PayloadFuncKind::FutureRead => {
1309                            self.component.future_read(type_index, options)
1310                        }
1311                        PayloadFuncKind::StreamWrite => {
1312                            self.component.stream_write(type_index, options)
1313                        }
1314                        PayloadFuncKind::StreamRead => {
1315                            self.component.stream_read(type_index, options)
1316                        }
1317                    }
1318                }
1319
1320                ShimKind::WaitableSetWait { async_ } => self
1321                    .component
1322                    .waitable_set_wait(*async_, self.memory_index.unwrap()),
1323                ShimKind::WaitableSetPoll { async_ } => self
1324                    .component
1325                    .waitable_set_poll(*async_, self.memory_index.unwrap()),
1326                ShimKind::ErrorContextNew { encoding } => self.component.error_context_new(
1327                    shim.options.into_iter(*encoding, self.memory_index, None)?,
1328                ),
1329                ShimKind::ErrorContextDebugMessage {
1330                    for_module,
1331                    encoding,
1332                } => {
1333                    let instance_index = self.instance_for(*for_module);
1334                    let realloc = self.info.exports_for(*for_module).import_realloc_fallback();
1335                    let realloc_index = realloc
1336                        .map(|r| self.core_alias_export(instance_index, r, ExportKind::Func));
1337
1338                    self.component
1339                        .error_context_debug_message(shim.options.into_iter(
1340                            *encoding,
1341                            self.memory_index,
1342                            realloc_index,
1343                        )?)
1344                }
1345                ShimKind::TaskReturn {
1346                    interface,
1347                    func,
1348                    result,
1349                    encoding,
1350                    for_module,
1351                } => {
1352                    // See `Import::ExportedTaskReturn` handling for why this
1353                    // encoder is treated specially.
1354                    let mut encoder = if interface.is_none() {
1355                        self.root_import_type_encoder(*interface)
1356                    } else {
1357                        self.root_export_type_encoder(*interface)
1358                    };
1359                    let result = match result {
1360                        Some(ty) => Some(encoder.encode_valtype(resolve, ty)?),
1361                        None => None,
1362                    };
1363
1364                    let exports = self.info.exports_for(*for_module);
1365                    let realloc = exports.import_realloc_for(*interface, func);
1366
1367                    let instance_index = self.instance_for(*for_module);
1368                    let realloc_index = realloc
1369                        .map(|r| self.core_alias_export(instance_index, r, ExportKind::Func));
1370                    let options =
1371                        shim.options
1372                            .into_iter(*encoding, self.memory_index, realloc_index)?;
1373                    self.component.task_return(result, options)
1374                }
1375            };
1376
1377            exports.push((shim.name.as_str(), ExportKind::Func, core_func_index));
1378        }
1379
1380        let instance_index = self.component.core_instantiate_exports(exports);
1381        self.component.core_instantiate(
1382            self.fixups_module_index.expect("must have fixup module"),
1383            [("", ModuleArg::Instance(instance_index))],
1384        );
1385        Ok(())
1386    }
1387
1388    /// Encode the specified `stream` or `future` type in the component using
1389    /// either the `root_import_type_encoder` or the `root_export_type_encoder`
1390    /// depending on the value of `imported`.
1391    ///
1392    /// Note that the payload type `T` of `stream<T>` or `future<T>` may be an
1393    /// imported or exported type, and that determines the appropriate type
1394    /// encoder to use.
1395    fn payload_type_index(&mut self, info: &PayloadInfo) -> Result<u32> {
1396        let resolve = &self.info.encoder.metadata.resolve;
1397        // What exactly is selected here as the encoder is a bit unusual here.
1398        // If the interface is imported, an import encoder is used. An import
1399        // encoder is also used though if `info` is exported and
1400        // `info.interface` is `None`, meaning that this is for a function that
1401        // is in the top-level of a world. At the top level of a world all
1402        // types are imported.
1403        //
1404        // Additionally for the import encoder the interface passed in is
1405        // `None`, not `info.interface`. Notably this means that references to
1406        // named types will be aliased from their imported versions, which is
1407        // what we want here.
1408        //
1409        // Finally though exports do use `info.interface`. Honestly I'm not
1410        // really entirely sure why. Fuzzing is happy though, and truly
1411        // everything must be ok if the fuzzers are happy, right?
1412        let ComponentValType::Type(type_index) = if info.imported || info.interface.is_none() {
1413            self.root_import_type_encoder(None)
1414        } else {
1415            self.root_export_type_encoder(info.interface)
1416        }
1417        .encode_valtype(resolve, &Type::Id(info.ty))?
1418        else {
1419            unreachable!()
1420        };
1421        Ok(type_index)
1422    }
1423
1424    /// This is a helper function that will declare any types necessary for
1425    /// declaring intrinsics that are imported into the module or adapter.
1426    ///
1427    /// For example resources must be declared to generate
1428    /// destructors/constructors/etc. Additionally types must also be declared
1429    /// for `task.return` with the component model async feature.
1430    fn declare_types_for_imported_intrinsics(&mut self, shims: &Shims<'_>) -> Result<()> {
1431        let resolve = &self.info.encoder.metadata.resolve;
1432        let world = &resolve.worlds[self.info.encoder.metadata.world];
1433
1434        // Iterate over the main module's exports and the exports of all
1435        // adapters. Look for exported interfaces.
1436        let main_module_keys = self.info.encoder.main_module_exports.iter();
1437        let main_module_keys = main_module_keys.map(|key| (CustomModule::Main, key));
1438        let adapter_keys = self.info.encoder.adapters.iter().flat_map(|(name, info)| {
1439            info.required_exports
1440                .iter()
1441                .map(move |key| (CustomModule::Adapter(name), key))
1442        });
1443        for (for_module, key) in main_module_keys.chain(adapter_keys) {
1444            let id = match &world.exports[key] {
1445                WorldItem::Interface { id, .. } => *id,
1446                WorldItem::Type { .. } => unreachable!(),
1447                WorldItem::Function(_) => continue,
1448            };
1449
1450            for ty in resolve.interfaces[id].types.values() {
1451                match &resolve.types[*ty].kind {
1452                    // Declare exported resources specially as they generally
1453                    // need special treatment for later handling exports and
1454                    // such.
1455                    TypeDefKind::Resource => {
1456                        // Load the destructor, previously detected in module
1457                        // validation, if one is present.
1458                        let exports = self.info.exports_for(for_module);
1459                        let dtor = exports.resource_dtor(*ty).map(|name| {
1460                            let name = &shims.shims[&ShimKind::ResourceDtor {
1461                                module: for_module,
1462                                export: name,
1463                            }]
1464                                .name;
1465                            let shim = self.shim_instance_index.unwrap();
1466                            self.core_alias_export(shim, name, ExportKind::Func)
1467                        });
1468
1469                        // Declare the resource with this destructor and register it in
1470                        // our internal map. This should be the first and only time this
1471                        // type is inserted into this map.
1472                        let resource_idx = self.component.type_resource(ValType::I32, dtor);
1473                        let prev = self.export_type_map.insert(*ty, resource_idx);
1474                        assert!(prev.is_none());
1475                    }
1476                    _other => {
1477                        self.root_export_type_encoder(Some(id))
1478                            .encode_valtype(resolve, &Type::Id(*ty))?;
1479                    }
1480                }
1481            }
1482        }
1483        Ok(())
1484    }
1485
1486    /// Helper to instantiate the main module and record various results of its
1487    /// instantiation within `self`.
1488    fn instantiate_main_module(&mut self, shims: &Shims<'_>) -> Result<()> {
1489        assert!(self.instance_index.is_none());
1490
1491        let instance_index = self.instantiate_core_module(shims, CustomModule::Main)?;
1492
1493        if let Some(memory) = self.info.info.exports.memory() {
1494            self.memory_index =
1495                Some(self.core_alias_export(instance_index, memory, ExportKind::Memory));
1496        }
1497
1498        self.instance_index = Some(instance_index);
1499        Ok(())
1500    }
1501
1502    /// This function will instantiate the specified adapter module, which may
1503    /// depend on previously-instantiated modules.
1504    fn instantiate_adapter_module(&mut self, shims: &Shims<'_>, name: &'a str) -> Result<()> {
1505        let instance = self.instantiate_core_module(shims, CustomModule::Adapter(name))?;
1506        self.adapter_instances.insert(name, instance);
1507        Ok(())
1508    }
1509
1510    /// Generic helper to instantiate a module.
1511    ///
1512    /// The `for_module` provided will have all of its imports satisfied from
1513    /// either previous instantiations or the `shims` module present. This
1514    /// iterates over the metadata produced during validation to determine what
1515    /// hooks up to what import.
1516    fn instantiate_core_module(
1517        &mut self,
1518        shims: &Shims,
1519        for_module: CustomModule<'_>,
1520    ) -> Result<u32> {
1521        let module = self.module_for(for_module);
1522
1523        let mut args = Vec::new();
1524        for (core_wasm_name, instance) in self.info.imports_for(for_module).modules() {
1525            match instance {
1526                // For import modules that are a "bag of names" iterate over
1527                // each name and materialize it into this component with the
1528                // `materialize_import` helper. This is then all bottled up into
1529                // a bag-of-exports instances which is then used for
1530                // instantiation.
1531                ImportInstance::Names(names) => {
1532                    let mut exports = Vec::new();
1533                    for (name, import) in names {
1534                        let (kind, index) = self
1535                            .materialize_import(&shims, for_module, core_wasm_name, name, import)
1536                            .with_context(|| {
1537                                format!("failed to satisfy import `{core_wasm_name}::{name}`")
1538                            })?;
1539                        exports.push((name.as_str(), kind, index));
1540                    }
1541                    let index = self.component.core_instantiate_exports(exports);
1542                    args.push((core_wasm_name.as_str(), ModuleArg::Instance(index)));
1543                }
1544
1545                // Some imports are entire instances, so use the instance for
1546                // the module identifier as the import.
1547                ImportInstance::Whole(which) => {
1548                    let instance = self.instance_for(which.to_custom_module());
1549                    args.push((core_wasm_name.as_str(), ModuleArg::Instance(instance)));
1550                }
1551            }
1552        }
1553
1554        // And with all arguments prepared now, instantiate the module.
1555        Ok(self.component.core_instantiate(module, args))
1556    }
1557
1558    /// Helper function to materialize an import into a core module within the
1559    /// component being built.
1560    ///
1561    /// This function is called for individual imports and uses the results of
1562    /// validation, notably the `Import` type, to determine what WIT-level or
1563    /// component-level construct is being hooked up.
1564    fn materialize_import(
1565        &mut self,
1566        shims: &Shims<'_>,
1567        for_module: CustomModule<'_>,
1568        module: &str,
1569        field: &str,
1570        import: &'a Import,
1571    ) -> Result<(ExportKind, u32)> {
1572        log::trace!("attempting to materialize import of `{module}::{field}` for {for_module:?}");
1573        let resolve = &self.info.encoder.metadata.resolve;
1574        match import {
1575            // Main module dependencies on an adapter in use are done with an
1576            // indirection here, so load the shim function and use that.
1577            Import::AdapterExport(_) => {
1578                assert!(self.info.encoder.adapters.contains_key(module));
1579                Ok(self.materialize_shim_import(
1580                    shims,
1581                    &ShimKind::Adapter {
1582                        adapter: module,
1583                        func: field,
1584                    },
1585                ))
1586            }
1587
1588            // Adapters might uset he main module's memory, in which case it
1589            // should have been previously instantiated.
1590            Import::MainModuleMemory => {
1591                let index = self
1592                    .memory_index
1593                    .ok_or_else(|| anyhow!("main module cannot import memory"))?;
1594                Ok((ExportKind::Memory, index))
1595            }
1596
1597            // Grab-bag of "this adapter wants this thing from the main module".
1598            Import::MainModuleExport { name, kind } => {
1599                let instance = self.instance_index.unwrap();
1600                let index = self.core_alias_export(instance, name, *kind);
1601                Ok((*kind, index))
1602            }
1603
1604            // A similar grab-bag to above but with a slightly different
1605            // structure. Should probably refactor to make these two the same in
1606            // the future.
1607            Import::Item(item) => {
1608                let instance = self.instance_for(item.which.to_custom_module());
1609                let index = self.core_alias_export(instance, &item.name, item.kind);
1610                Ok((item.kind, index))
1611            }
1612
1613            // Resource intrinsics related to exported resources. Despite being
1614            // an exported resource the component still provides necessary
1615            // intrinsics for manipulating resource state. These are all
1616            // handled here using the resource types created during
1617            // `declare_types_for_imported_intrinsics` above.
1618            Import::ExportedResourceDrop(_key, id) => {
1619                let index = self.component.resource_drop(self.export_type_map[id]);
1620                Ok((ExportKind::Func, index))
1621            }
1622            Import::ExportedResourceRep(_key, id) => {
1623                let index = self.component.resource_rep(self.export_type_map[id]);
1624                Ok((ExportKind::Func, index))
1625            }
1626            Import::ExportedResourceNew(_key, id) => {
1627                let index = self.component.resource_new(self.export_type_map[id]);
1628                Ok((ExportKind::Func, index))
1629            }
1630
1631            // And finally here at the end these cases are going to all fall
1632            // through to the code below. This is where these are connected to a
1633            // WIT `ImportedInterface` one way or another with the name that was
1634            // detected during validation.
1635            Import::ImportedResourceDrop(key, iface, id) => {
1636                let ty = &resolve.types[*id];
1637                let name = ty.name.as_ref().unwrap();
1638                self.materialize_wit_import(
1639                    shims,
1640                    for_module,
1641                    iface.map(|_| resolve.name_world_key(key)),
1642                    &format!("{name}_drop"),
1643                    key,
1644                    AbiVariant::GuestImport,
1645                )
1646            }
1647            Import::ExportedTaskReturn(key, interface, func, result) => {
1648                let (options, _sig) = task_return_options_and_type(resolve, *result);
1649                if options.is_empty() {
1650                    // Note that an "import type encoder" is used here despite
1651                    // this being for an exported function if the `interface`
1652                    // is none, meaning that this is for a top-level world
1653                    // function. In that situation all types that can be
1654                    // referred to are imported, not exported.
1655                    let mut encoder = if interface.is_none() {
1656                        self.root_import_type_encoder(*interface)
1657                    } else {
1658                        self.root_export_type_encoder(*interface)
1659                    };
1660
1661                    let result = match result {
1662                        Some(ty) => Some(encoder.encode_valtype(resolve, ty)?),
1663                        None => None,
1664                    };
1665                    let index = self.component.task_return(result, []);
1666                    Ok((ExportKind::Func, index))
1667                } else {
1668                    let metadata = &self.info.encoder.metadata.metadata;
1669                    let encoding = metadata.export_encodings.get(resolve, key, func).unwrap();
1670                    Ok(self.materialize_shim_import(
1671                        shims,
1672                        &ShimKind::TaskReturn {
1673                            for_module,
1674                            interface: *interface,
1675                            func,
1676                            result: *result,
1677                            encoding,
1678                        },
1679                    ))
1680                }
1681            }
1682            Import::BackpressureSet => {
1683                let index = self.component.backpressure_set();
1684                Ok((ExportKind::Func, index))
1685            }
1686            Import::WaitableSetWait { async_ } => {
1687                Ok(self
1688                    .materialize_shim_import(shims, &ShimKind::WaitableSetWait { async_: *async_ }))
1689            }
1690            Import::WaitableSetPoll { async_ } => {
1691                Ok(self
1692                    .materialize_shim_import(shims, &ShimKind::WaitableSetPoll { async_: *async_ }))
1693            }
1694            Import::Yield { async_ } => {
1695                let index = self.component.yield_(*async_);
1696                Ok((ExportKind::Func, index))
1697            }
1698            Import::SubtaskDrop => {
1699                let index = self.component.subtask_drop();
1700                Ok((ExportKind::Func, index))
1701            }
1702            Import::SubtaskCancel { async_ } => {
1703                let index = self.component.subtask_cancel(*async_);
1704                Ok((ExportKind::Func, index))
1705            }
1706            Import::StreamNew(info) => {
1707                let ty = self.payload_type_index(info)?;
1708                let index = self.component.stream_new(ty);
1709                Ok((ExportKind::Func, index))
1710            }
1711            Import::StreamRead { info, .. } => Ok(self.materialize_payload_import(
1712                shims,
1713                for_module,
1714                info,
1715                PayloadFuncKind::StreamRead,
1716            )),
1717            Import::StreamWrite { info, .. } => Ok(self.materialize_payload_import(
1718                shims,
1719                for_module,
1720                info,
1721                PayloadFuncKind::StreamWrite,
1722            )),
1723            Import::StreamCancelRead { info, async_ } => {
1724                let ty = self.payload_type_index(info)?;
1725                let index = self.component.stream_cancel_read(ty, *async_);
1726                Ok((ExportKind::Func, index))
1727            }
1728            Import::StreamCancelWrite { info, async_ } => {
1729                let ty = self.payload_type_index(info)?;
1730                let index = self.component.stream_cancel_write(ty, *async_);
1731                Ok((ExportKind::Func, index))
1732            }
1733            Import::StreamCloseReadable(info) => {
1734                let type_index = self.payload_type_index(info)?;
1735                let index = self.component.stream_close_readable(type_index);
1736                Ok((ExportKind::Func, index))
1737            }
1738            Import::StreamCloseWritable(info) => {
1739                let type_index = self.payload_type_index(info)?;
1740                let index = self.component.stream_close_writable(type_index);
1741                Ok((ExportKind::Func, index))
1742            }
1743            Import::FutureNew(info) => {
1744                let ty = self.payload_type_index(info)?;
1745                let index = self.component.future_new(ty);
1746                Ok((ExportKind::Func, index))
1747            }
1748            Import::FutureRead { info, .. } => Ok(self.materialize_payload_import(
1749                shims,
1750                for_module,
1751                info,
1752                PayloadFuncKind::FutureRead,
1753            )),
1754            Import::FutureWrite { info, .. } => Ok(self.materialize_payload_import(
1755                shims,
1756                for_module,
1757                info,
1758                PayloadFuncKind::FutureWrite,
1759            )),
1760            Import::FutureCancelRead { info, async_ } => {
1761                let ty = self.payload_type_index(info)?;
1762                let index = self.component.future_cancel_read(ty, *async_);
1763                Ok((ExportKind::Func, index))
1764            }
1765            Import::FutureCancelWrite { info, async_ } => {
1766                let ty = self.payload_type_index(info)?;
1767                let index = self.component.future_cancel_write(ty, *async_);
1768                Ok((ExportKind::Func, index))
1769            }
1770            Import::FutureCloseReadable(info) => {
1771                let type_index = self.payload_type_index(info)?;
1772                let index = self.component.future_close_readable(type_index);
1773                Ok((ExportKind::Func, index))
1774            }
1775            Import::FutureCloseWritable(info) => {
1776                let type_index = self.payload_type_index(info)?;
1777                let index = self.component.future_close_writable(type_index);
1778                Ok((ExportKind::Func, index))
1779            }
1780            Import::ErrorContextNew { encoding } => Ok(self.materialize_shim_import(
1781                shims,
1782                &ShimKind::ErrorContextNew {
1783                    encoding: *encoding,
1784                },
1785            )),
1786            Import::ErrorContextDebugMessage { encoding } => Ok(self.materialize_shim_import(
1787                shims,
1788                &ShimKind::ErrorContextDebugMessage {
1789                    for_module,
1790                    encoding: *encoding,
1791                },
1792            )),
1793            Import::ErrorContextDrop => {
1794                let index = self.component.error_context_drop();
1795                Ok((ExportKind::Func, index))
1796            }
1797            Import::WorldFunc(key, name, abi) => {
1798                self.materialize_wit_import(shims, for_module, None, name, key, *abi)
1799            }
1800            Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import(
1801                shims,
1802                for_module,
1803                Some(resolve.name_world_key(key)),
1804                name,
1805                key,
1806                *abi,
1807            ),
1808
1809            Import::WaitableSetNew => {
1810                let index = self.component.waitable_set_new();
1811                Ok((ExportKind::Func, index))
1812            }
1813            Import::WaitableSetDrop => {
1814                let index = self.component.waitable_set_drop();
1815                Ok((ExportKind::Func, index))
1816            }
1817            Import::WaitableJoin => {
1818                let index = self.component.waitable_join();
1819                Ok((ExportKind::Func, index))
1820            }
1821            Import::ContextGet(n) => {
1822                let index = self.component.context_get(*n);
1823                Ok((ExportKind::Func, index))
1824            }
1825            Import::ContextSet(n) => {
1826                let index = self.component.context_set(*n);
1827                Ok((ExportKind::Func, index))
1828            }
1829            Import::ExportedTaskCancel => {
1830                let index = self.component.task_cancel();
1831                Ok((ExportKind::Func, index))
1832            }
1833        }
1834    }
1835
1836    /// Helper for `materialize_import` above for materializing functions that
1837    /// are part of the "shim module" generated.
1838    fn materialize_shim_import(&mut self, shims: &Shims<'_>, kind: &ShimKind) -> (ExportKind, u32) {
1839        let index = self.core_alias_export(
1840            self.shim_instance_index
1841                .expect("shim should be instantiated"),
1842            &shims.shims[kind].name,
1843            ExportKind::Func,
1844        );
1845        (ExportKind::Func, index)
1846    }
1847
1848    /// Helper for `materialize_import` above for generating imports for
1849    /// future/stream read/write intrinsics.
1850    fn materialize_payload_import(
1851        &mut self,
1852        shims: &Shims<'_>,
1853        for_module: CustomModule<'_>,
1854        info: &PayloadInfo,
1855        kind: PayloadFuncKind,
1856    ) -> (ExportKind, u32) {
1857        self.materialize_shim_import(
1858            shims,
1859            &ShimKind::PayloadFunc {
1860                for_module,
1861                info,
1862                kind,
1863            },
1864        )
1865    }
1866
1867    /// Helper for `materialize_import` above which specifically operates on
1868    /// WIT-level functions identified by `interface_key`, `name`, and `abi`.
1869    fn materialize_wit_import(
1870        &mut self,
1871        shims: &Shims<'_>,
1872        for_module: CustomModule<'_>,
1873        interface_key: Option<String>,
1874        name: &String,
1875        key: &WorldKey,
1876        abi: AbiVariant,
1877    ) -> Result<(ExportKind, u32)> {
1878        let resolve = &self.info.encoder.metadata.resolve;
1879        let import = &self.info.import_map[&interface_key];
1880        let (index, _, lowering) = import.lowerings.get_full(&(name.clone(), abi)).unwrap();
1881        let metadata = self.info.module_metadata_for(for_module);
1882
1883        let index = match lowering {
1884            // All direct lowerings can be `canon lower`'d here immediately
1885            // and passed as arguments.
1886            Lowering::Direct => {
1887                let func_index = match &import.interface {
1888                    Some(interface) => {
1889                        let instance_index = self.imported_instances[interface];
1890                        self.component
1891                            .alias_export(instance_index, name, ComponentExportKind::Func)
1892                    }
1893                    None => self.imported_funcs[name],
1894                };
1895                self.component.lower_func(
1896                    func_index,
1897                    if let AbiVariant::GuestImportAsync = abi {
1898                        vec![CanonicalOption::Async]
1899                    } else {
1900                        Vec::new()
1901                    },
1902                )
1903            }
1904
1905            // Indirect lowerings come from the shim that was previously
1906            // created, so the specific export is loaded here and used as an
1907            // import.
1908            Lowering::Indirect { .. } => {
1909                let encoding = metadata.import_encodings.get(resolve, key, name).unwrap();
1910                return Ok(self.materialize_shim_import(
1911                    shims,
1912                    &ShimKind::IndirectLowering {
1913                        interface: interface_key,
1914                        index,
1915                        realloc: for_module,
1916                        encoding,
1917                    },
1918                ));
1919            }
1920
1921            // A "resource drop" intrinsic only needs to find the index of the
1922            // resource type itself and then the intrinsic is declared.
1923            Lowering::ResourceDrop(id) => {
1924                let resource_idx = self.lookup_resource_index(*id);
1925                self.component.resource_drop(resource_idx)
1926            }
1927        };
1928        Ok((ExportKind::Func, index))
1929    }
1930
1931    /// Generates component bits that are responsible for executing
1932    /// `_initialize`, if found, in the original component.
1933    ///
1934    /// The `_initialize` function was a part of WASIp1 where it generally is
1935    /// intended to run after imports and memory and such are all "hooked up"
1936    /// and performs other various initialization tasks. This is additionally
1937    /// specified in https://github.com/WebAssembly/component-model/pull/378
1938    /// to be part of the component model lowerings as well.
1939    ///
1940    /// This implements this functionality by encoding a core module that
1941    /// imports a function and then registers a `start` section with that
1942    /// imported function. This is all encoded after the
1943    /// imports/lowerings/tables/etc are all filled in above meaning that this
1944    /// is the last piece to run. That means that when this is running
1945    /// everything should be hooked up for all imported functions to work.
1946    ///
1947    /// Note that at this time `_initialize` is only detected in the "main
1948    /// module", not adapters/libraries.
1949    fn encode_initialize_with_start(&mut self) -> Result<()> {
1950        let initialize = match self.info.info.exports.initialize() {
1951            Some(name) => name,
1952            // If this core module didn't have `_initialize` or similar, then
1953            // there's nothing to do here.
1954            None => return Ok(()),
1955        };
1956        let initialize_index =
1957            self.core_alias_export(self.instance_index.unwrap(), initialize, ExportKind::Func);
1958        let mut shim = Module::default();
1959        let mut section = TypeSection::new();
1960        section.ty().function([], []);
1961        shim.section(&section);
1962        let mut section = ImportSection::new();
1963        section.import("", "", EntityType::Function(0));
1964        shim.section(&section);
1965        shim.section(&StartSection { function_index: 0 });
1966
1967        // Declare the core module within the component, create a dummy core
1968        // instance with one export of our `_initialize` function, and then use
1969        // that to instantiate the module we emit to run the `start` function in
1970        // core wasm to run `_initialize`.
1971        let shim_module_index = self.component.core_module(&shim);
1972        let shim_args_instance_index =
1973            self.component
1974                .core_instantiate_exports([("", ExportKind::Func, initialize_index)]);
1975        self.component.core_instantiate(
1976            shim_module_index,
1977            [("", ModuleArg::Instance(shim_args_instance_index))],
1978        );
1979        Ok(())
1980    }
1981
1982    /// Convenience function to go from `CustomModule` to the instance index
1983    /// corresponding to what that points to.
1984    fn instance_for(&self, module: CustomModule) -> u32 {
1985        match module {
1986            CustomModule::Main => self.instance_index.expect("instantiated by now"),
1987            CustomModule::Adapter(name) => self.adapter_instances[name],
1988        }
1989    }
1990
1991    /// Convenience function to go from `CustomModule` to the module index
1992    /// corresponding to what that points to.
1993    fn module_for(&self, module: CustomModule) -> u32 {
1994        match module {
1995            CustomModule::Main => self.module_index.unwrap(),
1996            CustomModule::Adapter(name) => self.adapter_modules[name],
1997        }
1998    }
1999
2000    /// Convenience function which caches aliases created so repeated calls to
2001    /// this function will all return the same index.
2002    fn core_alias_export(&mut self, instance: u32, name: &str, kind: ExportKind) -> u32 {
2003        *self
2004            .aliased_core_items
2005            .entry((instance, name.to_string()))
2006            .or_insert_with(|| self.component.core_alias_export(instance, name, kind))
2007    }
2008}
2009
2010/// A list of "shims" which start out during the component instantiation process
2011/// as functions which immediately trap due to a `call_indirect`-to-`null` but
2012/// will get filled in by the time the component instantiation process
2013/// completes.
2014///
2015/// Shims currently include:
2016///
2017/// * "Indirect functions" lowered from imported instances where the lowering
2018///   requires an item exported from the main module. These are indirect due to
2019///   the circular dependency between the module needing an import and the
2020///   import needing the module.
2021///
2022/// * Adapter modules which convert from a historical ABI to the component
2023///   model's ABI (e.g. wasi preview1 to preview2) get a shim since the adapters
2024///   are currently indicated as always requiring the memory of the main module.
2025///
2026/// This structure is created by `encode_shim_instantiation`.
2027#[derive(Default)]
2028struct Shims<'a> {
2029    /// The list of all shims that a module will require.
2030    shims: IndexMap<ShimKind<'a>, Shim<'a>>,
2031}
2032
2033struct Shim<'a> {
2034    /// Canonical ABI options required by this shim, used during `canon lower`
2035    /// operations.
2036    options: RequiredOptions,
2037
2038    /// The name, in the shim instance, of this shim.
2039    ///
2040    /// Currently this is `"0"`, `"1"`, ...
2041    name: String,
2042
2043    /// A human-readable debugging name for this shim, used in a core wasm
2044    /// `name` section.
2045    debug_name: String,
2046
2047    /// Precise information about what this shim is a lowering of.
2048    kind: ShimKind<'a>,
2049
2050    /// Wasm type of this shim.
2051    sig: WasmSignature,
2052}
2053
2054/// Which variation of `{stream|future}.{read|write}` we're emitting for a
2055/// `ShimKind::PayloadFunc`.
2056#[derive(Debug, Clone, Hash, Eq, PartialEq)]
2057enum PayloadFuncKind {
2058    FutureWrite,
2059    FutureRead,
2060    StreamWrite,
2061    StreamRead,
2062}
2063
2064#[derive(Debug, Clone, Hash, Eq, PartialEq)]
2065enum ShimKind<'a> {
2066    /// This shim is a late indirect lowering of an imported function in a
2067    /// component which is only possible after prior core wasm modules are
2068    /// instantiated so their memories and functions are available.
2069    IndirectLowering {
2070        /// The name of the interface that's being lowered.
2071        interface: Option<String>,
2072        /// The index within the `lowerings` array of the function being lowered.
2073        index: usize,
2074        /// Which instance to pull the `realloc` function from, if necessary.
2075        realloc: CustomModule<'a>,
2076        /// The string encoding that this lowering is going to use.
2077        encoding: StringEncoding,
2078    },
2079    /// This shim is a core wasm function defined in an adapter module but isn't
2080    /// available until the adapter module is itself instantiated.
2081    Adapter {
2082        /// The name of the adapter module this shim comes from.
2083        adapter: &'a str,
2084        /// The name of the export in the adapter module this shim points to.
2085        func: &'a str,
2086    },
2087    /// A shim used as the destructor for a resource which allows defining the
2088    /// resource before the core module being instantiated.
2089    ResourceDtor {
2090        /// Which instance to pull the destructor function from.
2091        module: CustomModule<'a>,
2092        /// The exported function name of this destructor in the core module.
2093        export: &'a str,
2094    },
2095    /// A shim used for a `{stream|future}.{read|write}` built-in function,
2096    /// which must refer to the core module instance's memory from/to which
2097    /// payload values must be lifted/lowered.
2098    PayloadFunc {
2099        /// Which instance to pull the `realloc` function and string encoding
2100        /// from, if necessary.
2101        for_module: CustomModule<'a>,
2102        /// Additional information regarding the function where this `stream` or
2103        /// `future` type appeared, which we use in combination with
2104        /// `for_module` to determine which `realloc` and string encoding to
2105        /// use, as well as which type to specify when emitting the built-in.
2106        info: &'a PayloadInfo,
2107        /// Which variation of `{stream|future}.{read|write}` we're emitting.
2108        kind: PayloadFuncKind,
2109    },
2110    /// A shim used for the `waitable-set.wait` built-in function, which must
2111    /// refer to the core module instance's memory to which results will be
2112    /// written.
2113    WaitableSetWait { async_: bool },
2114    /// A shim used for the `waitable-set.poll` built-in function, which must
2115    /// refer to the core module instance's memory to which results will be
2116    /// written.
2117    WaitableSetPoll { async_: bool },
2118    /// Shim for `task.return` to handle a reference to a `memory` which may
2119    TaskReturn {
2120        /// The interface (optional) that owns `func` below. If `None` then it's
2121        /// a world export.
2122        interface: Option<InterfaceId>,
2123        /// The function that this `task.return` is returning for, owned
2124        /// within `interface` above.
2125        func: &'a str,
2126        /// The WIT type that `func` returns.
2127        result: Option<Type>,
2128        /// Which instance to pull the `realloc` function from, if necessary.
2129        for_module: CustomModule<'a>,
2130        /// String encoding to use in the ABI options.
2131        encoding: StringEncoding,
2132    },
2133    /// A shim used for the `error-context.new` built-in function, which must
2134    /// refer to the core module instance's memory from which the debug message
2135    /// will be read.
2136    ErrorContextNew {
2137        /// String encoding to use when lifting the debug message.
2138        encoding: StringEncoding,
2139    },
2140    /// A shim used for the `error-context.debug-message` built-in function,
2141    /// which must refer to the core module instance's memory to which results
2142    /// will be written.
2143    ErrorContextDebugMessage {
2144        /// Which instance to pull the `realloc` function from, if necessary.
2145        for_module: CustomModule<'a>,
2146        /// The string encoding to use when lowering the debug message.
2147        encoding: StringEncoding,
2148    },
2149}
2150
2151/// Indicator for which module is being used for a lowering or where options
2152/// like `realloc` are drawn from.
2153///
2154/// This is necessary for situations such as an imported function being lowered
2155/// into the main module and additionally into an adapter module. For example an
2156/// adapter might adapt from preview1 to preview2 for the standard library of a
2157/// programming language but the main module's custom application code may also
2158/// explicitly import from preview2. These two different lowerings of a preview2
2159/// function are parameterized by this enumeration.
2160#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
2161enum CustomModule<'a> {
2162    /// This points to the "main module" which is generally the "output of LLVM"
2163    /// or what a user wrote.
2164    Main,
2165    /// This is selecting an adapter module, identified by name here, where
2166    /// something is being lowered into.
2167    Adapter(&'a str),
2168}
2169
2170impl<'a> Shims<'a> {
2171    /// Adds all shims necessary for the instantiation of `for_module`.
2172    ///
2173    /// This function will iterate over all the imports required by this module
2174    /// and for those that require a shim they're registered here.
2175    fn append_indirect(
2176        &mut self,
2177        world: &'a ComponentWorld<'a>,
2178        for_module: CustomModule<'a>,
2179    ) -> Result<()> {
2180        let module_imports = world.imports_for(for_module);
2181        let module_exports = world.exports_for(for_module);
2182        let resolve = &world.encoder.metadata.resolve;
2183
2184        for (module, field, import) in module_imports.imports() {
2185            match import {
2186                // These imports don't require shims, they can be satisfied
2187                // as-needed when required.
2188                Import::ImportedResourceDrop(..)
2189                | Import::MainModuleMemory
2190                | Import::MainModuleExport { .. }
2191                | Import::Item(_)
2192                | Import::ExportedResourceDrop(..)
2193                | Import::ExportedResourceRep(..)
2194                | Import::ExportedResourceNew(..)
2195                | Import::ExportedTaskCancel
2196                | Import::ErrorContextDrop
2197                | Import::BackpressureSet
2198                | Import::Yield { .. }
2199                | Import::SubtaskDrop
2200                | Import::SubtaskCancel { .. }
2201                | Import::FutureNew(..)
2202                | Import::StreamNew(..)
2203                | Import::FutureCancelRead { .. }
2204                | Import::FutureCancelWrite { .. }
2205                | Import::FutureCloseWritable { .. }
2206                | Import::FutureCloseReadable { .. }
2207                | Import::StreamCancelRead { .. }
2208                | Import::StreamCancelWrite { .. }
2209                | Import::StreamCloseWritable { .. }
2210                | Import::StreamCloseReadable { .. }
2211                | Import::WaitableSetNew
2212                | Import::WaitableSetDrop
2213                | Import::WaitableJoin
2214                | Import::ContextGet(_)
2215                | Import::ContextSet(_) => {}
2216
2217                // If `task.return` needs to be indirect then generate a shim
2218                // for it, otherwise skip the shim and let it get materialized
2219                // naturally later.
2220                Import::ExportedTaskReturn(key, interface, func, ty) => {
2221                    let (options, sig) = task_return_options_and_type(resolve, *ty);
2222                    if options.is_empty() {
2223                        continue;
2224                    }
2225                    let name = self.shims.len().to_string();
2226                    let encoding = world
2227                        .module_metadata_for(for_module)
2228                        .export_encodings
2229                        .get(resolve, key, func)
2230                        .ok_or_else(|| {
2231                            anyhow::anyhow!(
2232                                "missing component metadata for export of \
2233                                `{module}::{field}`"
2234                            )
2235                        })?;
2236                    self.push(Shim {
2237                        name,
2238                        debug_name: format!("task-return-{func}"),
2239                        options,
2240                        kind: ShimKind::TaskReturn {
2241                            interface: *interface,
2242                            func,
2243                            result: *ty,
2244                            for_module,
2245                            encoding,
2246                        },
2247                        sig,
2248                    });
2249                }
2250
2251                Import::FutureWrite { async_, info } => {
2252                    self.append_indirect_payload_push(
2253                        resolve,
2254                        for_module,
2255                        module,
2256                        *async_,
2257                        info,
2258                        PayloadFuncKind::FutureWrite,
2259                        vec![WasmType::I32; 2],
2260                        vec![WasmType::I32],
2261                    );
2262                }
2263                Import::FutureRead { async_, info } => {
2264                    self.append_indirect_payload_push(
2265                        resolve,
2266                        for_module,
2267                        module,
2268                        *async_,
2269                        info,
2270                        PayloadFuncKind::FutureRead,
2271                        vec![WasmType::I32; 2],
2272                        vec![WasmType::I32],
2273                    );
2274                }
2275                Import::StreamWrite { async_, info } => {
2276                    self.append_indirect_payload_push(
2277                        resolve,
2278                        for_module,
2279                        module,
2280                        *async_,
2281                        info,
2282                        PayloadFuncKind::StreamWrite,
2283                        vec![WasmType::I32; 3],
2284                        vec![WasmType::I32],
2285                    );
2286                }
2287                Import::StreamRead { async_, info } => {
2288                    self.append_indirect_payload_push(
2289                        resolve,
2290                        for_module,
2291                        module,
2292                        *async_,
2293                        info,
2294                        PayloadFuncKind::StreamRead,
2295                        vec![WasmType::I32; 3],
2296                        vec![WasmType::I32],
2297                    );
2298                }
2299
2300                Import::WaitableSetWait { async_ } => {
2301                    let name = self.shims.len().to_string();
2302                    self.push(Shim {
2303                        name,
2304                        debug_name: "waitable-set.wait".to_string(),
2305                        options: RequiredOptions::empty(),
2306                        kind: ShimKind::WaitableSetWait { async_: *async_ },
2307                        sig: WasmSignature {
2308                            params: vec![WasmType::I32; 2],
2309                            results: vec![WasmType::I32],
2310                            indirect_params: false,
2311                            retptr: false,
2312                        },
2313                    });
2314                }
2315
2316                Import::WaitableSetPoll { async_ } => {
2317                    let name = self.shims.len().to_string();
2318                    self.push(Shim {
2319                        name,
2320                        debug_name: "waitable-set.poll".to_string(),
2321                        options: RequiredOptions::empty(),
2322                        kind: ShimKind::WaitableSetPoll { async_: *async_ },
2323                        sig: WasmSignature {
2324                            params: vec![WasmType::I32; 2],
2325                            results: vec![WasmType::I32],
2326                            indirect_params: false,
2327                            retptr: false,
2328                        },
2329                    });
2330                }
2331
2332                Import::ErrorContextNew { encoding } => {
2333                    let name = self.shims.len().to_string();
2334                    self.push(Shim {
2335                        name,
2336                        debug_name: "error-new".to_string(),
2337                        options: RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING,
2338                        kind: ShimKind::ErrorContextNew {
2339                            encoding: *encoding,
2340                        },
2341                        sig: WasmSignature {
2342                            params: vec![WasmType::I32; 2],
2343                            results: vec![WasmType::I32],
2344                            indirect_params: false,
2345                            retptr: false,
2346                        },
2347                    });
2348                }
2349
2350                Import::ErrorContextDebugMessage { encoding } => {
2351                    let name = self.shims.len().to_string();
2352                    self.push(Shim {
2353                        name,
2354                        debug_name: "error-debug-message".to_string(),
2355                        options: RequiredOptions::MEMORY
2356                            | RequiredOptions::STRING_ENCODING
2357                            | RequiredOptions::REALLOC,
2358                        kind: ShimKind::ErrorContextDebugMessage {
2359                            for_module,
2360                            encoding: *encoding,
2361                        },
2362                        sig: WasmSignature {
2363                            params: vec![WasmType::I32; 2],
2364                            results: vec![],
2365                            indirect_params: false,
2366                            retptr: false,
2367                        },
2368                    });
2369                }
2370
2371                // Adapter imports into the main module must got through an
2372                // indirection, so that's registered here.
2373                Import::AdapterExport(ty) => {
2374                    let name = self.shims.len().to_string();
2375                    log::debug!("shim {name} is adapter `{module}::{field}`");
2376                    self.push(Shim {
2377                        name,
2378                        debug_name: format!("adapt-{module}-{field}"),
2379                        // Pessimistically assume that all adapters require
2380                        // memory in one form or another. While this isn't
2381                        // technically true it's true enough for WASI.
2382                        options: RequiredOptions::MEMORY,
2383                        kind: ShimKind::Adapter {
2384                            adapter: module,
2385                            func: field,
2386                        },
2387                        sig: WasmSignature {
2388                            params: ty.params().iter().map(to_wasm_type).collect(),
2389                            results: ty.results().iter().map(to_wasm_type).collect(),
2390                            indirect_params: false,
2391                            retptr: false,
2392                        },
2393                    });
2394
2395                    fn to_wasm_type(ty: &wasmparser::ValType) -> WasmType {
2396                        match ty {
2397                            wasmparser::ValType::I32 => WasmType::I32,
2398                            wasmparser::ValType::I64 => WasmType::I64,
2399                            wasmparser::ValType::F32 => WasmType::F32,
2400                            wasmparser::ValType::F64 => WasmType::F64,
2401                            _ => unreachable!(),
2402                        }
2403                    }
2404                }
2405
2406                // WIT-level functions may require an indirection, so yield some
2407                // metadata out of this `match` to the loop below to figure that
2408                // out.
2409                Import::InterfaceFunc(key, _, name, abi) => {
2410                    self.append_indirect_wit_func(
2411                        world,
2412                        for_module,
2413                        module,
2414                        field,
2415                        key,
2416                        name,
2417                        Some(resolve.name_world_key(key)),
2418                        *abi,
2419                    )?;
2420                }
2421                Import::WorldFunc(key, name, abi) => {
2422                    self.append_indirect_wit_func(
2423                        world, for_module, module, field, key, name, None, *abi,
2424                    )?;
2425                }
2426            }
2427        }
2428
2429        // In addition to all the shims added for imports above this module also
2430        // requires shims for resource destructors that it exports. Resource
2431        // types are declared before the module is instantiated so the actual
2432        // destructor is registered as a shim (defined here) and it's then
2433        // filled in with the module's exports later.
2434        for (export_name, export) in module_exports.iter() {
2435            let id = match export {
2436                Export::ResourceDtor(id) => id,
2437                _ => continue,
2438            };
2439            let resource = resolve.types[*id].name.as_ref().unwrap();
2440            let name = self.shims.len().to_string();
2441            self.push(Shim {
2442                name,
2443                debug_name: format!("dtor-{resource}"),
2444                options: RequiredOptions::empty(),
2445                kind: ShimKind::ResourceDtor {
2446                    module: for_module,
2447                    export: export_name,
2448                },
2449                sig: WasmSignature {
2450                    params: vec![WasmType::I32],
2451                    results: Vec::new(),
2452                    indirect_params: false,
2453                    retptr: false,
2454                },
2455            });
2456        }
2457
2458        Ok(())
2459    }
2460
2461    /// Helper of `append_indirect` above which pushes information for
2462    /// futures/streams read/write intrinsics.
2463    fn append_indirect_payload_push(
2464        &mut self,
2465        resolve: &Resolve,
2466        for_module: CustomModule<'a>,
2467        module: &str,
2468        async_: bool,
2469        info: &'a PayloadInfo,
2470        kind: PayloadFuncKind,
2471        params: Vec<WasmType>,
2472        results: Vec<WasmType>,
2473    ) {
2474        let debug_name = format!("{module}-{}", info.name);
2475        let name = self.shims.len().to_string();
2476
2477        let payload = info.payload(resolve);
2478        let (wit_param, wit_result) = match kind {
2479            PayloadFuncKind::StreamRead | PayloadFuncKind::FutureRead => (None, payload),
2480            PayloadFuncKind::StreamWrite | PayloadFuncKind::FutureWrite => (payload, None),
2481        };
2482        self.push(Shim {
2483            name,
2484            debug_name,
2485            options: RequiredOptions::MEMORY
2486                | RequiredOptions::for_import(
2487                    resolve,
2488                    &Function {
2489                        name: String::new(),
2490                        kind: FunctionKind::Freestanding,
2491                        params: match wit_param {
2492                            Some(ty) => vec![("a".to_string(), ty)],
2493                            None => Vec::new(),
2494                        },
2495                        result: wit_result,
2496                        docs: Default::default(),
2497                        stability: Stability::Unknown,
2498                    },
2499                    if async_ {
2500                        AbiVariant::GuestImportAsync
2501                    } else {
2502                        AbiVariant::GuestImport
2503                    },
2504                ),
2505            kind: ShimKind::PayloadFunc {
2506                for_module,
2507                info,
2508                kind,
2509            },
2510            sig: WasmSignature {
2511                params,
2512                results,
2513                indirect_params: false,
2514                retptr: false,
2515            },
2516        });
2517    }
2518
2519    /// Helper for `append_indirect` above which will conditionally push a shim
2520    /// for the WIT function specified by `interface_key`, `name`, and `abi`.
2521    fn append_indirect_wit_func(
2522        &mut self,
2523        world: &'a ComponentWorld<'a>,
2524        for_module: CustomModule<'a>,
2525        module: &str,
2526        field: &str,
2527        key: &WorldKey,
2528        name: &String,
2529        interface_key: Option<String>,
2530        abi: AbiVariant,
2531    ) -> Result<()> {
2532        let resolve = &world.encoder.metadata.resolve;
2533        let metadata = world.module_metadata_for(for_module);
2534        let interface = &world.import_map[&interface_key];
2535        let (index, _, lowering) = interface.lowerings.get_full(&(name.clone(), abi)).unwrap();
2536        let shim_name = self.shims.len().to_string();
2537        match lowering {
2538            Lowering::Direct | Lowering::ResourceDrop(_) => {}
2539
2540            Lowering::Indirect { sig, options } => {
2541                log::debug!(
2542                    "shim {shim_name} is import `{module}::{field}` lowering {index} `{name}`",
2543                );
2544                let encoding = metadata
2545                    .import_encodings
2546                    .get(resolve, key, name)
2547                    .ok_or_else(|| {
2548                        anyhow::anyhow!(
2549                            "missing component metadata for import of \
2550                                `{module}::{field}`"
2551                        )
2552                    })?;
2553                self.push(Shim {
2554                    name: shim_name,
2555                    debug_name: format!("indirect-{module}-{field}"),
2556                    options: *options,
2557                    kind: ShimKind::IndirectLowering {
2558                        interface: interface_key,
2559                        index,
2560                        realloc: for_module,
2561                        encoding,
2562                    },
2563                    sig: sig.clone(),
2564                });
2565            }
2566        }
2567
2568        Ok(())
2569    }
2570
2571    fn push(&mut self, shim: Shim<'a>) {
2572        // Only one shim per `ShimKind` is retained, so if it's already present
2573        // don't overwrite it. If it's not present though go ahead and insert
2574        // it.
2575        if !self.shims.contains_key(&shim.kind) {
2576            self.shims.insert(shim.kind.clone(), shim);
2577        }
2578    }
2579}
2580
2581fn task_return_options_and_type(
2582    resolve: &Resolve,
2583    ty: Option<Type>,
2584) -> (RequiredOptions, WasmSignature) {
2585    let func_tmp = Function {
2586        name: String::new(),
2587        kind: FunctionKind::Freestanding,
2588        params: match ty {
2589            Some(ty) => vec![("a".to_string(), ty)],
2590            None => Vec::new(),
2591        },
2592        result: None,
2593        docs: Default::default(),
2594        stability: Stability::Unknown,
2595    };
2596    let abi = AbiVariant::GuestImport;
2597    let options = RequiredOptions::for_import(resolve, &func_tmp, abi);
2598    let sig = resolve.wasm_signature(abi, &func_tmp);
2599    (options, sig)
2600}
2601
2602/// Alias argument to an instantiation
2603#[derive(Clone, Debug)]
2604pub struct Item {
2605    pub alias: String,
2606    pub kind: ExportKind,
2607    pub which: MainOrAdapter,
2608    pub name: String,
2609}
2610
2611/// Module argument to an instantiation
2612#[derive(Debug, PartialEq, Clone)]
2613pub enum MainOrAdapter {
2614    Main,
2615    Adapter(String),
2616}
2617
2618impl MainOrAdapter {
2619    fn to_custom_module(&self) -> CustomModule<'_> {
2620        match self {
2621            MainOrAdapter::Main => CustomModule::Main,
2622            MainOrAdapter::Adapter(s) => CustomModule::Adapter(s),
2623        }
2624    }
2625}
2626
2627/// Module instantiation argument
2628#[derive(Clone)]
2629pub enum Instance {
2630    /// Module argument
2631    MainOrAdapter(MainOrAdapter),
2632
2633    /// Alias argument
2634    Items(Vec<Item>),
2635}
2636
2637/// Provides fine-grained control of how a library module is instantiated
2638/// relative to other module instances
2639#[derive(Clone)]
2640pub struct LibraryInfo {
2641    /// If true, instantiate any shims prior to this module
2642    pub instantiate_after_shims: bool,
2643
2644    /// Instantiation arguments
2645    pub arguments: Vec<(String, Instance)>,
2646}
2647
2648/// Represents an adapter or library to be instantiated as part of the component
2649pub(super) struct Adapter {
2650    /// The wasm of the module itself, with `component-type` sections stripped
2651    wasm: Vec<u8>,
2652
2653    /// The metadata for the adapter
2654    metadata: ModuleMetadata,
2655
2656    /// The set of exports from the final world which are defined by this
2657    /// adapter or library
2658    required_exports: IndexSet<WorldKey>,
2659
2660    /// If present, treat this module as a library rather than a "minimal" adapter
2661    ///
2662    /// TODO: We should refactor how various flavors of module are represented
2663    /// and differentiated to avoid mistaking one for another.
2664    library_info: Option<LibraryInfo>,
2665}
2666
2667/// An encoder of components based on `wit` interface definitions.
2668#[derive(Default)]
2669pub struct ComponentEncoder {
2670    module: Vec<u8>,
2671    pub(super) metadata: Bindgen,
2672    validate: bool,
2673    pub(super) main_module_exports: IndexSet<WorldKey>,
2674    pub(super) adapters: IndexMap<String, Adapter>,
2675    import_name_map: HashMap<String, String>,
2676    realloc_via_memory_grow: bool,
2677    merge_imports_based_on_semver: Option<bool>,
2678    pub(super) reject_legacy_names: bool,
2679}
2680
2681impl ComponentEncoder {
2682    /// Set the core module to encode as a component.
2683    /// This method will also parse any component type information stored in custom sections
2684    /// inside the module, and add them as the interface, imports, and exports.
2685    /// It will also add any producers information inside the component type information to the
2686    /// core module.
2687    pub fn module(mut self, module: &[u8]) -> Result<Self> {
2688        let (wasm, metadata) = self.decode(module)?;
2689        let exports = self
2690            .merge_metadata(metadata)
2691            .context("failed merge WIT metadata for module with previous metadata")?;
2692        self.main_module_exports.extend(exports);
2693        self.module = if let Some(producers) = &self.metadata.producers {
2694            producers.add_to_wasm(&wasm)?
2695        } else {
2696            wasm.to_vec()
2697        };
2698        Ok(self)
2699    }
2700
2701    fn decode<'a>(&self, wasm: &'a [u8]) -> Result<(Cow<'a, [u8]>, Bindgen)> {
2702        let (bytes, metadata) = metadata::decode(wasm)?;
2703        match bytes {
2704            Some(wasm) => Ok((Cow::Owned(wasm), metadata)),
2705            None => Ok((Cow::Borrowed(wasm), metadata)),
2706        }
2707    }
2708
2709    fn merge_metadata(&mut self, metadata: Bindgen) -> Result<IndexSet<WorldKey>> {
2710        self.metadata.merge(metadata)
2711    }
2712
2713    /// Sets whether or not the encoder will validate its output.
2714    pub fn validate(mut self, validate: bool) -> Self {
2715        self.validate = validate;
2716        self
2717    }
2718
2719    /// Sets whether to merge imports based on semver to the specified value.
2720    ///
2721    /// This affects how when to WIT worlds are merged together, for example
2722    /// from two different libraries, whether their imports are unified when the
2723    /// semver version ranges for interface allow it.
2724    ///
2725    /// This is enabled by default.
2726    pub fn merge_imports_based_on_semver(mut self, merge: bool) -> Self {
2727        self.merge_imports_based_on_semver = Some(merge);
2728        self
2729    }
2730
2731    /// Sets whether to reject the historical mangling/name scheme for core wasm
2732    /// imports/exports as they map to the component model.
2733    ///
2734    /// The `wit-component` crate supported a different set of names prior to
2735    /// WebAssembly/component-model#378 and this can be used to disable this
2736    /// support.
2737    ///
2738    /// This is disabled by default.
2739    pub fn reject_legacy_names(mut self, reject: bool) -> Self {
2740        self.reject_legacy_names = reject;
2741        self
2742    }
2743
2744    /// Specifies a new adapter which is used to translate from a historical
2745    /// wasm ABI to the canonical ABI and the `interface` provided.
2746    ///
2747    /// This is primarily used to polyfill, for example,
2748    /// `wasi_snapshot_preview1` with a component-model using interface. The
2749    /// `name` provided is the module name of the adapter that is being
2750    /// polyfilled, for example `"wasi_snapshot_preview1"`.
2751    ///
2752    /// The `bytes` provided is a core wasm module which implements the `name`
2753    /// interface in terms of the `interface` interface. This core wasm module
2754    /// is severely restricted in its shape, for example it cannot have any data
2755    /// segments or element segments.
2756    ///
2757    /// The `interface` provided is the component-model-using-interface that the
2758    /// wasm module specified by `bytes` imports. The `bytes` will then import
2759    /// `interface` and export functions to get imported from the module `name`
2760    /// in the core wasm that's being wrapped.
2761    pub fn adapter(self, name: &str, bytes: &[u8]) -> Result<Self> {
2762        self.library_or_adapter(name, bytes, None)
2763    }
2764
2765    /// Specifies a shared-everything library to link into the component.
2766    ///
2767    /// Unlike adapters, libraries _may_ have data and/or element segments, but
2768    /// they must operate on an imported memory and table, respectively.  In
2769    /// this case, the correct amount of space is presumed to have been
2770    /// statically allocated in the main module's memory and table at the
2771    /// offsets which the segments target, e.g. as arranged by
2772    /// [super::linking::Linker].
2773    ///
2774    /// Libraries are treated similarly to adapters, except that they are not
2775    /// "minified" the way adapters are, and instantiation is controlled
2776    /// declaratively via the `library_info` parameter.
2777    pub fn library(self, name: &str, bytes: &[u8], library_info: LibraryInfo) -> Result<Self> {
2778        self.library_or_adapter(name, bytes, Some(library_info))
2779    }
2780
2781    fn library_or_adapter(
2782        mut self,
2783        name: &str,
2784        bytes: &[u8],
2785        library_info: Option<LibraryInfo>,
2786    ) -> Result<Self> {
2787        let (wasm, mut metadata) = self.decode(bytes)?;
2788        // Merge the adapter's document into our own document to have one large
2789        // document, and then afterwards merge worlds as well.
2790        //
2791        // Note that the `metadata` tracking import/export encodings is removed
2792        // since this adapter can get different lowerings and is allowed to
2793        // differ from the main module. This is then tracked within the
2794        // `Adapter` structure produced below.
2795        let adapter_metadata = mem::take(&mut metadata.metadata);
2796        let exports = self.merge_metadata(metadata).with_context(|| {
2797            format!("failed to merge WIT packages of adapter `{name}` into main packages")
2798        })?;
2799        if let Some(library_info) = &library_info {
2800            // Validate that all referenced modules can be resolved.
2801            for (_, instance) in &library_info.arguments {
2802                let resolve = |which: &_| match which {
2803                    MainOrAdapter::Main => Ok(()),
2804                    MainOrAdapter::Adapter(name) => {
2805                        if self.adapters.contains_key(name.as_str()) {
2806                            Ok(())
2807                        } else {
2808                            Err(anyhow!("instance refers to unknown adapter `{name}`"))
2809                        }
2810                    }
2811                };
2812
2813                match instance {
2814                    Instance::MainOrAdapter(which) => resolve(which)?,
2815                    Instance::Items(items) => {
2816                        for item in items {
2817                            resolve(&item.which)?;
2818                        }
2819                    }
2820                }
2821            }
2822        }
2823        self.adapters.insert(
2824            name.to_string(),
2825            Adapter {
2826                wasm: wasm.to_vec(),
2827                metadata: adapter_metadata,
2828                required_exports: exports,
2829                library_info,
2830            },
2831        );
2832        Ok(self)
2833    }
2834
2835    /// True if the realloc and stack allocation should use memory.grow
2836    /// The default is to use the main module realloc
2837    /// Can be useful if cabi_realloc cannot be called before the host
2838    /// runtime is initialized.
2839    pub fn realloc_via_memory_grow(mut self, value: bool) -> Self {
2840        self.realloc_via_memory_grow = value;
2841        self
2842    }
2843
2844    /// The instance import name map to use.
2845    ///
2846    /// This is used to rename instance imports in the final component.
2847    ///
2848    /// For example, if there is an instance import `foo:bar/baz` and it is
2849    /// desired that the import actually be an `unlocked-dep` name, then
2850    /// `foo:bar/baz` can be mapped to `unlocked-dep=<a:b/c@{>=x.y.z}>`.
2851    ///
2852    /// Note: the replacement names are not validated during encoding unless
2853    /// the `validate` option is set to true.
2854    pub fn import_name_map(mut self, map: HashMap<String, String>) -> Self {
2855        self.import_name_map = map;
2856        self
2857    }
2858
2859    /// Encode the component and return the bytes.
2860    pub fn encode(&mut self) -> Result<Vec<u8>> {
2861        if self.module.is_empty() {
2862            bail!("a module is required when encoding a component");
2863        }
2864
2865        if self.merge_imports_based_on_semver.unwrap_or(true) {
2866            self.metadata
2867                .resolve
2868                .merge_world_imports_based_on_semver(self.metadata.world)?;
2869        }
2870
2871        let world = ComponentWorld::new(self).context("failed to decode world from module")?;
2872        let mut state = EncodingState {
2873            component: ComponentBuilder::default(),
2874            module_index: None,
2875            instance_index: None,
2876            memory_index: None,
2877            shim_instance_index: None,
2878            fixups_module_index: None,
2879            adapter_modules: IndexMap::new(),
2880            adapter_instances: IndexMap::new(),
2881            import_type_map: HashMap::new(),
2882            import_func_type_map: HashMap::new(),
2883            export_type_map: HashMap::new(),
2884            export_func_type_map: HashMap::new(),
2885            imported_instances: Default::default(),
2886            imported_funcs: Default::default(),
2887            exported_instances: Default::default(),
2888            aliased_core_items: Default::default(),
2889            info: &world,
2890        };
2891        state.encode_imports(&self.import_name_map)?;
2892        state.encode_core_modules();
2893        state.encode_core_instantiation()?;
2894        state.encode_exports(CustomModule::Main)?;
2895        for name in self.adapters.keys() {
2896            state.encode_exports(CustomModule::Adapter(name))?;
2897        }
2898        state
2899            .component
2900            .raw_custom_section(&crate::base_producers().raw_custom_section());
2901        let bytes = state.component.finish();
2902
2903        if self.validate {
2904            Validator::new_with_features(WasmFeatures::all())
2905                .validate_all(&bytes)
2906                .context("failed to validate component output")?;
2907        }
2908
2909        Ok(bytes)
2910    }
2911}
2912
2913impl ComponentWorld<'_> {
2914    /// Convenience function to lookup a module's import map.
2915    fn imports_for(&self, module: CustomModule) -> &ImportMap {
2916        match module {
2917            CustomModule::Main => &self.info.imports,
2918            CustomModule::Adapter(name) => &self.adapters[name].info.imports,
2919        }
2920    }
2921
2922    /// Convenience function to lookup a module's export map.
2923    fn exports_for(&self, module: CustomModule) -> &ExportMap {
2924        match module {
2925            CustomModule::Main => &self.info.exports,
2926            CustomModule::Adapter(name) => &self.adapters[name].info.exports,
2927        }
2928    }
2929
2930    /// Convenience function to lookup a module's metadata.
2931    fn module_metadata_for(&self, module: CustomModule) -> &ModuleMetadata {
2932        match module {
2933            CustomModule::Main => &self.encoder.metadata.metadata,
2934            CustomModule::Adapter(name) => &self.encoder.adapters[name].metadata,
2935        }
2936    }
2937}
2938
2939#[cfg(all(test, feature = "dummy-module"))]
2940mod test {
2941    use super::*;
2942    use crate::{dummy_module, embed_component_metadata};
2943    use wit_parser::ManglingAndAbi;
2944
2945    #[test]
2946    fn it_renames_imports() {
2947        let mut resolve = Resolve::new();
2948        let pkg = resolve
2949            .push_str(
2950                "test.wit",
2951                r#"
2952package test:wit;
2953
2954interface i {
2955    f: func();
2956}
2957
2958world test {
2959    import i;
2960    import foo: interface {
2961        f: func();
2962    }
2963}
2964"#,
2965            )
2966            .unwrap();
2967        let world = resolve.select_world(pkg, None).unwrap();
2968
2969        let mut module = dummy_module(&resolve, world, ManglingAndAbi::Standard32);
2970
2971        embed_component_metadata(&mut module, &resolve, world, StringEncoding::UTF8).unwrap();
2972
2973        let encoded = ComponentEncoder::default()
2974            .import_name_map(HashMap::from([
2975                (
2976                    "foo".to_string(),
2977                    "unlocked-dep=<foo:bar/foo@{>=1.0.0 <1.1.0}>".to_string(),
2978                ),
2979                (
2980                    "test:wit/i".to_string(),
2981                    "locked-dep=<foo:bar/i@1.2.3>".to_string(),
2982                ),
2983            ]))
2984            .module(&module)
2985            .unwrap()
2986            .validate(true)
2987            .encode()
2988            .unwrap();
2989
2990        let wat = wasmprinter::print_bytes(encoded).unwrap();
2991        assert!(wat.contains("unlocked-dep=<foo:bar/foo@{>=1.0.0 <1.1.0}>"));
2992        assert!(wat.contains("locked-dep=<foo:bar/i@1.2.3>"));
2993    }
2994}