all repos — mgba @ caea7e070015060014409ce804e1851f4983f800

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->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	GBSavedataUnmask(gb);
299	GBSramDeinit(gb);
300	if (gb->sramRealVf) {
301		gb->sramRealVf->close(gb->sramRealVf);
302	}
303	gb->sramRealVf = NULL;
304	gb->sramVf = NULL;
305	if (gb->memory.cam && gb->memory.cam->stopRequestImage) {
306		gb->memory.cam->stopRequestImage(gb->memory.cam);
307	}
308}
309
310void GBSynthesizeROM(struct VFile* vf) {
311	if (!vf) {
312		return;
313	}
314	const struct GBCartridge cart = {
315		.logo = { _knownHeader[0], _knownHeader[1], _knownHeader[2], _knownHeader[3]}
316	};
317
318	vf->seek(vf, 0x100, SEEK_SET);
319	vf->write(vf, &cart, sizeof(cart));
320}
321
322void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
323	gb->biosVf = vf;
324}
325
326void GBApplyPatch(struct GB* gb, struct Patch* patch) {
327	size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
328	if (!patchedSize) {
329		return;
330	}
331	if (patchedSize > GB_SIZE_CART_MAX) {
332		patchedSize = GB_SIZE_CART_MAX;
333	}
334	void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
335	if (!patch->applyPatch(patch, gb->memory.rom, gb->pristineRomSize, newRom, patchedSize)) {
336		mappedMemoryFree(newRom, GB_SIZE_CART_MAX);
337		return;
338	}
339	if (gb->romVf) {
340#ifndef FIXED_ROM_BUFFER
341		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
342#endif
343		gb->romVf->close(gb->romVf);
344		gb->romVf = NULL;
345	}
346	gb->isPristine = false;
347	if (gb->memory.romBase == gb->memory.rom) {
348		gb->memory.romBase = newRom;
349	}
350	gb->memory.rom = newRom;
351	gb->memory.romSize = patchedSize;
352	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
353	gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
354}
355
356void GBDestroy(struct GB* gb) {
357	GBUnloadROM(gb);
358
359	if (gb->biosVf) {
360		gb->biosVf->close(gb->biosVf);
361		gb->biosVf = 0;
362	}
363
364	GBMemoryDeinit(gb);
365	GBAudioDeinit(&gb->audio);
366	GBVideoDeinit(&gb->video);
367	GBSIODeinit(&gb->sio);
368	mCoreCallbacksListDeinit(&gb->coreCallbacks);
369}
370
371void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh) {
372	irqh->reset = GBReset;
373	irqh->processEvents = GBProcessEvents;
374	irqh->setInterrupts = GBSetInterrupts;
375	irqh->irqVector = GBIRQVector;
376	irqh->hitIllegal = GBIllegal;
377	irqh->stop = GBStop;
378	irqh->halt = GBHalt;
379}
380
381static uint32_t _GBBiosCRC32(struct VFile* vf) {
382	ssize_t size = vf->size(vf);
383	if (size <= 0 || size > GB_SIZE_CART_BANK0) {
384		return 0;
385	}
386	void* bios = vf->map(vf, size, MAP_READ);
387	uint32_t biosCrc = doCrc32(bios, size);
388	vf->unmap(vf, bios, size);
389	return biosCrc;
390}
391
392bool GBIsBIOS(struct VFile* vf) {
393	switch (_GBBiosCRC32(vf)) {
394	case DMG_BIOS_CHECKSUM:
395	case DMG_2_BIOS_CHECKSUM:
396	case MGB_BIOS_CHECKSUM:
397	case SGB_BIOS_CHECKSUM:
398	case CGB_BIOS_CHECKSUM:
399		return true;
400	default:
401		return false;
402	}
403}
404
405void GBReset(struct LR35902Core* cpu) {
406	struct GB* gb = (struct GB*) cpu->master;
407	gb->memory.romBase = gb->memory.rom;
408	GBDetectModel(gb);
409
410	if (gb->biosVf) {
411		if (!GBIsBIOS(gb->biosVf)) {
412			gb->biosVf->close(gb->biosVf);
413			gb->biosVf = NULL;
414		} else {
415			gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
416			gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
417			ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
418			memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
419			if (size > 0x100) {
420				memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
421			}
422
423			cpu->a = 0;
424			cpu->f.packed = 0;
425			cpu->c = 0;
426			cpu->e = 0;
427			cpu->h = 0;
428			cpu->l = 0;
429			cpu->sp = 0;
430			cpu->pc = 0;
431		}
432	}
433
434	cpu->b = 0;
435	cpu->d = 0;
436
437	gb->timer.internalDiv = 0;
438
439	gb->cpuBlocked = false;
440	gb->earlyExit = false;
441	gb->doubleSpeed = 0;
442
443	if (gb->yankedRomSize) {
444		gb->memory.romSize = gb->yankedRomSize;
445		gb->yankedRomSize = 0;
446	}
447
448	gb->sgbBit = -1;
449	gb->currentSgbBits = 0;
450	memset(gb->sgbPacket, 0, sizeof(gb->sgbPacket));
451
452	mTimingClear(&gb->timing);
453
454	GBMemoryReset(gb);
455	GBVideoReset(&gb->video);
456	GBTimerReset(&gb->timer);
457	if (!gb->biosVf) {
458		GBSkipBIOS(gb);
459	} else {
460		mTimingSchedule(&gb->timing, &gb->timer.event, 0);
461	}
462
463	GBIOReset(gb);
464	GBAudioReset(&gb->audio);
465	GBSIOReset(&gb->sio);
466
467	cpu->memory.setActiveRegion(cpu, cpu->pc);
468
469	GBSavedataUnmask(gb);
470}
471
472void GBSkipBIOS(struct GB* gb) {
473	struct LR35902Core* cpu = gb->cpu;
474	int nextDiv = 0;
475
476	switch (gb->model) {
477	case GB_MODEL_AUTODETECT: // Silence warnings
478		gb->model = GB_MODEL_DMG;
479	case GB_MODEL_DMG:
480		cpu->a = 1;
481		cpu->f.packed = 0xB0;
482		cpu->c = 0x13;
483		cpu->e = 0xD8;
484		cpu->h = 1;
485		cpu->l = 0x4D;
486		gb->timer.internalDiv = 0xABC;
487		nextDiv = 4;
488		break;
489	case GB_MODEL_SGB:
490		cpu->a = 1;
491		cpu->f.packed = 0x00;
492		cpu->c = 0x14;
493		cpu->e = 0x00;
494		cpu->h = 0xC0;
495		cpu->l = 0x60;
496		gb->timer.internalDiv = 0xABC;
497		nextDiv = 4;
498		break;
499	case GB_MODEL_MGB:
500		cpu->a = 0xFF;
501		cpu->f.packed = 0xB0;
502		cpu->c = 0x13;
503		cpu->e = 0xD8;
504		cpu->h = 1;
505		cpu->l = 0x4D;
506		gb->timer.internalDiv = 0xABC;
507		nextDiv = 4;
508		break;
509	case GB_MODEL_SGB2:
510		cpu->a = 0xFF;
511		cpu->f.packed = 0x00;
512		cpu->c = 0x14;
513		cpu->e = 0x00;
514		cpu->h = 0xC0;
515		cpu->l = 0x60;
516		gb->timer.internalDiv = 0xABC;
517		nextDiv = 4;
518		break;
519	case GB_MODEL_AGB:
520		cpu->a = 0x11;
521		cpu->b = 1;
522		cpu->f.packed = 0x00;
523		cpu->c = 0;
524		cpu->e = 0x08;
525		cpu->h = 0;
526		cpu->l = 0x7C;
527		gb->timer.internalDiv = 0x1EA;
528		nextDiv = 0xC;
529		break;
530	case GB_MODEL_CGB:
531		cpu->a = 0x11;
532		cpu->f.packed = 0x80;
533		cpu->c = 0;
534		cpu->e = 0x08;
535		cpu->h = 0;
536		cpu->l = 0x7C;
537		gb->timer.internalDiv = 0x1EA;
538		nextDiv = 0xC;
539		break;
540	}
541
542	cpu->sp = 0xFFFE;
543	cpu->pc = 0x100;
544
545	mTimingDeschedule(&gb->timing, &gb->timer.event);
546	mTimingSchedule(&gb->timing, &gb->timer.event, 0);
547
548	if (gb->biosVf) {
549		GBUnmapBIOS(gb);
550	}
551}
552
553void GBUnmapBIOS(struct GB* gb) {
554	if (gb->memory.romBase < gb->memory.rom || gb->memory.romBase > &gb->memory.rom[gb->memory.romSize - 1]) {
555		free(gb->memory.romBase);
556		gb->memory.romBase = gb->memory.rom;
557	}
558}
559
560void GBDetectModel(struct GB* gb) {
561	if (gb->model != GB_MODEL_AUTODETECT) {
562		return;
563	}
564	if (gb->biosVf) {
565		switch (_GBBiosCRC32(gb->biosVf)) {
566		case DMG_BIOS_CHECKSUM:
567		case DMG_2_BIOS_CHECKSUM:
568			gb->model = GB_MODEL_DMG;
569			break;
570		case MGB_BIOS_CHECKSUM:
571			gb->model = GB_MODEL_MGB;
572			break;
573		case SGB_BIOS_CHECKSUM:
574			gb->model = GB_MODEL_SGB;
575			break;
576		case CGB_BIOS_CHECKSUM:
577			gb->model = GB_MODEL_CGB;
578			break;
579		default:
580			gb->biosVf->close(gb->biosVf);
581			gb->biosVf = NULL;
582		}
583	}
584	if (gb->model == GB_MODEL_AUTODETECT && gb->memory.rom) {
585		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
586		if (cart->cgb & 0x80) {
587			gb->model = GB_MODEL_CGB;
588		} else if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
589			gb->model = GB_MODEL_SGB;
590		} else {
591			gb->model = GB_MODEL_DMG;
592		}
593	}
594
595	switch (gb->model) {
596	case GB_MODEL_DMG:
597	case GB_MODEL_SGB:
598	case GB_MODEL_AUTODETECT: //Silence warnings
599		gb->audio.style = GB_AUDIO_DMG;
600		break;
601	case GB_MODEL_MGB:
602	case GB_MODEL_SGB2:
603		gb->audio.style = GB_AUDIO_MGB;
604		break;
605	case GB_MODEL_AGB:
606	case GB_MODEL_CGB:
607		gb->audio.style = GB_AUDIO_CGB;
608		break;
609	}
610}
611
612void GBUpdateIRQs(struct GB* gb) {
613	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
614	if (!irqs) {
615		return;
616	}
617	gb->cpu->halted = false;
618
619	if (!gb->memory.ime || gb->cpu->irqPending) {
620		return;
621	}
622	LR35902RaiseIRQ(gb->cpu);
623}
624
625void GBProcessEvents(struct LR35902Core* cpu) {
626	struct GB* gb = (struct GB*) cpu->master;
627	do {
628		int32_t cycles = cpu->cycles;
629		int32_t nextEvent;
630
631		cpu->cycles = 0;
632		cpu->nextEvent = INT_MAX;
633
634		nextEvent = cycles;
635		do {
636			nextEvent = mTimingTick(&gb->timing, nextEvent);
637		} while (gb->cpuBlocked);
638		cpu->nextEvent = nextEvent;
639
640		if (gb->earlyExit) {
641			gb->earlyExit = false;
642			break;
643		}
644		if (cpu->halted) {
645			cpu->cycles = cpu->nextEvent;
646			if (!gb->memory.ie || !gb->memory.ime) {
647				break;
648			}
649		}
650	} while (cpu->cycles >= cpu->nextEvent);
651}
652
653void GBSetInterrupts(struct LR35902Core* cpu, bool enable) {
654	struct GB* gb = (struct GB*) cpu->master;
655	if (!enable) {
656		gb->memory.ime = enable;
657		mTimingDeschedule(&gb->timing, &gb->eiPending);
658		GBUpdateIRQs(gb);
659	} else {
660		mTimingDeschedule(&gb->timing, &gb->eiPending);
661		mTimingSchedule(&gb->timing, &gb->eiPending, 4);
662	}
663}
664
665uint16_t GBIRQVector(struct LR35902Core* cpu) {
666	struct GB* gb = (struct GB*) cpu->master;
667	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
668
669	if (irqs & (1 << GB_IRQ_VBLANK)) {
670		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
671		return GB_VECTOR_VBLANK;
672	}
673	if (irqs & (1 << GB_IRQ_LCDSTAT)) {
674		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
675		return GB_VECTOR_LCDSTAT;
676	}
677	if (irqs & (1 << GB_IRQ_TIMER)) {
678		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
679		return GB_VECTOR_TIMER;
680	}
681	if (irqs & (1 << GB_IRQ_SIO)) {
682		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
683		return GB_VECTOR_SIO;
684	}
685	if (irqs & (1 << GB_IRQ_KEYPAD)) {
686		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
687		return GB_VECTOR_KEYPAD;
688	}
689	return 0;
690}
691
692static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate) {
693	UNUSED(timing);
694	UNUSED(cyclesLate);
695	struct GB* gb = user;
696	gb->memory.ime = true;
697	GBUpdateIRQs(gb);
698}
699
700void GBHalt(struct LR35902Core* cpu) {
701	struct GB* gb = (struct GB*) cpu->master;
702	if (!(gb->memory.ie & gb->memory.io[REG_IF])) {
703		cpu->cycles = cpu->nextEvent;
704		cpu->halted = true;
705	} else if (gb->model < GB_MODEL_CGB) {
706		mLOG(GB, STUB, "Unimplemented HALT bug");
707	}
708}
709
710void GBStop(struct LR35902Core* cpu) {
711	struct GB* gb = (struct GB*) cpu->master;
712	if (cpu->bus) {
713		mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X", cpu->pc, cpu->bus);
714	}
715	if (gb->memory.io[REG_KEY1] & 1) {
716		gb->doubleSpeed ^= 1;
717		gb->audio.timingFactor = gb->doubleSpeed + 1;
718		gb->memory.io[REG_KEY1] = 0;
719		gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
720	} else if (cpu->bus) {
721#ifdef USE_DEBUGGERS
722		if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
723			struct mDebuggerEntryInfo info = {
724				.address = cpu->pc - 1,
725				.type.bp.opcode = 0x1000 | cpu->bus
726			};
727			mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
728		}
729#endif
730		// Hang forever
731		gb->memory.ime = 0;
732		cpu->pc -= 2;
733	}
734	// TODO: Actually stop
735}
736
737void GBIllegal(struct LR35902Core* cpu) {
738	struct GB* gb = (struct GB*) cpu->master;
739	mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X", cpu->pc, cpu->bus);
740#ifdef USE_DEBUGGERS
741	if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
742		struct mDebuggerEntryInfo info = {
743			.address = cpu->pc,
744			.type.bp.opcode = cpu->bus
745		};
746		mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
747	}
748#endif
749	// Hang forever
750	gb->memory.ime = 0;
751	--cpu->pc;
752}
753
754bool GBIsROM(struct VFile* vf) {
755	if (!vf) {
756		return false;
757	}
758	vf->seek(vf, 0x104, SEEK_SET);
759	uint8_t header[4];
760
761	if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
762		return false;
763	}
764	if (memcmp(header, _knownHeader, sizeof(header))) {
765		return false;
766	}
767	return true;
768}
769
770void GBGetGameTitle(const struct GB* gb, char* out) {
771	const struct GBCartridge* cart = NULL;
772	if (gb->memory.rom) {
773		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
774	}
775	if (!cart) {
776		return;
777	}
778	if (cart->oldLicensee != 0x33) {
779		memcpy(out, cart->titleLong, 16);
780	} else {
781		memcpy(out, cart->titleShort, 11);
782	}
783}
784
785void GBGetGameCode(const struct GB* gb, char* out) {
786	memset(out, 0, 8);
787	const struct GBCartridge* cart = NULL;
788	if (gb->memory.rom) {
789		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
790	}
791	if (!cart) {
792		return;
793	}
794	if (cart->cgb == 0xC0) {
795		memcpy(out, "CGB-????", 8);
796	} else {
797		memcpy(out, "DMG-????", 8);
798	}
799	if (cart->oldLicensee == 0x33) {
800		memcpy(&out[4], cart->maker, 4);
801	}
802}
803
804void GBFrameEnded(struct GB* gb) {
805	GBSramClean(gb, gb->video.frameCounter);
806
807	if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
808		struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
809		size_t i;
810		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
811			struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
812			mCheatRefresh(device, cheats);
813		}
814	}
815
816	GBTestKeypadIRQ(gb);
817}
818
819enum GBModel GBNameToModel(const char* model) {
820	if (strcasecmp(model, "DMG") == 0) {
821		return GB_MODEL_DMG;
822	} else if (strcasecmp(model, "CGB") == 0) {
823		return GB_MODEL_CGB;
824	} else if (strcasecmp(model, "AGB") == 0) {
825		return GB_MODEL_AGB;
826	} else if (strcasecmp(model, "SGB") == 0) {
827		return GB_MODEL_SGB;
828	} else if (strcasecmp(model, "MGB") == 0) {
829		return GB_MODEL_MGB;
830	} else if (strcasecmp(model, "SGB2") == 0) {
831		return GB_MODEL_SGB2;
832	}
833	return GB_MODEL_AUTODETECT;
834}
835
836const char* GBModelToName(enum GBModel model) {
837	switch (model) {
838	case GB_MODEL_DMG:
839		return "DMG";
840	case GB_MODEL_SGB:
841		return "SGB";
842	case GB_MODEL_MGB:
843		return "MGB";
844	case GB_MODEL_SGB2:
845		return "SGB2";
846	case GB_MODEL_CGB:
847		return "CGB";
848	case GB_MODEL_AGB:
849		return "AGB";
850	default:
851	case GB_MODEL_AUTODETECT:
852		return NULL;
853	}
854}