all repos — mgba @ 8345e29798f8e22ce0e0053ff62d08d61dce36fa

mGBA Game Boy Advance Emulator

src/gba/gba.c (view raw)

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