all repos — mgba @ 28268a601bcd1fcc71389c1b8a278dd69bcefd9f

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