all repos — mgba @ c937529d4ab5bb328923cc7654de5518ce8c111e

mGBA Game Boy Advance Emulator

src/gba/gba.c (view raw)

  1/* Copyright (c) 2013-2014 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 "gba-bios.h"
  9#include "gba-io.h"
 10#include "gba-rr.h"
 11#include "gba-sio.h"
 12#include "gba-thread.h"
 13
 14#include "isa-inlines.h"
 15
 16#include "util/crc32.h"
 17#include "util/memory.h"
 18#include "util/patch.h"
 19#include "util/vfs.h"
 20
 21const uint32_t GBA_ARM7TDMI_FREQUENCY = 0x1000000;
 22const uint32_t GBA_COMPONENT_MAGIC = 0x1000000;
 23
 24static const size_t GBA_ROM_MAGIC_OFFSET = 2;
 25static const uint8_t GBA_ROM_MAGIC[] = { 0x00, 0xEA };
 26
 27struct GBACartridgeOverride {
 28	const char id[4];
 29	enum SavedataType type;
 30	int gpio;
 31	uint32_t busyLoop;
 32};
 33
 34static const struct GBACartridgeOverride _overrides[] = {
 35	// Boktai: The Sun is in Your Hand
 36	{ "U3IE", SAVEDATA_EEPROM, GPIO_RTC | GPIO_LIGHT_SENSOR, -1 },
 37	{ "U3IP", SAVEDATA_EEPROM, GPIO_RTC | GPIO_LIGHT_SENSOR, -1 },
 38
 39	// Boktai 2: Solar Boy Django
 40	{ "U32E", SAVEDATA_EEPROM, GPIO_RTC | GPIO_LIGHT_SENSOR, -1 },
 41	{ "U32P", SAVEDATA_EEPROM, GPIO_RTC | GPIO_LIGHT_SENSOR, -1 },
 42
 43	// Drill Dozer
 44	{ "V49J", SAVEDATA_SRAM, GPIO_RUMBLE, -1 },
 45	{ "V49E", SAVEDATA_SRAM, GPIO_RUMBLE, -1 },
 46
 47	// Final Fantasy Tactics Advance
 48	{ "AFXE", SAVEDATA_FLASH512, GPIO_NONE, 0x8000418 },
 49
 50	// Golden Sun: The Lost Age
 51	{ "AGFE", SAVEDATA_FLASH512, GPIO_NONE, 0x801353A },
 52
 53	// Koro Koro Puzzle - Happy Panechu!
 54	{ "KHPJ", SAVEDATA_EEPROM, GPIO_TILT, -1 },
 55
 56	// Mega Man Battle Network
 57	{ "AREE", SAVEDATA_SRAM, GPIO_NONE, 0x800032E },
 58
 59	// Metal Slug Advance
 60	{ "BSME", SAVEDATA_EEPROM, GPIO_NONE, 0x8000290 },
 61
 62	// Pokemon Ruby
 63	{ "AXVJ", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 64	{ "AXVE", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 65	{ "AXVP", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 66	{ "AXVI", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 67	{ "AXVS", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 68	{ "AXVD", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 69	{ "AXVF", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 70
 71	// Pokemon Sapphire
 72	{ "AXPJ", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 73	{ "AXPE", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 74	{ "AXPP", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 75	{ "AXPI", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 76	{ "AXPS", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 77	{ "AXPD", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 78	{ "AXPF", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 79
 80	// Pokemon Emerald
 81	{ "BPEJ", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 82	{ "BPEE", SAVEDATA_FLASH1M, GPIO_RTC, 0x80008C6 },
 83	{ "BPEP", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 84	{ "BPEI", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 85	{ "BPES", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 86	{ "BPED", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 87	{ "BPEF", SAVEDATA_FLASH1M, GPIO_RTC, -1 },
 88
 89	// Pokemon Mystery Dungeon
 90	{ "B24J", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 91	{ "B24E", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 92	{ "B24P", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 93	{ "B24U", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 94
 95	// Pokemon FireRed
 96	{ "BPRJ", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 97	{ "BPRE", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 98	{ "BPRP", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
 99
100	// Pokemon LeafGreen
101	{ "BPGJ", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
102	{ "BPGE", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
103	{ "BPGP", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
104
105	// RockMan EXE 4.5 - Real Operation
106	{ "BR4J", SAVEDATA_FLASH512, GPIO_RTC, -1 },
107
108	// Super Mario Advance 2
109	{ "AA2E", SAVEDATA_EEPROM, GPIO_NONE, 0x800052E },
110
111	// Super Mario Advance 3
112	{ "A3AE", SAVEDATA_EEPROM, GPIO_NONE, 0x8002B9C },
113
114	// Super Mario Advance 4
115	{ "AX4J", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
116	{ "AX4E", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
117	{ "AX4P", SAVEDATA_FLASH1M, GPIO_NONE, -1 },
118
119	// Wario Ware Twisted
120	{ "RZWJ", SAVEDATA_SRAM, GPIO_RUMBLE | GPIO_GYRO, -1 },
121	{ "RZWE", SAVEDATA_SRAM, GPIO_RUMBLE | GPIO_GYRO, -1 },
122	{ "RZWP", SAVEDATA_SRAM, GPIO_RUMBLE | GPIO_GYRO, -1 },
123
124	// Yoshi's Universal Gravitation
125	{ "KYGJ", SAVEDATA_EEPROM, GPIO_TILT, -1 },
126	{ "KYGE", SAVEDATA_EEPROM, GPIO_TILT, -1 },
127	{ "KYGP", SAVEDATA_EEPROM, GPIO_TILT, -1 },
128
129	{ { 0, 0, 0, 0 }, 0, 0, -1 }
130};
131
132static void GBAInit(struct ARMCore* cpu, struct ARMComponent* component);
133static void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh);
134static void GBAProcessEvents(struct ARMCore* cpu);
135static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles);
136static void GBAHitStub(struct ARMCore* cpu, uint32_t opcode);
137static void GBAIllegal(struct ARMCore* cpu, uint32_t opcode);
138
139static void _checkOverrides(struct GBA* gba, uint32_t code);
140
141void GBACreate(struct GBA* gba) {
142	gba->d.id = GBA_COMPONENT_MAGIC;
143	gba->d.init = GBAInit;
144	gba->d.deinit = 0;
145}
146
147static void GBAInit(struct ARMCore* cpu, struct ARMComponent* component) {
148	struct GBA* gba = (struct GBA*) component;
149	gba->cpu = cpu;
150	gba->debugger = 0;
151
152	GBAInterruptHandlerInit(&cpu->irqh);
153	GBAMemoryInit(gba);
154	GBASavedataInit(&gba->memory.savedata, 0);
155
156	gba->video.p = gba;
157	GBAVideoInit(&gba->video);
158
159	gba->audio.p = gba;
160	GBAAudioInit(&gba->audio, GBA_AUDIO_SAMPLES);
161
162	GBAIOInit(gba);
163
164	gba->sio.p = gba;
165	GBASIOInit(&gba->sio);
166
167	gba->timersEnabled = 0;
168	memset(gba->timers, 0, sizeof(gba->timers));
169
170	gba->springIRQ = 0;
171	gba->keySource = 0;
172	gba->rotationSource = 0;
173	gba->luminanceSource = 0;
174	gba->rtcSource = 0;
175	gba->rumble = 0;
176	gba->rr = 0;
177
178	gba->romVf = 0;
179	gba->biosVf = 0;
180
181	gba->logLevel = GBA_LOG_INFO | GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL;
182
183	gba->biosChecksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
184
185	gba->busyLoop = -1;
186}
187
188void GBADestroy(struct GBA* gba) {
189	if (gba->pristineRom == gba->memory.rom) {
190		gba->memory.rom = 0;
191	}
192
193	if (gba->romVf) {
194		gba->romVf->unmap(gba->romVf, gba->pristineRom, gba->pristineRomSize);
195	}
196
197	if (gba->biosVf) {
198		gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
199	}
200
201	GBAMemoryDeinit(gba);
202	GBAVideoDeinit(&gba->video);
203	GBAAudioDeinit(&gba->audio);
204	GBARRContextDestroy(gba);
205}
206
207void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
208	irqh->reset = GBAReset;
209	irqh->processEvents = GBAProcessEvents;
210	irqh->swi16 = GBASwi16;
211	irqh->swi32 = GBASwi32;
212	irqh->hitIllegal = GBAIllegal;
213	irqh->readCPSR = GBATestIRQ;
214	irqh->hitStub = GBAHitStub;
215}
216
217void GBAReset(struct ARMCore* cpu) {
218	ARMSetPrivilegeMode(cpu, MODE_IRQ);
219	cpu->gprs[ARM_SP] = SP_BASE_IRQ;
220	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
221	cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
222	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
223	cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
224
225	struct GBA* gba = (struct GBA*) cpu->master;
226	if (!GBARRIsPlaying(gba->rr) && !GBARRIsRecording(gba->rr)) {
227		GBASavedataUnmask(&gba->memory.savedata);
228	}
229	GBAMemoryReset(gba);
230	GBAVideoReset(&gba->video);
231	GBAAudioReset(&gba->audio);
232	GBAIOInit(gba);
233
234	GBASIODeinit(&gba->sio);
235	GBASIOInit(&gba->sio);
236
237	gba->timersEnabled = 0;
238	memset(gba->timers, 0, sizeof(gba->timers));
239}
240
241void GBASkipBIOS(struct ARMCore* cpu) {
242	if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
243		cpu->gprs[ARM_PC] = BASE_CART0;
244		int currentCycles = 0;
245		ARM_WRITE_PC;
246	}
247}
248
249static void GBAProcessEvents(struct ARMCore* cpu) {
250	do {
251		struct GBA* gba = (struct GBA*) cpu->master;
252		int32_t cycles = cpu->cycles;
253		int32_t nextEvent = INT_MAX;
254		int32_t testEvent;
255
256		gba->bus = cpu->prefetch[1];
257		if (cpu->executionMode == MODE_THUMB) {
258			gba->bus |= cpu->prefetch[1] << 16;
259		}
260
261		if (gba->springIRQ) {
262			ARMRaiseIRQ(cpu);
263			gba->springIRQ = 0;
264		}
265
266		testEvent = GBAVideoProcessEvents(&gba->video, cycles);
267		if (testEvent < nextEvent) {
268			nextEvent = testEvent;
269		}
270
271		testEvent = GBAAudioProcessEvents(&gba->audio, cycles);
272		if (testEvent < nextEvent) {
273			nextEvent = testEvent;
274		}
275
276		testEvent = GBATimersProcessEvents(gba, cycles);
277		if (testEvent < nextEvent) {
278			nextEvent = testEvent;
279		}
280
281		testEvent = GBAMemoryRunDMAs(gba, cycles);
282		if (testEvent < nextEvent) {
283			nextEvent = testEvent;
284		}
285
286		testEvent = GBASIOProcessEvents(&gba->sio, cycles);
287		if (testEvent < nextEvent) {
288			nextEvent = testEvent;
289		}
290
291		cpu->cycles -= cycles;
292		cpu->nextEvent = nextEvent;
293
294		if (cpu->halted) {
295			cpu->cycles = cpu->nextEvent;
296		}
297	} while (cpu->cycles >= cpu->nextEvent);
298}
299
300static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles) {
301	int32_t nextEvent = INT_MAX;
302	if (gba->timersEnabled) {
303		struct GBATimer* timer;
304		struct GBATimer* nextTimer;
305
306		timer = &gba->timers[0];
307		if (timer->enable) {
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_TM0CNT_LO >> 1] = timer->reload;
314				timer->oldReload = timer->reload;
315
316				if (timer->doIrq) {
317					GBARaiseIRQ(gba, IRQ_TIMER0);
318				}
319
320				if (gba->audio.enable) {
321					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 0) {
322						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
323					}
324
325					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 0) {
326						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
327					}
328				}
329
330				nextTimer = &gba->timers[1];
331				if (nextTimer->countUp) {
332					++gba->memory.io[REG_TM1CNT_LO >> 1];
333					if (!gba->memory.io[REG_TM1CNT_LO >> 1]) {
334						nextTimer->nextEvent = 0;
335					}
336				}
337			}
338			nextEvent = timer->nextEvent;
339		}
340
341		timer = &gba->timers[1];
342		if (timer->enable) {
343			timer->nextEvent -= cycles;
344			timer->lastEvent -= cycles;
345			if (timer->nextEvent <= 0) {
346				timer->lastEvent = timer->nextEvent;
347				timer->nextEvent += timer->overflowInterval;
348				gba->memory.io[REG_TM1CNT_LO >> 1] = timer->reload;
349				timer->oldReload = timer->reload;
350
351				if (timer->doIrq) {
352					GBARaiseIRQ(gba, IRQ_TIMER1);
353				}
354
355				if (gba->audio.enable) {
356					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 1) {
357						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
358					}
359
360					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 1) {
361						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
362					}
363				}
364
365				if (timer->countUp) {
366					timer->nextEvent = INT_MAX;
367				}
368
369				nextTimer = &gba->timers[2];
370				if (nextTimer->countUp) {
371					++gba->memory.io[REG_TM2CNT_LO >> 1];
372					if (!gba->memory.io[REG_TM2CNT_LO >> 1]) {
373						nextTimer->nextEvent = 0;
374					}
375				}
376			}
377			if (timer->nextEvent < nextEvent) {
378				nextEvent = timer->nextEvent;
379			}
380		}
381
382		timer = &gba->timers[2];
383		if (timer->enable) {
384			timer->nextEvent -= cycles;
385			timer->lastEvent -= cycles;
386			nextEvent = timer->nextEvent;
387			if (timer->nextEvent <= 0) {
388				timer->lastEvent = timer->nextEvent;
389				timer->nextEvent += timer->overflowInterval;
390				gba->memory.io[REG_TM2CNT_LO >> 1] = timer->reload;
391				timer->oldReload = timer->reload;
392
393				if (timer->doIrq) {
394					GBARaiseIRQ(gba, IRQ_TIMER2);
395				}
396
397				if (timer->countUp) {
398					timer->nextEvent = INT_MAX;
399				}
400
401				nextTimer = &gba->timers[3];
402				if (nextTimer->countUp) {
403					++gba->memory.io[REG_TM3CNT_LO >> 1];
404					if (!gba->memory.io[REG_TM3CNT_LO >> 1]) {
405						nextTimer->nextEvent = 0;
406					}
407				}
408			}
409			if (timer->nextEvent < nextEvent) {
410				nextEvent = timer->nextEvent;
411			}
412		}
413
414		timer = &gba->timers[3];
415		if (timer->enable) {
416			timer->nextEvent -= cycles;
417			timer->lastEvent -= cycles;
418			nextEvent = timer->nextEvent;
419			if (timer->nextEvent <= 0) {
420				timer->lastEvent = timer->nextEvent;
421				timer->nextEvent += timer->overflowInterval;
422				gba->memory.io[REG_TM3CNT_LO >> 1] = timer->reload;
423				timer->oldReload = timer->reload;
424
425				if (timer->doIrq) {
426					GBARaiseIRQ(gba, IRQ_TIMER3);
427				}
428
429				if (timer->countUp) {
430					timer->nextEvent = INT_MAX;
431				}
432			}
433			if (timer->nextEvent < nextEvent) {
434				nextEvent = timer->nextEvent;
435			}
436		}
437	}
438	return nextEvent;
439}
440
441void GBAAttachDebugger(struct GBA* gba, struct ARMDebugger* debugger) {
442	gba->debugger = debugger;
443	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = &debugger->d;
444	ARMHotplugAttach(gba->cpu, GBA_COMPONENT_DEBUGGER);
445}
446
447void GBADetachDebugger(struct GBA* gba) {
448	gba->debugger = 0;
449	ARMHotplugDetach(gba->cpu, GBA_COMPONENT_DEBUGGER);
450	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = 0;
451}
452
453void GBALoadROM(struct GBA* gba, struct VFile* vf, struct VFile* sav, const char* fname) {
454	gba->romVf = vf;
455	gba->pristineRomSize = vf->seek(vf, 0, SEEK_END);
456	vf->seek(vf, 0, SEEK_SET);
457	if (gba->pristineRomSize > SIZE_CART0) {
458		gba->pristineRomSize = SIZE_CART0;
459	}
460	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
461	if (!gba->pristineRom) {
462		GBALog(gba, GBA_LOG_WARN, "Couldn't map ROM");
463		return;
464	}
465	gba->memory.rom = gba->pristineRom;
466	gba->activeFile = fname;
467	gba->memory.romSize = gba->pristineRomSize;
468	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
469	GBASavedataInit(&gba->memory.savedata, sav);
470	GBAGPIOInit(&gba->memory.gpio, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
471	_checkOverrides(gba, ((struct GBACartridge*) gba->memory.rom)->id);
472	// TODO: error check
473}
474
475void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
476	gba->biosVf = vf;
477	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
478	if (!bios) {
479		GBALog(gba, GBA_LOG_WARN, "Couldn't map BIOS");
480		return;
481	}
482	gba->memory.bios = bios;
483	gba->memory.fullBios = 1;
484	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
485	GBALog(gba, GBA_LOG_DEBUG, "BIOS Checksum: 0x%X", checksum);
486	if (checksum == GBA_BIOS_CHECKSUM) {
487		GBALog(gba, GBA_LOG_INFO, "Official GBA BIOS detected");
488	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
489		GBALog(gba, GBA_LOG_INFO, "Official GBA (DS) BIOS detected");
490	} else {
491		GBALog(gba, GBA_LOG_WARN, "BIOS checksum incorrect");
492	}
493	gba->biosChecksum = checksum;
494	if (gba->memory.activeRegion == REGION_BIOS) {
495		gba->cpu->memory.activeRegion = gba->memory.bios;
496	}
497	// TODO: error check
498}
499
500void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
501	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
502	if (!patchedSize) {
503		return;
504	}
505	gba->memory.rom = anonymousMemoryMap(patchedSize);
506	memcpy(gba->memory.rom, gba->pristineRom, gba->memory.romSize > patchedSize ? patchedSize : gba->memory.romSize);
507	if (!patch->applyPatch(patch, gba->memory.rom, patchedSize)) {
508		mappedMemoryFree(gba->memory.rom, patchedSize);
509		gba->memory.rom = gba->pristineRom;
510		return;
511	}
512	gba->memory.romSize = patchedSize;
513	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
514}
515
516void GBATimerUpdateRegister(struct GBA* gba, int timer) {
517	struct GBATimer* currentTimer = &gba->timers[timer];
518	if (currentTimer->enable && !currentTimer->countUp) {
519		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> currentTimer->prescaleBits);
520	}
521}
522
523void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
524	gba->timers[timer].reload = reload;
525}
526
527void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
528	struct GBATimer* currentTimer = &gba->timers[timer];
529	GBATimerUpdateRegister(gba, timer);
530
531	int oldPrescale = currentTimer->prescaleBits;
532	switch (control & 0x0003) {
533	case 0x0000:
534		currentTimer->prescaleBits = 0;
535		break;
536	case 0x0001:
537		currentTimer->prescaleBits = 6;
538		break;
539	case 0x0002:
540		currentTimer->prescaleBits = 8;
541		break;
542	case 0x0003:
543		currentTimer->prescaleBits = 10;
544		break;
545	}
546	currentTimer->countUp = !!(control & 0x0004);
547	currentTimer->doIrq = !!(control & 0x0040);
548	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << currentTimer->prescaleBits;
549	int wasEnabled = currentTimer->enable;
550	currentTimer->enable = !!(control & 0x0080);
551	if (!wasEnabled && currentTimer->enable) {
552		if (!currentTimer->countUp) {
553			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
554		} else {
555			currentTimer->nextEvent = INT_MAX;
556		}
557		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
558		currentTimer->oldReload = currentTimer->reload;
559		currentTimer->lastEvent = 0;
560		gba->timersEnabled |= 1 << timer;
561	} else if (wasEnabled && !currentTimer->enable) {
562		if (!currentTimer->countUp) {
563			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
564		}
565		gba->timersEnabled &= ~(1 << timer);
566	} else if (currentTimer->prescaleBits != oldPrescale && !currentTimer->countUp) {
567		// FIXME: this might be before present
568		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
569	}
570
571	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
572		gba->cpu->nextEvent = currentTimer->nextEvent;
573	}
574};
575
576void GBAWriteIE(struct GBA* gba, uint16_t value) {
577	if (value & (1 << IRQ_KEYPAD)) {
578		GBALog(gba, GBA_LOG_STUB, "Keypad interrupts not implemented");
579	}
580
581	if (value & (1 << IRQ_GAMEPAK)) {
582		GBALog(gba, GBA_LOG_STUB, "Gamepak interrupts not implemented");
583	}
584
585	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
586		ARMRaiseIRQ(gba->cpu);
587	}
588}
589
590void GBAWriteIME(struct GBA* gba, uint16_t value) {
591	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
592		ARMRaiseIRQ(gba->cpu);
593	}
594}
595
596void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
597	gba->memory.io[REG_IF >> 1] |= 1 << irq;
598	gba->cpu->halted = 0;
599
600	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
601		ARMRaiseIRQ(gba->cpu);
602	}
603}
604
605void GBATestIRQ(struct ARMCore* cpu) {
606	struct GBA* gba = (struct GBA*) cpu->master;
607	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
608		gba->springIRQ = 1;
609		gba->cpu->nextEvent = 0;
610	}
611}
612
613void GBAHalt(struct GBA* gba) {
614	gba->cpu->nextEvent = 0;
615	gba->cpu->halted = 1;
616}
617
618static void _GBAVLog(struct GBA* gba, enum GBALogLevel level, const char* format, va_list args) {
619	struct GBAThread* threadContext = GBAThreadGetContext();
620	enum GBALogLevel logLevel = -1;
621
622	if (gba) {
623		logLevel = gba->logLevel;
624	}
625
626	if (threadContext) {
627		logLevel = threadContext->logLevel;
628		gba = threadContext->gba;
629	}
630
631	if (!(level & logLevel) && level != GBA_LOG_FATAL) {
632		return;
633	}
634
635	if (level == GBA_LOG_FATAL && gba) {
636		gba->cpu->nextEvent = 0;
637	}
638
639	if (threadContext) {
640		if (level == GBA_LOG_FATAL) {
641			MutexLock(&threadContext->stateMutex);
642			threadContext->state = THREAD_CRASHED;
643			MutexUnlock(&threadContext->stateMutex);
644		}
645		if (threadContext->logHandler) {
646			threadContext->logHandler(threadContext, level, format, args);
647			return;
648		}
649	}
650
651	vprintf(format, args);
652	printf("\n");
653
654	if (level == GBA_LOG_FATAL && !threadContext) {
655		abort();
656	}
657}
658
659void GBALog(struct GBA* gba, enum GBALogLevel level, const char* format, ...) {
660	va_list args;
661	va_start(args, format);
662	_GBAVLog(gba, level, format, args);
663	va_end(args);
664}
665
666void GBADebuggerLogShim(struct ARMDebugger* debugger, enum DebuggerLogLevel level, const char* format, ...) {
667	struct GBA* gba = 0;
668	if (debugger->cpu) {
669		gba = (struct GBA*) debugger->cpu->master;
670	}
671
672	enum GBALogLevel gbaLevel;
673	switch (level) {
674	default: // Avoids compiler warning
675	case DEBUGGER_LOG_DEBUG:
676		gbaLevel = GBA_LOG_DEBUG;
677		break;
678	case DEBUGGER_LOG_INFO:
679		gbaLevel = GBA_LOG_INFO;
680		break;
681	case DEBUGGER_LOG_WARN:
682		gbaLevel = GBA_LOG_WARN;
683		break;
684	case DEBUGGER_LOG_ERROR:
685		gbaLevel = GBA_LOG_ERROR;
686		break;
687	}
688	va_list args;
689	va_start(args, format);
690	_GBAVLog(gba, gbaLevel, format, args);
691	va_end(args);
692}
693
694bool GBAIsROM(struct VFile* vf) {
695	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
696		return false;
697	}
698	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
699	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
700		return false;
701	}
702	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
703}
704
705bool GBAIsBIOS(struct VFile* vf) {
706	if (vf->seek(vf, 0, SEEK_SET) < 0) {
707		return false;
708	}
709	uint32_t interruptTable[7];
710	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
711		return false;
712	}
713	int i;
714	for (i = 0; i < 7; ++i) {
715		if ((interruptTable[i] & 0xFFFF0000) != 0xEA000000) {
716			return false;
717		}
718	}
719	return true;
720}
721
722void GBAGetGameCode(struct GBA* gba, char* out) {
723	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
724}
725
726void GBAGetGameTitle(struct GBA* gba, char* out) {
727	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
728}
729
730void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
731	struct GBA* gba = (struct GBA*) cpu->master;
732	enum GBALogLevel level = GBA_LOG_FATAL;
733	if (gba->debugger) {
734		level = GBA_LOG_STUB;
735		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP);
736	}
737	GBALog(gba, level, "Stub opcode: %08x", opcode);
738}
739
740void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
741	struct GBA* gba = (struct GBA*) cpu->master;
742	GBALog(gba, GBA_LOG_WARN, "Illegal opcode: %08x", opcode);
743	if (gba->debugger) {
744		ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP);
745	}
746}
747
748void _checkOverrides(struct GBA* gba, uint32_t id) {
749	int i;
750	gba->busyLoop = -1;
751	if ((id & 0xFF) == 'F') {
752		GBALog(gba, GBA_LOG_DEBUG, "Found Classic NES Series game, using EEPROM saves");
753		GBASavedataInitEEPROM(&gba->memory.savedata);
754		return;
755	}
756	for (i = 0; _overrides[i].id[0]; ++i) {
757		const uint32_t* overrideId = (const uint32_t*) _overrides[i].id;
758		if (*overrideId == id) {
759			GBALog(gba, GBA_LOG_DEBUG, "Found override for game %s!", _overrides[i].id);
760			GBASavedataForceType(&gba->memory.savedata, _overrides[i].type);
761
762			if (_overrides[i].gpio & GPIO_RTC) {
763				GBAGPIOInitRTC(&gba->memory.gpio);
764			}
765
766			if (_overrides[i].gpio & GPIO_GYRO) {
767				GBAGPIOInitGyro(&gba->memory.gpio);
768			}
769
770			if (_overrides[i].gpio & GPIO_RUMBLE) {
771				GBAGPIOInitRumble(&gba->memory.gpio);
772			}
773
774			if (_overrides[i].gpio & GPIO_LIGHT_SENSOR) {
775				GBAGPIOInitLightSensor(&gba->memory.gpio);
776			}
777
778			if (_overrides[i].gpio & GPIO_TILT) {
779				GBAGPIOInitTilt(&gba->memory.gpio);
780			}
781
782			gba->busyLoop = _overrides[i].busyLoop;
783			return;
784		}
785	}
786}