all repos — mgba @ e11e5ef9707163895b454fbbdcab9670244e5ae9

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