Skip to main content

wasmtime/runtime/
module.rs

1use crate::prelude::*;
2#[cfg(feature = "std")]
3use crate::runtime::vm::open_file_for_mmap;
4use crate::runtime::vm::{CompiledModuleId, MmapVec, ModuleMemoryImages, VMWasmCallFunction};
5use crate::sync::OnceLock;
6use crate::{
7    Engine,
8    code::EngineCode,
9    code_memory::CodeMemory,
10    instantiate::CompiledModule,
11    resources::ResourcesRequired,
12    types::{ExportType, ExternType, ImportType},
13};
14use alloc::sync::Arc;
15use core::fmt;
16use core::ops::Range;
17use core::ptr::NonNull;
18#[cfg(feature = "std")]
19use std::{fs::File, path::Path};
20use wasmparser::{Parser, ValidPayload, Validator};
21use wasmtime_environ::{
22    CompiledFunctionsTable, CompiledModuleInfo, EntityIndex, FuncKey, HostPtr, ModuleTypes,
23    ObjectKind, StaticModuleIndex, TypeTrace, VMOffsets, VMSharedTypeIndex, WasmChecksum,
24};
25mod registry;
26
27pub use registry::*;
28
29/// A compiled WebAssembly module, ready to be instantiated.
30///
31/// A `Module` is a compiled in-memory representation of an input WebAssembly
32/// binary. A `Module` is then used to create an [`Instance`](crate::Instance)
33/// through an instantiation process. You cannot call functions or fetch
34/// globals, for example, on a `Module` because it's purely a code
35/// representation. Instead you'll need to create an
36/// [`Instance`](crate::Instance) to interact with the wasm module.
37///
38/// A `Module` can be created by compiling WebAssembly code through APIs such as
39/// [`Module::new`]. This would be a JIT-style use case where code is compiled
40/// just before it's used. Alternatively a `Module` can be compiled in one
41/// process and [`Module::serialize`] can be used to save it to storage. A later
42/// call to [`Module::deserialize`] will quickly load the module to execute and
43/// does not need to compile any code, representing a more AOT-style use case.
44///
45/// Currently a `Module` does not implement any form of tiering or dynamic
46/// optimization of compiled code. Creation of a `Module` via [`Module::new`] or
47/// related APIs will perform the entire compilation step synchronously. When
48/// finished no further compilation will happen at runtime or later during
49/// execution of WebAssembly instances for example.
50///
51/// Compilation of WebAssembly by default goes through Cranelift and is
52/// recommended to be done once-per-module. The same WebAssembly binary need not
53/// be compiled multiple times and can instead used an embedder-cached result of
54/// the first call.
55///
56/// `Module` is thread-safe and safe to share across threads.
57///
58/// ## Modules and `Clone`
59///
60/// Using `clone` on a `Module` is a cheap operation. It will not create an
61/// entirely new module, but rather just a new reference to the existing module.
62/// In other words it's a shallow copy, not a deep copy.
63///
64/// ## Examples
65///
66/// There are a number of ways you can create a `Module`, for example pulling
67/// the bytes from a number of locations. One example is loading a module from
68/// the filesystem:
69///
70/// ```no_run
71/// # use wasmtime::*;
72/// # fn main() -> Result<()> {
73/// let engine = Engine::default();
74/// let module = Module::from_file(&engine, "path/to/foo.wasm")?;
75/// # Ok(())
76/// # }
77/// ```
78///
79/// You can also load the wasm text format if more convenient too:
80///
81/// ```no_run
82/// # use wasmtime::*;
83/// # fn main() -> Result<()> {
84/// let engine = Engine::default();
85/// // Now we're using the WebAssembly text extension: `.wat`!
86/// let module = Module::from_file(&engine, "path/to/foo.wat")?;
87/// # Ok(())
88/// # }
89/// ```
90///
91/// And if you've already got the bytes in-memory you can use the
92/// [`Module::new`] constructor:
93///
94/// ```no_run
95/// # use wasmtime::*;
96/// # fn main() -> Result<()> {
97/// let engine = Engine::default();
98/// # let wasm_bytes: Vec<u8> = Vec::new();
99/// let module = Module::new(&engine, &wasm_bytes)?;
100///
101/// // It also works with the text format!
102/// let module = Module::new(&engine, "(module (func))")?;
103/// # Ok(())
104/// # }
105/// ```
106///
107/// Serializing and deserializing a module looks like:
108///
109/// ```no_run
110/// # use wasmtime::*;
111/// # fn main() -> Result<()> {
112/// let engine = Engine::default();
113/// # let wasm_bytes: Vec<u8> = Vec::new();
114/// let module = Module::new(&engine, &wasm_bytes)?;
115/// let module_bytes = module.serialize()?;
116///
117/// // ... can save `module_bytes` to disk or other storage ...
118///
119/// // recreate the module from the serialized bytes. For the `unsafe` bits
120/// // see the documentation of `deserialize`.
121/// let module = unsafe { Module::deserialize(&engine, &module_bytes)? };
122/// # Ok(())
123/// # }
124/// ```
125///
126/// [`Config`]: crate::Config
127#[derive(Clone)]
128pub struct Module {
129    inner: Arc<ModuleInner>,
130}
131
132// SAFETY: restating what rustc already infers to reduce work on rustc.
133//
134// See comments on the similar impls for `Engine` for more details.
135unsafe impl Send for Module {}
136unsafe impl Sync for Module {}
137
138fn _assert_send_sync(e: &Module) {
139    fn _assert<T: Send + Sync>(_: &T) {}
140    let Module { inner } = e;
141    _assert(e);
142    _assert(inner);
143}
144
145struct ModuleInner {
146    engine: Engine,
147    /// The compiled artifacts for this module that will be instantiated and
148    /// executed.
149    module: CompiledModule,
150
151    /// Runtime information such as the underlying mmap, type information, etc.
152    ///
153    /// Note that this `Arc` is used to share information between compiled
154    /// modules within a component. For bare core wasm modules created with
155    /// `Module::new`, for example, this is a uniquely owned `Arc`.
156    code: Arc<EngineCode>,
157
158    /// A set of initialization images for memories, if any.
159    ///
160    /// Note that this is behind a `OnceCell` to lazily create this image. On
161    /// Linux where `memfd_create` may be used to create the backing memory
162    /// image this is a pretty expensive operation, so by deferring it this
163    /// improves memory usage for modules that are created but may not ever be
164    /// instantiated.
165    memory_images: OnceLock<Option<ModuleMemoryImages>>,
166
167    /// Flag indicating whether this module can be serialized or not.
168    #[cfg(any(feature = "cranelift", feature = "winch"))]
169    serializable: bool,
170
171    /// Runtime offset information for `VMContext`.
172    offsets: VMOffsets<HostPtr>,
173
174    /// The checksum of the source binary from which this module was compiled.
175    checksum: WasmChecksum,
176}
177
178impl fmt::Debug for Module {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.debug_struct("Module")
181            .field("name", &self.name())
182            .finish_non_exhaustive()
183    }
184}
185
186impl fmt::Debug for ModuleInner {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_struct("ModuleInner")
189            .field("name", &self.module.module().name.as_ref())
190            .finish_non_exhaustive()
191    }
192}
193
194impl Module {
195    /// Creates a new WebAssembly `Module` from the given in-memory `bytes`.
196    ///
197    /// The `bytes` provided must be in one of the following formats:
198    ///
199    /// * A [binary-encoded][binary] WebAssembly module. This is always supported.
200    /// * A [text-encoded][text] instance of the WebAssembly text format.
201    ///   This is only supported when the `wat` feature of this crate is enabled.
202    ///   If this is supplied then the text format will be parsed before validation.
203    ///   Note that the `wat` feature is enabled by default.
204    ///
205    /// The data for the wasm module must be loaded in-memory if it's present
206    /// elsewhere, for example on disk. This requires that the entire binary is
207    /// loaded into memory all at once, this API does not support streaming
208    /// compilation of a module.
209    ///
210    /// The WebAssembly binary will be decoded and validated. It will also be
211    /// compiled according to the configuration of the provided `engine`.
212    ///
213    /// # Errors
214    ///
215    /// This function may fail and return an error. Errors may include
216    /// situations such as:
217    ///
218    /// * The binary provided could not be decoded because it's not a valid
219    ///   WebAssembly binary
220    /// * The WebAssembly binary may not validate (e.g. contains type errors)
221    /// * Implementation-specific limits were exceeded with a valid binary (for
222    ///   example too many locals)
223    /// * The wasm binary may use features that are not enabled in the
224    ///   configuration of `engine`
225    /// * If the `wat` feature is enabled and the input is text, then it may be
226    ///   rejected if it fails to parse.
227    ///
228    /// The error returned should contain full information about why module
229    /// creation failed if one is returned.
230    ///
231    /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
232    /// [text]: https://webassembly.github.io/spec/core/text/index.html
233    ///
234    /// # Examples
235    ///
236    /// The `new` function can be invoked with a in-memory array of bytes:
237    ///
238    /// ```no_run
239    /// # use wasmtime::*;
240    /// # fn main() -> Result<()> {
241    /// # let engine = Engine::default();
242    /// # let wasm_bytes: Vec<u8> = Vec::new();
243    /// let module = Module::new(&engine, &wasm_bytes)?;
244    /// # Ok(())
245    /// # }
246    /// ```
247    ///
248    /// Or you can also pass in a string to be parsed as the wasm text
249    /// format:
250    ///
251    /// ```
252    /// # use wasmtime::*;
253    /// # fn main() -> Result<()> {
254    /// # let engine = Engine::default();
255    /// let module = Module::new(&engine, "(module (func))")?;
256    /// # Ok(())
257    /// # }
258    /// ```
259    #[cfg(any(feature = "cranelift", feature = "winch"))]
260    pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module> {
261        crate::CodeBuilder::new(engine)
262            .wasm_binary_or_text(bytes.as_ref(), None)?
263            .compile_module()
264    }
265
266    /// Creates a new WebAssembly `Module` from the contents of the given
267    /// `file` on disk.
268    ///
269    /// This is a convenience function that will read the `file` provided and
270    /// pass the bytes to the [`Module::new`] function. For more information
271    /// see [`Module::new`]
272    ///
273    /// # Examples
274    ///
275    /// ```no_run
276    /// # use wasmtime::*;
277    /// # fn main() -> Result<()> {
278    /// let engine = Engine::default();
279    /// let module = Module::from_file(&engine, "./path/to/foo.wasm")?;
280    /// # Ok(())
281    /// # }
282    /// ```
283    ///
284    /// The `.wat` text format is also supported:
285    ///
286    /// ```no_run
287    /// # use wasmtime::*;
288    /// # fn main() -> Result<()> {
289    /// # let engine = Engine::default();
290    /// let module = Module::from_file(&engine, "./path/to/foo.wat")?;
291    /// # Ok(())
292    /// # }
293    /// ```
294    #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))]
295    pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module> {
296        crate::CodeBuilder::new(engine)
297            .wasm_binary_or_text_file(file.as_ref())?
298            .compile_module()
299    }
300
301    /// Creates a new WebAssembly `Module` from the given in-memory `binary`
302    /// data.
303    ///
304    /// This is similar to [`Module::new`] except that it requires that the
305    /// `binary` input is a WebAssembly binary, the text format is not supported
306    /// by this function. It's generally recommended to use [`Module::new`], but
307    /// if it's required to not support the text format this function can be
308    /// used instead.
309    ///
310    /// # Examples
311    ///
312    /// ```
313    /// # use wasmtime::*;
314    /// # fn main() -> Result<()> {
315    /// # let engine = Engine::default();
316    /// let wasm = b"\0asm\x01\0\0\0";
317    /// let module = Module::from_binary(&engine, wasm)?;
318    /// # Ok(())
319    /// # }
320    /// ```
321    ///
322    /// Note that the text format is **not** accepted by this function:
323    ///
324    /// ```
325    /// # use wasmtime::*;
326    /// # fn main() -> Result<()> {
327    /// # let engine = Engine::default();
328    /// assert!(Module::from_binary(&engine, b"(module)").is_err());
329    /// # Ok(())
330    /// # }
331    /// ```
332    #[cfg(any(feature = "cranelift", feature = "winch"))]
333    pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Module> {
334        crate::CodeBuilder::new(engine)
335            .wasm_binary(binary, None)?
336            .compile_module()
337    }
338
339    /// Creates a new WebAssembly `Module` from the contents of the given `file`
340    /// on disk, but with assumptions that the file is from a trusted source.
341    /// The file should be a binary- or text-format WebAssembly module, or a
342    /// precompiled artifact generated by the same version of Wasmtime.
343    ///
344    /// # Unsafety
345    ///
346    /// All of the reasons that [`deserialize`] is `unsafe` apply to this
347    /// function as well. Arbitrary data loaded from a file may trick Wasmtime
348    /// into arbitrary code execution since the contents of the file are not
349    /// validated to be a valid precompiled module.
350    ///
351    /// [`deserialize`]: Module::deserialize
352    ///
353    /// Additionally though this function is also `unsafe` because the file
354    /// referenced must remain unchanged and a valid precompiled module for the
355    /// entire lifetime of the [`Module`] returned. Any changes to the file on
356    /// disk may change future instantiations of the module to be incorrect.
357    /// This is because the file is mapped into memory and lazily loaded pages
358    /// reflect the current state of the file, not necessarily the original
359    /// state of the file.
360    #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))]
361    pub unsafe fn from_trusted_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module> {
362        let open_file = open_file_for_mmap(file.as_ref())?;
363        let mmap = crate::runtime::vm::MmapVec::from_file(open_file)?;
364        if &mmap[0..4] == b"\x7fELF" {
365            let code = engine.load_code(mmap, ObjectKind::Module)?;
366            return Module::from_parts(engine, code, None);
367        }
368
369        crate::CodeBuilder::new(engine)
370            .wasm_binary_or_text(&mmap[..], Some(file.as_ref()))?
371            .compile_module()
372    }
373
374    /// Deserializes an in-memory compiled module previously created with
375    /// [`Module::serialize`] or [`Engine::precompile_module`].
376    ///
377    /// This function will deserialize the binary blobs emitted by
378    /// [`Module::serialize`] and [`Engine::precompile_module`] back into an
379    /// in-memory [`Module`] that's ready to be instantiated.
380    ///
381    /// Note that the [`Module::deserialize_file`] method is more optimized than
382    /// this function, so if the serialized module is already present in a file
383    /// it's recommended to use that method instead.
384    ///
385    /// # Unsafety
386    ///
387    /// This function is marked as `unsafe` because if fed invalid input or used
388    /// improperly this could lead to memory safety vulnerabilities. This method
389    /// should not, for example, be exposed to arbitrary user input.
390    ///
391    /// The structure of the binary blob read here is only lightly validated
392    /// internally in `wasmtime`. This is intended to be an efficient
393    /// "rehydration" for a [`Module`] which has very few runtime checks beyond
394    /// deserialization. Arbitrary input could, for example, replace valid
395    /// compiled code with any other valid compiled code, meaning that this can
396    /// trivially be used to execute arbitrary code otherwise.
397    ///
398    /// For these reasons this function is `unsafe`. This function is only
399    /// designed to receive the previous input from [`Module::serialize`] and
400    /// [`Engine::precompile_module`]. If the exact output of those functions
401    /// (unmodified) is passed to this function then calls to this function can
402    /// be considered safe. It is the caller's responsibility to provide the
403    /// guarantee that only previously-serialized bytes are being passed in
404    /// here.
405    ///
406    /// Note that this function is designed to be safe receiving output from
407    /// *any* compiled version of `wasmtime` itself. This means that it is safe
408    /// to feed output from older versions of Wasmtime into this function, in
409    /// addition to newer versions of wasmtime (from the future!). These inputs
410    /// will deterministically and safely produce an `Err`. This function only
411    /// successfully accepts inputs from the same version of `wasmtime`, but the
412    /// safety guarantee only applies to externally-defined blobs of bytes, not
413    /// those defined by any version of wasmtime. (this means that if you cache
414    /// blobs across versions of wasmtime you can be safely guaranteed that
415    /// future versions of wasmtime will reject old cache entries).
416    ///
417    /// # Errors
418    ///
419    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
420    /// memory allocation fails. See the `OutOfMemory` type's documentation for
421    /// details on Wasmtime's out-of-memory handling.
422    pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module> {
423        let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Module)?;
424        Module::from_parts(engine, code, None)
425    }
426
427    /// In-place deserialization of an in-memory compiled module previously
428    /// created with [`Module::serialize`] or [`Engine::precompile_module`].
429    ///
430    /// See [`Self::deserialize`] for additional information; this method
431    /// works identically except that it will not create a copy of the provided
432    /// memory but will use it directly.
433    ///
434    /// # Unsafety
435    ///
436    /// All of the safety notes from [`Self::deserialize`] apply here as well
437    /// with the additional constraint that the code memory provide by `memory`
438    /// lives for as long as the module and is nevery externally modified for
439    /// the lifetime of the deserialized module.
440    pub unsafe fn deserialize_raw(engine: &Engine, memory: NonNull<[u8]>) -> Result<Module> {
441        // SAFETY: the contract required by `load_code_raw` is the same as this
442        // function.
443        let code = unsafe { engine.load_code_raw(memory, ObjectKind::Module)? };
444        Module::from_parts(engine, code, None)
445    }
446
447    /// Same as [`deserialize`], except that the contents of `path` are read to
448    /// deserialize into a [`Module`].
449    ///
450    /// This method is provided because it can be faster than [`deserialize`]
451    /// since the data doesn't need to be copied around, but rather the module
452    /// can be used directly from an mmap'd view of the file provided.
453    ///
454    /// [`deserialize`]: Module::deserialize
455    ///
456    /// # Unsafety
457    ///
458    /// All of the reasons that [`deserialize`] is `unsafe` applies to this
459    /// function as well. Arbitrary data loaded from a file may trick Wasmtime
460    /// into arbitrary code execution since the contents of the file are not
461    /// validated to be a valid precompiled module.
462    ///
463    /// Additionally though this function is also `unsafe` because the file
464    /// referenced must remain unchanged and a valid precompiled module for the
465    /// entire lifetime of the [`Module`] returned. Any changes to the file on
466    /// disk may change future instantiations of the module to be incorrect.
467    /// This is because the file is mapped into memory and lazily loaded pages
468    /// reflect the current state of the file, not necessarily the original
469    /// state of the file.
470    #[cfg(feature = "std")]
471    pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Module> {
472        let file = open_file_for_mmap(path.as_ref())?;
473        // SAFETY: the contract of `deserialize_open_file` is the samea s this
474        // function.
475        unsafe {
476            Self::deserialize_open_file(engine, file)
477                .with_context(|| format!("failed deserialization for: {}", path.as_ref().display()))
478        }
479    }
480
481    /// Same as [`deserialize_file`], except that it takes an open `File`
482    /// instead of a path.
483    ///
484    /// This method is provided because it can be used instead of
485    /// [`deserialize_file`] in situations where `wasmtime` is running with
486    /// limited file system permissions. In that case a process
487    /// with file system access can pass already opened files to `wasmtime`.
488    ///
489    /// [`deserialize_file`]: Module::deserialize_file
490    ///
491    /// Note that the corresponding will be mapped as private writeable
492    /// (copy-on-write) and executable. For `windows` this means the file needs
493    /// to be opened with at least `FILE_GENERIC_READ | FILE_GENERIC_EXECUTE`
494    /// [`access_mode`].
495    ///
496    /// [`access_mode`]: https://doc.rust-lang.org/std/os/windows/fs/trait.OpenOptionsExt.html#tymethod.access_mode
497    ///
498    /// # Unsafety
499    ///
500    /// All of the reasons that [`deserialize_file`] is `unsafe` applies to this
501    /// function as well.
502    #[cfg(feature = "std")]
503    pub unsafe fn deserialize_open_file(engine: &Engine, file: File) -> Result<Module> {
504        let code = engine.load_code_file(file, ObjectKind::Module)?;
505        Module::from_parts(engine, code, None)
506    }
507
508    /// Entrypoint for creating a `Module` for all above functions, both
509    /// of the AOT and jit-compiled categories.
510    ///
511    /// In all cases the compilation artifact, `code_memory`, is provided here.
512    /// The `info_and_types` argument is `None` when a module is being
513    /// deserialized from a precompiled artifact or it's `Some` if it was just
514    /// compiled and the values are already available.
515    pub(crate) fn from_parts(
516        engine: &Engine,
517        code_memory: Arc<CodeMemory>,
518        info_and_types: Option<(CompiledModuleInfo, CompiledFunctionsTable, ModuleTypes)>,
519    ) -> Result<Self> {
520        // Acquire this module's metadata and type information, deserializing
521        // it from the provided artifact if it wasn't otherwise provided
522        // already.
523        let (mut info, index, mut types) = match info_and_types {
524            Some((info, index, types)) => (info, index, types),
525            None => postcard::from_bytes(code_memory.wasmtime_info())?,
526        };
527
528        // Register function type signatures into the engine for the lifetime
529        // of the `Module` that will be returned. This notably also builds up
530        // maps for trampolines to be used for this module when inserted into
531        // stores.
532        //
533        // Note that the unsafety here should be ok since the `trampolines`
534        // field should only point to valid trampoline function pointers
535        // within the text section.
536        let signatures = engine
537            .register_and_canonicalize_types(&mut types, core::iter::once(&mut info.module))?;
538
539        // Package up all our data into an `EngineCode` and delegate to the final
540        // step of module compilation.
541        let code = try_new::<Arc<_>>(EngineCode::new(code_memory, signatures, types.into())?)?;
542        let index = try_new::<Arc<_>>(index)?;
543        Module::from_parts_raw(engine, code, info, index, true)
544    }
545
546    pub(crate) fn from_parts_raw(
547        engine: &Engine,
548        code: Arc<EngineCode>,
549        info: CompiledModuleInfo,
550        index: Arc<CompiledFunctionsTable>,
551        serializable: bool,
552    ) -> Result<Self> {
553        let checksum = info.checksum;
554        let module = CompiledModule::from_artifacts(code.clone(), info, index, engine.profiler())?;
555
556        // Validate the module can be used with the current instance allocator.
557        let offsets = VMOffsets::new(HostPtr, module.module());
558        engine
559            .allocator()
560            .validate_module(module.module(), &offsets)?;
561
562        let _ = serializable;
563
564        Ok(Self {
565            inner: try_new::<Arc<_>>(ModuleInner {
566                engine: engine.clone(),
567                code,
568                memory_images: OnceLock::new(),
569                module,
570                #[cfg(any(feature = "cranelift", feature = "winch"))]
571                serializable,
572                offsets,
573                checksum,
574            })?,
575        })
576    }
577
578    /// Validates `binary` input data as a WebAssembly binary given the
579    /// configuration in `engine`.
580    ///
581    /// This function will perform a speedy validation of the `binary` input
582    /// WebAssembly module (which is in [binary form][binary], the text format
583    /// is not accepted by this function) and return either `Ok` or `Err`
584    /// depending on the results of validation. The `engine` argument indicates
585    /// configuration for WebAssembly features, for example, which are used to
586    /// indicate what should be valid and what shouldn't be.
587    ///
588    /// Validation automatically happens as part of [`Module::new`].
589    ///
590    /// # Errors
591    ///
592    /// If validation fails for any reason (type check error, usage of a feature
593    /// that wasn't enabled, etc) then an error with a description of the
594    /// validation issue will be returned.
595    ///
596    /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
597    pub fn validate(engine: &Engine, binary: &[u8]) -> Result<()> {
598        let mut validator = Validator::new_with_features(engine.features());
599
600        let mut functions = Vec::new();
601        for payload in Parser::new(0).parse_all(binary) {
602            let payload = payload?;
603            if let ValidPayload::Func(a, b) = validator.payload(&payload)? {
604                functions.push((a, b));
605            }
606            if let wasmparser::Payload::Version { encoding, .. } = &payload {
607                if let wasmparser::Encoding::Component = encoding {
608                    bail!("component passed to module validation");
609                }
610            }
611        }
612
613        engine.run_maybe_parallel(functions, |(validator, body)| {
614            // FIXME: it would be best here to use a rayon-specific parallel
615            // iterator that maintains state-per-thread to share the function
616            // validator allocations (`Default::default` here) across multiple
617            // functions.
618            validator.into_validator(Default::default()).validate(&body)
619        })?;
620        Ok(())
621    }
622
623    /// Serializes this module to a vector of bytes.
624    ///
625    /// This function is similar to the [`Engine::precompile_module`] method
626    /// where it produces an artifact of Wasmtime which is suitable to later
627    /// pass into [`Module::deserialize`]. If a module is never instantiated
628    /// then it's recommended to use [`Engine::precompile_module`] instead of
629    /// this method, but if a module is both instantiated and serialized then
630    /// this method can be useful to get the serialized version without
631    /// compiling twice.
632    #[cfg(any(feature = "cranelift", feature = "winch"))]
633    pub fn serialize(&self) -> Result<Vec<u8>> {
634        // The current representation of compiled modules within a compiled
635        // component means that it cannot be serialized. The mmap returned here
636        // is the mmap for the entire component and while it contains all
637        // necessary data to deserialize this particular module it's all
638        // embedded within component-specific information.
639        //
640        // It's not the hardest thing in the world to support this but it's
641        // expected that there's not much of a use case at this time. In theory
642        // all that needs to be done is to edit the `.wasmtime.info` section
643        // to contains this module's metadata instead of the metadata for the
644        // whole component. The metadata itself is fairly trivially
645        // recreateable here it's more that there's no easy one-off API for
646        // editing the sections of an ELF object to use here.
647        //
648        // Overall for now this simply always returns an error in this
649        // situation. If you're reading this and feel that the situation should
650        // be different please feel free to open an issue.
651        if !self.inner.serializable {
652            bail!("cannot serialize a module exported from a component");
653        }
654        Ok(self.engine_code().image().to_vec())
655    }
656
657    pub(crate) fn compiled_module(&self) -> &CompiledModule {
658        &self.inner.module
659    }
660
661    pub(crate) fn engine_code(&self) -> &Arc<EngineCode> {
662        &self.inner.code
663    }
664
665    pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
666        self.compiled_module().module()
667    }
668
669    pub(crate) fn types(&self) -> &ModuleTypes {
670        self.inner.code.module_types()
671    }
672
673    #[cfg(any(
674        feature = "gc-drc",
675        feature = "gc-copying",
676        feature = "component-model"
677    ))]
678    pub(crate) fn signatures(&self) -> &crate::type_registry::TypeCollection {
679        self.inner.code.signatures()
680    }
681
682    /// Returns identifier/name that this [`Module`] has. This name
683    /// is used in traps/backtrace details.
684    ///
685    /// Note that most LLVM/clang/Rust-produced modules do not have a name
686    /// associated with them, but other wasm tooling can be used to inject or
687    /// add a name.
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// # use wasmtime::*;
693    /// # fn main() -> Result<()> {
694    /// # let engine = Engine::default();
695    /// let module = Module::new(&engine, "(module $foo)")?;
696    /// assert_eq!(module.name(), Some("foo"));
697    ///
698    /// let module = Module::new(&engine, "(module)")?;
699    /// assert_eq!(module.name(), None);
700    ///
701    /// # Ok(())
702    /// # }
703    /// ```
704    pub fn name(&self) -> Option<&str> {
705        let module = self.compiled_module().module();
706        let name = module.name?;
707        Some(&module.strings[name])
708    }
709
710    /// Returns the original Wasm bytecode for this module, if it is
711    /// available.
712    ///
713    /// Bytecode is only retained when the [`Engine`] was configured with
714    /// `guest-debug` support enabled (see [`Config::guest_debug`]). Returns
715    /// `None` when the module was compiled without that option.
716    ///
717    /// [`Config::guest_debug`]: crate::Config::guest_debug
718    pub fn debug_bytecode(&self) -> Option<&[u8]> {
719        self.compiled_module().bytecode()
720    }
721
722    /// Returns the list of imports that this [`Module`] has and must be
723    /// satisfied.
724    ///
725    /// This function returns the list of imports that the wasm module has, but
726    /// only the types of each import. The type of each import is used to
727    /// typecheck the [`Instance::new`](crate::Instance::new) method's `imports`
728    /// argument. The arguments to that function must match up 1-to-1 with the
729    /// entries in the array returned here.
730    ///
731    /// The imports returned reflect the order of the imports in the wasm module
732    /// itself, and note that no form of deduplication happens.
733    ///
734    /// # Examples
735    ///
736    /// Modules with no imports return an empty list here:
737    ///
738    /// ```
739    /// # use wasmtime::*;
740    /// # fn main() -> Result<()> {
741    /// # let engine = Engine::default();
742    /// let module = Module::new(&engine, "(module)")?;
743    /// assert_eq!(module.imports().len(), 0);
744    /// # Ok(())
745    /// # }
746    /// ```
747    ///
748    /// and modules with imports will have a non-empty list:
749    ///
750    /// ```
751    /// # use wasmtime::*;
752    /// # fn main() -> Result<()> {
753    /// # let engine = Engine::default();
754    /// let wat = r#"
755    ///     (module
756    ///         (import "host" "foo" (func))
757    ///     )
758    /// "#;
759    /// let module = Module::new(&engine, wat)?;
760    /// assert_eq!(module.imports().len(), 1);
761    /// let import = module.imports().next().unwrap();
762    /// assert_eq!(import.module(), "host");
763    /// assert_eq!(import.name(), "foo");
764    /// match import.ty() {
765    ///     ExternType::Func(_) => { /* ... */ }
766    ///     _ => panic!("unexpected import type!"),
767    /// }
768    /// # Ok(())
769    /// # }
770    /// ```
771    pub fn imports<'module>(
772        &'module self,
773    ) -> impl ExactSizeIterator<Item = ImportType<'module>> + 'module {
774        let module = self.compiled_module().module();
775        let types = self.types();
776        let engine = self.engine();
777        module.imports().map(move |(imp_mod, imp_field, ty)| {
778            debug_assert!(ty.is_canonicalized_for_runtime_usage());
779            ImportType::new(imp_mod, imp_field, ty, types, engine)
780        })
781    }
782
783    /// Returns the list of exports that this [`Module`] has and will be
784    /// available after instantiation.
785    ///
786    /// This function will return the type of each item that will be returned
787    /// from [`Instance::exports`](crate::Instance::exports). Each entry in this
788    /// list corresponds 1-to-1 with that list, and the entries here will
789    /// indicate the name of the export along with the type of the export.
790    ///
791    /// # Examples
792    ///
793    /// Modules might not have any exports:
794    ///
795    /// ```
796    /// # use wasmtime::*;
797    /// # fn main() -> Result<()> {
798    /// # let engine = Engine::default();
799    /// let module = Module::new(&engine, "(module)")?;
800    /// assert!(module.exports().next().is_none());
801    /// # Ok(())
802    /// # }
803    /// ```
804    ///
805    /// When the exports are not empty, you can inspect each export:
806    ///
807    /// ```
808    /// # use wasmtime::*;
809    /// # fn main() -> Result<()> {
810    /// # let engine = Engine::default();
811    /// let wat = r#"
812    ///     (module
813    ///         (func (export "foo"))
814    ///         (memory (export "memory") 1)
815    ///     )
816    /// "#;
817    /// let module = Module::new(&engine, wat)?;
818    /// assert_eq!(module.exports().len(), 2);
819    ///
820    /// let mut exports = module.exports();
821    /// let foo = exports.next().unwrap();
822    /// assert_eq!(foo.name(), "foo");
823    /// match foo.ty() {
824    ///     ExternType::Func(_) => { /* ... */ }
825    ///     _ => panic!("unexpected export type!"),
826    /// }
827    ///
828    /// let memory = exports.next().unwrap();
829    /// assert_eq!(memory.name(), "memory");
830    /// match memory.ty() {
831    ///     ExternType::Memory(_) => { /* ... */ }
832    ///     _ => panic!("unexpected export type!"),
833    /// }
834    /// # Ok(())
835    /// # }
836    /// ```
837    pub fn exports<'module>(
838        &'module self,
839    ) -> impl ExactSizeIterator<Item = ExportType<'module>> + 'module {
840        let module = self.compiled_module().module();
841        let types = self.types();
842        let engine = self.engine();
843        module.exports.iter().map(move |(name, entity_index)| {
844            ExportType::new(
845                &module.strings[name],
846                module.type_of(*entity_index),
847                types,
848                engine,
849            )
850        })
851    }
852
853    /// Looks up an export in this [`Module`] by name.
854    ///
855    /// This function will return the type of an export with the given name.
856    ///
857    /// # Examples
858    ///
859    /// There may be no export with that name:
860    ///
861    /// ```
862    /// # use wasmtime::*;
863    /// # fn main() -> Result<()> {
864    /// # let engine = Engine::default();
865    /// let module = Module::new(&engine, "(module)")?;
866    /// assert!(module.get_export("foo").is_none());
867    /// # Ok(())
868    /// # }
869    /// ```
870    ///
871    /// When there is an export with that name, it is returned:
872    ///
873    /// ```
874    /// # use wasmtime::*;
875    /// # fn main() -> Result<()> {
876    /// # let engine = Engine::default();
877    /// let wat = r#"
878    ///     (module
879    ///         (func (export "foo"))
880    ///         (memory (export "memory") 1)
881    ///     )
882    /// "#;
883    /// let module = Module::new(&engine, wat)?;
884    /// let foo = module.get_export("foo");
885    /// assert!(foo.is_some());
886    ///
887    /// let foo = foo.unwrap();
888    /// match foo {
889    ///     ExternType::Func(_) => { /* ... */ }
890    ///     _ => panic!("unexpected export type!"),
891    /// }
892    ///
893    /// # Ok(())
894    /// # }
895    /// ```
896    pub fn get_export(&self, name: &str) -> Option<ExternType> {
897        let module = self.compiled_module().module();
898        let name = module.strings.get_atom(name)?;
899        let entity_index = module.exports.get(&name)?;
900        Some(ExternType::from_wasmtime(
901            self.engine(),
902            self.types(),
903            &module.type_of(*entity_index),
904        ))
905    }
906
907    /// Looks up an export in this [`Module`] by name to get its index.
908    ///
909    /// This function will return the index of an export with the given name. This can be useful
910    /// to avoid the cost of looking up the export by name multiple times. Instead the
911    /// [`ModuleExport`] can be stored and used to look up the export on the
912    /// [`Instance`](crate::Instance) later.
913    pub fn get_export_index(&self, name: &str) -> Option<ModuleExport> {
914        let compiled_module = self.compiled_module();
915        let module = compiled_module.module();
916        let name = module.strings.get_atom(name)?;
917        let entity = *module.exports.get(&name)?;
918        Some(ModuleExport {
919            module: self.id(),
920            entity,
921        })
922    }
923
924    /// Returns the [`Engine`] that this [`Module`] was compiled by.
925    pub fn engine(&self) -> &Engine {
926        &self.inner.engine
927    }
928
929    #[allow(
930        unused,
931        reason = "used only for verification with wasmtime `rr` feature \
932        and requires a lot of unnecessary gating across crates"
933    )]
934    pub(crate) fn checksum(&self) -> &WasmChecksum {
935        &self.inner.checksum
936    }
937
938    /// Returns a summary of the resources required to instantiate this
939    /// [`Module`].
940    ///
941    /// Potential uses of the returned information:
942    ///
943    /// * Determining whether your pooling allocator configuration supports
944    ///   instantiating this module.
945    ///
946    /// * Deciding how many of which `Module` you want to instantiate within a
947    ///   fixed amount of resources, e.g. determining whether to create 5
948    ///   instances of module X or 10 instances of module Y.
949    ///
950    /// # Example
951    ///
952    /// ```
953    /// # fn main() -> wasmtime::Result<()> {
954    /// use wasmtime::{Config, Engine, Module};
955    ///
956    /// let mut config = Config::new();
957    /// config.wasm_multi_memory(true);
958    /// let engine = Engine::new(&config)?;
959    ///
960    /// let module = Module::new(&engine, r#"
961    ///     (module
962    ///         ;; Import a memory. Doesn't count towards required resources.
963    ///         (import "a" "b" (memory 10))
964    ///         ;; Define two local memories. These count towards the required
965    ///         ;; resources.
966    ///         (memory 1)
967    ///         (memory 6)
968    ///     )
969    /// "#)?;
970    ///
971    /// let resources = module.resources_required();
972    ///
973    /// // Instantiating the module will require allocating two memories, and
974    /// // the maximum initial memory size is six Wasm pages.
975    /// assert_eq!(resources.num_memories, 2);
976    /// assert_eq!(resources.max_initial_memory_size, Some(6));
977    ///
978    /// // The module doesn't need any tables.
979    /// assert_eq!(resources.num_tables, 0);
980    /// assert_eq!(resources.max_initial_table_size, None);
981    /// # Ok(()) }
982    /// ```
983    pub fn resources_required(&self) -> ResourcesRequired {
984        let em = self.env_module();
985        let num_memories = u32::try_from(em.num_defined_memories()).unwrap();
986        let max_initial_memory_size = em
987            .memories
988            .values()
989            .skip(em.num_imported_memories)
990            .map(|memory| memory.limits.min)
991            .max();
992        let num_tables = u32::try_from(em.num_defined_tables()).unwrap();
993        let max_initial_table_size = em
994            .tables
995            .values()
996            .skip(em.num_imported_tables)
997            .map(|table| table.limits.min)
998            .max();
999        ResourcesRequired {
1000            num_memories,
1001            max_initial_memory_size,
1002            num_tables,
1003            max_initial_table_size,
1004        }
1005    }
1006
1007    /// Returns the range of bytes in memory where this module's compilation
1008    /// image resides.
1009    ///
1010    /// The compilation image for a module contains executable code, data, debug
1011    /// information, etc. This is roughly the same as the `Module::serialize`
1012    /// but not the exact same.
1013    ///
1014    /// The range of memory reported here is exposed to allow low-level
1015    /// manipulation of the memory in platform-specific manners such as using
1016    /// `mlock` to force the contents to be paged in immediately or keep them
1017    /// paged in after they're loaded.
1018    ///
1019    /// It is not safe to modify the memory in this range, nor is it safe to
1020    /// modify the protections of memory in this range.
1021    ///
1022    /// Note that depending on the engine configuration, this image
1023    /// range may not actually be the code that is directly executed.
1024    pub fn image_range(&self) -> Range<*const u8> {
1025        self.engine_code().image().as_ptr_range()
1026    }
1027
1028    /// Force initialization of copy-on-write images to happen here-and-now
1029    /// instead of when they're requested during first instantiation.
1030    ///
1031    /// When [copy-on-write memory
1032    /// initialization](crate::Config::memory_init_cow) is enabled then Wasmtime
1033    /// will lazily create the initialization image for a module. This method
1034    /// can be used to explicitly dictate when this initialization happens.
1035    ///
1036    /// Note that this largely only matters on Linux when memfd is used.
1037    /// Otherwise the copy-on-write image typically comes from disk and in that
1038    /// situation the creation of the image is trivial as the image is always
1039    /// sourced from disk. On Linux, though, when memfd is used a memfd is
1040    /// created and the initialization image is written to it.
1041    ///
1042    /// Also note that this method is not required to be called, it's available
1043    /// as a performance optimization if required but is otherwise handled
1044    /// automatically.
1045    pub fn initialize_copy_on_write_image(&self) -> Result<()> {
1046        self.memory_images()?;
1047        Ok(())
1048    }
1049
1050    /// Get the map from `.text` section offsets to Wasm binary offsets for this
1051    /// module.
1052    ///
1053    /// Each entry is a (`.text` section offset, Wasm binary offset) pair.
1054    ///
1055    /// Entries are yielded in order of `.text` section offset.
1056    ///
1057    /// Some entries are missing a Wasm binary offset. This is for code that is
1058    /// not associated with any single location in the Wasm binary, or for when
1059    /// source information was optimized away.
1060    ///
1061    /// Not every module has an address map, since address map generation can be
1062    /// turned off on `Config`.
1063    ///
1064    /// There is not an entry for every `.text` section offset. Every offset
1065    /// after an entry's offset, but before the next entry's offset, is
1066    /// considered to map to the same Wasm binary offset as the original
1067    /// entry. For example, the address map will not contain the following
1068    /// sequence of entries:
1069    ///
1070    /// ```ignore
1071    /// [
1072    ///     // ...
1073    ///     (10, Some(42)),
1074    ///     (11, Some(42)),
1075    ///     (12, Some(42)),
1076    ///     (13, Some(43)),
1077    ///     // ...
1078    /// ]
1079    /// ```
1080    ///
1081    /// Instead, it will drop the entries for offsets `11` and `12` since they
1082    /// are the same as the entry for offset `10`:
1083    ///
1084    /// ```ignore
1085    /// [
1086    ///     // ...
1087    ///     (10, Some(42)),
1088    ///     (13, Some(43)),
1089    ///     // ...
1090    /// ]
1091    /// ```
1092    pub fn address_map<'a>(&'a self) -> Option<impl Iterator<Item = (usize, Option<u32>)> + 'a> {
1093        Some(
1094            wasmtime_environ::iterate_address_map(self.engine_code().address_map_data())?
1095                .map(|(offset, file_pos)| (offset as usize, file_pos.file_offset())),
1096        )
1097    }
1098
1099    /// Get this module's code object's `.text` section, containing its compiled
1100    /// executable code.
1101    pub fn text(&self) -> &[u8] {
1102        self.engine_code().text()
1103    }
1104
1105    /// Get information about functions in this module's `.text` section: their
1106    /// index, name, and offset+length.
1107    ///
1108    /// Results are yielded in a ModuleFunction struct.
1109    pub fn functions<'a>(&'a self) -> impl ExactSizeIterator<Item = ModuleFunction> + 'a {
1110        let module = self.compiled_module();
1111        let module_index = self.env_module().module_index;
1112        self.env_module().defined_func_indices().map(move |idx| {
1113            let key = FuncKey::DefinedWasmFunction(module_index, idx);
1114            let loc = module.func_loc(key);
1115            let idx = module.module().func_index(idx);
1116            ModuleFunction {
1117                module: module_index,
1118                index: idx,
1119                name: module.func_name(idx).map(|n| n.to_string()),
1120                offset: loc.start as usize,
1121                len: loc.length as usize,
1122            }
1123        })
1124    }
1125
1126    pub(crate) fn id(&self) -> CompiledModuleId {
1127        self.inner.module.unique_id()
1128    }
1129
1130    pub(crate) fn offsets(&self) -> &VMOffsets<HostPtr> {
1131        &self.inner.offsets
1132    }
1133
1134    /// Return the unique-within-Engine ID for this module.
1135    ///
1136    /// Allows distinguishing module identities when introspecting
1137    /// modules, e.g. via debug APIs.
1138    #[cfg(feature = "debug")]
1139    pub fn debug_index_in_engine(&self) -> u64 {
1140        self.id().as_u64()
1141    }
1142
1143    /// Return the address, in memory, of the trampoline that allows Wasm to
1144    /// call a array function of the given signature.
1145    ///
1146    /// Note that unlike all other code-pointer-returning functions,
1147    /// this *can* be present on `Module` (without a `StoreCode`)
1148    /// because we can execute the `EngineCode` for trampolines that
1149    /// leave the store to call the host.
1150    pub(crate) fn wasm_to_array_trampoline(
1151        &self,
1152        signature: VMSharedTypeIndex,
1153    ) -> Option<NonNull<VMWasmCallFunction>> {
1154        log::trace!("Looking up trampoline for {signature:?}");
1155        let trampoline_shared_ty = self.inner.engine.signatures().trampoline_type(signature);
1156        let trampoline_module_ty = self
1157            .inner
1158            .code
1159            .signatures()
1160            .trampoline_type(trampoline_shared_ty)?;
1161        debug_assert!(
1162            self.inner
1163                .engine
1164                .signatures()
1165                .borrow(
1166                    self.inner
1167                        .code
1168                        .signatures()
1169                        .shared_type(trampoline_module_ty)
1170                        .unwrap()
1171                )
1172                .unwrap()
1173                .unwrap_func()
1174                .is_trampoline_type()
1175        );
1176
1177        let ptr = self
1178            .compiled_module()
1179            .wasm_to_array_trampoline(trampoline_module_ty)
1180            .as_ptr()
1181            .cast::<VMWasmCallFunction>()
1182            .cast_mut();
1183        Some(NonNull::new(ptr).unwrap())
1184    }
1185
1186    pub(crate) fn memory_images(&self) -> Result<Option<&ModuleMemoryImages>> {
1187        let images = self
1188            .inner
1189            .memory_images
1190            .get_or_try_init(|| memory_images(&self.inner))?
1191            .as_ref();
1192        Ok(images)
1193    }
1194
1195    /// See [`CodeMemory::frame_table`].
1196    #[cfg(feature = "debug")]
1197    pub(crate) fn frame_table<'a>(&'a self) -> Option<wasmtime_environ::FrameTable<'a>> {
1198        self.inner.code.frame_table()
1199    }
1200
1201    /// Is this `Module` the same as another?
1202    ///
1203    /// Ordinarily, module identity does not matter: a Wasmtime user
1204    /// will create or obtain a module from some source and
1205    /// instantiate it, and any two `Module` objects created from the
1206    /// same source module are interchangeable. However, introspecting
1207    /// module identity may be useful when examining Wasm VM state,
1208    /// e.g. via debug APIs. It is guaranteed that `Module::same`
1209    /// returns true for `Module` objects that reference the same
1210    /// underlying module (e.g., one created via a `clone` of the
1211    /// other).
1212    #[inline]
1213    pub fn same(a: &Module, b: &Module) -> bool {
1214        Arc::ptr_eq(&a.inner, &b.inner)
1215    }
1216
1217    pub(crate) fn index(&self) -> &Arc<CompiledFunctionsTable> {
1218        &self.inner.module.index()
1219    }
1220}
1221
1222/// Describes a function for a given module.
1223pub struct ModuleFunction {
1224    /// The static module index this function belongs to.
1225    pub module: StaticModuleIndex,
1226    /// The function index within the module.
1227    pub index: wasmtime_environ::FuncIndex,
1228    /// The display name of the function, if available.
1229    pub name: Option<String>,
1230    /// The byte offset of this function in the text section.
1231    pub offset: usize,
1232    /// The byte length of this function in the text section.
1233    pub len: usize,
1234}
1235
1236impl Drop for ModuleInner {
1237    fn drop(&mut self) {
1238        // When a `Module` is being dropped that means that it's no longer
1239        // present in any `Store` and it's additionally not longer held by any
1240        // embedder. Take this opportunity to purge any lingering instantiations
1241        // within a pooling instance allocator, if applicable.
1242        self.engine
1243            .allocator()
1244            .purge_module(self.module.unique_id());
1245    }
1246}
1247
1248/// Describes the location of an export in a module.
1249#[derive(Copy, Clone)]
1250pub struct ModuleExport {
1251    /// The module that this export is defined in.
1252    pub(crate) module: CompiledModuleId,
1253    /// A raw index into the wasm module.
1254    pub(crate) entity: EntityIndex,
1255}
1256
1257/// Helper method to construct a `ModuleMemoryImages` for an associated
1258/// `CompiledModule`.
1259fn memory_images(inner: &Arc<ModuleInner>) -> Result<Option<ModuleMemoryImages>> {
1260    // If initialization via copy-on-write is explicitly disabled in
1261    // configuration then this path is skipped entirely.
1262    if !inner.engine.tunables().memory_init_cow {
1263        return Ok(None);
1264    }
1265
1266    // ... otherwise logic is delegated to the `ModuleMemoryImages::new`
1267    // constructor.
1268    ModuleMemoryImages::new(
1269        &inner.engine,
1270        inner.module.module(),
1271        inner.code.module_memory_image_source(),
1272    )
1273}
1274
1275impl crate::vm::ModuleMemoryImageSource for CodeMemory {
1276    fn wasm_data(&self) -> &[u8] {
1277        <Self>::wasm_data(self)
1278    }
1279
1280    fn mmap(&self) -> Option<&MmapVec> {
1281        Some(<Self>::mmap(self))
1282    }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287    use crate::{CodeBuilder, Engine, Module};
1288    use wasmtime_environ::MemoryInitialization;
1289
1290    #[test]
1291    #[cfg_attr(miri, ignore)]
1292    fn cow_on_by_default() {
1293        let engine = Engine::default();
1294        let module = Module::new(
1295            &engine,
1296            r#"
1297                (module
1298                    (memory 1)
1299                    (data (i32.const 100) "abcd")
1300                )
1301            "#,
1302        )
1303        .unwrap();
1304
1305        let init = &module.env_module().memory_initialization;
1306        assert!(matches!(init, MemoryInitialization::Static { .. }));
1307    }
1308
1309    #[test]
1310    #[cfg_attr(miri, ignore)]
1311    fn image_range_is_whole_image() {
1312        let wat = r#"
1313                (module
1314                    (memory 1)
1315                    (data (i32.const 0) "1234")
1316                    (func (export "f") (param i32) (result i32)
1317                        local.get 0))
1318            "#;
1319        let engine = Engine::default();
1320        let mut builder = CodeBuilder::new(&engine);
1321        builder.wasm_binary_or_text(wat.as_bytes(), None).unwrap();
1322        let bytes = builder.compile_module_serialized().unwrap();
1323
1324        let module = unsafe { Module::deserialize(&engine, &bytes).unwrap() };
1325        let image_range = module.image_range();
1326        let len = image_range.end.addr() - image_range.start.addr();
1327        // Length may be strictly greater if it becomes page-aligned.
1328        assert!(len >= bytes.len());
1329    }
1330}