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