all repos — mgba @ a8beb9f5f38f44e937ff752aee55d9928bf297c4

mGBA Game Boy Advance Emulator

src/gba/gba.c (view raw)

  1/* Copyright (c) 2013-2015 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 "core/thread.h"
  9
 10#include "arm/decoder.h"
 11#include "arm/isa-inlines.h"
 12
 13#include "gba/bios.h"
 14#include "gba/cheats.h"
 15#include "gba/context/overrides.h"
 16#include "gba/io.h"
 17#include "gba/rr/rr.h"
 18#include "gba/serialize.h"
 19#include "gba/sio.h"
 20
 21#include "util/crc32.h"
 22#include "util/memory.h"
 23#include "util/math.h"
 24#include "util/patch.h"
 25#include "util/vfs.h"
 26
 27mLOG_DEFINE_CATEGORY(GBA, "GBA");
 28
 29const uint32_t GBA_ARM7TDMI_FREQUENCY = 0x1000000;
 30const uint32_t GBA_COMPONENT_MAGIC = 0x1000000;
 31
 32static const size_t GBA_ROM_MAGIC_OFFSET = 3;
 33static const uint8_t GBA_ROM_MAGIC[] = { 0xEA };
 34
 35static const size_t GBA_MB_MAGIC_OFFSET = 0xC0;
 36
 37static void GBAInit(void* cpu, struct mCPUComponent* component);
 38static void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh);
 39static void GBAProcessEvents(struct ARMCore* cpu);
 40static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles);
 41static void GBAHitStub(struct ARMCore* cpu, uint32_t opcode);
 42static void GBAIllegal(struct ARMCore* cpu, uint32_t opcode);
 43static void GBABreakpoint(struct ARMCore* cpu, int immediate);
 44
 45static bool _setSoftwareBreakpoint(struct Debugger*, uint32_t address, enum ExecutionMode mode, uint32_t* opcode);
 46static bool _clearSoftwareBreakpoint(struct Debugger*, uint32_t address, enum ExecutionMode mode, uint32_t opcode);
 47
 48
 49#ifdef _3DS
 50extern uint32_t* romBuffer;
 51extern size_t romBufferSize;
 52#endif
 53
 54void GBACreate(struct GBA* gba) {
 55	gba->d.id = GBA_COMPONENT_MAGIC;
 56	gba->d.init = GBAInit;
 57	gba->d.deinit = 0;
 58}
 59
 60static void GBAInit(void* cpu, struct mCPUComponent* component) {
 61	struct GBA* gba = (struct GBA*) component;
 62	gba->cpu = cpu;
 63	gba->debugger = 0;
 64	gba->sync = 0;
 65
 66	GBAInterruptHandlerInit(&gba->cpu->irqh);
 67	GBAMemoryInit(gba);
 68	GBASavedataInit(&gba->memory.savedata, 0);
 69
 70	gba->video.p = gba;
 71	GBAVideoInit(&gba->video);
 72
 73	gba->audio.p = gba;
 74	GBAAudioInit(&gba->audio, GBA_AUDIO_SAMPLES);
 75
 76	GBAIOInit(gba);
 77
 78	gba->sio.p = gba;
 79	GBASIOInit(&gba->sio);
 80
 81	gba->timersEnabled = 0;
 82	memset(gba->timers, 0, sizeof(gba->timers));
 83
 84	gba->springIRQ = 0;
 85	gba->keySource = 0;
 86	gba->rotationSource = 0;
 87	gba->luminanceSource = 0;
 88	gba->rtcSource = 0;
 89	gba->rumble = 0;
 90	gba->rr = 0;
 91
 92	gba->romVf = 0;
 93	gba->biosVf = 0;
 94
 95	gba->stream = 0;
 96	gba->keyCallback = 0;
 97	gba->stopCallback = 0;
 98
 99	gba->biosChecksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
100
101	gba->idleOptimization = IDLE_LOOP_REMOVE;
102	gba->idleLoop = IDLE_LOOP_NONE;
103
104	gba->realisticTiming = true;
105	gba->hardCrash = true;
106	gba->allowOpposingDirections = true;
107
108	gba->performingDMA = false;
109
110	gba->pristineRom = 0;
111	gba->pristineRomSize = 0;
112	gba->yankedRomSize = 0;
113}
114
115void GBAUnloadROM(struct GBA* gba) {
116	if (gba->memory.rom && gba->pristineRom != gba->memory.rom) {
117		if (gba->yankedRomSize) {
118			gba->yankedRomSize = 0;
119		}
120		mappedMemoryFree(gba->memory.rom, SIZE_CART0);
121	}
122	gba->memory.rom = 0;
123
124	if (gba->romVf) {
125#ifndef _3DS
126		gba->romVf->unmap(gba->romVf, gba->pristineRom, gba->pristineRomSize);
127#endif
128		gba->pristineRom = 0;
129		gba->romVf = 0;
130	}
131
132	GBASavedataDeinit(&gba->memory.savedata);
133	gba->idleLoop = IDLE_LOOP_NONE;
134}
135
136void GBADestroy(struct GBA* gba) {
137	GBAUnloadROM(gba);
138
139	if (gba->biosVf) {
140		gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
141	}
142
143	GBAMemoryDeinit(gba);
144	GBAVideoDeinit(&gba->video);
145	GBAAudioDeinit(&gba->audio);
146	GBASIODeinit(&gba->sio);
147	gba->rr = 0;
148}
149
150void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
151	irqh->reset = GBAReset;
152	irqh->processEvents = GBAProcessEvents;
153	irqh->swi16 = GBASwi16;
154	irqh->swi32 = GBASwi32;
155	irqh->hitIllegal = GBAIllegal;
156	irqh->readCPSR = GBATestIRQ;
157	irqh->hitStub = GBAHitStub;
158	irqh->bkpt16 = GBABreakpoint;
159	irqh->bkpt32 = GBABreakpoint;
160}
161
162void GBAReset(struct ARMCore* cpu) {
163	ARMSetPrivilegeMode(cpu, MODE_IRQ);
164	cpu->gprs[ARM_SP] = SP_BASE_IRQ;
165	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
166	cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
167	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
168	cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
169
170	struct GBA* gba = (struct GBA*) cpu->master;
171	if (!gba->rr || (!gba->rr->isPlaying(gba->rr) && !gba->rr->isRecording(gba->rr))) {
172		GBASavedataUnmask(&gba->memory.savedata);
173	}
174
175	if (gba->yankedRomSize) {
176		gba->memory.romSize = gba->yankedRomSize;
177		gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
178		gba->yankedRomSize = 0;
179	}
180	GBAMemoryReset(gba);
181	GBAVideoReset(&gba->video);
182	GBAAudioReset(&gba->audio);
183	GBAIOInit(gba);
184
185	GBASIOReset(&gba->sio);
186
187	gba->timersEnabled = 0;
188	memset(gba->timers, 0, sizeof(gba->timers));
189
190	gba->lastJump = 0;
191	gba->haltPending = false;
192	gba->idleDetectionStep = 0;
193	gba->idleDetectionFailures = 0;
194}
195
196void GBASkipBIOS(struct GBA* gba) {
197	struct ARMCore* cpu = gba->cpu;
198	if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
199		if (gba->memory.rom) {
200			cpu->gprs[ARM_PC] = BASE_CART0;
201		} else {
202			cpu->gprs[ARM_PC] = BASE_WORKING_RAM;
203		}
204		int currentCycles = 0;
205		ARM_WRITE_PC;
206	}
207}
208
209static void GBAProcessEvents(struct ARMCore* cpu) {
210	struct GBA* gba = (struct GBA*) cpu->master;
211
212	gba->bus = cpu->prefetch[1];
213	if (cpu->executionMode == MODE_THUMB) {
214		gba->bus |= cpu->prefetch[1] << 16;
215	}
216
217	if (gba->springIRQ) {
218		ARMRaiseIRQ(cpu);
219		gba->springIRQ = 0;
220	}
221
222	do {
223		int32_t cycles = cpu->nextEvent;
224		int32_t nextEvent = INT_MAX;
225		int32_t testEvent;
226#ifndef NDEBUG
227		if (cycles < 0) {
228			mLOG(GBA, FATAL, "Negative cycles passed: %i", cycles);
229		}
230#endif
231
232		testEvent = GBAVideoProcessEvents(&gba->video, cycles);
233		if (testEvent < nextEvent) {
234			nextEvent = testEvent;
235		}
236
237		testEvent = GBAAudioProcessEvents(&gba->audio, cycles);
238		if (testEvent < nextEvent) {
239			nextEvent = testEvent;
240		}
241
242		testEvent = GBATimersProcessEvents(gba, cycles);
243		if (testEvent < nextEvent) {
244			nextEvent = testEvent;
245		}
246
247		testEvent = GBAMemoryRunDMAs(gba, cycles);
248		if (testEvent < nextEvent) {
249			nextEvent = testEvent;
250		}
251
252		testEvent = GBASIOProcessEvents(&gba->sio, cycles);
253		if (testEvent < nextEvent) {
254			nextEvent = testEvent;
255		}
256
257		cpu->cycles -= cycles;
258		cpu->nextEvent = nextEvent;
259
260		if (cpu->halted) {
261			cpu->cycles = cpu->nextEvent;
262		}
263	} while (cpu->cycles >= cpu->nextEvent);
264}
265
266static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles) {
267	int32_t nextEvent = INT_MAX;
268	if (gba->timersEnabled) {
269		struct GBATimer* timer;
270		struct GBATimer* nextTimer;
271
272		timer = &gba->timers[0];
273		if (GBATimerFlagsIsEnable(timer->flags)) {
274			timer->nextEvent -= cycles;
275			timer->lastEvent -= cycles;
276			while (timer->nextEvent <= 0) {
277				timer->lastEvent = timer->nextEvent;
278				timer->nextEvent += timer->overflowInterval;
279				gba->memory.io[REG_TM0CNT_LO >> 1] = timer->reload;
280				timer->oldReload = timer->reload;
281
282				if (GBATimerFlagsIsDoIrq(timer->flags)) {
283					GBARaiseIRQ(gba, IRQ_TIMER0);
284				}
285
286				if (gba->audio.enable) {
287					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 0) {
288						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
289					}
290
291					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 0) {
292						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
293					}
294				}
295
296				nextTimer = &gba->timers[1];
297				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
298					++gba->memory.io[REG_TM1CNT_LO >> 1];
299					if (!gba->memory.io[REG_TM1CNT_LO >> 1]) {
300						nextTimer->nextEvent = 0;
301					}
302				}
303			}
304			nextEvent = timer->nextEvent;
305		}
306
307		timer = &gba->timers[1];
308		if (GBATimerFlagsIsEnable(timer->flags)) {
309			timer->nextEvent -= cycles;
310			timer->lastEvent -= cycles;
311			if (timer->nextEvent <= 0) {
312				timer->lastEvent = timer->nextEvent;
313				timer->nextEvent += timer->overflowInterval;
314				gba->memory.io[REG_TM1CNT_LO >> 1] = timer->reload;
315				timer->oldReload = timer->reload;
316
317				if (GBATimerFlagsIsDoIrq(timer->flags)) {
318					GBARaiseIRQ(gba, IRQ_TIMER1);
319				}
320
321				if (gba->audio.enable) {
322					if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 1) {
323						GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
324					}
325
326					if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 1) {
327						GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
328					}
329				}
330
331				if (GBATimerFlagsIsCountUp(timer->flags)) {
332					timer->nextEvent = INT_MAX;
333				}
334
335				nextTimer = &gba->timers[2];
336				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
337					++gba->memory.io[REG_TM2CNT_LO >> 1];
338					if (!gba->memory.io[REG_TM2CNT_LO >> 1]) {
339						nextTimer->nextEvent = 0;
340					}
341				}
342			}
343			if (timer->nextEvent < nextEvent) {
344				nextEvent = timer->nextEvent;
345			}
346		}
347
348		timer = &gba->timers[2];
349		if (GBATimerFlagsIsEnable(timer->flags)) {
350			timer->nextEvent -= cycles;
351			timer->lastEvent -= cycles;
352			if (timer->nextEvent <= 0) {
353				timer->lastEvent = timer->nextEvent;
354				timer->nextEvent += timer->overflowInterval;
355				gba->memory.io[REG_TM2CNT_LO >> 1] = timer->reload;
356				timer->oldReload = timer->reload;
357
358				if (GBATimerFlagsIsDoIrq(timer->flags)) {
359					GBARaiseIRQ(gba, IRQ_TIMER2);
360				}
361
362				if (GBATimerFlagsIsCountUp(timer->flags)) {
363					timer->nextEvent = INT_MAX;
364				}
365
366				nextTimer = &gba->timers[3];
367				if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
368					++gba->memory.io[REG_TM3CNT_LO >> 1];
369					if (!gba->memory.io[REG_TM3CNT_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[3];
380		if (GBATimerFlagsIsEnable(timer->flags)) {
381			timer->nextEvent -= cycles;
382			timer->lastEvent -= cycles;
383			if (timer->nextEvent <= 0) {
384				timer->lastEvent = timer->nextEvent;
385				timer->nextEvent += timer->overflowInterval;
386				gba->memory.io[REG_TM3CNT_LO >> 1] = timer->reload;
387				timer->oldReload = timer->reload;
388
389				if (GBATimerFlagsIsDoIrq(timer->flags)) {
390					GBARaiseIRQ(gba, IRQ_TIMER3);
391				}
392
393				if (GBATimerFlagsIsCountUp(timer->flags)) {
394					timer->nextEvent = INT_MAX;
395				}
396			}
397			if (timer->nextEvent < nextEvent) {
398				nextEvent = timer->nextEvent;
399			}
400		}
401	}
402	return nextEvent;
403}
404
405void GBAAttachDebugger(struct GBA* gba, struct Debugger* debugger) {
406	debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
407	debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
408	gba->debugger = debugger;
409	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = &debugger->d;
410	ARMHotplugAttach(gba->cpu, GBA_COMPONENT_DEBUGGER);
411}
412
413void GBADetachDebugger(struct GBA* gba) {
414	gba->debugger = 0;
415	ARMHotplugDetach(gba->cpu, GBA_COMPONENT_DEBUGGER);
416	gba->cpu->components[GBA_COMPONENT_DEBUGGER] = 0;
417}
418
419bool GBALoadMB(struct GBA* gba, struct VFile* vf, const char* fname) {
420	GBAUnloadROM(gba);
421	gba->romVf = vf;
422	gba->pristineRomSize = vf->size(vf);
423	vf->seek(vf, 0, SEEK_SET);
424	if (gba->pristineRomSize > SIZE_WORKING_RAM) {
425		gba->pristineRomSize = SIZE_WORKING_RAM;
426	}
427#ifdef _3DS
428	gba->pristineRom = 0;
429	if (gba->pristineRomSize <= romBufferSize) {
430		gba->pristineRom = romBuffer;
431		vf->read(vf, romBuffer, gba->pristineRomSize);
432	}
433#else
434	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
435#endif
436	if (!gba->pristineRom) {
437		mLOG(GBA, WARN, "Couldn't map ROM");
438		return false;
439	}
440	gba->yankedRomSize = 0;
441	gba->memory.romSize = 0;
442	gba->memory.romMask = 0;
443	gba->romCrc32 = doCrc32(gba->pristineRom, gba->pristineRomSize);
444	return true;
445}
446
447bool GBALoadROM2(struct GBA* gba, struct VFile* vf) {
448	GBAUnloadROM(gba);
449	gba->romVf = vf;
450	gba->pristineRomSize = vf->size(vf);
451	vf->seek(vf, 0, SEEK_SET);
452	if (gba->pristineRomSize > SIZE_CART0) {
453		gba->pristineRomSize = SIZE_CART0;
454	}
455#ifdef _3DS
456	gba->pristineRom = 0;
457	if (gba->pristineRomSize <= romBufferSize) {
458		gba->pristineRom = romBuffer;
459		vf->read(vf, romBuffer, gba->pristineRomSize);
460	}
461#else
462	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
463#endif
464	if (!gba->pristineRom) {
465		mLOG(GBA, WARN, "Couldn't map ROM");
466		return false;
467	}
468	gba->yankedRomSize = 0;
469	gba->memory.rom = gba->pristineRom;
470	gba->memory.romSize = gba->pristineRomSize;
471	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
472	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
473	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
474	// TODO: error check
475	return true;
476}
477
478bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
479	GBASavedataInit(&gba->memory.savedata, sav);
480	return true;
481}
482
483void GBAYankROM(struct GBA* gba) {
484	gba->yankedRomSize = gba->memory.romSize;
485	gba->memory.romSize = 0;
486	gba->memory.romMask = 0;
487	GBARaiseIRQ(gba, IRQ_GAMEPAK);
488}
489
490void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
491	gba->biosVf = vf;
492	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
493	if (!bios) {
494		mLOG(GBA, WARN, "Couldn't map BIOS");
495		return;
496	}
497	gba->memory.bios = bios;
498	gba->memory.fullBios = 1;
499	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
500	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
501	if (checksum == GBA_BIOS_CHECKSUM) {
502		mLOG(GBA, INFO, "Official GBA BIOS detected");
503	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
504		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
505	} else {
506		mLOG(GBA, WARN, "BIOS checksum incorrect");
507	}
508	gba->biosChecksum = checksum;
509	if (gba->memory.activeRegion == REGION_BIOS) {
510		gba->cpu->memory.activeRegion = gba->memory.bios;
511	}
512	// TODO: error check
513}
514
515void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
516	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
517	if (!patchedSize || patchedSize > SIZE_CART0) {
518		return;
519	}
520	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
521	if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
522		mappedMemoryFree(gba->memory.rom, patchedSize);
523		gba->memory.rom = gba->pristineRom;
524		return;
525	}
526	gba->memory.romSize = patchedSize;
527	gba->memory.romMask = SIZE_CART0 - 1;
528	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
529}
530
531void GBATimerUpdateRegister(struct GBA* gba, int timer) {
532	struct GBATimer* currentTimer = &gba->timers[timer];
533	if (GBATimerFlagsIsEnable(currentTimer->flags) && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
534		int32_t prefetchSkew = 0;
535		if (gba->memory.lastPrefetchedPc - gba->memory.lastPrefetchedLoads * WORD_SIZE_THUMB >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
536			prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
537		}
538		// Reading this takes two cycles (1N+1I), so let's remove them preemptively
539		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> GBATimerFlagsGetPrescaleBits(currentTimer->flags));
540	}
541}
542
543void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
544	gba->timers[timer].reload = reload;
545	gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << GBATimerFlagsGetPrescaleBits(gba->timers[timer].flags);
546}
547
548void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
549	struct GBATimer* currentTimer = &gba->timers[timer];
550	GBATimerUpdateRegister(gba, timer);
551
552	unsigned oldPrescale = GBATimerFlagsGetPrescaleBits(currentTimer->flags);
553	switch (control & 0x0003) {
554	case 0x0000:
555		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 0);
556		break;
557	case 0x0001:
558		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 6);
559		break;
560	case 0x0002:
561		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 8);
562		break;
563	case 0x0003:
564		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 10);
565		break;
566	}
567	currentTimer->flags = GBATimerFlagsTestFillCountUp(currentTimer->flags, control & 0x0004);
568	currentTimer->flags = GBATimerFlagsTestFillDoIrq(currentTimer->flags, control & 0x0040);
569	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << GBATimerFlagsGetPrescaleBits(currentTimer->flags);
570	bool wasEnabled = GBATimerFlagsIsEnable(currentTimer->flags);
571	currentTimer->flags = GBATimerFlagsTestFillEnable(currentTimer->flags, control & 0x0080);
572	if (!wasEnabled && GBATimerFlagsIsEnable(currentTimer->flags)) {
573		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
574			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
575		} else {
576			currentTimer->nextEvent = INT_MAX;
577		}
578		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
579		currentTimer->oldReload = currentTimer->reload;
580		currentTimer->lastEvent = gba->cpu->cycles;
581		gba->timersEnabled |= 1 << timer;
582	} else if (wasEnabled && !GBATimerFlagsIsEnable(currentTimer->flags)) {
583		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
584			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
585		}
586		gba->timersEnabled &= ~(1 << timer);
587	} else if (GBATimerFlagsGetPrescaleBits(currentTimer->flags) != oldPrescale && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
588		// FIXME: this might be before present
589		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
590	}
591
592	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
593		gba->cpu->nextEvent = currentTimer->nextEvent;
594	}
595};
596
597void GBAWriteIE(struct GBA* gba, uint16_t value) {
598	if (value & (1 << IRQ_KEYPAD)) {
599		mLOG(GBA, STUB, "Keypad interrupts not implemented");
600	}
601
602	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
603		ARMRaiseIRQ(gba->cpu);
604	}
605}
606
607void GBAWriteIME(struct GBA* gba, uint16_t value) {
608	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
609		ARMRaiseIRQ(gba->cpu);
610	}
611}
612
613void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
614	gba->memory.io[REG_IF >> 1] |= 1 << irq;
615	gba->cpu->halted = 0;
616
617	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
618		ARMRaiseIRQ(gba->cpu);
619	}
620}
621
622void GBATestIRQ(struct ARMCore* cpu) {
623	struct GBA* gba = (struct GBA*) cpu->master;
624	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
625		gba->springIRQ = 1;
626		gba->cpu->nextEvent = gba->cpu->cycles;
627	}
628}
629
630void GBAHalt(struct GBA* gba) {
631	gba->cpu->nextEvent = gba->cpu->cycles;
632	gba->cpu->halted = 1;
633}
634
635void GBAStop(struct GBA* gba) {
636	if (!gba->stopCallback) {
637		return;
638	}
639	gba->cpu->nextEvent = gba->cpu->cycles;
640	gba->stopCallback->stop(gba->stopCallback);
641}
642
643bool GBAIsROM(struct VFile* vf) {
644	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
645		return false;
646	}
647	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
648	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
649		return false;
650	}
651	if (GBAIsBIOS(vf)) {
652		return false;
653	}
654	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
655}
656
657bool GBAIsMB(struct VFile* vf) {
658	if (!GBAIsROM(vf)) {
659		return false;
660	}
661	if (vf->size(vf) > SIZE_WORKING_RAM) {
662		return false;
663	}
664	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
665		return false;
666	}
667	uint32_t signature;
668	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
669		return false;
670	}
671	uint32_t opcode;
672	LOAD_32(opcode, 0, &signature);
673	struct ARMInstructionInfo info;
674	ARMDecodeARM(opcode, &info);
675	if (info.branchType != ARM_BRANCH) {
676		return false;
677	}
678	if (info.op1.immediate <= 0) {
679		return false;
680	} else if (info.op1.immediate == 28) {
681		// Ancient toolchain that is known to throw MB detection for a loop
682		return false;
683	} else if (info.op1.immediate != 24) {
684		return true;
685	}
686	// Found a libgba-linked cart...these are a bit harder to detect.
687	return false;
688}
689
690bool GBAIsBIOS(struct VFile* vf) {
691	if (vf->seek(vf, 0, SEEK_SET) < 0) {
692		return false;
693	}
694	uint8_t interruptTable[7 * 4];
695	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
696		return false;
697	}
698	int i;
699	for (i = 0; i < 7; ++i) {
700		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
701			return false;
702		}
703	}
704	return true;
705}
706
707void GBAGetGameCode(struct GBA* gba, char* out) {
708	if (!gba->memory.rom) {
709		out[0] = '\0';
710		return;
711	}
712	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
713}
714
715void GBAGetGameTitle(struct GBA* gba, char* out) {
716	if (gba->memory.rom) {
717		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
718		return;
719	}
720	if (gba->pristineRom) {
721		memcpy(out, &((struct GBACartridge*) gba->pristineRom)->title, 12);
722		return;
723	}
724	strncpy(out, "(BIOS)", 12);
725}
726
727void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
728	struct GBA* gba = (struct GBA*) cpu->master;
729	if (gba->debugger) {
730		struct DebuggerEntryInfo info = {
731			.address = _ARMPCAddress(cpu),
732			.opcode = opcode
733		};
734		DebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
735	}
736	// TODO: More sensible category?
737	mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
738}
739
740void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
741	struct GBA* gba = (struct GBA*) cpu->master;
742	if (!gba->yankedRomSize) {
743		// TODO: More sensible category?
744		mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
745	}
746	if (gba->debugger) {
747		struct DebuggerEntryInfo info = {
748			.address = _ARMPCAddress(cpu),
749			.opcode = opcode
750		};
751		DebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
752	} else {
753		ARMRaiseUndefined(cpu);
754	}
755}
756
757void GBABreakpoint(struct ARMCore* cpu, int immediate) {
758	struct GBA* gba = (struct GBA*) cpu->master;
759	if (immediate >= GBA_COMPONENT_MAX) {
760		return;
761	}
762	switch (immediate) {
763	case GBA_COMPONENT_DEBUGGER:
764		if (gba->debugger) {
765			struct DebuggerEntryInfo info = {
766				.address = _ARMPCAddress(cpu)
767			};
768			DebuggerEnter(gba->debugger, DEBUGGER_ENTER_BREAKPOINT, &info);
769		}
770		break;
771	case GBA_COMPONENT_CHEAT_DEVICE:
772		if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
773			struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
774			struct GBACheatHook* hook = 0;
775			size_t i;
776			for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
777				struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
778				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
779					GBACheatRefresh(device, cheats);
780					hook = cheats->hook;
781				}
782			}
783			if (hook) {
784				ARMRunFake(cpu, hook->patchedOpcode);
785			}
786		}
787		break;
788	default:
789		break;
790	}
791}
792
793void GBAFrameStarted(struct GBA* gba) {
794	UNUSED(gba);
795
796	// TODO: Put back rewind
797}
798
799void GBAFrameEnded(struct GBA* gba) {
800	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
801
802	if (gba->rr) {
803		gba->rr->nextFrame(gba->rr);
804	}
805
806	if (gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
807		struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
808		size_t i;
809		for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
810			struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
811			if (!cheats->hook) {
812				GBACheatRefresh(device, cheats);
813			}
814		}
815	}
816
817	if (gba->stream && gba->stream->postVideoFrame) {
818		const color_t* pixels;
819		unsigned stride;
820		gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
821		gba->stream->postVideoFrame(gba->stream, pixels, stride);
822	}
823
824	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
825		GBAHardwarePlayerUpdate(gba);
826	}
827
828	struct mCoreThread* thread = mCoreThreadGet();
829	if (!thread) {
830		return;
831	}
832
833	if (thread->frameCallback) {
834		thread->frameCallback(thread);
835	}
836
837	// TODO: Put back RR
838}
839
840void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
841	size_t immediate;
842	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
843		if (gba->cpu->components[immediate] == component) {
844			break;
845		}
846	}
847	if (immediate == gba->cpu->numComponents) {
848		return;
849	}
850	if (mode == MODE_ARM) {
851		int32_t value;
852		int32_t old;
853		value = 0xE1200070;
854		value |= immediate & 0xF;
855		value |= (immediate & 0xFFF0) << 4;
856		GBAPatch32(gba->cpu, address, value, &old);
857		*opcode = old;
858	} else {
859		int16_t value;
860		int16_t old;
861		value = 0xBE00;
862		value |= immediate & 0xFF;
863		GBAPatch16(gba->cpu, address, value, &old);
864		*opcode = (uint16_t) old;
865	}
866}
867
868void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
869	if (mode == MODE_ARM) {
870		GBAPatch32(gba->cpu, address, opcode, 0);
871	} else {
872		GBAPatch16(gba->cpu, address, opcode, 0);
873	}
874}
875
876static bool _setSoftwareBreakpoint(struct Debugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
877	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d, address, mode, opcode);
878	return true;
879}
880
881static bool _clearSoftwareBreakpoint(struct Debugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
882	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
883	return true;
884}