all repos — mgba @ 52c66de6945adefa72d87cf5c461af4b30fd1d68

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