all repos — mgba @ bd2c472cb355f96ad5a30a52964ed7606ead6ddb

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