all repos — mgba @ 6b1cbbd5e2f08c52a5f22ac6a71c3b2caba523d1

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