Skip to main content

wasmtime_environ/compile/
module_environ.rs

1use crate::error::{OutOfMemory, Result, bail};
2use crate::module::{
3    FuncRefIndex, Initializer, MemoryInitialization, Module, TableSegment, TableSegmentElements,
4    TableSegmentInit,
5};
6use crate::prelude::*;
7use crate::{
8    ConstExpr, ConstOp, DataIndex, DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex,
9    DefinedTableIndex, ElemIndex, EngineOrModuleTypeIndex, EntityIndex, EntityType, FuncIndex,
10    FuncKey, GlobalIndex, IndexType, MemoryIndex, MemoryInitializer, ModuleInternedTypeIndex,
11    ModuleStartup, ModuleTypesBuilder, PanicOnOom as _, PassiveElemIndex, PrimaryMap,
12    RuntimeDataIndex, StaticModuleIndex, TableIndex, TableInitialValue, TableInitialization, Tag,
13    TagIndex, Trap, Tunables, TypeConvert, TypeIndex, WasmHeapTopType, WasmHeapType, WasmResult,
14    WasmValType, WasmparserTypeConverter,
15};
16use alloc::borrow::Cow;
17use cranelift_entity::packed_option::{PackedOption, ReservedValue};
18use cranelift_entity::{EntitySet, SecondaryMap};
19use std::collections::HashMap;
20use std::mem;
21use std::path::PathBuf;
22use std::sync::Arc;
23use wasmparser::{
24    CustomSectionReader, DataKind, ElementItems, ElementKind, Encoding, ExternalKind,
25    FuncToValidate, FunctionBody, KnownCustom, NameSectionReader, Naming, Parser, Payload, TypeRef,
26    Validator, ValidatorResources, types::Types,
27};
28
29/// Object containing the standalone environment information.
30pub struct ModuleEnvironment<'a, 'data> {
31    /// The current module being translated
32    result: ModuleTranslation<'data>,
33
34    /// Intern'd types for this entire translation, shared by all modules.
35    types: &'a mut ModuleTypesBuilder,
36
37    // Various bits and pieces of configuration
38    validator: &'a mut Validator,
39    tunables: &'a Tunables,
40}
41
42/// Identifies a FACT adapter-module import that the compiler lowers inline when
43/// translating the adapter function.
44#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
45pub enum FactInlineIntrinsic {
46    /// `enter-sync-call`: push a deferred component-model thread inline.
47    EnterSyncCall,
48
49    /// `exit-sync-call`: pop the deferred thread inline on the fast path, or
50    /// fall back to the out-of-line `exit-sync-call` libcall when the thread
51    /// was promoted.
52    ExitSyncCall,
53
54    /// `trap`: raise the given trap.
55    Trap(Trap),
56
57    /// An intrinsic that only exists for components.
58    #[cfg(feature = "component-model")]
59    Component(crate::component::FactComponentIntrinsic),
60}
61
62/// A statically-known function import.
63#[derive(Clone, Debug)]
64pub enum KnownFunc {
65    /// A function described by the given key.
66    FuncKey(FuncKey),
67    /// An always-inlined FACT intrinsic.
68    FactIntrinsic(FactInlineIntrinsic),
69}
70
71impl From<FuncKey> for KnownFunc {
72    fn from(key: FuncKey) -> Self {
73        Self::FuncKey(key)
74    }
75}
76
77impl From<FactInlineIntrinsic> for KnownFunc {
78    fn from(intrinsic: FactInlineIntrinsic) -> Self {
79        Self::FactIntrinsic(intrinsic)
80    }
81}
82
83/// A statically-known import of a core Wasm global, memory, or table.
84#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
85pub struct KnownEntity<T> {
86    /// The module that defines this entity.
87    pub module: StaticModuleIndex,
88    /// The entity's index in the defining module's defined-entity index space.
89    pub index: T,
90}
91
92/// A statically-known import of a core wasm global.
93#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
94pub enum KnownGlobal {
95    /// A global defined by a module in the same component.
96    Defined(KnownEntity<DefinedGlobalIndex>),
97
98    /// A component instance's runtime-managed flags, such as its `may-leave`
99    /// flag.
100    #[cfg(feature = "component-model")]
101    ComponentInstanceFlags(crate::component::RuntimeComponentInstanceIndex),
102}
103
104/// The result of translating via `ModuleEnvironment`.
105///
106/// Function bodies are not yet translated, and data initializers have not yet
107/// been copied out of the original buffer.
108pub struct ModuleTranslation<'data> {
109    /// Module information.
110    pub module: Module,
111
112    /// The input wasm binary.
113    ///
114    /// This can be useful, for example, when modules are parsed from a
115    /// component and the embedder wants access to the raw wasm modules
116    /// themselves.
117    pub wasm: &'data [u8],
118
119    /// The byte offset of this module's Wasm binary within the outer
120    /// binary (e.g. a component). For standalone modules this is 0.
121    /// This is used to convert component-relative source locations to
122    /// module-relative source locations.
123    pub wasm_module_offset: u64,
124
125    /// References to the function bodies.
126    pub function_body_inputs: PrimaryMap<DefinedFuncIndex, FunctionBodyData<'data>>,
127
128    /// For each imported function, the single statically-known function that
129    /// always satisfies that import, if any.
130    ///
131    /// This is used to turn what would otherwise be indirect calls through the
132    /// imports table into direct calls, when possible.
133    ///
134    /// When filled in, this only ever contains
135    /// `FuncKey::DefinedWasmFunction(..)`s, `FuncKey::Intrinsic(..)`s, and
136    /// `FuncKey::FactInlineIntrinsic`s.
137    pub known_imported_functions: SecondaryMap<FuncIndex, Option<KnownFunc>>,
138
139    /// For each function import, the function import whose `vmctx` this one
140    /// is statically guaranteed to always share, when that is not itself.
141    ///
142    /// Function imports that always resolve to functions from the same
143    /// instance hold the same `vmctx` pointer in their `VMFunctionImport`
144    /// slots, so they can all load the callee `vmctx` from a single slot and
145    /// let GVN collapse what would otherwise be many identical loads into one.
146    ///
147    /// No value means this import must use its own slot.
148    ///
149    /// Only filled in for modules compiled as part of a component.
150    pub imported_func_vmctx_representative: SecondaryMap<FuncIndex, PackedOption<FuncIndex>>,
151
152    /// Imported functions that never unwind a Wasm exception into their
153    /// caller, such as the host intrinsics imported by FACT adapter modules.
154    ///
155    /// Calls to these need no exception handlers, even inside a `try_table`.
156    pub imported_funcs_never_throw: EntitySet<FuncIndex>,
157
158    /// For each imported global, memory, or table, the single statically-known
159    /// defined entity that always satisfies that import, if any.
160    ///
161    /// This is used to access the entity via the defining module's precise
162    /// `AliasRegionKey::Defined{Global,Memory,Table}` region instead of the
163    /// conservative `AliasRegionKey::Public{Global,Memory,Table}` region that is
164    /// shared by every entity of that kind which crosses a module boundary.
165    ///
166    /// XXX: Being "known" requires more here than it does for functions: it is
167    /// not enough that *this* module's import is always the same entity,
168    /// *every* module that may import that entity must also always import that
169    /// same entity. Otherwise a function from one of those other modules, which
170    /// accesses the entity via the conservative region, could be inlined next
171    /// to one of our accesses via the precise region, and accessing the same
172    /// memory through two different alias regions is invalid.
173    ///
174    /// This extra condition is an artifact of this implementation, and how we
175    /// consume this data to choose the alias region for loads and stores to a
176    /// global/memory/table, not something inherent to knowing exactly which
177    /// entity satisfies a particular import. Really, there are two independent
178    /// axes here:
179    ///
180    /// 1. Is this import always satisfied by the same defined entity?
181    ///
182    /// 2. Is that entity's identity additionally known to *every* other module
183    ///    that may import it?
184    ///
185    /// Only alias regions need (2), but other theoretical optimizations could
186    /// be perfectly happy with just (1). For example, if we know that an import
187    /// of an immutable global is always a particular defined global, then we
188    /// could inline that global's value at each `global.get` of the import,
189    /// regardless what any other module does or does not know about that
190    /// global.
191    ///
192    /// TODO(#14164): Actually record (1) and (2) in separate maps, enabling
193    /// optimizations that rely on just (1) but not (2), instead of folding them
194    /// into this same map.
195    pub known_imported_globals: SecondaryMap<GlobalIndex, Option<KnownGlobal>>,
196
197    /// Same as `known_imported_globals`, but for memories.
198    pub known_imported_memories: SecondaryMap<MemoryIndex, Option<KnownEntity<DefinedMemoryIndex>>>,
199
200    /// Same as `known_imported_globals`, but for tables.
201    pub known_imported_tables: SecondaryMap<TableIndex, Option<KnownEntity<DefinedTableIndex>>>,
202
203    /// For each global defined by this module, whether every module that may
204    /// import this global always imports exactly this global.
205    ///
206    /// When this holds, accesses of the global may use its precise
207    /// `AliasRegionKey::DefinedGlobal` region even when the global is exported,
208    /// because every module that can reach it agrees on that same region. This
209    /// is vacuously true of globals that nothing in the component imports.
210    ///
211    /// This can only be determined by looking at the whole component, so it is
212    /// always `false` for standalone modules.
213    pub globals_known_to_importers: EntitySet<DefinedGlobalIndex>,
214
215    /// Same as [`Self::globals_known_to_importers`], but for memories.
216    pub memories_known_to_importers: EntitySet<DefinedMemoryIndex>,
217
218    /// Same as [`Self::globals_known_to_importers`], but for tables.
219    pub tables_known_to_importers: EntitySet<DefinedTableIndex>,
220
221    /// A list of type signatures which are considered exported from this
222    /// module, or those that can possibly be called. This list is sorted, and
223    /// trampolines for each of these signatures are required.
224    pub exported_signatures: Vec<ModuleInternedTypeIndex>,
225
226    /// DWARF debug information, if enabled, parsed from the module.
227    pub debuginfo: DebugInfoData<'data>,
228
229    /// Set if debuginfo was found but it was not parsed due to `Tunables`
230    /// configuration.
231    pub has_unparsed_debuginfo: bool,
232
233    /// The desired alignment of `data` in the final data section of the object
234    /// file that we'll emit.
235    ///
236    /// Note that this is 1 by default but `MemoryInitialization::Static` might
237    /// switch this to a higher alignment to facilitate mmap-ing data from
238    /// an object file into a linear memory.
239    pub data_align: Option<u64>,
240
241    /// Map from a data segment to whether it's a passive data segment or not.
242    pub runtime_data_map: SecondaryMap<DataIndex, Option<RuntimeDataIndex>>,
243
244    /// Map from an elem segment to whether it's a passive elem segment or not.
245    pub passive_elem_map: SecondaryMap<ElemIndex, Option<PassiveElemIndex>>,
246
247    /// List of passive element segments found in this module which will get
248    /// concatenated for the final artifact.
249    pub runtime_data: PrimaryMap<RuntimeDataIndex, Cow<'data, [u8]>>,
250
251    /// Record of all passive data segments that this module contains.
252    ///
253    /// These are processed during [`ModuleTranslation::finalize_memory_init`]
254    /// and eventually moved over into the `runtime_data` list above. Until
255    /// then, however, their `RuntimeDataIndex` is not yet assigned.
256    passive_data: Vec<(DataIndex, &'data [u8])>,
257
258    /// When we're parsing the code section this will be incremented so we know
259    /// which function is currently being defined.
260    code_index: u32,
261
262    /// The type information of the current module made available at the end of the
263    /// validation process.
264    types: Option<Types>,
265
266    /// Per-function [`BranchHintReader`]s from the `metadata.code.branch_hint`
267    /// section, keyed by function index. Populated only when
268    /// [`Tunables::branch_hinting`] is enabled.
269    branch_hints: HashMap<FuncIndex, BranchHintReader<'data>>,
270
271    /// The WebAssembly `start` function, if defined.
272    pub start_func: Option<FuncIndex>,
273
274    /// Initializers for `global` values which aren't considered "simple".
275    ///
276    /// These initializers are later compiled into a "module startup" function.
277    pub global_initializers: Vec<(DefinedGlobalIndex, ConstExpr)>,
278
279    /// Definitions of all passive elements found within a module.
280    ///
281    /// This maps passive element segments to their definition, either functions
282    /// or expressions-basd.
283    pub passive_elements: PrimaryMap<PassiveElemIndex, TableSegmentElements>,
284
285    /// WebAssembly table initialization data, per table.
286    ///
287    /// This keeps track of all per-table initialization (e.g. initial value for
288    /// non-null tables) as well as active element segments. This is processed
289    /// and refined by [`ModuleTranslation::finalize_table_init`] after
290    /// translation.
291    pub table_initialization: TableInitialization,
292
293    /// WebAssembly memory initialization.
294    ///
295    /// This is held here in an `Unprocessed` form during translation, and then
296    /// this is later finished with [`ModuleTranslation::finalize_memory_init`].
297    pub memory_init: MemoryInit<'data>,
298}
299
300/// Different forms of memory initialization that happens for a module.
301pub enum MemoryInit<'a> {
302    /// Raw active data segments that are being applied for an instance.
303    ///
304    /// This list contains the raw data  which hasn't yet been processed into
305    /// `RuntimeDataIndex`, for example. This is later processed during
306    /// [`ModuleTranslation::finalize_memory_init`] to optionally shuffle things
307    /// around.
308    Unprocessed(Vec<MemoryInitializer<'a>>),
309
310    /// Finalized memory initialization to be executed after
311    /// [`ModuleTranslation::finalize_memory_init`] has run. This represents
312    /// active data segments which may have been merged from the `Unprocessed`
313    /// list above, and may or may not have statically know offsets.
314    Processed(Vec<(MemoryIndex, MemorySegmentOffset, RuntimeDataIndex)>),
315}
316
317/// Offset within [`MemoryInit::Processed`] which indicates the initial offset
318/// a data segment is applied at.
319pub enum MemorySegmentOffset {
320    /// A "complicated" constant expression deferred to get evaluated at runtime
321    /// with compiled code.
322    Expr(ConstExpr),
323
324    /// A statically known, in-bounds, constant value.
325    Static(u64),
326}
327
328/// Lazy decoder over the branch hints attached to a single function in the
329/// `metadata.code.branch_hint` custom section
330/// ([branch-hinting proposal](https://github.com/WebAssembly/branch-hinting)).
331pub type BranchHintReader<'a> = wasmparser::SectionLimited<'a, wasmparser::BranchHint>;
332
333impl<'data> ModuleTranslation<'data> {
334    /// Create a new translation for the module with the given index.
335    pub fn new(module_index: StaticModuleIndex) -> Self {
336        Self {
337            module: Module::new(module_index),
338            wasm: &[],
339            wasm_module_offset: 0,
340            function_body_inputs: PrimaryMap::default(),
341            known_imported_functions: SecondaryMap::default(),
342            imported_func_vmctx_representative: SecondaryMap::default(),
343            imported_funcs_never_throw: EntitySet::new(),
344            known_imported_globals: SecondaryMap::default(),
345            known_imported_memories: SecondaryMap::default(),
346            known_imported_tables: SecondaryMap::default(),
347            globals_known_to_importers: EntitySet::new(),
348            memories_known_to_importers: EntitySet::new(),
349            tables_known_to_importers: EntitySet::new(),
350            exported_signatures: Vec::default(),
351            debuginfo: DebugInfoData::default(),
352            has_unparsed_debuginfo: false,
353            data_align: None,
354            runtime_data: Default::default(),
355            code_index: 0,
356            types: None,
357            runtime_data_map: Default::default(),
358            passive_elem_map: Default::default(),
359            branch_hints: HashMap::default(),
360            start_func: None,
361            global_initializers: Vec::new(),
362            passive_elements: Default::default(),
363            table_initialization: Default::default(),
364            memory_init: MemoryInit::Unprocessed(Vec::new()),
365            passive_data: Default::default(),
366        }
367    }
368
369    /// Returns the [`BranchHintReader`] for `func`, if the section attached any.
370    pub fn branch_hints(&self, func: FuncIndex) -> Option<BranchHintReader<'data>> {
371        self.branch_hints.get(&func).cloned()
372    }
373
374    /// Returns a reference to the type information of the current module.
375    pub fn get_types(&self) -> &Types {
376        self.types
377            .as_ref()
378            .expect("module type information to be available")
379    }
380
381    /// Get this translation's module's index.
382    pub fn module_index(&self) -> StaticModuleIndex {
383        self.module.module_index
384    }
385}
386
387/// Contains function data: byte code and its offset in the module.
388pub struct FunctionBodyData<'a> {
389    /// The body of the function, containing code and locals.
390    pub body: FunctionBody<'a>,
391    /// Validator for the function body
392    pub validator: FuncToValidate<ValidatorResources>,
393}
394
395#[derive(Debug, Default)]
396#[expect(missing_docs, reason = "self-describing fields")]
397pub struct DebugInfoData<'a> {
398    pub dwarf: Dwarf<'a>,
399    pub name_section: NameSection<'a>,
400    pub wasm_file: WasmFileInfo,
401    pub debug_loc: gimli::DebugLoc<Reader<'a>>,
402    pub debug_loclists: gimli::DebugLocLists<Reader<'a>>,
403    pub debug_ranges: gimli::DebugRanges<Reader<'a>>,
404    pub debug_rnglists: gimli::DebugRngLists<Reader<'a>>,
405    pub debug_cu_index: gimli::DebugCuIndex<Reader<'a>>,
406    pub debug_tu_index: gimli::DebugTuIndex<Reader<'a>>,
407}
408
409#[expect(missing_docs, reason = "self-describing")]
410pub type Dwarf<'input> = gimli::Dwarf<Reader<'input>>;
411
412type Reader<'input> = gimli::EndianSlice<'input, gimli::LittleEndian>;
413
414#[derive(Debug, Default)]
415#[expect(missing_docs, reason = "self-describing fields")]
416pub struct NameSection<'a> {
417    pub module_name: Option<&'a str>,
418    pub func_names: HashMap<FuncIndex, &'a str>,
419    pub locals_names: HashMap<FuncIndex, HashMap<u32, &'a str>>,
420}
421
422#[derive(Debug, Default)]
423#[expect(missing_docs, reason = "self-describing fields")]
424pub struct WasmFileInfo {
425    pub path: Option<PathBuf>,
426    pub code_section_offset: u64,
427    pub imported_func_count: u32,
428    pub funcs: Vec<FunctionMetadata>,
429}
430
431#[derive(Debug)]
432#[expect(missing_docs, reason = "self-describing fields")]
433pub struct FunctionMetadata {
434    pub params: Box<[WasmValType]>,
435    pub locals: Box<[(u32, WasmValType)]>,
436}
437
438impl<'a, 'data> ModuleEnvironment<'a, 'data> {
439    /// Allocates the environment data structures.
440    pub fn new(
441        tunables: &'a Tunables,
442        validator: &'a mut Validator,
443        types: &'a mut ModuleTypesBuilder,
444        module_index: StaticModuleIndex,
445    ) -> Self {
446        Self {
447            result: ModuleTranslation::new(module_index),
448            types,
449            tunables,
450            validator,
451        }
452    }
453
454    /// Translate a wasm module using this environment.
455    ///
456    /// This function will translate the `data` provided with `parser`,
457    /// validating everything along the way with this environment's validator.
458    ///
459    /// The result of translation, [`ModuleTranslation`], contains everything
460    /// necessary to compile functions afterwards as well as learn type
461    /// information about the module at runtime.
462    pub fn translate(
463        mut self,
464        parser: Parser,
465        data: &'data [u8],
466    ) -> Result<ModuleTranslation<'data>> {
467        self.result.wasm = data;
468        self.result.module.has_shadow_memories = self.tunables.memory_watchpoints;
469
470        for payload in parser.parse_all(data) {
471            self.translate_payload(payload?)?;
472        }
473
474        Ok(self.result)
475    }
476
477    fn translate_payload(&mut self, payload: Payload<'data>) -> Result<()> {
478        match payload {
479            Payload::Version {
480                num,
481                encoding,
482                range,
483            } => {
484                self.validator.version(num, encoding, &range)?;
485                match encoding {
486                    Encoding::Module => {}
487                    Encoding::Component => {
488                        bail!("expected a WebAssembly module but was given a WebAssembly component")
489                    }
490                }
491            }
492
493            Payload::End(offset) => {
494                self.result.types = Some(self.validator.end(offset)?);
495
496                // With the `escaped_funcs` set of functions finished
497                // we can calculate the set of signatures that are exported as
498                // the set of exported functions' signatures.
499                self.result.exported_signatures = self
500                    .result
501                    .module
502                    .functions
503                    .iter()
504                    .filter_map(|(_, func)| {
505                        if func.is_escaping() {
506                            Some(func.signature.unwrap_module_type_index())
507                        } else {
508                            None
509                        }
510                    })
511                    .collect();
512                self.result.exported_signatures.sort_unstable();
513                self.result.exported_signatures.dedup();
514            }
515
516            Payload::TypeSection(types) => {
517                self.validator.type_section(&types)?;
518
519                let count = self.validator.types(0).unwrap().core_type_count_in_module();
520                log::trace!("interning {count} Wasm types");
521
522                let capacity = usize::try_from(count).unwrap();
523                self.result.module.types.reserve(capacity)?;
524                self.types.reserve_wasm_signatures(capacity);
525
526                // Iterate over each *rec group* -- not type -- defined in the
527                // types section. Rec groups are the unit of canonicalization
528                // and therefore the unit at which we need to process at a
529                // time. `wasmparser` has already done the hard work of
530                // de-duplicating and canonicalizing the rec groups within the
531                // module for us, we just need to translate them into our data
532                // structures. Note that, if the Wasm defines duplicate rec
533                // groups, we need copy the duplicates over (shallowly) as well,
534                // so that our types index space doesn't have holes.
535                let mut type_index = 0;
536                while type_index < count {
537                    let validator_types = self.validator.types(0).unwrap();
538
539                    // Get the rec group for the current type index, which is
540                    // always the first type defined in a rec group.
541                    log::trace!("looking up wasmparser type for index {type_index}");
542                    let core_type_id = validator_types.core_type_at_in_module(type_index);
543                    log::trace!(
544                        "  --> {core_type_id:?} = {:?}",
545                        validator_types[core_type_id],
546                    );
547                    let rec_group_id = validator_types.rec_group_id_of(core_type_id);
548                    debug_assert_eq!(
549                        validator_types
550                            .rec_group_elements(rec_group_id)
551                            .position(|id| id == core_type_id),
552                        Some(0)
553                    );
554
555                    // Intern the rec group and then fill in this module's types
556                    // index space.
557                    let interned = self.types.intern_rec_group(validator_types, rec_group_id)?;
558                    let elems = self.types.rec_group_elements(interned);
559                    let len = elems.len();
560                    self.result.module.types.reserve(len)?;
561                    for ty in elems {
562                        self.result.module.types.push(ty.into())?;
563                    }
564
565                    // Advance `type_index` to the start of the next rec group.
566                    type_index += u32::try_from(len).unwrap();
567                }
568            }
569
570            Payload::ImportSection(imports) => {
571                self.validator.import_section(&imports)?;
572
573                let cnt = usize::try_from(imports.count()).unwrap();
574                self.result.module.initializers.reserve(cnt)?;
575
576                for entry in imports.into_imports() {
577                    let import = entry?;
578                    let ty = match import.ty {
579                        TypeRef::Func(index) => {
580                            let index = TypeIndex::from_u32(index);
581                            let interned_index = self.result.module.types[index];
582                            self.result.module.num_imported_funcs += 1;
583                            self.result.debuginfo.wasm_file.imported_func_count += 1;
584                            EntityType::Function(interned_index)
585                        }
586                        TypeRef::Memory(ty) => {
587                            self.result.module.num_imported_memories += 1;
588                            EntityType::Memory(ty.into())
589                        }
590                        TypeRef::Global(ty) => {
591                            self.result.module.num_imported_globals += 1;
592                            EntityType::Global(self.convert_global_type(&ty)?)
593                        }
594                        TypeRef::Table(ty) => {
595                            self.result.module.num_imported_tables += 1;
596                            EntityType::Table(self.convert_table_type(&ty)?)
597                        }
598                        TypeRef::Tag(ty) => {
599                            let index = TypeIndex::from_u32(ty.func_type_idx);
600                            let signature = self.result.module.types[index];
601                            let exception = self.types.define_exception_type_for_tag(
602                                signature.unwrap_module_type_index(),
603                            );
604                            let tag = Tag {
605                                signature,
606                                exception: EngineOrModuleTypeIndex::Module(exception),
607                            };
608                            self.result.module.num_imported_tags += 1;
609                            EntityType::Tag(tag)
610                        }
611                        TypeRef::FuncExact(_) => {
612                            bail!("custom-descriptors proposal not implemented yet");
613                        }
614                    };
615                    self.declare_import(import.module, import.name, ty)?;
616                }
617            }
618
619            Payload::FunctionSection(functions) => {
620                self.validator.function_section(&functions)?;
621
622                let cnt = usize::try_from(functions.count()).unwrap();
623                self.result.module.functions.reserve_exact(cnt)?;
624
625                for entry in functions {
626                    let sigindex = entry?;
627                    let ty = TypeIndex::from_u32(sigindex);
628                    let interned_index = self.result.module.types[ty];
629                    self.result.module.push_function(interned_index);
630                }
631            }
632
633            Payload::TableSection(tables) => {
634                self.validator.table_section(&tables)?;
635                let cnt = usize::try_from(tables.count()).unwrap();
636                self.result.module.tables.reserve_exact(cnt)?;
637
638                for entry in tables {
639                    let wasmparser::Table { ty, init } = entry?;
640                    let table = self.convert_table_type(&ty)?;
641                    self.result.module.needs_gc_heap |= table.ref_type.is_vmgcref_type();
642                    self.result.module.tables.push(table)?;
643                    let init = match init {
644                        wasmparser::TableInit::RefNull => TableInitialValue::Null,
645                        wasmparser::TableInit::Expr(expr) => {
646                            let (init, escaped) = ConstExpr::from_wasmparser(self, expr)?;
647                            for f in escaped {
648                                self.flag_func_escaped(f);
649                            }
650                            TableInitialValue::Expr(init)
651                        }
652                    };
653                    self.result.table_initialization.initial_values.push(init)?;
654                    self.result
655                        .module
656                        .table_initialization
657                        .push(Default::default())?;
658                }
659            }
660
661            Payload::MemorySection(memories) => {
662                self.validator.memory_section(&memories)?;
663
664                let cnt = usize::try_from(memories.count()).unwrap();
665                self.result.module.memories.reserve_exact(cnt)?;
666
667                for entry in memories {
668                    let memory = entry?;
669                    self.result.module.memories.push(memory.into())?;
670                }
671            }
672
673            Payload::TagSection(tags) => {
674                self.validator.tag_section(&tags)?;
675
676                for entry in tags {
677                    let sigindex = entry?.func_type_idx;
678                    let ty = TypeIndex::from_u32(sigindex);
679                    let interned_index = self.result.module.types[ty];
680                    let exception = self
681                        .types
682                        .define_exception_type_for_tag(interned_index.unwrap_module_type_index());
683                    self.result.module.push_tag(interned_index, exception);
684                }
685            }
686
687            Payload::GlobalSection(globals) => {
688                self.validator.global_section(&globals)?;
689
690                let cnt = usize::try_from(globals.count()).unwrap();
691                self.result.module.globals.reserve_exact(cnt)?;
692
693                for entry in globals {
694                    let wasmparser::Global { ty, init_expr } = entry?;
695                    let (initializer, escaped) = ConstExpr::from_wasmparser(self, init_expr)?;
696                    for f in escaped {
697                        self.flag_func_escaped(f);
698                    }
699                    let ty = self.convert_global_type(&ty)?;
700                    let index = self.result.module.globals.push(ty)?;
701                    let defined_index = self.result.module.defined_global_index(index).unwrap();
702                    match initializer.const_eval() {
703                        Some(val) => {
704                            self.result
705                                .module
706                                .global_initializers
707                                .push((defined_index, val))?;
708                        }
709                        None => {
710                            // "Complicated" global initializers are deferred
711                            // to get evaluated in the startup function.
712                            self.require_startup_func();
713                            self.result
714                                .global_initializers
715                                .push((defined_index, initializer));
716                        }
717                    }
718                }
719            }
720
721            Payload::ExportSection(exports) => {
722                self.validator.export_section(&exports)?;
723
724                let cnt = usize::try_from(exports.count()).unwrap();
725                self.result.module.exports.reserve(cnt)?;
726
727                for entry in exports {
728                    let wasmparser::Export { name, kind, index } = entry?;
729                    let entity = match kind {
730                        ExternalKind::Func | ExternalKind::FuncExact => {
731                            let index = FuncIndex::from_u32(index);
732                            self.flag_func_escaped(index);
733                            EntityIndex::Function(index)
734                        }
735                        ExternalKind::Table => EntityIndex::Table(TableIndex::from_u32(index)),
736                        ExternalKind::Memory => EntityIndex::Memory(MemoryIndex::from_u32(index)),
737                        ExternalKind::Global => EntityIndex::Global(GlobalIndex::from_u32(index)),
738                        ExternalKind::Tag => EntityIndex::Tag(TagIndex::from_u32(index)),
739                    };
740                    let name = self.result.module.strings.insert(name)?;
741                    self.result.module.exports.insert(name, entity)?;
742                }
743            }
744
745            Payload::StartSection { func, range } => {
746                self.validator.start_section(func, &range)?;
747
748                let func_index = FuncIndex::from_u32(func);
749                debug_assert!(self.result.start_func.is_none());
750                self.result.start_func = Some(func_index);
751
752                // To make startup a bit easier, invoking the `start` function
753                // is a responsibility deferred to the startup function.
754                self.require_startup_func();
755            }
756
757            Payload::ElementSection(elements) => {
758                self.validator.element_section(&elements)?;
759
760                // Whether writes to tables made so far during instantiation
761                // could be observed outside of this instance, which becomes
762                // true once an active segment applies to an imported table.
763                let mut side_effects_visible = false;
764
765                for (index, entry) in elements.into_iter().enumerate() {
766                    let wasmparser::Element {
767                        kind,
768                        items,
769                        range: _,
770                    } = entry?;
771
772                    // Build up a list of `FuncIndex` corresponding to all the
773                    // entries listed in this segment. Note that it's not
774                    // possible to create anything other than a `ref.null
775                    // extern` for externref segments, so those just get
776                    // translated to the reserved value of `FuncIndex`.
777                    let elements = match items {
778                        ElementItems::Functions(funcs) => {
779                            let mut elems =
780                                Vec::with_capacity(usize::try_from(funcs.count()).unwrap());
781                            for func in funcs {
782                                let func = FuncIndex::from_u32(func?);
783                                self.flag_func_escaped(func);
784                                elems.push(func);
785                            }
786                            TableSegmentElements::Functions(elems.into())
787                        }
788                        ElementItems::Expressions(ty, items) => {
789                            let ty = self.convert_ref_type(ty)?;
790                            let mut exprs =
791                                Vec::with_capacity(usize::try_from(items.count()).unwrap());
792                            for expr in items {
793                                let (expr, escaped) = ConstExpr::from_wasmparser(self, expr?)?;
794                                exprs.push(expr);
795                                for func in escaped {
796                                    self.flag_func_escaped(func);
797                                }
798                            }
799                            TableSegmentElements::Expressions {
800                                ty,
801                                exprs: exprs.into(),
802                            }
803                        }
804                    };
805
806                    let passive_index = match kind {
807                        ElementKind::Active {
808                            table_index,
809                            offset_expr,
810                        } => {
811                            let table_index = TableIndex::from_u32(table_index.unwrap_or(0));
812                            let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
813                            debug_assert!(escaped.is_empty());
814
815                            // The spec's instantiation evaluates the
816                            // expressions of all element segments before
817                            // executing any active segment's `table.init`
818                            // (https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation).
819                            // So if any element expression may trap, and an
820                            // earlier write (including from this segment)
821                            // could be observed, then stage its evaluation
822                            // into a passive element segment, which is
823                            // evaluated before any active segment is applied.
824                            // Note that this passive segment isn't registered
825                            // in `passive_elem_map` so it's not reachable from
826                            // wasm itself.
827                            //
828                            // If no imported table has been written yet then a
829                            // trap is unobservable, so evaluating in place is
830                            // fine and avoids the extra copy.
831                            side_effects_visible |=
832                                self.result.module.is_imported_table(table_index);
833                            let init = if side_effects_visible && elements_may_trap(&elements) {
834                                let len = elements.len();
835                                let index = self
836                                    .result
837                                    .module
838                                    .passive_elements
839                                    .push((elements.ty(), len))?;
840                                self.result.passive_elements.push(elements);
841                                self.require_startup_func();
842                                TableSegmentInit::Staged { index, len }
843                            } else {
844                                TableSegmentInit::Direct(elements)
845                            };
846
847                            self.result
848                                .table_initialization
849                                .segments
850                                .push(TableSegment {
851                                    table_index,
852                                    offset,
853                                    init,
854                                })?;
855                            None
856                        }
857
858                        ElementKind::Passive => {
859                            let passive_index = self
860                                .result
861                                .module
862                                .passive_elements
863                                .push((elements.ty(), elements.len()))?;
864                            self.result.passive_elements.push(elements);
865                            // One-time initialization of passive element
866                            // segments is deferred to the startup function.
867                            self.require_startup_func();
868                            Some(passive_index)
869                        }
870
871                        ElementKind::Declared => None,
872                    };
873                    let elem_index = ElemIndex::from_u32(index as u32);
874                    self.result
875                        .passive_elem_map
876                        .insert(elem_index, passive_index);
877                }
878            }
879
880            Payload::CodeSectionStart {
881                count,
882                unchecked_range,
883                ..
884            } => {
885                self.validator.code_section_start(&unchecked_range)?;
886                let cnt = usize::try_from(count).unwrap();
887                self.result.function_body_inputs.reserve_exact(cnt);
888                self.result.debuginfo.wasm_file.code_section_offset = unchecked_range.start;
889            }
890
891            Payload::CodeSectionEntry(body) => {
892                let validator = self.validator.code_section_entry(&body)?;
893                let func_index =
894                    self.result.code_index + self.result.module.num_imported_funcs as u32;
895                let func_index = FuncIndex::from_u32(func_index);
896
897                if self.tunables.debug_native {
898                    let sig_index = self.result.module.functions[func_index]
899                        .signature
900                        .unwrap_module_type_index();
901                    let sig = self.types[sig_index].unwrap_func();
902                    let mut locals = Vec::new();
903                    for pair in body.get_locals_reader()? {
904                        let (cnt, ty) = pair?;
905                        let ty = self.convert_valtype(ty)?;
906                        locals.push((cnt, ty));
907                    }
908                    self.result
909                        .debuginfo
910                        .wasm_file
911                        .funcs
912                        .push(FunctionMetadata {
913                            locals: locals.into_boxed_slice(),
914                            params: sig.params().into(),
915                        });
916                }
917                if self.tunables.debug_guest {
918                    // All functions are potentially reachable and
919                    // callable by the guest debugger, so they must
920                    // all be flagged as escaping.
921                    self.flag_func_escaped(func_index);
922                }
923                self.result
924                    .function_body_inputs
925                    .push(FunctionBodyData { validator, body });
926                self.result.code_index += 1;
927            }
928
929            Payload::DataSection(data) => {
930                self.validator.data_section(&data)?;
931
932                assert!(self.result.module.memory_initialization.is_segmented());
933
934                for (index, entry) in data.into_iter().enumerate() {
935                    let wasmparser::Data {
936                        kind,
937                        data,
938                        range: _,
939                    } = entry?;
940                    let data_index = DataIndex::from_u32(index.try_into().unwrap());
941                    match kind {
942                        DataKind::Active {
943                            memory_index,
944                            offset_expr,
945                        } => {
946                            let memory_index = MemoryIndex::from_u32(memory_index);
947                            let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
948                            debug_assert!(escaped.is_empty());
949
950                            let MemoryInit::Unprocessed(list) = &mut self.result.memory_init else {
951                                panic!("memory initializers should be unprocessed at this point");
952                            };
953                            list.push(MemoryInitializer {
954                                memory_index,
955                                offset,
956                                data,
957                            });
958                        }
959                        DataKind::Passive => {
960                            self.result.passive_data.push((data_index, data));
961                        }
962                    }
963                }
964            }
965
966            Payload::DataCountSection { count, range } => {
967                self.validator.data_count_section(count, &range)?;
968
969                // Note: the count passed in here is the *total* segment count
970                // There is no way to reserve for just the passive segments as
971                // they are discovered when iterating the data section entries
972                // Given that the total segment count might be much larger than
973                // the passive count, do not reserve anything here.
974            }
975
976            Payload::CustomSection(s)
977                if s.name() == "webidl-bindings" || s.name() == "wasm-interface-types" =>
978            {
979                bail!(
980                    "\
981Support for interface types has temporarily been removed from `wasmtime`.
982
983For more information about this temporary change you can read on the issue online:
984
985    https://github.com/bytecodealliance/wasmtime/issues/1271
986
987and for re-adding support for interface types you can see this issue:
988
989    https://github.com/bytecodealliance/wasmtime/issues/677
990"
991                )
992            }
993
994            Payload::CustomSection(s) => {
995                self.register_custom_section(&s);
996            }
997
998            // It's expected that validation will probably reject other
999            // payloads such as `UnknownSection` or those related to the
1000            // component model. If, however, something gets past validation then
1001            // that's a bug in Wasmtime as we forgot to implement something.
1002            other => {
1003                self.validator.payload(&other)?;
1004                panic!("unimplemented section in wasm file {other:?}");
1005            }
1006        }
1007        Ok(())
1008    }
1009
1010    fn register_custom_section(&mut self, section: &CustomSectionReader<'data>) {
1011        match section.as_known() {
1012            KnownCustom::Name(name) => {
1013                let result = self.name_section(name);
1014                if let Err(e) = result {
1015                    log::warn!("failed to parse name section {e:?}");
1016                }
1017            }
1018            KnownCustom::BranchHints(reader) if self.tunables.branch_hinting => {
1019                // Branch hints are advisory and this section is never validated;
1020                // it is decoded lazily during compilation, so record only the
1021                // per-function sub-readers here. Discard the whole section if any
1022                // entry is malformed rather than applying it partially.
1023                let mut hints = HashMap::new();
1024                let result: wasmparser::Result<()> = reader.into_iter().try_for_each(|func| {
1025                    let func = func?;
1026                    // A well-formed section lists each function at most once; keep
1027                    // the first entry deterministically if it repeats.
1028                    hints
1029                        .entry(FuncIndex::from_u32(func.func))
1030                        .or_insert(func.hints);
1031                    Ok(())
1032                });
1033                match result {
1034                    Ok(()) => self.result.branch_hints = hints,
1035                    Err(e) => log::warn!("failed to parse branch-hint section {e:?}"),
1036                }
1037            }
1038            _ => {
1039                let name = section.name().trim_end_matches(".dwo");
1040                if name.starts_with(".debug_") {
1041                    self.dwarf_section(name, section);
1042                }
1043            }
1044        }
1045    }
1046
1047    fn dwarf_section(&mut self, name: &str, section: &CustomSectionReader<'data>) {
1048        if !self.tunables.debug_native && !self.tunables.parse_wasm_debuginfo {
1049            self.result.has_unparsed_debuginfo = true;
1050            return;
1051        }
1052        let info = &mut self.result.debuginfo;
1053        let dwarf = &mut info.dwarf;
1054        let endian = gimli::LittleEndian;
1055        let data = section.data();
1056        let slice = gimli::EndianSlice::new(data, endian);
1057
1058        match name {
1059            // `gimli::Dwarf` fields.
1060            ".debug_abbrev" => dwarf.debug_abbrev = gimli::DebugAbbrev::new(data, endian),
1061            ".debug_addr" => dwarf.debug_addr = gimli::DebugAddr::from(slice),
1062            ".debug_info" => {
1063                dwarf.debug_info = gimli::DebugInfo::new(data, endian);
1064            }
1065            ".debug_line" => dwarf.debug_line = gimli::DebugLine::new(data, endian),
1066            ".debug_line_str" => dwarf.debug_line_str = gimli::DebugLineStr::from(slice),
1067            ".debug_str" => dwarf.debug_str = gimli::DebugStr::new(data, endian),
1068            ".debug_str_offsets" => dwarf.debug_str_offsets = gimli::DebugStrOffsets::from(slice),
1069            ".debug_str_sup" => {
1070                let mut dwarf_sup: Dwarf<'data> = Default::default();
1071                dwarf_sup.debug_str = gimli::DebugStr::from(slice);
1072                dwarf.sup = Some(Arc::new(dwarf_sup));
1073            }
1074            ".debug_types" => dwarf.debug_types = gimli::DebugTypes::from(slice),
1075
1076            // Additional fields.
1077            ".debug_loc" => info.debug_loc = gimli::DebugLoc::from(slice),
1078            ".debug_loclists" => info.debug_loclists = gimli::DebugLocLists::from(slice),
1079            ".debug_ranges" => info.debug_ranges = gimli::DebugRanges::new(data, endian),
1080            ".debug_rnglists" => info.debug_rnglists = gimli::DebugRngLists::new(data, endian),
1081
1082            // DWARF package fields
1083            ".debug_cu_index" => info.debug_cu_index = gimli::DebugCuIndex::new(data, endian),
1084            ".debug_tu_index" => info.debug_tu_index = gimli::DebugTuIndex::new(data, endian),
1085
1086            // We don't use these at the moment.
1087            ".debug_aranges" | ".debug_pubnames" | ".debug_pubtypes" => return,
1088            other => {
1089                log::warn!("unknown debug section `{other}`");
1090                return;
1091            }
1092        }
1093
1094        dwarf.ranges = gimli::RangeLists::new(info.debug_ranges, info.debug_rnglists);
1095        dwarf.locations = gimli::LocationLists::new(info.debug_loc, info.debug_loclists);
1096    }
1097
1098    /// Declares a new import with the `module` and `field` names, importing the
1099    /// `ty` specified.
1100    ///
1101    /// Note that this method is somewhat tricky due to the implementation of
1102    /// the module linking proposal. In the module linking proposal two-level
1103    /// imports are recast as single-level imports of instances. That recasting
1104    /// happens here by recording an import of an instance for the first time
1105    /// we see a two-level import.
1106    ///
1107    /// When the module linking proposal is disabled, however, disregard this
1108    /// logic and instead work directly with two-level imports since no
1109    /// instances are defined.
1110    fn declare_import(
1111        &mut self,
1112        module: &'data str,
1113        field: &'data str,
1114        ty: EntityType,
1115    ) -> Result<(), OutOfMemory> {
1116        let index = self.push_type(ty);
1117        self.result.module.initializers.push(Initializer::Import {
1118            name: self.result.module.strings.insert(module)?,
1119            field: self.result.module.strings.insert(field)?,
1120            index,
1121        })?;
1122        Ok(())
1123    }
1124
1125    fn push_type(&mut self, ty: EntityType) -> EntityIndex {
1126        match ty {
1127            EntityType::Function(ty) => EntityIndex::Function({
1128                let func_index = self
1129                    .result
1130                    .module
1131                    .push_function(ty.unwrap_module_type_index());
1132                // Imported functions can escape; in fact, they've already done
1133                // so to get here.
1134                self.flag_func_escaped(func_index);
1135                func_index
1136            }),
1137            EntityType::Table(ty) => {
1138                EntityIndex::Table(self.result.module.tables.push(ty).panic_on_oom())
1139            }
1140            EntityType::Memory(ty) => {
1141                EntityIndex::Memory(self.result.module.memories.push(ty).panic_on_oom())
1142            }
1143            EntityType::Global(ty) => {
1144                EntityIndex::Global(self.result.module.globals.push(ty).panic_on_oom())
1145            }
1146            EntityType::Tag(ty) => {
1147                EntityIndex::Tag(self.result.module.tags.push(ty).panic_on_oom())
1148            }
1149        }
1150    }
1151
1152    fn flag_func_escaped(&mut self, func: FuncIndex) {
1153        let ty = &mut self.result.module.functions[func];
1154        // If this was already assigned a funcref index no need to re-assign it.
1155        if ty.is_escaping() {
1156            return;
1157        }
1158        let index = self.result.module.num_escaped_funcs as u32;
1159        ty.func_ref = FuncRefIndex::from_u32(index);
1160        self.result.module.num_escaped_funcs += 1;
1161    }
1162
1163    /// Parses the Name section of the wasm module.
1164    fn name_section(&mut self, names: NameSectionReader<'data>) -> WasmResult<()> {
1165        for subsection in names {
1166            match subsection? {
1167                wasmparser::Name::Function(names) => {
1168                    for name in names {
1169                        let Naming { index, name } = name?;
1170                        // Skip this naming if it's naming a function that
1171                        // doesn't actually exist.
1172                        if (index as usize) >= self.result.module.functions.len() {
1173                            continue;
1174                        }
1175
1176                        // Store the name unconditionally, regardless of
1177                        // whether we're parsing debuginfo, since function
1178                        // names are almost always present in the
1179                        // final compilation artifact.
1180                        let index = FuncIndex::from_u32(index);
1181                        self.result
1182                            .debuginfo
1183                            .name_section
1184                            .func_names
1185                            .insert(index, name);
1186                    }
1187                }
1188                wasmparser::Name::Module { name, .. } => {
1189                    self.result.module.name =
1190                        Some(self.result.module.strings.insert(name).panic_on_oom());
1191                    if self.tunables.debug_native {
1192                        self.result.debuginfo.name_section.module_name = Some(name);
1193                    }
1194                }
1195                wasmparser::Name::Local(reader) => {
1196                    if !self.tunables.debug_native {
1197                        continue;
1198                    }
1199                    for f in reader {
1200                        let f = f?;
1201                        // Skip this naming if it's naming a function that
1202                        // doesn't actually exist.
1203                        if (f.index as usize) >= self.result.module.functions.len() {
1204                            continue;
1205                        }
1206                        for name in f.names {
1207                            let Naming { index, name } = name?;
1208
1209                            self.result
1210                                .debuginfo
1211                                .name_section
1212                                .locals_names
1213                                .entry(FuncIndex::from_u32(f.index))
1214                                .or_insert(HashMap::new())
1215                                .insert(index, name);
1216                        }
1217                    }
1218                }
1219                wasmparser::Name::Label(_)
1220                | wasmparser::Name::Type(_)
1221                | wasmparser::Name::Table(_)
1222                | wasmparser::Name::Global(_)
1223                | wasmparser::Name::Memory(_)
1224                | wasmparser::Name::Element(_)
1225                | wasmparser::Name::Data(_)
1226                | wasmparser::Name::Tag(_)
1227                | wasmparser::Name::Field(_)
1228                | wasmparser::Name::Parameter(_)
1229                | wasmparser::Name::TagParameter(_)
1230                | wasmparser::Name::Unknown { .. } => {}
1231            }
1232        }
1233        Ok(())
1234    }
1235
1236    fn require_startup_func(&mut self) {
1237        self.result.require_startup_func(self.types);
1238    }
1239}
1240
1241impl TypeConvert for ModuleEnvironment<'_, '_> {
1242    fn lookup_heap_type(&self, index: wasmparser::UnpackedIndex) -> WasmHeapType {
1243        WasmparserTypeConverter::new(&self.types, |idx| {
1244            self.result.module.types[idx].unwrap_module_type_index()
1245        })
1246        .lookup_heap_type(index)
1247    }
1248
1249    fn lookup_type_index(&self, index: wasmparser::UnpackedIndex) -> EngineOrModuleTypeIndex {
1250        WasmparserTypeConverter::new(&self.types, |idx| {
1251            self.result.module.types[idx].unwrap_module_type_index()
1252        })
1253        .lookup_type_index(index)
1254    }
1255}
1256
1257impl ModuleTranslation<'_> {
1258    /// Called after translation is complete this will finalize the memory
1259    /// initialization strategy for this module.
1260    ///
1261    /// This will notably use `Self::try_static_init` to attempt to massage
1262    /// data segments to being CoW-init-friendly. Afterwards the
1263    /// `self.memory_init` field is transitioned from `Unprocessed` to
1264    /// `Processed`.
1265    pub fn finalize_memory_init(
1266        &mut self,
1267        tunables: &Tunables,
1268        page_size: u64,
1269        max_image_size_always_allowed: u64,
1270        types: &mut ModuleTypesBuilder,
1271    ) {
1272        // Memory images are installed before the module's startup function
1273        // runs. If a table initializer can trap, using a memory image would
1274        // initialize memory even though the startup function should trap
1275        // before reaching the memory initializers.
1276        if tunables.memory_init_cow && !self.table_initialization_may_trap() {
1277            self.try_static_init(page_size, max_image_size_always_allowed);
1278        }
1279
1280        // Record/replay records every instance's startup as an activation,
1281        // so whether a module has one must not depend on how its memories
1282        // are initialized, which differs between engine configurations.
1283        if tunables.rr.is_some() {
1284            self.require_startup_func(types);
1285        }
1286
1287        // If any memory is statically initialized, and if that memory has an
1288        // initial data segment, then a startup function is at least
1289        // conditionally needed if the memory needs initialization. Flag as such
1290        // here.
1291        if let MemoryInitialization::Static { map } = &self.module.memory_initialization {
1292            if map.iter().any(|(_, v)| v.is_some()) {
1293                self.require_startup_func_if_memories_need_init(types);
1294            }
1295        }
1296
1297        // If, after `try_static_init`, initializers are still `Unprocessed`
1298        // then this is the catch-all fallback path for initialization. All
1299        // segments are promoted into `self.runtime_data` and then the
1300        // initialization is rewritten to `Processed`.
1301        if let MemoryInit::Unprocessed(list) = &mut self.memory_init {
1302            let segments = mem::take(list);
1303            let mut new_initializers = Vec::new();
1304            for segment in segments {
1305                new_initializers.push((
1306                    segment.memory_index,
1307                    MemorySegmentOffset::Expr(segment.offset),
1308                    self.runtime_data.push(segment.data.into()),
1309                ));
1310            }
1311            if !new_initializers.is_empty() {
1312                self.require_startup_func(types);
1313            }
1314            self.memory_init = MemoryInit::Processed(new_initializers);
1315        }
1316
1317        // At this point append all passive data to the `runtime_data` list.
1318        // This notably occurs after `try_static_init` above to ensure that the
1319        // page-aligned data for static initialization, if applicable, comes
1320        // first.
1321        for (data_index, segment) in self.passive_data.iter() {
1322            let runtime_index = self.runtime_data.push((*segment).into());
1323            self.runtime_data_map
1324                .insert(*data_index, Some(runtime_index));
1325        }
1326
1327        // And, finally, record all chunks from `self.runtime_data` within
1328        // `self.module.runtime_data` as well.
1329        let mut cur = 0;
1330        for (idx, data) in self.runtime_data.iter() {
1331            let len = u32::try_from(data.len()).unwrap();
1332            let i = self.module.runtime_data.push(cur..cur + len).panic_on_oom();
1333            cur += len;
1334            assert_eq!(idx, i);
1335        }
1336    }
1337
1338    /// Returns whether an active table initializer may trap during startup.
1339    ///
1340    /// Memory images are installed while allocating an instance, before the
1341    /// startup function executes. Therefore a memory image cannot be used when
1342    /// a table initializer might trap: doing so would make the memory
1343    /// observable even though execution should stop before reaching the memory
1344    /// initializers.
1345    fn table_initialization_may_trap(&self) -> bool {
1346        self.table_initialization.segments.iter().any(|segment| {
1347            let offset = match segment.offset.ops() {
1348                &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()),
1349                &[ConstOp::I64Const(offset)] => offset.cast_unsigned(),
1350                // A dynamic offset cannot be proven to be in bounds here.
1351                _ => return true,
1352            };
1353            let top = match offset.checked_add(segment.init.len()) {
1354                Some(top) => top,
1355                None => return true,
1356            };
1357            if top > self.module.tables[segment.table_index].limits.min {
1358                return true;
1359            }
1360            match &segment.init {
1361                TableSegmentInit::Direct(elements) => elements_may_trap(elements),
1362                TableSegmentInit::Staged { .. } => true,
1363            }
1364        })
1365    }
1366
1367    /// Attempts to convert segmented memory initialization into static
1368    /// initialization for the module that this translation represents.
1369    ///
1370    /// If this module's memory initialization is not compatible with paged
1371    /// initialization then this won't change anything. Otherwise if it is
1372    /// compatible then the `memory_initialization` field will be updated.
1373    ///
1374    /// Takes a `page_size` argument in order to ensure that all
1375    /// initialization is page-aligned for mmap-ability, and
1376    /// `max_image_size_always_allowed` to control how we decide
1377    /// whether to use static init.
1378    ///
1379    /// We will try to avoid generating very sparse images, which are
1380    /// possible if e.g. a module has an initializer at offset 0 and a
1381    /// very high offset (say, 1 GiB). To avoid this, we use a dual
1382    /// condition: we always allow images less than
1383    /// `max_image_size_always_allowed`, and the embedder of Wasmtime
1384    /// can set this if desired to ensure that static init should
1385    /// always be done if the size of the module or its heaps is
1386    /// otherwise bounded by the system. We also allow images with
1387    /// static init data bigger than that, but only if it is "dense",
1388    /// defined as having at least half (50%) of its pages with some
1389    /// data.
1390    ///
1391    /// We could do something slightly better by building a dense part
1392    /// and keeping a sparse list of outlier/leftover segments (see
1393    /// issue #3820). This would also allow mostly-static init of
1394    /// modules that have some dynamically-placed data segments. But,
1395    /// for now, this is sufficient to allow a system that "knows what
1396    /// it's doing" to always get static init.
1397    fn try_static_init(&mut self, page_size: u64, max_image_size_always_allowed: u64) {
1398        let segments = match &mut self.memory_init {
1399            MemoryInit::Unprocessed(list) => list,
1400            _ => return,
1401        };
1402
1403        // First a dry run of memory initialization is performed. This
1404        // collects information about the extent of memory initialized for each
1405        // memory as well as the size of all data segments being copied in.
1406        struct Memory<'a> {
1407            data_size: u64,
1408            min_addr: u64,
1409            max_addr: u64,
1410            segments: Vec<(u64, &'a [u8])>,
1411        }
1412        let mut info = PrimaryMap::with_capacity(self.module.memories.len());
1413        for _ in 0..self.module.memories.len() {
1414            info.push(Memory {
1415                data_size: 0,
1416                min_addr: u64::MAX,
1417                max_addr: 0,
1418                segments: Vec::new(),
1419            });
1420        }
1421
1422        for initializer in segments.iter() {
1423            let &MemoryInitializer {
1424                memory_index,
1425                ref offset,
1426                ref data,
1427            } = initializer;
1428
1429            // Currently `Static` only applies to locally-defined memories,
1430            // so if a data segment references an imported memory then
1431            // transitioning to a `Static` memory initializer is not
1432            // possible.
1433            if self.module.defined_memory_index(memory_index).is_none() {
1434                return;
1435            }
1436
1437            // First up determine the start/end range and verify that they're
1438            // in-bounds for the initial size of the memory at `memory_index`.
1439            // Note that this can bail if we don't have access to globals yet
1440            // (e.g. this is a task happening before instantiation at
1441            // compile-time).
1442            let start = match (offset.ops(), self.module.memories[memory_index].idx_type) {
1443                (&[ConstOp::I32Const(offset)], IndexType::I32) => offset.cast_unsigned().into(),
1444                (&[ConstOp::I64Const(offset)], IndexType::I64) => offset.cast_unsigned(),
1445                _ => return,
1446            };
1447            let len = u64::try_from(data.len()).unwrap();
1448            let end = match start.checked_add(len) {
1449                Some(end) => end,
1450                None => return,
1451            };
1452
1453            match self.module.memories[memory_index].minimum_byte_size() {
1454                Ok(max) => {
1455                    if end > max {
1456                        return;
1457                    }
1458                }
1459
1460                // Note that computing the minimum can overflow if the page
1461                // size is the default 64KiB and the memory's minimum size in
1462                // pages is `1 << 48`, the maximum number of minimum pages for
1463                // 64-bit memories. We don't return `false` to signal an error
1464                // here and instead defer the error to runtime, when it will be
1465                // impossible to allocate that much memory anyways.
1466                Err(_) => return,
1467            }
1468
1469            // Skip empty in-bounds data segments.
1470            if data.is_empty() {
1471                continue;
1472            }
1473
1474            let info = &mut info[memory_index];
1475            let len64 = u64::try_from(data.len()).unwrap();
1476            info.data_size += len64;
1477            info.min_addr = info.min_addr.min(start);
1478            info.max_addr = info.max_addr.max(start + len64);
1479            info.segments.push((start, data));
1480        }
1481
1482        // Validate that the memory information collected is indeed valid for
1483        // static memory initialization.
1484        for (i, info) in info.iter().filter(|(_, info)| info.data_size > 0) {
1485            let image_size = info.max_addr - info.min_addr;
1486
1487            // Simplify things for now by bailing out entirely if any memory has
1488            // a page size smaller than the host's page size. This fixes a case
1489            // where currently initializers are created in host-page-size units
1490            // of length which means that a larger-than-the-entire-memory
1491            // initializer can be created. This can be handled technically but
1492            // would require some more changes to help fix the assert elsewhere
1493            // that this protects against.
1494            if self.module.memories[i].page_size() < page_size {
1495                return;
1496            }
1497
1498            // If the range of memory being initialized is less than twice the
1499            // total size of the data itself then it's assumed that static
1500            // initialization is ok. This means we'll at most double memory
1501            // consumption during the memory image creation process, which is
1502            // currently assumed to "probably be ok" but this will likely need
1503            // tweaks over time.
1504            if image_size < info.data_size.saturating_mul(2) {
1505                continue;
1506            }
1507
1508            // If the memory initialization image is larger than the size of all
1509            // data, then we still allow memory initialization if the image will
1510            // be of a relatively modest size, such as 1MB here.
1511            if image_size < max_image_size_always_allowed {
1512                continue;
1513            }
1514
1515            // At this point memory initialization is concluded to be too
1516            // expensive to do at compile time so it's entirely deferred to
1517            // happen at runtime.
1518            return;
1519        }
1520
1521        // Here's where we've now committed to changing to static memory. The
1522        // memory initialization image is built here from the page data and then
1523        // it's converted to a single initializer.
1524        let mut map = TryPrimaryMap::with_capacity(info.len()).panic_on_oom();
1525        let mut new_initializers = Vec::new();
1526        for (memory, info) in info.iter() {
1527            // Create the in-memory `image` which is the initialized contents of
1528            // this linear memory.
1529            let extent = if info.segments.len() > 0 {
1530                (info.max_addr - info.min_addr) as usize
1531            } else {
1532                0
1533            };
1534            let mut image = Vec::with_capacity(extent);
1535            for (offset, data) in info.segments.iter() {
1536                let offset = usize::try_from(*offset - info.min_addr).unwrap();
1537                if image.len() < offset {
1538                    image.resize(offset, 0u8);
1539                    image.extend_from_slice(data);
1540                } else {
1541                    image.splice(
1542                        offset..(offset + data.len()).min(image.len()),
1543                        data.iter().copied(),
1544                    );
1545                }
1546            }
1547            assert_eq!(image.len(), extent);
1548            assert_eq!(image.capacity(), extent);
1549            let mut offset = if info.segments.len() > 0 {
1550                info.min_addr
1551            } else {
1552                0
1553            };
1554
1555            // Chop off trailing zeros from the image as memory is already
1556            // zero-initialized. Note that `i` is the position of a nonzero
1557            // entry here, so to not lose it we truncate to `i + 1`.
1558            if let Some(i) = image.iter().rposition(|i| *i != 0) {
1559                image.truncate(i + 1);
1560            }
1561
1562            // Also chop off leading zeros, if any.
1563            if let Some(i) = image.iter().position(|i| *i != 0) {
1564                offset += i as u64;
1565                image.drain(..i);
1566            }
1567            let mut len = u64::try_from(image.len()).unwrap();
1568
1569            // The goal is to enable mapping this image directly into memory, so
1570            // the offset into linear memory must be a multiple of the page
1571            // size. If that's not already the case then the image is padded at
1572            // the front and back with extra zeros as necessary
1573            if offset % page_size != 0 {
1574                let zero_padding = offset % page_size;
1575                image.splice(0..0, std::iter::repeat(0).take(zero_padding as usize));
1576                offset -= zero_padding;
1577                len += zero_padding;
1578            }
1579            if len % page_size != 0 {
1580                let zero_padding = page_size - (len % page_size);
1581                image.extend(std::iter::repeat(0).take(zero_padding as usize));
1582                len += zero_padding;
1583            }
1584            let runtime_index = if image.is_empty() {
1585                None
1586            } else {
1587                Some(self.runtime_data.push(image.into()))
1588            };
1589
1590            // Offset/length should now always be page-aligned.
1591            assert!(offset % page_size == 0);
1592            assert!(len % page_size == 0);
1593
1594            // Record the static memory initializer which describes this image,
1595            // only needed if the image is actually present and has a nonzero
1596            // length. The `offset` has been calculates above, originally
1597            // sourced from `info.min_addr`. The `data` field is the extent
1598            // within the final data segment we'll emit to an ELF image, which
1599            // is the concatenation of `self.data`, so here it's the size of
1600            // the section-so-far plus the current segment we're appending.
1601            let idx = map.push(runtime_index.map(|i| (offset, i))).panic_on_oom();
1602            assert_eq!(idx, memory);
1603            if let Some(runtime_index) = runtime_index {
1604                new_initializers.push((idx, MemorySegmentOffset::Static(offset), runtime_index));
1605            }
1606        }
1607        self.data_align = Some(page_size);
1608        self.module.memory_initialization = MemoryInitialization::Static { map };
1609        self.memory_init = MemoryInit::Processed(new_initializers);
1610    }
1611
1612    /// Finalizes the initialization of tables.
1613    ///
1614    /// This is invoked after translation and notably uses
1615    /// `Self::try_func_table_init` to attempt to optimize initialization of
1616    /// tables into static precomputed images.
1617    pub fn finalize_table_init(&mut self, tunables: &Tunables, types: &mut ModuleTypesBuilder) {
1618        if tunables.table_lazy_init {
1619            self.try_func_table_init();
1620        }
1621
1622        // If any table has a non-null initializers, or if there's any active
1623        // data segments, then a startup function is unconditionally required to
1624        // configure the table.
1625        if self
1626            .table_initialization
1627            .initial_values
1628            .iter()
1629            .any(|(_, v)| !matches!(v, TableInitialValue::Null))
1630            || !self.table_initialization.segments.is_empty()
1631        {
1632            self.require_startup_func(types);
1633        }
1634    }
1635
1636    /// Attempts to convert the module's table initializers to
1637    /// FuncTable form where possible. This enables lazy table
1638    /// initialization later by providing a one-to-one map of initial
1639    /// table values, without having to parse all segments.
1640    fn try_func_table_init(&mut self) {
1641        // This should be large enough to support very large Wasm
1642        // modules with huge funcref tables, but small enough to avoid
1643        // OOMs or DoS on truly sparse tables.
1644        const MAX_FUNC_TABLE_SIZE: u64 = 1024 * 1024;
1645
1646        // First convert any element-initialized tables to images of just that
1647        // single function if the minimum size of the table allows doing so.
1648        for ((i, init), (_, table)) in self.table_initialization.initial_values.iter_mut().zip(
1649            self.module
1650                .tables
1651                .iter()
1652                .skip(self.module.num_imported_tables),
1653        ) {
1654            let table_size = table.limits.min;
1655            if table_size > MAX_FUNC_TABLE_SIZE {
1656                continue;
1657            }
1658            if let TableInitialValue::Expr(expr) = init {
1659                if let [ConstOp::RefFunc(f)] = expr.ops() {
1660                    assert!(self.module.table_initialization[i].is_empty());
1661                    self.module.table_initialization[i] =
1662                        try_vec![*f; table_size as usize].panic_on_oom();
1663                    *init = TableInitialValue::Null;
1664                }
1665            }
1666        }
1667
1668        let mut segments = mem::take(&mut self.table_initialization.segments)
1669            .into_iter()
1670            .peekable();
1671
1672        // The goal of this loop is to interpret a table segment and apply it
1673        // "statically" to a local table. This will iterate over segments and
1674        // apply them one-by-one to each table.
1675        //
1676        // If any segment can't be applied, however, then this loop exits and
1677        // all remaining segments are placed back into the segment list. This is
1678        // because segments are supposed to be initialized one-at-a-time which
1679        // means that intermediate state is visible with respect to traps. If
1680        // anything isn't statically known to not trap it's pessimistically
1681        // assumed to trap meaning all further segment initializers must be
1682        // applied manually at instantiation time.
1683        while let Some(segment) = segments.peek() {
1684            let defined_index = match self.module.defined_table_index(segment.table_index) {
1685                Some(index) => index,
1686                // Skip imported tables: we can't provide a preconstructed
1687                // table for them, because their values depend on the
1688                // imported table overlaid with whatever segments we have.
1689                None => break,
1690            };
1691
1692            // If the base of this segment is dynamic, then we can't
1693            // include it in the statically-built array of initial
1694            // contents.
1695            let offset = match segment.offset.ops() {
1696                &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()),
1697                &[ConstOp::I64Const(offset)] => offset.cast_unsigned(),
1698                _ => break,
1699            };
1700
1701            // Get the end of this segment. If out-of-bounds, or too
1702            // large for our dense table representation, then skip the
1703            // segment.
1704            let top = match offset.checked_add(segment.init.len()) {
1705                Some(top) => top,
1706                None => break,
1707            };
1708            let table_size = self.module.tables[segment.table_index].limits.min;
1709            if top > table_size || top > MAX_FUNC_TABLE_SIZE {
1710                break;
1711            }
1712
1713            match self.module.tables[segment.table_index]
1714                .ref_type
1715                .heap_type
1716                .top()
1717            {
1718                WasmHeapTopType::Func => {}
1719                // If this is not a funcref table, then we can't support a
1720                // pre-computed table of function indices. Technically this
1721                // initializer won't trap so we could continue processing
1722                // segments, but that's left as a future optimization if
1723                // necessary.
1724                WasmHeapTopType::Any
1725                | WasmHeapTopType::Extern
1726                | WasmHeapTopType::Cont
1727                | WasmHeapTopType::Exn => break,
1728            }
1729
1730            // Function indices can be optimized here, but fully general
1731            // expressions are deferred to get evaluated at runtime.
1732            let function_elements = match &segment.init {
1733                TableSegmentInit::Direct(TableSegmentElements::Functions(indices)) => indices,
1734                TableSegmentInit::Direct(TableSegmentElements::Expressions { .. })
1735                | TableSegmentInit::Staged { .. } => break,
1736            };
1737
1738            match &self.table_initialization.initial_values[defined_index] {
1739                TableInitialValue::Null => {}
1740
1741                // If this table is still listed as an initial value here
1742                // then that means the initial size of the table doesn't
1743                // support a precomputed function list, so skip this.
1744                // Technically this won't trap so it's possible to process
1745                // further initializers, but that's left as a future
1746                // optimization.
1747                TableInitialValue::Expr(_) => break,
1748            }
1749            let precomputed = &mut self.module.table_initialization[defined_index];
1750
1751            // At this point we're committing to pre-initializing the table
1752            // with the `segment` that's being iterated over. This segment is
1753            // applied to the `precomputed` list for the table by ensuring
1754            // it's large enough to hold the segment and then copying the
1755            // segment into the precomputed list.
1756            if precomputed.len() < top as usize {
1757                precomputed
1758                    .resize(top as usize, FuncIndex::reserved_value())
1759                    .panic_on_oom();
1760            }
1761            let dst = &mut precomputed[offset as usize..top as usize];
1762            dst.copy_from_slice(&function_elements);
1763
1764            // advance the iterator to see the next segment
1765            let _ = segments.next();
1766        }
1767        self.table_initialization.segments = segments.try_collect().panic_on_oom();
1768    }
1769
1770    /// Helper function to ratchet the `startup` function for this module as
1771    /// `Always`.
1772    fn require_startup_func(&mut self, types: &mut ModuleTypesBuilder) {
1773        let ty = match self.module.startup {
1774            ModuleStartup::None => types.startup_func_type().into(),
1775            ModuleStartup::Always(_) => return,
1776            ModuleStartup::IfMemoriesNeedInit(ty) => ty,
1777        };
1778        self.module.startup = ModuleStartup::Always(ty);
1779    }
1780
1781    /// Helper function to ratchet the `startup` function for this module as
1782    /// `IfMemoriesNeedInit`.
1783    fn require_startup_func_if_memories_need_init(&mut self, types: &mut ModuleTypesBuilder) {
1784        let ty = match self.module.startup {
1785            ModuleStartup::None => types.startup_func_type().into(),
1786            ModuleStartup::Always(_) | ModuleStartup::IfMemoriesNeedInit(_) => return,
1787        };
1788        self.module.startup = ModuleStartup::IfMemoriesNeedInit(ty);
1789    }
1790}
1791
1792/// Returns whether evaluating any element of `elements` may trap.
1793fn elements_may_trap(elements: &TableSegmentElements) -> bool {
1794    match elements {
1795        TableSegmentElements::Functions(_) => false,
1796        TableSegmentElements::Expressions { exprs, .. } => exprs
1797            .iter()
1798            .any(|expr| expr.ops().iter().any(|op| op.may_trap())),
1799    }
1800}