all repos — mgba @ d5548f6da87cd39070d96e69bc4293c9a121ce89

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