all repos — mgba @ da7ad5e0221861e30168c70b7e8fefc39619c6dc

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