Files
SecurityEmulator/src/CPU.cpp

83 lines
2.4 KiB
C++
Raw Normal View History

2026-02-04 12:52:42 +01:00
#include "CPU.h"
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <array>
#include <cassert>
2026-02-04 12:52:42 +01:00
CPU::CPU(std::shared_ptr<Bus> bus) : m_Bus(bus), m_IsHalted(false), m_Context({m_Instruction, m_InstructionPointer, m_Flags, m_Registers, m_Bus, m_IsHalted}) {
2026-02-04 12:52:42 +01:00
m_InstructionPointer = 0x00008000;
for(int i = 0; i < 16; i++)
{
m_Registers[i] = 0;
}
}
void CPU::Step() {
2026-02-04 12:52:42 +01:00
FetchDecode();
Execute();
}
void CPU::FetchDecode() {
uint8_t opcode_raw = m_Bus->AccessX<uint8_t>(m_InstructionPointer);
Opcode opcode = static_cast<Opcode>(opcode_raw);
2026-02-04 12:52:42 +01:00
switch(opcode_raw) {
case Opcode::MOV_R_IMM32 ... 0xBF: // 0xB8 to 0xBF
m_Instruction.m_Opcode = Opcode::MOV_R_IMM32;
m_Instruction.m_Operand1 = opcode_raw - 0xB8;
2026-02-04 12:52:42 +01:00
m_Instruction.m_Operand2 = m_Bus->AccessX<uint32_t>(m_InstructionPointer + 1);
m_Instruction.m_Length = 5;
break;
case Opcode::NOP:
case Opcode::HLT:
m_Instruction.m_Opcode = opcode;
m_Instruction.m_Length = 1;
2026-02-04 12:52:42 +01:00
break;
case Opcode::ADD_RM32_R32:
m_Instruction.m_Opcode = opcode;
m_Instruction.optional.m_ModRM = x86::process_modrm(m_Bus->AccessX<uint8_t>(m_InstructionPointer + 1));
m_Instruction.m_Length = 2;
FetchModRMFields();
2026-02-04 12:52:42 +01:00
break;
}
m_InstructionPointer += m_Instruction.m_Length;
}
void CPU::Execute() {
2026-02-04 12:52:42 +01:00
std::cout << "Executing... \n";
uint8_t opcode_value = static_cast<uint8_t>(m_Instruction.m_Opcode);
auto& exec_table = GetExecutorTable();
if(exec_table[opcode_value])
{
exec_table[opcode_value](m_Context);
return;
}
throw std::runtime_error("Opcode not found!");
}
void CPU::FetchModRMFields() {
assert(m_Instruction.m_Length != 0); // FetchDecode() must set m_Length before calling FetchModRMFields()
x86::ModRMState state = m_Instruction.optional.m_ModRM.m_State;
switch(state) {
case x86::ModRMState::LR:
case x86::ModRMState::R:
break;
case x86::ModRMState::DISP32:
case x86::ModRMState::LR_DISP32:
m_Instruction.m_Operand1 = m_Bus->AccessX<uint32_t>(m_InstructionPointer + m_Instruction.m_Length);
m_Instruction.m_Length += 4;
break;
case x86::ModRMState::LR_DISP8:
m_Instruction.m_Operand1 = m_Bus->AccessX<uint8_t>(m_InstructionPointer + m_Instruction.m_Length);
m_Instruction.m_Length += 1;
break;
default:
throw std::runtime_error("Instruction could not be modified according to the modrm field!");
}
}