all repos — mgba @ 4eeff830ed69a1a1207b41b94e98e8dfbe25964c

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