all repos — mgba @ e423cd45e5805f0d45fceb032eee8bee6d00f1c6

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