This commit is contained in:
Nilton Constantino
2026-01-31 15:15:42 +00:00
parent 944abaa833
commit dd61314bf9
7 changed files with 958 additions and 51 deletions
@@ -162,14 +162,21 @@ impl PrometeuOS {
/// Loads a cartridge into the PVM and resets the execution state.
pub fn initialize_vm(&mut self, vm: &mut VirtualMachine, cartridge: &Cartridge) {
vm.initialize(cartridge.program.clone(), &cartridge.entrypoint);
// Determines the numeric app_id
self.current_app_id = cartridge.app_id;
self.current_cartridge_title = cartridge.title.clone();
self.current_cartridge_app_version = cartridge.app_version.clone();
self.current_cartridge_app_mode = cartridge.app_mode;
self.current_entrypoint = cartridge.entrypoint.clone();
match vm.initialize(cartridge.program.clone(), &cartridge.entrypoint) {
Ok(_) => {
// Determines the numeric app_id
self.current_app_id = cartridge.app_id;
self.current_cartridge_title = cartridge.title.clone();
self.current_cartridge_app_version = cartridge.app_version.clone();
self.current_cartridge_app_mode = cartridge.app_mode;
self.current_entrypoint = cartridge.entrypoint.clone();
}
Err(e) => {
self.log(LogLevel::Error, LogSource::Vm, 0, format!("Failed to initialize VM: {:?}", e));
// Fail fast: no program is installed, no app id is switched.
// We don't update current_app_id or other fields.
}
}
}
/// Executes a single VM instruction (Debug).
@@ -427,7 +434,11 @@ mod tests {
let mut hw = Hardware::new();
let signals = InputSignals::default();
let rom = vec![0x02, 0x00, 0x00, 0x00, 0x00, 0x00];
let rom = prometeu_bytecode::pbc::write_pbc(&prometeu_bytecode::pbc::PbcFile {
version: 0,
cp: vec![],
rom: vec![0x02, 0x00, 0x00, 0x00, 0x00, 0x00],
}).unwrap();
let cartridge = Cartridge {
app_id: 1234,
title: "test".to_string(),
@@ -466,10 +477,14 @@ mod tests {
// PUSH_CONST 0 (dummy)
// FrameSync (0x80)
// JMP 0
let rom = vec![
0x80, 0x00, // FrameSync (2 bytes opcode)
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // JMP 0 (2 bytes opcode + 4 bytes u32)
];
let rom = prometeu_bytecode::pbc::write_pbc(&prometeu_bytecode::pbc::PbcFile {
version: 0,
cp: vec![],
rom: vec![
0x80, 0x00, // FrameSync (2 bytes opcode)
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // JMP 0 (2 bytes opcode + 4 bytes u32)
],
}).unwrap();
let cartridge = Cartridge {
app_id: 1234,
title: "test".to_string(),
@@ -665,11 +680,15 @@ mod tests {
let signals = InputSignals::default();
// PushI32 0 (0x17), then Ret (0x51)
let rom = vec![
0x17, 0x00, // PushI32
0x00, 0x00, 0x00, 0x00, // value 0
0x51, 0x00 // Ret
];
let rom = prometeu_bytecode::pbc::write_pbc(&prometeu_bytecode::pbc::PbcFile {
version: 0,
cp: vec![],
rom: vec![
0x17, 0x00, // PushI32
0x00, 0x00, 0x00, 0x00, // value 0
0x51, 0x00 // Ret
],
}).unwrap();
let cartridge = Cartridge {
app_id: 1234,
title: "test".to_string(),
@@ -19,6 +19,15 @@ pub enum VmFault {
Panic(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VmInitError {
InvalidFormat,
UnsupportedFormat,
PpbcParseFailed,
PbsV0LoadFailed(prometeu_bytecode::v0::LoadError),
EntrypointNotFound,
}
pub struct HostReturn<'a> {
stack: &'a mut Vec<Value>
}
@@ -2,7 +2,7 @@ use crate::hardware::HardwareBridge;
use crate::virtual_machine::call_frame::CallFrame;
use crate::virtual_machine::scope_frame::ScopeFrame;
use crate::virtual_machine::value::Value;
use crate::virtual_machine::{NativeInterface, Program};
use crate::virtual_machine::{NativeInterface, Program, VmInitError};
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::pbc::{self, ConstantPoolEntry};
use prometeu_bytecode::abi::{TrapInfo, TRAP_OOB};
@@ -98,44 +98,72 @@ impl VirtualMachine {
/// Resets the VM state and loads a new program.
/// This is typically called by the Firmware when starting a new App/Cartridge.
pub fn initialize(&mut self, program_bytes: Vec<u8>, entrypoint: &str) {
// PBC (Prometeu ByteCode) is a binary format that includes a header,
// constant pool, and the raw ROM (bytecode).
if program_bytes.starts_with(b"PPBC") {
if let Ok(pbc_file) = pbc::parse_pbc(&program_bytes) {
let cp = pbc_file.cp.into_iter().map(|entry| match entry {
ConstantPoolEntry::Int32(v) => Value::Int32(v),
ConstantPoolEntry::Int64(v) => Value::Int64(v),
ConstantPoolEntry::Float64(v) => Value::Float(v),
ConstantPoolEntry::Boolean(v) => Value::Boolean(v),
ConstantPoolEntry::String(v) => Value::String(v),
ConstantPoolEntry::Null => Value::Null,
}).collect();
self.program = Program::new(pbc_file.rom, cp);
} else {
// Fallback for raw bytes if PBC parsing fails
self.program = Program::new(program_bytes, vec![]);
}
} else {
// If it doesn't have the PPBC signature, treat it as raw bytecode.
self.program = Program::new(program_bytes, vec![]);
}
// Resolve the entrypoint. Currently supports numeric addresses.
if let Ok(addr) = entrypoint.parse::<usize>() {
self.pc = addr;
} else {
self.pc = 0;
}
// Full state reset to ensure a clean start for the App
pub fn initialize(&mut self, program_bytes: Vec<u8>, entrypoint: &str) -> Result<(), VmInitError> {
// Fail fast: reset state upfront. If we return early with an error,
// the VM is left in a "halted and empty" state.
self.program = Program::default();
self.pc = 0;
self.operand_stack.clear();
self.call_stack.clear();
self.scope_stack.clear();
self.globals.clear();
self.heap.clear();
self.cycles = 0;
self.halted = false;
self.halted = true; // execution is impossible until successful load
// Only recognized formats are loadable.
let program = if program_bytes.starts_with(b"PPBC") {
// PBC (Prometeu ByteCode) legacy format
let pbc_file = pbc::parse_pbc(&program_bytes).map_err(|_| VmInitError::PpbcParseFailed)?;
let cp = pbc_file.cp.into_iter().map(|entry| match entry {
ConstantPoolEntry::Int32(v) => Value::Int32(v),
ConstantPoolEntry::Int64(v) => Value::Int64(v),
ConstantPoolEntry::Float64(v) => Value::Float(v),
ConstantPoolEntry::Boolean(v) => Value::Boolean(v),
ConstantPoolEntry::String(v) => Value::String(v),
ConstantPoolEntry::Null => Value::Null,
}).collect();
Program::new(pbc_file.rom, cp)
} else if program_bytes.starts_with(b"PBS\0") {
// PBS v0 industrial format
match prometeu_bytecode::v0::BytecodeLoader::load(&program_bytes) {
Ok(module) => {
let cp = module.const_pool.into_iter().map(|entry| match entry {
ConstantPoolEntry::Int32(v) => Value::Int32(v),
ConstantPoolEntry::Int64(v) => Value::Int64(v),
ConstantPoolEntry::Float64(v) => Value::Float(v),
ConstantPoolEntry::Boolean(v) => Value::Boolean(v),
ConstantPoolEntry::String(v) => Value::String(v),
ConstantPoolEntry::Null => Value::Null,
}).collect();
Program::new(module.code, cp)
}
Err(prometeu_bytecode::v0::LoadError::InvalidVersion) => return Err(VmInitError::UnsupportedFormat),
Err(e) => {
return Err(VmInitError::PbsV0LoadFailed(e));
}
}
} else {
return Err(VmInitError::InvalidFormat);
};
// Resolve the entrypoint. Currently supports numeric addresses or empty (defaults to 0).
let pc = if entrypoint.is_empty() {
0
} else {
let addr = entrypoint.parse::<usize>().map_err(|_| VmInitError::EntrypointNotFound)?;
if addr >= program.rom.len() && (addr > 0 || !program.rom.is_empty()) {
return Err(VmInitError::EntrypointNotFound);
}
addr
};
// Finalize initialization by applying the new program and PC.
self.program = program;
self.pc = pc;
self.halted = false; // Successfully loaded, execution is now possible
Ok(())
}
/// Prepares the VM to execute a specific entrypoint by setting the PC and
@@ -1522,4 +1550,69 @@ mod tests {
_ => panic!("Expected Trap"),
}
}
#[test]
fn test_loader_hardening_invalid_magic() {
let mut vm = VirtualMachine::default();
let res = vm.initialize(vec![0, 0, 0, 0], "");
assert_eq!(res, Err(VmInitError::InvalidFormat));
// VM should remain empty
assert_eq!(vm.program.rom.len(), 0);
}
#[test]
fn test_loader_hardening_unsupported_version() {
let mut vm = VirtualMachine::default();
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // version 1 (unsupported)
let res = vm.initialize(header, "");
assert_eq!(res, Err(VmInitError::UnsupportedFormat));
}
#[test]
fn test_loader_hardening_malformed_pbs_v0() {
let mut vm = VirtualMachine::default();
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 section claimed but none provided
let res = vm.initialize(header, "");
match res {
Err(VmInitError::PbsV0LoadFailed(prometeu_bytecode::v0::LoadError::UnexpectedEof)) => {},
_ => panic!("Expected PbsV0LoadFailed(UnexpectedEof), got {:?}", res),
}
}
#[test]
fn test_loader_hardening_entrypoint_not_found() {
let mut vm = VirtualMachine::default();
// Valid empty PBS v0 module
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
// Try to initialize with numeric entrypoint 10 (out of bounds for empty ROM)
let res = vm.initialize(header, "10");
assert_eq!(res, Err(VmInitError::EntrypointNotFound));
// VM state should not be updated
assert_eq!(vm.pc, 0);
assert_eq!(vm.program.rom.len(), 0);
}
#[test]
fn test_loader_hardening_successful_init() {
let mut vm = VirtualMachine::default();
vm.pc = 123; // Pollution
let mut header = vec![0u8; 32];
header[0..4].copy_from_slice(b"PBS\0");
let res = vm.initialize(header, "");
assert!(res.is_ok());
assert_eq!(vm.pc, 0);
assert_eq!(vm.program.rom.len(), 0);
assert_eq!(vm.cycles, 0);
}
}