all repos — mgba @ 647872a8d90feb79deebfc13ccd0c868e99c7e2a

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