all repos — mgba @ 2b71e5c797516e6a0c8dcf1ca014549c31fb55a4

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