all repos — mgba @ 401bc9e9d632869c25072694b3c491f86e93ba8c

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