all repos — mgba @ 8c8361477d8bd34d905368a3b76952aef65ff70d

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