1
0
Fork 0
forked from koniifer/ableos
ableos-framebuffer/hbvm/src/vm/mod.rs

425 lines
17 KiB
Rust
Raw Normal View History

//! HoleyBytes Virtual Machine
//!
//! All unsafe code here should be sound, if input bytecode passes validation.
// # General safety notice:
// - Validation has to assure there is 256 registers (r0 - r255)
// - Instructions have to be valid as specified (values and sizes)
// - Mapped pages should be at least 4 KiB
2023-06-24 17:16:14 -05:00
pub mod mem;
pub mod value;
use {
2023-07-24 11:48:42 -05:00
self::{mem::HandlePageFault, value::ValueVariant},
crate::validate,
2023-07-24 11:48:42 -05:00
core::{cmp::Ordering, ops},
hbbytecode::{OpParam, ParamBB, ParamBBB, ParamBBBB, ParamBBD, ParamBBDH, ParamBBW, ParamBD},
mem::Memory,
value::Value,
};
2023-06-24 17:16:14 -05:00
/// HoleyBytes Virtual Machine
2023-07-11 10:04:48 -05:00
pub struct Vm<'a, PfHandler, const TIMER_QUOTIENT: usize> {
2023-06-24 17:16:14 -05:00
/// Holds 256 registers
///
/// Writing to register 0 is considered undefined behaviour
/// in terms of HoleyBytes program execution
pub registers: [Value; 256],
2023-06-24 17:16:14 -05:00
/// Memory implementation
pub memory: Memory,
2023-06-24 17:16:14 -05:00
/// Trap handler
2023-07-11 10:04:48 -05:00
pub pfhandler: PfHandler,
2023-06-24 17:16:14 -05:00
2023-07-21 19:42:43 -05:00
/// Program counter
2023-07-24 11:48:42 -05:00
pub pc: usize,
2023-06-24 17:16:14 -05:00
/// Program
program: &'a [u8],
2023-07-11 03:29:23 -05:00
2023-07-13 04:05:41 -05:00
/// Cached program length (without unreachable end)
program_len: usize,
2023-07-11 03:29:23 -05:00
/// Program timer
timer: usize,
}
2023-07-11 10:04:48 -05:00
impl<'a, PfHandler: HandlePageFault, const TIMER_QUOTIENT: usize>
Vm<'a, PfHandler, TIMER_QUOTIENT>
{
2023-06-24 17:16:14 -05:00
/// Create a new VM with program and trap handler
///
/// # Safety
/// Program code has to be validated
2023-07-11 10:04:48 -05:00
pub unsafe fn new_unchecked(program: &'a [u8], traph: PfHandler) -> Self {
Self {
registers: [Value::from(0_u64); 256],
memory: Default::default(),
2023-07-11 10:04:48 -05:00
pfhandler: traph,
pc: 0,
2023-07-13 04:05:41 -05:00
program_len: program.len() - 12,
program,
2023-07-11 03:29:23 -05:00
timer: 0,
}
}
2023-06-24 17:16:14 -05:00
/// Create a new VM with program and trap handler only if it passes validation
2023-07-11 10:04:48 -05:00
pub fn new_validated(program: &'a [u8], traph: PfHandler) -> Result<Self, validate::Error> {
validate::validate(program)?;
2023-06-24 17:16:14 -05:00
Ok(unsafe { Self::new_unchecked(program, traph) })
}
2023-06-24 17:16:14 -05:00
/// Execute program
///
/// Program can return [`VmRunError`] if a trap handling failed
2023-07-11 03:29:23 -05:00
pub fn run(&mut self) -> Result<VmRunOk, VmRunError> {
use hbbytecode::opcode::*;
loop {
2023-07-13 04:05:41 -05:00
// Check instruction boundary
if self.pc >= self.program_len {
return Ok(VmRunOk::End);
}
2023-07-11 03:29:23 -05:00
2023-06-24 17:16:14 -05:00
// Big match
//
// Contribution guide:
// - Zero register shall never be overwitten. It's value has to always be 0.
// - Prefer `Self::read_reg` and `Self::write_reg` functions
// - Extract parameters using `param!` macro
// - Prioritise speed over code size
// - Memory is cheap, CPUs not that much
// - Do not heap allocate at any cost
// - Yes, user-provided trap handler may allocate,
// but that is not our »fault«.
// - Unsafe is kinda must, but be sure you have validated everything
// - Your contributions have to pass sanitizers and Miri
// - Strictly follow the spec
// - The spec does not specify how you perform actions, in what order,
// just that the observable effects have to be performed in order and
// correctly.
// - Yes, we assume you run 64 bit CPU. Else ?conradluget a better CPU
// sorry 8 bit fans, HBVM won't run on your Speccy :(
unsafe {
2023-07-13 04:05:41 -05:00
match *self.program.get_unchecked(self.pc) {
UN => {
2023-07-24 11:48:42 -05:00
self.decode::<()>();
2023-07-13 04:05:41 -05:00
return Err(VmRunError::Unreachable);
}
2023-07-24 11:48:42 -05:00
NOP => self.decode::<()>(),
ADD => self.binary_op(u64::wrapping_add),
SUB => self.binary_op(u64::wrapping_sub),
MUL => self.binary_op(u64::wrapping_mul),
AND => self.binary_op::<u64>(ops::BitAnd::bitand),
OR => self.binary_op::<u64>(ops::BitOr::bitor),
XOR => self.binary_op::<u64>(ops::BitXor::bitxor),
SL => self.binary_op(|l, r| u64::wrapping_shl(l, r as u32)),
SR => self.binary_op(|l, r| u64::wrapping_shr(l, r as u32)),
SRS => self.binary_op(|l, r| i64::wrapping_shl(l, r as u32)),
CMP => {
2023-07-21 17:46:30 -05:00
// Compare a0 <=> a1
// < → -1
// > → 1
// = → 0
2023-07-24 11:48:42 -05:00
let ParamBBB(tg, a0, a1) = self.decode();
self.write_reg(
tg,
2023-07-24 11:48:42 -05:00
self.read_reg(a0)
.cast::<i64>()
.cmp(&self.read_reg(a1).cast::<i64>())
as i64,
);
}
CMPU => {
2023-07-21 17:46:30 -05:00
// Unsigned comparsion
2023-07-24 11:48:42 -05:00
let ParamBBB(tg, a0, a1) = self.decode();
self.write_reg(
tg,
2023-07-24 11:48:42 -05:00
self.read_reg(a0)
.cast::<u64>()
.cmp(&self.read_reg(a1).cast::<u64>())
as i64,
);
}
NOT => {
2023-07-21 17:46:30 -05:00
// Logical negation
2023-07-24 11:48:42 -05:00
let ParamBB(tg, a0) = self.decode();
self.write_reg(tg, !self.read_reg(a0).cast::<u64>());
}
NEG => {
2023-07-21 17:46:30 -05:00
// Bitwise negation
2023-07-24 11:48:42 -05:00
let ParamBB(tg, a0) = self.decode();
self.write_reg(
2023-07-24 11:48:42 -05:00
tg,
match self.read_reg(a0).cast::<u64>() {
0 => 1_u64,
_ => 0,
2023-07-07 08:22:03 -05:00
},
);
}
DIR => {
2023-07-21 17:46:30 -05:00
// Fused Division-Remainder
2023-07-24 11:48:42 -05:00
let ParamBBBB(dt, rt, a0, a1) = self.decode();
let a0 = self.read_reg(a0).cast::<u64>();
let a1 = self.read_reg(a1).cast::<u64>();
2023-07-07 08:22:03 -05:00
self.write_reg(dt, a0.checked_div(a1).unwrap_or(u64::MAX));
self.write_reg(rt, a0.checked_rem(a1).unwrap_or(u64::MAX));
}
2023-07-24 11:48:42 -05:00
ADDI => self.binary_op_imm(u64::wrapping_add),
MULI => self.binary_op_imm(u64::wrapping_sub),
ANDI => self.binary_op_imm::<u64>(ops::BitAnd::bitand),
ORI => self.binary_op_imm::<u64>(ops::BitOr::bitor),
XORI => self.binary_op_imm::<u64>(ops::BitXor::bitxor),
SLI => self.binary_op_ims(u64::wrapping_shl),
SRI => self.binary_op_ims(u64::wrapping_shr),
SRSI => self.binary_op_ims(i64::wrapping_shr),
CMPI => {
2023-07-24 11:48:42 -05:00
let ParamBBD(tg, a0, imm) = self.decode();
self.write_reg(
tg,
2023-07-24 11:48:42 -05:00
self.read_reg(a0)
.cast::<i64>()
.cmp(&Value::from(imm).cast::<i64>())
as i64,
);
}
CMPUI => {
2023-07-24 11:48:42 -05:00
let ParamBBD(tg, a0, imm) = self.decode();
self.write_reg(tg, self.read_reg(a0).cast::<u64>().cmp(&imm) as i64);
}
CP => {
2023-07-24 11:48:42 -05:00
let ParamBB(tg, a0) = self.decode();
self.write_reg(tg, self.read_reg(a0));
}
SWA => {
2023-07-21 17:46:30 -05:00
// Swap registers
2023-07-24 11:48:42 -05:00
let ParamBB(r0, r1) = self.decode();
2023-07-21 17:46:30 -05:00
match (r0, r1) {
(0, 0) => (),
(dst, 0) | (0, dst) => self.write_reg(dst, 0_u64),
(r0, r1) => {
core::ptr::swap(
self.registers.get_unchecked_mut(usize::from(r0)),
self.registers.get_unchecked_mut(usize::from(r1)),
);
}
}
}
LI => {
2023-07-24 11:48:42 -05:00
let ParamBD(tg, imm) = self.decode();
self.write_reg(tg, imm);
}
LD => {
2023-07-21 17:46:30 -05:00
// Load. If loading more than register size, continue on adjecent registers
2023-07-24 11:48:42 -05:00
let ParamBBDH(dst, base, off, count) = self.decode();
let n: usize = match dst {
0 => 1,
_ => 0,
};
2023-06-24 17:16:14 -05:00
self.memory.load(
2023-07-24 11:48:42 -05:00
self.read_reg(base).cast::<u64>() + off + n as u64,
2023-06-24 17:16:14 -05:00
self.registers.as_mut_ptr().add(usize::from(dst) + n).cast(),
usize::from(count).saturating_sub(n),
2023-07-11 10:04:48 -05:00
&mut self.pfhandler,
2023-06-24 17:16:14 -05:00
)?;
}
ST => {
2023-07-21 17:46:30 -05:00
// Store. Same rules apply as to LD
2023-07-24 11:48:42 -05:00
let ParamBBDH(dst, base, off, count) = self.decode();
2023-06-24 17:16:14 -05:00
self.memory.store(
2023-07-24 11:48:42 -05:00
self.read_reg(base).cast::<u64>() + off,
2023-06-24 17:16:14 -05:00
self.registers.as_ptr().add(usize::from(dst)).cast(),
count.into(),
2023-07-11 10:04:48 -05:00
&mut self.pfhandler,
2023-06-24 17:16:14 -05:00
)?;
}
BMC => {
2023-07-21 17:46:30 -05:00
// Block memory copy
2023-07-24 11:48:42 -05:00
let ParamBBD(src, dst, count) = self.decode();
2023-06-24 17:16:14 -05:00
self.memory.block_copy(
2023-07-24 11:48:42 -05:00
self.read_reg(src).cast::<u64>(),
self.read_reg(dst).cast::<u64>(),
2023-06-24 17:16:14 -05:00
count as _,
2023-07-11 10:04:48 -05:00
&mut self.pfhandler,
2023-06-24 17:16:14 -05:00
)?;
}
BRC => {
2023-07-21 17:46:30 -05:00
// Block register copy
2023-07-24 11:48:42 -05:00
let ParamBBB(src, dst, count) = self.decode();
core::ptr::copy(
self.registers.get_unchecked(usize::from(src)),
self.registers.get_unchecked_mut(usize::from(dst)),
usize::from(count),
);
}
2023-07-12 05:45:50 -05:00
JAL => {
2023-07-21 17:46:30 -05:00
// Jump and link. Save PC after this instruction to
// specified register and jump to reg + offset.
2023-07-24 11:48:42 -05:00
let ParamBBD(save, reg, offset) = self.decode();
2023-07-12 05:45:50 -05:00
self.write_reg(save, self.pc as u64);
2023-07-24 11:48:42 -05:00
self.pc = (self.read_reg(reg).cast::<u64>() + offset) as usize;
}
2023-07-21 17:46:30 -05:00
// Conditional jumps, jump only to immediates
2023-07-24 11:48:42 -05:00
JEQ => self.cond_jmp::<u64>(Ordering::Equal),
JNE => {
2023-07-24 11:48:42 -05:00
let ParamBBD(a0, a1, jt) = self.decode();
if self.read_reg(a0).cast::<u64>() != self.read_reg(a1).cast::<u64>() {
self.pc = jt as usize;
}
}
2023-07-24 11:48:42 -05:00
JLT => self.cond_jmp::<u64>(Ordering::Less),
JGT => self.cond_jmp::<u64>(Ordering::Greater),
JLTU => self.cond_jmp::<i64>(Ordering::Less),
JGTU => self.cond_jmp::<i64>(Ordering::Greater),
ECALL => {
2023-07-24 11:48:42 -05:00
self.decode::<()>();
2023-07-21 17:46:30 -05:00
// So we don't get timer interrupt after ECALL
if TIMER_QUOTIENT != 0 {
self.timer = self.timer.wrapping_add(1);
}
2023-07-11 10:04:48 -05:00
return Ok(VmRunOk::Ecall);
}
2023-07-24 11:48:42 -05:00
ADDF => self.binary_op::<f64>(ops::Add::add),
SUBF => self.binary_op::<f64>(ops::Sub::sub),
MULF => self.binary_op::<f64>(ops::Mul::mul),
DIRF => {
2023-07-24 11:48:42 -05:00
let ParamBBBB(dt, rt, a0, a1) = self.decode();
let a0 = self.read_reg(a0).cast::<f64>();
let a1 = self.read_reg(a1).cast::<f64>();
2023-07-07 08:22:03 -05:00
self.write_reg(dt, a0 / a1);
self.write_reg(rt, a0 % a1);
}
2023-07-07 08:23:53 -05:00
FMAF => {
2023-07-24 11:48:42 -05:00
let ParamBBBB(dt, a0, a1, a2) = self.decode();
2023-07-07 08:22:03 -05:00
self.write_reg(
dt,
2023-07-24 11:48:42 -05:00
self.read_reg(a0).cast::<f64>() * self.read_reg(a1).cast::<f64>()
+ self.read_reg(a2).cast::<f64>(),
2023-07-07 08:22:03 -05:00
);
}
NEGF => {
2023-07-24 11:48:42 -05:00
let ParamBB(dt, a0) = self.decode();
self.write_reg(dt, -self.read_reg(a0).cast::<f64>());
2023-07-07 08:22:03 -05:00
}
ITF => {
2023-07-24 11:48:42 -05:00
let ParamBB(dt, a0) = self.decode();
self.write_reg(dt, self.read_reg(a0).cast::<i64>() as f64);
2023-07-07 08:22:03 -05:00
}
FTI => {
2023-07-24 11:48:42 -05:00
let ParamBB(dt, a0) = self.decode();
self.write_reg(dt, self.read_reg(a0).cast::<f64>() as i64);
}
2023-07-24 11:48:42 -05:00
ADDFI => self.binary_op_imm::<f64>(ops::Add::add),
MULFI => self.binary_op_imm::<f64>(ops::Mul::mul),
2023-07-11 10:04:48 -05:00
op => return Err(VmRunError::InvalidOpcode(op)),
}
}
2023-07-11 03:32:26 -05:00
if TIMER_QUOTIENT != 0 {
self.timer = self.timer.wrapping_add(1);
if self.timer % TIMER_QUOTIENT == 0 {
return Ok(VmRunOk::Timer);
}
}
}
}
2023-07-24 11:48:42 -05:00
/// Decode instruction operands
#[inline]
unsafe fn decode<T: OpParam>(&mut self) -> T {
let data = self.program.as_ptr().add(self.pc + 1).cast::<T>().read();
self.pc += 1 + core::mem::size_of::<T>();
data
}
/// Perform binary operating over two registers
#[inline]
unsafe fn binary_op<T: ValueVariant>(&mut self, op: impl Fn(T, T) -> T) {
let ParamBBB(tg, a0, a1) = self.decode();
self.write_reg(
tg,
op(self.read_reg(a0).cast::<T>(), self.read_reg(a1).cast::<T>()),
);
}
/// Perform binary operation over register and immediate
#[inline]
unsafe fn binary_op_imm<T: ValueVariant>(&mut self, op: impl Fn(T, T) -> T) {
let ParamBBD(tg, reg, imm) = self.decode();
self.write_reg(
tg,
op(self.read_reg(reg).cast::<T>(), Value::from(imm).cast::<T>()),
);
}
/// Perform binary operation over register and shift immediate
#[inline]
unsafe fn binary_op_ims<T: ValueVariant>(&mut self, op: impl Fn(T, u32) -> T) {
let ParamBBW(tg, reg, imm) = self.decode();
self.write_reg(tg, op(self.read_reg(reg).cast::<T>(), imm));
}
/// Jump at `#3` if ordering on `#0 <=> #1` is equal to expected
#[inline]
unsafe fn cond_jmp<T: ValueVariant + Ord>(&mut self, expected: Ordering) {
let ParamBBD(a0, a1, ja) = self.decode();
if self
.read_reg(a0)
.cast::<T>()
.cmp(&self.read_reg(a1).cast::<T>())
== expected
{
self.pc = ja as usize;
}
}
2023-06-24 17:16:14 -05:00
/// Read register
#[inline]
unsafe fn read_reg(&self, n: u8) -> Value {
2023-06-24 17:16:14 -05:00
*self.registers.get_unchecked(n as usize)
}
2023-06-24 17:16:14 -05:00
/// Write a register.
/// Writing to register 0 is no-op.
#[inline]
2023-07-07 08:22:03 -05:00
unsafe fn write_reg(&mut self, n: u8, value: impl Into<Value>) {
if n != 0 {
2023-07-07 08:22:03 -05:00
*self.registers.get_unchecked_mut(n as usize) = value.into();
}
}
}
2023-06-24 17:16:14 -05:00
/// Virtual machine halt error
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
2023-06-24 17:16:14 -05:00
pub enum VmRunError {
2023-07-11 10:04:48 -05:00
/// Tried to execute invalid instruction
InvalidOpcode(u8),
2023-06-24 17:16:14 -05:00
/// Unhandled load access exception
2023-06-24 17:28:20 -05:00
LoadAccessEx(u64),
2023-06-24 17:16:14 -05:00
/// Unhandled store access exception
2023-06-24 17:28:20 -05:00
StoreAccessEx(u64),
2023-07-13 04:05:41 -05:00
/// Reached unreachable code
Unreachable,
}
2023-07-11 03:29:23 -05:00
/// Virtual machine halt ok
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum VmRunOk {
2023-07-11 03:33:55 -05:00
/// Program has eached its end
2023-07-11 03:29:23 -05:00
End,
2023-07-11 03:33:55 -05:00
/// Program was interrupted by a timer
2023-07-11 03:29:23 -05:00
Timer,
2023-07-11 10:04:48 -05:00
/// Environment call
Ecall,
2023-07-11 03:29:23 -05:00
}