all repos — mgba @ bb71c4486d6d5157121a0f9b9627977c5c7c30ba

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