all repos — mgba @ 475c7790c5ddd94127eaa0f4b6b569e7beae2f79

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