all repos — mgba @ 2b09a8c207d9a80f9529516b369a522a371cde71

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->video.vcount = 0x7D;
258		gba->memory.io[REG_VCOUNT >> 1] = 0x7D;
259		gba->memory.io[REG_POSTFLG >> 1] = 1;
260		ARMWritePC(cpu);
261	}
262}
263
264static void GBAProcessEvents(struct ARMCore* cpu) {
265	struct GBA* gba = (struct GBA*) cpu->master;
266
267	gba->bus = cpu->prefetch[1];
268	if (cpu->executionMode == MODE_THUMB) {
269		gba->bus |= cpu->prefetch[1] << 16;
270	}
271
272	int32_t nextEvent = cpu->nextEvent;
273	while (cpu->cycles >= nextEvent) {
274		cpu->nextEvent = INT_MAX;
275		nextEvent = 0;
276		do {
277			int32_t cycles = cpu->cycles;
278			cpu->cycles = 0;
279#ifndef NDEBUG
280			if (cycles < 0) {
281				mLOG(GBA, FATAL, "Negative cycles passed: %i", cycles);
282			}
283#endif
284			nextEvent = mTimingTick(&gba->timing, nextEvent + cycles);
285		} while (gba->cpuBlocked);
286
287		cpu->nextEvent = nextEvent;
288		if (cpu->halted) {
289			cpu->cycles = nextEvent;
290			if (!gba->memory.io[REG_IME >> 1] || !gba->memory.io[REG_IE >> 1]) {
291				break;
292			}
293		}
294#ifndef NDEBUG
295		else if (nextEvent < 0) {
296			mLOG(GBA, FATAL, "Negative cycles will pass: %i", nextEvent);
297		}
298#endif
299		if (gba->earlyExit) {
300			break;
301		}
302	}
303	gba->earlyExit = false;
304#ifndef NDEBUG
305	if (gba->cpuBlocked) {
306		mLOG(GBA, FATAL, "CPU is blocked!");
307	}
308#endif
309}
310
311#ifdef USE_DEBUGGERS
312void GBAAttachDebugger(struct GBA* gba, struct mDebugger* debugger) {
313	gba->debugger = (struct ARMDebugger*) debugger->platform;
314	gba->debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
315	gba->debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
316	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
317	ARMHotplugAttach(gba->cpu, CPU_COMPONENT_DEBUGGER);
318}
319
320void GBADetachDebugger(struct GBA* gba) {
321	if (gba->debugger) {
322		ARMHotplugDetach(gba->cpu, CPU_COMPONENT_DEBUGGER);
323	}
324	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
325	gba->debugger = NULL;
326}
327#endif
328
329bool GBALoadNull(struct GBA* gba) {
330	GBAUnloadROM(gba);
331	gba->romVf = NULL;
332	gba->pristineRomSize = 0;
333#ifndef FIXED_ROM_BUFFER
334	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
335#else
336	gba->memory.rom = romBuffer;
337#endif
338	gba->isPristine = false;
339	gba->yankedRomSize = 0;
340	gba->memory.romSize = SIZE_CART0;
341	gba->memory.romMask = SIZE_CART0 - 1;
342	gba->memory.mirroring = false;
343	gba->romCrc32 = 0;
344
345	if (gba->cpu) {
346		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
347	}
348	return true;
349}
350
351bool GBALoadMB(struct GBA* gba, struct VFile* vf) {
352	GBAUnloadROM(gba);
353	gba->romVf = vf;
354	gba->pristineRomSize = vf->size(vf);
355	vf->seek(vf, 0, SEEK_SET);
356	if (gba->pristineRomSize > SIZE_WORKING_RAM) {
357		gba->pristineRomSize = SIZE_WORKING_RAM;
358	}
359	gba->isPristine = true;
360	memset(gba->memory.wram, 0, SIZE_WORKING_RAM);
361	gba->yankedRomSize = 0;
362	gba->memory.romSize = 0;
363	gba->memory.romMask = 0;
364	gba->romCrc32 = doCrc32(gba->memory.wram, gba->pristineRomSize);
365	if (gba->cpu && gba->memory.activeRegion == REGION_WORKING_RAM) {
366		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
367	}
368	return true;
369}
370
371bool GBALoadROM(struct GBA* gba, struct VFile* vf) {
372	if (!vf) {
373		return false;
374	}
375	GBAUnloadROM(gba);
376	gba->romVf = vf;
377	gba->pristineRomSize = vf->size(vf);
378	vf->seek(vf, 0, SEEK_SET);
379	if (gba->pristineRomSize > SIZE_CART0) {
380		gba->isPristine = false;
381		gba->memory.romSize = 0x01000000;
382#ifdef FIXED_ROM_BUFFER
383		gba->memory.rom = romBuffer;
384#else
385		gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
386#endif
387	} else {
388		gba->isPristine = true;
389#ifdef FIXED_ROM_BUFFER
390		if (gba->pristineRomSize <= romBufferSize) {
391			gba->memory.rom = romBuffer;
392			vf->read(vf, romBuffer, gba->pristineRomSize);
393		}
394#else
395		gba->memory.rom = vf->map(vf, gba->pristineRomSize, MAP_READ);
396#endif
397		gba->memory.romSize = gba->pristineRomSize;
398	}
399	if (!gba->memory.rom) {
400		mLOG(GBA, WARN, "Couldn't map ROM");
401		return false;
402	}
403	gba->yankedRomSize = 0;
404	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
405	gba->memory.mirroring = false;
406	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
407	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
408	GBAVFameDetect(&gba->memory.vfame, gba->memory.rom, gba->memory.romSize);
409	if (popcount32(gba->memory.romSize) != 1) {
410		// This ROM is either a bad dump or homebrew. Emulate flash cart behavior.
411#ifndef FIXED_ROM_BUFFER
412		void* newRom = anonymousMemoryMap(SIZE_CART0);
413		memcpy(newRom, gba->memory.rom, gba->pristineRomSize);
414		gba->memory.rom = newRom;
415#endif
416		gba->memory.romSize = SIZE_CART0;
417		gba->memory.romMask = SIZE_CART0 - 1;
418		gba->isPristine = false;
419	}
420	if (gba->cpu && gba->memory.activeRegion >= REGION_CART0) {
421		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
422	}
423	// TODO: error check
424	return true;
425}
426
427bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
428	GBASavedataInit(&gba->memory.savedata, sav);
429	return true;
430}
431
432void GBAYankROM(struct GBA* gba) {
433	gba->yankedRomSize = gba->memory.romSize;
434	gba->memory.romSize = 0;
435	gba->memory.romMask = 0;
436	GBARaiseIRQ(gba, IRQ_GAMEPAK);
437}
438
439void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
440	gba->biosVf = vf;
441	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
442	if (!bios) {
443		mLOG(GBA, WARN, "Couldn't map BIOS");
444		return;
445	}
446	gba->memory.bios = bios;
447	gba->memory.fullBios = 1;
448	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
449	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
450	if (checksum == GBA_BIOS_CHECKSUM) {
451		mLOG(GBA, INFO, "Official GBA BIOS detected");
452	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
453		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
454	} else {
455		mLOG(GBA, WARN, "BIOS checksum incorrect");
456	}
457	gba->biosChecksum = checksum;
458	if (gba->memory.activeRegion == REGION_BIOS) {
459		gba->cpu->memory.activeRegion = gba->memory.bios;
460	}
461	// TODO: error check
462}
463
464void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
465	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
466	if (!patchedSize || patchedSize > SIZE_CART0) {
467		return;
468	}
469	void* newRom = anonymousMemoryMap(SIZE_CART0);
470	if (!patch->applyPatch(patch, gba->memory.rom, gba->pristineRomSize, newRom, patchedSize)) {
471		mappedMemoryFree(newRom, SIZE_CART0);
472		return;
473	}
474	if (gba->romVf) {
475#ifndef FIXED_ROM_BUFFER
476		gba->romVf->unmap(gba->romVf, gba->memory.rom, gba->pristineRomSize);
477#endif
478		gba->romVf->close(gba->romVf);
479		gba->romVf = NULL;
480	}
481	gba->isPristine = false;
482	gba->memory.rom = newRom;
483	gba->memory.hw.gpioBase = &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1];
484	gba->memory.romSize = patchedSize;
485	gba->memory.romMask = SIZE_CART0 - 1;
486	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
487}
488
489void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
490	gba->memory.io[REG_IF >> 1] |= 1 << irq;
491	GBATestIRQ(gba->cpu);
492}
493
494void GBATestIRQ(struct ARMCore* cpu) {
495	struct GBA* gba = (struct GBA*) cpu->master;
496	if (gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
497		if (!mTimingIsScheduled(&gba->timing, &gba->irqEvent)) {
498			mTimingSchedule(&gba->timing, &gba->irqEvent, GBA_IRQ_DELAY);
499		}
500	}
501}
502
503void GBAHalt(struct GBA* gba) {
504	gba->cpu->nextEvent = gba->cpu->cycles;
505	gba->cpu->halted = 1;
506}
507
508void GBAStop(struct GBA* gba) {
509	size_t c;
510	for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
511		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
512		if (callbacks->sleep) {
513			callbacks->sleep(callbacks->context);
514		}
515	}
516	gba->cpu->nextEvent = gba->cpu->cycles;
517}
518
519void GBADebug(struct GBA* gba, uint16_t flags) {
520	gba->debugFlags = flags;
521	if (GBADebugFlagsIsSend(gba->debugFlags)) {
522		int level = 1 << GBADebugFlagsGetLevel(gba->debugFlags);
523		level &= 0x1F;
524		char oolBuf[0x101];
525		strncpy(oolBuf, gba->debugString, sizeof(oolBuf) - 1);
526		memset(gba->debugString, 0, sizeof(gba->debugString));
527		oolBuf[0x100] = '\0';
528		mLog(_mLOG_CAT_GBA_DEBUG, level, "%s", oolBuf);
529	}
530	gba->debugFlags = GBADebugFlagsClearSend(gba->debugFlags);
531}
532
533bool GBAIsROM(struct VFile* vf) {
534#ifdef USE_ELF
535	struct ELF* elf = ELFOpen(vf);
536	if (elf) {
537		uint32_t entry = ELFEntry(elf);
538		bool isGBA = true;
539		isGBA = isGBA && ELFMachine(elf) == EM_ARM;
540		isGBA = isGBA && (entry == BASE_CART0 || entry == BASE_WORKING_RAM);
541		ELFClose(elf);
542		return isGBA;
543	}
544#endif
545	if (!vf) {
546		return false;
547	}
548
549	uint8_t signature[sizeof(GBA_ROM_MAGIC) + sizeof(GBA_ROM_MAGIC2)];
550	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
551		return false;
552	}
553	if (vf->read(vf, &signature, sizeof(GBA_ROM_MAGIC)) != sizeof(GBA_ROM_MAGIC)) {
554		return false;
555	}
556	if (memcmp(signature, GBA_ROM_MAGIC, sizeof(GBA_ROM_MAGIC)) != 0) {
557		return false;
558	}
559
560	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET2, SEEK_SET) < 0) {
561		return false;
562	}
563	if (vf->read(vf, &signature, sizeof(GBA_ROM_MAGIC2)) != sizeof(GBA_ROM_MAGIC2)) {
564		return false;
565	}
566	if (memcmp(signature, GBA_ROM_MAGIC2, sizeof(GBA_ROM_MAGIC2)) != 0) {
567		// If the signature byte is missing then we must be using an unfixed ROM
568		uint32_t buffer[0x9C / sizeof(uint32_t)];
569		if (vf->seek(vf, 0x4, SEEK_SET) < 0) {
570			return false;
571		}
572		if (vf->read(vf, &buffer, sizeof(buffer)) != sizeof(buffer)) {
573			return false;
574		}
575		uint32_t bits = 0;
576		size_t i;
577		for (i = 0; i < sizeof(buffer) / sizeof(*buffer); ++i) {
578			bits |= buffer[i];
579		}
580		if (bits) {
581			return false;
582		}
583	}
584
585
586	if (GBAIsBIOS(vf)) {
587		return false;
588	}
589	return true;
590}
591
592bool GBAIsMB(struct VFile* vf) {
593	if (!GBAIsROM(vf)) {
594		return false;
595	}
596#ifdef USE_ELF
597	struct ELF* elf = ELFOpen(vf);
598	if (elf) {
599		bool isMB = ELFEntry(elf) == BASE_WORKING_RAM;
600		ELFClose(elf);
601		return isMB;
602	}
603#endif
604	if (vf->size(vf) > SIZE_WORKING_RAM) {
605		return false;
606	}
607	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
608		return false;
609	}
610	uint32_t signature;
611	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
612		return false;
613	}
614	uint32_t opcode;
615	LOAD_32(opcode, 0, &signature);
616	struct ARMInstructionInfo info;
617	ARMDecodeARM(opcode, &info);
618	if (info.branchType == ARM_BRANCH) {
619		if (info.op1.immediate <= 0) {
620			return false;
621		} else if (info.op1.immediate == 28) {
622			// Ancient toolchain that is known to throw MB detection for a loop
623			return false;
624		} else if (info.op1.immediate != 24) {
625			return true;
626		}
627	}
628
629	uint32_t pc = GBA_MB_MAGIC_OFFSET;
630	int i;
631	for (i = 0; i < 80; ++i) {
632		if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
633			break;
634		}
635		pc += 4;
636		LOAD_32(opcode, 0, &signature);
637		ARMDecodeARM(opcode, &info);
638		if (info.mnemonic != ARM_MN_LDR) {
639			continue;
640		}
641		if ((info.operandFormat & ARM_OPERAND_MEMORY) && info.memory.baseReg == ARM_PC && info.memory.format & ARM_MEMORY_IMMEDIATE_OFFSET) {
642			uint32_t immediate = info.memory.offset.immediate;
643			if (info.memory.format & ARM_MEMORY_OFFSET_SUBTRACT) {
644				immediate = -immediate;
645			}
646			immediate += pc + 8;
647			if (vf->seek(vf, immediate, SEEK_SET) < 0) {
648				break;
649			}
650			if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
651				break;
652			}
653			LOAD_32(immediate, 0, &signature);
654			if (vf->seek(vf, pc, SEEK_SET) < 0) {
655				break;
656			}
657			if ((immediate & ~0x7FF) == BASE_WORKING_RAM) {
658				return true;
659			}
660		}
661	}
662	// Found a libgba-linked cart...these are a bit harder to detect.
663	return false;
664}
665
666bool GBAIsBIOS(struct VFile* vf) {
667	if (vf->seek(vf, 0, SEEK_SET) < 0) {
668		return false;
669	}
670	uint8_t interruptTable[7 * 4];
671	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
672		return false;
673	}
674	int i;
675	for (i = 0; i < 7; ++i) {
676		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
677			return false;
678		}
679	}
680	return true;
681}
682
683void GBAGetGameCode(const struct GBA* gba, char* out) {
684	memset(out, 0, 8);
685	if (!gba->memory.rom) {
686		return;
687	}
688
689	memcpy(out, "AGB-", 4);
690	memcpy(&out[4], &((struct GBACartridge*) gba->memory.rom)->id, 4);
691}
692
693void GBAGetGameTitle(const struct GBA* gba, char* out) {
694	if (gba->memory.rom) {
695		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
696		return;
697	}
698	if (gba->isPristine && gba->memory.wram) {
699		memcpy(out, &((struct GBACartridge*) gba->memory.wram)->title, 12);
700		return;
701	}
702	strncpy(out, "(BIOS)", 12);
703}
704
705void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
706	struct GBA* gba = (struct GBA*) cpu->master;
707	UNUSED(gba);
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
855static void _triggerIRQ(struct mTiming* timing, void* user, uint32_t cyclesLate) {
856	UNUSED(timing);
857	UNUSED(cyclesLate);
858	struct GBA* gba = user;
859	gba->cpu->halted = 0;
860	if (!(gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1])) {
861		return;
862	}
863
864	if (gba->memory.io[REG_IME >> 1] && !gba->cpu->cpsr.i) {
865		ARMRaiseIRQ(gba->cpu);
866	}
867}
868
869void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
870	size_t immediate;
871	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
872		if (gba->cpu->components[immediate] == component) {
873			break;
874		}
875	}
876	if (immediate == gba->cpu->numComponents) {
877		return;
878	}
879	if (mode == MODE_ARM) {
880		int32_t value;
881		int32_t old;
882		value = 0xE1200070;
883		value |= immediate & 0xF;
884		value |= (immediate & 0xFFF0) << 4;
885		GBAPatch32(gba->cpu, address, value, &old);
886		*opcode = old;
887	} else {
888		int16_t value;
889		int16_t old;
890		value = 0xBE00;
891		value |= immediate & 0xFF;
892		GBAPatch16(gba->cpu, address, value, &old);
893		*opcode = (uint16_t) old;
894	}
895}
896
897void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
898	if (mode == MODE_ARM) {
899		GBAPatch32(gba->cpu, address, opcode, 0);
900	} else {
901		GBAPatch16(gba->cpu, address, opcode, 0);
902	}
903}
904
905#ifdef USE_DEBUGGERS
906static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
907	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d.p->d, address, mode, opcode);
908	return true;
909}
910
911static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
912	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
913	return true;
914}
915#endif