all repos — mgba @ d0277a7125981d4dbe3f2f74b0367dbb4e0b21c7

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