Compare commits

...

15 Commits

Author SHA1 Message Date
Rekai Nyangadzayi Musuka 6bac543b30 fix: account for pipeline in obscure bios behaviour 2022-09-12 23:36:11 -03:00
Rekai Nyangadzayi Musuka 42b0a5dfc6 chore: update README.md 2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka f9954b346d fix: advance r15, even when the pipeline is reloaded from the scheduler
The PC would fall behind whenever an IRQ was called because the pipeline
was reloaded (+8 to PC), however that was never actually done by any code

Now, the PC is always incremented when the pipeline is reloaded
2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka a57b44bc5c chore: dump pipeline state on cpu panic 2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka d1970fb71f fix: reimpl THUMB.5 instructions
pipeline branch now passes arm.gba and thumb.gba again

(TODO: Stop rewriting my commits away)
2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka 4339126bee fix: impl workaround for stage2 miscompilation 2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka 57a6273025 chore: instantly refill the pipeline on flush
I believe this to be necessary in order to get hardware interrupts
working.

thumb.gba test 108 fails but I'm committing anyways (despite the
regression) because this is kind of rebase/merge hell and I have
something that at least sort of works rn
2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka ee4bb9929f fix: reimpl handleInterrupt code 2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka 7d76308ed0 feat: implement basic pipeline
passes arm.gba, thumb.gb and armwrestler, fails in actual games
TODO: run FuzzARM debug specific titles
2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka 25b4112b32 feat: resolve off-by-{word, halfword} errors when printing debug info 2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka 19b3346464 feat: reimplement cpu logging 2022-09-12 23:23:25 -03:00
Rekai Nyangadzayi Musuka 59c9ff910e feat: implement open bus for unmapped i/o 2022-09-12 23:18:29 -03:00
Rekai Nyangadzayi Musuka 0027d3f8a3 chore: comment open bus impl 2022-09-11 07:38:55 -03:00
Rekai Nyangadzayi Musuka 9f45888910 chore: update dependencies 2022-09-11 06:59:10 -03:00
Rekai Nyangadzayi Musuka bf442d5a40 chore: Update README.md 2022-09-10 07:34:52 -03:00
23 changed files with 565 additions and 265 deletions

View File

@ -1,17 +1,16 @@
# ZBA (working title)
An in-progress Gameboy Advance Emulator written in Zig ⚡!
An in-progress Game Boy Advance Emulator written in Zig ⚡!
## Tests
- [ ] [jsmolka's GBA Test Collection](https://github.com/jsmolka/gba-tests)
- [x] [jsmolka's GBA Test Collection](https://github.com/jsmolka/gba-tests)
- [x] `arm.gba` and `thumb.gba`
- [x] `flash64.gba`, `flash128.gba`, `none.gba`, and `sram.gba`
- [x] `hello.gba`, `shades.gba`, and `stripes.gba`
- [x] `memory.gba`
- [x] `bios.gba`
- [ ] `nes.gba`
- [x] `nes.gba`
- [ ] [DenSinH's GBA ROMs](https://github.com/DenSinH/GBARoms)
- [x] `eeprom-test`
- [x] `flash-test`
- [x] `eeprom-test` and `flash-test`
- [x] `midikey2freq`
- [ ] `swi-tests-random`
- [ ] [destoer's GBA Tests](https://github.com/destoer/gba_tests)
@ -36,14 +35,14 @@ An in-progress Gameboy Advance Emulator written in Zig ⚡!
* [ARM7TDMI Data Sheet](https://www.dca.fee.unicamp.br/cursos/EA871/references/ARM/ARM7TDMIDataSheet.pdf)
## Compiling
Most recently built on Zig [0.10.0-dev.2978+803376708](https://github.com/ziglang/zig/tree/803376708)
Most recently built on Zig [0.10.0-dev.3900+ab4b26d8a](https://github.com/ziglang/zig/tree/ab4b26d8a)
### Dependencies
* [SDL.zig](https://github.com/MasterQ32/SDL.zig)
* [SDL2](https://www.libsdl.org/download-2.0.php)
* [zig-clap](https://github.com/Hejsil/zig-clap)
* [known-folders](https://github.com/ziglibs/known-folders)
* [`bitfields.zig`](https://github.com/FlorenceOS/Florence/blob/f6044db788d35d43d66c1d7e58ef1e3c79f10d6f/lib/util/bitfields.zig)
* [`bitfields.zig`](https://github.com/FlorenceOS/Florence/blob/aaa5a9e568197ad24780ec9adb421217530d4466/lib/util/bitfields.zig)
`bitfields.zig` from [FlorenceOS](https://github.com/FlorenceOS) is included under `lib/util/bitfield.zig`.

@ -1 +1 @@
Subproject commit d66925011971fbe221fc2a7f7cb4cd8c181d9ba3
Subproject commit 76ec54bf1d13170f1a9998063eecf8087856541a

View File

@ -88,7 +88,7 @@ pub fn dbgRead(self: *const Self, comptime T: type, address: u32) T {
},
0x02 => self.ewram.read(T, aligned_addr),
0x03 => self.iwram.read(T, aligned_addr),
0x04 => io.read(self, T, aligned_addr),
0x04 => self.readIo(T, address),
// Internal Display Memory
0x05 => self.ppu.palette.read(T, aligned_addr),
@ -113,31 +113,46 @@ pub fn dbgRead(self: *const Self, comptime T: type, address: u32) T {
};
}
fn readIo(self: *const Self, comptime T: type, unaligned_address: u32) T {
const maybe_value = io.read(self, T, forceAlign(T, unaligned_address));
return if (maybe_value) |value| value else self.readOpenBus(T, unaligned_address);
}
fn readOpenBus(self: *const Self, comptime T: type, address: u32) T {
const r15 = self.cpu.?.r[15];
const word = if (self.cpu.?.cpsr.t.read()) blk: {
const word = blk: {
// If u32 Open Bus, read recently fetched opcode (PC + 8)
if (!self.cpu.?.cpsr.t.read()) break :blk self.dbgRead(u32, r15 + 4);
const page = @truncate(u8, r15 >> 24);
switch (page) {
// EWRAM, PALRAM, VRAM, and Game ROM (16-bit)
0x02, 0x05, 0x06, 0x08...0x0D => {
// (PC + 4)
const halfword = self.dbgRead(u16, r15 + 2);
break :blk @as(u32, halfword) << 16 | halfword;
},
// BIOS or OAM (32-bit)
0x00, 0x07 => {
// Aligned: (PC + 6) | (PC + 4)
// Unaligned: (PC + 4) | (PC + 2)
const offset: u32 = if (address & 3 == 0b00) 2 else 0;
break :blk @as(u32, self.dbgRead(u16, (r15 + 2) + offset)) << 16 | self.dbgRead(u16, r15 + offset);
break :blk @as(u32, self.dbgRead(u16, r15 + 2 + offset)) << 16 | self.dbgRead(u16, r15 + offset);
},
// IWRAM (16-bit but special)
0x03 => {
// Aligned: (PC + 2) | (PC + 4)
// Unaligned: (PC + 4) | (PC + 2)
const offset: u32 = if (address & 3 == 0b00) 2 else 0;
break :blk @as(u32, self.dbgRead(u16, (r15 + 2) - offset)) << 16 | self.dbgRead(u16, r15 + offset);
break :blk @as(u32, self.dbgRead(u16, r15 + 2 - offset)) << 16 | self.dbgRead(u16, r15 + offset);
},
else => unreachable,
}
} else self.dbgRead(u32, r15 + 4);
};
return @truncate(T, rotr(u32, word, 8 * (address & 3)));
}
@ -158,7 +173,7 @@ pub fn read(self: *Self, comptime T: type, address: u32) T {
},
0x02 => self.ewram.read(T, aligned_addr),
0x03 => self.iwram.read(T, aligned_addr),
0x04 => io.read(self, T, aligned_addr),
0x04 => self.readIo(T, address),
// Internal Display Memory
0x05 => self.ppu.palette.read(T, aligned_addr),

View File

@ -1,6 +1,7 @@
const std = @import("std");
const SDL = @import("sdl2");
const io = @import("bus/io.zig");
const util = @import("util.zig");
const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
const Scheduler = @import("scheduler.zig").Scheduler;
@ -9,13 +10,11 @@ const SoundFifo = std.fifo.LinearFifo(u8, .{ .Static = 0x20 });
const AudioDeviceId = SDL.SDL_AudioDeviceID;
const intToBytes = @import("util.zig").intToBytes;
const readUndefined = @import("util.zig").readUndefined;
const writeUndefined = @import("util.zig").writeUndefined;
const log = std.log.scoped(.APU);
pub const host_sample_rate = 1 << 15;
pub fn read(comptime T: type, apu: *const Apu, addr: u32) T {
pub fn read(comptime T: type, apu: *const Apu, addr: u32) ?T {
const byte = @truncate(u8, addr);
return switch (T) {
@ -38,7 +37,7 @@ pub fn read(comptime T: type, apu: *const Apu, addr: u32) T {
0x84 => apu.getSoundCntX(),
0x88 => apu.bias.raw, // SOUNDBIAS
0x90...0x9F => apu.ch3.wave_dev.read(T, apu.ch3.select, addr),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
},
u8 => switch (byte) {
0x60 => apu.ch1.getSoundCntL(), // NR10
@ -52,9 +51,9 @@ pub fn read(comptime T: type, apu: *const Apu, addr: u32) T {
0x81 => @truncate(u8, apu.psg_cnt.raw >> 8), // NR51
0x84 => apu.getSoundCntX(),
0x89 => @truncate(u8, apu.bias.raw >> 8), // SOUNDBIAS_H
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
},
u32 => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
u32 => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => @compileError("APU: Unsupported read width"),
};
}
@ -78,7 +77,7 @@ pub fn write(comptime T: type, apu: *Apu, addr: u32, value: T) void {
0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value),
0xA0 => apu.chA.push(value), // FIFO_A
0xA4 => apu.chB.push(value), // FIFO_B
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
},
u16 => switch (byte) {
0x60 => apu.ch1.setSoundCntL(@truncate(u8, value)), // SOUND1CNT_L
@ -101,7 +100,7 @@ pub fn write(comptime T: type, apu: *Apu, addr: u32, value: T) void {
0x88 => apu.bias.raw = value, // SOUNDBIAS
// WAVE_RAM
0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value),
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
},
u8 => switch (byte) {
0x60 => apu.ch1.setSoundCntL(value),
@ -133,7 +132,7 @@ pub fn write(comptime T: type, apu: *Apu, addr: u32, value: T) void {
0x84 => apu.setSoundCntX(value >> 7 & 1 == 1), // NR52
0x89 => apu.setSoundBiasH(value),
0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value),
else => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
},
else => @compileError("APU: Unsupported write width"),
}

View File

@ -39,12 +39,12 @@ pub fn read(self: *Self, comptime T: type, r15: u32, addr: u32) T {
}
log.debug("Rejected read since r15=0x{X:0>8}", .{r15});
return @truncate(T, self.uncheckedRead(T, self.addr_latch + 8));
return @truncate(T, self.uncheckedRead(T, self.addr_latch));
}
pub fn dbgRead(self: *const Self, comptime T: type, r15: u32, addr: u32) T {
if (r15 < Self.size) return self.uncheckedRead(T, addr);
return @truncate(T, self.uncheckedRead(T, self.addr_latch + 8));
return @truncate(T, self.uncheckedRead(T, self.addr_latch));
}
fn uncheckedRead(self: *const Self, comptime T: type, addr: u32) T {

View File

@ -1,11 +1,10 @@
const std = @import("std");
const util = @import("../util.zig");
const DmaControl = @import("io.zig").DmaControl;
const Bus = @import("../Bus.zig");
const Arm7tdmi = @import("../cpu.zig").Arm7tdmi;
const readUndefined = @import("../util.zig").readUndefined;
const writeUndefined = @import("../util.zig").writeUndefined;
pub const DmaTuple = std.meta.Tuple(&[_]type{ DmaController(0), DmaController(1), DmaController(2), DmaController(3) });
const log = std.log.scoped(.DmaTransfer);
@ -13,7 +12,7 @@ pub fn create() DmaTuple {
return .{ DmaController(0).init(), DmaController(1).init(), DmaController(2).init(), DmaController(3).init() };
}
pub fn read(comptime T: type, dma: *const DmaTuple, addr: u32) T {
pub fn read(comptime T: type, dma: *const DmaTuple, addr: u32) ?T {
const byte = @truncate(u8, addr);
return switch (T) {
@ -22,16 +21,16 @@ pub fn read(comptime T: type, dma: *const DmaTuple, addr: u32) T {
0xC4 => @as(T, dma.*[1].cnt.raw) << 16,
0xD0 => @as(T, dma.*[2].cnt.raw) << 16,
0xDC => @as(T, dma.*[3].cnt.raw) << 16,
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
},
u16 => switch (byte) {
0xBA => dma.*[0].cnt.raw,
0xC6 => dma.*[1].cnt.raw,
0xD2 => dma.*[2].cnt.raw,
0xDE => dma.*[3].cnt.raw,
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
},
u8 => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
u8 => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => @compileError("DMA: Unsupported read width"),
};
}
@ -53,7 +52,7 @@ pub fn write(comptime T: type, dma: *DmaTuple, addr: u32, value: T) void {
0xD4 => dma.*[3].setSad(value),
0xD8 => dma.*[3].setDad(value),
0xDC => dma.*[3].setCnt(value),
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
},
u16 => switch (byte) {
0xB0 => dma.*[0].setSad(setU32L(dma.*[0].sad, value)),
@ -83,9 +82,9 @@ pub fn write(comptime T: type, dma: *DmaTuple, addr: u32, value: T) void {
0xDA => dma.*[3].setDad(setU32H(dma.*[3].dad, value)),
0xDC => dma.*[3].setCntL(value),
0xDE => dma.*[3].setCntH(value),
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
},
u8 => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
u8 => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
else => @compileError("DMA: Unsupported write width"),
}
}

View File

@ -1,5 +1,9 @@
const std = @import("std");
const builtin = @import("builtin");
const timer = @import("timer.zig");
const dma = @import("dma.zig");
const apu = @import("../apu.zig");
const util = @import("../util.zig");
const Bit = @import("bitfield").Bit;
const Bitfield = @import("bitfield").Bitfield;
@ -7,12 +11,6 @@ const Bus = @import("../Bus.zig");
const DmaController = @import("dma.zig").DmaController;
const Scheduler = @import("../scheduler.zig").Scheduler;
const timer = @import("timer.zig");
const dma = @import("dma.zig");
const apu = @import("../apu.zig");
const readUndefined = @import("../util.zig").readUndefined;
const writeUndefined = @import("../util.zig").writeUndefined;
const log = std.log.scoped(.@"I/O");
pub const Io = struct {
@ -43,7 +41,7 @@ pub const Io = struct {
}
};
pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
pub fn read(bus: *const Bus, comptime T: type, address: u32) ?T {
return switch (T) {
u32 => switch (address) {
// Display
@ -58,18 +56,18 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_0100...0x0400_010C => timer.read(T, &bus.tim, address),
// Serial Communication 1
0x0400_0128 => readTodo("Read {} from SIOCNT and SIOMLT_SEND", .{T}),
0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT and SIOMLT_SEND", .{T}),
// Keypad Input
0x0400_0130 => readTodo("Read {} from KEYINPUT", .{T}),
0x0400_0130 => util.io.read.todo(log, "Read {} from KEYINPUT", .{T}),
// Serial Communication 2
0x0400_0150 => readTodo("Read {} from JOY_RECV", .{T}),
0x0400_0150 => util.io.read.todo(log, "Read {} from JOY_RECV", .{T}),
// Interrupts
0x0400_0200 => @as(T, bus.io.irq.raw) << 16 | bus.io.ie.raw,
0x0400_0208 => @boolToInt(bus.io.ime),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
},
u16 => switch (address) {
// Display
@ -80,7 +78,7 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_000A => bus.ppu.bg[1].cnt.raw,
0x0400_000C => bus.ppu.bg[2].cnt.raw,
0x0400_000E => bus.ppu.bg[3].cnt.raw,
0x0400_004C => readTodo("Read {} from MOSAIC", .{T}),
0x0400_004C => util.io.read.todo(log, "Read {} from MOSAIC", .{T}),
0x0400_0050 => bus.ppu.bldcnt.raw,
// Sound
@ -93,20 +91,20 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_0100...0x0400_010E => timer.read(T, &bus.tim, address),
// Serial Communication 1
0x0400_0128 => readTodo("Read {} from SIOCNT", .{T}),
0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT", .{T}),
// Keypad Input
0x0400_0130 => bus.io.keyinput.raw,
// Serial Communication 2
0x0400_0134 => readTodo("Read {} from RCNT", .{T}),
0x0400_0134 => util.io.read.todo(log, "Read {} from RCNT", .{T}),
// Interrupts
0x0400_0200 => bus.io.ie.raw,
0x0400_0202 => bus.io.irq.raw,
0x0400_0204 => readTodo("Read {} from WAITCNT", .{T}),
0x0400_0204 => util.io.read.todo(log, "Read {} from WAITCNT", .{T}),
0x0400_0208 => @boolToInt(bus.io.ime),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
},
u8 => return switch (address) {
// Display
@ -123,18 +121,18 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_0060...0x0400_00A7 => apu.read(T, &bus.apu, address),
// Serial Communication 1
0x0400_0128 => readTodo("Read {} from SIOCNT_L", .{T}),
0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT_L", .{T}),
// Keypad Input
0x0400_0130 => readTodo("read {} from KEYINPUT_L", .{T}),
0x0400_0130 => util.io.read.todo(log, "read {} from KEYINPUT_L", .{T}),
// Serial Communication 2
0x0400_0135 => readTodo("Read {} from RCNT_H", .{T}),
0x0400_0135 => util.io.read.todo(log, "Read {} from RCNT_H", .{T}),
// Interrupts
0x0400_0200 => @truncate(T, bus.io.ie.raw),
0x0400_0300 => @enumToInt(bus.io.postflg),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
},
else => @compileError("I/O: Unsupported read width"),
};
@ -210,7 +208,7 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0204 => log.debug("Wrote 0x{X:0>8} to WAITCNT", .{value}),
0x0400_0208 => bus.io.ime = value & 1 == 1,
0x0400_020C...0x0400_021C => {}, // Unused
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, address }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, address }),
},
u16 => switch (address) {
// Display
@ -292,7 +290,7 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0204 => log.debug("Wrote 0x{X:0>4} to WAITCNT", .{value}),
0x0400_0208 => bus.io.ime = value & 1 == 1,
0x0400_0206, 0x0400_020A => {}, // Not Used
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, address }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, address }),
},
u8 => switch (address) {
// Display
@ -325,17 +323,12 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0301 => bus.io.haltcnt = if (value >> 7 & 1 == 0) .Halt else std.debug.panic("TODO: Implement STOP", .{}),
0x0400_0410 => log.debug("Wrote 0x{X:0>2} to the common yet undocumented 0x{X:0>8}", .{ value, address }),
else => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, address }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, address }),
},
else => @compileError("I/O: Unsupported write width"),
};
}
fn readTodo(comptime format: []const u8, args: anytype) u8 {
log.debug(format, args);
return 0;
}
/// Read / Write
pub const PostFlag = enum(u1) {
FirstBoot = 0,

View File

@ -1,4 +1,5 @@
const std = @import("std");
const util = @import("../util.zig");
const TimerControl = @import("io.zig").TimerControl;
const Io = @import("io.zig").Io;
@ -6,8 +7,6 @@ const Scheduler = @import("../scheduler.zig").Scheduler;
const Event = @import("../scheduler.zig").Event;
const Arm7tdmi = @import("../cpu.zig").Arm7tdmi;
const readUndefined = @import("../util.zig").readUndefined;
const writeUndefined = @import("../util.zig").writeUndefined;
pub const TimerTuple = std.meta.Tuple(&[_]type{ Timer(0), Timer(1), Timer(2), Timer(3) });
const log = std.log.scoped(.Timer);
@ -15,7 +14,7 @@ pub fn create(sched: *Scheduler) TimerTuple {
return .{ Timer(0).init(sched), Timer(1).init(sched), Timer(2).init(sched), Timer(3).init(sched) };
}
pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) T {
pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) ?T {
const nybble = @truncate(u4, addr);
return switch (T) {
@ -24,7 +23,7 @@ pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) T {
0x4 => @as(T, tim.*[1].cnt.raw) << 16 | tim.*[1].getCntL(),
0x8 => @as(T, tim.*[2].cnt.raw) << 16 | tim.*[2].getCntL(),
0xC => @as(T, tim.*[3].cnt.raw) << 16 | tim.*[3].getCntL(),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
},
u16 => switch (nybble) {
0x0 => tim.*[0].getCntL(),
@ -35,9 +34,9 @@ pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) T {
0xA => tim.*[2].cnt.raw,
0xC => tim.*[3].getCntL(),
0xE => tim.*[3].cnt.raw,
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
},
u8 => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
u8 => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => @compileError("TIM: Unsupported read width"),
};
}
@ -51,7 +50,7 @@ pub fn write(comptime T: type, tim: *TimerTuple, addr: u32, value: T) void {
0x4 => tim.*[1].setCnt(value),
0x8 => tim.*[2].setCnt(value),
0xC => tim.*[3].setCnt(value),
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
},
u16 => switch (nybble) {
0x0 => tim.*[0].setCntL(value),
@ -62,9 +61,9 @@ pub fn write(comptime T: type, tim: *TimerTuple, addr: u32, value: T) void {
0xA => tim.*[2].setCntH(value),
0xC => tim.*[3].setCntL(value),
0xE => tim.*[3].setCntH(value),
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
},
u8 => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
u8 => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
else => @compileError("TIM: Unsupported write width"),
};
}

View File

@ -243,6 +243,7 @@ pub const Arm7tdmi = struct {
const Self = @This();
r: [16]u32,
pipe: Pipline,
sched: *Scheduler,
bus: *Bus,
cpsr: PSR,
@ -263,6 +264,7 @@ pub const Arm7tdmi = struct {
pub fn init(sched: *Scheduler, bus: *Bus, log_file: ?std.fs.File) Self {
return Self{
.r = [_]u32{0x00} ** 16,
.pipe = Pipline.init(),
.sched = sched,
.bus = bus,
.cpsr = .{ .raw = 0x0000_001F },
@ -322,8 +324,21 @@ pub const Arm7tdmi = struct {
return self.bus.io.haltcnt == .Halt;
}
pub fn setCpsrNoFlush(self: *Self, value: u32) void {
if (value & 0x1F != self.cpsr.raw & 0x1F) self.changeModeFromIdx(@truncate(u5, value & 0x1F));
self.cpsr.raw = value;
}
pub fn setCpsr(self: *Self, value: u32) void {
if (value & 0x1F != self.cpsr.raw & 0x1F) self.changeModeFromIdx(@truncate(u5, value & 0x1F));
const new: PSR = .{ .raw = value };
if (self.cpsr.t.read() != new.t.read()) {
// If THUMB to ARM or ARM to THUMB, flush pipeline
self.r[15] &= if (new.t.read()) ~@as(u32, 1) else ~@as(u32, 3);
if (new.t.read()) self.pipe.reload(u16, self) else self.pipe.reload(u32, self);
}
self.cpsr.raw = value;
}
@ -414,31 +429,35 @@ pub const Arm7tdmi = struct {
pub fn fastBoot(self: *Self) void {
self.r = std.mem.zeroes([16]u32);
self.r[0] = 0x08000000;
self.r[1] = 0x000000EA;
// self.r[0] = 0x08000000;
// self.r[1] = 0x000000EA;
self.r[13] = 0x0300_7F00;
self.r[15] = 0x0800_0000;
self.banked_r[bankedIdx(.Irq, .R13)] = 0x0300_7FA0;
self.banked_r[bankedIdx(.Supervisor, .R13)] = 0x0300_7FE0;
self.cpsr.raw = 0x6000001F;
// self.cpsr.raw = 0x6000001F;
self.cpsr.raw = 0x0000_001F;
}
pub fn step(self: *Self) void {
if (self.cpsr.t.read()) {
const opcode = self.fetch(u16);
if (self.cpsr.t.read()) blk: {
const opcode = @truncate(u16, self.pipe.step(self, u16) orelse break :blk);
if (cpu_logging) self.logger.?.mgbaLog(self, opcode);
thumb.lut[thumb.idx(opcode)](self, self.bus, opcode);
} else {
const opcode = self.fetch(u32);
} else blk: {
const opcode = self.pipe.step(self, u32) orelse break :blk;
if (cpu_logging) self.logger.?.mgbaLog(self, opcode);
if (checkCond(self.cpsr, @truncate(u4, opcode >> 28))) {
arm.lut[arm.idx(opcode)](self, self.bus, opcode);
}
}
if (!self.pipe.flushed) self.r[15] += if (self.cpsr.t.read()) 2 else @as(u32, 4);
self.pipe.flushed = false;
}
pub fn stepDmaTransfer(self: *Self) bool {
@ -473,27 +492,26 @@ pub const Arm7tdmi = struct {
pub fn handleInterrupt(self: *Self) void {
const should_handle = self.bus.io.ie.raw & self.bus.io.irq.raw;
if (should_handle != 0) {
self.bus.io.haltcnt = .Execute;
// log.debug("An Interrupt was Fired!", .{});
// Return if IME is disabled, CPSR I is set or there is nothing to handle
if (!self.bus.io.ime or self.cpsr.i.read() or should_handle == 0) return;
// Either IME is not true or I in CPSR is true
// Don't handle interrupts
if (!self.bus.io.ime or self.cpsr.i.read()) return;
// log.debug("An interrupt was Handled!", .{});
// If pipeline isn't full, return but reschedule the handling of the event
if (!self.pipe.isFull()) return;
// retAddr.gba says r15 on it's own is off by -04h in both ARM and THUMB mode
const r15 = self.r[15] + 4;
const cpsr = self.cpsr.raw;
// log.debug("Handling Interrupt!", .{});
self.bus.io.haltcnt = .Execute;
self.changeMode(.Irq);
self.cpsr.t.write(false);
self.cpsr.i.write(true);
const ret_addr = self.r[15] - if (self.cpsr.t.read()) 2 else @as(u32, 4);
const new_spsr = self.cpsr.raw;
self.r[14] = r15;
self.spsr.raw = cpsr;
self.r[15] = 0x000_0018;
}
self.changeMode(.Irq);
self.cpsr.t.write(false);
self.cpsr.i.write(true);
self.r[14] = ret_addr;
self.spsr.raw = new_spsr;
self.r[15] = 0x0000_0018;
self.pipe.reload(u32, self);
}
inline fn fetch(self: *Self, comptime T: type) T {
@ -507,8 +525,12 @@ pub const Arm7tdmi = struct {
return self.bus.read(T, self.r[15]);
}
pub fn fakePC(self: *const Self) u32 {
return self.r[15] + 4;
fn debug_log(self: *const Self, file: *const File, opcode: u32) void {
if (self.binary_log) {
self.skyLog(file) catch unreachable;
} else {
self.mgbaLog(file, opcode) catch unreachable;
}
}
pub fn panic(self: *const Self, comptime format: []const u8, args: anytype) noreturn {
@ -525,6 +547,8 @@ pub const Arm7tdmi = struct {
std.debug.print("spsr: 0x{X:0>8} ", .{self.spsr.raw});
prettyPrintPsr(&self.spsr);
std.debug.print("pipeline: {??X:0>8}\n", .{self.pipe.stage});
if (self.cpsr.t.read()) {
const opcode = self.bus.dbgRead(u16, self.r[15] - 4);
const id = thumb.idx(opcode);
@ -588,7 +612,7 @@ pub const Arm7tdmi = struct {
const r12 = self.r[12];
const r13 = self.r[13];
const r14 = self.r[14];
const r15 = self.r[15];
const r15 = self.r[15] -| if (self.cpsr.t.read()) 2 else @as(u32, 4);
const c_psr = self.cpsr.raw;
@ -596,7 +620,7 @@ pub const Arm7tdmi = struct {
if (self.cpsr.t.read()) {
if (opcode >> 11 == 0x1E) {
// Instruction 1 of a BL Opcode, print in ARM mode
const other_half = self.bus.dbgRead(u16, self.r[15]);
const other_half = self.bus.debugRead(u16, self.r[15] - 2);
const bl_opcode = @as(u32, opcode) << 16 | other_half;
log_str = try std.fmt.bufPrint(&buf, arm_fmt, .{ r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, c_psr, bl_opcode });
@ -632,6 +656,59 @@ pub fn checkCond(cpsr: PSR, cond: u4) bool {
};
}
const Pipline = struct {
const Self = @This();
stage: [2]?u32,
flushed: bool,
fn init() Self {
return .{
.stage = [_]?u32{null} ** 2,
.flushed = false,
};
}
pub fn flush(self: *Self) void {
for (self.stage) |*opcode| opcode.* = null;
self.flushed = true;
// Note: If using this, add
// if (!self.pipe.flushed) self.r[15] += if (self.cpsr.t.read()) 2 else @as(u32, 4);
// to the end of Arm7tdmi.step
}
pub fn isFull(self: *const Self) bool {
return self.stage[0] != null and self.stage[1] != null;
}
pub fn step(self: *Self, cpu: *Arm7tdmi, comptime T: type) ?u32 {
comptime std.debug.assert(T == u32 or T == u16);
// FIXME: https://github.com/ziglang/zig/issues/12642
const opcode = self.stage[0..1][0];
self.stage[0] = self.stage[1];
self.stage[1] = cpu.bus.read(T, cpu.r[15]);
return opcode;
}
pub fn reload(self: *Self, comptime T: type, cpu: *Arm7tdmi) void {
comptime std.debug.assert(T == u32 or T == u16);
// Sometimes, the pipeline can be reloaded twice in the same instruction
// This can happen if:
// 1. R15 is written to
// 2. The CPSR is written to (and T changes), so R15 is written to again
self.stage[0] = cpu.bus.read(T, cpu.r[15]);
self.stage[1] = cpu.bus.read(T, cpu.r[15] + if (T == u32) 4 else @as(u32, 2));
cpu.r[15] += if (T == u32) 8 else @as(u32, 4);
self.flushed = true;
}
};
pub const PSR = extern union {
mode: Bitfield(u32, 0, 5),
t: Bit(u32, 5),

View File

@ -55,8 +55,10 @@ pub fn blockDataTransfer(comptime P: bool, comptime U: bool, comptime S: bool, c
if (L) {
cpu.r[15] = bus.read(u32, und_addr);
cpu.pipe.reload(u32, cpu);
} else {
bus.write(u32, und_addr, cpu.r[15] + 8);
// FIXME: Should r15 on write be +12 ahead?
bus.write(u32, und_addr, cpu.r[15] + 4);
}
cpu.r[rn] = if (U) cpu.r[rn] + 0x40 else cpu.r[rn] - 0x40;
@ -86,17 +88,23 @@ pub fn blockDataTransfer(comptime P: bool, comptime U: bool, comptime S: bool, c
cpu.setUserModeRegister(i, bus.read(u32, address));
} else {
const value = bus.read(u32, address);
cpu.r[i] = if (i == 0xF) value & 0xFFFF_FFFC else value;
if (S and i == 0xF) cpu.setCpsr(cpu.spsr.raw);
cpu.r[i] = value;
if (i == 0xF) {
cpu.r[i] &= ~@as(u32, 3); // Align r15
cpu.pipe.reload(u32, cpu);
if (S) cpu.setCpsr(cpu.spsr.raw);
}
}
} else {
if (S) {
// Always Transfer User mode Registers
// This happens regardless if r15 is in the list
const value = cpu.getUserModeRegister(i);
bus.write(u32, address, value + if (i == 0xF) 8 else @as(u32, 0)); // PC is already 4 ahead to make 12
bus.write(u32, address, value + if (i == 0xF) 4 else @as(u32, 0)); // PC is already 8 ahead to make 12
} else {
bus.write(u32, address, cpu.r[i] + if (i == 0xF) 8 else @as(u32, 0));
bus.write(u32, address, cpu.r[i] + if (i == 0xF) 4 else @as(u32, 0));
}
}
}

View File

@ -9,14 +9,20 @@ const sext = @import("../../util.zig").sext;
pub fn branch(comptime L: bool) InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u32) void {
if (L) cpu.r[14] = cpu.r[15];
cpu.r[15] = cpu.fakePC() +% (sext(u32, u24, opcode) << 2);
if (L) cpu.r[14] = cpu.r[15] - 4;
cpu.r[15] +%= sext(u32, u24, opcode) << 2;
cpu.pipe.reload(u32, cpu);
}
}.inner;
}
pub fn branchAndExchange(cpu: *Arm7tdmi, _: *Bus, opcode: u32) void {
const rn = opcode & 0xF;
cpu.cpsr.t.write(cpu.r[rn] & 1 == 1);
cpu.r[15] = cpu.r[rn] & 0xFFFF_FFFE;
const thumb = cpu.r[rn] & 1 == 1;
cpu.r[15] = cpu.r[rn] & if (thumb) ~@as(u32, 1) else ~@as(u32, 3);
cpu.cpsr.t.write(thumb);
if (thumb) cpu.pipe.reload(u16, cpu) else cpu.pipe.reload(u32, cpu);
}

View File

@ -5,7 +5,7 @@ const InstrFn = @import("../../cpu.zig").arm.InstrFn;
const rotateRight = @import("../barrel_shifter.zig").rotateRight;
const execute = @import("../barrel_shifter.zig").execute;
pub fn dataProcessing(comptime I: bool, comptime S: bool, comptime instrKind: u4) InstrFn {
pub fn dataProcessing(comptime I: bool, comptime S: bool, comptime kind: u4) InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u32) void {
const rd = @truncate(u4, opcode >> 12 & 0xF);
@ -13,124 +13,276 @@ pub fn dataProcessing(comptime I: bool, comptime S: bool, comptime instrKind: u4
const old_carry = @boolToInt(cpu.cpsr.c.read());
// If certain conditions are met, PC is 12 ahead instead of 8
// TODO: Why these conditions?
if (!I and opcode >> 4 & 1 == 1) cpu.r[15] += 4;
const op1 = cpu.r[rn];
const op1 = if (rn == 0xF) cpu.fakePC() else cpu.r[rn];
var op2: u32 = undefined;
if (I) {
const amount = @truncate(u8, (opcode >> 8 & 0xF) << 1);
op2 = rotateRight(S, &cpu.cpsr, opcode & 0xFF, amount);
} else {
op2 = execute(S, cpu, opcode);
}
const amount = @truncate(u8, (opcode >> 8 & 0xF) << 1);
const op2 = if (I) rotateRight(S, &cpu.cpsr, opcode & 0xFF, amount) else execute(S, cpu, opcode);
// Undo special condition from above
if (!I and opcode >> 4 & 1 == 1) cpu.r[15] -= 4;
switch (instrKind) {
0x0 => {
// AND
const result = op1 & op2;
cpu.r[rd] = result;
setArmLogicOpFlags(S, cpu, rd, result);
},
0x1 => {
// EOR
const result = op1 ^ op2;
cpu.r[rd] = result;
setArmLogicOpFlags(S, cpu, rd, result);
},
0x2 => {
// SUB
cpu.r[rd] = armSub(S, cpu, rd, op1, op2);
},
0x3 => {
// RSB
cpu.r[rd] = armSub(S, cpu, rd, op2, op1);
},
0x4 => {
// ADD
cpu.r[rd] = armAdd(S, cpu, rd, op1, op2);
},
0x5 => {
// ADC
cpu.r[rd] = armAdc(S, cpu, rd, op1, op2, old_carry);
},
0x6 => {
// SBC
cpu.r[rd] = armSbc(S, cpu, rd, op1, op2, old_carry);
},
0x7 => {
// RSC
cpu.r[rd] = armSbc(S, cpu, rd, op2, op1, old_carry);
},
var result: u32 = undefined;
var didOverflow: bool = undefined;
// Perform Data Processing Logic
switch (kind) {
0x0 => result = op1 & op2, // AND
0x1 => result = op1 ^ op2, // EOR
0x2 => result = op1 -% op2, // SUB
0x3 => result = op2 -% op1, // RSB
0x4 => result = newAdd(&didOverflow, op1, op2), // ADD
0x5 => result = newAdc(&didOverflow, op1, op2, old_carry), // ADC
0x6 => result = newSbc(op1, op2, old_carry), // SBC
0x7 => result = newSbc(op2, op1, old_carry), // RSC
0x8 => {
// TST
if (rd == 0xF) {
undefinedTestBehaviour(cpu);
return;
}
if (rd == 0xF)
return undefinedTestBehaviour(cpu);
const result = op1 & op2;
setTestOpFlags(S, cpu, opcode, result);
result = op1 & op2;
},
0x9 => {
// TEQ
if (rd == 0xF) {
undefinedTestBehaviour(cpu);
return;
}
if (rd == 0xF)
return undefinedTestBehaviour(cpu);
const result = op1 ^ op2;
setTestOpFlags(S, cpu, opcode, result);
result = op1 ^ op2;
},
0xA => {
// CMP
if (rd == 0xF) {
undefinedTestBehaviour(cpu);
return;
}
if (rd == 0xF)
return undefinedTestBehaviour(cpu);
cmp(cpu, op1, op2);
result = op1 -% op2;
},
0xB => {
// CMN
if (rd == 0xF) {
undefinedTestBehaviour(cpu);
return;
}
if (rd == 0xF)
return undefinedTestBehaviour(cpu);
cmn(cpu, op1, op2);
didOverflow = @addWithOverflow(u32, op1, op2, &result);
},
0xC => {
// ORR
const result = op1 | op2;
0xC => result = op1 | op2, // ORR
0xD => result = op2, // MOV
0xE => result = op1 & ~op2, // BIC
0xF => result = ~op2, // MVN
}
// Write to Destination Register
switch (kind) {
0x8, 0x9, 0xA, 0xB => {}, // Test Operations
else => {
cpu.r[rd] = result;
setArmLogicOpFlags(S, cpu, rd, result);
if (rd == 0xF) cpu.pipe.reload(u32, cpu);
},
0xD => {
// MOV
cpu.r[rd] = op2;
setArmLogicOpFlags(S, cpu, rd, op2);
}
// Write Flags
switch (kind) {
0x0, 0x1, 0xC, 0xD, 0xE, 0xF => {
// Logic Operation Flags
if (S) {
if (rd == 0xF) {
cpu.setCpsr(cpu.spsr.raw);
} else {
cpu.cpsr.n.write(result >> 31 & 1 == 1);
cpu.cpsr.z.write(result == 0);
// C set by Barrel Shifter, V is unaffected
}
}
},
0xE => {
// BIC
const result = op1 & ~op2;
cpu.r[rd] = result;
setArmLogicOpFlags(S, cpu, rd, result);
0x2, 0x3 => {
// SUB, RSB Flags
if (S) {
cpu.cpsr.n.write(result >> 31 & 1 == 1);
cpu.cpsr.z.write(result == 0);
if (kind == 0x2) {
// SUB specific
cpu.cpsr.c.write(op2 <= op1);
cpu.cpsr.v.write(((op1 ^ result) & (~op2 ^ result)) >> 31 & 1 == 1);
} else {
// RSB Specific
cpu.cpsr.c.write(op1 <= op2);
cpu.cpsr.v.write(((op2 ^ result) & (~op1 ^ result)) >> 31 & 1 == 1);
}
if (rd == 0xF) cpu.setCpsr(cpu.spsr.raw);
}
},
0xF => {
// MVN
const result = ~op2;
cpu.r[rd] = result;
setArmLogicOpFlags(S, cpu, rd, result);
0x4, 0x5 => {
// ADD, ADC Flags
if (S) {
cpu.cpsr.n.write(result >> 31 & 1 == 1);
cpu.cpsr.z.write(result == 0);
cpu.cpsr.c.write(didOverflow);
cpu.cpsr.v.write(((op1 ^ result) & (op2 ^ result)) >> 31 & 1 == 1);
if (rd == 0xF) cpu.setCpsr(cpu.spsr.raw);
}
},
0x6, 0x7 => {
// SBC, RSC Flags
if (S) {
cpu.cpsr.n.write(result >> 31 & 1 == 1);
cpu.cpsr.z.write(result == 0);
if (kind == 0x6) {
// SBC specific
const subtrahend = @as(u64, op2) -% old_carry +% 1;
cpu.cpsr.c.write(subtrahend <= op1);
cpu.cpsr.v.write(((op1 ^ result) & (~op2 ^ result)) >> 31 & 1 == 1);
} else {
// RSC Specific
const subtrahend = @as(u64, op1) -% old_carry +% 1;
cpu.cpsr.c.write(subtrahend <= op2);
cpu.cpsr.v.write(((op2 ^ result) & (~op1 ^ result)) >> 31 & 1 == 1);
}
if (rd == 0xF) cpu.setCpsr(cpu.spsr.raw);
}
},
0x8, 0x9, 0xA, 0xB => {
// Test Operation Flags
cpu.cpsr.n.write(result >> 31 & 1 == 1);
cpu.cpsr.z.write(result == 0);
if (kind == 0xA) {
// CMP specific
cpu.cpsr.c.write(op2 <= op1);
cpu.cpsr.v.write(((op1 ^ result) & (~op2 ^ result)) >> 31 & 1 == 1);
} else if (kind == 0xB) {
// CMN specific
cpu.cpsr.c.write(didOverflow);
cpu.cpsr.v.write(((op1 ^ result) & (op2 ^ result)) >> 31 & 1 == 1);
} else {
// TEST, TEQ specific
// Barrel Shifter should always calc CPSR C in TST
if (!S) _ = execute(true, cpu, opcode);
}
},
}
}
}.inner;
}
// pub fn dataProcessing(comptime I: bool, comptime S: bool, comptime instrKind: u4) InstrFn {
// return struct {
// fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u32) void {
// const rd = @truncate(u4, opcode >> 12 & 0xF);
// const rn = opcode >> 16 & 0xF;
// const old_carry = @boolToInt(cpu.cpsr.c.read());
// // If certain conditions are met, PC is 12 ahead instead of 8
// // TODO: What are these conditions? I can't remember
// if (!I and opcode >> 4 & 1 == 1) cpu.r[15] += 4;
// const op1 = cpu.r[rn];
// const amount = @truncate(u8, (opcode >> 8 & 0xF) << 1);
// const op2 = if (I) rotateRight(S, &cpu.cpsr, opcode & 0xFF, amount) else execute(S, cpu, opcode);
// // Undo special condition from above
// if (!I and opcode >> 4 & 1 == 1) cpu.r[15] -= 4;
// switch (instrKind) {
// 0x0 => {
// // AND
// const result = op1 & op2;
// cpu.r[rd] = result;
// setArmLogicOpFlags(S, cpu, rd, result);
// },
// 0x1 => {
// // EOR
// const result = op1 ^ op2;
// cpu.r[rd] = result;
// setArmLogicOpFlags(S, cpu, rd, result);
// },
// 0x2 => {
// // SUB
// cpu.r[rd] = armSub(S, cpu, rd, op1, op2);
// },
// 0x3 => {
// // RSB
// cpu.r[rd] = armSub(S, cpu, rd, op2, op1);
// },
// 0x4 => {
// // ADD
// cpu.r[rd] = armAdd(S, cpu, rd, op1, op2);
// },
// 0x5 => {
// // ADC
// cpu.r[rd] = armAdc(S, cpu, rd, op1, op2, old_carry);
// },
// 0x6 => {
// // SBC
// cpu.r[rd] = armSbc(S, cpu, rd, op1, op2, old_carry);
// },
// 0x7 => {
// // RSC
// cpu.r[rd] = armSbc(S, cpu, rd, op2, op1, old_carry);
// },
// 0x8 => {
// // TST
// if (rd == 0xF)
// return undefinedTestBehaviour(cpu);
// const result = op1 & op2;
// setTestOpFlags(S, cpu, opcode, result);
// },
// 0x9 => {
// // TEQ
// if (rd == 0xF)
// return undefinedTestBehaviour(cpu);
// const result = op1 ^ op2;
// setTestOpFlags(S, cpu, opcode, result);
// },
// 0xA => {
// // CMP
// if (rd == 0xF)
// return undefinedTestBehaviour(cpu);
// cmp(cpu, op1, op2);
// },
// 0xB => {
// // CMN
// if (rd == 0xF)
// return undefinedTestBehaviour(cpu);
// cmn(cpu, op1, op2);
// },
// 0xC => {
// // ORR
// const result = op1 | op2;
// cpu.r[rd] = result;
// setArmLogicOpFlags(S, cpu, rd, result);
// },
// 0xD => {
// // MOV
// cpu.r[rd] = op2;
// setArmLogicOpFlags(S, cpu, rd, op2);
// },
// 0xE => {
// // BIC
// const result = op1 & ~op2;
// cpu.r[rd] = result;
// setArmLogicOpFlags(S, cpu, rd, result);
// },
// 0xF => {
// // MVN
// const result = ~op2;
// cpu.r[rd] = result;
// setArmLogicOpFlags(S, cpu, rd, result);
// },
// }
// if (rd == 0xF) cpu.pipe.reload(u32, cpu);
// }
// }.inner;
// }
fn armSbc(comptime S: bool, cpu: *Arm7tdmi, rd: u4, left: u32, right: u32, old_carry: u1) u32 {
var result: u32 = undefined;
if (S and rd == 0xF) {
@ -143,6 +295,14 @@ fn armSbc(comptime S: bool, cpu: *Arm7tdmi, rd: u4, left: u32, right: u32, old_c
return result;
}
fn newSbc(left: u32, right: u32, old_carry: u1) u32 {
// TODO: Make your own version (thanks peach.bot)
const subtrahend = @as(u64, right) -% old_carry +% 1;
const ret = @truncate(u32, left -% subtrahend);
return ret;
}
pub fn sbc(comptime S: bool, cpu: *Arm7tdmi, left: u32, right: u32, old_carry: u1) u32 {
// TODO: Make your own version (thanks peach.bot)
const subtrahend = @as(u64, right) -% old_carry +% 1;
@ -195,6 +355,12 @@ fn armAdd(comptime S: bool, cpu: *Arm7tdmi, rd: u4, left: u32, right: u32) u32 {
return result;
}
fn newAdd(didOverflow: *bool, left: u32, right: u32) u32 {
var ret: u32 = undefined;
didOverflow.* = @addWithOverflow(u32, left, right, &ret);
return ret;
}
pub fn add(comptime S: bool, cpu: *Arm7tdmi, left: u32, right: u32) u32 {
var result: u32 = undefined;
const didOverflow = @addWithOverflow(u32, left, right, &result);
@ -221,6 +387,15 @@ fn armAdc(comptime S: bool, cpu: *Arm7tdmi, rd: u4, left: u32, right: u32, old_c
return result;
}
fn newAdc(didOverflow: *bool, left: u32, right: u32, old_carry: u1) u32 {
var ret: u32 = undefined;
const did = @addWithOverflow(u32, left, right, &ret);
const overflow = @addWithOverflow(u32, ret, old_carry, &ret);
didOverflow.* = did or overflow;
return ret;
}
pub fn adc(comptime S: bool, cpu: *Arm7tdmi, left: u32, right: u32, old_carry: u1) u32 {
var result: u32 = undefined;
const did = @addWithOverflow(u32, left, right, &result);
@ -280,5 +455,5 @@ fn setTestOpFlags(comptime S: bool, cpu: *Arm7tdmi, opcode: u32, result: u32) vo
fn undefinedTestBehaviour(cpu: *Arm7tdmi) void {
@setCold(true);
cpu.setCpsr(cpu.spsr.raw);
cpu.setCpsrNoFlush(cpu.spsr.raw);
}

View File

@ -15,20 +15,8 @@ pub fn halfAndSignedDataTransfer(comptime P: bool, comptime U: bool, comptime I:
const rm = opcode & 0xF;
const imm_offset_high = opcode >> 8 & 0xF;
var base: u32 = undefined;
if (rn == 0xF) {
base = cpu.fakePC();
if (!L) base += 4;
} else {
base = cpu.r[rn];
}
var offset: u32 = undefined;
if (I) {
offset = imm_offset_high << 4 | rm;
} else {
offset = cpu.r[rm];
}
const base = cpu.r[rn] + if (!L and rn == 0xF) 4 else @as(u32, 0);
const offset = if (I) imm_offset_high << 4 | rm else cpu.r[rm];
const modified_base = if (U) base +% offset else base -% offset;
var address = if (P) modified_base else base;

View File

@ -14,13 +14,8 @@ pub fn singleDataTransfer(comptime I: bool, comptime P: bool, comptime U: bool,
const rn = opcode >> 16 & 0xF;
const rd = opcode >> 12 & 0xF;
var base: u32 = undefined;
if (rn == 0xF) {
base = cpu.fakePC();
if (!L) base += 4; // Offset of 12
} else {
base = cpu.r[rn];
}
// rn is r15 and L is not set, the PC is 12 ahead
const base = cpu.r[rn] + if (!L and rn == 0xF) 4 else @as(u32, 0);
const offset = if (I) shifter.immShift(false, cpu, opcode) else opcode & 0xFFF;
@ -40,18 +35,26 @@ pub fn singleDataTransfer(comptime I: bool, comptime P: bool, comptime U: bool,
} else {
if (B) {
// STRB
const value = if (rd == 0xF) cpu.r[rd] + 8 else cpu.r[rd];
const value = cpu.r[rd] + if (rd == 0xF) 4 else @as(u32, 0); // PC is 12 ahead
bus.write(u8, address, @truncate(u8, value));
} else {
// STR
const value = if (rd == 0xF) cpu.r[rd] + 8 else cpu.r[rd];
const value = cpu.r[rd] + if (rd == 0xF) 4 else @as(u32, 0);
bus.write(u32, address, value);
}
}
address = modified_base;
if (W and P or !P) cpu.r[rn] = address;
if (L) cpu.r[rd] = result; // This emulates the LDR rd == rn behaviour
if (W and P or !P) {
cpu.r[rn] = address;
if (rn == 0xF) cpu.pipe.reload(u32, cpu);
}
if (L) {
// This emulates the LDR rd == rn behaviour
cpu.r[rd] = result;
if (rd == 0xF) cpu.pipe.reload(u32, cpu);
}
}
}.inner;
}

View File

@ -6,7 +6,7 @@ pub fn armSoftwareInterrupt() InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, _: u32) void {
// Copy Values from Current Mode
const r15 = cpu.r[15];
const ret_addr = cpu.r[15] - 4;
const cpsr = cpu.cpsr.raw;
// Switch Mode
@ -14,9 +14,10 @@ pub fn armSoftwareInterrupt() InstrFn {
cpu.cpsr.t.write(false); // Force ARM Mode
cpu.cpsr.i.write(true); // Disable normal interrupts
cpu.r[14] = r15; // Resume Execution
cpu.r[14] = ret_addr; // Resume Execution
cpu.spsr.raw = cpsr; // Previous mode CPSR
cpu.r[15] = 0x0000_0008;
cpu.pipe.reload(u32, cpu);
}
}.inner;
}

View File

@ -18,11 +18,9 @@ pub fn execute(comptime S: bool, cpu: *Arm7tdmi, opcode: u32) u32 {
fn registerShift(comptime S: bool, cpu: *Arm7tdmi, opcode: u32) u32 {
const rs_idx = opcode >> 8 & 0xF;
const rm = cpu.r[opcode & 0xF];
const rs = @truncate(u8, cpu.r[rs_idx]);
const rm_idx = opcode & 0xF;
const rm = if (rm_idx == 0xF) cpu.fakePC() else cpu.r[rm_idx];
return switch (@truncate(u2, opcode >> 5)) {
0b00 => logicalLeft(S, &cpu.cpsr, rm, rs),
0b01 => logicalRight(S, &cpu.cpsr, rm, rs),
@ -33,9 +31,7 @@ fn registerShift(comptime S: bool, cpu: *Arm7tdmi, opcode: u32) u32 {
pub fn immShift(comptime S: bool, cpu: *Arm7tdmi, opcode: u32) u32 {
const amount = @truncate(u8, opcode >> 7 & 0x1F);
const rm_idx = opcode & 0xF;
const rm = if (rm_idx == 0xF) cpu.fakePC() else cpu.r[rm_idx];
const rm = cpu.r[opcode & 0xF];
var result: u32 = undefined;
if (amount == 0) {

View File

@ -33,7 +33,8 @@ pub fn fmt14(comptime L: bool, comptime R: bool) InstrFn {
if (R) {
if (L) {
const value = bus.read(u32, address);
cpu.r[15] = value & 0xFFFF_FFFE;
cpu.r[15] = value & ~@as(u32, 1);
cpu.pipe.reload(u16, cpu);
} else {
bus.write(u32, address, cpu.r[14]);
}
@ -52,7 +53,13 @@ pub fn fmt15(comptime L: bool, comptime rb: u3) InstrFn {
const end_address = cpu.r[rb] + 4 * countRlist(opcode);
if (opcode & 0xFF == 0) {
if (L) cpu.r[15] = bus.read(u32, address) else bus.write(u32, address, cpu.r[15] + 4);
if (L) {
cpu.r[15] = bus.read(u32, address);
cpu.pipe.reload(u16, cpu);
} else {
bus.write(u32, address, cpu.r[15] + 2);
}
cpu.r[rb] += 0x40;
return;
}

View File

@ -9,16 +9,13 @@ pub fn fmt16(comptime cond: u4) InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u16) void {
// B
const offset = sext(u32, u8, opcode & 0xFF) << 1;
if (cond == 0xE or cond == 0xF)
cpu.panic("[CPU/THUMB.16] Undefined conditional branch with condition {}", .{cond});
const should_execute = switch (cond) {
0xE, 0xF => cpu.panic("[CPU/THUMB.16] Undefined conditional branch with condition {}", .{cond}),
else => checkCond(cpu.cpsr, cond),
};
if (!checkCond(cpu.cpsr, cond)) return;
if (should_execute) {
cpu.r[15] = (cpu.r[15] + 2) +% offset;
}
cpu.r[15] +%= sext(u32, u8, opcode & 0xFF) << 1;
cpu.pipe.reload(u16, cpu);
}
}.inner;
}
@ -27,8 +24,8 @@ pub fn fmt18() InstrFn {
return struct {
// B but conditional
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u16) void {
const offset = sext(u32, u11, opcode & 0x7FF) << 1;
cpu.r[15] = (cpu.r[15] + 2) +% offset;
cpu.r[15] +%= sext(u32, u11, opcode & 0x7FF) << 1;
cpu.pipe.reload(u16, cpu);
}
}.inner;
}
@ -41,13 +38,16 @@ pub fn fmt19(comptime is_low: bool) InstrFn {
if (is_low) {
// Instruction 2
const old_pc = cpu.r[15];
const next_opcode = cpu.r[15] - 2;
cpu.r[15] = cpu.r[14] +% (offset << 1);
cpu.r[14] = old_pc | 1;
cpu.r[14] = next_opcode | 1;
cpu.pipe.reload(u16, cpu);
} else {
// Instruction 1
cpu.r[14] = (cpu.r[15] + 2) +% (sext(u32, u11, offset) << 12);
const lr_offset = sext(u32, u11, offset) << 12;
cpu.r[14] = (cpu.r[15] +% lr_offset) & ~@as(u32, 1);
}
}
}.inner;

View File

@ -10,8 +10,6 @@ const sub = @import("../arm/data_processing.zig").sub;
const cmp = @import("../arm/data_processing.zig").cmp;
const setLogicOpFlags = @import("../arm/data_processing.zig").setLogicOpFlags;
const log = std.log.scoped(.Thumb1);
pub fn fmt1(comptime op: u2, comptime offset: u5) InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u16) void {
@ -58,29 +56,38 @@ pub fn fmt1(comptime op: u2, comptime offset: u5) InstrFn {
pub fn fmt5(comptime op: u2, comptime h1: u1, comptime h2: u1) InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u16) void {
const src_idx = @as(u4, h2) << 3 | (opcode >> 3 & 0x7);
const dst_idx = @as(u4, h1) << 3 | (opcode & 0x7);
const rs = @as(u4, h2) << 3 | (opcode >> 3 & 0x7);
const rd = @as(u4, h1) << 3 | (opcode & 0x7);
const src = if (src_idx == 0xF) (cpu.r[src_idx] + 2) & 0xFFFF_FFFE else cpu.r[src_idx];
const dst = if (dst_idx == 0xF) (cpu.r[dst_idx] + 2) & 0xFFFF_FFFE else cpu.r[dst_idx];
const rs_value = if (rs == 0xF) cpu.r[rs] & ~@as(u32, 1) else cpu.r[rs];
const rd_value = if (rd == 0xF) cpu.r[rd] & ~@as(u32, 1) else cpu.r[rd];
switch (op) {
0b00 => {
// ADD
const sum = add(false, cpu, dst, src);
cpu.r[dst_idx] = if (dst_idx == 0xF) sum & 0xFFFF_FFFE else sum;
const sum = add(false, cpu, rd_value, rs_value);
cpu.r[rd] = if (rd == 0xF) sum & ~@as(u32, 1) else sum;
},
0b01 => cmp(cpu, dst, src), // CMP
0b01 => cmp(cpu, rd_value, rs_value), // CMP
0b10 => {
// MOV
cpu.r[dst_idx] = if (dst_idx == 0xF) src & 0xFFFF_FFFE else src;
cpu.r[rd] = if (rd == 0xF) rs_value & ~@as(u32, 1) else rs_value;
},
0b11 => {
// BX
cpu.cpsr.t.write(src & 1 == 1);
cpu.r[15] = src & 0xFFFF_FFFE;
const thumb = rs_value & 1 == 1;
cpu.r[15] = rs_value & ~@as(u32, 1);
cpu.cpsr.t.write(thumb);
if (thumb) cpu.pipe.reload(u16, cpu) else cpu.pipe.reload(u32, cpu);
// TODO: We shouldn't need to worry about the if statement
// below, because in BX, rd SBZ (and H1 is guaranteed to be 0)
return;
},
}
if (rd == 0xF) cpu.pipe.reload(u16, cpu);
}
}.inner;
}
@ -133,10 +140,9 @@ pub fn fmt12(comptime isSP: bool, comptime rd: u3) InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, opcode: u16) void {
// ADD
const left = if (isSP) cpu.r[13] else (cpu.r[15] + 2) & 0xFFFF_FFFD;
const left = if (isSP) cpu.r[13] else cpu.r[15] & ~@as(u32, 2);
const right = (opcode & 0xFF) << 2;
const result = left + right;
cpu.r[rd] = result;
cpu.r[rd] = left + right;
}
}.inner;
}

View File

@ -11,7 +11,9 @@ pub fn fmt6(comptime rd: u3) InstrFn {
fn inner(cpu: *Arm7tdmi, bus: *Bus, opcode: u16) void {
// LDR
const offset = (opcode & 0xFF) << 2;
cpu.r[rd] = bus.read(u32, (cpu.r[15] + 2 & 0xFFFF_FFFD) + offset);
// Bit 1 of the PC intentionally ignored
cpu.r[rd] = bus.read(u32, (cpu.r[15] & ~@as(u32, 2)) + offset);
}
}.inner;
}

View File

@ -6,7 +6,7 @@ pub fn fmt17() InstrFn {
return struct {
fn inner(cpu: *Arm7tdmi, _: *Bus, _: u16) void {
// Copy Values from Current Mode
const r15 = cpu.r[15];
const ret_addr = cpu.r[15] - 2;
const cpsr = cpu.cpsr.raw;
// Switch Mode
@ -14,9 +14,10 @@ pub fn fmt17() InstrFn {
cpu.cpsr.t.write(false); // Force ARM Mode
cpu.cpsr.i.write(true); // Disable normal interrupts
cpu.r[14] = r15; // Resume Execution
cpu.r[14] = ret_addr; // Resume Execution
cpu.spsr.raw = cpsr; // Previous mode CPSR
cpu.r[15] = 0x0000_0008;
cpu.pipe.reload(u32, cpu);
}
}.inner;
}

View File

@ -13,10 +13,11 @@ const Atomic = std.atomic.Atomic;
const Allocator = std.mem.Allocator;
// TODO: Move these to a TOML File
const sync_audio = true; // Enable Audio Sync
const sync_audio = false; // Enable Audio Sync
const sync_video: RunKind = .LimitedFPS; // Configure Video Sync
pub const win_scale = 3; // 1x, 2x, 3x, etc. Window Scaling
pub const cpu_logging = false; // Enable detailed CPU logging
pub const allow_unhandled_io = true; // Only relevant in Debug Builds
// 228 Lines which consist of 308 dots (which are 4 cycles long)
const cycles_per_frame: u64 = 228 * (308 * 4); //280896

View File

@ -3,6 +3,8 @@ const builtin = @import("builtin");
const Log2Int = std.math.Log2Int;
const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
const allow_unhandled_io = @import("emu.zig").allow_unhandled_io;
// Sign-Extend value of type `T` to type `U`
pub fn sext(comptime T: type, comptime U: type, value: T) T {
// U must have less bits than T
@ -102,6 +104,28 @@ pub const FilePaths = struct {
save: ?[]const u8,
};
pub const io = struct {
pub const read = struct {
pub fn todo(comptime log: anytype, comptime format: []const u8, args: anytype) u8 {
log.debug(format, args);
return 0;
}
pub fn undef(comptime T: type, log: anytype, comptime format: []const u8, args: anytype) ?T {
log.warn(format, args);
if (builtin.mode == .Debug and !allow_unhandled_io) std.debug.panic("TODO: Implement I/O Register", .{});
return null;
}
};
pub const write = struct {
pub fn undef(log: anytype, comptime format: []const u8, args: anytype) void {
log.warn(format, args);
if (builtin.mode == .Debug and !allow_unhandled_io) std.debug.panic("TODO: Implement I/O Register", .{});
}
};
};
pub fn readUndefined(log: anytype, comptime format: []const u8, args: anytype) u8 {
log.warn(format, args);
if (builtin.mode == .Debug) std.debug.panic("TODO: Implement I/O Register", .{});
@ -127,6 +151,7 @@ pub const Logger = struct {
pub fn print(self: *Self, comptime format: []const u8, args: anytype) !void {
try self.buf.writer().print(format, args);
try self.buf.flush(); // FIXME: On panics, whatever is in the buffer isn't written to file
}
pub fn mgbaLog(self: *Self, cpu: *const Arm7tdmi, opcode: u32) void {
@ -166,7 +191,7 @@ pub const Logger = struct {
cpu.r[12],
cpu.r[13],
cpu.r[14],
cpu.r[15],
cpu.r[15] - if (cpu.cpsr.t.read()) 2 else @as(u32, 4),
cpu.cpsr.raw,
opcode,
};