all repos — mgba @ 11035f5a778d92bdbbc07c1302fde03353f2b7ee

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