all repos — mgba @ 2a4ecde790e92a389500aac625f372103d7cf0e5

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