all repos — mgba @ 10ab177c26af4d712a0843b20c20cd1ca27ef314

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