all repos — mgba @ 72e5aa078281a797854e4bd4620489e956fce866

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