all repos — mgba @ 51f9a76ab212514ba8035a85b60af4b963fabc11

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		GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
161	}
162	return vf;
163}
164
165void GBResizeSram(struct GB* gb, size_t size) {
166	if (gb->memory.sram && size <= gb->sramSize) {
167		return;
168	}
169	struct VFile* vf = gb->sramVf;
170	if (vf) {
171		if (vf == gb->sramRealVf) {
172			ssize_t vfSize = vf->size(vf);
173			if (vfSize >= 0 && (size_t) vfSize < size) {
174				uint8_t extdataBuffer[0x100];
175				if (vfSize & 0xFF) {
176					vf->seek(vf, -(vfSize & 0xFF), SEEK_END);
177					vf->read(vf, extdataBuffer, vfSize & 0xFF);
178				}
179				if (gb->memory.sram) {
180					vf->unmap(vf, gb->memory.sram, gb->sramSize);
181				}
182				vf->truncate(vf, size + (vfSize & 0xFF));
183				if (vfSize & 0xFF) {
184					vf->seek(vf, size, SEEK_SET);
185					vf->write(vf, extdataBuffer, vfSize & 0xFF);
186				}
187				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
188				memset(&gb->memory.sram[gb->sramSize], 0xFF, size - gb->sramSize);
189			} else if (size > gb->sramSize || !gb->memory.sram) {
190				if (gb->memory.sram) {
191					vf->unmap(vf, gb->memory.sram, gb->sramSize);
192				}
193				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
194			}
195		} else {
196			if (gb->memory.sram) {
197				vf->unmap(vf, gb->memory.sram, gb->sramSize);
198			}
199			gb->memory.sram = vf->map(vf, size, MAP_READ);
200		}
201		if (gb->memory.sram == (void*) -1) {
202			gb->memory.sram = NULL;
203		}
204	} else {
205		uint8_t* newSram = anonymousMemoryMap(size);
206		if (gb->memory.sram) {
207			if (size > gb->sramSize) {
208				memcpy(newSram, gb->memory.sram, gb->sramSize);
209				memset(&newSram[gb->sramSize], 0xFF, size - gb->sramSize);
210			} else {
211				memcpy(newSram, gb->memory.sram, size);
212			}
213			mappedMemoryFree(gb->memory.sram, gb->sramSize);
214		} else {
215			memset(newSram, 0xFF, size);
216		}
217		gb->memory.sram = newSram;
218	}
219	if (gb->sramSize < size) {
220		gb->sramSize = size;
221	}
222}
223
224void GBSramClean(struct GB* gb, uint32_t frameCount) {
225	// TODO: Share with GBASavedataClean
226	if (!gb->sramVf) {
227		return;
228	}
229	if (gb->sramDirty & GB_SRAM_DIRT_NEW) {
230		gb->sramDirtAge = frameCount;
231		gb->sramDirty &= ~GB_SRAM_DIRT_NEW;
232		if (!(gb->sramDirty & GB_SRAM_DIRT_SEEN)) {
233			gb->sramDirty |= GB_SRAM_DIRT_SEEN;
234		}
235	} else if ((gb->sramDirty & GB_SRAM_DIRT_SEEN) && frameCount - gb->sramDirtAge > CLEANUP_THRESHOLD) {
236		if (gb->sramMaskWriteback) {
237			GBSavedataUnmask(gb);
238		}
239		if (gb->memory.mbcType == GB_MBC3_RTC) {
240			GBMBCRTCWrite(gb);
241		}
242		gb->sramDirty = 0;
243		if (gb->memory.sram && gb->sramVf->sync(gb->sramVf, gb->memory.sram, gb->sramSize)) {
244			mLOG(GB_MEM, INFO, "Savedata synced");
245		} else {
246			mLOG(GB_MEM, INFO, "Savedata failed to sync!");
247		}
248	}
249}
250
251void GBSavedataMask(struct GB* gb, struct VFile* vf, bool writeback) {
252	GBSramDeinit(gb);
253	gb->sramVf = vf;
254	gb->sramMaskWriteback = writeback;
255	gb->memory.sram = vf->map(vf, gb->sramSize, MAP_READ);
256	GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
257}
258
259void GBSavedataUnmask(struct GB* gb) {
260	if (!gb->sramRealVf || gb->sramVf == gb->sramRealVf) {
261		return;
262	}
263	struct VFile* vf = gb->sramVf;
264	GBSramDeinit(gb);
265	gb->sramVf = gb->sramRealVf;
266	gb->memory.sram = gb->sramVf->map(gb->sramVf, gb->sramSize, MAP_WRITE);
267	if (gb->sramMaskWriteback) {
268		vf->seek(vf, 0, SEEK_SET);
269		vf->read(vf, gb->memory.sram, gb->sramSize);
270		gb->sramMaskWriteback = false;
271	}
272	GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
273	vf->close(vf);
274}
275
276void GBUnloadROM(struct GB* gb) {
277	// TODO: Share with GBAUnloadROM
278	if (gb->memory.rom && gb->memory.romBase != gb->memory.rom && !gb->isPristine) {
279		free(gb->memory.romBase);
280	}
281	if (gb->memory.rom && !gb->isPristine) {
282		if (gb->yankedRomSize) {
283			gb->yankedRomSize = 0;
284		}
285		mappedMemoryFree(gb->memory.rom, GB_SIZE_CART_MAX);
286	}
287
288	if (gb->romVf) {
289#ifndef FIXED_ROM_BUFFER
290		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
291#endif
292		gb->romVf->close(gb->romVf);
293		gb->romVf = NULL;
294	}
295	gb->memory.rom = NULL;
296	gb->memory.mbcType = GB_MBC_AUTODETECT;
297	gb->isPristine = false;
298
299	gb->sramMaskWriteback = false;
300	GBSramDeinit(gb);
301	if (gb->sramRealVf) {
302		gb->sramRealVf->close(gb->sramRealVf);
303	}
304	gb->sramRealVf = NULL;
305	gb->sramVf = NULL;
306	if (gb->memory.cam && gb->memory.cam->stopRequestImage) {
307		gb->memory.cam->stopRequestImage(gb->memory.cam);
308	}
309}
310
311void GBSynthesizeROM(struct VFile* vf) {
312	if (!vf) {
313		return;
314	}
315	const struct GBCartridge cart = {
316		.logo = { _knownHeader[0], _knownHeader[1], _knownHeader[2], _knownHeader[3]}
317	};
318
319	vf->seek(vf, 0x100, SEEK_SET);
320	vf->write(vf, &cart, sizeof(cart));
321}
322
323void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
324	gb->biosVf = vf;
325}
326
327void GBApplyPatch(struct GB* gb, struct Patch* patch) {
328	size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
329	if (!patchedSize) {
330		return;
331	}
332	if (patchedSize > GB_SIZE_CART_MAX) {
333		patchedSize = GB_SIZE_CART_MAX;
334	}
335	void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
336	if (!patch->applyPatch(patch, gb->memory.rom, gb->pristineRomSize, newRom, patchedSize)) {
337		mappedMemoryFree(newRom, GB_SIZE_CART_MAX);
338		return;
339	}
340	if (gb->romVf) {
341#ifndef FIXED_ROM_BUFFER
342		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
343#endif
344		gb->romVf->close(gb->romVf);
345		gb->romVf = NULL;
346	}
347	gb->isPristine = false;
348	if (gb->memory.romBase == gb->memory.rom) {
349		gb->memory.romBase = newRom;
350	}
351	gb->memory.rom = newRom;
352	gb->memory.romSize = patchedSize;
353	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
354	gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
355}
356
357void GBDestroy(struct GB* gb) {
358	GBUnloadROM(gb);
359
360	if (gb->biosVf) {
361		gb->biosVf->close(gb->biosVf);
362		gb->biosVf = 0;
363	}
364
365	GBMemoryDeinit(gb);
366	GBAudioDeinit(&gb->audio);
367	GBVideoDeinit(&gb->video);
368	GBSIODeinit(&gb->sio);
369	mCoreCallbacksListDeinit(&gb->coreCallbacks);
370}
371
372void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh) {
373	irqh->reset = GBReset;
374	irqh->processEvents = GBProcessEvents;
375	irqh->setInterrupts = GBSetInterrupts;
376	irqh->irqVector = GBIRQVector;
377	irqh->hitIllegal = GBIllegal;
378	irqh->stop = GBStop;
379	irqh->halt = GBHalt;
380}
381
382static uint32_t _GBBiosCRC32(struct VFile* vf) {
383	ssize_t size = vf->size(vf);
384	if (size <= 0 || size > GB_SIZE_CART_BANK0) {
385		return 0;
386	}
387	void* bios = vf->map(vf, size, MAP_READ);
388	uint32_t biosCrc = doCrc32(bios, size);
389	vf->unmap(vf, bios, size);
390	return biosCrc;
391}
392
393bool GBIsBIOS(struct VFile* vf) {
394	switch (_GBBiosCRC32(vf)) {
395	case DMG_BIOS_CHECKSUM:
396	case DMG_2_BIOS_CHECKSUM:
397	case MGB_BIOS_CHECKSUM:
398	case SGB_BIOS_CHECKSUM:
399	case CGB_BIOS_CHECKSUM:
400		return true;
401	default:
402		return false;
403	}
404}
405
406void GBReset(struct LR35902Core* cpu) {
407	struct GB* gb = (struct GB*) cpu->master;
408	gb->memory.romBase = gb->memory.rom;
409	GBDetectModel(gb);
410
411	if (gb->biosVf) {
412		if (!GBIsBIOS(gb->biosVf)) {
413			gb->biosVf->close(gb->biosVf);
414			gb->biosVf = NULL;
415		} else {
416			gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
417			gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
418			ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
419			memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
420			if (size > 0x100) {
421				memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
422			}
423
424			cpu->a = 0;
425			cpu->f.packed = 0;
426			cpu->c = 0;
427			cpu->e = 0;
428			cpu->h = 0;
429			cpu->l = 0;
430			cpu->sp = 0;
431			cpu->pc = 0;
432		}
433	}
434
435	cpu->b = 0;
436	cpu->d = 0;
437
438	gb->timer.internalDiv = 0;
439
440	gb->cpuBlocked = false;
441	gb->earlyExit = false;
442	gb->doubleSpeed = 0;
443
444	if (gb->yankedRomSize) {
445		gb->memory.romSize = gb->yankedRomSize;
446		gb->yankedRomSize = 0;
447	}
448
449	gb->sgbBit = -1;
450	gb->sgbControllers = 0;
451	gb->sgbCurrentController = 0;
452	gb->currentSgbBits = 0;
453	memset(gb->sgbPacket, 0, sizeof(gb->sgbPacket));
454
455	mTimingClear(&gb->timing);
456
457	GBMemoryReset(gb);
458	GBVideoReset(&gb->video);
459	GBTimerReset(&gb->timer);
460	if (!gb->biosVf) {
461		GBSkipBIOS(gb);
462	} else {
463		mTimingSchedule(&gb->timing, &gb->timer.event, 0);
464	}
465
466	GBIOReset(gb);
467	GBAudioReset(&gb->audio);
468	GBSIOReset(&gb->sio);
469
470	cpu->memory.setActiveRegion(cpu, cpu->pc);
471
472	gb->sramMaskWriteback = false;
473	GBSavedataUnmask(gb);
474}
475
476void GBSkipBIOS(struct GB* gb) {
477	struct LR35902Core* cpu = gb->cpu;
478	int nextDiv = 0;
479
480	switch (gb->model) {
481	case GB_MODEL_AUTODETECT: // Silence warnings
482		gb->model = GB_MODEL_DMG;
483		// Fall through
484	case GB_MODEL_DMG:
485		cpu->a = 1;
486		cpu->f.packed = 0xB0;
487		cpu->c = 0x13;
488		cpu->e = 0xD8;
489		cpu->h = 1;
490		cpu->l = 0x4D;
491		gb->timer.internalDiv = 0xABC;
492		nextDiv = 4;
493		break;
494	case GB_MODEL_SGB:
495		cpu->a = 1;
496		cpu->f.packed = 0x00;
497		cpu->c = 0x14;
498		cpu->e = 0x00;
499		cpu->h = 0xC0;
500		cpu->l = 0x60;
501		gb->timer.internalDiv = 0xABC;
502		nextDiv = 4;
503		break;
504	case GB_MODEL_MGB:
505		cpu->a = 0xFF;
506		cpu->f.packed = 0xB0;
507		cpu->c = 0x13;
508		cpu->e = 0xD8;
509		cpu->h = 1;
510		cpu->l = 0x4D;
511		gb->timer.internalDiv = 0xABC;
512		nextDiv = 4;
513		break;
514	case GB_MODEL_SGB2:
515		cpu->a = 0xFF;
516		cpu->f.packed = 0x00;
517		cpu->c = 0x14;
518		cpu->e = 0x00;
519		cpu->h = 0xC0;
520		cpu->l = 0x60;
521		gb->timer.internalDiv = 0xABC;
522		nextDiv = 4;
523		break;
524	case GB_MODEL_AGB:
525		cpu->a = 0x11;
526		cpu->b = 1;
527		cpu->f.packed = 0x00;
528		cpu->c = 0;
529		cpu->e = 0x08;
530		cpu->h = 0;
531		cpu->l = 0x7C;
532		gb->timer.internalDiv = 0x1EA;
533		nextDiv = 0xC;
534		break;
535	case GB_MODEL_CGB:
536		cpu->a = 0x11;
537		cpu->f.packed = 0x80;
538		cpu->c = 0;
539		cpu->e = 0x08;
540		cpu->h = 0;
541		cpu->l = 0x7C;
542		gb->timer.internalDiv = 0x1EA;
543		nextDiv = 0xC;
544		break;
545	}
546
547	cpu->sp = 0xFFFE;
548	cpu->pc = 0x100;
549
550	mTimingDeschedule(&gb->timing, &gb->timer.event);
551	mTimingSchedule(&gb->timing, &gb->timer.event, 0);
552
553	GBIOWrite(gb, REG_LCDC, 0x91);
554
555	if (gb->biosVf) {
556		GBUnmapBIOS(gb);
557	}
558}
559
560void GBUnmapBIOS(struct GB* gb) {
561	if (gb->memory.romBase < gb->memory.rom || gb->memory.romBase > &gb->memory.rom[gb->memory.romSize - 1]) {
562		free(gb->memory.romBase);
563		gb->memory.romBase = gb->memory.rom;
564	}
565	// XXX: Force AGB registers for AGB-mode
566	if (gb->model == GB_MODEL_AGB && gb->cpu->pc == 0x100) {
567		gb->cpu->b = 1;
568	}
569}
570
571void GBDetectModel(struct GB* gb) {
572	if (gb->model != GB_MODEL_AUTODETECT) {
573		return;
574	}
575	if (gb->biosVf) {
576		switch (_GBBiosCRC32(gb->biosVf)) {
577		case DMG_BIOS_CHECKSUM:
578		case DMG_2_BIOS_CHECKSUM:
579			gb->model = GB_MODEL_DMG;
580			break;
581		case MGB_BIOS_CHECKSUM:
582			gb->model = GB_MODEL_MGB;
583			break;
584		case SGB_BIOS_CHECKSUM:
585			gb->model = GB_MODEL_SGB;
586			break;
587		case CGB_BIOS_CHECKSUM:
588			gb->model = GB_MODEL_CGB;
589			break;
590		default:
591			gb->biosVf->close(gb->biosVf);
592			gb->biosVf = NULL;
593		}
594	}
595	if (gb->model == GB_MODEL_AUTODETECT && gb->memory.rom) {
596		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
597		if (cart->cgb & 0x80) {
598			gb->model = GB_MODEL_CGB;
599		} else if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
600			gb->model = GB_MODEL_SGB;
601		} else {
602			gb->model = GB_MODEL_DMG;
603		}
604	}
605
606	switch (gb->model) {
607	case GB_MODEL_DMG:
608	case GB_MODEL_SGB:
609	case GB_MODEL_AUTODETECT: //Silence warnings
610		gb->audio.style = GB_AUDIO_DMG;
611		break;
612	case GB_MODEL_MGB:
613	case GB_MODEL_SGB2:
614		gb->audio.style = GB_AUDIO_MGB;
615		break;
616	case GB_MODEL_AGB:
617	case GB_MODEL_CGB:
618		gb->audio.style = GB_AUDIO_CGB;
619		break;
620	}
621}
622
623void GBUpdateIRQs(struct GB* gb) {
624	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
625	if (!irqs) {
626		gb->cpu->irqPending = false;
627		return;
628	}
629	gb->cpu->halted = false;
630
631	if (!gb->memory.ime) {
632		gb->cpu->irqPending = false;
633		return;
634	}
635	if (gb->cpu->irqPending) {
636		return;
637	}
638	LR35902RaiseIRQ(gb->cpu);
639}
640
641void GBProcessEvents(struct LR35902Core* cpu) {
642	struct GB* gb = (struct GB*) cpu->master;
643	do {
644		int32_t cycles = cpu->cycles;
645		int32_t nextEvent;
646
647		cpu->cycles = 0;
648		cpu->nextEvent = INT_MAX;
649
650		nextEvent = cycles;
651		do {
652			nextEvent = mTimingTick(&gb->timing, nextEvent);
653		} while (gb->cpuBlocked);
654		cpu->nextEvent = nextEvent;
655
656		if (cpu->halted) {
657			cpu->cycles = cpu->nextEvent;
658			if (!gb->memory.ie || !gb->memory.ime) {
659				break;
660			}
661		}
662		if (gb->earlyExit) {
663			break;
664		}
665	} while (cpu->cycles >= cpu->nextEvent);
666	gb->earlyExit = false;
667}
668
669void GBSetInterrupts(struct LR35902Core* cpu, bool enable) {
670	struct GB* gb = (struct GB*) cpu->master;
671	mTimingDeschedule(&gb->timing, &gb->eiPending);
672	if (!enable) {
673		gb->memory.ime = false;
674		GBUpdateIRQs(gb);
675	} else {
676		mTimingSchedule(&gb->timing, &gb->eiPending, 4);
677	}
678}
679
680uint16_t GBIRQVector(struct LR35902Core* cpu) {
681	struct GB* gb = (struct GB*) cpu->master;
682	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
683
684	if (irqs & (1 << GB_IRQ_VBLANK)) {
685		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
686		return GB_VECTOR_VBLANK;
687	}
688	if (irqs & (1 << GB_IRQ_LCDSTAT)) {
689		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
690		return GB_VECTOR_LCDSTAT;
691	}
692	if (irqs & (1 << GB_IRQ_TIMER)) {
693		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
694		return GB_VECTOR_TIMER;
695	}
696	if (irqs & (1 << GB_IRQ_SIO)) {
697		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
698		return GB_VECTOR_SIO;
699	}
700	if (irqs & (1 << GB_IRQ_KEYPAD)) {
701		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
702		return GB_VECTOR_KEYPAD;
703	}
704	return 0;
705}
706
707static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate) {
708	UNUSED(timing);
709	UNUSED(cyclesLate);
710	struct GB* gb = user;
711	gb->memory.ime = true;
712	GBUpdateIRQs(gb);
713}
714
715void GBHalt(struct LR35902Core* cpu) {
716	struct GB* gb = (struct GB*) cpu->master;
717	if (!(gb->memory.ie & gb->memory.io[REG_IF])) {
718		cpu->cycles = cpu->nextEvent;
719		cpu->halted = true;
720	} else if (gb->model < GB_MODEL_CGB) {
721		mLOG(GB, STUB, "Unimplemented HALT bug");
722	}
723}
724
725void GBStop(struct LR35902Core* cpu) {
726	struct GB* gb = (struct GB*) cpu->master;
727	if (cpu->bus) {
728		mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X", cpu->pc, cpu->bus);
729	}
730	if (gb->memory.io[REG_KEY1] & 1) {
731		gb->doubleSpeed ^= 1;
732		gb->audio.timingFactor = gb->doubleSpeed + 1;
733		gb->memory.io[REG_KEY1] = 0;
734		gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
735	} else if (cpu->bus) {
736#ifdef USE_DEBUGGERS
737		if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
738			struct mDebuggerEntryInfo info = {
739				.address = cpu->pc - 1,
740				.type.bp.opcode = 0x1000 | cpu->bus
741			};
742			mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
743		}
744#endif
745		// Hang forever
746		gb->memory.ime = 0;
747		cpu->pc -= 2;
748	}
749	// TODO: Actually stop
750}
751
752void GBIllegal(struct LR35902Core* cpu) {
753	struct GB* gb = (struct GB*) cpu->master;
754	mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X", cpu->pc, cpu->bus);
755#ifdef USE_DEBUGGERS
756	if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
757		struct mDebuggerEntryInfo info = {
758			.address = cpu->pc,
759			.type.bp.opcode = cpu->bus
760		};
761		mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
762	}
763#endif
764	// Hang forever
765	gb->memory.ime = 0;
766	--cpu->pc;
767}
768
769bool GBIsROM(struct VFile* vf) {
770	if (!vf) {
771		return false;
772	}
773	vf->seek(vf, 0x104, SEEK_SET);
774	uint8_t header[4];
775
776	if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
777		return false;
778	}
779	if (memcmp(header, _knownHeader, sizeof(header))) {
780		return false;
781	}
782	return true;
783}
784
785void GBGetGameTitle(const struct GB* gb, char* out) {
786	const struct GBCartridge* cart = NULL;
787	if (gb->memory.rom) {
788		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
789	}
790	if (!cart) {
791		return;
792	}
793	if (cart->oldLicensee != 0x33) {
794		memcpy(out, cart->titleLong, 16);
795	} else {
796		memcpy(out, cart->titleShort, 11);
797	}
798}
799
800void GBGetGameCode(const struct GB* gb, char* out) {
801	memset(out, 0, 8);
802	const struct GBCartridge* cart = NULL;
803	if (gb->memory.rom) {
804		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
805	}
806	if (!cart) {
807		return;
808	}
809	if (cart->cgb == 0xC0) {
810		memcpy(out, "CGB-????", 8);
811	} else {
812		memcpy(out, "DMG-????", 8);
813	}
814	if (cart->oldLicensee == 0x33) {
815		memcpy(&out[4], cart->maker, 4);
816	}
817}
818
819void GBFrameStarted(struct GB* gb) {
820	GBTestKeypadIRQ(gb);
821
822	size_t c;
823	for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
824		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
825		if (callbacks->videoFrameStarted) {
826			callbacks->videoFrameStarted(callbacks->context);
827		}
828	}
829}
830
831void GBFrameEnded(struct GB* gb) {
832	GBSramClean(gb, gb->video.frameCounter);
833
834	if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
835		struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
836		size_t i;
837		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
838			struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
839			mCheatRefresh(device, cheats);
840		}
841	}
842
843	// TODO: Move to common code
844	if (gb->stream && gb->stream->postVideoFrame) {
845		const color_t* pixels;
846		size_t stride;
847		gb->video.renderer->getPixels(gb->video.renderer, &stride, (const void**) &pixels);
848		gb->stream->postVideoFrame(gb->stream, pixels, stride);
849	}
850
851	size_t c;
852	for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
853		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
854		if (callbacks->videoFrameEnded) {
855			callbacks->videoFrameEnded(callbacks->context);
856		}
857	}
858}
859
860enum GBModel GBNameToModel(const char* model) {
861	if (strcasecmp(model, "DMG") == 0) {
862		return GB_MODEL_DMG;
863	} else if (strcasecmp(model, "CGB") == 0) {
864		return GB_MODEL_CGB;
865	} else if (strcasecmp(model, "AGB") == 0) {
866		return GB_MODEL_AGB;
867	} else if (strcasecmp(model, "SGB") == 0) {
868		return GB_MODEL_SGB;
869	} else if (strcasecmp(model, "MGB") == 0) {
870		return GB_MODEL_MGB;
871	} else if (strcasecmp(model, "SGB2") == 0) {
872		return GB_MODEL_SGB2;
873	}
874	return GB_MODEL_AUTODETECT;
875}
876
877const char* GBModelToName(enum GBModel model) {
878	switch (model) {
879	case GB_MODEL_DMG:
880		return "DMG";
881	case GB_MODEL_SGB:
882		return "SGB";
883	case GB_MODEL_MGB:
884		return "MGB";
885	case GB_MODEL_SGB2:
886		return "SGB2";
887	case GB_MODEL_CGB:
888		return "CGB";
889	case GB_MODEL_AGB:
890		return "AGB";
891	default:
892	case GB_MODEL_AUTODETECT:
893		return NULL;
894	}
895}