all repos — mgba @ 0e8e55e8eda47f9ba7d7b8c5867b725cfa1f7f9b

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	do {
209		struct GBA* gba = (struct GBA*) cpu->master;
210		int32_t cycles = cpu->nextEvent;
211		int32_t nextEvent = INT_MAX;
212		int32_t testEvent;
213#ifndef NDEBUG
214		if (cycles < 0) {
215			GBALog(gba, GBA_LOG_FATAL, "Negative cycles passed: %i", cycles);
216		}
217#endif
218
219		gba->bus = cpu->prefetch[1];
220		if (cpu->executionMode == MODE_THUMB) {
221			gba->bus |= cpu->prefetch[1] << 16;
222		}
223
224		if (gba->springIRQ) {
225			ARMRaiseIRQ(cpu);
226			gba->springIRQ = 0;
227		}
228
229		testEvent = GBAVideoProcessEvents(&gba->video, cycles);
230		if (testEvent < nextEvent) {
231			nextEvent = testEvent;
232		}
233
234		testEvent = GBAAudioProcessEvents(&gba->audio, cycles);
235		if (testEvent < nextEvent) {
236			nextEvent = testEvent;
237		}
238
239		testEvent = GBATimersProcessEvents(gba, cycles);
240		if (testEvent < nextEvent) {
241			nextEvent = testEvent;
242		}
243
244		testEvent = GBAMemoryRunDMAs(gba, cycles);
245		if (testEvent < nextEvent) {
246			nextEvent = testEvent;
247		}
248
249		testEvent = GBASIOProcessEvents(&gba->sio, cycles);
250		if (testEvent < nextEvent) {
251			nextEvent = testEvent;
252		}
253
254		cpu->cycles -= cycles;
255		cpu->nextEvent = nextEvent;
256
257		if (cpu->halted) {
258			cpu->cycles = cpu->nextEvent;
259		}
260	} while (cpu->cycles >= cpu->nextEvent);
261}
262
263static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles) {
264	int32_t nextEvent = INT_MAX;
265	if (gba->timersEnabled) {
266		struct GBATimer* timer;
267		struct GBATimer* nextTimer;
268
269		timer = &gba->timers[0];
270		if (GBATimerFlagsIsEnable(timer->flags)) {
271			timer->nextEvent -= cycles;
272			timer->lastEvent -= cycles;
273			while (timer->nextEvent <= 0) {
274				timer->lastEvent = timer->nextEvent;
275				timer->nextEvent += timer->overflowInterval;
276				gba->memory.io[REG_TM0CNT_LO >> 1] = timer->reload;
277				timer->oldReload = timer->reload;
278
279				if (GBATimerFlagsIsDoIrq(timer->flags)) {
280					GBARaiseIRQ(gba, IRQ_TIMER0);
281				}
282
283				if (gba->audio.enable) {
284					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 0) {
285						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
286					}
287
288					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 0) {
289						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
290					}
291				}
292
293				nextTimer = &gba->timers[1];
294				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
295					++gba->memory.io[REG_TM1CNT_LO >> 1];
296					if (!gba->memory.io[REG_TM1CNT_LO >> 1]) {
297						nextTimer->nextEvent = 0;
298					}
299				}
300			}
301			nextEvent = timer->nextEvent;
302		}
303
304		timer = &gba->timers[1];
305		if (GBATimerFlagsIsEnable(timer->flags)) {
306			timer->nextEvent -= cycles;
307			timer->lastEvent -= cycles;
308			if (timer->nextEvent <= 0) {
309				timer->lastEvent = timer->nextEvent;
310				timer->nextEvent += timer->overflowInterval;
311				gba->memory.io[REG_TM1CNT_LO >> 1] = timer->reload;
312				timer->oldReload = timer->reload;
313
314				if (GBATimerFlagsIsDoIrq(timer->flags)) {
315					GBARaiseIRQ(gba, IRQ_TIMER1);
316				}
317
318				if (gba->audio.enable) {
319					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 1) {
320						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
321					}
322
323					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 1) {
324						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
325					}
326				}
327
328				if (GBATimerFlagsIsCountUp(timer->flags)) {
329					timer->nextEvent = INT_MAX;
330				}
331
332				nextTimer = &gba->timers[2];
333				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
334					++gba->memory.io[REG_TM2CNT_LO >> 1];
335					if (!gba->memory.io[REG_TM2CNT_LO >> 1]) {
336						nextTimer->nextEvent = 0;
337					}
338				}
339			}
340			if (timer->nextEvent < nextEvent) {
341				nextEvent = timer->nextEvent;
342			}
343		}
344
345		timer = &gba->timers[2];
346		if (GBATimerFlagsIsEnable(timer->flags)) {
347			timer->nextEvent -= cycles;
348			timer->lastEvent -= cycles;
349			if (timer->nextEvent <= 0) {
350				timer->lastEvent = timer->nextEvent;
351				timer->nextEvent += timer->overflowInterval;
352				gba->memory.io[REG_TM2CNT_LO >> 1] = timer->reload;
353				timer->oldReload = timer->reload;
354
355				if (GBATimerFlagsIsDoIrq(timer->flags)) {
356					GBARaiseIRQ(gba, IRQ_TIMER2);
357				}
358
359				if (GBATimerFlagsIsCountUp(timer->flags)) {
360					timer->nextEvent = INT_MAX;
361				}
362
363				nextTimer = &gba->timers[3];
364				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
365					++gba->memory.io[REG_TM3CNT_LO >> 1];
366					if (!gba->memory.io[REG_TM3CNT_LO >> 1]) {
367						nextTimer->nextEvent = 0;
368					}
369				}
370			}
371			if (timer->nextEvent < nextEvent) {
372				nextEvent = timer->nextEvent;
373			}
374		}
375
376		timer = &gba->timers[3];
377		if (GBATimerFlagsIsEnable(timer->flags)) {
378			timer->nextEvent -= cycles;
379			timer->lastEvent -= cycles;
380			if (timer->nextEvent <= 0) {
381				timer->lastEvent = timer->nextEvent;
382				timer->nextEvent += timer->overflowInterval;
383				gba->memory.io[REG_TM3CNT_LO >> 1] = timer->reload;
384				timer->oldReload = timer->reload;
385
386				if (GBATimerFlagsIsDoIrq(timer->flags)) {
387					GBARaiseIRQ(gba, IRQ_TIMER3);
388				}
389
390				if (GBATimerFlagsIsCountUp(timer->flags)) {
391					timer->nextEvent = INT_MAX;
392				}
393			}
394			if (timer->nextEvent < nextEvent) {
395				nextEvent = timer->nextEvent;
396			}
397		}
398	}
399	return nextEvent;
400}
401
402void GBAAttachDebugger(struct GBA* gba, struct ARMDebugger* debugger) {
403	debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
404	debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
405	gba->debugger = debugger;
406	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = &debugger->d;
407	ARMHotplugAttach(gba->cpu, GBA_COMPONENT_DEBUGGER);
408}
409
410void GBADetachDebugger(struct GBA* gba) {
411	gba->debugger = 0;
412	ARMHotplugDetach(gba->cpu, GBA_COMPONENT_DEBUGGER);
413	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = 0;
414}
415
416bool GBALoadMB(struct GBA* gba, struct VFile* vf, const char* fname) {
417	GBAUnloadROM(gba);
418	gba->romVf = vf;
419	gba->pristineRomSize = vf->size(vf);
420	vf->seek(vf, 0, SEEK_SET);
421	if (gba->pristineRomSize > SIZE_WORKING_RAM) {
422		gba->pristineRomSize = SIZE_WORKING_RAM;
423	}
424#ifdef _3DS
425	gba->pristineRom = 0;
426	if (gba->pristineRomSize <= romBufferSize) {
427		gba->pristineRom = romBuffer;
428		vf->read(vf, romBuffer, gba->pristineRomSize);
429	}
430#else
431	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
432#endif
433	if (!gba->pristineRom) {
434		GBALog(gba, GBA_LOG_WARN, "Couldn't map ROM");
435		return false;
436	}
437	gba->yankedRomSize = 0;
438	gba->activeFile = fname;
439	gba->memory.romSize = 0;
440	gba->memory.romMask = 0;
441	gba->romCrc32 = doCrc32(gba->pristineRom, gba->pristineRomSize);
442	return true;
443}
444
445bool GBALoadROM(struct GBA* gba, struct VFile* vf, struct VFile* sav, const char* fname) {
446	GBAUnloadROM(gba);
447	gba->romVf = vf;
448	gba->pristineRomSize = vf->size(vf);
449	vf->seek(vf, 0, SEEK_SET);
450	if (gba->pristineRomSize > SIZE_CART0) {
451		gba->pristineRomSize = SIZE_CART0;
452	}
453#ifdef _3DS
454	gba->pristineRom = 0;
455	if (gba->pristineRomSize <= romBufferSize) {
456		gba->pristineRom = romBuffer;
457		vf->read(vf, romBuffer, gba->pristineRomSize);
458	}
459#else
460	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
461#endif
462	if (!gba->pristineRom) {
463		GBALog(gba, GBA_LOG_WARN, "Couldn't map ROM");
464		return false;
465	}
466	gba->yankedRomSize = 0;
467	gba->memory.rom = gba->pristineRom;
468	gba->activeFile = fname;
469	gba->memory.romSize = gba->pristineRomSize;
470	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
471	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
472	GBASavedataInit(&gba->memory.savedata, sav);
473	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
474	return true;
475	// TODO: error check
476}
477
478void GBAYankROM(struct GBA* gba) {
479	gba->yankedRomSize = gba->memory.romSize;
480	gba->memory.romSize = 0;
481	gba->memory.romMask = 0;
482	GBARaiseIRQ(gba, IRQ_GAMEPAK);
483}
484
485void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
486	gba->biosVf = vf;
487	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
488	if (!bios) {
489		GBALog(gba, GBA_LOG_WARN, "Couldn't map BIOS");
490		return;
491	}
492	gba->memory.bios = bios;
493	gba->memory.fullBios = 1;
494	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
495	GBALog(gba, GBA_LOG_DEBUG, "BIOS Checksum: 0x%X", checksum);
496	if (checksum == GBA_BIOS_CHECKSUM) {
497		GBALog(gba, GBA_LOG_INFO, "Official GBA BIOS detected");
498	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
499		GBALog(gba, GBA_LOG_INFO, "Official GBA (DS) BIOS detected");
500	} else {
501		GBALog(gba, GBA_LOG_WARN, "BIOS checksum incorrect");
502	}
503	gba->biosChecksum = checksum;
504	if (gba->memory.activeRegion == REGION_BIOS) {
505		gba->cpu->memory.activeRegion = gba->memory.bios;
506	}
507	// TODO: error check
508}
509
510void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
511	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
512	if (!patchedSize || patchedSize > SIZE_CART0) {
513		return;
514	}
515	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
516	if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
517		mappedMemoryFree(gba->memory.rom, patchedSize);
518		gba->memory.rom = gba->pristineRom;
519		return;
520	}
521	gba->memory.romSize = patchedSize;
522	gba->memory.romMask = SIZE_CART0 - 1;
523	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
524}
525
526void GBATimerUpdateRegister(struct GBA* gba, int timer) {
527	struct GBATimer* currentTimer = &gba->timers[timer];
528	if (GBATimerFlagsIsEnable(currentTimer->flags) && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
529		int32_t prefetchSkew = 0;
530		if (gba->memory.lastPrefetchedPc - gba->memory.lastPrefetchedLoads * WORD_SIZE_THUMB >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
531			prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
532		}
533		// Reading this takes two cycles (1N+1I), so let's remove them preemptively
534		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> GBATimerFlagsGetPrescaleBits(currentTimer->flags));
535	}
536}
537
538void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
539	gba->timers[timer].reload = reload;
540	gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << GBATimerFlagsGetPrescaleBits(gba->timers[timer].flags);
541}
542
543void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
544	struct GBATimer* currentTimer = &gba->timers[timer];
545	GBATimerUpdateRegister(gba, timer);
546
547	unsigned oldPrescale = GBATimerFlagsGetPrescaleBits(currentTimer->flags);
548	switch (control & 0x0003) {
549	case 0x0000:
550		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 0);
551		break;
552	case 0x0001:
553		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 6);
554		break;
555	case 0x0002:
556		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 8);
557		break;
558	case 0x0003:
559		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 10);
560		break;
561	}
562	currentTimer->flags = GBATimerFlagsTestFillCountUp(currentTimer->flags, control & 0x0004);
563	currentTimer->flags = GBATimerFlagsTestFillDoIrq(currentTimer->flags, control & 0x0040);
564	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << GBATimerFlagsGetPrescaleBits(currentTimer->flags);
565	bool wasEnabled = GBATimerFlagsIsEnable(currentTimer->flags);
566	currentTimer->flags = GBATimerFlagsTestFillEnable(currentTimer->flags, control & 0x0080);
567	if (!wasEnabled && GBATimerFlagsIsEnable(currentTimer->flags)) {
568		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
569			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
570		} else {
571			currentTimer->nextEvent = INT_MAX;
572		}
573		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
574		currentTimer->oldReload = currentTimer->reload;
575		currentTimer->lastEvent = gba->cpu->cycles;
576		gba->timersEnabled |= 1 << timer;
577	} else if (wasEnabled && !GBATimerFlagsIsEnable(currentTimer->flags)) {
578		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
579			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
580		}
581		gba->timersEnabled &= ~(1 << timer);
582	} else if (GBATimerFlagsGetPrescaleBits(currentTimer->flags) != oldPrescale && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
583		// FIXME: this might be before present
584		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
585	}
586
587	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
588		gba->cpu->nextEvent = currentTimer->nextEvent;
589	}
590};
591
592void GBAWriteIE(struct GBA* gba, uint16_t value) {
593	if (value & (1 << IRQ_KEYPAD)) {
594		GBALog(gba, GBA_LOG_STUB, "Keypad interrupts not implemented");
595	}
596
597	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
598		ARMRaiseIRQ(gba->cpu);
599	}
600}
601
602void GBAWriteIME(struct GBA* gba, uint16_t value) {
603	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
604		ARMRaiseIRQ(gba->cpu);
605	}
606}
607
608void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
609	gba->memory.io[REG_IF >> 1] |= 1 << irq;
610	gba->cpu->halted = 0;
611
612	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
613		ARMRaiseIRQ(gba->cpu);
614	}
615}
616
617void GBATestIRQ(struct ARMCore* cpu) {
618	struct GBA* gba = (struct GBA*) cpu->master;
619	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
620		gba->springIRQ = 1;
621		gba->cpu->nextEvent = gba->cpu->cycles;
622	}
623}
624
625void GBAHalt(struct GBA* gba) {
626	gba->cpu->nextEvent = gba->cpu->cycles;
627	gba->cpu->halted = 1;
628}
629
630void GBAStop(struct GBA* gba) {
631	if (!gba->stopCallback) {
632		return;
633	}
634	gba->cpu->nextEvent = gba->cpu->cycles;
635	gba->stopCallback->stop(gba->stopCallback);
636}
637
638static void _GBAVLog(struct GBA* gba, enum GBALogLevel level, const char* format, va_list args) {
639	struct GBAThread* threadContext = GBAThreadGetContext();
640	enum GBALogLevel logLevel = GBA_LOG_ALL;
641
642	if (gba) {
643		logLevel = gba->logLevel;
644	}
645
646	if (threadContext) {
647		logLevel = threadContext->logLevel;
648		gba = threadContext->gba;
649	}
650
651	if (!(level & logLevel) && level != GBA_LOG_FATAL) {
652		return;
653	}
654
655	if (level == GBA_LOG_FATAL && gba) {
656		gba->cpu->nextEvent = 0;
657	}
658
659	if (threadContext) {
660		if (level == GBA_LOG_FATAL) {
661			MutexLock(&threadContext->stateMutex);
662			threadContext->state = THREAD_CRASHED;
663			MutexUnlock(&threadContext->stateMutex);
664		}
665	}
666	if (gba && gba->logHandler) {
667		gba->logHandler(threadContext, level, format, args);
668		return;
669	}
670
671	vprintf(format, args);
672	printf("\n");
673
674	if (level == GBA_LOG_FATAL && !threadContext) {
675		abort();
676	}
677}
678
679void GBALog(struct GBA* gba, enum GBALogLevel level, const char* format, ...) {
680	va_list args;
681	va_start(args, format);
682	_GBAVLog(gba, level, format, args);
683	va_end(args);
684}
685
686void GBADebuggerLogShim(struct ARMDebugger* debugger, enum DebuggerLogLevel level, const char* format, ...) {
687	struct GBA* gba = 0;
688	if (debugger->cpu) {
689		gba = (struct GBA*) debugger->cpu->master;
690	}
691
692	enum GBALogLevel gbaLevel;
693	switch (level) {
694	default: // Avoids compiler warning
695	case DEBUGGER_LOG_DEBUG:
696		gbaLevel = GBA_LOG_DEBUG;
697		break;
698	case DEBUGGER_LOG_INFO:
699		gbaLevel = GBA_LOG_INFO;
700		break;
701	case DEBUGGER_LOG_WARN:
702		gbaLevel = GBA_LOG_WARN;
703		break;
704	case DEBUGGER_LOG_ERROR:
705		gbaLevel = GBA_LOG_ERROR;
706		break;
707	}
708	va_list args;
709	va_start(args, format);
710	_GBAVLog(gba, gbaLevel, format, args);
711	va_end(args);
712}
713
714bool GBAIsROM(struct VFile* vf) {
715	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
716		return false;
717	}
718	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
719	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
720		return false;
721	}
722	if (GBAIsBIOS(vf)) {
723		return false;
724	}
725	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
726}
727
728bool GBAIsMB(struct VFile* vf) {
729	if (!GBAIsROM(vf)) {
730		return false;
731	}
732	if (vf->size(vf) > SIZE_WORKING_RAM) {
733		return false;
734	}
735	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
736		return false;
737	}
738	uint32_t signature;
739	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
740		return false;
741	}
742	uint32_t opcode;
743	LOAD_32(opcode, 0, &signature);
744	struct ARMInstructionInfo info;
745	ARMDecodeARM(opcode, &info);
746	if (info.branchType != ARM_BRANCH) {
747		return false;
748	}
749	if (info.op1.immediate <= 0) {
750		return false;
751	} else if (info.op1.immediate == 28) {
752		// Ancient toolchain that is known to throw MB detection for a loop
753		return false;
754	} else if (info.op1.immediate != 24) {
755		return true;
756	}
757	// Found a libgba-linked cart...these are a bit harder to detect.
758	return false;
759}
760
761bool GBAIsBIOS(struct VFile* vf) {
762	if (vf->seek(vf, 0, SEEK_SET) < 0) {
763		return false;
764	}
765	uint8_t interruptTable[7 * 4];
766	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
767		return false;
768	}
769	int i;
770	for (i = 0; i < 7; ++i) {
771		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
772			return false;
773		}
774	}
775	return true;
776}
777
778void GBAGetGameCode(struct GBA* gba, char* out) {
779	if (!gba->memory.rom) {
780		out[0] = '\0';
781		return;
782	}
783	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
784}
785
786void GBAGetGameTitle(struct GBA* gba, char* out) {
787	if (gba->memory.rom) {
788		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
789		return;
790	}
791	if (gba->pristineRom) {
792		memcpy(out, &((struct GBACartridge*) gba->pristineRom)->title, 12);
793		return;
794	}
795	strncpy(out, "(BIOS)", 12);
796}
797
798void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
799	struct GBA* gba = (struct GBA*) cpu->master;
800	enum GBALogLevel level = GBA_LOG_ERROR;
801	if (gba->debugger) {
802		level = GBA_LOG_STUB;
803		struct DebuggerEntryInfo info = {
804			.address = _ARMPCAddress(cpu),
805			.opcode = opcode
806		};
807		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
808	}
809	GBALog(gba, level, "Stub opcode: %08x", opcode);
810}
811
812void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
813	struct GBA* gba = (struct GBA*) cpu->master;
814	if (!gba->yankedRomSize) {
815		GBALog(gba, GBA_LOG_WARN, "Illegal opcode: %08x", opcode);
816	}
817	if (gba->debugger) {
818		struct DebuggerEntryInfo info = {
819			.address = _ARMPCAddress(cpu),
820			.opcode = opcode
821		};
822		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
823	} else {
824		ARMRaiseUndefined(cpu);
825	}
826}
827
828void GBABreakpoint(struct ARMCore* cpu, int immediate) {
829	struct GBA* gba = (struct GBA*) cpu->master;
830	if (immediate >= GBA_COMPONENT_MAX) {
831		return;
832	}
833	switch (immediate) {
834	case GBA_COMPONENT_DEBUGGER:
835		if (gba->debugger) {
836			struct DebuggerEntryInfo info = {
837				.address = _ARMPCAddress(cpu)
838			};
839			ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_BREAKPOINT, &info);
840		}
841		break;
842	case GBA_COMPONENT_CHEAT_DEVICE:
843		if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
844			struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
845			struct GBACheatHook* hook = 0;
846			size_t i;
847			for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
848				struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
849				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
850					GBACheatRefresh(device, cheats);
851					hook = cheats->hook;
852				}
853			}
854			if (hook) {
855				ARMRunFake(cpu, hook->patchedOpcode);
856			}
857		}
858		break;
859	default:
860		break;
861	}
862}
863
864void GBAFrameStarted(struct GBA* gba) {
865	UNUSED(gba);
866
867	struct GBAThread* thread = GBAThreadGetContext();
868	if (!thread) {
869		return;
870	}
871
872	if (thread->rewindBuffer) {
873		--thread->rewindBufferNext;
874		if (thread->rewindBufferNext <= 0) {
875			thread->rewindBufferNext = thread->rewindBufferInterval;
876			GBARecordFrame(thread);
877		}
878	}
879}
880
881void GBAFrameEnded(struct GBA* gba) {
882	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
883
884	if (gba->rr) {
885		gba->rr->nextFrame(gba->rr);
886	}
887
888	if (gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
889		struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
890		size_t i;
891		for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
892			struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
893			if (!cheats->hook) {
894				GBACheatRefresh(device, cheats);
895			}
896		}
897	}
898
899	if (gba->stream && gba->stream->postVideoFrame) {
900		gba->stream->postVideoFrame(gba->stream, gba->video.renderer);
901	}
902
903	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
904		GBAHardwarePlayerUpdate(gba);
905	}
906
907	struct GBAThread* thread = GBAThreadGetContext();
908	if (!thread) {
909		return;
910	}
911
912	if (thread->frameCallback) {
913		thread->frameCallback(thread);
914	}
915}
916
917void GBASetBreakpoint(struct GBA* gba, struct ARMComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
918	size_t immediate;
919	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
920		if (gba->cpu->components[immediate] == component) {
921			break;
922		}
923	}
924	if (immediate == gba->cpu->numComponents) {
925		return;
926	}
927	if (mode == MODE_ARM) {
928		int32_t value;
929		int32_t old;
930		value = 0xE1200070;
931		value |= immediate & 0xF;
932		value |= (immediate & 0xFFF0) << 4;
933		GBAPatch32(gba->cpu, address, value, &old);
934		*opcode = old;
935	} else {
936		int16_t value;
937		int16_t old;
938		value = 0xBE00;
939		value |= immediate & 0xFF;
940		GBAPatch16(gba->cpu, address, value, &old);
941		*opcode = (uint16_t) old;
942	}
943}
944
945void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
946	if (mode == MODE_ARM) {
947		GBAPatch32(gba->cpu, address, opcode, 0);
948	} else {
949		GBAPatch16(gba->cpu, address, opcode, 0);
950	}
951}
952
953#if (!defined(USE_PTHREADS) && !defined(_WIN32)) || defined(DISABLE_THREADING)
954struct GBAThread* GBAThreadGetContext(void) {
955	return 0;
956}
957#endif
958
959static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
960	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d, address, mode, opcode);
961	return true;
962}
963
964static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
965	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
966	return true;
967}