Feature: Basic GUI that displays hex information, register information, instruction information.

This commit is contained in:
0x221E
2026-02-06 19:20:42 +01:00
parent caadd2f706
commit 88721ee0da
29 changed files with 8476 additions and 91 deletions

View File

@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.10)
project(emulator CXX)
project(emulator C CXX)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@@ -7,6 +7,8 @@ set(CMAKE_CXX_STANDDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_subdirectory(external/glfw)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_definitions(Debug)
set(CMAKE_BUILD_TYPE Debug)
@@ -16,6 +18,17 @@ else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector")
endif()
file(GLOB_RECURSE SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
find_package(OpenGL REQUIRED)
add_executable(emulator ${SRC_FILES})
file(GLOB_RECURSE SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
file(GLOB IMGUI_SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/external/imgui/*.cpp")
add_executable(emulator ${SRC_FILES}
${CMAKE_CURRENT_SOURCE_DIR}/external/glad/src/glad.c ${IMGUI_SRC_FILES})
target_link_libraries(emulator PRIVATE glfw OpenGL::GL)
target_include_directories(emulator PRIVATE external/glfw/include
external/glad/include
external/imgui
external/imgui_club/imgui_memory_editor
)

View File

@@ -1,5 +1,7 @@
#include <stdio.h>
int main(void){
int a = 16;
printf("Hello!");
return 0;
}

311
external/glad/include/KHR/khrplatform.h vendored Normal file
View File

@@ -0,0 +1,311 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
/*
* To support platform where unsigned long cannot be used interchangeably with
* inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
* Ideally, we could just use (u)intptr_t everywhere, but this could result in
* ABI breakage if khronos_uintptr_t is changed from unsigned long to
* unsigned long long or similar (this results in different C++ name mangling).
* To avoid changes for existing platforms, we restrict usage of intptr_t to
* platforms where the size of a pointer is larger than the size of long.
*/
#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
#define KHRONOS_USE_INTPTR_T
#endif
#endif
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef KHRONOS_USE_INTPTR_T
typedef intptr_t khronos_intptr_t;
typedef uintptr_t khronos_uintptr_t;
#elif defined(_WIN64)
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
#endif
#if defined(_WIN64)
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */

5169
external/glad/include/glad/glad.h vendored Normal file

File diff suppressed because it is too large Load Diff

2532
external/glad/src/glad.c vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
#include "Arithmetic.h"
#include "ExecutorCases.h"
#include "CPUContext.h"
#include "Instruction.h"
#include "Bus.h"
@@ -25,6 +26,30 @@ namespace executor_cases {
}
std::cout << std::endl;
}
// TODO: Finish the function
void Add_r32_rm32(CPUContext& cc){
// x86::ModRM modrm = cc.m_Instruction.optional.m_ModRM;
// std::cout << "[Instruction] ";
// switch(modrm.m_State) {
// case x86::ModRMState::R:
// cc.m_Registers[modrm.m_Reg] += cc.m_Registers[modrm.m_Rm];
// std::cout << "add " << x86::Register2Str((x86::Register)modrm.m_Reg) << ", " << x86::Register2Str((x86::Register)modrm.m_Rm);
// break;
// default:
// uint32_t dstAddress = ;ResolveModRMAddress(cc);
// uint32_t dstPrevValue = cc.m_Bus->AccessX<uint32_t>(dstAddress);
// uint32_t currRegValue = cc.m_Registers[cc.m_Instruction.optional.m_ModRM.m_Reg];
// uint32_t result = dstPrevValue + currRegValue;
// std::cout << "add DWORD PTR [0x" << helpers::ResolveModRMAddress(cc) << "], " << x86::Register2Str((x86::Register)modrm.m_Reg);
// break;
// }
// std::cout << std::endl;
std::runtime_error("Not implemented!");
}
namespace helpers {

View File

@@ -6,10 +6,9 @@ struct CPUContext;
namespace executor_cases {
void Add_rm32_r32(CPUContext& cc);
void Add_r32_rm32(CPUContext& cc); //TODO: Finish
namespace helpers {
void Add_rm_dst(CPUContext& cc, uint32_t address);
}
}

View File

@@ -2,9 +2,6 @@
#include <stdexcept>
Bus::Bus() {
for(int i = 0; i < 992 * 1024; i++)
{
m_RAM[i] = 0x90;
}
Bus::Bus(std::shared_ptr<RAM> ram) : m_RAM(ram) {
}

View File

@@ -5,10 +5,13 @@
#include <type_traits>
#include <stdexcept>
#include <cstring>
#include <memory>
#include "RAM.h"
class Bus {
public:
Bus();
Bus(std::shared_ptr<RAM> m_Bus);
~Bus() = default;
public:
@@ -24,7 +27,7 @@ public:
case 0x00008000 ... 0x000FFFFF:
{
uint64_t offset = address - 0x00008000;
std::memcpy(&m_RAM[offset], &value, sizeof(T));
std::memcpy(&m_RAM->Data()[offset], &value, sizeof(T));
break;
}
default:
@@ -45,7 +48,7 @@ public:
{
uint64_t offset = address - 0x00008000;
T value;
std::memcpy(&value, &m_RAM[offset], sizeof(T));
std::memcpy(&value, &m_RAM->Data()[offset], sizeof(T));
return value;
}
default:
@@ -54,5 +57,5 @@ public:
}
private:
uint8_t m_RAM[992 * 1024];
std::shared_ptr<RAM> m_RAM;
};

View File

@@ -8,7 +8,7 @@
#include <array>
#include <cassert>
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}) {
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}) {
m_InstructionPointer = 0x00008000;
for(int i = 0; i < 8; i++)
@@ -44,6 +44,28 @@ void CPU::Dump() {
std::cout << std::endl;
}
void CPU::Reset() {
for(uint8_t i = 0; i < 8; i++)
{
m_Registers[i] = 0;
m_SegmentRegisters[i] = 0;
}
m_InstructionPointer = 0x8000;
m_Flags = 0;
std::cout << "[CPU] State Flushed!" << std::endl;
m_IsHalted = false;
m_Instruction.m_Opcode = (Opcode)0;
m_Instruction.m_Operand1 = 0;
m_Instruction.m_Operand2 = 0;
std::memset(m_Instruction.m_Displacement, 0, 4);
m_Instruction.optional.m_ModRM = (x86::ModRM){ .m_State = x86::ModRMState::INVALID, .m_Reg = 0, .m_Rm = 0 };
}
CPUStatus CPU::GetStatus() {
return (CPUStatus){.m_Registers = m_Registers, .m_IP = m_InstructionPointer, .m_Instruction = m_Instruction};
}
void CPU::FetchDecode() {
uint8_t opcode_raw = m_Bus->AccessX<uint8_t>(m_InstructionPointer);
Opcode opcode = static_cast<Opcode>(opcode_raw);
@@ -83,7 +105,6 @@ void CPU::Execute() {
if(exec_table[opcode_value])
{
exec_table[opcode_value](m_Context);
Dump();
return;
}
throw std::runtime_error("Opcode not found!");
@@ -98,11 +119,16 @@ void CPU::FetchModRMFields() {
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);
{
uint32_t disp = m_Bus->AccessX<uint32_t>(m_InstructionPointer + m_Instruction.m_Length);
std::memcpy(&m_Instruction.m_Displacement, &disp, 4);
m_Instruction.m_DisplacementSize = 4;
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_Displacement[0] = m_Bus->AccessX<uint8_t>(m_InstructionPointer + m_Instruction.m_Length);
m_Instruction.m_DisplacementSize = 1;
m_Instruction.m_Length += 1;
break;
default:

View File

@@ -6,18 +6,28 @@
#include "Instruction.h"
#include "Bus.h"
#include "ExecutorCases.h"
#include "CPUContext.h"
struct CPUStatus {
uint32_t* m_Registers;
uint32_t& m_IP;
Instruction& m_Instruction;
};
class CPU {
public:
CPU(std::shared_ptr<Bus> bus);
CPU(std::shared_ptr<Bus>& bus);
~CPU() = default;
public:
void Step();
void Dump();
void Reset();
bool IsHalted() { return m_IsHalted; }
CPUStatus GetStatus();
private:
void FetchDecode();

5
src/CPUContext.cpp Normal file
View File

@@ -0,0 +1,5 @@
#include "CPUContext.h"
CPUContext::CPUContext(Instruction& i, uint32_t& ip, uint32_t& flags, uint32_t* reg, std::shared_ptr<Bus>& bus, bool& isHalted) : m_Instruction(i), m_InstructionPointer(ip), m_Flags(flags), m_Registers(reg), m_Bus(bus), m_IsHalted(isHalted) { }
CPUContext::~CPUContext() = default;

19
src/CPUContext.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
struct Instruction;
struct Bus;
#include <cstdint>
#include <memory>
struct CPUContext {
Instruction& m_Instruction;
uint32_t& m_InstructionPointer;
uint32_t& m_Flags;
uint32_t* m_Registers;
std::shared_ptr<Bus> m_Bus;
bool& m_IsHalted;
CPUContext(Instruction& i, uint32_t& ip, uint32_t& flags, uint32_t* reg, std::shared_ptr<Bus>& bus, bool& isHalted);
~CPUContext();
};

View File

@@ -1,6 +1,7 @@
#include "ControlFlow.h"
#include "ExecutorCases.h"
#include "CPUContext.h"
#include <iostream>

View File

@@ -2,6 +2,7 @@
#include "ExecutorCases.h"
#include "Instruction.h"
#include "CPUContext.h"
#include "Bus.h"
#include <iostream>

View File

@@ -6,15 +6,12 @@
#include "Misc.h"
#include "Instruction.h"
#include "CPUContext.h"
#include "Bus.h"
#include <bitset>
#include <iostream>
CPUContext::CPUContext(Instruction& i, uint32_t& ip, uint32_t& flags, uint32_t* reg, std::shared_ptr<Bus>& bus, bool& isHalted) : m_Instruction(i), m_InstructionPointer(ip), m_Flags(flags), m_Registers(reg), m_Bus(bus), m_IsHalted(isHalted) { }
CPUContext::~CPUContext() = default;
constexpr std::array<ExecutorCase, 255> GenerateExecutorTable(){
std::array<ExecutorCase, 255> table{};
table[Opcode::NOP] = executor_cases::Nop;
@@ -22,6 +19,7 @@ constexpr std::array<ExecutorCase, 255> GenerateExecutorTable(){
table[Opcode::MOV_R32_IMM32] = executor_cases::Mov_r32_imm32;
table[Opcode::MOV_RM32_R32] = executor_cases::Mov_rm32_r32;
table[Opcode::ADD_RM32_R32] = executor_cases::Add_rm32_r32;
table[Opcode::ADD_R32_RM32] = executor_cases::Add_r32_rm32;
return table;
}
@@ -40,10 +38,10 @@ namespace executor_cases::helpers {
switch(modrm.m_State) {
case x86::ModRMState::LR_DISP32:
case x86::ModRMState::LR_DISP8:
value = cc.m_Registers[modrm.m_Rm] + cc.m_Instruction.m_Operand1;
value = cc.m_Registers[modrm.m_Rm] + cc.m_Instruction.m_Displacement[0];
break;
case x86::ModRMState::DISP32:
value = cc.m_Instruction.m_Operand1;
std::memcpy(&value, &cc.m_Instruction.m_Displacement, 4);
break;
case x86::ModRMState::LR:
value = cc.m_Registers[modrm.m_Rm];

View File

@@ -4,20 +4,7 @@
#include <memory>
#include <array>
struct Instruction;
class Bus;
struct CPUContext {
Instruction& m_Instruction;
uint32_t& m_InstructionPointer;
uint32_t& m_Flags;
uint32_t* m_Registers;
std::shared_ptr<Bus> m_Bus;
bool& m_IsHalted;
CPUContext(Instruction& i, uint32_t& ip, uint32_t& flags, uint32_t* reg, std::shared_ptr<Bus>& bus, bool& isHalted);
~CPUContext();
};
struct CPUContext;
typedef void (*ExecutorCase)(CPUContext&);

136
src/GUI.cpp Normal file
View File

@@ -0,0 +1,136 @@
#include "GUI.h"
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <imgui_memory_editor.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <cstdlib>
#include <iostream>
#include "Userspace.h"
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
return;
}
}
GUI::GUI(Userspace& user) :m_Userspace(user) {
if(!glfwInit())
exit(1);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
CreateWindow();
}
void GUI::CreateWindow() {
m_Window = glfwCreateWindow(1020, 640, "CPUSecX86", NULL, NULL);
if(!m_Window)
{
glfwTerminate();
return;
}
glfwMakeContextCurrent(m_Window);
glfwSetKeyCallback(m_Window, key_callback);
ImGui::CreateContext();
int version = gladLoadGL();
std::cout << "OpenGL Version: " << std::dec << version << std::endl;
ImGui_ImplGlfw_InitForOpenGL(m_Window, true);
ImGui_ImplOpenGL3_Init("#version 460");
ImGuiIO& io = ImGui::GetIO();
io.FontGlobalScale = 2.0f;
}
void GUI::Run() {
while (!glfwWindowShouldClose(m_Window))
{
glfwPollEvents();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ControlGUI();
DebugInfoGUI();
static MemoryEditor process_mem;
size_t data_size = 0x10000;
process_mem.DrawWindow("Process Memory", m_Userspace.RetrieveMemory(), data_size);
glClear(GL_COLOR_BUFFER_BIT);
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(m_Window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void GUI::Terminate() {
glfwDestroyWindow(m_Window);
glfwTerminate();
}
void GUI::ControlGUI() {
ImGui::Begin("Emulator Control");
ImGui::Text("Current State: %s", m_Userspace.IsRunning() ? "Running" : "Stopped");
if(ImGui::Button("Start"))
m_Userspace.Start();
ImGui::SameLine();
if(ImGui::Button("Stop"))
m_Userspace.Stop();
ImGui::SameLine();
if (ImGui::Button("Reset"))
m_Userspace.Reset();
if(ImGui::Button("Step"))
m_Userspace.Step();
ImGui::End();
}
void GUI::DebugInfoGUI() {
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal;
if (m_Userspace.IsRunning()) flags |= ImGuiInputTextFlags_ReadOnly;
CPUStatus status = m_Userspace.GetCPUStatus();
ImGui::Begin("Debug Information");
ImGui::Text("GP Registers");
ImGui::InputScalar("EAX", ImGuiDataType_U32, &status.m_Registers[0], NULL, NULL, "%08X", flags);
ImGui::InputScalar("ECX", ImGuiDataType_U32, &status.m_Registers[1], NULL, NULL, "%08X", flags);
ImGui::InputScalar("EDX", ImGuiDataType_U32, &status.m_Registers[2], NULL, NULL, "%08X", flags);
ImGui::InputScalar("EBX", ImGuiDataType_U32, &status.m_Registers[3], NULL, NULL, "%08X", flags);
ImGui::InputScalar("ESP", ImGuiDataType_U32, &status.m_Registers[4], NULL, NULL, "%08X", flags);
ImGui::InputScalar("EBP", ImGuiDataType_U32, &status.m_Registers[5], NULL, NULL, "%08X", flags);
ImGui::InputScalar("ESI", ImGuiDataType_U32, &status.m_Registers[6], NULL, NULL, "%08X", flags);
ImGui::InputScalar("EDI", ImGuiDataType_U32, &status.m_Registers[7], NULL, NULL, "%08X", flags);
ImGui::Separator();
ImGui::Text("Other Registers");
ImGui::InputScalar("IP", ImGuiDataType_U32, &status.m_IP, NULL, NULL, "%08X", flags);
ImGui::Separator();
ImGui::Text("Instruction Information");
ImGui::Text("Instruction Length: %d", status.m_Instruction.m_Length);
ImGui::Text("Opcode: %s", Opcode2Str(status.m_Instruction.m_Opcode).c_str());
ImGui::Text("Operand1: %x", status.m_Instruction.m_Operand1);
ImGui::Text("Operand2: %x", status.m_Instruction.m_Operand2);
ImGui::Text("ModRM R/M: %d", status.m_Instruction.optional.m_ModRM.m_Rm);
ImGui::Text("ModRM R: %d", status.m_Instruction.optional.m_ModRM.m_Reg);
ImGui::Text("ModRM Status: %d", status.m_Instruction.optional.m_ModRM.m_State);
ImGui::End();
}
GUI::~GUI() {
Terminate();
}

23
src/GUI.h Normal file
View File

@@ -0,0 +1,23 @@
#pragma once
struct GLFWwindow;
struct Userspace;
class GUI {
public:
GUI(Userspace& user);
~GUI();
void Run();
private:
void CreateWindow();
void Terminate();
void ControlGUI();
void DebugInfoGUI();
private:
GLFWwindow* m_Window;
Userspace& m_Userspace;
};

View File

@@ -53,10 +53,15 @@ namespace x86 {
std::string Opcode2Str(Opcode op) {
switch(op) {
case 0: return "EMPTY";
case Opcode::ADD_RM32_R32: return "ADD_RM32_R32";
case Opcode::ADD_R32_RM32: return "ADD_R32_RM32";
case Opcode::MOV_R32_IMM32: return "MOV_R32_IMM32";
case Opcode::MOV_RM32_R32: return "MOV_RM32_R32";
case Opcode::NOP: return "NOP";
case Opcode::HLT: return "HLT";
}
throw std::runtime_error("Opcode Invalid!");
std::string what = "Opcode '" + std::to_string(op) + "' invalid!";
throw std::runtime_error(what);
}

View File

@@ -39,6 +39,7 @@ enum Opcode : uint8_t {
MOV_R32_IMM32 = 0xB8,
MOV_RM32_R32 = 0x89,
ADD_RM32_R32 = 0x01,
ADD_R32_RM32 = 0x03,
};
std::string Opcode2Str(Opcode op);
@@ -48,8 +49,9 @@ struct Instruction{
size_t m_Length;
uint32_t m_Operand1;
uint32_t m_Operand2;
// uint8_t m_Displacement[];
union {
x86::ModRM m_ModRM;
} optional;
uint8_t m_Displacement[4];
uint8_t m_DisplacementSize;
};

View File

@@ -1,20 +0,0 @@
#include "Metal.h"
#include "Bus.h"
Metal::Metal() : m_Bus(std::make_shared<Bus>()), m_CPU(m_Bus) { }
void Metal::Upload2Memory(uint8_t bytes[], size_t len) {
uint64_t start = 0x00008000;
for (size_t i = 0; i < len; i++) {
m_Bus->WriteX<uint8_t>(start + i, bytes[i]);
std::cout << "Written " << std::hex << bytes[i] << " to " << std::hex << start + i << std::endl;
}
}
void Metal::Run() {
m_Running = true;
while(m_Running && !m_CPU.IsHalted()) {
m_CPU.Step();
}
}

View File

@@ -1,22 +0,0 @@
#pragma once
class Bus;
#include <cstdint>
#include <memory>
#include "CPU.h"
class Metal {
public:
Metal();
~Metal() = default;
void Upload2Memory(uint8_t bytes[], size_t len);
void Run();
private:
std::shared_ptr<Bus> m_Bus;
CPU m_CPU;
bool m_Running = false;
};

View File

@@ -1,6 +1,7 @@
#include "Misc.h"
#include "ExecutorCases.h"
#include "CPUContext.h"
#include <iostream>

12
src/RAM.cpp Normal file
View File

@@ -0,0 +1,12 @@
#include "RAM.h"
RAM::RAM() {
for(int i = 0; i < 992 * 1024; i++)
{
m_Memory[i] = 0x90;
}
}
uint8_t* RAM::Data() {
return m_Memory;
}

14
src/RAM.h Normal file
View File

@@ -0,0 +1,14 @@
#pragma once
#include <cstdint>
class RAM {
public:
RAM();
~RAM() = default;
uint8_t* Data();
private:
uint8_t m_Memory[992 * 1024];
};

85
src/Userspace.cpp Normal file
View File

@@ -0,0 +1,85 @@
#include "Userspace.h"
#include "Bus.h"
#include "RAM.h"
#include <thread>
Userspace::Userspace() : m_RAM(std::make_shared<RAM>()),m_ProgramMemory(std::make_shared<RAM>()), m_Bus(std::make_shared<Bus>(m_RAM)), m_CPU(m_Bus) {
std::cout << "[Userspace] Emulation started." << std::endl;
m_ApplicationRunning = true;
m_Running = false;
}
void Userspace::Upload2Memory(uint8_t bytes[], size_t len) {
m_ProgramMemoryLen = len;
std::memcpy(m_RAM->Data(), bytes, len);
std::memcpy(m_ProgramMemory->Data(), bytes, len);
}
uint8_t* Userspace::RetrieveMemory() {
return m_RAM->Data();
}
void Userspace::Run() {
while(m_ApplicationRunning) {
EmulatorLoop();
}
}
void Userspace::EmulatorLoop() {
while(m_Running) {
if(!m_CPU.IsHalted()) {
m_CPU.Step();
}
if (m_CPU.IsHalted()) {
if(m_Running)
m_Running = false;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
if(!m_Running)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void Userspace::Reset() {
if(m_CPU.IsHalted()) m_Running = false;
m_CPU.Reset();
std::memcpy(m_RAM->Data(), m_ProgramMemory->Data(), m_ProgramMemoryLen);
}
void Userspace::Start() {
m_Running = true;
}
void Userspace::Step() {
if(!m_CPU.IsHalted())
{
m_CPU.Step();
std::cout << "[Userspace] CPU stepped!" << std::endl;
}
else
{
std::cout << "[Userspace] CPU is halted! Cannot step." << std::endl;
}
}
void Userspace::Stop() {
m_Running = false;
std::cout << "[Userspace] Emulation stopped." << std::endl;
}
void Userspace::Exit() {
m_Running = false;
m_ApplicationRunning = false;
std::cout << "[Userspace] Emulation exited." << std::endl;
}
bool Userspace::IsRunning() {
return m_Running;
}
CPUStatus Userspace::GetCPUStatus() {
return m_CPU.GetStatus();
}

42
src/Userspace.h Normal file
View File

@@ -0,0 +1,42 @@
#pragma once
class Bus;
#include <cstdint>
#include <memory>
#include <atomic>
#include "CPU.h"
class Userspace {
public:
Userspace();
~Userspace() = default;
void Upload2Memory(uint8_t bytes[], size_t len);
uint8_t* RetrieveMemory();
void Run();
void Start();
void Stop();
void Step();
void Reset();
void Exit();
bool IsRunning();
CPUStatus GetCPUStatus();
private:
std::shared_ptr<RAM> m_RAM;
std::shared_ptr<Bus> m_Bus;
CPU m_CPU;
std::atomic<bool> m_Running = false;
std::atomic<bool> m_ApplicationRunning = false;
std::shared_ptr<RAM> m_ProgramMemory;
size_t m_ProgramMemoryLen;
private:
void EmulatorLoop();
};

View File

@@ -1,26 +1,35 @@
#include <iostream>
#include "Metal.h"
#include "Userspace.h"
#include "GUI.h"
#include <thread>
// nop
// mov eax, 0xF4
// mov ecx, 0x8000
// mov edx, 0x8000
// mov [edx], eax
// add DWORD PTR [0x8011], eax
uint8_t test[] = {
0x90,
0xB8, 0xF4, 0x00, 0x00, 0x00,
0xB9, 0x00, 0x80, 0x00, 0x00,
0xBA, 0x00, 0x80, 0x00, 0x00,
0x89, 0x02,
0x01, 0x05, 0x18, 0x80, 0x00, 0x00,
0x01, 0x05, 0x16, 0x80, 0x00, 0x00,
0x00,
};
int main(int argc, char** argv) {
Metal metal;
metal.Upload2Memory(test, 25);
metal.Run();
Userspace user;
GUI gui(user);
user.Upload2Memory(test, 23);
std::thread tuserspace(&Userspace::Run, &user);
gui.Run();
user.Exit();
tuserspace.join();
return 0;
}