all repos — mgba @ eced06bc2abf974dafb5001526092369f6f44511

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