all repos — mgba @ 61c2f6a07b901a1ec793d2e683b09ce029019e56

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