all repos — mgba @ a4e29886c9aab8a54a1232bac1bf4a4b7eb1b3db

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