1
0
Fork 0
forked from koniifer/ableos

Added convenience macro for defining host externals

This commit is contained in:
Erin 2022-05-10 18:41:45 +02:00 committed by ondra05
parent 86f466cdb0
commit 0775577d31

View file

@ -4,63 +4,134 @@ use wasmi::{
Signature, Trap, ValueType, Signature, Trap, ValueType,
}; };
const ADD_FUNC_INDEX: usize = 0; macro_rules! wasmi_type {
const GET_TIME_INDEX: usize = 2; (bool) => {
const GET_RANDOM_INDEX: usize = 3; ValueType::I32
const GET_INPUT_INDEX: usize = 4; };
const PRINT_CHAR: usize = 6; (u8) => {
const SEND_SIGNAL_INDEX: usize = 1; ValueType::I32
};
(u16) => {
ValueType::I32
};
(u32) => {
ValueType::I32
};
(u64) => {
ValueType::I64
};
(i8) => {
ValueType::I32
};
(i16) => {
ValueType::I32
};
(i32) => {
ValueType::I32
};
(i64) => {
ValueType::I64
};
(f32) => {
ValueType::F32
};
(f64) => {
ValueType::F64
};
}
pub struct HostExternals; macro_rules! wasmi_return_type {
impl HostExternals { () => {
fn check_signature(&self, index: usize, signature: &Signature) -> bool { None
let (params, ret_ty): (&[_], _) = match index { };
ADD_FUNC_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)), ($type: ident) => {
SEND_SIGNAL_INDEX => (&[ValueType::I32, ValueType::I32], Some(ValueType::I32)), Some(wasmi_type!($type))
GET_TIME_INDEX => (&[], Some(ValueType::I32)), };
GET_RANDOM_INDEX => (&[], Some(ValueType::I32)), }
GET_INPUT_INDEX => (&[], Some(ValueType::I32)),
PRINT_CHAR => (&[ValueType::I32], None), macro_rules! host_externals {
_ => return false, (
$($index: literal: $name: ident ($($arg_name: ident: $arg_type: ident),* $(,)?) $(-> $return_type: ident)? $block: block)*
) => {
pub struct HostExternals;
impl Externals for HostExternals {
fn invoke_index(
&mut self,
index: usize,
args: RuntimeArgs
) -> Result<Option<RuntimeValue>, Trap> {
match index {
$(
$index => match args.as_ref() {
[$($arg_name),*] => {
$(
let $arg_name: $arg_type = (*$arg_name)
.try_into()
.ok_or(wasmi::TrapKind::UnexpectedSignature)?;
)*
$block
},
_ => return Err(wasmi::TrapKind::UnexpectedSignature.into()),
}
),*
_ => {
error!("Unimplemented function at {index}");
Err(Trap::new(wasmi::TrapKind::Unreachable))
}
}
}
}
impl ModuleImportResolver for HostExternals {
fn resolve_func(&self, field_name: &str, signature: &Signature) -> Result<FuncRef, Error> {
let (index, param_types, return_type): (usize, &[ValueType], Option<ValueType>) =
match field_name {
$(
stringify!($name) => (
$index,
&[$(wasmi_type!($arg_type)),*],
wasmi_return_type!($($return_type)?),
),
)*
_ => {
return Err(Error::Instantiation(format!(
"Export {field_name} not found",
)));
},
}; };
if params.len() != signature.params().len() || ret_ty != signature.return_type() { if !(param_types.len() != signature.params().len() || return_type != signature.return_type())
false && param_types
} else {
params
.iter() .iter()
.zip(signature.params()) .zip(signature.params())
.find(|(ty, param)| ty != param) .find(|(ty, param)| ty != param)
.is_none() .is_none()
{
trace!("Resolved export {field_name} at func {index}");
Ok(FuncInstance::alloc_host(signature.clone(), index))
} else {
Err(Error::Instantiation(format!(
"Export {field_name} has a bad signature {signature:?}",
)))
} }
} }
}
};
} }
impl Externals for HostExternals { host_externals! {
fn invoke_index( 0: add(a: u32, b: u32) -> u32 {
&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; let result = a + b;
trace!("SYSCALL: {} + {} = {}", a, b, result); trace!("SYSCALL: {} + {} = {}", a, b, result);
Ok(Some(RuntimeValue::I32(result as i32))) Ok(Some(result.into()))
} }
SEND_SIGNAL_INDEX => { 1: send_signal(pid: u32, signal: u32) -> i32 {
let pid: u32 = args.nth_checked(0)?;
let signal: u32 = args.nth_checked(1)?;
trace!("SYSCALL: send signal {} to pid {}", signal, pid); trace!("SYSCALL: send signal {} to pid {}", signal, pid);
let ret = RuntimeValue::I32(0); Ok(Some(0.into()))
Ok(Some(ret))
} }
GET_TIME_INDEX => { 2: get_time() -> u32 {
use core::sync::atomic::Ordering::*; use core::sync::atomic::Ordering::*;
trace!("SYSCALL: get time"); trace!("SYSCALL: get time");
@ -68,71 +139,30 @@ impl Externals for HostExternals {
let tick_time = kernel::TICK.load(Relaxed); let tick_time = kernel::TICK.load(Relaxed);
x86_64::instructions::interrupts::enable(); x86_64::instructions::interrupts::enable();
let ret = RuntimeValue::I32(tick_time.try_into().unwrap()); let ret: u32 = tick_time.try_into().unwrap();
Ok(Some(ret)) Ok(Some(ret.into()))
} }
GET_RANDOM_INDEX => { 3: get_random() -> i32 {
trace!("SYSCALL: get random"); trace!("SYSCALL: get random");
let rand = generate_process_pass(); let rand = generate_process_pass() as i32;
Ok(Some(rand.into()))
let ret = RuntimeValue::I32(rand as i32);
// let ret = RuntimeValue::I32(rand.try_into().unwrap());
Ok(Some(ret))
} }
GET_INPUT_INDEX => { 4: get_input() -> i32 {
let input = None; let input = None;
x86_64::instructions::interrupts::without_interrupts(|| KEYBUFF.lock().pop()); x86_64::instructions::interrupts::without_interrupts(|| KEYBUFF.lock().pop());
if let Some(chr) = input { if let Some(chr) = input {
trace!("SYSCALL: input: {}", chr); trace!("SYSCALL: input: {}", chr);
} }
let ret = RuntimeValue::I32(input.unwrap_or(0x00 as char) as i32); let ret = input.unwrap_or(0x00 as char) as i32;
Ok(Some(ret.into()))
Ok(Some(ret))
} }
PRINT_CHAR => { 5: print_char(chr: u8) {
let chr: u8 = args.nth_checked(0)?;
trace!("SYSCALL: print: {}", chr); trace!("SYSCALL: print: {}", chr);
print!("{}", char::from(chr)); print!("{}", char::from(chr));
Ok(None) Ok(None)
} }
_ => {
error!("Unimplemented function at {}", index);
Err(Trap::new(wasmi::TrapKind::Unreachable))
}
}
}
}
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,
"send_signal" => SEND_SIGNAL_INDEX,
"get_time" => GET_TIME_INDEX,
"get_random" => GET_RANDOM_INDEX,
"get_input" => GET_INPUT_INDEX,
"print_char" => PRINT_CHAR,
_ => {
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, signature
)));
}
trace!("Resolved export {} as func {}", field_name, index);
Ok(FuncInstance::alloc_host(signature.clone(), index))
}
} }