all repos — mgba @ 33ca1e2e9ce98d63ecbd6ff3e815197ade0c6a1b

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