feature/trap-handlers
ondra05 2023-06-22 11:37:48 +02:00
parent 8ab55e801f
commit 1caacf8dfd
No known key found for this signature in database
GPG Key ID: 0DA6D2BB2285E881
3 changed files with 24 additions and 7 deletions

View File

@ -1,3 +1,5 @@
use hbvm::vm::trap::HandleTrap;
use {
hbvm::{validate::validate, vm::Vm},
std::io::{stdin, Read},
@ -6,13 +8,13 @@ use {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut prog = vec![];
stdin().read_to_end(&mut prog)?;
if let Err(e) = validate(&prog) {
eprintln!("Program validation error: {e:?}");
return Ok(());
} else {
unsafe {
let mut vm = Vm::new_unchecked(&prog);
let mut vm = Vm::new_unchecked(&prog, TestTrapHandler);
vm.memory.insert_test_page();
println!("Program interrupt: {:?}", vm.run());
println!("{:?}", vm.registers);
@ -24,3 +26,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
pub fn time() -> u32 {
9
}
struct TestTrapHandler;
impl HandleTrap for TestTrapHandler {
#[inline]
fn page_fault(&mut self) {}
}

View File

@ -11,6 +11,10 @@
// program size. If you are (rightfully) worried about the UB, for now just
// append your program with 11 zeroes.
use self::trap::HandleTrap;
pub mod trap;
mod mem;
mod value;
@ -72,28 +76,30 @@ macro_rules! cond_jump {
}};
}
pub struct Vm<'a> {
pub struct Vm<'a, T> {
pub registers: [Value; 256],
pub memory: Memory,
pub traph: T,
pc: usize,
program: &'a [u8],
}
impl<'a> Vm<'a> {
impl<'a, T: HandleTrap> Vm<'a, T> {
/// # Safety
/// Program code has to be validated
pub unsafe fn new_unchecked(program: &'a [u8]) -> Self {
pub unsafe fn new_unchecked(program: &'a [u8], traph: T) -> Self {
Self {
registers: [Value::from(0_u64); 256],
memory: Default::default(),
traph,
pc: 0,
program,
}
}
pub fn new_validated(program: &'a [u8]) -> Result<Self, validate::Error> {
pub fn new_validated(program: &'a [u8], traph: T) -> Result<Self, validate::Error> {
validate::validate(program)?;
Ok(unsafe { Self::new_unchecked(program) })
Ok(unsafe { Self::new_unchecked(program, traph) })
}
pub fn run(&mut self) -> HaltReason {

3
hbvm/src/vm/trap.rs Normal file
View File

@ -0,0 +1,3 @@
pub trait HandleTrap {
fn page_fault(&mut self) {}
}