all repos — mgba @ e45519075a4bd3d54d0f30e41792a7973287c789

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