Compare commits
2 Commits
elf
...
76197fac8f
| Author | SHA1 | Date | |
|---|---|---|---|
| 76197fac8f | |||
| bc5ddef311 |
Binary file not shown.
@@ -3,6 +3,8 @@ use crate::{instructions::encode::Encode, prelude::*};
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Interrupt {
|
||||
Software(u8),
|
||||
Breakpoint,
|
||||
HardFault,
|
||||
}
|
||||
|
||||
pub type Address = u32;
|
||||
@@ -10,6 +12,8 @@ pub type Address = u32;
|
||||
impl Interrupt {
|
||||
const fn as_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::Breakpoint => 0,
|
||||
Self::HardFault => 1,
|
||||
Self::Software(code) => code,
|
||||
}
|
||||
}
|
||||
@@ -19,10 +23,11 @@ impl Interrupt {
|
||||
impl From<u8> for Interrupt {
|
||||
#[allow(unreachable_code)]
|
||||
fn from(code: u8) -> Self {
|
||||
return Self::Software(code);
|
||||
todo!("Implement this once a hardware interrupt convention is established.");
|
||||
|
||||
// Self::Software(_code)
|
||||
match code {
|
||||
0 => Self::Breakpoint,
|
||||
1 => Self::HardFault,
|
||||
_ => Self::Software(code),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +78,8 @@ pub enum Register {
|
||||
}
|
||||
|
||||
impl Register {
|
||||
#[must_use]
|
||||
// this is here so clippy shuts up about the must_use tag.
|
||||
#[allow(clippy::must_use_candidate)]
|
||||
pub fn general() -> Vec<Self> {
|
||||
vec![
|
||||
Self::Rg0,
|
||||
|
||||
@@ -8,8 +8,9 @@ use std::{
|
||||
#[allow(unused_imports)]
|
||||
use crate::emulator::misc::rpc::{Activity, RpcClient};
|
||||
|
||||
use crate::emulator::system::model::StateUpdate;
|
||||
use crate::emulator::system::{
|
||||
model::{Command, PersistentState, Running, State},
|
||||
model::{Command, Running},
|
||||
processor::Processor,
|
||||
};
|
||||
|
||||
@@ -19,28 +20,32 @@ use common::prelude::*;
|
||||
#[allow(unused_variables)]
|
||||
pub fn run_emulator(
|
||||
cmd_rx: &Receiver<Command>,
|
||||
state_tx: &Sender<State>,
|
||||
state_tx: &Sender<StateUpdate>,
|
||||
mut processor: Processor,
|
||||
rpc_client: Option<&Arc<RpcClient>>,
|
||||
) {
|
||||
println!("INFO: Starting emulator.");
|
||||
|
||||
let mut running = Running::Paused;
|
||||
let mut addr = 0u32;
|
||||
let mut addr;
|
||||
let mut history = Vec::<(u32, Instruction)>::new();
|
||||
let size = 256;
|
||||
|
||||
let memory_view = processor.memory.read_range(addr, size);
|
||||
let initial_state = state(&mut processor, running, 0, memory_view, &mut history);
|
||||
let _ = state_tx.send(initial_state);
|
||||
state_tx
|
||||
.send(StateUpdate::Running(Running::Paused))
|
||||
.expect("Failed to send initial state!");
|
||||
|
||||
let mut instruction_count = 0;
|
||||
let mut update = false;
|
||||
|
||||
loop {
|
||||
let cmd = if running == Running::Running {
|
||||
match cmd_rx.try_recv() {
|
||||
Ok(cmd) => Some(cmd),
|
||||
Err(mpsc::TryRecvError::Empty) => None,
|
||||
Err(mpsc::TryRecvError::Empty) => {
|
||||
update = false;
|
||||
None
|
||||
}
|
||||
Err(mpsc::TryRecvError::Disconnected) => break,
|
||||
}
|
||||
} else {
|
||||
@@ -92,6 +97,8 @@ pub fn run_emulator(
|
||||
processor.reset();
|
||||
}
|
||||
Command::Step => {
|
||||
update = true;
|
||||
|
||||
running = Running::Paused;
|
||||
|
||||
// Execute one cycle.
|
||||
@@ -110,33 +117,91 @@ pub fn run_emulator(
|
||||
|
||||
instruction_count += 1;
|
||||
}
|
||||
Command::Read(new, _size) => {
|
||||
addr = new;
|
||||
}
|
||||
Command::Write(offset, data) => {
|
||||
processor.memory.write_range(offset, data);
|
||||
update = true;
|
||||
|
||||
processor
|
||||
.memory
|
||||
.write_range(offset, data)
|
||||
.unwrap_or_else(|_| {
|
||||
report_err(
|
||||
state_tx,
|
||||
"Failed to write memory range!",
|
||||
&mut processor,
|
||||
);
|
||||
});
|
||||
}
|
||||
Command::Interrupt(_interrupt) => {
|
||||
update = true;
|
||||
|
||||
todo!("implement interrupts")
|
||||
}
|
||||
Command::MemRequest(new, size) if update => {
|
||||
addr = new;
|
||||
let _ = state_tx.send(StateUpdate::MemoryView(
|
||||
processor.memory.read_range(addr, size).unwrap_or_else(|_| {
|
||||
report_err(
|
||||
state_tx,
|
||||
"Failed to read memory range!",
|
||||
&mut processor,
|
||||
);
|
||||
Vec::new()
|
||||
}),
|
||||
));
|
||||
}
|
||||
Command::DisplayRequest if update => {
|
||||
let _ = state_tx.send(StateUpdate::DisplayView(
|
||||
processor.display().unwrap_or_else(|_| {
|
||||
report_err(
|
||||
state_tx,
|
||||
"Failed to read display!",
|
||||
&mut processor,
|
||||
);
|
||||
Vec::new()
|
||||
}),
|
||||
));
|
||||
}
|
||||
Command::StackRequest if update => {
|
||||
let _ = state_tx.send(StateUpdate::StackView(
|
||||
processor.get_stack(32).unwrap_or_else(|_| {
|
||||
report_err(state_tx, "Failed to read stack!", &mut processor);
|
||||
Vec::new()
|
||||
}),
|
||||
));
|
||||
}
|
||||
Command::RegisterRequest if update => {
|
||||
let _ = state_tx.send(StateUpdate::Registers(processor.registers));
|
||||
}
|
||||
Command::RunningRequest if update => {
|
||||
let _ = state_tx.send(StateUpdate::Running(running));
|
||||
}
|
||||
Command::HistoryRequest if update => {
|
||||
let hsc = history.clone();
|
||||
history.clear();
|
||||
let _ = state_tx.send(StateUpdate::InstructionHistory(hsc));
|
||||
}
|
||||
Command::InstructionCountRequest if update => {
|
||||
let _ = state_tx.send(StateUpdate::Instructions(instruction_count));
|
||||
}
|
||||
Command::WriteBlock(addr, block) => {
|
||||
processor
|
||||
.memory
|
||||
.write_range(addr, block.to_vec())
|
||||
.unwrap_or_else(|_| {
|
||||
report_err(
|
||||
state_tx,
|
||||
"Failed to write memory block!",
|
||||
&mut processor,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let memory_view = processor.memory.read_range(addr, size);
|
||||
let state = state(
|
||||
&mut processor,
|
||||
running,
|
||||
instruction_count,
|
||||
memory_view,
|
||||
&mut history,
|
||||
);
|
||||
|
||||
println!("state");
|
||||
|
||||
let _ = state_tx.send(state);
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if running == Running::Running {
|
||||
let mut update = false;
|
||||
update = true;
|
||||
|
||||
// Execute one cycle.
|
||||
let instruction = match processor.cycle() {
|
||||
@@ -149,60 +214,16 @@ pub fn run_emulator(
|
||||
};
|
||||
|
||||
history.push(instruction);
|
||||
|
||||
// let instruction = match Instruction::decode(cpu_lock.get(Register::Cir))
|
||||
// {};
|
||||
|
||||
if matches!(instruction.1, Instruction::Halt) {
|
||||
running = Running::Halted;
|
||||
update = true;
|
||||
}
|
||||
|
||||
instruction_count += 1;
|
||||
|
||||
// Send state updates every 100 instructions
|
||||
if instruction_count % 100 == 0 {
|
||||
update = true;
|
||||
}
|
||||
|
||||
if update {
|
||||
let memory_view = processor.memory.read_range(addr, size);
|
||||
let state = state(
|
||||
&mut processor,
|
||||
running,
|
||||
instruction_count,
|
||||
memory_view,
|
||||
&mut history,
|
||||
);
|
||||
println!("running state");
|
||||
// println!("state!!! {:?}", state.history);
|
||||
let _ = state_tx.send(state);
|
||||
}
|
||||
} else {
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn state(
|
||||
cpu_lock: &mut Processor,
|
||||
running: Running,
|
||||
instruction_count: usize,
|
||||
memory_view: Vec<u8>,
|
||||
history: &mut Vec<(u32, Instruction)>,
|
||||
) -> State {
|
||||
let hsclone = history.clone();
|
||||
history.clear();
|
||||
|
||||
State {
|
||||
// TODO: Replace with actual register access from your CPU.
|
||||
reg_file: cpu_lock.registers,
|
||||
running,
|
||||
instructions: instruction_count,
|
||||
stack_view: cpu_lock.get_stack(32),
|
||||
memory_view,
|
||||
display_view: cpu_lock.display(),
|
||||
error: None,
|
||||
persistent: PersistentState { history: hsclone },
|
||||
}
|
||||
fn report_err(state_tx: &Sender<StateUpdate>, why: &str, processor: &mut Processor) {
|
||||
processor.begin_interrupt(Interrupt::HardFault);
|
||||
let _ = state_tx.send(StateUpdate::Error(why.to_string()));
|
||||
}
|
||||
|
||||
@@ -1,13 +1,43 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::emulator::system::model::ProcessorError;
|
||||
|
||||
pub trait MemoryUnit: Send + Sync {
|
||||
fn reset(&mut self);
|
||||
fn read_byte(&mut self, addr: u32) -> u8;
|
||||
fn write_byte(&mut self, addr: u32, value: u8);
|
||||
fn read_word(&mut self, addr: u32) -> u32;
|
||||
fn write_word(&mut self, addr: u32, value: u32);
|
||||
fn read_range(&mut self, addr: u32, size: u32) -> Vec<u8>;
|
||||
fn write_range(&mut self, addr: u32, value: Vec<u8>);
|
||||
fn read_byte(&mut self, addr: u32) -> Result<u8, ProcessorError>;
|
||||
fn write_byte(&mut self, addr: u32, value: u8) -> Result<(), ProcessorError>;
|
||||
fn read_word(&mut self, addr: u32) -> Result<u32, ProcessorError>;
|
||||
fn write_word(&mut self, addr: u32, value: u32) -> Result<(), ProcessorError>;
|
||||
|
||||
fn read_range(&mut self, addr: u32, size: u32) -> Result<Vec<u8>, ProcessorError> {
|
||||
let mut data = Vec::with_capacity(size as usize);
|
||||
for i in 0..size {
|
||||
data.push(self.read_byte(addr + i)?);
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn write_range(&mut self, addr: u32, value: Vec<u8>) -> Result<(), ProcessorError> {
|
||||
for (i, byte) in value.into_iter().enumerate() {
|
||||
self.write_byte(addr + i as u32, byte)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_block(&mut self, addr: u32) -> Result<[u8; 256], ProcessorError> {
|
||||
let mut data = [0; 256];
|
||||
for (i, byte) in data.iter_mut().enumerate() {
|
||||
*byte = self.read_byte(addr + i as u32)?;
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn write_block(&mut self, addr: u32, data: [u8; 256]) -> Result<(), ProcessorError> {
|
||||
for (i, byte) in data.iter().enumerate() {
|
||||
self.write_byte(addr + i as u32, *byte)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MainStore {
|
||||
@@ -64,59 +94,77 @@ impl MemoryUnit for MainStore {
|
||||
self.data.clear();
|
||||
}
|
||||
|
||||
fn read_byte(&mut self, addr: u32) -> u8 {
|
||||
fn read_byte(&mut self, addr: u32) -> Result<u8, ProcessorError> {
|
||||
let (block_addr, offset) = Self::segment_addr(addr);
|
||||
let block = self.block(block_addr);
|
||||
block.data[offset as usize]
|
||||
Ok(block.data[offset as usize])
|
||||
}
|
||||
|
||||
fn read_word(&mut self, addr: u32) -> Result<u32, ProcessorError> {
|
||||
if addr % 4 != 0 {
|
||||
return Err(ProcessorError::BadMemoryAccess(addr));
|
||||
}
|
||||
|
||||
fn read_word(&mut self, addr: u32) -> u32 {
|
||||
let (block_addr, offset) = Self::segment_addr(addr);
|
||||
|
||||
println!("reading word from {block_addr:x?} + {offset}");
|
||||
|
||||
let block = self.mut_block(block_addr);
|
||||
let mut bytes = [0; 4];
|
||||
bytes[0] = block.data[offset as usize];
|
||||
bytes[1] = block.data[(offset + 1) as usize];
|
||||
bytes[2] = block.data[(offset + 2) as usize];
|
||||
bytes[3] = block.data[(offset + 3) as usize];
|
||||
u32::from_be_bytes(bytes)
|
||||
Ok(u32::from_be_bytes(bytes))
|
||||
}
|
||||
|
||||
fn read_range(&mut self, addr: u32, size: u32) -> Vec<u8> {
|
||||
fn read_range(&mut self, addr: u32, size: u32) -> Result<Vec<u8>, ProcessorError> {
|
||||
let mut data = Vec::with_capacity(size as usize);
|
||||
for i in 0..size {
|
||||
data.push(self.read_byte(addr + i));
|
||||
data.push(self.read_byte(addr + i)?);
|
||||
}
|
||||
|
||||
// println!("reading {data:?} from {addr:x?}");
|
||||
|
||||
data
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn write_byte(&mut self, addr: u32, value: u8) {
|
||||
fn write_byte(&mut self, addr: u32, value: u8) -> Result<(), ProcessorError> {
|
||||
let (block_addr, offset) = Self::segment_addr(addr);
|
||||
let block = self.mut_block(block_addr);
|
||||
block.data[offset as usize] = value;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_word(&mut self, addr: u32, value: u32) -> Result<(), ProcessorError> {
|
||||
if addr % 4 != 0 {
|
||||
return Err(ProcessorError::BadMemoryAccess(addr));
|
||||
}
|
||||
|
||||
fn write_word(&mut self, addr: u32, value: u32) {
|
||||
let (block_addr, offset) = Self::segment_addr(addr);
|
||||
let block = self.mut_block(block_addr);
|
||||
block.data[offset as usize] = (value >> 24) as u8;
|
||||
block.data[(offset + 1) as usize] = (value >> 16) as u8;
|
||||
block.data[(offset + 2) as usize] = (value >> 8) as u8;
|
||||
block.data[(offset + 3) as usize] = value as u8;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_range(&mut self, addr: u32, value: Vec<u8>) {
|
||||
// println!("writing {value:?} to {addr:x?}");
|
||||
|
||||
fn write_range(&mut self, addr: u32, value: Vec<u8>) -> Result<(), ProcessorError> {
|
||||
for (i, byte) in value.into_iter().enumerate() {
|
||||
let (block_addr, offset) = Self::segment_addr(addr + i as u32);
|
||||
let block = self.mut_block(block_addr);
|
||||
block.data[offset as usize] = byte;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_block(&mut self, addr: u32) -> Result<[u8; 256], ProcessorError> {
|
||||
let (block_addr, _) = Self::segment_addr(addr);
|
||||
let block = self.block(block_addr);
|
||||
Ok(block.data)
|
||||
}
|
||||
|
||||
fn write_block(&mut self, addr: u32, data: [u8; 256]) -> Result<(), ProcessorError> {
|
||||
let (block_addr, _) = Self::segment_addr(addr);
|
||||
let block = self.mut_block(block_addr);
|
||||
block.data = data;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
|
||||
use common::prelude::*;
|
||||
|
||||
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
|
||||
@@ -16,15 +18,143 @@ pub trait IODevice: Send + Sync {
|
||||
|
||||
#[derive(PartialEq, Eq, Debug, Clone)]
|
||||
pub enum Command {
|
||||
// set emulator state.
|
||||
Start,
|
||||
Stop,
|
||||
Step,
|
||||
Reset(usize),
|
||||
Interrupt(Interrupt),
|
||||
|
||||
// Performs direct read/write operations on the emulator's memory.
|
||||
Read(Address, u32),
|
||||
Write(Address, Vec<u8>),
|
||||
WriteBlock(Address, Box<[u8; 256]>),
|
||||
|
||||
// request emulator state.
|
||||
MemRequest(Address, u32),
|
||||
DisplayRequest,
|
||||
StackRequest,
|
||||
RegisterRequest,
|
||||
RunningRequest,
|
||||
HistoryRequest,
|
||||
InstructionCountRequest,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ProcessorError {
|
||||
InvalidInstruction(u32),
|
||||
InvalidRegister(u8),
|
||||
BadMemoryAccess(u32),
|
||||
}
|
||||
|
||||
impl std::error::Error for ProcessorError {}
|
||||
|
||||
impl std::fmt::Display for ProcessorError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::InvalidInstruction(instruction) => {
|
||||
write!(f, "Invalid instruction: {instruction}")
|
||||
}
|
||||
Self::InvalidRegister(register) => {
|
||||
write!(f, "Invalid register: {register}")
|
||||
}
|
||||
Self::BadMemoryAccess(address) => {
|
||||
write!(f, "Bad memory access: {address}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub state_receiver: Receiver<StateUpdate>,
|
||||
pub cmd_sender: Sender<Command>,
|
||||
|
||||
// Processor state
|
||||
pub reg_file: RegFile,
|
||||
pub running: Running,
|
||||
pub instructions: usize,
|
||||
|
||||
// Memory access views
|
||||
pub stack_view: Vec<u8>,
|
||||
pub memory_view: Vec<u8>,
|
||||
pub display_view: Vec<u8>,
|
||||
|
||||
pub error_log: Vec<String>,
|
||||
|
||||
pub instruction_history: Vec<(u32, Instruction)>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
#[must_use]
|
||||
pub fn new(sender: Sender<Command>, receiver: Receiver<StateUpdate>) -> Self {
|
||||
Self {
|
||||
state_receiver: receiver,
|
||||
cmd_sender: sender,
|
||||
reg_file: RegFile::default(),
|
||||
running: Running::Paused,
|
||||
instructions: 0,
|
||||
stack_view: vec![],
|
||||
memory_view: vec![],
|
||||
display_view: vec![],
|
||||
error_log: vec![],
|
||||
instruction_history: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send(&mut self, cmd: Command) {
|
||||
if let Err(e) = self.cmd_sender.send(cmd) {
|
||||
self.error_log.push(e.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self) -> Result<(), mpsc::TryRecvError> {
|
||||
while let Ok(update) = self.state_receiver.try_recv() {
|
||||
match update {
|
||||
StateUpdate::Registers(reg_file) => self.reg_file = reg_file,
|
||||
StateUpdate::Running(running) => self.running = running,
|
||||
StateUpdate::Instructions(instructions) => {
|
||||
self.instructions = instructions;
|
||||
}
|
||||
StateUpdate::StackView(stack_view) => self.stack_view = stack_view,
|
||||
StateUpdate::MemoryView(memory_view) => self.memory_view = memory_view,
|
||||
StateUpdate::DisplayView(display_view) => {
|
||||
self.display_view = display_view;
|
||||
}
|
||||
StateUpdate::Error(err_state) => self.error_log.push(err_state),
|
||||
StateUpdate::InstructionHistory(history) => {
|
||||
self.instruction_history.extend(history);
|
||||
}
|
||||
}
|
||||
|
||||
if self.error_log.len() > 256 {
|
||||
self.error_log.drain(0..self.error_log.len() - 256);
|
||||
}
|
||||
|
||||
if self.instruction_history.len() > 1024 {
|
||||
self.instruction_history
|
||||
.drain(0..self.instruction_history.len() - 1024);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = self.state_receiver.try_recv() {
|
||||
match e {
|
||||
mpsc::TryRecvError::Empty => {}
|
||||
mpsc::TryRecvError::Disconnected => {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub enum StateUpdate {
|
||||
Registers(RegFile),
|
||||
Running(Running),
|
||||
Instructions(usize),
|
||||
StackView(Vec<u8>),
|
||||
MemoryView(Vec<u8>),
|
||||
DisplayView(Vec<u8>),
|
||||
Error(String),
|
||||
InstructionHistory(Vec<(u32, Instruction)>),
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -195,47 +325,3 @@ impl RegFile {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub reg_file: RegFile,
|
||||
pub running: Running,
|
||||
pub instructions: usize,
|
||||
|
||||
// Memory access views
|
||||
pub stack_view: Vec<u8>,
|
||||
pub memory_view: Vec<u8>,
|
||||
pub display_view: Vec<u8>,
|
||||
pub error: Option<String>,
|
||||
|
||||
pub persistent: PersistentState,
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
reg_file: RegFile::default(),
|
||||
running: Running::Paused,
|
||||
instructions: 0,
|
||||
stack_view: vec![],
|
||||
memory_view: vec![],
|
||||
display_view: vec![],
|
||||
persistent: PersistentState::default(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PersistentState {
|
||||
pub history: Vec<(u32, Instruction)>,
|
||||
}
|
||||
|
||||
impl PersistentState {
|
||||
pub fn update(&mut self, new_state: &Self) {
|
||||
self.history.extend(new_state.history.clone());
|
||||
if self.history.len() > 1024 {
|
||||
let len = self.history.len() - 1024;
|
||||
self.history.drain(..len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,10 @@ use std::{
|
||||
|
||||
use crate::emulator::system::{
|
||||
memory::MemoryUnit,
|
||||
model::{IODevice, RegFile},
|
||||
model::{IODevice, ProcessorError, RegFile},
|
||||
};
|
||||
|
||||
use common::instructions::{
|
||||
Instruction, Interrupt, Register, errors::InstructionDecodeError,
|
||||
};
|
||||
use common::instructions::{Instruction, Interrupt, Register};
|
||||
|
||||
pub struct Processor {
|
||||
pub memory: Box<dyn MemoryUnit>,
|
||||
@@ -25,7 +23,6 @@ fn log(message: &str) {
|
||||
println!("\x1b[32mINFO:\x1b[0m {message}");
|
||||
}
|
||||
|
||||
#[allow(clippy::needless_pass_by_ref_mut)]
|
||||
impl Processor {
|
||||
#[must_use]
|
||||
pub fn new(memory: Box<dyn MemoryUnit>, io_devices: Vec<Arc<dyn IODevice>>) -> Self {
|
||||
@@ -48,7 +45,7 @@ impl Processor {
|
||||
self.memory.reset();
|
||||
}
|
||||
|
||||
pub fn cycle(&mut self) -> Result<(u32, Instruction), InstructionDecodeError> {
|
||||
pub fn cycle(&mut self) -> Result<(u32, Instruction), ProcessorError> {
|
||||
self.halted = false;
|
||||
|
||||
// Get value from PCX.
|
||||
@@ -58,17 +55,18 @@ impl Processor {
|
||||
|
||||
// Set MAR to the previous value of PCX.
|
||||
*self.reg(Register::Mar) = addr;
|
||||
let val = self.memory.read_word(addr);
|
||||
let val = self.memory.read_word(addr)?;
|
||||
|
||||
// Set CIR to the value of RAM[MAR].
|
||||
*self.reg(Register::Mar) = val;
|
||||
|
||||
// Decode and execute the instruction.
|
||||
let instruction = Instruction::decode(val)?;
|
||||
let instruction = Instruction::decode(val)
|
||||
.map_err(|_| ProcessorError::InvalidInstruction(val))?;
|
||||
|
||||
log(&instruction.to_string());
|
||||
|
||||
instruction.execute(self);
|
||||
instruction.execute(self)?;
|
||||
|
||||
Ok((addr, instruction))
|
||||
}
|
||||
@@ -89,7 +87,7 @@ impl Processor {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn display(&mut self) -> Vec<u8> {
|
||||
pub fn display(&mut self) -> Result<Vec<u8>, ProcessorError> {
|
||||
self.memory.read_range(0x20000, 2000)
|
||||
}
|
||||
|
||||
@@ -99,21 +97,7 @@ impl Processor {
|
||||
self.set_flag(Flag::LessThan, a < b);
|
||||
}
|
||||
|
||||
// stack operations
|
||||
|
||||
pub fn push(&mut self, value: u32) {
|
||||
let stack_ptr = self.get(Register::Spr);
|
||||
*self.reg(Register::Spr) += 4;
|
||||
self.memory.write_word(stack_ptr, value);
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> u32 {
|
||||
*self.reg(Register::Spr) -= 4;
|
||||
self.memory.read_word(self.get(Register::Spr))
|
||||
}
|
||||
|
||||
// functions to set new state
|
||||
|
||||
fn set_flag(&mut self, flag: Flag, value: bool) {
|
||||
if value {
|
||||
*self.reg(Register::Sts) |= flag as u32;
|
||||
@@ -135,16 +119,18 @@ impl Processor {
|
||||
*self.reg(Register::Pcx) = self.get(reg) + u32::from(offset);
|
||||
}
|
||||
|
||||
fn begin_interrupt(&mut self, _int: Interrupt) {
|
||||
pub fn begin_interrupt(&mut self, _int: Interrupt) {
|
||||
// first we get the address of the interrupt descriptor table.
|
||||
todo!();
|
||||
}
|
||||
|
||||
// TODO: remove this once implemented
|
||||
#[allow(clippy::needless_pass_by_ref_mut)]
|
||||
fn end_interrupt(&mut self) {
|
||||
todo!();
|
||||
}
|
||||
|
||||
pub fn get_stack(&mut self, n: u32) -> Vec<u8> {
|
||||
pub fn get_stack(&mut self, n: u32) -> Result<Vec<u8>, ProcessorError> {
|
||||
let addr = self.get(Register::Spr);
|
||||
let size = n * 4;
|
||||
// returns the stack
|
||||
@@ -170,12 +156,12 @@ enum Flag {
|
||||
}
|
||||
|
||||
trait Executable {
|
||||
fn execute(self, cpu: &mut Processor);
|
||||
fn execute(self, cpu: &mut Processor) -> Result<(), ProcessorError>;
|
||||
}
|
||||
|
||||
impl Executable for Instruction {
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn execute(self, cpu: &mut Processor) {
|
||||
fn execute(self, cpu: &mut Processor) -> Result<(), ProcessorError> {
|
||||
match self {
|
||||
// No operation - a blank line.
|
||||
// Copies from SrcReg to a.drReg.
|
||||
@@ -193,7 +179,8 @@ impl Executable for Instruction {
|
||||
// effective address must be byte-aligned.
|
||||
Self::LoadByte(a) => {
|
||||
*cpu.reg(a.r2) = u32::from(
|
||||
cpu.memory.read_byte(cpu.get(a.r1) + u32::from(a.immediate)),
|
||||
cpu.memory
|
||||
.read_byte(cpu.get(a.r1) + u32::from(a.immediate))?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -201,7 +188,8 @@ impl Executable for Instruction {
|
||||
// a.drReg. The effective address must be byte-aligned.
|
||||
Self::LoadByteSigned(a) => {
|
||||
*cpu.reg(a.r2) = sign_extend(u32::from(
|
||||
cpu.memory.read_byte(cpu.get(a.r1) + u32::from(a.immediate)),
|
||||
cpu.memory
|
||||
.read_byte(cpu.get(a.r1) + u32::from(a.immediate))?,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -210,23 +198,28 @@ impl Executable for Instruction {
|
||||
Self::LoadHalfword(a) => {
|
||||
// we read an entire word, then right shift so we only get the first half
|
||||
// of the word
|
||||
*cpu.reg(a.r2) =
|
||||
cpu.memory.read_word(cpu.get(a.r1) + u32::from(a.immediate)) >> 16;
|
||||
*cpu.reg(a.r2) = cpu
|
||||
.memory
|
||||
.read_word(cpu.get(a.r1) + u32::from(a.immediate))?
|
||||
>> 16;
|
||||
}
|
||||
|
||||
// Loads a sign-extended half-word from memory address (base + offset) into
|
||||
// a.drReg. The effective address must be 2-byte-aligned.
|
||||
Self::LoadHalfwordSigned(a) => {
|
||||
*cpu.reg(a.r2) = sign_extend(
|
||||
cpu.memory.read_word(cpu.get(a.r1) + u32::from(a.immediate)) >> 16,
|
||||
cpu.memory
|
||||
.read_word(cpu.get(a.r1) + u32::from(a.immediate))?
|
||||
>> 16,
|
||||
);
|
||||
}
|
||||
|
||||
// Loads a word from memory address (base + offset) into a.drReg. The
|
||||
// effective address must be 4-byte-aligned.
|
||||
Self::LoadWord(a) => {
|
||||
*cpu.reg(a.r2) =
|
||||
cpu.memory.read_word(cpu.get(a.r1) + u32::from(a.immediate));
|
||||
*cpu.reg(a.r2) = cpu
|
||||
.memory
|
||||
.read_word(cpu.get(a.r1) + u32::from(a.immediate))?;
|
||||
}
|
||||
|
||||
// Stores a byte from SrcReg in memory address (base + offset) The effective
|
||||
@@ -235,7 +228,7 @@ impl Executable for Instruction {
|
||||
cpu.memory.write_byte(
|
||||
cpu.get(a.r2) + u32::from(a.immediate),
|
||||
cpu.get(a.r1) as u8,
|
||||
);
|
||||
)?;
|
||||
}
|
||||
|
||||
// Stores a half-word from SrcReg in memory address (base + offset) The
|
||||
@@ -244,16 +237,16 @@ impl Executable for Instruction {
|
||||
// split the value into bytes and then write two bytes
|
||||
let bytes = (cpu.get(a.r1) as u16).to_le_bytes();
|
||||
cpu.memory
|
||||
.write_byte(cpu.get(a.r2) + u32::from(a.immediate), bytes[0]);
|
||||
.write_byte(cpu.get(a.r2) + u32::from(a.immediate), bytes[0])?;
|
||||
cpu.memory
|
||||
.write_byte(cpu.get(a.r2) + u32::from(a.immediate) + 1, bytes[1]);
|
||||
.write_byte(cpu.get(a.r2) + u32::from(a.immediate) + 1, bytes[1])?;
|
||||
}
|
||||
|
||||
// Stores a word from SrcReg in memory address (base + offset) The effective
|
||||
// address must be 4-byte-aligned.
|
||||
Self::StoreWord(a) => {
|
||||
cpu.memory
|
||||
.write_word(cpu.get(a.r2) + u32::from(a.immediate), cpu.get(a.r1));
|
||||
.write_word(cpu.get(a.r2) + u32::from(a.immediate), cpu.get(a.r1))?;
|
||||
}
|
||||
|
||||
// Loads a 16-bit literal value into reg, setting the bottom 16 bits of the
|
||||
@@ -411,6 +404,7 @@ impl Executable for Instruction {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,9 @@ fn test_nop_instruction() {
|
||||
let mut cpu = create_test_processor();
|
||||
let initial_state = cpu.registers;
|
||||
|
||||
Instruction::Nop.execute(&mut cpu);
|
||||
Instruction::Nop.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
cpu.registers.get(Register::Rg0),
|
||||
@@ -37,7 +39,9 @@ fn test_mov_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
mov_instr.execute(&mut cpu);
|
||||
mov_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0x1234_5678);
|
||||
}
|
||||
|
||||
@@ -53,7 +57,9 @@ fn test_mov_signed_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
mov_signed_instr.execute(&mut cpu);
|
||||
mov_signed_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0xFFFF_FFFF);
|
||||
}
|
||||
|
||||
@@ -61,7 +67,9 @@ fn test_mov_signed_instruction() {
|
||||
fn test_load_byte_instruction() {
|
||||
let mut cpu = create_test_processor();
|
||||
let addr = 0x100;
|
||||
cpu.memory.write_byte(addr, 0xAB);
|
||||
cpu.memory
|
||||
.write_byte(addr, 0xAB)
|
||||
.expect("Failed to write byte to memory");
|
||||
*cpu.reg(Register::Rg1) = addr - 4;
|
||||
|
||||
let load_byte_instr = Instruction::LoadByte(ITypeArgs::new(
|
||||
@@ -70,7 +78,9 @@ fn test_load_byte_instruction() {
|
||||
Some(Register::Rg2),
|
||||
));
|
||||
|
||||
load_byte_instr.execute(&mut cpu);
|
||||
load_byte_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0x0000_00AB);
|
||||
}
|
||||
|
||||
@@ -78,7 +88,9 @@ fn test_load_byte_instruction() {
|
||||
fn test_load_byte_signed_instruction() {
|
||||
let mut cpu = create_test_processor();
|
||||
let addr = 0x100;
|
||||
cpu.memory.write_byte(addr, 0xFF);
|
||||
cpu.memory
|
||||
.write_byte(addr, 0xFF)
|
||||
.expect("Failed to write byte to memory");
|
||||
*cpu.reg(Register::Rg1) = addr;
|
||||
|
||||
let load_byte_signed_instr = Instruction::LoadByteSigned(ITypeArgs::new(
|
||||
@@ -87,7 +99,9 @@ fn test_load_byte_signed_instruction() {
|
||||
Some(Register::Rg2),
|
||||
));
|
||||
|
||||
load_byte_signed_instr.execute(&mut cpu);
|
||||
load_byte_signed_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0xFFFF_FFFF);
|
||||
}
|
||||
|
||||
@@ -95,7 +109,9 @@ fn test_load_byte_signed_instruction() {
|
||||
fn test_load_halfword_instruction() {
|
||||
let mut cpu = create_test_processor();
|
||||
let addr = 0x100;
|
||||
cpu.memory.write_word(addr, 0x1234_5678);
|
||||
cpu.memory
|
||||
.write_word(addr, 0x1234_5678)
|
||||
.expect("Failed to write word to memory");
|
||||
*cpu.reg(Register::Rg1) = addr;
|
||||
|
||||
let load_halfword_instr = Instruction::LoadHalfword(ITypeArgs::new(
|
||||
@@ -104,7 +120,9 @@ fn test_load_halfword_instruction() {
|
||||
Some(Register::Rg2),
|
||||
));
|
||||
|
||||
load_halfword_instr.execute(&mut cpu);
|
||||
load_halfword_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0x0000_1234);
|
||||
}
|
||||
|
||||
@@ -112,7 +130,9 @@ fn test_load_halfword_instruction() {
|
||||
fn test_load_word_instruction() {
|
||||
let mut cpu = create_test_processor();
|
||||
let addr = 0x100;
|
||||
cpu.memory.write_word(addr, 0x1234_5678);
|
||||
cpu.memory
|
||||
.write_word(addr, 0x1234_5678)
|
||||
.expect("Failed to write word to memory");
|
||||
*cpu.reg(Register::Rg1) = addr;
|
||||
|
||||
let load_word_instr = Instruction::LoadWord(ITypeArgs::new(
|
||||
@@ -121,7 +141,9 @@ fn test_load_word_instruction() {
|
||||
Some(Register::Rg2),
|
||||
));
|
||||
|
||||
load_word_instr.execute(&mut cpu);
|
||||
load_word_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0x1234_5678);
|
||||
}
|
||||
|
||||
@@ -138,8 +160,10 @@ fn test_store_byte_instruction() {
|
||||
Some(Register::Rg1),
|
||||
));
|
||||
|
||||
store_byte_instr.execute(&mut cpu);
|
||||
assert_eq!(cpu.memory.read_byte(addr), 0xAB);
|
||||
store_byte_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.memory.read_byte(addr).expect("Emulator was slain by losing the game while attempting to execute instruction"), 0xAB);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -155,8 +179,10 @@ fn test_store_word_instruction() {
|
||||
Some(Register::Rg1),
|
||||
));
|
||||
|
||||
store_word_instr.execute(&mut cpu);
|
||||
assert_eq!(cpu.memory.read_word(addr), 0x1234_5678);
|
||||
store_word_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.memory.read_word(addr).expect("Emulator was slain by losing the game while attempting to execute instruction"), 0x1234_5678);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -172,7 +198,9 @@ fn test_add_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
add_instr.execute(&mut cpu);
|
||||
add_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), 40);
|
||||
}
|
||||
|
||||
@@ -189,7 +217,9 @@ fn test_sub_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
sub_instr.execute(&mut cpu);
|
||||
sub_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), 30);
|
||||
}
|
||||
|
||||
@@ -206,7 +236,9 @@ fn test_and_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
and_instr.execute(&mut cpu);
|
||||
and_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), 0b1000);
|
||||
}
|
||||
|
||||
@@ -223,7 +255,9 @@ fn test_or_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
or_instr.execute(&mut cpu);
|
||||
or_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), 0b1110);
|
||||
}
|
||||
|
||||
@@ -240,7 +274,9 @@ fn test_xor_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
xor_instr.execute(&mut cpu);
|
||||
xor_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), 0b0110);
|
||||
}
|
||||
|
||||
@@ -256,7 +292,9 @@ fn test_not_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
not_instr.execute(&mut cpu);
|
||||
not_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg2), 0xF0F0_F0F0);
|
||||
}
|
||||
|
||||
@@ -273,7 +311,9 @@ fn test_compare_equal() {
|
||||
None,
|
||||
));
|
||||
|
||||
cmp_instr.execute(&mut cpu);
|
||||
cmp_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
|
||||
assert!(cpu.get_flag(Flag::Equal));
|
||||
assert!(!cpu.get_flag(Flag::GreaterThan));
|
||||
@@ -293,7 +333,9 @@ fn test_compare_greater_than() {
|
||||
None,
|
||||
));
|
||||
|
||||
cmp_instr.execute(&mut cpu);
|
||||
cmp_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
|
||||
assert!(!cpu.get_flag(Flag::Equal));
|
||||
assert!(cpu.get_flag(Flag::GreaterThan));
|
||||
@@ -313,7 +355,9 @@ fn test_compare_less_than() {
|
||||
None,
|
||||
));
|
||||
|
||||
cmp_instr.execute(&mut cpu);
|
||||
cmp_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
|
||||
assert!(!cpu.get_flag(Flag::Equal));
|
||||
assert!(!cpu.get_flag(Flag::GreaterThan));
|
||||
@@ -328,7 +372,9 @@ fn test_increment_instruction() {
|
||||
let inc_instr =
|
||||
Instruction::Increment(RTypeArgs::new(Some(Register::Rg1), None, None, None));
|
||||
|
||||
inc_instr.execute(&mut cpu);
|
||||
inc_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 43);
|
||||
}
|
||||
|
||||
@@ -340,7 +386,9 @@ fn test_decrement_instruction() {
|
||||
let dec_instr =
|
||||
Instruction::Decrement(RTypeArgs::new(Some(Register::Rg1), None, None, None));
|
||||
|
||||
dec_instr.execute(&mut cpu);
|
||||
dec_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 41);
|
||||
}
|
||||
|
||||
@@ -356,7 +404,9 @@ fn test_shift_left_with_shamt() {
|
||||
Some(2),
|
||||
));
|
||||
|
||||
shl_instr.execute(&mut cpu);
|
||||
shl_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 0b10_1000);
|
||||
}
|
||||
|
||||
@@ -372,7 +422,9 @@ fn test_shift_right_with_shamt() {
|
||||
Some(2),
|
||||
));
|
||||
|
||||
shr_instr.execute(&mut cpu);
|
||||
shr_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 0b1010);
|
||||
}
|
||||
|
||||
@@ -389,7 +441,9 @@ fn test_shift_left_with_register() {
|
||||
None,
|
||||
));
|
||||
|
||||
shl_instr.execute(&mut cpu);
|
||||
shl_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 0b101_0000);
|
||||
}
|
||||
|
||||
@@ -403,7 +457,9 @@ fn test_load_lower_immediate() {
|
||||
None,
|
||||
));
|
||||
|
||||
lli_instr.execute(&mut cpu);
|
||||
lli_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 0x0000_1234);
|
||||
}
|
||||
|
||||
@@ -418,7 +474,9 @@ fn test_load_upper_immediate() {
|
||||
None,
|
||||
));
|
||||
|
||||
lui_instr.execute(&mut cpu);
|
||||
lui_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg1), 0x1234_5678);
|
||||
}
|
||||
|
||||
@@ -430,7 +488,9 @@ fn test_jump_unconditional() {
|
||||
|
||||
let jump_instr = Instruction::Jump(ITypeArgs::new(0x100, Some(Register::Rg1), None));
|
||||
|
||||
jump_instr.execute(&mut cpu);
|
||||
jump_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Pcx), 0x1100);
|
||||
assert_ne!(cpu.get(Register::Pcx), initial_pc);
|
||||
}
|
||||
@@ -444,7 +504,9 @@ fn test_jump_equal_when_flag_set() {
|
||||
let jump_eq_instr =
|
||||
Instruction::JumpEq(ITypeArgs::new(0x100, Some(Register::Rg1), None));
|
||||
|
||||
jump_eq_instr.execute(&mut cpu);
|
||||
jump_eq_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Pcx), 0x1100);
|
||||
}
|
||||
|
||||
@@ -458,7 +520,9 @@ fn test_jump_equal_when_flag_not_set() {
|
||||
let jump_eq_instr =
|
||||
Instruction::JumpEq(ITypeArgs::new(0x100, Some(Register::Rg1), None));
|
||||
|
||||
jump_eq_instr.execute(&mut cpu);
|
||||
jump_eq_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Pcx), initial_pc);
|
||||
}
|
||||
|
||||
@@ -467,7 +531,9 @@ fn test_halt_instruction() {
|
||||
let mut cpu = create_test_processor();
|
||||
assert!(!cpu.halted);
|
||||
|
||||
Instruction::Halt.execute(&mut cpu);
|
||||
Instruction::Halt.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert!(cpu.halted);
|
||||
}
|
||||
|
||||
@@ -484,7 +550,9 @@ fn test_nand_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
nand_instr.execute(&mut cpu);
|
||||
nand_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), !0b1000);
|
||||
}
|
||||
|
||||
@@ -501,7 +569,9 @@ fn test_nor_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
nor_instr.execute(&mut cpu);
|
||||
nor_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), !0b1110);
|
||||
}
|
||||
|
||||
@@ -518,6 +588,8 @@ fn test_xnor_instruction() {
|
||||
None,
|
||||
));
|
||||
|
||||
xnor_instr.execute(&mut cpu);
|
||||
xnor_instr.execute(&mut cpu).expect(
|
||||
"Emulator was slain by losing the game while attempting to execute instruction",
|
||||
);
|
||||
assert_eq!(cpu.get(Register::Rg3), !0b0110);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
use crate::emulator::{
|
||||
system::model::{Command, Running, State},
|
||||
ui::interface::Component,
|
||||
@@ -9,17 +7,19 @@ use common::{instructions::Register, prelude::Instruction};
|
||||
|
||||
pub struct ControlPanel {
|
||||
visible: bool,
|
||||
sender: Sender<Command>,
|
||||
}
|
||||
|
||||
impl ControlPanel {
|
||||
#[must_use]
|
||||
pub const fn new(sender: Sender<Command>) -> Self {
|
||||
Self {
|
||||
visible: false,
|
||||
sender,
|
||||
#[allow(clippy::must_use_candidate)]
|
||||
pub const fn new() -> Self {
|
||||
Self { visible: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ControlPanel {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ControlPanel {
|
||||
@@ -47,46 +47,58 @@ impl Component for ControlPanel {
|
||||
.clicked()
|
||||
{
|
||||
if state.running == Running::Running {
|
||||
self.sender.send(Command::Stop).unwrap_or_else(|_| {
|
||||
state.error = Some("Failed to send command".to_string());
|
||||
state.cmd_sender.send(Command::Stop).unwrap_or_else(|_| {
|
||||
state.error_log.push("Failed to send command".to_string());
|
||||
});
|
||||
} else {
|
||||
self.sender.send(Command::Start).unwrap_or_else(|_| {
|
||||
state.error = Some("Failed to send command".to_string());
|
||||
state.cmd_sender.send(Command::Start).unwrap_or_else(|_| {
|
||||
state.error_log.push("Failed to send command".to_string());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Step
|
||||
if ui.button("Step").clicked() {
|
||||
self.sender.send(Command::Step).unwrap_or_else(|_| {
|
||||
state.error = Some("Failed to send command".to_string());
|
||||
state.cmd_sender.send(Command::Step).unwrap_or_else(|_| {
|
||||
state.error_log.push("Failed to send command".to_string());
|
||||
});
|
||||
}
|
||||
|
||||
// Resets the emulator and all attached devices
|
||||
if ui.button("Reset All").clicked() {
|
||||
self.sender.send(Command::Reset(0)).unwrap_or_else(|_| {
|
||||
state.error = Some("Failed to send command".to_string());
|
||||
state
|
||||
.cmd_sender
|
||||
.send(Command::Reset(0))
|
||||
.unwrap_or_else(|_| {
|
||||
state.error_log.push("Failed to send command".to_string());
|
||||
});
|
||||
}
|
||||
|
||||
// Resets the emulator and all attached devices
|
||||
if ui.button("Clear Registers").clicked() {
|
||||
self.sender.send(Command::Reset(1)).unwrap_or_else(|_| {
|
||||
state.error = Some("Failed to send command".to_string());
|
||||
state
|
||||
.cmd_sender
|
||||
.send(Command::Reset(1))
|
||||
.unwrap_or_else(|_| {
|
||||
state.error_log.push("Failed to send command".to_string());
|
||||
});
|
||||
}
|
||||
|
||||
// Resets the emulator and all attached devices
|
||||
if ui.button("Clear RAM").clicked() {
|
||||
self.sender.send(Command::Reset(2)).unwrap_or_else(|_| {
|
||||
state.error = Some("Failed to send command".to_string());
|
||||
state
|
||||
.cmd_sender
|
||||
.send(Command::Reset(2))
|
||||
.unwrap_or_else(|_| {
|
||||
state.error_log.push("Failed to send command".to_string());
|
||||
});
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
state.send(Command::RegisterRequest);
|
||||
state.send(Command::RunningRequest);
|
||||
|
||||
// Status info
|
||||
ui.label(format!(
|
||||
"Status: {}",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::emulator::{
|
||||
system::model::State,
|
||||
system::model::{Command, State},
|
||||
ui::interface::{Category, Component},
|
||||
};
|
||||
|
||||
@@ -40,6 +40,8 @@ impl Component for Display {
|
||||
}
|
||||
|
||||
fn render(&mut self, state: &mut State, ui: &mut egui::Ui, _ctx: &egui::Context) {
|
||||
state.send(Command::DisplayRequest);
|
||||
|
||||
let display: Vec<u8> = state.display_view.clone();
|
||||
let font_id = FontId::monospace(12.0);
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::{
|
||||
ffi::OsStr,
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::mpsc::Sender,
|
||||
};
|
||||
|
||||
use common::prelude::Instruction;
|
||||
@@ -19,6 +18,7 @@ use crate::emulator::{
|
||||
|
||||
use assembler::prelude::*;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Editor {
|
||||
// editor state
|
||||
path: Option<PathBuf>,
|
||||
@@ -41,7 +41,6 @@ pub struct Editor {
|
||||
|
||||
// other
|
||||
visible: bool,
|
||||
sender: Sender<Command>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -94,14 +93,13 @@ impl Component for Editor {
|
||||
|
||||
impl Editor {
|
||||
#[must_use]
|
||||
pub const fn new(sender: Sender<Command>) -> Self {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
path: None,
|
||||
text: String::new(),
|
||||
buffer: String::new(),
|
||||
output: Vec::new(),
|
||||
unsaved: true,
|
||||
sender,
|
||||
cursor_col: 1,
|
||||
cursor_line: 1,
|
||||
visible: false,
|
||||
@@ -199,38 +197,6 @@ impl Editor {
|
||||
)
|
||||
});
|
||||
|
||||
// if let Some(path) = FileDialog::new()
|
||||
// .add_filter("Assembly Files or Binaries", &["dsa", "dsb"])
|
||||
// .add_filter("all", &["*"])
|
||||
// .set_directory(&work_dir)
|
||||
// .pick_file()
|
||||
// {
|
||||
// match path.extension().and_then(|ext| ext.to_str()) {
|
||||
// Some("dsb") => {
|
||||
// let contents = match std::fs::read(&path) {
|
||||
// Ok(contents) => contents,
|
||||
// Err(why) => {
|
||||
// self.error = Some(format!("Failed to read file: {why}"));
|
||||
// return;
|
||||
// }
|
||||
// };
|
||||
|
||||
// self.path = Some(path.clone());
|
||||
// self.output = contents;
|
||||
// self.unsaved = false;
|
||||
// self.text = String::from("Loaded Binary File!");
|
||||
// self.buffer = self.text.clone();
|
||||
// self.unsaved = false;
|
||||
// }
|
||||
// _ => {
|
||||
// if let Ok(contents) = std::fs::read_to_string(&path) {
|
||||
// self.path = Some(path.clone());
|
||||
// self.text.clone_from(&contents);
|
||||
// self.buffer = contents;
|
||||
// self.unsaved = false;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if self.save_file_dialog.is_some() {
|
||||
// TODO: Flash an error stating you can only have one menu open at once.
|
||||
self.save_file_dialog = None;
|
||||
@@ -338,33 +304,6 @@ impl Editor {
|
||||
}
|
||||
}
|
||||
|
||||
// fn open(&mut self) {
|
||||
// let work_dir = std::env::current_dir().unwrap_or_else(|_| {
|
||||
// dirs::home_dir().expect(
|
||||
// "Couldn't get your current working directory or your home directory.",
|
||||
// )
|
||||
// });
|
||||
|
||||
// if let Some(path) = FileDialog::new()
|
||||
// .add_filter("Assembly Files or Binaries", &["dsa", "dsb"])
|
||||
// .add_filter("all", &["*"])
|
||||
// .set_directory(&work_dir)
|
||||
// .pick_file()
|
||||
// {
|
||||
// if let Ok(contents) = std::fs::read_to_string(&path) {
|
||||
// self.path = Some(path.clone());
|
||||
// self.text.clone_from(&contents);
|
||||
// self.buffer = contents;
|
||||
// self.unsaved = false;
|
||||
// }
|
||||
|
||||
// std::env::set_current_dir(
|
||||
// path.parent().expect("A file should be in a directory!"),
|
||||
// )
|
||||
// .expect("ERROR: Failed to set current working directory.");
|
||||
// }
|
||||
// }
|
||||
|
||||
fn render_output(&self, _state: &mut State, ui: &mut Ui, _ctx: &Context) {
|
||||
// Output area with synchronized scrolling
|
||||
egui::ScrollArea::vertical()
|
||||
@@ -526,7 +465,7 @@ impl Editor {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_toolbar(&mut self, _state: &mut State, ui: &mut Ui, ctx: &Context) {
|
||||
fn render_toolbar(&mut self, state: &State, ui: &mut Ui, ctx: &Context) {
|
||||
self.handle_file_dialogs(ctx);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
@@ -567,7 +506,8 @@ impl Editor {
|
||||
Some("Can't load program at invalid offset!".to_string());
|
||||
}
|
||||
|
||||
self.sender
|
||||
state
|
||||
.cmd_sender
|
||||
.send(Command::Write(self.load_offset, self.output.clone()))
|
||||
.unwrap_or_else(|_| {
|
||||
self.error = Some("Failed to send command".to_string());
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use egui::{Context, Ui};
|
||||
|
||||
use crate::emulator::{system::model::State, ui::interface::Component};
|
||||
use crate::emulator::{
|
||||
system::model::{Command, State},
|
||||
ui::interface::Component,
|
||||
};
|
||||
|
||||
pub struct History {
|
||||
visible: bool,
|
||||
@@ -20,11 +23,13 @@ impl Component for History {
|
||||
}
|
||||
|
||||
fn render(&mut self, state: &mut State, ui: &mut Ui, _ctx: &Context) {
|
||||
state.send(Command::HistoryRequest);
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("output_scroll")
|
||||
.max_width(400.0)
|
||||
.show(ui, |ui| {
|
||||
if state.persistent.history.is_empty() {
|
||||
if state.instruction_history.is_empty() {
|
||||
ui.label(
|
||||
egui::RichText::new("No output data")
|
||||
.font(egui::FontId::monospace(12.0))
|
||||
@@ -40,7 +45,7 @@ impl Component for History {
|
||||
.show(ui, |ui| {
|
||||
// Process bytes in chunks of 4
|
||||
for (idx, instruction) in
|
||||
state.persistent.history.iter().enumerate()
|
||||
state.instruction_history.iter().enumerate()
|
||||
{
|
||||
ui.label(format!("{idx}: "));
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::emulator::system::model::{Command, PersistentState, Running, State};
|
||||
use crate::emulator::system::model::{Command, Running, State, StateUpdate};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
pub trait Component {
|
||||
@@ -34,21 +34,15 @@ impl Category {
|
||||
}
|
||||
|
||||
pub struct EmulatorUI {
|
||||
pub sender: Sender<Command>,
|
||||
pub receiver: Receiver<State>,
|
||||
pub state: State,
|
||||
pub persistent: PersistentState,
|
||||
pub components: Vec<Box<dyn Component>>,
|
||||
}
|
||||
|
||||
impl EmulatorUI {
|
||||
#[must_use]
|
||||
pub fn new(sender: Sender<Command>, receiver: Receiver<State>) -> Self {
|
||||
pub fn new(sender: Sender<Command>, receiver: Receiver<StateUpdate>) -> Self {
|
||||
Self {
|
||||
sender,
|
||||
receiver,
|
||||
state: State::default(),
|
||||
persistent: PersistentState::default(),
|
||||
state: State::new(sender, receiver),
|
||||
components: vec![],
|
||||
}
|
||||
}
|
||||
@@ -56,19 +50,13 @@ impl EmulatorUI {
|
||||
pub fn add_component(&mut self, component: Box<dyn Component>) {
|
||||
self.components.push(component);
|
||||
}
|
||||
|
||||
fn update_state(&mut self) {
|
||||
while let Ok(state) = self.receiver.try_recv() {
|
||||
self.state = state;
|
||||
self.persistent.update(&self.state.persistent);
|
||||
self.state.persistent = self.persistent.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for EmulatorUI {
|
||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.update_state();
|
||||
if let Err(e) = self.state.update() {
|
||||
self.state.error_log.push(e.to_string());
|
||||
}
|
||||
|
||||
if self.state.running == Running::Running {
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use common::prelude::Instruction;
|
||||
use egui::{Context, Ui};
|
||||
use egui_file::FileDialog;
|
||||
|
||||
use crate::emulator::{
|
||||
system::model::{Command, State},
|
||||
ui::interface::Component,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Loader {
|
||||
path: Option<PathBuf>,
|
||||
output: Vec<u8>,
|
||||
load_offset: u32,
|
||||
offset_str: String,
|
||||
|
||||
// file dialogs
|
||||
open_file_dialog: Option<FileDialog>,
|
||||
|
||||
// other
|
||||
visible: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl Component for Loader {
|
||||
fn name(&self) -> &'static str {
|
||||
"Loader"
|
||||
}
|
||||
|
||||
fn visible(&mut self) -> &mut bool {
|
||||
&mut self.visible
|
||||
}
|
||||
|
||||
fn category(&self) -> super::interface::Category {
|
||||
super::interface::Category::Programming
|
||||
}
|
||||
|
||||
fn render(&mut self, state: &mut State, ui: &mut Ui, ctx: &Context) {
|
||||
ui.vertical(|ui| {
|
||||
self.render_toolbar(state, ui, ctx);
|
||||
|
||||
ui.add_space(4.0); // Add some spacing instead of just a separator
|
||||
ui.separator();
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false; 2])
|
||||
.max_height(ui.available_height() - 100.0)
|
||||
.show(ui, |ui| {
|
||||
self.render_output(state, ui, ctx);
|
||||
});
|
||||
|
||||
self.render_bottom_bar(state, ui, ctx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Loader {
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
path: None,
|
||||
output: Vec::new(),
|
||||
visible: false,
|
||||
load_offset: 0,
|
||||
offset_str: String::new(),
|
||||
error: None,
|
||||
open_file_dialog: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn filename(&self) -> &str {
|
||||
if let Some(path) = &self.path {
|
||||
return path
|
||||
.file_name()
|
||||
.unwrap_or_else(|| OsStr::new("Unnamed!"))
|
||||
.to_str()
|
||||
.map_or_else(
|
||||
|| unreachable!("File name should be valid UTF-8."),
|
||||
|ext| ext,
|
||||
);
|
||||
}
|
||||
"Unnamed!"
|
||||
}
|
||||
|
||||
fn open(&mut self) {
|
||||
let work_dir = std::env::current_dir().unwrap_or_else(|_| {
|
||||
dirs::home_dir().expect(
|
||||
"Couldn't get your current working directory or your home directory.",
|
||||
)
|
||||
});
|
||||
|
||||
if self.open_file_dialog.is_some() {
|
||||
// TODO: Flash an error stating you can only have one menu open at once.
|
||||
self.open_file_dialog = None;
|
||||
}
|
||||
|
||||
if self.open_file_dialog.is_none() {
|
||||
if let Some(p) = &self.path {
|
||||
let path = p.parent().map(Path::to_path_buf);
|
||||
let mut dialog = FileDialog::open_file(path);
|
||||
dialog.open();
|
||||
self.open_file_dialog = Some(dialog);
|
||||
} else {
|
||||
let mut dialog = FileDialog::open_file(Some(work_dir));
|
||||
dialog.open();
|
||||
self.open_file_dialog = Some(dialog);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_file_dialogs(&mut self, ctx: &egui::Context) {
|
||||
// Handle open dialog
|
||||
if let Some(dialog) = &mut self.open_file_dialog {
|
||||
if dialog.show(ctx).selected() {
|
||||
if let Some(file) = dialog.path() {
|
||||
// check if the file is a binary file
|
||||
if file.extension().is_some_and(|ext| ext == "dsb") {
|
||||
match std::fs::read(file) {
|
||||
Ok(content) => {
|
||||
self.output = content;
|
||||
self.error = None;
|
||||
}
|
||||
Err(e) => {
|
||||
self.error = Some(format!("Failed to read file: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.open_file_dialog = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_output(&self, _state: &mut State, ui: &mut Ui, _ctx: &Context) {
|
||||
// Output area with synchronized scrolling
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("output_scroll")
|
||||
.max_width(400.0)
|
||||
.show(ui, |ui| {
|
||||
if self.output.is_empty() {
|
||||
ui.label(
|
||||
egui::RichText::new("No output data")
|
||||
.font(egui::FontId::monospace(12.0))
|
||||
.color(egui::Color32::GRAY),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
egui::Grid::new("output_grid")
|
||||
.spacing([5.0, 2.0]) // Horizontal and vertical spacing
|
||||
.num_columns(4)
|
||||
.striped(false)
|
||||
.show(ui, |ui| {
|
||||
// Process bytes in chunks of 4
|
||||
for (line_num, chunk) in self.output.chunks(4).enumerate() {
|
||||
let address = line_num * 4;
|
||||
|
||||
// Convert chunk to u32 (little-endian)
|
||||
let mut bytes = [0u8; 4];
|
||||
for (i, &byte) in chunk.iter().enumerate() {
|
||||
if i < 4 {
|
||||
bytes[i] = byte;
|
||||
}
|
||||
}
|
||||
let value = u32::from_be_bytes(bytes);
|
||||
|
||||
// Address column
|
||||
ui.with_layout(
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
ui.set_min_width(80.0);
|
||||
let style = ui.style_mut();
|
||||
style.visuals.widgets.inactive.bg_fill =
|
||||
egui::Color32::from_gray(30);
|
||||
ui.label(
|
||||
egui::RichText::new(format!("0x{address:04X}"))
|
||||
.font(egui::FontId::monospace(12.0)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Individual bytes column
|
||||
let byte_str = chunk
|
||||
.iter()
|
||||
.map(|b| format!("{b:02X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
ui.label(
|
||||
egui::RichText::new(format!("{byte_str:<11}"))
|
||||
.font(egui::FontId::monospace(12.0))
|
||||
.color(egui::Color32::from_rgb(200, 200, 255)),
|
||||
);
|
||||
|
||||
// Hex column
|
||||
ui.label(
|
||||
egui::RichText::new(format!("0x{value:08X}"))
|
||||
.font(egui::FontId::monospace(12.0))
|
||||
.color(egui::Color32::from_rgb(255, 200, 200)),
|
||||
);
|
||||
|
||||
// Instruction column
|
||||
let instruction = Instruction::decode(value).map_or_else(
|
||||
|_| format!("{value:10}"),
|
||||
|instruction| instruction.to_string(),
|
||||
);
|
||||
|
||||
ui.label(
|
||||
egui::RichText::new(instruction)
|
||||
.font(egui::FontId::monospace(12.0))
|
||||
.color(egui::Color32::from_rgb(200, 255, 200)),
|
||||
);
|
||||
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn render_bottom_bar(&self, _state: &mut State, ui: &mut Ui, _ctx: &Context) {
|
||||
ui.horizontal(|ui| {
|
||||
// error display
|
||||
ui.label(
|
||||
egui::RichText::new(self.error.clone().unwrap_or_default())
|
||||
.color(egui::Color32::RED),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn render_toolbar(&mut self, state: &State, ui: &mut Ui, ctx: &Context) {
|
||||
self.handle_file_dialogs(ctx);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("Filename: {}", self.filename()));
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().button_padding = egui::vec2(8.0, 4.0);
|
||||
ui.spacing_mut().item_spacing.x = 6.0;
|
||||
|
||||
// Opens a file
|
||||
if ui.button("Open").clicked() {
|
||||
self.open();
|
||||
}
|
||||
|
||||
// Loads the generated binary into the assembler at the provided offset
|
||||
if ui.button("Load").clicked() {
|
||||
if self.error.is_some() {
|
||||
self.error =
|
||||
Some("Can't load program at invalid offset!".to_string());
|
||||
}
|
||||
|
||||
state
|
||||
.cmd_sender
|
||||
.send(Command::Write(self.load_offset, self.output.clone()))
|
||||
.unwrap_or_else(|_| {
|
||||
self.error = Some("Failed to send command".to_string());
|
||||
});
|
||||
}
|
||||
|
||||
// Entry widget to enter a load offset
|
||||
if ui.text_edit_singleline(&mut self.offset_str).changed() {
|
||||
if let Some(offset) = parse_address(&self.offset_str) {
|
||||
self.load_offset = offset;
|
||||
self.error = None;
|
||||
} else {
|
||||
self.error = Some("Invalid offset".to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_address(address: &str) -> Option<u32> {
|
||||
address.strip_prefix("0x").map_or_else(
|
||||
|| {
|
||||
address.strip_prefix("0b").map_or_else(
|
||||
|| {
|
||||
address.strip_prefix("0o").map_or_else(
|
||||
|| address.parse::<u32>().ok(),
|
||||
|oct| u32::from_str_radix(oct, 8).ok(),
|
||||
)
|
||||
},
|
||||
|bin| u32::from_str_radix(bin, 2).ok(),
|
||||
)
|
||||
},
|
||||
|hex| u32::from_str_radix(hex, 16).ok(),
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{num::ParseIntError, sync::mpsc::Sender};
|
||||
use std::num::ParseIntError;
|
||||
|
||||
use common::prelude::Instruction;
|
||||
|
||||
@@ -7,23 +7,22 @@ use crate::emulator::{
|
||||
ui::interface::Component,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MemoryInspector {
|
||||
view_size: u32,
|
||||
view_addr: u32,
|
||||
visible: bool,
|
||||
addr_input: String,
|
||||
sender: Sender<Command>,
|
||||
}
|
||||
|
||||
impl MemoryInspector {
|
||||
#[must_use]
|
||||
pub const fn new(sender: Sender<Command>) -> Self {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
view_size: 256,
|
||||
view_addr: 0,
|
||||
visible: false,
|
||||
addr_input: String::new(),
|
||||
sender,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,28 +62,26 @@ impl Component for MemoryInspector {
|
||||
let search_clicked = ui.button("🔍 Search").clicked();
|
||||
|
||||
// Handle Enter key in text field
|
||||
let enter_pressed =
|
||||
address_response.lost_focus() && ctx.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
let enter_pressed = address_response.lost_focus()
|
||||
&& ctx.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
|
||||
if search_clicked || enter_pressed {
|
||||
if let Ok(new) = parse_address(&self.addr_input) {
|
||||
self.view_addr = new;
|
||||
|
||||
if let Err(why) = self.sender.send(Command::Read(new, self.view_size)) {
|
||||
panic!(
|
||||
"Error sending message across threads -- cannot be recovered: {why}"
|
||||
)
|
||||
}
|
||||
} else {
|
||||
state.error = Some("Invalid address".to_string());
|
||||
state.error_log.push("Invalid address".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let _ = state
|
||||
.cmd_sender
|
||||
.send(Command::MemRequest(self.view_addr, self.view_size));
|
||||
|
||||
ui.label("(hex or decimal)");
|
||||
});
|
||||
|
||||
// Show input error if any
|
||||
if let Some(error) = &state.error {
|
||||
if let Some(error) = state.error_log.last() {
|
||||
ui.colored_label(egui::Color32::RED, format!("Error: {error}"));
|
||||
}
|
||||
|
||||
@@ -113,9 +110,12 @@ impl Component for MemoryInspector {
|
||||
ui.end_row();
|
||||
|
||||
// Memory data (8 bytes per row)
|
||||
for (row, chunk) in (0u32..).zip(state.memory_view.chunks(4)) {
|
||||
for (row, chunk) in (0u32..).zip(state.memory_view.chunks(4))
|
||||
{
|
||||
let row_address = self.view_addr + (row * 4);
|
||||
ui.monospace(format!("0x{row_address:08X} ({row_address})"));
|
||||
ui.monospace(format!(
|
||||
"0x{row_address:08X} ({row_address})"
|
||||
));
|
||||
for &byte in chunk {
|
||||
ui.monospace(format!("{byte:02X}"));
|
||||
}
|
||||
@@ -126,12 +126,16 @@ impl Component for MemoryInspector {
|
||||
}
|
||||
|
||||
// combine all 4 bytes in the chunk into a u32
|
||||
let combined = chunk
|
||||
.iter()
|
||||
.fold(0u32, |acc, &byte| (acc << 8) | u32::from(byte));
|
||||
let combined = chunk.iter().fold(0u32, |acc, &byte| {
|
||||
(acc << 8) | u32::from(byte)
|
||||
});
|
||||
|
||||
ui.monospace(format!("{combined}"));
|
||||
ui.monospace(format!("{}", Instruction::decode(combined).unwrap_or(Instruction::Nop)));
|
||||
ui.monospace(format!(
|
||||
"{}",
|
||||
Instruction::decode(combined)
|
||||
.unwrap_or(Instruction::Nop)
|
||||
));
|
||||
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod display;
|
||||
pub mod editor;
|
||||
pub mod history;
|
||||
pub mod interface;
|
||||
pub mod loader;
|
||||
pub mod memory_inspector;
|
||||
pub mod menu;
|
||||
pub mod stack_inspector;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use crate::emulator::{system::model::State, ui::interface::Component};
|
||||
use crate::emulator::{
|
||||
system::model::{Command, State},
|
||||
ui::interface::Component,
|
||||
};
|
||||
|
||||
use common::instructions::Register;
|
||||
|
||||
@@ -33,6 +36,8 @@ impl Component for StackInspector {
|
||||
}
|
||||
|
||||
fn render(&mut self, state: &mut State, ui: &mut egui::Ui, _ctx: &egui::Context) {
|
||||
state.send(Command::StackRequest);
|
||||
|
||||
ui.vertical(|ui| {
|
||||
ui.heading("Stack Inspector");
|
||||
egui::ScrollArea::vertical()
|
||||
|
||||
+10
-7
@@ -30,7 +30,7 @@ use crate::emulator::{
|
||||
system::{
|
||||
emulator::run_emulator,
|
||||
memory::MainStore,
|
||||
model::{Command, State},
|
||||
model::{Command, StateUpdate},
|
||||
processor::Processor,
|
||||
},
|
||||
ui::{
|
||||
@@ -86,7 +86,7 @@ pub fn android_main(app: AndroidApp) -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
pub fn setup_emulator(
|
||||
cmd_receiver: Receiver<Command>,
|
||||
state_sender: Sender<State>,
|
||||
state_sender: Sender<StateUpdate>,
|
||||
rpc_client: Option<Arc<RpcClient>>,
|
||||
) {
|
||||
let main_store = MainStore::new();
|
||||
@@ -101,22 +101,22 @@ pub fn setup_emulator(
|
||||
#[must_use]
|
||||
pub fn setup_ui(
|
||||
cmd_sender: Sender<Command>,
|
||||
state_reciever: Receiver<State>,
|
||||
state_reciever: Receiver<StateUpdate>,
|
||||
) -> EmulatorUI {
|
||||
let mut ui = EmulatorUI::new(cmd_sender.clone(), state_reciever);
|
||||
let mut ui = EmulatorUI::new(cmd_sender, state_reciever);
|
||||
|
||||
// Create UI modules.
|
||||
let control_unit = ControlPanel::new(cmd_sender.clone());
|
||||
let control_unit = ControlPanel::new();
|
||||
|
||||
ui.add_component(Box::new(control_unit));
|
||||
|
||||
let mem_inspector = MemoryInspector::new(cmd_sender.clone());
|
||||
let mem_inspector = MemoryInspector::new();
|
||||
ui.add_component(Box::new(mem_inspector));
|
||||
|
||||
let stack_inspector = StackInspector::new();
|
||||
ui.add_component(Box::new(stack_inspector));
|
||||
|
||||
let editor = Editor::new(cmd_sender);
|
||||
let editor = Editor::new();
|
||||
ui.add_component(Box::new(editor));
|
||||
|
||||
let display = Display::new();
|
||||
@@ -125,5 +125,8 @@ pub fn setup_ui(
|
||||
let history = emulator::ui::history::History::new();
|
||||
ui.add_component(Box::new(history));
|
||||
|
||||
let loader = emulator::ui::loader::Loader::new();
|
||||
ui.add_component(Box::new(loader));
|
||||
|
||||
ui
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user