2022-02-09 07:08:40 -06:00
|
|
|
use alloc::format;
|
|
|
|
use wasmi::{
|
|
|
|
Error, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue,
|
|
|
|
Signature, Trap, ValueType,
|
|
|
|
};
|
|
|
|
|
2022-02-12 03:25:02 -06:00
|
|
|
pub struct HostExternals {}
|
2022-02-09 07:08:40 -06:00
|
|
|
|
|
|
|
const ADD_FUNC_INDEX: usize = 0;
|
2022-02-26 07:35:36 -06:00
|
|
|
const SEND_SIGNAL_INDEX: usize = 1;
|
2022-02-09 07:08:40 -06:00
|
|
|
|
|
|
|
impl Externals for HostExternals {
|
|
|
|
fn invoke_index(
|
|
|
|
&mut self,
|
|
|
|
index: usize,
|
|
|
|
args: RuntimeArgs,
|
|
|
|
) -> Result<Option<RuntimeValue>, Trap> {
|
|
|
|
match index {
|
|
|
|
ADD_FUNC_INDEX => {
|
|
|
|
let a: u32 = args.nth_checked(0)?;
|
|
|
|
let b: u32 = args.nth_checked(1)?;
|
|
|
|
let result = a + b;
|
2022-02-12 03:25:02 -06:00
|
|
|
println!("SYSCALL: {} + {} = {}", a, b, result);
|
2022-02-09 07:08:40 -06:00
|
|
|
Ok(Some(RuntimeValue::I32(result as i32)))
|
|
|
|
}
|
2022-02-26 07:35:36 -06:00
|
|
|
SEND_SIGNAL_INDEX => {
|
|
|
|
let pid: u32 = args.nth_checked(0)?;
|
|
|
|
let signal: u32 = args.nth_checked(1)?;
|
|
|
|
|
|
|
|
println!("SYSCALL: send signal {} to pid {}", signal, pid);
|
|
|
|
let ret = RuntimeValue::I32(0);
|
|
|
|
Ok(Some(ret))
|
|
|
|
}
|
2022-02-09 07:08:40 -06:00
|
|
|
_ => panic!("Unimplemented function at {}", index),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl HostExternals {
|
|
|
|
fn check_signature(&self, index: usize, signature: &Signature) -> bool {
|
|
|
|
let (params, ret_ty): (&[ValueType], Option<ValueType>) = match index {
|
|
|
|
ADD_FUNC_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)),
|
2022-02-26 07:35:36 -06:00
|
|
|
SEND_SIGNAL_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)),
|
2022-02-09 07:08:40 -06:00
|
|
|
_ => return false,
|
|
|
|
};
|
|
|
|
signature.params() == params && signature.return_type() == ret_ty
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ModuleImportResolver for HostExternals {
|
|
|
|
fn resolve_func(&self, field_name: &str, signature: &Signature) -> Result<FuncRef, Error> {
|
|
|
|
let index = match field_name {
|
|
|
|
"add" => ADD_FUNC_INDEX,
|
2022-02-26 07:35:36 -06:00
|
|
|
"send_signal" => SEND_SIGNAL_INDEX,
|
2022-02-09 07:08:40 -06:00
|
|
|
_ => {
|
|
|
|
return Err(Error::Instantiation(format!(
|
|
|
|
"Export {} not found",
|
|
|
|
field_name
|
|
|
|
)))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if !self.check_signature(index, signature) {
|
|
|
|
return Err(Error::Instantiation(format!(
|
|
|
|
"Export {} has a bad signature",
|
|
|
|
field_name
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(FuncInstance::alloc_host(
|
|
|
|
Signature::new(&[ValueType::I32, ValueType::I32][..], Some(ValueType::I32)),
|
|
|
|
index,
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|