all repos — mgba @ 026f5233db5a96707d2b4a06f0b22747f0b16b71

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