all repos — mgba @ b02fba9d28ee22fb0c8a2d9aa6488c7319b5c401

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