all repos — mgba @ de065be15c1308aca3827a5c5953ede501c3b50a

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->activeFile = fname;
442	gba->memory.romSize = 0;
443	gba->memory.romMask = 0;
444	gba->romCrc32 = doCrc32(gba->pristineRom, gba->pristineRomSize);
445	return true;
446}
447
448bool GBALoadROM2(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->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
474	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
475	// TODO: error check
476	return true;
477}
478
479bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
480	GBASavedataInit(&gba->memory.savedata, sav);
481	return true;
482}
483
484void GBAYankROM(struct GBA* gba) {
485	gba->yankedRomSize = gba->memory.romSize;
486	gba->memory.romSize = 0;
487	gba->memory.romMask = 0;
488	GBARaiseIRQ(gba, IRQ_GAMEPAK);
489}
490
491void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
492	gba->biosVf = vf;
493	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
494	if (!bios) {
495		mLOG(GBA, WARN, "Couldn't map BIOS");
496		return;
497	}
498	gba->memory.bios = bios;
499	gba->memory.fullBios = 1;
500	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
501	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
502	if (checksum == GBA_BIOS_CHECKSUM) {
503		mLOG(GBA, INFO, "Official GBA BIOS detected");
504	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
505		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
506	} else {
507		mLOG(GBA, WARN, "BIOS checksum incorrect");
508	}
509	gba->biosChecksum = checksum;
510	if (gba->memory.activeRegion == REGION_BIOS) {
511		gba->cpu->memory.activeRegion = gba->memory.bios;
512	}
513	// TODO: error check
514}
515
516void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
517	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
518	if (!patchedSize || patchedSize > SIZE_CART0) {
519		return;
520	}
521	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
522	if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
523		mappedMemoryFree(gba->memory.rom, patchedSize);
524		gba->memory.rom = gba->pristineRom;
525		return;
526	}
527	gba->memory.romSize = patchedSize;
528	gba->memory.romMask = SIZE_CART0 - 1;
529	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
530}
531
532void GBATimerUpdateRegister(struct GBA* gba, int timer) {
533	struct GBATimer* currentTimer = &gba->timers[timer];
534	if (GBATimerFlagsIsEnable(currentTimer->flags) && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
535		int32_t prefetchSkew = 0;
536		if (gba->memory.lastPrefetchedPc - gba->memory.lastPrefetchedLoads * WORD_SIZE_THUMB >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
537			prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
538		}
539		// Reading this takes two cycles (1N+1I), so let's remove them preemptively
540		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> GBATimerFlagsGetPrescaleBits(currentTimer->flags));
541	}
542}
543
544void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
545	gba->timers[timer].reload = reload;
546	gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << GBATimerFlagsGetPrescaleBits(gba->timers[timer].flags);
547}
548
549void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
550	struct GBATimer* currentTimer = &gba->timers[timer];
551	GBATimerUpdateRegister(gba, timer);
552
553	unsigned oldPrescale = GBATimerFlagsGetPrescaleBits(currentTimer->flags);
554	switch (control & 0x0003) {
555	case 0x0000:
556		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 0);
557		break;
558	case 0x0001:
559		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 6);
560		break;
561	case 0x0002:
562		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 8);
563		break;
564	case 0x0003:
565		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 10);
566		break;
567	}
568	currentTimer->flags = GBATimerFlagsTestFillCountUp(currentTimer->flags, control & 0x0004);
569	currentTimer->flags = GBATimerFlagsTestFillDoIrq(currentTimer->flags, control & 0x0040);
570	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << GBATimerFlagsGetPrescaleBits(currentTimer->flags);
571	bool wasEnabled = GBATimerFlagsIsEnable(currentTimer->flags);
572	currentTimer->flags = GBATimerFlagsTestFillEnable(currentTimer->flags, control & 0x0080);
573	if (!wasEnabled && GBATimerFlagsIsEnable(currentTimer->flags)) {
574		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
575			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
576		} else {
577			currentTimer->nextEvent = INT_MAX;
578		}
579		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
580		currentTimer->oldReload = currentTimer->reload;
581		currentTimer->lastEvent = gba->cpu->cycles;
582		gba->timersEnabled |= 1 << timer;
583	} else if (wasEnabled && !GBATimerFlagsIsEnable(currentTimer->flags)) {
584		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
585			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
586		}
587		gba->timersEnabled &= ~(1 << timer);
588	} else if (GBATimerFlagsGetPrescaleBits(currentTimer->flags) != oldPrescale && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
589		// FIXME: this might be before present
590		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
591	}
592
593	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
594		gba->cpu->nextEvent = currentTimer->nextEvent;
595	}
596};
597
598void GBAWriteIE(struct GBA* gba, uint16_t value) {
599	if (value & (1 << IRQ_KEYPAD)) {
600		mLOG(GBA, STUB, "Keypad interrupts not implemented");
601	}
602
603	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
604		ARMRaiseIRQ(gba->cpu);
605	}
606}
607
608void GBAWriteIME(struct GBA* gba, uint16_t value) {
609	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
610		ARMRaiseIRQ(gba->cpu);
611	}
612}
613
614void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
615	gba->memory.io[REG_IF >> 1] |= 1 << irq;
616	gba->cpu->halted = 0;
617
618	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
619		ARMRaiseIRQ(gba->cpu);
620	}
621}
622
623void GBATestIRQ(struct ARMCore* cpu) {
624	struct GBA* gba = (struct GBA*) cpu->master;
625	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
626		gba->springIRQ = 1;
627		gba->cpu->nextEvent = gba->cpu->cycles;
628	}
629}
630
631void GBAHalt(struct GBA* gba) {
632	gba->cpu->nextEvent = gba->cpu->cycles;
633	gba->cpu->halted = 1;
634}
635
636void GBAStop(struct GBA* gba) {
637	if (!gba->stopCallback) {
638		return;
639	}
640	gba->cpu->nextEvent = gba->cpu->cycles;
641	gba->stopCallback->stop(gba->stopCallback);
642}
643
644bool GBAIsROM(struct VFile* vf) {
645	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
646		return false;
647	}
648	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
649	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
650		return false;
651	}
652	if (GBAIsBIOS(vf)) {
653		return false;
654	}
655	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
656}
657
658bool GBAIsMB(struct VFile* vf) {
659	if (!GBAIsROM(vf)) {
660		return false;
661	}
662	if (vf->size(vf) > SIZE_WORKING_RAM) {
663		return false;
664	}
665	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
666		return false;
667	}
668	uint32_t signature;
669	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
670		return false;
671	}
672	uint32_t opcode;
673	LOAD_32(opcode, 0, &signature);
674	struct ARMInstructionInfo info;
675	ARMDecodeARM(opcode, &info);
676	if (info.branchType != ARM_BRANCH) {
677		return false;
678	}
679	if (info.op1.immediate <= 0) {
680		return false;
681	} else if (info.op1.immediate == 28) {
682		// Ancient toolchain that is known to throw MB detection for a loop
683		return false;
684	} else if (info.op1.immediate != 24) {
685		return true;
686	}
687	// Found a libgba-linked cart...these are a bit harder to detect.
688	return false;
689}
690
691bool GBAIsBIOS(struct VFile* vf) {
692	if (vf->seek(vf, 0, SEEK_SET) < 0) {
693		return false;
694	}
695	uint8_t interruptTable[7 * 4];
696	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
697		return false;
698	}
699	int i;
700	for (i = 0; i < 7; ++i) {
701		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
702			return false;
703		}
704	}
705	return true;
706}
707
708void GBAGetGameCode(struct GBA* gba, char* out) {
709	if (!gba->memory.rom) {
710		out[0] = '\0';
711		return;
712	}
713	memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
714}
715
716void GBAGetGameTitle(struct GBA* gba, char* out) {
717	if (gba->memory.rom) {
718		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
719		return;
720	}
721	if (gba->pristineRom) {
722		memcpy(out, &((struct GBACartridge*) gba->pristineRom)->title, 12);
723		return;
724	}
725	strncpy(out, "(BIOS)", 12);
726}
727
728void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
729	struct GBA* gba = (struct GBA*) cpu->master;
730	if (gba->debugger) {
731		struct DebuggerEntryInfo info = {
732			.address = _ARMPCAddress(cpu),
733			.opcode = opcode
734		};
735		DebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
736	}
737	// TODO: More sensible category?
738	mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
739}
740
741void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
742	struct GBA* gba = (struct GBA*) cpu->master;
743	if (!gba->yankedRomSize) {
744		// TODO: More sensible category?
745		mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
746	}
747	if (gba->debugger) {
748		struct DebuggerEntryInfo info = {
749			.address = _ARMPCAddress(cpu),
750			.opcode = opcode
751		};
752		DebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
753	} else {
754		ARMRaiseUndefined(cpu);
755	}
756}
757
758void GBABreakpoint(struct ARMCore* cpu, int immediate) {
759	struct GBA* gba = (struct GBA*) cpu->master;
760	if (immediate >= GBA_COMPONENT_MAX) {
761		return;
762	}
763	switch (immediate) {
764	case GBA_COMPONENT_DEBUGGER:
765		if (gba->debugger) {
766			struct DebuggerEntryInfo info = {
767				.address = _ARMPCAddress(cpu)
768			};
769			DebuggerEnter(gba->debugger, DEBUGGER_ENTER_BREAKPOINT, &info);
770		}
771		break;
772	case GBA_COMPONENT_CHEAT_DEVICE:
773		if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
774			struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
775			struct GBACheatHook* hook = 0;
776			size_t i;
777			for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
778				struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
779				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
780					GBACheatRefresh(device, cheats);
781					hook = cheats->hook;
782				}
783			}
784			if (hook) {
785				ARMRunFake(cpu, hook->patchedOpcode);
786			}
787		}
788		break;
789	default:
790		break;
791	}
792}
793
794void GBAFrameStarted(struct GBA* gba) {
795	UNUSED(gba);
796
797	// TODO: Put back rewind
798}
799
800void GBAFrameEnded(struct GBA* gba) {
801	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
802
803	if (gba->rr) {
804		gba->rr->nextFrame(gba->rr);
805	}
806
807	if (gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
808		struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
809		size_t i;
810		for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
811			struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
812			if (!cheats->hook) {
813				GBACheatRefresh(device, cheats);
814			}
815		}
816	}
817
818	if (gba->stream && gba->stream->postVideoFrame) {
819		const color_t* pixels;
820		unsigned stride;
821		gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
822		gba->stream->postVideoFrame(gba->stream, pixels, stride);
823	}
824
825	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
826		GBAHardwarePlayerUpdate(gba);
827	}
828
829	struct mCoreThread* thread = mCoreThreadGet();
830	if (!thread) {
831		return;
832	}
833
834	if (thread->frameCallback) {
835		thread->frameCallback(thread);
836	}
837
838	// TODO: Put back RR
839}
840
841void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
842	size_t immediate;
843	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
844		if (gba->cpu->components[immediate] == component) {
845			break;
846		}
847	}
848	if (immediate == gba->cpu->numComponents) {
849		return;
850	}
851	if (mode == MODE_ARM) {
852		int32_t value;
853		int32_t old;
854		value = 0xE1200070;
855		value |= immediate & 0xF;
856		value |= (immediate & 0xFFF0) << 4;
857		GBAPatch32(gba->cpu, address, value, &old);
858		*opcode = old;
859	} else {
860		int16_t value;
861		int16_t old;
862		value = 0xBE00;
863		value |= immediate & 0xFF;
864		GBAPatch16(gba->cpu, address, value, &old);
865		*opcode = (uint16_t) old;
866	}
867}
868
869void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
870	if (mode == MODE_ARM) {
871		GBAPatch32(gba->cpu, address, opcode, 0);
872	} else {
873		GBAPatch16(gba->cpu, address, opcode, 0);
874	}
875}
876
877static bool _setSoftwareBreakpoint(struct Debugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
878	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d, address, mode, opcode);
879	return true;
880}
881
882static bool _clearSoftwareBreakpoint(struct Debugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
883	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
884	return true;
885}