added domains into crates
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,152 @@
|
||||
# prometeu-bytecode
|
||||
|
||||
Official contract (ABI) of the PROMETEU ecosystem. This crate defines the Instruction Set Architecture (ISA), the `.pbc` file format (Prometeu ByteCode), and basic tools for assembly (Assembler) and disassembly (Disassembler).
|
||||
|
||||
## Design
|
||||
|
||||
The PVM (Prometeu Virtual Machine) is a **stack-based** machine. Most instructions operate on values at the top of the operand stack. The default multi-byte data format in ROM is **Little-Endian**.
|
||||
|
||||
### Stack Notation Convention
|
||||
In the tables below, we use the following notation to represent the state of the stack:
|
||||
`[a, b] -> [c]`
|
||||
Means the instruction removes `a` and `b` from the stack (where `b` was at the top) and pushes `c` to the top.
|
||||
|
||||
---
|
||||
|
||||
## Instruction Set Architecture (ISA)
|
||||
|
||||
### 6.1 Execution Control
|
||||
|
||||
| OpCode | Value | Operands | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `Nop` | `0x00` | - | `[] -> []` | No operation. |
|
||||
| `Halt` | `0x01` | - | `[] -> []` | Permanently halts VM execution. |
|
||||
| `Jmp` | `0x02` | `addr: u32` | `[] -> []` | Unconditional jump to absolute address `addr`. |
|
||||
| `JmpIfFalse`| `0x03` | `addr: u32` | `[bool] -> []` | Jumps to `addr` if the popped value is `false`. |
|
||||
| `JmpIfTrue` | `0x04` | `addr: u32` | `[bool] -> []` | Jumps to `addr` if the popped value is `true`. |
|
||||
| `Trap` | `0x05` | - | `[] -> []` | Debugger interruption (breakpoint). |
|
||||
|
||||
### 6.2 Stack Manipulation
|
||||
|
||||
| OpCode | Value | Operands | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `PushConst` | `0x10` | `idx: u32` | `[] -> [val]` | Loads the constant at index `idx` from the Constant Pool. |
|
||||
| `Pop` | `0x11` | - | `[val] -> []` | Removes and discards the top value of the stack. |
|
||||
| `Dup` | `0x12` | - | `[val] -> [val, val]` | Duplicates the value at the top of the stack. |
|
||||
| `Swap` | `0x13` | - | `[a, b] -> [b, a]` | Swaps the positions of the two values at the top. |
|
||||
| `PushI64` | `0x14` | `val: i64` | `[] -> [i64]` | Pushes an immediate 64-bit integer. |
|
||||
| `PushF64` | `0x15` | `val: f64` | `[] -> [f64]` | Pushes an immediate 64-bit floating point. |
|
||||
| `PushBool` | `0x16` | `val: u8` | `[] -> [bool]` | Pushes a boolean (0=false, 1=true). |
|
||||
| `PushI32` | `0x17` | `val: i32` | `[] -> [i32]` | Pushes an immediate 32-bit integer. |
|
||||
| `PopN` | `0x18` | `n: u16` | `[...] -> [...]` | Removes `n` values from the stack at once. |
|
||||
|
||||
### 6.3 Arithmetic
|
||||
The VM performs automatic type promotion (e.g., `i32` + `f64` results in `f64`).
|
||||
|
||||
| OpCode | Value | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `Add` | `0x20` | `[a, b] -> [a + b]` | Adds the two top values. |
|
||||
| `Sub` | `0x21` | `[a, b] -> [a - b]` | Subtracts `b` from `a`. |
|
||||
| `Mul` | `0x22` | `[a, b] -> [a * b]` | Multiplies the two top values. |
|
||||
| `Div` | `0x23` | `[a, b] -> [a / b]` | Divides `a` by `b`. Error if `b == 0`. |
|
||||
| `Neg` | `0x3E` | `[a] -> [-a]` | Negates the numeric sign. |
|
||||
|
||||
### 6.4 Logic and Comparison
|
||||
|
||||
| OpCode | Value | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `Eq` | `0x30` | `[a, b] -> [bool]` | Tests equality. |
|
||||
| `Neq` | `0x31` | `[a, b] -> [bool]` | Tests inequality. |
|
||||
| `Lt` | `0x32` | `[a, b] -> [bool]` | `a < b` |
|
||||
| `Gt` | `0x33` | `[a, b] -> [bool]` | `a > b` |
|
||||
| `Lte` | `0x3C` | `[a, b] -> [bool]` | `a <= b` |
|
||||
| `Gte` | `0x3D` | `[a, b] -> [bool]` | `a >= b` |
|
||||
| `And` | `0x34` | `[a, b] -> [bool]` | Logical AND (boolean). |
|
||||
| `Or` | `0x35` | `[a, b] -> [bool]` | Logical OR (boolean). |
|
||||
| `Not` | `0x36` | `[a] -> [!a]` | Logical NOT. |
|
||||
| `BitAnd` | `0x37` | `[a, b] -> [int]` | Bitwise AND. |
|
||||
| `BitOr` | `0x38` | `[a, b] -> [int]` | Bitwise OR. |
|
||||
| `BitXor` | `0x39` | `[a, b] -> [int]` | Bitwise XOR. |
|
||||
| `Shl` | `0x3A` | `[a, b] -> [int]` | Shift Left: `a << b`. |
|
||||
| `Shr` | `0x3B` | `[a, b] -> [int]` | Shift Right: `a >> b`. |
|
||||
|
||||
### 6.5 Variables and Memory
|
||||
|
||||
| OpCode | Value | Operands | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `GetGlobal`| `0x40` | `idx: u32` | `[] -> [val]` | Loads value from global `idx`. |
|
||||
| `SetGlobal`| `0x41` | `idx: u32` | `[val] -> []` | Stores top of stack in global `idx`. |
|
||||
| `GetLocal` | `0x42` | `idx: u32` | `[] -> [val]` | Loads local `idx` from the current frame. |
|
||||
| `SetLocal` | `0x43` | `idx: u32` | `[val] -> []` | Stores top of stack in local `idx` of the current frame. |
|
||||
|
||||
### 6.6 Functions and Scope
|
||||
|
||||
| OpCode | Value | Operands | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `Call` | `0x50` | `addr: u32, args: u32` | `[a1, a2] -> [...]` | Calls `addr`. The `args` values at the top become locals of the new frame. |
|
||||
| `Ret` | `0x51` | - | `[val] -> [val]` | Returns from the current function, clearing the frame and returning the top value. |
|
||||
| `PushScope`| `0x52` | - | `[] -> []` | Starts a sub-scope (block) for temporary locals. |
|
||||
| `PopScope` | `0x53` | - | `[] -> []` | Ends sub-scope, removing locals created in it from the stack. |
|
||||
|
||||
### 6.7 Heap (Dynamic Memory)
|
||||
|
||||
| OpCode | Value | Operands | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `Alloc` | `0x60` | `size: u32` | `[] -> [ref]` | Allocates `size` slots on the heap and returns a reference. |
|
||||
| `LoadRef` | `0x61` | `offset: u32`| `[ref] -> [val]` | Reads value from the heap at address `ref + offset`. |
|
||||
| `StoreRef`| `0x62` | `offset: u32`| `[ref, val] -> []` | Writes `val` to the heap at address `ref + offset`. |
|
||||
|
||||
### 6.8 System and Synchronization
|
||||
|
||||
| OpCode | Value | Operands | Stack | Description |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `Syscall` | `0x70` | `id: u32` | `[...] -> [...]` | Invokes a system/firmware function. The stack depends on the syscall. |
|
||||
| `FrameSync`| `0x80` | - | `[] -> []` | Marks the end of processing for the current logical frame (60 FPS). |
|
||||
|
||||
---
|
||||
|
||||
## PBC Structure (Prometeu ByteCode)
|
||||
|
||||
PBC is the official binary format for Prometeu programs.
|
||||
|
||||
```rust
|
||||
// Example of how to load a PBC file
|
||||
let bytes = std::fs::read("game.pbc")?;
|
||||
let pbc = prometeu_bytecode::pbc::parse_pbc(&bytes)?;
|
||||
|
||||
println!("ROM size: {} bytes", pbc.rom.len());
|
||||
println!("Constants: {}", pbc.cp.len());
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Assembler and Disassembler
|
||||
|
||||
This crate provides tools to facilitate code generation and inspection.
|
||||
|
||||
### Assembly (Assembler)
|
||||
```rust
|
||||
use prometeu_bytecode::asm::{assemble, Asm, Operand};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
|
||||
let instructions = vec![
|
||||
Asm::Op(OpCode::PushI32, vec![Operand::I32(10)]),
|
||||
Asm::Op(OpCode::PushI32, vec![Operand::I32(20)]),
|
||||
Asm::Op(OpCode::Add, vec![]),
|
||||
Asm::Op(OpCode::Halt, vec![]),
|
||||
];
|
||||
|
||||
let rom_bytes = assemble(&instructions).unwrap();
|
||||
```
|
||||
|
||||
### Disassembly (Disassembler)
|
||||
```rust
|
||||
use prometeu_bytecode::disasm::disasm;
|
||||
|
||||
let rom = vec![/* ... bytes ... */];
|
||||
let code = disasm(&rom);
|
||||
|
||||
for instr in code {
|
||||
println!("{:04X}: {:?} {:?}", instr.pc, instr.opcode, instr.operands);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,147 @@
|
||||
//! 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.
|
||||
|
||||
use crate::opcode::OpCode;
|
||||
use crate::opcode_spec::OpCodeSpecExt;
|
||||
|
||||
/// Returns the size in bytes of the operands for a given OpCode.
|
||||
///
|
||||
/// Note: This does NOT include the 2 bytes of the OpCode itself.
|
||||
/// For example, `PushI32` has a size of 4, but occupies 6 bytes in ROM (2 for OpCode + 4 for value).
|
||||
pub fn operand_size(opcode: OpCode) -> usize {
|
||||
opcode.spec().imm_bytes as usize
|
||||
}
|
||||
|
||||
// --- 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>,
|
||||
}
|
||||
|
||||
/// Checks if an instruction is a jump (branch) instruction.
|
||||
pub fn is_jump(opcode: OpCode) -> bool {
|
||||
opcode.spec().is_branch
|
||||
}
|
||||
|
||||
/// Checks if an instruction has any immediate operands in the instruction stream.
|
||||
pub fn has_immediate(opcode: OpCode) -> bool {
|
||||
opcode.spec().imm_bytes > 0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_trap_code_stability() {
|
||||
// These numeric values are normative and must not change.
|
||||
assert_eq!(TRAP_INVALID_GATE, 0x01);
|
||||
assert_eq!(TRAP_DEAD_GATE, 0x02);
|
||||
assert_eq!(TRAP_OOB, 0x03);
|
||||
assert_eq!(TRAP_TYPE, 0x04);
|
||||
assert_eq!(TRAP_INVALID_SYSCALL, 0x07);
|
||||
assert_eq!(TRAP_STACK_UNDERFLOW, 0x08);
|
||||
assert_eq!(TRAP_INVALID_LOCAL, 0x09);
|
||||
assert_eq!(TRAP_DIV_ZERO, 0x0A);
|
||||
assert_eq!(TRAP_INVALID_FUNC, 0x0B);
|
||||
assert_eq!(TRAP_BAD_RET_SLOTS, 0x0C);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_abi_documentation_snapshot() {
|
||||
// Snapshot of the ABI rules for traps and operands.
|
||||
let abi_info = r#"
|
||||
HIP Traps:
|
||||
- INVALID_GATE (0x01): Non-existent gate handle.
|
||||
- DEAD_GATE (0x02): Gate handle with RC=0.
|
||||
- OOB (0x03): Access beyond allocated slots.
|
||||
- TYPE (0x04): Type mismatch during heap access.
|
||||
|
||||
System Traps:
|
||||
- INVALID_SYSCALL (0x07): Unknown syscall ID.
|
||||
- STACK_UNDERFLOW (0x08): Missing syscall arguments.
|
||||
- INVALID_LOCAL (0x09): Local slot out of bounds.
|
||||
- DIV_ZERO (0x0A): Division by zero.
|
||||
- INVALID_FUNC (0x0B): Function table index out of bounds.
|
||||
- BAD_RET_SLOTS (0x0C): Stack height mismatch at RET.
|
||||
|
||||
Operand Sizes:
|
||||
- Alloc: 8 bytes (u32 type_id, u32 slots)
|
||||
- GateLoad: 4 bytes (u32 offset)
|
||||
- GateStore: 4 bytes (u32 offset)
|
||||
- PopN: 4 bytes (u32 count)
|
||||
"#;
|
||||
// This test serves as a "doc-lock".
|
||||
// If you change the ABI, you must update this string.
|
||||
let current_info = format!(
|
||||
"\nHIP Traps:\n- INVALID_GATE (0x{:02X}): Non-existent gate handle.\n- DEAD_GATE (0x{:02X}): Gate handle with RC=0.\n- OOB (0x{:02X}): Access beyond allocated slots.\n- TYPE (0x{:02X}): Type mismatch during heap access.\n\nSystem Traps:\n- INVALID_SYSCALL (0x{:02X}): Unknown syscall ID.\n- STACK_UNDERFLOW (0x{:02X}): Missing syscall arguments.\n- INVALID_LOCAL (0x{:02X}): Local slot out of bounds.\n- DIV_ZERO (0x{:02X}): Division by zero.\n- INVALID_FUNC (0x{:02X}): Function table index out of bounds.\n- BAD_RET_SLOTS (0x{:02X}): Stack height mismatch at RET.\n\nOperand Sizes:\n- Alloc: {} bytes (u32 type_id, u32 slots)\n- GateLoad: {} bytes (u32 offset)\n- GateStore: {} bytes (u32 offset)\n- PopN: {} bytes (u32 count)\n",
|
||||
TRAP_INVALID_GATE, TRAP_DEAD_GATE, TRAP_OOB, TRAP_TYPE,
|
||||
TRAP_INVALID_SYSCALL, TRAP_STACK_UNDERFLOW, TRAP_INVALID_LOCAL, TRAP_DIV_ZERO, TRAP_INVALID_FUNC, TRAP_BAD_RET_SLOTS,
|
||||
operand_size(OpCode::Alloc),
|
||||
operand_size(OpCode::GateLoad),
|
||||
operand_size(OpCode::GateStore),
|
||||
operand_size(OpCode::PopN)
|
||||
);
|
||||
|
||||
assert_eq!(current_info.trim(), abi_info.trim());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operand_size_matches_spec_for_all_opcodes() {
|
||||
// Scan a generous numeric range and validate every decodable opcode.
|
||||
// This ensures that abi::operand_size (if kept) never diverges from the
|
||||
// canonical spec (OpcodeSpec::imm_bytes).
|
||||
for raw in 0u16..=1023u16 {
|
||||
if let Ok(op) = OpCode::try_from(raw) {
|
||||
assert_eq!(
|
||||
operand_size(op),
|
||||
op.spec().imm_bytes as usize,
|
||||
"operand_size must match spec for {:?}",
|
||||
op
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::opcode::OpCode;
|
||||
use crate::readwrite::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Represents an operand for an instruction.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Operand {
|
||||
/// 32-bit unsigned integer (e.g., indices, addresses).
|
||||
U32(u32),
|
||||
/// 32-bit signed integer.
|
||||
I32(i32),
|
||||
/// 64-bit signed integer.
|
||||
I64(i64),
|
||||
/// 64-bit floating point.
|
||||
F64(f64),
|
||||
/// Boolean (true/false).
|
||||
Bool(bool),
|
||||
/// A symbolic label that will be resolved to an absolute PC address.
|
||||
Label(String),
|
||||
/// A symbolic label that will be resolved to a PC address relative to another label.
|
||||
RelLabel(String, String),
|
||||
}
|
||||
|
||||
/// Represents an assembly-level element (either an instruction or a label).
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Asm {
|
||||
/// An OpCode followed by its operands. The mnemonics represent the operation to be performed.
|
||||
Op(OpCode, Vec<Operand>),
|
||||
/// A named marker in the code (e.g., "start:").
|
||||
Label(String),
|
||||
}
|
||||
|
||||
/// Internal helper to calculate the next PC based on the operands' sizes.
|
||||
pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
|
||||
let mut pcp: u32 = initial_pc;
|
||||
for operand in operands {
|
||||
match operand {
|
||||
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) | Operand::RelLabel(_, _) => pcp += 4,
|
||||
Operand::I64(_) | Operand::F64(_) => pcp += 8,
|
||||
Operand::Bool(_) => pcp += 1,
|
||||
}
|
||||
}
|
||||
pcp
|
||||
}
|
||||
|
||||
pub struct AssembleResult {
|
||||
pub code: Vec<u8>,
|
||||
pub unresolved_labels: HashMap<String, Vec<u32>>,
|
||||
}
|
||||
|
||||
/// Converts a list of assembly instructions into raw ROM bytes.
|
||||
///
|
||||
/// The assembly process is done in two passes:
|
||||
/// 1. **Label Resolution**: Iterates through all instructions to calculate the PC (Program Counter)
|
||||
/// of each label and stores them in a map.
|
||||
/// 2. **Code Generation**: Translates each OpCode and its operands (resolving labels using the map)
|
||||
/// into the final binary format.
|
||||
pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
|
||||
let res = assemble_with_unresolved(instructions)?;
|
||||
if !res.unresolved_labels.is_empty() {
|
||||
let labels: Vec<_> = res.unresolved_labels.keys().cloned().collect();
|
||||
return Err(format!("Undefined labels: {:?}", labels));
|
||||
}
|
||||
Ok(res.code)
|
||||
}
|
||||
|
||||
pub fn assemble_with_unresolved(instructions: &[Asm]) -> Result<AssembleResult, String> {
|
||||
let mut labels = HashMap::new();
|
||||
let mut current_pc = 0u32;
|
||||
|
||||
// First pass: resolve labels
|
||||
for instr in instructions {
|
||||
match instr {
|
||||
Asm::Label(name) => {
|
||||
labels.insert(name.clone(), current_pc);
|
||||
}
|
||||
Asm::Op(_opcode, operands) => {
|
||||
current_pc += 2; // OpCode is u16 (2 bytes)
|
||||
current_pc = update_pc_by_operand(current_pc, operands);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: generate bytes
|
||||
let mut rom = Vec::new();
|
||||
let mut unresolved_labels: HashMap<String, Vec<u32>> = HashMap::new();
|
||||
let mut pc = 0u32;
|
||||
|
||||
for instr in instructions {
|
||||
match instr {
|
||||
Asm::Label(_) => {}
|
||||
Asm::Op(opcode, operands) => {
|
||||
write_u16_le(&mut rom, *opcode as u16).map_err(|e| e.to_string())?;
|
||||
pc += 2;
|
||||
for operand in operands {
|
||||
match operand {
|
||||
Operand::U32(v) => {
|
||||
write_u32_le(&mut rom, *v).map_err(|e| e.to_string())?;
|
||||
pc += 4;
|
||||
}
|
||||
Operand::I32(v) => {
|
||||
write_u32_le(&mut rom, *v as u32).map_err(|e| e.to_string())?;
|
||||
pc += 4;
|
||||
}
|
||||
Operand::I64(v) => {
|
||||
write_i64_le(&mut rom, *v).map_err(|e| e.to_string())?;
|
||||
pc += 8;
|
||||
}
|
||||
Operand::F64(v) => {
|
||||
write_f64_le(&mut rom, *v).map_err(|e| e.to_string())?;
|
||||
pc += 8;
|
||||
}
|
||||
Operand::Bool(v) => {
|
||||
rom.push(if *v { 1 } else { 0 });
|
||||
pc += 1;
|
||||
}
|
||||
Operand::Label(name) => {
|
||||
if let Some(addr) = labels.get(name) {
|
||||
write_u32_le(&mut rom, *addr).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
unresolved_labels.entry(name.clone()).or_default().push(pc);
|
||||
write_u32_le(&mut rom, 0).map_err(|e| e.to_string())?; // Placeholder
|
||||
}
|
||||
pc += 4;
|
||||
}
|
||||
Operand::RelLabel(name, base) => {
|
||||
let addr = labels.get(name).ok_or(format!("Undefined label: {}", name))?;
|
||||
let base_addr = labels.get(base).ok_or(format!("Undefined base label: {}", base))?;
|
||||
let rel_addr = (*addr as i64) - (*base_addr as i64);
|
||||
write_u32_le(&mut rom, rel_addr as u32).map_err(|e| e.to_string())?;
|
||||
pc += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(AssembleResult {
|
||||
code: rom,
|
||||
unresolved_labels,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
//! 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<'a>(pc: usize, bytes: &'a [u8]) -> Result<DecodedInstr<'a>, 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],
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::asm::{assemble, Asm, Operand};
|
||||
use crate::opcode::OpCode;
|
||||
|
||||
#[test]
|
||||
fn decode_basic_no_imm() {
|
||||
// Encode a NOP (0x0000)
|
||||
let rom = assemble(&[Asm::Op(OpCode::Nop, vec![])]).unwrap();
|
||||
let d = decode_next(0, &rom).unwrap();
|
||||
assert_eq!(d.opcode, OpCode::Nop);
|
||||
assert_eq!(d.pc, 0);
|
||||
assert_eq!(d.next_pc, 2);
|
||||
assert_eq!(d.imm.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_with_u32_imm() {
|
||||
// PUSH_CONST 0x11223344
|
||||
let rom = assemble(&[Asm::Op(OpCode::PushConst, vec![Operand::U32(0x11223344)])]).unwrap();
|
||||
let d = decode_next(0, &rom).unwrap();
|
||||
assert_eq!(d.opcode, OpCode::PushConst);
|
||||
assert_eq!(d.imm_u32().unwrap(), 0x11223344);
|
||||
assert_eq!(d.next_pc, 2 + 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_with_u8_imm() {
|
||||
// PUSH_BOOL true
|
||||
let rom = assemble(&[Asm::Op(OpCode::PushBool, vec![Operand::Bool(true)])]).unwrap();
|
||||
let d = decode_next(0, &rom).unwrap();
|
||||
assert_eq!(d.opcode, OpCode::PushBool);
|
||||
assert_eq!(d.imm.len(), 1);
|
||||
assert_eq!(d.imm_u8().unwrap(), 1);
|
||||
assert_eq!(d.next_pc, 2 + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_with_i64_and_f64() {
|
||||
// PUSH_I64, PUSH_F64
|
||||
let rom = assemble(&[
|
||||
Asm::Op(OpCode::PushI64, vec![Operand::I64(-123)]),
|
||||
Asm::Op(OpCode::PushF64, vec![Operand::F64(3.25)]),
|
||||
]).unwrap();
|
||||
|
||||
let d0 = decode_next(0, &rom).unwrap();
|
||||
assert_eq!(d0.opcode, OpCode::PushI64);
|
||||
assert_eq!(d0.imm_i64().unwrap(), -123);
|
||||
|
||||
let d1 = decode_next(d0.next_pc, &rom).unwrap();
|
||||
assert_eq!(d1.opcode, OpCode::PushF64);
|
||||
assert!((d1.imm_f64().unwrap() - 3.25).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_truncated() {
|
||||
let rom: Vec<u8> = vec![0x00, 0x00]; // NOP complete
|
||||
assert!(matches!(decode_next(1, &rom), Err(DecodeError::TruncatedOpcode { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_encode_decode_table() {
|
||||
let rom = assemble(&[
|
||||
Asm::Op(OpCode::Nop, vec![]),
|
||||
Asm::Op(OpCode::PushConst, vec![Operand::U32(7)]),
|
||||
Asm::Op(OpCode::Jmp, vec![Operand::U32(4)]),
|
||||
Asm::Op(OpCode::PushI64, vec![Operand::I64(42)]),
|
||||
Asm::Op(OpCode::Halt, vec![]),
|
||||
]).unwrap();
|
||||
|
||||
let mut pc = 0usize;
|
||||
let mut decoded = Vec::new();
|
||||
while pc < rom.len() {
|
||||
let d = decode_next(pc, &rom).unwrap();
|
||||
decoded.push(d.opcode);
|
||||
pc = d.next_pc;
|
||||
}
|
||||
|
||||
assert_eq!(decoded, vec![OpCode::Nop, OpCode::PushConst, OpCode::Jmp, OpCode::PushI64, OpCode::Halt]);
|
||||
assert_eq!(pc, rom.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use crate::opcode::OpCode;
|
||||
use crate::readwrite::*;
|
||||
use std::io::{Cursor, Read};
|
||||
|
||||
/// Represents a disassembled instruction.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Instr {
|
||||
/// The absolute address (PC) where this instruction starts in ROM.
|
||||
pub pc: u32,
|
||||
/// The decoded OpCode.
|
||||
pub opcode: OpCode,
|
||||
/// The list of operands extracted from the byte stream.
|
||||
pub operands: Vec<DisasmOperand>,
|
||||
}
|
||||
|
||||
/// Represents an operand decoded from the byte stream.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum DisasmOperand {
|
||||
U32(u32),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
F64(f64),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// Translates raw ROM bytes back into a human-readable list of instructions.
|
||||
///
|
||||
/// This is the inverse of the assembly process. It reads the bytes sequentially,
|
||||
/// identifies the OpCode, and then reads the correct number of operand bytes
|
||||
/// based on the ISA rules.
|
||||
pub fn disasm(rom: &[u8]) -> Result<Vec<Instr>, String> {
|
||||
let mut instructions = Vec::new();
|
||||
let mut cursor = Cursor::new(rom);
|
||||
|
||||
while (cursor.position() as usize) < rom.len() {
|
||||
let pc = cursor.position() as u32;
|
||||
let op_val = read_u16_le(&mut cursor).map_err(|e| e.to_string())?;
|
||||
let opcode = OpCode::try_from(op_val)?;
|
||||
let mut operands = Vec::new();
|
||||
|
||||
match opcode {
|
||||
OpCode::PushConst | OpCode::PushI32 | OpCode::PushBounded | OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue
|
||||
| OpCode::GetGlobal | OpCode::SetGlobal | OpCode::GetLocal | OpCode::SetLocal
|
||||
| OpCode::PopN | OpCode::Syscall | OpCode::GateLoad | OpCode::GateStore | OpCode::Call => {
|
||||
let v = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
|
||||
operands.push(DisasmOperand::U32(v));
|
||||
}
|
||||
OpCode::PushI64 | OpCode::PushF64 => {
|
||||
let v = read_i64_le(&mut cursor).map_err(|e| e.to_string())?;
|
||||
operands.push(DisasmOperand::I64(v));
|
||||
}
|
||||
OpCode::PushBool => {
|
||||
let mut b_buf = [0u8; 1];
|
||||
cursor.read_exact(&mut b_buf).map_err(|e| e.to_string())?;
|
||||
operands.push(DisasmOperand::Bool(b_buf[0] != 0));
|
||||
}
|
||||
OpCode::Alloc => {
|
||||
let v1 = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
|
||||
let v2 = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
|
||||
operands.push(DisasmOperand::U32(v1));
|
||||
operands.push(DisasmOperand::U32(v2));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
instructions.push(Instr { pc, opcode, operands });
|
||||
}
|
||||
|
||||
Ok(instructions)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub fn read_u32_le(buf: &[u8], pos: usize) -> Option<u32> {
|
||||
let b = buf.get(pos..pos + 4)?;
|
||||
Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
|
||||
pub fn write_u32_le(buf: &mut [u8], pos: usize, v: u32) -> Option<()> {
|
||||
let b = buf.get_mut(pos..pos + 4)?;
|
||||
let le = v.to_le_bytes();
|
||||
b.copy_from_slice(&le);
|
||||
Some(())
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! 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::decoder::decode_next;
|
||||
use crate::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
|
||||
}
|
||||
|
||||
/// Recomputes all `code_len` values in place from the next function start
|
||||
/// (exclusive end), using the combined code buffer length for the last one.
|
||||
pub fn recompute_function_lengths_in_place(functions: &mut [FunctionMeta], code_len_total: usize) {
|
||||
let layouts = compute_function_layouts(functions, code_len_total);
|
||||
for i in 0..functions.len() {
|
||||
let start = layouts[i].start;
|
||||
let end = layouts[i].end;
|
||||
functions[i].code_len = end.saturating_sub(start) as u32;
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the function index that contains `pc_abs` (absolute), using the
|
||||
/// canonical ranges (end = next start, exclusive). Returns `None` if none.
|
||||
pub fn function_index_by_pc(functions: &[FunctionMeta], code_len_total: usize, pc_abs: usize) -> Option<usize> {
|
||||
let layouts = compute_function_layouts(functions, code_len_total);
|
||||
for i in 0..functions.len() {
|
||||
let start = layouts[i].start;
|
||||
let end = layouts[i].end;
|
||||
if pc_abs >= start && pc_abs < end {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Alias: canonical function lookup by absolute PC.
|
||||
#[inline]
|
||||
pub fn lookup_function_by_pc(functions: &[FunctionMeta], code_len_total: usize, pc_abs: usize) -> Option<usize> {
|
||||
function_index_by_pc(functions, code_len_total, pc_abs)
|
||||
}
|
||||
|
||||
/// Returns true if `rel_pc` (relative to the function start) is a valid
|
||||
/// instruction boundary as determined by the canonical decoder.
|
||||
///
|
||||
/// Contract:
|
||||
/// - `rel_pc == 0` is always a boundary if `func_idx` is valid.
|
||||
/// - Boundaries are computed by stepping with `decoder::decode_next` from the
|
||||
/// function start up to (and possibly past) `rel_pc` but never beyond the
|
||||
/// function exclusive end.
|
||||
/// - Any decode error before reaching `rel_pc` yields `false` (invalid program).
|
||||
pub fn is_boundary(functions: &[FunctionMeta], code: &[u8], code_len_total: usize, func_idx: usize, rel_pc: usize) -> bool {
|
||||
let (start, end) = match functions.get(func_idx) {
|
||||
Some(_) => {
|
||||
let layouts = compute_function_layouts(functions, code_len_total);
|
||||
let l = &layouts[func_idx];
|
||||
(l.start, l.end)
|
||||
}
|
||||
None => return false,
|
||||
};
|
||||
|
||||
let func_len = end.saturating_sub(start);
|
||||
if rel_pc == 0 { return true; }
|
||||
if rel_pc > func_len { return false; }
|
||||
|
||||
let target = start + rel_pc;
|
||||
let mut pc = start;
|
||||
while pc < end {
|
||||
match decode_next(pc, code) {
|
||||
Ok(di) => {
|
||||
let next = di.next_pc;
|
||||
if next > end { return false; }
|
||||
if next == target { return true; }
|
||||
if next <= pc { return false; } // must make progress
|
||||
pc = next;
|
||||
if pc > target { return false; }
|
||||
}
|
||||
Err(_) => return false,
|
||||
}
|
||||
}
|
||||
// If we reached end without matching `target`, only boundary is exact end
|
||||
target == end
|
||||
}
|
||||
|
||||
/// Returns true if `abs_pc` is a valid instruction boundary for the function
|
||||
/// containing it, according to the canonical decoder. Returns false if `abs_pc`
|
||||
/// is not within any function range or if decoding fails.
|
||||
pub fn is_boundary_abs(functions: &[FunctionMeta], code: &[u8], code_len_total: usize, abs_pc: usize) -> bool {
|
||||
if let Some(func_idx) = lookup_function_by_pc(functions, code_len_total, abs_pc) {
|
||||
let layouts = compute_function_layouts(functions, code_len_total);
|
||||
let (start, _end) = {
|
||||
let l = &layouts[func_idx];
|
||||
(l.start, l.end)
|
||||
};
|
||||
let rel = abs_pc.saturating_sub(start);
|
||||
return is_boundary(functions, code, code_len_total, func_idx, rel);
|
||||
}
|
||||
|
||||
// Not inside any function range; allow exact function starts/ends as
|
||||
// valid boundaries (e.g., last function end == total code len).
|
||||
let layouts = compute_function_layouts(functions, code_len_total);
|
||||
for i in 0..functions.len() {
|
||||
let start = layouts[i].start;
|
||||
let end = layouts[i].end;
|
||||
if abs_pc == start || abs_pc == end {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::asm::{assemble, Asm, Operand};
|
||||
use crate::opcode::OpCode;
|
||||
|
||||
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 boundaries_known_sequence() {
|
||||
// Build a function with mixed immediate sizes:
|
||||
// [NOP][PUSH_I32 4][PUSH_I64 8][PUSH_BOOL 1][HALT]
|
||||
let code = assemble(&[
|
||||
Asm::Op(OpCode::Nop, vec![]),
|
||||
Asm::Op(OpCode::PushI32, vec![Operand::I32(123)]),
|
||||
Asm::Op(OpCode::PushI64, vec![Operand::I64(42)]),
|
||||
Asm::Op(OpCode::PushBool, vec![Operand::Bool(true)]),
|
||||
Asm::Op(OpCode::Halt, vec![]),
|
||||
]).unwrap();
|
||||
|
||||
// Single function starting at 0
|
||||
let code_len_total = code.len();
|
||||
let mut funcs = build_funcs(&[0], None);
|
||||
recompute_function_lengths_in_place(&mut funcs, code_len_total);
|
||||
|
||||
// Expected boundaries (relative): 0, 2, 8, 18, 21, 23
|
||||
// Explanation per instruction size: opcode(2) + imm
|
||||
let expected = [0usize, 2, 8, 18, 21, 23];
|
||||
for rel in 0..=expected.last().copied().unwrap() {
|
||||
let should_be_boundary = expected.contains(&rel);
|
||||
assert_eq!(
|
||||
is_boundary(&funcs, &code, code_len_total, 0, rel),
|
||||
should_be_boundary,
|
||||
"rel_pc={} boundary mismatch",
|
||||
rel
|
||||
);
|
||||
}
|
||||
|
||||
// Check absolute variant too
|
||||
for rel in expected {
|
||||
let abs = rel;
|
||||
assert!(is_boundary_abs(&funcs, &code, code_len_total, abs));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fuzz_table_monotonic_and_boundaries() {
|
||||
// Build a pseudo-random but valid sequence using a simple pattern over opcodes
|
||||
// to avoid invalid encodings. We cycle through a few known-good opcodes.
|
||||
let ops = [
|
||||
OpCode::Nop,
|
||||
OpCode::PushI32,
|
||||
OpCode::PushBool,
|
||||
OpCode::PushI64,
|
||||
OpCode::Pop,
|
||||
OpCode::Ret,
|
||||
];
|
||||
|
||||
let mut prog = Vec::new();
|
||||
for i in 0..50 {
|
||||
let op = ops[i % ops.len()];
|
||||
let asm = match op {
|
||||
OpCode::Nop => Asm::Op(OpCode::Nop, vec![]),
|
||||
OpCode::PushI32 => Asm::Op(OpCode::PushI32, vec![Operand::I32(i as i32)]),
|
||||
OpCode::PushBool => Asm::Op(OpCode::PushBool, vec![Operand::Bool(i % 2 == 0)]),
|
||||
OpCode::PushI64 => Asm::Op(OpCode::PushI64, vec![Operand::I64(i as i64)]),
|
||||
OpCode::Pop => Asm::Op(OpCode::Pop, vec![]),
|
||||
OpCode::Ret => Asm::Op(OpCode::Ret, vec![]),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
prog.push(asm);
|
||||
}
|
||||
|
||||
let code = assemble(&prog).unwrap();
|
||||
let code_len_total = code.len();
|
||||
let mut funcs = build_funcs(&[0], None);
|
||||
recompute_function_lengths_in_place(&mut funcs, code_len_total);
|
||||
let layouts = compute_function_layouts(&funcs, code_len_total);
|
||||
let (start, end) = (layouts[0].start, layouts[0].end);
|
||||
assert_eq!(start, 0);
|
||||
assert_eq!(end, code_len_total);
|
||||
|
||||
// Walk with decoder and verify boundaries are accepted
|
||||
let mut pc = start;
|
||||
while pc < end {
|
||||
assert!(is_boundary_abs(&funcs, &code, code_len_total, pc));
|
||||
let di = decode_next(pc, &code).expect("decode_next");
|
||||
assert!(di.next_pc > pc && di.next_pc <= end);
|
||||
pc = di.next_pc;
|
||||
}
|
||||
// End must be a boundary too
|
||||
assert!(is_boundary(&funcs, &code, code_len_total, 0, end - start));
|
||||
}
|
||||
|
||||
#[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,28 @@
|
||||
//! # Prometeu Bytecode (PBC)
|
||||
//!
|
||||
//! This crate defines the core Application Binary Interface (ABI) and Instruction Set Architecture (ISA)
|
||||
//! for the Prometeu Virtual Machine (PVM).
|
||||
//!
|
||||
//! It serves as the "source of truth" for how programs are structured, encoded, and executed
|
||||
//! within the ecosystem.
|
||||
//!
|
||||
//! ## Core Components:
|
||||
//! - [`opcode`]: Defines the available instructions and their performance characteristics.
|
||||
//! - [`abi`]: Specifies the binary rules for operands and stack behavior.
|
||||
//! - [`asm`]: Provides a programmatic Assembler to convert high-level instructions to bytes.
|
||||
//! - [`disasm`]: Provides a Disassembler to inspect compiled bytecode.
|
||||
//! - [`readwrite`]: Internal utilities for Little-Endian binary I/O.
|
||||
|
||||
pub mod opcode;
|
||||
pub mod opcode_spec;
|
||||
pub mod abi;
|
||||
pub mod readwrite;
|
||||
pub mod asm;
|
||||
pub mod disasm;
|
||||
pub mod layout;
|
||||
pub mod decoder;
|
||||
|
||||
mod model;
|
||||
pub mod io;
|
||||
|
||||
pub use model::*;
|
||||
@@ -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,414 @@
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::asm::{assemble, Asm, Operand};
|
||||
|
||||
#[test]
|
||||
fn test_opcode_stability() {
|
||||
// Normative test: ensures opcode numeric values are frozen.
|
||||
assert_eq!(OpCode::Nop as u16, 0x00);
|
||||
assert_eq!(OpCode::PushConst as u16, 0x10);
|
||||
assert_eq!(OpCode::Alloc as u16, 0x60);
|
||||
assert_eq!(OpCode::GateLoad as u16, 0x61);
|
||||
assert_eq!(OpCode::GateStore as u16, 0x62);
|
||||
assert_eq!(OpCode::GateBeginPeek as u16, 0x63);
|
||||
assert_eq!(OpCode::GateEndPeek as u16, 0x64);
|
||||
assert_eq!(OpCode::GateBeginBorrow as u16, 0x65);
|
||||
assert_eq!(OpCode::GateEndBorrow as u16, 0x66);
|
||||
assert_eq!(OpCode::GateBeginMutate as u16, 0x67);
|
||||
assert_eq!(OpCode::GateEndMutate as u16, 0x68);
|
||||
assert_eq!(OpCode::GateRetain as u16, 0x69);
|
||||
assert_eq!(OpCode::GateRelease as u16, 0x6A);
|
||||
assert_eq!(OpCode::FrameSync as u16, 0x80);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hip_bytecode_golden() {
|
||||
// Golden test for HIP opcodes and their encodings.
|
||||
// Rule: All multi-byte operands are little-endian.
|
||||
|
||||
let instructions = vec![
|
||||
Asm::Op(OpCode::Alloc, vec![Operand::U32(0x11223344), Operand::U32(0x55667788)]),
|
||||
Asm::Op(OpCode::GateLoad, vec![Operand::U32(0xAABBCCDD)]),
|
||||
Asm::Op(OpCode::GateStore, vec![Operand::U32(0x11223344)]),
|
||||
Asm::Op(OpCode::GateBeginPeek, vec![]),
|
||||
Asm::Op(OpCode::GateRetain, vec![]),
|
||||
Asm::Op(OpCode::GateRelease, vec![]),
|
||||
];
|
||||
|
||||
let bytes = assemble(&instructions).unwrap();
|
||||
|
||||
let mut expected = Vec::new();
|
||||
// Alloc (0x60, 0x00) + type_id (44 33 22 11) + slots (88 77 66 55)
|
||||
expected.extend_from_slice(&[0x60, 0x00, 0x44, 0x33, 0x22, 0x11, 0x88, 0x77, 0x66, 0x55]);
|
||||
// GateLoad (0x61, 0x00) + offset (DD CC BB AA)
|
||||
expected.extend_from_slice(&[0x61, 0x00, 0xDD, 0xCC, 0xBB, 0xAA]);
|
||||
// GateStore (0x62, 0x00) + offset (44 33 22 11)
|
||||
expected.extend_from_slice(&[0x62, 0x00, 0x44, 0x33, 0x22, 0x11]);
|
||||
// GateBeginPeek (0x63, 0x00)
|
||||
expected.extend_from_slice(&[0x63, 0x00]);
|
||||
// GateRetain (0x69, 0x00)
|
||||
expected.extend_from_slice(&[0x69, 0x00]);
|
||||
// GateRelease (0x6A, 0x00)
|
||||
expected.extend_from_slice(&[0x6A, 0x00]);
|
||||
|
||||
assert_eq!(bytes, expected);
|
||||
}
|
||||
}
|
||||
@@ -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,52 @@
|
||||
//! Binary I/O utilities for the Prometeu ecosystem.
|
||||
//! All multi-byte data is encoded in Little-Endian format.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
/// Reads a 16-bit unsigned integer from a reader.
|
||||
pub fn read_u16_le<R: Read>(mut reader: R) -> io::Result<u16> {
|
||||
let mut buf = [0u8; 2];
|
||||
reader.read_exact(&mut buf)?;
|
||||
Ok(u16::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Reads a 32-bit unsigned integer from a reader.
|
||||
pub fn read_u32_le<R: Read>(mut reader: R) -> io::Result<u32> {
|
||||
let mut buf = [0u8; 4];
|
||||
reader.read_exact(&mut buf)?;
|
||||
Ok(u32::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Reads a 64-bit signed integer from a reader.
|
||||
pub fn read_i64_le<R: Read>(mut reader: R) -> io::Result<i64> {
|
||||
let mut buf = [0u8; 8];
|
||||
reader.read_exact(&mut buf)?;
|
||||
Ok(i64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Reads a 64-bit floating point from a reader.
|
||||
pub fn read_f64_le<R: Read>(mut reader: R) -> io::Result<f64> {
|
||||
let mut buf = [0u8; 8];
|
||||
reader.read_exact(&mut buf)?;
|
||||
Ok(f64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Writes a 16-bit unsigned integer to a writer.
|
||||
pub fn write_u16_le<W: Write>(mut writer: W, val: u16) -> io::Result<()> {
|
||||
writer.write_all(&val.to_le_bytes())
|
||||
}
|
||||
|
||||
/// Writes a 32-bit unsigned integer to a writer.
|
||||
pub fn write_u32_le<W: Write>(mut writer: W, val: u32) -> io::Result<()> {
|
||||
writer.write_all(&val.to_le_bytes())
|
||||
}
|
||||
|
||||
/// Writes a 64-bit signed integer to a writer.
|
||||
pub fn write_i64_le<W: Write>(mut writer: W, val: i64) -> io::Result<()> {
|
||||
writer.write_all(&val.to_le_bytes())
|
||||
}
|
||||
|
||||
/// Writes a 64-bit floating point to a writer.
|
||||
pub fn write_f64_le<W: Write>(mut writer: W, val: f64) -> io::Result<()> {
|
||||
writer.write_all(&val.to_le_bytes())
|
||||
}
|
||||
Reference in New Issue
Block a user