all repos — mgba @ ea12461c5ba577c7056ffb9348098d3f0f592822

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