all repos — mgba @ 50402c830729f2ba5a6fc3e6facfd8b258f7f97d

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