all repos — mgba @ a5a7ace86eb0feaf156842029af59a869151712a

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 "gba.h"
  7
  8#include "gba/bios.h"
  9#include "gba/cheats.h"
 10#include "gba/io.h"
 11#include "gba/supervisor/rr.h"
 12#include "gba/supervisor/thread.h"
 13#include "gba/serialize.h"
 14#include "gba/sio.h"
 15
 16#include "isa-inlines.h"
 17
 18#include "util/crc32.h"
 19#include "util/memory.h"
 20#include "util/patch.h"
 21#include "util/vfs.h"
 22
 23const uint32_t GBA_ARM7TDMI_FREQUENCY = 0x1000000;
 24const uint32_t GBA_COMPONENT_MAGIC = 0x1000000;
 25
 26static const size_t GBA_ROM_MAGIC_OFFSET = 3;
 27static const uint8_t GBA_ROM_MAGIC[] = { 0xEA };
 28
 29static void GBAInit(struct ARMCore* cpu, struct ARMComponent* component);
 30static void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh);
 31static void GBAProcessEvents(struct ARMCore* cpu);
 32static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles);
 33static void GBAHitStub(struct ARMCore* cpu, uint32_t opcode);
 34static void GBAIllegal(struct ARMCore* cpu, uint32_t opcode);
 35static void GBABreakpoint(struct ARMCore* cpu, int immediate);
 36
 37static bool _setSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t* opcode);
 38static bool _clearSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t opcode);
 39
 40void GBACreate(struct GBA* gba) {
 41	gba->d.id = GBA_COMPONENT_MAGIC;
 42	gba->d.init = GBAInit;
 43	gba->d.deinit = 0;
 44}
 45
 46static void GBAInit(struct ARMCore* cpu, struct ARMComponent* component) {
 47	struct GBA* gba = (struct GBA*) component;
 48	gba->cpu = cpu;
 49	gba->debugger = 0;
 50
 51	GBAInterruptHandlerInit(&cpu->irqh);
 52	GBAMemoryInit(gba);
 53	GBASavedataInit(&gba->memory.savedata, 0);
 54
 55	gba->video.p = gba;
 56	GBAVideoInit(&gba->video);
 57
 58	gba->audio.p = gba;
 59	GBAAudioInit(&gba->audio, GBA_AUDIO_SAMPLES);
 60
 61	GBAIOInit(gba);
 62
 63	gba->sio.p = gba;
 64	GBASIOInit(&gba->sio);
 65
 66	gba->timersEnabled = 0;
 67	memset(gba->timers, 0, sizeof(gba->timers));
 68
 69	gba->springIRQ = 0;
 70	gba->keySource = 0;
 71	gba->rotationSource = 0;
 72	gba->luminanceSource = 0;
 73	gba->rtcSource = 0;
 74	gba->rumble = 0;
 75	gba->rr = 0;
 76
 77	gba->romVf = 0;
 78	gba->biosVf = 0;
 79
 80	gba->logLevel = GBA_LOG_INFO | GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL;
 81
 82	gba->biosChecksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
 83
 84	gba->idleOptimization = IDLE_LOOP_REMOVE;
 85	gba->idleLoop = IDLE_LOOP_NONE;
 86	gba->lastJump = 0;
 87	gba->idleDetectionStep = 0;
 88	gba->idleDetectionFailures = 0;
 89	gba->performingDMA = false;
 90}
 91
 92void GBADestroy(struct GBA* gba) {
 93	if (gba->pristineRom == gba->memory.rom) {
 94		gba->memory.rom = 0;
 95	}
 96
 97	if (gba->romVf) {
 98		gba->romVf->unmap(gba->romVf, gba->pristineRom, gba->pristineRomSize);
 99	}
100
101	if (gba->biosVf) {
102		gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
103	}
104
105	GBAMemoryDeinit(gba);
106	GBAVideoDeinit(&gba->video);
107	GBAAudioDeinit(&gba->audio);
108	GBARRContextDestroy(gba);
109}
110
111void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
112	irqh->reset = GBAReset;
113	irqh->processEvents = GBAProcessEvents;
114	irqh->swi16 = GBASwi16;
115	irqh->swi32 = GBASwi32;
116	irqh->hitIllegal = GBAIllegal;
117	irqh->readCPSR = GBATestIRQ;
118	irqh->hitStub = GBAHitStub;
119	irqh->bkpt16 = GBABreakpoint;
120	irqh->bkpt32 = GBABreakpoint;
121}
122
123void GBAReset(struct ARMCore* cpu) {
124	ARMSetPrivilegeMode(cpu, MODE_IRQ);
125	cpu->gprs[ARM_SP] = SP_BASE_IRQ;
126	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
127	cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
128	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
129	cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
130
131	struct GBA* gba = (struct GBA*) cpu->master;
132	if (!GBARRIsPlaying(gba->rr) && !GBARRIsRecording(gba->rr)) {
133		GBASavedataUnmask(&gba->memory.savedata);
134	}
135	GBAMemoryReset(gba);
136	GBAVideoReset(&gba->video);
137	GBAAudioReset(&gba->audio);
138	GBAIOInit(gba);
139
140	GBASIODeinit(&gba->sio);
141	GBASIOInit(&gba->sio);
142
143	gba->timersEnabled = 0;
144	memset(gba->timers, 0, sizeof(gba->timers));
145}
146
147void GBASkipBIOS(struct ARMCore* cpu) {
148	if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
149		cpu->gprs[ARM_PC] = BASE_CART0;
150		int currentCycles = 0;
151		ARM_WRITE_PC;
152	}
153}
154
155static void GBAProcessEvents(struct ARMCore* cpu) {
156	do {
157		struct GBA* gba = (struct GBA*) cpu->master;
158		int32_t cycles = cpu->nextEvent;
159		int32_t nextEvent = INT_MAX;
160		int32_t testEvent;
161
162		gba->bus = cpu->prefetch[1];
163		if (cpu->executionMode == MODE_THUMB) {
164			gba->bus |= cpu->prefetch[1] << 16;
165		}
166
167		if (gba->springIRQ) {
168			ARMRaiseIRQ(cpu);
169			gba->springIRQ = 0;
170		}
171
172		testEvent = GBAVideoProcessEvents(&gba->video, cycles);
173		if (testEvent < nextEvent) {
174			nextEvent = testEvent;
175		}
176
177		testEvent = GBAAudioProcessEvents(&gba->audio, cycles);
178		if (testEvent < nextEvent) {
179			nextEvent = testEvent;
180		}
181
182		testEvent = GBATimersProcessEvents(gba, cycles);
183		if (testEvent < nextEvent) {
184			nextEvent = testEvent;
185		}
186
187		testEvent = GBAMemoryRunDMAs(gba, cycles);
188		if (testEvent < nextEvent) {
189			nextEvent = testEvent;
190		}
191
192		testEvent = GBASIOProcessEvents(&gba->sio, cycles);
193		if (testEvent < nextEvent) {
194			nextEvent = testEvent;
195		}
196
197		cpu->cycles -= cycles;
198		cpu->nextEvent = nextEvent;
199
200		if (cpu->halted) {
201			cpu->cycles = cpu->nextEvent;
202		}
203	} while (cpu->cycles >= cpu->nextEvent);
204}
205
206static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles) {
207	int32_t nextEvent = INT_MAX;
208	if (gba->timersEnabled) {
209		struct GBATimer* timer;
210		struct GBATimer* nextTimer;
211
212		timer = &gba->timers[0];
213		if (timer->enable) {
214			timer->nextEvent -= cycles;
215			timer->lastEvent -= cycles;
216			if (timer->nextEvent <= 0) {
217				timer->lastEvent = timer->nextEvent;
218				timer->nextEvent += timer->overflowInterval;
219				gba->memory.io[REG_TM0CNT_LO >> 1] = timer->reload;
220				timer->oldReload = timer->reload;
221
222				if (timer->doIrq) {
223					GBARaiseIRQ(gba, IRQ_TIMER0);
224				}
225
226				if (gba->audio.enable) {
227					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 0) {
228						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
229					}
230
231					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 0) {
232						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
233					}
234				}
235
236				nextTimer = &gba->timers[1];
237				if (nextTimer->countUp) {
238					++gba->memory.io[REG_TM1CNT_LO >> 1];
239					if (!gba->memory.io[REG_TM1CNT_LO >> 1]) {
240						nextTimer->nextEvent = 0;
241					}
242				}
243			}
244			nextEvent = timer->nextEvent;
245		}
246
247		timer = &gba->timers[1];
248		if (timer->enable) {
249			timer->nextEvent -= cycles;
250			timer->lastEvent -= cycles;
251			if (timer->nextEvent <= 0) {
252				timer->lastEvent = timer->nextEvent;
253				timer->nextEvent += timer->overflowInterval;
254				gba->memory.io[REG_TM1CNT_LO >> 1] = timer->reload;
255				timer->oldReload = timer->reload;
256
257				if (timer->doIrq) {
258					GBARaiseIRQ(gba, IRQ_TIMER1);
259				}
260
261				if (gba->audio.enable) {
262					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 1) {
263						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
264					}
265
266					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 1) {
267						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
268					}
269				}
270
271				if (timer->countUp) {
272					timer->nextEvent = INT_MAX;
273				}
274
275				nextTimer = &gba->timers[2];
276				if (nextTimer->countUp) {
277					++gba->memory.io[REG_TM2CNT_LO >> 1];
278					if (!gba->memory.io[REG_TM2CNT_LO >> 1]) {
279						nextTimer->nextEvent = 0;
280					}
281				}
282			}
283			if (timer->nextEvent < nextEvent) {
284				nextEvent = timer->nextEvent;
285			}
286		}
287
288		timer = &gba->timers[2];
289		if (timer->enable) {
290			timer->nextEvent -= cycles;
291			timer->lastEvent -= cycles;
292			if (timer->nextEvent <= 0) {
293				timer->lastEvent = timer->nextEvent;
294				timer->nextEvent += timer->overflowInterval;
295				gba->memory.io[REG_TM2CNT_LO >> 1] = timer->reload;
296				timer->oldReload = timer->reload;
297
298				if (timer->doIrq) {
299					GBARaiseIRQ(gba, IRQ_TIMER2);
300				}
301
302				if (timer->countUp) {
303					timer->nextEvent = INT_MAX;
304				}
305
306				nextTimer = &gba->timers[3];
307				if (nextTimer->countUp) {
308					++gba->memory.io[REG_TM3CNT_LO >> 1];
309					if (!gba->memory.io[REG_TM3CNT_LO >> 1]) {
310						nextTimer->nextEvent = 0;
311					}
312				}
313			}
314			if (timer->nextEvent < nextEvent) {
315				nextEvent = timer->nextEvent;
316			}
317		}
318
319		timer = &gba->timers[3];
320		if (timer->enable) {
321			timer->nextEvent -= cycles;
322			timer->lastEvent -= cycles;
323			if (timer->nextEvent <= 0) {
324				timer->lastEvent = timer->nextEvent;
325				timer->nextEvent += timer->overflowInterval;
326				gba->memory.io[REG_TM3CNT_LO >> 1] = timer->reload;
327				timer->oldReload = timer->reload;
328
329				if (timer->doIrq) {
330					GBARaiseIRQ(gba, IRQ_TIMER3);
331				}
332
333				if (timer->countUp) {
334					timer->nextEvent = INT_MAX;
335				}
336			}
337			if (timer->nextEvent < nextEvent) {
338				nextEvent = timer->nextEvent;
339			}
340		}
341	}
342	return nextEvent;
343}
344
345void GBAAttachDebugger(struct GBA* gba, struct ARMDebugger* debugger) {
346	debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
347	debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
348	gba->debugger = debugger;
349	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = &debugger->d;
350	ARMHotplugAttach(gba->cpu, GBA_COMPONENT_DEBUGGER);
351}
352
353void GBADetachDebugger(struct GBA* gba) {
354	gba->debugger = 0;
355	ARMHotplugDetach(gba->cpu, GBA_COMPONENT_DEBUGGER);
356	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = 0;
357}
358
359void GBALoadROM(struct GBA* gba, struct VFile* vf, struct VFile* sav, const char* fname) {
360	gba->romVf = vf;
361	gba->pristineRomSize = vf->size(vf);
362	vf->seek(vf, 0, SEEK_SET);
363	if (gba->pristineRomSize > SIZE_CART0) {
364		gba->pristineRomSize = SIZE_CART0;
365	}
366	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
367	if (!gba->pristineRom) {
368		GBALog(gba, GBA_LOG_WARN, "Couldn't map ROM");
369		return;
370	}
371	gba->memory.rom = gba->pristineRom;
372	gba->activeFile = fname;
373	gba->memory.romSize = gba->pristineRomSize;
374	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
375	GBASavedataInit(&gba->memory.savedata, sav);
376	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
377	// TODO: error check
378}
379
380void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
381	gba->biosVf = vf;
382	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
383	if (!bios) {
384		GBALog(gba, GBA_LOG_WARN, "Couldn't map BIOS");
385		return;
386	}
387	gba->memory.bios = bios;
388	gba->memory.fullBios = 1;
389	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
390	GBALog(gba, GBA_LOG_DEBUG, "BIOS Checksum: 0x%X", checksum);
391	if (checksum == GBA_BIOS_CHECKSUM) {
392		GBALog(gba, GBA_LOG_INFO, "Official GBA BIOS detected");
393	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
394		GBALog(gba, GBA_LOG_INFO, "Official GBA (DS) BIOS detected");
395	} else {
396		GBALog(gba, GBA_LOG_WARN, "BIOS checksum incorrect");
397	}
398	gba->biosChecksum = checksum;
399	if (gba->memory.activeRegion == REGION_BIOS) {
400		gba->cpu->memory.activeRegion = gba->memory.bios;
401	}
402	// TODO: error check
403}
404
405void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
406	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
407	if (!patchedSize) {
408		return;
409	}
410	gba->memory.rom = anonymousMemoryMap(patchedSize);
411	if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
412		mappedMemoryFree(gba->memory.rom, patchedSize);
413		gba->memory.rom = gba->pristineRom;
414		return;
415	}
416	gba->memory.romSize = patchedSize;
417	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
418}
419
420void GBATimerUpdateRegister(struct GBA* gba, int timer) {
421	struct GBATimer* currentTimer = &gba->timers[timer];
422	if (currentTimer->enable && !currentTimer->countUp) {
423		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> currentTimer->prescaleBits);
424	}
425}
426
427void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
428	gba->timers[timer].reload = reload;
429}
430
431void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
432	struct GBATimer* currentTimer = &gba->timers[timer];
433	GBATimerUpdateRegister(gba, timer);
434
435	int oldPrescale = currentTimer->prescaleBits;
436	switch (control & 0x0003) {
437	case 0x0000:
438		currentTimer->prescaleBits = 0;
439		break;
440	case 0x0001:
441		currentTimer->prescaleBits = 6;
442		break;
443	case 0x0002:
444		currentTimer->prescaleBits = 8;
445		break;
446	case 0x0003:
447		currentTimer->prescaleBits = 10;
448		break;
449	}
450	currentTimer->countUp = !!(control & 0x0004);
451	currentTimer->doIrq = !!(control & 0x0040);
452	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << currentTimer->prescaleBits;
453	int wasEnabled = currentTimer->enable;
454	currentTimer->enable = !!(control & 0x0080);
455	if (!wasEnabled && currentTimer->enable) {
456		if (!currentTimer->countUp) {
457			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
458		} else {
459			currentTimer->nextEvent = INT_MAX;
460		}
461		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
462		currentTimer->oldReload = currentTimer->reload;
463		currentTimer->lastEvent = 0;
464		gba->timersEnabled |= 1 << timer;
465	} else if (wasEnabled && !currentTimer->enable) {
466		if (!currentTimer->countUp) {
467			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
468		}
469		gba->timersEnabled &= ~(1 << timer);
470	} else if (currentTimer->prescaleBits != oldPrescale && !currentTimer->countUp) {
471		// FIXME: this might be before present
472		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
473	}
474
475	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
476		gba->cpu->nextEvent = currentTimer->nextEvent;
477	}
478};
479
480void GBAWriteIE(struct GBA* gba, uint16_t value) {
481	if (value & (1 << IRQ_KEYPAD)) {
482		GBALog(gba, GBA_LOG_STUB, "Keypad interrupts not implemented");
483	}
484
485	if (value & (1 << IRQ_GAMEPAK)) {
486		GBALog(gba, GBA_LOG_STUB, "Gamepak interrupts not implemented");
487	}
488
489	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
490		ARMRaiseIRQ(gba->cpu);
491	}
492}
493
494void GBAWriteIME(struct GBA* gba, uint16_t value) {
495	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
496		ARMRaiseIRQ(gba->cpu);
497	}
498}
499
500void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
501	gba->memory.io[REG_IF >> 1] |= 1 << irq;
502	gba->cpu->halted = 0;
503
504	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
505		ARMRaiseIRQ(gba->cpu);
506	}
507}
508
509void GBATestIRQ(struct ARMCore* cpu) {
510	struct GBA* gba = (struct GBA*) cpu->master;
511	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
512		gba->springIRQ = 1;
513		gba->cpu->nextEvent = 0;
514	}
515}
516
517void GBAHalt(struct GBA* gba) {
518	gba->cpu->nextEvent = 0;
519	gba->cpu->halted = 1;
520}
521
522static void _GBAVLog(struct GBA* gba, enum GBALogLevel level, const char* format, va_list args) {
523	struct GBAThread* threadContext = GBAThreadGetContext();
524	enum GBALogLevel logLevel = -1;
525
526	if (gba) {
527		logLevel = gba->logLevel;
528	}
529
530	if (threadContext) {
531		logLevel = threadContext->logLevel;
532		gba = threadContext->gba;
533	}
534
535	if (!(level & logLevel) && level != GBA_LOG_FATAL) {
536		return;
537	}
538
539	if (level == GBA_LOG_FATAL && gba) {
540		gba->cpu->nextEvent = 0;
541	}
542
543	if (threadContext) {
544		if (level == GBA_LOG_FATAL) {
545			MutexLock(&threadContext->stateMutex);
546			threadContext->state = THREAD_CRASHED;
547			MutexUnlock(&threadContext->stateMutex);
548		}
549		if (threadContext->logHandler) {
550			threadContext->logHandler(threadContext, level, format, args);
551			return;
552		}
553	}
554
555	vprintf(format, args);
556	printf("\n");
557
558	if (level == GBA_LOG_FATAL && !threadContext) {
559		abort();
560	}
561}
562
563void GBALog(struct GBA* gba, enum GBALogLevel level, const char* format, ...) {
564	va_list args;
565	va_start(args, format);
566	_GBAVLog(gba, level, format, args);
567	va_end(args);
568}
569
570void GBADebuggerLogShim(struct ARMDebugger* debugger, enum DebuggerLogLevel level, const char* format, ...) {
571	struct GBA* gba = 0;
572	if (debugger->cpu) {
573		gba = (struct GBA*) debugger->cpu->master;
574	}
575
576	enum GBALogLevel gbaLevel;
577	switch (level) {
578	default: // Avoids compiler warning
579	case DEBUGGER_LOG_DEBUG:
580		gbaLevel = GBA_LOG_DEBUG;
581		break;
582	case DEBUGGER_LOG_INFO:
583		gbaLevel = GBA_LOG_INFO;
584		break;
585	case DEBUGGER_LOG_WARN:
586		gbaLevel = GBA_LOG_WARN;
587		break;
588	case DEBUGGER_LOG_ERROR:
589		gbaLevel = GBA_LOG_ERROR;
590		break;
591	}
592	va_list args;
593	va_start(args, format);
594	_GBAVLog(gba, gbaLevel, format, args);
595	va_end(args);
596}
597
598bool GBAIsROM(struct VFile* vf) {
599	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
600		return false;
601	}
602	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
603	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
604		return false;
605	}
606	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
607}
608
609bool GBAIsBIOS(struct VFile* vf) {
610	if (vf->seek(vf, 0, SEEK_SET) < 0) {
611		return false;
612	}
613	uint32_t interruptTable[7];
614	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
615		return false;
616	}
617	int i;
618	for (i = 0; i < 7; ++i) {
619		if ((interruptTable[i] & 0xFFFF0000) != 0xEA000000) {
620			return false;
621		}
622	}
623	return true;
624}
625
626void GBAGetGameCode(struct GBA* gba, char* out) {
627	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
628}
629
630void GBAGetGameTitle(struct GBA* gba, char* out) {
631	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
632}
633
634void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
635	struct GBA* gba = (struct GBA*) cpu->master;
636	enum GBALogLevel level = GBA_LOG_FATAL;
637	if (gba->debugger) {
638		level = GBA_LOG_STUB;
639		struct DebuggerEntryInfo info = {
640			.address = _ARMPCAddress(cpu),
641			.opcode = opcode
642		};
643		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
644	}
645	GBALog(gba, level, "Stub opcode: %08x", opcode);
646}
647
648void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
649	struct GBA* gba = (struct GBA*) cpu->master;
650	GBALog(gba, GBA_LOG_WARN, "Illegal opcode: %08x", opcode);
651	if (gba->debugger) {
652		struct DebuggerEntryInfo info = {
653			.address = _ARMPCAddress(cpu),
654			.opcode = opcode
655		};
656		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
657	}
658}
659
660void GBABreakpoint(struct ARMCore* cpu, int immediate) {
661	struct GBA* gba = (struct GBA*) cpu->master;
662	if (immediate >= GBA_COMPONENT_MAX) {
663		return;
664	}
665	switch (immediate) {
666	case GBA_COMPONENT_DEBUGGER:
667		if (gba->debugger) {
668			struct DebuggerEntryInfo info = {
669				.address = _ARMPCAddress(cpu)
670			};
671			ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_BREAKPOINT, &info);
672		}
673		break;
674	case GBA_COMPONENT_CHEAT_DEVICE:
675		if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
676			struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
677			struct GBACheatHook* hook = 0;
678			size_t i;
679			for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
680				struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
681				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
682					GBACheatRefresh(device, cheats);
683					hook = cheats->hook;
684				}
685			}
686			if (hook) {
687				ARMRunFake(cpu, hook->patchedOpcode);
688			}
689		}
690		break;
691	default:
692		break;
693	}
694}
695
696void GBAFrameStarted(struct GBA* gba) {
697	UNUSED(gba);
698
699	struct GBAThread* thread = GBAThreadGetContext();
700	if (!thread) {
701		return;
702	}
703
704	if (thread->rewindBuffer) {
705		--thread->rewindBufferNext;
706		if (thread->rewindBufferNext <= 0) {
707			thread->rewindBufferNext = thread->rewindBufferInterval;
708			GBARecordFrame(thread);
709		}
710	}
711}
712
713void GBAFrameEnded(struct GBA* gba) {
714	if (gba->rr) {
715		GBARRNextFrame(gba->rr);
716	}
717
718	if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
719		struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
720		size_t i;
721		for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
722			struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
723			if (!cheats->hook) {
724				GBACheatRefresh(device, cheats);
725			}
726		}
727	}
728
729
730	struct GBAThread* thread = GBAThreadGetContext();
731	if (!thread) {
732		return;
733	}
734
735	if (thread->stream) {
736		thread->stream->postVideoFrame(thread->stream, thread->renderer);
737	}
738
739	if (thread->frameCallback) {
740		thread->frameCallback(thread);
741	}
742}
743
744void GBASetBreakpoint(struct GBA* gba, struct ARMComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
745	size_t immediate;
746	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
747		if (gba->cpu->components[immediate] == component) {
748			break;
749		}
750	}
751	if (immediate == gba->cpu->numComponents) {
752		return;
753	}
754	if (mode == MODE_ARM) {
755		int32_t value;
756		int32_t old;
757		value = 0xE1200070;
758		value |= immediate & 0xF;
759		value |= (immediate & 0xFFF0) << 4;
760		GBAPatch32(gba->cpu, address, value, &old);
761		*opcode = old;
762	} else {
763		int16_t value;
764		int16_t old;
765		value = 0xBE00;
766		value |= immediate & 0xFF;
767		GBAPatch16(gba->cpu, address, value, &old);
768		*opcode = (uint16_t) old;
769	}
770}
771
772void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
773	if (mode == MODE_ARM) {
774		GBAPatch32(gba->cpu, address, opcode, 0);
775	} else {
776		GBAPatch16(gba->cpu, address, opcode, 0);
777	}
778}
779
780static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
781	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d, address, mode, opcode);
782	return true;
783}
784
785static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
786	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
787	return true;
788}