all repos — mgba @ f0686a3b786b0c264d2dfe37080839ba6c9775ce

mGBA Game Boy Advance Emulator

src/gb/gb.c (view raw)

  1/* Copyright (c) 2013-2016 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 <mgba/internal/gb/gb.h>
  7
  8#include <mgba/internal/gb/io.h>
  9#include <mgba/internal/gb/mbc.h>
 10#include <mgba/internal/lr35902/lr35902.h>
 11
 12#include <mgba/core/core.h>
 13#include <mgba/core/cheats.h>
 14#include <mgba-util/crc32.h>
 15#include <mgba-util/memory.h>
 16#include <mgba-util/math.h>
 17#include <mgba-util/patch.h>
 18#include <mgba-util/vfs.h>
 19
 20#define CLEANUP_THRESHOLD 15
 21
 22const uint32_t CGB_LR35902_FREQUENCY = 0x800000;
 23const uint32_t SGB_LR35902_FREQUENCY = 0x418B1E;
 24
 25const uint32_t GB_COMPONENT_MAGIC = 0x400000;
 26
 27static const uint8_t _knownHeader[4] = { 0xCE, 0xED, 0x66, 0x66};
 28
 29#define DMG_BIOS_CHECKSUM 0xC2F5CC97
 30#define DMG_2_BIOS_CHECKSUM 0x59C8598E
 31#define MGB_BIOS_CHECKSUM 0xE6920754
 32#define SGB_BIOS_CHECKSUM 0xEC8A83B9
 33#define CGB_BIOS_CHECKSUM 0x41884E46
 34
 35mLOG_DEFINE_CATEGORY(GB, "GB", "gb");
 36
 37static void GBInit(void* cpu, struct mCPUComponent* component);
 38static void GBDeinit(struct mCPUComponent* component);
 39static void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh);
 40static void GBProcessEvents(struct LR35902Core* cpu);
 41static void GBSetInterrupts(struct LR35902Core* cpu, bool enable);
 42static void GBIllegal(struct LR35902Core* cpu);
 43static void GBStop(struct LR35902Core* cpu);
 44
 45static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate);
 46
 47#ifdef FIXED_ROM_BUFFER
 48extern uint32_t* romBuffer;
 49extern size_t romBufferSize;
 50#endif
 51
 52void GBCreate(struct GB* gb) {
 53	gb->d.id = GB_COMPONENT_MAGIC;
 54	gb->d.init = GBInit;
 55	gb->d.deinit = GBDeinit;
 56}
 57
 58static void GBInit(void* cpu, struct mCPUComponent* component) {
 59	struct GB* gb = (struct GB*) component;
 60	gb->cpu = cpu;
 61	gb->sync = NULL;
 62
 63	GBInterruptHandlerInit(&gb->cpu->irqh);
 64	GBMemoryInit(gb);
 65
 66	gb->video.p = gb;
 67	GBVideoInit(&gb->video);
 68
 69	gb->audio.p = gb;
 70	GBAudioInit(&gb->audio, 2048, &gb->memory.io[REG_NR52], GB_AUDIO_DMG); // TODO: Remove magic constant
 71
 72	gb->sio.p = gb;
 73	GBSIOInit(&gb->sio);
 74
 75	gb->timer.p = gb;
 76
 77	gb->model = GB_MODEL_AUTODETECT;
 78
 79	gb->biosVf = NULL;
 80	gb->romVf = NULL;
 81	gb->sramVf = NULL;
 82	gb->sramRealVf = NULL;
 83
 84	gb->isPristine = false;
 85	gb->pristineRomSize = 0;
 86	gb->yankedRomSize = 0;
 87
 88	mCoreCallbacksListInit(&gb->coreCallbacks, 0);
 89	gb->stream = NULL;
 90
 91	mTimingInit(&gb->timing, &gb->cpu->cycles, &gb->cpu->nextEvent);
 92	gb->audio.timing = &gb->timing;
 93
 94	gb->eiPending.name = "GB EI";
 95	gb->eiPending.callback = _enableInterrupts;
 96	gb->eiPending.context = gb;
 97	gb->eiPending.priority = 0;
 98}
 99
100static void GBDeinit(struct mCPUComponent* component) {
101	struct GB* gb = (struct GB*) component;
102	mTimingDeinit(&gb->timing);
103}
104
105bool GBLoadROM(struct GB* gb, struct VFile* vf) {
106	if (!vf) {
107		return false;
108	}
109	GBUnloadROM(gb);
110	gb->romVf = vf;
111	gb->pristineRomSize = vf->size(vf);
112	vf->seek(vf, 0, SEEK_SET);
113	gb->isPristine = true;
114#ifdef FIXED_ROM_BUFFER
115	if (gb->pristineRomSize <= romBufferSize) {
116		gb->memory.rom = romBuffer;
117		vf->read(vf, romBuffer, gb->pristineRomSize);
118	}
119#else
120	gb->memory.rom = vf->map(vf, gb->pristineRomSize, MAP_READ);
121#endif
122	if (!gb->memory.rom) {
123		return false;
124	}
125	gb->yankedRomSize = 0;
126	gb->memory.romBase = gb->memory.rom;
127	gb->memory.romSize = gb->pristineRomSize;
128	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
129	GBMBCInit(gb);
130
131	if (gb->cpu) {
132		struct LR35902Core* cpu = gb->cpu;
133		cpu->memory.setActiveRegion(cpu, cpu->pc);
134	}
135
136	// TODO: error check
137	return true;
138}
139
140static void GBSramDeinit(struct GB* gb) {
141	if (gb->sramVf) {
142		gb->sramVf->unmap(gb->sramVf, gb->memory.sram, gb->sramSize);
143		if (gb->memory.mbcType == GB_MBC3_RTC && gb->sramVf == gb->sramRealVf) {
144			GBMBCRTCWrite(gb);
145		}
146		gb->sramVf = NULL;
147	} else if (gb->memory.sram) {
148		mappedMemoryFree(gb->memory.sram, gb->sramSize);
149	}
150	gb->memory.sram = 0;
151}
152
153bool GBLoadSave(struct GB* gb, struct VFile* vf) {
154	GBSramDeinit(gb);
155	gb->sramVf = vf;
156	gb->sramRealVf = vf;
157	if (gb->sramSize) {
158		GBResizeSram(gb, gb->sramSize);
159	}
160	return vf;
161}
162
163void GBResizeSram(struct GB* gb, size_t size) {
164	if (gb->memory.sram && size <= gb->sramSize) {
165		return;
166	}
167	struct VFile* vf = gb->sramVf;
168	if (vf) {
169		if (vf == gb->sramRealVf) {
170			ssize_t vfSize = vf->size(vf);
171			if (vfSize >= 0 && (size_t) vfSize < size) {
172				uint8_t extdataBuffer[0x100];
173				if (vfSize & 0xFF) {
174					vf->seek(vf, -(vfSize & 0xFF), SEEK_END);
175					vf->read(vf, extdataBuffer, vfSize & 0xFF);
176				}
177				if (gb->memory.sram) {
178					vf->unmap(vf, gb->memory.sram, gb->sramSize);
179				}
180				vf->truncate(vf, size + (vfSize & 0xFF));
181				if (vfSize & 0xFF) {
182					vf->seek(vf, size, SEEK_SET);
183					vf->write(vf, extdataBuffer, vfSize & 0xFF);
184				}
185				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
186				memset(&gb->memory.sram[gb->sramSize], 0xFF, size - gb->sramSize);
187			} else if (size > gb->sramSize || !gb->memory.sram) {
188				if (gb->memory.sram) {
189					vf->unmap(vf, gb->memory.sram, gb->sramSize);
190				}
191				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
192			}
193		} else {
194			if (gb->memory.sram) {
195				vf->unmap(vf, gb->memory.sram, gb->sramSize);
196			}
197			gb->memory.sram = vf->map(vf, size, MAP_READ);
198		}
199		if (gb->memory.sram == (void*) -1) {
200			gb->memory.sram = NULL;
201		}
202	} else {
203		uint8_t* newSram = anonymousMemoryMap(size);
204		if (gb->memory.sram) {
205			if (size > gb->sramSize) {
206				memcpy(newSram, gb->memory.sram, gb->sramSize);
207				memset(&newSram[gb->sramSize], 0xFF, size - gb->sramSize);
208			} else {
209				memcpy(newSram, gb->memory.sram, size);
210			}
211			mappedMemoryFree(gb->memory.sram, gb->sramSize);
212		} else {
213			memset(newSram, 0xFF, size);
214		}
215		gb->memory.sram = newSram;
216	}
217	if (gb->sramSize < size) {
218		gb->sramSize = size;
219	}
220}
221
222void GBSramClean(struct GB* gb, uint32_t frameCount) {
223	// TODO: Share with GBASavedataClean
224	if (!gb->sramVf) {
225		return;
226	}
227	if (gb->sramDirty & GB_SRAM_DIRT_NEW) {
228		gb->sramDirtAge = frameCount;
229		gb->sramDirty &= ~GB_SRAM_DIRT_NEW;
230		if (!(gb->sramDirty & GB_SRAM_DIRT_SEEN)) {
231			gb->sramDirty |= GB_SRAM_DIRT_SEEN;
232		}
233	} else if ((gb->sramDirty & GB_SRAM_DIRT_SEEN) && frameCount - gb->sramDirtAge > CLEANUP_THRESHOLD) {
234		if (gb->sramMaskWriteback) {
235			GBSavedataUnmask(gb);
236		}
237		if (gb->memory.mbcType == GB_MBC3_RTC) {
238			GBMBCRTCWrite(gb);
239		}
240		gb->sramDirty = 0;
241		if (gb->memory.sram && gb->sramVf->sync(gb->sramVf, gb->memory.sram, gb->sramSize)) {
242			mLOG(GB_MEM, INFO, "Savedata synced");
243		} else {
244			mLOG(GB_MEM, INFO, "Savedata failed to sync!");
245		}
246	}
247}
248
249void GBSavedataMask(struct GB* gb, struct VFile* vf, bool writeback) {
250	GBSramDeinit(gb);
251	gb->sramVf = vf;
252	gb->sramMaskWriteback = writeback;
253	gb->memory.sram = vf->map(vf, gb->sramSize, MAP_READ);
254	GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
255}
256
257void GBSavedataUnmask(struct GB* gb) {
258	if (gb->sramVf == gb->sramRealVf) {
259		return;
260	}
261	struct VFile* vf = gb->sramVf;
262	GBSramDeinit(gb);
263	gb->sramVf = gb->sramRealVf;
264	gb->memory.sram = gb->sramVf->map(gb->sramVf, gb->sramSize, MAP_WRITE);
265	if (gb->sramMaskWriteback) {
266		vf->seek(vf, 0, SEEK_SET);
267		vf->read(vf, gb->memory.sram, gb->sramSize);
268		gb->sramMaskWriteback = false;
269	}
270	vf->close(vf);
271}
272
273void GBUnloadROM(struct GB* gb) {
274	// TODO: Share with GBAUnloadROM
275	if (gb->memory.rom && gb->memory.romBase != gb->memory.rom && !gb->isPristine) {
276		free(gb->memory.romBase);
277	}
278	if (gb->memory.rom && !gb->isPristine) {
279		if (gb->yankedRomSize) {
280			gb->yankedRomSize = 0;
281		}
282		mappedMemoryFree(gb->memory.rom, GB_SIZE_CART_MAX);
283	}
284
285	if (gb->romVf) {
286#ifndef FIXED_ROM_BUFFER
287		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
288#endif
289		gb->romVf->close(gb->romVf);
290		gb->romVf = NULL;
291	}
292	gb->memory.rom = NULL;
293	gb->memory.mbcType = GB_MBC_AUTODETECT;
294	gb->isPristine = false;
295
296	gb->sramMaskWriteback = false;
297	GBSavedataUnmask(gb);
298	GBSramDeinit(gb);
299	if (gb->sramRealVf) {
300		gb->sramRealVf->close(gb->sramRealVf);
301	}
302	gb->sramRealVf = NULL;
303	gb->sramVf = NULL;
304	if (gb->memory.cam && gb->memory.cam->stopRequestImage) {
305		gb->memory.cam->stopRequestImage(gb->memory.cam);
306	}
307}
308
309void GBSynthesizeROM(struct VFile* vf) {
310	if (!vf) {
311		return;
312	}
313	const struct GBCartridge cart = {
314		.logo = { _knownHeader[0], _knownHeader[1], _knownHeader[2], _knownHeader[3]}
315	};
316
317	vf->seek(vf, 0x100, SEEK_SET);
318	vf->write(vf, &cart, sizeof(cart));
319}
320
321void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
322	gb->biosVf = vf;
323}
324
325void GBApplyPatch(struct GB* gb, struct Patch* patch) {
326	size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
327	if (!patchedSize) {
328		return;
329	}
330	if (patchedSize > GB_SIZE_CART_MAX) {
331		patchedSize = GB_SIZE_CART_MAX;
332	}
333	void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
334	if (!patch->applyPatch(patch, gb->memory.rom, gb->pristineRomSize, newRom, patchedSize)) {
335		mappedMemoryFree(newRom, GB_SIZE_CART_MAX);
336		return;
337	}
338	if (gb->romVf) {
339#ifndef FIXED_ROM_BUFFER
340		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
341#endif
342		gb->romVf->close(gb->romVf);
343		gb->romVf = NULL;
344	}
345	gb->isPristine = false;
346	if (gb->memory.romBase == gb->memory.rom) {
347		gb->memory.romBase = newRom;
348	}
349	gb->memory.rom = newRom;
350	gb->memory.romSize = patchedSize;
351	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
352	gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
353}
354
355void GBDestroy(struct GB* gb) {
356	GBUnloadROM(gb);
357
358	if (gb->biosVf) {
359		gb->biosVf->close(gb->biosVf);
360		gb->biosVf = 0;
361	}
362
363	GBMemoryDeinit(gb);
364	GBAudioDeinit(&gb->audio);
365	GBVideoDeinit(&gb->video);
366	GBSIODeinit(&gb->sio);
367	mCoreCallbacksListDeinit(&gb->coreCallbacks);
368}
369
370void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh) {
371	irqh->reset = GBReset;
372	irqh->processEvents = GBProcessEvents;
373	irqh->setInterrupts = GBSetInterrupts;
374	irqh->hitIllegal = GBIllegal;
375	irqh->stop = GBStop;
376	irqh->halt = GBHalt;
377}
378
379static uint32_t _GBBiosCRC32(struct VFile* vf) {
380	ssize_t size = vf->size(vf);
381	if (size <= 0 || size > GB_SIZE_CART_BANK0) {
382		return 0;
383	}
384	void* bios = vf->map(vf, size, MAP_READ);
385	uint32_t biosCrc = doCrc32(bios, size);
386	vf->unmap(vf, bios, size);
387	return biosCrc;
388}
389
390bool GBIsBIOS(struct VFile* vf) {
391	switch (_GBBiosCRC32(vf)) {
392	case DMG_BIOS_CHECKSUM:
393	case DMG_2_BIOS_CHECKSUM:
394	case MGB_BIOS_CHECKSUM:
395	case SGB_BIOS_CHECKSUM:
396	case CGB_BIOS_CHECKSUM:
397		return true;
398	default:
399		return false;
400	}
401}
402
403void GBReset(struct LR35902Core* cpu) {
404	struct GB* gb = (struct GB*) cpu->master;
405	gb->memory.romBase = gb->memory.rom;
406	GBDetectModel(gb);
407
408	if (gb->biosVf) {
409		if (!GBIsBIOS(gb->biosVf)) {
410			gb->biosVf->close(gb->biosVf);
411			gb->biosVf = NULL;
412		} else {
413			gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
414			gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
415			ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
416			memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
417			if (size > 0x100) {
418				memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
419			}
420
421			cpu->a = 0;
422			cpu->f.packed = 0;
423			cpu->c = 0;
424			cpu->e = 0;
425			cpu->h = 0;
426			cpu->l = 0;
427			cpu->sp = 0;
428			cpu->pc = 0;
429		}
430	}
431
432	cpu->b = 0;
433	cpu->d = 0;
434
435	if (!gb->biosVf) {
436		switch (gb->model) {
437		case GB_MODEL_AUTODETECT: // Silence warnings
438			gb->model = GB_MODEL_DMG;
439		case GB_MODEL_DMG:
440			cpu->a = 1;
441			cpu->f.packed = 0xB0;
442			cpu->c = 0x13;
443			cpu->e = 0xD8;
444			cpu->h = 1;
445			cpu->l = 0x4D;
446			gb->timer.internalDiv = 0x2AF3;
447			break;
448		case GB_MODEL_SGB:
449			cpu->a = 1;
450			cpu->f.packed = 0x00;
451			cpu->c = 0x14;
452			cpu->e = 0x00;
453			cpu->h = 0xC0;
454			cpu->l = 0x60;
455			gb->timer.internalDiv = 0x2AF3;
456			break;
457		case GB_MODEL_MGB:
458			cpu->a = 0xFF;
459			cpu->f.packed = 0xB0;
460			cpu->c = 0x13;
461			cpu->e = 0xD8;
462			cpu->h = 1;
463			cpu->l = 0x4D;
464			gb->timer.internalDiv = 0x2AF3;
465			break;
466		case GB_MODEL_SGB2:
467			cpu->a = 0xFF;
468			cpu->f.packed = 0x00;
469			cpu->c = 0x14;
470			cpu->e = 0x00;
471			cpu->h = 0xC0;
472			cpu->l = 0x60;
473			gb->timer.internalDiv = 0x2AF3;
474			break;
475		case GB_MODEL_AGB:
476			cpu->b = 1;
477			// Fall through
478		case GB_MODEL_CGB:
479			cpu->a = 0x11;
480			cpu->f.packed = 0x80;
481			cpu->c = 0;
482			cpu->e = 0x08;
483			cpu->h = 0;
484			cpu->l = 0x7C;
485			gb->timer.internalDiv = 0x7A8;
486			break;
487		}
488
489		cpu->sp = 0xFFFE;
490		cpu->pc = 0x100;
491	}
492
493	gb->cpuBlocked = false;
494	gb->earlyExit = false;
495	gb->doubleSpeed = 0;
496
497	cpu->memory.setActiveRegion(cpu, cpu->pc);
498
499	if (gb->yankedRomSize) {
500		gb->memory.romSize = gb->yankedRomSize;
501		gb->yankedRomSize = 0;
502	}
503
504	gb->sgbBit = -1;
505	gb->currentSgbBits = 0;
506	memset(gb->sgbPacket, 0, sizeof(gb->sgbPacket));
507
508	mTimingClear(&gb->timing);
509
510	GBMemoryReset(gb);
511	GBVideoReset(&gb->video);
512	GBTimerReset(&gb->timer);
513	mTimingSchedule(&gb->timing, &gb->timer.event, GB_DMG_DIV_PERIOD);
514
515	GBAudioReset(&gb->audio);
516	GBIOReset(gb);
517	GBSIOReset(&gb->sio);
518
519	GBSavedataUnmask(gb);
520}
521
522void GBDetectModel(struct GB* gb) {
523	if (gb->model != GB_MODEL_AUTODETECT) {
524		return;
525	}
526	if (gb->biosVf) {
527		switch (_GBBiosCRC32(gb->biosVf)) {
528		case DMG_BIOS_CHECKSUM:
529		case DMG_2_BIOS_CHECKSUM:
530			gb->model = GB_MODEL_DMG;
531			break;
532		case MGB_BIOS_CHECKSUM:
533			gb->model = GB_MODEL_MGB;
534			break;
535		case SGB_BIOS_CHECKSUM:
536			gb->model = GB_MODEL_SGB;
537			break;
538		case CGB_BIOS_CHECKSUM:
539			gb->model = GB_MODEL_CGB;
540			break;
541		default:
542			gb->biosVf->close(gb->biosVf);
543			gb->biosVf = NULL;
544		}
545	}
546	if (gb->model == GB_MODEL_AUTODETECT && gb->memory.rom) {
547		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
548		if (cart->cgb & 0x80) {
549			gb->model = GB_MODEL_CGB;
550		} else if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
551			gb->model = GB_MODEL_SGB;
552		} else {
553			gb->model = GB_MODEL_DMG;
554		}
555	}
556
557	switch (gb->model) {
558	case GB_MODEL_DMG:
559	case GB_MODEL_SGB:
560	case GB_MODEL_AUTODETECT: //Silence warnings
561		gb->audio.style = GB_AUDIO_DMG;
562		break;
563	case GB_MODEL_MGB:
564	case GB_MODEL_SGB2:
565		gb->audio.style = GB_AUDIO_MGB;
566		break;
567	case GB_MODEL_AGB:
568	case GB_MODEL_CGB:
569		gb->audio.style = GB_AUDIO_CGB;
570		break;
571	}
572}
573
574void GBUpdateIRQs(struct GB* gb) {
575	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
576	if (!irqs) {
577		return;
578	}
579	gb->cpu->halted = false;
580
581	if (!gb->memory.ime || gb->cpu->irqPending) {
582		return;
583	}
584
585	if (irqs & (1 << GB_IRQ_VBLANK)) {
586		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_VBLANK);
587		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
588		return;
589	}
590	if (irqs & (1 << GB_IRQ_LCDSTAT)) {
591		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_LCDSTAT);
592		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
593		return;
594	}
595	if (irqs & (1 << GB_IRQ_TIMER)) {
596		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_TIMER);
597		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
598		return;
599	}
600	if (irqs & (1 << GB_IRQ_SIO)) {
601		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_SIO);
602		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
603		return;
604	}
605	if (irqs & (1 << GB_IRQ_KEYPAD)) {
606		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_KEYPAD);
607		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
608	}
609}
610
611void GBProcessEvents(struct LR35902Core* cpu) {
612	struct GB* gb = (struct GB*) cpu->master;
613	do {
614		int32_t cycles = cpu->cycles;
615		int32_t nextEvent;
616
617		cpu->cycles = 0;
618		cpu->nextEvent = INT_MAX;
619
620		nextEvent = cycles;
621		do {
622			nextEvent = mTimingTick(&gb->timing, nextEvent);
623		} while (gb->cpuBlocked);
624		cpu->nextEvent = nextEvent;
625
626		if (gb->earlyExit) {
627			gb->earlyExit = false;
628			break;
629		}
630		if (cpu->halted) {
631			cpu->cycles = cpu->nextEvent;
632			if (!gb->memory.ie || !gb->memory.ime) {
633				break;
634			}
635		}
636	} while (cpu->cycles >= cpu->nextEvent);
637}
638
639void GBSetInterrupts(struct LR35902Core* cpu, bool enable) {
640	struct GB* gb = (struct GB*) cpu->master;
641	if (!enable) {
642		gb->memory.ime = enable;
643		mTimingDeschedule(&gb->timing, &gb->eiPending);
644		GBUpdateIRQs(gb);
645	} else {
646		mTimingDeschedule(&gb->timing, &gb->eiPending);
647		mTimingSchedule(&gb->timing, &gb->eiPending, 4);
648	}
649}
650
651static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate) {
652	UNUSED(timing);
653	UNUSED(cyclesLate);
654	struct GB* gb = user;
655	gb->memory.ime = true;
656	GBUpdateIRQs(gb);
657}
658
659void GBHalt(struct LR35902Core* cpu) {
660	if (!cpu->irqPending) {
661		cpu->cycles = cpu->nextEvent;
662		cpu->halted = true;
663	}
664}
665
666void GBStop(struct LR35902Core* cpu) {
667	struct GB* gb = (struct GB*) cpu->master;
668	if (cpu->bus) {
669		mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X", cpu->pc, cpu->bus);
670	}
671	if (gb->memory.io[REG_KEY1] & 1) {
672		gb->doubleSpeed ^= 1;
673		gb->audio.timingFactor = gb->doubleSpeed + 1;
674		gb->memory.io[REG_KEY1] = 0;
675		gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
676	} else if (cpu->bus) {
677#ifdef USE_DEBUGGERS
678		if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
679			struct mDebuggerEntryInfo info = {
680				.address = cpu->pc - 1,
681				.opcode = 0x1000 | cpu->bus
682			};
683			mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
684		}
685#endif
686		// Hang forever
687		gb->memory.ime = 0;
688		cpu->pc -= 2;
689	}
690	// TODO: Actually stop
691}
692
693void GBIllegal(struct LR35902Core* cpu) {
694	struct GB* gb = (struct GB*) cpu->master;
695	mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X", cpu->pc, cpu->bus);
696#ifdef USE_DEBUGGERS
697	if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
698		struct mDebuggerEntryInfo info = {
699			.address = cpu->pc,
700			.opcode = cpu->bus
701		};
702		mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
703	}
704#endif
705	// Hang forever
706	gb->memory.ime = 0;
707	--cpu->pc;
708}
709
710bool GBIsROM(struct VFile* vf) {
711	if (!vf) {
712		return false;
713	}
714	vf->seek(vf, 0x104, SEEK_SET);
715	uint8_t header[4];
716
717	if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
718		return false;
719	}
720	if (memcmp(header, _knownHeader, sizeof(header))) {
721		return false;
722	}
723	return true;
724}
725
726void GBGetGameTitle(const struct GB* gb, char* out) {
727	const struct GBCartridge* cart = NULL;
728	if (gb->memory.rom) {
729		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
730	}
731	if (!cart) {
732		return;
733	}
734	if (cart->oldLicensee != 0x33) {
735		memcpy(out, cart->titleLong, 16);
736	} else {
737		memcpy(out, cart->titleShort, 11);
738	}
739}
740
741void GBGetGameCode(const struct GB* gb, char* out) {
742	memset(out, 0, 8);
743	const struct GBCartridge* cart = NULL;
744	if (gb->memory.rom) {
745		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
746	}
747	if (!cart) {
748		return;
749	}
750	if (cart->cgb == 0xC0) {
751		memcpy(out, "CGB-????", 8);
752	} else {
753		memcpy(out, "DMG-????", 8);
754	}
755	if (cart->oldLicensee == 0x33) {
756		memcpy(&out[4], cart->maker, 4);
757	}
758}
759
760void GBFrameEnded(struct GB* gb) {
761	GBSramClean(gb, gb->video.frameCounter);
762
763	if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
764		struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
765		size_t i;
766		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
767			struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
768			mCheatRefresh(device, cheats);
769		}
770	}
771
772	GBTestKeypadIRQ(gb);
773}
774
775enum GBModel GBNameToModel(const char* model) {
776	if (strcasecmp(model, "DMG") == 0) {
777		return GB_MODEL_DMG;
778	} else if (strcasecmp(model, "CGB") == 0) {
779		return GB_MODEL_CGB;
780	} else if (strcasecmp(model, "AGB") == 0) {
781		return GB_MODEL_AGB;
782	} else if (strcasecmp(model, "SGB") == 0) {
783		return GB_MODEL_SGB;
784	} else if (strcasecmp(model, "MGB") == 0) {
785		return GB_MODEL_MGB;
786	} else if (strcasecmp(model, "SGB2") == 0) {
787		return GB_MODEL_SGB2;
788	}
789	return GB_MODEL_AUTODETECT;
790}
791
792const char* GBModelToName(enum GBModel model) {
793	switch (model) {
794	case GB_MODEL_DMG:
795		return "DMG";
796	case GB_MODEL_SGB:
797		return "SGB";
798	case GB_MODEL_MGB:
799		return "MGB";
800	case GB_MODEL_SGB2:
801		return "SGB2";
802	case GB_MODEL_CGB:
803		return "CGB";
804	case GB_MODEL_AGB:
805		return "AGB";
806	default:
807	case GB_MODEL_AUTODETECT:
808		return NULL;
809	}
810}