181a89169SAlex Crichton use crate::prelude::*;
215b464b6SAdam Bratschi-Kaye #[cfg(feature = "std")]
315b464b6SAdam Bratschi-Kaye use crate::runtime::vm::open_file_for_mmap;
4b500820eSAlex Crichton use crate::runtime::vm::{CompiledModuleId, MmapVec, ModuleMemoryImages, VMWasmCallFunction};
581a89169SAlex Crichton use crate::sync::OnceLock;
6d4242001SAdam Bratschi-Kaye use crate::{
790ac295eSAlex Crichton Engine,
899ecf728SChris Fallin code::EngineCode,
9d4242001SAdam Bratschi-Kaye code_memory::CodeMemory,
10d4242001SAdam Bratschi-Kaye instantiate::CompiledModule,
11d4242001SAdam Bratschi-Kaye resources::ResourcesRequired,
12d4242001SAdam Bratschi-Kaye types::{ExportType, ExternType, ImportType},
13d4242001SAdam Bratschi-Kaye };
1481a89169SAlex Crichton use alloc::sync::Arc;
1581a89169SAlex Crichton use core::fmt;
1681a89169SAlex Crichton use core::ops::Range;
1781a89169SAlex Crichton use core::ptr::NonNull;
1881a89169SAlex Crichton #[cfg(feature = "std")]
1915b464b6SAdam Bratschi-Kaye use std::{fs::File, path::Path};
20d4242001SAdam Bratschi-Kaye use wasmparser::{Parser, ValidPayload, Validator};
2102155232SChris Fallin #[cfg(feature = "debug")]
2202155232SChris Fallin use wasmtime_environ::FrameTable;
23d4242001SAdam Bratschi-Kaye use wasmtime_environ::{
241806c265SNick Fitzgerald CompiledFunctionsTable, CompiledModuleInfo, EntityIndex, HostPtr, ModuleTypes, ObjectKind,
25b298f375SArjun Ramesh TypeTrace, VMOffsets, VMSharedTypeIndex, WasmChecksum,
26d4242001SAdam Bratschi-Kaye };
272d25f862SChris Fallin #[cfg(feature = "gc")]
282d25f862SChris Fallin use wasmtime_unwinder::ExceptionTable;
29d4242001SAdam Bratschi-Kaye mod registry;
30d4242001SAdam Bratschi-Kaye
31d3132c9dSAlex Crichton pub use registry::*;
32d4242001SAdam Bratschi-Kaye
33d4242001SAdam Bratschi-Kaye /// A compiled WebAssembly module, ready to be instantiated.
34d4242001SAdam Bratschi-Kaye ///
35d4242001SAdam Bratschi-Kaye /// A `Module` is a compiled in-memory representation of an input WebAssembly
36d4242001SAdam Bratschi-Kaye /// binary. A `Module` is then used to create an [`Instance`](crate::Instance)
37d4242001SAdam Bratschi-Kaye /// through an instantiation process. You cannot call functions or fetch
38d4242001SAdam Bratschi-Kaye /// globals, for example, on a `Module` because it's purely a code
39d4242001SAdam Bratschi-Kaye /// representation. Instead you'll need to create an
40d4242001SAdam Bratschi-Kaye /// [`Instance`](crate::Instance) to interact with the wasm module.
41d4242001SAdam Bratschi-Kaye ///
426d105f4dSAlex Crichton /// A `Module` can be created by compiling WebAssembly code through APIs such as
436d105f4dSAlex Crichton /// [`Module::new`]. This would be a JIT-style use case where code is compiled
446d105f4dSAlex Crichton /// just before it's used. Alternatively a `Module` can be compiled in one
456d105f4dSAlex Crichton /// process and [`Module::serialize`] can be used to save it to storage. A later
466d105f4dSAlex Crichton /// call to [`Module::deserialize`] will quickly load the module to execute and
476d105f4dSAlex Crichton /// does not need to compile any code, representing a more AOT-style use case.
48d4242001SAdam Bratschi-Kaye ///
496d105f4dSAlex Crichton /// Currently a `Module` does not implement any form of tiering or dynamic
506d105f4dSAlex Crichton /// optimization of compiled code. Creation of a `Module` via [`Module::new`] or
516d105f4dSAlex Crichton /// related APIs will perform the entire compilation step synchronously. When
526d105f4dSAlex Crichton /// finished no further compilation will happen at runtime or later during
536d105f4dSAlex Crichton /// execution of WebAssembly instances for example.
546d105f4dSAlex Crichton ///
556d105f4dSAlex Crichton /// Compilation of WebAssembly by default goes through Cranelift and is
566d105f4dSAlex Crichton /// recommended to be done once-per-module. The same WebAssembly binary need not
576d105f4dSAlex Crichton /// be compiled multiple times and can instead used an embedder-cached result of
586d105f4dSAlex Crichton /// the first call.
596d105f4dSAlex Crichton ///
606d105f4dSAlex Crichton /// `Module` is thread-safe and safe to share across threads.
61d4242001SAdam Bratschi-Kaye ///
62d4242001SAdam Bratschi-Kaye /// ## Modules and `Clone`
63d4242001SAdam Bratschi-Kaye ///
64d4242001SAdam Bratschi-Kaye /// Using `clone` on a `Module` is a cheap operation. It will not create an
65d4242001SAdam Bratschi-Kaye /// entirely new module, but rather just a new reference to the existing module.
66d4242001SAdam Bratschi-Kaye /// In other words it's a shallow copy, not a deep copy.
67d4242001SAdam Bratschi-Kaye ///
68d4242001SAdam Bratschi-Kaye /// ## Examples
69d4242001SAdam Bratschi-Kaye ///
70d4242001SAdam Bratschi-Kaye /// There are a number of ways you can create a `Module`, for example pulling
71d4242001SAdam Bratschi-Kaye /// the bytes from a number of locations. One example is loading a module from
72d4242001SAdam Bratschi-Kaye /// the filesystem:
73d4242001SAdam Bratschi-Kaye ///
74d4242001SAdam Bratschi-Kaye /// ```no_run
75d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
7696e19700SNick Fitzgerald /// # fn main() -> Result<()> {
77d4242001SAdam Bratschi-Kaye /// let engine = Engine::default();
78d4242001SAdam Bratschi-Kaye /// let module = Module::from_file(&engine, "path/to/foo.wasm")?;
79d4242001SAdam Bratschi-Kaye /// # Ok(())
80d4242001SAdam Bratschi-Kaye /// # }
81d4242001SAdam Bratschi-Kaye /// ```
82d4242001SAdam Bratschi-Kaye ///
83d4242001SAdam Bratschi-Kaye /// You can also load the wasm text format if more convenient too:
84d4242001SAdam Bratschi-Kaye ///
85d4242001SAdam Bratschi-Kaye /// ```no_run
86d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
8796e19700SNick Fitzgerald /// # fn main() -> Result<()> {
88d4242001SAdam Bratschi-Kaye /// let engine = Engine::default();
89d4242001SAdam Bratschi-Kaye /// // Now we're using the WebAssembly text extension: `.wat`!
90d4242001SAdam Bratschi-Kaye /// let module = Module::from_file(&engine, "path/to/foo.wat")?;
91d4242001SAdam Bratschi-Kaye /// # Ok(())
92d4242001SAdam Bratschi-Kaye /// # }
93d4242001SAdam Bratschi-Kaye /// ```
94d4242001SAdam Bratschi-Kaye ///
95d4242001SAdam Bratschi-Kaye /// And if you've already got the bytes in-memory you can use the
96d4242001SAdam Bratschi-Kaye /// [`Module::new`] constructor:
97d4242001SAdam Bratschi-Kaye ///
98d4242001SAdam Bratschi-Kaye /// ```no_run
99d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
10096e19700SNick Fitzgerald /// # fn main() -> Result<()> {
101d4242001SAdam Bratschi-Kaye /// let engine = Engine::default();
102d4242001SAdam Bratschi-Kaye /// # let wasm_bytes: Vec<u8> = Vec::new();
103d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, &wasm_bytes)?;
104d4242001SAdam Bratschi-Kaye ///
105d4242001SAdam Bratschi-Kaye /// // It also works with the text format!
106d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module (func))")?;
107d4242001SAdam Bratschi-Kaye /// # Ok(())
108d4242001SAdam Bratschi-Kaye /// # }
109d4242001SAdam Bratschi-Kaye /// ```
110d4242001SAdam Bratschi-Kaye ///
1116d105f4dSAlex Crichton /// Serializing and deserializing a module looks like:
1126d105f4dSAlex Crichton ///
1136d105f4dSAlex Crichton /// ```no_run
1146d105f4dSAlex Crichton /// # use wasmtime::*;
11596e19700SNick Fitzgerald /// # fn main() -> Result<()> {
1166d105f4dSAlex Crichton /// let engine = Engine::default();
1176d105f4dSAlex Crichton /// # let wasm_bytes: Vec<u8> = Vec::new();
1186d105f4dSAlex Crichton /// let module = Module::new(&engine, &wasm_bytes)?;
1196d105f4dSAlex Crichton /// let module_bytes = module.serialize()?;
1206d105f4dSAlex Crichton ///
1216d105f4dSAlex Crichton /// // ... can save `module_bytes` to disk or other storage ...
1226d105f4dSAlex Crichton ///
1236d105f4dSAlex Crichton /// // recreate the module from the serialized bytes. For the `unsafe` bits
1246d105f4dSAlex Crichton /// // see the documentation of `deserialize`.
1256d105f4dSAlex Crichton /// let module = unsafe { Module::deserialize(&engine, &module_bytes)? };
1266d105f4dSAlex Crichton /// # Ok(())
1276d105f4dSAlex Crichton /// # }
1286d105f4dSAlex Crichton /// ```
1296d105f4dSAlex Crichton ///
130d4242001SAdam Bratschi-Kaye /// [`Config`]: crate::Config
131d4242001SAdam Bratschi-Kaye #[derive(Clone)]
132d4242001SAdam Bratschi-Kaye pub struct Module {
133d4242001SAdam Bratschi-Kaye inner: Arc<ModuleInner>,
134d4242001SAdam Bratschi-Kaye }
135d4242001SAdam Bratschi-Kaye
136d4242001SAdam Bratschi-Kaye struct ModuleInner {
137d4242001SAdam Bratschi-Kaye engine: Engine,
138d4242001SAdam Bratschi-Kaye /// The compiled artifacts for this module that will be instantiated and
139d4242001SAdam Bratschi-Kaye /// executed.
140d4242001SAdam Bratschi-Kaye module: CompiledModule,
141d4242001SAdam Bratschi-Kaye
142d4242001SAdam Bratschi-Kaye /// Runtime information such as the underlying mmap, type information, etc.
143d4242001SAdam Bratschi-Kaye ///
144d4242001SAdam Bratschi-Kaye /// Note that this `Arc` is used to share information between compiled
145d4242001SAdam Bratschi-Kaye /// modules within a component. For bare core wasm modules created with
146d4242001SAdam Bratschi-Kaye /// `Module::new`, for example, this is a uniquely owned `Arc`.
14799ecf728SChris Fallin code: Arc<EngineCode>,
148d4242001SAdam Bratschi-Kaye
149d4242001SAdam Bratschi-Kaye /// A set of initialization images for memories, if any.
150d4242001SAdam Bratschi-Kaye ///
151d4242001SAdam Bratschi-Kaye /// Note that this is behind a `OnceCell` to lazily create this image. On
152d4242001SAdam Bratschi-Kaye /// Linux where `memfd_create` may be used to create the backing memory
153d4242001SAdam Bratschi-Kaye /// image this is a pretty expensive operation, so by deferring it this
154d4242001SAdam Bratschi-Kaye /// improves memory usage for modules that are created but may not ever be
155d4242001SAdam Bratschi-Kaye /// instantiated.
15681a89169SAlex Crichton memory_images: OnceLock<Option<ModuleMemoryImages>>,
157d4242001SAdam Bratschi-Kaye
158d4242001SAdam Bratschi-Kaye /// Flag indicating whether this module can be serialized or not.
159e60b6e62SAlex Crichton #[cfg(any(feature = "cranelift", feature = "winch"))]
160d4242001SAdam Bratschi-Kaye serializable: bool,
161d4242001SAdam Bratschi-Kaye
162d4242001SAdam Bratschi-Kaye /// Runtime offset information for `VMContext`.
163d4242001SAdam Bratschi-Kaye offsets: VMOffsets<HostPtr>,
164b298f375SArjun Ramesh
165b298f375SArjun Ramesh /// The checksum of the source binary from which this module was compiled.
166b298f375SArjun Ramesh checksum: WasmChecksum,
167d4242001SAdam Bratschi-Kaye }
168d4242001SAdam Bratschi-Kaye
16981a89169SAlex Crichton impl fmt::Debug for Module {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result17081a89169SAlex Crichton fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171d4242001SAdam Bratschi-Kaye f.debug_struct("Module")
172d4242001SAdam Bratschi-Kaye .field("name", &self.name())
173d4242001SAdam Bratschi-Kaye .finish_non_exhaustive()
174d4242001SAdam Bratschi-Kaye }
175d4242001SAdam Bratschi-Kaye }
176d4242001SAdam Bratschi-Kaye
177a9473409SNick Fitzgerald impl fmt::Debug for ModuleInner {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result178a9473409SNick Fitzgerald fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179a9473409SNick Fitzgerald f.debug_struct("ModuleInner")
180a9473409SNick Fitzgerald .field("name", &self.module.module().name.as_ref())
181a9473409SNick Fitzgerald .finish_non_exhaustive()
182a9473409SNick Fitzgerald }
183a9473409SNick Fitzgerald }
184a9473409SNick Fitzgerald
185d4242001SAdam Bratschi-Kaye impl Module {
186d4242001SAdam Bratschi-Kaye /// Creates a new WebAssembly `Module` from the given in-memory `bytes`.
187d4242001SAdam Bratschi-Kaye ///
188d4242001SAdam Bratschi-Kaye /// The `bytes` provided must be in one of the following formats:
189d4242001SAdam Bratschi-Kaye ///
190d4242001SAdam Bratschi-Kaye /// * A [binary-encoded][binary] WebAssembly module. This is always supported.
191d4242001SAdam Bratschi-Kaye /// * A [text-encoded][text] instance of the WebAssembly text format.
192d4242001SAdam Bratschi-Kaye /// This is only supported when the `wat` feature of this crate is enabled.
193d4242001SAdam Bratschi-Kaye /// If this is supplied then the text format will be parsed before validation.
194d4242001SAdam Bratschi-Kaye /// Note that the `wat` feature is enabled by default.
195d4242001SAdam Bratschi-Kaye ///
196d4242001SAdam Bratschi-Kaye /// The data for the wasm module must be loaded in-memory if it's present
197d4242001SAdam Bratschi-Kaye /// elsewhere, for example on disk. This requires that the entire binary is
198d4242001SAdam Bratschi-Kaye /// loaded into memory all at once, this API does not support streaming
199d4242001SAdam Bratschi-Kaye /// compilation of a module.
200d4242001SAdam Bratschi-Kaye ///
2016d105f4dSAlex Crichton /// The WebAssembly binary will be decoded and validated. It will also be
2026d105f4dSAlex Crichton /// compiled according to the configuration of the provided `engine`.
203d4242001SAdam Bratschi-Kaye ///
204d4242001SAdam Bratschi-Kaye /// # Errors
205d4242001SAdam Bratschi-Kaye ///
206d4242001SAdam Bratschi-Kaye /// This function may fail and return an error. Errors may include
207d4242001SAdam Bratschi-Kaye /// situations such as:
208d4242001SAdam Bratschi-Kaye ///
209d4242001SAdam Bratschi-Kaye /// * The binary provided could not be decoded because it's not a valid
210d4242001SAdam Bratschi-Kaye /// WebAssembly binary
211d4242001SAdam Bratschi-Kaye /// * The WebAssembly binary may not validate (e.g. contains type errors)
212d4242001SAdam Bratschi-Kaye /// * Implementation-specific limits were exceeded with a valid binary (for
213d4242001SAdam Bratschi-Kaye /// example too many locals)
214d4242001SAdam Bratschi-Kaye /// * The wasm binary may use features that are not enabled in the
215d4242001SAdam Bratschi-Kaye /// configuration of `engine`
216d4242001SAdam Bratschi-Kaye /// * If the `wat` feature is enabled and the input is text, then it may be
217d4242001SAdam Bratschi-Kaye /// rejected if it fails to parse.
218d4242001SAdam Bratschi-Kaye ///
219d4242001SAdam Bratschi-Kaye /// The error returned should contain full information about why module
220d4242001SAdam Bratschi-Kaye /// creation failed if one is returned.
221d4242001SAdam Bratschi-Kaye ///
222d4242001SAdam Bratschi-Kaye /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
223d4242001SAdam Bratschi-Kaye /// [text]: https://webassembly.github.io/spec/core/text/index.html
224d4242001SAdam Bratschi-Kaye ///
225d4242001SAdam Bratschi-Kaye /// # Examples
226d4242001SAdam Bratschi-Kaye ///
227d4242001SAdam Bratschi-Kaye /// The `new` function can be invoked with a in-memory array of bytes:
228d4242001SAdam Bratschi-Kaye ///
229d4242001SAdam Bratschi-Kaye /// ```no_run
230d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
23196e19700SNick Fitzgerald /// # fn main() -> Result<()> {
232d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
233d4242001SAdam Bratschi-Kaye /// # let wasm_bytes: Vec<u8> = Vec::new();
234d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, &wasm_bytes)?;
235d4242001SAdam Bratschi-Kaye /// # Ok(())
236d4242001SAdam Bratschi-Kaye /// # }
237d4242001SAdam Bratschi-Kaye /// ```
238d4242001SAdam Bratschi-Kaye ///
239d4242001SAdam Bratschi-Kaye /// Or you can also pass in a string to be parsed as the wasm text
240d4242001SAdam Bratschi-Kaye /// format:
241d4242001SAdam Bratschi-Kaye ///
242d4242001SAdam Bratschi-Kaye /// ```
243d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
24496e19700SNick Fitzgerald /// # fn main() -> Result<()> {
245d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
246d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module (func))")?;
247d4242001SAdam Bratschi-Kaye /// # Ok(())
248d4242001SAdam Bratschi-Kaye /// # }
249d4242001SAdam Bratschi-Kaye /// ```
250d4242001SAdam Bratschi-Kaye #[cfg(any(feature = "cranelift", feature = "winch"))]
new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module>251d4242001SAdam Bratschi-Kaye pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module> {
25255664f5aSAlex Crichton crate::CodeBuilder::new(engine)
253f673cde3SAlex Crichton .wasm_binary_or_text(bytes.as_ref(), None)?
25455664f5aSAlex Crichton .compile_module()
255d4242001SAdam Bratschi-Kaye }
256d4242001SAdam Bratschi-Kaye
257d4242001SAdam Bratschi-Kaye /// Creates a new WebAssembly `Module` from the contents of the given
258d4242001SAdam Bratschi-Kaye /// `file` on disk.
259d4242001SAdam Bratschi-Kaye ///
260d4242001SAdam Bratschi-Kaye /// This is a convenience function that will read the `file` provided and
261d4242001SAdam Bratschi-Kaye /// pass the bytes to the [`Module::new`] function. For more information
262d4242001SAdam Bratschi-Kaye /// see [`Module::new`]
263d4242001SAdam Bratschi-Kaye ///
264d4242001SAdam Bratschi-Kaye /// # Examples
265d4242001SAdam Bratschi-Kaye ///
266d4242001SAdam Bratschi-Kaye /// ```no_run
267d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
26896e19700SNick Fitzgerald /// # fn main() -> Result<()> {
269d4242001SAdam Bratschi-Kaye /// let engine = Engine::default();
270d4242001SAdam Bratschi-Kaye /// let module = Module::from_file(&engine, "./path/to/foo.wasm")?;
271d4242001SAdam Bratschi-Kaye /// # Ok(())
272d4242001SAdam Bratschi-Kaye /// # }
273d4242001SAdam Bratschi-Kaye /// ```
274d4242001SAdam Bratschi-Kaye ///
275d4242001SAdam Bratschi-Kaye /// The `.wat` text format is also supported:
276d4242001SAdam Bratschi-Kaye ///
277d4242001SAdam Bratschi-Kaye /// ```no_run
278d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
27996e19700SNick Fitzgerald /// # fn main() -> Result<()> {
280d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
281d4242001SAdam Bratschi-Kaye /// let module = Module::from_file(&engine, "./path/to/foo.wat")?;
282d4242001SAdam Bratschi-Kaye /// # Ok(())
283d4242001SAdam Bratschi-Kaye /// # }
284d4242001SAdam Bratschi-Kaye /// ```
28581a89169SAlex Crichton #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))]
from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module>286d4242001SAdam Bratschi-Kaye pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module> {
28755664f5aSAlex Crichton crate::CodeBuilder::new(engine)
288f673cde3SAlex Crichton .wasm_binary_or_text_file(file.as_ref())?
28955664f5aSAlex Crichton .compile_module()
290d4242001SAdam Bratschi-Kaye }
291d4242001SAdam Bratschi-Kaye
292d4242001SAdam Bratschi-Kaye /// Creates a new WebAssembly `Module` from the given in-memory `binary`
293d4242001SAdam Bratschi-Kaye /// data.
294d4242001SAdam Bratschi-Kaye ///
295d4242001SAdam Bratschi-Kaye /// This is similar to [`Module::new`] except that it requires that the
296d4242001SAdam Bratschi-Kaye /// `binary` input is a WebAssembly binary, the text format is not supported
297d4242001SAdam Bratschi-Kaye /// by this function. It's generally recommended to use [`Module::new`], but
298d4242001SAdam Bratschi-Kaye /// if it's required to not support the text format this function can be
299d4242001SAdam Bratschi-Kaye /// used instead.
300d4242001SAdam Bratschi-Kaye ///
301d4242001SAdam Bratschi-Kaye /// # Examples
302d4242001SAdam Bratschi-Kaye ///
303d4242001SAdam Bratschi-Kaye /// ```
304d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
30596e19700SNick Fitzgerald /// # fn main() -> Result<()> {
306d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
307d4242001SAdam Bratschi-Kaye /// let wasm = b"\0asm\x01\0\0\0";
308d4242001SAdam Bratschi-Kaye /// let module = Module::from_binary(&engine, wasm)?;
309d4242001SAdam Bratschi-Kaye /// # Ok(())
310d4242001SAdam Bratschi-Kaye /// # }
311d4242001SAdam Bratschi-Kaye /// ```
312d4242001SAdam Bratschi-Kaye ///
313d4242001SAdam Bratschi-Kaye /// Note that the text format is **not** accepted by this function:
314d4242001SAdam Bratschi-Kaye ///
315d4242001SAdam Bratschi-Kaye /// ```
316d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
31796e19700SNick Fitzgerald /// # fn main() -> Result<()> {
318d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
319d4242001SAdam Bratschi-Kaye /// assert!(Module::from_binary(&engine, b"(module)").is_err());
320d4242001SAdam Bratschi-Kaye /// # Ok(())
321d4242001SAdam Bratschi-Kaye /// # }
322d4242001SAdam Bratschi-Kaye /// ```
323d4242001SAdam Bratschi-Kaye #[cfg(any(feature = "cranelift", feature = "winch"))]
from_binary(engine: &Engine, binary: &[u8]) -> Result<Module>324d4242001SAdam Bratschi-Kaye pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Module> {
32555664f5aSAlex Crichton crate::CodeBuilder::new(engine)
326f673cde3SAlex Crichton .wasm_binary(binary, None)?
32755664f5aSAlex Crichton .compile_module()
328d4242001SAdam Bratschi-Kaye }
329d4242001SAdam Bratschi-Kaye
330d4242001SAdam Bratschi-Kaye /// Creates a new WebAssembly `Module` from the contents of the given `file`
331d4242001SAdam Bratschi-Kaye /// on disk, but with assumptions that the file is from a trusted source.
332d4242001SAdam Bratschi-Kaye /// The file should be a binary- or text-format WebAssembly module, or a
333d4242001SAdam Bratschi-Kaye /// precompiled artifact generated by the same version of Wasmtime.
334d4242001SAdam Bratschi-Kaye ///
335d4242001SAdam Bratschi-Kaye /// # Unsafety
336d4242001SAdam Bratschi-Kaye ///
337d4242001SAdam Bratschi-Kaye /// All of the reasons that [`deserialize`] is `unsafe` apply to this
338d4242001SAdam Bratschi-Kaye /// function as well. Arbitrary data loaded from a file may trick Wasmtime
339d4242001SAdam Bratschi-Kaye /// into arbitrary code execution since the contents of the file are not
340d4242001SAdam Bratschi-Kaye /// validated to be a valid precompiled module.
341d4242001SAdam Bratschi-Kaye ///
342d4242001SAdam Bratschi-Kaye /// [`deserialize`]: Module::deserialize
343d4242001SAdam Bratschi-Kaye ///
344d4242001SAdam Bratschi-Kaye /// Additionally though this function is also `unsafe` because the file
345d4242001SAdam Bratschi-Kaye /// referenced must remain unchanged and a valid precompiled module for the
346d4242001SAdam Bratschi-Kaye /// entire lifetime of the [`Module`] returned. Any changes to the file on
347d4242001SAdam Bratschi-Kaye /// disk may change future instantiations of the module to be incorrect.
348d4242001SAdam Bratschi-Kaye /// This is because the file is mapped into memory and lazily loaded pages
349d4242001SAdam Bratschi-Kaye /// reflect the current state of the file, not necessarily the original
350d4242001SAdam Bratschi-Kaye /// state of the file.
35181a89169SAlex Crichton #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))]
from_trusted_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module>352d4242001SAdam Bratschi-Kaye pub unsafe fn from_trusted_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module> {
35315b464b6SAdam Bratschi-Kaye let open_file = open_file_for_mmap(file.as_ref())?;
354e60b6e62SAlex Crichton let mmap = crate::runtime::vm::MmapVec::from_file(open_file)?;
355d4242001SAdam Bratschi-Kaye if &mmap[0..4] == b"\x7fELF" {
356d4242001SAdam Bratschi-Kaye let code = engine.load_code(mmap, ObjectKind::Module)?;
357d4242001SAdam Bratschi-Kaye return Module::from_parts(engine, code, None);
358d4242001SAdam Bratschi-Kaye }
359d4242001SAdam Bratschi-Kaye
36055664f5aSAlex Crichton crate::CodeBuilder::new(engine)
361f673cde3SAlex Crichton .wasm_binary_or_text(&mmap[..], Some(file.as_ref()))?
36255664f5aSAlex Crichton .compile_module()
363d4242001SAdam Bratschi-Kaye }
364d4242001SAdam Bratschi-Kaye
365d4242001SAdam Bratschi-Kaye /// Deserializes an in-memory compiled module previously created with
366d4242001SAdam Bratschi-Kaye /// [`Module::serialize`] or [`Engine::precompile_module`].
367d4242001SAdam Bratschi-Kaye ///
368d4242001SAdam Bratschi-Kaye /// This function will deserialize the binary blobs emitted by
369d4242001SAdam Bratschi-Kaye /// [`Module::serialize`] and [`Engine::precompile_module`] back into an
370d4242001SAdam Bratschi-Kaye /// in-memory [`Module`] that's ready to be instantiated.
371d4242001SAdam Bratschi-Kaye ///
372d4242001SAdam Bratschi-Kaye /// Note that the [`Module::deserialize_file`] method is more optimized than
373d4242001SAdam Bratschi-Kaye /// this function, so if the serialized module is already present in a file
374d4242001SAdam Bratschi-Kaye /// it's recommended to use that method instead.
375d4242001SAdam Bratschi-Kaye ///
376d4242001SAdam Bratschi-Kaye /// # Unsafety
377d4242001SAdam Bratschi-Kaye ///
378d4242001SAdam Bratschi-Kaye /// This function is marked as `unsafe` because if fed invalid input or used
379d4242001SAdam Bratschi-Kaye /// improperly this could lead to memory safety vulnerabilities. This method
380d4242001SAdam Bratschi-Kaye /// should not, for example, be exposed to arbitrary user input.
381d4242001SAdam Bratschi-Kaye ///
382d4242001SAdam Bratschi-Kaye /// The structure of the binary blob read here is only lightly validated
383d4242001SAdam Bratschi-Kaye /// internally in `wasmtime`. This is intended to be an efficient
384d4242001SAdam Bratschi-Kaye /// "rehydration" for a [`Module`] which has very few runtime checks beyond
385d4242001SAdam Bratschi-Kaye /// deserialization. Arbitrary input could, for example, replace valid
386d4242001SAdam Bratschi-Kaye /// compiled code with any other valid compiled code, meaning that this can
387d4242001SAdam Bratschi-Kaye /// trivially be used to execute arbitrary code otherwise.
388d4242001SAdam Bratschi-Kaye ///
389d4242001SAdam Bratschi-Kaye /// For these reasons this function is `unsafe`. This function is only
390d4242001SAdam Bratschi-Kaye /// designed to receive the previous input from [`Module::serialize`] and
391d4242001SAdam Bratschi-Kaye /// [`Engine::precompile_module`]. If the exact output of those functions
392d4242001SAdam Bratschi-Kaye /// (unmodified) is passed to this function then calls to this function can
393d4242001SAdam Bratschi-Kaye /// be considered safe. It is the caller's responsibility to provide the
394d4242001SAdam Bratschi-Kaye /// guarantee that only previously-serialized bytes are being passed in
395d4242001SAdam Bratschi-Kaye /// here.
396d4242001SAdam Bratschi-Kaye ///
397d4242001SAdam Bratschi-Kaye /// Note that this function is designed to be safe receiving output from
398d4242001SAdam Bratschi-Kaye /// *any* compiled version of `wasmtime` itself. This means that it is safe
399d4242001SAdam Bratschi-Kaye /// to feed output from older versions of Wasmtime into this function, in
400d4242001SAdam Bratschi-Kaye /// addition to newer versions of wasmtime (from the future!). These inputs
401d4242001SAdam Bratschi-Kaye /// will deterministically and safely produce an `Err`. This function only
402d4242001SAdam Bratschi-Kaye /// successfully accepts inputs from the same version of `wasmtime`, but the
403d4242001SAdam Bratschi-Kaye /// safety guarantee only applies to externally-defined blobs of bytes, not
404d4242001SAdam Bratschi-Kaye /// those defined by any version of wasmtime. (this means that if you cache
405d4242001SAdam Bratschi-Kaye /// blobs across versions of wasmtime you can be safely guaranteed that
406d4242001SAdam Bratschi-Kaye /// future versions of wasmtime will reject old cache entries).
deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module>407d4242001SAdam Bratschi-Kaye pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module> {
408d4242001SAdam Bratschi-Kaye let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Module)?;
409d4242001SAdam Bratschi-Kaye Module::from_parts(engine, code, None)
410d4242001SAdam Bratschi-Kaye }
411d4242001SAdam Bratschi-Kaye
41299efc20bSPaul Osborne /// In-place deserialization of an in-memory compiled module previously
41399efc20bSPaul Osborne /// created with [`Module::serialize`] or [`Engine::precompile_module`].
41499efc20bSPaul Osborne ///
41599efc20bSPaul Osborne /// See [`Self::deserialize`] for additional information; this method
41699efc20bSPaul Osborne /// works identically except that it will not create a copy of the provided
41799efc20bSPaul Osborne /// memory but will use it directly.
41899efc20bSPaul Osborne ///
41999efc20bSPaul Osborne /// # Unsafety
42099efc20bSPaul Osborne ///
42199efc20bSPaul Osborne /// All of the safety notes from [`Self::deserialize`] apply here as well
42299efc20bSPaul Osborne /// with the additional constraint that the code memory provide by `memory`
42399efc20bSPaul Osborne /// lives for as long as the module and is nevery externally modified for
42499efc20bSPaul Osborne /// the lifetime of the deserialized module.
deserialize_raw(engine: &Engine, memory: NonNull<[u8]>) -> Result<Module>42599efc20bSPaul Osborne pub unsafe fn deserialize_raw(engine: &Engine, memory: NonNull<[u8]>) -> Result<Module> {
4260f457fadSAlex Crichton // SAFETY: the contract required by `load_code_raw` is the same as this
4270f457fadSAlex Crichton // function.
4280f457fadSAlex Crichton let code = unsafe { engine.load_code_raw(memory, ObjectKind::Module)? };
42999efc20bSPaul Osborne Module::from_parts(engine, code, None)
43099efc20bSPaul Osborne }
43199efc20bSPaul Osborne
432d4242001SAdam Bratschi-Kaye /// Same as [`deserialize`], except that the contents of `path` are read to
433d4242001SAdam Bratschi-Kaye /// deserialize into a [`Module`].
434d4242001SAdam Bratschi-Kaye ///
435d4242001SAdam Bratschi-Kaye /// This method is provided because it can be faster than [`deserialize`]
436d4242001SAdam Bratschi-Kaye /// since the data doesn't need to be copied around, but rather the module
437d4242001SAdam Bratschi-Kaye /// can be used directly from an mmap'd view of the file provided.
438d4242001SAdam Bratschi-Kaye ///
439d4242001SAdam Bratschi-Kaye /// [`deserialize`]: Module::deserialize
440d4242001SAdam Bratschi-Kaye ///
441d4242001SAdam Bratschi-Kaye /// # Unsafety
442d4242001SAdam Bratschi-Kaye ///
443d4242001SAdam Bratschi-Kaye /// All of the reasons that [`deserialize`] is `unsafe` applies to this
444d4242001SAdam Bratschi-Kaye /// function as well. Arbitrary data loaded from a file may trick Wasmtime
445d4242001SAdam Bratschi-Kaye /// into arbitrary code execution since the contents of the file are not
446d4242001SAdam Bratschi-Kaye /// validated to be a valid precompiled module.
447d4242001SAdam Bratschi-Kaye ///
448d4242001SAdam Bratschi-Kaye /// Additionally though this function is also `unsafe` because the file
449d4242001SAdam Bratschi-Kaye /// referenced must remain unchanged and a valid precompiled module for the
450d4242001SAdam Bratschi-Kaye /// entire lifetime of the [`Module`] returned. Any changes to the file on
451d4242001SAdam Bratschi-Kaye /// disk may change future instantiations of the module to be incorrect.
452d4242001SAdam Bratschi-Kaye /// This is because the file is mapped into memory and lazily loaded pages
4530e9121daSFrankReh /// reflect the current state of the file, not necessarily the original
454d4242001SAdam Bratschi-Kaye /// state of the file.
45581a89169SAlex Crichton #[cfg(feature = "std")]
deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Module>456d4242001SAdam Bratschi-Kaye pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Module> {
45715b464b6SAdam Bratschi-Kaye let file = open_file_for_mmap(path.as_ref())?;
4580f457fadSAlex Crichton // SAFETY: the contract of `deserialize_open_file` is the samea s this
4590f457fadSAlex Crichton // function.
4600f457fadSAlex Crichton unsafe {
46115b464b6SAdam Bratschi-Kaye Self::deserialize_open_file(engine, file)
46215b464b6SAdam Bratschi-Kaye .with_context(|| format!("failed deserialization for: {}", path.as_ref().display()))
46315b464b6SAdam Bratschi-Kaye }
4640f457fadSAlex Crichton }
46515b464b6SAdam Bratschi-Kaye
46615b464b6SAdam Bratschi-Kaye /// Same as [`deserialize_file`], except that it takes an open `File`
46715b464b6SAdam Bratschi-Kaye /// instead of a path.
46815b464b6SAdam Bratschi-Kaye ///
46915b464b6SAdam Bratschi-Kaye /// This method is provided because it can be used instead of
47015b464b6SAdam Bratschi-Kaye /// [`deserialize_file`] in situations where `wasmtime` is running with
47115b464b6SAdam Bratschi-Kaye /// limited file system permissions. In that case a process
47215b464b6SAdam Bratschi-Kaye /// with file system access can pass already opened files to `wasmtime`.
47315b464b6SAdam Bratschi-Kaye ///
47415b464b6SAdam Bratschi-Kaye /// [`deserialize_file`]: Module::deserialize_file
47515b464b6SAdam Bratschi-Kaye ///
47615b464b6SAdam Bratschi-Kaye /// Note that the corresponding will be mapped as private writeable
47715b464b6SAdam Bratschi-Kaye /// (copy-on-write) and executable. For `windows` this means the file needs
47815b464b6SAdam Bratschi-Kaye /// to be opened with at least `FILE_GENERIC_READ | FILE_GENERIC_EXECUTE`
47915b464b6SAdam Bratschi-Kaye /// [`access_mode`].
48015b464b6SAdam Bratschi-Kaye ///
48115b464b6SAdam Bratschi-Kaye /// [`access_mode`]: https://doc.rust-lang.org/std/os/windows/fs/trait.OpenOptionsExt.html#tymethod.access_mode
48215b464b6SAdam Bratschi-Kaye ///
48315b464b6SAdam Bratschi-Kaye /// # Unsafety
48415b464b6SAdam Bratschi-Kaye ///
48515b464b6SAdam Bratschi-Kaye /// All of the reasons that [`deserialize_file`] is `unsafe` applies to this
48615b464b6SAdam Bratschi-Kaye /// function as well.
48715b464b6SAdam Bratschi-Kaye #[cfg(feature = "std")]
deserialize_open_file(engine: &Engine, file: File) -> Result<Module>48815b464b6SAdam Bratschi-Kaye pub unsafe fn deserialize_open_file(engine: &Engine, file: File) -> Result<Module> {
48915b464b6SAdam Bratschi-Kaye let code = engine.load_code_file(file, ObjectKind::Module)?;
490d4242001SAdam Bratschi-Kaye Module::from_parts(engine, code, None)
491d4242001SAdam Bratschi-Kaye }
492d4242001SAdam Bratschi-Kaye
493d4242001SAdam Bratschi-Kaye /// Entrypoint for creating a `Module` for all above functions, both
4940e9121daSFrankReh /// of the AOT and jit-compiled categories.
495d4242001SAdam Bratschi-Kaye ///
496d4242001SAdam Bratschi-Kaye /// In all cases the compilation artifact, `code_memory`, is provided here.
497d4242001SAdam Bratschi-Kaye /// The `info_and_types` argument is `None` when a module is being
498d4242001SAdam Bratschi-Kaye /// deserialized from a precompiled artifact or it's `Some` if it was just
499d4242001SAdam Bratschi-Kaye /// compiled and the values are already available.
from_parts( engine: &Engine, code_memory: Arc<CodeMemory>, info_and_types: Option<(CompiledModuleInfo, CompiledFunctionsTable, ModuleTypes)>, ) -> Result<Self>50055664f5aSAlex Crichton pub(crate) fn from_parts(
501d4242001SAdam Bratschi-Kaye engine: &Engine,
502d4242001SAdam Bratschi-Kaye code_memory: Arc<CodeMemory>,
5031806c265SNick Fitzgerald info_and_types: Option<(CompiledModuleInfo, CompiledFunctionsTable, ModuleTypes)>,
504d4242001SAdam Bratschi-Kaye ) -> Result<Self> {
505d4242001SAdam Bratschi-Kaye // Acquire this module's metadata and type information, deserializing
506d4242001SAdam Bratschi-Kaye // it from the provided artifact if it wasn't otherwise provided
507d4242001SAdam Bratschi-Kaye // already.
5081806c265SNick Fitzgerald let (mut info, index, mut types) = match info_and_types {
5091806c265SNick Fitzgerald Some((info, index, types)) => (info, index, types),
5109034e101SAlex Crichton None => postcard::from_bytes(code_memory.wasmtime_info())?,
511d4242001SAdam Bratschi-Kaye };
512d4242001SAdam Bratschi-Kaye
513d4242001SAdam Bratschi-Kaye // Register function type signatures into the engine for the lifetime
514d4242001SAdam Bratschi-Kaye // of the `Module` that will be returned. This notably also builds up
515d4242001SAdam Bratschi-Kaye // maps for trampolines to be used for this module when inserted into
516d4242001SAdam Bratschi-Kaye // stores.
517d4242001SAdam Bratschi-Kaye //
518d4242001SAdam Bratschi-Kaye // Note that the unsafety here should be ok since the `trampolines`
519d4242001SAdam Bratschi-Kaye // field should only point to valid trampoline function pointers
520d4242001SAdam Bratschi-Kaye // within the text section.
5219e3b5ee5SNick Fitzgerald let signatures = engine
5229e3b5ee5SNick Fitzgerald .register_and_canonicalize_types(&mut types, core::iter::once(&mut info.module))?;
523d4242001SAdam Bratschi-Kaye
52499ecf728SChris Fallin // Package up all our data into an `EngineCode` and delegate to the final
525d4242001SAdam Bratschi-Kaye // step of module compilation.
526*6e0ded7cSNick Fitzgerald let code = try_new::<Arc<_>>(EngineCode::new(code_memory, signatures, types.into())?)?;
527601c8b93SNick Fitzgerald let index = try_new::<Arc<_>>(index)?;
5281806c265SNick Fitzgerald Module::from_parts_raw(engine, code, info, index, true)
529d4242001SAdam Bratschi-Kaye }
530d4242001SAdam Bratschi-Kaye
from_parts_raw( engine: &Engine, code: Arc<EngineCode>, info: CompiledModuleInfo, index: Arc<CompiledFunctionsTable>, serializable: bool, ) -> Result<Self>531d4242001SAdam Bratschi-Kaye pub(crate) fn from_parts_raw(
532d4242001SAdam Bratschi-Kaye engine: &Engine,
53399ecf728SChris Fallin code: Arc<EngineCode>,
534d4242001SAdam Bratschi-Kaye info: CompiledModuleInfo,
5351806c265SNick Fitzgerald index: Arc<CompiledFunctionsTable>,
536d4242001SAdam Bratschi-Kaye serializable: bool,
537d4242001SAdam Bratschi-Kaye ) -> Result<Self> {
538b298f375SArjun Ramesh let checksum = info.checksum;
53999ecf728SChris Fallin let module = CompiledModule::from_artifacts(code.clone(), info, index, engine.profiler())?;
540d4242001SAdam Bratschi-Kaye
541d4242001SAdam Bratschi-Kaye // Validate the module can be used with the current instance allocator.
542d4242001SAdam Bratschi-Kaye let offsets = VMOffsets::new(HostPtr, module.module());
543d4242001SAdam Bratschi-Kaye engine
544d4242001SAdam Bratschi-Kaye .allocator()
545d4242001SAdam Bratschi-Kaye .validate_module(module.module(), &offsets)?;
546d4242001SAdam Bratschi-Kaye
547e60b6e62SAlex Crichton let _ = serializable;
548e60b6e62SAlex Crichton
549d4242001SAdam Bratschi-Kaye Ok(Self {
550601c8b93SNick Fitzgerald inner: try_new::<Arc<_>>(ModuleInner {
551d4242001SAdam Bratschi-Kaye engine: engine.clone(),
552d4242001SAdam Bratschi-Kaye code,
55381a89169SAlex Crichton memory_images: OnceLock::new(),
554d4242001SAdam Bratschi-Kaye module,
555e60b6e62SAlex Crichton #[cfg(any(feature = "cranelift", feature = "winch"))]
556d4242001SAdam Bratschi-Kaye serializable,
557d4242001SAdam Bratschi-Kaye offsets,
558b298f375SArjun Ramesh checksum,
559601c8b93SNick Fitzgerald })?,
560d4242001SAdam Bratschi-Kaye })
561d4242001SAdam Bratschi-Kaye }
562d4242001SAdam Bratschi-Kaye
563d4242001SAdam Bratschi-Kaye /// Validates `binary` input data as a WebAssembly binary given the
564d4242001SAdam Bratschi-Kaye /// configuration in `engine`.
565d4242001SAdam Bratschi-Kaye ///
566d4242001SAdam Bratschi-Kaye /// This function will perform a speedy validation of the `binary` input
567d4242001SAdam Bratschi-Kaye /// WebAssembly module (which is in [binary form][binary], the text format
568d4242001SAdam Bratschi-Kaye /// is not accepted by this function) and return either `Ok` or `Err`
569d4242001SAdam Bratschi-Kaye /// depending on the results of validation. The `engine` argument indicates
570d4242001SAdam Bratschi-Kaye /// configuration for WebAssembly features, for example, which are used to
571d4242001SAdam Bratschi-Kaye /// indicate what should be valid and what shouldn't be.
572d4242001SAdam Bratschi-Kaye ///
573d4242001SAdam Bratschi-Kaye /// Validation automatically happens as part of [`Module::new`].
574d4242001SAdam Bratschi-Kaye ///
575d4242001SAdam Bratschi-Kaye /// # Errors
576d4242001SAdam Bratschi-Kaye ///
577d4242001SAdam Bratschi-Kaye /// If validation fails for any reason (type check error, usage of a feature
578d4242001SAdam Bratschi-Kaye /// that wasn't enabled, etc) then an error with a description of the
579d4242001SAdam Bratschi-Kaye /// validation issue will be returned.
580d4242001SAdam Bratschi-Kaye ///
581d4242001SAdam Bratschi-Kaye /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
validate(engine: &Engine, binary: &[u8]) -> Result<()>582d4242001SAdam Bratschi-Kaye pub fn validate(engine: &Engine, binary: &[u8]) -> Result<()> {
58362e51da5SAlex Crichton let mut validator = Validator::new_with_features(engine.features());
584d4242001SAdam Bratschi-Kaye
585d4242001SAdam Bratschi-Kaye let mut functions = Vec::new();
586d4242001SAdam Bratschi-Kaye for payload in Parser::new(0).parse_all(binary) {
5879034e101SAlex Crichton let payload = payload?;
5889034e101SAlex Crichton if let ValidPayload::Func(a, b) = validator.payload(&payload)? {
589d4242001SAdam Bratschi-Kaye functions.push((a, b));
590d4242001SAdam Bratschi-Kaye }
591d4242001SAdam Bratschi-Kaye if let wasmparser::Payload::Version { encoding, .. } = &payload {
592d4242001SAdam Bratschi-Kaye if let wasmparser::Encoding::Component = encoding {
593d4242001SAdam Bratschi-Kaye bail!("component passed to module validation");
594d4242001SAdam Bratschi-Kaye }
595d4242001SAdam Bratschi-Kaye }
596d4242001SAdam Bratschi-Kaye }
597d4242001SAdam Bratschi-Kaye
5989034e101SAlex Crichton engine.run_maybe_parallel(functions, |(validator, body)| {
599d4242001SAdam Bratschi-Kaye // FIXME: it would be best here to use a rayon-specific parallel
600d4242001SAdam Bratschi-Kaye // iterator that maintains state-per-thread to share the function
601d4242001SAdam Bratschi-Kaye // validator allocations (`Default::default` here) across multiple
602d4242001SAdam Bratschi-Kaye // functions.
603d4242001SAdam Bratschi-Kaye validator.into_validator(Default::default()).validate(&body)
6049034e101SAlex Crichton })?;
605d4242001SAdam Bratschi-Kaye Ok(())
606d4242001SAdam Bratschi-Kaye }
607d4242001SAdam Bratschi-Kaye
608d4242001SAdam Bratschi-Kaye /// Serializes this module to a vector of bytes.
609d4242001SAdam Bratschi-Kaye ///
610d4242001SAdam Bratschi-Kaye /// This function is similar to the [`Engine::precompile_module`] method
611d4242001SAdam Bratschi-Kaye /// where it produces an artifact of Wasmtime which is suitable to later
612d4242001SAdam Bratschi-Kaye /// pass into [`Module::deserialize`]. If a module is never instantiated
613d4242001SAdam Bratschi-Kaye /// then it's recommended to use [`Engine::precompile_module`] instead of
614d4242001SAdam Bratschi-Kaye /// this method, but if a module is both instantiated and serialized then
615d4242001SAdam Bratschi-Kaye /// this method can be useful to get the serialized version without
616d4242001SAdam Bratschi-Kaye /// compiling twice.
617d4242001SAdam Bratschi-Kaye #[cfg(any(feature = "cranelift", feature = "winch"))]
serialize(&self) -> Result<Vec<u8>>618d4242001SAdam Bratschi-Kaye pub fn serialize(&self) -> Result<Vec<u8>> {
619d4242001SAdam Bratschi-Kaye // The current representation of compiled modules within a compiled
620d4242001SAdam Bratschi-Kaye // component means that it cannot be serialized. The mmap returned here
621d4242001SAdam Bratschi-Kaye // is the mmap for the entire component and while it contains all
622d4242001SAdam Bratschi-Kaye // necessary data to deserialize this particular module it's all
623d4242001SAdam Bratschi-Kaye // embedded within component-specific information.
624d4242001SAdam Bratschi-Kaye //
625d4242001SAdam Bratschi-Kaye // It's not the hardest thing in the world to support this but it's
626d4242001SAdam Bratschi-Kaye // expected that there's not much of a use case at this time. In theory
627d4242001SAdam Bratschi-Kaye // all that needs to be done is to edit the `.wasmtime.info` section
628d4242001SAdam Bratschi-Kaye // to contains this module's metadata instead of the metadata for the
629d4242001SAdam Bratschi-Kaye // whole component. The metadata itself is fairly trivially
630d4242001SAdam Bratschi-Kaye // recreateable here it's more that there's no easy one-off API for
631d4242001SAdam Bratschi-Kaye // editing the sections of an ELF object to use here.
632d4242001SAdam Bratschi-Kaye //
633d4242001SAdam Bratschi-Kaye // Overall for now this simply always returns an error in this
634d4242001SAdam Bratschi-Kaye // situation. If you're reading this and feel that the situation should
635d4242001SAdam Bratschi-Kaye // be different please feel free to open an issue.
636d4242001SAdam Bratschi-Kaye if !self.inner.serializable {
637d4242001SAdam Bratschi-Kaye bail!("cannot serialize a module exported from a component");
638d4242001SAdam Bratschi-Kaye }
63999ecf728SChris Fallin Ok(self.engine_code().image().to_vec())
640d4242001SAdam Bratschi-Kaye }
641d4242001SAdam Bratschi-Kaye
compiled_module(&self) -> &CompiledModule642d4242001SAdam Bratschi-Kaye pub(crate) fn compiled_module(&self) -> &CompiledModule {
643d4242001SAdam Bratschi-Kaye &self.inner.module
644d4242001SAdam Bratschi-Kaye }
645d4242001SAdam Bratschi-Kaye
engine_code(&self) -> &Arc<EngineCode>64699ecf728SChris Fallin pub(crate) fn engine_code(&self) -> &Arc<EngineCode> {
647d4242001SAdam Bratschi-Kaye &self.inner.code
648d4242001SAdam Bratschi-Kaye }
649d4242001SAdam Bratschi-Kaye
env_module(&self) -> &Arc<wasmtime_environ::Module>6502835a34bSAlex Crichton pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
651d4242001SAdam Bratschi-Kaye self.compiled_module().module()
652d4242001SAdam Bratschi-Kaye }
653d4242001SAdam Bratschi-Kaye
types(&self) -> &ModuleTypes654d4242001SAdam Bratschi-Kaye pub(crate) fn types(&self) -> &ModuleTypes {
655d4242001SAdam Bratschi-Kaye self.inner.code.module_types()
656d4242001SAdam Bratschi-Kaye }
657d4242001SAdam Bratschi-Kaye
658cb235ecfSNick Fitzgerald #[cfg(any(feature = "component-model", feature = "gc-drc"))]
signatures(&self) -> &crate::type_registry::TypeCollection659cb235ecfSNick Fitzgerald pub(crate) fn signatures(&self) -> &crate::type_registry::TypeCollection {
660d4242001SAdam Bratschi-Kaye self.inner.code.signatures()
661d4242001SAdam Bratschi-Kaye }
662d4242001SAdam Bratschi-Kaye
663d4242001SAdam Bratschi-Kaye /// Returns identifier/name that this [`Module`] has. This name
664d4242001SAdam Bratschi-Kaye /// is used in traps/backtrace details.
665d4242001SAdam Bratschi-Kaye ///
666d4242001SAdam Bratschi-Kaye /// Note that most LLVM/clang/Rust-produced modules do not have a name
667d4242001SAdam Bratschi-Kaye /// associated with them, but other wasm tooling can be used to inject or
668d4242001SAdam Bratschi-Kaye /// add a name.
669d4242001SAdam Bratschi-Kaye ///
670d4242001SAdam Bratschi-Kaye /// # Examples
671d4242001SAdam Bratschi-Kaye ///
672d4242001SAdam Bratschi-Kaye /// ```
673d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
67496e19700SNick Fitzgerald /// # fn main() -> Result<()> {
675d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
676d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module $foo)")?;
677d4242001SAdam Bratschi-Kaye /// assert_eq!(module.name(), Some("foo"));
678d4242001SAdam Bratschi-Kaye ///
679d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module)")?;
680d4242001SAdam Bratschi-Kaye /// assert_eq!(module.name(), None);
681d4242001SAdam Bratschi-Kaye ///
682d4242001SAdam Bratschi-Kaye /// # Ok(())
683d4242001SAdam Bratschi-Kaye /// # }
684d4242001SAdam Bratschi-Kaye /// ```
name(&self) -> Option<&str>685d4242001SAdam Bratschi-Kaye pub fn name(&self) -> Option<&str> {
6861f16b28fSNick Fitzgerald let module = self.compiled_module().module();
6871f16b28fSNick Fitzgerald let name = module.name?;
6881f16b28fSNick Fitzgerald Some(&module.strings[name])
689d4242001SAdam Bratschi-Kaye }
690d4242001SAdam Bratschi-Kaye
691c07c94d2SChris Fallin /// Returns the original Wasm bytecode for this module, if it is
692c07c94d2SChris Fallin /// available.
693c07c94d2SChris Fallin ///
694c07c94d2SChris Fallin /// Bytecode is only retained when the [`Engine`] was configured with
695c07c94d2SChris Fallin /// `guest-debug` support enabled (see [`Config::guest_debug`]). Returns
696c07c94d2SChris Fallin /// `None` when the module was compiled without that option.
697c07c94d2SChris Fallin ///
698c07c94d2SChris Fallin /// [`Config::guest_debug`]: crate::Config::guest_debug
debug_bytecode(&self) -> Option<&[u8]>699c07c94d2SChris Fallin pub fn debug_bytecode(&self) -> Option<&[u8]> {
700c07c94d2SChris Fallin self.compiled_module().bytecode()
701c07c94d2SChris Fallin }
702c07c94d2SChris Fallin
703d4242001SAdam Bratschi-Kaye /// Returns the list of imports that this [`Module`] has and must be
704d4242001SAdam Bratschi-Kaye /// satisfied.
705d4242001SAdam Bratschi-Kaye ///
706d4242001SAdam Bratschi-Kaye /// This function returns the list of imports that the wasm module has, but
707d4242001SAdam Bratschi-Kaye /// only the types of each import. The type of each import is used to
708d4242001SAdam Bratschi-Kaye /// typecheck the [`Instance::new`](crate::Instance::new) method's `imports`
709d4242001SAdam Bratschi-Kaye /// argument. The arguments to that function must match up 1-to-1 with the
710d4242001SAdam Bratschi-Kaye /// entries in the array returned here.
711d4242001SAdam Bratschi-Kaye ///
712d4242001SAdam Bratschi-Kaye /// The imports returned reflect the order of the imports in the wasm module
713d4242001SAdam Bratschi-Kaye /// itself, and note that no form of deduplication happens.
714d4242001SAdam Bratschi-Kaye ///
715d4242001SAdam Bratschi-Kaye /// # Examples
716d4242001SAdam Bratschi-Kaye ///
717d4242001SAdam Bratschi-Kaye /// Modules with no imports return an empty list here:
718d4242001SAdam Bratschi-Kaye ///
719d4242001SAdam Bratschi-Kaye /// ```
720d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
72196e19700SNick Fitzgerald /// # fn main() -> Result<()> {
722d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
723d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module)")?;
724d4242001SAdam Bratschi-Kaye /// assert_eq!(module.imports().len(), 0);
725d4242001SAdam Bratschi-Kaye /// # Ok(())
726d4242001SAdam Bratschi-Kaye /// # }
727d4242001SAdam Bratschi-Kaye /// ```
728d4242001SAdam Bratschi-Kaye ///
729d4242001SAdam Bratschi-Kaye /// and modules with imports will have a non-empty list:
730d4242001SAdam Bratschi-Kaye ///
731d4242001SAdam Bratschi-Kaye /// ```
732d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
73396e19700SNick Fitzgerald /// # fn main() -> Result<()> {
734d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
735d4242001SAdam Bratschi-Kaye /// let wat = r#"
736d4242001SAdam Bratschi-Kaye /// (module
737d4242001SAdam Bratschi-Kaye /// (import "host" "foo" (func))
738d4242001SAdam Bratschi-Kaye /// )
739d4242001SAdam Bratschi-Kaye /// "#;
740d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, wat)?;
741d4242001SAdam Bratschi-Kaye /// assert_eq!(module.imports().len(), 1);
742d4242001SAdam Bratschi-Kaye /// let import = module.imports().next().unwrap();
743d4242001SAdam Bratschi-Kaye /// assert_eq!(import.module(), "host");
744d4242001SAdam Bratschi-Kaye /// assert_eq!(import.name(), "foo");
745d4242001SAdam Bratschi-Kaye /// match import.ty() {
746d4242001SAdam Bratschi-Kaye /// ExternType::Func(_) => { /* ... */ }
747d4242001SAdam Bratschi-Kaye /// _ => panic!("unexpected import type!"),
748d4242001SAdam Bratschi-Kaye /// }
749d4242001SAdam Bratschi-Kaye /// # Ok(())
750d4242001SAdam Bratschi-Kaye /// # }
751d4242001SAdam Bratschi-Kaye /// ```
imports<'module>( &'module self, ) -> impl ExactSizeIterator<Item = ImportType<'module>> + 'module752d4242001SAdam Bratschi-Kaye pub fn imports<'module>(
753d4242001SAdam Bratschi-Kaye &'module self,
754d4242001SAdam Bratschi-Kaye ) -> impl ExactSizeIterator<Item = ImportType<'module>> + 'module {
755d4242001SAdam Bratschi-Kaye let module = self.compiled_module().module();
756d4242001SAdam Bratschi-Kaye let types = self.types();
7578652011fSNick Fitzgerald let engine = self.engine();
75831f45079SNick Fitzgerald module.imports().map(move |(imp_mod, imp_field, ty)| {
759cb235ecfSNick Fitzgerald debug_assert!(ty.is_canonicalized_for_runtime_usage());
760b281c0f8SNick Fitzgerald ImportType::new(imp_mod, imp_field, ty, types, engine)
761b281c0f8SNick Fitzgerald })
762d4242001SAdam Bratschi-Kaye }
763d4242001SAdam Bratschi-Kaye
764d4242001SAdam Bratschi-Kaye /// Returns the list of exports that this [`Module`] has and will be
765d4242001SAdam Bratschi-Kaye /// available after instantiation.
766d4242001SAdam Bratschi-Kaye ///
767d4242001SAdam Bratschi-Kaye /// This function will return the type of each item that will be returned
768d4242001SAdam Bratschi-Kaye /// from [`Instance::exports`](crate::Instance::exports). Each entry in this
769d4242001SAdam Bratschi-Kaye /// list corresponds 1-to-1 with that list, and the entries here will
770d4242001SAdam Bratschi-Kaye /// indicate the name of the export along with the type of the export.
771d4242001SAdam Bratschi-Kaye ///
772d4242001SAdam Bratschi-Kaye /// # Examples
773d4242001SAdam Bratschi-Kaye ///
774d4242001SAdam Bratschi-Kaye /// Modules might not have any exports:
775d4242001SAdam Bratschi-Kaye ///
776d4242001SAdam Bratschi-Kaye /// ```
777d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
77896e19700SNick Fitzgerald /// # fn main() -> Result<()> {
779d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
780d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module)")?;
781d4242001SAdam Bratschi-Kaye /// assert!(module.exports().next().is_none());
782d4242001SAdam Bratschi-Kaye /// # Ok(())
783d4242001SAdam Bratschi-Kaye /// # }
784d4242001SAdam Bratschi-Kaye /// ```
785d4242001SAdam Bratschi-Kaye ///
786d4242001SAdam Bratschi-Kaye /// When the exports are not empty, you can inspect each export:
787d4242001SAdam Bratschi-Kaye ///
788d4242001SAdam Bratschi-Kaye /// ```
789d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
79096e19700SNick Fitzgerald /// # fn main() -> Result<()> {
791d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
792d4242001SAdam Bratschi-Kaye /// let wat = r#"
793d4242001SAdam Bratschi-Kaye /// (module
794d4242001SAdam Bratschi-Kaye /// (func (export "foo"))
795d4242001SAdam Bratschi-Kaye /// (memory (export "memory") 1)
796d4242001SAdam Bratschi-Kaye /// )
797d4242001SAdam Bratschi-Kaye /// "#;
798d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, wat)?;
799d4242001SAdam Bratschi-Kaye /// assert_eq!(module.exports().len(), 2);
800d4242001SAdam Bratschi-Kaye ///
801d4242001SAdam Bratschi-Kaye /// let mut exports = module.exports();
802d4242001SAdam Bratschi-Kaye /// let foo = exports.next().unwrap();
803d4242001SAdam Bratschi-Kaye /// assert_eq!(foo.name(), "foo");
804d4242001SAdam Bratschi-Kaye /// match foo.ty() {
805d4242001SAdam Bratschi-Kaye /// ExternType::Func(_) => { /* ... */ }
806d4242001SAdam Bratschi-Kaye /// _ => panic!("unexpected export type!"),
807d4242001SAdam Bratschi-Kaye /// }
808d4242001SAdam Bratschi-Kaye ///
809d4242001SAdam Bratschi-Kaye /// let memory = exports.next().unwrap();
810d4242001SAdam Bratschi-Kaye /// assert_eq!(memory.name(), "memory");
811d4242001SAdam Bratschi-Kaye /// match memory.ty() {
812d4242001SAdam Bratschi-Kaye /// ExternType::Memory(_) => { /* ... */ }
813d4242001SAdam Bratschi-Kaye /// _ => panic!("unexpected export type!"),
814d4242001SAdam Bratschi-Kaye /// }
815d4242001SAdam Bratschi-Kaye /// # Ok(())
816d4242001SAdam Bratschi-Kaye /// # }
817d4242001SAdam Bratschi-Kaye /// ```
exports<'module>( &'module self, ) -> impl ExactSizeIterator<Item = ExportType<'module>> + 'module818d4242001SAdam Bratschi-Kaye pub fn exports<'module>(
819d4242001SAdam Bratschi-Kaye &'module self,
820d4242001SAdam Bratschi-Kaye ) -> impl ExactSizeIterator<Item = ExportType<'module>> + 'module {
821d4242001SAdam Bratschi-Kaye let module = self.compiled_module().module();
822d4242001SAdam Bratschi-Kaye let types = self.types();
8238652011fSNick Fitzgerald let engine = self.engine();
824d4242001SAdam Bratschi-Kaye module.exports.iter().map(move |(name, entity_index)| {
8251f16b28fSNick Fitzgerald ExportType::new(
8261f16b28fSNick Fitzgerald &module.strings[name],
8271f16b28fSNick Fitzgerald module.type_of(*entity_index),
8281f16b28fSNick Fitzgerald types,
8291f16b28fSNick Fitzgerald engine,
8301f16b28fSNick Fitzgerald )
831d4242001SAdam Bratschi-Kaye })
832d4242001SAdam Bratschi-Kaye }
833d4242001SAdam Bratschi-Kaye
834d4242001SAdam Bratschi-Kaye /// Looks up an export in this [`Module`] by name.
835d4242001SAdam Bratschi-Kaye ///
836d4242001SAdam Bratschi-Kaye /// This function will return the type of an export with the given name.
837d4242001SAdam Bratschi-Kaye ///
838d4242001SAdam Bratschi-Kaye /// # Examples
839d4242001SAdam Bratschi-Kaye ///
840d4242001SAdam Bratschi-Kaye /// There may be no export with that name:
841d4242001SAdam Bratschi-Kaye ///
842d4242001SAdam Bratschi-Kaye /// ```
843d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
84496e19700SNick Fitzgerald /// # fn main() -> Result<()> {
845d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
846d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, "(module)")?;
847d4242001SAdam Bratschi-Kaye /// assert!(module.get_export("foo").is_none());
848d4242001SAdam Bratschi-Kaye /// # Ok(())
849d4242001SAdam Bratschi-Kaye /// # }
850d4242001SAdam Bratschi-Kaye /// ```
851d4242001SAdam Bratschi-Kaye ///
852d4242001SAdam Bratschi-Kaye /// When there is an export with that name, it is returned:
853d4242001SAdam Bratschi-Kaye ///
854d4242001SAdam Bratschi-Kaye /// ```
855d4242001SAdam Bratschi-Kaye /// # use wasmtime::*;
85696e19700SNick Fitzgerald /// # fn main() -> Result<()> {
857d4242001SAdam Bratschi-Kaye /// # let engine = Engine::default();
858d4242001SAdam Bratschi-Kaye /// let wat = r#"
859d4242001SAdam Bratschi-Kaye /// (module
860d4242001SAdam Bratschi-Kaye /// (func (export "foo"))
861d4242001SAdam Bratschi-Kaye /// (memory (export "memory") 1)
862d4242001SAdam Bratschi-Kaye /// )
863d4242001SAdam Bratschi-Kaye /// "#;
864d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, wat)?;
865d4242001SAdam Bratschi-Kaye /// let foo = module.get_export("foo");
866d4242001SAdam Bratschi-Kaye /// assert!(foo.is_some());
867d4242001SAdam Bratschi-Kaye ///
868d4242001SAdam Bratschi-Kaye /// let foo = foo.unwrap();
869d4242001SAdam Bratschi-Kaye /// match foo {
870d4242001SAdam Bratschi-Kaye /// ExternType::Func(_) => { /* ... */ }
871d4242001SAdam Bratschi-Kaye /// _ => panic!("unexpected export type!"),
872d4242001SAdam Bratschi-Kaye /// }
873d4242001SAdam Bratschi-Kaye ///
874d4242001SAdam Bratschi-Kaye /// # Ok(())
875d4242001SAdam Bratschi-Kaye /// # }
876d4242001SAdam Bratschi-Kaye /// ```
get_export(&self, name: &str) -> Option<ExternType>877d4242001SAdam Bratschi-Kaye pub fn get_export(&self, name: &str) -> Option<ExternType> {
878d4242001SAdam Bratschi-Kaye let module = self.compiled_module().module();
8791f16b28fSNick Fitzgerald let name = module.strings.get_atom(name)?;
8801f16b28fSNick Fitzgerald let entity_index = module.exports.get(&name)?;
881d4242001SAdam Bratschi-Kaye Some(ExternType::from_wasmtime(
8828652011fSNick Fitzgerald self.engine(),
883d4242001SAdam Bratschi-Kaye self.types(),
884d4242001SAdam Bratschi-Kaye &module.type_of(*entity_index),
885d4242001SAdam Bratschi-Kaye ))
886d4242001SAdam Bratschi-Kaye }
887d4242001SAdam Bratschi-Kaye
888d4242001SAdam Bratschi-Kaye /// Looks up an export in this [`Module`] by name to get its index.
889d4242001SAdam Bratschi-Kaye ///
890d4242001SAdam Bratschi-Kaye /// This function will return the index of an export with the given name. This can be useful
891d4242001SAdam Bratschi-Kaye /// to avoid the cost of looking up the export by name multiple times. Instead the
892d4242001SAdam Bratschi-Kaye /// [`ModuleExport`] can be stored and used to look up the export on the
893d4242001SAdam Bratschi-Kaye /// [`Instance`](crate::Instance) later.
get_export_index(&self, name: &str) -> Option<ModuleExport>894d4242001SAdam Bratschi-Kaye pub fn get_export_index(&self, name: &str) -> Option<ModuleExport> {
895d4242001SAdam Bratschi-Kaye let compiled_module = self.compiled_module();
896d4242001SAdam Bratschi-Kaye let module = compiled_module.module();
8971f16b28fSNick Fitzgerald let name = module.strings.get_atom(name)?;
8981f16b28fSNick Fitzgerald let entity = *module.exports.get(&name)?;
899e012eedaSAlex Crichton Some(ModuleExport {
900d4242001SAdam Bratschi-Kaye module: self.id(),
901d4242001SAdam Bratschi-Kaye entity,
902d4242001SAdam Bratschi-Kaye })
903d4242001SAdam Bratschi-Kaye }
904d4242001SAdam Bratschi-Kaye
905d4242001SAdam Bratschi-Kaye /// Returns the [`Engine`] that this [`Module`] was compiled by.
engine(&self) -> &Engine906d4242001SAdam Bratschi-Kaye pub fn engine(&self) -> &Engine {
907d4242001SAdam Bratschi-Kaye &self.inner.engine
908d4242001SAdam Bratschi-Kaye }
909d4242001SAdam Bratschi-Kaye
910b298f375SArjun Ramesh #[allow(
911b298f375SArjun Ramesh unused,
912b298f375SArjun Ramesh reason = "used only for verification with wasmtime `rr` feature \
913b298f375SArjun Ramesh and requires a lot of unnecessary gating across crates"
914b298f375SArjun Ramesh )]
checksum(&self) -> &WasmChecksum915b298f375SArjun Ramesh pub(crate) fn checksum(&self) -> &WasmChecksum {
916b298f375SArjun Ramesh &self.inner.checksum
917b298f375SArjun Ramesh }
918b298f375SArjun Ramesh
919d4242001SAdam Bratschi-Kaye /// Returns a summary of the resources required to instantiate this
920d4242001SAdam Bratschi-Kaye /// [`Module`].
921d4242001SAdam Bratschi-Kaye ///
922d4242001SAdam Bratschi-Kaye /// Potential uses of the returned information:
923d4242001SAdam Bratschi-Kaye ///
924d4242001SAdam Bratschi-Kaye /// * Determining whether your pooling allocator configuration supports
925d4242001SAdam Bratschi-Kaye /// instantiating this module.
926d4242001SAdam Bratschi-Kaye ///
927d4242001SAdam Bratschi-Kaye /// * Deciding how many of which `Module` you want to instantiate within a
928d4242001SAdam Bratschi-Kaye /// fixed amount of resources, e.g. determining whether to create 5
929d4242001SAdam Bratschi-Kaye /// instances of module X or 10 instances of module Y.
930d4242001SAdam Bratschi-Kaye ///
931d4242001SAdam Bratschi-Kaye /// # Example
932d4242001SAdam Bratschi-Kaye ///
933d4242001SAdam Bratschi-Kaye /// ```
934d4242001SAdam Bratschi-Kaye /// # fn main() -> wasmtime::Result<()> {
935d4242001SAdam Bratschi-Kaye /// use wasmtime::{Config, Engine, Module};
936d4242001SAdam Bratschi-Kaye ///
937d4242001SAdam Bratschi-Kaye /// let mut config = Config::new();
938d4242001SAdam Bratschi-Kaye /// config.wasm_multi_memory(true);
939d4242001SAdam Bratschi-Kaye /// let engine = Engine::new(&config)?;
940d4242001SAdam Bratschi-Kaye ///
941d4242001SAdam Bratschi-Kaye /// let module = Module::new(&engine, r#"
942d4242001SAdam Bratschi-Kaye /// (module
943d4242001SAdam Bratschi-Kaye /// ;; Import a memory. Doesn't count towards required resources.
944d4242001SAdam Bratschi-Kaye /// (import "a" "b" (memory 10))
945d4242001SAdam Bratschi-Kaye /// ;; Define two local memories. These count towards the required
946d4242001SAdam Bratschi-Kaye /// ;; resources.
947d4242001SAdam Bratschi-Kaye /// (memory 1)
948d4242001SAdam Bratschi-Kaye /// (memory 6)
949d4242001SAdam Bratschi-Kaye /// )
950d4242001SAdam Bratschi-Kaye /// "#)?;
951d4242001SAdam Bratschi-Kaye ///
952d4242001SAdam Bratschi-Kaye /// let resources = module.resources_required();
953d4242001SAdam Bratschi-Kaye ///
954d4242001SAdam Bratschi-Kaye /// // Instantiating the module will require allocating two memories, and
955d4242001SAdam Bratschi-Kaye /// // the maximum initial memory size is six Wasm pages.
956d4242001SAdam Bratschi-Kaye /// assert_eq!(resources.num_memories, 2);
957d4242001SAdam Bratschi-Kaye /// assert_eq!(resources.max_initial_memory_size, Some(6));
958d4242001SAdam Bratschi-Kaye ///
959d4242001SAdam Bratschi-Kaye /// // The module doesn't need any tables.
960d4242001SAdam Bratschi-Kaye /// assert_eq!(resources.num_tables, 0);
961d4242001SAdam Bratschi-Kaye /// assert_eq!(resources.max_initial_table_size, None);
962d4242001SAdam Bratschi-Kaye /// # Ok(()) }
963d4242001SAdam Bratschi-Kaye /// ```
resources_required(&self) -> ResourcesRequired964d4242001SAdam Bratschi-Kaye pub fn resources_required(&self) -> ResourcesRequired {
965d4242001SAdam Bratschi-Kaye let em = self.env_module();
9662a7f0653SAlex Crichton let num_memories = u32::try_from(em.num_defined_memories()).unwrap();
967d4242001SAdam Bratschi-Kaye let max_initial_memory_size = em
9682a7f0653SAlex Crichton .memories
969d4242001SAdam Bratschi-Kaye .values()
970d4242001SAdam Bratschi-Kaye .skip(em.num_imported_memories)
9712a7f0653SAlex Crichton .map(|memory| memory.limits.min)
972d4242001SAdam Bratschi-Kaye .max();
9737a49e44fSAlex Crichton let num_tables = u32::try_from(em.num_defined_tables()).unwrap();
974d4242001SAdam Bratschi-Kaye let max_initial_table_size = em
9757a49e44fSAlex Crichton .tables
976d4242001SAdam Bratschi-Kaye .values()
977d4242001SAdam Bratschi-Kaye .skip(em.num_imported_tables)
9787a49e44fSAlex Crichton .map(|table| table.limits.min)
979d4242001SAdam Bratschi-Kaye .max();
980d4242001SAdam Bratschi-Kaye ResourcesRequired {
981d4242001SAdam Bratschi-Kaye num_memories,
982d4242001SAdam Bratschi-Kaye max_initial_memory_size,
983d4242001SAdam Bratschi-Kaye num_tables,
984d4242001SAdam Bratschi-Kaye max_initial_table_size,
985d4242001SAdam Bratschi-Kaye }
986d4242001SAdam Bratschi-Kaye }
987d4242001SAdam Bratschi-Kaye
988d4242001SAdam Bratschi-Kaye /// Returns the range of bytes in memory where this module's compilation
989d4242001SAdam Bratschi-Kaye /// image resides.
990d4242001SAdam Bratschi-Kaye ///
991d4242001SAdam Bratschi-Kaye /// The compilation image for a module contains executable code, data, debug
992d4242001SAdam Bratschi-Kaye /// information, etc. This is roughly the same as the `Module::serialize`
993d4242001SAdam Bratschi-Kaye /// but not the exact same.
994d4242001SAdam Bratschi-Kaye ///
995d4242001SAdam Bratschi-Kaye /// The range of memory reported here is exposed to allow low-level
996d4242001SAdam Bratschi-Kaye /// manipulation of the memory in platform-specific manners such as using
997d4242001SAdam Bratschi-Kaye /// `mlock` to force the contents to be paged in immediately or keep them
998d4242001SAdam Bratschi-Kaye /// paged in after they're loaded.
999d4242001SAdam Bratschi-Kaye ///
1000d4242001SAdam Bratschi-Kaye /// It is not safe to modify the memory in this range, nor is it safe to
1001d4242001SAdam Bratschi-Kaye /// modify the protections of memory in this range.
100299ecf728SChris Fallin ///
100399ecf728SChris Fallin /// Note that depending on the engine configuration, this image
100499ecf728SChris Fallin /// range may not actually be the code that is directly executed.
image_range(&self) -> Range<*const u8>1005120e6b23SAlex Crichton pub fn image_range(&self) -> Range<*const u8> {
10065566d520SChris Fallin self.engine_code().image().as_ptr_range()
1007d4242001SAdam Bratschi-Kaye }
1008d4242001SAdam Bratschi-Kaye
1009d4242001SAdam Bratschi-Kaye /// Force initialization of copy-on-write images to happen here-and-now
1010d4242001SAdam Bratschi-Kaye /// instead of when they're requested during first instantiation.
1011d4242001SAdam Bratschi-Kaye ///
1012d4242001SAdam Bratschi-Kaye /// When [copy-on-write memory
1013d4242001SAdam Bratschi-Kaye /// initialization](crate::Config::memory_init_cow) is enabled then Wasmtime
1014d4242001SAdam Bratschi-Kaye /// will lazily create the initialization image for a module. This method
1015d4242001SAdam Bratschi-Kaye /// can be used to explicitly dictate when this initialization happens.
1016d4242001SAdam Bratschi-Kaye ///
1017d4242001SAdam Bratschi-Kaye /// Note that this largely only matters on Linux when memfd is used.
1018d4242001SAdam Bratschi-Kaye /// Otherwise the copy-on-write image typically comes from disk and in that
1019d4242001SAdam Bratschi-Kaye /// situation the creation of the image is trivial as the image is always
1020d4242001SAdam Bratschi-Kaye /// sourced from disk. On Linux, though, when memfd is used a memfd is
1021d4242001SAdam Bratschi-Kaye /// created and the initialization image is written to it.
1022d4242001SAdam Bratschi-Kaye ///
1023d4242001SAdam Bratschi-Kaye /// Also note that this method is not required to be called, it's available
1024d4242001SAdam Bratschi-Kaye /// as a performance optimization if required but is otherwise handled
1025d4242001SAdam Bratschi-Kaye /// automatically.
initialize_copy_on_write_image(&self) -> Result<()>1026d4242001SAdam Bratschi-Kaye pub fn initialize_copy_on_write_image(&self) -> Result<()> {
10272835a34bSAlex Crichton self.memory_images()?;
1028d4242001SAdam Bratschi-Kaye Ok(())
1029d4242001SAdam Bratschi-Kaye }
1030d4242001SAdam Bratschi-Kaye
1031d4242001SAdam Bratschi-Kaye /// Get the map from `.text` section offsets to Wasm binary offsets for this
1032d4242001SAdam Bratschi-Kaye /// module.
1033d4242001SAdam Bratschi-Kaye ///
1034d4242001SAdam Bratschi-Kaye /// Each entry is a (`.text` section offset, Wasm binary offset) pair.
1035d4242001SAdam Bratschi-Kaye ///
1036d4242001SAdam Bratschi-Kaye /// Entries are yielded in order of `.text` section offset.
1037d4242001SAdam Bratschi-Kaye ///
1038d4242001SAdam Bratschi-Kaye /// Some entries are missing a Wasm binary offset. This is for code that is
1039d4242001SAdam Bratschi-Kaye /// not associated with any single location in the Wasm binary, or for when
1040d4242001SAdam Bratschi-Kaye /// source information was optimized away.
1041d4242001SAdam Bratschi-Kaye ///
1042d4242001SAdam Bratschi-Kaye /// Not every module has an address map, since address map generation can be
1043d4242001SAdam Bratschi-Kaye /// turned off on `Config`.
1044d4242001SAdam Bratschi-Kaye ///
1045d4242001SAdam Bratschi-Kaye /// There is not an entry for every `.text` section offset. Every offset
1046d4242001SAdam Bratschi-Kaye /// after an entry's offset, but before the next entry's offset, is
1047d4242001SAdam Bratschi-Kaye /// considered to map to the same Wasm binary offset as the original
1048d4242001SAdam Bratschi-Kaye /// entry. For example, the address map will not contain the following
1049d4242001SAdam Bratschi-Kaye /// sequence of entries:
1050d4242001SAdam Bratschi-Kaye ///
1051d4242001SAdam Bratschi-Kaye /// ```ignore
1052d4242001SAdam Bratschi-Kaye /// [
1053d4242001SAdam Bratschi-Kaye /// // ...
1054d4242001SAdam Bratschi-Kaye /// (10, Some(42)),
1055d4242001SAdam Bratschi-Kaye /// (11, Some(42)),
1056d4242001SAdam Bratschi-Kaye /// (12, Some(42)),
1057d4242001SAdam Bratschi-Kaye /// (13, Some(43)),
1058d4242001SAdam Bratschi-Kaye /// // ...
1059d4242001SAdam Bratschi-Kaye /// ]
1060d4242001SAdam Bratschi-Kaye /// ```
1061d4242001SAdam Bratschi-Kaye ///
1062d4242001SAdam Bratschi-Kaye /// Instead, it will drop the entries for offsets `11` and `12` since they
1063d4242001SAdam Bratschi-Kaye /// are the same as the entry for offset `10`:
1064d4242001SAdam Bratschi-Kaye ///
1065d4242001SAdam Bratschi-Kaye /// ```ignore
1066d4242001SAdam Bratschi-Kaye /// [
1067d4242001SAdam Bratschi-Kaye /// // ...
1068d4242001SAdam Bratschi-Kaye /// (10, Some(42)),
1069d4242001SAdam Bratschi-Kaye /// (13, Some(43)),
1070d4242001SAdam Bratschi-Kaye /// // ...
1071d4242001SAdam Bratschi-Kaye /// ]
1072d4242001SAdam Bratschi-Kaye /// ```
address_map<'a>(&'a self) -> Option<impl Iterator<Item = (usize, Option<u32>)> + 'a>1073d4242001SAdam Bratschi-Kaye pub fn address_map<'a>(&'a self) -> Option<impl Iterator<Item = (usize, Option<u32>)> + 'a> {
1074d4242001SAdam Bratschi-Kaye Some(
107599ecf728SChris Fallin wasmtime_environ::iterate_address_map(self.engine_code().address_map_data())?
1076d4242001SAdam Bratschi-Kaye .map(|(offset, file_pos)| (offset as usize, file_pos.file_offset())),
1077d4242001SAdam Bratschi-Kaye )
1078d4242001SAdam Bratschi-Kaye }
1079d4242001SAdam Bratschi-Kaye
1080d4242001SAdam Bratschi-Kaye /// Get this module's code object's `.text` section, containing its compiled
1081d4242001SAdam Bratschi-Kaye /// executable code.
text(&self) -> &[u8]1082d4242001SAdam Bratschi-Kaye pub fn text(&self) -> &[u8] {
108399ecf728SChris Fallin self.engine_code().text()
1084d4242001SAdam Bratschi-Kaye }
1085d4242001SAdam Bratschi-Kaye
1086f9946472SL. Pereira /// Get information about functions in this module's `.text` section: their
1087f9946472SL. Pereira /// index, name, and offset+length.
1088d4242001SAdam Bratschi-Kaye ///
1089f9946472SL. Pereira /// Results are yielded in a ModuleFunction struct.
functions<'a>(&'a self) -> impl ExactSizeIterator<Item = ModuleFunction> + 'a1090f9946472SL. Pereira pub fn functions<'a>(&'a self) -> impl ExactSizeIterator<Item = ModuleFunction> + 'a {
1091f9946472SL. Pereira let module = self.compiled_module();
109299ecf728SChris Fallin self.env_module().defined_func_indices().map(|idx| {
1093f9946472SL. Pereira let loc = module.func_loc(idx);
1094f9946472SL. Pereira let idx = module.module().func_index(idx);
1095f9946472SL. Pereira ModuleFunction {
1096f9946472SL. Pereira index: idx,
1097f9946472SL. Pereira name: module.func_name(idx).map(|n| n.to_string()),
1098f9946472SL. Pereira offset: loc.start as usize,
1099f9946472SL. Pereira len: loc.length as usize,
1100f9946472SL. Pereira }
1101d4242001SAdam Bratschi-Kaye })
1102d4242001SAdam Bratschi-Kaye }
1103d4242001SAdam Bratschi-Kaye
id(&self) -> CompiledModuleId1104d4242001SAdam Bratschi-Kaye pub(crate) fn id(&self) -> CompiledModuleId {
1105d4242001SAdam Bratschi-Kaye self.inner.module.unique_id()
1106d4242001SAdam Bratschi-Kaye }
11072835a34bSAlex Crichton
offsets(&self) -> &VMOffsets<HostPtr>11082835a34bSAlex Crichton pub(crate) fn offsets(&self) -> &VMOffsets<HostPtr> {
11092835a34bSAlex Crichton &self.inner.offsets
11102835a34bSAlex Crichton }
11112835a34bSAlex Crichton
11127051ab30SChris Fallin /// Return the unique-within-Engine ID for this module.
11137051ab30SChris Fallin ///
11147051ab30SChris Fallin /// Allows distinguishing module identities when introspecting
11157051ab30SChris Fallin /// modules, e.g. via debug APIs.
11167051ab30SChris Fallin #[cfg(feature = "debug")]
debug_index_in_engine(&self) -> u6411177051ab30SChris Fallin pub fn debug_index_in_engine(&self) -> u64 {
11187051ab30SChris Fallin self.id().as_u64()
11197051ab30SChris Fallin }
11207051ab30SChris Fallin
11212835a34bSAlex Crichton /// Return the address, in memory, of the trampoline that allows Wasm to
11222835a34bSAlex Crichton /// call a array function of the given signature.
112399ecf728SChris Fallin ///
112499ecf728SChris Fallin /// Note that unlike all other code-pointer-returning functions,
112599ecf728SChris Fallin /// this *can* be present on `Module` (without a `StoreCode`)
112699ecf728SChris Fallin /// because we can execute the `EngineCode` for trampolines that
112799ecf728SChris Fallin /// leave the store to call the host.
wasm_to_array_trampoline( &self, signature: VMSharedTypeIndex, ) -> Option<NonNull<VMWasmCallFunction>>11282835a34bSAlex Crichton pub(crate) fn wasm_to_array_trampoline(
11292835a34bSAlex Crichton &self,
11302835a34bSAlex Crichton signature: VMSharedTypeIndex,
11312835a34bSAlex Crichton ) -> Option<NonNull<VMWasmCallFunction>> {
11322835a34bSAlex Crichton log::trace!("Looking up trampoline for {signature:?}");
11332835a34bSAlex Crichton let trampoline_shared_ty = self.inner.engine.signatures().trampoline_type(signature);
11342835a34bSAlex Crichton let trampoline_module_ty = self
11352835a34bSAlex Crichton .inner
11362835a34bSAlex Crichton .code
11372835a34bSAlex Crichton .signatures()
11382835a34bSAlex Crichton .trampoline_type(trampoline_shared_ty)?;
113990ac295eSAlex Crichton debug_assert!(
114090ac295eSAlex Crichton self.inner
11412835a34bSAlex Crichton .engine
11422835a34bSAlex Crichton .signatures()
11432835a34bSAlex Crichton .borrow(
11442835a34bSAlex Crichton self.inner
11452835a34bSAlex Crichton .code
11462835a34bSAlex Crichton .signatures()
11472835a34bSAlex Crichton .shared_type(trampoline_module_ty)
11482835a34bSAlex Crichton .unwrap()
11492835a34bSAlex Crichton )
11502835a34bSAlex Crichton .unwrap()
11512835a34bSAlex Crichton .unwrap_func()
115290ac295eSAlex Crichton .is_trampoline_type()
115390ac295eSAlex Crichton );
11542835a34bSAlex Crichton
11552835a34bSAlex Crichton let ptr = self
11562835a34bSAlex Crichton .compiled_module()
11572835a34bSAlex Crichton .wasm_to_array_trampoline(trampoline_module_ty)
11581806c265SNick Fitzgerald .expect("always have a trampoline for the trampoline type")
11592835a34bSAlex Crichton .as_ptr()
11602835a34bSAlex Crichton .cast::<VMWasmCallFunction>()
11612835a34bSAlex Crichton .cast_mut();
11622835a34bSAlex Crichton Some(NonNull::new(ptr).unwrap())
11632835a34bSAlex Crichton }
11642835a34bSAlex Crichton
memory_images(&self) -> Result<Option<&ModuleMemoryImages>>11652835a34bSAlex Crichton pub(crate) fn memory_images(&self) -> Result<Option<&ModuleMemoryImages>> {
11662835a34bSAlex Crichton let images = self
11672835a34bSAlex Crichton .inner
11682835a34bSAlex Crichton .memory_images
1169b500820eSAlex Crichton .get_or_try_init(|| memory_images(&self.inner))?
11702835a34bSAlex Crichton .as_ref();
11712835a34bSAlex Crichton Ok(images)
11722835a34bSAlex Crichton }
11738ea25906SNick Fitzgerald
11742d25f862SChris Fallin /// Obtain an exception-table parser on this module's exception metadata.
11752d25f862SChris Fallin #[cfg(feature = "gc")]
exception_table<'a>(&'a self) -> ExceptionTable<'a>11762d25f862SChris Fallin pub(crate) fn exception_table<'a>(&'a self) -> ExceptionTable<'a> {
117799ecf728SChris Fallin ExceptionTable::parse(self.inner.code.exception_tables())
11782d25f862SChris Fallin .expect("Exception tables were validated on module load")
11792d25f862SChris Fallin }
118002155232SChris Fallin
118102155232SChris Fallin /// Obtain a frame-table parser on this module's frame state slot
118202155232SChris Fallin /// (debug instrumentation) metadata.
118302155232SChris Fallin #[cfg(feature = "debug")]
frame_table<'a>(&'a self) -> Option<FrameTable<'a>>118402155232SChris Fallin pub(crate) fn frame_table<'a>(&'a self) -> Option<FrameTable<'a>> {
118599ecf728SChris Fallin let data = self.inner.code.frame_tables();
118602155232SChris Fallin if data.is_empty() {
118702155232SChris Fallin None
118802155232SChris Fallin } else {
118917fbd3c6SChris Fallin let orig_text = self.inner.code.text();
119017fbd3c6SChris Fallin Some(
119117fbd3c6SChris Fallin FrameTable::parse(data, orig_text)
119217fbd3c6SChris Fallin .expect("Frame tables were validated on module load"),
119317fbd3c6SChris Fallin )
119402155232SChris Fallin }
119502155232SChris Fallin }
119617fbd3c6SChris Fallin
119717fbd3c6SChris Fallin /// Is this `Module` the same as another?
119817fbd3c6SChris Fallin ///
119917fbd3c6SChris Fallin /// Ordinarily, module identity does not matter: a Wasmtime user
120017fbd3c6SChris Fallin /// will create or obtain a module from some source and
120117fbd3c6SChris Fallin /// instantiate it, and any two `Module` objects created from the
120217fbd3c6SChris Fallin /// same source module are interchangeable. However, introspecting
120317fbd3c6SChris Fallin /// module identity may be useful when examining Wasm VM state,
120417fbd3c6SChris Fallin /// e.g. via debug APIs. It is guaranteed that `Module::same`
120517fbd3c6SChris Fallin /// returns true for `Module` objects that reference the same
120617fbd3c6SChris Fallin /// underlying module (e.g., one created via a `clone` of the
120717fbd3c6SChris Fallin /// other).
120817fbd3c6SChris Fallin #[inline]
same(a: &Module, b: &Module) -> bool120917fbd3c6SChris Fallin pub fn same(a: &Module, b: &Module) -> bool {
121017fbd3c6SChris Fallin Arc::ptr_eq(&a.inner, &b.inner)
121117fbd3c6SChris Fallin }
1212d4242001SAdam Bratschi-Kaye }
1213d4242001SAdam Bratschi-Kaye
1214f9946472SL. Pereira /// Describes a function for a given module.
1215f9946472SL. Pereira pub struct ModuleFunction {
1216f9946472SL. Pereira pub index: wasmtime_environ::FuncIndex,
1217f9946472SL. Pereira pub name: Option<String>,
1218f9946472SL. Pereira pub offset: usize,
1219f9946472SL. Pereira pub len: usize,
1220f9946472SL. Pereira }
1221f9946472SL. Pereira
1222d4242001SAdam Bratschi-Kaye impl Drop for ModuleInner {
drop(&mut self)1223d4242001SAdam Bratschi-Kaye fn drop(&mut self) {
1224d4242001SAdam Bratschi-Kaye // When a `Module` is being dropped that means that it's no longer
1225d4242001SAdam Bratschi-Kaye // present in any `Store` and it's additionally not longer held by any
1226d4242001SAdam Bratschi-Kaye // embedder. Take this opportunity to purge any lingering instantiations
1227d4242001SAdam Bratschi-Kaye // within a pooling instance allocator, if applicable.
1228d4242001SAdam Bratschi-Kaye self.engine
1229d4242001SAdam Bratschi-Kaye .allocator()
1230d4242001SAdam Bratschi-Kaye .purge_module(self.module.unique_id());
1231d4242001SAdam Bratschi-Kaye }
1232d4242001SAdam Bratschi-Kaye }
1233d4242001SAdam Bratschi-Kaye
1234d4242001SAdam Bratschi-Kaye /// Describes the location of an export in a module.
1235d4242001SAdam Bratschi-Kaye #[derive(Copy, Clone)]
1236d4242001SAdam Bratschi-Kaye pub struct ModuleExport {
1237d4242001SAdam Bratschi-Kaye /// The module that this export is defined in.
1238d4242001SAdam Bratschi-Kaye pub(crate) module: CompiledModuleId,
1239d4242001SAdam Bratschi-Kaye /// A raw index into the wasm module.
1240d4242001SAdam Bratschi-Kaye pub(crate) entity: EntityIndex,
1241d4242001SAdam Bratschi-Kaye }
1242d4242001SAdam Bratschi-Kaye
_assert_send_sync()1243d4242001SAdam Bratschi-Kaye fn _assert_send_sync() {
1244d4242001SAdam Bratschi-Kaye fn _assert<T: Send + Sync>() {}
1245d4242001SAdam Bratschi-Kaye _assert::<Module>();
1246d4242001SAdam Bratschi-Kaye }
1247d4242001SAdam Bratschi-Kaye
1248d4242001SAdam Bratschi-Kaye /// Helper method to construct a `ModuleMemoryImages` for an associated
1249d4242001SAdam Bratschi-Kaye /// `CompiledModule`.
memory_images(inner: &Arc<ModuleInner>) -> Result<Option<ModuleMemoryImages>>1250b500820eSAlex Crichton fn memory_images(inner: &Arc<ModuleInner>) -> Result<Option<ModuleMemoryImages>> {
1251d4242001SAdam Bratschi-Kaye // If initialization via copy-on-write is explicitly disabled in
1252d4242001SAdam Bratschi-Kaye // configuration then this path is skipped entirely.
1253b500820eSAlex Crichton if !inner.engine.tunables().memory_init_cow {
1254d4242001SAdam Bratschi-Kaye return Ok(None);
1255d4242001SAdam Bratschi-Kaye }
1256d4242001SAdam Bratschi-Kaye
1257d4242001SAdam Bratschi-Kaye // ... otherwise logic is delegated to the `ModuleMemoryImages::new`
1258d4242001SAdam Bratschi-Kaye // constructor.
1259b500820eSAlex Crichton ModuleMemoryImages::new(
1260b500820eSAlex Crichton &inner.engine,
1261b500820eSAlex Crichton inner.module.module(),
126299ecf728SChris Fallin inner.code.module_memory_image_source(),
1263b500820eSAlex Crichton )
1264b500820eSAlex Crichton }
1265b500820eSAlex Crichton
1266b500820eSAlex Crichton impl crate::vm::ModuleMemoryImageSource for CodeMemory {
wasm_data(&self) -> &[u8]1267b500820eSAlex Crichton fn wasm_data(&self) -> &[u8] {
1268b500820eSAlex Crichton <Self>::wasm_data(self)
1269b500820eSAlex Crichton }
1270b500820eSAlex Crichton
mmap(&self) -> Option<&MmapVec>1271b500820eSAlex Crichton fn mmap(&self) -> Option<&MmapVec> {
1272b500820eSAlex Crichton Some(<Self>::mmap(self))
1273b500820eSAlex Crichton }
1274d4242001SAdam Bratschi-Kaye }
1275d4242001SAdam Bratschi-Kaye
1276d4242001SAdam Bratschi-Kaye #[cfg(test)]
1277d4242001SAdam Bratschi-Kaye mod tests {
12785566d520SChris Fallin use crate::{CodeBuilder, Engine, Module};
1279d4242001SAdam Bratschi-Kaye use wasmtime_environ::MemoryInitialization;
1280d4242001SAdam Bratschi-Kaye
1281d4242001SAdam Bratschi-Kaye #[test]
cow_on_by_default()1282d4242001SAdam Bratschi-Kaye fn cow_on_by_default() {
1283d4242001SAdam Bratschi-Kaye let engine = Engine::default();
1284d4242001SAdam Bratschi-Kaye let module = Module::new(
1285d4242001SAdam Bratschi-Kaye &engine,
1286d4242001SAdam Bratschi-Kaye r#"
1287d4242001SAdam Bratschi-Kaye (module
1288d4242001SAdam Bratschi-Kaye (memory 1)
1289d4242001SAdam Bratschi-Kaye (data (i32.const 100) "abcd")
1290d4242001SAdam Bratschi-Kaye )
1291d4242001SAdam Bratschi-Kaye "#,
1292d4242001SAdam Bratschi-Kaye )
1293d4242001SAdam Bratschi-Kaye .unwrap();
1294d4242001SAdam Bratschi-Kaye
1295d4242001SAdam Bratschi-Kaye let init = &module.env_module().memory_initialization;
1296d4242001SAdam Bratschi-Kaye assert!(matches!(init, MemoryInitialization::Static { .. }));
1297d4242001SAdam Bratschi-Kaye }
12985566d520SChris Fallin
12995566d520SChris Fallin #[test]
13005566d520SChris Fallin #[cfg_attr(miri, ignore)]
image_range_is_whole_image()13015566d520SChris Fallin fn image_range_is_whole_image() {
13025566d520SChris Fallin let wat = r#"
13035566d520SChris Fallin (module
13045566d520SChris Fallin (memory 1)
13055566d520SChris Fallin (data (i32.const 0) "1234")
13065566d520SChris Fallin (func (export "f") (param i32) (result i32)
13075566d520SChris Fallin local.get 0))
13085566d520SChris Fallin "#;
13095566d520SChris Fallin let engine = Engine::default();
13105566d520SChris Fallin let mut builder = CodeBuilder::new(&engine);
13115566d520SChris Fallin builder.wasm_binary_or_text(wat.as_bytes(), None).unwrap();
13125566d520SChris Fallin let bytes = builder.compile_module_serialized().unwrap();
13135566d520SChris Fallin
13145566d520SChris Fallin let module = unsafe { Module::deserialize(&engine, &bytes).unwrap() };
13155566d520SChris Fallin let image_range = module.image_range();
13165566d520SChris Fallin let len = image_range.end.addr() - image_range.start.addr();
13175566d520SChris Fallin // Length may be strictly greater if it becomes page-aligned.
13185566d520SChris Fallin assert!(len >= bytes.len());
13195566d520SChris Fallin }
1320d4242001SAdam Bratschi-Kaye }
1321