holey-bytes/hbvm/src/validate.rs

65 lines
2.2 KiB
Rust
Raw Permalink Normal View History

2023-06-24 22:18:31 +00:00
//! Validate if program is sound to execute
2023-06-24 22:16:14 +00:00
/// Program validation error kind
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
2023-06-24 22:16:14 +00:00
/// Unknown opcode
InvalidInstruction,
2023-06-24 22:16:14 +00:00
/// VM doesn't implement this valid opcode
Unimplemented,
2023-06-24 22:16:14 +00:00
/// Attempted to copy over register boundary
RegisterArrayOverflow,
}
2023-06-24 22:16:14 +00:00
/// Error
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Error {
2023-06-24 22:16:14 +00:00
/// Kind
2023-07-07 13:22:03 +00:00
pub kind: ErrorKind,
2023-06-24 22:16:14 +00:00
/// Location in bytecode
pub index: usize,
}
2023-06-24 22:16:14 +00:00
/// Perform bytecode validation. If it passes, the program should be
/// sound to execute.
pub fn validate(mut program: &[u8]) -> Result<(), Error> {
use hbbytecode::opcode::*;
let start = program;
loop {
2023-06-24 22:16:14 +00:00
// Match on instruction types and perform necessary checks
program = match program {
[] => return Ok(()),
[LD..=ST, reg, _, _, _, _, _, _, _, _, _, count, ..]
if usize::from(*reg) * 8 + usize::from(*count) > 2048 =>
{
return Err(Error {
2023-07-07 13:22:03 +00:00
kind: ErrorKind::RegisterArrayOverflow,
index: (program.as_ptr() as usize) - (start.as_ptr() as usize),
})
}
[BRC, src, dst, count, ..]
if src.checked_add(*count).is_none() || dst.checked_add(*count).is_none() =>
{
return Err(Error {
2023-07-07 13:22:03 +00:00
kind: ErrorKind::RegisterArrayOverflow,
index: (program.as_ptr() as usize) - (start.as_ptr() as usize),
})
}
[NOP | ECALL, rest @ ..]
| [DIR | DIRF, _, _, _, _, rest @ ..]
| [ADD..=CMPU | BRC | ADDF..=MULF, _, _, _, rest @ ..]
2023-07-07 13:22:03 +00:00
| [NEG..=NOT | CP..=SWA | NEGF..=FTI, _, _, rest @ ..]
| [LI | JMP, _, _, _, _, _, _, _, _, _, rest @ ..]
| [ADDI..=CMPUI | BMC | JEQ..=JGTU | ADDFI..=MULFI, _, _, _, _, _, _, _, _, _, _, rest @ ..]
| [LD..=ST, _, _, _, _, _, _, _, _, _, _, _, _, rest @ ..] => rest,
_ => {
return Err(Error {
2023-07-07 13:22:03 +00:00
kind: ErrorKind::InvalidInstruction,
index: (program.as_ptr() as usize) - (start.as_ptr() as usize),
})
}
}
}
}