all repos — mgba @ d25ba2ec59b940940950aa1330fe563bced278bd

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