all repos — mgba @ f22391275b49bcec3d94fb5e63c9983aef3ee0c3

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