all repos — mgba @ 4fd479897c6972377ac625f43306aa794bc4d5c0

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