all repos — mgba @ 04e40ff45933a47c055ae1799f1539c5e8f9a109

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