81 lines
2.1 KiB
Rust
Raw Normal View History

2019-01-10 22:59:57 -05:00
use wabt::wat2wasm;
use wasmer_clif_backend::CraneliftCompiler;
2019-01-28 11:55:44 -08:00
use wasmer_runtime_core::{
error::Result,
global::Global,
memory::Memory,
prelude::*,
2019-01-29 10:16:39 -08:00
table::Table,
2019-01-29 13:04:42 -08:00
types::{ElementType, MemoryDescriptor, TableDescriptor, Value},
2019-01-29 15:44:15 -08:00
units::Pages,
2019-01-28 11:55:44 -08:00
};
static EXAMPLE_WASM: &'static [u8] = include_bytes!("simple.wasm");
fn main() -> Result<()> {
2019-01-10 22:59:57 -05:00
let wasm_binary = wat2wasm(IMPORT_MODULE.as_bytes()).expect("WAST not valid or malformed");
let inner_module = wasmer_runtime_core::compile_with(&wasm_binary, &CraneliftCompiler::new())?;
2019-01-08 21:57:28 -05:00
2019-02-04 23:07:58 -08:00
let memory = Memory::new(MemoryDescriptor {
2019-01-29 15:44:15 -08:00
minimum: Pages(1),
maximum: Some(Pages(1)),
shared: false,
2019-01-28 11:55:44 -08:00
})
.unwrap();
let global = Global::new(Value::I32(42));
2019-01-29 13:04:42 -08:00
let table = Table::new(TableDescriptor {
element: ElementType::Anyfunc,
2019-01-29 15:44:15 -08:00
minimum: 10,
maximum: None,
2019-01-29 10:16:39 -08:00
})
.unwrap();
2019-02-04 15:07:32 -08:00
memory.access_mut()[0] = 42;
2019-01-21 16:24:49 -08:00
let import_object = imports! {
"env" => {
"print_num" => func!(print_num),
"memory" => memory,
2019-01-28 11:55:44 -08:00
"global" => global,
2019-01-29 10:16:39 -08:00
"table" => table,
2019-01-21 16:24:49 -08:00
},
};
2019-02-04 15:07:32 -08:00
let inner_instance = inner_module.instantiate(&import_object)?;
2019-01-21 16:24:49 -08:00
let outer_imports = imports! {
"env" => inner_instance,
};
2019-01-12 22:02:19 -05:00
let outer_module = wasmer_runtime_core::compile_with(EXAMPLE_WASM, &CraneliftCompiler::new())?;
2019-02-04 15:07:32 -08:00
let outer_instance = outer_module.instantiate(&outer_imports)?;
2019-01-10 22:59:57 -05:00
let ret = outer_instance.call("main", &[Value::I32(42)])?;
println!("ret: {:?}", ret);
2019-01-08 21:57:28 -05:00
Ok(())
}
2019-02-04 15:07:32 -08:00
fn print_num(n: i32, ctx: &mut vm::Ctx) -> i32 {
2019-01-08 21:57:28 -05:00
println!("print_num({})", n);
2019-01-29 12:12:37 -08:00
2019-02-04 15:07:32 -08:00
let memory: &Memory = ctx.memory(0);
2019-01-29 12:12:37 -08:00
2019-02-04 15:07:32 -08:00
let a = memory.access()[0] as i32;
2019-01-29 12:12:37 -08:00
a + n + 1
2019-01-08 21:57:28 -05:00
}
2019-01-10 22:59:57 -05:00
static IMPORT_MODULE: &str = r#"
(module
(type $t0 (func (param i32) (result i32)))
(import "env" "memory" (memory 1 1))
2019-01-29 10:16:39 -08:00
(import "env" "table" (table 10 anyfunc))
2019-01-28 11:55:44 -08:00
(import "env" "global" (global i32))
2019-01-10 22:59:57 -05:00
(import "env" "print_i32" (func $print_i32 (type $t0)))
(func $print_num (export "print_num") (type $t0) (param $p0 i32) (result i32)
2019-01-28 11:55:44 -08:00
get_global 0
2019-01-10 22:59:57 -05:00
call $print_i32))
"#;