all repos — mgba @ 6055c4e8dbdf408f7a1a6dc367e5e6e2b9846cac

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