Skip to main content

wasmtime_environ/
module.rs

1//! Data structures for representing decoded wasm modules.
2
3use crate::prelude::*;
4use crate::*;
5use core::ops::Range;
6use cranelift_entity::{EntityRef, packed_option::ReservedValue};
7use serde_derive::{Deserialize, Serialize};
8
9/// A WebAssembly linear memory initializer.
10#[derive(Clone, Debug)]
11pub struct MemoryInitializer<'a> {
12    /// The index of a linear memory to initialize.
13    pub memory_index: MemoryIndex,
14    /// The base offset to start this segment at.
15    pub offset: ConstExpr,
16    /// The range of the data to write within the linear memory.
17    ///
18    /// This range indexes into a separately stored data section which will be
19    /// provided with the compiled module's code as well.
20    pub data: &'a [u8],
21}
22
23/// The type of WebAssembly linear memory initialization to use for a module.
24#[derive(Debug, Serialize, Deserialize)]
25pub enum MemoryInitialization {
26    /// Memory initialization is segmented.
27    ///
28    /// Segmented initialization can be used for any module, but it is required
29    /// if:
30    ///
31    /// * A data segment referenced an imported memory.
32    /// * A data segment uses a global base.
33    ///
34    /// Segmented initialization is performed by processing the complete set of
35    /// data segments when the module is instantiated.
36    ///
37    /// This is the default memory initialization type.
38    Segmented,
39
40    /// Memory initialization is statically known and involves a single `memcpy`
41    /// or otherwise simply making the defined data visible.
42    ///
43    /// To be statically initialized everything must reference a defined memory
44    /// and all data segments have a statically known in-bounds base (no
45    /// globals).
46    ///
47    /// This form of memory initialization is a more optimized version of
48    /// `Segmented` where memory can be initialized with one of a few methods:
49    ///
50    /// * First it could be initialized with a single `memcpy` of data from the
51    ///   module to the linear memory.
52    /// * Otherwise techniques like `mmap` are also possible to make this data,
53    ///   which might reside in a compiled module on disk, available immediately
54    ///   in a linear memory's address space.
55    ///
56    /// To facilitate the latter of these techniques the `try_static_init`
57    /// function below, which creates this variant, takes a host page size
58    /// argument which can page-align everything to make mmap-ing possible.
59    Static {
60        /// The initialization contents for each linear memory.
61        ///
62        /// This array has, for each module's own linear memory, the contents
63        /// necessary to initialize it. If the memory has a `None` value then no
64        /// initialization is necessary (it's zero-filled). Otherwise with
65        /// `Some` the first element of the tuple is the offset in memory to
66        /// start the initialization and the `Range` is the range within the
67        /// final data section of the compiled module of bytes to copy into the
68        /// memory.
69        ///
70        /// The offset, range base, and range end are all guaranteed to be page
71        /// aligned to the page size passed in to `try_static_init`.
72        map: TryPrimaryMap<MemoryIndex, Option<(u64, RuntimeDataIndex)>>,
73    },
74}
75
76impl Default for MemoryInitialization {
77    fn default() -> Self {
78        Self::Segmented
79    }
80}
81
82impl MemoryInitialization {
83    /// Returns whether this initialization is of the form
84    /// `MemoryInitialization::Segmented`.
85    pub fn is_segmented(&self) -> bool {
86        match self {
87            MemoryInitialization::Segmented => true,
88            _ => false,
89        }
90    }
91}
92
93/// Table initialization data for all tables in the module.
94#[derive(Debug, Default, Serialize, Deserialize)]
95pub struct TableInitialization {
96    /// Initial values for tables defined within the module itself.
97    ///
98    /// This contains the initial values and initializers for tables defined
99    /// within a wasm, so excluding imported tables. This initializer can
100    /// represent null-initialized tables, element-initialized tables (e.g. with
101    /// the function-references proposal), or precomputed images of table
102    /// initialization. For example table initializers to a table that are all
103    /// in-bounds will get removed from `segment` and moved into
104    /// `initial_values` here.
105    pub initial_values: TryPrimaryMap<DefinedTableIndex, TableInitialValue>,
106
107    /// Element segments present in the initial wasm module which are executed
108    /// at instantiation time.
109    ///
110    /// These element segments are iterated over during instantiation to apply
111    /// any segments that weren't already moved into `initial_values` above.
112    pub segments: TryVec<TableSegment>,
113}
114
115/// Initial value for all elements in a table.
116#[derive(Debug, Serialize, Deserialize)]
117pub enum TableInitialValue {
118    /// Initialize each table element to null, optionally setting some elements
119    /// to non-null given the precomputed image.
120    Null,
121    /// An arbitrary const expression.
122    Expr(ConstExpr),
123}
124
125/// A WebAssembly table initializer segment.
126#[derive(Clone, Debug, Serialize, Deserialize)]
127pub struct TableSegment {
128    /// The index of a table to initialize.
129    pub table_index: TableIndex,
130    /// The base offset to start this segment at.
131    pub offset: ConstExpr,
132    /// The values to write into the table elements.
133    pub elements: TableSegmentElements,
134}
135
136/// Elements of a table segment, either a list of functions or list of arbitrary
137/// expressions.
138#[derive(Clone, Debug, Serialize, Deserialize)]
139pub enum TableSegmentElements {
140    /// A sequential list of functions where `FuncIndex::reserved_value()`
141    /// indicates a null function.
142    Functions(
143        #[serde(deserialize_with = "crate::types::deserialize_boxed_slice")] Box<[FuncIndex]>,
144    ),
145    /// Arbitrary expressions, aka either functions, null or a load of a global.
146    Expressions {
147        /// The type of each element in `exprs`.
148        ty: WasmRefType,
149        /// The const expressions for this segment's elements.
150        #[serde(deserialize_with = "crate::types::deserialize_boxed_slice")]
151        exprs: Box<[ConstExpr]>,
152    },
153}
154
155impl TableSegmentElements {
156    /// Returns the type of this segment.
157    pub fn ty(&self) -> WasmRefType {
158        match self {
159            Self::Functions(_) => WasmRefType::FUNCREF,
160            Self::Expressions { ty, .. } => *ty,
161        }
162    }
163
164    /// Returns the number of elements in this segment.
165    pub fn len(&self) -> u64 {
166        match self {
167            Self::Functions(s) => u64::try_from(s.len()).unwrap(),
168            Self::Expressions { exprs, .. } => u64::try_from(exprs.len()).unwrap(),
169        }
170    }
171}
172
173/// A translated WebAssembly module, excluding the function bodies and
174/// memory initializers.
175#[derive(Debug, Serialize, Deserialize)]
176pub struct Module {
177    /// This module's index.
178    pub module_index: StaticModuleIndex,
179
180    /// A pool of strings used in this module.
181    pub strings: StringPool,
182
183    /// The name of this wasm module, often found in the wasm file.
184    pub name: Option<Atom>,
185
186    /// All import records, in the order they are declared in the module.
187    pub initializers: TryVec<Initializer>,
188
189    /// Exported entities.
190    pub exports: TryIndexMap<Atom, EntityIndex>,
191
192    /// Whether or not this module has a start function,
193    pub startup: ModuleStartup,
194
195    /// Precompute per-table static images, if applicable.
196    ///
197    /// This map tracks, for each defined table in this module, the initial
198    /// precomputed contents of the table. This is only applicable for funcref
199    /// tables and the `TryVec` here uses `FuncIndex::reserved_value()` for null
200    /// entries. This structure is filled in if table initialization is detected
201    /// to be infallible as part of [`ModuleTranslation::finalize_table_init`].
202    pub table_initialization: TryPrimaryMap<DefinedTableIndex, TryVec<FuncIndex>>,
203
204    /// WebAssembly linear memory initializer.
205    ///
206    /// This will track how memory is initialized, either exclusively via
207    /// segments or if some memories can be initialized with static images. This
208    /// is computed during [`ModuleTranslation::finalize_memory_init`].
209    pub memory_initialization: MemoryInitialization,
210
211    /// WebAssembly passive elements.
212    ///
213    /// This is a map of all passive element segments to their type and the
214    /// initial size of the segment. Note that the contents of the segment are
215    /// initialized by compiled code.
216    pub passive_elements: TryPrimaryMap<PassiveElemIndex, (WasmRefType, u64)>,
217
218    /// Where runtime data segments are located in the module's image.
219    ///
220    /// Note that this does not directly correspond to either active or passive
221    /// data segments. Those are massaged during
222    /// [`ModuleTranslation::finalize_memory_init`] into the form used here.
223    pub runtime_data: TryPrimaryMap<RuntimeDataIndex, Range<u32>>,
224
225    /// Types declared in the wasm module.
226    pub types: TryPrimaryMap<TypeIndex, EngineOrModuleTypeIndex>,
227
228    /// Number of imported or aliased functions in the module.
229    pub num_imported_funcs: usize,
230
231    /// Number of imported or aliased tables in the module.
232    pub num_imported_tables: usize,
233
234    /// Number of imported or aliased memories in the module.
235    pub num_imported_memories: usize,
236
237    /// Number of imported or aliased globals in the module.
238    pub num_imported_globals: usize,
239
240    /// Number of imported or aliased tags in the module.
241    pub num_imported_tags: usize,
242
243    /// Does this module need a GC heap to run?
244    pub needs_gc_heap: bool,
245
246    /// Number of functions that "escape" from this module may need to have a
247    /// `VMFuncRef` constructed for them.
248    ///
249    /// This is also the number of functions in the `functions` array below with
250    /// an `func_ref` index (and is the maximum func_ref index).
251    pub num_escaped_funcs: usize,
252
253    /// Types of functions, imported and local.
254    pub functions: TryPrimaryMap<FuncIndex, FunctionType>,
255
256    /// WebAssembly tables.
257    pub tables: TryPrimaryMap<TableIndex, Table>,
258
259    /// WebAssembly linear memory plans.
260    pub memories: TryPrimaryMap<MemoryIndex, Memory>,
261
262    /// WebAssembly global variables.
263    pub globals: TryPrimaryMap<GlobalIndex, Global>,
264
265    /// "Simple" WebAssembly global initializers for locally-defined globals.
266    ///
267    /// This map does not track initialization of all globals in this module,
268    /// but only those considered "simple" which can be easily evaluated at
269    /// compile-time. For example an initialization expression of `i32.const N`
270    /// is considered simple. These globals are manually initialized in the
271    /// host.
272    ///
273    /// This is all in contrast to [`ModuleTranslation::global_initializers`]
274    /// which is processed in compiled code and initialized after the instance
275    /// has been created.
276    pub global_initializers: TryVec<(DefinedGlobalIndex, GlobalConstValue)>,
277
278    /// WebAssembly exception and control tags.
279    pub tags: TryPrimaryMap<TagIndex, Tag>,
280}
281
282/// Initialization routines for creating an instance, encompassing imports,
283/// modules, instances, aliases, etc.
284#[derive(Debug, Serialize, Deserialize)]
285pub enum Initializer {
286    /// An imported item is required to be provided.
287    Import {
288        /// Name of this import
289        name: Atom,
290        /// The field name projection of this import
291        field: Atom,
292        /// Where this import will be placed, which also has type information
293        /// about the import.
294        index: EntityIndex,
295    },
296}
297
298impl Module {
299    /// Allocates the module data structures.
300    pub fn new(module_index: StaticModuleIndex) -> Self {
301        Self {
302            module_index,
303            strings: Default::default(),
304            name: Default::default(),
305            initializers: Default::default(),
306            exports: Default::default(),
307            startup: ModuleStartup::None,
308            table_initialization: Default::default(),
309            memory_initialization: Default::default(),
310            passive_elements: Default::default(),
311            runtime_data: Default::default(),
312            types: Default::default(),
313            num_imported_funcs: Default::default(),
314            num_imported_tables: Default::default(),
315            num_imported_memories: Default::default(),
316            num_imported_globals: Default::default(),
317            num_imported_tags: Default::default(),
318            needs_gc_heap: Default::default(),
319            num_escaped_funcs: Default::default(),
320            functions: Default::default(),
321            tables: Default::default(),
322            memories: Default::default(),
323            globals: Default::default(),
324            global_initializers: Default::default(),
325            tags: Default::default(),
326        }
327    }
328
329    /// Convert a `DefinedFuncIndex` into a `FuncIndex`.
330    #[inline]
331    pub fn func_index(&self, defined_func: DefinedFuncIndex) -> FuncIndex {
332        FuncIndex::new(self.num_imported_funcs + defined_func.index())
333    }
334
335    /// Convert a `FuncIndex` into a `DefinedFuncIndex`. Returns None if the
336    /// index is an imported function.
337    #[inline]
338    pub fn defined_func_index(&self, func: FuncIndex) -> Option<DefinedFuncIndex> {
339        if func.index() < self.num_imported_funcs {
340            None
341        } else {
342            Some(DefinedFuncIndex::new(
343                func.index() - self.num_imported_funcs,
344            ))
345        }
346    }
347
348    /// Test whether the given function index is for an imported function.
349    #[inline]
350    pub fn is_imported_function(&self, index: FuncIndex) -> bool {
351        index.index() < self.num_imported_funcs
352    }
353
354    /// Convert a `DefinedTableIndex` into a `TableIndex`.
355    #[inline]
356    pub fn table_index(&self, defined_table: DefinedTableIndex) -> TableIndex {
357        TableIndex::new(self.num_imported_tables + defined_table.index())
358    }
359
360    /// Convert a `TableIndex` into a `DefinedTableIndex`. Returns None if the
361    /// index is an imported table.
362    #[inline]
363    pub fn defined_table_index(&self, table: TableIndex) -> Option<DefinedTableIndex> {
364        if table.index() < self.num_imported_tables {
365            None
366        } else {
367            Some(DefinedTableIndex::new(
368                table.index() - self.num_imported_tables,
369            ))
370        }
371    }
372
373    /// Test whether the given table index is for an exported table.
374    #[inline]
375    pub fn is_exported_table(&self, index: TableIndex) -> bool {
376        self.exports.values().any(|entity| *entity == index.into())
377    }
378
379    /// Test whether the given table index is for an imported table.
380    #[inline]
381    pub fn is_imported_table(&self, index: TableIndex) -> bool {
382        index.index() < self.num_imported_tables
383    }
384
385    /// Convert a `DefinedMemoryIndex` into a `MemoryIndex`.
386    #[inline]
387    pub fn memory_index(&self, defined_memory: DefinedMemoryIndex) -> MemoryIndex {
388        MemoryIndex::new(self.num_imported_memories + defined_memory.index())
389    }
390
391    /// Convert a `MemoryIndex` into a `DefinedMemoryIndex`. Returns None if the
392    /// index is an imported memory.
393    #[inline]
394    pub fn defined_memory_index(&self, memory: MemoryIndex) -> Option<DefinedMemoryIndex> {
395        if memory.index() < self.num_imported_memories {
396            None
397        } else {
398            Some(DefinedMemoryIndex::new(
399                memory.index() - self.num_imported_memories,
400            ))
401        }
402    }
403
404    /// Convert a `DefinedMemoryIndex` into an `OwnedMemoryIndex`. Returns None
405    /// if the index is an imported memory.
406    #[inline]
407    pub fn owned_memory_index(&self, memory: DefinedMemoryIndex) -> OwnedMemoryIndex {
408        assert!(
409            memory.index() < self.memories.len(),
410            "non-shared memory must have an owned index"
411        );
412
413        // Once we know that the memory index is not greater than the number of
414        // plans, we can iterate through the plans up to the memory index and
415        // count how many are not shared (i.e., owned).
416        let owned_memory_index = self
417            .memories
418            .iter()
419            .skip(self.num_imported_memories)
420            .take(memory.index())
421            .filter(|(_, mp)| !mp.shared)
422            .count();
423        OwnedMemoryIndex::new(owned_memory_index)
424    }
425
426    /// Test whether the given memory index is for an exported memory.
427    #[inline]
428    pub fn is_exported_memory(&self, index: MemoryIndex) -> bool {
429        self.exports.values().any(|entity| *entity == index.into())
430    }
431
432    /// Test whether the given memory index is for an imported memory.
433    #[inline]
434    pub fn is_imported_memory(&self, index: MemoryIndex) -> bool {
435        index.index() < self.num_imported_memories
436    }
437
438    /// Convert a `DefinedGlobalIndex` into a `GlobalIndex`.
439    #[inline]
440    pub fn global_index(&self, defined_global: DefinedGlobalIndex) -> GlobalIndex {
441        GlobalIndex::new(self.num_imported_globals + defined_global.index())
442    }
443
444    /// Convert a `GlobalIndex` into a `DefinedGlobalIndex`. Returns None if the
445    /// index is an imported global.
446    #[inline]
447    pub fn defined_global_index(&self, global: GlobalIndex) -> Option<DefinedGlobalIndex> {
448        if global.index() < self.num_imported_globals {
449            None
450        } else {
451            Some(DefinedGlobalIndex::new(
452                global.index() - self.num_imported_globals,
453            ))
454        }
455    }
456
457    /// Test whether the given global index is for an exported global.
458    #[inline]
459    pub fn is_exported_global(&self, index: GlobalIndex) -> bool {
460        self.exports.values().any(|entity| *entity == index.into())
461    }
462
463    /// Test whether the given global index is for an imported global.
464    #[inline]
465    pub fn is_imported_global(&self, index: GlobalIndex) -> bool {
466        index.index() < self.num_imported_globals
467    }
468
469    /// Test whether the given tag index is for an imported tag.
470    #[inline]
471    pub fn is_imported_tag(&self, index: TagIndex) -> bool {
472        index.index() < self.num_imported_tags
473    }
474
475    /// Convert a `DefinedTagIndex` into a `TagIndex`.
476    #[inline]
477    pub fn tag_index(&self, defined_tag: DefinedTagIndex) -> TagIndex {
478        TagIndex::new(self.num_imported_tags + defined_tag.index())
479    }
480
481    /// Convert a `TagIndex` into a `DefinedTagIndex`. Returns None if the
482    /// index is an imported tag.
483    #[inline]
484    pub fn defined_tag_index(&self, tag: TagIndex) -> Option<DefinedTagIndex> {
485        if tag.index() < self.num_imported_tags {
486            None
487        } else {
488            Some(DefinedTagIndex::new(tag.index() - self.num_imported_tags))
489        }
490    }
491
492    /// Returns an iterator of all the imports in this module, along with their
493    /// module name, field name, and type that's being imported.
494    pub fn imports(&self) -> impl ExactSizeIterator<Item = (&str, &str, EntityType)> {
495        let pool = &self.strings;
496        self.initializers.iter().map(move |i| match i {
497            Initializer::Import { name, field, index } => {
498                (&pool[name], &pool[field], self.type_of(*index))
499            }
500        })
501    }
502
503    /// Get this module's `i`th import.
504    pub fn import(&self, i: usize) -> Option<(&str, &str, EntityType)> {
505        match self.initializers.get(i)? {
506            Initializer::Import { name, field, index } => Some((
507                &self.strings[name],
508                &self.strings[field],
509                self.type_of(*index),
510            )),
511        }
512    }
513
514    /// Get the entity index for this module's `i`th import.
515    pub fn import_index(&self, i: usize) -> Option<EntityIndex> {
516        match self.initializers.get(i)? {
517            Initializer::Import { index, .. } => Some(*index),
518        }
519    }
520
521    /// Test whether the given entity index refers to one of this module's
522    /// imports, rather than to something it defines itself.
523    pub fn is_imported(&self, entity: EntityIndex) -> bool {
524        match entity {
525            EntityIndex::Function(i) => self.is_imported_function(i),
526            EntityIndex::Table(i) => self.is_imported_table(i),
527            EntityIndex::Memory(i) => self.is_imported_memory(i),
528            EntityIndex::Global(i) => self.is_imported_global(i),
529            EntityIndex::Tag(i) => self.is_imported_tag(i),
530        }
531    }
532
533    /// Get the position of the import that defines the given entity, suitable
534    /// for indexing an instantiation's argument list.
535    ///
536    /// Returns `None` when this module defines the entity itself, rather than
537    /// importing it.
538    ///
539    /// Note that this has to scan the initializers: imports of different kinds
540    /// are interleaved in declaration order, so an import's position is not
541    /// recoverable from the `num_imported_*` counts alone.
542    pub fn import_position(&self, entity: EntityIndex) -> Option<usize> {
543        if !self.is_imported(entity) {
544            return None;
545        }
546        self.initializers.iter().position(|i| match i {
547            Initializer::Import { index, .. } => *index == entity,
548        })
549    }
550
551    /// Returns the type of an item based on its index
552    pub fn type_of(&self, index: EntityIndex) -> EntityType {
553        match index {
554            EntityIndex::Global(i) => EntityType::Global(self.globals[i]),
555            EntityIndex::Table(i) => EntityType::Table(self.tables[i]),
556            EntityIndex::Memory(i) => EntityType::Memory(self.memories[i]),
557            EntityIndex::Function(i) => EntityType::Function(self.functions[i].signature),
558            EntityIndex::Tag(i) => EntityType::Tag(self.tags[i]),
559        }
560    }
561
562    /// Appends a new tag to this module with the given type information.
563    pub fn push_tag(
564        &mut self,
565        signature: impl Into<EngineOrModuleTypeIndex>,
566        exception: impl Into<EngineOrModuleTypeIndex>,
567    ) -> TagIndex {
568        let signature = signature.into();
569        let exception = exception.into();
570        self.tags
571            .push(Tag {
572                signature,
573                exception,
574            })
575            .panic_on_oom()
576    }
577
578    /// Appends a new function to this module with the given type information,
579    /// used for functions that either don't escape or aren't certain whether
580    /// they escape yet.
581    pub fn push_function(&mut self, signature: impl Into<EngineOrModuleTypeIndex>) -> FuncIndex {
582        let signature = signature.into();
583        self.functions
584            .push(FunctionType {
585                signature,
586                func_ref: FuncRefIndex::reserved_value(),
587            })
588            .panic_on_oom()
589    }
590
591    /// Returns an iterator over all of the defined function indices in this
592    /// module.
593    pub fn defined_func_indices(&self) -> impl ExactSizeIterator<Item = DefinedFuncIndex> + use<> {
594        (0..self.functions.len() - self.num_imported_funcs).map(|i| DefinedFuncIndex::new(i))
595    }
596
597    /// Returns the number of functions defined by this module itself: all
598    /// functions minus imported functions.
599    pub fn num_defined_funcs(&self) -> usize {
600        self.functions.len() - self.num_imported_funcs
601    }
602
603    /// Returns the number of tables defined by this module itself: all tables
604    /// minus imported tables.
605    pub fn num_defined_tables(&self) -> usize {
606        self.tables.len() - self.num_imported_tables
607    }
608
609    /// Returns the number of memories defined by this module itself: all
610    /// memories minus imported memories.
611    pub fn num_defined_memories(&self) -> usize {
612        self.memories.len() - self.num_imported_memories
613    }
614
615    /// Returns the number of globals defined by this module itself: all
616    /// globals minus imported globals.
617    pub fn num_defined_globals(&self) -> usize {
618        self.globals.len() - self.num_imported_globals
619    }
620
621    /// Returns the number of tags defined by this module itself: all tags
622    /// minus imported tags.
623    pub fn num_defined_tags(&self) -> usize {
624        self.tags.len() - self.num_imported_tags
625    }
626
627    /// Tests whether `index` is valid for this module.
628    pub fn is_valid(&self, index: EntityIndex) -> bool {
629        match index {
630            EntityIndex::Function(i) => self.functions.is_valid(i),
631            EntityIndex::Table(i) => self.tables.is_valid(i),
632            EntityIndex::Memory(i) => self.memories.is_valid(i),
633            EntityIndex::Global(i) => self.globals.is_valid(i),
634            EntityIndex::Tag(i) => self.tags.is_valid(i),
635        }
636    }
637}
638
639impl TypeTrace for Module {
640    fn trace<F, E>(&self, func: &mut F) -> Result<(), E>
641    where
642        F: FnMut(EngineOrModuleTypeIndex) -> Result<(), E>,
643    {
644        // NB: Do not `..` elide unmodified fields so that we get compile errors
645        // when adding new fields that might need re-canonicalization.
646        let Self {
647            module_index: _,
648            strings: _,
649            name: _,
650            initializers: _,
651            exports: _,
652            startup,
653            table_initialization: _,
654            memory_initialization: _,
655            passive_elements: _,
656            runtime_data: _,
657            types,
658            num_imported_funcs: _,
659            num_imported_tables: _,
660            num_imported_memories: _,
661            num_imported_globals: _,
662            num_imported_tags: _,
663            num_escaped_funcs: _,
664            needs_gc_heap: _,
665            functions,
666            tables,
667            memories: _,
668            globals,
669            global_initializers: _,
670            tags,
671        } = self;
672
673        for t in types.values().copied() {
674            func(t)?;
675        }
676        for f in functions.values() {
677            f.trace(func)?;
678        }
679        for t in tables.values() {
680            t.trace(func)?;
681        }
682        for g in globals.values() {
683            g.trace(func)?;
684        }
685        for t in tags.values() {
686            t.trace(func)?;
687        }
688        startup.trace(func)?;
689        Ok(())
690    }
691
692    fn trace_mut<F, E>(&mut self, func: &mut F) -> Result<(), E>
693    where
694        F: FnMut(&mut EngineOrModuleTypeIndex) -> Result<(), E>,
695    {
696        // NB: Do not `..` elide unmodified fields so that we get compile errors
697        // when adding new fields that might need re-canonicalization.
698        let Self {
699            module_index: _,
700            strings: _,
701            name: _,
702            initializers: _,
703            exports: _,
704            startup,
705            table_initialization: _,
706            memory_initialization: _,
707            passive_elements: _,
708            runtime_data: _,
709            types,
710            num_imported_funcs: _,
711            num_imported_tables: _,
712            num_imported_memories: _,
713            num_imported_globals: _,
714            num_imported_tags: _,
715            num_escaped_funcs: _,
716            needs_gc_heap: _,
717            functions,
718            tables,
719            memories: _,
720            globals,
721            global_initializers: _,
722            tags,
723        } = self;
724
725        for t in types.values_mut() {
726            func(t)?;
727        }
728        for f in functions.values_mut() {
729            f.trace_mut(func)?;
730        }
731        for t in tables.values_mut() {
732            t.trace_mut(func)?;
733        }
734        for g in globals.values_mut() {
735            g.trace_mut(func)?;
736        }
737        for t in tags.values_mut() {
738            t.trace_mut(func)?;
739        }
740        startup.trace_mut(func)?;
741        Ok(())
742    }
743}
744
745impl TypeTrace for ModuleStartup {
746    fn trace<F, E>(&self, func: &mut F) -> Result<(), E>
747    where
748        F: FnMut(EngineOrModuleTypeIndex) -> Result<(), E>,
749    {
750        match self {
751            ModuleStartup::None => Ok(()),
752            ModuleStartup::Always(t) | ModuleStartup::IfMemoriesNeedInit(t) => func(*t),
753        }
754    }
755
756    fn trace_mut<F, E>(&mut self, func: &mut F) -> Result<(), E>
757    where
758        F: FnMut(&mut EngineOrModuleTypeIndex) -> Result<(), E>,
759    {
760        match self {
761            ModuleStartup::None => Ok(()),
762            ModuleStartup::Always(t) | ModuleStartup::IfMemoriesNeedInit(t) => func(t),
763        }
764    }
765}
766
767/// Type information about functions in a wasm module.
768#[derive(Debug, Serialize, Deserialize)]
769pub struct FunctionType {
770    /// The type of this function, indexed into the module-wide type tables for
771    /// a module compilation.
772    pub signature: EngineOrModuleTypeIndex,
773    /// The index into the funcref table, if present. Note that this is
774    /// `reserved_value()` if the function does not escape from a module.
775    pub func_ref: FuncRefIndex,
776}
777
778impl TypeTrace for FunctionType {
779    fn trace<F, E>(&self, func: &mut F) -> Result<(), E>
780    where
781        F: FnMut(EngineOrModuleTypeIndex) -> Result<(), E>,
782    {
783        func(self.signature)
784    }
785
786    fn trace_mut<F, E>(&mut self, func: &mut F) -> Result<(), E>
787    where
788        F: FnMut(&mut EngineOrModuleTypeIndex) -> Result<(), E>,
789    {
790        func(&mut self.signature)
791    }
792}
793
794impl FunctionType {
795    /// Returns whether this function's type is one that "escapes" the current
796    /// module, meaning that the function is exported, used in `ref.func`, used
797    /// in a table, etc.
798    pub fn is_escaping(&self) -> bool {
799        !self.func_ref.is_reserved_value()
800    }
801}
802
803/// Index into the funcref table within a VMContext for a function.
804#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize)]
805pub struct FuncRefIndex(u32);
806cranelift_entity::entity_impl!(FuncRefIndex);
807
808/// Different means of startup for a wasm module.
809#[derive(Debug, Serialize, Deserialize)]
810pub enum ModuleStartup {
811    /// No startup is necessary.
812    None,
813
814    /// Startup is always required, for example to apply active table segments.
815    ///
816    /// The type of the startup function, of wasm signature `[] -> []`, is
817    /// provided here.
818    Always(EngineOrModuleTypeIndex),
819
820    /// Startup is only required if some linear memory within this module, at
821    /// runtime, says `needs_init() == true`.
822    ///
823    /// This special mode of startup indicates that the startup function has no
824    /// purpose other than to initialize the initial contents of
825    /// `MemoryInitialization::Static` linear memories. In this situation if all
826    /// memories say `needs_init() == false` then the startup function won't
827    /// actually do anything meaning that it can be optimized slightly by
828    /// skipping it entirely.
829    IfMemoriesNeedInit(EngineOrModuleTypeIndex),
830}
831
832impl ModuleStartup {
833    /// Returns if this is `ModuleStartup::None`.
834    pub fn is_none(&self) -> bool {
835        matches!(self, Self::None)
836    }
837}