all repos — mgba @ dd76386f4cee134237f6a86c37f178eeca8bd44b

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