all repos — mgba @ 0a6e2b49ab3cc40b7ba4752d47e04ed9a13b7192

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