all repos — mgba @ e78333611d8d72394d5fd68539c0a0a8e2ffe45f

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->hardCrash = true;
109	gba->allowOpposingDirections = true;
110
111	gba->performingDMA = false;
112
113	gba->isPristine = false;
114	gba->pristineRomSize = 0;
115	gba->yankedRomSize = 0;
116
117	mTimingInit(&gba->timing, &gba->cpu->cycles, &gba->cpu->nextEvent);
118}
119
120void GBAUnloadROM(struct GBA* gba) {
121	if (gba->memory.rom && !gba->isPristine) {
122		if (gba->yankedRomSize) {
123			gba->yankedRomSize = 0;
124		}
125		mappedMemoryFree(gba->memory.rom, SIZE_CART0);
126	}
127
128	if (gba->romVf) {
129#ifndef FIXED_ROM_BUFFER
130		if (gba->isPristine) {
131			gba->romVf->unmap(gba->romVf, gba->memory.rom, gba->pristineRomSize);
132		}
133#endif
134		gba->romVf->close(gba->romVf);
135		gba->romVf = NULL;
136	}
137	gba->memory.rom = NULL;
138	gba->isPristine = false;
139
140	GBASavedataDeinit(&gba->memory.savedata);
141	if (gba->memory.savedata.realVf) {
142		gba->memory.savedata.realVf->close(gba->memory.savedata.realVf);
143		gba->memory.savedata.realVf = 0;
144	}
145	gba->idleLoop = IDLE_LOOP_NONE;
146}
147
148void GBADestroy(struct GBA* gba) {
149	GBAUnloadROM(gba);
150
151	if (gba->biosVf) {
152		gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
153		gba->biosVf->close(gba->biosVf);
154		gba->biosVf = 0;
155	}
156
157	GBAMemoryDeinit(gba);
158	GBAVideoDeinit(&gba->video);
159	GBAAudioDeinit(&gba->audio);
160	GBASIODeinit(&gba->sio);
161	gba->rr = 0;
162	mTimingDeinit(&gba->timing);
163	mCoreCallbacksListDeinit(&gba->coreCallbacks);
164}
165
166void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
167	irqh->reset = GBAReset;
168	irqh->processEvents = GBAProcessEvents;
169	irqh->swi16 = GBASwi16;
170	irqh->swi32 = GBASwi32;
171	irqh->hitIllegal = GBAIllegal;
172	irqh->readCPSR = GBATestIRQ;
173	irqh->hitStub = GBAHitStub;
174	irqh->bkpt16 = GBABreakpoint;
175	irqh->bkpt32 = GBABreakpoint;
176}
177
178void GBAReset(struct ARMCore* cpu) {
179	ARMSetPrivilegeMode(cpu, MODE_IRQ);
180	cpu->gprs[ARM_SP] = SP_BASE_IRQ;
181	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
182	cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
183	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
184	cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
185
186	struct GBA* gba = (struct GBA*) cpu->master;
187	if (!gba->rr || (!gba->rr->isPlaying(gba->rr) && !gba->rr->isRecording(gba->rr))) {
188		GBASavedataUnmask(&gba->memory.savedata);
189	}
190
191	gba->cpuBlocked = false;
192	gba->earlyExit = false;
193	if (gba->yankedRomSize) {
194		gba->memory.romSize = gba->yankedRomSize;
195		gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
196		gba->yankedRomSize = 0;
197	}
198	mTimingClear(&gba->timing);
199	GBAMemoryReset(gba);
200	GBAVideoReset(&gba->video);
201	GBAAudioReset(&gba->audio);
202	GBAIOInit(gba);
203	GBATimerInit(gba);
204
205	GBASIOReset(&gba->sio);
206
207	gba->lastJump = 0;
208	gba->haltPending = false;
209	gba->idleDetectionStep = 0;
210	gba->idleDetectionFailures = 0;
211
212	gba->debug = false;
213	memset(gba->debugString, 0, sizeof(gba->debugString));
214	if (gba->pristineRomSize > SIZE_CART0) {
215		GBAMatrixReset(gba);
216	}
217
218	if (!gba->romVf && gba->memory.rom) {
219		GBASkipBIOS(gba);
220	}
221}
222
223void GBASkipBIOS(struct GBA* gba) {
224	struct ARMCore* cpu = gba->cpu;
225	if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
226		if (gba->memory.rom) {
227			cpu->gprs[ARM_PC] = BASE_CART0;
228		} else {
229			cpu->gprs[ARM_PC] = BASE_WORKING_RAM;
230		}
231		gba->memory.io[REG_VCOUNT >> 1] = 0x7E;
232		gba->memory.io[REG_POSTFLG >> 1] = 1;
233		int currentCycles = 0;
234		ARM_WRITE_PC;
235	}
236}
237
238static void GBAProcessEvents(struct ARMCore* cpu) {
239	struct GBA* gba = (struct GBA*) cpu->master;
240
241	gba->bus = cpu->prefetch[1];
242	if (cpu->executionMode == MODE_THUMB) {
243		gba->bus |= cpu->prefetch[1] << 16;
244	}
245
246	if (gba->springIRQ && !cpu->cpsr.i) {
247		ARMRaiseIRQ(cpu);
248		gba->springIRQ = 0;
249	}
250
251	int32_t nextEvent = cpu->nextEvent;
252	while (cpu->cycles >= nextEvent) {
253		cpu->nextEvent = INT_MAX;
254		nextEvent = 0;
255		do {
256			int32_t cycles = cpu->cycles;
257			cpu->cycles = 0;
258#ifndef NDEBUG
259			if (cycles < 0) {
260				mLOG(GBA, FATAL, "Negative cycles passed: %i", cycles);
261			}
262#endif
263			nextEvent = mTimingTick(&gba->timing, nextEvent + cycles);
264		} while (gba->cpuBlocked);
265
266		cpu->nextEvent = nextEvent;
267
268		if (gba->earlyExit) {
269			gba->earlyExit = false;
270			break;
271		}
272		if (cpu->halted) {
273			cpu->cycles = nextEvent;
274			if (!gba->memory.io[REG_IME >> 1] || !gba->memory.io[REG_IE >> 1]) {
275				break;
276			}
277		}
278#ifndef NDEBUG
279		else if (nextEvent < 0) {
280			mLOG(GBA, FATAL, "Negative cycles will pass: %i", nextEvent);
281		}
282#endif
283	}
284#ifndef NDEBUG
285	if (gba->cpuBlocked) {
286		mLOG(GBA, FATAL, "CPU is blocked!");
287	}
288#endif
289}
290
291#ifdef USE_DEBUGGERS
292void GBAAttachDebugger(struct GBA* gba, struct mDebugger* debugger) {
293	gba->debugger = (struct ARMDebugger*) debugger->platform;
294	gba->debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
295	gba->debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
296	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
297	ARMHotplugAttach(gba->cpu, CPU_COMPONENT_DEBUGGER);
298}
299
300void GBADetachDebugger(struct GBA* gba) {
301	if (gba->debugger) {
302		ARMHotplugDetach(gba->cpu, CPU_COMPONENT_DEBUGGER);
303	}
304	gba->cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
305	gba->debugger = NULL;
306}
307#endif
308
309bool GBALoadNull(struct GBA* gba) {
310	GBAUnloadROM(gba);
311	gba->romVf = NULL;
312	gba->pristineRomSize = 0;
313#ifndef FIXED_ROM_BUFFER
314	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
315#else
316	gba->memory.rom = romBuffer;
317#endif
318	gba->isPristine = false;
319	gba->yankedRomSize = 0;
320	gba->memory.romSize = SIZE_CART0;
321	gba->memory.romMask = SIZE_CART0 - 1;
322	gba->memory.mirroring = false;
323	gba->romCrc32 = 0;
324
325	if (gba->cpu) {
326		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
327	}
328	return true;
329}
330
331bool GBALoadMB(struct GBA* gba, struct VFile* vf) {
332	GBAUnloadROM(gba);
333	gba->romVf = vf;
334	gba->pristineRomSize = vf->size(vf);
335	vf->seek(vf, 0, SEEK_SET);
336	if (gba->pristineRomSize > SIZE_WORKING_RAM) {
337		gba->pristineRomSize = SIZE_WORKING_RAM;
338	}
339	gba->isPristine = true;
340	memset(gba->memory.wram, 0, SIZE_WORKING_RAM);
341	vf->read(vf, gba->memory.wram, gba->pristineRomSize);
342	if (!gba->memory.wram) {
343		mLOG(GBA, WARN, "Couldn't map ROM");
344		return false;
345	}
346	gba->yankedRomSize = 0;
347	gba->memory.romSize = 0;
348	gba->memory.romMask = 0;
349	gba->romCrc32 = doCrc32(gba->memory.wram, gba->pristineRomSize);
350	if (gba->cpu && gba->memory.activeRegion == REGION_WORKING_RAM) {
351		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
352	}
353	return true;
354}
355
356bool GBALoadROM(struct GBA* gba, struct VFile* vf) {
357	if (!vf) {
358		return false;
359	}
360	GBAUnloadROM(gba);
361	gba->romVf = vf;
362	gba->pristineRomSize = vf->size(vf);
363	vf->seek(vf, 0, SEEK_SET);
364	if (gba->pristineRomSize > SIZE_CART0) {
365		gba->isPristine = false;
366		gba->memory.romSize = 0x01000000;
367#ifdef FIXED_ROM_BUFFER
368		gba->memory.rom = romBuffer;
369#else
370		gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
371#endif
372	} else {
373		gba->isPristine = true;
374#ifdef FIXED_ROM_BUFFER
375		if (gba->pristineRomSize <= romBufferSize) {
376			gba->memory.rom = romBuffer;
377			vf->read(vf, romBuffer, gba->pristineRomSize);
378		}
379#else
380		gba->memory.rom = vf->map(vf, gba->pristineRomSize, MAP_READ);
381#endif
382		gba->memory.romSize = gba->pristineRomSize;
383	}
384	if (!gba->memory.rom) {
385		mLOG(GBA, WARN, "Couldn't map ROM");
386		return false;
387	}
388	gba->yankedRomSize = 0;
389	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
390	gba->memory.mirroring = false;
391	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
392	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
393	GBAVFameDetect(&gba->memory.vfame, gba->memory.rom, gba->memory.romSize);
394	if (popcount32(gba->memory.romSize) != 1) {
395		// This ROM is either a bad dump or homebrew. Emulate flash cart behavior.
396#ifndef FIXED_ROM_BUFFER
397		void* newRom = anonymousMemoryMap(SIZE_CART0);
398		memcpy(newRom, gba->memory.rom, gba->pristineRomSize);
399		gba->memory.rom = newRom;
400#endif
401		gba->memory.romSize = SIZE_CART0;
402		gba->isPristine = false;
403	}
404	if (gba->cpu && gba->memory.activeRegion >= REGION_CART0) {
405		gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
406	}
407	// TODO: error check
408	return true;
409}
410
411bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
412	GBASavedataInit(&gba->memory.savedata, sav);
413	return true;
414}
415
416void GBAYankROM(struct GBA* gba) {
417	gba->yankedRomSize = gba->memory.romSize;
418	gba->memory.romSize = 0;
419	gba->memory.romMask = 0;
420	GBARaiseIRQ(gba, IRQ_GAMEPAK);
421}
422
423void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
424	gba->biosVf = vf;
425	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
426	if (!bios) {
427		mLOG(GBA, WARN, "Couldn't map BIOS");
428		return;
429	}
430	gba->memory.bios = bios;
431	gba->memory.fullBios = 1;
432	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
433	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
434	if (checksum == GBA_BIOS_CHECKSUM) {
435		mLOG(GBA, INFO, "Official GBA BIOS detected");
436	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
437		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
438	} else {
439		mLOG(GBA, WARN, "BIOS checksum incorrect");
440	}
441	gba->biosChecksum = checksum;
442	if (gba->memory.activeRegion == REGION_BIOS) {
443		gba->cpu->memory.activeRegion = gba->memory.bios;
444	}
445	// TODO: error check
446}
447
448void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
449	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
450	if (!patchedSize || patchedSize > SIZE_CART0) {
451		return;
452	}
453	void* newRom = anonymousMemoryMap(SIZE_CART0);
454	if (!patch->applyPatch(patch, gba->memory.rom, gba->pristineRomSize, newRom, patchedSize)) {
455		mappedMemoryFree(newRom, SIZE_CART0);
456		return;
457	}
458	if (gba->romVf) {
459#ifndef FIXED_ROM_BUFFER
460		gba->romVf->unmap(gba->romVf, gba->memory.rom, gba->pristineRomSize);
461#endif
462		gba->romVf->close(gba->romVf);
463		gba->romVf = NULL;
464	}
465	gba->isPristine = false;
466	gba->memory.rom = newRom;
467	gba->memory.hw.gpioBase = &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1];
468	gba->memory.romSize = patchedSize;
469	gba->memory.romMask = SIZE_CART0 - 1;
470	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
471}
472
473void GBAWriteIE(struct GBA* gba, uint16_t value) {
474	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
475		ARMRaiseIRQ(gba->cpu);
476	}
477}
478
479void GBAWriteIME(struct GBA* gba, uint16_t value) {
480	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
481		ARMRaiseIRQ(gba->cpu);
482	}
483}
484
485void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
486	gba->memory.io[REG_IF >> 1] |= 1 << irq;
487
488	if (gba->memory.io[REG_IE >> 1] & 1 << irq) {
489		gba->cpu->halted = 0;
490		if (gba->memory.io[REG_IME >> 1]) {
491			ARMRaiseIRQ(gba->cpu);
492		}
493	}
494}
495
496void GBATestIRQ(struct ARMCore* cpu) {
497	struct GBA* gba = (struct GBA*) cpu->master;
498	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
499		gba->springIRQ = gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1];
500		gba->cpu->nextEvent = gba->cpu->cycles;
501	}
502}
503
504void GBAHalt(struct GBA* gba) {
505	gba->cpu->nextEvent = gba->cpu->cycles;
506	gba->cpu->halted = 1;
507}
508
509void GBAStop(struct GBA* gba) {
510	size_t c;
511	for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
512		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
513		if (callbacks->sleep) {
514			callbacks->sleep(callbacks->context);
515		}
516	}
517	gba->cpu->nextEvent = gba->cpu->cycles;
518}
519
520void GBADebug(struct GBA* gba, uint16_t flags) {
521	gba->debugFlags = flags;
522	if (GBADebugFlagsIsSend(gba->debugFlags)) {
523		int level = 1 << GBADebugFlagsGetLevel(gba->debugFlags);
524		level &= 0x1F;
525		char oolBuf[0x101];
526		strncpy(oolBuf, gba->debugString, 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#ifdef USE_DEBUGGERS
708	if (gba->debugger) {
709		struct mDebuggerEntryInfo info = {
710			.address = _ARMPCAddress(cpu),
711			.type.bp.opcode = opcode
712		};
713		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
714	}
715#endif
716	// TODO: More sensible category?
717	mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
718}
719
720void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
721	struct GBA* gba = (struct GBA*) cpu->master;
722	if (!gba->yankedRomSize) {
723		// TODO: More sensible category?
724		mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
725	}
726	if (cpu->executionMode == MODE_THUMB && (opcode & 0xFFC0) == 0xE800) {
727		mLOG(GBA, DEBUG, "Hit Wii U VC opcode: %08x", opcode);
728		return;
729	}
730#ifdef USE_DEBUGGERS
731	if (gba->debugger) {
732		struct mDebuggerEntryInfo info = {
733			.address = _ARMPCAddress(cpu),
734			.type.bp.opcode = opcode
735		};
736		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
737	} else
738#endif
739	{
740		ARMRaiseUndefined(cpu);
741	}
742}
743
744void GBABreakpoint(struct ARMCore* cpu, int immediate) {
745	struct GBA* gba = (struct GBA*) cpu->master;
746	if (immediate >= CPU_COMPONENT_MAX) {
747		return;
748	}
749	switch (immediate) {
750#ifdef USE_DEBUGGERS
751	case CPU_COMPONENT_DEBUGGER:
752		if (gba->debugger) {
753			struct mDebuggerEntryInfo info = {
754				.address = _ARMPCAddress(cpu),
755				.type.bp.breakType = BREAKPOINT_SOFTWARE
756			};
757			mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
758		}
759		break;
760#endif
761	case CPU_COMPONENT_CHEAT_DEVICE:
762		if (gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
763			struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
764			struct GBACheatHook* hook = 0;
765			size_t i;
766			for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
767				struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
768				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
769					mCheatRefresh(device, &cheats->d);
770					hook = cheats->hook;
771				}
772			}
773			if (hook) {
774				ARMRunFake(cpu, hook->patchedOpcode);
775			}
776		}
777		break;
778	default:
779		break;
780	}
781}
782
783void GBAFrameStarted(struct GBA* gba) {
784	GBATestKeypadIRQ(gba);
785
786	size_t c;
787	for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
788		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
789		if (callbacks->videoFrameStarted) {
790			callbacks->videoFrameStarted(callbacks->context);
791		}
792	}
793}
794
795void GBAFrameEnded(struct GBA* gba) {
796	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
797
798	if (gba->rr) {
799		gba->rr->nextFrame(gba->rr);
800	}
801
802	if (gba->cpu->components && gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
803		struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
804		size_t i;
805		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
806			struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
807			if (!cheats->hook) {
808				mCheatRefresh(device, &cheats->d);
809			}
810		}
811	}
812
813	if (gba->stream && gba->stream->postVideoFrame) {
814		const color_t* pixels;
815		size_t stride;
816		gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
817		gba->stream->postVideoFrame(gba->stream, pixels, stride);
818	}
819
820	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
821		GBAHardwarePlayerUpdate(gba);
822	}
823
824	size_t c;
825	for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
826		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
827		if (callbacks->videoFrameEnded) {
828			callbacks->videoFrameEnded(callbacks->context);
829		}
830	}
831}
832
833void GBATestKeypadIRQ(struct GBA* gba) {
834	uint16_t keycnt = gba->memory.io[REG_KEYCNT >> 1];
835	if (!(keycnt & 0x4000)) {
836		return;
837	}
838	int isAnd = keycnt & 0x8000;
839	if (!gba->keySource) {
840		// TODO?
841		return;
842	}
843
844	keycnt &= 0x3FF;
845	uint16_t keyInput = *gba->keySource & keycnt;
846
847	if (isAnd && keycnt == keyInput) {
848		GBARaiseIRQ(gba, IRQ_KEYPAD);
849	} else if (!isAnd && keyInput) {
850		GBARaiseIRQ(gba, IRQ_KEYPAD);
851	}
852}
853
854void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
855	size_t immediate;
856	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
857		if (gba->cpu->components[immediate] == component) {
858			break;
859		}
860	}
861	if (immediate == gba->cpu->numComponents) {
862		return;
863	}
864	if (mode == MODE_ARM) {
865		int32_t value;
866		int32_t old;
867		value = 0xE1200070;
868		value |= immediate & 0xF;
869		value |= (immediate & 0xFFF0) << 4;
870		GBAPatch32(gba->cpu, address, value, &old);
871		*opcode = old;
872	} else {
873		int16_t value;
874		int16_t old;
875		value = 0xBE00;
876		value |= immediate & 0xFF;
877		GBAPatch16(gba->cpu, address, value, &old);
878		*opcode = (uint16_t) old;
879	}
880}
881
882void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
883	if (mode == MODE_ARM) {
884		GBAPatch32(gba->cpu, address, opcode, 0);
885	} else {
886		GBAPatch16(gba->cpu, address, opcode, 0);
887	}
888}
889
890static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
891	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d.p->d, address, mode, opcode);
892	return true;
893}
894
895static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
896	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
897	return true;
898}