all repos — mgba @ 78002b4df7cf200fa612a4c3b0d0cc8c8b7165fc

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