Compare commits
38 commits
trunk
...
feature/hb
Author | SHA1 | Date | |
---|---|---|---|
Erin | d36a2335c7 | ||
Erin | e5f50c7b6c | ||
Erin | c648bf0b24 | ||
Erin | 51e0db9c7d | ||
Erin | cf05464c14 | ||
Erin | b0b4022a85 | ||
Erin | 299e8e6759 | ||
Erin | 3fc6bb9171 | ||
6f4f156ca0 | |||
IntoTheNight | 73ad40b369 | ||
0fb89ec4b3 | |||
f44220074d | |||
Erin | b218aa4a00 | ||
63b2dc7514 | |||
Erin | 0351a954d0 | ||
Erin | e32f0d1e61 | ||
Erin | 81f79dc7a5 | ||
Erin | 7ca0b1d4eb | ||
Erin | 447f8b2075 | ||
Erin | b271d024cd | ||
Erin | 7d17f48562 | ||
Erin | 387d4c7ce7 | ||
Erin | b7d4243113 | ||
Erin | 3af50b29fb | ||
able | 2d639797d9 | ||
able | a63c252c7a | ||
Erin | da1553d030 | ||
Erin | f0a00ebb8d | ||
Erin | 2bbf6ceee0 | ||
Erin | 2c9e315889 | ||
able | f53a42977d | ||
able | 8bc0d0020c | ||
able | f58f801aa9 | ||
able | a642b68474 | ||
Erin | 79c367dc18 | ||
Erin | 8b9a75adb4 | ||
Erin | 7e233f4ae1 | ||
Erin | 0c69d80fc2 |
252
Cargo.lock
generated
252
Cargo.lock
generated
|
@ -13,6 +13,34 @@ dependencies = [
|
|||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56fc6cf8dc8c4158eed8649f9b8b0ea1518eb62b544fe9490d66fa0b349eafe9"
|
||||
|
||||
[[package]]
|
||||
name = "ariadne"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72fe02fc62033df9ba41cba57ee19acf5e742511a140c7dbc3a873e19a19a1bd"
|
||||
dependencies = [
|
||||
"unicode-width",
|
||||
"yansi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "beef"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
|
@ -20,8 +48,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "compiler"
|
||||
version = "0.1.0"
|
||||
name = "convert_case"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
|
||||
|
||||
[[package]]
|
||||
name = "delegate"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d358e0ec5c59a5e1603b933def447096886121660fc680dc1e64a0753981fe3c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "0.99.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
|
@ -32,12 +92,75 @@ dependencies = [
|
|||
"ahash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"allocator-api2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hbasm"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ariadne",
|
||||
"bytemuck",
|
||||
"hashbrown 0.14.0",
|
||||
"hbbytecode",
|
||||
"lasso",
|
||||
"literify",
|
||||
"logos",
|
||||
"paste",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hbbytecode"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "hbvm"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"delegate",
|
||||
"derive_more",
|
||||
"hashbrown 0.13.2",
|
||||
"hbbytecode",
|
||||
"log",
|
||||
"paste",
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lasso"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4644821e1c3d7a560fe13d842d13f587c07348a1a05d3a797152d41c90c56df2"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"hashbrown 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "literify"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "54e4d365df794ed78b4ce1061886f82eae7afa8e3a98ce4c4b0bfd0c777b1175"
|
||||
dependencies = [
|
||||
"litrs",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "litrs"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f17c3668f3cc1132437cdadc93dab05e52d592f06948d3f64828430c36e4a70"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -49,14 +172,137 @@ dependencies = [
|
|||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "logos"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c000ca4d908ff18ac99b93a062cb8958d331c3220719c52e77cb19cc6ac5d2c1"
|
||||
dependencies = [
|
||||
"logos-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "logos-codegen"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc487311295e0002e452025d6b580b77bb17286de87b57138f3b5db711cded68"
|
||||
dependencies = [
|
||||
"beef",
|
||||
"fnv",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex-syntax",
|
||||
"syn 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "logos-derive"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbfc0d229f1f42d790440136d941afd806bc9e949e2bcb8faa813b0f00d1267e"
|
||||
dependencies = [
|
||||
"logos-codegen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.59"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6aeca18b86b413c660b781aa319e4e2648a3e6f9eadc9b47e9038e6fe9f3451b"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.6.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
|
||||
|
||||
[[package]]
|
||||
name = "static_assertions"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
[workspace]
|
||||
members = ["hbvm", "compiler"]
|
||||
members = ["hbasm", "hbbytecode", "hbvm"]
|
||||
|
|
|
@ -1,28 +0,0 @@
|
|||
# Math operations
|
||||
```
|
||||
MATH_OP
|
||||
Add
|
||||
Sub
|
||||
Mul
|
||||
Div
|
||||
Mod
|
||||
```
|
||||
```
|
||||
MATH_TYPE
|
||||
Unsigned
|
||||
Signed
|
||||
FloatingPoint
|
||||
```
|
||||
|
||||
```
|
||||
MATH_OP_SIDES
|
||||
Register Constant
|
||||
Register Register
|
||||
Constant Constant
|
||||
Constant Register
|
||||
```
|
||||
`[MATH_OP] [MATH_OP_SIDES] [MATH_TYPE] [IMM_LHS] [IMM_RHS] [REG]`
|
||||
|
||||
|
||||
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
load 0 a0 ;; 05 00 A0
|
||||
load 10 a1 ;; 05 10 A1
|
||||
add a0 1 a0 ;; 01 A0 01 A0
|
||||
jump_neq a0 a1 0 ;; a1 A0 A1 0
|
|
@ -1,4 +0,0 @@
|
|||
load 10 A1
|
||||
load 0 A0
|
||||
add A0 1
|
||||
jump_less_than A0 A1 0
|
|
@ -1,8 +0,0 @@
|
|||
[package]
|
||||
name = "compiler"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
|
@ -1,5 +0,0 @@
|
|||
fn main() {
|
||||
let prog = "load 1, A0
|
||||
jump 0";
|
||||
println!("Hello, world!");
|
||||
}
|
22
hbasm/Cargo.toml
Normal file
22
hbasm/Cargo.toml
Normal file
|
@ -0,0 +1,22 @@
|
|||
[package]
|
||||
name = "hbasm"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
ariadne = "0.3.0"
|
||||
hbbytecode = { path = "../hbbytecode" }
|
||||
literify = "0.1"
|
||||
paste = "1.0"
|
||||
hashbrown = "0.14.0"
|
||||
bytemuck = "1.13.1"
|
||||
|
||||
[dependencies.lasso]
|
||||
version = "0.7"
|
||||
default-features = false
|
||||
features = ["no-std"]
|
||||
|
||||
[dependencies.logos]
|
||||
version = "0.13"
|
||||
default-features = false
|
||||
features = ["export_derive"]
|
18
hbasm/assets/serial_driver.hbasm
Normal file
18
hbasm/assets/serial_driver.hbasm
Normal file
|
@ -0,0 +1,18 @@
|
|||
jmp r0, start
|
||||
start:
|
||||
jmp r0, init_serial_port
|
||||
|
||||
-- Uses r20 to set the port
|
||||
init_serial_port:
|
||||
add r20, r30, r10
|
||||
li r20, 00
|
||||
|
||||
-- outb(PORT + 1, 0x00); // Disable all interrupts
|
||||
-- outb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor)
|
||||
-- outb(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud
|
||||
-- outb(PORT + 1, 0x00); // (hi byte)
|
||||
-- outb(PORT + 3, 0x03); // 8 bits, no parity, one stop bit
|
||||
-- outb(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold
|
||||
-- outb(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set
|
||||
-- outb(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip
|
||||
-- outb(PORT + 0, 0xAE); // Test serial chip (send byte 0xAE and check if serial returns same byte)
|
50
hbasm/src/lib.rs
Normal file
50
hbasm/src/lib.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
#![no_std]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
mod macros;
|
||||
|
||||
use {alloc::vec::Vec, hashbrown::HashSet};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Assembler {
|
||||
pub buf: Vec<u8>,
|
||||
pub sub: HashSet<usize>,
|
||||
}
|
||||
|
||||
macros::impl_both!(
|
||||
bbbb(p0: R, p1: R, p2: R, p3: R)
|
||||
=> [DIR, DIRF, FMAF],
|
||||
bbb(p0: R, p1: R, p2: R)
|
||||
=> [ADD, SUB, MUL, AND, OR, XOR, SL, SR, SRS, CMP, CMPU, BRC, ADDF, SUBF, MULF],
|
||||
bbdh(p0: R, p1: R, p2: I, p3: u16)
|
||||
=> [LD, ST],
|
||||
bbd(p0: R, p1: R, p2: I)
|
||||
=> [ADDI, MULI, ANDI, ORI, XORI, SLI, SRI, SRSI, CMPI, CMPUI,
|
||||
BMC, JEQ, JNE, JLT, JGT, JLTU, JGTU, ADDFI, MULFI],
|
||||
bb(p0: R, p1: R)
|
||||
=> [NEG, NOT, CP, SWA, NEGF, ITF, FTI],
|
||||
bd(p0: R, p1: I)
|
||||
=> [LI, JMP],
|
||||
n()
|
||||
=> [NOP, ECALL],
|
||||
);
|
||||
|
||||
pub trait Imm {
|
||||
fn insert(&self, asm: &mut Assembler);
|
||||
}
|
||||
|
||||
macro_rules! impl_imm_le_bytes {
|
||||
($($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl Imm for $ty {
|
||||
#[inline(always)]
|
||||
fn insert(&self, asm: &mut Assembler) {
|
||||
asm.buf.extend(self.to_le_bytes());
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_imm_le_bytes!(u64, i64, f64);
|
73
hbasm/src/macros/asm.rs
Normal file
73
hbasm/src/macros/asm.rs
Normal file
|
@ -0,0 +1,73 @@
|
|||
macro_rules! impl_asm_opcodes {
|
||||
(
|
||||
$generic:ident
|
||||
($($param_i:ident: $param_ty:ty),*)
|
||||
=> []
|
||||
) => {};
|
||||
|
||||
(
|
||||
$generic:ident
|
||||
($($param_i:ident: $param_ty:ty),*)
|
||||
=> [$opcode:ident, $($rest:tt)*]
|
||||
) => {
|
||||
paste::paste! {
|
||||
#[allow(dead_code)]
|
||||
#[inline(always)]
|
||||
pub fn [<i_ $opcode:lower>](&mut self, $($param_i: $param_ty),*) {
|
||||
self.$generic(hbbytecode::opcode::$opcode, $($param_i),*)
|
||||
}
|
||||
}
|
||||
|
||||
macros::asm::impl_asm_opcodes!(
|
||||
$generic($($param_i: $param_ty),*)
|
||||
=> [$($rest)*]
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_asm_insert {
|
||||
($self:expr, $id:ident, I) => {
|
||||
Imm::insert(&$id, $self)
|
||||
};
|
||||
|
||||
($self:expr, $id:ident, $_:ident) => {
|
||||
$self.buf.extend($id.to_le_bytes())
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_asm {
|
||||
(
|
||||
$(
|
||||
$ityn:ident
|
||||
($($param_i:ident: $param_ty:ident),* $(,)?)
|
||||
=> [$($opcode:ident),* $(,)?],
|
||||
)*
|
||||
) => {
|
||||
paste::paste! {
|
||||
$(
|
||||
#[allow(dead_code)]
|
||||
fn [<i_param_ $ityn>](&mut self, opcode: u8, $($param_i: macros::asm::ident_map_ty!($param_ty)),*) {
|
||||
self.buf.push(opcode);
|
||||
$(macros::asm::impl_asm_insert!(self, $param_i, $param_ty);)*
|
||||
}
|
||||
|
||||
macros::asm::impl_asm_opcodes!(
|
||||
[<i_param_ $ityn>]($($param_i: macros::asm::ident_map_ty!($param_ty)),*)
|
||||
=> [$($opcode,)*]
|
||||
);
|
||||
)*
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[rustfmt::skip]
|
||||
macro_rules! ident_map_ty {
|
||||
(R) => { u8 };
|
||||
(I) => { impl Imm };
|
||||
($id:ident) => { $id };
|
||||
}
|
||||
|
||||
pub(crate) use {ident_map_ty, impl_asm, impl_asm_opcodes};
|
||||
|
||||
#[allow(clippy::single_component_path_imports)]
|
||||
pub(crate) use impl_asm_insert;
|
14
hbasm/src/macros/mod.rs
Normal file
14
hbasm/src/macros/mod.rs
Normal file
|
@ -0,0 +1,14 @@
|
|||
pub mod asm;
|
||||
pub mod text;
|
||||
|
||||
macro_rules! impl_both {
|
||||
($($tt:tt)*) => {
|
||||
impl Assembler {
|
||||
$crate::macros::asm::impl_asm!($($tt)*);
|
||||
}
|
||||
|
||||
$crate::macros::text::gen_text!($($tt)*);
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use impl_both;
|
202
hbasm/src/macros/text.rs
Normal file
202
hbasm/src/macros/text.rs
Normal file
|
@ -0,0 +1,202 @@
|
|||
macro_rules! gen_text {
|
||||
(
|
||||
$(
|
||||
$ityn:ident
|
||||
($($param_i:ident: $param_ty:ident),* $(,)?)
|
||||
=> [$($opcode:ident),* $(,)?],
|
||||
)*
|
||||
) => {
|
||||
pub mod text {
|
||||
use {
|
||||
crate::{
|
||||
Assembler,
|
||||
macros::text::*,
|
||||
},
|
||||
hashbrown::HashMap,
|
||||
lasso::{Key, Rodeo, Spur},
|
||||
logos::{Lexer, Logos, Span},
|
||||
};
|
||||
|
||||
paste::paste!(literify::literify! {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Logos)]
|
||||
#[logos(extras = Rodeo)]
|
||||
#[logos(skip r"[ \t\t]+")]
|
||||
#[logos(skip r"-- .*")]
|
||||
pub enum Token {
|
||||
$($(#[token(~([<$opcode:lower>]), |_| hbbytecode::opcode::[<$opcode:upper>])])*)*
|
||||
Opcode(u8),
|
||||
|
||||
#[regex("[0-9]+", |l| l.slice().parse().ok())]
|
||||
#[regex(
|
||||
"-[0-9]+",
|
||||
|lexer| {
|
||||
Some(u64::from_ne_bytes(lexer.slice().parse::<i64>().ok()?.to_ne_bytes()))
|
||||
},
|
||||
)] Integer(u64),
|
||||
|
||||
#[regex(
|
||||
"r[0-9]+",
|
||||
|lexer| match lexer.slice()[1..].parse() {
|
||||
Ok(n) => Some(n),
|
||||
_ => None
|
||||
},
|
||||
)] Register(u8),
|
||||
|
||||
#[regex(
|
||||
r"\p{XID_Start}\p{XID_Continue}*:",
|
||||
|lexer| lexer.extras.get_or_intern(&lexer.slice()[..lexer.slice().len() - 1]),
|
||||
)] Label(Spur),
|
||||
|
||||
#[regex(
|
||||
r"\p{XID_Start}\p{XID_Continue}*",
|
||||
|lexer| lexer.extras.get_or_intern(lexer.slice()),
|
||||
)] Symbol(Spur),
|
||||
|
||||
#[token("\n")]
|
||||
#[token(";")] ISep,
|
||||
#[token(",")] PSep,
|
||||
}
|
||||
});
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ErrorKind {
|
||||
UnexpectedToken,
|
||||
InvalidToken,
|
||||
UnexpectedEnd,
|
||||
InvalidSymbol,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Error {
|
||||
pub kind: ErrorKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
pub fn assemble(asm: &mut Assembler, code: &str) -> Result<(), Error> {
|
||||
pub struct TextAsm<'a> {
|
||||
asm: &'a mut Assembler,
|
||||
lexer: Lexer<'a, Token>,
|
||||
symloc: HashMap<Spur, usize>,
|
||||
}
|
||||
|
||||
impl<'a> TextAsm<'a> {
|
||||
fn next(&mut self) -> Result<Token, ErrorKind> {
|
||||
match self.lexer.next() {
|
||||
Some(Ok(t)) => Ok(t),
|
||||
Some(Err(())) => Err(ErrorKind::InvalidToken),
|
||||
None => Err(ErrorKind::UnexpectedEnd),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn run(&mut self) -> Result<(), ErrorKind> {
|
||||
loop {
|
||||
match self.lexer.next() {
|
||||
Some(Ok(Token::Opcode(op))) => {
|
||||
match op {
|
||||
$(
|
||||
$(hbbytecode::opcode::$opcode)|* => paste::paste!({
|
||||
param_extract_itm!(self, $($param_i: $param_ty),*);
|
||||
self.asm.[<i_param_ $ityn>](op, $($param_i),*);
|
||||
}),
|
||||
)*
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
Some(Ok(Token::Label(lbl))) => {
|
||||
self.symloc.insert(lbl, self.asm.buf.len());
|
||||
}
|
||||
Some(Ok(Token::ISep)) => (),
|
||||
Some(Ok(_)) => return Err(ErrorKind::UnexpectedToken),
|
||||
Some(Err(())) => return Err(ErrorKind::InvalidToken),
|
||||
None => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut asm = TextAsm {
|
||||
asm,
|
||||
lexer: Token::lexer(code),
|
||||
symloc: HashMap::default(),
|
||||
};
|
||||
|
||||
asm.run()
|
||||
.map_err(|kind| Error { kind, span: asm.lexer.span() })?;
|
||||
|
||||
for &loc in &asm.asm.sub {
|
||||
let val = asm.symloc
|
||||
.get(
|
||||
&Spur::try_from_usize(bytemuck::pod_read_unaligned::<u64>(&asm.asm.buf[loc..loc+core::mem::size_of::<u64>()]) as _)
|
||||
.unwrap()
|
||||
)
|
||||
.ok_or(Error { kind: ErrorKind::InvalidSymbol, span: 0..0 })?
|
||||
.to_le_bytes();
|
||||
|
||||
asm.asm.buf[loc..]
|
||||
.iter_mut()
|
||||
.zip(val)
|
||||
.for_each(|(dst, src)| *dst = src);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum InternalImm {
|
||||
Const(u64),
|
||||
Named(Spur),
|
||||
}
|
||||
|
||||
impl $crate::Imm for InternalImm {
|
||||
#[inline]
|
||||
fn insert(&self, asm: &mut Assembler) {
|
||||
match self {
|
||||
Self::Const(a) => a.insert(asm),
|
||||
Self::Named(a) => {
|
||||
asm.sub.insert(asm.buf.len());
|
||||
asm.buf.extend((a.into_usize() as u64).to_le_bytes());
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! extract_pat {
|
||||
($self:expr, $pat:pat) => {
|
||||
let $pat = $self.next()?
|
||||
else { return Err(ErrorKind::UnexpectedToken) };
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! extract {
|
||||
($self:expr, R, $id:ident) => {
|
||||
extract_pat!($self, Token::Register($id));
|
||||
};
|
||||
|
||||
($self:expr, I, $id:ident) => {
|
||||
let $id = match $self.next()? {
|
||||
Token::Integer(a) => InternalImm::Const(a),
|
||||
Token::Symbol(a) => InternalImm::Named(a),
|
||||
_ => return Err(ErrorKind::UnexpectedToken),
|
||||
};
|
||||
};
|
||||
|
||||
($self:expr, u16, $id:ident) => {
|
||||
extract_pat!($self, Token::Integer($id));
|
||||
let $id = u16::try_from($id).map_err(|_| ErrorKind::InvalidToken)?;
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! param_extract_itm {
|
||||
($self:expr, $($id:ident: $ty:ident)? $(, $($tt:tt)*)?) => {
|
||||
$(extract!($self, $ty, $id);)?
|
||||
$(
|
||||
extract_pat!($self, Token::PSep);
|
||||
param_extract_itm!($self, $($tt)*);
|
||||
)?
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use {extract, extract_pat, gen_text, param_extract_itm};
|
55
hbasm/src/main.rs
Normal file
55
hbasm/src/main.rs
Normal file
|
@ -0,0 +1,55 @@
|
|||
use std::io::Write;
|
||||
|
||||
use hbasm::Assembler;
|
||||
|
||||
use {
|
||||
ariadne::{ColorGenerator, Label, Report, ReportKind, Source},
|
||||
std::{
|
||||
error::Error,
|
||||
io::{stdin, Read},
|
||||
},
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut code = String::new();
|
||||
stdin().read_to_string(&mut code)?;
|
||||
|
||||
let mut assembler = Assembler::default();
|
||||
if let Err(e) = hbasm::text::assemble(&mut assembler, &code) {
|
||||
let mut colors = ColorGenerator::new();
|
||||
|
||||
let e_code = match e.kind {
|
||||
hbasm::text::ErrorKind::UnexpectedToken => 1,
|
||||
hbasm::text::ErrorKind::InvalidToken => 2,
|
||||
hbasm::text::ErrorKind::UnexpectedEnd => 3,
|
||||
hbasm::text::ErrorKind::InvalidSymbol => 4,
|
||||
};
|
||||
let message = match e.kind {
|
||||
hbasm::text::ErrorKind::UnexpectedToken => "This token is not expected!",
|
||||
hbasm::text::ErrorKind::InvalidToken => "The token is not valid!",
|
||||
hbasm::text::ErrorKind::UnexpectedEnd => {
|
||||
"The assembler reached the end of input unexpectedly!"
|
||||
}
|
||||
hbasm::text::ErrorKind::InvalidSymbol => {
|
||||
"This referenced symbol doesn't have a corresponding label!"
|
||||
}
|
||||
};
|
||||
let a = colors.next();
|
||||
|
||||
Report::build(ReportKind::Error, "engine_internal", e.span.clone().start)
|
||||
.with_code(e_code)
|
||||
.with_message(format!("{:?}", e.kind))
|
||||
.with_label(
|
||||
Label::new(("engine_internal", e.span.clone()))
|
||||
.with_message(message)
|
||||
.with_color(a),
|
||||
)
|
||||
.finish()
|
||||
.eprint(("engine_internal", Source::from(&code)))
|
||||
.unwrap();
|
||||
} else {
|
||||
std::io::stdout().lock().write_all(&assembler.buf).unwrap();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
6
hbbytecode/Cargo.toml
Normal file
6
hbbytecode/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "hbbytecode"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
60
hbbytecode/hbbytecode.h
Normal file
60
hbbytecode/hbbytecode.h
Normal file
|
@ -0,0 +1,60 @@
|
|||
/* HoleyBytes Bytecode representation in C
|
||||
* Requires C23 compiler or better
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <assert.h>
|
||||
#include <limits.h>
|
||||
#include <stdint.h>
|
||||
|
||||
static_assert(CHAR_BIT == 8, "Cursed architectures are not supported");
|
||||
|
||||
enum hbbc_Opcode: uint8_t {
|
||||
hbbc_Op_NOP , hbbc_Op_ADD , hbbc_Op_SUB , hbbc_Op_MUL , hbbc_Op_AND , hbbc_Op_OR ,
|
||||
hbbc_Op_XOR , hbbc_Op_SL , hbbc_Op_SR , hbbc_Op_SRS , hbbc_Op_CMP , hbbc_Op_CMPU ,
|
||||
hbbc_Op_DIR , hbbc_Op_NEG , hbbc_Op_NOT , hbbc_Op_ADDI , hbbc_Op_MULI , hbbc_Op_ANDI ,
|
||||
hbbc_Op_ORI , hbbc_Op_XORI , hbbc_Op_SLI , hbbc_Op_SRI , hbbc_Op_SRSI , hbbc_Op_CMPI ,
|
||||
hbbc_Op_CMPUI , hbbc_Op_CP , hbbc_Op_SWA , hbbc_Op_LI , hbbc_Op_LD , hbbc_Op_ST ,
|
||||
hbbc_Op_BMC , hbbc_Op_BRC , hbbc_Op_JMP , hbbc_Op_JEQ , hbbc_Op_JNE , hbbc_Op_JLT ,
|
||||
hbbc_Op_JGT , hbbc_Op_JLTU , hbbc_Op_JGTU , hbbc_Op_ECALL , hbbc_Op_ADDF , hbbc_Op_SUBF ,
|
||||
hbbc_Op_MULF , hbbc_Op_DIRF , hbbc_Op_FMAF , hbbc_Op_NEGF , hbbc_Op_ITF , hbbc_Op_FTI ,
|
||||
hbbc_Op_ADDFI , hbbc_Op_MULFI ,
|
||||
} typedef hbbc_Opcode;
|
||||
|
||||
static_assert(sizeof(hbbc_Opcode) == 1);
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct hbbc_ParamBBBB
|
||||
{ uint8_t _0; uint8_t _1; uint8_t _2; uint8_t _3; }
|
||||
typedef hbbc_ParamBBBB;
|
||||
static_assert(sizeof(hbbc_ParamBBBB) == 32 / 8);
|
||||
|
||||
struct hbbc_ParamBBB
|
||||
{ uint8_t _0; uint8_t _1; uint8_t _2; }
|
||||
typedef hbbc_ParamBBB;
|
||||
static_assert(sizeof(hbbc_ParamBBB) == 24 / 8);
|
||||
|
||||
struct hbbc_ParamBBDH
|
||||
{ uint8_t _0; uint8_t _1; uint64_t _2; uint16_t _3; }
|
||||
typedef hbbc_ParamBBDH;
|
||||
static_assert(sizeof(hbbc_ParamBBDH) == 96 / 8);
|
||||
|
||||
struct hbbc_ParamBBD
|
||||
{ uint8_t _0; uint8_t _1; uint64_t _2; }
|
||||
typedef hbbc_ParamBBD;
|
||||
static_assert(sizeof(hbbc_ParamBBD) == 80 / 8);
|
||||
|
||||
struct hbbc_ParamBB
|
||||
{ uint8_t _0; uint8_t _1; }
|
||||
typedef hbbc_ParamBB;
|
||||
static_assert(sizeof(hbbc_ParamBB) == 16 / 8);
|
||||
|
||||
struct hbbc_ParamBD
|
||||
{ uint8_t _0; uint64_t _1; }
|
||||
typedef hbbc_ParamBD;
|
||||
static_assert(sizeof(hbbc_ParamBD) == 72 / 8);
|
||||
|
||||
typedef uint64_t hbbc_ParamD;
|
||||
static_assert(sizeof(hbbc_ParamD) == 64 / 8);
|
||||
|
||||
#pragma pack(pop)
|
107
hbbytecode/src/lib.rs
Normal file
107
hbbytecode/src/lib.rs
Normal file
|
@ -0,0 +1,107 @@
|
|||
#![no_std]
|
||||
|
||||
macro_rules! constmod {
|
||||
($vis:vis $mname:ident($repr:ty) {
|
||||
$(#![doc = $mdoc:literal])?
|
||||
$($cname:ident = $val:expr $(,$doc:literal)?;)*
|
||||
}) => {
|
||||
$(#[doc = $mdoc])?
|
||||
$vis mod $mname {
|
||||
$(
|
||||
$(#[doc = $doc])?
|
||||
pub const $cname: $repr = $val;
|
||||
)*
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
constmod!(pub opcode(u8) {
|
||||
//! Opcode constant module
|
||||
|
||||
NOP = 0, "N; Do nothing";
|
||||
|
||||
ADD = 1, "BBB; #0 ← #1 + #2";
|
||||
SUB = 2, "BBB; #0 ← #1 - #2";
|
||||
MUL = 3, "BBB; #0 ← #1 × #2";
|
||||
AND = 4, "BBB; #0 ← #1 & #2";
|
||||
OR = 5, "BBB; #0 ← #1 | #2";
|
||||
XOR = 6, "BBB; #0 ← #1 ^ #2";
|
||||
SL = 7, "BBB; #0 ← #1 « #2";
|
||||
SR = 8, "BBB; #0 ← #1 » #2";
|
||||
SRS = 9, "BBB; #0 ← #1 » #2 (signed)";
|
||||
CMP = 10, "BBB; #0 ← #1 <=> #2";
|
||||
CMPU = 11, "BBB; #0 ← #1 <=> #2 (unsigned)";
|
||||
DIR = 12, "BBBB; #0 ← #2 / #3, #1 ← #2 % #3";
|
||||
NEG = 13, "BB; #0 ← -#1";
|
||||
NOT = 14, "BB; #0 ← !#1";
|
||||
|
||||
ADDI = 15, "BBD; #0 ← #1 + imm #2";
|
||||
MULI = 16, "BBD; #0 ← #1 × imm #2";
|
||||
ANDI = 17, "BBD; #0 ← #1 & imm #2";
|
||||
ORI = 18, "BBD; #0 ← #1 | imm #2";
|
||||
XORI = 19, "BBD; #0 ← #1 ^ imm #2";
|
||||
SLI = 20, "BBD; #0 ← #1 « imm #2";
|
||||
SRI = 21, "BBD; #0 ← #1 » imm #2";
|
||||
SRSI = 22, "BBD; #0 ← #1 » imm #2 (signed)";
|
||||
CMPI = 23, "BBD; #0 ← #1 <=> imm #2";
|
||||
CMPUI = 24, "BBD; #0 ← #1 <=> imm #2 (unsigned)";
|
||||
|
||||
CP = 25, "BB; Copy #0 ← #1";
|
||||
SWA = 26, "BB; Swap #0 and #1";
|
||||
LI = 27, "BD; #0 ← imm #1";
|
||||
LD = 28, "BBDB; #0 ← [#1 + imm #3], imm #4 bytes, overflowing";
|
||||
ST = 29, "BBDB; [#1 + imm #3] ← #0, imm #4 bytes, overflowing";
|
||||
BMC = 30, "BBD; [#0] ← [#1], imm #2 bytes";
|
||||
BRC = 31, "BBB; #0 ← #1, imm #2 registers";
|
||||
|
||||
JMP = 32, "BD; Unconditional jump [#0 + imm #1]";
|
||||
JEQ = 33, "BBD; if #0 = #1 → jump imm #2";
|
||||
JNE = 34, "BBD; if #0 ≠ #1 → jump imm #2";
|
||||
JLT = 35, "BBD; if #0 < #1 → jump imm #2";
|
||||
JGT = 36, "BBD; if #0 > #1 → jump imm #2";
|
||||
JLTU = 37, "BBD; if #0 < #1 → jump imm #2 (unsigned)";
|
||||
JGTU = 38, "BBD; if #0 > #1 → jump imm #2 (unsigned)";
|
||||
ECALL = 39, "N; Issue system call";
|
||||
|
||||
ADDF = 40, "BBB; #0 ← #1 +. #2";
|
||||
SUBF = 41, "BBB; #0 ← #1 -. #2";
|
||||
MULF = 42, "BBB; #0 ← #1 +. #2";
|
||||
DIRF = 43, "BBBB; #0 ← #2 / #3, #1 ← #2 % #3";
|
||||
FMAF = 44, "BBBB; #0 ← (#1 * #2) + #3";
|
||||
NEGF = 45, "BB; #0 ← -#1";
|
||||
ITF = 46, "BB; #0 ← #1 as float";
|
||||
FTI = 47, "BB; #0 ← #1 as int";
|
||||
|
||||
ADDFI = 48, "BBD; #0 ← #1 +. imm #2";
|
||||
MULFI = 49, "BBD; #0 ← #1 *. imm #2";
|
||||
});
|
||||
|
||||
#[repr(packed)]
|
||||
pub struct ParamBBBB(pub u8, pub u8, pub u8, pub u8);
|
||||
|
||||
#[repr(packed)]
|
||||
pub struct ParamBBB(pub u8, pub u8, pub u8);
|
||||
|
||||
#[repr(packed)]
|
||||
pub struct ParamBBDH(pub u8, pub u8, pub u64, pub u16);
|
||||
|
||||
#[repr(packed)]
|
||||
pub struct ParamBBD(pub u8, pub u8, pub u64);
|
||||
|
||||
#[repr(packed)]
|
||||
pub struct ParamBB(pub u8, pub u8);
|
||||
|
||||
#[repr(packed)]
|
||||
pub struct ParamBD(pub u8, pub u64);
|
||||
|
||||
/// # Safety
|
||||
/// Has to be valid to be decoded from bytecode.
|
||||
pub unsafe trait OpParam {}
|
||||
unsafe impl OpParam for ParamBBBB {}
|
||||
unsafe impl OpParam for ParamBBB {}
|
||||
unsafe impl OpParam for ParamBBDH {}
|
||||
unsafe impl OpParam for ParamBBD {}
|
||||
unsafe impl OpParam for ParamBB {}
|
||||
unsafe impl OpParam for ParamBD {}
|
||||
unsafe impl OpParam for u64 {}
|
||||
unsafe impl OpParam for () {}
|
|
@ -3,8 +3,14 @@ name = "hbvm"
|
|||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
log = "*"
|
||||
hashbrown = "0.13.2"
|
||||
delegate = "0.9"
|
||||
derive_more = "0.99"
|
||||
hashbrown = "0.13"
|
||||
hbbytecode.path = "../hbbytecode"
|
||||
log = "0.4"
|
||||
paste = "1.0"
|
||||
static_assertions = "1.0"
|
||||
|
|
0
hbvm/README.md
Normal file
0
hbvm/README.md
Normal file
|
@ -1,2 +0,0 @@
|
|||
pub mod ops;
|
||||
pub mod types;
|
|
@ -1,68 +0,0 @@
|
|||
#[repr(u8)]
|
||||
pub enum Operations {
|
||||
NOP = 0,
|
||||
|
||||
ADD = 1,
|
||||
SUB = 2,
|
||||
MUL = 3,
|
||||
DIV = 4,
|
||||
MOD = 5,
|
||||
|
||||
AND = 6,
|
||||
OR = 7,
|
||||
XOR = 8,
|
||||
NOT = 9,
|
||||
|
||||
// LOADs a memory address/constant into a register
|
||||
LOAD = 15,
|
||||
// STOREs a register/constant into a memory address
|
||||
STORE = 16,
|
||||
|
||||
MapPage = 17,
|
||||
UnmapPage = 18,
|
||||
|
||||
// SHIFT LEFT 16 A0
|
||||
Shift = 20,
|
||||
|
||||
JUMP = 100,
|
||||
JumpCond = 101,
|
||||
RET = 103,
|
||||
|
||||
EnviromentCall = 255,
|
||||
}
|
||||
|
||||
pub enum PageMapTypes {
|
||||
// Have the host make a new VMPage
|
||||
VMPage = 0,
|
||||
// Ask the host to map a RealPage into memory
|
||||
RealPage = 1,
|
||||
}
|
||||
|
||||
pub enum MathOpSubTypes {
|
||||
Unsigned = 0,
|
||||
Signed = 1,
|
||||
FloatingPoint = 2,
|
||||
}
|
||||
|
||||
pub enum MathOpSides {
|
||||
RegisterConstant = 0,
|
||||
RegisterRegister = 1,
|
||||
ConstantConstant = 2,
|
||||
ConstantRegister = 3,
|
||||
}
|
||||
|
||||
pub enum RWSubTypes {
|
||||
AddrToReg = 0,
|
||||
RegToAddr,
|
||||
ConstToReg,
|
||||
ConstToAddr,
|
||||
}
|
||||
|
||||
pub enum JumpConditionals {
|
||||
Equal = 0,
|
||||
NotEqual = 1,
|
||||
LessThan = 2,
|
||||
LessThanOrEqualTo = 3,
|
||||
GreaterThan = 4,
|
||||
GreaterThanOrEqualTo = 5,
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
|
||||
pub const CONST_U8: u8 = 0x00;
|
||||
pub const CONST_I8: i8 = 0x01;
|
||||
|
||||
pub const CONST_U64: u8 = 0x02;
|
||||
pub const CONST_I64: u8 = 0x03;
|
||||
pub const CONST_F64: u8 = 0x04;
|
||||
|
||||
pub const ADDRESS: u8 = 0x05;
|
|
@ -1,6 +0,0 @@
|
|||
use alloc::vec::Vec;
|
||||
|
||||
pub type CallStack = Vec<FnCall>;
|
||||
pub struct FnCall {
|
||||
pub ret: usize,
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
pub struct EngineConfig {
|
||||
pub call_stack_depth: usize,
|
||||
pub quantum: u32,
|
||||
}
|
||||
|
||||
impl EngineConfig {
|
||||
pub fn default() -> Self {
|
||||
Self {
|
||||
call_stack_depth: 32,
|
||||
quantum: 0,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
use super::Engine;
|
||||
|
||||
pub type EnviromentCall = fn(&mut Engine) -> Result<&mut Engine, u64>;
|
|
@ -1,100 +0,0 @@
|
|||
pub mod call_stack;
|
||||
pub mod config;
|
||||
pub mod enviroment_calls;
|
||||
pub mod regs;
|
||||
#[cfg(test)]
|
||||
pub mod tests;
|
||||
|
||||
use {
|
||||
self::call_stack::CallStack,
|
||||
crate::{memory, HaltStatus, RuntimeErrors},
|
||||
alloc::vec::Vec,
|
||||
config::EngineConfig,
|
||||
log::trace,
|
||||
regs::Registers,
|
||||
};
|
||||
// pub const PAGE_SIZE: usize = 8192;
|
||||
|
||||
pub struct RealPage {
|
||||
pub ptr: *mut u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct VMPage {
|
||||
pub data: [u8; 8192],
|
||||
}
|
||||
impl VMPage {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
data: [0; 4096 * 2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Page {
|
||||
VMPage(VMPage),
|
||||
RealPage(RealPage),
|
||||
}
|
||||
impl Page {
|
||||
pub fn data(&self) -> [u8; 4096 * 2] {
|
||||
match self {
|
||||
Page::VMPage(vmpage) => vmpage.data,
|
||||
Page::RealPage(_) => {
|
||||
unimplemented!("Memmapped hw page not yet supported")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn empty_enviroment_call(engine: &mut Engine) -> Result<&mut Engine, u64> {
|
||||
trace!("Registers {:?}", engine.registers);
|
||||
Err(0)
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
pub index: usize,
|
||||
pub program: Vec<u8>,
|
||||
pub registers: Registers,
|
||||
pub config: EngineConfig,
|
||||
|
||||
/// BUG: This DOES NOT account for overflowing
|
||||
pub last_timer_count: u32,
|
||||
pub timer_callback: Option<fn() -> u32>,
|
||||
pub memory: memory::Memory,
|
||||
pub enviroment_call_table: [Option<EnviromentCall>; 256],
|
||||
pub call_stack: CallStack,
|
||||
}
|
||||
use crate::engine::enviroment_calls::EnviromentCall;
|
||||
impl Engine {
|
||||
pub fn set_timer_callback(&mut self, func: fn() -> u32) {
|
||||
self.timer_callback = Some(func);
|
||||
}
|
||||
pub fn set_register(&mut self, register: u8, value: u64) {}
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(program: Vec<u8>) -> Self {
|
||||
let mut mem = memory::Memory::new();
|
||||
for (addr, byte) in program.clone().into_iter().enumerate() {
|
||||
let _ = mem.set_addr8(addr as u64, byte);
|
||||
}
|
||||
trace!("{:?}", mem.read_addr8(0));
|
||||
let ecall_table: [Option<EnviromentCall>; 256] = [None; 256];
|
||||
Self {
|
||||
index: 0,
|
||||
program,
|
||||
registers: Registers::new(),
|
||||
config: EngineConfig::default(),
|
||||
last_timer_count: 0,
|
||||
timer_callback: None,
|
||||
enviroment_call_table: ecall_table,
|
||||
memory: mem,
|
||||
call_stack: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dump(&self) {}
|
||||
pub fn run(&mut self) -> Result<HaltStatus, RuntimeErrors> {
|
||||
Ok(HaltStatus::Halted)
|
||||
}
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
#[rustfmt::skip]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Registers {
|
||||
pub a0: u64, pub b0: u64, pub c0: u64, pub d0: u64, pub e0: u64, pub f0: u64,
|
||||
pub a1: u64, pub b1: u64, pub c1: u64, pub d1: u64, pub e1: u64, pub f1: u64,
|
||||
pub a2: u64, pub b2: u64, pub c2: u64, pub d2: u64, pub e2: u64, pub f2: u64,
|
||||
pub a3: u64, pub b3: u64, pub c3: u64, pub d3: u64, pub e3: u64, pub f3: u64,
|
||||
pub a4: u64, pub b4: u64, pub c4: u64, pub d4: u64, pub e4: u64, pub f4: u64,
|
||||
pub a5: u64, pub b5: u64, pub c5: u64, pub d5: u64, pub e5: u64, pub f5: u64,
|
||||
pub a6: u64, pub b6: u64, pub c6: u64, pub d6: u64, pub e6: u64, pub f6: u64,
|
||||
pub a7: u64, pub b7: u64, pub c7: u64, pub d7: u64, pub e7: u64, pub f7: u64,
|
||||
pub a8: u64, pub b8: u64, pub c8: u64, pub d8: u64, pub e8: u64, pub f8: u64,
|
||||
pub a9: u64, pub b9: u64, pub c9: u64, pub d9: u64, pub e9: u64, pub f9: u64,
|
||||
}
|
||||
|
||||
impl Registers {
|
||||
#[rustfmt::skip]
|
||||
pub fn new() -> Self{
|
||||
Self {
|
||||
a0: 0, b0: 0, c0: 0, d0: 0, e0: 0, f0: 0,
|
||||
a1: 0, b1: 0, c1: 0, d1: 0, e1: 0, f1: 0,
|
||||
a2: 0, b2: 0, c2: 0, d2: 0, e2: 0, f2: 0,
|
||||
a3: 0, b3: 0, c3: 0, d3: 0, e3: 0, f3: 0,
|
||||
a4: 0, b4: 0, c4: 0, d4: 0, e4: 0, f4: 0,
|
||||
a5: 0, b5: 0, c5: 0, d5: 0, e5: 0, f5: 0,
|
||||
a6: 0, b6: 0, c6: 0, d6: 0, e6: 0, f6: 0,
|
||||
a7: 0, b7: 0, c7: 0, d7: 0, e7: 0, f7: 0,
|
||||
a8: 0, b8: 0, c8: 0, d8: 0, e8: 0, f8: 0,
|
||||
a9: 0, b9: 0, c9: 0, d9: 0, e9: 0, f9: 0,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,125 +0,0 @@
|
|||
use {
|
||||
super::Engine,
|
||||
crate::{HaltStatus, RuntimeErrors},
|
||||
alloc::vec,
|
||||
RuntimeErrors::*,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn invalid_program() {
|
||||
let prog = vec![1, 0];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.run();
|
||||
assert_eq!(ret, Err(InvalidOpcodePair(1, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_program() {
|
||||
let prog = vec![];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.run();
|
||||
assert_eq!(ret, Ok(HaltStatus::Halted));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_quantum_reached() {
|
||||
let prog = vec![0, 0, 0, 0];
|
||||
let mut eng = Engine::new(prog);
|
||||
eng.set_timer_callback(|| {
|
||||
return 1;
|
||||
});
|
||||
eng.config.quantum = 1;
|
||||
let ret = eng.run();
|
||||
assert_eq!(ret, Ok(HaltStatus::Running));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jump_out_of_bounds() {
|
||||
use crate::bytecode::ops::Operations::JUMP;
|
||||
let prog = vec![JUMP as u8, 0, 0, 0, 0, 0, 0, 1, 0];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.run();
|
||||
assert_eq!(ret, Err(InvalidJumpAddress(256)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_system_call() {
|
||||
let prog = vec![255, 0];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.run();
|
||||
assert_eq!(ret, Err(InvalidSystemCall(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_u8() {
|
||||
use crate::bytecode::ops::{MathOpSides::ConstantConstant, Operations::ADD};
|
||||
|
||||
let prog = vec![ADD as u8, ConstantConstant as u8, 100, 98, 0xA0];
|
||||
let mut eng = Engine::new(prog);
|
||||
let _ = eng.run();
|
||||
assert_eq!(eng.registers.a0, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_u8() {
|
||||
use crate::bytecode::ops::Operations::SUB;
|
||||
|
||||
let prog = vec![SUB as u8];
|
||||
let mut eng = Engine::new(prog);
|
||||
let _ = eng.run();
|
||||
assert_eq!(eng.registers.a0, 1);
|
||||
}
|
||||
#[test]
|
||||
fn mul_u8() {
|
||||
use crate::bytecode::ops::{MathOpSides::ConstantConstant, Operations::MUL};
|
||||
|
||||
let prog = vec![MUL as u8, ConstantConstant as u8, 1, 2, 0xA0];
|
||||
let mut eng = Engine::new(prog);
|
||||
let _ = eng.run();
|
||||
assert_eq!(eng.registers.a0, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn div_u8() {
|
||||
use crate::bytecode::ops::Operations::DIV;
|
||||
|
||||
let prog = vec![DIV as u8];
|
||||
let mut eng = Engine::new(prog);
|
||||
let _ = eng.run();
|
||||
assert_eq!(eng.registers.a0, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_register() {
|
||||
let prog = alloc::vec![];
|
||||
let mut eng = Engine::new(prog);
|
||||
eng.set_register(0xA0, 1);
|
||||
assert_eq!(eng.registers.a0, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_u8() {
|
||||
use crate::bytecode::ops::{Operations::LOAD, RWSubTypes::AddrToReg};
|
||||
|
||||
let prog = vec![LOAD as u8, AddrToReg as u8, 0, 0, 0, 0, 0, 0, 1, 0, 0xA0];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.memory.set_addr8(256, 1);
|
||||
assert_eq!(ret, Ok(()));
|
||||
let _ = eng.run();
|
||||
assert_eq!(eng.registers.a0, 1);
|
||||
}
|
||||
#[test]
|
||||
fn set_memory_8() {
|
||||
let prog = vec![];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.memory.set_addr8(256, 1);
|
||||
assert_eq!(ret, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_memory_64() {
|
||||
let prog = vec![];
|
||||
let mut eng = Engine::new(prog);
|
||||
let ret = eng.memory.set_addr64(256, 1);
|
||||
assert_eq!(ret, Ok(()));
|
||||
}
|
|
@ -1,23 +1,7 @@
|
|||
#![doc = include_str!("../README.md")]
|
||||
#![no_std]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
pub mod bytecode;
|
||||
pub mod engine;
|
||||
pub mod memory;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum RuntimeErrors {
|
||||
InvalidOpcodePair(u8, u8),
|
||||
RegisterTooSmall,
|
||||
HostError(u64),
|
||||
PageNotMapped(u64),
|
||||
InvalidJumpAddress(u64),
|
||||
InvalidSystemCall(u8),
|
||||
}
|
||||
|
||||
// If you solve the halting problem feel free to remove this
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum HaltStatus {
|
||||
Halted,
|
||||
Running,
|
||||
}
|
||||
pub mod validate;
|
||||
pub mod vm;
|
||||
|
|
|
@ -1,31 +1,42 @@
|
|||
use hbvm::{
|
||||
bytecode::ops::{Operations::*, RWSubTypes::*},
|
||||
engine::Engine,
|
||||
RuntimeErrors,
|
||||
use hbvm::vm::mem::{HandlePageFault, Memory, MemoryAccessReason, PageSize};
|
||||
|
||||
use {
|
||||
hbvm::{validate::validate, vm::Vm},
|
||||
std::io::{stdin, Read},
|
||||
};
|
||||
|
||||
fn main() -> Result<(), RuntimeErrors> {
|
||||
// TODO: Grab program from cmdline
|
||||
#[rustfmt::skip]
|
||||
let prog: Vec<u8> = vec![
|
||||
NOP as u8,
|
||||
JUMP as u8, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
];
|
||||
|
||||
let mut eng = Engine::new(prog);
|
||||
// eng.set_timer_callback(time);
|
||||
eng.enviroment_call_table[10] = Some(print_fn);
|
||||
eng.run()?;
|
||||
eng.dump();
|
||||
println!("{:#?}", eng.registers);
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut prog = vec![];
|
||||
stdin().read_to_end(&mut prog)?;
|
||||
|
||||
if let Err(e) = validate(&prog) {
|
||||
eprintln!("Program validation error: {e:?}");
|
||||
return Ok(());
|
||||
} else {
|
||||
unsafe {
|
||||
let mut vm = Vm::<_, 0>::new_unchecked(&prog, TestTrapHandler);
|
||||
vm.memory.insert_test_page();
|
||||
println!("Program interrupt: {:?}", vm.run());
|
||||
println!("{:?}", vm.registers);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn time() -> u32 {
|
||||
9
|
||||
}
|
||||
pub fn print_fn(engine: &mut Engine) -> Result<&mut Engine, u64> {
|
||||
println!("hello");
|
||||
Ok(engine)
|
||||
|
||||
struct TestTrapHandler;
|
||||
impl HandlePageFault for TestTrapHandler {
|
||||
fn page_fault(
|
||||
&mut self,
|
||||
_: MemoryAccessReason,
|
||||
_: &mut Memory,
|
||||
_: u64,
|
||||
_: PageSize,
|
||||
_: *mut u8,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,70 +0,0 @@
|
|||
use crate::engine::VMPage;
|
||||
|
||||
use {
|
||||
crate::{engine::Page, RuntimeErrors},
|
||||
alloc::vec::Vec,
|
||||
hashbrown::HashMap,
|
||||
log::trace,
|
||||
};
|
||||
|
||||
pub struct Memory {
|
||||
inner: HashMap<u64, Page>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: HashMap::new(),
|
||||
}
|
||||
//
|
||||
}
|
||||
|
||||
pub fn map_vec(&mut self, address: u64, vec: Vec<u8>) {
|
||||
panic!("Mapping vectors into pages is not supported yet");
|
||||
}
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
pub fn read_addr8(&mut self, address: u64) -> Result<u8, RuntimeErrors> {
|
||||
let (page, offset) = addr_to_page(address);
|
||||
trace!("page {} offset {}", page, offset);
|
||||
match self.inner.get(&page) {
|
||||
Some(page) => {
|
||||
let val = page.data()[offset as usize];
|
||||
trace!("Value {}", val);
|
||||
Ok(val)
|
||||
}
|
||||
None => {
|
||||
trace!("page not mapped");
|
||||
Err(RuntimeErrors::PageNotMapped(page))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn read_addr64(&mut self, address: u64) -> u64 {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn set_addr8(&mut self, address: u64, value: u8) -> Result<(), RuntimeErrors> {
|
||||
let (page, offset) = addr_to_page(address);
|
||||
let ret: Option<(&u64, &mut Page)> = self.inner.get_key_value_mut(&page);
|
||||
match ret {
|
||||
Some((_, page)) => {
|
||||
page.data()[offset as usize] = value;
|
||||
}
|
||||
None => {
|
||||
let mut pg = VMPage::new();
|
||||
pg.data[offset as usize] = value;
|
||||
self.inner.insert(page, Page::VMPage(pg));
|
||||
trace!("Mapped page {}", page);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_addr64(&mut self, address: u64, value: u64) -> Result<(), RuntimeErrors> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
fn addr_to_page(addr: u64) -> (u64, u64) {
|
||||
(addr / 8192, addr % 8192)
|
||||
}
|
64
hbvm/src/validate.rs
Normal file
64
hbvm/src/validate.rs
Normal file
|
@ -0,0 +1,64 @@
|
|||
//! Validate if program is sound to execute
|
||||
|
||||
/// Program validation error kind
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ErrorKind {
|
||||
/// Unknown opcode
|
||||
InvalidInstruction,
|
||||
/// VM doesn't implement this valid opcode
|
||||
Unimplemented,
|
||||
/// Attempted to copy over register boundary
|
||||
RegisterArrayOverflow,
|
||||
}
|
||||
|
||||
/// Error
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Error {
|
||||
/// Kind
|
||||
pub kind: ErrorKind,
|
||||
/// Location in bytecode
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
/// Perform bytecode validation. If it passes, the program should be
|
||||
/// sound to execute.
|
||||
pub fn validate(mut program: &[u8]) -> Result<(), Error> {
|
||||
use hbbytecode::opcode::*;
|
||||
|
||||
let start = program;
|
||||
loop {
|
||||
// Match on instruction types and perform necessary checks
|
||||
program = match program {
|
||||
[] => return Ok(()),
|
||||
[LD..=ST, reg, _, _, _, _, _, _, _, _, _, count, ..]
|
||||
if usize::from(*reg) * 8 + usize::from(*count) > 2048 =>
|
||||
{
|
||||
return Err(Error {
|
||||
kind: ErrorKind::RegisterArrayOverflow,
|
||||
index: (program.as_ptr() as usize) - (start.as_ptr() as usize),
|
||||
})
|
||||
}
|
||||
[BRC, src, dst, count, ..]
|
||||
if src.checked_add(*count).is_none() || dst.checked_add(*count).is_none() =>
|
||||
{
|
||||
return Err(Error {
|
||||
kind: ErrorKind::RegisterArrayOverflow,
|
||||
index: (program.as_ptr() as usize) - (start.as_ptr() as usize),
|
||||
})
|
||||
}
|
||||
[NOP | ECALL, rest @ ..]
|
||||
| [DIR | DIRF, _, _, _, _, rest @ ..]
|
||||
| [ADD..=CMPU | BRC | ADDF..=MULF, _, _, _, rest @ ..]
|
||||
| [NEG..=NOT | CP..=SWA | NEGF..=FTI, _, _, rest @ ..]
|
||||
| [LI | JMP, _, _, _, _, _, _, _, _, _, rest @ ..]
|
||||
| [ADDI..=CMPUI | BMC | JEQ..=JGTU | ADDFI..=MULFI, _, _, _, _, _, _, _, _, _, _, rest @ ..]
|
||||
| [LD..=ST, _, _, _, _, _, _, _, _, _, _, _, _, rest @ ..] => rest,
|
||||
_ => {
|
||||
return Err(Error {
|
||||
kind: ErrorKind::InvalidInstruction,
|
||||
index: (program.as_ptr() as usize) - (start.as_ptr() as usize),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
434
hbvm/src/vm/mem/mod.rs
Normal file
434
hbvm/src/vm/mem/mod.rs
Normal file
|
@ -0,0 +1,434 @@
|
|||
//! Program memory implementation
|
||||
|
||||
pub mod paging;
|
||||
|
||||
mod pfhandler;
|
||||
|
||||
pub use pfhandler::HandlePageFault;
|
||||
|
||||
use {
|
||||
self::paging::{PageTable, Permission, PtEntry},
|
||||
super::VmRunError,
|
||||
alloc::boxed::Box,
|
||||
core::mem::MaybeUninit,
|
||||
derive_more::Display,
|
||||
};
|
||||
|
||||
/// HoleyBytes virtual memory
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Memory {
|
||||
/// Root page table
|
||||
root_pt: *mut PageTable,
|
||||
}
|
||||
|
||||
impl Default for Memory {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
root_pt: Box::into_raw(Box::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
let _ = unsafe { Box::from_raw(self.root_pt) };
|
||||
}
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
// HACK: Just for allocation testing, will be removed when proper memory interfaces
|
||||
// implemented.
|
||||
pub fn insert_test_page(&mut self) {
|
||||
unsafe {
|
||||
let mut entry = PtEntry::new(
|
||||
{
|
||||
let layout = alloc::alloc::Layout::from_size_align_unchecked(4096, 4096);
|
||||
let ptr = alloc::alloc::alloc_zeroed(layout);
|
||||
if ptr.is_null() {
|
||||
alloc::alloc::handle_alloc_error(layout);
|
||||
}
|
||||
|
||||
core::ptr::write_bytes(ptr, 69, 10);
|
||||
ptr.cast()
|
||||
},
|
||||
Permission::Write,
|
||||
);
|
||||
|
||||
for _ in 0..4 {
|
||||
let mut pt = Box::<PageTable>::default();
|
||||
pt[0] = entry;
|
||||
entry = PtEntry::new(Box::into_raw(pt) as _, Permission::Node);
|
||||
}
|
||||
|
||||
(*self.root_pt)[0] = entry;
|
||||
}
|
||||
}
|
||||
|
||||
/// Load value from an address
|
||||
///
|
||||
/// # Safety
|
||||
/// Applies same conditions as for [`core::ptr::copy_nonoverlapping`]
|
||||
pub unsafe fn load(
|
||||
&mut self,
|
||||
addr: u64,
|
||||
target: *mut u8,
|
||||
count: usize,
|
||||
traph: &mut impl HandlePageFault,
|
||||
) -> Result<(), LoadError> {
|
||||
self.memory_access(
|
||||
MemoryAccessReason::Load,
|
||||
addr,
|
||||
target,
|
||||
count,
|
||||
|perm| {
|
||||
matches!(
|
||||
perm,
|
||||
Permission::Readonly | Permission::Write | Permission::Exec
|
||||
)
|
||||
},
|
||||
|src, dst, count| core::ptr::copy_nonoverlapping(src, dst, count),
|
||||
traph,
|
||||
)
|
||||
.map_err(LoadError)
|
||||
}
|
||||
|
||||
/// Store value to an address
|
||||
///
|
||||
/// # Safety
|
||||
/// Applies same conditions as for [`core::ptr::copy_nonoverlapping`]
|
||||
pub unsafe fn store(
|
||||
&mut self,
|
||||
addr: u64,
|
||||
source: *const u8,
|
||||
count: usize,
|
||||
traph: &mut impl HandlePageFault,
|
||||
) -> Result<(), StoreError> {
|
||||
self.memory_access(
|
||||
MemoryAccessReason::Store,
|
||||
addr,
|
||||
source.cast_mut(),
|
||||
count,
|
||||
|perm| perm == Permission::Write,
|
||||
|dst, src, count| core::ptr::copy_nonoverlapping(src, dst, count),
|
||||
traph,
|
||||
)
|
||||
.map_err(StoreError)
|
||||
}
|
||||
|
||||
/// Copy a block of memory
|
||||
///
|
||||
/// # Safety
|
||||
/// - Same as for [`Self::load`] and [`Self::store`]
|
||||
/// - Your faith in the gods of UB
|
||||
/// - Addr-san claims it's fine but who knows is she isn't lying :ferrisSus:
|
||||
pub unsafe fn block_copy(
|
||||
&mut self,
|
||||
src: u64,
|
||||
dst: u64,
|
||||
count: usize,
|
||||
traph: &mut impl HandlePageFault,
|
||||
) -> Result<(), BlkCopyError> {
|
||||
// Yea, i know it is possible to do this more efficiently, but I am too lazy.
|
||||
|
||||
const STACK_BUFFER_SIZE: usize = 512;
|
||||
|
||||
// Decide if to use stack-allocated buffer or to heap allocate
|
||||
// Deallocation is again decided on size at the end of the function
|
||||
let mut buf = MaybeUninit::<[u8; STACK_BUFFER_SIZE]>::uninit();
|
||||
let buf = if count <= STACK_BUFFER_SIZE {
|
||||
buf.as_mut_ptr().cast()
|
||||
} else {
|
||||
unsafe {
|
||||
let layout = core::alloc::Layout::from_size_align_unchecked(count, 1);
|
||||
let ptr = alloc::alloc::alloc(layout);
|
||||
if ptr.is_null() {
|
||||
alloc::alloc::handle_alloc_error(layout);
|
||||
}
|
||||
|
||||
ptr
|
||||
}
|
||||
};
|
||||
|
||||
// Perform memory block transfer
|
||||
let status = (|| {
|
||||
// Load to buffer
|
||||
self.memory_access(
|
||||
MemoryAccessReason::Load,
|
||||
src,
|
||||
buf,
|
||||
count,
|
||||
|perm| {
|
||||
matches!(
|
||||
perm,
|
||||
Permission::Readonly | Permission::Write | Permission::Exec
|
||||
)
|
||||
},
|
||||
|src, dst, count| core::ptr::copy(src, dst, count),
|
||||
traph,
|
||||
)
|
||||
.map_err(|addr| BlkCopyError {
|
||||
access_reason: MemoryAccessReason::Load,
|
||||
addr,
|
||||
})?;
|
||||
|
||||
// Store from buffer
|
||||
self.memory_access(
|
||||
MemoryAccessReason::Store,
|
||||
dst,
|
||||
buf,
|
||||
count,
|
||||
|perm| perm == Permission::Write,
|
||||
|dst, src, count| core::ptr::copy(src, dst, count),
|
||||
traph,
|
||||
)
|
||||
.map_err(|addr| BlkCopyError {
|
||||
access_reason: MemoryAccessReason::Store,
|
||||
addr,
|
||||
})?;
|
||||
|
||||
Ok::<_, BlkCopyError>(())
|
||||
})();
|
||||
|
||||
// Deallocate if used heap-allocated array
|
||||
if count > STACK_BUFFER_SIZE {
|
||||
alloc::alloc::dealloc(
|
||||
buf,
|
||||
core::alloc::Layout::from_size_align_unchecked(count, 1),
|
||||
);
|
||||
}
|
||||
|
||||
status
|
||||
}
|
||||
|
||||
/// Split address to pages, check their permissions and feed pointers with offset
|
||||
/// to a specified function.
|
||||
///
|
||||
/// If page is not found, execute page fault trap handler.
|
||||
#[allow(clippy::too_many_arguments)] // Silence peasant
|
||||
fn memory_access(
|
||||
&mut self,
|
||||
reason: MemoryAccessReason,
|
||||
src: u64,
|
||||
mut dst: *mut u8,
|
||||
len: usize,
|
||||
permission_check: fn(Permission) -> bool,
|
||||
action: fn(*mut u8, *mut u8, usize),
|
||||
traph: &mut impl HandlePageFault,
|
||||
) -> Result<(), u64> {
|
||||
let mut pspl = AddrSplitter::new(src, len, self.root_pt);
|
||||
loop {
|
||||
match pspl.next() {
|
||||
// Page found
|
||||
Some(Ok(AddrSplitOk {
|
||||
vaddr,
|
||||
ptr,
|
||||
size,
|
||||
perm,
|
||||
})) => {
|
||||
if !permission_check(perm) {
|
||||
return Err(vaddr);
|
||||
}
|
||||
|
||||
// Perform memory action and bump dst pointer
|
||||
action(ptr, dst, size);
|
||||
dst = unsafe { dst.add(size) };
|
||||
}
|
||||
Some(Err(AddrSplitError { addr, size })) => {
|
||||
// Execute page fault handler
|
||||
if traph.page_fault(reason, self, addr, size, dst) {
|
||||
// Shift the splitter address
|
||||
pspl.bump(size);
|
||||
|
||||
// Bump dst pointer
|
||||
dst = unsafe { dst.add(size as _) };
|
||||
} else {
|
||||
return Err(addr); // Unhandleable
|
||||
}
|
||||
}
|
||||
None => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Result from address split
|
||||
struct AddrSplitOk {
|
||||
/// Virtual address
|
||||
vaddr: u64,
|
||||
|
||||
/// Pointer to the start for perform operation
|
||||
ptr: *mut u8,
|
||||
|
||||
/// Size to the end of page / end of desired size
|
||||
size: usize,
|
||||
|
||||
/// Page permission
|
||||
perm: Permission,
|
||||
}
|
||||
|
||||
struct AddrSplitError {
|
||||
/// Address of failure
|
||||
addr: u64,
|
||||
|
||||
/// Requested page size
|
||||
size: PageSize,
|
||||
}
|
||||
|
||||
/// Address splitter into pages
|
||||
struct AddrSplitter {
|
||||
/// Current address
|
||||
addr: u64,
|
||||
|
||||
/// Size left
|
||||
size: usize,
|
||||
|
||||
/// Page table
|
||||
pagetable: *const PageTable,
|
||||
}
|
||||
|
||||
impl AddrSplitter {
|
||||
/// Create a new page splitter
|
||||
pub const fn new(addr: u64, size: usize, pagetable: *const PageTable) -> Self {
|
||||
Self {
|
||||
addr,
|
||||
size,
|
||||
pagetable,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bump address by size X
|
||||
fn bump(&mut self, page_size: PageSize) {
|
||||
self.addr += page_size as u64;
|
||||
self.size = self.size.saturating_sub(page_size as _);
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for AddrSplitter {
|
||||
type Item = Result<AddrSplitOk, AddrSplitError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
// The end, everything is fine
|
||||
if self.size == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (base, perm, size, offset) = 'a: {
|
||||
let mut current_pt = self.pagetable;
|
||||
|
||||
// Walk the page table
|
||||
for lvl in (0..5).rev() {
|
||||
// Get an entry
|
||||
unsafe {
|
||||
let entry = (*current_pt).get_unchecked(
|
||||
usize::try_from((self.addr >> (lvl * 9 + 12)) & ((1 << 9) - 1))
|
||||
.expect("?conradluget a better CPU"),
|
||||
);
|
||||
|
||||
let ptr = entry.ptr();
|
||||
match entry.permission() {
|
||||
// No page → page fault
|
||||
Permission::Empty => {
|
||||
return Some(Err(AddrSplitError {
|
||||
addr: self.addr,
|
||||
size: PageSize::from_lvl(lvl)?,
|
||||
}))
|
||||
}
|
||||
|
||||
// Node → proceed waking
|
||||
Permission::Node => current_pt = ptr as _,
|
||||
|
||||
// Leaft → return relevant data
|
||||
perm => {
|
||||
break 'a (
|
||||
// Pointer in host memory
|
||||
ptr as *mut u8,
|
||||
perm,
|
||||
PageSize::from_lvl(lvl)?,
|
||||
// In-page offset
|
||||
self.addr as usize & ((1 << (lvl * 9 + 12)) - 1),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return None; // Reached the end (should not happen)
|
||||
};
|
||||
|
||||
// Get available byte count in the selected page with offset
|
||||
let avail = (size as usize - offset).clamp(0, self.size);
|
||||
self.bump(size);
|
||||
|
||||
Some(Ok(AddrSplitOk {
|
||||
vaddr: self.addr,
|
||||
ptr: unsafe { base.add(offset) }, // Return pointer to the start of region
|
||||
size: avail,
|
||||
perm,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Page size
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PageSize {
|
||||
/// 4 KiB page (on level 0)
|
||||
Size4K = 4096,
|
||||
|
||||
/// 2 MiB page (on level 1)
|
||||
Size2M = 1024 * 1024 * 2,
|
||||
|
||||
/// 1 GiB page (on level 2)
|
||||
Size1G = 1024 * 1024 * 1024,
|
||||
}
|
||||
|
||||
impl PageSize {
|
||||
/// Convert page table level to size of page
|
||||
fn from_lvl(lvl: u8) -> Option<Self> {
|
||||
match lvl {
|
||||
0 => Some(PageSize::Size4K),
|
||||
1 => Some(PageSize::Size2M),
|
||||
2 => Some(PageSize::Size1G),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unhandled load access trap
|
||||
#[derive(Clone, Copy, Display, Debug, PartialEq, Eq)]
|
||||
pub struct LoadError(u64);
|
||||
|
||||
/// Unhandled store access trap
|
||||
#[derive(Clone, Copy, Display, Debug, PartialEq, Eq)]
|
||||
pub struct StoreError(u64);
|
||||
|
||||
#[derive(Clone, Copy, Display, Debug, PartialEq, Eq)]
|
||||
pub enum MemoryAccessReason {
|
||||
Load,
|
||||
Store,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BlkCopyError {
|
||||
access_reason: MemoryAccessReason,
|
||||
addr: u64,
|
||||
}
|
||||
|
||||
impl From<BlkCopyError> for VmRunError {
|
||||
fn from(value: BlkCopyError) -> Self {
|
||||
match value.access_reason {
|
||||
MemoryAccessReason::Load => Self::LoadAccessEx(value.addr),
|
||||
MemoryAccessReason::Store => Self::StoreAccessEx(value.addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LoadError> for VmRunError {
|
||||
fn from(value: LoadError) -> Self {
|
||||
Self::LoadAccessEx(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StoreError> for VmRunError {
|
||||
fn from(value: StoreError) -> Self {
|
||||
Self::StoreAccessEx(value.0)
|
||||
}
|
||||
}
|
152
hbvm/src/vm/mem/paging.rs
Normal file
152
hbvm/src/vm/mem/paging.rs
Normal file
|
@ -0,0 +1,152 @@
|
|||
//! Page table and associated structures implementation
|
||||
|
||||
use {
|
||||
core::{
|
||||
fmt::Debug,
|
||||
mem::MaybeUninit,
|
||||
ops::{Index, IndexMut},
|
||||
slice::SliceIndex,
|
||||
},
|
||||
delegate::delegate,
|
||||
};
|
||||
|
||||
/// Page entry permission
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum Permission {
|
||||
/// No page present
|
||||
#[default]
|
||||
Empty,
|
||||
/// Points to another pagetable
|
||||
Node,
|
||||
/// Page is read only
|
||||
Readonly,
|
||||
/// Page is readable and writable
|
||||
Write,
|
||||
/// Page is readable and executable
|
||||
Exec,
|
||||
}
|
||||
|
||||
/// Page table entry
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PtEntry(u64);
|
||||
impl PtEntry {
|
||||
/// Create new
|
||||
///
|
||||
/// # Safety
|
||||
/// - `ptr` has to point to valid data and shall not be deallocated
|
||||
/// troughout the entry lifetime
|
||||
#[inline]
|
||||
pub unsafe fn new(ptr: *mut PtPointedData, permission: Permission) -> Self {
|
||||
Self(ptr as u64 | permission as u64)
|
||||
}
|
||||
|
||||
/// Get permission
|
||||
#[inline]
|
||||
pub fn permission(&self) -> Permission {
|
||||
unsafe { core::mem::transmute(self.0 as u8 & 0b111) }
|
||||
}
|
||||
|
||||
/// Get pointer to the data (leaf) or next page table (node)
|
||||
#[inline]
|
||||
pub fn ptr(&self) -> *mut PtPointedData {
|
||||
(self.0 & !((1 << 12) - 1)) as _
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for PtEntry {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("PtEntry")
|
||||
.field("ptr", &self.ptr())
|
||||
.field("permission", &self.permission())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Page table
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(align(4096))]
|
||||
pub struct PageTable([PtEntry; 512]);
|
||||
|
||||
impl PageTable {
|
||||
delegate!(to self.0 {
|
||||
/// Returns a reference to an element or subslice depending on the type of
|
||||
/// index.
|
||||
///
|
||||
/// - If given a position, returns a reference to the element at that
|
||||
/// position or `None` if out of bounds.
|
||||
/// - If given a range, returns the subslice corresponding to that range,
|
||||
/// or `None` if out of bounds.
|
||||
///
|
||||
pub fn get<I>(&self, ix: I) -> Option<&I::Output>
|
||||
where I: SliceIndex<[PtEntry]>;
|
||||
|
||||
/// Returns a mutable reference to an element or subslice depending on the
|
||||
/// type of index (see [`get`]) or `None` if the index is out of bounds.
|
||||
pub fn get_mut<I>(&mut self, ix: I) -> Option<&mut I::Output>
|
||||
where I: SliceIndex<[PtEntry]>;
|
||||
|
||||
/// Returns a reference to an element or subslice, without doing bounds
|
||||
/// checking.
|
||||
///
|
||||
/// For a safe alternative see [`get`].
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
|
||||
/// even if the resulting reference is not used.
|
||||
pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
|
||||
where I: SliceIndex<[PtEntry]>;
|
||||
|
||||
/// Returns a mutable reference to an element or subslice, without doing
|
||||
/// bounds checking.
|
||||
///
|
||||
/// For a safe alternative see [`get_mut`].
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
|
||||
/// even if the resulting reference is not used.
|
||||
pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
|
||||
where I: SliceIndex<[PtEntry]>;
|
||||
});
|
||||
}
|
||||
|
||||
impl<Idx> Index<Idx> for PageTable
|
||||
where
|
||||
Idx: SliceIndex<[PtEntry]>,
|
||||
{
|
||||
type Output = Idx::Output;
|
||||
|
||||
#[inline(always)]
|
||||
fn index(&self, index: Idx) -> &Self::Output {
|
||||
&self.0[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl<Idx> IndexMut<Idx> for PageTable
|
||||
where
|
||||
Idx: SliceIndex<[PtEntry]>,
|
||||
{
|
||||
#[inline(always)]
|
||||
fn index_mut(&mut self, index: Idx) -> &mut Self::Output {
|
||||
&mut self.0[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PageTable {
|
||||
fn default() -> Self {
|
||||
// SAFETY: It's fine, zeroed page table entry is valid (= empty)
|
||||
Self(unsafe { MaybeUninit::zeroed().assume_init() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Data page table entry can possibly point to
|
||||
#[derive(Clone, Copy)]
|
||||
#[repr(C, align(4096))]
|
||||
pub union PtPointedData {
|
||||
/// Node - next page table
|
||||
pub pt: PageTable,
|
||||
/// Leaf
|
||||
pub page: u8,
|
||||
}
|
16
hbvm/src/vm/mem/pfhandler.rs
Normal file
16
hbvm/src/vm/mem/pfhandler.rs
Normal file
|
@ -0,0 +1,16 @@
|
|||
//! Program trap handling interfaces
|
||||
|
||||
use super::{Memory, MemoryAccessReason, PageSize};
|
||||
|
||||
/// Handle VM traps
|
||||
pub trait HandlePageFault {
|
||||
/// Handle page fault
|
||||
fn page_fault(
|
||||
&mut self,
|
||||
reason: MemoryAccessReason,
|
||||
memory: &mut Memory,
|
||||
vaddr: u64,
|
||||
size: PageSize,
|
||||
dataptr: *mut u8,
|
||||
) -> bool;
|
||||
}
|
367
hbvm/src/vm/mod.rs
Normal file
367
hbvm/src/vm/mod.rs
Normal file
|
@ -0,0 +1,367 @@
|
|||
//! HoleyBytes Virtual Machine
|
||||
//!
|
||||
//! All unsafe code here should be sound, if input bytecode passes validation.
|
||||
|
||||
// # General safety notice:
|
||||
// - Validation has to assure there is 256 registers (r0 - r255)
|
||||
// - Instructions have to be valid as specified (values and sizes)
|
||||
// - Mapped pages should be at least 4 KiB
|
||||
// - Yes, I am aware of the UB when jumping in-mid of instruction where
|
||||
// the read byte corresponds to an instruction whose lenght exceets the
|
||||
// program size. If you are (rightfully) worried about the UB, for now just
|
||||
// append your program with 11 zeroes.
|
||||
|
||||
use self::mem::HandlePageFault;
|
||||
|
||||
pub mod mem;
|
||||
pub mod value;
|
||||
|
||||
use {
|
||||
crate::validate,
|
||||
core::ops,
|
||||
hbbytecode::{OpParam, ParamBB, ParamBBB, ParamBBBB, ParamBBD, ParamBBDH, ParamBD},
|
||||
mem::Memory,
|
||||
static_assertions::assert_impl_one,
|
||||
value::Value,
|
||||
};
|
||||
|
||||
/// Extract a parameter from program
|
||||
macro_rules! param {
|
||||
($self:expr, $ty:ty) => {{
|
||||
assert_impl_one!($ty: OpParam);
|
||||
let data = $self
|
||||
.program
|
||||
.as_ptr()
|
||||
.add($self.pc + 1)
|
||||
.cast::<$ty>()
|
||||
.read();
|
||||
$self.pc += 1 + core::mem::size_of::<$ty>();
|
||||
data
|
||||
}};
|
||||
}
|
||||
|
||||
/// Perform binary operation `#0 ← #1 OP #2`
|
||||
macro_rules! binary_op {
|
||||
($self:expr, $ty:ident, $handler:expr) => {{
|
||||
let ParamBBB(tg, a0, a1) = param!($self, ParamBBB);
|
||||
$self.write_reg(
|
||||
tg,
|
||||
$handler(
|
||||
Value::$ty(&$self.read_reg(a0)),
|
||||
Value::$ty(&$self.read_reg(a1)),
|
||||
),
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
/// Perform binary operation with immediate `#0 ← #1 OP imm #2`
|
||||
macro_rules! binary_op_imm {
|
||||
($self:expr, $ty:ident, $handler:expr) => {{
|
||||
let ParamBBD(tg, a0, imm) = param!($self, ParamBBD);
|
||||
$self.write_reg(
|
||||
tg,
|
||||
$handler(Value::$ty(&$self.read_reg(a0)), Value::$ty(&imm.into())),
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
/// Jump at `#3` if ordering on `#0 <=> #1` is equal to expected
|
||||
macro_rules! cond_jump {
|
||||
($self:expr, $ty:ident, $expected:ident) => {{
|
||||
let ParamBBD(a0, a1, jt) = param!($self, ParamBBD);
|
||||
if core::cmp::Ord::cmp(&$self.read_reg(a0).as_u64(), &$self.read_reg(a1).as_u64())
|
||||
== core::cmp::Ordering::$expected
|
||||
{
|
||||
$self.pc = jt as usize;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// HoleyBytes Virtual Machine
|
||||
pub struct Vm<'a, PfHandler, const TIMER_QUOTIENT: usize> {
|
||||
/// Holds 256 registers
|
||||
///
|
||||
/// Writing to register 0 is considered undefined behaviour
|
||||
/// in terms of HoleyBytes program execution
|
||||
pub registers: [Value; 256],
|
||||
|
||||
/// Memory implementation
|
||||
pub memory: Memory,
|
||||
|
||||
/// Trap handler
|
||||
pub pfhandler: PfHandler,
|
||||
|
||||
// Program counter
|
||||
pc: usize,
|
||||
|
||||
/// Program
|
||||
program: &'a [u8],
|
||||
|
||||
/// Program timer
|
||||
timer: usize,
|
||||
}
|
||||
|
||||
impl<'a, PfHandler: HandlePageFault, const TIMER_QUOTIENT: usize>
|
||||
Vm<'a, PfHandler, TIMER_QUOTIENT>
|
||||
{
|
||||
/// Create a new VM with program and trap handler
|
||||
///
|
||||
/// # Safety
|
||||
/// Program code has to be validated
|
||||
pub unsafe fn new_unchecked(program: &'a [u8], traph: PfHandler) -> Self {
|
||||
Self {
|
||||
registers: [Value::from(0_u64); 256],
|
||||
memory: Default::default(),
|
||||
pfhandler: traph,
|
||||
pc: 0,
|
||||
program,
|
||||
timer: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new VM with program and trap handler only if it passes validation
|
||||
pub fn new_validated(program: &'a [u8], traph: PfHandler) -> Result<Self, validate::Error> {
|
||||
validate::validate(program)?;
|
||||
Ok(unsafe { Self::new_unchecked(program, traph) })
|
||||
}
|
||||
|
||||
/// Execute program
|
||||
///
|
||||
/// Program can return [`VmRunError`] if a trap handling failed
|
||||
pub fn run(&mut self) -> Result<VmRunOk, VmRunError> {
|
||||
use hbbytecode::opcode::*;
|
||||
loop {
|
||||
// Fetch instruction
|
||||
let Some(&opcode) = self.program.get(self.pc)
|
||||
else { return Ok(VmRunOk::End) };
|
||||
|
||||
// Big match
|
||||
unsafe {
|
||||
match opcode {
|
||||
NOP => param!(self, ()),
|
||||
ADD => binary_op!(self, as_u64, u64::wrapping_add),
|
||||
SUB => binary_op!(self, as_u64, u64::wrapping_sub),
|
||||
MUL => binary_op!(self, as_u64, u64::wrapping_mul),
|
||||
AND => binary_op!(self, as_u64, ops::BitAnd::bitand),
|
||||
OR => binary_op!(self, as_u64, ops::BitOr::bitor),
|
||||
XOR => binary_op!(self, as_u64, ops::BitXor::bitxor),
|
||||
SL => binary_op!(self, as_u64, ops::Shl::shl),
|
||||
SR => binary_op!(self, as_u64, ops::Shr::shr),
|
||||
SRS => binary_op!(self, as_i64, ops::Shr::shr),
|
||||
CMP => {
|
||||
let ParamBBB(tg, a0, a1) = param!(self, ParamBBB);
|
||||
self.write_reg(
|
||||
tg,
|
||||
self.read_reg(a0).as_i64().cmp(&self.read_reg(a1).as_i64()) as i64,
|
||||
);
|
||||
}
|
||||
CMPU => {
|
||||
let ParamBBB(tg, a0, a1) = param!(self, ParamBBB);
|
||||
self.write_reg(
|
||||
tg,
|
||||
self.read_reg(a0).as_u64().cmp(&self.read_reg(a1).as_u64()) as i64,
|
||||
);
|
||||
}
|
||||
NOT => {
|
||||
let param = param!(self, ParamBB);
|
||||
self.write_reg(param.0, !self.read_reg(param.1).as_u64());
|
||||
}
|
||||
NEG => {
|
||||
let param = param!(self, ParamBB);
|
||||
self.write_reg(
|
||||
param.0,
|
||||
match self.read_reg(param.1).as_u64() {
|
||||
0 => 1_u64,
|
||||
_ => 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
DIR => {
|
||||
let ParamBBBB(dt, rt, a0, a1) = param!(self, ParamBBBB);
|
||||
let a0 = self.read_reg(a0).as_u64();
|
||||
let a1 = self.read_reg(a1).as_u64();
|
||||
self.write_reg(dt, a0.checked_div(a1).unwrap_or(u64::MAX));
|
||||
self.write_reg(rt, a0.checked_rem(a1).unwrap_or(u64::MAX));
|
||||
}
|
||||
ADDI => binary_op_imm!(self, as_u64, ops::Add::add),
|
||||
MULI => binary_op_imm!(self, as_u64, ops::Mul::mul),
|
||||
ANDI => binary_op_imm!(self, as_u64, ops::BitAnd::bitand),
|
||||
ORI => binary_op_imm!(self, as_u64, ops::BitOr::bitor),
|
||||
XORI => binary_op_imm!(self, as_u64, ops::BitXor::bitxor),
|
||||
SLI => binary_op_imm!(self, as_u64, ops::Shl::shl),
|
||||
SRI => binary_op_imm!(self, as_u64, ops::Shr::shr),
|
||||
SRSI => binary_op_imm!(self, as_i64, ops::Shr::shr),
|
||||
CMPI => {
|
||||
let ParamBBD(tg, a0, imm) = param!(self, ParamBBD);
|
||||
self.write_reg(
|
||||
tg,
|
||||
self.read_reg(a0).as_i64().cmp(&Value::from(imm).as_i64()) as i64,
|
||||
);
|
||||
}
|
||||
CMPUI => {
|
||||
let ParamBBD(tg, a0, imm) = param!(self, ParamBBD);
|
||||
self.write_reg(tg, self.read_reg(a0).as_u64().cmp(&imm) as i64);
|
||||
}
|
||||
CP => {
|
||||
let param = param!(self, ParamBB);
|
||||
self.write_reg(param.0, self.read_reg(param.1));
|
||||
}
|
||||
SWA => {
|
||||
let ParamBB(src, dst) = param!(self, ParamBB);
|
||||
if src + dst != 0 {
|
||||
core::ptr::swap(
|
||||
self.registers.get_unchecked_mut(usize::from(src)),
|
||||
self.registers.get_unchecked_mut(usize::from(dst)),
|
||||
);
|
||||
}
|
||||
}
|
||||
LI => {
|
||||
let param = param!(self, ParamBD);
|
||||
self.write_reg(param.0, param.1);
|
||||
}
|
||||
LD => {
|
||||
let ParamBBDH(dst, base, off, count) = param!(self, ParamBBDH);
|
||||
let n: usize = match dst {
|
||||
0 => 1,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
self.memory.load(
|
||||
self.read_reg(base).as_u64() + off + n as u64,
|
||||
self.registers.as_mut_ptr().add(usize::from(dst) + n).cast(),
|
||||
usize::from(count).saturating_sub(n),
|
||||
&mut self.pfhandler,
|
||||
)?;
|
||||
}
|
||||
ST => {
|
||||
let ParamBBDH(dst, base, off, count) = param!(self, ParamBBDH);
|
||||
self.memory.store(
|
||||
self.read_reg(base).as_u64() + off,
|
||||
self.registers.as_ptr().add(usize::from(dst)).cast(),
|
||||
count.into(),
|
||||
&mut self.pfhandler,
|
||||
)?;
|
||||
}
|
||||
BMC => {
|
||||
let ParamBBD(src, dst, count) = param!(self, ParamBBD);
|
||||
self.memory.block_copy(
|
||||
self.read_reg(src).as_u64(),
|
||||
self.read_reg(dst).as_u64(),
|
||||
count as _,
|
||||
&mut self.pfhandler,
|
||||
)?;
|
||||
}
|
||||
BRC => {
|
||||
let ParamBBB(src, dst, count) = param!(self, ParamBBB);
|
||||
core::ptr::copy(
|
||||
self.registers.get_unchecked(usize::from(src)),
|
||||
self.registers.get_unchecked_mut(usize::from(dst)),
|
||||
usize::from(count * 8),
|
||||
);
|
||||
}
|
||||
JMP => {
|
||||
let ParamBD(reg, offset) = param!(self, ParamBD);
|
||||
self.pc = (self.read_reg(reg).as_u64() + offset) as usize;
|
||||
}
|
||||
JEQ => cond_jump!(self, int, Equal),
|
||||
JNE => {
|
||||
let ParamBBD(a0, a1, jt) = param!(self, ParamBBD);
|
||||
if self.read_reg(a0).as_u64() != self.read_reg(a1).as_u64() {
|
||||
self.pc = jt as usize;
|
||||
}
|
||||
}
|
||||
JLT => cond_jump!(self, int, Less),
|
||||
JGT => cond_jump!(self, int, Greater),
|
||||
JLTU => cond_jump!(self, sint, Less),
|
||||
JGTU => cond_jump!(self, sint, Greater),
|
||||
ECALL => {
|
||||
param!(self, ());
|
||||
return Ok(VmRunOk::Ecall);
|
||||
}
|
||||
ADDF => binary_op!(self, as_f64, ops::Add::add),
|
||||
SUBF => binary_op!(self, as_f64, ops::Sub::sub),
|
||||
MULF => binary_op!(self, as_f64, ops::Mul::mul),
|
||||
DIRF => {
|
||||
let ParamBBBB(dt, rt, a0, a1) = param!(self, ParamBBBB);
|
||||
let a0 = self.read_reg(a0).as_f64();
|
||||
let a1 = self.read_reg(a1).as_f64();
|
||||
self.write_reg(dt, a0 / a1);
|
||||
self.write_reg(rt, a0 % a1);
|
||||
}
|
||||
FMAF => {
|
||||
let ParamBBBB(dt, a0, a1, a2) = param!(self, ParamBBBB);
|
||||
self.write_reg(
|
||||
dt,
|
||||
self.read_reg(a0).as_f64() * self.read_reg(a1).as_f64()
|
||||
+ self.read_reg(a2).as_f64(),
|
||||
);
|
||||
}
|
||||
NEGF => {
|
||||
let ParamBB(dt, a0) = param!(self, ParamBB);
|
||||
self.write_reg(dt, -self.read_reg(a0).as_f64());
|
||||
}
|
||||
ITF => {
|
||||
let ParamBB(dt, a0) = param!(self, ParamBB);
|
||||
self.write_reg(dt, self.read_reg(a0).as_i64() as f64);
|
||||
}
|
||||
FTI => {
|
||||
let ParamBB(dt, a0) = param!(self, ParamBB);
|
||||
self.write_reg(dt, self.read_reg(a0).as_f64() as i64);
|
||||
}
|
||||
ADDFI => binary_op_imm!(self, as_f64, ops::Add::add),
|
||||
MULFI => binary_op_imm!(self, as_f64, ops::Mul::mul),
|
||||
op => return Err(VmRunError::InvalidOpcode(op)),
|
||||
}
|
||||
}
|
||||
|
||||
if TIMER_QUOTIENT != 0 {
|
||||
self.timer = self.timer.wrapping_add(1);
|
||||
if self.timer % TIMER_QUOTIENT == 0 {
|
||||
return Ok(VmRunOk::Timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read register
|
||||
#[inline]
|
||||
unsafe fn read_reg(&self, n: u8) -> Value {
|
||||
*self.registers.get_unchecked(n as usize)
|
||||
}
|
||||
|
||||
/// Write a register.
|
||||
/// Writing to register 0 is no-op.
|
||||
#[inline]
|
||||
unsafe fn write_reg(&mut self, n: u8, value: impl Into<Value>) {
|
||||
if n != 0 {
|
||||
*self.registers.get_unchecked_mut(n as usize) = value.into();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Virtual machine halt error
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum VmRunError {
|
||||
/// Tried to execute invalid instruction
|
||||
InvalidOpcode(u8),
|
||||
|
||||
/// Unhandled load access exception
|
||||
LoadAccessEx(u64),
|
||||
|
||||
/// Unhandled store access exception
|
||||
StoreAccessEx(u64),
|
||||
}
|
||||
|
||||
/// Virtual machine halt ok
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum VmRunOk {
|
||||
/// Program has eached its end
|
||||
End,
|
||||
|
||||
/// Program was interrupted by a timer
|
||||
Timer,
|
||||
|
||||
/// Environment call
|
||||
Ecall,
|
||||
}
|
48
hbvm/src/vm/value.rs
Normal file
48
hbvm/src/vm/value.rs
Normal file
|
@ -0,0 +1,48 @@
|
|||
//! HoleyBytes register value definition
|
||||
|
||||
use core::fmt::Debug;
|
||||
|
||||
/// Define [`Value`] union
|
||||
///
|
||||
/// # Safety
|
||||
/// Union variants have to be sound to byte-reinterpretate
|
||||
/// between each other. Otherwise the behaviour is undefined.
|
||||
macro_rules! value_def {
|
||||
($($ty:ident),* $(,)?) => {
|
||||
/// HBVM register value
|
||||
#[derive(Copy, Clone)]
|
||||
#[repr(packed)]
|
||||
pub union Value {
|
||||
$(pub $ty: $ty),*
|
||||
}
|
||||
|
||||
paste::paste! {
|
||||
impl Value {$(
|
||||
#[doc = "Byte-reinterpret [`Value`] as [`" $ty "`]"]
|
||||
#[inline]
|
||||
pub fn [<as_ $ty>](&self) -> $ty {
|
||||
unsafe { self.$ty }
|
||||
}
|
||||
)*}
|
||||
}
|
||||
|
||||
$(
|
||||
impl From<$ty> for Value {
|
||||
#[inline]
|
||||
fn from(value: $ty) -> Self {
|
||||
Self { $ty: value }
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
value_def!(u64, i64, f64);
|
||||
static_assertions::const_assert_eq!(core::mem::size_of::<Value>(), 8);
|
||||
|
||||
impl Debug for Value {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
// Print formatted as hexadecimal, unsigned integer
|
||||
write!(f, "{:x}", self.as_u64())
|
||||
}
|
||||
}
|
|
@ -1,3 +1,4 @@
|
|||
hex_literal_case = "Upper"
|
||||
imports_granularity = "One"
|
||||
struct_field_align_threshold = 5
|
||||
enum_discrim_align_threshold = 5
|
295
spec.md
Normal file
295
spec.md
Normal file
|
@ -0,0 +1,295 @@
|
|||
# HoleyBytes ISA Specification
|
||||
|
||||
# Bytecode format
|
||||
- All numbers are encoded little-endian
|
||||
- There is 256 registers, they are represented by a byte
|
||||
- Immediate values are 64 bit
|
||||
|
||||
### Instruction encoding
|
||||
- Instruction parameters are packed (no alignment)
|
||||
- [opcode, …parameters…]
|
||||
|
||||
### Instruction parameter types
|
||||
- B = Byte
|
||||
- D = Doubleword (64 bits)
|
||||
- H = Halfword (16 bits)
|
||||
|
||||
| Name | Size |
|
||||
|:----:|:--------|
|
||||
| BBBB | 32 bits |
|
||||
| BBB | 24 bits |
|
||||
| BBDH | 96 bits |
|
||||
| BBD | 80 bits |
|
||||
| BB | 16 bits |
|
||||
| BD | 72 bits |
|
||||
| D | 64 bits |
|
||||
| N | 0 bits |
|
||||
|
||||
# Instructions
|
||||
- `#n`: register in parameter *n*
|
||||
- `imm #n`: for immediate in parameter *n*
|
||||
- `P ← V`: Set register P to value V
|
||||
- `[x]`: Address x
|
||||
|
||||
## No-op
|
||||
- N type
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:----------:|
|
||||
| 0 | NOP | Do nothing |
|
||||
|
||||
## Integer binary ops.
|
||||
- BBB type
|
||||
- `#0 ← #1 <op> #2`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:-----------------------:|
|
||||
| 1 | ADD | Wrapping addition |
|
||||
| 2 | SUB | Wrapping subtraction |
|
||||
| 3 | MUL | Wrapping multiplication |
|
||||
| 4 | AND | Bitand |
|
||||
| 5 | OR | Bitor |
|
||||
| 6 | XOR | Bitxor |
|
||||
| 7 | SL | Unsigned left bitshift |
|
||||
| 8 | SR | Unsigned right bitshift |
|
||||
| 9 | SRS | Signed right bitshift |
|
||||
|
||||
### Comparsion
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:-------------------:|
|
||||
| 10 | CMP | Signed comparsion |
|
||||
| 11 | CMPU | Unsigned comparsion |
|
||||
|
||||
#### Comparsion table
|
||||
| #1 *op* #2 | Result |
|
||||
|:----------:|:------:|
|
||||
| < | -1 |
|
||||
| = | 0 |
|
||||
| > | 1 |
|
||||
|
||||
### Division-remainder
|
||||
- Type BBBB
|
||||
- In case of `#3` is zero, the resulting value is all-ones
|
||||
- `#0 ← #2 ÷ #3`
|
||||
- `#1 ← #2 % #3`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:-------------------------------:|
|
||||
| 12 | DIR | Divide and remainder combinated |
|
||||
|
||||
### Negations
|
||||
- Type BB
|
||||
- `#0 ← #1 <op> #2`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:----------------:|
|
||||
| 13 | NEG | Bit negation |
|
||||
| 14 | NOT | Logical negation |
|
||||
|
||||
## Integer immediate binary ops.
|
||||
- Type BBD
|
||||
- `#0 ← #1 <op> imm #2`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:-----------------------:|
|
||||
| 15 | ADDI | Wrapping addition |
|
||||
| 16 | MULI | Wrapping subtraction |
|
||||
| 17 | ANDI | Bitand |
|
||||
| 18 | ORI | Bitor |
|
||||
| 19 | XORI | Bitxor |
|
||||
| 20 | SLI | Unsigned left bitshift |
|
||||
| 21 | SRI | Unsigned right bitshift |
|
||||
| 22 | SRSI | Signed right bitshift |
|
||||
|
||||
### Comparsion
|
||||
- Comparsion is the same as when RRR type
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:-----:|:-------------------:|
|
||||
| 23 | CMPI | Signed comparsion |
|
||||
| 24 | CMPUI | Unsigned comparsion |
|
||||
|
||||
## Register value set / copy
|
||||
|
||||
### Copy
|
||||
- Type BB
|
||||
- `#0 ← #1`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:------:|
|
||||
| 25 | CP | Copy |
|
||||
|
||||
### Swap
|
||||
- Type BB
|
||||
- Swap #0 and #1
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:------:|
|
||||
| 26 | SWA | Swap |
|
||||
|
||||
### Load immediate
|
||||
- Type BD
|
||||
- `#0 ← #1`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:--------------:|
|
||||
| 27 | LI | Load immediate |
|
||||
|
||||
## Memory operations
|
||||
- Type BBDH
|
||||
- If loaded/store value exceeds one register size, continue accessing following registers
|
||||
|
||||
### Load / Store
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:---------------------------------------:|
|
||||
| 28 | LD | `#0 ← [#1 + imm #3], copy imm #4 bytes` |
|
||||
| 29 | ST | `[#1 + imm #3] ← #0, copy imm #4 bytes` |
|
||||
|
||||
## Block copy
|
||||
- Block copy source and target can overlap
|
||||
|
||||
### Memory copy
|
||||
- Type BBD
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:--------------------------------:|
|
||||
| 30 | BMC | `[#0] ← [#1], copy imm #2 bytes` |
|
||||
|
||||
### Register copy
|
||||
- Type BBB
|
||||
- Copy a block a register to another location (again, overflowing to following registers)
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:--------------------------------:|
|
||||
| 31 | BRC | `#0 ← #1, copy imm #2 registers` |
|
||||
|
||||
## Control flow
|
||||
|
||||
### Unconditional jump
|
||||
- Type BD
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:---------------------:|
|
||||
| 32 | JMP | Jump at `#0 + imm #1` |
|
||||
|
||||
### Conditional jumps
|
||||
- Type BBD
|
||||
- Jump at `imm #2` if `#0 <op> #1`
|
||||
|
||||
| Opcode | Name | Comparsion |
|
||||
|:------:|:----:|:------------:|
|
||||
| 33 | JEQ | = |
|
||||
| 34 | JNE | ≠ |
|
||||
| 35 | JLT | < (signed) |
|
||||
| 36 | JGT | > (signed) |
|
||||
| 37 | JLTU | < (unsigned) |
|
||||
| 38 | JGTU | > (unsigned) |
|
||||
|
||||
### Environment call
|
||||
- Type N
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:-----:|:-------------------------------------:|
|
||||
| 39 | ECALL | Cause an trap to the host environment |
|
||||
|
||||
## Floating point operations
|
||||
- Type BBB
|
||||
- `#0 ← #1 <op> #2`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:--------------:|
|
||||
| 40 | ADDF | Addition |
|
||||
| 41 | SUBF | Subtraction |
|
||||
| 42 | MULF | Multiplication |
|
||||
|
||||
### Division-remainder
|
||||
- Type BBBB
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:-------------------------:|
|
||||
| 43 | DIRF | Same as for integer `DIR` |
|
||||
|
||||
### Fused Multiply-Add
|
||||
- Type BBBB
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:---------------------:|
|
||||
| 44 | FMAF | `#0 ← (#1 * #2) + #3` |
|
||||
|
||||
### Negation
|
||||
- Type BB
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:----------:|
|
||||
| 45 | NEGF | `#0 ← -#1` |
|
||||
|
||||
### Conversion
|
||||
- Type BB
|
||||
- Signed
|
||||
- `#0 ← #1 as _`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:----:|:------------:|
|
||||
| 46 | ITF | Int to Float |
|
||||
| 47 | FTI | Float to Int |
|
||||
|
||||
## Floating point immediate operations
|
||||
- Type BBD
|
||||
- `#0 ← #1 <op> imm #2`
|
||||
|
||||
| Opcode | Name | Action |
|
||||
|:------:|:-----:|:--------------:|
|
||||
| 48 | ADDFI | Addition |
|
||||
| 49 | MULFI | Multiplication |
|
||||
|
||||
# Registers
|
||||
- There is 255 registers + one zero register (with index 0)
|
||||
- Reading from zero register yields zero
|
||||
- Writing to zero register is a no-op
|
||||
|
||||
# Memory
|
||||
- Addresses are 64 bit
|
||||
- Memory implementation is arbitrary
|
||||
- In case of accessing invalid address:
|
||||
- Program shall trap (LoadAccessEx, StoreAccessEx) with parameter of accessed address
|
||||
- Value of register when trapped is undefined
|
||||
|
||||
## Recommendations
|
||||
- Leave address `0x0` as invalid
|
||||
- If paging used:
|
||||
- Leave first page invalid
|
||||
- Pages should be at least 4 KiB
|
||||
|
||||
# Program execution
|
||||
- The way of program execution is implementation defined
|
||||
- The order of instruction is arbitrary, as long all observable
|
||||
effects are applied in the program's order
|
||||
|
||||
# Program validation
|
||||
- Invalid program should cause runtime error:
|
||||
- The form of error is arbitrary. Can be a trap or an interpreter-specified error
|
||||
- It shall not be handleable from within the program
|
||||
- Executing invalid opcode should trap
|
||||
- Program can be validaded either before execution or when executing
|
||||
|
||||
# Traps
|
||||
Program should at least implement these traps:
|
||||
- Environment call
|
||||
- Invalid instruction exception
|
||||
- Load address exception
|
||||
- Store address exception
|
||||
|
||||
and executing environment should be able to get information about them,
|
||||
like the opcode of invalid instruction or attempted address to load/store.
|
||||
Details about these are left as an implementation detail.
|
||||
|
||||
# Assembly
|
||||
HoleyBytes assembly format is not defined, this is just a weak description
|
||||
of `hbasm` syntax.
|
||||
|
||||
- Opcode names correspond to specified opcode names, lowercase (`nop`)
|
||||
- Parameters are separated by comma (`addi r0, r0, 1`)
|
||||
- Instructions are separated by either line feed or semicolon
|
||||
- Registers are represented by `r` followed by the number (`r10`)
|
||||
- Labels are defined by label name followed with colon (`loop:`)
|
||||
- Labels are references simply by their name (`print`)
|
||||
- Immediates are entered plainly. Negative numbers supported.
|
Loading…
Reference in a new issue