1 //! Running pre-compiled Wasm programs.
2 
3 use wasmtime::{Config, Engine, Instance, Module, Result, Store};
4 
main() -> Result<()>5 fn main() -> Result<()> {
6     // Create the default configuration for this host platform. Note that this
7     // configuration must match the configuration used to pre-compile the Wasm
8     // program. We cannot run Wasm programs pre-compiled for configurations that
9     // do not match our own, therefore if you enabled or disabled any particular
10     // Wasm proposals or tweaked memory knobs when pre-compiling, you should
11     // make identical adjustments to this config.
12     let config = Config::default();
13 
14     // Create an `Engine` with that configuration.
15     let engine = Engine::new(&config)?;
16 
17     // Create a runtime `Module` from a Wasm program that was pre-compiled and
18     // written to the `add.cwasm` file by `wasmtime/examples/pre_compile.rs`.
19     //
20     // **Warning:** Wasmtime does not (and in general cannot) fully validate
21     // pre-compiled modules for safety -- only create `Module`s and `Component`s
22     // from pre-compiled bytes you control and trust! Passing unknown or
23     // untrusted bytes will lead to arbitrary code execution vulnerabilities in
24     // your system!
25     let module = match unsafe { Module::deserialize_file(&engine, "add.cwasm") } {
26         Ok(module) => module,
27         Err(error) => {
28             println!("failed to deserialize pre-compiled module: {error:?}");
29             return Ok(());
30         }
31     };
32 
33     // Instantiate the module and invoke its `add` function!
34     let mut store = Store::new(&engine, ());
35     let instance = Instance::new(&mut store, &module, &[])?;
36     let add = instance.get_typed_func::<(i32, i32), i32>(&mut store, "add")?;
37     let sum = add.call(&mut store, (3, 8))?;
38     println!("the sum of 3 and 8 is {sum}");
39 
40     Ok(())
41 }
42