all repos — mgba @ 3a834d564daeee9f3b1671efcef3b189e3d9aab5

mGBA Game Boy Advance Emulator

src/gba/gba.c (view raw)

  1/* Copyright (c) 2013-2015 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "gba.h"
  7
  8#include "core/thread.h"
  9
 10#include "arm/decoder.h"
 11#include "arm/debugger/debugger.h"
 12#include "arm/isa-inlines.h"
 13
 14#include "gba/bios.h"
 15#include "gba/cheats.h"
 16#include "gba/io.h"
 17#include "gba/overrides.h"
 18#include "gba/rr/rr.h"
 19#include "gba/serialize.h"
 20#include "gba/sio.h"
 21#include "gba/vfame.h"
 22
 23#include "util/crc32.h"
 24#include "util/memory.h"
 25#include "util/math.h"
 26#include "util/patch.h"
 27#include "util/vfs.h"
 28
 29mLOG_DEFINE_CATEGORY(GBA, "GBA");
 30
 31const uint32_t GBA_COMPONENT_MAGIC = 0x1000000;
 32
 33static const size_t GBA_ROM_MAGIC_OFFSET = 3;
 34static const uint8_t GBA_ROM_MAGIC[] = { 0xEA };
 35
 36static const size_t GBA_MB_MAGIC_OFFSET = 0xC0;
 37
 38static void GBAInit(void* cpu, struct mCPUComponent* component);
 39static void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh);
 40static void GBAProcessEvents(struct ARMCore* cpu);
 41static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles);
 42static void GBAHitStub(struct ARMCore* cpu, uint32_t opcode);
 43static void GBAIllegal(struct ARMCore* cpu, uint32_t opcode);
 44static void GBABreakpoint(struct ARMCore* cpu, int immediate);
 45
 46static bool _setSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t* opcode);
 47static bool _clearSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t opcode);
 48
 49
 50#ifdef _3DS
 51extern uint32_t* romBuffer;
 52extern size_t romBufferSize;
 53#endif
 54
 55void GBACreate(struct GBA* gba) {
 56	gba->d.id = GBA_COMPONENT_MAGIC;
 57	gba->d.init = GBAInit;
 58	gba->d.deinit = 0;
 59}
 60
 61static void GBAInit(void* cpu, struct mCPUComponent* component) {
 62	struct GBA* gba = (struct GBA*) component;
 63	gba->cpu = cpu;
 64	gba->debugger = 0;
 65	gba->sync = 0;
 66
 67	GBAInterruptHandlerInit(&gba->cpu->irqh);
 68	GBAMemoryInit(gba);
 69	GBASavedataInit(&gba->memory.savedata, 0);
 70
 71	gba->video.p = gba;
 72	GBAVideoInit(&gba->video);
 73
 74	gba->audio.p = gba;
 75	GBAAudioInit(&gba->audio, GBA_AUDIO_SAMPLES);
 76
 77	GBAIOInit(gba);
 78
 79	gba->sio.p = gba;
 80	GBASIOInit(&gba->sio);
 81
 82	gba->timersEnabled = 0;
 83	memset(gba->timers, 0, sizeof(gba->timers));
 84
 85	gba->springIRQ = 0;
 86	gba->keySource = 0;
 87	gba->rotationSource = 0;
 88	gba->luminanceSource = 0;
 89	gba->rtcSource = 0;
 90	gba->rumble = 0;
 91	gba->rr = 0;
 92
 93	gba->romVf = 0;
 94	gba->biosVf = 0;
 95
 96	gba->stream = 0;
 97	gba->keyCallback = 0;
 98	gba->stopCallback = 0;
 99
100	gba->biosChecksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
101
102	gba->idleOptimization = IDLE_LOOP_REMOVE;
103	gba->idleLoop = IDLE_LOOP_NONE;
104
105	gba->realisticTiming = true;
106	gba->hardCrash = true;
107	gba->allowOpposingDirections = true;
108
109	gba->performingDMA = false;
110
111	gba->pristineRom = 0;
112	gba->pristineRomSize = 0;
113	gba->yankedRomSize = 0;
114}
115
116void GBAUnloadROM(struct GBA* gba) {
117	if (gba->memory.rom && gba->pristineRom != gba->memory.rom) {
118		if (gba->yankedRomSize) {
119			gba->yankedRomSize = 0;
120		}
121		mappedMemoryFree(gba->memory.rom, SIZE_CART0);
122	}
123	gba->memory.rom = 0;
124
125	if (gba->romVf) {
126#ifndef _3DS
127		gba->romVf->unmap(gba->romVf, gba->pristineRom, gba->pristineRomSize);
128#endif
129		gba->romVf->close(gba->romVf);
130		gba->pristineRom = 0;
131		gba->romVf = 0;
132	}
133
134	GBASavedataDeinit(&gba->memory.savedata);
135	gba->idleLoop = IDLE_LOOP_NONE;
136}
137
138void GBADestroy(struct GBA* gba) {
139	GBAUnloadROM(gba);
140
141	if (gba->biosVf) {
142		gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
143		gba->biosVf->close(gba->biosVf);
144		gba->biosVf = 0;
145	}
146
147	GBAMemoryDeinit(gba);
148	GBAVideoDeinit(&gba->video);
149	GBAAudioDeinit(&gba->audio);
150	GBASIODeinit(&gba->sio);
151	gba->rr = 0;
152}
153
154void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
155	irqh->reset = GBAReset;
156	irqh->processEvents = GBAProcessEvents;
157	irqh->swi16 = GBASwi16;
158	irqh->swi32 = GBASwi32;
159	irqh->hitIllegal = GBAIllegal;
160	irqh->readCPSR = GBATestIRQ;
161	irqh->hitStub = GBAHitStub;
162	irqh->bkpt16 = GBABreakpoint;
163	irqh->bkpt32 = GBABreakpoint;
164}
165
166void GBAReset(struct ARMCore* cpu) {
167	ARMSetPrivilegeMode(cpu, MODE_IRQ);
168	cpu->gprs[ARM_SP] = SP_BASE_IRQ;
169	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
170	cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
171	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
172	cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
173
174	struct GBA* gba = (struct GBA*) cpu->master;
175	if (!gba->rr || (!gba->rr->isPlaying(gba->rr) && !gba->rr->isRecording(gba->rr))) {
176		GBASavedataUnmask(&gba->memory.savedata);
177	}
178
179	if (gba->yankedRomSize) {
180		gba->memory.romSize = gba->yankedRomSize;
181		gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
182		gba->yankedRomSize = 0;
183	}
184	GBAMemoryReset(gba);
185	GBAVideoReset(&gba->video);
186	GBAAudioReset(&gba->audio);
187	GBAIOInit(gba);
188
189	GBASIOReset(&gba->sio);
190
191	gba->timersEnabled = 0;
192	memset(gba->timers, 0, sizeof(gba->timers));
193
194	gba->lastJump = 0;
195	gba->haltPending = false;
196	gba->idleDetectionStep = 0;
197	gba->idleDetectionFailures = 0;
198}
199
200void GBASkipBIOS(struct GBA* gba) {
201	struct ARMCore* cpu = gba->cpu;
202	if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
203		if (gba->memory.rom) {
204			cpu->gprs[ARM_PC] = BASE_CART0;
205		} else {
206			cpu->gprs[ARM_PC] = BASE_WORKING_RAM;
207		}
208		int currentCycles = 0;
209		ARM_WRITE_PC;
210	}
211}
212
213static void GBAProcessEvents(struct ARMCore* cpu) {
214	struct GBA* gba = (struct GBA*) cpu->master;
215
216	gba->bus = cpu->prefetch[1];
217	if (cpu->executionMode == MODE_THUMB) {
218		gba->bus |= cpu->prefetch[1] << 16;
219	}
220
221	if (gba->springIRQ && !cpu->cpsr.i) {
222		ARMRaiseIRQ(cpu);
223		gba->springIRQ = 0;
224	}
225
226	do {
227		int32_t cycles = cpu->nextEvent;
228		int32_t nextEvent = INT_MAX;
229		int32_t testEvent;
230#ifndef NDEBUG
231		if (cycles < 0) {
232			mLOG(GBA, FATAL, "Negative cycles passed: %i", cycles);
233		}
234#endif
235
236		testEvent = GBAVideoProcessEvents(&gba->video, cycles);
237		if (testEvent < nextEvent) {
238#ifndef NDEBUG
239			if (testEvent == 0) {
240				mLOG(GBA, ERROR, "Video requiring 0 cycles");
241			}
242#endif
243			nextEvent = testEvent;
244		}
245
246		testEvent = GBAAudioProcessEvents(&gba->audio, cycles);
247		if (testEvent < nextEvent) {
248#ifndef NDEBUG
249			if (testEvent == 0) {
250				mLOG(GBA, ERROR, "Audio requiring 0 cycles");
251			}
252#endif
253			nextEvent = testEvent;
254		}
255
256		testEvent = GBATimersProcessEvents(gba, cycles);
257		if (testEvent < nextEvent) {
258#ifndef NDEBUG
259			if (testEvent == 0) {
260				mLOG(GBA, ERROR, "Timers requiring 0 cycles");
261			}
262#endif
263			nextEvent = testEvent;
264		}
265
266		testEvent = GBAMemoryRunDMAs(gba, cycles);
267		if (testEvent < nextEvent) {
268#ifndef NDEBUG
269			if (testEvent == 0) {
270				mLOG(GBA, ERROR, "DMAs requiring 0 cycles");
271			}
272#endif
273			nextEvent = testEvent;
274		}
275
276		testEvent = GBASIOProcessEvents(&gba->sio, cycles);
277		if (testEvent < nextEvent) {
278			nextEvent = testEvent;
279		}
280
281		cpu->cycles -= cycles;
282		cpu->nextEvent = nextEvent;
283
284		if (cpu->halted) {
285			cpu->cycles = cpu->nextEvent;
286		}
287		if (nextEvent == 0) {
288			break;
289		}
290#ifndef NDEBUG
291		else if (nextEvent < 0) {
292			mLOG(GBA, FATAL, "Negative cycles will pass: %i", nextEvent);
293		}
294#endif
295	} while (cpu->cycles >= cpu->nextEvent);
296}
297
298static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles) {
299	int32_t nextEvent = INT_MAX;
300	if (gba->timersEnabled) {
301		struct GBATimer* timer;
302		struct GBATimer* nextTimer;
303
304		timer = &gba->timers[0];
305		if (GBATimerFlagsIsEnable(timer->flags)) {
306			timer->nextEvent -= cycles;
307			timer->lastEvent -= cycles;
308			while (timer->nextEvent <= 0) {
309				timer->lastEvent = timer->nextEvent;
310				timer->nextEvent += timer->overflowInterval;
311				gba->memory.io[REG_TM0CNT_LO >> 1] = timer->reload;
312				timer->oldReload = timer->reload;
313
314				if (GBATimerFlagsIsDoIrq(timer->flags)) {
315					GBARaiseIRQ(gba, IRQ_TIMER0);
316				}
317
318				if (gba->audio.enable) {
319					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 0) {
320						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
321					}
322
323					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 0) {
324						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
325					}
326				}
327
328				nextTimer = &gba->timers[1];
329				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
330					++gba->memory.io[REG_TM1CNT_LO >> 1];
331					if (!gba->memory.io[REG_TM1CNT_LO >> 1]) {
332						nextTimer->nextEvent = 0;
333					}
334				}
335			}
336			nextEvent = timer->nextEvent;
337		}
338
339		timer = &gba->timers[1];
340		if (GBATimerFlagsIsEnable(timer->flags)) {
341			timer->nextEvent -= cycles;
342			timer->lastEvent -= cycles;
343			if (timer->nextEvent <= 0) {
344				timer->lastEvent = timer->nextEvent;
345				timer->nextEvent += timer->overflowInterval;
346				gba->memory.io[REG_TM1CNT_LO >> 1] = timer->reload;
347				timer->oldReload = timer->reload;
348
349				if (GBATimerFlagsIsDoIrq(timer->flags)) {
350					GBARaiseIRQ(gba, IRQ_TIMER1);
351				}
352
353				if (gba->audio.enable) {
354					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 1) {
355						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
356					}
357
358					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 1) {
359						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
360					}
361				}
362
363				if (GBATimerFlagsIsCountUp(timer->flags)) {
364					timer->nextEvent = INT_MAX;
365				}
366
367				nextTimer = &gba->timers[2];
368				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
369					++gba->memory.io[REG_TM2CNT_LO >> 1];
370					if (!gba->memory.io[REG_TM2CNT_LO >> 1]) {
371						nextTimer->nextEvent = 0;
372					}
373				}
374			}
375			if (timer->nextEvent < nextEvent) {
376				nextEvent = timer->nextEvent;
377			}
378		}
379
380		timer = &gba->timers[2];
381		if (GBATimerFlagsIsEnable(timer->flags)) {
382			timer->nextEvent -= cycles;
383			timer->lastEvent -= cycles;
384			if (timer->nextEvent <= 0) {
385				timer->lastEvent = timer->nextEvent;
386				timer->nextEvent += timer->overflowInterval;
387				gba->memory.io[REG_TM2CNT_LO >> 1] = timer->reload;
388				timer->oldReload = timer->reload;
389
390				if (GBATimerFlagsIsDoIrq(timer->flags)) {
391					GBARaiseIRQ(gba, IRQ_TIMER2);
392				}
393
394				if (GBATimerFlagsIsCountUp(timer->flags)) {
395					timer->nextEvent = INT_MAX;
396				}
397
398				nextTimer = &gba->timers[3];
399				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
400					++gba->memory.io[REG_TM3CNT_LO >> 1];
401					if (!gba->memory.io[REG_TM3CNT_LO >> 1]) {
402						nextTimer->nextEvent = 0;
403					}
404				}
405			}
406			if (timer->nextEvent < nextEvent) {
407				nextEvent = timer->nextEvent;
408			}
409		}
410
411		timer = &gba->timers[3];
412		if (GBATimerFlagsIsEnable(timer->flags)) {
413			timer->nextEvent -= cycles;
414			timer->lastEvent -= cycles;
415			if (timer->nextEvent <= 0) {
416				timer->lastEvent = timer->nextEvent;
417				timer->nextEvent += timer->overflowInterval;
418				gba->memory.io[REG_TM3CNT_LO >> 1] = timer->reload;
419				timer->oldReload = timer->reload;
420
421				if (GBATimerFlagsIsDoIrq(timer->flags)) {
422					GBARaiseIRQ(gba, IRQ_TIMER3);
423				}
424
425				if (GBATimerFlagsIsCountUp(timer->flags)) {
426					timer->nextEvent = INT_MAX;
427				}
428			}
429			if (timer->nextEvent < nextEvent) {
430				nextEvent = timer->nextEvent;
431			}
432		}
433	}
434	return nextEvent;
435}
436
437void GBAAttachDebugger(struct GBA* gba, struct mDebugger* debugger) {
438	gba->debugger = (struct ARMDebugger*) debugger->platform;
439	gba->debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
440	gba->debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
441	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
442	ARMHotplugAttach(gba->cpu, CPU_COMPONENT_DEBUGGER);
443}
444
445void GBADetachDebugger(struct GBA* gba) {
446	gba->debugger = 0;
447	ARMHotplugDetach(gba->cpu, CPU_COMPONENT_DEBUGGER);
448	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = 0;
449}
450
451bool GBALoadMB(struct GBA* gba, struct VFile* vf) {
452	GBAUnloadROM(gba);
453	gba->romVf = vf;
454	gba->pristineRomSize = vf->size(vf);
455	vf->seek(vf, 0, SEEK_SET);
456	if (gba->pristineRomSize > SIZE_WORKING_RAM) {
457		gba->pristineRomSize = SIZE_WORKING_RAM;
458	}
459#ifdef _3DS
460	gba->pristineRom = 0;
461	if (gba->pristineRomSize <= romBufferSize) {
462		gba->pristineRom = romBuffer;
463		vf->read(vf, romBuffer, gba->pristineRomSize);
464	}
465#else
466	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
467#endif
468	if (!gba->pristineRom) {
469		mLOG(GBA, WARN, "Couldn't map ROM");
470		return false;
471	}
472	gba->yankedRomSize = 0;
473	gba->memory.romSize = 0;
474	gba->memory.romMask = 0;
475	gba->romCrc32 = doCrc32(gba->pristineRom, gba->pristineRomSize);
476	return true;
477}
478
479bool GBALoadROM(struct GBA* gba, struct VFile* vf) {
480	GBAUnloadROM(gba);
481	gba->romVf = vf;
482	gba->pristineRomSize = vf->size(vf);
483	vf->seek(vf, 0, SEEK_SET);
484	if (gba->pristineRomSize > SIZE_CART0) {
485		gba->pristineRomSize = SIZE_CART0;
486	}
487#ifdef _3DS
488	gba->pristineRom = 0;
489	if (gba->pristineRomSize <= romBufferSize) {
490		gba->pristineRom = romBuffer;
491		vf->read(vf, romBuffer, gba->pristineRomSize);
492	}
493#else
494	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
495#endif
496	if (!gba->pristineRom) {
497		mLOG(GBA, WARN, "Couldn't map ROM");
498		return false;
499	}
500	gba->yankedRomSize = 0;
501	gba->memory.rom = gba->pristineRom;
502	gba->memory.romSize = gba->pristineRomSize;
503	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
504	gba->memory.mirroring = false;
505	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
506	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
507	GBAVFameDetect(&gba->memory.vfame, gba->memory.rom, gba->memory.romSize);
508	// TODO: error check
509	return true;
510}
511
512bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
513	GBASavedataInit(&gba->memory.savedata, sav);
514	return true;
515}
516
517void GBAYankROM(struct GBA* gba) {
518	gba->yankedRomSize = gba->memory.romSize;
519	gba->memory.romSize = 0;
520	gba->memory.romMask = 0;
521	GBARaiseIRQ(gba, IRQ_GAMEPAK);
522}
523
524void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
525	gba->biosVf = vf;
526	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
527	if (!bios) {
528		mLOG(GBA, WARN, "Couldn't map BIOS");
529		return;
530	}
531	gba->memory.bios = bios;
532	gba->memory.fullBios = 1;
533	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
534	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
535	if (checksum == GBA_BIOS_CHECKSUM) {
536		mLOG(GBA, INFO, "Official GBA BIOS detected");
537	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
538		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
539	} else {
540		mLOG(GBA, WARN, "BIOS checksum incorrect");
541	}
542	gba->biosChecksum = checksum;
543	if (gba->memory.activeRegion == REGION_BIOS) {
544		gba->cpu->memory.activeRegion = gba->memory.bios;
545	}
546	// TODO: error check
547}
548
549void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
550	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
551	if (!patchedSize || patchedSize > SIZE_CART0) {
552		return;
553	}
554	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
555	if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
556		mappedMemoryFree(gba->memory.rom, patchedSize);
557		gba->memory.rom = gba->pristineRom;
558		return;
559	}
560	gba->memory.romSize = patchedSize;
561	gba->memory.romMask = SIZE_CART0 - 1;
562	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
563}
564
565void GBATimerUpdateRegister(struct GBA* gba, int timer) {
566	struct GBATimer* currentTimer = &gba->timers[timer];
567	if (GBATimerFlagsIsEnable(currentTimer->flags) && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
568		int32_t prefetchSkew = 0;
569		if (gba->memory.lastPrefetchedPc >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
570			prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
571		}
572		// Reading this takes two cycles (1N+1I), so let's remove them preemptively
573		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> GBATimerFlagsGetPrescaleBits(currentTimer->flags));
574	}
575}
576
577void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
578	gba->timers[timer].reload = reload;
579	gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << GBATimerFlagsGetPrescaleBits(gba->timers[timer].flags);
580}
581
582void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
583	struct GBATimer* currentTimer = &gba->timers[timer];
584	GBATimerUpdateRegister(gba, timer);
585
586	unsigned oldPrescale = GBATimerFlagsGetPrescaleBits(currentTimer->flags);
587	switch (control & 0x0003) {
588	case 0x0000:
589		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 0);
590		break;
591	case 0x0001:
592		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 6);
593		break;
594	case 0x0002:
595		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 8);
596		break;
597	case 0x0003:
598		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 10);
599		break;
600	}
601	currentTimer->flags = GBATimerFlagsTestFillCountUp(currentTimer->flags, timer > 0 && (control & 0x0004));
602	currentTimer->flags = GBATimerFlagsTestFillDoIrq(currentTimer->flags, control & 0x0040);
603	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << GBATimerFlagsGetPrescaleBits(currentTimer->flags);
604	bool wasEnabled = GBATimerFlagsIsEnable(currentTimer->flags);
605	currentTimer->flags = GBATimerFlagsTestFillEnable(currentTimer->flags, control & 0x0080);
606	if (!wasEnabled && GBATimerFlagsIsEnable(currentTimer->flags)) {
607		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
608			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
609		} else {
610			currentTimer->nextEvent = INT_MAX;
611		}
612		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
613		currentTimer->oldReload = currentTimer->reload;
614		currentTimer->lastEvent = gba->cpu->cycles;
615		gba->timersEnabled |= 1 << timer;
616	} else if (wasEnabled && !GBATimerFlagsIsEnable(currentTimer->flags)) {
617		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
618			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
619		}
620		gba->timersEnabled &= ~(1 << timer);
621	} else if (GBATimerFlagsGetPrescaleBits(currentTimer->flags) != oldPrescale && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
622		// FIXME: this might be before present
623		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
624	}
625
626	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
627		gba->cpu->nextEvent = currentTimer->nextEvent;
628	}
629};
630
631void GBAWriteIE(struct GBA* gba, uint16_t value) {
632	if (value & (1 << IRQ_KEYPAD)) {
633		mLOG(GBA, STUB, "Keypad interrupts not implemented");
634	}
635
636	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
637		ARMRaiseIRQ(gba->cpu);
638	}
639}
640
641void GBAWriteIME(struct GBA* gba, uint16_t value) {
642	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
643		ARMRaiseIRQ(gba->cpu);
644	}
645}
646
647void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
648	gba->memory.io[REG_IF >> 1] |= 1 << irq;
649	gba->cpu->halted = 0;
650
651	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
652		ARMRaiseIRQ(gba->cpu);
653	}
654}
655
656void GBATestIRQ(struct ARMCore* cpu) {
657	struct GBA* gba = (struct GBA*) cpu->master;
658	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
659		gba->springIRQ = 1;
660		gba->cpu->nextEvent = gba->cpu->cycles;
661	}
662}
663
664void GBAHalt(struct GBA* gba) {
665	gba->cpu->nextEvent = gba->cpu->cycles;
666	gba->cpu->halted = 1;
667}
668
669void GBAStop(struct GBA* gba) {
670	if (!gba->stopCallback) {
671		return;
672	}
673	gba->cpu->nextEvent = gba->cpu->cycles;
674	gba->stopCallback->stop(gba->stopCallback);
675}
676
677bool GBAIsROM(struct VFile* vf) {
678	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
679		return false;
680	}
681	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
682	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
683		return false;
684	}
685	if (GBAIsBIOS(vf)) {
686		return false;
687	}
688	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
689}
690
691bool GBAIsMB(struct VFile* vf) {
692	if (!GBAIsROM(vf)) {
693		return false;
694	}
695	if (vf->size(vf) > SIZE_WORKING_RAM) {
696		return false;
697	}
698	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
699		return false;
700	}
701	uint32_t signature;
702	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
703		return false;
704	}
705	uint32_t opcode;
706	LOAD_32(opcode, 0, &signature);
707	struct ARMInstructionInfo info;
708	ARMDecodeARM(opcode, &info);
709	if (info.branchType != ARM_BRANCH) {
710		return false;
711	}
712	if (info.op1.immediate <= 0) {
713		return false;
714	} else if (info.op1.immediate == 28) {
715		// Ancient toolchain that is known to throw MB detection for a loop
716		return false;
717	} else if (info.op1.immediate != 24) {
718		return true;
719	}
720	// Found a libgba-linked cart...these are a bit harder to detect.
721	return false;
722}
723
724bool GBAIsBIOS(struct VFile* vf) {
725	if (vf->seek(vf, 0, SEEK_SET) < 0) {
726		return false;
727	}
728	uint8_t interruptTable[7 * 4];
729	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
730		return false;
731	}
732	int i;
733	for (i = 0; i < 7; ++i) {
734		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
735			return false;
736		}
737	}
738	return true;
739}
740
741void GBAGetGameCode(struct GBA* gba, char* out) {
742	memset(out, 0, 8);
743	if (!gba->memory.rom) {
744		return;
745	}
746
747	memcpy(out, "AGB-", 4);
748	memcpy(&out[4], &((struct GBACartridge*) gba->memory.rom)->id, 4);
749}
750
751void GBAGetGameTitle(struct GBA* gba, char* out) {
752	if (gba->memory.rom) {
753		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
754		return;
755	}
756	if (gba->pristineRom) {
757		memcpy(out, &((struct GBACartridge*) gba->pristineRom)->title, 12);
758		return;
759	}
760	strncpy(out, "(BIOS)", 12);
761}
762
763void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
764	struct GBA* gba = (struct GBA*) cpu->master;
765	if (gba->debugger) {
766		struct mDebuggerEntryInfo info = {
767			.address = _ARMPCAddress(cpu),
768			.opcode = opcode
769		};
770		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
771	}
772	// TODO: More sensible category?
773	mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
774}
775
776void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
777	struct GBA* gba = (struct GBA*) cpu->master;
778	if (!gba->yankedRomSize) {
779		// TODO: More sensible category?
780		mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
781	}
782	if (gba->debugger) {
783		struct mDebuggerEntryInfo info = {
784			.address = _ARMPCAddress(cpu),
785			.opcode = opcode
786		};
787		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
788	} else {
789		ARMRaiseUndefined(cpu);
790	}
791}
792
793void GBABreakpoint(struct ARMCore* cpu, int immediate) {
794	struct GBA* gba = (struct GBA*) cpu->master;
795	if (immediate >= CPU_COMPONENT_MAX) {
796		return;
797	}
798	switch (immediate) {
799	case CPU_COMPONENT_DEBUGGER:
800		if (gba->debugger) {
801			struct mDebuggerEntryInfo info = {
802				.address = _ARMPCAddress(cpu)
803			};
804			mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
805		}
806		break;
807	case CPU_COMPONENT_CHEAT_DEVICE:
808		if (gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
809			struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
810			struct GBACheatHook* hook = 0;
811			size_t i;
812			for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
813				struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
814				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
815					mCheatRefresh(device, &cheats->d);
816					hook = cheats->hook;
817				}
818			}
819			if (hook) {
820				ARMRunFake(cpu, hook->patchedOpcode);
821			}
822		}
823		break;
824	default:
825		break;
826	}
827}
828
829void GBAFrameStarted(struct GBA* gba) {
830	UNUSED(gba);
831
832	struct mCoreThread* thread = mCoreThreadGet();
833	mCoreThreadFrameStarted(thread);
834}
835
836void GBAFrameEnded(struct GBA* gba) {
837	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
838
839	if (gba->rr) {
840		gba->rr->nextFrame(gba->rr);
841	}
842
843	if (gba->cpu->components && gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
844		struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
845		size_t i;
846		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
847			struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
848			mCheatRefresh(device, &cheats->d);
849		}
850	}
851
852	if (gba->stream && gba->stream->postVideoFrame) {
853		const color_t* pixels;
854		unsigned stride;
855		gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
856		gba->stream->postVideoFrame(gba->stream, pixels, stride);
857	}
858
859	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
860		GBAHardwarePlayerUpdate(gba);
861	}
862
863	struct mCoreThread* thread = mCoreThreadGet();
864	mCoreThreadFrameEnded(thread);
865
866	// TODO: Put back RR
867}
868
869void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
870	size_t immediate;
871	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
872		if (gba->cpu->components[immediate] == component) {
873			break;
874		}
875	}
876	if (immediate == gba->cpu->numComponents) {
877		return;
878	}
879	if (mode == MODE_ARM) {
880		int32_t value;
881		int32_t old;
882		value = 0xE1200070;
883		value |= immediate & 0xF;
884		value |= (immediate & 0xFFF0) << 4;
885		GBAPatch32(gba->cpu, address, value, &old);
886		*opcode = old;
887	} else {
888		int16_t value;
889		int16_t old;
890		value = 0xBE00;
891		value |= immediate & 0xFF;
892		GBAPatch16(gba->cpu, address, value, &old);
893		*opcode = (uint16_t) old;
894	}
895}
896
897void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
898	if (mode == MODE_ARM) {
899		GBAPatch32(gba->cpu, address, opcode, 0);
900	} else {
901		GBAPatch16(gba->cpu, address, opcode, 0);
902	}
903}
904
905static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
906	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d.p->d, address, mode, opcode);
907	return true;
908}
909
910static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
911	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
912	return true;
913}