all repos — mgba @ 98016c55a387ee3676de198af9b534e53e25625d

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