aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/cpu/Cpu.kt
diff options
context:
space:
mode:
authorJames Barnett <noreply@jamesbarnett.xyz>2018-07-21 19:46:20 +0100
committerJames Barnett <noreply@jamesbarnett.xyz>2018-07-21 19:46:20 +0100
commitc6a953d722b1fdc27a9db6f78f00c52fe43a7222 (patch)
tree6efab06c40d0bd3c26876ca2b40f2f0f20b2def2 /src/main/kotlin/cpu/Cpu.kt
parent2861f2db6f918c48019c1ac3f91bf6a407452493 (diff)
downloadKGB-c6a953d722b1fdc27a9db6f78f00c52fe43a7222.tar.xz
KGB-c6a953d722b1fdc27a9db6f78f00c52fe43a7222.zip
Add ability to step through CPU execution of boot rom
Diffstat (limited to 'src/main/kotlin/cpu/Cpu.kt')
-rw-r--r--src/main/kotlin/cpu/Cpu.kt61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/main/kotlin/cpu/Cpu.kt b/src/main/kotlin/cpu/Cpu.kt
index 91150c4..f474dbb 100644
--- a/src/main/kotlin/cpu/Cpu.kt
+++ b/src/main/kotlin/cpu/Cpu.kt
@@ -2,12 +2,16 @@ package cpu
import cpu.opcodes.*
import ram.Ram
+import kotlin.concurrent.thread
class Cpu {
val registers = Registers()
val ram = Ram()
+ var currentOp: Operation? = null
+ var nextOp: Operation? = null
+
var standardOpcodes: Map<Int, Operation>
var extendedOpcodes: Map<Int, Operation>
init {
@@ -33,4 +37,61 @@ class Cpu {
}
+ fun loadRom(rom: ByteArray) {
+ ram.load(rom)
+ }
+
+ fun executeNextInstruction() {
+
+ val (op, opArgs) = getNextOp()
+ op.command.invoke(registers, ram, opArgs)
+
+ currentOp = op
+ nextOp = peekNextOp()
+ }
+
+ fun run() {
+ thread {
+ while(true) {
+ executeNextInstruction()
+ }
+ }
+
+ }
+
+ private fun getNextOp(): Pair<Operation, IntArray> {
+
+ var addr = registers.PC
+ val startByte = ram.readByte(addr)
+ val op: Operation
+
+ op = if(startByte == 0xCB) {
+ extendedOpcodes[ram.readByte(++addr)]!!
+ } else {
+ standardOpcodes[startByte]!!
+ }
+
+ val opLength = op.length
+ val opArgs = IntArray(opLength)
+
+ IntRange(0, opLength -1).forEach {i ->
+ opArgs[i] = ram.readByte(++addr)
+ }
+
+ registers.PC = ++addr
+
+ return Pair(op, opArgs)
+ }
+
+
+ private fun peekNextOp(): Operation {
+
+ val startByte = ram.readByte(registers.PC)
+ return if(startByte == 0xCB) {
+ extendedOpcodes[ram.readByte(registers.PC + 1)]!!
+ } else {
+ standardOpcodes[startByte]!!
+ }
+ }
+
} \ No newline at end of file