dev/vm-improvements (#3)

Co-authored-by: Nilton Constantino <nilton.constantino@visma.com>
Reviewed-on: #3
This commit is contained in:
2026-03-24 13:40:19 +00:00
co-authored by Nilton Constantino
parent 78485b194c
commit c8a0444d8e
24 changed files with 1477 additions and 194 deletions
+29
View File
@@ -0,0 +1,29 @@
use crate::opcode::OpCode;
pub fn operand_size(opcode: OpCode) -> usize {
match opcode {
OpCode::PushConst => 4,
OpCode::PushI32 => 4,
OpCode::PushI64 => 8,
OpCode::PushF64 => 8,
OpCode::PushBool => 1,
OpCode::PopN => 4,
OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue => 4,
OpCode::GetGlobal | OpCode::SetGlobal => 4,
OpCode::GetLocal | OpCode::SetLocal => 4,
OpCode::Call => 8, // addr(u32) + args_count(u32)
OpCode::Syscall => 4,
_ => 0,
}
}
pub fn is_jump(opcode: OpCode) -> bool {
match opcode {
OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue => true,
_ => false,
}
}
pub fn has_immediate(opcode: OpCode) -> bool {
operand_size(opcode) > 0
}
+69
View File
@@ -0,0 +1,69 @@
use crate::opcode::OpCode;
use crate::readwrite::*;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub enum Operand {
U32(u32),
I32(i32),
I64(i64),
F64(f64),
Bool(bool),
Label(String),
}
#[derive(Debug, Clone)]
pub enum Asm {
Op(OpCode, Vec<Operand>),
Label(String),
}
pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
let mut labels = HashMap::new();
let mut current_pc = 0u32;
// First pass: resolve labels
for instr in instructions {
match instr {
Asm::Label(name) => {
labels.insert(name.clone(), current_pc);
}
Asm::Op(_opcode, operands) => {
current_pc += 2; // OpCode is u16 (2 bytes)
for operand in operands {
match operand {
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) => current_pc += 4,
Operand::I64(_) | Operand::F64(_) => current_pc += 8,
Operand::Bool(_) => current_pc += 1,
}
}
}
}
}
// Second pass: generate bytes
let mut rom = Vec::new();
for instr in instructions {
match instr {
Asm::Label(_) => {}
Asm::Op(opcode, operands) => {
write_u16_le(&mut rom, *opcode as u16).map_err(|e| e.to_string())?;
for operand in operands {
match operand {
Operand::U32(v) => write_u32_le(&mut rom, *v).map_err(|e| e.to_string())?,
Operand::I32(v) => write_u32_le(&mut rom, *v as u32).map_err(|e| e.to_string())?,
Operand::I64(v) => write_i64_le(&mut rom, *v).map_err(|e| e.to_string())?,
Operand::F64(v) => write_f64_le(&mut rom, *v).map_err(|e| e.to_string())?,
Operand::Bool(v) => rom.push(if *v { 1 } else { 0 }),
Operand::Label(name) => {
let addr = labels.get(name).ok_or(format!("Undefined label: {}", name))?;
write_u32_le(&mut rom, *addr).map_err(|e| e.to_string())?;
}
}
}
}
}
}
Ok(rom)
}
+64
View File
@@ -0,0 +1,64 @@
use crate::opcode::OpCode;
use crate::readwrite::*;
use std::io::{Cursor, Read};
#[derive(Debug, Clone)]
pub struct Instr {
pub pc: u32,
pub opcode: OpCode,
pub operands: Vec<DisasmOperand>,
}
#[derive(Debug, Clone)]
pub enum DisasmOperand {
U32(u32),
I32(i32),
I64(i64),
F64(f64),
Bool(bool),
}
pub fn disasm(rom: &[u8]) -> Result<Vec<Instr>, String> {
let mut instructions = Vec::new();
let mut cursor = Cursor::new(rom);
while (cursor.position() as usize) < rom.len() {
let pc = cursor.position() as u32;
let op_val = read_u16_le(&mut cursor).map_err(|e| e.to_string())?;
let opcode = OpCode::try_from(op_val)?;
let mut operands = Vec::new();
match opcode {
OpCode::PushConst | OpCode::PushI32 | OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue
| OpCode::GetGlobal | OpCode::SetGlobal | OpCode::GetLocal | OpCode::SetLocal
| OpCode::PopN | OpCode::Syscall => {
let v = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::U32(v));
}
OpCode::PushI64 => {
let v = read_i64_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::I64(v));
}
OpCode::PushF64 => {
let v = read_f64_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::F64(v));
}
OpCode::PushBool => {
let mut b_buf = [0u8; 1];
cursor.read_exact(&mut b_buf).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::Bool(b_buf[0] != 0));
}
OpCode::Call => {
let addr = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
let args = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::U32(addr));
operands.push(DisasmOperand::U32(args));
}
_ => {}
}
instructions.push(Instr { pc, opcode, operands });
}
Ok(instructions)
}
+51
View File
@@ -0,0 +1,51 @@
pub mod opcode;
pub mod abi;
pub mod pbc;
pub mod readwrite;
pub mod asm;
pub mod disasm;
#[cfg(test)]
mod tests {
use crate::opcode::OpCode;
use crate::asm::{self, Asm, Operand};
use crate::pbc::{self, PbcFile, ConstantPoolEntry};
use crate::disasm;
#[test]
fn test_golden_abi_roundtrip() {
// 1. Create a simple assembly program: PushI32 42; Halt
let instructions = vec![
Asm::Op(OpCode::PushI32, vec![Operand::I32(42)]),
Asm::Op(OpCode::Halt, vec![]),
];
let rom = asm::assemble(&instructions).expect("Failed to assemble");
// 2. Create a PBC file
let pbc_file = PbcFile {
cp: vec![ConstantPoolEntry::Int32(100)], // Random CP entry
rom,
};
let bytes = pbc::write_pbc(&pbc_file).expect("Failed to write PBC");
// 3. Parse it back
let parsed_pbc = pbc::parse_pbc(&bytes).expect("Failed to parse PBC");
assert_eq!(parsed_pbc.cp, pbc_file.cp);
assert_eq!(parsed_pbc.rom, pbc_file.rom);
// 4. Disassemble ROM
let dis_instrs = disasm::disasm(&parsed_pbc.rom).expect("Failed to disassemble");
assert_eq!(dis_instrs.len(), 2);
assert_eq!(dis_instrs[0].opcode, OpCode::PushI32);
if let disasm::DisasmOperand::U32(v) = dis_instrs[0].operands[0] {
assert_eq!(v, 42);
} else {
panic!("Wrong operand type");
}
assert_eq!(dis_instrs[1].opcode, OpCode::Halt);
}
}
+177
View File
@@ -0,0 +1,177 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum OpCode {
// 6.1 Execution Control
Nop = 0x00,
Halt = 0x01,
Jmp = 0x02,
JmpIfFalse = 0x03,
JmpIfTrue = 0x04,
Trap = 0x05,
// 6.2 Stack
PushConst = 0x10,
Pop = 0x11,
Dup = 0x12,
Swap = 0x13,
PushI64 = 0x14,
PushF64 = 0x15,
PushBool = 0x16,
PushI32 = 0x17,
PopN = 0x18,
// 6.3 Arithmetic
Add = 0x20,
Sub = 0x21,
Mul = 0x22,
Div = 0x23,
// 6.4 Comparison and Logic
Eq = 0x30,
Neq = 0x31,
Lt = 0x32,
Gt = 0x33,
And = 0x34,
Or = 0x35,
Not = 0x36,
BitAnd = 0x37,
BitOr = 0x38,
BitXor = 0x39,
Shl = 0x3A,
Shr = 0x3B,
Lte = 0x3C,
Gte = 0x3D,
Neg = 0x3E,
// 6.5 Variables
GetGlobal = 0x40,
SetGlobal = 0x41,
GetLocal = 0x42,
SetLocal = 0x43,
// 6.6 Functions
Call = 0x50,
Ret = 0x51,
PushScope = 0x52,
PopScope = 0x53,
// 6.7 Heap
Alloc = 0x60,
LoadRef = 0x61,
StoreRef = 0x62,
// 6.8 Peripherals and System
Syscall = 0x70,
FrameSync = 0x80,
}
impl TryFrom<u16> for OpCode {
type Error = String;
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(OpCode::Nop),
0x01 => Ok(OpCode::Halt),
0x02 => Ok(OpCode::Jmp),
0x03 => Ok(OpCode::JmpIfFalse),
0x04 => Ok(OpCode::JmpIfTrue),
0x05 => Ok(OpCode::Trap),
0x10 => Ok(OpCode::PushConst),
0x11 => Ok(OpCode::Pop),
0x12 => Ok(OpCode::Dup),
0x13 => Ok(OpCode::Swap),
0x14 => Ok(OpCode::PushI64),
0x15 => Ok(OpCode::PushF64),
0x16 => Ok(OpCode::PushBool),
0x17 => Ok(OpCode::PushI32),
0x18 => Ok(OpCode::PopN),
0x20 => Ok(OpCode::Add),
0x21 => Ok(OpCode::Sub),
0x22 => Ok(OpCode::Mul),
0x23 => Ok(OpCode::Div),
0x30 => Ok(OpCode::Eq),
0x31 => Ok(OpCode::Neq),
0x32 => Ok(OpCode::Lt),
0x33 => Ok(OpCode::Gt),
0x34 => Ok(OpCode::And),
0x35 => Ok(OpCode::Or),
0x36 => Ok(OpCode::Not),
0x37 => Ok(OpCode::BitAnd),
0x38 => Ok(OpCode::BitOr),
0x39 => Ok(OpCode::BitXor),
0x3A => Ok(OpCode::Shl),
0x3B => Ok(OpCode::Shr),
0x3C => Ok(OpCode::Lte),
0x3D => Ok(OpCode::Gte),
0x3E => Ok(OpCode::Neg),
0x40 => Ok(OpCode::GetGlobal),
0x41 => Ok(OpCode::SetGlobal),
0x42 => Ok(OpCode::GetLocal),
0x43 => Ok(OpCode::SetLocal),
0x50 => Ok(OpCode::Call),
0x51 => Ok(OpCode::Ret),
0x52 => Ok(OpCode::PushScope),
0x53 => Ok(OpCode::PopScope),
0x60 => Ok(OpCode::Alloc),
0x61 => Ok(OpCode::LoadRef),
0x62 => Ok(OpCode::StoreRef),
0x70 => Ok(OpCode::Syscall),
0x80 => Ok(OpCode::FrameSync),
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
}
}
}
impl OpCode {
pub fn cycles(&self) -> u64 {
match self {
OpCode::Nop => 1,
OpCode::Halt => 1,
OpCode::Jmp => 2,
OpCode::JmpIfFalse => 3,
OpCode::JmpIfTrue => 3,
OpCode::Trap => 1,
OpCode::PushConst => 2,
OpCode::Pop => 1,
OpCode::PopN => 2,
OpCode::Dup => 1,
OpCode::Swap => 1,
OpCode::PushI64 => 2,
OpCode::PushF64 => 2,
OpCode::PushBool => 2,
OpCode::PushI32 => 2,
OpCode::Add => 2,
OpCode::Sub => 2,
OpCode::Mul => 4,
OpCode::Div => 6,
OpCode::Eq => 2,
OpCode::Neq => 2,
OpCode::Lt => 2,
OpCode::Gt => 2,
OpCode::And => 2,
OpCode::Or => 2,
OpCode::Not => 1,
OpCode::BitAnd => 2,
OpCode::BitOr => 2,
OpCode::BitXor => 2,
OpCode::Shl => 2,
OpCode::Shr => 2,
OpCode::Lte => 2,
OpCode::Gte => 2,
OpCode::Neg => 1,
OpCode::GetGlobal => 3,
OpCode::SetGlobal => 3,
OpCode::GetLocal => 2,
OpCode::SetLocal => 2,
OpCode::Call => 5,
OpCode::Ret => 4,
OpCode::PushScope => 3,
OpCode::PopScope => 3,
OpCode::Alloc => 10,
OpCode::LoadRef => 3,
OpCode::StoreRef => 3,
OpCode::Syscall => 1,
OpCode::FrameSync => 1,
}
}
}
+111
View File
@@ -0,0 +1,111 @@
use crate::readwrite::*;
use std::io::{Cursor, Read, Write};
#[derive(Debug, Clone, PartialEq)]
pub enum ConstantPoolEntry {
Null,
Int64(i64),
Float64(f64),
Boolean(bool),
String(String),
Int32(i32),
}
#[derive(Debug, Clone, Default)]
pub struct PbcFile {
pub cp: Vec<ConstantPoolEntry>,
pub rom: Vec<u8>,
}
pub fn parse_pbc(bytes: &[u8]) -> Result<PbcFile, String> {
if bytes.len() < 4 || &bytes[0..4] != b"PPBC" {
return Err("Invalid PBC signature".into());
}
let mut cursor = Cursor::new(&bytes[4..]);
let cp_count = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as usize;
let mut cp = Vec::with_capacity(cp_count);
for _ in 0..cp_count {
let mut tag_buf = [0u8; 1];
cursor.read_exact(&mut tag_buf).map_err(|e| e.to_string())?;
let tag = tag_buf[0];
match tag {
1 => {
let val = read_i64_le(&mut cursor).map_err(|e| e.to_string())?;
cp.push(ConstantPoolEntry::Int64(val));
}
2 => {
let val = read_f64_le(&mut cursor).map_err(|e| e.to_string())?;
cp.push(ConstantPoolEntry::Float64(val));
}
3 => {
let mut bool_buf = [0u8; 1];
cursor.read_exact(&mut bool_buf).map_err(|e| e.to_string())?;
cp.push(ConstantPoolEntry::Boolean(bool_buf[0] != 0));
}
4 => {
let len = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as usize;
let mut s_buf = vec![0u8; len];
cursor.read_exact(&mut s_buf).map_err(|e| e.to_string())?;
let s = String::from_utf8_lossy(&s_buf).into_owned();
cp.push(ConstantPoolEntry::String(s));
}
5 => {
let val = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as i32;
cp.push(ConstantPoolEntry::Int32(val));
}
_ => cp.push(ConstantPoolEntry::Null),
}
}
let rom_size = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as usize;
let mut rom = vec![0u8; rom_size];
cursor.read_exact(&mut rom).map_err(|e| e.to_string())?;
Ok(PbcFile { cp, rom })
}
pub fn write_pbc(pbc: &PbcFile) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
out.write_all(b"PPBC").map_err(|e| e.to_string())?;
write_u32_le(&mut out, pbc.cp.len() as u32).map_err(|e| e.to_string())?;
for entry in &pbc.cp {
match entry {
ConstantPoolEntry::Null => {
out.write_all(&[0]).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Int64(v) => {
out.write_all(&[1]).map_err(|e| e.to_string())?;
write_i64_le(&mut out, *v).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Float64(v) => {
out.write_all(&[2]).map_err(|e| e.to_string())?;
write_f64_le(&mut out, *v).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Boolean(v) => {
out.write_all(&[3]).map_err(|e| e.to_string())?;
out.write_all(&[if *v { 1 } else { 0 }]).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::String(v) => {
out.write_all(&[4]).map_err(|e| e.to_string())?;
let bytes = v.as_bytes();
write_u32_le(&mut out, bytes.len() as u32).map_err(|e| e.to_string())?;
out.write_all(bytes).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Int32(v) => {
out.write_all(&[5]).map_err(|e| e.to_string())?;
write_u32_le(&mut out, *v as u32).map_err(|e| e.to_string())?;
}
}
}
write_u32_le(&mut out, pbc.rom.len() as u32).map_err(|e| e.to_string())?;
out.write_all(&pbc.rom).map_err(|e| e.to_string())?;
Ok(out)
}
+41
View File
@@ -0,0 +1,41 @@
use std::io::{self, Read, Write};
pub fn read_u16_le<R: Read>(mut reader: R) -> io::Result<u16> {
let mut buf = [0u8; 2];
reader.read_exact(&mut buf)?;
Ok(u16::from_le_bytes(buf))
}
pub fn read_u32_le<R: Read>(mut reader: R) -> io::Result<u32> {
let mut buf = [0u8; 4];
reader.read_exact(&mut buf)?;
Ok(u32::from_le_bytes(buf))
}
pub fn read_i64_le<R: Read>(mut reader: R) -> io::Result<i64> {
let mut buf = [0u8; 8];
reader.read_exact(&mut buf)?;
Ok(i64::from_le_bytes(buf))
}
pub fn read_f64_le<R: Read>(mut reader: R) -> io::Result<f64> {
let mut buf = [0u8; 8];
reader.read_exact(&mut buf)?;
Ok(f64::from_le_bytes(buf))
}
pub fn write_u16_le<W: Write>(mut writer: W, val: u16) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}
pub fn write_u32_le<W: Write>(mut writer: W, val: u32) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}
pub fn write_i64_le<W: Write>(mut writer: W, val: i64) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}
pub fn write_f64_le<W: Write>(mut writer: W, val: f64) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}