2019-10-24 13:43:00 +00:00
|
|
|
use crate::{print, println};
|
2019-10-24 14:43:38 +00:00
|
|
|
use wasmi::{
|
|
|
|
Error as InterpreterError, Externals, FuncInstance, FuncRef, ImportsBuilder,
|
|
|
|
ModuleImportResolver, ModuleInstance, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType,
|
|
|
|
};
|
2019-10-24 13:43:00 +00:00
|
|
|
|
2019-10-24 14:02:28 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
use crate::{serial_print, serial_println};
|
|
|
|
|
|
|
|
mod hack;
|
|
|
|
|
2019-10-24 13:43:00 +00:00
|
|
|
pub fn run() {
|
|
|
|
use alloc::vec::Vec;
|
|
|
|
|
|
|
|
let bytes = include_bytes!("../../data/h.wasm");
|
|
|
|
let b: Vec<u8> = bytes.iter().cloned().collect();
|
2019-10-24 14:21:48 +00:00
|
|
|
println!("[ ] loaded wasm into a Vec");
|
2019-10-24 13:43:00 +00:00
|
|
|
|
|
|
|
let module = wasmi::Module::from_buffer(&b).unwrap();
|
|
|
|
let mut imports = ImportsBuilder::new();
|
|
|
|
imports.push_resolver("h", &H);
|
|
|
|
|
|
|
|
let instance = ModuleInstance::new(&module, &imports)
|
|
|
|
.expect("failed to load wasm module")
|
|
|
|
.assert_no_start();
|
|
|
|
|
2019-10-24 14:21:48 +00:00
|
|
|
println!("[ ] invoking export");
|
2019-10-24 13:43:00 +00:00
|
|
|
let _ = instance.invoke_export("h", &[], &mut H);
|
|
|
|
}
|
|
|
|
|
2019-10-24 14:02:28 +00:00
|
|
|
#[test_case]
|
|
|
|
fn test_wasm() {
|
|
|
|
serial_print!("running h example... ");
|
|
|
|
run();
|
|
|
|
serial_println!("[ok]");
|
|
|
|
}
|
|
|
|
|
2019-10-24 13:43:00 +00:00
|
|
|
struct H;
|
|
|
|
const H_FUNC: usize = 0;
|
|
|
|
|
|
|
|
impl Externals for H {
|
|
|
|
fn invoke_index(
|
|
|
|
&mut self,
|
|
|
|
index: usize,
|
|
|
|
args: RuntimeArgs,
|
|
|
|
) -> Result<Option<RuntimeValue>, Trap> {
|
|
|
|
use core::char::from_u32;
|
|
|
|
match index {
|
|
|
|
H_FUNC => {
|
|
|
|
let ch_t: i32 = args.nth(0);
|
|
|
|
let ch = from_u32(ch_t as u32);
|
|
|
|
print!("{}", ch.unwrap());
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
_ => panic!("unknown function called"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ModuleImportResolver for H {
|
|
|
|
fn resolve_func(
|
|
|
|
&self,
|
|
|
|
field_name: &str,
|
|
|
|
_signature: &Signature,
|
|
|
|
) -> Result<FuncRef, InterpreterError> {
|
|
|
|
let func_ref = match field_name {
|
2019-10-24 14:43:38 +00:00
|
|
|
"h" => FuncInstance::alloc_host(Signature::new(&[ValueType::I32][..], None), H_FUNC),
|
2019-10-24 13:43:00 +00:00
|
|
|
_ => panic!("unknwon function asked for"),
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(func_ref)
|
|
|
|
}
|
|
|
|
}
|