all repos — mgba @ d6e9315ff568cd4906c2cdf25786cbe5a6e6fc17

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 SGB2_BIOS_CHECKSUM 0X53D0DD63
 34#define CGB_BIOS_CHECKSUM 0x41884E46
 35
 36mLOG_DEFINE_CATEGORY(GB, "GB", "gb");
 37
 38static void GBInit(void* cpu, struct mCPUComponent* component);
 39static void GBDeinit(struct mCPUComponent* component);
 40static void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh);
 41static void GBProcessEvents(struct LR35902Core* cpu);
 42static void GBSetInterrupts(struct LR35902Core* cpu, bool enable);
 43static uint16_t GBIRQVector(struct LR35902Core* cpu);
 44static void GBIllegal(struct LR35902Core* cpu);
 45static void GBStop(struct LR35902Core* cpu);
 46
 47static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate);
 48
 49void GBCreate(struct GB* gb) {
 50	gb->d.id = GB_COMPONENT_MAGIC;
 51	gb->d.init = GBInit;
 52	gb->d.deinit = GBDeinit;
 53}
 54
 55static void GBInit(void* cpu, struct mCPUComponent* component) {
 56	struct GB* gb = (struct GB*) component;
 57	gb->cpu = cpu;
 58	gb->sync = NULL;
 59
 60	GBInterruptHandlerInit(&gb->cpu->irqh);
 61	GBMemoryInit(gb);
 62
 63	gb->video.p = gb;
 64	GBVideoInit(&gb->video);
 65
 66	gb->audio.p = gb;
 67	GBAudioInit(&gb->audio, 2048, &gb->memory.io[REG_NR52], GB_AUDIO_DMG); // TODO: Remove magic constant
 68
 69	gb->sio.p = gb;
 70	GBSIOInit(&gb->sio);
 71
 72	gb->timer.p = gb;
 73
 74	gb->model = GB_MODEL_AUTODETECT;
 75
 76	gb->biosVf = NULL;
 77	gb->romVf = NULL;
 78	gb->sramVf = NULL;
 79	gb->sramRealVf = NULL;
 80
 81	gb->isPristine = false;
 82	gb->pristineRomSize = 0;
 83	gb->yankedRomSize = 0;
 84
 85	mCoreCallbacksListInit(&gb->coreCallbacks, 0);
 86	gb->stream = NULL;
 87
 88	mTimingInit(&gb->timing, &gb->cpu->cycles, &gb->cpu->nextEvent);
 89	gb->audio.timing = &gb->timing;
 90
 91	gb->eiPending.name = "GB EI";
 92	gb->eiPending.callback = _enableInterrupts;
 93	gb->eiPending.context = gb;
 94	gb->eiPending.priority = 0;
 95}
 96
 97static void GBDeinit(struct mCPUComponent* component) {
 98	struct GB* gb = (struct GB*) component;
 99	mTimingDeinit(&gb->timing);
100}
101
102bool GBLoadROM(struct GB* gb, struct VFile* vf) {
103	if (!vf) {
104		return false;
105	}
106	GBUnloadROM(gb);
107	gb->romVf = vf;
108	gb->pristineRomSize = vf->size(vf);
109	vf->seek(vf, 0, SEEK_SET);
110	gb->isPristine = true;
111	gb->memory.rom = vf->map(vf, gb->pristineRomSize, MAP_READ);
112	if (!gb->memory.rom) {
113		return false;
114	}
115	gb->yankedRomSize = 0;
116	gb->memory.romBase = gb->memory.rom;
117	gb->memory.romSize = gb->pristineRomSize;
118	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
119	GBMBCInit(gb);
120
121	if (gb->cpu) {
122		struct LR35902Core* cpu = gb->cpu;
123		cpu->memory.setActiveRegion(cpu, cpu->pc);
124	}
125
126	// TODO: error check
127	return true;
128}
129
130static void GBSramDeinit(struct GB* gb) {
131	if (gb->sramVf) {
132		gb->sramVf->unmap(gb->sramVf, gb->memory.sram, gb->sramSize);
133		if (gb->memory.mbcType == GB_MBC3_RTC && gb->sramVf == gb->sramRealVf) {
134			GBMBCRTCWrite(gb);
135		}
136		gb->sramVf = NULL;
137	} else if (gb->memory.sram) {
138		mappedMemoryFree(gb->memory.sram, gb->sramSize);
139	}
140	gb->memory.sram = 0;
141}
142
143bool GBLoadSave(struct GB* gb, struct VFile* vf) {
144	GBSramDeinit(gb);
145	gb->sramVf = vf;
146	gb->sramRealVf = vf;
147	if (gb->sramSize) {
148		GBResizeSram(gb, gb->sramSize);
149		GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
150	}
151	return vf;
152}
153
154void GBResizeSram(struct GB* gb, size_t size) {
155	if (gb->memory.sram && size <= gb->sramSize) {
156		return;
157	}
158	struct VFile* vf = gb->sramVf;
159	if (vf) {
160		if (vf == gb->sramRealVf) {
161			ssize_t vfSize = vf->size(vf);
162			if (vfSize >= 0 && (size_t) vfSize < size) {
163				uint8_t extdataBuffer[0x100];
164				if (vfSize & 0xFF) {
165					vf->seek(vf, -(vfSize & 0xFF), SEEK_END);
166					vf->read(vf, extdataBuffer, vfSize & 0xFF);
167				}
168				if (gb->memory.sram) {
169					vf->unmap(vf, gb->memory.sram, gb->sramSize);
170				}
171				vf->truncate(vf, size + (vfSize & 0xFF));
172				if (vfSize & 0xFF) {
173					vf->seek(vf, size, SEEK_SET);
174					vf->write(vf, extdataBuffer, vfSize & 0xFF);
175				}
176				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
177				memset(&gb->memory.sram[vfSize], 0xFF, size - vfSize);
178			} else if (size > gb->sramSize || !gb->memory.sram) {
179				if (gb->memory.sram) {
180					vf->unmap(vf, gb->memory.sram, gb->sramSize);
181				}
182				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
183			}
184		} else {
185			if (gb->memory.sram) {
186				vf->unmap(vf, gb->memory.sram, gb->sramSize);
187			}
188			gb->memory.sram = vf->map(vf, size, MAP_READ);
189		}
190		if (gb->memory.sram == (void*) -1) {
191			gb->memory.sram = NULL;
192		}
193	} else if (size) {
194		uint8_t* newSram = anonymousMemoryMap(size);
195		if (gb->memory.sram) {
196			if (size > gb->sramSize) {
197				memcpy(newSram, gb->memory.sram, gb->sramSize);
198				memset(&newSram[gb->sramSize], 0xFF, size - gb->sramSize);
199			} else {
200				memcpy(newSram, gb->memory.sram, size);
201			}
202			mappedMemoryFree(gb->memory.sram, gb->sramSize);
203		} else {
204			memset(newSram, 0xFF, size);
205		}
206		gb->memory.sram = newSram;
207	}
208	if (gb->sramSize < size) {
209		gb->sramSize = size;
210	}
211}
212
213void GBSramClean(struct GB* gb, uint32_t frameCount) {
214	// TODO: Share with GBASavedataClean
215	if (!gb->sramVf) {
216		return;
217	}
218	if (gb->sramDirty & GB_SRAM_DIRT_NEW) {
219		gb->sramDirtAge = frameCount;
220		gb->sramDirty &= ~GB_SRAM_DIRT_NEW;
221		if (!(gb->sramDirty & GB_SRAM_DIRT_SEEN)) {
222			gb->sramDirty |= GB_SRAM_DIRT_SEEN;
223		}
224	} else if ((gb->sramDirty & GB_SRAM_DIRT_SEEN) && frameCount - gb->sramDirtAge > CLEANUP_THRESHOLD) {
225		if (gb->sramMaskWriteback) {
226			GBSavedataUnmask(gb);
227		}
228		if (gb->memory.mbcType == GB_MBC3_RTC) {
229			GBMBCRTCWrite(gb);
230		}
231		gb->sramDirty = 0;
232		if (gb->memory.sram && gb->sramVf->sync(gb->sramVf, gb->memory.sram, gb->sramSize)) {
233			mLOG(GB_MEM, INFO, "Savedata synced");
234		} else {
235			mLOG(GB_MEM, INFO, "Savedata failed to sync!");
236		}
237	}
238}
239
240void GBSavedataMask(struct GB* gb, struct VFile* vf, bool writeback) {
241	struct VFile* oldVf = gb->sramVf;
242	GBSramDeinit(gb);
243	if (oldVf && oldVf != gb->sramRealVf) {
244		oldVf->close(oldVf);
245	}
246	gb->sramVf = vf;
247	gb->sramMaskWriteback = writeback;
248	gb->memory.sram = vf->map(vf, gb->sramSize, MAP_READ);
249	GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
250}
251
252void GBSavedataUnmask(struct GB* gb) {
253	if (!gb->sramRealVf || gb->sramVf == gb->sramRealVf) {
254		return;
255	}
256	struct VFile* vf = gb->sramVf;
257	GBSramDeinit(gb);
258	gb->sramVf = gb->sramRealVf;
259	gb->memory.sram = gb->sramVf->map(gb->sramVf, gb->sramSize, MAP_WRITE);
260	if (gb->sramMaskWriteback) {
261		vf->seek(vf, 0, SEEK_SET);
262		vf->read(vf, gb->memory.sram, gb->sramSize);
263		gb->sramMaskWriteback = false;
264	}
265	GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
266	vf->close(vf);
267}
268
269void GBUnloadROM(struct GB* gb) {
270	// TODO: Share with GBAUnloadROM
271	if (gb->memory.rom && gb->memory.romBase != gb->memory.rom && !gb->isPristine) {
272		free(gb->memory.romBase);
273	}
274	if (gb->memory.rom && !gb->isPristine) {
275		if (gb->yankedRomSize) {
276			gb->yankedRomSize = 0;
277		}
278		mappedMemoryFree(gb->memory.rom, GB_SIZE_CART_MAX);
279	}
280
281	if (gb->romVf) {
282#ifndef FIXED_ROM_BUFFER
283		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
284#endif
285		gb->romVf->close(gb->romVf);
286		gb->romVf = NULL;
287	}
288	gb->memory.rom = NULL;
289	gb->memory.mbcType = GB_MBC_AUTODETECT;
290	gb->isPristine = false;
291
292	gb->sramMaskWriteback = false;
293	GBSramDeinit(gb);
294	if (gb->sramRealVf) {
295		gb->sramRealVf->close(gb->sramRealVf);
296	}
297	gb->sramRealVf = NULL;
298	gb->sramVf = NULL;
299	if (gb->memory.cam && gb->memory.cam->stopRequestImage) {
300		gb->memory.cam->stopRequestImage(gb->memory.cam);
301	}
302}
303
304void GBSynthesizeROM(struct VFile* vf) {
305	if (!vf) {
306		return;
307	}
308	const struct GBCartridge cart = {
309		.logo = { _knownHeader[0], _knownHeader[1], _knownHeader[2], _knownHeader[3]}
310	};
311
312	vf->seek(vf, 0x100, SEEK_SET);
313	vf->write(vf, &cart, sizeof(cart));
314}
315
316void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
317	gb->biosVf = vf;
318}
319
320void GBApplyPatch(struct GB* gb, struct Patch* patch) {
321	size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
322	if (!patchedSize) {
323		return;
324	}
325	if (patchedSize > GB_SIZE_CART_MAX) {
326		patchedSize = GB_SIZE_CART_MAX;
327	}
328	void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
329	if (!patch->applyPatch(patch, gb->memory.rom, gb->pristineRomSize, newRom, patchedSize)) {
330		mappedMemoryFree(newRom, GB_SIZE_CART_MAX);
331		return;
332	}
333	if (gb->romVf) {
334#ifndef FIXED_ROM_BUFFER
335		gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
336#endif
337		gb->romVf->close(gb->romVf);
338		gb->romVf = NULL;
339	}
340	gb->isPristine = false;
341	if (gb->memory.romBase == gb->memory.rom) {
342		gb->memory.romBase = newRom;
343	}
344	gb->memory.rom = newRom;
345	gb->memory.romSize = patchedSize;
346	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
347	gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
348}
349
350void GBDestroy(struct GB* gb) {
351	GBUnloadROM(gb);
352
353	if (gb->biosVf) {
354		gb->biosVf->close(gb->biosVf);
355		gb->biosVf = 0;
356	}
357
358	GBMemoryDeinit(gb);
359	GBAudioDeinit(&gb->audio);
360	GBVideoDeinit(&gb->video);
361	GBSIODeinit(&gb->sio);
362	mCoreCallbacksListDeinit(&gb->coreCallbacks);
363}
364
365void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh) {
366	irqh->reset = GBReset;
367	irqh->processEvents = GBProcessEvents;
368	irqh->setInterrupts = GBSetInterrupts;
369	irqh->irqVector = GBIRQVector;
370	irqh->hitIllegal = GBIllegal;
371	irqh->stop = GBStop;
372	irqh->halt = GBHalt;
373}
374
375static uint32_t _GBBiosCRC32(struct VFile* vf) {
376	ssize_t size = vf->size(vf);
377	if (size <= 0 || size > GB_SIZE_CART_BANK0) {
378		return 0;
379	}
380	void* bios = vf->map(vf, size, MAP_READ);
381	uint32_t biosCrc = doCrc32(bios, size);
382	vf->unmap(vf, bios, size);
383	return biosCrc;
384}
385
386bool GBIsBIOS(struct VFile* vf) {
387	switch (_GBBiosCRC32(vf)) {
388	case DMG_BIOS_CHECKSUM:
389	case DMG_2_BIOS_CHECKSUM:
390	case MGB_BIOS_CHECKSUM:
391	case SGB_BIOS_CHECKSUM:
392	case SGB2_BIOS_CHECKSUM:
393	case CGB_BIOS_CHECKSUM:
394		return true;
395	default:
396		return false;
397	}
398}
399
400void GBReset(struct LR35902Core* cpu) {
401	struct GB* gb = (struct GB*) cpu->master;
402	gb->memory.romBase = gb->memory.rom;
403	GBDetectModel(gb);
404
405	if (gb->biosVf) {
406		if (!GBIsBIOS(gb->biosVf)) {
407			gb->biosVf->close(gb->biosVf);
408			gb->biosVf = NULL;
409		} else {
410			GBMapBIOS(gb);
411			cpu->a = 0;
412			cpu->f.packed = 0;
413			cpu->c = 0;
414			cpu->e = 0;
415			cpu->h = 0;
416			cpu->l = 0;
417			cpu->sp = 0;
418			cpu->pc = 0;
419		}
420	}
421
422	cpu->b = 0;
423	cpu->d = 0;
424
425	gb->timer.internalDiv = 0;
426
427	gb->cpuBlocked = false;
428	gb->earlyExit = false;
429	gb->doubleSpeed = 0;
430
431	if (gb->yankedRomSize) {
432		gb->memory.romSize = gb->yankedRomSize;
433		gb->yankedRomSize = 0;
434	}
435
436	gb->sgbBit = -1;
437	gb->sgbControllers = 0;
438	gb->sgbCurrentController = 0;
439	gb->currentSgbBits = 0;
440	memset(gb->sgbPacket, 0, sizeof(gb->sgbPacket));
441
442	mTimingClear(&gb->timing);
443
444	GBMemoryReset(gb);
445	GBVideoReset(&gb->video);
446	GBTimerReset(&gb->timer);
447	if (!gb->biosVf) {
448		GBSkipBIOS(gb);
449	} else {
450		mTimingSchedule(&gb->timing, &gb->timer.event, 0);
451	}
452
453	GBIOReset(gb);
454	GBAudioReset(&gb->audio);
455	GBSIOReset(&gb->sio);
456
457	cpu->memory.setActiveRegion(cpu, cpu->pc);
458
459	gb->sramMaskWriteback = false;
460	GBSavedataUnmask(gb);
461}
462
463void GBSkipBIOS(struct GB* gb) {
464	struct LR35902Core* cpu = gb->cpu;
465	int nextDiv = 0;
466
467	switch (gb->model) {
468	case GB_MODEL_AUTODETECT: // Silence warnings
469		gb->model = GB_MODEL_DMG;
470		// Fall through
471	case GB_MODEL_DMG:
472		cpu->a = 1;
473		cpu->f.packed = 0xB0;
474		cpu->c = 0x13;
475		cpu->e = 0xD8;
476		cpu->h = 1;
477		cpu->l = 0x4D;
478		gb->timer.internalDiv = 0xABC;
479		nextDiv = 4;
480		break;
481	case GB_MODEL_SGB:
482		cpu->a = 1;
483		cpu->f.packed = 0x00;
484		cpu->c = 0x14;
485		cpu->e = 0x00;
486		cpu->h = 0xC0;
487		cpu->l = 0x60;
488		gb->timer.internalDiv = 0xABC;
489		nextDiv = 4;
490		break;
491	case GB_MODEL_MGB:
492		cpu->a = 0xFF;
493		cpu->f.packed = 0xB0;
494		cpu->c = 0x13;
495		cpu->e = 0xD8;
496		cpu->h = 1;
497		cpu->l = 0x4D;
498		gb->timer.internalDiv = 0xABC;
499		nextDiv = 4;
500		break;
501	case GB_MODEL_SGB2:
502		cpu->a = 0xFF;
503		cpu->f.packed = 0x00;
504		cpu->c = 0x14;
505		cpu->e = 0x00;
506		cpu->h = 0xC0;
507		cpu->l = 0x60;
508		gb->timer.internalDiv = 0xABC;
509		nextDiv = 4;
510		break;
511	case GB_MODEL_AGB:
512		cpu->a = 0x11;
513		cpu->b = 1;
514		cpu->f.packed = 0x00;
515		cpu->c = 0;
516		cpu->e = 0x08;
517		cpu->h = 0;
518		cpu->l = 0x7C;
519		gb->timer.internalDiv = 0x1EA;
520		nextDiv = 0xC;
521		break;
522	case GB_MODEL_CGB:
523		cpu->a = 0x11;
524		cpu->f.packed = 0x80;
525		cpu->c = 0;
526		cpu->e = 0x08;
527		cpu->h = 0;
528		cpu->l = 0x7C;
529		gb->timer.internalDiv = 0x1EA;
530		nextDiv = 0xC;
531		break;
532	}
533
534	cpu->sp = 0xFFFE;
535	cpu->pc = 0x100;
536
537	mTimingDeschedule(&gb->timing, &gb->timer.event);
538	mTimingSchedule(&gb->timing, &gb->timer.event, 0);
539
540	GBIOWrite(gb, REG_LCDC, 0x91);
541
542	if (gb->biosVf) {
543		GBUnmapBIOS(gb);
544	}
545}
546
547void GBMapBIOS(struct GB* gb) {
548	gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
549	gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
550	ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
551	memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
552	if (size > 0x100) {
553		memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
554	}
555}
556
557void GBUnmapBIOS(struct GB* gb) {
558	if (gb->memory.romBase < gb->memory.rom || gb->memory.romBase > &gb->memory.rom[gb->memory.romSize - 1]) {
559		free(gb->memory.romBase);
560		gb->memory.romBase = gb->memory.rom;
561	}
562	// XXX: Force AGB registers for AGB-mode
563	if (gb->model == GB_MODEL_AGB && gb->cpu->pc == 0x100) {
564		gb->cpu->b = 1;
565	}
566}
567
568void GBDetectModel(struct GB* gb) {
569	if (gb->model != GB_MODEL_AUTODETECT) {
570		return;
571	}
572	if (gb->biosVf) {
573		switch (_GBBiosCRC32(gb->biosVf)) {
574		case DMG_BIOS_CHECKSUM:
575		case DMG_2_BIOS_CHECKSUM:
576			gb->model = GB_MODEL_DMG;
577			break;
578		case MGB_BIOS_CHECKSUM:
579			gb->model = GB_MODEL_MGB;
580			break;
581		case SGB_BIOS_CHECKSUM:
582			gb->model = GB_MODEL_SGB;
583			break;
584		case SGB2_BIOS_CHECKSUM:
585			gb->model = GB_MODEL_SGB2;
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] & 0x1F;
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] & 0x1F)) {
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}