all repos — mgba @ 0293e723d805c3255c2873f4a1cb9de0128ee217

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