一台未完善的虚拟机
zyx201309
·
·
科技·工程
一台虚拟机
闲着没事,让DS写了一个汇编代码编写并执行的虚拟机
注意,此虚拟机需1GB硬盘(但是可以在硬件控制处修改)
// 编译参数:g++ computer.cpp -o vm.exe -mwindows -lcomctl32
#include <windows.h>
#include <commctrl.h>
#include <vector>
#include <fstream>
#include <cstring>
#include <cstdint>
#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <string>
#include <algorithm>
// C++11 兼容的文件系统操作
#include <sys/stat.h>
// 链接库
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
// ==================== 硬件配置 ====================
constexpr size_t MEMORY_SIZE = 1 * 1024 * 1024; // 10MB
constexpr size_t DISK_SIZE = 1LL * 1024 * 1024 * 10; // 1GB
constexpr size_t SECTOR_SIZE = 512;
// ==================== C++11 文件工具函数 ====================
bool fileExists(const std::string& path) {
struct stat buffer;
return (stat(path.c_str(), &buffer) == 0);
}
uint64_t fileSize(const std::string& path) {
struct stat buffer;
if (stat(path.c_str(), &buffer) != 0) return 0;
return static_cast<uint64_t>(buffer.st_size);
}
// ==================== 虚拟内存 新增断点管理 ====================
class VirtualMemory {
private:
std::vector<uint8_t> memory;
std::vector<bool> breakpointList;
public:
VirtualMemory() : memory(MEMORY_SIZE, 0), breakpointList(MEMORY_SIZE, false) {}
uint8_t readByte(uint64_t addr) {
if (addr >= MEMORY_SIZE) throw std::out_of_range("内存读取越界");
return memory[addr];
}
void writeByte(uint64_t addr, uint8_t val) {
if (addr >= MEMORY_SIZE) throw std::out_of_range("内存写入越界");
memory[addr] = val;
}
uint64_t readQword(uint64_t addr) {
if (addr + 8 > MEMORY_SIZE) throw std::out_of_range("内存读取越界");
uint64_t val = 0;
for (int i = 0; i < 8; i++) {
val |= (uint64_t)memory[addr + i] << (i * 8);
}
return val;
}
void writeQword(uint64_t addr, uint64_t val) {
if (addr + 8 > MEMORY_SIZE) throw std::out_of_range("内存写入越界");
for (int i = 0; i < 8; i++) {
memory[addr + i] = (val >> (i * 8)) & 0xFF;
}
}
void readBytes(uint64_t addr, uint8_t* buf, size_t len) {
if (addr + len > MEMORY_SIZE) throw std::out_of_range("内存读取越界");
for (size_t i = 0; i < len; i++) {
buf[i] = memory[addr + i];
}
}
void setBreakpoint(uint64_t addr, bool enable) {
if(addr < MEMORY_SIZE) breakpointList[addr] = enable;
}
bool checkBreakpoint(uint64_t addr) {
if(addr >= MEMORY_SIZE) return false;
return breakpointList[addr];
}
size_t getSize() const { return MEMORY_SIZE; }
};
// ==================== 虚拟磁盘 ====================
class VirtualDisk {
private:
std::fstream file;
std::string path;
bool valid;
bool createNewDisk() {
std::ofstream newFile(path.c_str(), std::ios::binary | std::ios::trunc);
if (!newFile.is_open()) return false;
newFile.seekp(DISK_SIZE - 1);
newFile.write("", 1);
newFile.flush();
newFile.close();
return fileSize(path) == DISK_SIZE;
}
public:
VirtualDisk(const std::string& p) : path(p), valid(false) {
if (fileExists(path)) {
if (fileSize(path) == DISK_SIZE) {
file.open(path.c_str(), std::ios::in | std::ios::out | std::ios::binary);
if (file.is_open()) {
valid = true;
return;
}
} else {
remove(path.c_str());
}
}
if (createNewDisk()) {
file.open(path.c_str(), std::ios::in | std::ios::out | std::ios::binary);
if (file.is_open()) {
valid = true;
return;
}
}
throw std::runtime_error("无法创建或打开虚拟磁盘文件");
}
~VirtualDisk() {
if (file.is_open()) {
file.close();
}
}
bool readSector(uint64_t sector, uint8_t* buf) {
if (!valid) return false;
if (sector >= DISK_SIZE / SECTOR_SIZE) return false;
file.seekg(sector * SECTOR_SIZE, std::ios::beg);
if (!file) return false;
file.read(reinterpret_cast<char*>(buf), SECTOR_SIZE);
return file.good();
}
bool writeSector(uint64_t sector, const uint8_t* buf) {
if (!valid) return false;
if (sector >= DISK_SIZE / SECTOR_SIZE) return false;
file.seekp(sector * SECTOR_SIZE, std::ios::beg);
if (!file) return false;
file.write(reinterpret_cast<const char*>(buf), SECTOR_SIZE);
file.flush();
return file.good();
}
bool isValid() const { return valid; }
size_t getTotalSectors() const { return DISK_SIZE / SECTOR_SIZE; }
std::string getPath() const { return path; }
};
// ==================== 64位CPU定义 ====================
struct CPU {
uint64_t rax, rbx, rcx, rdx;
uint64_t rsi, rdi;
uint64_t rsp, rbp;
uint64_t rip;
uint64_t flags;
CPU() : rax(0), rbx(0), rcx(0), rdx(0),
rsi(0), rdi(0), rsp(MEMORY_SIZE - 16), rbp(0),
rip(0), flags(0) {}
};
// ==================== 虚拟机引擎 新增运行状态控制和断点处理 ====================
class VirtualMachine {
private:
CPU cpu;
VirtualMemory memory;
VirtualDisk disk;
bool running;
bool pausedByBreakpoint;
uint64_t instructionCount;
bool programLoaded;
std::vector<std::string> outputLog;
bool zeroFlag; // 零标志
bool carryFlag; // 进位标志
bool signFlag; // 符号标志
bool overflowFlag; // 溢出标志位,新增这行即可
uint64_t& getReg(int idx) {
switch (idx) {
case 0: return cpu.rax;
case 1: return cpu.rbx;
case 2: return cpu.rcx;
case 3: return cpu.rdx;
case 4: return cpu.rsi;
case 5: return cpu.rdi;
case 6: return cpu.rsp;
case 7: return cpu.rbp;
default: throw std::invalid_argument("无效寄存器编号");
}
}
void updateFlags(uint64_t result, bool carry = false) {
zeroFlag = (result == 0);
signFlag = (result & 0x8000000000000000) != 0;
carryFlag = carry;
// 溢出标志暂时不在这里计算,由各指令分支单独处理
// 如果指令分支没有显式设置,保持上一次的值即可
cpu.flags = 0;
if (carryFlag) cpu.flags |= 0x1;
if (zeroFlag) cpu.flags |= 0x40;
if (signFlag) cpu.flags |= 0x80;
if (overflowFlag) cpu.flags |= 0x800;
}
public:
VirtualMachine(const std::string& diskPath)
: cpu(), memory(), disk(diskPath), running(false), pausedByBreakpoint(false),
instructionCount(0), programLoaded(false),
zeroFlag(false), carryFlag(false), signFlag(false), overflowFlag(false) {}
void loadProgram(const std::vector<uint8_t>& code, uint64_t addr = 0x1000) {
if (code.empty()) {
throw std::runtime_error("程序二进制为空,无法加载");
}
if (addr + code.size() > MEMORY_SIZE) {
throw std::out_of_range("程序太大,无法加载到内存");
}
for (size_t i = 0; i < code.size(); i++) {
memory.writeByte(addr + i, code[i]);
}
cpu.rip = addr;
programLoaded = true;
instructionCount = 0;
outputLog.clear();
zeroFlag = false;
carryFlag = false;
signFlag = false;
pausedByBreakpoint = false;
addOutput("程序已加载到地址 0x" + toHex(addr) + ", 大小: " + std::to_string(code.size()) + " 字节");
}
bool step() {
if (!programLoaded) return false;
if (cpu.rip >= MEMORY_SIZE) {
addOutput("指令指针越界,停止执行");
running = false;
return false;
}
if(memory.checkBreakpoint(cpu.rip) && running) {
pausedByBreakpoint = true;
running = false;
addOutput("触发断点,地址: 0x" + toHex(cpu.rip));
return false;
}
uint8_t opcode = memory.readByte(cpu.rip);
instructionCount++;
switch (opcode) {
case 0x00: { // HALT
addOutput("执行 HALT 指令,停止");
running = false;
return false;
}
case 0x01: { // MOV reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
getReg(regIdx) = imm;
cpu.rip += 10;
break;
}
case 0x02: { // MOV reg1, reg2
uint8_t reg1 = memory.readByte(cpu.rip + 1);
uint8_t reg2 = memory.readByte(cpu.rip + 2);
getReg(reg1) = getReg(reg2);
cpu.rip += 3;
break;
}
case 0x03: { // LOAD reg, [addr]
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t addr = memory.readQword(cpu.rip + 2);
getReg(regIdx) = memory.readQword(addr);
cpu.rip += 10;
break;
}
case 0x04: { // STORE [addr], reg
uint64_t addr = memory.readQword(cpu.rip + 1);
uint8_t regIdx = memory.readByte(cpu.rip + 9);
memory.writeQword(addr, getReg(regIdx));
cpu.rip += 10;
break;
}
case 0x10: { // ADD reg, imm64 - 寄存器加64位立即数
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t srcVal = getReg(regIdx);
uint64_t imm = memory.readQword(cpu.rip + 2);
uint64_t result = srcVal + imm;
carryFlag = (result < srcVal);
// 加法溢出:两个正数相加得负数,或两个负数相加得正数
bool srcSign = (srcVal & 0x8000000000000000) != 0;
bool immSign = (imm & 0x8000000000000000) != 0;
bool resSign = (result & 0x8000000000000000) != 0;
overflowFlag = (srcSign == immSign) && (resSign != srcSign);
getReg(regIdx) = result;
updateFlags(result, carryFlag);
cpu.rip += 10;
break;
}
case 0x11: { // ADD reg1, reg2 - 两个寄存器值相加
uint8_t reg1 = memory.readByte(cpu.rip + 1);
uint8_t reg2 = memory.readByte(cpu.rip + 2);
uint64_t val1 = getReg(reg1);
uint64_t val2 = getReg(reg2);
uint64_t result = val1 + val2;
carryFlag = (result < val1);
// 加法溢出标志计算
bool sign1 = (val1 & 0x8000000000000000) != 0;
bool sign2 = (val2 & 0x8000000000000000) != 0;
bool resSign = (result & 0x8000000000000000) != 0;
overflowFlag = (sign1 == sign2) && (resSign != sign1);
getReg(reg1) = result;
updateFlags(result, carryFlag);
cpu.rip += 3;
break;
}
case 0x12: { // SUB reg, imm64 - 寄存器减去64位立即数
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t srcVal = getReg(regIdx);
uint64_t imm = memory.readQword(cpu.rip + 2);
uint64_t result = srcVal - imm;
carryFlag = (srcVal < imm);
// 减法溢出:被减数和减数符号不同,且结果符号与被减数符号不同
bool srcSign = (srcVal & 0x8000000000000000) != 0;
bool immSign = (imm & 0x8000000000000000) != 0;
bool resSign = (result & 0x8000000000000000) != 0;
overflowFlag = (srcSign != immSign) && (resSign != srcSign);
getReg(regIdx) = result;
updateFlags(result, carryFlag);
cpu.rip += 10;
break;
}
case 0x13: { // SUB reg1, reg2 - 两个寄存器值相减
uint8_t reg1 = memory.readByte(cpu.rip + 1);
uint8_t reg2 = memory.readByte(cpu.rip + 2);
uint64_t val1 = getReg(reg1);
uint64_t val2 = getReg(reg2);
uint64_t result = val1 - val2;
carryFlag = (val1 < val2);
// 减法溢出标志计算
bool sign1 = (val1 & 0x8000000000000000) != 0;
bool sign2 = (val2 & 0x8000000000000000) != 0;
bool resSign = (result & 0x8000000000000000) != 0;
overflowFlag = (sign1 != sign2) && (resSign != sign1);
getReg(reg1) = result;
updateFlags(result, carryFlag);
cpu.rip += 3;
break;
}
case 0x14: { // MUL reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
getReg(regIdx) *= imm;
updateFlags(getReg(regIdx));
cpu.rip += 10;
break;
}
case 0x15: { // DIV reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
if (imm != 0) {
getReg(regIdx) /= imm;
updateFlags(getReg(regIdx));
} else {
addOutput("除零异常!地址 0x" + toHex(cpu.rip));
running = false;
return false;
}
cpu.rip += 10;
break;
}
case 0x20: { // CMP reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
uint64_t srcVal = getReg(regIdx); // 被减数
uint64_t result = srcVal - imm;
carryFlag = (srcVal < imm);
// 直接在这里计算溢出标志,不依赖任何外部变量
bool srcSign = (srcVal & 0x8000000000000000) != 0;
bool immSign = (imm & 0x8000000000000000) != 0;
bool resSign = (result & 0x8000000000000000) != 0;
overflowFlag = (srcSign != immSign) && (resSign != srcSign);
updateFlags(result, carryFlag);
cpu.rip += 10;
break;
}
case 0x21: { // CMP reg1, reg2
uint8_t reg1 = memory.readByte(cpu.rip + 1);
uint8_t reg2 = memory.readByte(cpu.rip + 2);
uint64_t val1 = getReg(reg1);
uint64_t val2 = getReg(reg2);
uint64_t result = val1 - val2;
carryFlag = (val1 < val2);
bool sign1 = (val1 & 0x8000000000000000) != 0;
bool sign2 = (val2 & 0x8000000000000000) != 0;
bool resSign = (result & 0x8000000000000000) != 0;
overflowFlag = (sign1 != sign2) && (resSign != sign1);
updateFlags(result, carryFlag);
cpu.rip += 3;
break;
}
case 0x30: { // JMP addr
uint64_t addr = memory.readQword(cpu.rip + 1);
cpu.rip = addr;
break;
}
case 0x31: { // JE addr (等于则跳转)
uint64_t addr = memory.readQword(cpu.rip + 1);
if (zeroFlag) {
cpu.rip = addr;
} else {
cpu.rip += 9;
}
break;
}
case 0x32: { // JNE addr (不等于则跳转)
uint64_t addr = memory.readQword(cpu.rip + 1);
if (!zeroFlag) {
cpu.rip = addr;
} else {
cpu.rip += 9;
}
break;
}
case 0x33: { // JG addr (大于则跳转)
uint64_t addr = memory.readQword(cpu.rip + 1);
if (!zeroFlag && (signFlag == overflowFlag)) {
cpu.rip = addr;
} else {
cpu.rip += 9;
}
break;
}
case 0x34: { // JL addr (小于则跳转)
uint64_t addr = memory.readQword(cpu.rip + 1);
if (signFlag != overflowFlag) {
cpu.rip = addr;
} else {
cpu.rip += 9;
}
break;
}
case 0x35: { // JGE addr (大于等于则跳转)
uint64_t addr = memory.readQword(cpu.rip + 1);
if (signFlag == overflowFlag) {
cpu.rip = addr;
} else {
cpu.rip += 9;
}
break;
}
case 0x36: { // JLE addr (小于等于则跳转)
uint64_t addr = memory.readQword(cpu.rip + 1);
if (zeroFlag || (signFlag != overflowFlag)) {
cpu.rip = addr;
} else {
cpu.rip += 9;
}
break;
}
case 0x40: { // AND reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
getReg(regIdx) &= imm;
updateFlags(getReg(regIdx));
cpu.rip += 10;
break;
}
case 0x41: { // OR reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
getReg(regIdx) |= imm;
updateFlags(getReg(regIdx));
cpu.rip += 10;
break;
}
case 0x42: { // XOR reg, imm64
uint8_t regIdx = memory.readByte(cpu.rip + 1);
uint64_t imm = memory.readQword(cpu.rip + 2);
getReg(regIdx) ^= imm;
updateFlags(getReg(regIdx));
cpu.rip += 10;
break;
}
case 0x43: { // NOT reg
uint8_t regIdx = memory.readByte(cpu.rip + 1);
getReg(regIdx) = ~getReg(regIdx);
updateFlags(getReg(regIdx));
cpu.rip += 2;
break;
}
case 0x50: { // PUSH reg
uint8_t regIdx = memory.readByte(cpu.rip + 1);
cpu.rsp -= 8;
// 新增栈边界检查,栈指针不能小于0,防止下溢
if(cpu.rsp < 0) {
addOutput("栈下溢异常,地址 0x" + toHex(cpu.rsp));
running = false;
return false;
}
memory.writeQword(cpu.rsp, getReg(regIdx));
cpu.rip += 2;
break;
}
case 0x51: { // POP reg
// 新增栈边界检查,栈指针不能超过初始化的最大RSP地址,防止上溢
if(cpu.rsp >= MEMORY_SIZE - 8) {
addOutput("栈上溢异常,地址 0x" + toHex(cpu.rsp));
running = false;
return false;
}
uint8_t regIdx = memory.readByte(cpu.rip + 1);
getReg(regIdx) = memory.readQword(cpu.rsp);
cpu.rsp += 8;
cpu.rip += 2;
break;
}
case 0x60: { // CALL addr
uint64_t addr = memory.readQword(cpu.rip + 1);
cpu.rsp -= 8;
memory.writeQword(cpu.rsp, cpu.rip + 9);
cpu.rip = addr;
break;
}
case 0x61: { // RET
cpu.rip = memory.readQword(cpu.rsp);
cpu.rsp += 8;
break;
}
case 0x7F: { // INT 通用中断入口
uint8_t intNum = memory.readByte(cpu.rip + 1);
if(intNum == 0x10) {
addOutput("INT 0x10: RAX = 0x" + toHex(cpu.rax) + " (" + std::to_string(cpu.rax) + ")");
} else if(intNum == 0x20) {
uint8_t sectorBuf[SECTOR_SIZE] = {0};
if (disk.readSector(cpu.rax, sectorBuf)) {
for (size_t i = 0; i < SECTOR_SIZE; i++) {
memory.writeByte(cpu.rbx + i, sectorBuf[i]);
}
addOutput("磁盘读取成功: 扇区 " + std::to_string(cpu.rax));
} else {
addOutput("磁盘读取失败: 扇区 " + std::to_string(cpu.rax));
}
} else if(intNum == 0x21) {
uint8_t sectorBuf[SECTOR_SIZE] = {0};
for (size_t i = 0; i < SECTOR_SIZE; i++) {
sectorBuf[i] = memory.readByte(cpu.rbx + i);
}
if (disk.writeSector(cpu.rax, sectorBuf)) {
addOutput("磁盘写入成功: 扇区 " + std::to_string(cpu.rax));
} else {
addOutput("磁盘写入失败: 扇区 " + std::to_string(cpu.rax));
}
} else {
addOutput("未知中断 0x" + toHex(intNum));
}
cpu.rip += 2;
break;
}
default: {
addOutput("未知指令 0x" + toHex(opcode) + " 在地址 0x" + toHex(cpu.rip));
running = false;
return false;
}
}
return true;
}
void run(uint64_t maxInstructions = 1000000) {
if (!programLoaded) return;
running = true;
pausedByBreakpoint = false;
instructionCount = 0;
addOutput("开始执行程序...");
while (running && instructionCount < maxInstructions) {
if (!step()) {
running = false;
break;
}
// 每1000条指令处理一次UI消息,避免窗口卡死无响应
if(instructionCount % 1000 == 0) {
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
if(!pausedByBreakpoint) {
addOutput("程序执行完毕,共执行 " + std::to_string(instructionCount) + " 条指令");
}
}
void addOutput(const std::string& msg) {
outputLog.push_back(msg);
}
std::string toHex(uint64_t value) {
std::ostringstream oss;
oss << std::hex << std::setw(16) << std::setfill('0') << value;
return oss.str();
}
// 获取状态信息
CPU getCPU() const { return cpu; }
VirtualMemory& getMemory() { return memory; }
VirtualDisk& getDisk() { return disk; }
uint64_t getInstructionCount() const { return instructionCount; }
bool isProgramLoaded() const { return programLoaded; }
bool isRunning() const { return running; }
bool isPausedByBreakpoint() const { return pausedByBreakpoint; }
void setRunning(bool status) { running = status; }
const std::vector<std::string>& getOutputLog() const { return outputLog; }
};
// ==================== 全局变量 ====================
VirtualMachine* g_vm = nullptr;
HWND g_hWndMain = NULL;
HWND g_hWndRegisters = NULL;
HWND g_hWndMemory = NULL;
HWND g_hWndOutput = NULL;
HWND g_hWndCode = NULL;
HWND g_hWndStatus = NULL;
HWND g_hWndToolBar = NULL;
HWND g_hWndCodeEditor = NULL;
HFONT g_hCustomFont = NULL;
HINSTANCE g_hInst = NULL;
// 控件ID
#define IDC_REGISTERS 1001
#define IDC_MEMORY 1002
#define IDC_OUTPUT 1003
#define IDC_CODE 1004
#define IDC_STATUS 1005
#define IDM_RUN_EDITOR_CODE 1006
// 菜单ID
#define IDM_LOAD 2001
#define IDM_SAVEASM 2008
#define IDM_LOADBIN 2009
#define IDM_SAVEBIN 2010
#define IDM_RUN 2002
#define IDM_STEP 2003
#define IDM_STOP 2004
#define IDM_RESET 2005
#define IDM_EXIT 2006
#define IDM_ABOUT 2007
// 工具栏ID
#define IDT_LOAD 3001
#define IDT_RUN 3002
#define IDT_STEP 3003
#define IDT_STOP 3004
// 快捷键ID
#define HOTKEY_RUN_ID 1
#define HOTKEY_STEP_ID 2
#define HOTKEY_STOP_ID 3
#define HOTKEY_RUN_EDITOR_ID 4
// ==================== 辅助函数 ====================
std::string toHexString(uint64_t value, int width = 16) {
std::ostringstream oss;
oss << std::hex << std::setw(width) << std::setfill('0') << value;
return oss.str();
}
void updateRegisters() {
if (!g_vm || !g_hWndRegisters) return;
CPU cpu = g_vm->getCPU();
std::ostringstream oss;
oss << "RAX: 0x" << toHexString(cpu.rax) << "\r\n";
oss << "RBX: 0x" << toHexString(cpu.rbx) << "\r\n";
oss << "RCX: 0x" << toHexString(cpu.rcx) << "\r\n";
oss << "RDX: 0x" << toHexString(cpu.rdx) << "\r\n";
oss << "RSI: 0x" << toHexString(cpu.rsi) << "\r\n";
oss << "RDI: 0x" << toHexString(cpu.rdi) << "\r\n";
oss << "RSP: 0x" << toHexString(cpu.rsp) << "\r\n";
oss << "RBP: 0x" << toHexString(cpu.rbp) << "\r\n";
oss << "RIP: 0x" << toHexString(cpu.rip) << "\r\n";
oss << "FLAGS: 0x" << toHexString(cpu.flags) << "\r\n";
oss << "指令数: " << g_vm->getInstructionCount();
SetWindowText(g_hWndRegisters, oss.str().c_str());
}
void updateMemory(uint64_t startAddr = 0x1000) {
if (!g_vm || !g_hWndMemory) return;
std::ostringstream oss;
for (int row = 0; row < 16; row++) {
uint64_t addr = startAddr + row * 16;
oss << toHexString(addr) << ": ";
for (int col = 0; col < 16; col++) {
try {
uint8_t byte = g_vm->getMemory().readByte(addr + col);
oss << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " ";
} catch (...) {
oss << "?? ";
}
}
oss << " |";
for (int col = 0; col < 16; col++) {
try {
uint8_t byte = g_vm->getMemory().readByte(addr + col);
char c = (byte >= 32 && byte <= 126) ? byte : '.';
oss << c;
} catch (...) {
oss << "?";
}
}
oss << "\r\n";
}
SetWindowText(g_hWndMemory, oss.str().c_str());
}
void updateOutput() {
if (!g_vm || !g_hWndOutput) return;
std::ostringstream oss;
const auto& log = g_vm->getOutputLog();
for (int i = 0; i < (int)log.size(); i++) {
oss << log[i] << "\r\n";
}
SetWindowText(g_hWndOutput, oss.str().c_str());
// 自动滚动到底部
int len = GetWindowTextLength(g_hWndOutput);
SendMessage(g_hWndOutput, EM_SETSEL, len, len);
SendMessage(g_hWndOutput, EM_SCROLLCARET, 0, 0);
}
void updateStatus() {
if (!g_vm || !g_hWndStatus) return;
std::string status = "状态: ";
if (g_vm->isRunning()) {
status += "运行中";
} else if(g_vm->isPausedByBreakpoint()) {
status += "断点暂停";
} else if (g_vm->isProgramLoaded()) {
status += "程序已加载";
} else {
status += "就绪";
}
status += " | 指令数: " + std::to_string(g_vm->getInstructionCount());
SetWindowText(g_hWndStatus, status.c_str());
}
void updateAll() {
updateRegisters();
updateMemory();
updateOutput();
updateStatus();
}
// 汇编解析辅助:获取寄存器编号(大小写兼容)
int getRegIndex(const std::string& regName) {
std::string lowerReg = regName;
std::transform(lowerReg.begin(), lowerReg.end(), lowerReg.begin(), ::tolower);
if(lowerReg == "rax") return 0;
if(lowerReg == "rbx") return 1;
if(lowerReg == "rcx") return 2;
if(lowerReg == "rdx") return 3;
if(lowerReg == "rsi") return 4;
if(lowerReg == "rdi") return 5;
if(lowerReg == "rsp") return 6;
if(lowerReg == "rbp") return 7;
return -1;
}
// 辅助生成reg1,reg2格式的双寄存器指令
std::vector<uint8_t> encodeDoubleReg(uint8_t baseOp, uint8_t reg1, uint8_t reg2) {
return {baseOp, reg1, reg2};
}
// 辅助生成带立即数的单寄存器指令
std::vector<uint8_t> encodeRegImm64(uint8_t baseOp, uint8_t reg, uint64_t imm) {
std::vector<uint8_t> code = {baseOp, reg};
for(int i=0;i<8;i++) code.push_back(static_cast<uint8_t>((imm >> (i*8)) & 0xFF));
return code;
}
// 辅助生成带64位地址的跳转指令
std::vector<uint8_t> encodeJumpAddr(uint8_t baseOp, uint64_t addr) {
std::vector<uint8_t> code = {baseOp};
for(int i=0;i<8;i++) code.push_back(static_cast<uint8_t>((addr >> (i*8)) & 0xFF));
return code;
}
// ==================== 辅助函数 ====================
// 该部分包含窗口创建、界面更新、消息处理等辅助函数,以及完整的入口点
// 加载汇编文件并解析为二进制,然后加载到虚拟机
void loadAssemblyFile(const std::string& filename) {
if (!g_vm) return;
std::ifstream file(filename);
if (!file.is_open()) {
MessageBox(g_hWndMain, "无法打开文件", "错误", MB_ICONERROR);
return;
}
std::vector<uint8_t> binary;
std::string line;
int lineNum = 0;
try {
while (std::getline(file, line)) {
lineNum++;
// 去除注释
size_t commentPos = line.find(';');
if (commentPos != std::string::npos) {
line = line.substr(0, commentPos);
}
// 去除首尾空格
while (!line.empty() && isspace(line.front())) line.erase(line.begin());
while (!line.empty() && isspace(line.back())) line.pop_back();
if (line.empty()) continue;
std::istringstream iss(line);
std::string mnemonic;
iss >> mnemonic;
std::transform(mnemonic.begin(), mnemonic.end(), mnemonic.begin(), ::toupper);
if (mnemonic == "HLT" || mnemonic == "HALT") {
binary.push_back(0x00);
}
else if (mnemonic == "MOV") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
// 去除逗号
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
// 判断第二个操作数是否是立即数
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[1] == '0' && (operand2[1] == 'x' || operand2[0] == 'X'))){
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x01, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("无效寄存器: " + operand2);
binary.push_back(0x02);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "ADD") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[1] == '0' && (operand2[1] == 'x' || operand2[0] == 'X'))){
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x10, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("无效寄存器: " + operand2);
binary.push_back(0x11);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "SUB") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[1] == '0' && (operand2[1] == 'x' || operand2[0] == 'X'))){
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x12, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("无效寄存器: " + operand2);
binary.push_back(0x13);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "MUL") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[1] == '0' && (operand2[1] == 'x' || operand2[0] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x14, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
throw std::runtime_error("MUL指令仅支持立即数操作数");
}
}
else if (mnemonic == "DIV") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[1] == '0' && (operand2[1] == 'x' || operand2[0] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x15, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
throw std::runtime_error("DIV指令仅支持立即数操作数");
}
}
else if (mnemonic == "CMP") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x20, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("无效寄存器: " + operand2);
binary.push_back(0x21);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "JG") {
std::string operand;
iss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x33, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JL") {
std::string operand;
iss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x34, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JGE") {
std::string operand;
iss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x35, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JLE") {
std::string operand;
iss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x36, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "AND") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x40, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "OR") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x41, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "XOR") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x42, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "NOT") {
std::string operand1;
iss >> operand1;
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
binary.push_back(0x43);
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "LOAD") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
// 剥离中括号提取地址
if(operand2.front() == '[') operand2.erase(operand2.begin());
if(operand2.back() == ']') operand2.pop_back();
uint64_t addr = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x03, static_cast<uint8_t>(regIdx), addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "STORE") {
std::string operand1, operand2;
if (!(iss >> operand1 >> operand2)) throw std::runtime_error("语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
// 剥离中括号提取地址
if(operand1.front() == '[') operand1.erase(operand1.begin());
if(operand1.back() == ']') operand1.pop_back();
uint64_t addr = std::stoull(operand1, nullptr, 0);
int regIdx = getRegIndex(operand2);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand2);
binary.push_back(0x04);
for(int i=0;i<8;i++) binary.push_back(static_cast<uint8_t>((addr >> (i*8)) & 0xFF));
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "PUSH") {
std::string operand1;
iss >> operand1;
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
binary.push_back(0x50);
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "POP") {
std::string operand1;
iss >> operand1;
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("无效寄存器: " + operand1);
binary.push_back(0x51);
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "CALL") {
std::string operand;
iss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x60, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "RET") {
binary.push_back(0x61);
}
else {
throw std::runtime_error("未知指令: " + mnemonic);
}
}
g_vm->loadProgram(binary);
updateAll();
} catch (const std::exception& e) {
std::string errMsg = "汇编错误 (行 " + std::to_string(lineNum) + "): " + e.what();
MessageBox(g_hWndMain, errMsg.c_str(), "汇编错误", MB_ICONERROR);
}
}
void loadCodeFromEditor() {
if (!g_hWndCodeEditor) {
MessageBox(NULL, "代码编辑框未初始化", "错误", MB_OK | MB_ICONERROR);
return;
}
// 获取编辑框文本长度
int len = GetWindowTextLength(g_hWndCodeEditor);
if (len == 0) {
MessageBox(NULL, "编辑框内没有代码", "提示", MB_OK);
return;
}
// 替换原来的new char[] / delete[]写法
std::vector<char> tempBuf(len + 1, 0);
GetWindowText(g_hWndCodeEditor, tempBuf.data(), len + 1);
std::string code(tempBuf.data());
// 重置虚拟机:销毁旧实例新建全新干净的虚拟机
if (g_vm) delete g_vm;
g_vm = new VirtualMachine("vm_disk.img");
// 解析代码文本
std::vector<uint8_t> binary;
std::istringstream iss(code);
std::string line;
int lineNum = 0;
while (std::getline(iss, line)) {
lineNum++;
// 跳过空行和注释
if (line.empty() || line[0] == ';') continue;
// 去掉行尾注释
size_t commentPos = line.find(';');
if (commentPos != std::string::npos) {
line = line.substr(0, commentPos);
}
// 去掉首尾空格
while (!line.empty() && std::isspace(line.front())) line.erase(line.begin());
while (!line.empty() && std::isspace(line.back())) line.pop_back();
if (line.empty()) continue;
std::istringstream lineIss(line);
std::string mnemonic;
lineIss >> mnemonic;
// 转换为大写
for (auto& c : mnemonic) c = std::toupper(c);
// 补全所有和loadAssemblyFile一致的完整指令解析逻辑
if (mnemonic == "MOV") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) {
std::string err = "第" + std::to_string(lineNum) + "行语法错误";
throw std::runtime_error(err);
}
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器 " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x01, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器 " + operand2);
auto code = encodeDoubleReg(0x02, static_cast<uint8_t>(regIdx), static_cast<uint8_t>(regIdx2));
binary.insert(binary.end(), code.begin(), code.end());
}
}
else if (mnemonic == "ADD") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x10, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand2);
binary.push_back(0x11);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "SUB") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x12, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand2);
binary.push_back(0x13);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "MUL") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x14, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
throw std::runtime_error("第" + std::to_string(lineNum) + "行: MUL指令仅支持立即数操作数");
}
}
else if (mnemonic == "DIV") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x15, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
throw std::runtime_error("第" + std::to_string(lineNum) + "行: DIV指令仅支持立即数操作数");
}
}
else if (mnemonic == "CMP") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
if ((operand2[0] >= '0' && operand2[0] <= '9') || (operand2.size() >= 2 && operand2[0] == '0' && (operand2[1] == 'x' || operand2[1] == 'X'))) {
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x20, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
} else {
int regIdx2 = getRegIndex(operand2);
if (regIdx2 == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand2);
binary.push_back(0x21);
binary.push_back(static_cast<uint8_t>(regIdx));
binary.push_back(static_cast<uint8_t>(regIdx2));
}
}
else if (mnemonic == "JMP") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x30, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JE" || mnemonic == "JZ") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x31, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JNE" || mnemonic == "JNZ") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x32, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JG") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x33, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JL") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x34, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JGE") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x35, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "JLE") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x36, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "AND") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x40, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "OR") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x41, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "XOR") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
uint64_t imm = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x42, static_cast<uint8_t>(regIdx), imm);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "NOT") {
std::string operand1;
lineIss >> operand1;
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
binary.push_back(0x43);
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "LOAD") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
if(operand2.front() == '[') operand2.erase(operand2.begin());
if(operand2.back() == ']') operand2.pop_back();
uint64_t addr = std::stoull(operand2, nullptr, 0);
auto code = encodeRegImm64(0x03, static_cast<uint8_t>(regIdx), addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "STORE") {
std::string operand1, operand2;
if (!(lineIss >> operand1 >> operand2)) throw std::runtime_error("第" + std::to_string(lineNum) + "行语法错误");
if (!operand1.empty() && operand1.back() == ',') operand1.pop_back();
if(operand1.front() == '[') operand1.erase(operand1.begin());
if(operand1.back() == ']') operand1.pop_back();
uint64_t addr = std::stoull(operand1, nullptr, 0);
int regIdx = getRegIndex(operand2);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand2);
binary.push_back(0x04);
for(int i=0;i<8;i++) binary.push_back(static_cast<uint8_t>((addr >> (i*8)) & 0xFF));
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "PUSH") {
std::string operand1;
lineIss >> operand1;
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
binary.push_back(0x50);
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "POP") {
std::string operand1;
lineIss >> operand1;
int regIdx = getRegIndex(operand1);
if (regIdx == -1) throw std::runtime_error("第" + std::to_string(lineNum) + "行: 无效寄存器: " + operand1);
binary.push_back(0x51);
binary.push_back(static_cast<uint8_t>(regIdx));
}
else if (mnemonic == "CALL") {
std::string operand;
lineIss >> operand;
uint64_t addr = std::stoull(operand, nullptr, 0);
auto code = encodeJumpAddr(0x60, addr);
binary.insert(binary.end(), code.begin(), code.end());
}
else if (mnemonic == "RET") {
binary.push_back(0x61);
}
else if (mnemonic == "INT") {
std::string operand;
lineIss >> operand; // 修复为读取当前行输入流的INT操作数
uint8_t intNum = static_cast<uint8_t>(std::stoull(operand, nullptr, 0));
binary.push_back(0x7F); // 对应step里的通用中断入口opcode
binary.push_back(intNum);
}
else if (mnemonic == "HLT" || mnemonic == "HALT") {
binary.push_back(0x00);
}
else {
throw std::runtime_error("第" + std::to_string(lineNum) + "行: 未知指令 " + mnemonic);
}
}
// 加载二进制到虚拟机(使用VirtualMachine原生提供的loadProgram方法,彻底解决之前loadBinary不存在的问题)
g_vm->loadProgram(binary);
updateAll();
// 输出提示
std::string outputMsg = "已从编辑框加载 " + std::to_string(binary.size()) + " 字节机器码";
g_vm->addOutput(outputMsg);
updateOutput();
}
// 加载二进制文件
void loadBinaryFile(const std::string& filename) {
if (!g_vm) return;
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
MessageBox(g_hWndMain, "无法打开二进制文件", "错误", MB_ICONERROR);
return;
}
std::vector<uint8_t> binary((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
if (binary.empty()) {
MessageBox(g_hWndMain, "文件为空", "错误", MB_ICONERROR);
return;
}
try {
g_vm->loadProgram(binary);
updateAll();
} catch (const std::exception& e) {
MessageBox(g_hWndMain, e.what(), "加载失败", MB_ICONERROR);
}
}
// 窗口过程函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CREATE: {
// 寄存器视图
g_hWndRegisters = CreateWindowEx(0, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_READONLY | WS_VSCROLL ,
10, 10, 300, 200, hWnd, (HMENU)IDC_REGISTERS, g_hInst, NULL);
// 内存视图
g_hWndMemory = CreateWindowEx(0, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_READONLY | WS_VSCROLL,
320, 10, 620, 200, hWnd, (HMENU)IDC_MEMORY, g_hInst, NULL);
// 新增可编辑代码编辑区
g_hWndCodeEditor = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "; 在此处直接编写汇编代码", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE,
10, 220, 930, 200, hWnd, (HMENU)IDC_CODE, g_hInst, NULL);
// 输出日志窗口调整到下方
g_hWndOutput = CreateWindowEx(0, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_READONLY | WS_VSCROLL ,
10, 430, 930, 100, hWnd, (HMENU)IDC_OUTPUT, g_hInst, NULL);
// 状态栏
g_hWndStatus = CreateWindowEx(0, "STATIC", "状态: 就绪", WS_CHILD | WS_VISIBLE | SS_SIMPLE,
10, 540, 930, 20, hWnd, (HMENU)IDC_STATUS, g_hInst, NULL);
// 创建14号Consolas等宽字体
g_hCustomFont = CreateFont(
14, 0, 0, 0,
FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
"Consolas"
);
// 仅修改状态栏字体
SendMessage(g_hWndStatus, WM_SETFONT, (WPARAM)g_hCustomFont, TRUE);
// 可选:给所有显示控件统一使用自定义字体
SendMessage(g_hWndRegisters, WM_SETFONT, (WPARAM)g_hCustomFont, TRUE);
SendMessage(g_hWndMemory, WM_SETFONT, (WPARAM)g_hCustomFont, TRUE);
SendMessage(g_hWndOutput, WM_SETFONT, (WPARAM)g_hCustomFont, TRUE);
SendMessage(g_hWndCodeEditor, WM_SETFONT, (WPARAM)g_hCustomFont, TRUE);
// 注册快捷键
if (!RegisterHotKey(hWnd, HOTKEY_RUN_ID, 0, VK_F5))
MessageBox(hWnd, "F5热键注册失败,可能被其他程序占用", "提示", MB_OK);
if (!RegisterHotKey(hWnd, HOTKEY_STEP_ID, 0, VK_F10))
MessageBox(hWnd, "F10热键注册失败,可能被其他程序占用", "提示", MB_OK);
if (!RegisterHotKey(hWnd, HOTKEY_STOP_ID, MOD_SHIFT, VK_F5))
MessageBox(hWnd, "Shift+F5热键注册失败,可能被其他程序占用", "提示", MB_OK);
if (!RegisterHotKey(hWnd, HOTKEY_RUN_EDITOR_ID, MOD_CONTROL, VK_F5))
MessageBox(hWnd, "Ctrl+F5热键注册失败,可能被其他程序占用", "提示", MB_OK);
// 创建菜单
HMENU hMenu = CreateMenu();
HMENU hFileMenu = CreatePopupMenu();
AppendMenu(hFileMenu, MF_STRING, IDM_LOAD, "加载汇编文件");
AppendMenu(hFileMenu, MF_STRING, IDM_LOADBIN, "加载二进制文件");
AppendMenu(hFileMenu, MF_STRING, IDM_SAVEBIN, "导出二进制文件");
AppendMenu(hFileMenu, MF_SEPARATOR, 0, NULL);
AppendMenu(hFileMenu, MF_STRING, IDM_EXIT, "退出");
AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hFileMenu, "文件");
HMENU hRunMenu = CreatePopupMenu();
AppendMenu(hRunMenu, MF_STRING | (g_vm && g_vm->isRunning() ? MF_GRAYED : 0), IDM_RUN, "运行 (F5)");
AppendMenu(hRunMenu, MF_STRING, IDM_RUN_EDITOR_CODE, "导入编辑区代码\tCtrl+F5");
AppendMenu(hRunMenu, MF_STRING, IDM_STEP, "单步执行 (F10)");
AppendMenu(hRunMenu, MF_STRING, IDM_STOP, "停止 (Shift+F5)");
AppendMenu(hRunMenu, MF_STRING, IDM_RESET, "重置CPU");
AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hRunMenu, "执行");
SetMenu(hWnd, hMenu);
updateAll();
break;
}
case WM_HOTKEY: {
switch (wParam) {
case HOTKEY_RUN_ID:
if (g_vm && g_vm->isProgramLoaded() && !g_vm->isRunning()) {
g_vm->run();
updateAll();
}
break;
case HOTKEY_STEP_ID:
if (g_vm && g_vm->isProgramLoaded()) {
g_vm->step();
updateAll();
}
break;
case HOTKEY_STOP_ID:
if (g_vm && g_vm->isRunning()) {
g_vm->setRunning(false);
g_vm->addOutput("用户手动停止");
updateAll();
}
break;
case HOTKEY_RUN_EDITOR_ID:
SendMessage(hWnd, WM_COMMAND, IDM_RUN_EDITOR_CODE, 0);
break;
}
break;
}
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case IDM_LOAD: {
OPENFILENAME ofn = {0};
char szFile[260] = {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "汇编文件 (*.asm)\0*.asm\0所有文件 (*.*)\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn)) {
loadAssemblyFile(szFile);
}
break;
}
case IDM_LOADBIN: {
OPENFILENAME ofn = {0};
char szFile[260] = {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "二进制文件 (*.bin)\0*.bin\0所有文件 (*.*)\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn)) {
loadBinaryFile(szFile);
}
break;
}
case IDM_SAVEBIN: {
// 导出当前内存的一段区域为二进制
if (!g_vm || !g_vm->isProgramLoaded()) {
MessageBox(hWnd, "请先加载程序", "提示", MB_OK);
break;
}
OPENFILENAME ofn = {0};
char szFile[260] = {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "二进制文件 (*.bin)\0*.bin\0所有文件 (*.*)\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_PATHMUSTEXIST;
if (GetSaveFileName(&ofn)) {
std::ofstream outFile(szFile, std::ios::binary);
if (!outFile.is_open()) {
MessageBox(hWnd, "无法创建文件", "错误", MB_ICONERROR);
break;
}
// 默认导出从0x1000开始的1KB
uint64_t startAddr = 0x1000;
uint64_t size = 1024;
try {
for (uint64_t i = 0; i < size; i++) {
uint8_t byte = g_vm->getMemory().readByte(startAddr + i);
outFile.write(reinterpret_cast<const char*>(&byte), 1);
}
outFile.close();
g_vm->addOutput("已导出二进制文件: " + std::string(szFile));
updateAll();
} catch (const std::exception& e) {
MessageBox(hWnd, e.what(), "导出失败", MB_ICONERROR);
}
}
break;
}
case IDM_RUN:
if (g_vm && g_vm->isProgramLoaded() && !g_vm->isRunning()) {
g_vm->run();
updateAll();
}
break;
case IDM_STEP:
if (g_vm && g_vm->isProgramLoaded()) {
g_vm->step();
updateAll();
}
break;
case IDM_STOP:
if (g_vm && g_vm->isRunning()) {
g_vm->setRunning(false);
g_vm->addOutput("用户手动停止");
updateAll();
}
break;
case IDM_RESET:
if (g_vm) {
delete g_vm;
g_vm = nullptr;
}
try {
g_vm = new VirtualMachine("vm_disk.img");
updateAll();
} catch (const std::exception& e) {
MessageBox(hWnd, e.what(), "初始化失败", MB_OK | MB_ICONERROR);
return 0;
}
break;
case IDM_EXIT:
PostQuitMessage(0);
break;
case IDM_RUN_EDITOR_CODE:
try {
loadCodeFromEditor();
} catch (const std::exception& e) {
MessageBox(hWnd, e.what(), "汇编解析错误", MB_OK | MB_ICONERROR);
}
break;
}
break;
}
case WM_DESTROY:
UnregisterHotKey(hWnd, HOTKEY_RUN_ID);
UnregisterHotKey(hWnd, HOTKEY_STEP_ID);
UnregisterHotKey(hWnd, HOTKEY_STOP_ID);
UnregisterHotKey(hWnd, HOTKEY_RUN_EDITOR_ID);
// 新增释放自定义字体资源,避免GDI泄漏
if(g_hCustomFont != NULL) {
DeleteObject(g_hCustomFont);
g_hCustomFont = NULL;
}
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 程序入口点
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
g_hInst = hInstance;
// 初始化公共控件
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&icex);
// 创建虚拟机实例
try {
g_vm = new VirtualMachine("vm_disk.img");
} catch (const std::exception& e) {
MessageBox(NULL, e.what(), "初始化失败", MB_ICONERROR);
return 1;
}
// 注册窗口类
WNDCLASSEX wcex = {0};
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszClassName = "VirtualMachineClass";
if (!RegisterClassEx(&wcex)) {
MessageBox(NULL, "窗口注册失败", "错误", MB_ICONERROR);
return 1;
}
// 创建主窗口
g_hWndMain = CreateWindowEx(0, "VirtualMachineClass", "X64 虚拟机模拟器", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 1000, 700, NULL, NULL, hInstance, NULL);
if (!g_hWndMain) {
MessageBox(NULL, "窗口创建失败", "错误", MB_ICONERROR);
return 1;
}
ShowWindow(g_hWndMain, nCmdShow);
UpdateWindow(g_hWndMain);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
delete g_vm;
return (int)msg.wParam;
}