all repos — mgba @ 9756f79f044767052280bcc7d7d1225b1f326698

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