all repos — mgba @ e251a69a29e8059733ae788bd4be5852b76cdac1

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