all repos — mgba @ d588b8c462d780cea27489a0dc697bf0c5e36984

mGBA Game Boy Advance Emulator

src/gba/gba.c (view raw)

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