pub struct Module { /* private fields */ }
Expand description

A compiled WebAssembly module, ready to be instantiated.

A Module is a compiled in-memory representation of an input WebAssembly binary. A Module is then used to create an Instance through an instantiation process. You cannot call functions or fetch globals, for example, on a Module because it’s purely a code representation. Instead you’ll need to create an Instance to interact with the wasm module.

Creating a Module currently involves compiling code, meaning that it can be an expensive operation. All Module instances are compiled according to the configuration in Config, but typically they’re JIT-compiled. If you’d like to instantiate a module multiple times you can do so with compiling the original wasm module only once with a single Module instance.

The Module is thread-safe and safe to share across threads.

Modules and Clone

Using clone on a Module is a cheap operation. It will not create an entirely new module, but rather just a new reference to the existing module. In other words it’s a shallow copy, not a deep copy.

Examples

There are a number of ways you can create a Module, for example pulling the bytes from a number of locations. One example is loading a module from the filesystem:

let engine = Engine::default();
let module = Module::from_file(&engine, "path/to/foo.wasm")?;

You can also load the wasm text format if more convenient too:

let engine = Engine::default();
// Now we're using the WebAssembly text extension: `.wat`!
let module = Module::from_file(&engine, "path/to/foo.wat")?;

And if you’ve already got the bytes in-memory you can use the [Module::new] constructor:

let engine = Engine::default();
let module = Module::new(&engine, &wasm_bytes)?;

// It also works with the text format!
let module = Module::new(&engine, "(module (func))")?;

Implementations

Deserializes an in-memory compiled module previously created with [Module::serialize] or [Engine::precompile_module].

This function will deserialize the binary blobs emitted by [Module::serialize] and [Engine::precompile_module] back into an in-memory Module that’s ready to be instantiated.

Note that the Module::deserialize_file method is more optimized than this function, so if the serialized module is already present in a file it’s recommended to use that method instead.

Unsafety

This function is marked as unsafe because if fed invalid input or used improperly this could lead to memory safety vulnerabilities. This method should not, for example, be exposed to arbitrary user input.

The structure of the binary blob read here is only lightly validated internally in wasmtime. This is intended to be an efficient “rehydration” for a Module which has very few runtime checks beyond deserialization. Arbitrary input could, for example, replace valid compiled code with any other valid compiled code, meaning that this can trivially be used to execute arbitrary code otherwise.

For these reasons this function is unsafe. This function is only designed to receive the previous input from [Module::serialize] and [Engine::precompile_module]. If the exact output of those functions (unmodified) is passed to this function then calls to this function can be considered safe. It is the caller’s responsibility to provide the guarantee that only previously-serialized bytes are being passed in here.

Note that this function is designed to be safe receiving output from any compiled version of wasmtime itself. This means that it is safe to feed output from older versions of Wasmtime into this function, in addition to newer versions of wasmtime (from the future!). These inputs will deterministically and safely produce an Err. This function only successfully accepts inputs from the same version of wasmtime, but the safety guarantee only applies to externally-defined blobs of bytes, not those defined by any version of wasmtime. (this means that if you cache blobs across versions of wasmtime you can be safely guaranteed that future versions of wasmtime will reject old cache entries).

Same as deserialize, except that the contents of path are read to deserialize into a Module.

For more information see the documentation of the deserialize method for why this function is unsafe.

This method is provided because it can be faster than deserialize since the data doesn’t need to be copied around, but rather the module can be used directly from an mmap’d view of the file provided.

Validates binary input data as a WebAssembly binary given the configuration in engine.

This function will perform a speedy validation of the binary input WebAssembly module (which is in binary form, the text format is not accepted by this function) and return either Ok or Err depending on the results of validation. The engine argument indicates configuration for WebAssembly features, for example, which are used to indicate what should be valid and what shouldn’t be.

Validation automatically happens as part of [Module::new].

Errors

If validation fails for any reason (type check error, usage of a feature that wasn’t enabled, etc) then an error with a description of the validation issue will be returned.

Returns the type signature of this module.

Returns identifier/name that this Module has. This name is used in traps/backtrace details.

Note that most LLVM/clang/Rust-produced modules do not have a name associated with them, but other wasm tooling can be used to inject or add a name.

Examples
let module = Module::new(&engine, "(module $foo)")?;
assert_eq!(module.name(), Some("foo"));

let module = Module::new(&engine, "(module)")?;
assert_eq!(module.name(), None);

let module = Module::new_with_name(&engine, "(module)", "bar")?;
assert_eq!(module.name(), Some("bar"));

Returns the list of imports that this Module has and must be satisfied.

This function returns the list of imports that the wasm module has, but only the types of each import. The type of each import is used to typecheck the Instance::new method’s imports argument. The arguments to that function must match up 1-to-1 with the entries in the array returned here.

The imports returned reflect the order of the imports in the wasm module itself, and note that no form of deduplication happens.

Examples

Modules with no imports return an empty list here:

let module = Module::new(&engine, "(module)")?;
assert_eq!(module.imports().len(), 0);

and modules with imports will have a non-empty list:

let wat = r#"
    (module
        (import "host" "foo" (func))
    )
"#;
let module = Module::new(&engine, wat)?;
assert_eq!(module.imports().len(), 1);
let import = module.imports().next().unwrap();
assert_eq!(import.module(), "host");
assert_eq!(import.name(), Some("foo"));
match import.ty() {
    ExternType::Func(_) => { /* ... */ }
    _ => panic!("unexpected import type!"),
}

Returns the list of exports that this Module has and will be available after instantiation.

This function will return the type of each item that will be returned from Instance::exports. Each entry in this list corresponds 1-to-1 with that list, and the entries here will indicate the name of the export along with the type of the export.

Examples

Modules might not have any exports:

let module = Module::new(&engine, "(module)")?;
assert!(module.exports().next().is_none());

When the exports are not empty, you can inspect each export:

let wat = r#"
    (module
        (func (export "foo"))
        (memory (export "memory") 1)
    )
"#;
let module = Module::new(&engine, wat)?;
assert_eq!(module.exports().len(), 2);

let mut exports = module.exports();
let foo = exports.next().unwrap();
assert_eq!(foo.name(), "foo");
match foo.ty() {
    ExternType::Func(_) => { /* ... */ }
    _ => panic!("unexpected export type!"),
}

let memory = exports.next().unwrap();
assert_eq!(memory.name(), "memory");
match memory.ty() {
    ExternType::Memory(_) => { /* ... */ }
    _ => panic!("unexpected export type!"),
}

Looks up an export in this Module by name.

This function will return the type of an export with the given name.

Examples

There may be no export with that name:

let module = Module::new(&engine, "(module)")?;
assert!(module.get_export("foo").is_none());

When there is an export with that name, it is returned:

let wat = r#"
    (module
        (func (export "foo"))
        (memory (export "memory") 1)
    )
"#;
let module = Module::new(&engine, wat)?;
let foo = module.get_export("foo");
assert!(foo.is_some());

let foo = foo.unwrap();
match foo {
    ExternType::Func(_) => { /* ... */ }
    _ => panic!("unexpected export type!"),
}

Returns the Engine that this Module was compiled by.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more