all repos — mgba @ 7c4df24bc76581a354dc56593caf5f879f1107e6

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
391void 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;
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	// TODO: error check
413}
414
415void GBAYankROM(struct GBA* gba) {
416	gba->yankedRomSize = gba->memory.romSize;
417	gba->memory.romSize = 0;
418	gba->memory.romMask = 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->memory.romMask = SIZE_CART0 - 1;
460	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
461}
462
463void GBATimerUpdateRegister(struct GBA* gba, int timer) {
464	struct GBATimer* currentTimer = &gba->timers[timer];
465	if (currentTimer->enable && !currentTimer->countUp) {
466		int32_t prefetchSkew = 0;
467		if (gba->memory.lastPrefetchedPc - gba->memory.lastPrefetchedLoads * WORD_SIZE_THUMB >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
468			prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
469		}
470		// Reading this takes two cycles (1N+1I), so let's remove them preemptively
471		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> currentTimer->prescaleBits);
472	}
473}
474
475void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
476	gba->timers[timer].reload = reload;
477	gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << gba->timers[timer].prescaleBits;
478}
479
480void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
481	struct GBATimer* currentTimer = &gba->timers[timer];
482	GBATimerUpdateRegister(gba, timer);
483
484	int oldPrescale = currentTimer->prescaleBits;
485	switch (control & 0x0003) {
486	case 0x0000:
487		currentTimer->prescaleBits = 0;
488		break;
489	case 0x0001:
490		currentTimer->prescaleBits = 6;
491		break;
492	case 0x0002:
493		currentTimer->prescaleBits = 8;
494		break;
495	case 0x0003:
496		currentTimer->prescaleBits = 10;
497		break;
498	}
499	currentTimer->countUp = !!(control & 0x0004);
500	currentTimer->doIrq = !!(control & 0x0040);
501	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << currentTimer->prescaleBits;
502	int wasEnabled = currentTimer->enable;
503	currentTimer->enable = !!(control & 0x0080);
504	if (!wasEnabled && currentTimer->enable) {
505		if (!currentTimer->countUp) {
506			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
507		} else {
508			currentTimer->nextEvent = INT_MAX;
509		}
510		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
511		currentTimer->oldReload = currentTimer->reload;
512		currentTimer->lastEvent = gba->cpu->cycles;
513		gba->timersEnabled |= 1 << timer;
514	} else if (wasEnabled && !currentTimer->enable) {
515		if (!currentTimer->countUp) {
516			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
517		}
518		gba->timersEnabled &= ~(1 << timer);
519	} else if (currentTimer->prescaleBits != oldPrescale && !currentTimer->countUp) {
520		// FIXME: this might be before present
521		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
522	}
523
524	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
525		gba->cpu->nextEvent = currentTimer->nextEvent;
526	}
527};
528
529void GBAWriteIE(struct GBA* gba, uint16_t value) {
530	if (value & (1 << IRQ_KEYPAD)) {
531		GBALog(gba, GBA_LOG_STUB, "Keypad interrupts not implemented");
532	}
533
534	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
535		ARMRaiseIRQ(gba->cpu);
536	}
537}
538
539void GBAWriteIME(struct GBA* gba, uint16_t value) {
540	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
541		ARMRaiseIRQ(gba->cpu);
542	}
543}
544
545void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
546	gba->memory.io[REG_IF >> 1] |= 1 << irq;
547	gba->cpu->halted = 0;
548
549	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
550		ARMRaiseIRQ(gba->cpu);
551	}
552}
553
554void GBATestIRQ(struct ARMCore* cpu) {
555	struct GBA* gba = (struct GBA*) cpu->master;
556	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
557		gba->springIRQ = 1;
558		gba->cpu->nextEvent = 0;
559	}
560}
561
562void GBAHalt(struct GBA* gba) {
563	gba->cpu->nextEvent = 0;
564	gba->cpu->halted = 1;
565}
566
567void GBAStop(struct GBA* gba) {
568	if (!gba->stopCallback) {
569		return;
570	}
571	gba->cpu->nextEvent = 0;
572	gba->stopCallback->stop(gba->stopCallback);
573}
574
575static void _GBAVLog(struct GBA* gba, enum GBALogLevel level, const char* format, va_list args) {
576	struct GBAThread* threadContext = GBAThreadGetContext();
577	enum GBALogLevel logLevel = GBA_LOG_ALL;
578
579	if (gba) {
580		logLevel = gba->logLevel;
581	}
582
583	if (threadContext) {
584		logLevel = threadContext->logLevel;
585		gba = threadContext->gba;
586	}
587
588	if (!(level & logLevel) && level != GBA_LOG_FATAL) {
589		return;
590	}
591
592	if (level == GBA_LOG_FATAL && gba) {
593		gba->cpu->nextEvent = 0;
594	}
595
596	if (threadContext) {
597		if (level == GBA_LOG_FATAL) {
598			MutexLock(&threadContext->stateMutex);
599			threadContext->state = THREAD_CRASHED;
600			MutexUnlock(&threadContext->stateMutex);
601		}
602	}
603	if (gba && gba->logHandler) {
604		gba->logHandler(threadContext, level, format, args);
605		return;
606	}
607
608	vprintf(format, args);
609	printf("\n");
610
611	if (level == GBA_LOG_FATAL && !threadContext) {
612		abort();
613	}
614}
615
616void GBALog(struct GBA* gba, enum GBALogLevel level, const char* format, ...) {
617	va_list args;
618	va_start(args, format);
619	_GBAVLog(gba, level, format, args);
620	va_end(args);
621}
622
623void GBADebuggerLogShim(struct ARMDebugger* debugger, enum DebuggerLogLevel level, const char* format, ...) {
624	struct GBA* gba = 0;
625	if (debugger->cpu) {
626		gba = (struct GBA*) debugger->cpu->master;
627	}
628
629	enum GBALogLevel gbaLevel;
630	switch (level) {
631	default: // Avoids compiler warning
632	case DEBUGGER_LOG_DEBUG:
633		gbaLevel = GBA_LOG_DEBUG;
634		break;
635	case DEBUGGER_LOG_INFO:
636		gbaLevel = GBA_LOG_INFO;
637		break;
638	case DEBUGGER_LOG_WARN:
639		gbaLevel = GBA_LOG_WARN;
640		break;
641	case DEBUGGER_LOG_ERROR:
642		gbaLevel = GBA_LOG_ERROR;
643		break;
644	}
645	va_list args;
646	va_start(args, format);
647	_GBAVLog(gba, gbaLevel, format, args);
648	va_end(args);
649}
650
651bool GBAIsROM(struct VFile* vf) {
652	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
653		return false;
654	}
655	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
656	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
657		return false;
658	}
659	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
660}
661
662bool GBAIsBIOS(struct VFile* vf) {
663	if (vf->seek(vf, 0, SEEK_SET) < 0) {
664		return false;
665	}
666	uint32_t interruptTable[7];
667	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
668		return false;
669	}
670	int i;
671	for (i = 0; i < 7; ++i) {
672		if ((interruptTable[i] & 0xFFFF0000) != 0xEA000000) {
673			return false;
674		}
675	}
676	return true;
677}
678
679void GBAGetGameCode(struct GBA* gba, char* out) {
680	if (!gba->memory.rom) {
681		out[0] = '\0';
682		return;
683	}
684	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
685}
686
687void GBAGetGameTitle(struct GBA* gba, char* out) {
688	if (!gba->memory.rom) {
689		strncpy(out, "(BIOS)", 12);
690		return;
691	}
692	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
693}
694
695void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
696	struct GBA* gba = (struct GBA*) cpu->master;
697	enum GBALogLevel level = GBA_LOG_ERROR;
698	if (gba->debugger) {
699		level = GBA_LOG_STUB;
700		struct DebuggerEntryInfo info = {
701			.address = _ARMPCAddress(cpu),
702			.opcode = opcode
703		};
704		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
705	}
706	GBALog(gba, level, "Stub opcode: %08x", opcode);
707}
708
709void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
710	struct GBA* gba = (struct GBA*) cpu->master;
711	if (!gba->yankedRomSize) {
712		GBALog(gba, GBA_LOG_WARN, "Illegal opcode: %08x", opcode);
713	}
714	if (gba->debugger) {
715		struct DebuggerEntryInfo info = {
716			.address = _ARMPCAddress(cpu),
717			.opcode = opcode
718		};
719		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
720	} else {
721		ARMRaiseUndefined(cpu);
722	}
723}
724
725void GBABreakpoint(struct ARMCore* cpu, int immediate) {
726	struct GBA* gba = (struct GBA*) cpu->master;
727	if (immediate >= GBA_COMPONENT_MAX) {
728		return;
729	}
730	switch (immediate) {
731	case GBA_COMPONENT_DEBUGGER:
732		if (gba->debugger) {
733			struct DebuggerEntryInfo info = {
734				.address = _ARMPCAddress(cpu)
735			};
736			ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_BREAKPOINT, &info);
737		}
738		break;
739	case GBA_COMPONENT_CHEAT_DEVICE:
740		if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
741			struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
742			struct GBACheatHook* hook = 0;
743			size_t i;
744			for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
745				struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
746				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
747					GBACheatRefresh(device, cheats);
748					hook = cheats->hook;
749				}
750			}
751			if (hook) {
752				ARMRunFake(cpu, hook->patchedOpcode);
753			}
754		}
755		break;
756	default:
757		break;
758	}
759}
760
761void GBAFrameStarted(struct GBA* gba) {
762	UNUSED(gba);
763
764	struct GBAThread* thread = GBAThreadGetContext();
765	if (!thread) {
766		return;
767	}
768
769	if (thread->rewindBuffer) {
770		--thread->rewindBufferNext;
771		if (thread->rewindBufferNext <= 0) {
772			thread->rewindBufferNext = thread->rewindBufferInterval;
773			GBARecordFrame(thread);
774		}
775	}
776}
777
778void GBAFrameEnded(struct GBA* gba) {
779	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
780
781	if (gba->rr) {
782		gba->rr->nextFrame(gba->rr);
783	}
784
785	if (gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
786		struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
787		size_t i;
788		for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
789			struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
790			if (!cheats->hook) {
791				GBACheatRefresh(device, cheats);
792			}
793		}
794	}
795
796	if (gba->stream) {
797		gba->stream->postVideoFrame(gba->stream, gba->video.renderer);
798	}
799
800	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
801		GBAHardwarePlayerUpdate(gba);
802	}
803
804	struct GBAThread* thread = GBAThreadGetContext();
805	if (!thread) {
806		return;
807	}
808
809	if (thread->frameCallback) {
810		thread->frameCallback(thread);
811	}
812}
813
814void GBASetBreakpoint(struct GBA* gba, struct ARMComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
815	size_t immediate;
816	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
817		if (gba->cpu->components[immediate] == component) {
818			break;
819		}
820	}
821	if (immediate == gba->cpu->numComponents) {
822		return;
823	}
824	if (mode == MODE_ARM) {
825		int32_t value;
826		int32_t old;
827		value = 0xE1200070;
828		value |= immediate & 0xF;
829		value |= (immediate & 0xFFF0) << 4;
830		GBAPatch32(gba->cpu, address, value, &old);
831		*opcode = old;
832	} else {
833		int16_t value;
834		int16_t old;
835		value = 0xBE00;
836		value |= immediate & 0xFF;
837		GBAPatch16(gba->cpu, address, value, &old);
838		*opcode = (uint16_t) old;
839	}
840}
841
842void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
843	if (mode == MODE_ARM) {
844		GBAPatch32(gba->cpu, address, opcode, 0);
845	} else {
846		GBAPatch16(gba->cpu, address, opcode, 0);
847	}
848}
849
850static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
851	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d, address, mode, opcode);
852	return true;
853}
854
855static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
856	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
857	return true;
858}