realign and clean up
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "prometeu-bytecode"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
@@ -0,0 +1,50 @@
|
||||
//! This module defines the Application Binary Interface (ABI) of the Prometeu Virtual Machine.
|
||||
//! It specifies how instructions are encoded in bytes and how they interact with memory.
|
||||
|
||||
// --- HIP Trap Codes ---
|
||||
|
||||
/// Attempted to access a gate that does not exist or has been recycled incorrectly.
|
||||
pub const TRAP_INVALID_GATE: u32 = 0x01;
|
||||
/// Attempted to access a gate that has been explicitly released (RC=0).
|
||||
pub const TRAP_DEAD_GATE: u32 = 0x02;
|
||||
/// Attempted to access a field or index beyond the allocated slots for a gate.
|
||||
pub const TRAP_OOB: u32 = 0x03;
|
||||
/// Attempted a typed operation on a gate whose storage type does not match.
|
||||
pub const TRAP_TYPE: u32 = 0x04;
|
||||
/// The syscall ID provided is not recognized by the system.
|
||||
pub const TRAP_INVALID_SYSCALL: u32 = 0x0000_0007;
|
||||
/// Not enough arguments on the stack for the requested syscall.
|
||||
pub const TRAP_STACK_UNDERFLOW: u32 = 0x0000_0008;
|
||||
/// Attempted to access a local slot that is out of bounds for the current frame.
|
||||
pub const TRAP_INVALID_LOCAL: u32 = 0x0000_0009;
|
||||
/// Division or modulo by zero.
|
||||
pub const TRAP_DIV_ZERO: u32 = 0x0000_000A;
|
||||
/// Attempted to call a function that does not exist in the function table.
|
||||
pub const TRAP_INVALID_FUNC: u32 = 0x0000_000B;
|
||||
/// Executed RET with an incorrect stack height (mismatch with function metadata).
|
||||
pub const TRAP_BAD_RET_SLOTS: u32 = 0x0000_000C;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Detailed information about a source code span.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct SourceSpan {
|
||||
pub file_id: u32,
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
}
|
||||
|
||||
/// Detailed information about a runtime trap.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TrapInfo {
|
||||
/// The specific trap code (e.g., TRAP_OOB).
|
||||
pub code: u32,
|
||||
/// The numeric value of the opcode that triggered the trap.
|
||||
pub opcode: u16,
|
||||
/// A human-readable message explaining the trap.
|
||||
pub message: String,
|
||||
/// The absolute Program Counter (PC) address where the trap occurred.
|
||||
pub pc: u32,
|
||||
/// Optional source span information if debug symbols are available.
|
||||
pub span: Option<SourceSpan>,
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Canonical bytecode decoder for Prometeu Bytecode (PBC).
|
||||
//!
|
||||
//! Single source of truth for instruction decoding used by compiler/linker/verifier/VM.
|
||||
//!
|
||||
//! Contract:
|
||||
//! - Instructions are encoded as: [opcode: u16 LE][immediate: spec.imm_bytes]
|
||||
//! - `decode_next(pc, bytes)` returns a typed `DecodedInstr` with canonical `next_pc`.
|
||||
//! - Immediate helpers validate sizes deterministically and return explicit errors.
|
||||
|
||||
use crate::opcode::OpCode;
|
||||
use crate::opcode_spec::{OpCodeSpecExt, OpcodeSpec};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DecodeError {
|
||||
TruncatedOpcode { pc: usize },
|
||||
UnknownOpcode { pc: usize, opcode: u16 },
|
||||
TruncatedImmediate { pc: usize, opcode: OpCode, need: usize, have: usize },
|
||||
ImmediateSizeMismatch { pc: usize, opcode: OpCode, expected: usize, actual: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct DecodedInstr<'a> {
|
||||
pub opcode: OpCode,
|
||||
pub pc: usize,
|
||||
pub next_pc: usize,
|
||||
/// Raw immediate bytes slice, guaranteed to have length `opcode.spec().imm_bytes`.
|
||||
pub imm: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> DecodedInstr<'a> {
|
||||
#[inline]
|
||||
fn ensure_len(&self, expected: usize) -> Result<(), DecodeError> {
|
||||
if self.imm.len() != expected {
|
||||
return Err(DecodeError::ImmediateSizeMismatch {
|
||||
pc: self.pc,
|
||||
opcode: self.opcode,
|
||||
expected,
|
||||
actual: self.imm.len(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn imm_u8(&self) -> Result<u8, DecodeError> {
|
||||
self.ensure_len(1)?;
|
||||
Ok(self.imm[0])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn imm_u16(&self) -> Result<u16, DecodeError> {
|
||||
self.ensure_len(2)?;
|
||||
Ok(u16::from_le_bytes(self.imm.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn imm_u32(&self) -> Result<u32, DecodeError> {
|
||||
self.ensure_len(4)?;
|
||||
Ok(u32::from_le_bytes(self.imm.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn imm_i32(&self) -> Result<i32, DecodeError> {
|
||||
self.ensure_len(4)?;
|
||||
Ok(i32::from_le_bytes(self.imm.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn imm_i64(&self) -> Result<i64, DecodeError> {
|
||||
self.ensure_len(8)?;
|
||||
Ok(i64::from_le_bytes(self.imm.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn imm_f64(&self) -> Result<f64, DecodeError> {
|
||||
self.ensure_len(8)?;
|
||||
Ok(f64::from_le_bytes(self.imm.try_into().unwrap()))
|
||||
}
|
||||
|
||||
/// Helper for opcodes carrying two u32 values packed in 8 bytes (e.g., ALLOC meta).
|
||||
#[inline]
|
||||
pub fn imm_u32x2(&self) -> Result<(u32, u32), DecodeError> {
|
||||
self.ensure_len(8)?;
|
||||
let a = u32::from_le_bytes(self.imm[0..4].try_into().unwrap());
|
||||
let b = u32::from_le_bytes(self.imm[4..8].try_into().unwrap());
|
||||
Ok((a, b))
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the instruction at program counter `pc` from `bytes`.
|
||||
/// Returns the decoded instruction with canonical `next_pc`.
|
||||
#[inline]
|
||||
pub fn decode_next(pc: usize, bytes: &'_ [u8]) -> Result<DecodedInstr<'_>, DecodeError> {
|
||||
if pc + 2 > bytes.len() {
|
||||
return Err(DecodeError::TruncatedOpcode { pc });
|
||||
}
|
||||
|
||||
let opcode_val = u16::from_le_bytes([bytes[pc], bytes[pc + 1]]);
|
||||
let opcode = OpCode::try_from(opcode_val)
|
||||
.map_err(|_| DecodeError::UnknownOpcode { pc, opcode: opcode_val })?;
|
||||
|
||||
let spec: OpcodeSpec = opcode.spec();
|
||||
let imm_start = pc + 2;
|
||||
let imm_end = imm_start + (spec.imm_bytes as usize);
|
||||
|
||||
if imm_end > bytes.len() {
|
||||
return Err(DecodeError::TruncatedImmediate {
|
||||
pc,
|
||||
opcode,
|
||||
need: spec.imm_bytes as usize,
|
||||
have: bytes.len().saturating_sub(imm_start),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(DecodedInstr {
|
||||
opcode,
|
||||
pc,
|
||||
next_pc: imm_end,
|
||||
imm: &bytes[imm_start..imm_end],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Shared bytecode layout utilities, used by both compiler (emitter/linker)
|
||||
//! and the VM (verifier/loader). This ensures a single source of truth for
|
||||
//! how function ranges, instruction boundaries, and pc→function lookups are
|
||||
//! interpreted post-link.
|
||||
|
||||
use crate::model::FunctionMeta;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionLayout {
|
||||
pub start: usize,
|
||||
pub end: usize, // exclusive
|
||||
}
|
||||
|
||||
/// Precompute canonical [start, end) ranges for all functions.
|
||||
///
|
||||
/// Contract:
|
||||
/// - Ranges are computed by sorting functions by `code_offset` (stable),
|
||||
/// then using the next function's start as the current end; the last
|
||||
/// function ends at `code_len_total`.
|
||||
/// - The returned vector is indexed by the original function indices.
|
||||
pub fn compute_function_layouts(functions: &[FunctionMeta], code_len_total: usize) -> Vec<FunctionLayout> {
|
||||
// Build index array and sort by start offset (stable to preserve relative order).
|
||||
let mut idxs: Vec<usize> = (0..functions.len()).collect();
|
||||
idxs.sort_by_key(|&i| functions[i].code_offset as usize);
|
||||
|
||||
// Optional guard: offsets should be strictly increasing (duplicates are suspicious).
|
||||
for w in idxs.windows(2) {
|
||||
if let [a, b] = *w {
|
||||
let sa = functions[a].code_offset as usize;
|
||||
let sb = functions[b].code_offset as usize;
|
||||
debug_assert!(sa < sb, "Function code_offset must be strictly increasing: {} vs {} (indices {} and {})", sa, sb, a, b);
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = vec![FunctionLayout { start: 0, end: 0 }; functions.len()];
|
||||
for (pos, &i) in idxs.iter().enumerate() {
|
||||
let start = functions[i].code_offset as usize;
|
||||
let end = if pos + 1 < idxs.len() {
|
||||
functions[idxs[pos + 1]].code_offset as usize
|
||||
} else {
|
||||
code_len_total
|
||||
};
|
||||
out[i] = FunctionLayout { start, end };
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn build_funcs(offsets: &[usize], lens: Option<&[usize]>) -> Vec<FunctionMeta> {
|
||||
let mut v = Vec::new();
|
||||
for (i, off) in offsets.iter().copied().enumerate() {
|
||||
let len_u32 = lens.and_then(|ls| ls.get(i).copied()).unwrap_or(0) as u32;
|
||||
v.push(FunctionMeta {
|
||||
code_offset: off as u32,
|
||||
code_len: len_u32,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_function_layouts_end_is_next_start() {
|
||||
// Synthetic functions with known offsets: 0, 10, 25; total_len = 40
|
||||
let funcs = build_funcs(&[0, 10, 25], None);
|
||||
let layouts = compute_function_layouts(&funcs, 40);
|
||||
|
||||
assert_eq!(layouts.len(), 3);
|
||||
assert_eq!(layouts[0], FunctionLayout { start: 0, end: 10 });
|
||||
assert_eq!(layouts[1], FunctionLayout { start: 10, end: 25 });
|
||||
assert_eq!(layouts[2], FunctionLayout { start: 25, end: 40 });
|
||||
|
||||
for i in 0..3 {
|
||||
let l = &layouts[i];
|
||||
assert_eq!(l.end - l.start, (funcs.get(i + 1).map(|n| n.code_offset as usize).unwrap_or(40)) - (funcs[i].code_offset as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
mod opcode;
|
||||
mod opcode_spec;
|
||||
mod abi;
|
||||
mod layout;
|
||||
mod decoder;
|
||||
mod model;
|
||||
mod value;
|
||||
mod program_image;
|
||||
|
||||
pub use abi::{
|
||||
TrapInfo,
|
||||
TRAP_INVALID_LOCAL,
|
||||
TRAP_OOB,
|
||||
TRAP_TYPE,
|
||||
TRAP_BAD_RET_SLOTS,
|
||||
TRAP_DEAD_GATE,
|
||||
TRAP_DIV_ZERO,
|
||||
TRAP_INVALID_FUNC,
|
||||
TRAP_INVALID_GATE,
|
||||
TRAP_STACK_UNDERFLOW,
|
||||
TRAP_INVALID_SYSCALL,
|
||||
};
|
||||
pub use model::{
|
||||
BytecodeLoader,
|
||||
FunctionMeta,
|
||||
LoadError,
|
||||
};
|
||||
pub use value::Value;
|
||||
pub use opcode_spec::OpCodeSpecExt;
|
||||
pub use opcode::OpCode;
|
||||
pub use decoder::{decode_next, DecodeError};
|
||||
pub use layout::{compute_function_layouts, FunctionLayout};
|
||||
pub use program_image::ProgramImage;
|
||||
@@ -0,0 +1,650 @@
|
||||
use crate::abi::SourceSpan;
|
||||
use crate::opcode::OpCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// An entry in the Constant Pool.
|
||||
///
|
||||
/// The Constant Pool is a table of unique values used by the program.
|
||||
/// Instead of embedding large data (like strings) directly in the instruction stream,
|
||||
/// the bytecode uses `PushConst <index>` to load these values onto the stack.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub enum ConstantPoolEntry {
|
||||
/// Reserved index (0). Represents a null/undefined value.
|
||||
Null,
|
||||
/// A 64-bit integer constant.
|
||||
Int64(i64),
|
||||
/// A 64-bit floating point constant.
|
||||
Float64(f64),
|
||||
/// A boolean constant.
|
||||
Boolean(bool),
|
||||
/// A UTF-8 string constant.
|
||||
String(String),
|
||||
/// A 32-bit integer constant.
|
||||
Int32(i32),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum LoadError {
|
||||
InvalidMagic,
|
||||
InvalidVersion,
|
||||
InvalidEndianness,
|
||||
OverlappingSections,
|
||||
SectionOutOfBounds,
|
||||
InvalidOpcode,
|
||||
InvalidConstIndex,
|
||||
InvalidFunctionIndex,
|
||||
MalformedHeader,
|
||||
MalformedSection,
|
||||
UnexpectedEof,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionMeta {
|
||||
pub code_offset: u32,
|
||||
pub code_len: u32,
|
||||
pub param_slots: u16,
|
||||
pub local_slots: u16,
|
||||
pub return_slots: u16,
|
||||
pub max_stack_slots: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DebugInfo {
|
||||
pub pc_to_span: Vec<(u32, SourceSpan)>, // Sorted by PC
|
||||
pub function_names: Vec<(u32, String)>, // (func_idx, name)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Export {
|
||||
pub symbol: String,
|
||||
pub func_idx: u32,
|
||||
}
|
||||
|
||||
/// Represents the final serialized format of a PBS v0 module.
|
||||
///
|
||||
/// This structure is a pure data container for the PBS format. It does NOT
|
||||
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
||||
/// All multi-module programs must be flattened and linked by the compiler
|
||||
/// before being serialized into this format.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct BytecodeModule {
|
||||
pub version: u16,
|
||||
pub const_pool: Vec<ConstantPoolEntry>,
|
||||
pub functions: Vec<FunctionMeta>,
|
||||
pub code: Vec<u8>,
|
||||
pub debug_info: Option<DebugInfo>,
|
||||
pub exports: Vec<Export>,
|
||||
}
|
||||
|
||||
impl BytecodeModule {
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
let cp_data = self.serialize_const_pool();
|
||||
let func_data = self.serialize_functions();
|
||||
let code_data = self.code.clone();
|
||||
let debug_data = self.debug_info.as_ref().map(|di| self.serialize_debug(di)).unwrap_or_default();
|
||||
let export_data = self.serialize_exports();
|
||||
|
||||
let mut final_sections = Vec::new();
|
||||
if !cp_data.is_empty() { final_sections.push((0, cp_data)); }
|
||||
if !func_data.is_empty() { final_sections.push((1, func_data)); }
|
||||
if !code_data.is_empty() { final_sections.push((2, code_data)); }
|
||||
if !debug_data.is_empty() { final_sections.push((3, debug_data)); }
|
||||
if !export_data.is_empty() { final_sections.push((4, export_data)); }
|
||||
|
||||
let mut out = Vec::new();
|
||||
// Magic "PBS\0"
|
||||
out.extend_from_slice(b"PBS\0");
|
||||
// Version 0
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
// Endianness 0 (Little Endian), Reserved
|
||||
out.extend_from_slice(&[0u8, 0u8]);
|
||||
// section_count
|
||||
out.extend_from_slice(&(final_sections.len() as u32).to_le_bytes());
|
||||
// padding to 32 bytes
|
||||
out.extend_from_slice(&[0u8; 20]);
|
||||
|
||||
let mut current_offset = 32 + (final_sections.len() as u32 * 12);
|
||||
|
||||
// Write section table
|
||||
for (kind, data) in &final_sections {
|
||||
let k: u32 = *kind;
|
||||
out.extend_from_slice(&k.to_le_bytes());
|
||||
out.extend_from_slice(¤t_offset.to_le_bytes());
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
current_offset += data.len() as u32;
|
||||
}
|
||||
|
||||
// Write section data
|
||||
for (_, data) in final_sections {
|
||||
out.extend_from_slice(&data);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn serialize_const_pool(&self) -> Vec<u8> {
|
||||
if self.const_pool.is_empty() { return Vec::new(); }
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.const_pool.len() as u32).to_le_bytes());
|
||||
for entry in &self.const_pool {
|
||||
match entry {
|
||||
ConstantPoolEntry::Null => data.push(0),
|
||||
ConstantPoolEntry::Int64(v) => {
|
||||
data.push(1);
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
ConstantPoolEntry::Float64(v) => {
|
||||
data.push(2);
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
ConstantPoolEntry::Boolean(v) => {
|
||||
data.push(3);
|
||||
data.push(if *v { 1 } else { 0 });
|
||||
}
|
||||
ConstantPoolEntry::String(v) => {
|
||||
data.push(4);
|
||||
let s_bytes = v.as_bytes();
|
||||
data.extend_from_slice(&(s_bytes.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(s_bytes);
|
||||
}
|
||||
ConstantPoolEntry::Int32(v) => {
|
||||
data.push(5);
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_functions(&self) -> Vec<u8> {
|
||||
if self.functions.is_empty() { return Vec::new(); }
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.functions.len() as u32).to_le_bytes());
|
||||
for f in &self.functions {
|
||||
data.extend_from_slice(&f.code_offset.to_le_bytes());
|
||||
data.extend_from_slice(&f.code_len.to_le_bytes());
|
||||
data.extend_from_slice(&f.param_slots.to_le_bytes());
|
||||
data.extend_from_slice(&f.local_slots.to_le_bytes());
|
||||
data.extend_from_slice(&f.return_slots.to_le_bytes());
|
||||
data.extend_from_slice(&f.max_stack_slots.to_le_bytes());
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_debug(&self, di: &DebugInfo) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(di.pc_to_span.len() as u32).to_le_bytes());
|
||||
for (pc, span) in &di.pc_to_span {
|
||||
data.extend_from_slice(&pc.to_le_bytes());
|
||||
data.extend_from_slice(&span.file_id.to_le_bytes());
|
||||
data.extend_from_slice(&span.start.to_le_bytes());
|
||||
data.extend_from_slice(&span.end.to_le_bytes());
|
||||
}
|
||||
data.extend_from_slice(&(di.function_names.len() as u32).to_le_bytes());
|
||||
for (idx, name) in &di.function_names {
|
||||
data.extend_from_slice(&idx.to_le_bytes());
|
||||
let n_bytes = name.as_bytes();
|
||||
data.extend_from_slice(&(n_bytes.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(n_bytes);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn serialize_exports(&self) -> Vec<u8> {
|
||||
if self.exports.is_empty() { return Vec::new(); }
|
||||
let mut data = Vec::new();
|
||||
data.extend_from_slice(&(self.exports.len() as u32).to_le_bytes());
|
||||
for exp in &self.exports {
|
||||
data.extend_from_slice(&exp.func_idx.to_le_bytes());
|
||||
let s_bytes = exp.symbol.as_bytes();
|
||||
data.extend_from_slice(&(s_bytes.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(s_bytes);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
pub struct BytecodeLoader;
|
||||
|
||||
impl BytecodeLoader {
|
||||
pub fn load(bytes: &[u8]) -> Result<BytecodeModule, LoadError> {
|
||||
if bytes.len() < 32 {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
|
||||
// Magic "PBS\0"
|
||||
if &bytes[0..4] != b"PBS\0" {
|
||||
return Err(LoadError::InvalidMagic);
|
||||
}
|
||||
|
||||
let version = u16::from_le_bytes([bytes[4], bytes[5]]);
|
||||
if version != 0 {
|
||||
return Err(LoadError::InvalidVersion);
|
||||
}
|
||||
|
||||
let endianness = bytes[6];
|
||||
if endianness != 0 { // 0 = Little Endian
|
||||
return Err(LoadError::InvalidEndianness);
|
||||
}
|
||||
|
||||
let section_count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
|
||||
|
||||
let mut sections = Vec::new();
|
||||
let mut pos = 32;
|
||||
for _ in 0..section_count {
|
||||
if pos + 12 > bytes.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let kind = u32::from_le_bytes([bytes[pos], bytes[pos+1], bytes[pos+2], bytes[pos+3]]);
|
||||
let offset = u32::from_le_bytes([bytes[pos+4], bytes[pos+5], bytes[pos+6], bytes[pos+7]]);
|
||||
let length = u32::from_le_bytes([bytes[pos+8], bytes[pos+9], bytes[pos+10], bytes[pos+11]]);
|
||||
|
||||
// Basic bounds check
|
||||
if (offset as usize) + (length as usize) > bytes.len() {
|
||||
return Err(LoadError::SectionOutOfBounds);
|
||||
}
|
||||
|
||||
sections.push((kind, offset, length));
|
||||
pos += 12;
|
||||
}
|
||||
|
||||
// Check for overlapping sections
|
||||
for i in 0..sections.len() {
|
||||
for j in i + 1..sections.len() {
|
||||
let (_, o1, l1) = sections[i];
|
||||
let (_, o2, l2) = sections[j];
|
||||
|
||||
if (o1 < o2 + l2) && (o2 < o1 + l1) {
|
||||
return Err(LoadError::OverlappingSections);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut module = BytecodeModule {
|
||||
version,
|
||||
const_pool: Vec::new(),
|
||||
functions: Vec::new(),
|
||||
code: Vec::new(),
|
||||
debug_info: None,
|
||||
exports: Vec::new(),
|
||||
};
|
||||
|
||||
for (kind, offset, length) in sections {
|
||||
let section_data = &bytes[offset as usize..(offset + length) as usize];
|
||||
match kind {
|
||||
0 => { // Const Pool
|
||||
module.const_pool = parse_const_pool(section_data)?;
|
||||
}
|
||||
1 => { // Functions
|
||||
module.functions = parse_functions(section_data)?;
|
||||
}
|
||||
2 => { // Code
|
||||
module.code = section_data.to_vec();
|
||||
}
|
||||
3 => { // Debug Info
|
||||
module.debug_info = Some(parse_debug_section(section_data)?);
|
||||
}
|
||||
4 => { // Exports
|
||||
module.exports = parse_exports(section_data)?;
|
||||
}
|
||||
_ => {} // Skip unknown or optional sections
|
||||
}
|
||||
}
|
||||
|
||||
// Additional validations
|
||||
validate_module(&module)?;
|
||||
|
||||
Ok(module)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_const_pool(data: &[u8]) -> Result<Vec<ConstantPoolEntry>, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut cp = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos >= data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let tag = data[pos];
|
||||
pos += 1;
|
||||
match tag {
|
||||
0 => cp.push(ConstantPoolEntry::Null),
|
||||
1 => { // Int64
|
||||
if pos + 8 > data.len() { return Err(LoadError::UnexpectedEof); }
|
||||
let val = i64::from_le_bytes(data[pos..pos+8].try_into().unwrap());
|
||||
cp.push(ConstantPoolEntry::Int64(val));
|
||||
pos += 8;
|
||||
}
|
||||
2 => { // Float64
|
||||
if pos + 8 > data.len() { return Err(LoadError::UnexpectedEof); }
|
||||
let val = f64::from_le_bytes(data[pos..pos+8].try_into().unwrap());
|
||||
cp.push(ConstantPoolEntry::Float64(val));
|
||||
pos += 8;
|
||||
}
|
||||
3 => { // Boolean
|
||||
if pos >= data.len() { return Err(LoadError::UnexpectedEof); }
|
||||
cp.push(ConstantPoolEntry::Boolean(data[pos] != 0));
|
||||
pos += 1;
|
||||
}
|
||||
4 => { // String
|
||||
if pos + 4 > data.len() { return Err(LoadError::UnexpectedEof); }
|
||||
let len = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap()) as usize;
|
||||
pos += 4;
|
||||
if pos + len > data.len() { return Err(LoadError::UnexpectedEof); }
|
||||
let s = String::from_utf8_lossy(&data[pos..pos+len]).into_owned();
|
||||
cp.push(ConstantPoolEntry::String(s));
|
||||
pos += len;
|
||||
}
|
||||
5 => { // Int32
|
||||
if pos + 4 > data.len() { return Err(LoadError::UnexpectedEof); }
|
||||
let val = i32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
|
||||
cp.push(ConstantPoolEntry::Int32(val));
|
||||
pos += 4;
|
||||
}
|
||||
_ => return Err(LoadError::MalformedSection),
|
||||
}
|
||||
}
|
||||
Ok(cp)
|
||||
}
|
||||
|
||||
fn parse_functions(data: &[u8]) -> Result<Vec<FunctionMeta>, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut functions = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos + 16 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let code_offset = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
|
||||
let code_len = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap());
|
||||
let param_slots = u16::from_le_bytes(data[pos+8..pos+10].try_into().unwrap());
|
||||
let local_slots = u16::from_le_bytes(data[pos+10..pos+12].try_into().unwrap());
|
||||
let return_slots = u16::from_le_bytes(data[pos+12..pos+14].try_into().unwrap());
|
||||
let max_stack_slots = u16::from_le_bytes(data[pos+14..pos+16].try_into().unwrap());
|
||||
|
||||
functions.push(FunctionMeta {
|
||||
code_offset,
|
||||
code_len,
|
||||
param_slots,
|
||||
local_slots,
|
||||
return_slots,
|
||||
max_stack_slots,
|
||||
});
|
||||
pos += 16;
|
||||
}
|
||||
Ok(functions)
|
||||
}
|
||||
|
||||
fn parse_debug_section(data: &[u8]) -> Result<DebugInfo, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(DebugInfo::default());
|
||||
}
|
||||
if data.len() < 8 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
|
||||
let mut pos = 0;
|
||||
|
||||
// PC to Span table
|
||||
let span_count = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap()) as usize;
|
||||
pos += 4;
|
||||
let mut pc_to_span = Vec::with_capacity(span_count);
|
||||
for _ in 0..span_count {
|
||||
if pos + 16 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let pc = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
|
||||
let file_id = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap());
|
||||
let start = u32::from_le_bytes(data[pos+8..pos+12].try_into().unwrap());
|
||||
let end = u32::from_le_bytes(data[pos+12..pos+16].try_into().unwrap());
|
||||
pc_to_span.push((pc, SourceSpan { file_id, start, end }));
|
||||
pos += 16;
|
||||
}
|
||||
|
||||
// Function names table
|
||||
if pos + 4 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let func_name_count = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap()) as usize;
|
||||
pos += 4;
|
||||
let mut function_names = Vec::with_capacity(func_name_count);
|
||||
for _ in 0..func_name_count {
|
||||
if pos + 8 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let func_idx = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
|
||||
let name_len = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap()) as usize;
|
||||
pos += 8;
|
||||
if pos + name_len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let name = String::from_utf8_lossy(&data[pos..pos+name_len]).into_owned();
|
||||
function_names.push((func_idx, name));
|
||||
pos += name_len;
|
||||
}
|
||||
|
||||
Ok(DebugInfo { pc_to_span, function_names })
|
||||
}
|
||||
|
||||
fn parse_exports(data: &[u8]) -> Result<Vec<Export>, LoadError> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if data.len() < 4 {
|
||||
return Err(LoadError::MalformedSection);
|
||||
}
|
||||
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
|
||||
let mut exports = Vec::with_capacity(count);
|
||||
let mut pos = 4;
|
||||
|
||||
for _ in 0..count {
|
||||
if pos + 8 > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let func_idx = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
|
||||
let name_len = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap()) as usize;
|
||||
pos += 8;
|
||||
if pos + name_len > data.len() {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
let symbol = String::from_utf8_lossy(&data[pos..pos+name_len]).into_owned();
|
||||
exports.push(Export { symbol, func_idx });
|
||||
pos += name_len;
|
||||
}
|
||||
Ok(exports)
|
||||
}
|
||||
|
||||
|
||||
fn validate_module(module: &BytecodeModule) -> Result<(), LoadError> {
|
||||
for func in &module.functions {
|
||||
// Opcode stream bounds
|
||||
if (func.code_offset as usize) + (func.code_len as usize) > module.code.len() {
|
||||
return Err(LoadError::InvalidFunctionIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Basic opcode scan for const pool indices
|
||||
let mut pos = 0;
|
||||
while pos < module.code.len() {
|
||||
if pos + 2 > module.code.len() {
|
||||
break; // Unexpected EOF in middle of opcode, maybe should be error
|
||||
}
|
||||
let op_val = u16::from_le_bytes([module.code[pos], module.code[pos+1]]);
|
||||
let opcode = OpCode::try_from(op_val).map_err(|_| LoadError::InvalidOpcode)?;
|
||||
pos += 2;
|
||||
|
||||
match opcode {
|
||||
OpCode::PushConst => {
|
||||
if pos + 4 > module.code.len() { return Err(LoadError::UnexpectedEof); }
|
||||
let idx = u32::from_le_bytes(module.code[pos..pos+4].try_into().unwrap()) as usize;
|
||||
if idx >= module.const_pool.len() {
|
||||
return Err(LoadError::InvalidConstIndex);
|
||||
}
|
||||
pos += 4;
|
||||
}
|
||||
OpCode::PushI32 | OpCode::PushBounded | OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue
|
||||
| OpCode::GetGlobal | OpCode::SetGlobal | OpCode::GetLocal | OpCode::SetLocal
|
||||
| OpCode::PopN | OpCode::Syscall | OpCode::GateLoad | OpCode::GateStore => {
|
||||
pos += 4;
|
||||
}
|
||||
OpCode::PushI64 | OpCode::PushF64 => {
|
||||
pos += 8;
|
||||
}
|
||||
OpCode::PushBool => {
|
||||
pos += 1;
|
||||
}
|
||||
OpCode::Call => {
|
||||
pos += 4;
|
||||
}
|
||||
OpCode::Alloc => {
|
||||
pos += 8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn create_header(section_count: u32) -> Vec<u8> {
|
||||
let mut h = vec![0u8; 32];
|
||||
h[0..4].copy_from_slice(b"PBS\0");
|
||||
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
||||
h[6] = 0; // endianness
|
||||
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_magic() {
|
||||
let mut data = create_header(0);
|
||||
data[0] = b'X';
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_version() {
|
||||
let mut data = create_header(0);
|
||||
data[4] = 1;
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidVersion));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_endianness() {
|
||||
let mut data = create_header(0);
|
||||
data[6] = 1;
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidEndianness));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_overlapping_sections() {
|
||||
let mut data = create_header(2);
|
||||
// Section 1: Kind 0, Offset 64, Length 32
|
||||
data.extend_from_slice(&0u32.to_le_bytes());
|
||||
data.extend_from_slice(&64u32.to_le_bytes());
|
||||
data.extend_from_slice(&32u32.to_le_bytes());
|
||||
// Section 2: Kind 1, Offset 80, Length 32 (Overlaps with Section 1)
|
||||
data.extend_from_slice(&1u32.to_le_bytes());
|
||||
data.extend_from_slice(&80u32.to_le_bytes());
|
||||
data.extend_from_slice(&32u32.to_le_bytes());
|
||||
|
||||
// Ensure data is long enough for the offsets
|
||||
data.resize(256, 0);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::OverlappingSections));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_section_out_of_bounds() {
|
||||
let mut data = create_header(1);
|
||||
// Section 1: Kind 0, Offset 64, Length 1000
|
||||
data.extend_from_slice(&0u32.to_le_bytes());
|
||||
data.extend_from_slice(&64u32.to_le_bytes());
|
||||
data.extend_from_slice(&1000u32.to_le_bytes());
|
||||
|
||||
data.resize(256, 0);
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::SectionOutOfBounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_function_code_offset() {
|
||||
let mut data = create_header(2);
|
||||
// Section 1: Functions, Kind 1, Offset 64, Length 20 (Header 4 + 1 entry 16)
|
||||
data.extend_from_slice(&1u32.to_le_bytes());
|
||||
data.extend_from_slice(&64u32.to_le_bytes());
|
||||
data.extend_from_slice(&20u32.to_le_bytes());
|
||||
|
||||
// Section 2: Code, Kind 2, Offset 128, Length 10
|
||||
data.extend_from_slice(&2u32.to_le_bytes());
|
||||
data.extend_from_slice(&128u32.to_le_bytes());
|
||||
data.extend_from_slice(&10u32.to_le_bytes());
|
||||
|
||||
data.resize(256, 0);
|
||||
|
||||
// Setup functions section
|
||||
let func_data_start = 64;
|
||||
data[func_data_start..func_data_start+4].copy_from_slice(&1u32.to_le_bytes()); // 1 function
|
||||
let entry_start = func_data_start + 4;
|
||||
data[entry_start..entry_start+4].copy_from_slice(&5u32.to_le_bytes()); // code_offset = 5
|
||||
data[entry_start+4..entry_start+8].copy_from_slice(&10u32.to_le_bytes()); // code_len = 10
|
||||
// 5 + 10 = 15 > 10 (code section length)
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidFunctionIndex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_const_index() {
|
||||
let mut data = create_header(2);
|
||||
// Section 1: Const Pool, Kind 0, Offset 64, Length 4 (Empty CP)
|
||||
data.extend_from_slice(&0u32.to_le_bytes());
|
||||
data.extend_from_slice(&64u32.to_le_bytes());
|
||||
data.extend_from_slice(&4u32.to_le_bytes());
|
||||
|
||||
// Section 2: Code, Kind 2, Offset 128, Length 6 (PushConst 0)
|
||||
data.extend_from_slice(&2u32.to_le_bytes());
|
||||
data.extend_from_slice(&128u32.to_le_bytes());
|
||||
data.extend_from_slice(&6u32.to_le_bytes());
|
||||
|
||||
data.resize(256, 0);
|
||||
|
||||
// Setup empty CP
|
||||
data[64..68].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// Setup code with PushConst 0
|
||||
data[128..130].copy_from_slice(&(OpCode::PushConst as u16).to_le_bytes());
|
||||
data[130..134].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidConstIndex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_minimal_load() {
|
||||
let data = create_header(0);
|
||||
let module = BytecodeLoader::load(&data).unwrap();
|
||||
assert_eq!(module.version, 0);
|
||||
assert!(module.const_pool.is_empty());
|
||||
assert!(module.functions.is_empty());
|
||||
assert!(module.code.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
/// Represents a single instruction in the Prometeu Virtual Machine.
|
||||
///
|
||||
/// Each OpCode is encoded as a 16-bit unsigned integer (u16) in the bytecode.
|
||||
/// The PVM is a stack-based machine, meaning most instructions take their
|
||||
/// operands from the top of the stack and push their results back onto it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u16)]
|
||||
pub enum OpCode {
|
||||
// --- 6.1 Execution Control ---
|
||||
|
||||
/// No operation. Does nothing for 1 cycle.
|
||||
Nop = 0x00,
|
||||
/// Stops the Virtual Machine execution immediately.
|
||||
Halt = 0x01,
|
||||
/// Unconditional jump to a specific PC (Program Counter) address.
|
||||
/// Operand: addr (u32)
|
||||
Jmp = 0x02,
|
||||
/// Jumps to `addr` if the value at the top of the stack is `false`.
|
||||
/// Operand: addr (u32)
|
||||
/// Stack: [bool] -> []
|
||||
JmpIfFalse = 0x03,
|
||||
/// Jumps to `addr` if the value at the top of the stack is `true`.
|
||||
/// Operand: addr (u32)
|
||||
/// Stack: [bool] -> []
|
||||
JmpIfTrue = 0x04,
|
||||
/// Triggers a software breakpoint. Used for debugging.
|
||||
Trap = 0x05,
|
||||
|
||||
// --- 6.2 Stack Manipulation ---
|
||||
|
||||
/// Loads a constant from the Constant Pool into the stack.
|
||||
/// Operand: index (u32)
|
||||
/// Stack: [] -> [value]
|
||||
PushConst = 0x10,
|
||||
/// Removes the top value from the stack.
|
||||
/// Stack: [val] -> []
|
||||
Pop = 0x11,
|
||||
/// Duplicates the top value of the stack.
|
||||
/// Stack: [val] -> [val, val]
|
||||
Dup = 0x12,
|
||||
/// Swaps the two top values of the stack.
|
||||
/// Stack: [a, b] -> [b, a]
|
||||
Swap = 0x13,
|
||||
/// Pushes a 64-bit integer literal onto the stack.
|
||||
/// Operand: value (i64)
|
||||
PushI64 = 0x14,
|
||||
/// Pushes a 64-bit float literal onto the stack.
|
||||
/// Operand: value (f64)
|
||||
PushF64 = 0x15,
|
||||
/// Pushes a boolean literal onto the stack (0=false, 1=true).
|
||||
/// Operand: value (u8)
|
||||
PushBool = 0x16,
|
||||
/// Pushes a 32-bit integer literal onto the stack.
|
||||
/// Operand: value (i32)
|
||||
PushI32 = 0x17,
|
||||
/// Removes `n` values from the stack.
|
||||
/// Operand: n (u32)
|
||||
PopN = 0x18,
|
||||
/// Pushes a 16-bit bounded integer literal onto the stack.
|
||||
/// Operand: value (u32, must be <= 0xFFFF)
|
||||
/// Stack: [] -> [bounded]
|
||||
PushBounded = 0x19,
|
||||
|
||||
// --- 6.3 Arithmetic ---
|
||||
|
||||
/// Adds the two top values (a + b).
|
||||
/// Stack: [a, b] -> [result]
|
||||
Add = 0x20,
|
||||
/// Subtracts the top value from the second one (a - b).
|
||||
/// Stack: [a, b] -> [result]
|
||||
Sub = 0x21,
|
||||
/// Multiplies the two top values (a * b).
|
||||
/// Stack: [a, b] -> [result]
|
||||
Mul = 0x22,
|
||||
/// Divides the second top value by the top one (a / b).
|
||||
/// Stack: [a, b] -> [result]
|
||||
Div = 0x23,
|
||||
/// Remainder of the division of the second top value by the top one (a % b).
|
||||
/// Stack: [a, b] -> [result]
|
||||
Mod = 0x24,
|
||||
/// Converts a bounded value to a 64-bit integer.
|
||||
/// Stack: [bounded] -> [int64]
|
||||
BoundToInt = 0x25,
|
||||
/// Converts an integer to a bounded value, trapping if out of range (0..65535).
|
||||
/// Stack: [int] -> [bounded]
|
||||
IntToBoundChecked = 0x26,
|
||||
|
||||
// --- 6.4 Comparison and Logic ---
|
||||
|
||||
/// Checks if a equals b.
|
||||
/// Stack: [a, b] -> [bool]
|
||||
Eq = 0x30,
|
||||
/// Checks if a is not equal to b.
|
||||
/// Stack: [a, b] -> [bool]
|
||||
Neq = 0x31,
|
||||
/// Checks if a is less than b.
|
||||
/// Stack: [a, b] -> [bool]
|
||||
Lt = 0x32,
|
||||
/// Checks if a is greater than b.
|
||||
/// Stack: [a, b] -> [bool]
|
||||
Gt = 0x33,
|
||||
/// Logical AND.
|
||||
/// Stack: [bool, bool] -> [bool]
|
||||
And = 0x34,
|
||||
/// Logical OR.
|
||||
/// Stack: [bool, bool] -> [bool]
|
||||
Or = 0x35,
|
||||
/// Logical NOT.
|
||||
/// Stack: [bool] -> [bool]
|
||||
Not = 0x36,
|
||||
/// Bitwise AND.
|
||||
/// Stack: [int, int] -> [int]
|
||||
BitAnd = 0x37,
|
||||
/// Bitwise OR.
|
||||
/// Stack: [int, int] -> [int]
|
||||
BitOr = 0x38,
|
||||
/// Bitwise XOR.
|
||||
/// Stack: [int, int] -> [int]
|
||||
BitXor = 0x39,
|
||||
/// Bitwise Shift Left.
|
||||
/// Stack: [int, count] -> [int]
|
||||
Shl = 0x3A,
|
||||
/// Bitwise Shift Right.
|
||||
/// Stack: [int, count] -> [int]
|
||||
Shr = 0x3B,
|
||||
/// Checks if a is less than or equal to b.
|
||||
/// Stack: [a, b] -> [bool]
|
||||
Lte = 0x3C,
|
||||
/// Checks if a is greater than or equal to b.
|
||||
/// Stack: [a, b] -> [bool]
|
||||
Gte = 0x3D,
|
||||
/// Negates a number (-a).
|
||||
/// Stack: [num] -> [num]
|
||||
Neg = 0x3E,
|
||||
|
||||
// --- 6.5 Variables ---
|
||||
|
||||
/// Loads a value from a global variable slot.
|
||||
/// Operand: slot_index (u32)
|
||||
/// Stack: [] -> [value]
|
||||
GetGlobal = 0x40,
|
||||
/// Stores the top value into a global variable slot.
|
||||
/// Operand: slot_index (u32)
|
||||
/// Stack: [value] -> []
|
||||
SetGlobal = 0x41,
|
||||
/// Loads a value from a local variable slot in the current frame.
|
||||
/// Operand: slot_index (u32)
|
||||
/// Stack: [] -> [value]
|
||||
GetLocal = 0x42,
|
||||
/// Stores the top value into a local variable slot in the current frame.
|
||||
/// Operand: slot_index (u32)
|
||||
/// Stack: [value] -> []
|
||||
SetLocal = 0x43,
|
||||
|
||||
// --- 6.6 Functions ---
|
||||
|
||||
/// Calls a function by its index in the function table.
|
||||
/// Operand: func_id (u32)
|
||||
/// Stack: [arg0, arg1, ...] -> [return_slots...]
|
||||
Call = 0x50,
|
||||
/// Returns from the current function.
|
||||
/// Stack: [return_val] -> [return_val]
|
||||
Ret = 0x51,
|
||||
/// Starts a new local scope (for blocks/loops).
|
||||
PushScope = 0x52,
|
||||
/// Ends the current local scope, discarding its local variables.
|
||||
PopScope = 0x53,
|
||||
|
||||
// --- 6.7 HIP (Heap Interface Protocol) ---
|
||||
|
||||
/// Allocates `slots` slots on the heap with the given `type_id`.
|
||||
/// Operands: type_id (u32), slots (u32)
|
||||
/// Stack: [] -> [gate]
|
||||
Alloc = 0x60,
|
||||
/// Reads a value from the heap at `gate + offset`.
|
||||
/// Operand: offset (u32)
|
||||
/// Stack: [gate] -> [value]
|
||||
GateLoad = 0x61,
|
||||
/// Writes a value to the heap at `gate + offset`.
|
||||
/// Operand: offset (u32)
|
||||
/// Stack: [gate, value] -> []
|
||||
GateStore = 0x62,
|
||||
|
||||
/// Marks the beginning of a Peek scope for a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateBeginPeek = 0x63,
|
||||
/// Marks the end of a Peek scope for a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateEndPeek = 0x64,
|
||||
/// Marks the beginning of a Borrow scope for a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateBeginBorrow = 0x65,
|
||||
/// Marks the end of a Borrow scope for a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateEndBorrow = 0x66,
|
||||
/// Marks the beginning of a Mutate scope for a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateBeginMutate = 0x67,
|
||||
/// Marks the end of a Mutate scope for a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateEndMutate = 0x68,
|
||||
|
||||
/// Increments the reference count of a gate.
|
||||
/// Stack: [gate] -> [gate]
|
||||
GateRetain = 0x69,
|
||||
/// Decrements the reference count of a gate.
|
||||
/// Stack: [gate] -> []
|
||||
GateRelease = 0x6A,
|
||||
|
||||
// --- 6.8 Peripherals and System ---
|
||||
|
||||
/// Invokes a system function (Firmware/OS).
|
||||
/// Operand: syscall_id (u32)
|
||||
/// Stack: [args...] -> [results...] (depends on syscall)
|
||||
Syscall = 0x70,
|
||||
/// Synchronizes the VM with the hardware frame (usually 60Hz).
|
||||
/// Execution pauses until the next VSync.
|
||||
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),
|
||||
0x19 => Ok(OpCode::PushBounded),
|
||||
0x20 => Ok(OpCode::Add),
|
||||
0x21 => Ok(OpCode::Sub),
|
||||
0x22 => Ok(OpCode::Mul),
|
||||
0x23 => Ok(OpCode::Div),
|
||||
0x24 => Ok(OpCode::Mod),
|
||||
0x25 => Ok(OpCode::BoundToInt),
|
||||
0x26 => Ok(OpCode::IntToBoundChecked),
|
||||
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::GateLoad),
|
||||
0x62 => Ok(OpCode::GateStore),
|
||||
0x63 => Ok(OpCode::GateBeginPeek),
|
||||
0x64 => Ok(OpCode::GateEndPeek),
|
||||
0x65 => Ok(OpCode::GateBeginBorrow),
|
||||
0x66 => Ok(OpCode::GateEndBorrow),
|
||||
0x67 => Ok(OpCode::GateBeginMutate),
|
||||
0x68 => Ok(OpCode::GateEndMutate),
|
||||
0x69 => Ok(OpCode::GateRetain),
|
||||
0x6A => Ok(OpCode::GateRelease),
|
||||
0x70 => Ok(OpCode::Syscall),
|
||||
0x80 => Ok(OpCode::FrameSync),
|
||||
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpCode {
|
||||
/// Returns the cost of the instruction in VM cycles.
|
||||
/// This is used for performance monitoring and resource limiting (Certification).
|
||||
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::PushBounded => 2,
|
||||
OpCode::Add => 2,
|
||||
OpCode::Sub => 2,
|
||||
OpCode::Mul => 4,
|
||||
OpCode::Div => 6,
|
||||
OpCode::Mod => 6,
|
||||
OpCode::BoundToInt => 1,
|
||||
OpCode::IntToBoundChecked => 1,
|
||||
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::GateLoad => 3,
|
||||
OpCode::GateStore => 3,
|
||||
OpCode::GateBeginPeek => 1,
|
||||
OpCode::GateEndPeek => 1,
|
||||
OpCode::GateBeginBorrow => 1,
|
||||
OpCode::GateEndBorrow => 1,
|
||||
OpCode::GateBeginMutate => 1,
|
||||
OpCode::GateEndMutate => 1,
|
||||
OpCode::GateRetain => 1,
|
||||
OpCode::GateRelease => 1,
|
||||
OpCode::Syscall => 1,
|
||||
OpCode::FrameSync => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
use crate::opcode::OpCode;
|
||||
|
||||
/// Specification for a single OpCode.
|
||||
/// All JMP/JMP_IF_* immediate are u32 absolute offsets from function start.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct OpcodeSpec {
|
||||
pub name: &'static str,
|
||||
pub imm_bytes: u8, // immediate payload size (decode)
|
||||
pub pops: u16, // slots popped
|
||||
pub pushes: u16, // slots pushed
|
||||
pub is_branch: bool, // has a control-flow target
|
||||
pub is_terminator: bool, // ends basic block: JMP/RET/TRAP/HALT
|
||||
pub may_trap: bool, // runtime trap possible
|
||||
}
|
||||
|
||||
pub trait OpCodeSpecExt {
|
||||
fn spec(&self) -> OpcodeSpec;
|
||||
}
|
||||
|
||||
impl OpCodeSpecExt for OpCode {
|
||||
fn spec(&self) -> OpcodeSpec {
|
||||
match self {
|
||||
OpCode::Nop => OpcodeSpec { name: "NOP", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Halt => OpcodeSpec { name: "HALT", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: true, may_trap: false },
|
||||
OpCode::Jmp => OpcodeSpec { name: "JMP", imm_bytes: 4, pops: 0, pushes: 0, is_branch: true, is_terminator: true, may_trap: false },
|
||||
OpCode::JmpIfFalse => OpcodeSpec { name: "JMP_IF_FALSE", imm_bytes: 4, pops: 1, pushes: 0, is_branch: true, is_terminator: false, may_trap: true },
|
||||
OpCode::JmpIfTrue => OpcodeSpec { name: "JMP_IF_TRUE", imm_bytes: 4, pops: 1, pushes: 0, is_branch: true, is_terminator: false, may_trap: true },
|
||||
OpCode::Trap => OpcodeSpec { name: "TRAP", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: true, may_trap: true },
|
||||
OpCode::PushConst => OpcodeSpec { name: "PUSH_CONST", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Pop => OpcodeSpec { name: "POP", imm_bytes: 0, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PopN => OpcodeSpec { name: "POP_N", imm_bytes: 4, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Dup => OpcodeSpec { name: "DUP", imm_bytes: 0, pops: 1, pushes: 2, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Swap => OpcodeSpec { name: "SWAP", imm_bytes: 0, pops: 2, pushes: 2, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushI64 => OpcodeSpec { name: "PUSH_I64", imm_bytes: 8, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushF64 => OpcodeSpec { name: "PUSH_F64", imm_bytes: 8, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushBool => OpcodeSpec { name: "PUSH_BOOL", imm_bytes: 1, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushI32 => OpcodeSpec { name: "PUSH_I32", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PushBounded => OpcodeSpec { name: "PUSH_BOUNDED", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Add => OpcodeSpec { name: "ADD", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Sub => OpcodeSpec { name: "SUB", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Mul => OpcodeSpec { name: "MUL", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Div => OpcodeSpec { name: "DIV", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Mod => OpcodeSpec { name: "MOD", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::BoundToInt => OpcodeSpec { name: "BOUND_TO_INT", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::IntToBoundChecked => OpcodeSpec { name: "INT_TO_BOUND_CHECKED", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Eq => OpcodeSpec { name: "EQ", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Neq => OpcodeSpec { name: "NEQ", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Lt => OpcodeSpec { name: "LT", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Gt => OpcodeSpec { name: "GT", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::And => OpcodeSpec { name: "AND", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Or => OpcodeSpec { name: "OR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Not => OpcodeSpec { name: "NOT", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::BitAnd => OpcodeSpec { name: "BIT_AND", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::BitOr => OpcodeSpec { name: "BIT_OR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::BitXor => OpcodeSpec { name: "BIT_XOR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Shl => OpcodeSpec { name: "SHL", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Shr => OpcodeSpec { name: "SHR", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Lte => OpcodeSpec { name: "LTE", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Gte => OpcodeSpec { name: "GTE", imm_bytes: 0, pops: 2, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Neg => OpcodeSpec { name: "NEG", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::GetGlobal => OpcodeSpec { name: "GET_GLOBAL", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::SetGlobal => OpcodeSpec { name: "SET_GLOBAL", imm_bytes: 4, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::GetLocal => OpcodeSpec { name: "GET_LOCAL", imm_bytes: 4, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::SetLocal => OpcodeSpec { name: "SET_LOCAL", imm_bytes: 4, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Call => OpcodeSpec { name: "CALL", imm_bytes: 4, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Ret => OpcodeSpec { name: "RET", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: true, may_trap: false },
|
||||
OpCode::PushScope => OpcodeSpec { name: "PUSH_SCOPE", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::PopScope => OpcodeSpec { name: "POP_SCOPE", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
OpCode::Alloc => OpcodeSpec { name: "ALLOC", imm_bytes: 8, pops: 0, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateLoad => OpcodeSpec { name: "GATE_LOAD", imm_bytes: 4, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateStore => OpcodeSpec { name: "GATE_STORE", imm_bytes: 4, pops: 2, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateBeginPeek => OpcodeSpec { name: "GATE_BEGIN_PEEK", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateEndPeek => OpcodeSpec { name: "GATE_END_PEEK", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateBeginBorrow => OpcodeSpec { name: "GATE_BEGIN_BORROW", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateEndBorrow => OpcodeSpec { name: "GATE_END_BORROW", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateBeginMutate => OpcodeSpec { name: "GATE_BEGIN_MUTATE", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateEndMutate => OpcodeSpec { name: "GATE_END_MUTATE", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateRetain => OpcodeSpec { name: "GATE_RETAIN", imm_bytes: 0, pops: 1, pushes: 1, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::GateRelease => OpcodeSpec { name: "GATE_RELEASE", imm_bytes: 0, pops: 1, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::Syscall => OpcodeSpec { name: "SYSCALL", imm_bytes: 4, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: true },
|
||||
OpCode::FrameSync => OpcodeSpec { name: "FRAME_SYNC", imm_bytes: 0, pops: 0, pushes: 0, is_branch: false, is_terminator: false, may_trap: false },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Infer the numeric range from the TryFrom<u16> mapping used in opcode.rs tests
|
||||
// by scanning a plausible range (0..1024) and keeping all successful decodes.
|
||||
#[test]
|
||||
fn every_opcode_has_spec_and_imm_defined() {
|
||||
let mut count = 0usize;
|
||||
for val in 0u16..=1023u16 {
|
||||
if let Ok(op) = OpCode::try_from(val) {
|
||||
let spec = op.spec();
|
||||
// Access all fields to ensure they are present and not optimized away
|
||||
let _ = (
|
||||
spec.name,
|
||||
spec.imm_bytes,
|
||||
spec.pops,
|
||||
spec.pushes,
|
||||
spec.is_branch,
|
||||
spec.is_terminator,
|
||||
spec.may_trap,
|
||||
);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
assert!(count > 0, "No opcodes were found via OpCode::try_from");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use crate::abi::TrapInfo;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use crate::model::{BytecodeModule, ConstantPoolEntry, DebugInfo, Export, FunctionMeta};
|
||||
use crate::value::Value;
|
||||
|
||||
/// Represents a fully linked, executable PBS program image.
|
||||
///
|
||||
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||
/// MUST be performed by the compiler before this image is created.
|
||||
///
|
||||
/// The runtime (VM) assumes this image is authoritative and performs no
|
||||
/// additional linking or fixups.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ProgramImage {
|
||||
pub rom: Arc<[u8]>,
|
||||
pub constant_pool: Arc<[Value]>,
|
||||
pub functions: Arc<[FunctionMeta]>,
|
||||
pub debug_info: Option<DebugInfo>,
|
||||
pub exports: Arc<HashMap<String, u32>>,
|
||||
}
|
||||
|
||||
impl ProgramImage {
|
||||
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>, functions: Vec<FunctionMeta>, debug_info: Option<DebugInfo>, exports: HashMap<String, u32>) -> Self {
|
||||
Self {
|
||||
rom: Arc::from(rom),
|
||||
constant_pool: Arc::from(constant_pool),
|
||||
functions: Arc::from(functions),
|
||||
debug_info,
|
||||
exports: Arc::new(exports),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_trap(&self, code: u32, opcode: u16, mut message: String, pc: u32) -> TrapInfo {
|
||||
let span = self.debug_info.as_ref().and_then(|di| {
|
||||
di.pc_to_span.iter().find(|(p, _)| *p == pc).map(|(_, s)| s.clone())
|
||||
});
|
||||
|
||||
if let Some(func_idx) = self.find_function_index(pc) {
|
||||
if let Some(func_name) = self.get_function_name(func_idx) {
|
||||
message = format!("{} (in function {})", message, func_name);
|
||||
}
|
||||
}
|
||||
|
||||
TrapInfo {
|
||||
code,
|
||||
opcode,
|
||||
message,
|
||||
pc,
|
||||
span,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_function_index(&self, pc: u32) -> Option<usize> {
|
||||
self.functions.iter().position(|f| {
|
||||
pc >= f.code_offset && pc < (f.code_offset + f.code_len)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_function_name(&self, func_idx: usize) -> Option<&str> {
|
||||
self.debug_info.as_ref()
|
||||
.and_then(|di| di.function_names.iter().find(|(idx, _)| *idx as usize == func_idx))
|
||||
.map(|(_, name)| name.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BytecodeModule> for ProgramImage {
|
||||
fn from(module: BytecodeModule) -> Self {
|
||||
let constant_pool: Vec<Value> = module.const_pool.iter().map(|entry| {
|
||||
match entry {
|
||||
ConstantPoolEntry::Null => Value::Null,
|
||||
ConstantPoolEntry::Int64(v) => Value::Int64(*v),
|
||||
ConstantPoolEntry::Float64(v) => Value::Float(*v),
|
||||
ConstantPoolEntry::Boolean(v) => Value::Boolean(*v),
|
||||
ConstantPoolEntry::String(v) => Value::String(v.clone()),
|
||||
ConstantPoolEntry::Int32(v) => Value::Int32(*v),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
let mut exports = HashMap::new();
|
||||
for export in module.exports {
|
||||
exports.insert(export.symbol, export.func_idx);
|
||||
}
|
||||
|
||||
ProgramImage::new(
|
||||
module.code,
|
||||
constant_pool,
|
||||
module.functions,
|
||||
module.debug_info,
|
||||
exports,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProgramImage> for BytecodeModule {
|
||||
fn from(program: ProgramImage) -> Self {
|
||||
let const_pool = program.constant_pool.iter().map(|v| match v {
|
||||
Value::Null => ConstantPoolEntry::Null,
|
||||
Value::Int64(v) => ConstantPoolEntry::Int64(*v),
|
||||
Value::Float(v) => ConstantPoolEntry::Float64(*v),
|
||||
Value::Boolean(v) => ConstantPoolEntry::Boolean(*v),
|
||||
Value::String(v) => ConstantPoolEntry::String(v.clone()),
|
||||
Value::Int32(v) => ConstantPoolEntry::Int32(*v),
|
||||
Value::Bounded(v) => ConstantPoolEntry::Int32(*v as i32),
|
||||
Value::Gate(_) => ConstantPoolEntry::Null,
|
||||
}).collect();
|
||||
|
||||
let exports = program.exports.iter().map(|(symbol, &func_idx)| Export {
|
||||
symbol: symbol.clone(),
|
||||
func_idx,
|
||||
}).collect();
|
||||
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool,
|
||||
functions: program.functions.as_ref().to_vec(),
|
||||
code: program.rom.as_ref().to_vec(),
|
||||
debug_info: program.debug_info.clone(),
|
||||
exports,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Represents any piece of data that can be stored on the VM stack or in globals.
|
||||
///
|
||||
/// The PVM is "dynamically typed" at the bytecode level, meaning a single
|
||||
/// `Value` enum can hold different primitive types. The VM performs
|
||||
/// automatic type promotion (e.g., adding an Int32 to a Float64 results
|
||||
/// in a Float64) to ensure mathematical correctness.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Value {
|
||||
/// 32-bit signed integer. Used for most loop counters and indices.
|
||||
Int32(i32),
|
||||
/// 64-bit signed integer. Used for large numbers and timestamps.
|
||||
Int64(i64),
|
||||
/// 64-bit double precision float. Used for physics and complex math.
|
||||
Float(f64),
|
||||
/// Boolean value (true/false).
|
||||
Boolean(bool),
|
||||
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
|
||||
String(String),
|
||||
/// Bounded 16-bit-ish integer.
|
||||
Bounded(u32),
|
||||
/// A pointer to an object on the heap.
|
||||
Gate(usize),
|
||||
/// Represents the absence of a value (equivalent to `null` or `undefined`).
|
||||
Null,
|
||||
}
|
||||
|
||||
impl PartialEq for Value {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Value::Int32(a), Value::Int32(b)) => a == b,
|
||||
(Value::Int64(a), Value::Int64(b)) => a == b,
|
||||
(Value::Int32(a), Value::Int64(b)) => *a as i64 == *b,
|
||||
(Value::Int64(a), Value::Int32(b)) => *a == *b as i64,
|
||||
(Value::Float(a), Value::Float(b)) => a == b,
|
||||
(Value::Int32(a), Value::Float(b)) => *a as f64 == *b,
|
||||
(Value::Float(a), Value::Int32(b)) => *a == *b as f64,
|
||||
(Value::Int64(a), Value::Float(b)) => *a as f64 == *b,
|
||||
(Value::Float(a), Value::Int64(b)) => *a == *b as f64,
|
||||
(Value::Boolean(a), Value::Boolean(b)) => a == b,
|
||||
(Value::String(a), Value::String(b)) => a == b,
|
||||
(Value::Bounded(a), Value::Bounded(b)) => a == b,
|
||||
(Value::Gate(a), Value::Gate(b)) => a == b,
|
||||
(Value::Null, Value::Null) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Value {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
match (self, other) {
|
||||
(Value::Int32(a), Value::Int32(b)) => a.partial_cmp(b),
|
||||
(Value::Int64(a), Value::Int64(b)) => a.partial_cmp(b),
|
||||
(Value::Int32(a), Value::Int64(b)) => (*a as i64).partial_cmp(b),
|
||||
(Value::Int64(a), Value::Int32(b)) => a.partial_cmp(&(*b as i64)),
|
||||
(Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
|
||||
(Value::Bounded(a), Value::Bounded(b)) => a.partial_cmp(b),
|
||||
(Value::Int32(a), Value::Float(b)) => (*a as f64).partial_cmp(b),
|
||||
(Value::Float(a), Value::Int32(b)) => a.partial_cmp(&(*b as f64)),
|
||||
(Value::Int64(a), Value::Float(b)) => (*a as f64).partial_cmp(b),
|
||||
(Value::Float(a), Value::Int64(b)) => a.partial_cmp(&(*b as f64)),
|
||||
(Value::Boolean(a), Value::Boolean(b)) => a.partial_cmp(b),
|
||||
(Value::String(a), Value::String(b)) => a.partial_cmp(b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn as_float(&self) -> Option<f64> {
|
||||
match self {
|
||||
Value::Int32(i) => Some(*i as f64),
|
||||
Value::Int64(i) => Some(*i as f64),
|
||||
Value::Float(f) => Some(*f),
|
||||
Value::Bounded(b) => Some(*b as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_integer(&self) -> Option<i64> {
|
||||
match self {
|
||||
Value::Int32(i) => Some(*i as i64),
|
||||
Value::Int64(i) => Some(*i),
|
||||
Value::Float(f) => Some(*f as i64),
|
||||
Value::Bounded(b) => Some(*b as i64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
Value::Int32(i) => i.to_string(),
|
||||
Value::Int64(i) => i.to_string(),
|
||||
Value::Float(f) => f.to_string(),
|
||||
Value::Bounded(b) => format!("{}b", b),
|
||||
Value::Boolean(b) => b.to_string(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Gate(r) => format!("[Gate {}]", r),
|
||||
Value::Null => "null".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_value_equality() {
|
||||
assert_eq!(Value::Int32(10), Value::Int32(10));
|
||||
assert_eq!(Value::Int64(10), Value::Int64(10));
|
||||
assert_eq!(Value::Int32(10), Value::Int64(10));
|
||||
assert_eq!(Value::Int64(10), Value::Int32(10));
|
||||
assert_eq!(Value::Float(10.5), Value::Float(10.5));
|
||||
assert_eq!(Value::Int32(10), Value::Float(10.0));
|
||||
assert_eq!(Value::Float(10.0), Value::Int32(10));
|
||||
assert_eq!(Value::Int64(10), Value::Float(10.0));
|
||||
assert_eq!(Value::Float(10.0), Value::Int64(10));
|
||||
assert_ne!(Value::Int32(10), Value::Int32(11));
|
||||
assert_ne!(Value::Int64(10), Value::Int64(11));
|
||||
assert_ne!(Value::Int32(10), Value::Int64(11));
|
||||
assert_ne!(Value::Int32(10), Value::Float(10.1));
|
||||
assert_eq!(Value::Boolean(true), Value::Boolean(true));
|
||||
assert_ne!(Value::Boolean(true), Value::Boolean(false));
|
||||
assert_eq!(Value::String("oi".into()), Value::String("oi".into()));
|
||||
assert_eq!(Value::Null, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_value_conversions() {
|
||||
let v_int32 = Value::Int32(42);
|
||||
assert_eq!(v_int32.as_float(), Some(42.0));
|
||||
assert_eq!(v_int32.as_integer(), Some(42));
|
||||
|
||||
let v_int64 = Value::Int64(42);
|
||||
assert_eq!(v_int64.as_float(), Some(42.0));
|
||||
assert_eq!(v_int64.as_integer(), Some(42));
|
||||
|
||||
let v_float = Value::Float(42.7);
|
||||
assert_eq!(v_float.as_float(), Some(42.7));
|
||||
assert_eq!(v_float.as_integer(), Some(42));
|
||||
|
||||
let v_bool = Value::Boolean(true);
|
||||
assert_eq!(v_bool.as_float(), None);
|
||||
assert_eq!(v_bool.as_integer(), None);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
# PROMETEU Core
|
||||
|
||||
This crate contains the core library that defines the behavior of PROMETEU's hardware and software.
|
||||
|
||||
## Responsibilities
|
||||
|
||||
- **Logical Hardware**: Definition of GFX, Input, Audio, and Touch.
|
||||
- **Virtual Machine**: Execution of custom bytecode (PBC - Prometeu Byte Code).
|
||||
- **Virtual FS**: File management and "cartridge" access.
|
||||
- **Firmware/OS**: The internal operating system that manages the application lifecycle, splash screens, and the Hub Home.
|
||||
|
||||
## Architecture
|
||||
|
||||
The core is designed to be deterministic and portable. It does not make direct calls to the host operating system; instead, it defines traits that hosts must implement (e.g., `FsBackend`).
|
||||
@@ -5,6 +5,6 @@ edition = "2024"
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
@@ -1,4 +1,4 @@
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_bytecode::{Value, TRAP_OOB};
|
||||
use crate::vm_fault::VmFault;
|
||||
|
||||
pub struct HostReturn<'a> {
|
||||
@@ -17,7 +17,7 @@ impl<'a> HostReturn<'a> {
|
||||
}
|
||||
pub fn push_bounded(&mut self, v: u32) -> Result<(), VmFault> {
|
||||
if v > 0xFFFF {
|
||||
return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_OOB, "Bounded value overflow".into()));
|
||||
return Err(VmFault::Trap(TRAP_OOB, "Bounded value overflow".into()));
|
||||
}
|
||||
self.stack.push(Value::Bounded(v));
|
||||
Ok(())
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_bytecode::{Value, TRAP_TYPE};
|
||||
use crate::vm_fault::VmFault;
|
||||
|
||||
pub fn expect_bounded(args: &[Value], idx: usize) -> Result<u32, VmFault> {
|
||||
@@ -7,13 +7,13 @@ pub fn expect_bounded(args: &[Value], idx: usize) -> Result<u32, VmFault> {
|
||||
Value::Bounded(b) => Some(*b),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected bounded at index {}", idx)))
|
||||
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, format!("Expected bounded at index {}", idx)))
|
||||
}
|
||||
|
||||
pub fn expect_int(args: &[Value], idx: usize) -> Result<i64, VmFault> {
|
||||
args.get(idx)
|
||||
.and_then(|v| v.as_integer())
|
||||
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected integer at index {}", idx)))
|
||||
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, format!("Expected integer at index {}", idx)))
|
||||
}
|
||||
|
||||
pub fn expect_bool(args: &[Value], idx: usize) -> Result<bool, VmFault> {
|
||||
@@ -22,5 +22,5 @@ pub fn expect_bool(args: &[Value], idx: usize) -> Result<bool, VmFault> {
|
||||
Value::Boolean(b) => Some(*b),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected boolean at index {}", idx)))
|
||||
.ok_or_else(|| VmFault::Trap(TRAP_TYPE, format!("Expected boolean at index {}", idx)))
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
serde_json = "1.0.149"
|
||||
prometeu-vm = { path = "../prometeu-vm" }
|
||||
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
prometeu-hal = { path = "../prometeu-hal" }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -5,7 +5,7 @@ use prometeu_hal::log::{LogLevel, LogService, LogSource};
|
||||
use prometeu_hal::telemetry::{CertificationConfig, Certifier, TelemetryFrame};
|
||||
use std::collections::HashMap;
|
||||
use std::time::Instant;
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_bytecode::{Value, TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE};
|
||||
use prometeu_hal::{expect_bool, expect_int, HostContext, HostReturn, NativeInterface, SyscallId};
|
||||
use prometeu_hal::asset::{BankType, LoadStatus, SlotRef};
|
||||
use prometeu_hal::button::Button;
|
||||
@@ -352,7 +352,7 @@ impl VirtualMachineRuntime {
|
||||
2 => LogLevel::Info,
|
||||
3 => LogLevel::Warn,
|
||||
4 => LogLevel::Error,
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Invalid log level: {}", level_val))),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, format!("Invalid log level: {}", level_val))),
|
||||
};
|
||||
|
||||
let app_id = self.current_app_id;
|
||||
@@ -422,427 +422,6 @@ impl VirtualMachineRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_hal::{HostReturn, InputSignals};
|
||||
use super::*;
|
||||
|
||||
fn call_syscall(os: &mut VirtualMachineRuntime, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<(), VmFault> {
|
||||
let args_count = Syscall::from_u32(id).expect(&format!("Invalid syscall id: 0x{:08X}", id)).args_count();
|
||||
let mut args = Vec::new();
|
||||
for _ in 0..args_count {
|
||||
// Protege contra underflow/erros de pilha durante testes
|
||||
match vm.pop() {
|
||||
Ok(v) => args.push(v),
|
||||
Err(e) => return Err(VmFault::Panic(e)),
|
||||
}
|
||||
}
|
||||
args.reverse();
|
||||
let mut ret = HostReturn::new(&mut vm.operand_stack);
|
||||
os.syscall(id, &args, &mut ret, &mut HostContext::new(Some(hw)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_infinite_loop_budget_reset_bug() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
let rom = prometeu_bytecode::BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![prometeu_bytecode::FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 6,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
}],
|
||||
code: vec![0x02, 0x00, 0x00, 0x00, 0x00, 0x00],
|
||||
debug_info: None,
|
||||
exports: vec![prometeu_bytecode::Export { symbol: "main".into(), func_idx: 0 }],
|
||||
}.serialize();
|
||||
let cartridge = Cartridge {
|
||||
app_id: 1234,
|
||||
title: "test".to_string(),
|
||||
app_version: "1.0.0".to_string(),
|
||||
app_mode: AppMode::Game,
|
||||
entrypoint: "0".to_string(),
|
||||
program: rom,
|
||||
assets: vec![],
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
};
|
||||
os.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
// First tick
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_1 = vm.cycles;
|
||||
assert!(cycles_after_tick_1 >= VirtualMachineRuntime::CYCLES_PER_LOGICAL_FRAME);
|
||||
|
||||
// Second tick - Now it SHOULD NOT gain more budget
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_2 = vm.cycles;
|
||||
|
||||
// FIX: It should not have consumed cycles in the second tick because the logical frame budget ended
|
||||
println!("Cycles after tick 1: {}, tick 2: {}", cycles_after_tick_1, cycles_after_tick_2);
|
||||
assert_eq!(cycles_after_tick_2, cycles_after_tick_1, "VM should NOT have consumed more cycles in the second tick because logical frame budget is exhausted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_budget_reset_on_frame_sync() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
// Loop that calls FrameSync:
|
||||
// PUSH_CONST 0 (dummy)
|
||||
// FrameSync (0x80)
|
||||
// JMP 0
|
||||
let rom = prometeu_bytecode::BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![prometeu_bytecode::FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 8,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
}],
|
||||
code: vec![
|
||||
0x80, 0x00, // FrameSync (2 bytes opcode)
|
||||
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // JMP 0 (2 bytes opcode + 4 bytes u32)
|
||||
],
|
||||
debug_info: None,
|
||||
exports: vec![prometeu_bytecode::Export { symbol: "main".into(), func_idx: 0 }],
|
||||
}.serialize();
|
||||
let cartridge = Cartridge {
|
||||
app_id: 1234,
|
||||
title: "test".to_string(),
|
||||
app_version: "1.0.0".to_string(),
|
||||
app_mode: AppMode::Game,
|
||||
entrypoint: "0".to_string(),
|
||||
program: rom,
|
||||
assets: vec![],
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
};
|
||||
os.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
// First tick
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_1 = vm.cycles;
|
||||
|
||||
// Should have stopped at FrameSync
|
||||
assert!(cycles_after_tick_1 > 0, "VM should have consumed some cycles");
|
||||
assert!(cycles_after_tick_1 < VirtualMachineRuntime::CYCLES_PER_LOGICAL_FRAME);
|
||||
|
||||
// Second tick - Should reset the budget and run a bit more until the next FrameSync
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
let cycles_after_tick_2 = vm.cycles;
|
||||
|
||||
assert!(cycles_after_tick_2 > cycles_after_tick_1, "VM should have consumed more cycles because FrameSync reset the budget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_telemetry_cycles_budget() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
// Standard budget
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
assert_eq!(os.telemetry_current.cycles_budget, VirtualMachineRuntime::CYCLES_PER_LOGICAL_FRAME);
|
||||
|
||||
// Custom budget via CAP
|
||||
let mut config = CertificationConfig::default();
|
||||
config.enabled = true;
|
||||
config.cycles_budget_per_frame = Some(50000);
|
||||
|
||||
let mut os_custom = VirtualMachineRuntime::new(Some(config));
|
||||
os_custom.tick(&mut vm, &signals, &mut hw);
|
||||
assert_eq!(os_custom.telemetry_current.cycles_budget, 50000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_color_logic() {
|
||||
let os = VirtualMachineRuntime::new(None);
|
||||
|
||||
// Deve retornar a cor raw diretamente
|
||||
assert_eq!(os.get_color(0x07E0), Color::GREEN);
|
||||
assert_eq!(os.get_color(0xF800), Color::RED);
|
||||
assert_eq!(os.get_color(0x001F), Color::BLUE);
|
||||
assert_eq!(os.get_color(3), Color::from_raw(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gfx_set_sprite_syscall_pops() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
|
||||
// Push arguments in order 1 to 10
|
||||
vm.push(Value::String("mouse_cursor".to_string())); // arg1: assetName
|
||||
vm.push(Value::Int32(0)); // arg2: id
|
||||
|
||||
// Simulating touch.x and touch.y syscalls
|
||||
vm.push(Value::Int32(10)); // arg3: x (returned from syscall)
|
||||
vm.push(Value::Int32(20)); // arg4: y (returned from syscall)
|
||||
|
||||
vm.push(Value::Int32(0)); // arg5: tileId
|
||||
vm.push(Value::Int32(0)); // arg6: paletteId
|
||||
vm.push(Value::Boolean(true)); // arg7: active
|
||||
vm.push(Value::Boolean(false)); // arg8: flipX
|
||||
vm.push(Value::Boolean(false)); // arg9: flipY
|
||||
vm.push(Value::Int32(4)); // arg10: priority
|
||||
|
||||
let res = call_syscall(&mut os, 0x1007, &mut vm, &mut hw);
|
||||
assert!(res.is_ok(), "GfxSetSprite syscall should succeed, but got: {:?}", res.err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gfx_set_sprite_with_swapped_arguments_repro() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
|
||||
// Repro: what if the compiler is pushing in reverse order?
|
||||
vm.push(Value::Int32(4)); // arg10?
|
||||
vm.push(Value::Boolean(false));
|
||||
vm.push(Value::Boolean(false));
|
||||
vm.push(Value::Boolean(true));
|
||||
vm.push(Value::Int32(0));
|
||||
vm.push(Value::Int32(0));
|
||||
vm.push(Value::Int32(20));
|
||||
vm.push(Value::Int32(10));
|
||||
vm.push(Value::Int32(0));
|
||||
vm.push(Value::String("mouse_cursor".to_string())); // arg1?
|
||||
|
||||
let res = call_syscall(&mut os, 0x1007, &mut vm, &mut hw);
|
||||
assert!(res.is_err());
|
||||
// Because it tries to pop priority but gets a string
|
||||
match res.err().unwrap() {
|
||||
VmFault::Trap(code, _) => assert_eq!(code, prometeu_bytecode::abi::TRAP_TYPE),
|
||||
_ => panic!("Expected Trap"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_syscall_log_write_and_rate_limit() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
|
||||
os.current_app_id = 123;
|
||||
|
||||
// 1. Normal log test
|
||||
vm.push(Value::Int64(2)); // Info
|
||||
vm.push(Value::String("Hello Log".to_string()));
|
||||
let res = call_syscall(&mut os, 0x5001, &mut vm, &mut hw);
|
||||
assert!(res.is_ok());
|
||||
|
||||
let recent = os.log_service.get_recent(1);
|
||||
assert_eq!(recent[0].msg, "Hello Log");
|
||||
assert_eq!(recent[0].level, LogLevel::Info);
|
||||
assert_eq!(recent[0].source, LogSource::App { app_id: 123 });
|
||||
|
||||
// 2. Truncation test
|
||||
let long_msg = "A".repeat(300);
|
||||
vm.push(Value::Int64(3)); // Warn
|
||||
vm.push(Value::String(long_msg));
|
||||
call_syscall(&mut os, 0x5001, &mut vm, &mut hw).unwrap();
|
||||
|
||||
let recent = os.log_service.get_recent(1);
|
||||
assert_eq!(recent[0].msg.len(), 256);
|
||||
assert!(recent[0].msg.starts_with("AAAAA"));
|
||||
|
||||
// 3. Rate Limit Test
|
||||
// We already made 2 logs. The limit is 10.
|
||||
for i in 0..8 {
|
||||
vm.push(Value::Int64(2));
|
||||
vm.push(Value::String(format!("Log {}", i)));
|
||||
call_syscall(&mut os, 0x5001, &mut vm, &mut hw).unwrap();
|
||||
}
|
||||
|
||||
// The 11th log should be ignored (and generate a system warning)
|
||||
vm.push(Value::Int64(2));
|
||||
vm.push(Value::String("Eleventh log".to_string()));
|
||||
call_syscall(&mut os, 0x5001, &mut vm, &mut hw).unwrap();
|
||||
|
||||
let recent = os.log_service.get_recent(2);
|
||||
// The last log should be the rate limit warning (came after the 10th log attempted)
|
||||
assert_eq!(recent[1].msg, "App exceeded log limit per frame");
|
||||
assert_eq!(recent[1].level, LogLevel::Warn);
|
||||
// The log "Eleventh log" should not be there
|
||||
assert_ne!(recent[0].msg, "Eleventh log");
|
||||
|
||||
// 4. Rate limit reset test in the next frame
|
||||
os.begin_logical_frame(&InputSignals::default(), &mut hw);
|
||||
vm.push(Value::Int64(2));
|
||||
vm.push(Value::String("New frame log".to_string()));
|
||||
call_syscall(&mut os, 0x5001, &mut vm, &mut hw).unwrap();
|
||||
|
||||
let recent = os.log_service.get_recent(1);
|
||||
assert_eq!(recent[0].msg, "New frame log");
|
||||
|
||||
// 5. LOG_WRITE_TAG test
|
||||
vm.push(Value::Int64(2)); // Info
|
||||
vm.push(Value::Int64(42)); // Tag
|
||||
vm.push(Value::String("Tagged Log".to_string()));
|
||||
call_syscall(&mut os, 0x5002, &mut vm, &mut hw).unwrap();
|
||||
|
||||
let recent = os.log_service.get_recent(1);
|
||||
assert_eq!(recent[0].msg, "Tagged Log");
|
||||
assert_eq!(recent[0].tag, 42);
|
||||
// Syscall de log é void: não empurra valor na pilha
|
||||
|
||||
// 6. GFX Syscall return test
|
||||
vm.push(Value::Int64(1)); // color_idx
|
||||
call_syscall(&mut os, 0x1001, &mut vm, &mut hw).unwrap(); // gfx.clear
|
||||
assert_eq!(vm.pop().unwrap(), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_entrypoint_called_every_frame() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
let signals = InputSignals::default();
|
||||
|
||||
// PushI32 0 (0x17), then Ret (0x51)
|
||||
let rom = prometeu_bytecode::BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![prometeu_bytecode::FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: 10,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 0,
|
||||
}],
|
||||
code: vec![
|
||||
0x17, 0x00, // PushI32
|
||||
0x00, 0x00, 0x00, 0x00, // value 0
|
||||
0x11, 0x00, // Pop
|
||||
0x51, 0x00 // Ret
|
||||
],
|
||||
debug_info: None,
|
||||
exports: vec![prometeu_bytecode::Export { symbol: "main".into(), func_idx: 0 }],
|
||||
}.serialize();
|
||||
let cartridge = Cartridge {
|
||||
app_id: 1234,
|
||||
title: "test".to_string(),
|
||||
app_version: "1.0.0".to_string(),
|
||||
app_mode: AppMode::Game,
|
||||
entrypoint: "0".to_string(),
|
||||
program: rom,
|
||||
assets: vec![],
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
};
|
||||
os.initialize_vm(&mut vm, &cartridge);
|
||||
|
||||
// First frame
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
assert_eq!(os.logical_frame_index, 1);
|
||||
assert!(!os.logical_frame_active);
|
||||
assert!(vm.call_stack.is_empty());
|
||||
|
||||
// Second frame - Should call entrypoint again
|
||||
os.tick(&mut vm, &signals, &mut hw);
|
||||
assert_eq!(os.logical_frame_index, 2);
|
||||
assert!(!os.logical_frame_active);
|
||||
assert!(vm.call_stack.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_os_unknown_syscall_returns_trap() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut vm = VirtualMachine::default();
|
||||
let mut hw = Hardware::new();
|
||||
let mut ret = HostReturn::new(&mut vm.operand_stack);
|
||||
|
||||
let res = os.syscall(0xDEADBEEF, &[], &mut ret, &mut HostContext::new(Some(&mut hw)));
|
||||
assert!(res.is_err());
|
||||
match res.err().unwrap() {
|
||||
VmFault::Trap(code, _) => assert_eq!(code, prometeu_bytecode::abi::TRAP_INVALID_SYSCALL),
|
||||
_ => panic!("Expected Trap"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gfx_clear565_syscall() {
|
||||
let mut hw = Hardware::new();
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut stack = Vec::new();
|
||||
|
||||
// Success case
|
||||
let args = vec![Value::Bounded(0xF800)]; // Red
|
||||
{
|
||||
let mut ret = HostReturn::new(&mut stack);
|
||||
os.syscall(Syscall::GfxClear565 as u32, &args, &mut ret, &mut HostContext::new(Some(&mut hw))).unwrap();
|
||||
}
|
||||
assert_eq!(stack.len(), 0); // void return
|
||||
|
||||
// OOB case
|
||||
let args = vec![Value::Bounded(0x10000)];
|
||||
{
|
||||
let mut ret = HostReturn::new(&mut stack);
|
||||
let res = os.syscall(Syscall::GfxClear565 as u32, &args, &mut ret, &mut HostContext::new(Some(&mut hw)));
|
||||
assert!(res.is_err());
|
||||
match res.err().unwrap() {
|
||||
VmFault::Trap(trap, _) => assert_eq!(trap, prometeu_bytecode::abi::TRAP_OOB),
|
||||
_ => panic!("Expected Trap OOB"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_input_snapshots_syscalls() {
|
||||
let mut hw = Hardware::new();
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
|
||||
// Pad snapshot
|
||||
let mut stack = Vec::new();
|
||||
{
|
||||
let mut ret = HostReturn::new(&mut stack);
|
||||
os.syscall(Syscall::InputPadSnapshot as u32, &[], &mut ret, &mut HostContext::new(Some(&mut hw))).unwrap();
|
||||
}
|
||||
assert_eq!(stack.len(), 48);
|
||||
|
||||
// Touch snapshot
|
||||
let mut stack = Vec::new();
|
||||
{
|
||||
let mut ret = HostReturn::new(&mut stack);
|
||||
os.syscall(Syscall::InputTouchSnapshot as u32, &[], &mut ret, &mut HostContext::new(Some(&mut hw))).unwrap();
|
||||
}
|
||||
assert_eq!(stack.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_os_syscall_without_hardware_fails_graciously() {
|
||||
let mut os = VirtualMachineRuntime::new(None);
|
||||
let mut stack = Vec::new();
|
||||
let mut ret = HostReturn::new(&mut stack);
|
||||
|
||||
// GfxClear needs hardware
|
||||
let res = os.syscall(Syscall::GfxClear as u32, &[Value::Int64(0)], &mut ret, &mut HostContext::new(None));
|
||||
assert_eq!(res, Err(VmFault::Unavailable));
|
||||
|
||||
// SystemHasCart DOES NOT need hardware
|
||||
let res = os.syscall(Syscall::SystemHasCart as u32, &[], &mut ret, &mut HostContext::new(None));
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeInterface for VirtualMachineRuntime {
|
||||
/// Dispatches a syscall from the VM to the native implementation.
|
||||
///
|
||||
@@ -857,7 +436,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
/// Each syscall returns the number of virtual cycles it consumed.
|
||||
fn syscall(&mut self, id: SyscallId, args: &[Value], ret: &mut HostReturn, ctx: &mut HostContext) -> Result<(), VmFault> {
|
||||
self.telemetry_current.syscalls += 1;
|
||||
let syscall = Syscall::from_u32(id).ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_INVALID_SYSCALL, format!(
|
||||
let syscall = Syscall::from_u32(id).ok_or_else(|| VmFault::Trap(TRAP_INVALID_SYSCALL, format!(
|
||||
"Unknown syscall: 0x{:08X}", id
|
||||
)))?;
|
||||
|
||||
@@ -958,7 +537,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::GfxSetSprite => {
|
||||
let asset_name = match args.get(0).ok_or_else(|| VmFault::Panic("Missing asset_name".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string asset_name".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string asset_name".into())),
|
||||
};
|
||||
let index = expect_int(args, 1)? as usize;
|
||||
let x = expect_int(args, 2)? as i32;
|
||||
@@ -971,7 +550,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let priority = expect_int(args, 9)? as u8;
|
||||
|
||||
let bank_id = hw.assets().find_slot_by_name(&asset_name, BankType::TILES).unwrap_or(0);
|
||||
|
||||
|
||||
if index < 512 {
|
||||
*hw.gfx_mut().sprite_mut(index) = Sprite {
|
||||
tile: Tile { id: tile_id, flip_x: false, flip_y: false, palette_id },
|
||||
@@ -992,7 +571,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let y = expect_int(args, 1)? as i32;
|
||||
let msg = match args.get(2).ok_or_else(|| VmFault::Panic("Missing message".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string message".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
|
||||
};
|
||||
let color_val = expect_int(args, 3)?;
|
||||
let color = self.get_color(color_val);
|
||||
@@ -1004,7 +583,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::GfxClear565 => {
|
||||
let color_val = expect_int(args, 0)? as u32;
|
||||
if color_val > 0xFFFF {
|
||||
return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_OOB, "Color value out of bounds (bounded)".into()));
|
||||
return Err(VmFault::Trap(TRAP_OOB, "Color value out of bounds (bounded)".into()));
|
||||
}
|
||||
let color = Color::from_raw(color_val as u16);
|
||||
hw.gfx_mut().clear(color);
|
||||
@@ -1209,7 +788,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Value::Int32(i) => *i as f64,
|
||||
Value::Int64(i) => *i as f64,
|
||||
Value::Bounded(b) => *b as f64,
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected number for pitch".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected number for pitch".into())),
|
||||
};
|
||||
|
||||
hw.audio_mut().play(0, sample_id as u16, voice_id, volume, pan, pitch, 0, prometeu_hal::LoopMode::Off);
|
||||
@@ -1221,7 +800,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::AudioPlay => {
|
||||
let asset_name = match args.get(0).ok_or_else(|| VmFault::Panic("Missing asset_name".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string asset_name".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string asset_name".into())),
|
||||
};
|
||||
let sample_id = expect_int(args, 1)? as u16;
|
||||
let voice_id = expect_int(args, 2)? as usize;
|
||||
@@ -1232,7 +811,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Value::Int32(i) => *i as f64,
|
||||
Value::Int64(i) => *i as f64,
|
||||
Value::Bounded(b) => *b as f64,
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected number for pitch".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected number for pitch".into())),
|
||||
};
|
||||
let loop_mode = match expect_int(args, 6)? {
|
||||
0 => prometeu_hal::LoopMode::Off,
|
||||
@@ -1252,7 +831,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::FsOpen => {
|
||||
let path = match args.get(0).ok_or_else(|| VmFault::Panic("Missing path".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string path".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string path".into())),
|
||||
};
|
||||
if self.fs_state != FsState::Mounted {
|
||||
ret.push_int(-1);
|
||||
@@ -1282,7 +861,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let handle = expect_int(args, 0)? as u32;
|
||||
let content = match args.get(1).ok_or_else(|| VmFault::Panic("Missing content".into()))? {
|
||||
Value::String(s) => s.as_bytes().to_vec(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string content".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string content".into())),
|
||||
};
|
||||
let path = self.open_files.get(&handle).ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
|
||||
match self.fs.write_file(path, &content) {
|
||||
@@ -1302,7 +881,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::FsListDir => {
|
||||
let path = match args.get(0).ok_or_else(|| VmFault::Panic("Missing path".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string path".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string path".into())),
|
||||
};
|
||||
match self.fs.list_dir(&path) {
|
||||
Ok(entries) => {
|
||||
@@ -1317,7 +896,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::FsExists => {
|
||||
let path = match args.get(0).ok_or_else(|| VmFault::Panic("Missing path".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string path".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string path".into())),
|
||||
};
|
||||
ret.push_bool(self.fs.exists(&path));
|
||||
Ok(())
|
||||
@@ -1326,7 +905,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::FsDelete => {
|
||||
let path = match args.get(0).ok_or_else(|| VmFault::Panic("Missing path".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string path".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string path".into())),
|
||||
};
|
||||
match self.fs.delete(&path) {
|
||||
Ok(_) => ret.push_bool(true),
|
||||
@@ -1342,7 +921,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let level = expect_int(args, 0)?;
|
||||
let msg = match args.get(1).ok_or_else(|| VmFault::Panic("Missing message".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string message".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
|
||||
};
|
||||
self.syscall_log_write(level, 0, msg)?;
|
||||
// void
|
||||
@@ -1354,7 +933,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let tag = expect_int(args, 1)? as u16;
|
||||
let msg = match args.get(2).ok_or_else(|| VmFault::Panic("Missing message".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string message".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string message".into())),
|
||||
};
|
||||
self.syscall_log_write(level, tag, msg)?;
|
||||
// void
|
||||
@@ -1365,15 +944,15 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
Syscall::AssetLoad => {
|
||||
let asset_id = match args.get(0).ok_or_else(|| VmFault::Panic("Missing asset_id".into()))? {
|
||||
Value::String(s) => s.clone(),
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Expected string asset_id".into())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Expected string asset_id".into())),
|
||||
};
|
||||
let asset_type_val = expect_int(args, 1)? as u32;
|
||||
let slot_index = expect_int(args, 2)? as usize;
|
||||
|
||||
|
||||
let asset_type = match asset_type_val {
|
||||
0 => BankType::TILES,
|
||||
1 => BankType::SOUNDS,
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
};
|
||||
let slot = SlotRef { asset_type, index: slot_index };
|
||||
|
||||
@@ -1416,7 +995,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let asset_type = match asset_type_val {
|
||||
0 => BankType::TILES,
|
||||
1 => BankType::SOUNDS,
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
};
|
||||
let info = hw.assets().bank_info(asset_type);
|
||||
let json = serde_json::to_string(&info).unwrap_or_default();
|
||||
@@ -1429,7 +1008,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
||||
let asset_type = match asset_type_val {
|
||||
0 => BankType::TILES,
|
||||
1 => BankType::SOUNDS,
|
||||
_ => return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||
};
|
||||
let slot = SlotRef { asset_type, index: slot_index };
|
||||
let info = hw.assets().slot_info(slot);
|
||||
|
||||
@@ -5,5 +5,5 @@ edition = "2024"
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
prometeu-bytecode = { path = "../../compiler/prometeu-bytecode" }
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
prometeu-hal = { path = "../prometeu-hal" }
|
||||
|
||||
@@ -5,8 +5,6 @@ pub mod local_addressing;
|
||||
pub mod verifier;
|
||||
pub mod vm_init_error;
|
||||
|
||||
pub use prometeu_bytecode::abi::TrapInfo;
|
||||
pub use prometeu_bytecode::opcode::OpCode;
|
||||
pub use prometeu_hal::{
|
||||
HostContext, HostReturn, NativeInterface, SyscallId,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::call_frame::CallFrame;
|
||||
use prometeu_bytecode::abi::{TrapInfo, TRAP_INVALID_LOCAL};
|
||||
use prometeu_bytecode::{TrapInfo, TRAP_INVALID_LOCAL};
|
||||
use prometeu_bytecode::FunctionMeta;
|
||||
|
||||
/// Computes the absolute stack index for the start of the current frame's locals (including args).
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use prometeu_hal::syscalls::Syscall;
|
||||
use prometeu_bytecode::decoder::{decode_next, DecodeError};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use prometeu_bytecode::opcode_spec::OpCodeSpecExt;
|
||||
use prometeu_bytecode::{decode_next, DecodeError};
|
||||
use prometeu_bytecode::OpCode;
|
||||
use prometeu_bytecode::OpCodeSpecExt;
|
||||
use prometeu_bytecode::FunctionMeta;
|
||||
use prometeu_bytecode::layout;
|
||||
use prometeu_bytecode::{compute_function_layouts, FunctionLayout};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -28,7 +28,7 @@ impl Verifier {
|
||||
pub fn verify(code: &[u8], functions: &[FunctionMeta]) -> Result<Vec<u16>, VerifierError> {
|
||||
let mut max_stacks = Vec::with_capacity(functions.len());
|
||||
// Precompute function [start, end) ranges once for O(1) lookups
|
||||
let layouts = layout::compute_function_layouts(functions, code.len());
|
||||
let layouts = compute_function_layouts(functions, code.len());
|
||||
for (i, func) in functions.iter().enumerate() {
|
||||
max_stacks.push(Self::verify_function(code, func, i, functions, &layouts)?);
|
||||
}
|
||||
@@ -40,7 +40,7 @@ impl Verifier {
|
||||
func: &FunctionMeta,
|
||||
func_idx: usize,
|
||||
all_functions: &[FunctionMeta],
|
||||
layouts: &[layout::FunctionLayout],
|
||||
layouts: &[FunctionLayout],
|
||||
) -> Result<u16, VerifierError> {
|
||||
let func_start = func.code_offset as usize;
|
||||
// Use precomputed canonical range end
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
use crate::call_frame::CallFrame;
|
||||
use crate::scope_frame::ScopeFrame;
|
||||
use crate::{HostContext, NativeInterface};
|
||||
use prometeu_bytecode::abi::{
|
||||
TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DEAD_GATE, TRAP_DIV_ZERO, TRAP_INVALID_FUNC, TRAP_INVALID_GATE, TRAP_OOB,
|
||||
TRAP_TYPE,
|
||||
};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use prometeu_bytecode::program_image::ProgramImage;
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_hal::vm_fault::VmFault;
|
||||
use crate::verifier::Verifier;
|
||||
use crate::vm_init_error::VmInitError;
|
||||
use crate::{HostContext, NativeInterface};
|
||||
use prometeu_bytecode::{TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DEAD_GATE, TRAP_DIV_ZERO, TRAP_INVALID_FUNC, TRAP_INVALID_GATE, TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_STACK_UNDERFLOW, TRAP_TYPE};
|
||||
use prometeu_bytecode::OpCode;
|
||||
use prometeu_bytecode::ProgramImage;
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_hal::vm_fault::VmFault;
|
||||
|
||||
/// Reason why the Virtual Machine stopped execution during a specific run.
|
||||
/// This allows the system to decide if it should continue execution in the next tick
|
||||
@@ -363,7 +360,7 @@ impl VirtualMachine {
|
||||
let start_pc = self.pc;
|
||||
|
||||
// Fetch & Decode
|
||||
let instr = prometeu_bytecode::decoder::decode_next(self.pc, &self.program.rom)
|
||||
let instr = prometeu_bytecode::decode_next(self.pc, &self.program.rom)
|
||||
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
||||
|
||||
let opcode = instr.opcode;
|
||||
@@ -884,7 +881,7 @@ impl VirtualMachine {
|
||||
let pc_at_syscall = start_pc as u32;
|
||||
let id = instr.imm_u32().map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
|
||||
let syscall = prometeu_hal::syscalls::Syscall::from_u32(id).ok_or_else(|| {
|
||||
self.trap(prometeu_bytecode::abi::TRAP_INVALID_SYSCALL, OpCode::Syscall as u16, format!("Unknown syscall: 0x{:08X}", id), pc_at_syscall)
|
||||
self.trap(TRAP_INVALID_SYSCALL, OpCode::Syscall as u16, format!("Unknown syscall: 0x{:08X}", id), pc_at_syscall)
|
||||
})?;
|
||||
|
||||
let args_count = syscall.args_count();
|
||||
@@ -892,7 +889,7 @@ impl VirtualMachine {
|
||||
let mut args = Vec::with_capacity(args_count);
|
||||
for _ in 0..args_count {
|
||||
let v = self.pop().map_err(|_e| {
|
||||
self.trap(prometeu_bytecode::abi::TRAP_STACK_UNDERFLOW, OpCode::Syscall as u16, "Syscall argument stack underflow".to_string(), pc_at_syscall)
|
||||
self.trap(TRAP_STACK_UNDERFLOW, OpCode::Syscall as u16, "Syscall argument stack underflow".to_string(), pc_at_syscall)
|
||||
})?;
|
||||
args.push(v);
|
||||
}
|
||||
@@ -1007,9 +1004,8 @@ mod tests {
|
||||
}]);
|
||||
vm
|
||||
}
|
||||
use crate::{HostReturn};
|
||||
use prometeu_bytecode::abi::SourceSpan;
|
||||
use prometeu_bytecode::FunctionMeta;
|
||||
use crate::HostReturn;
|
||||
use prometeu_bytecode::{FunctionMeta, TRAP_INVALID_LOCAL, TRAP_STACK_UNDERFLOW};
|
||||
use prometeu_hal::expect_int;
|
||||
|
||||
struct MockNative;
|
||||
@@ -1669,7 +1665,7 @@ mod tests {
|
||||
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_OOB);
|
||||
assert_eq!(trap.code, TRAP_OOB);
|
||||
assert_eq!(trap.opcode, OpCode::GateLoad as u16);
|
||||
assert!(trap.message.contains("Out-of-bounds"));
|
||||
}
|
||||
@@ -1696,7 +1692,7 @@ mod tests {
|
||||
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_TYPE);
|
||||
assert_eq!(trap.code, TRAP_TYPE);
|
||||
assert_eq!(trap.opcode, OpCode::GateLoad as u16);
|
||||
}
|
||||
_ => panic!("Expected Trap, got {:?}", report.reason),
|
||||
@@ -1772,7 +1768,7 @@ mod tests {
|
||||
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_INVALID_GATE);
|
||||
assert_eq!(trap.code, TRAP_INVALID_GATE);
|
||||
assert_eq!(trap.opcode, OpCode::GateLoad as u16);
|
||||
}
|
||||
_ => panic!("Expected Trap, got {:?}", report.reason),
|
||||
@@ -1903,7 +1899,7 @@ mod tests {
|
||||
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_TYPE);
|
||||
assert_eq!(trap.code, TRAP_TYPE);
|
||||
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
||||
}
|
||||
_ => panic!("Expected Trap, got {:?}", report.reason),
|
||||
@@ -1925,7 +1921,7 @@ mod tests {
|
||||
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_INVALID_SYSCALL);
|
||||
assert_eq!(trap.code, TRAP_INVALID_SYSCALL);
|
||||
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
||||
assert!(trap.message.contains("Unknown syscall"));
|
||||
assert_eq!(trap.pc, 0);
|
||||
@@ -1950,7 +1946,7 @@ mod tests {
|
||||
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_STACK_UNDERFLOW);
|
||||
assert_eq!(trap.code, TRAP_STACK_UNDERFLOW);
|
||||
assert_eq!(trap.opcode, OpCode::Syscall as u16);
|
||||
assert!(trap.message.contains("underflow"));
|
||||
assert_eq!(trap.pc, 0);
|
||||
@@ -1998,7 +1994,7 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
match res.err().unwrap() {
|
||||
VmFault::Trap(code, _) => {
|
||||
assert_eq!(code, prometeu_bytecode::abi::TRAP_OOB);
|
||||
assert_eq!(code, TRAP_OOB);
|
||||
}
|
||||
_ => panic!("Expected Trap"),
|
||||
}
|
||||
@@ -2430,7 +2426,7 @@ mod tests {
|
||||
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, prometeu_bytecode::abi::TRAP_INVALID_LOCAL);
|
||||
assert_eq!(trap.code, TRAP_INVALID_LOCAL);
|
||||
assert_eq!(trap.opcode, OpCode::GetLocal as u16);
|
||||
assert!(trap.message.contains("out of bounds"));
|
||||
}
|
||||
@@ -2577,97 +2573,4 @@ mod tests {
|
||||
_ => panic!("Expected Trap, got {:?}", report.reason),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_traceable_trap_with_span() {
|
||||
let mut rom = Vec::new();
|
||||
// 0: PUSH_I32 10 (6 bytes)
|
||||
// 6: PUSH_I32 0 (6 bytes)
|
||||
// 12: DIV (2 bytes)
|
||||
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
||||
rom.extend_from_slice(&10i32.to_le_bytes());
|
||||
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
||||
rom.extend_from_slice(&0i32.to_le_bytes());
|
||||
rom.extend_from_slice(&(OpCode::Div as u16).to_le_bytes());
|
||||
|
||||
let mut pc_to_span = Vec::new();
|
||||
pc_to_span.push((0, SourceSpan { file_id: 1, start: 10, end: 15 }));
|
||||
pc_to_span.push((6, SourceSpan { file_id: 1, start: 16, end: 20 }));
|
||||
pc_to_span.push((12, SourceSpan { file_id: 1, start: 21, end: 25 }));
|
||||
|
||||
let debug_info = prometeu_bytecode::DebugInfo {
|
||||
pc_to_span,
|
||||
function_names: vec![(0, "main".to_string())],
|
||||
};
|
||||
|
||||
let program = ProgramImage::new(rom.clone(), vec![], vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: rom.len() as u32,
|
||||
..Default::default()
|
||||
}], Some(debug_info), std::collections::HashMap::new());
|
||||
let mut vm = VirtualMachine {
|
||||
program,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut native = MockNative;
|
||||
let mut ctx = HostContext::new(None);
|
||||
|
||||
vm.prepare_call("0");
|
||||
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, TRAP_DIV_ZERO);
|
||||
assert_eq!(trap.pc, 12);
|
||||
assert_eq!(trap.span, Some(SourceSpan { file_id: 1, start: 21, end: 25 }));
|
||||
}
|
||||
_ => panic!("Expected Trap, got {:?}", report.reason),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_traceable_trap_with_function_name() {
|
||||
let mut rom = Vec::new();
|
||||
// 0: PUSH_I32 10 (6 bytes)
|
||||
// 6: PUSH_I32 0 (6 bytes)
|
||||
// 12: DIV (2 bytes)
|
||||
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
||||
rom.extend_from_slice(&10i32.to_le_bytes());
|
||||
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
|
||||
rom.extend_from_slice(&0i32.to_le_bytes());
|
||||
rom.extend_from_slice(&(OpCode::Div as u16).to_le_bytes());
|
||||
|
||||
let pc_to_span = vec![(12, SourceSpan { file_id: 1, start: 21, end: 25 })];
|
||||
let function_names = vec![(0, "math_utils::divide".to_string())];
|
||||
|
||||
let debug_info = prometeu_bytecode::DebugInfo {
|
||||
pc_to_span,
|
||||
function_names,
|
||||
};
|
||||
|
||||
let functions = vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: rom.len() as u32,
|
||||
..Default::default()
|
||||
}];
|
||||
|
||||
let program = ProgramImage::new(rom, vec![], functions, Some(debug_info), std::collections::HashMap::new());
|
||||
let mut vm = VirtualMachine {
|
||||
program,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut native = MockNative;
|
||||
let mut ctx = HostContext::new(None);
|
||||
|
||||
vm.prepare_call("0");
|
||||
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
|
||||
match report.reason {
|
||||
LogicalFrameEndingReason::Trap(trap) => {
|
||||
assert_eq!(trap.code, TRAP_DIV_ZERO);
|
||||
assert!(trap.message.contains("math_utils::divide"));
|
||||
}
|
||||
_ => panic!("Expected Trap, got {:?}", report.reason),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user