all repos — mgba @ a4e105737c43742d3a0e52ba8582730456569488

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