all repos — mgba @ 5a50f47bf70069865ced0c306c789d77270af453

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	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	bool isELF = false;
220#ifdef USE_ELF
221	struct ELF* elf = ELFOpen(gba->romVf);
222	if (elf) {
223		isELF = true;
224		ELFClose(elf);
225	}
226#endif
227
228	if (GBAIsMB(gba->romVf) && !isELF) {
229		gba->romVf->seek(gba->romVf, 0, SEEK_SET);
230		gba->romVf->read(gba->romVf, gba->memory.wram, gba->pristineRomSize);
231	}
232
233	gba->lastJump = 0;
234	gba->haltPending = false;
235	gba->idleDetectionStep = 0;
236	gba->idleDetectionFailures = 0;
237
238	gba->debug = false;
239	memset(gba->debugString, 0, sizeof(gba->debugString));
240
241
242	if (gba->romVf && gba->pristineRomSize > SIZE_CART0) {
243		char ident;
244		gba->romVf->seek(gba->romVf, 0xAC, SEEK_SET);
245		gba->romVf->read(gba->romVf, &ident, 1);
246		gba->romVf->seek(gba->romVf, 0, SEEK_SET);
247		if (ident == 'M') {
248			GBAMatrixReset(gba);
249		}
250	}
251}
252
253void GBASkipBIOS(struct GBA* gba) {
254	struct ARMCore* cpu = gba->cpu;
255	if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
256		if (gba->memory.rom) {
257			cpu->gprs[ARM_PC] = BASE_CART0;
258		} else {
259			cpu->gprs[ARM_PC] = BASE_WORKING_RAM + 0xC0;
260		}
261		gba->video.vcount = 0x7D;
262		gba->memory.io[REG_VCOUNT >> 1] = 0x7D;
263		gba->memory.io[REG_POSTFLG >> 1] = 1;
264		ARMWritePC(cpu);
265	}
266}
267
268static void GBAProcessEvents(struct ARMCore* cpu) {
269	struct GBA* gba = (struct GBA*) cpu->master;
270
271	gba->bus = cpu->prefetch[1];
272	if (cpu->executionMode == MODE_THUMB) {
273		gba->bus |= cpu->prefetch[1] << 16;
274	}
275
276	int32_t nextEvent = cpu->nextEvent;
277	while (cpu->cycles >= nextEvent) {
278		cpu->nextEvent = INT_MAX;
279		nextEvent = 0;
280		do {
281			int32_t cycles = cpu->cycles;
282			cpu->cycles = 0;
283#ifdef USE_DEBUGGERS
284			gba->timing.globalCycles += cycles;
285#endif
286#ifndef NDEBUG
287			if (cycles < 0) {
288				mLOG(GBA, FATAL, "Negative cycles passed: %i", cycles);
289			}
290#endif
291			nextEvent = mTimingTick(&gba->timing, cycles < nextEvent ? nextEvent : cycles);
292		} while (gba->cpuBlocked && !gba->earlyExit);
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	if (gba->cpuBlocked) {
312		cpu->cycles = cpu->nextEvent;
313	}
314}
315
316#ifdef USE_DEBUGGERS
317void GBAAttachDebugger(struct GBA* gba, struct mDebugger* debugger) {
318	gba->debugger = (struct ARMDebugger*) debugger->platform;
319	gba->debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
320	gba->debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
321	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
322	ARMHotplugAttach(gba->cpu, CPU_COMPONENT_DEBUGGER);
323}
324
325void GBADetachDebugger(struct GBA* gba) {
326	if (gba->debugger) {
327		ARMHotplugDetach(gba->cpu, CPU_COMPONENT_DEBUGGER);
328	}
329	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
330	gba->debugger = NULL;
331}
332#endif
333
334bool GBALoadNull(struct GBA* gba) {
335	GBAUnloadROM(gba);
336	gba->romVf = NULL;
337	gba->pristineRomSize = 0;
338#ifndef FIXED_ROM_BUFFER
339	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
340#else
341	gba->memory.rom = romBuffer;
342#endif
343	gba->isPristine = false;
344	gba->yankedRomSize = 0;
345	gba->memory.romSize = SIZE_CART0;
346	gba->memory.romMask = SIZE_CART0 - 1;
347	gba->memory.mirroring = false;
348	gba->romCrc32 = 0;
349
350	if (gba->cpu) {
351		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
352	}
353	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
354	return true;
355}
356
357bool GBALoadMB(struct GBA* gba, struct VFile* vf) {
358	GBAUnloadROM(gba);
359	gba->romVf = vf;
360	gba->pristineRomSize = vf->size(vf);
361	vf->seek(vf, 0, SEEK_SET);
362	if (gba->pristineRomSize > SIZE_WORKING_RAM) {
363		gba->pristineRomSize = SIZE_WORKING_RAM;
364	}
365	gba->isPristine = true;
366	memset(gba->memory.wram, 0, SIZE_WORKING_RAM);
367	gba->yankedRomSize = 0;
368	gba->memory.romSize = 0;
369	gba->memory.romMask = 0;
370	gba->romCrc32 = doCrc32(gba->memory.wram, gba->pristineRomSize);
371	if (gba->cpu && gba->memory.activeRegion == REGION_WORKING_RAM) {
372		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
373	}
374	return true;
375}
376
377bool GBALoadROM(struct GBA* gba, struct VFile* vf) {
378	if (!vf) {
379		return false;
380	}
381	GBAUnloadROM(gba);
382	gba->romVf = vf;
383	gba->pristineRomSize = vf->size(vf);
384	vf->seek(vf, 0, SEEK_SET);
385	if (gba->pristineRomSize > SIZE_CART0) {
386		gba->isPristine = false;
387		char ident;
388		vf->seek(vf, 0xAC, SEEK_SET);
389		vf->read(vf, &ident, 1);
390		if (ident == 'M') {
391			gba->memory.romSize = 0x01000000;
392#ifdef FIXED_ROM_BUFFER
393			gba->memory.rom = romBuffer;
394#else
395			gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
396#endif
397		} else {
398			gba->memory.rom = vf->map(vf, SIZE_CART0, MAP_READ);
399			gba->memory.romSize = SIZE_CART0;
400		}
401	} else {
402		gba->isPristine = true;
403		gba->memory.rom = vf->map(vf, gba->pristineRomSize, MAP_READ);
404		gba->memory.romSize = gba->pristineRomSize;
405	}
406	if (!gba->memory.rom) {
407		mLOG(GBA, WARN, "Couldn't map ROM");
408		return false;
409	}
410	gba->yankedRomSize = 0;
411	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
412	gba->memory.mirroring = false;
413	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
414	if (popcount32(gba->memory.romSize) != 1) {
415		// This ROM is either a bad dump or homebrew. Emulate flash cart behavior.
416#ifndef FIXED_ROM_BUFFER
417		void* newRom = anonymousMemoryMap(SIZE_CART0);
418		memcpy(newRom, gba->memory.rom, gba->pristineRomSize);
419		gba->memory.rom = newRom;
420#endif
421		gba->memory.romSize = SIZE_CART0;
422		gba->memory.romMask = SIZE_CART0 - 1;
423		gba->isPristine = false;
424	}
425	if (gba->cpu && gba->memory.activeRegion >= REGION_CART0) {
426		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
427	}
428	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
429	GBAVFameDetect(&gba->memory.vfame, gba->memory.rom, gba->memory.romSize);
430	// TODO: error check
431	return true;
432}
433
434bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
435	GBASavedataInit(&gba->memory.savedata, sav);
436	return sav;
437}
438
439void GBAYankROM(struct GBA* gba) {
440	gba->yankedRomSize = gba->memory.romSize;
441	gba->memory.romSize = 0;
442	gba->memory.romMask = 0;
443	GBARaiseIRQ(gba, IRQ_GAMEPAK, 0);
444}
445
446void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
447	if (vf->size(vf) != SIZE_BIOS) {
448		mLOG(GBA, WARN, "Incorrect BIOS size");
449		return;
450	}
451	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
452	if (!bios) {
453		mLOG(GBA, WARN, "Couldn't map BIOS");
454		return;
455	}
456	if (gba->biosVf) {
457		gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
458		gba->biosVf->close(gba->biosVf);
459	}
460	gba->biosVf = vf;
461	gba->memory.bios = bios;
462	gba->memory.fullBios = 1;
463	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
464	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
465	if (checksum == GBA_BIOS_CHECKSUM) {
466		mLOG(GBA, INFO, "Official GBA BIOS detected");
467	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
468		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
469	} else {
470		mLOG(GBA, WARN, "BIOS checksum incorrect");
471	}
472	gba->biosChecksum = checksum;
473	if (gba->memory.activeRegion == REGION_BIOS) {
474		gba->cpu->memory.activeRegion = gba->memory.bios;
475	}
476	// TODO: error check
477}
478
479void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
480	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
481	if (!patchedSize || patchedSize > SIZE_CART0) {
482		return;
483	}
484	void* newRom = anonymousMemoryMap(SIZE_CART0);
485	if (!patch->applyPatch(patch, gba->memory.rom, gba->pristineRomSize, newRom, patchedSize)) {
486		mappedMemoryFree(newRom, SIZE_CART0);
487		return;
488	}
489	if (gba->romVf) {
490#ifndef FIXED_ROM_BUFFER
491		gba->romVf->unmap(gba->romVf, gba->memory.rom, gba->pristineRomSize);
492#endif
493		gba->romVf->close(gba->romVf);
494		gba->romVf = NULL;
495	}
496	gba->isPristine = false;
497	gba->memory.rom = newRom;
498	gba->memory.hw.gpioBase = &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1];
499	gba->memory.romSize = patchedSize;
500	gba->memory.romMask = SIZE_CART0 - 1;
501	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
502}
503
504void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq, uint32_t cyclesLate) {
505	gba->memory.io[REG_IF >> 1] |= 1 << irq;
506	GBATestIRQ(gba, cyclesLate);
507}
508
509void GBATestIRQNoDelay(struct ARMCore* cpu) {
510	struct GBA* gba = (struct GBA*) cpu->master;
511	GBATestIRQ(gba, 0);
512}
513
514void GBATestIRQ(struct GBA* gba, uint32_t cyclesLate) {
515	if (gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
516		if (!mTimingIsScheduled(&gba->timing, &gba->irqEvent)) {
517			mTimingSchedule(&gba->timing, &gba->irqEvent, GBA_IRQ_DELAY - cyclesLate);
518		}
519	}
520}
521
522void GBAHalt(struct GBA* gba) {
523	gba->cpu->nextEvent = gba->cpu->cycles;
524	gba->cpu->halted = 1;
525}
526
527void GBAStop(struct GBA* gba) {
528	int validIrqs = (1 << IRQ_GAMEPAK) | (1 << IRQ_KEYPAD) | (1 << IRQ_SIO);
529	int sleep = gba->memory.io[REG_IE >> 1] & validIrqs;
530	size_t c;
531	for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
532		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
533		if (sleep && callbacks->sleep) {
534			callbacks->sleep(callbacks->context);
535		} else if (callbacks->shutdown) {
536			callbacks->shutdown(callbacks->context);
537		}
538	}
539	gba->cpu->nextEvent = gba->cpu->cycles;
540}
541
542void GBADebug(struct GBA* gba, uint16_t flags) {
543	gba->debugFlags = flags;
544	if (GBADebugFlagsIsSend(gba->debugFlags)) {
545		int level = 1 << GBADebugFlagsGetLevel(gba->debugFlags);
546		level &= 0x1F;
547		char oolBuf[0x101];
548		strncpy(oolBuf, gba->debugString, sizeof(oolBuf) - 1);
549		memset(gba->debugString, 0, sizeof(gba->debugString));
550		oolBuf[0x100] = '\0';
551		mLog(_mLOG_CAT_GBA_DEBUG, level, "%s", oolBuf);
552	}
553	gba->debugFlags = GBADebugFlagsClearSend(gba->debugFlags);
554}
555
556bool GBAIsROM(struct VFile* vf) {
557#ifdef USE_ELF
558	struct ELF* elf = ELFOpen(vf);
559	if (elf) {
560		uint32_t entry = ELFEntry(elf);
561		bool isGBA = true;
562		isGBA = isGBA && ELFMachine(elf) == EM_ARM;
563		isGBA = isGBA && (entry == BASE_CART0 || entry == BASE_WORKING_RAM);
564		ELFClose(elf);
565		return isGBA;
566	}
567#endif
568	if (!vf) {
569		return false;
570	}
571
572	uint8_t signature[sizeof(GBA_ROM_MAGIC) + sizeof(GBA_ROM_MAGIC2)];
573	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
574		return false;
575	}
576	if (vf->read(vf, &signature, sizeof(GBA_ROM_MAGIC)) != sizeof(GBA_ROM_MAGIC)) {
577		return false;
578	}
579	if (memcmp(signature, GBA_ROM_MAGIC, sizeof(GBA_ROM_MAGIC)) != 0) {
580		return false;
581	}
582
583	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET2, SEEK_SET) < 0) {
584		return false;
585	}
586	if (vf->read(vf, &signature, sizeof(GBA_ROM_MAGIC2)) != sizeof(GBA_ROM_MAGIC2)) {
587		return false;
588	}
589	if (memcmp(signature, GBA_ROM_MAGIC2, sizeof(GBA_ROM_MAGIC2)) != 0) {
590		// If the signature byte is missing then we must be using an unfixed ROM
591		uint32_t buffer[0x9C / sizeof(uint32_t)];
592		if (vf->seek(vf, 0x4, SEEK_SET) < 0) {
593			return false;
594		}
595		if (vf->read(vf, &buffer, sizeof(buffer)) != sizeof(buffer)) {
596			return false;
597		}
598		uint32_t bits = 0;
599		size_t i;
600		for (i = 0; i < sizeof(buffer) / sizeof(*buffer); ++i) {
601			bits |= buffer[i];
602		}
603		if (bits) {
604			return false;
605		}
606	}
607
608
609	if (GBAIsBIOS(vf)) {
610		return false;
611	}
612	return true;
613}
614
615bool GBAIsMB(struct VFile* vf) {
616	if (!GBAIsROM(vf)) {
617		return false;
618	}
619#ifdef USE_ELF
620	struct ELF* elf = ELFOpen(vf);
621	if (elf) {
622		bool isMB = ELFEntry(elf) == BASE_WORKING_RAM;
623		ELFClose(elf);
624		return isMB;
625	}
626#endif
627	if (vf->size(vf) > SIZE_WORKING_RAM) {
628		return false;
629	}
630	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
631		return false;
632	}
633	uint32_t signature;
634	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
635		return false;
636	}
637	uint32_t opcode;
638	LOAD_32(opcode, 0, &signature);
639	struct ARMInstructionInfo info;
640	ARMDecodeARM(opcode, &info);
641	if (info.branchType == ARM_BRANCH) {
642		if (info.op1.immediate <= 0) {
643			return false;
644		} else if (info.op1.immediate == 28) {
645			// Ancient toolchain that is known to throw MB detection for a loop
646			return false;
647		} else if (info.op1.immediate != 24) {
648			return true;
649		}
650	}
651
652	uint32_t pc = GBA_MB_MAGIC_OFFSET;
653	int i;
654	for (i = 0; i < 80; ++i) {
655		if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
656			break;
657		}
658		pc += 4;
659		LOAD_32(opcode, 0, &signature);
660		ARMDecodeARM(opcode, &info);
661		if (info.mnemonic != ARM_MN_LDR) {
662			continue;
663		}
664		if ((info.operandFormat & ARM_OPERAND_MEMORY) && info.memory.baseReg == ARM_PC && info.memory.format & ARM_MEMORY_IMMEDIATE_OFFSET) {
665			uint32_t immediate = info.memory.offset.immediate;
666			if (info.memory.format & ARM_MEMORY_OFFSET_SUBTRACT) {
667				immediate = -immediate;
668			}
669			immediate += pc + 8;
670			if (vf->seek(vf, immediate, SEEK_SET) < 0) {
671				break;
672			}
673			if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
674				break;
675			}
676			LOAD_32(immediate, 0, &signature);
677			if (vf->seek(vf, pc, SEEK_SET) < 0) {
678				break;
679			}
680			if ((immediate & ~0x7FF) == BASE_WORKING_RAM) {
681				return true;
682			}
683		}
684	}
685	// Found a libgba-linked cart...these are a bit harder to detect.
686	return false;
687}
688
689bool GBAIsBIOS(struct VFile* vf) {
690	if (vf->seek(vf, 0, SEEK_SET) < 0) {
691		return false;
692	}
693	uint8_t interruptTable[7 * 4];
694	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
695		return false;
696	}
697	int i;
698	for (i = 0; i < 7; ++i) {
699		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
700			return false;
701		}
702	}
703	return true;
704}
705
706void GBAGetGameCode(const struct GBA* gba, char* out) {
707	memset(out, 0, 8);
708	if (!gba->memory.rom) {
709		return;
710	}
711
712	memcpy(out, "AGB-", 4);
713	memcpy(&out[4], &((struct GBACartridge*) gba->memory.rom)->id, 4);
714}
715
716void GBAGetGameTitle(const struct GBA* gba, char* out) {
717	if (gba->memory.rom) {
718		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
719		return;
720	}
721	if (gba->isPristine && gba->memory.wram) {
722		memcpy(out, &((struct GBACartridge*) gba->memory.wram)->title, 12);
723		return;
724	}
725	strncpy(out, "(BIOS)", 12);
726}
727
728void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
729	struct GBA* gba = (struct GBA*) cpu->master;
730	UNUSED(gba);
731#ifdef USE_DEBUGGERS
732	if (gba->debugger) {
733		struct mDebuggerEntryInfo info = {
734			.address = _ARMPCAddress(cpu),
735			.type.bp.opcode = opcode
736		};
737		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
738	}
739#endif
740	// TODO: More sensible category?
741	mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
742}
743
744void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
745	struct GBA* gba = (struct GBA*) cpu->master;
746	if (cpu->executionMode == MODE_THUMB && (opcode & 0xFFC0) == 0xE800) {
747		mLOG(GBA, INFO, "Hit Wii U VC opcode: %08x", opcode);
748		return;
749	}
750	if (!gba->yankedRomSize) {
751		// TODO: More sensible category?
752		mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
753	}
754#ifdef USE_DEBUGGERS
755	if (gba->debugger) {
756		struct mDebuggerEntryInfo info = {
757			.address = _ARMPCAddress(cpu),
758			.type.bp.opcode = opcode
759		};
760		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
761	}
762#endif
763	ARMRaiseUndefined(cpu);
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	int wasDirty = gba->memory.savedata.dirty;
824	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
825
826	if (gba->cpu->components && gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
827		struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
828		size_t i;
829		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
830			struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
831			if (!cheats->hook) {
832				mCheatRefresh(device, &cheats->d);
833			}
834		}
835	}
836
837	if (gba->stream && gba->stream->postVideoFrame) {
838		const color_t* pixels;
839		size_t stride;
840		gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
841		gba->stream->postVideoFrame(gba->stream, pixels, stride);
842	}
843
844	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
845		GBAHardwarePlayerUpdate(gba);
846	}
847
848	size_t c;
849	for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
850		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
851		if (callbacks->videoFrameEnded) {
852			callbacks->videoFrameEnded(callbacks->context);
853		}
854		if (callbacks->savedataUpdated && wasDirty && !gba->memory.savedata.dirty) {
855			callbacks->savedataUpdated(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 void _clearSoftwareBreakpoint(struct ARMDebugger* debugger, const struct ARMDebugBreakpoint* breakpoint) {
938	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, breakpoint->d.address, breakpoint->sw.mode, breakpoint->sw.opcode);
939}
940#endif