all repos — mgba @ a6e92b6df779f0eb7fe76109f0b419a2a4bbd960

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