gbemu/lib/cpu.c

64 lines
1.5 KiB
C
Raw Normal View History

2025-01-30 14:30:19 -07:00
#include <cpu.h>
2025-01-30 16:27:27 -07:00
#include <bus.h>
cpu_context ctx = {0};
2025-01-30 14:30:19 -07:00
void cpu_init() {
2025-01-30 16:27:27 -07:00
ctx.regs.pc = 0x100;
}
static void fetch_instruction() {
ctx.cur_opcode = bus_read(ctx.regs.pc++);
ctx.cur_inst = instruction_by_opcode(ctx.cur_opcode);
if(ctx.cur_inst == NULL){
printf("Unknown Instruction! %d\n", ctx.cur_opcode);
exit(-7);
}
}
2025-01-30 14:30:19 -07:00
2025-01-30 16:27:27 -07:00
static void fetch_data() {
ctx.mem_dest = 0;
ctx.dest_is_mem = false;
switch(ctx.cur_inst->mode) {
case AM_IMP: return;
case AM_R:
ctx.fetched_data = cpu_read_reg(ctx.cur_inst->reg_1);
return;
case AM_R_D8:
ctx.fetched_data = bus_read(ctx.regs.pc);
emu_cycles(1);
ctx.regs.pc++;
return;
case AM_D16: {
u16 lo = bus_read(ctx.regs.pc);
emu_cycles(1);
u16 hi = bus_read(ctx.regs.pc+1);
emu_cycles(1);
ctx.fetched_data = lo | (hi << 8);
ctx.regs.pc += 2;
return;
}
default:
printf("Unknown Addressing Mode! %d\n", ctx.cur_inst->mode);
exit(-7);
return;
}
}
static void execute() {
printf("\tNot executing yet...\n");
2025-01-30 14:30:19 -07:00
}
bool cpu_step() {
2025-01-30 16:27:27 -07:00
if(!ctx.halted) {
u16 pc = ctx.regs.pc;
fetch_instruction();
fetch_data();
printf("Executing Instruction: %02X PC: %04X\n", ctx.cur_opcode, pc);
execute();
}
return true;
2025-01-30 14:30:19 -07:00
}