Coverage Report

Created: 2026-11-23 07:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasm-tools/crates/wit-component/src/encoding.rs
Line
Count
Source
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
74
use crate::StringEncoding;
75
use crate::encoding::wit::{component_extern_name, interface_extern_name};
76
use crate::metadata::{self, Bindgen, ModuleMetadata};
77
use crate::validation::{
78
    Export, ExportMap, Import, ImportInstance, ImportMap, PayloadInfo, PayloadType,
79
};
80
use anyhow::{Context, Result, anyhow, bail};
81
use indexmap::{IndexMap, IndexSet};
82
use std::borrow::Cow;
83
use std::collections::HashMap;
84
use std::hash::Hash;
85
use std::mem;
86
use wasm_encoder::reencode::{Reencode, RoundtripReencoder};
87
use wasm_encoder::*;
88
use wasmparser::{Validator, WasmFeatures};
89
use wit_parser::{
90
    Function, FunctionKind, InterfaceId, LiveTypes, Param, Resolve, Stability, Type, TypeDefKind,
91
    TypeId, TypeOwner, WorldId, WorldItem, WorldKey,
92
    abi::{AbiVariant, WasmSignature, WasmType},
93
};
94
95
const INDIRECT_TABLE_NAME: &str = "$imports";
96
const SHIM_MEMORY_NAME: &str = "$memory";
97
const TLS_BASE_GET: &str = "$get-tls-base";
98
const TLS_BASE_SET: &str = "$set-tls-base";
99
100
pub(crate) mod fixup;
101
102
mod wit;
103
pub use wit::{encode, encode_world};
104
105
mod types;
106
use types::{InstanceTypeEncoder, RootTypeEncoder, TypeEncodingMaps, ValtypeEncoder};
107
mod world;
108
use world::{ComponentWorld, ImportedInterface, Lowering};
109
110
mod dedupe;
111
pub(crate) use dedupe::ModuleImportMap;
112
use wasm_metadata::AddMetadataField;
113
114
0
fn to_wasm_type(ty: &wasmparser::ValType) -> WasmType {
115
0
    match ty {
116
0
        wasmparser::ValType::I32 => WasmType::I32,
117
0
        wasmparser::ValType::I64 => WasmType::I64,
118
0
        wasmparser::ValType::F32 => WasmType::F32,
119
0
        wasmparser::ValType::F64 => WasmType::F64,
120
0
        _ => unreachable!(),
121
    }
122
0
}
123
124
30.0k
fn import_func_name(f: &Function) -> String {
125
30.0k
    match f.kind {
126
        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
127
18.5k
            format!("import-func-{}", f.item_name())
128
        }
129
130
        // transform `[method]foo.bar` into `import-method-foo-bar` to
131
        // have it be a valid kebab-name which can't conflict with
132
        // anything else.
133
        //
134
        // There's probably a better and more "formal" way to do this
135
        // but quick-and-dirty string manipulation should work well
136
        // enough for now hopefully.
137
        FunctionKind::Getter
138
        | FunctionKind::Setter
139
        | FunctionKind::Method(_)
140
        | FunctionKind::MethodGetter(_)
141
        | FunctionKind::MethodSetter(_)
142
        | FunctionKind::AsyncMethod(_)
143
        | FunctionKind::Static(_)
144
        | FunctionKind::StaticGetter(_)
145
        | FunctionKind::StaticSetter(_)
146
        | FunctionKind::AsyncStatic(_)
147
        | FunctionKind::Constructor(_) => {
148
11.4k
            format!(
149
                "import-{}",
150
11.4k
                f.name.replace('[', "").replace([']', '.'], "-")
151
            )
152
        }
153
    }
154
30.0k
}
155
156
bitflags::bitflags! {
157
    /// Options in the `canon lower` or `canon lift` required for a particular
158
    /// function.
159
    #[derive(Copy, Clone, Debug)]
160
    pub struct RequiredOptions: u8 {
161
        /// A memory must be specified, typically the "main module"'s memory
162
        /// export.
163
        const MEMORY = 1 << 0;
164
        /// A `realloc` function must be specified, typically named
165
        /// `cabi_realloc`.
166
        const REALLOC = 1 << 1;
167
        /// A string encoding must be specified, which is always utf-8 for now
168
        /// today.
169
        const STRING_ENCODING = 1 << 2;
170
        const ASYNC = 1 << 3;
171
    }
172
}
173
174
impl RequiredOptions {
175
17.1k
    fn for_import(
176
17.1k
        resolve: &Resolve,
177
17.1k
        world: WorldId,
178
17.1k
        func: &Function,
179
17.1k
        abi: AbiVariant,
180
17.1k
    ) -> RequiredOptions {
181
17.1k
        let sig = resolve.wasm_signature(world, abi, func);
182
17.1k
        let mut ret = RequiredOptions::empty();
183
        // Lift the params and lower the results for imports
184
17.1k
        ret.add_lift(TypeContents::for_types(
185
17.1k
            resolve,
186
17.1k
            func.params.iter().map(|p| &p.ty),
187
        ));
188
17.1k
        ret.add_lower(TypeContents::for_types(resolve, &func.result));
189
190
        // If anything is indirect then `memory` will be required to read the
191
        // indirect values.
192
17.1k
        if sig.retptr || sig.indirect_params {
193
4.93k
            ret |= RequiredOptions::MEMORY;
194
12.2k
        }
195
17.1k
        if abi == AbiVariant::GuestImportAsync {
196
5.92k
            ret |= RequiredOptions::ASYNC;
197
11.2k
        }
198
17.1k
        ret
199
17.1k
    }
200
201
15.5k
    fn for_export(
202
15.5k
        resolve: &Resolve,
203
15.5k
        world: WorldId,
204
15.5k
        func: &Function,
205
15.5k
        abi: AbiVariant,
206
15.5k
    ) -> RequiredOptions {
207
15.5k
        let sig = resolve.wasm_signature(world, abi, func);
208
15.5k
        let mut ret = RequiredOptions::empty();
209
        // Lower the params and lift the results for exports
210
15.5k
        ret.add_lower(TypeContents::for_types(
211
15.5k
            resolve,
212
15.5k
            func.params.iter().map(|p| &p.ty),
213
        ));
214
15.5k
        ret.add_lift(TypeContents::for_types(resolve, &func.result));
215
216
        // If anything is indirect then `memory` will be required to read the
217
        // indirect values, but if the arguments are indirect then `realloc` is
218
        // additionally required to allocate space for the parameters.
219
15.5k
        if sig.retptr || sig.indirect_params {
220
2.59k
            ret |= RequiredOptions::MEMORY;
221
2.59k
            if sig.indirect_params {
222
555
                ret |= RequiredOptions::REALLOC;
223
2.03k
            }
224
12.9k
        }
225
15.5k
        if let AbiVariant::GuestExportAsync | AbiVariant::GuestExportAsyncStackful = abi {
226
1.86k
            ret |= RequiredOptions::ASYNC;
227
1.86k
            ret |= task_return_options_and_type(resolve, world, func).0;
228
13.6k
        }
229
15.5k
        ret
230
15.5k
    }
231
232
5.34k
    fn for_payload(
233
5.34k
        resolve: &Resolve,
234
5.34k
        world: WorldId,
235
5.34k
        info: &PayloadInfo,
236
5.34k
        kind: &PayloadFuncKind,
237
5.34k
        async_: bool,
238
5.34k
    ) -> RequiredOptions {
239
5.34k
        let payload = info.payload(resolve);
240
5.34k
        let (wit_param, wit_result) = match kind {
241
2.67k
            PayloadFuncKind::StreamRead | PayloadFuncKind::FutureRead => (None, payload),
242
2.67k
            PayloadFuncKind::StreamWrite | PayloadFuncKind::FutureWrite => (payload, None),
243
        };
244
        RequiredOptions::MEMORY
245
5.34k
            | RequiredOptions::for_import(
246
5.34k
                resolve,
247
5.34k
                world,
248
                &Function {
249
5.34k
                    name: String::new(),
250
5.34k
                    kind: FunctionKind::Freestanding,
251
5.34k
                    params: match wit_param {
252
1.62k
                        Some(ty) => vec![Param {
253
1.62k
                            name: "a".to_string(),
254
1.62k
                            ty,
255
1.62k
                            span: Default::default(),
256
1.62k
                        }],
257
3.71k
                        None => Vec::new(),
258
                    },
259
5.34k
                    result: wit_result,
260
5.34k
                    docs: Default::default(),
261
5.34k
                    stability: Stability::Unknown,
262
5.34k
                    span: Default::default(),
263
5.34k
                    external_id: None,
264
                },
265
5.34k
                if async_ {
266
5.34k
                    AbiVariant::GuestImportAsync
267
                } else {
268
0
                    AbiVariant::GuestImport
269
                },
270
            )
271
5.34k
    }
272
273
32.6k
    fn add_lower(&mut self, types: TypeContents) {
274
        // If lists/strings are lowered into wasm then memory is required as
275
        // usual but `realloc` is also required to allow the external caller to
276
        // allocate space in the destination for the list/string.
277
32.6k
        if types.contains(TypeContents::NEEDS_MEMORY) {
278
228
            *self |= RequiredOptions::MEMORY | RequiredOptions::REALLOC;
279
32.4k
        }
280
32.6k
        if types.contains(TypeContents::STRING) {
281
1.03k
            *self |= RequiredOptions::MEMORY
282
1.03k
                | RequiredOptions::STRING_ENCODING
283
1.03k
                | RequiredOptions::REALLOC;
284
31.6k
        }
285
32.6k
    }
286
287
32.6k
    fn add_lift(&mut self, types: TypeContents) {
288
        // Unlike for `lower` when lifting a string/list all that's needed is
289
        // memory, since the string/list already resides in memory `realloc`
290
        // isn't needed.
291
32.6k
        if types.contains(TypeContents::NEEDS_MEMORY) {
292
282
            *self |= RequiredOptions::MEMORY;
293
32.3k
        }
294
32.6k
        if types.contains(TypeContents::STRING) {
295
857
            *self |= RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING;
296
31.8k
        }
297
32.6k
    }
298
299
25.0k
    fn into_iter(
300
25.0k
        self,
301
25.0k
        encoding: StringEncoding,
302
25.0k
        memory_index: Option<u32>,
303
25.0k
        realloc_index: Option<u32>,
304
25.0k
    ) -> Result<impl ExactSizeIterator<Item = CanonicalOption>> {
305
        #[derive(Default)]
306
        struct Iter {
307
            options: [Option<CanonicalOption>; 5],
308
            current: usize,
309
            count: usize,
310
        }
311
312
        impl Iter {
313
18.1k
            fn push(&mut self, option: CanonicalOption) {
314
18.1k
                assert!(self.count < self.options.len());
315
18.1k
                self.options[self.count] = Some(option);
316
18.1k
                self.count += 1;
317
18.1k
            }
318
        }
319
320
        impl Iterator for Iter {
321
            type Item = CanonicalOption;
322
323
43.1k
            fn next(&mut self) -> Option<Self::Item> {
324
43.1k
                if self.current == self.count {
325
25.0k
                    return None;
326
18.1k
                }
327
18.1k
                let option = self.options[self.current];
328
18.1k
                self.current += 1;
329
18.1k
                option
330
43.1k
            }
331
332
10.3k
            fn size_hint(&self) -> (usize, Option<usize>) {
333
10.3k
                (self.count - self.current, Some(self.count - self.current))
334
10.3k
            }
335
        }
336
337
        impl ExactSizeIterator for Iter {}
338
339
25.0k
        let mut iter = Iter::default();
340
341
25.0k
        if self.contains(RequiredOptions::MEMORY) {
342
9.01k
            iter.push(CanonicalOption::Memory(memory_index.ok_or_else(|| {
343
0
                anyhow!("module does not export a memory named `memory`")
344
0
            })?));
345
15.9k
        }
346
347
25.0k
        if self.contains(RequiredOptions::REALLOC) {
348
1.47k
            iter.push(CanonicalOption::Realloc(realloc_index.ok_or_else(
349
0
                || anyhow!("module does not export a function named `cabi_realloc`"),
350
0
            )?));
351
23.5k
        }
352
353
25.0k
        if self.contains(RequiredOptions::STRING_ENCODING) {
354
1.65k
            iter.push(encoding.into());
355
23.3k
        }
356
357
25.0k
        if self.contains(RequiredOptions::ASYNC) {
358
6.01k
            iter.push(CanonicalOption::Async);
359
18.9k
        }
360
361
25.0k
        Ok(iter)
362
25.0k
    }
363
}
364
365
bitflags::bitflags! {
366
    /// Flags about what kinds of types are present within the recursive
367
    /// structure of a type.
368
    struct TypeContents: u8 {
369
        const STRING = 1 << 0;
370
        const NEEDS_MEMORY = 1 << 1;
371
    }
372
}
373
374
impl TypeContents {
375
94.4k
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
94.4k
        let mut cur = TypeContents::empty();
377
272k
        for ty in types {
378
272k
            cur |= Self::for_type(resolve, ty);
379
272k
        }
380
94.4k
        cur
381
94.4k
    }
<wit_component::encoding::TypeContents>::for_types::<core::slice::iter::Iter<wit_parser::Type>>
Line
Count
Source
375
28.9k
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
28.9k
        let mut cur = TypeContents::empty();
377
134k
        for ty in types {
378
134k
            cur |= Self::for_type(resolve, ty);
379
134k
        }
380
28.9k
        cur
381
28.9k
    }
<wit_component::encoding::TypeContents>::for_types::<core::iter::adapters::map::Map<core::slice::iter::Iter<wit_parser::Field>, <wit_component::encoding::TypeContents>::for_type::{closure#0}>>
Line
Count
Source
375
101
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
101
        let mut cur = TypeContents::empty();
377
259
        for ty in types {
378
259
            cur |= Self::for_type(resolve, ty);
379
259
        }
380
101
        cur
381
101
    }
<wit_component::encoding::TypeContents>::for_types::<core::iter::adapters::map::Map<core::slice::iter::Iter<wit_parser::Param>, <wit_component::encoding::RequiredOptions>::for_export::{closure#0}>>
Line
Count
Source
375
15.5k
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
15.5k
        let mut cur = TypeContents::empty();
377
69.9k
        for ty in types {
378
69.9k
            cur |= Self::for_type(resolve, ty);
379
69.9k
        }
380
15.5k
        cur
381
15.5k
    }
<wit_component::encoding::TypeContents>::for_types::<core::iter::adapters::map::Map<core::slice::iter::Iter<wit_parser::Param>, <wit_component::encoding::RequiredOptions>::for_import::{closure#0}>>
Line
Count
Source
375
17.1k
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
17.1k
        let mut cur = TypeContents::empty();
377
40.7k
        for ty in types {
378
40.7k
            cur |= Self::for_type(resolve, ty);
379
40.7k
        }
380
17.1k
        cur
381
17.1k
    }
<wit_component::encoding::TypeContents>::for_types::<core::iter::adapters::flatten::Flatten<core::iter::adapters::map::Map<core::slice::iter::Iter<wit_parser::Case>, <wit_component::encoding::TypeContents>::for_type::{closure#1}>>>
Line
Count
Source
375
73
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
73
        let mut cur = TypeContents::empty();
377
507
        for ty in types {
378
507
            cur |= Self::for_type(resolve, ty);
379
507
        }
380
73
        cur
381
73
    }
<wit_component::encoding::TypeContents>::for_types::<&core::option::Option<wit_parser::Type>>
Line
Count
Source
375
32.6k
    fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
376
32.6k
        let mut cur = TypeContents::empty();
377
32.6k
        for ty in types {
378
26.8k
            cur |= Self::for_type(resolve, ty);
379
26.8k
        }
380
32.6k
        cur
381
32.6k
    }
382
383
73
    fn for_optional_types<'a>(
384
73
        resolve: &Resolve,
385
73
        types: impl Iterator<Item = Option<&'a Type>>,
386
73
    ) -> Self {
387
73
        Self::for_types(resolve, types.flatten())
388
73
    }
389
390
55.3k
    fn for_optional_type(resolve: &Resolve, ty: Option<&Type>) -> Self {
391
55.3k
        match ty {
392
52.4k
            Some(ty) => Self::for_type(resolve, ty),
393
2.92k
            None => Self::empty(),
394
        }
395
55.3k
    }
396
397
333k
    fn for_type(resolve: &Resolve, ty: &Type) -> Self {
398
333k
        match ty {
399
85.3k
            Type::Id(id) => match &resolve.types[*id].kind {
400
7.20k
                TypeDefKind::Handle(h) => match h {
401
1.85k
                    wit_parser::Handle::Own(_) => Self::empty(),
402
5.35k
                    wit_parser::Handle::Borrow(_) => Self::empty(),
403
                },
404
0
                TypeDefKind::Resource => Self::empty(),
405
101
                TypeDefKind::Record(r) => Self::for_types(resolve, r.fields.iter().map(|f| &f.ty)),
406
28.9k
                TypeDefKind::Tuple(t) => Self::for_types(resolve, t.types.iter()),
407
40
                TypeDefKind::Flags(_) => Self::empty(),
408
4.87k
                TypeDefKind::Option(t) => Self::for_type(resolve, t),
409
27.6k
                TypeDefKind::Result(r) => {
410
27.6k
                    Self::for_optional_type(resolve, r.ok.as_ref())
411
27.6k
                        | Self::for_optional_type(resolve, r.err.as_ref())
412
                }
413
73
                TypeDefKind::Variant(v) => {
414
592
                    Self::for_optional_types(resolve, v.cases.iter().map(|c| c.ty.as_ref()))
415
                }
416
156
                TypeDefKind::Enum(_) => Self::empty(),
417
2.38k
                TypeDefKind::List(t) => Self::for_type(resolve, t) | Self::NEEDS_MEMORY,
418
0
                TypeDefKind::Map(k, v) => {
419
0
                    Self::for_type(resolve, k) | Self::for_type(resolve, v) | Self::NEEDS_MEMORY
420
                }
421
897
                TypeDefKind::FixedLengthList(t, _elements) => Self::for_type(resolve, t),
422
282
                TypeDefKind::Type(t) => Self::for_type(resolve, t),
423
10.7k
                TypeDefKind::Future(_) => Self::empty(),
424
1.89k
                TypeDefKind::Stream(_) => Self::empty(),
425
0
                TypeDefKind::Unknown => unreachable!(),
426
            },
427
3.18k
            Type::String => Self::STRING,
428
244k
            _ => Self::empty(),
429
        }
430
333k
    }
431
}
432
433
/// State relating to encoding a component.
434
pub struct EncodingState<'a> {
435
    /// The component being encoded.
436
    component: ComponentBuilder,
437
    /// The index into the core module index space for the inner core module.
438
    ///
439
    /// If `None`, the core module has not been encoded.
440
    module_index: Option<u32>,
441
    /// The index into the core instance index space for the inner core module.
442
    ///
443
    /// If `None`, the core module has not been instantiated.
444
    instance_index: Option<u32>,
445
    /// The index in the core memory index space for the exported memory.
446
    ///
447
    /// If `None`, then the memory has not yet been aliased.
448
    memory_index: Option<u32>,
449
    /// The index of the shim instance used for lowering imports into the core instance.
450
    ///
451
    /// If `None`, then the shim instance how not yet been encoded.
452
    shim_instance_index: Option<u32>,
453
454
    /// A map of named adapter modules and the index that the module was defined
455
    /// at.
456
    adapter_modules: IndexMap<&'a str, u32>,
457
    /// A map of adapter module instances and the index of their instance.
458
    adapter_instances: IndexMap<&'a str, u32>,
459
460
    /// Imported/exported instances and what index they were imported as.
461
    instances: IndexMap<InterfaceId, u32>,
462
    imported_funcs: IndexMap<String, u32>,
463
464
    /// Maps used when translating types to the component model binary format.
465
    /// Note that imports and exports are stored in separate maps since they
466
    /// need fresh hierarchies of types in case the same interface is both
467
    /// imported and exported.
468
    type_encoding_maps: TypeEncodingMaps<'a>,
469
470
    /// Cache of items that have been aliased from core instances.
471
    ///
472
    /// This is a helper to reduce the number of aliases created by ensuring
473
    /// that repeated requests for the same item return the same index of an
474
    /// original `core alias` item.
475
    aliased_core_items: HashMap<(u32, String), u32>,
476
477
    /// Metadata about the world inferred from the input to `ComponentEncoder`.
478
    info: &'a ComponentWorld<'a>,
479
480
    /// Maps from the instance an export came from, plus its original core
481
    /// name, to the index of the wrapper function which the fixup module
482
    /// defines for it.
483
    ///
484
    /// Used to invoke the task hook around lifted exports, post-return
485
    /// functions, callbacks, and `realloc` functions.
486
    export_task_initialization_wrappers: HashMap<(fixup::ImportedInstance, String), u32>,
487
}
488
489
impl<'a> EncodingState<'a> {
490
4.76k
    fn encode_core_modules(&mut self) {
491
4.76k
        assert!(self.module_index.is_none());
492
4.76k
        let idx = self
493
4.76k
            .component
494
4.76k
            .core_module_raw(Some("main"), &self.info.encoder.module);
495
4.76k
        self.module_index = Some(idx);
496
497
4.76k
        for (name, adapter) in self.info.adapters.iter() {
498
0
            let debug_name = if adapter.library_info.is_some() {
499
0
                name.to_string()
500
            } else {
501
0
                format!("wit-component:adapter:{name}")
502
            };
503
0
            let idx = if self.info.encoder.debug_names {
504
0
                let mut add_meta = wasm_metadata::AddMetadata::default();
505
0
                add_meta.name = AddMetadataField::Set(debug_name.clone());
506
0
                let wasm = add_meta
507
0
                    .to_wasm(&adapter.wasm)
508
0
                    .expect("core wasm can get name added");
509
0
                self.component.core_module_raw(Some(&debug_name), &wasm)
510
            } else {
511
0
                self.component
512
0
                    .core_module_raw(Some(&debug_name), &adapter.wasm)
513
            };
514
0
            let prev = self.adapter_modules.insert(name, idx);
515
0
            assert!(prev.is_none());
516
        }
517
4.76k
    }
518
519
9.12k
    fn root_import_type_encoder(
520
9.12k
        &mut self,
521
9.12k
        interface: Option<InterfaceId>,
522
9.12k
    ) -> RootTypeEncoder<'_, 'a> {
523
9.12k
        RootTypeEncoder {
524
9.12k
            state: self,
525
9.12k
            interface,
526
9.12k
            import_types: true,
527
9.12k
        }
528
9.12k
    }
529
530
65.2k
    fn root_export_type_encoder(
531
65.2k
        &mut self,
532
65.2k
        interface: Option<InterfaceId>,
533
65.2k
    ) -> RootTypeEncoder<'_, 'a> {
534
65.2k
        RootTypeEncoder {
535
65.2k
            state: self,
536
65.2k
            interface,
537
65.2k
            import_types: false,
538
65.2k
        }
539
65.2k
    }
540
541
1.77k
    fn instance_type_encoder(&mut self, interface: InterfaceId) -> InstanceTypeEncoder<'_, 'a> {
542
1.77k
        InstanceTypeEncoder {
543
1.77k
            state: self,
544
1.77k
            interface,
545
1.77k
            type_encoding_maps: Default::default(),
546
1.77k
            ty: Default::default(),
547
1.77k
        }
548
1.77k
    }
549
550
4.76k
    fn encode_imports(&mut self, name_map: &HashMap<String, String>) -> Result<()> {
551
4.76k
        let mut has_funcs = false;
552
4.76k
        for (name, info) in self.info.import_map.iter() {
553
3.27k
            match name {
554
1.77k
                Some(name) => {
555
1.77k
                    self.encode_interface_import(name_map.get(name).unwrap_or(name), info)?
556
                }
557
1.50k
                None => has_funcs = true,
558
            }
559
        }
560
561
4.76k
        let resolve = &self.info.encoder.metadata.resolve;
562
4.76k
        let world = &resolve.worlds[self.info.encoder.metadata.world];
563
564
        // FIXME: ideally this would use the liveness analysis from
565
        // world-building to only encode live types, not all type in a world.
566
4.99k
        for (_name, item) in world.imports.iter() {
567
4.99k
            if let WorldItem::Type { id, .. } = item {
568
2.08k
                self.root_import_type_encoder(None)
569
2.08k
                    .encode_valtype(resolve, &Type::Id(*id))?;
570
2.91k
            }
571
        }
572
573
4.76k
        if has_funcs {
574
1.50k
            let info = &self.info.import_map[&None];
575
1.50k
            self.encode_root_import_funcs(info)?;
576
3.25k
        }
577
4.76k
        Ok(())
578
4.76k
    }
579
580
1.77k
    fn encode_interface_import(&mut self, name: &str, info: &ImportedInterface) -> Result<()> {
581
1.77k
        let resolve = &self.info.encoder.metadata.resolve;
582
1.77k
        let interface_id = info.interface.as_ref().unwrap();
583
1.77k
        let interface_id = *interface_id;
584
1.77k
        let interface = &resolve.interfaces[interface_id];
585
1.77k
        log::trace!("encoding imports for `{name}` as {interface_id:?}");
586
1.77k
        let mut encoder = self.instance_type_encoder(interface_id);
587
588
        // First encode all type information
589
1.77k
        if let Some(live) = encoder.state.info.live_type_imports.get(&interface_id) {
590
895
            for ty in live {
591
895
                log::trace!(
592
                    "encoding extra type {ty:?} name={:?}",
593
0
                    resolve.types[*ty].name
594
                );
595
895
                encoder.encode_valtype(resolve, &Type::Id(*ty))?;
596
            }
597
1.00k
        }
598
599
        // Next encode all required functions from this imported interface
600
        // into the instance type.
601
2.78k
        for (_, func) in interface.functions.iter() {
602
2.78k
            if !(info
603
2.78k
                .lowerings
604
2.78k
                .contains_key(&(func.name.clone(), AbiVariant::GuestImport))
605
424
                || info
606
424
                    .lowerings
607
424
                    .contains_key(&(func.name.clone(), AbiVariant::GuestImportAsync)))
608
            {
609
0
                continue;
610
2.78k
            }
611
2.78k
            log::trace!("encoding function type for `{}`", func.name);
612
2.78k
            let idx = encoder.encode_func_type(resolve, func)?;
613
614
2.78k
            encoder.ty.export(
615
2.78k
                crate::encoding::types::extern_name(&func.name, func.external_id.as_deref()),
616
2.78k
                ComponentTypeRef::Func(idx),
617
            );
618
        }
619
620
1.77k
        let ty = encoder.ty;
621
        // Don't encode empty instance types since they're not
622
        // meaningful to the runtime of the component anyway.
623
1.77k
        if ty.is_empty() {
624
610
            return Ok(());
625
1.16k
        }
626
1.16k
        let instance_type_idx = self
627
1.16k
            .component
628
1.16k
            .type_instance(Some(&format!("ty-{name}")), &ty);
629
630
        // `name` is the interface's name unless it's a plain name, which is the
631
        // case for imports with `implements` and of anonymous interfaces.
632
1.16k
        let is_interface_name = info.implements.is_none() && interface.name.is_some();
633
1.16k
        let extern_name = interface_extern_name(
634
1.16k
            resolve,
635
1.16k
            name,
636
1.16k
            is_interface_name.then_some(interface_id),
637
1.16k
            info.implements,
638
1.16k
            info.external_id.clone(),
639
1.16k
            self.info.encoder.emit_canonical_names,
640
        );
641
1.16k
        let instance_idx = self
642
1.16k
            .component
643
1.16k
            .import(extern_name, ComponentTypeRef::Instance(instance_type_idx));
644
1.16k
        let prev = self.instances.insert(interface_id, instance_idx);
645
1.16k
        assert!(prev.is_none());
646
1.16k
        Ok(())
647
1.77k
    }
648
649
1.50k
    fn encode_root_import_funcs(&mut self, info: &ImportedInterface) -> Result<()> {
650
1.50k
        let resolve = &self.info.encoder.metadata.resolve;
651
1.50k
        let world = self.info.encoder.metadata.world;
652
4.01k
        for (name, item) in resolve.worlds[world].imports.iter() {
653
4.01k
            let func = match item {
654
1.14k
                WorldItem::Function(f) => f,
655
2.87k
                WorldItem::Interface { .. } | WorldItem::Type { .. } => continue,
656
            };
657
1.14k
            let name = resolve.name_world_key(name);
658
1.14k
            if !(info
659
1.14k
                .lowerings
660
1.14k
                .contains_key(&(name.clone(), AbiVariant::GuestImport))
661
158
                || info
662
158
                    .lowerings
663
158
                    .contains_key(&(name.clone(), AbiVariant::GuestImportAsync)))
664
            {
665
0
                continue;
666
1.14k
            }
667
1.14k
            log::trace!("encoding function type for `{}`", func.name);
668
1.14k
            let idx = self
669
1.14k
                .root_import_type_encoder(None)
670
1.14k
                .encode_func_type(resolve, func)?;
671
1.14k
            let func_idx = self.component.import(
672
1.14k
                crate::encoding::types::extern_name(name.as_str(), func.external_id.as_deref()),
673
1.14k
                ComponentTypeRef::Func(idx),
674
            );
675
1.14k
            let prev = self.imported_funcs.insert(name, func_idx);
676
1.14k
            assert!(prev.is_none());
677
        }
678
1.50k
        Ok(())
679
1.50k
    }
680
681
662
    fn alias_instance_type_export(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
682
662
        let ty = &self.info.encoder.metadata.resolve.types[id];
683
662
        let name = ty.name.as_ref().expect("type must have a name");
684
662
        let instance = self.instances[&interface];
685
662
        self.component
686
662
            .alias_export(instance, name, ComponentExportKind::Type)
687
662
    }
688
689
4.76k
    fn encode_core_instantiation(
690
4.76k
        &mut self,
691
4.76k
        fixup_hook: Option<&mut dyn FnMut(&mut fixup::FixupModule) -> Result<()>>,
692
4.76k
    ) -> Result<()> {
693
        // Encode a shim instantiation if needed
694
4.76k
        let (shims, mut fixups) = self.encode_shim_instantiation()?;
695
696
        // Next declare any types needed for imported intrinsics. This
697
        // populates `export_type_map` and will additionally be used for
698
        // imports to modules instantiated below.
699
4.76k
        self.declare_types_for_imported_intrinsics(&shims)?;
700
701
        // Next instantiate the main module. This provides the linear memory to
702
        // use for all future adapters and enables creating indirect lowerings
703
        // at the end.
704
4.76k
        self.instantiate_main_module(&shims)?;
705
706
4.76k
        for (name, _adapter) in self.info.adapters.iter() {
707
0
            self.instantiate_adapter_module(&shims, name)?;
708
        }
709
710
4.76k
        if let Some(initialize) = self.info.info.exports.initialize() {
711
4.76k
            fixups.add_initialize(initialize)?;
712
0
        }
713
714
4.76k
        if let Some(hook) = fixup_hook {
715
0
            hook(&mut fixups)?;
716
4.76k
        }
717
718
        // With all the relevant core wasm instances in play now the original shim
719
        // module, if present, can be filled in with lowerings/adapters/etc.
720
4.76k
        fixups.instantiate(&shims, self)?;
721
722
4.76k
        Ok(())
723
4.76k
    }
724
725
429
    fn lookup_resource_index(&mut self, id: TypeId) -> u32 {
726
429
        let resolve = &self.info.encoder.metadata.resolve;
727
429
        let ty = &resolve.types[id];
728
429
        match ty.owner {
729
            // If this resource is owned by a world then it's a top-level
730
            // resource which means it must have already been translated so
731
            // it's available for lookup in `import_type_map`.
732
147
            TypeOwner::World(_) => self.type_encoding_maps.id_to_index[&id],
733
282
            TypeOwner::Interface(i) => {
734
282
                let instance = self.instances[&i];
735
282
                let name = ty.name.as_ref().expect("resources must be named");
736
282
                self.component
737
282
                    .alias_export(instance, name, ComponentExportKind::Type)
738
            }
739
0
            TypeOwner::None => panic!("resources must have an owner"),
740
        }
741
429
    }
742
743
4.76k
    fn encode_exports(&mut self, module: CustomModule) -> Result<()> {
744
4.76k
        let resolve = &self.info.encoder.metadata.resolve;
745
4.76k
        let exports = match module {
746
4.76k
            CustomModule::Main => &self.info.encoder.main_module_exports,
747
0
            CustomModule::Adapter(name) => &self.info.encoder.adapters[name].required_exports,
748
        };
749
750
4.76k
        if exports.is_empty() {
751
2.75k
            return Ok(());
752
2.00k
        }
753
754
2.00k
        let mut interface_func_core_names = IndexMap::new();
755
2.00k
        let mut world_func_core_names = IndexMap::new();
756
37.5k
        for (core_name, export) in self.info.exports_for(module).iter() {
757
37.5k
            match export {
758
477
                Export::WorldFunc(_, name, _) => {
759
477
                    let prev = world_func_core_names.insert(name, core_name);
760
477
                    assert!(prev.is_none());
761
                }
762
15.0k
                Export::InterfaceFunc(key, _, name, _) => {
763
15.0k
                    let prev = interface_func_core_names
764
15.0k
                        .entry(key)
765
15.0k
                        .or_insert(IndexMap::new())
766
15.0k
                        .insert(name.as_str(), core_name);
767
15.0k
                    assert!(prev.is_none());
768
                }
769
                Export::WorldFuncCallback(..)
770
                | Export::InterfaceFuncCallback(..)
771
                | Export::WorldFuncPostReturn(..)
772
                | Export::InterfaceFuncPostReturn(..)
773
                | Export::ResourceDtor(..)
774
                | Export::Memory(_)
775
                | Export::GeneralPurposeRealloc
776
                | Export::GeneralPurposeExportRealloc
777
                | Export::GeneralPurposeImportRealloc
778
                | Export::Initialize
779
                | Export::ReallocForAdapter
780
                | Export::IndirectFunctionTable
781
22.0k
                | Export::WasmTaskHook => continue,
782
            }
783
        }
784
785
2.00k
        let world = &resolve.worlds[self.info.encoder.metadata.world];
786
787
9.21k
        for export_name in exports {
788
9.21k
            let export_string = if self.info.encoder.emit_canonical_names {
789
0
                resolve.name_canonicalized_world_key(export_name)
790
            } else {
791
9.21k
                resolve.name_world_key(export_name)
792
            };
793
9.21k
            match &world.exports[export_name] {
794
477
                WorldItem::Function(func) => {
795
477
                    let ty = self
796
477
                        .root_import_type_encoder(None)
797
477
                        .encode_func_type(resolve, func)?;
798
477
                    let core_name = world_func_core_names[&func.name];
799
477
                    let idx = self.encode_lift(module, &core_name, export_name, func, ty)?;
800
477
                    self.component.export(
801
477
                        crate::encoding::types::extern_name(
802
477
                            &export_string,
803
477
                            func.external_id.as_deref(),
804
                        ),
805
477
                        ComponentExportKind::Func,
806
477
                        idx,
807
477
                        None,
808
                    );
809
                }
810
8.74k
                item @ WorldItem::Interface { id, .. } => {
811
8.74k
                    let core_names = interface_func_core_names.get(export_name);
812
8.74k
                    self.encode_interface_export(
813
8.74k
                        &export_string,
814
8.74k
                        module,
815
8.74k
                        export_name,
816
8.74k
                        item,
817
8.74k
                        *id,
818
8.74k
                        core_names,
819
0
                    )?;
820
                }
821
0
                WorldItem::Type { .. } => unreachable!(),
822
            }
823
        }
824
825
2.00k
        Ok(())
826
4.76k
    }
827
828
8.74k
    fn encode_interface_export(
829
8.74k
        &mut self,
830
8.74k
        export_name: &str,
831
8.74k
        module: CustomModule<'_>,
832
8.74k
        key: &WorldKey,
833
8.74k
        item: &WorldItem,
834
8.74k
        export: InterfaceId,
835
8.74k
        interface_func_core_names: Option<&IndexMap<&str, &str>>,
836
8.74k
    ) -> Result<()> {
837
8.74k
        log::trace!("encode interface export `{export_name}`");
838
8.74k
        let resolve = &self.info.encoder.metadata.resolve;
839
840
        // First execute a `canon lift` for all the functions in this interface
841
        // from the core wasm export. This requires type information but notably
842
        // not exported type information since we don't want to export this
843
        // interface's types from the root of the component. Each lifted
844
        // function is saved off into an `imports` array to get imported into
845
        // the nested component synthesized below.
846
8.74k
        let mut imports = Vec::new();
847
8.74k
        let mut root = self.root_export_type_encoder(Some(export));
848
15.0k
        for (_, func) in &resolve.interfaces[export].functions {
849
15.0k
            let core_name = interface_func_core_names.unwrap()[func.name.as_str()];
850
15.0k
            let ty = root.encode_func_type(resolve, func)?;
851
15.0k
            let func_index = root.state.encode_lift(module, &core_name, key, func, ty)?;
852
15.0k
            imports.push((
853
15.0k
                import_func_name(func),
854
15.0k
                ComponentExportKind::Func,
855
15.0k
                func_index,
856
15.0k
            ));
857
        }
858
859
        // Next a nested component is created which will import the functions
860
        // above and then reexport them. The purpose of them is to "re-type" the
861
        // functions through type ascription on each `func` item.
862
8.74k
        let mut nested = NestedComponentTypeEncoder {
863
8.74k
            component: ComponentBuilder::default(),
864
8.74k
            type_encoding_maps: Default::default(),
865
8.74k
            export_types: false,
866
8.74k
            interface: export,
867
8.74k
            state: self,
868
8.74k
            imports: IndexMap::new(),
869
8.74k
        };
870
871
        // Import all transitively-referenced types from other interfaces into
872
        // this component. This temporarily switches the `interface` listed to
873
        // the interface of the referred-to-type to generate the import. After
874
        // this loop `interface` is rewritten to `export`.
875
        //
876
        // Each component is a standalone "island" so the necessary type
877
        // information needs to be rebuilt within this component. This ensures
878
        // that we're able to build a valid component and additionally connect
879
        // all the type information to the outer context.
880
8.74k
        let mut types_to_import = LiveTypes::default();
881
8.74k
        types_to_import.add_interface(resolve, export);
882
8.74k
        let exports_used = &nested.state.info.exports_used[&export];
883
71.2k
        for ty in types_to_import.iter() {
884
71.2k
            if let TypeOwner::Interface(owner) = resolve.types[ty].owner {
885
41.6k
                if owner == export {
886
                    // Here this deals with the current exported interface which
887
                    // is handled below.
888
40.7k
                    continue;
889
926
                }
890
891
                // Ensure that `self` has encoded this type before. If so this
892
                // is a noop but otherwise it generates the type here.
893
926
                let mut encoder = if exports_used.contains(&owner) {
894
16
                    nested.state.root_export_type_encoder(Some(export))
895
                } else {
896
910
                    nested.state.root_import_type_encoder(Some(export))
897
                };
898
926
                encoder.encode_valtype(resolve, &Type::Id(ty))?;
899
900
                // Next generate the same type but this time within the
901
                // component itself. The type generated above (or prior) will be
902
                // used to satisfy this type import.
903
926
                nested.interface = owner;
904
926
                nested.encode_valtype(resolve, &Type::Id(ty))?;
905
29.6k
            }
906
        }
907
8.74k
        nested.interface = export;
908
909
        // Record the map of types imported to their index at where they were
910
        // imported. This is used after imports are encoded as exported types
911
        // will refer to these.
912
8.74k
        let imported_type_maps = nested.type_encoding_maps.clone();
913
914
        // Handle resource types for this instance specially, namely importing
915
        // them into the nested component. This models how the resource is
916
        // imported from its definition in the outer component to get reexported
917
        // internally. This chiefly avoids creating a second resource which is
918
        // not desired in this situation.
919
8.74k
        let mut resources = HashMap::new();
920
40.7k
        for (_name, ty) in resolve.interfaces[export].types.iter() {
921
40.7k
            if !matches!(resolve.types[*ty].kind, TypeDefKind::Resource) {
922
39.4k
                continue;
923
1.27k
            }
924
1.27k
            let idx = match nested.encode_valtype(resolve, &Type::Id(*ty))? {
925
1.27k
                ComponentValType::Type(idx) => idx,
926
0
                _ => unreachable!(),
927
            };
928
1.27k
            resources.insert(*ty, idx);
929
        }
930
931
        // Next import each function of this interface. This will end up
932
        // defining local types as necessary or using the types as imported
933
        // above.
934
15.0k
        for (_, func) in resolve.interfaces[export].functions.iter() {
935
15.0k
            let ty = nested.encode_func_type(resolve, func)?;
936
15.0k
            nested
937
15.0k
                .component
938
15.0k
                .import(&import_func_name(func), ComponentTypeRef::Func(ty));
939
        }
940
941
        // Swap the `nested.type_map` which was previously from `TypeId` to
942
        // `u32` to instead being from `u32` to `TypeId`. This reverse map is
943
        // then used in conjunction with `self.type_map` to satisfy all type
944
        // imports of the nested component generated. The type import's index in
945
        // the inner component is translated to a `TypeId` via `reverse_map`
946
        // which is then translated back to our own index space via `type_map`.
947
8.74k
        let reverse_map = nested
948
8.74k
            .type_encoding_maps
949
8.74k
            .id_to_index
950
8.74k
            .drain()
951
28.2k
            .map(|p| (p.1, p.0))
952
8.74k
            .collect::<HashMap<_, _>>();
953
8.74k
        nested.type_encoding_maps.def_to_index.clear();
954
8.74k
        for (name, idx) in nested.imports.drain(..) {
955
2.33k
            let id = reverse_map[&idx];
956
2.33k
            let idx = nested.state.type_encoding_maps.id_to_index[&id];
957
2.33k
            imports.push((name, ComponentExportKind::Type, idx))
958
        }
959
960
        // Before encoding exports reset the type map to what all was imported
961
        // from foreign interfaces. This will enable any encoded types below to
962
        // refer to imports which, after type substitution, will point to the
963
        // correct type in the outer component context.
964
8.74k
        nested.type_encoding_maps = imported_type_maps;
965
966
        // Next the component reexports all of its imports, but notably uses the
967
        // type ascription feature to change the type of the function. Note that
968
        // no structural change is happening to the types here but instead types
969
        // are getting proper names and such now that this nested component is a
970
        // new type index space. Hence the `export_types = true` flag here which
971
        // flows through the type encoding and when types are emitted.
972
8.74k
        nested.export_types = true;
973
8.74k
        nested.type_encoding_maps.func_type_map.clear();
974
975
        // To start off all type information is encoded. This will be used by
976
        // functions below but notably this also has special handling for
977
        // resources. Resources reexport their imported resource type under
978
        // the final name which achieves the desired goal of threading through
979
        // the original resource without creating a new one.
980
40.7k
        for (_, id) in resolve.interfaces[export].types.iter() {
981
40.7k
            let ty = &resolve.types[*id];
982
40.7k
            match ty.kind {
983
1.27k
                TypeDefKind::Resource => {
984
1.27k
                    let idx = nested.component.export(
985
1.27k
                        crate::encoding::types::extern_name(
986
1.27k
                            ty.name.as_ref().expect("resources must be named"),
987
1.27k
                            ty.external_id.as_deref(),
988
1.27k
                        ),
989
1.27k
                        ComponentExportKind::Type,
990
1.27k
                        resources[id],
991
1.27k
                        None,
992
1.27k
                    );
993
1.27k
                    nested.type_encoding_maps.id_to_index.insert(*id, idx);
994
1.27k
                }
995
                _ => {
996
39.4k
                    nested.encode_valtype(resolve, &Type::Id(*id))?;
997
                }
998
            }
999
        }
1000
1001
15.0k
        for (i, (_, func)) in resolve.interfaces[export].functions.iter().enumerate() {
1002
15.0k
            let ty = nested.encode_func_type(resolve, func)?;
1003
15.0k
            nested.component.export(
1004
15.0k
                crate::encoding::types::extern_name(&func.name, func.external_id.as_deref()),
1005
15.0k
                ComponentExportKind::Func,
1006
15.0k
                i as u32,
1007
15.0k
                Some(ComponentTypeRef::Func(ty)),
1008
            );
1009
        }
1010
1011
        // Embed the component within our component and then instantiate it with
1012
        // the lifted functions. That final instance is then exported under the
1013
        // appropriate name as the final typed export of this component.
1014
8.74k
        let component = nested.component;
1015
8.74k
        let component_index = self
1016
8.74k
            .component
1017
8.74k
            .component(Some(&format!("{export_name}-shim-component")), component);
1018
8.74k
        let instance_index = self.component.instantiate(
1019
8.74k
            Some(&format!("{export_name}-shim-instance")),
1020
8.74k
            component_index,
1021
8.74k
            imports,
1022
        );
1023
8.74k
        let extern_name =
1024
8.74k
            component_extern_name(resolve, key, item, self.info.encoder.emit_canonical_names);
1025
8.74k
        let idx = self.component.export(
1026
8.74k
            extern_name,
1027
8.74k
            ComponentExportKind::Instance,
1028
8.74k
            instance_index,
1029
8.74k
            None,
1030
        );
1031
8.74k
        let prev = self.instances.insert(export, idx);
1032
8.74k
        assert!(prev.is_none());
1033
1034
        // After everything is all said and done remove all the type information
1035
        // about type exports of this interface. Any entries in the map
1036
        // currently were used to create the instance above but aren't the
1037
        // actual copy of the exported type since that comes from the exported
1038
        // instance itself. Entries will be re-inserted into this map as
1039
        // necessary via aliases from the exported instance which is the new
1040
        // source of truth for all these types.
1041
40.7k
        for (_name, id) in resolve.interfaces[export].types.iter() {
1042
40.7k
            self.type_encoding_maps.id_to_index.remove(id);
1043
40.7k
            self.type_encoding_maps
1044
40.7k
                .def_to_index
1045
40.7k
                .remove(&resolve.types[*id].kind);
1046
40.7k
        }
1047
1048
8.74k
        return Ok(());
1049
1050
        struct NestedComponentTypeEncoder<'state, 'a> {
1051
            component: ComponentBuilder,
1052
            type_encoding_maps: TypeEncodingMaps<'a>,
1053
            export_types: bool,
1054
            interface: InterfaceId,
1055
            state: &'state mut EncodingState<'a>,
1056
            imports: IndexMap<String, u32>,
1057
        }
1058
1059
        impl<'a> ValtypeEncoder<'a> for NestedComponentTypeEncoder<'_, 'a> {
1060
94.5k
            fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) {
1061
94.5k
                self.component.type_defined(None)
1062
94.5k
            }
1063
24.3k
            fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) {
1064
24.3k
                self.component.type_function(None)
1065
24.3k
            }
1066
40.4k
            fn export_type(
1067
40.4k
                &mut self,
1068
40.4k
                idx: u32,
1069
40.4k
                name: wasm_encoder::ComponentExternName<'a>,
1070
40.4k
            ) -> Option<u32> {
1071
40.4k
                if self.export_types {
1072
39.4k
                    Some(
1073
39.4k
                        self.component
1074
39.4k
                            .export(name, ComponentExportKind::Type, idx, None),
1075
39.4k
                    )
1076
                } else {
1077
1.04k
                    let name = self.unique_import_name(&name.name);
1078
1.04k
                    let ret = self
1079
1.04k
                        .component
1080
1.04k
                        .import(&name, ComponentTypeRef::Type(TypeBounds::Eq(idx)));
1081
1.04k
                    self.imports.insert(name, ret);
1082
1.04k
                    Some(ret)
1083
                }
1084
40.4k
            }
1085
1.29k
            fn export_resource(&mut self, name: wasm_encoder::ComponentExternName<'a>) -> u32 {
1086
1.29k
                if self.export_types {
1087
0
                    panic!("resources should already be exported")
1088
                } else {
1089
1.29k
                    let name = self.unique_import_name(&name.name);
1090
1.29k
                    let ret = self
1091
1.29k
                        .component
1092
1.29k
                        .import(&name, ComponentTypeRef::Type(TypeBounds::SubResource));
1093
1.29k
                    self.imports.insert(name, ret);
1094
1.29k
                    ret
1095
                }
1096
1.29k
            }
1097
0
            fn import_type(&mut self, _: InterfaceId, _id: TypeId) -> Result<u32> {
1098
0
                unreachable!()
1099
            }
1100
257k
            fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> {
1101
257k
                &mut self.type_encoding_maps
1102
257k
            }
1103
41.7k
            fn interface(&self) -> Option<InterfaceId> {
1104
41.7k
                Some(self.interface)
1105
41.7k
            }
1106
        }
1107
1108
        impl NestedComponentTypeEncoder<'_, '_> {
1109
2.33k
            fn unique_import_name(&mut self, name: &str) -> String {
1110
2.33k
                let mut name = format!("import-type-{name}");
1111
2.33k
                let mut n = 0;
1112
2.37k
                while self.imports.contains_key(&name) {
1113
45
                    name = format!("{name}{n}");
1114
45
                    n += 1;
1115
45
                }
1116
2.33k
                name
1117
2.33k
            }
1118
        }
1119
8.74k
    }
1120
1121
15.5k
    fn encode_lift(
1122
15.5k
        &mut self,
1123
15.5k
        module: CustomModule<'_>,
1124
15.5k
        core_name: &str,
1125
15.5k
        key: &WorldKey,
1126
15.5k
        func: &Function,
1127
15.5k
        ty: u32,
1128
15.5k
    ) -> Result<u32> {
1129
15.5k
        let resolve = &self.info.encoder.metadata.resolve;
1130
15.5k
        let metadata = self.info.module_metadata_for(module);
1131
1132
15.5k
        let core_alias_export =
1133
30.2k
            |me: &mut Self, core_name: &str| me.hooked_core_alias_export(module, core_name);
1134
1135
15.5k
        let core_func_index = core_alias_export(self, core_name);
1136
15.5k
        let exports = self.info.exports_for(module);
1137
1138
15.5k
        let options = RequiredOptions::for_export(
1139
15.5k
            resolve,
1140
15.5k
            self.info.encoder.metadata.world,
1141
15.5k
            func,
1142
15.5k
            exports
1143
15.5k
                .abi(key, func)
1144
15.5k
                .ok_or_else(|| anyhow!("no ABI found for {}", func.name))?,
1145
        );
1146
1147
15.5k
        let encoding = metadata
1148
15.5k
            .export_encodings
1149
15.5k
            .get(resolve, key, &func.name)
1150
15.5k
            .unwrap();
1151
15.5k
        let exports = self.info.exports_for(module);
1152
15.5k
        let realloc_index = if options.contains(RequiredOptions::REALLOC) {
1153
1.31k
            let realloc = exports.export_realloc_for(key, &func.name);
1154
1.31k
            resolve_realloc(self.info, module, realloc)
1155
1.31k
                .map(|(module, name)| self.hooked_core_alias_export(module, name))
1156
        } else {
1157
14.1k
            None
1158
        };
1159
15.5k
        let mut options = options
1160
15.5k
            .into_iter(encoding, self.memory_index, realloc_index)?
1161
15.5k
            .collect::<Vec<_>>();
1162
1163
15.5k
        if let Some(post_return) = exports.post_return(key, func) {
1164
13.6k
            let post_return = core_alias_export(self, post_return);
1165
13.6k
            options.push(CanonicalOption::PostReturn(post_return));
1166
13.6k
        }
1167
15.5k
        if let Some(callback) = exports.callback(key, func) {
1168
1.13k
            let callback = core_alias_export(self, callback);
1169
1.13k
            options.push(CanonicalOption::Callback(callback));
1170
14.3k
        }
1171
15.5k
        let func_index = self
1172
15.5k
            .component
1173
15.5k
            .lift_func(Some(&func.name), core_func_index, ty, options);
1174
15.5k
        Ok(func_index)
1175
15.5k
    }
1176
1177
4.76k
    fn encode_shim_instantiation(&mut self) -> Result<(Shims<'a>, fixup::FixupModule)> {
1178
4.76k
        let mut ret = Shims::default();
1179
4.76k
        let mut fixups = fixup::FixupModule::default();
1180
4.76k
        fixups.index_type = self.info.index_type();
1181
1182
4.76k
        ret.append_indirect(self.info, CustomModule::Main)
1183
4.76k
            .context("failed to register indirect shims for main module")?;
1184
1185
        // For all required adapter modules a shim is created for each required
1186
        // function and additionally a set of shims are created for the
1187
        // interface imported into the shim module itself.
1188
4.76k
        for (adapter_name, _adapter) in self.info.adapters.iter() {
1189
0
            ret.append_indirect(self.info, CustomModule::Adapter(adapter_name))
1190
0
                .with_context(|| {
1191
0
                    format!("failed to register indirect shims for adapter {adapter_name}")
1192
0
                })?;
1193
        }
1194
1195
        // Determine if a TLS global needs to be synthesized here by seeing if
1196
        // it was imported into any module.
1197
4.76k
        let tls_base_global_type = if self.info.can_use_context_slot_1() {
1198
0
            None
1199
        } else {
1200
4.76k
            let infos = [&self.info.info]
1201
4.76k
                .into_iter()
1202
4.76k
                .chain(self.info.adapters.values().map(|a| &a.info));
1203
4.76k
            let mut ret = None;
1204
4.76k
            for info in infos {
1205
43.6k
                for (_, _, import) in info.imports.imports() {
1206
43.6k
                    let ty = match import {
1207
0
                        Import::TlsBaseGet { ty } | Import::TlsBaseSet { ty } => *ty,
1208
43.6k
                        _ => continue,
1209
                    };
1210
0
                    let prev = *ret.get_or_insert(ty);
1211
0
                    if prev != ty {
1212
0
                        bail!("conflicting TLS base pointer types `{prev}` and `{ty}`");
1213
0
                    }
1214
                }
1215
            }
1216
4.76k
            match ret {
1217
0
                Some(ret) => Some(ret.try_into()?),
1218
4.76k
                None => None,
1219
            }
1220
        };
1221
1222
4.76k
        if ret.shims.is_empty()
1223
3.23k
            && self.info.info.imports.imported_memory().is_none()
1224
3.23k
            && tls_base_global_type.is_none()
1225
        {
1226
3.23k
            return Ok((ret, fixups));
1227
1.52k
        }
1228
1229
1.52k
        assert!(self.shim_instance_index.is_none());
1230
1231
        // This function encodes a single module, the shim module, which defines
1232
        // functions to indirectly call through tables or globals. This shim
1233
        // additionally may contain the memory for the main module if it needs
1234
        // it as well as the TLS base pointer for the program. This shim is
1235
        // instantiated before the main module.
1236
1237
1.52k
        let mut types = TypeSection::new();
1238
1.52k
        let mut shim_globals = GlobalSection::new();
1239
1.52k
        let mut shim_tables = TableSection::new();
1240
1.52k
        let mut shim_memories = MemorySection::new();
1241
1.52k
        let mut shim_functions = FunctionSection::new();
1242
1.52k
        let mut shim_exports = ExportSection::new();
1243
1.52k
        let mut shim_code = CodeSection::new();
1244
1.52k
        let mut sigs = IndexMap::new();
1245
1.52k
        let mut trapping_stubs = IndexMap::new();
1246
1.52k
        let mut func_indexes = Vec::new();
1247
1.52k
        let mut func_names = NameMap::new();
1248
1249
1.52k
        let mut intern_type =
1250
8.58k
            |types: &mut TypeSection, params: Vec<ValType>, results: Vec<ValType>| {
1251
8.58k
                *sigs
1252
8.58k
                    .entry((params, results))
1253
8.58k
                    .or_insert_with_key(|(params, results)| {
1254
2.19k
                        let index = types.len();
1255
2.19k
                        types
1256
2.19k
                            .ty()
1257
2.19k
                            .function(params.iter().copied(), results.iter().copied());
1258
2.19k
                        index
1259
2.19k
                    })
1260
8.58k
            };
1261
1262
8.58k
        for shim in ret.shims.values() {
1263
8.58k
            let type_index = intern_type(
1264
8.58k
                &mut types,
1265
8.58k
                shim.sig
1266
8.58k
                    .params
1267
8.58k
                    .iter()
1268
21.1k
                    .map(|ty| self.info.index_type().encoder_val_type(ty))
1269
8.58k
                    .collect(),
1270
8.58k
                shim.sig
1271
8.58k
                    .results
1272
8.58k
                    .iter()
1273
8.58k
                    .map(|ty| self.info.index_type().encoder_val_type(ty))
1274
8.58k
                    .collect(),
1275
            );
1276
1277
8.58k
            let trapping_stub = if self.info.encoder.shim_return_call_ref {
1278
                // Generate a stub which is `unreachable` for the initializer of
1279
                // this global. This can be deduplicated by type signature.
1280
4.19k
                Some(*trapping_stubs.entry(type_index).or_insert_with(|| {
1281
914
                    let mut stub = wasm_encoder::Function::new(std::iter::empty());
1282
914
                    stub.instructions().unreachable().end();
1283
914
                    let index = shim_code.len();
1284
914
                    shim_functions.function(type_index);
1285
914
                    shim_code.function(&stub);
1286
914
                    func_names.append(index, "trap stub before initialization");
1287
914
                    index
1288
914
                }))
1289
            } else {
1290
4.39k
                None
1291
            };
1292
1293
8.58k
            let func_index = shim_functions.len();
1294
8.58k
            shim_functions.function(type_index);
1295
8.58k
            let mut func = wasm_encoder::Function::new(std::iter::empty());
1296
21.1k
            for i in 0..shim.sig.params.len() {
1297
21.1k
                func.instructions().local_get(i as u32);
1298
21.1k
            }
1299
8.58k
            fixups.add_shim(&self.info.encoder, shim)?;
1300
8.58k
            if self.info.encoder.shim_return_call_ref {
1301
4.19k
                // Generate a global-per-function which gets exported from the
1302
4.19k
                // module and then filled in later.
1303
4.19k
                let global = shim_globals.len();
1304
4.19k
                let ty = GlobalType {
1305
4.19k
                    val_type: RefType {
1306
4.19k
                        nullable: false,
1307
4.19k
                        heap_type: HeapType::Concrete(type_index),
1308
4.19k
                    }
1309
4.19k
                    .into(),
1310
4.19k
                    mutable: true,
1311
4.19k
                    shared: false,
1312
4.19k
                };
1313
4.19k
                let global_name = format!("g{}", shim.name);
1314
4.19k
                shim_globals.global(ty, &ConstExpr::ref_func(trapping_stub.unwrap()));
1315
4.19k
                shim_exports.export(&global_name, ExportKind::Global, global);
1316
4.19k
1317
4.19k
                func.instructions().global_get(global);
1318
4.19k
                func.instructions().return_call_ref(type_index);
1319
4.39k
            } else {
1320
4.39k
                func.instructions().i32_const(func_index as i32);
1321
4.39k
                func.instructions().call_indirect(0, type_index);
1322
4.39k
            }
1323
8.58k
            func.instructions().end();
1324
8.58k
            shim_code.function(&func);
1325
8.58k
            shim_exports.export(&shim.name, ExportKind::Func, func_index);
1326
1327
8.58k
            func_indexes.push(func_index);
1328
8.58k
            func_names.append(func_index, &shim.debug_name);
1329
        }
1330
1331
1.52k
        if !ret.shims.is_empty() && !self.info.encoder.shim_return_call_ref {
1332
936
            let table_type = TableType {
1333
936
                element_type: RefType::FUNCREF,
1334
936
                minimum: ret.shims.len() as u64,
1335
936
                maximum: Some(ret.shims.len() as u64),
1336
936
                table64: false,
1337
936
                shared: false,
1338
936
            };
1339
936
1340
936
            shim_tables.table(table_type);
1341
936
            shim_exports.export(INDIRECT_TABLE_NAME, ExportKind::Table, 0);
1342
936
        }
1343
1344
        // If the main module imports its memory then define it here and export
1345
        // it for everyone else to use.
1346
1.52k
        if let Some(ty) = self.info.info.imports.imported_memory() {
1347
0
            shim_memories.memory(RoundtripReencoder.memory_type(ty)?);
1348
0
            shim_exports.export(SHIM_MEMORY_NAME, ExportKind::Memory, 0);
1349
1.52k
        }
1350
1351
        // If the TLS base pointer is stored in a `global`, as opposed to a
1352
        // `context` slot, then define that global here along with accessors
1353
        // for it which everyone else uses.
1354
1.52k
        if let Some(ty) = tls_base_global_type {
1355
0
            let get_ty = intern_type(&mut types, Vec::new(), vec![ty]);
1356
0
            let set_ty = intern_type(&mut types, vec![ty], Vec::new());
1357
1358
0
            let global = shim_globals.len();
1359
0
            shim_globals.global(
1360
0
                GlobalType {
1361
0
                    val_type: ty,
1362
0
                    mutable: true,
1363
0
                    shared: false,
1364
0
                },
1365
0
                &match ty {
1366
0
                    ValType::I64 => ConstExpr::i64_const(0),
1367
0
                    ValType::I32 => ConstExpr::i32_const(0),
1368
0
                    _ => unreachable!(),
1369
                },
1370
            );
1371
1372
0
            let get = shim_functions.len();
1373
0
            shim_functions.function(get_ty);
1374
0
            let mut func = wasm_encoder::Function::new(std::iter::empty());
1375
0
            func.instructions().global_get(global).end();
1376
0
            shim_code.function(&func);
1377
0
            shim_exports.export(TLS_BASE_GET, ExportKind::Func, get);
1378
0
            func_names.append(get, TLS_BASE_GET);
1379
1380
0
            let set = shim_functions.len();
1381
0
            shim_functions.function(set_ty);
1382
0
            let mut func = wasm_encoder::Function::new(std::iter::empty());
1383
0
            func.instructions().local_get(0).global_set(global).end();
1384
0
            shim_code.function(&func);
1385
0
            shim_exports.export(TLS_BASE_SET, ExportKind::Func, set);
1386
0
            func_names.append(set, TLS_BASE_SET);
1387
1.52k
        }
1388
1389
1.52k
        let mut shim_names = NameSection::new();
1390
1.52k
        shim_names.module("wit-component:shim");
1391
1.52k
        shim_names.functions(&func_names);
1392
1393
1.52k
        let mut shim = Module::new();
1394
1.52k
        shim.section(&types);
1395
1.52k
        if !shim_functions.is_empty() {
1396
1.52k
            shim.section(&shim_functions);
1397
1.52k
        }
1398
1.52k
        if !shim_tables.is_empty() {
1399
936
            shim.section(&shim_tables);
1400
936
        }
1401
1.52k
        if !shim_memories.is_empty() {
1402
0
            shim.section(&shim_memories);
1403
1.52k
        }
1404
1.52k
        if !shim_globals.is_empty() {
1405
592
            shim.section(&shim_globals);
1406
936
        }
1407
1.52k
        if !shim_exports.is_empty() {
1408
1.52k
            shim.section(&shim_exports);
1409
1.52k
        }
1410
1.52k
        if !shim_code.is_empty() {
1411
1.52k
            shim.section(&shim_code);
1412
1.52k
        }
1413
1.52k
        shim.section(&RawCustomSection(
1414
1.52k
            &crate::base_producers().raw_custom_section(),
1415
1.52k
        ));
1416
1.52k
        if self.info.encoder.debug_names {
1417
632
            shim.section(&shim_names);
1418
896
        }
1419
1420
1.52k
        let shim_module_index = self
1421
1.52k
            .component
1422
1.52k
            .core_module(Some("wit-component-shim-module"), &shim);
1423
1424
1.52k
        let shim_instance = self.component.core_instantiate(
1425
1.52k
            Some("wit-component-shim-instance"),
1426
1.52k
            shim_module_index,
1427
1.52k
            [],
1428
        );
1429
1.52k
        self.shim_instance_index = Some(shim_instance);
1430
1431
        // With the shim instantiated the memory it defines, if any, is now
1432
        // available for use as a canonical option.
1433
1.52k
        if self.info.info.imports.imported_memory().is_some() {
1434
0
            assert!(self.memory_index.is_none());
1435
0
            self.memory_index = Some(self.core_alias_export(
1436
0
                Some("memory"),
1437
0
                shim_instance,
1438
0
                SHIM_MEMORY_NAME,
1439
0
                ExportKind::Memory,
1440
0
            ));
1441
1.52k
        }
1442
1443
1.52k
        Ok((ret, fixups))
1444
4.76k
    }
1445
1446
8.58k
    fn encode_shim(&mut self, shims: &Shims<'_>, shim: &Shim<'_>) -> Result<u32> {
1447
8.58k
        let resolve = &self.info.encoder.metadata.resolve;
1448
8.58k
        Ok(match &shim.kind {
1449
            // Indirect lowerings are a `canon lower`'d function with
1450
            // options specified from a previously instantiated instance.
1451
            // This previous instance could either be the main module or an
1452
            // adapter module, which affects the `realloc` option here.
1453
            // Currently only one linear memory is supported so the linear
1454
            // memory always comes from the main module.
1455
            ShimKind::IndirectLowering {
1456
1.30k
                interface,
1457
1.30k
                index,
1458
1.30k
                realloc,
1459
1.30k
                encoding,
1460
            } => {
1461
1.30k
                let interface = &self.info.import_map[interface];
1462
1.30k
                let ((name, _), _) = interface.lowerings.get_index(*index).unwrap();
1463
1.30k
                let func_index = match &interface.interface {
1464
949
                    Some(interface_id) => {
1465
949
                        let instance_index = self.instances[interface_id];
1466
949
                        self.component
1467
949
                            .alias_export(instance_index, name, ComponentExportKind::Func)
1468
                    }
1469
359
                    None => self.imported_funcs[name],
1470
                };
1471
1472
1.30k
                let realloc_export = self
1473
1.30k
                    .info
1474
1.30k
                    .exports_for(*realloc)
1475
1.30k
                    .import_realloc_for(interface.interface, name);
1476
1.30k
                let realloc = self.realloc_index(
1477
1.30k
                    shims,
1478
1.30k
                    *realloc,
1479
1.30k
                    ReallocSite::AfterInstantiation,
1480
1.30k
                    shim.options,
1481
1.30k
                    realloc_export,
1482
                );
1483
1484
1.30k
                self.component.lower_func(
1485
1.30k
                    Some(&shim.debug_name),
1486
1.30k
                    func_index,
1487
1.30k
                    shim.options
1488
1.30k
                        .into_iter(*encoding, self.memory_index, realloc)?,
1489
                )
1490
            }
1491
1492
            // Adapter shims are defined by an export from an adapter
1493
            // instance, so use the specified name here and the previously
1494
            // created instances to get the core item that represents the
1495
            // shim.
1496
0
            ShimKind::Adapter { adapter, func } => self.core_alias_export(
1497
0
                Some(func),
1498
0
                self.adapter_instances[adapter],
1499
0
                func,
1500
0
                ExportKind::Func,
1501
            ),
1502
1503
            // Resources are required for a module to be instantiated
1504
            // meaning that any destructor for the resource must be called
1505
            // indirectly due to the otherwise circular dependency between
1506
            // the module and the resource itself.
1507
1.27k
            ShimKind::ResourceDtor { module, export } => self.core_alias_export(
1508
1.27k
                Some(export),
1509
1.27k
                self.instance_for(*module),
1510
1.27k
                export,
1511
1.27k
                ExportKind::Func,
1512
            ),
1513
1514
            ShimKind::PayloadFunc {
1515
3.56k
                for_module,
1516
3.56k
                info,
1517
3.56k
                kind,
1518
3.56k
            } => self.encode_payload_func(
1519
3.56k
                shims,
1520
3.56k
                for_module,
1521
3.56k
                info,
1522
3.56k
                kind,
1523
3.56k
                shim.options,
1524
3.56k
                ReallocSite::AfterInstantiation,
1525
0
            )?,
1526
1527
            ShimKind::WaitableSetWait => {
1528
933
                self.component.waitable_set_wait(self.memory_index.unwrap())
1529
            }
1530
            ShimKind::WaitableSetPoll => {
1531
933
                self.component.waitable_set_poll(self.memory_index.unwrap())
1532
            }
1533
0
            ShimKind::ErrorContextNew { encoding } => self
1534
0
                .component
1535
0
                .error_context_new(shim.options.into_iter(*encoding, self.memory_index, None)?),
1536
            ShimKind::ErrorContextDebugMessage {
1537
0
                for_module,
1538
0
                encoding,
1539
            } => {
1540
0
                let realloc = self.info.exports_for(*for_module).import_realloc_fallback();
1541
0
                let realloc_index = self.realloc_index(
1542
0
                    shims,
1543
0
                    *for_module,
1544
0
                    ReallocSite::AfterInstantiation,
1545
0
                    shim.options,
1546
0
                    realloc,
1547
                );
1548
1549
0
                self.component
1550
0
                    .error_context_debug_message(shim.options.into_iter(
1551
0
                        *encoding,
1552
0
                        self.memory_index,
1553
0
                        realloc_index,
1554
0
                    )?)
1555
            }
1556
            ShimKind::TaskReturn {
1557
574
                interface,
1558
574
                func,
1559
574
                result,
1560
574
                encoding,
1561
574
                for_module,
1562
            } => {
1563
                // See `Import::ExportedTaskReturn` handling for why this
1564
                // encoder is treated specially.
1565
574
                let mut encoder = if interface.is_none() {
1566
31
                    self.root_import_type_encoder(*interface)
1567
                } else {
1568
543
                    self.root_export_type_encoder(*interface)
1569
                };
1570
574
                let result = match result {
1571
563
                    Some(ty) => Some(encoder.encode_valtype(resolve, ty)?),
1572
11
                    None => None,
1573
                };
1574
1575
574
                let exports = self.info.exports_for(*for_module);
1576
574
                let realloc = exports.import_realloc_for(*interface, func);
1577
1578
574
                let instance_index = self.instance_for(*for_module);
1579
574
                let realloc_index = realloc.map(|r| {
1580
574
                    self.core_alias_export(Some("realloc"), instance_index, r, ExportKind::Func)
1581
574
                });
1582
574
                let options =
1583
574
                    shim.options
1584
574
                        .into_iter(*encoding, self.memory_index, realloc_index)?;
1585
574
                self.component.task_return(result, options)
1586
            }
1587
0
            ShimKind::ThreadNewIndirect { func_ty } => {
1588
                // Encode the function type for the thread start function so we can reference it in the `canon` call.
1589
0
                let (func_ty_idx, f) = self.component.core_type(Some("thread-start"));
1590
0
                f.core().func_type(func_ty);
1591
1592
                // In order for the funcref table referenced by `thread.new-indirect` to be used,
1593
                // it must have been exported by the main module.
1594
0
                let exports = self.info.exports_for(CustomModule::Main);
1595
0
                let instance_index = self.instance_for(CustomModule::Main);
1596
0
                let table_idx = exports.indirect_function_table().map(|table| {
1597
0
                        self.core_alias_export(
1598
0
                            Some("indirect-function-table"),
1599
0
                            instance_index,
1600
0
                            table,
1601
0
                            ExportKind::Table,
1602
                        )
1603
0
                    }).ok_or_else(|| {
1604
0
                        anyhow!(
1605
                            "table __indirect_function_table must be an exported funcref table for thread.new-indirect"
1606
                        )
1607
0
                    })?;
1608
1609
0
                self.component.thread_new_indirect(func_ty_idx, table_idx)
1610
            }
1611
1612
0
            ShimKind::Realloc { module, export } => {
1613
0
                let instance = self.instance_for(*module);
1614
0
                self.core_alias_export(Some(export), instance, export, ExportKind::Func)
1615
            }
1616
        })
1617
8.58k
    }
1618
1619
3.56k
    fn encode_payload_func(
1620
3.56k
        &mut self,
1621
3.56k
        shims: &Shims<'_>,
1622
3.56k
        for_module: &CustomModule,
1623
3.56k
        info: &PayloadInfo,
1624
3.56k
        kind: &PayloadFuncKind,
1625
3.56k
        options: RequiredOptions,
1626
3.56k
        site: ReallocSite,
1627
3.56k
    ) -> Result<u32> {
1628
3.56k
        let resolve = &self.info.encoder.metadata.resolve;
1629
3.56k
        let metadata = self.info.module_metadata_for(*for_module);
1630
3.56k
        let encoding = match &info.ty {
1631
3.56k
            PayloadType::Type { function, .. } => {
1632
3.56k
                if info.imported {
1633
832
                    metadata.import_encodings.get(resolve, &info.key, function)
1634
                } else {
1635
2.73k
                    metadata.export_encodings.get(resolve, &info.key, function)
1636
                }
1637
            }
1638
0
            PayloadType::UnitFuture | PayloadType::UnitStream => None,
1639
        };
1640
3.56k
        let realloc = payload_realloc_name(self.info, *for_module, info);
1641
3.56k
        let encoding = encoding.unwrap_or(StringEncoding::UTF8);
1642
3.56k
        let realloc_index = self.realloc_index(shims, *for_module, site, options, realloc);
1643
3.56k
        let type_index = self.payload_type_index(info)?;
1644
3.56k
        let options = options.into_iter(encoding, self.memory_index, realloc_index)?;
1645
1646
3.56k
        Ok(match kind {
1647
1.15k
            PayloadFuncKind::FutureWrite => self.component.future_write(type_index, options),
1648
1.15k
            PayloadFuncKind::FutureRead => self.component.future_read(type_index, options),
1649
629
            PayloadFuncKind::StreamWrite => self.component.stream_write(type_index, options),
1650
629
            PayloadFuncKind::StreamRead => self.component.stream_read(type_index, options),
1651
        })
1652
3.56k
    }
1653
1654
    /// Encode the specified `stream` or `future` type in the component using
1655
    /// either the `root_import_type_encoder` or the `root_export_type_encoder`
1656
    /// depending on the value of `imported`.
1657
    ///
1658
    /// Note that the payload type `T` of `stream<T>` or `future<T>` may be an
1659
    /// imported or exported type, and that determines the appropriate type
1660
    /// encoder to use.
1661
19.6k
    fn payload_type_index(&mut self, info: &PayloadInfo) -> Result<u32> {
1662
19.6k
        let resolve = &self.info.encoder.metadata.resolve;
1663
        // What exactly is selected here as the encoder is a bit unusual here.
1664
        // If the interface is imported, an import encoder is used. An import
1665
        // encoder is also used though if `info` is exported and
1666
        // `info.interface` is `None`, meaning that this is for a function that
1667
        // is in the top-level of a world. At the top level of a world all
1668
        // types are imported.
1669
        //
1670
        // Additionally for the import encoder the interface passed in is
1671
        // `None`, not `info.interface`. Notably this means that references to
1672
        // named types will be aliased from their imported versions, which is
1673
        // what we want here.
1674
        //
1675
        // Finally though exports do use `info.interface`. Honestly I'm not
1676
        // really entirely sure why. Fuzzing is happy though, and truly
1677
        // everything must be ok if the fuzzers are happy, right?
1678
19.6k
        let mut encoder = if info.imported || info.interface.is_none() {
1679
4.41k
            self.root_import_type_encoder(None)
1680
        } else {
1681
15.1k
            self.root_export_type_encoder(info.interface)
1682
        };
1683
19.6k
        match info.ty {
1684
19.6k
            PayloadType::Type { id, .. } => match encoder.encode_valtype(resolve, &Type::Id(id))? {
1685
19.6k
                ComponentValType::Type(index) => Ok(index),
1686
0
                ComponentValType::Primitive(_) => unreachable!(),
1687
            },
1688
0
            PayloadType::UnitFuture => Ok(encoder.encode_unit_future()),
1689
0
            PayloadType::UnitStream => Ok(encoder.encode_unit_stream()),
1690
        }
1691
19.6k
    }
1692
1693
    /// This is a helper function that will declare any types necessary for
1694
    /// declaring intrinsics that are imported into the module or adapter.
1695
    ///
1696
    /// For example resources must be declared to generate
1697
    /// destructors/constructors/etc. Additionally types must also be declared
1698
    /// for `task.return` with the component model async feature.
1699
4.76k
    fn declare_types_for_imported_intrinsics(&mut self, shims: &Shims<'_>) -> Result<()> {
1700
4.76k
        let resolve = &self.info.encoder.metadata.resolve;
1701
4.76k
        let world = &resolve.worlds[self.info.encoder.metadata.world];
1702
1703
        // Iterate over the main module's exports and the exports of all
1704
        // adapters. Look for exported interfaces.
1705
4.76k
        let main_module_keys = self.info.encoder.main_module_exports.iter();
1706
9.21k
        let main_module_keys = main_module_keys.map(|key| (CustomModule::Main, key));
1707
4.76k
        let adapter_keys = self.info.encoder.adapters.iter().flat_map(|(name, info)| {
1708
0
            info.required_exports
1709
0
                .iter()
1710
0
                .map(move |key| (CustomModule::Adapter(name), key))
1711
0
        });
1712
9.21k
        for (for_module, key) in main_module_keys.chain(adapter_keys) {
1713
9.21k
            let id = match &world.exports[key] {
1714
8.74k
                WorldItem::Interface { id, .. } => *id,
1715
0
                WorldItem::Type { .. } => unreachable!(),
1716
477
                WorldItem::Function(_) => continue,
1717
            };
1718
1719
40.7k
            for ty in resolve.interfaces[id].types.values() {
1720
40.7k
                let def = &resolve.types[*ty];
1721
40.7k
                match &def.kind {
1722
                    // Declare exported resources specially as they generally
1723
                    // need special treatment for later handling exports and
1724
                    // such.
1725
                    TypeDefKind::Resource => {
1726
                        // Load the destructor, previously detected in module
1727
                        // validation, if one is present.
1728
1.27k
                        let exports = self.info.exports_for(for_module);
1729
1.27k
                        let dtor = exports.resource_dtor(*ty).map(|name| {
1730
1.27k
                            let shim = &shims.shims[&ShimKind::ResourceDtor {
1731
1.27k
                                module: for_module,
1732
1.27k
                                export: name,
1733
1.27k
                            }];
1734
1.27k
                            let index = self.shim_instance_index.unwrap();
1735
1.27k
                            self.core_alias_export(
1736
1.27k
                                Some(&shim.debug_name),
1737
1.27k
                                index,
1738
1.27k
                                &shim.name,
1739
1.27k
                                ExportKind::Func,
1740
                            )
1741
1.27k
                        });
1742
1743
                        // Declare the resource with this destructor and
1744
                        // register it in our internal map. This should be the
1745
                        // first and only time this type is inserted into this
1746
                        // map.
1747
                        //
1748
                        // Note that the `rep` of this resource is the index
1749
                        // type for linear memory and isn't otherwise
1750
                        // customizable at this time.
1751
1.27k
                        let resource_idx = self.component.type_resource(
1752
1.27k
                            Some(def.name.as_ref().unwrap()),
1753
1.27k
                            self.info.index_type().encoder_ptr(),
1754
1.27k
                            dtor,
1755
                        );
1756
1.27k
                        let prev = self
1757
1.27k
                            .type_encoding_maps
1758
1.27k
                            .id_to_index
1759
1.27k
                            .insert(*ty, resource_idx);
1760
1.27k
                        assert!(prev.is_none());
1761
                    }
1762
39.4k
                    _other => {
1763
39.4k
                        self.root_export_type_encoder(Some(id))
1764
39.4k
                            .encode_valtype(resolve, &Type::Id(*ty))?;
1765
                    }
1766
                }
1767
            }
1768
        }
1769
4.76k
        Ok(())
1770
4.76k
    }
1771
1772
    /// Helper to instantiate the main module and record various results of its
1773
    /// instantiation within `self`.
1774
4.76k
    fn instantiate_main_module(&mut self, shims: &Shims<'_>) -> Result<()> {
1775
4.76k
        assert!(self.instance_index.is_none());
1776
1777
4.76k
        let instance_index = self.instantiate_core_module(shims, CustomModule::Main)?;
1778
1779
        // If memory hasn't been defined yet then it's provided by the main
1780
        // module here.
1781
4.76k
        if self.memory_index.is_none() {
1782
4.76k
            if let Some((memory, _)) = self.info.info.exports.memory() {
1783
4.76k
                self.memory_index = Some(self.core_alias_export(
1784
4.76k
                    Some("memory"),
1785
4.76k
                    instance_index,
1786
4.76k
                    memory,
1787
4.76k
                    ExportKind::Memory,
1788
4.76k
                ));
1789
4.76k
            }
1790
0
        }
1791
1792
4.76k
        self.instance_index = Some(instance_index);
1793
4.76k
        Ok(())
1794
4.76k
    }
1795
1796
    /// This function will instantiate the specified adapter module, which may
1797
    /// depend on previously-instantiated modules.
1798
0
    fn instantiate_adapter_module(&mut self, shims: &Shims<'_>, name: &'a str) -> Result<()> {
1799
0
        let instance = self.instantiate_core_module(shims, CustomModule::Adapter(name))?;
1800
0
        self.adapter_instances.insert(name, instance);
1801
0
        Ok(())
1802
0
    }
1803
1804
    /// Generic helper to instantiate a module.
1805
    ///
1806
    /// The `for_module` provided will have all of its imports satisfied from
1807
    /// either previous instantiations or the `shims` module present. This
1808
    /// iterates over the metadata produced during validation to determine what
1809
    /// hooks up to what import.
1810
4.76k
    fn instantiate_core_module(
1811
4.76k
        &mut self,
1812
4.76k
        shims: &Shims,
1813
4.76k
        for_module: CustomModule<'_>,
1814
4.76k
    ) -> Result<u32> {
1815
4.76k
        let module = self.module_for(for_module);
1816
1817
4.76k
        let mut args = Vec::new();
1818
4.87k
        for (core_wasm_name, instance) in self.info.imports_for(for_module).modules() {
1819
4.87k
            match instance {
1820
                // For import modules that are a "bag of names" iterate over
1821
                // each name and materialize it into this component with the
1822
                // `materialize_import` helper. This is then all bottled up into
1823
                // a bag-of-exports instance which is then used for
1824
                // instantiation.
1825
4.87k
                ImportInstance::Names(names) => {
1826
4.87k
                    let mut exports = Vec::new();
1827
43.6k
                    for (name, import) in names {
1828
43.6k
                        log::trace!(
1829
                            "attempting to materialize import of `{core_wasm_name}::{name}` for {for_module:?}"
1830
                        );
1831
43.6k
                        let (kind, index) = self
1832
43.6k
                            .materialize_import(&shims, for_module, import)
1833
43.6k
                            .with_context(|| {
1834
0
                                format!("failed to satisfy import `{core_wasm_name}::{name}`")
1835
0
                            })?;
1836
43.6k
                        exports.push((name.as_str(), kind, index));
1837
                    }
1838
4.87k
                    let index = self
1839
4.87k
                        .component
1840
4.87k
                        .core_instantiate_exports(Some(core_wasm_name), exports);
1841
4.87k
                    args.push((core_wasm_name.as_str(), ModuleArg::Instance(index)));
1842
                }
1843
1844
                // Some imports are entire instances, so use the instance for
1845
                // the module identifier as the import.
1846
0
                ImportInstance::Whole(which) => {
1847
0
                    let instance = self.instance_for(which.to_custom_module());
1848
0
                    args.push((core_wasm_name.as_str(), ModuleArg::Instance(instance)));
1849
0
                }
1850
            }
1851
        }
1852
1853
        // And with all arguments prepared now, instantiate the module.
1854
4.76k
        Ok(self
1855
4.76k
            .component
1856
4.76k
            .core_instantiate(Some(for_module.debug_name()), module, args))
1857
4.76k
    }
1858
1859
    /// Helper function to materialize an import into a core module within the
1860
    /// component being built.
1861
    ///
1862
    /// This function is called for individual imports and uses the results of
1863
    /// validation, notably the `Import` type, to determine what WIT-level or
1864
    /// component-level construct is being hooked up.
1865
43.6k
    fn materialize_import(
1866
43.6k
        &mut self,
1867
43.6k
        shims: &Shims<'_>,
1868
43.6k
        for_module: CustomModule<'_>,
1869
43.6k
        import: &'a Import,
1870
43.6k
    ) -> Result<(ExportKind, u32)> {
1871
43.6k
        let resolve = &self.info.encoder.metadata.resolve;
1872
43.6k
        match import {
1873
            // Main module dependencies on an adapter in use are done with an
1874
            // indirection here, so load the shim function and use that.
1875
            Import::AdapterExport {
1876
0
                adapter,
1877
0
                func,
1878
                ty: _,
1879
            } => {
1880
0
                assert!(self.info.encoder.adapters.contains_key(adapter));
1881
0
                Ok(self.materialize_shim_import(shims, &ShimKind::Adapter { adapter, func }))
1882
            }
1883
1884
            // Adapters might use the main module's memory, in which case it
1885
            // should have been previously instantiated.
1886
            Import::MainModuleMemory(_) => {
1887
0
                let index = self
1888
0
                    .memory_index
1889
0
                    .ok_or_else(|| anyhow!("main module cannot import memory"))?;
1890
0
                Ok((ExportKind::Memory, index))
1891
            }
1892
1893
            // Grab-bag of "this adapter wants this thing from the main module".
1894
0
            Import::MainModuleExport { name, kind } => {
1895
0
                let instance = self.instance_index.unwrap();
1896
0
                let index = self.core_alias_export(Some(name), instance, name, *kind);
1897
0
                Ok((*kind, index))
1898
            }
1899
1900
            // A similar grab-bag to above but with a slightly different
1901
            // structure. Should probably refactor to make these two the same in
1902
            // the future.
1903
0
            Import::Item(item) => {
1904
0
                let instance = self.instance_for(item.which.to_custom_module());
1905
0
                let index =
1906
0
                    self.core_alias_export(Some(&item.name), instance, &item.name, item.kind);
1907
0
                Ok((item.kind, index))
1908
            }
1909
1910
            // Resource intrinsics related to exported resources. Despite being
1911
            // an exported resource the component still provides necessary
1912
            // intrinsics for manipulating resource state. These are all
1913
            // handled here using the resource types created during
1914
            // `declare_types_for_imported_intrinsics` above.
1915
1.27k
            Import::ExportedResourceDrop(_key, id) => {
1916
1.27k
                let index = self
1917
1.27k
                    .component
1918
1.27k
                    .resource_drop(self.type_encoding_maps.id_to_index[id]);
1919
1.27k
                Ok((ExportKind::Func, index))
1920
            }
1921
1.27k
            Import::ExportedResourceRep(_key, id) => {
1922
1.27k
                let index = self
1923
1.27k
                    .component
1924
1.27k
                    .resource_rep(self.type_encoding_maps.id_to_index[id]);
1925
1.27k
                Ok((ExportKind::Func, index))
1926
            }
1927
1.27k
            Import::ExportedResourceNew(_key, id) => {
1928
1.27k
                let index = self
1929
1.27k
                    .component
1930
1.27k
                    .resource_new(self.type_encoding_maps.id_to_index[id]);
1931
1.27k
                Ok((ExportKind::Func, index))
1932
            }
1933
1934
            // And finally here at the end these cases are going to all fall
1935
            // through to the code below. This is where these are connected to a
1936
            // WIT `ImportedInterface` one way or another with the name that was
1937
            // detected during validation.
1938
429
            Import::ImportedResourceDrop(key, iface, id) => {
1939
429
                let ty = &resolve.types[*id];
1940
429
                let name = ty.name.as_ref().unwrap();
1941
429
                self.materialize_wit_import(
1942
429
                    shims,
1943
429
                    for_module,
1944
429
                    iface.map(|_| resolve.name_world_key(key)),
1945
429
                    &format!("{name}_drop"),
1946
429
                    key,
1947
429
                    AbiVariant::GuestImport,
1948
                )
1949
            }
1950
2.00k
            Import::ExportedTaskReturn(key, interface, func) => {
1951
2.00k
                let (options, _sig) =
1952
2.00k
                    task_return_options_and_type(resolve, self.info.encoder.metadata.world, func);
1953
2.00k
                let result_ty = func.result;
1954
2.00k
                if options.is_empty() || self.memory_index.is_some() {
1955
                    // Note that an "import type encoder" is used here despite
1956
                    // this being for an exported function if the `interface`
1957
                    // is none, meaning that this is for a top-level world
1958
                    // function. In that situation all types that can be
1959
                    // referred to are imported, not exported.
1960
1.43k
                    let mut encoder = if interface.is_none() {
1961
72
                        self.root_import_type_encoder(*interface)
1962
                    } else {
1963
1.36k
                        self.root_export_type_encoder(*interface)
1964
                    };
1965
1966
1.43k
                    let result = match result_ty.as_ref() {
1967
1.34k
                        Some(ty) => Some(encoder.encode_valtype(resolve, ty)?),
1968
91
                        None => None,
1969
                    };
1970
1.43k
                    let metadata = &self.info.module_metadata_for(for_module);
1971
1.43k
                    let encoding = metadata
1972
1.43k
                        .export_encodings
1973
1.43k
                        .get(resolve, key, &func.name)
1974
1.43k
                        .ok_or_else(|| {
1975
0
                            anyhow!("missing component metadata for export of `{}`", func.name)
1976
0
                        })?;
1977
1.43k
                    let options = options
1978
1.43k
                        .into_iter(encoding, self.memory_index, None)?
1979
1.43k
                        .collect::<Vec<_>>();
1980
1.43k
                    let index = self.component.task_return(result, options);
1981
1.43k
                    Ok((ExportKind::Func, index))
1982
                } else {
1983
574
                    let metadata = &self.info.module_metadata_for(for_module);
1984
574
                    let encoding = metadata
1985
574
                        .export_encodings
1986
574
                        .get(resolve, key, &func.name)
1987
574
                        .unwrap();
1988
574
                    Ok(self.materialize_shim_import(
1989
574
                        shims,
1990
574
                        &ShimKind::TaskReturn {
1991
574
                            for_module,
1992
574
                            interface: *interface,
1993
574
                            func: &func.name,
1994
574
                            result: result_ty,
1995
574
                            encoding,
1996
574
                        },
1997
574
                    ))
1998
                }
1999
            }
2000
            Import::BackpressureInc => {
2001
933
                let index = self.component.backpressure_inc();
2002
933
                Ok((ExportKind::Func, index))
2003
            }
2004
            Import::BackpressureDec => {
2005
933
                let index = self.component.backpressure_dec();
2006
933
                Ok((ExportKind::Func, index))
2007
            }
2008
            Import::WaitableSetWait => {
2009
933
                if let Some(memory) = self.memory_index {
2010
0
                    let index = self.component.waitable_set_wait(memory);
2011
0
                    return Ok((ExportKind::Func, index));
2012
933
                }
2013
933
                Ok(self.materialize_shim_import(shims, &ShimKind::WaitableSetWait))
2014
            }
2015
            Import::WaitableSetPoll => {
2016
933
                if let Some(memory) = self.memory_index {
2017
0
                    let index = self.component.waitable_set_poll(memory);
2018
0
                    return Ok((ExportKind::Func, index));
2019
933
                }
2020
933
                Ok(self.materialize_shim_import(shims, &ShimKind::WaitableSetPoll))
2021
            }
2022
            Import::SubtaskDrop => {
2023
933
                let index = self.component.subtask_drop();
2024
933
                Ok((ExportKind::Func, index))
2025
            }
2026
933
            Import::SubtaskCancel { async_ } => {
2027
933
                let index = self.component.subtask_cancel(*async_);
2028
933
                Ok((ExportKind::Func, index))
2029
            }
2030
678
            Import::StreamNew(info) => {
2031
678
                let ty = self.payload_type_index(info)?;
2032
678
                let index = self.component.stream_new(ty);
2033
678
                Ok((ExportKind::Func, index))
2034
            }
2035
678
            Import::StreamRead { info, async_ } => self.materialize_payload_import(
2036
678
                shims,
2037
678
                for_module,
2038
678
                info,
2039
678
                PayloadFuncKind::StreamRead,
2040
678
                *async_,
2041
            ),
2042
678
            Import::StreamWrite { info, async_ } => self.materialize_payload_import(
2043
678
                shims,
2044
678
                for_module,
2045
678
                info,
2046
678
                PayloadFuncKind::StreamWrite,
2047
678
                *async_,
2048
            ),
2049
678
            Import::StreamForward(info) => {
2050
678
                let ty = self.payload_type_index(info)?;
2051
678
                let index = self.component.stream_forward(ty);
2052
678
                Ok((ExportKind::Func, index))
2053
            }
2054
678
            Import::StreamCancelRead { info, async_ } => {
2055
678
                let ty = self.payload_type_index(info)?;
2056
678
                let index = self.component.stream_cancel_read(ty, *async_);
2057
678
                Ok((ExportKind::Func, index))
2058
            }
2059
678
            Import::StreamCancelWrite { info, async_ } => {
2060
678
                let ty = self.payload_type_index(info)?;
2061
678
                let index = self.component.stream_cancel_write(ty, *async_);
2062
678
                Ok((ExportKind::Func, index))
2063
            }
2064
678
            Import::StreamDropReadable(info) => {
2065
678
                let type_index = self.payload_type_index(info)?;
2066
678
                let index = self.component.stream_drop_readable(type_index);
2067
678
                Ok((ExportKind::Func, index))
2068
            }
2069
678
            Import::StreamDropWritable(info) => {
2070
678
                let type_index = self.payload_type_index(info)?;
2071
678
                let index = self.component.stream_drop_writable(type_index);
2072
678
                Ok((ExportKind::Func, index))
2073
            }
2074
1.99k
            Import::FutureNew(info) => {
2075
1.99k
                let ty = self.payload_type_index(info)?;
2076
1.99k
                let index = self.component.future_new(ty);
2077
1.99k
                Ok((ExportKind::Func, index))
2078
            }
2079
1.99k
            Import::FutureRead { info, async_ } => self.materialize_payload_import(
2080
1.99k
                shims,
2081
1.99k
                for_module,
2082
1.99k
                info,
2083
1.99k
                PayloadFuncKind::FutureRead,
2084
1.99k
                *async_,
2085
            ),
2086
1.99k
            Import::FutureWrite { info, async_ } => self.materialize_payload_import(
2087
1.99k
                shims,
2088
1.99k
                for_module,
2089
1.99k
                info,
2090
1.99k
                PayloadFuncKind::FutureWrite,
2091
1.99k
                *async_,
2092
            ),
2093
1.99k
            Import::FutureForward(info) => {
2094
1.99k
                let ty = self.payload_type_index(info)?;
2095
1.99k
                let index = self.component.future_forward(ty);
2096
1.99k
                Ok((ExportKind::Func, index))
2097
            }
2098
1.99k
            Import::FutureCancelRead { info, async_ } => {
2099
1.99k
                let ty = self.payload_type_index(info)?;
2100
1.99k
                let index = self.component.future_cancel_read(ty, *async_);
2101
1.99k
                Ok((ExportKind::Func, index))
2102
            }
2103
1.99k
            Import::FutureCancelWrite { info, async_ } => {
2104
1.99k
                let ty = self.payload_type_index(info)?;
2105
1.99k
                let index = self.component.future_cancel_write(ty, *async_);
2106
1.99k
                Ok((ExportKind::Func, index))
2107
            }
2108
1.99k
            Import::FutureDropReadable(info) => {
2109
1.99k
                let type_index = self.payload_type_index(info)?;
2110
1.99k
                let index = self.component.future_drop_readable(type_index);
2111
1.99k
                Ok((ExportKind::Func, index))
2112
            }
2113
1.99k
            Import::FutureDropWritable(info) => {
2114
1.99k
                let type_index = self.payload_type_index(info)?;
2115
1.99k
                let index = self.component.future_drop_writable(type_index);
2116
1.99k
                Ok((ExportKind::Func, index))
2117
            }
2118
0
            Import::ErrorContextNew { encoding } => {
2119
0
                if self.memory_index.is_some() {
2120
0
                    let options = (RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING)
2121
0
                        .into_iter(*encoding, self.memory_index, None)?;
2122
0
                    let index = self.component.error_context_new(options);
2123
0
                    return Ok((ExportKind::Func, index));
2124
0
                }
2125
0
                Ok(self.materialize_shim_import(
2126
0
                    shims,
2127
0
                    &ShimKind::ErrorContextNew {
2128
0
                        encoding: *encoding,
2129
0
                    },
2130
0
                ))
2131
            }
2132
0
            Import::ErrorContextDebugMessage { encoding } => Ok(self.materialize_shim_import(
2133
0
                shims,
2134
0
                &ShimKind::ErrorContextDebugMessage {
2135
0
                    for_module,
2136
0
                    encoding: *encoding,
2137
0
                },
2138
0
            )),
2139
            Import::ErrorContextDrop => {
2140
0
                let index = self.component.error_context_drop();
2141
0
                Ok((ExportKind::Func, index))
2142
            }
2143
1.14k
            Import::WorldFunc(key, name, abi) => {
2144
1.14k
                self.materialize_wit_import(shims, for_module, None, name, key, *abi)
2145
            }
2146
2.78k
            Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import(
2147
2.78k
                shims,
2148
2.78k
                for_module,
2149
2.78k
                Some(resolve.name_world_key(key)),
2150
2.78k
                name,
2151
2.78k
                key,
2152
2.78k
                *abi,
2153
            ),
2154
2155
            Import::WaitableSetNew => {
2156
933
                let index = self.component.waitable_set_new();
2157
933
                Ok((ExportKind::Func, index))
2158
            }
2159
            Import::WaitableSetDrop => {
2160
933
                let index = self.component.waitable_set_drop();
2161
933
                Ok((ExportKind::Func, index))
2162
            }
2163
            Import::WaitableJoin => {
2164
933
                let index = self.component.waitable_join();
2165
933
                Ok((ExportKind::Func, index))
2166
            }
2167
933
            Import::ContextGet { ty, slot } => {
2168
933
                let index = self.component.context_get((*ty).try_into()?, *slot);
2169
933
                Ok((ExportKind::Func, index))
2170
            }
2171
933
            Import::ContextSet { ty, slot } => {
2172
933
                let index = self.component.context_set((*ty).try_into()?, *slot);
2173
933
                Ok((ExportKind::Func, index))
2174
            }
2175
0
            Import::TlsBaseGet { ty } => Ok((
2176
0
                ExportKind::Func,
2177
0
                self.materialize_tls_base_import(false, (*ty).try_into()?),
2178
            )),
2179
0
            Import::TlsBaseSet { ty } => Ok((
2180
0
                ExportKind::Func,
2181
0
                self.materialize_tls_base_import(true, (*ty).try_into()?),
2182
            )),
2183
            Import::ExportedTaskCancel => {
2184
933
                let index = self.component.task_cancel();
2185
933
                Ok((ExportKind::Func, index))
2186
            }
2187
            Import::ThreadIndex => {
2188
0
                let index = self.component.thread_index();
2189
0
                Ok((ExportKind::Func, index))
2190
            }
2191
0
            Import::ThreadNewIndirect { closure_ty, .. } => Ok(self.materialize_shim_import(
2192
0
                shims,
2193
                &ShimKind::ThreadNewIndirect {
2194
0
                    func_ty: FuncType::new([(*closure_ty).try_into()?], []),
2195
                },
2196
            )),
2197
            Import::ThreadResumeLater => {
2198
0
                let index = self.component.thread_resume_later();
2199
0
                Ok((ExportKind::Func, index))
2200
            }
2201
            Import::ThreadSuspend => {
2202
0
                let index = self.component.thread_suspend();
2203
0
                Ok((ExportKind::Func, index))
2204
            }
2205
            Import::ThreadYield => {
2206
933
                let index = self.component.thread_yield();
2207
933
                Ok((ExportKind::Func, index))
2208
            }
2209
            Import::ThreadSuspendThenResume => {
2210
0
                let index = self.component.thread_suspend_then_resume();
2211
0
                Ok((ExportKind::Func, index))
2212
            }
2213
            Import::ThreadYieldThenResume => {
2214
0
                let index = self.component.thread_yield_then_resume();
2215
0
                Ok((ExportKind::Func, index))
2216
            }
2217
            Import::ThreadSuspendThenPromote => {
2218
0
                let index = self.component.thread_suspend_then_promote();
2219
0
                Ok((ExportKind::Func, index))
2220
            }
2221
            Import::ThreadYieldThenPromote => {
2222
0
                let index = self.component.thread_yield_then_promote();
2223
0
                Ok((ExportKind::Func, index))
2224
            }
2225
        }
2226
43.6k
    }
2227
2228
    /// Helper to satisfy `__wasm_{get,set}_tls_base` imports.
2229
    ///
2230
    /// For more information on this see WebAssembly/wasi-libc#857
2231
0
    fn materialize_tls_base_import(&mut self, set: bool, ty: ValType) -> u32 {
2232
0
        if self.info.can_use_context_slot_1() {
2233
0
            if set {
2234
0
                self.component.context_set(ty, 1)
2235
            } else {
2236
0
                self.component.context_get(ty, 1)
2237
            }
2238
        } else {
2239
0
            let name = if set { TLS_BASE_SET } else { TLS_BASE_GET };
2240
0
            self.core_alias_export(
2241
0
                Some(name),
2242
0
                self.shim_instance_index.unwrap(),
2243
0
                name,
2244
0
                ExportKind::Func,
2245
            )
2246
        }
2247
0
    }
2248
2249
    /// Helper for `materialize_import` above for materializing functions that
2250
    /// are part of the "shim module" generated.
2251
9.09k
    fn materialize_shim_import(&mut self, shims: &Shims<'_>, kind: &ShimKind) -> (ExportKind, u32) {
2252
9.09k
        let index = self.core_alias_export(
2253
9.09k
            Some(&shims.shims[kind].debug_name),
2254
9.09k
            self.shim_instance_index
2255
9.09k
                .expect("shim should be instantiated"),
2256
9.09k
            &shims.shims[kind].name,
2257
9.09k
            ExportKind::Func,
2258
        );
2259
9.09k
        (ExportKind::Func, index)
2260
9.09k
    }
2261
2262
    /// Helper for `materialize_import` above for generating imports for
2263
    /// future/stream read/write intrinsics.
2264
5.34k
    fn materialize_payload_import(
2265
5.34k
        &mut self,
2266
5.34k
        shims: &Shims<'_>,
2267
5.34k
        for_module: CustomModule<'_>,
2268
5.34k
        info: &PayloadInfo,
2269
5.34k
        kind: PayloadFuncKind,
2270
5.34k
        async_: bool,
2271
5.34k
    ) -> Result<(ExportKind, u32)> {
2272
5.34k
        let shim_kind = ShimKind::PayloadFunc {
2273
5.34k
            for_module,
2274
5.34k
            info,
2275
5.34k
            kind,
2276
5.34k
        };
2277
5.34k
        if shims.shims.get(&shim_kind).is_some() {
2278
5.34k
            return Ok(self.materialize_shim_import(shims, &shim_kind));
2279
0
        }
2280
0
        let resolve = &self.info.encoder.metadata.resolve;
2281
0
        let world = self.info.encoder.metadata.world;
2282
0
        let options = RequiredOptions::for_payload(resolve, world, info, &kind, async_);
2283
0
        let func = self.encode_payload_func(
2284
0
            shims,
2285
0
            &for_module,
2286
0
            info,
2287
0
            &kind,
2288
0
            options,
2289
0
            ReallocSite::BeforeInstantiation,
2290
0
        )?;
2291
0
        Ok((ExportKind::Func, func))
2292
5.34k
    }
2293
2294
    /// Helper for `materialize_import` above which specifically operates on
2295
    /// WIT-level functions identified by `interface_key`, `name`, and `abi`.
2296
4.35k
    fn materialize_wit_import(
2297
4.35k
        &mut self,
2298
4.35k
        shims: &Shims<'_>,
2299
4.35k
        for_module: CustomModule<'_>,
2300
4.35k
        interface_key: Option<String>,
2301
4.35k
        name: &String,
2302
4.35k
        key: &WorldKey,
2303
4.35k
        abi: AbiVariant,
2304
4.35k
    ) -> Result<(ExportKind, u32)> {
2305
4.35k
        let resolve = &self.info.encoder.metadata.resolve;
2306
4.35k
        let import = &self.info.import_map[&interface_key];
2307
4.35k
        let (index, _, lowering) = import.lowerings.get_full(&(name.clone(), abi)).unwrap();
2308
4.35k
        let metadata = self.info.module_metadata_for(for_module);
2309
2310
4.35k
        let index = match lowering {
2311
            // All direct lowerings can be `canon lower`'d here immediately
2312
            // and passed as arguments.
2313
2.62k
            Lowering::Direct { options } => {
2314
2.62k
                let func_index = match &import.interface {
2315
1.83k
                    Some(interface) => {
2316
1.83k
                        let instance_index = self.instances[interface];
2317
1.83k
                        self.component
2318
1.83k
                            .alias_export(instance_index, name, ComponentExportKind::Func)
2319
                    }
2320
784
                    None => self.imported_funcs[name],
2321
                };
2322
2.62k
                let encoding = metadata
2323
2.62k
                    .import_encodings
2324
2.62k
                    .get(resolve, key, name)
2325
2.62k
                    .ok_or_else(|| anyhow!("missing component metadata for import of `{name}`"))?;
2326
2.62k
                let realloc = self
2327
2.62k
                    .info
2328
2.62k
                    .exports_for(for_module)
2329
2.62k
                    .import_realloc_for(import.interface, name);
2330
2.62k
                let realloc = self.realloc_index(
2331
2.62k
                    shims,
2332
2.62k
                    for_module,
2333
2.62k
                    ReallocSite::BeforeInstantiation,
2334
2.62k
                    *options,
2335
2.62k
                    realloc,
2336
                );
2337
2.62k
                let options = options
2338
2.62k
                    .into_iter(encoding, self.memory_index, realloc)?
2339
2.62k
                    .collect::<Vec<_>>();
2340
2.62k
                self.component.lower_func(Some(name), func_index, options)
2341
            }
2342
2343
            // Indirect lowerings come from the shim that was previously
2344
            // created, so the specific export is loaded here and used as an
2345
            // import.
2346
            Lowering::Indirect { .. } => {
2347
1.30k
                let encoding = metadata.import_encodings.get(resolve, key, name).unwrap();
2348
1.30k
                return Ok(self.materialize_shim_import(
2349
1.30k
                    shims,
2350
1.30k
                    &ShimKind::IndirectLowering {
2351
1.30k
                        interface: interface_key,
2352
1.30k
                        index,
2353
1.30k
                        realloc: for_module,
2354
1.30k
                        encoding,
2355
1.30k
                    },
2356
1.30k
                ));
2357
            }
2358
2359
            // A "resource drop" intrinsic only needs to find the index of the
2360
            // resource type itself and then the intrinsic is declared.
2361
429
            Lowering::ResourceDrop(id) => {
2362
429
                let resource_idx = self.lookup_resource_index(*id);
2363
429
                self.component.resource_drop(resource_idx)
2364
            }
2365
        };
2366
3.04k
        Ok((ExportKind::Func, index))
2367
4.35k
    }
2368
2369
    /// Returns the core function index to use for the `realloc` canonical
2370
    /// option where the function is named `export` within `module`.
2371
7.49k
    fn realloc_index(
2372
7.49k
        &mut self,
2373
7.49k
        shims: &Shims<'_>,
2374
7.49k
        module: CustomModule<'_>,
2375
7.49k
        site: ReallocSite,
2376
7.49k
        options: RequiredOptions,
2377
7.49k
        export: Option<&str>,
2378
7.49k
    ) -> Option<u32> {
2379
7.49k
        if !options.contains(RequiredOptions::REALLOC) {
2380
7.33k
            return None;
2381
162
        }
2382
162
        let (module, export) = resolve_realloc(self.info, module, export)?;
2383
2384
162
        if !realloc_needs_shim(self.info, site) {
2385
162
            let instance = self.instance_for(module);
2386
162
            return Some(self.core_alias_export(Some(export), instance, export, ExportKind::Func));
2387
0
        }
2388
2389
0
        let kind = ShimKind::Realloc { module, export };
2390
0
        let shim = shims.shims.get(&kind).unwrap_or_else(|| {
2391
0
            panic!(
2392
                "no shim was registered for the `realloc` \
2393
                 function `{export}` in `{}`",
2394
0
                module.debug_name()
2395
            )
2396
        });
2397
0
        let instance = self
2398
0
            .shim_instance_index
2399
0
            .expect("shim should be instantiated");
2400
0
        Some(self.core_alias_export(
2401
0
            Some(&shim.debug_name),
2402
0
            instance,
2403
0
            &shim.name,
2404
0
            ExportKind::Func,
2405
0
        ))
2406
7.49k
    }
2407
2408
31.5k
    fn hooked_core_alias_export(&mut self, module: CustomModule<'_>, core_name: &str) -> u32 {
2409
31.5k
        let key = (module.to_imported_instance(), core_name.to_string());
2410
31.5k
        if let Some(&wrapper_idx) = self.export_task_initialization_wrappers.get(&key) {
2411
0
            wrapper_idx
2412
        } else {
2413
31.5k
            let instance = self.instance_for(module);
2414
31.5k
            self.core_alias_export(Some(core_name), instance, core_name, ExportKind::Func)
2415
        }
2416
31.5k
    }
2417
2418
    /// Convenience function to go from `CustomModule` to the instance index
2419
    /// corresponding to what that points to.
2420
33.6k
    fn instance_for(&self, module: CustomModule) -> u32 {
2421
33.6k
        match module {
2422
33.6k
            CustomModule::Main => self.instance_index.expect("instantiated by now"),
2423
0
            CustomModule::Adapter(name) => self.adapter_instances[name],
2424
        }
2425
33.6k
    }
2426
2427
    /// Convenience function to go from `CustomModule` to the module index
2428
    /// corresponding to what that points to.
2429
4.76k
    fn module_for(&self, module: CustomModule) -> u32 {
2430
4.76k
        match module {
2431
4.76k
            CustomModule::Main => self.module_index.unwrap(),
2432
0
            CustomModule::Adapter(name) => self.adapter_modules[name],
2433
        }
2434
4.76k
    }
2435
2436
    /// Convenience function which caches aliases created so repeated calls to
2437
    /// this function will all return the same index.
2438
48.7k
    fn core_alias_export(
2439
48.7k
        &mut self,
2440
48.7k
        debug_name: Option<&str>,
2441
48.7k
        instance: u32,
2442
48.7k
        name: &str,
2443
48.7k
        kind: ExportKind,
2444
48.7k
    ) -> u32 {
2445
48.7k
        *self
2446
48.7k
            .aliased_core_items
2447
48.7k
            .entry((instance, name.to_string()))
2448
48.7k
            .or_insert_with(|| {
2449
45.3k
                self.component
2450
45.3k
                    .core_alias_export(debug_name, instance, name, kind)
2451
45.3k
            })
2452
48.7k
    }
2453
}
2454
2455
/// A list of "shims" which start out during the component instantiation process
2456
/// as functions which immediately trap due to a `call_indirect`-to-`null` but
2457
/// will get filled in by the time the component instantiation process
2458
/// completes.
2459
///
2460
/// Shims currently include:
2461
///
2462
/// * "Indirect functions" lowered from imported instances where the lowering
2463
///   requires an item exported from the main module. These are indirect due to
2464
///   the circular dependency between the module needing an import and the
2465
///   import needing the module.
2466
///
2467
/// * Adapter modules which convert from a historical ABI to the component
2468
///   model's ABI (e.g. wasi preview1 to preview2) get a shim since the adapters
2469
///   are currently indicated as always requiring the memory of the main module.
2470
///
2471
/// This structure is created by `encode_shim_instantiation`.
2472
#[derive(Default)]
2473
struct Shims<'a> {
2474
    /// The list of all shims that a module will require.
2475
    shims: IndexMap<ShimKind<'a>, Shim<'a>>,
2476
}
2477
2478
struct Shim<'a> {
2479
    /// Canonical ABI options required by this shim, used during `canon lower`
2480
    /// operations.
2481
    options: RequiredOptions,
2482
2483
    /// The name, in the shim instance, of this shim.
2484
    ///
2485
    /// Currently this is `"0"`, `"1"`, ...
2486
    name: String,
2487
2488
    /// A human-readable debugging name for this shim, used in a core wasm
2489
    /// `name` section.
2490
    debug_name: String,
2491
2492
    /// Precise information about what this shim is a lowering of.
2493
    kind: ShimKind<'a>,
2494
2495
    /// Wasm type of this shim.
2496
    sig: WasmSignature,
2497
}
2498
2499
/// Which variation of `{stream|future}.{read|write}` we're emitting for a
2500
/// `ShimKind::PayloadFunc`.
2501
#[derive(Debug, Clone, Hash, Eq, PartialEq, Copy)]
2502
enum PayloadFuncKind {
2503
    FutureWrite,
2504
    FutureRead,
2505
    StreamWrite,
2506
    StreamRead,
2507
}
2508
2509
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
2510
enum ShimKind<'a> {
2511
    /// This shim is a late indirect lowering of an imported function in a
2512
    /// component which is only possible after prior core wasm modules are
2513
    /// instantiated so their memories and functions are available.
2514
    IndirectLowering {
2515
        /// The name of the interface that's being lowered.
2516
        interface: Option<String>,
2517
        /// The index within the `lowerings` array of the function being lowered.
2518
        index: usize,
2519
        /// Which instance to pull the `realloc` function from, if necessary.
2520
        realloc: CustomModule<'a>,
2521
        /// The string encoding that this lowering is going to use.
2522
        encoding: StringEncoding,
2523
    },
2524
    /// This shim is a core wasm function defined in an adapter module but isn't
2525
    /// available until the adapter module is itself instantiated.
2526
    Adapter {
2527
        /// The name of the adapter module this shim comes from.
2528
        adapter: &'a str,
2529
        /// The name of the export in the adapter module this shim points to.
2530
        func: &'a str,
2531
    },
2532
    /// A shim used as the destructor for a resource which allows defining the
2533
    /// resource before the core module being instantiated.
2534
    ResourceDtor {
2535
        /// Which instance to pull the destructor function from.
2536
        module: CustomModule<'a>,
2537
        /// The exported function name of this destructor in the core module.
2538
        export: &'a str,
2539
    },
2540
    /// A shim used for a `{stream|future}.{read|write}` built-in function,
2541
    /// which must refer to the core module instance's memory from/to which
2542
    /// payload values must be lifted/lowered.
2543
    PayloadFunc {
2544
        /// Which instance to pull the `realloc` function and string encoding
2545
        /// from, if necessary.
2546
        for_module: CustomModule<'a>,
2547
        /// Additional information regarding the function where this `stream` or
2548
        /// `future` type appeared, which we use in combination with
2549
        /// `for_module` to determine which `realloc` and string encoding to
2550
        /// use, as well as which type to specify when emitting the built-in.
2551
        info: &'a PayloadInfo,
2552
        /// Which variation of `{stream|future}.{read|write}` we're emitting.
2553
        kind: PayloadFuncKind,
2554
    },
2555
    /// A shim used for the `waitable-set.wait` built-in function, which must
2556
    /// refer to the core module instance's memory to which results will be
2557
    /// written.
2558
    WaitableSetWait,
2559
    /// A shim used for the `waitable-set.poll` built-in function, which must
2560
    /// refer to the core module instance's memory to which results will be
2561
    /// written.
2562
    WaitableSetPoll,
2563
    /// Shim for `task.return` to handle a reference to a `memory` which may
2564
    TaskReturn {
2565
        /// The interface (optional) that owns `func` below. If `None` then it's
2566
        /// a world export.
2567
        interface: Option<InterfaceId>,
2568
        /// The function that this `task.return` is returning for, owned
2569
        /// within `interface` above.
2570
        func: &'a str,
2571
        /// The WIT type that `func` returns.
2572
        result: Option<Type>,
2573
        /// Which instance to pull the `realloc` function from, if necessary.
2574
        for_module: CustomModule<'a>,
2575
        /// String encoding to use in the ABI options.
2576
        encoding: StringEncoding,
2577
    },
2578
    /// A shim used for the `error-context.new` built-in function, which must
2579
    /// refer to the core module instance's memory from which the debug message
2580
    /// will be read.
2581
    ErrorContextNew {
2582
        /// String encoding to use when lifting the debug message.
2583
        encoding: StringEncoding,
2584
    },
2585
    /// A shim used for the `error-context.debug-message` built-in function,
2586
    /// which must refer to the core module instance's memory to which results
2587
    /// will be written.
2588
    ErrorContextDebugMessage {
2589
        /// Which instance to pull the `realloc` function from, if necessary.
2590
        for_module: CustomModule<'a>,
2591
        /// The string encoding to use when lowering the debug message.
2592
        encoding: StringEncoding,
2593
    },
2594
    /// A shim used for the `thread.new-indirect` built-in function, which
2595
    /// must refer to the core module instance's indirect function table.
2596
    ThreadNewIndirect {
2597
        /// The function type to use when creating the thread.
2598
        func_ty: FuncType,
2599
    },
2600
    /// A shim for a `realloc` function used as a canonical option.
2601
    Realloc {
2602
        /// Which instance the `realloc` function is exported from.
2603
        module: CustomModule<'a>,
2604
        /// The name of the `realloc` export within `module`.
2605
        export: &'a str,
2606
    },
2607
}
2608
2609
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2610
enum ReallocSite {
2611
    /// This `realloc` is needed before the main module is instantiated.
2612
    BeforeInstantiation,
2613
    /// This `realloc` is needed after the main module is instantiated, but
2614
    /// before the fixup module is instantiated.
2615
    AfterInstantiation,
2616
}
2617
2618
324
fn realloc_needs_shim(world: &ComponentWorld<'_>, site: ReallocSite) -> bool {
2619
324
    match site {
2620
        // The function isn't available at all yet, so an indirection is
2621
        // required no matter what.
2622
0
        ReallocSite::BeforeInstantiation => true,
2623
2624
        // The function itself is available, but if task hooks are enabled then
2625
        // the hooked version of it is defined by the fixup module which hasn't
2626
        // been instantiated yet.
2627
324
        ReallocSite::AfterInstantiation => world.info.exports.wasm_task_hook().is_some(),
2628
    }
2629
324
}
2630
2631
/// Indicator for which module is being used for a lowering or where options
2632
/// like `realloc` are drawn from.
2633
///
2634
/// This is necessary for situations such as an imported function being lowered
2635
/// into the main module and additionally into an adapter module. For example an
2636
/// adapter might adapt from preview1 to preview2 for the standard library of a
2637
/// programming language but the main module's custom application code may also
2638
/// explicitly import from preview2. These two different lowerings of a preview2
2639
/// function are parameterized by this enumeration.
2640
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
2641
enum CustomModule<'a> {
2642
    /// This points to the "main module" which is generally the "output of LLVM"
2643
    /// or what a user wrote.
2644
    Main,
2645
    /// This is selecting an adapter module, identified by name here, where
2646
    /// something is being lowered into.
2647
    Adapter(&'a str),
2648
}
2649
2650
impl<'a> CustomModule<'a> {
2651
4.76k
    fn debug_name(&self) -> &'a str {
2652
4.76k
        match self {
2653
4.76k
            CustomModule::Main => "main",
2654
0
            CustomModule::Adapter(s) => s,
2655
        }
2656
4.76k
    }
2657
2658
    /// Returns the instance, as imported into the fixup module, that this
2659
    /// module corresponds to.
2660
31.5k
    fn to_imported_instance(&self) -> fixup::ImportedInstance {
2661
31.5k
        match self {
2662
31.5k
            CustomModule::Main => fixup::ImportedInstance::Main,
2663
0
            CustomModule::Adapter(s) => fixup::ImportedInstance::Adapter(s.to_string()),
2664
        }
2665
31.5k
    }
2666
}
2667
2668
impl<'a> Shims<'a> {
2669
    /// Adds all shims necessary for the instantiation of `for_module`.
2670
    ///
2671
    /// This function will iterate over all the imports required by this module
2672
    /// and for those that require a shim they're registered here.
2673
4.76k
    fn append_indirect(
2674
4.76k
        &mut self,
2675
4.76k
        world: &'a ComponentWorld<'a>,
2676
4.76k
        for_module: CustomModule<'a>,
2677
4.76k
    ) -> Result<()> {
2678
4.76k
        let module_imports = world.imports_for(for_module);
2679
4.76k
        let module_exports = world.exports_for(for_module);
2680
4.76k
        let resolve = &world.encoder.metadata.resolve;
2681
4.76k
        let memory_available = world.info.imports.imported_memory().is_some();
2682
2683
43.6k
        for (module, field, import) in module_imports.imports() {
2684
43.6k
            match import {
2685
                // These imports don't require shims, they can be satisfied
2686
                // as-needed when required.
2687
                Import::ImportedResourceDrop(..)
2688
                | Import::MainModuleMemory(_)
2689
                | Import::MainModuleExport { .. }
2690
                | Import::Item(_)
2691
                | Import::ExportedResourceDrop(..)
2692
                | Import::ExportedResourceRep(..)
2693
                | Import::ExportedResourceNew(..)
2694
                | Import::ExportedTaskCancel
2695
                | Import::ErrorContextDrop
2696
                | Import::BackpressureInc
2697
                | Import::BackpressureDec
2698
                | Import::SubtaskDrop
2699
                | Import::SubtaskCancel { .. }
2700
                | Import::FutureNew(..)
2701
                | Import::StreamNew(..)
2702
                | Import::FutureForward { .. }
2703
                | Import::FutureCancelRead { .. }
2704
                | Import::FutureCancelWrite { .. }
2705
                | Import::FutureDropWritable { .. }
2706
                | Import::FutureDropReadable { .. }
2707
                | Import::StreamForward { .. }
2708
                | Import::StreamCancelRead { .. }
2709
                | Import::StreamCancelWrite { .. }
2710
                | Import::StreamDropWritable { .. }
2711
                | Import::StreamDropReadable { .. }
2712
                | Import::WaitableSetNew
2713
                | Import::WaitableSetDrop
2714
                | Import::WaitableJoin
2715
                | Import::ContextGet { .. }
2716
                | Import::ContextSet { .. }
2717
                | Import::TlsBaseGet { .. }
2718
                | Import::TlsBaseSet { .. }
2719
                | Import::ThreadIndex
2720
                | Import::ThreadResumeLater
2721
                | Import::ThreadSuspend { .. }
2722
                | Import::ThreadYield { .. }
2723
                | Import::ThreadSuspendThenResume { .. }
2724
                | Import::ThreadYieldThenResume { .. }
2725
                | Import::ThreadSuspendThenPromote { .. }
2726
30.5k
                | Import::ThreadYieldThenPromote { .. } => {}
2727
2728
                // If `task.return` needs to be indirect then generate a shim
2729
                // for it, otherwise skip the shim and let it get materialized
2730
                // naturally later.
2731
2.00k
                Import::ExportedTaskReturn(key, interface, func) => {
2732
2.00k
                    let (options, sig) =
2733
2.00k
                        task_return_options_and_type(resolve, world.encoder.metadata.world, func);
2734
2.00k
                    if options.is_empty() || memory_available {
2735
1.43k
                        continue;
2736
574
                    }
2737
574
                    let name = self.shims.len().to_string();
2738
574
                    let encoding = world
2739
574
                        .module_metadata_for(for_module)
2740
574
                        .export_encodings
2741
574
                        .get(resolve, key, &func.name)
2742
574
                        .ok_or_else(|| {
2743
0
                            anyhow::anyhow!(
2744
                                "missing component metadata for export of \
2745
                                `{module}::{field}`"
2746
                            )
2747
0
                        })?;
2748
574
                    self.push(Shim {
2749
574
                        name,
2750
574
                        debug_name: format!("task-return-{}", func.name),
2751
574
                        options,
2752
574
                        kind: ShimKind::TaskReturn {
2753
574
                            interface: *interface,
2754
574
                            func: &func.name,
2755
574
                            result: func.result,
2756
574
                            for_module,
2757
574
                            encoding,
2758
574
                        },
2759
574
                        sig,
2760
574
                    });
2761
                }
2762
2763
1.99k
                Import::FutureWrite { async_, info } => {
2764
1.99k
                    self.append_indirect_payload_push(
2765
1.99k
                        world,
2766
1.99k
                        for_module,
2767
1.99k
                        module,
2768
1.99k
                        *async_,
2769
1.99k
                        info,
2770
1.99k
                        PayloadFuncKind::FutureWrite,
2771
1.99k
                        vec![WasmType::I32, WasmType::Pointer],
2772
1.99k
                        vec![WasmType::I32],
2773
1.99k
                    );
2774
1.99k
                }
2775
1.99k
                Import::FutureRead { async_, info } => {
2776
1.99k
                    self.append_indirect_payload_push(
2777
1.99k
                        world,
2778
1.99k
                        for_module,
2779
1.99k
                        module,
2780
1.99k
                        *async_,
2781
1.99k
                        info,
2782
1.99k
                        PayloadFuncKind::FutureRead,
2783
1.99k
                        vec![WasmType::I32, WasmType::Pointer],
2784
1.99k
                        vec![WasmType::I32],
2785
1.99k
                    );
2786
1.99k
                }
2787
678
                Import::StreamWrite { async_, info } => {
2788
678
                    self.append_indirect_payload_push(
2789
678
                        world,
2790
678
                        for_module,
2791
678
                        module,
2792
678
                        *async_,
2793
678
                        info,
2794
678
                        PayloadFuncKind::StreamWrite,
2795
678
                        vec![WasmType::I32, WasmType::Pointer, WasmType::Length],
2796
678
                        vec![WasmType::Length],
2797
678
                    );
2798
678
                }
2799
678
                Import::StreamRead { async_, info } => {
2800
678
                    self.append_indirect_payload_push(
2801
678
                        world,
2802
678
                        for_module,
2803
678
                        module,
2804
678
                        *async_,
2805
678
                        info,
2806
678
                        PayloadFuncKind::StreamRead,
2807
678
                        vec![WasmType::I32, WasmType::Pointer, WasmType::Length],
2808
678
                        vec![WasmType::Length],
2809
678
                    );
2810
678
                }
2811
2812
                Import::WaitableSetWait => {
2813
933
                    if memory_available {
2814
0
                        continue;
2815
933
                    }
2816
933
                    let name = self.shims.len().to_string();
2817
933
                    self.push(Shim {
2818
933
                        name,
2819
933
                        debug_name: "waitable-set.wait".to_string(),
2820
933
                        options: RequiredOptions::empty(),
2821
933
                        kind: ShimKind::WaitableSetWait,
2822
933
                        sig: WasmSignature {
2823
933
                            params: vec![WasmType::I32, WasmType::Pointer],
2824
933
                            results: vec![WasmType::I32],
2825
933
                            indirect_params: false,
2826
933
                            retptr: false,
2827
933
                        },
2828
933
                    });
2829
                }
2830
2831
                Import::WaitableSetPoll => {
2832
933
                    if memory_available {
2833
0
                        continue;
2834
933
                    }
2835
933
                    let name = self.shims.len().to_string();
2836
933
                    self.push(Shim {
2837
933
                        name,
2838
933
                        debug_name: "waitable-set.poll".to_string(),
2839
933
                        options: RequiredOptions::empty(),
2840
933
                        kind: ShimKind::WaitableSetPoll,
2841
933
                        sig: WasmSignature {
2842
933
                            params: vec![WasmType::I32, WasmType::Pointer],
2843
933
                            results: vec![WasmType::I32],
2844
933
                            indirect_params: false,
2845
933
                            retptr: false,
2846
933
                        },
2847
933
                    });
2848
                }
2849
2850
0
                Import::ErrorContextNew { encoding } => {
2851
0
                    if memory_available {
2852
0
                        continue;
2853
0
                    }
2854
0
                    let name = self.shims.len().to_string();
2855
0
                    self.push(Shim {
2856
0
                        name,
2857
0
                        debug_name: "error-new".to_string(),
2858
0
                        options: RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING,
2859
0
                        kind: ShimKind::ErrorContextNew {
2860
0
                            encoding: *encoding,
2861
0
                        },
2862
0
                        sig: WasmSignature {
2863
0
                            params: vec![WasmType::Pointer, WasmType::Length],
2864
0
                            results: vec![WasmType::I32],
2865
0
                            indirect_params: false,
2866
0
                            retptr: false,
2867
0
                        },
2868
0
                    });
2869
                }
2870
2871
0
                Import::ErrorContextDebugMessage { encoding } => {
2872
0
                    let name = self.shims.len().to_string();
2873
0
                    let options = RequiredOptions::MEMORY
2874
0
                        | RequiredOptions::STRING_ENCODING
2875
0
                        | RequiredOptions::REALLOC;
2876
0
                    self.push(Shim {
2877
0
                        name,
2878
0
                        debug_name: "error-debug-message".to_string(),
2879
0
                        options,
2880
0
                        kind: ShimKind::ErrorContextDebugMessage {
2881
0
                            for_module,
2882
0
                            encoding: *encoding,
2883
0
                        },
2884
0
                        sig: WasmSignature {
2885
0
                            params: vec![WasmType::I32, WasmType::Pointer],
2886
0
                            results: vec![],
2887
0
                            indirect_params: false,
2888
0
                            retptr: false,
2889
0
                        },
2890
0
                    });
2891
0
                    let realloc = module_exports.import_realloc_fallback();
2892
0
                    self.push_realloc(
2893
0
                        world,
2894
0
                        for_module,
2895
0
                        ReallocSite::AfterInstantiation,
2896
0
                        options,
2897
0
                        realloc,
2898
0
                    );
2899
0
                }
2900
2901
                Import::ThreadNewIndirect {
2902
0
                    table_idx_ty,
2903
0
                    closure_ty,
2904
                } => {
2905
0
                    let name = self.shims.len().to_string();
2906
0
                    self.push(Shim {
2907
0
                        name,
2908
0
                        debug_name: "thread.new-indirect".to_string(),
2909
0
                        options: RequiredOptions::empty(),
2910
                        kind: ShimKind::ThreadNewIndirect {
2911
0
                            func_ty: FuncType::new([(*closure_ty).try_into()?], vec![]),
2912
                        },
2913
0
                        sig: WasmSignature {
2914
0
                            params: vec![to_wasm_type(table_idx_ty), to_wasm_type(closure_ty)],
2915
0
                            results: vec![WasmType::I32],
2916
0
                            indirect_params: false,
2917
0
                            retptr: false,
2918
0
                        },
2919
                    });
2920
                }
2921
2922
                // Adapter imports into the main module must got through an
2923
                // indirection, so that's registered here.
2924
0
                Import::AdapterExport { adapter, func, ty } => {
2925
0
                    let name = self.shims.len().to_string();
2926
0
                    log::debug!("shim {name} is adapter `{module}::{field}`");
2927
0
                    self.push(Shim {
2928
0
                        name,
2929
0
                        debug_name: format!("adapt-{module}-{field}"),
2930
0
                        // Pessimistically assume that all adapters require
2931
0
                        // memory in one form or another. While this isn't
2932
0
                        // technically true it's true enough for WASI.
2933
0
                        options: RequiredOptions::MEMORY,
2934
0
                        kind: ShimKind::Adapter { adapter, func },
2935
0
                        sig: WasmSignature {
2936
0
                            params: ty.params().iter().map(to_wasm_type).collect(),
2937
0
                            results: ty.results().iter().map(to_wasm_type).collect(),
2938
0
                            indirect_params: false,
2939
0
                            retptr: false,
2940
0
                        },
2941
0
                    });
2942
                }
2943
2944
                // WIT-level functions may require an indirection, so yield some
2945
                // metadata out of this `match` to the loop below to figure that
2946
                // out.
2947
2.78k
                Import::InterfaceFunc(key, _, name, abi) => {
2948
2.78k
                    self.append_indirect_wit_func(
2949
2.78k
                        world,
2950
2.78k
                        for_module,
2951
2.78k
                        module,
2952
2.78k
                        field,
2953
2.78k
                        key,
2954
2.78k
                        name,
2955
2.78k
                        Some(resolve.name_world_key(key)),
2956
2.78k
                        *abi,
2957
0
                    )?;
2958
                }
2959
1.14k
                Import::WorldFunc(key, name, abi) => {
2960
1.14k
                    self.append_indirect_wit_func(
2961
1.14k
                        world, for_module, module, field, key, name, None, *abi,
2962
0
                    )?;
2963
                }
2964
            }
2965
        }
2966
2967
        // In addition to all the shims added for imports above this module also
2968
        // requires shims for resource destructors that it exports. Resource
2969
        // types are declared before the module is instantiated so the actual
2970
        // destructor is registered as a shim (defined here) and it's then
2971
        // filled in with the module's exports later.
2972
45.8k
        for (export_name, export) in module_exports.iter() {
2973
45.8k
            let id = match export {
2974
1.27k
                Export::ResourceDtor(id) => id,
2975
44.5k
                _ => continue,
2976
            };
2977
1.27k
            let resource = resolve.types[*id].name.as_ref().unwrap();
2978
1.27k
            let name = self.shims.len().to_string();
2979
1.27k
            self.push(Shim {
2980
1.27k
                name,
2981
1.27k
                debug_name: format!("dtor-{resource}"),
2982
1.27k
                options: RequiredOptions::empty(),
2983
1.27k
                kind: ShimKind::ResourceDtor {
2984
1.27k
                    module: for_module,
2985
1.27k
                    export: export_name,
2986
1.27k
                },
2987
1.27k
                sig: WasmSignature {
2988
1.27k
                    params: vec![WasmType::Pointer],
2989
1.27k
                    results: Vec::new(),
2990
1.27k
                    indirect_params: false,
2991
1.27k
                    retptr: false,
2992
1.27k
                },
2993
1.27k
            });
2994
        }
2995
2996
4.76k
        Ok(())
2997
4.76k
    }
2998
2999
    /// Helper of `append_indirect` above which pushes information for
3000
    /// futures/streams read/write intrinsics.
3001
5.34k
    fn append_indirect_payload_push(
3002
5.34k
        &mut self,
3003
5.34k
        world: &'a ComponentWorld<'a>,
3004
5.34k
        for_module: CustomModule<'a>,
3005
5.34k
        module: &str,
3006
5.34k
        async_: bool,
3007
5.34k
        info: &'a PayloadInfo,
3008
5.34k
        kind: PayloadFuncKind,
3009
5.34k
        params: Vec<WasmType>,
3010
5.34k
        results: Vec<WasmType>,
3011
5.34k
    ) {
3012
5.34k
        let resolve = &world.encoder.metadata.resolve;
3013
5.34k
        let debug_name = format!("{module}-{}", info.name);
3014
5.34k
        let name = self.shims.len().to_string();
3015
3016
5.34k
        let options = RequiredOptions::for_payload(
3017
5.34k
            resolve,
3018
5.34k
            world.encoder.metadata.world,
3019
5.34k
            info,
3020
5.34k
            &kind,
3021
5.34k
            async_,
3022
        );
3023
5.34k
        if !options.contains(RequiredOptions::REALLOC)
3024
5.31k
            && world.info.imports.imported_memory().is_some()
3025
        {
3026
0
            return;
3027
5.34k
        }
3028
5.34k
        self.push(Shim {
3029
5.34k
            name,
3030
5.34k
            debug_name,
3031
5.34k
            options,
3032
5.34k
            kind: ShimKind::PayloadFunc {
3033
5.34k
                for_module,
3034
5.34k
                info,
3035
5.34k
                kind,
3036
5.34k
            },
3037
5.34k
            sig: WasmSignature {
3038
5.34k
                params,
3039
5.34k
                results,
3040
5.34k
                indirect_params: false,
3041
5.34k
                retptr: false,
3042
5.34k
            },
3043
5.34k
        });
3044
5.34k
        let realloc = payload_realloc_name(world, for_module, info);
3045
5.34k
        self.push_realloc(
3046
5.34k
            world,
3047
5.34k
            for_module,
3048
5.34k
            ReallocSite::AfterInstantiation,
3049
5.34k
            options,
3050
5.34k
            realloc,
3051
        );
3052
5.34k
    }
3053
3054
    /// Helper for `append_indirect` above which will conditionally push a shim
3055
    /// for the WIT function specified by `interface_key`, `name`, and `abi`.
3056
3.92k
    fn append_indirect_wit_func(
3057
3.92k
        &mut self,
3058
3.92k
        world: &'a ComponentWorld<'a>,
3059
3.92k
        for_module: CustomModule<'a>,
3060
3.92k
        module: &str,
3061
3.92k
        field: &str,
3062
3.92k
        key: &WorldKey,
3063
3.92k
        name: &String,
3064
3.92k
        interface_key: Option<String>,
3065
3.92k
        abi: AbiVariant,
3066
3.92k
    ) -> Result<()> {
3067
3.92k
        let resolve = &world.encoder.metadata.resolve;
3068
3.92k
        let metadata = world.module_metadata_for(for_module);
3069
3.92k
        let interface = &world.import_map[&interface_key];
3070
3.92k
        let (index, _, lowering) = interface.lowerings.get_full(&(name.clone(), abi)).unwrap();
3071
3.92k
        let shim_name = self.shims.len().to_string();
3072
3.92k
        match lowering {
3073
0
            Lowering::ResourceDrop(_) => {}
3074
3075
2.62k
            Lowering::Direct { options } => {
3076
2.62k
                let realloc = world
3077
2.62k
                    .exports_for(for_module)
3078
2.62k
                    .import_realloc_for(interface.interface, name);
3079
2.62k
                self.push_realloc(
3080
2.62k
                    world,
3081
2.62k
                    for_module,
3082
2.62k
                    ReallocSite::BeforeInstantiation,
3083
2.62k
                    *options,
3084
2.62k
                    realloc,
3085
2.62k
                );
3086
2.62k
            }
3087
3088
1.30k
            Lowering::Indirect { sig, options } => {
3089
1.30k
                log::debug!(
3090
                    "shim {shim_name} is import `{module}::{field}` lowering {index} `{name}`",
3091
                );
3092
1.30k
                let encoding = metadata
3093
1.30k
                    .import_encodings
3094
1.30k
                    .get(resolve, key, name)
3095
1.30k
                    .ok_or_else(|| {
3096
0
                        anyhow::anyhow!(
3097
                            "missing component metadata for import of \
3098
                                `{module}::{field}`"
3099
                        )
3100
0
                    })?;
3101
1.30k
                self.push(Shim {
3102
1.30k
                    name: shim_name,
3103
1.30k
                    debug_name: format!("indirect-{module}-{field}"),
3104
1.30k
                    options: *options,
3105
1.30k
                    kind: ShimKind::IndirectLowering {
3106
1.30k
                        interface: interface_key,
3107
1.30k
                        index,
3108
1.30k
                        realloc: for_module,
3109
1.30k
                        encoding,
3110
1.30k
                    },
3111
1.30k
                    sig: sig.clone(),
3112
1.30k
                });
3113
3114
1.30k
                let realloc = world
3115
1.30k
                    .exports_for(for_module)
3116
1.30k
                    .import_realloc_for(interface.interface, name);
3117
1.30k
                self.push_realloc(
3118
1.30k
                    world,
3119
1.30k
                    for_module,
3120
1.30k
                    ReallocSite::AfterInstantiation,
3121
1.30k
                    *options,
3122
1.30k
                    realloc,
3123
                );
3124
            }
3125
        }
3126
3127
3.92k
        Ok(())
3128
3.92k
    }
3129
3130
    /// Registers a shim, if one is necessary, for the `realloc` function named
3131
    /// `export` within `for_module` which is going to be used at `site` by
3132
    /// something requiring `options`.
3133
9.27k
    fn push_realloc(
3134
9.27k
        &mut self,
3135
9.27k
        world: &'a ComponentWorld<'a>,
3136
9.27k
        for_module: CustomModule<'a>,
3137
9.27k
        site: ReallocSite,
3138
9.27k
        options: RequiredOptions,
3139
9.27k
        export: Option<&'a str>,
3140
9.27k
    ) {
3141
9.27k
        if !options.contains(RequiredOptions::REALLOC) {
3142
9.11k
            return;
3143
162
        }
3144
162
        let Some((for_module, export)) = resolve_realloc(world, for_module, export) else {
3145
0
            return;
3146
        };
3147
162
        if !realloc_needs_shim(world, site) {
3148
162
            return;
3149
0
        }
3150
0
        let name = self.shims.len().to_string();
3151
0
        self.push(Shim {
3152
0
            name,
3153
0
            debug_name: format!("realloc-{}-{export}", for_module.debug_name()),
3154
0
            options: RequiredOptions::empty(),
3155
0
            kind: ShimKind::Realloc {
3156
0
                module: for_module,
3157
0
                export,
3158
0
            },
3159
0
            sig: WasmSignature {
3160
0
                params: vec![WasmType::Pointer; 4],
3161
0
                results: vec![WasmType::Pointer],
3162
0
                indirect_params: false,
3163
0
                retptr: false,
3164
0
            },
3165
0
        });
3166
9.27k
    }
3167
3168
10.3k
    fn push(&mut self, shim: Shim<'a>) {
3169
        // Only one shim per `ShimKind` is retained, so if it's already present
3170
        // don't overwrite it. If it's not present though go ahead and insert
3171
        // it.
3172
10.3k
        if !self.shims.contains_key(&shim.kind) {
3173
8.58k
            self.shims.insert(shim.kind.clone(), shim);
3174
8.58k
        }
3175
10.3k
    }
3176
}
3177
3178
/// Resolves which module, and which export of it, provides the `realloc`
3179
/// canonical option for `module`, where `export` is `module`'s own realloc
3180
/// export if it has one.
3181
///
3182
/// Libraries in a shared-everything link which don't export a realloc of their
3183
/// own fall back to the one shared by the rest of the link
3184
1.63k
fn resolve_realloc<'a>(
3185
1.63k
    world: &'a ComponentWorld<'a>,
3186
1.63k
    module: CustomModule<'a>,
3187
1.63k
    export: Option<&'a str>,
3188
1.63k
) -> Option<(CustomModule<'a>, &'a str)> {
3189
1.63k
    if let Some(export) = export {
3190
1.63k
        return Some((module, export));
3191
0
    }
3192
0
    match module {
3193
        // If the main module doesn't have a realloc, then there's nothing to
3194
        // use.
3195
0
        CustomModule::Main => None,
3196
3197
        // For libraries fallback to the realloc in the main module, if present.
3198
0
        CustomModule::Adapter(name) => {
3199
0
            let _info = world.adapters[name].library_info.as_ref()?;
3200
0
            let main_realloc = world.info.exports.general_purpose_realloc()?;
3201
0
            Some((CustomModule::Main, main_realloc))
3202
        }
3203
    }
3204
1.63k
}
3205
3206
8.91k
fn payload_realloc_name<'a>(
3207
8.91k
    world: &'a ComponentWorld<'_>,
3208
8.91k
    for_module: CustomModule<'_>,
3209
8.91k
    info: &PayloadInfo,
3210
8.91k
) -> Option<&'a str> {
3211
8.91k
    let exports = world.exports_for(for_module);
3212
8.91k
    match &info.ty {
3213
8.91k
        PayloadType::Type { function, .. } => {
3214
8.91k
            if info.imported {
3215
1.82k
                exports.import_realloc_for(info.interface, function)
3216
            } else {
3217
7.08k
                exports.export_realloc_for(&info.key, function)
3218
            }
3219
        }
3220
0
        PayloadType::UnitFuture | PayloadType::UnitStream => None,
3221
    }
3222
8.91k
}
3223
3224
7.88k
pub(crate) fn task_return_options_and_type(
3225
7.88k
    resolve: &Resolve,
3226
7.88k
    world: WorldId,
3227
7.88k
    func: &Function,
3228
7.88k
) -> (RequiredOptions, WasmSignature) {
3229
7.88k
    let func_tmp = Function {
3230
7.88k
        name: String::new(),
3231
7.88k
        kind: FunctionKind::Freestanding,
3232
7.88k
        params: match &func.result {
3233
7.51k
            Some(ty) => vec![Param {
3234
7.51k
                name: "a".to_string(),
3235
7.51k
                ty: *ty,
3236
7.51k
                span: Default::default(),
3237
7.51k
            }],
3238
371
            None => Vec::new(),
3239
        },
3240
7.88k
        result: None,
3241
7.88k
        docs: Default::default(),
3242
7.88k
        stability: Stability::Unknown,
3243
7.88k
        span: Default::default(),
3244
7.88k
        external_id: None,
3245
    };
3246
7.88k
    let abi = AbiVariant::GuestImport;
3247
7.88k
    let mut options = RequiredOptions::for_import(resolve, world, func, abi);
3248
    // `task.return` does not support a `realloc` canonical option.
3249
7.88k
    options.remove(RequiredOptions::REALLOC);
3250
7.88k
    let sig = resolve.wasm_signature(world, abi, &func_tmp);
3251
7.88k
    (options, sig)
3252
7.88k
}
3253
3254
/// Alias argument to an instantiation
3255
#[derive(Clone, Debug)]
3256
pub struct Item {
3257
    /// The alias name for this export
3258
    pub alias: String,
3259
    /// The kind of export being aliased
3260
    pub kind: ExportKind,
3261
    /// Which module or adapter the export comes from
3262
    pub which: MainOrAdapter,
3263
    /// The name of the export in the source module
3264
    pub name: String,
3265
}
3266
3267
/// Module argument to an instantiation
3268
#[derive(Debug, PartialEq, Clone)]
3269
pub enum MainOrAdapter {
3270
    /// The main module
3271
    Main,
3272
    /// An adapter module, identified by name
3273
    Adapter(String),
3274
}
3275
3276
impl MainOrAdapter {
3277
0
    fn to_custom_module(&self) -> CustomModule<'_> {
3278
0
        match self {
3279
0
            MainOrAdapter::Main => CustomModule::Main,
3280
0
            MainOrAdapter::Adapter(s) => CustomModule::Adapter(s),
3281
        }
3282
0
    }
3283
}
3284
3285
/// Module instantiation argument
3286
#[derive(Clone)]
3287
pub enum Instance {
3288
    /// Module argument
3289
    MainOrAdapter(MainOrAdapter),
3290
3291
    /// Alias argument
3292
    Items(Vec<Item>),
3293
}
3294
3295
/// Provides fine-grained control of how a library module is instantiated
3296
/// relative to other module instances
3297
#[derive(Clone)]
3298
pub struct LibraryInfo {
3299
    /// Instantiation arguments
3300
    pub arguments: Vec<(String, Instance)>,
3301
}
3302
3303
/// Represents an adapter or library to be instantiated as part of the component
3304
pub(super) struct Adapter {
3305
    /// The wasm of the module itself, with `component-type` sections stripped
3306
    wasm: Vec<u8>,
3307
3308
    /// The metadata for the adapter
3309
    metadata: ModuleMetadata,
3310
3311
    /// The set of exports from the final world which are defined by this
3312
    /// adapter or library
3313
    required_exports: IndexSet<WorldKey>,
3314
3315
    /// If present, treat this module as a library rather than a "minimal" adapter
3316
    ///
3317
    /// TODO: We should refactor how various flavors of module are represented
3318
    /// and differentiated to avoid mistaking one for another.
3319
    library_info: Option<LibraryInfo>,
3320
}
3321
3322
/// An encoder of components based on `wit` interface definitions.
3323
#[derive(Default)]
3324
pub struct ComponentEncoder {
3325
    module: Vec<u8>,
3326
    module_import_map: Option<ModuleImportMap>,
3327
    pub(super) metadata: Bindgen,
3328
    validate: bool,
3329
    pub(super) main_module_exports: IndexSet<WorldKey>,
3330
    pub(super) adapters: IndexMap<String, Adapter>,
3331
    import_name_map: HashMap<String, String>,
3332
    realloc_via_memory_grow: bool,
3333
    merge_imports_based_on_semver: Option<bool>,
3334
    pub(super) reject_legacy_names: bool,
3335
    debug_names: bool,
3336
    shim_return_call_ref: bool,
3337
    emit_canonical_names: bool,
3338
}
3339
3340
impl ComponentEncoder {
3341
    /// Set the core module to encode as a component.
3342
    /// This method will also parse any component type information stored in custom sections
3343
    /// inside the module and add them as the interface, imports, and exports.
3344
    /// It will also add any producers information inside the component type information to the
3345
    /// core module.
3346
4.76k
    pub fn module(&mut self, module: &[u8]) -> Result<&mut Self> {
3347
4.76k
        let (wasm, metadata) = self.decode(module.as_ref())?;
3348
4.76k
        let (wasm, module_import_map) = ModuleImportMap::new(wasm)?;
3349
4.76k
        self.module = if let Some(producers) = &metadata.producers {
3350
4.76k
            producers.add_to_wasm(&wasm)?
3351
        } else {
3352
0
            wasm.to_vec()
3353
        };
3354
4.76k
        let exports = self
3355
4.76k
            .merge_metadata(metadata)
3356
4.76k
            .context("failed merge WIT metadata for module with previous metadata")?;
3357
4.76k
        self.main_module_exports.extend(exports);
3358
4.76k
        self.module_import_map = module_import_map;
3359
4.76k
        Ok(self)
3360
4.76k
    }
3361
3362
4.76k
    fn decode<'a>(&self, wasm: &'a [u8]) -> Result<(Cow<'a, [u8]>, Bindgen)> {
3363
4.76k
        let (bytes, metadata) = metadata::decode(wasm)?;
3364
4.76k
        match bytes {
3365
4.76k
            Some(wasm) => Ok((Cow::Owned(wasm), metadata)),
3366
0
            None => Ok((Cow::Borrowed(wasm), metadata)),
3367
        }
3368
4.76k
    }
3369
3370
4.76k
    fn merge_metadata(&mut self, metadata: Bindgen) -> Result<IndexSet<WorldKey>> {
3371
4.76k
        self.metadata.merge(metadata)
3372
4.76k
    }
3373
3374
    /// Sets whether or not the encoder will validate its output.
3375
0
    pub fn validate(&mut self, validate: bool) -> &mut Self {
3376
0
        self.validate = validate;
3377
0
        self
3378
0
    }
3379
3380
    /// Sets whether or not to generate debug names in the output component.
3381
4.76k
    pub fn debug_names(&mut self, debug_names: bool) -> &mut Self {
3382
4.76k
        self.debug_names = debug_names;
3383
4.76k
        self
3384
4.76k
    }
3385
3386
    /// Configures whether the shim module, if needed, will use
3387
    /// `return_call_ref` as opposed to the default `call_indirect`.
3388
4.76k
    pub fn shim_return_call_ref(&mut self, enable: bool) -> &mut Self {
3389
4.76k
        self.shim_return_call_ref = enable;
3390
4.76k
        self
3391
4.76k
    }
3392
3393
    /// Sets whether to merge imports based on semver to the specified value.
3394
    ///
3395
    /// This affects how when to WIT worlds are merged together, for example
3396
    /// from two different libraries, whether their imports are unified when the
3397
    /// semver version ranges for interface allow it.
3398
    ///
3399
    /// This is enabled by default.
3400
0
    pub fn merge_imports_based_on_semver(&mut self, merge: bool) -> &mut Self {
3401
0
        self.merge_imports_based_on_semver = Some(merge);
3402
0
        self
3403
0
    }
3404
3405
    /// Sets whether to emit canonical interface names in the component binary.
3406
    ///
3407
    /// When enabled, import/export names use canonical version prefixes (e.g.,
3408
    /// `wasi:cli/exit@0.2` instead of `wasi:cli/exit@0.2.1`) and the
3409
    /// `version_suffix` field is populated.
3410
    ///
3411
    /// This is disabled by default.
3412
0
    pub fn emit_canonical_names(&mut self, emit: bool) -> &mut Self {
3413
0
        self.emit_canonical_names = emit;
3414
0
        self
3415
0
    }
3416
3417
    /// Sets whether to reject the historical mangling/name scheme for core wasm
3418
    /// imports/exports as they map to the component model.
3419
    ///
3420
    /// The `wit-component` crate supported a different set of names prior to
3421
    /// WebAssembly/component-model#378 and this can be used to disable this
3422
    /// support.
3423
    ///
3424
    /// This is disabled by default.
3425
0
    pub fn reject_legacy_names(&mut self, reject: bool) -> &mut Self {
3426
0
        self.reject_legacy_names = reject;
3427
0
        self
3428
0
    }
3429
3430
    /// Specifies a new adapter which is used to translate from a historical
3431
    /// wasm ABI to the canonical ABI and the `interface` provided.
3432
    ///
3433
    /// This is primarily used to polyfill, for example,
3434
    /// `wasi_snapshot_preview1` with a component-model using interface. The
3435
    /// `name` provided is the module name of the adapter that is being
3436
    /// polyfilled, for example `"wasi_snapshot_preview1"`.
3437
    ///
3438
    /// The `bytes` provided is a core wasm module which implements the `name`
3439
    /// interface in terms of the `interface` interface. This core wasm module
3440
    /// is severely restricted in its shape, for example it cannot have any data
3441
    /// segments or element segments.
3442
    ///
3443
    /// The `interface` provided is the component-model-using-interface that the
3444
    /// wasm module specified by `bytes` imports. The `bytes` will then import
3445
    /// `interface` and export functions to get imported from the module `name`
3446
    /// in the core wasm that's being wrapped.
3447
0
    pub fn adapter(&mut self, name: &str, bytes: &[u8]) -> Result<&mut Self> {
3448
0
        self.library_or_adapter(name, bytes, None)
3449
0
    }
3450
3451
    /// Specifies a shared-everything library to link into the component.
3452
    ///
3453
    /// Unlike adapters, libraries _may_ have data and/or element segments, but
3454
    /// they must operate on an imported memory and table, respectively.  In
3455
    /// this case, the correct amount of space is presumed to have been
3456
    /// statically allocated in the main module's memory and table at the
3457
    /// offsets which the segments target, e.g. as arranged by
3458
    /// [super::linking::Linker].
3459
    ///
3460
    /// Libraries are treated similarly to adapters, except that they are not
3461
    /// "minified" the way adapters are, and instantiation is controlled
3462
    /// declaratively via the `library_info` parameter.
3463
0
    pub fn library(
3464
0
        &mut self,
3465
0
        name: &str,
3466
0
        bytes: &[u8],
3467
0
        library_info: LibraryInfo,
3468
0
    ) -> Result<&mut Self> {
3469
0
        self.library_or_adapter(name, bytes, Some(library_info))
3470
0
    }
3471
3472
0
    fn library_or_adapter(
3473
0
        &mut self,
3474
0
        name: &str,
3475
0
        bytes: &[u8],
3476
0
        library_info: Option<LibraryInfo>,
3477
0
    ) -> Result<&mut Self> {
3478
0
        let (wasm, mut metadata) = self.decode(bytes)?;
3479
        // Merge the adapter's document into our own document to have one large
3480
        // document, and then afterwards merge worlds as well.
3481
        //
3482
        // Note that the `metadata` tracking import/export encodings is removed
3483
        // since this adapter can get different lowerings and is allowed to
3484
        // differ from the main module. This is then tracked within the
3485
        // `Adapter` structure produced below.
3486
0
        let adapter_metadata = mem::take(&mut metadata.metadata);
3487
0
        let exports = self.merge_metadata(metadata).with_context(|| {
3488
0
            format!("failed to merge WIT packages of adapter `{name}` into main packages")
3489
0
        })?;
3490
0
        if let Some(library_info) = &library_info {
3491
            // Validate that all referenced modules can be resolved.
3492
0
            for (_, instance) in &library_info.arguments {
3493
0
                let resolve = |which: &_| match which {
3494
0
                    MainOrAdapter::Main => Ok(()),
3495
0
                    MainOrAdapter::Adapter(name) => {
3496
0
                        if self.adapters.contains_key(name.as_str()) {
3497
0
                            Ok(())
3498
                        } else {
3499
0
                            Err(anyhow!("instance refers to unknown adapter `{name}`"))
3500
                        }
3501
                    }
3502
0
                };
3503
3504
0
                match instance {
3505
0
                    Instance::MainOrAdapter(which) => resolve(which)?,
3506
0
                    Instance::Items(items) => {
3507
0
                        for item in items {
3508
0
                            resolve(&item.which)?;
3509
                        }
3510
                    }
3511
                }
3512
            }
3513
0
        }
3514
0
        self.adapters.insert(
3515
0
            name.to_string(),
3516
0
            Adapter {
3517
0
                wasm: wasm.to_vec(),
3518
0
                metadata: adapter_metadata,
3519
0
                required_exports: exports,
3520
0
                library_info,
3521
0
            },
3522
        );
3523
0
        Ok(self)
3524
0
    }
3525
3526
    /// Whether adapters use `memory.grow` for realloc and stack allocation.
3527
    ///
3528
    /// By default an adapter imports `cabi_realloc` from the main module.
3529
    /// Setting this to `true` makes it allocate with `memory.grow` instead,
3530
    /// which can be useful if `cabi_realloc` cannot be called before the host
3531
    /// runtime is initialized.
3532
    ///
3533
    /// This only affects modules added with [`ComponentEncoder::adapter`]. It
3534
    /// has no effect on the main module and does not synthesize a
3535
    /// `cabi_realloc` for a module that doesn't export one.
3536
4.76k
    pub fn realloc_via_memory_grow(&mut self, value: bool) -> &mut Self {
3537
4.76k
        self.realloc_via_memory_grow = value;
3538
4.76k
        self
3539
4.76k
    }
3540
3541
    /// The instance import name map to use.
3542
    ///
3543
    /// This is used to rename instance imports in the final component.
3544
    ///
3545
    /// For example, if there is an instance import `foo:bar/baz` and it is
3546
    /// desired that the import actually be named `a:b/c@x.y.z`, then
3547
    /// `foo:bar/baz` can be mapped to `a:b/c@x.y.z`.
3548
    ///
3549
    /// Note: the replacement names are not validated during encoding unless
3550
    /// the `validate` option is set to true.
3551
0
    pub fn import_name_map(&mut self, map: HashMap<String, String>) -> &mut Self {
3552
0
        self.import_name_map = map;
3553
0
        self
3554
0
    }
3555
3556
    /// Encode the component and return the bytes.
3557
4.76k
    pub fn encode(&mut self) -> Result<Vec<u8>> {
3558
4.76k
        self.encode_with_fixups(None)
3559
4.76k
    }
3560
3561
4.76k
    pub(crate) fn encode_with_fixups(
3562
4.76k
        &mut self,
3563
4.76k
        fixup_hook: Option<&mut dyn FnMut(&mut fixup::FixupModule) -> Result<()>>,
3564
4.76k
    ) -> Result<Vec<u8>> {
3565
4.76k
        if self.module.is_empty() {
3566
0
            bail!("a module is required when encoding a component");
3567
4.76k
        }
3568
3569
4.76k
        if self.merge_imports_based_on_semver.unwrap_or(true) {
3570
4.76k
            self.metadata
3571
4.76k
                .resolve
3572
4.76k
                .merge_world_imports_based_on_semver(self.metadata.world)?;
3573
0
        }
3574
3575
4.76k
        if self.emit_canonical_names {
3576
0
            check_duplicate_canonical_names(&self.metadata.resolve, self.metadata.world)?;
3577
4.76k
        }
3578
3579
4.76k
        self.finalize_resolve_with_nominal_ids();
3580
3581
4.76k
        let world = ComponentWorld::new(self).context("failed to decode world from module")?;
3582
4.76k
        let mut state = EncodingState {
3583
4.76k
            component: ComponentBuilder::default(),
3584
4.76k
            module_index: None,
3585
4.76k
            instance_index: None,
3586
4.76k
            memory_index: None,
3587
4.76k
            shim_instance_index: None,
3588
4.76k
            adapter_modules: IndexMap::new(),
3589
4.76k
            adapter_instances: IndexMap::new(),
3590
4.76k
            type_encoding_maps: Default::default(),
3591
4.76k
            instances: Default::default(),
3592
4.76k
            imported_funcs: Default::default(),
3593
4.76k
            aliased_core_items: Default::default(),
3594
4.76k
            info: &world,
3595
4.76k
            export_task_initialization_wrappers: HashMap::new(),
3596
4.76k
        };
3597
4.76k
        state.encode_imports(&self.import_name_map)?;
3598
4.76k
        state.encode_core_modules();
3599
4.76k
        state.encode_core_instantiation(fixup_hook)?;
3600
4.76k
        state.encode_exports(CustomModule::Main)?;
3601
4.76k
        for name in self.adapters.keys() {
3602
0
            state.encode_exports(CustomModule::Adapter(name))?;
3603
        }
3604
4.76k
        if self.debug_names {
3605
858
            state.component.append_names();
3606
3.90k
        }
3607
4.76k
        state
3608
4.76k
            .component
3609
4.76k
            .raw_custom_section(&crate::base_producers().raw_custom_section());
3610
4.76k
        let bytes = state.component.finish();
3611
3612
4.76k
        if self.validate {
3613
0
            Validator::new_with_features(WasmFeatures::all())
3614
0
                .validate_all(&bytes)
3615
0
                .context("failed to validate component output")?;
3616
4.76k
        }
3617
3618
4.76k
        Ok(bytes)
3619
4.76k
    }
3620
3621
    /// Call the `generate_nominal_type_ids` method on the `Resolve` that we're
3622
    /// using, adjusting any preexisting keys/pointers as necessary.
3623
    ///
3624
    /// This is the final step after merging all known `Resolve`s together
3625
    /// before a component is actually created. By creating a unique
3626
    /// `InterfaceId` for all interfaces it makes the generation process easier
3627
    /// since there's no need to fret about whether an `InterfaceId` is an
3628
    /// import or an export for example.
3629
4.76k
    fn finalize_resolve_with_nominal_ids(&mut self) {
3630
        // Before calling `generate_nominal_type_ids` we need to handle the fact
3631
        // that the exports of the world are going to be rewritten. The only
3632
        // pointers we have into those are the exports of the main module and
3633
        // adapters. To handle this, before we generate nominal ids, indices of
3634
        // exports are saved here on the stack to get restored later on.
3635
        // Effectively we're clearing out the exports and rebuilding them later.
3636
4.76k
        let world = &self.metadata.resolve.worlds[self.metadata.world];
3637
4.76k
        let main_module_exports = self
3638
4.76k
            .main_module_exports
3639
4.76k
            .iter()
3640
9.21k
            .map(|i| world.exports.get_index_of(i).unwrap())
3641
4.76k
            .collect::<Vec<_>>();
3642
4.76k
        let adapter_exports = self
3643
4.76k
            .adapters
3644
4.76k
            .values()
3645
4.76k
            .map(|adapter| {
3646
0
                adapter
3647
0
                    .required_exports
3648
0
                    .iter()
3649
0
                    .map(|i| world.exports.get_index_of(i).unwrap())
3650
0
                    .collect::<Vec<_>>()
3651
0
            })
3652
4.76k
            .collect::<Vec<_>>();
3653
3654
        // With everything saved this will modify `Resolve` to ensure there's a
3655
        // nominal identifier for all interfaces (e.g. not both simultaneously
3656
        // imported and exported).
3657
4.76k
        self.metadata
3658
4.76k
            .resolve
3659
4.76k
            .generate_nominal_type_ids(self.metadata.world);
3660
3661
        // Rebuild the sets of exports now that the world's exports have been
3662
        // clobbered.
3663
4.76k
        self.main_module_exports.clear();
3664
4.76k
        let world = &self.metadata.resolve.worlds[self.metadata.world];
3665
9.21k
        for index in main_module_exports {
3666
9.21k
            let (key, _) = world.exports.get_index(index).unwrap();
3667
9.21k
            self.main_module_exports.insert(key.clone());
3668
9.21k
        }
3669
4.76k
        for (exports, adapter) in adapter_exports.into_iter().zip(self.adapters.values_mut()) {
3670
0
            adapter.required_exports.clear();
3671
0
            for index in exports {
3672
0
                let (key, _) = world.exports.get_index(index).unwrap();
3673
0
                adapter.required_exports.insert(key.clone());
3674
0
            }
3675
        }
3676
4.76k
    }
3677
}
3678
3679
impl ComponentWorld<'_> {
3680
    /// Convenience function to lookup a module's import map.
3681
9.52k
    fn imports_for(&self, module: CustomModule) -> &ImportMap {
3682
9.52k
        match module {
3683
9.52k
            CustomModule::Main => &self.info.imports,
3684
0
            CustomModule::Adapter(name) => &self.adapters[name].info.imports,
3685
        }
3686
9.52k
    }
3687
3688
    /// Convenience function to lookup a module's export map.
3689
61.1k
    fn exports_for(&self, module: CustomModule) -> &ExportMap {
3690
61.1k
        match module {
3691
61.1k
            CustomModule::Main => &self.info.exports,
3692
0
            CustomModule::Adapter(name) => &self.adapters[name].info.exports,
3693
        }
3694
61.1k
    }
3695
3696
    /// Convenience function to lookup a module's metadata.
3697
29.9k
    fn module_metadata_for(&self, module: CustomModule) -> &ModuleMetadata {
3698
29.9k
        match module {
3699
29.9k
            CustomModule::Main => &self.encoder.metadata.metadata,
3700
0
            CustomModule::Adapter(name) => &self.encoder.adapters[name].metadata,
3701
        }
3702
29.9k
    }
3703
}
3704
3705
/// Verifies that no two imports, and no two exports, of the world share the
3706
/// same canonical name.
3707
3.01k
pub(crate) fn check_duplicate_canonical_names(resolve: &Resolve, world: WorldId) -> Result<()> {
3708
3.01k
    let world = &resolve.worlds[world];
3709
3.01k
    let mut names = HashMap::new();
3710
3.83k
    for key in world.imports.keys() {
3711
3.83k
        let WorldKey::Interface(id) = key else {
3712
3.13k
            continue;
3713
        };
3714
705
        let canonical = resolve.canonicalized_id_of(*id).unwrap();
3715
705
        if let Some(prev) = names.insert(canonical.clone(), *id) {
3716
0
            bail!(
3717
                "import `{}` and import `{}` both have the canonical name \
3718
                 `{canonical}`; semver-compatible imports must be merged \
3719
                 before emitting canonical names",
3720
0
                resolve.id_of(prev).unwrap(),
3721
0
                resolve.id_of(*id).unwrap(),
3722
            );
3723
705
        }
3724
    }
3725
3.01k
    names.clear();
3726
7.24k
    for key in world.exports.keys() {
3727
7.24k
        let WorldKey::Interface(id) = key else {
3728
7.17k
            continue;
3729
        };
3730
70
        let canonical = resolve.canonicalized_id_of(*id).unwrap();
3731
70
        if let Some(prev) = names.insert(canonical.clone(), *id) {
3732
0
            bail!(
3733
                "export `{}` and export `{}` both have the canonical name \
3734
                 `{canonical}`; semver-compatible versions of the same \
3735
                 interface cannot both be exported when emitting canonical \
3736
                 names",
3737
0
                resolve.id_of(prev).unwrap(),
3738
0
                resolve.id_of(*id).unwrap(),
3739
            );
3740
70
        }
3741
    }
3742
3.01k
    Ok(())
3743
3.01k
}
3744
3745
#[cfg(all(test, feature = "dummy-module"))]
3746
mod test {
3747
    use super::*;
3748
    use crate::{dummy_module, embed_component_metadata};
3749
    use wit_parser::ManglingAndAbi;
3750
3751
    #[test]
3752
    fn it_renames_imports() {
3753
        let mut resolve = Resolve::new();
3754
        let pkg = resolve
3755
            .push_str(
3756
                "test.wit",
3757
                r#"
3758
package test:wit;
3759
3760
interface i {
3761
    f: func();
3762
}
3763
3764
world test {
3765
    import i;
3766
    import foo: interface {
3767
        f: func();
3768
    }
3769
}
3770
"#,
3771
            )
3772
            .unwrap();
3773
        let world = resolve.select_world(&[pkg], None).unwrap();
3774
3775
        let mut module = dummy_module(
3776
            &resolve,
3777
            world,
3778
            ManglingAndAbi::Standard32,
3779
            crate::IndexType::I32,
3780
        );
3781
3782
        embed_component_metadata(&mut module, &resolve, world, StringEncoding::UTF8, true).unwrap();
3783
3784
        let encoded = ComponentEncoder::default()
3785
            .import_name_map(HashMap::from([
3786
                ("foo".to_string(), "foo:bar/foo@1.0.0".to_string()),
3787
                ("test:wit/i".to_string(), "foo:bar/i@1.2.3".to_string()),
3788
            ]))
3789
            .module(&module)
3790
            .unwrap()
3791
            .validate(true)
3792
            .encode()
3793
            .unwrap();
3794
3795
        let wat = wasmprinter::print_bytes(encoded).unwrap();
3796
        assert!(wat.contains("(import \"foo:bar/foo@1.0.0\""));
3797
        assert!(wat.contains("(import \"foo:bar/i@1.2.3\""));
3798
        assert!(!wat.contains("(import \"foo\""));
3799
        assert!(!wat.contains("(import \"test:wit/i\""));
3800
    }
3801
}