all repos — mgba @ a6cd5f44dbd25e8420d3f0643a2b3bbd607d99bb

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	if (!vf) {
494		return false;
495	}
496	GBAUnloadROM(gba);
497	gba->romVf = vf;
498	gba->pristineRomSize = vf->size(vf);
499	vf->seek(vf, 0, SEEK_SET);
500	if (gba->pristineRomSize > SIZE_CART0) {
501		gba->pristineRomSize = SIZE_CART0;
502	}
503#ifdef _3DS
504	gba->pristineRom = 0;
505	if (gba->pristineRomSize <= romBufferSize) {
506		gba->pristineRom = romBuffer;
507		vf->read(vf, romBuffer, gba->pristineRomSize);
508	}
509#else
510	gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
511#endif
512	if (!gba->pristineRom) {
513		mLOG(GBA, WARN, "Couldn't map ROM");
514		return false;
515	}
516	gba->yankedRomSize = 0;
517	gba->memory.rom = gba->pristineRom;
518	gba->memory.romSize = gba->pristineRomSize;
519	gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
520	gba->memory.mirroring = false;
521	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
522	GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
523	GBAVFameDetect(&gba->memory.vfame, gba->memory.rom, gba->memory.romSize);
524	// TODO: error check
525	return true;
526}
527
528bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
529	GBASavedataInit(&gba->memory.savedata, sav);
530	return true;
531}
532
533void GBAYankROM(struct GBA* gba) {
534	gba->yankedRomSize = gba->memory.romSize;
535	gba->memory.romSize = 0;
536	gba->memory.romMask = 0;
537	GBARaiseIRQ(gba, IRQ_GAMEPAK);
538}
539
540void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
541	gba->biosVf = vf;
542	uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
543	if (!bios) {
544		mLOG(GBA, WARN, "Couldn't map BIOS");
545		return;
546	}
547	gba->memory.bios = bios;
548	gba->memory.fullBios = 1;
549	uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
550	mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
551	if (checksum == GBA_BIOS_CHECKSUM) {
552		mLOG(GBA, INFO, "Official GBA BIOS detected");
553	} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
554		mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
555	} else {
556		mLOG(GBA, WARN, "BIOS checksum incorrect");
557	}
558	gba->biosChecksum = checksum;
559	if (gba->memory.activeRegion == REGION_BIOS) {
560		gba->cpu->memory.activeRegion = gba->memory.bios;
561	}
562	// TODO: error check
563}
564
565void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
566	size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
567	if (!patchedSize || patchedSize > SIZE_CART0) {
568		return;
569	}
570	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
571	if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
572		mappedMemoryFree(gba->memory.rom, patchedSize);
573		gba->memory.rom = gba->pristineRom;
574		return;
575	}
576	gba->memory.romSize = patchedSize;
577	gba->memory.romMask = SIZE_CART0 - 1;
578	gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
579}
580
581void GBATimerUpdateRegister(struct GBA* gba, int timer) {
582	struct GBATimer* currentTimer = &gba->timers[timer];
583	if (GBATimerFlagsIsEnable(currentTimer->flags) && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
584		int32_t prefetchSkew = 0;
585		if (gba->memory.lastPrefetchedPc >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
586			prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
587		}
588		// Reading this takes two cycles (1N+1I), so let's remove them preemptively
589		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> GBATimerFlagsGetPrescaleBits(currentTimer->flags));
590	}
591}
592
593void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
594	gba->timers[timer].reload = reload;
595	gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << GBATimerFlagsGetPrescaleBits(gba->timers[timer].flags);
596}
597
598void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
599	struct GBATimer* currentTimer = &gba->timers[timer];
600	GBATimerUpdateRegister(gba, timer);
601
602	unsigned oldPrescale = GBATimerFlagsGetPrescaleBits(currentTimer->flags);
603	switch (control & 0x0003) {
604	case 0x0000:
605		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 0);
606		break;
607	case 0x0001:
608		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 6);
609		break;
610	case 0x0002:
611		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 8);
612		break;
613	case 0x0003:
614		currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 10);
615		break;
616	}
617	currentTimer->flags = GBATimerFlagsTestFillCountUp(currentTimer->flags, timer > 0 && (control & 0x0004));
618	currentTimer->flags = GBATimerFlagsTestFillDoIrq(currentTimer->flags, control & 0x0040);
619	currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << GBATimerFlagsGetPrescaleBits(currentTimer->flags);
620	bool wasEnabled = GBATimerFlagsIsEnable(currentTimer->flags);
621	currentTimer->flags = GBATimerFlagsTestFillEnable(currentTimer->flags, control & 0x0080);
622	if (!wasEnabled && GBATimerFlagsIsEnable(currentTimer->flags)) {
623		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
624			currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
625		} else {
626			currentTimer->nextEvent = INT_MAX;
627		}
628		gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
629		currentTimer->oldReload = currentTimer->reload;
630		currentTimer->lastEvent = gba->cpu->cycles;
631		gba->timersEnabled |= 1 << timer;
632	} else if (wasEnabled && !GBATimerFlagsIsEnable(currentTimer->flags)) {
633		if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
634			gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
635		}
636		gba->timersEnabled &= ~(1 << timer);
637	} else if (GBATimerFlagsGetPrescaleBits(currentTimer->flags) != oldPrescale && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
638		// FIXME: this might be before present
639		currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
640	}
641
642	if (currentTimer->nextEvent < gba->cpu->nextEvent) {
643		gba->cpu->nextEvent = currentTimer->nextEvent;
644	}
645};
646
647void GBAWriteIE(struct GBA* gba, uint16_t value) {
648	if (value & (1 << IRQ_KEYPAD)) {
649		mLOG(GBA, STUB, "Keypad interrupts not implemented");
650	}
651
652	if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
653		ARMRaiseIRQ(gba->cpu);
654	}
655}
656
657void GBAWriteIME(struct GBA* gba, uint16_t value) {
658	if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
659		ARMRaiseIRQ(gba->cpu);
660	}
661}
662
663void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
664	gba->memory.io[REG_IF >> 1] |= 1 << irq;
665	gba->cpu->halted = 0;
666
667	if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
668		ARMRaiseIRQ(gba->cpu);
669	}
670}
671
672void GBATestIRQ(struct ARMCore* cpu) {
673	struct GBA* gba = (struct GBA*) cpu->master;
674	if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
675		gba->springIRQ = 1;
676		gba->cpu->nextEvent = gba->cpu->cycles;
677	}
678}
679
680void GBAHalt(struct GBA* gba) {
681	gba->cpu->nextEvent = gba->cpu->cycles;
682	gba->cpu->halted = 1;
683}
684
685void GBAStop(struct GBA* gba) {
686	if (!gba->stopCallback) {
687		return;
688	}
689	gba->cpu->nextEvent = gba->cpu->cycles;
690	gba->stopCallback->stop(gba->stopCallback);
691}
692
693void GBADebug(struct GBA* gba, uint16_t flags) {
694	gba->debugFlags = flags;
695	if (GBADebugFlagsIsSend(gba->debugFlags)) {
696		int level = 1 << GBADebugFlagsGetLevel(gba->debugFlags);
697		level &= 0x1F;
698		char oolBuf[0x101];
699		strncpy(oolBuf, gba->debugString, sizeof(gba->debugString));
700		oolBuf[0x100] = '\0';
701		mLog(_mLOG_CAT_GBA_DEBUG(), level, "%s", oolBuf);
702	}
703	gba->debugFlags = GBADebugFlagsClearSend(gba->debugFlags);
704}
705
706bool GBAIsROM(struct VFile* vf) {
707	if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
708		return false;
709	}
710	uint8_t signature[sizeof(GBA_ROM_MAGIC)];
711	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
712		return false;
713	}
714	if (GBAIsBIOS(vf)) {
715		return false;
716	}
717	return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
718}
719
720bool GBAIsMB(struct VFile* vf) {
721	if (!GBAIsROM(vf)) {
722		return false;
723	}
724	if (vf->size(vf) > SIZE_WORKING_RAM) {
725		return false;
726	}
727	if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
728		return false;
729	}
730	uint32_t signature;
731	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
732		return false;
733	}
734	uint32_t opcode;
735	LOAD_32(opcode, 0, &signature);
736	struct ARMInstructionInfo info;
737	ARMDecodeARM(opcode, &info);
738	if (info.branchType != ARM_BRANCH) {
739		return false;
740	}
741	if (info.op1.immediate <= 0) {
742		return false;
743	} else if (info.op1.immediate == 28) {
744		// Ancient toolchain that is known to throw MB detection for a loop
745		return false;
746	} else if (info.op1.immediate != 24) {
747		return true;
748	}
749	// Found a libgba-linked cart...these are a bit harder to detect.
750	return false;
751}
752
753bool GBAIsBIOS(struct VFile* vf) {
754	if (vf->seek(vf, 0, SEEK_SET) < 0) {
755		return false;
756	}
757	uint8_t interruptTable[7 * 4];
758	if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
759		return false;
760	}
761	int i;
762	for (i = 0; i < 7; ++i) {
763		if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
764			return false;
765		}
766	}
767	return true;
768}
769
770void GBAGetGameCode(const struct GBA* gba, char* out) {
771	memset(out, 0, 8);
772	if (!gba->memory.rom) {
773		return;
774	}
775
776	memcpy(out, "AGB-", 4);
777	memcpy(&out[4], &((struct GBACartridge*) gba->memory.rom)->id, 4);
778}
779
780void GBAGetGameTitle(const struct GBA* gba, char* out) {
781	if (gba->memory.rom) {
782		memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
783		return;
784	}
785	if (gba->pristineRom) {
786		memcpy(out, &((struct GBACartridge*) gba->pristineRom)->title, 12);
787		return;
788	}
789	strncpy(out, "(BIOS)", 12);
790}
791
792void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
793	struct GBA* gba = (struct GBA*) cpu->master;
794#ifdef USE_DEBUGGERS
795	if (gba->debugger) {
796		struct mDebuggerEntryInfo info = {
797			.address = _ARMPCAddress(cpu),
798			.opcode = opcode
799		};
800		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
801	}
802#endif
803	// TODO: More sensible category?
804	mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
805}
806
807void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
808	struct GBA* gba = (struct GBA*) cpu->master;
809	if (!gba->yankedRomSize) {
810		// TODO: More sensible category?
811		mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
812	}
813#ifdef USE_DEBUGGERS
814	if (gba->debugger) {
815		struct mDebuggerEntryInfo info = {
816			.address = _ARMPCAddress(cpu),
817			.opcode = opcode
818		};
819		mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
820	} else
821#endif
822	{
823		ARMRaiseUndefined(cpu);
824	}
825}
826
827void GBABreakpoint(struct ARMCore* cpu, int immediate) {
828	struct GBA* gba = (struct GBA*) cpu->master;
829	if (immediate >= CPU_COMPONENT_MAX) {
830		return;
831	}
832	switch (immediate) {
833#ifdef USE_DEBUGGERS
834	case CPU_COMPONENT_DEBUGGER:
835		if (gba->debugger) {
836			struct mDebuggerEntryInfo info = {
837				.address = _ARMPCAddress(cpu),
838				.breakType = BREAKPOINT_SOFTWARE
839			};
840			mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
841		}
842		break;
843#endif
844	case CPU_COMPONENT_CHEAT_DEVICE:
845		if (gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
846			struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
847			struct GBACheatHook* hook = 0;
848			size_t i;
849			for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
850				struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
851				if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
852					mCheatRefresh(device, &cheats->d);
853					hook = cheats->hook;
854				}
855			}
856			if (hook) {
857				ARMRunFake(cpu, hook->patchedOpcode);
858			}
859		}
860		break;
861	default:
862		break;
863	}
864}
865
866void GBAFrameStarted(struct GBA* gba) {
867	UNUSED(gba);
868
869	struct mCoreCallbacks* callbacks = gba->coreCallbacks;
870	if (callbacks && callbacks->videoFrameStarted) {
871		callbacks->videoFrameStarted(callbacks->context);
872	}
873}
874
875void GBAFrameEnded(struct GBA* gba) {
876	GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
877
878	if (gba->rr) {
879		gba->rr->nextFrame(gba->rr);
880	}
881
882	if (gba->cpu->components && gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
883		struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
884		size_t i;
885		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
886			struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
887			mCheatRefresh(device, &cheats->d);
888		}
889	}
890
891	if (gba->stream && gba->stream->postVideoFrame) {
892		const color_t* pixels;
893		size_t stride;
894		gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
895		gba->stream->postVideoFrame(gba->stream, pixels, stride);
896	}
897
898	if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
899		GBAHardwarePlayerUpdate(gba);
900	}
901
902	struct mCoreCallbacks* callbacks = gba->coreCallbacks;
903	if (callbacks && callbacks->videoFrameEnded) {
904		callbacks->videoFrameEnded(callbacks->context);
905	}
906}
907
908void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
909	size_t immediate;
910	for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
911		if (gba->cpu->components[immediate] == component) {
912			break;
913		}
914	}
915	if (immediate == gba->cpu->numComponents) {
916		return;
917	}
918	if (mode == MODE_ARM) {
919		int32_t value;
920		int32_t old;
921		value = 0xE1200070;
922		value |= immediate & 0xF;
923		value |= (immediate & 0xFFF0) << 4;
924		GBAPatch32(gba->cpu, address, value, &old);
925		*opcode = old;
926	} else {
927		int16_t value;
928		int16_t old;
929		value = 0xBE00;
930		value |= immediate & 0xFF;
931		GBAPatch16(gba->cpu, address, value, &old);
932		*opcode = (uint16_t) old;
933	}
934}
935
936void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
937	if (mode == MODE_ARM) {
938		GBAPatch32(gba->cpu, address, opcode, 0);
939	} else {
940		GBAPatch16(gba->cpu, address, opcode, 0);
941	}
942}
943
944static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
945	GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d.p->d, address, mode, opcode);
946	return true;
947}
948
949static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
950	GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
951	return true;
952}