all repos — mgba @ 981a8bcb7d253835c334e7b6671ce5a523917bd3

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