all repos — mgba @ 8d89fb78ba9b76e53b1fba0f9c0549db4a220b1d

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