all repos — mgba @ 8c10d2f85708d70c1a393a58164eca73a8daed76

mGBA Game Boy Advance Emulator

src/gba/gba.c (view raw)

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