all repos — mgba @ 2def7289f3cb02c3a3edc51e26ce3f634033e264

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