all repos — mgba @ b1828dbc59b8a9cc080c8c7f9472c46a3d39e90c

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