all repos — mgba @ a748e0c795a4ab7117eaac78349cecb303873ddf

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