all repos — mgba @ fc095ffd63259166d9a20cf23133b25efd966aea

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 "gb.h"
  7
  8#include "gb/io.h"
  9
 10#include "core/core.h"
 11#include "core/cheats.h"
 12#include "util/crc32.h"
 13#include "util/memory.h"
 14#include "util/math.h"
 15#include "util/patch.h"
 16#include "util/vfs.h"
 17
 18const uint32_t CGB_LR35902_FREQUENCY = 0x800000;
 19const uint32_t SGB_LR35902_FREQUENCY = 0x418B1E;
 20
 21const uint32_t GB_COMPONENT_MAGIC = 0x400000;
 22
 23mLOG_DEFINE_CATEGORY(GB, "GB");
 24
 25static void GBInit(void* cpu, struct mCPUComponent* component);
 26static void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh);
 27static void GBProcessEvents(struct LR35902Core* cpu);
 28static void GBSetInterrupts(struct LR35902Core* cpu, bool enable);
 29static void GBIllegal(struct LR35902Core* cpu);
 30static void GBStop(struct LR35902Core* cpu);
 31
 32#ifdef _3DS
 33extern uint32_t* romBuffer;
 34extern size_t romBufferSize;
 35#endif
 36
 37void GBCreate(struct GB* gb) {
 38	gb->d.id = GB_COMPONENT_MAGIC;
 39	gb->d.init = GBInit;
 40	gb->d.deinit = 0;
 41}
 42
 43static void GBInit(void* cpu, struct mCPUComponent* component) {
 44	struct GB* gb = (struct GB*) component;
 45	gb->cpu = cpu;
 46	gb->sync = NULL;
 47
 48	GBInterruptHandlerInit(&gb->cpu->irqh);
 49	GBMemoryInit(gb);
 50
 51	gb->video.p = gb;
 52	GBVideoInit(&gb->video);
 53
 54	gb->audio.p = gb;
 55	GBAudioInit(&gb->audio, 2048, &gb->memory.io[REG_NR52], GB_AUDIO_DMG); // TODO: Remove magic constant
 56
 57	gb->sio.p = gb;
 58	GBSIOInit(&gb->sio);
 59
 60	gb->timer.p = gb;
 61
 62	gb->biosVf = 0;
 63	gb->romVf = 0;
 64	gb->sramVf = 0;
 65
 66	gb->pristineRom = 0;
 67	gb->pristineRomSize = 0;
 68	gb->yankedRomSize = 0;
 69
 70	gb->stream = NULL;
 71}
 72
 73bool GBLoadROM(struct GB* gb, struct VFile* vf) {
 74	GBUnloadROM(gb);
 75	gb->romVf = vf;
 76	gb->pristineRomSize = vf->size(vf);
 77	vf->seek(vf, 0, SEEK_SET);
 78#ifdef _3DS
 79	gb->pristineRom = 0;
 80	if (gb->pristineRomSize <= romBufferSize) {
 81		gb->pristineRom = romBuffer;
 82		vf->read(vf, romBuffer, gb->pristineRomSize);
 83	}
 84#else
 85	gb->pristineRom = vf->map(vf, gb->pristineRomSize, MAP_READ);
 86#endif
 87	if (!gb->pristineRom) {
 88		return false;
 89	}
 90	gb->yankedRomSize = 0;
 91	gb->memory.rom = gb->pristineRom;
 92	gb->memory.romBase = gb->memory.rom;
 93	gb->memory.romSize = gb->pristineRomSize;
 94	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
 95
 96	// TODO: error check
 97	return true;
 98}
 99
100bool GBLoadSave(struct GB* gb, struct VFile* vf) {
101	gb->sramVf = vf;
102	gb->sramRealVf = vf;
103	return vf;
104}
105
106static void GBSramDeinit(struct GB* gb) {
107	if (gb->sramVf) {
108		gb->sramVf->unmap(gb->sramVf, gb->memory.sram, gb->sramSize);
109		gb->sramVf = 0;
110	} else if (gb->memory.sram) {
111		mappedMemoryFree(gb->memory.sram, gb->sramSize);
112	}
113	gb->memory.sram = 0;
114}
115
116void GBResizeSram(struct GB* gb, size_t size) {
117	struct VFile* vf = gb->sramVf;
118	if (vf) {
119		if (vf == gb->sramRealVf) {
120			if (vf->size(vf) >= 0 && (size_t) vf->size(vf) < size) {
121				uint8_t extdataBuffer[0x100];
122				if (vf->size(vf) & 0xFF) {
123					// Copy over appended data, e.g. RTC data
124					memcpy(extdataBuffer, &gb->memory.sram[gb->sramSize - (vf->size(vf) & 0xFF)], vf->size(vf) & 0xFF);
125				}
126				vf->unmap(vf, gb->memory.sram, gb->sramSize);
127				vf->truncate(vf, size);
128				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
129				memset(&gb->memory.sram[gb->sramSize], 0xFF, size - gb->sramSize);
130				if (size & 0xFF) {
131					memcpy(&gb->memory.sram[gb->sramSize - (size & 0xFF)], extdataBuffer, size & 0xFF);
132				}
133			} else {
134				vf->unmap(vf, gb->memory.sram, gb->sramSize);
135				gb->memory.sram = vf->map(vf, size, MAP_WRITE);
136			}
137		} else {
138			vf->unmap(vf, gb->memory.sram, gb->sramSize);
139			gb->memory.sram = vf->map(vf, size, MAP_READ);
140		}
141	} else {
142		uint8_t* newSram = anonymousMemoryMap(size);
143		if (gb->memory.sram) {
144			if (size > gb->sramSize) {
145				memcpy(newSram, gb->memory.sram, gb->sramSize);
146				memset(&newSram[gb->sramSize], 0xFF, size - gb->sramSize);
147			} else {
148				memcpy(newSram, gb->memory.sram, size);
149			}
150			mappedMemoryFree(gb->memory.sram, gb->sramSize);
151		} else {
152			memset(newSram, 0xFF, size);
153		}
154		gb->memory.sram = newSram;
155	}
156	gb->sramSize = size;
157}
158
159void GBSavedataMask(struct GB* gb, struct VFile* vf) {
160	GBSramDeinit(gb);
161	gb->sramVf = vf;
162	gb->memory.sram = vf->map(vf, gb->sramSize, MAP_READ);
163}
164
165void GBSavedataUnmask(struct GB* gb) {
166	if (gb->sramVf == gb->sramRealVf) {
167		return;
168	}
169	GBSramDeinit(gb);
170	gb->sramVf = gb->sramRealVf;
171	gb->memory.sram = gb->sramVf->map(gb->sramVf, gb->sramSize, MAP_WRITE);
172}
173
174void GBUnloadROM(struct GB* gb) {
175	// TODO: Share with GBAUnloadROM
176	if (gb->memory.rom && gb->memory.romBase != gb->memory.rom) {
177		free(gb->memory.romBase);
178	}
179	if (gb->memory.rom && gb->pristineRom != gb->memory.rom) {
180		if (gb->yankedRomSize) {
181			gb->yankedRomSize = 0;
182		}
183		mappedMemoryFree(gb->memory.rom, GB_SIZE_CART_MAX);
184	}
185	gb->memory.rom = 0;
186
187	if (gb->romVf) {
188#ifndef _3DS
189		gb->romVf->unmap(gb->romVf, gb->pristineRom, gb->pristineRomSize);
190#endif
191		gb->romVf->close(gb->romVf);
192		gb->pristineRom = 0;
193		gb->romVf = 0;
194	}
195
196	GBSramDeinit(gb);
197}
198
199void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
200	gb->biosVf = vf;
201}
202
203void GBApplyPatch(struct GB* gb, struct Patch* patch) {
204	size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
205	if (!patchedSize) {
206		return;
207	}
208	if (patchedSize > GB_SIZE_CART_MAX) {
209		patchedSize = GB_SIZE_CART_MAX;
210	}
211	gb->memory.rom = anonymousMemoryMap(GB_SIZE_CART_MAX);
212	if (!patch->applyPatch(patch, gb->pristineRom, gb->pristineRomSize, gb->memory.rom, patchedSize)) {
213		mappedMemoryFree(gb->memory.rom, patchedSize);
214		gb->memory.rom = gb->pristineRom;
215		return;
216	}
217	gb->memory.romSize = patchedSize;
218	gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
219}
220
221void GBDestroy(struct GB* gb) {
222	GBUnloadROM(gb);
223
224	if (gb->biosVf) {
225		gb->biosVf->close(gb->biosVf);
226		gb->biosVf = 0;
227	}
228
229	GBMemoryDeinit(gb);
230	GBVideoDeinit(&gb->video);
231	GBSIODeinit(&gb->sio);
232}
233
234void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh) {
235	irqh->reset = GBReset;
236	irqh->processEvents = GBProcessEvents;
237	irqh->setInterrupts = GBSetInterrupts;
238	irqh->hitIllegal = GBIllegal;
239	irqh->stop = GBStop;
240	irqh->halt = GBHalt;
241}
242
243void GBReset(struct LR35902Core* cpu) {
244	struct GB* gb = (struct GB*) cpu->master;
245
246	if (gb->biosVf) {
247		gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
248		gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
249		ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
250		uint32_t biosCrc = doCrc32(gb->memory.romBase, size);
251		switch (biosCrc) {
252		case 0x59C8598E:
253			gb->model = GB_MODEL_DMG;
254			gb->audio.style = GB_AUDIO_DMG;
255			break;
256		case 0x41884E46:
257			gb->model = GB_MODEL_CGB;
258			gb->audio.style = GB_AUDIO_CGB;
259			break;
260		default:
261			free(gb->memory.romBase);
262			gb->memory.romBase = gb->memory.rom;
263			gb->biosVf = NULL;
264			break;
265		}
266
267		memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
268		if (size > 0x100) {
269			memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
270		}
271
272		cpu->a = 0;
273		cpu->f.packed = 0;
274		cpu->c = 0;
275		cpu->e = 0;
276		cpu->h = 0;
277		cpu->l = 0;
278		cpu->sp = 0;
279		cpu->pc = 0;
280	}
281	if (!gb->biosVf) {
282		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
283		if (cart->cgb & 0x80) {
284			gb->model = GB_MODEL_CGB;
285			gb->audio.style = GB_AUDIO_CGB;
286			cpu->a = 0x11;
287			cpu->f.packed = 0x80;
288			cpu->c = 0;
289			cpu->e = 0x08;
290			cpu->h = 0;
291			cpu->l = 0x7C;
292		} else {
293			// TODO: SGB
294			gb->model = GB_MODEL_DMG;
295			gb->audio.style = GB_AUDIO_DMG;
296			cpu->a = 1;
297			cpu->f.packed = 0xB0;
298			cpu->c = 0x13;
299			cpu->e = 0xD8;
300			cpu->h = 1;
301			cpu->l = 0x4D;
302		}
303
304		cpu->sp = 0xFFFE;
305		cpu->pc = 0x100;
306	}
307
308	cpu->b = 0;
309	cpu->d = 0;
310
311	gb->eiPending = INT_MAX;
312	gb->doubleSpeed = 0;
313
314	cpu->memory.setActiveRegion(cpu, cpu->pc);
315
316	if (gb->yankedRomSize) {
317		gb->memory.romSize = gb->yankedRomSize;
318		gb->yankedRomSize = 0;
319	}
320	GBMemoryReset(gb);
321	GBVideoReset(&gb->video);
322	GBTimerReset(&gb->timer);
323	GBIOReset(gb);
324	GBAudioReset(&gb->audio);
325	GBSIOReset(&gb->sio);
326
327	GBSavedataUnmask(gb);
328}
329
330void GBUpdateIRQs(struct GB* gb) {
331	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
332	if (!irqs) {
333		return;
334	}
335	gb->cpu->halted = false;
336
337	if (!gb->memory.ime || gb->cpu->irqPending) {
338		return;
339	}
340
341	if (irqs & (1 << GB_IRQ_VBLANK)) {
342		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_VBLANK);
343		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
344		return;
345	}
346	if (irqs & (1 << GB_IRQ_LCDSTAT)) {
347		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_LCDSTAT);
348		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
349		return;
350	}
351	if (irqs & (1 << GB_IRQ_TIMER)) {
352		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_TIMER);
353		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
354		return;
355	}
356	if (irqs & (1 << GB_IRQ_SIO)) {
357		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_SIO);
358		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
359		return;
360	}
361	if (irqs & (1 << GB_IRQ_KEYPAD)) {
362		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_KEYPAD);
363		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
364	}
365}
366
367void GBProcessEvents(struct LR35902Core* cpu) {
368	struct GB* gb = (struct GB*) cpu->master;
369	do {
370		int32_t cycles = cpu->nextEvent;
371		int32_t nextEvent = INT_MAX;
372		int32_t testEvent;
373
374		if (gb->eiPending != INT_MAX) {
375			gb->eiPending -= cycles;
376			if (gb->eiPending <= 0) {
377				gb->memory.ime = true;
378				GBUpdateIRQs(gb);
379				gb->eiPending = INT_MAX;
380			} else {
381				nextEvent = gb->eiPending;
382			}
383		}
384
385		testEvent = GBVideoProcessEvents(&gb->video, cycles >> gb->doubleSpeed);
386		if (testEvent != INT_MAX) {
387			testEvent <<= gb->doubleSpeed;
388			if (testEvent < nextEvent) {
389				nextEvent = testEvent;
390			}
391		}
392
393		testEvent = GBAudioProcessEvents(&gb->audio, cycles >> gb->doubleSpeed);
394		if (testEvent != INT_MAX) {
395			testEvent <<= gb->doubleSpeed;
396			if (testEvent < nextEvent) {
397				nextEvent = testEvent;
398			}
399		}
400
401		testEvent = GBTimerProcessEvents(&gb->timer, cycles);
402		if (testEvent < nextEvent) {
403			nextEvent = testEvent;
404		}
405
406		testEvent = GBSIOProcessEvents(&gb->sio, cycles);
407		if (testEvent < nextEvent) {
408			nextEvent = testEvent;
409		}
410
411		testEvent = GBMemoryProcessEvents(gb, cycles);
412		if (testEvent < nextEvent) {
413			nextEvent = testEvent;
414		}
415
416		cpu->cycles -= cycles;
417		cpu->nextEvent = nextEvent;
418
419		if (cpu->halted) {
420			cpu->cycles = cpu->nextEvent;
421		}
422	} while (cpu->cycles >= cpu->nextEvent);
423}
424
425void GBSetInterrupts(struct LR35902Core* cpu, bool enable) {
426	struct GB* gb = (struct GB*) cpu->master;
427	if (!enable) {
428		gb->memory.ime = enable;
429		gb->eiPending = INT_MAX;
430		GBUpdateIRQs(gb);
431	} else {
432		if (cpu->nextEvent > cpu->cycles + 4) {
433			cpu->nextEvent = cpu->cycles + 4;
434		}
435		gb->eiPending = cpu->cycles + 4;
436	}
437}
438
439void GBHalt(struct LR35902Core* cpu) {
440	if (!cpu->irqPending) {
441		cpu->cycles = cpu->nextEvent;
442		cpu->halted = true;
443	}
444}
445
446void GBStop(struct LR35902Core* cpu) {
447	struct GB* gb = (struct GB*) cpu->master;
448	if (cpu->bus) {
449		mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X\n", cpu->pc, cpu->bus);
450		if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
451			struct mDebuggerEntryInfo info = {
452				.address = cpu->pc - 1,
453				.opcode = 0x1000 | cpu->bus
454			};
455			mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
456		}
457		// Hang forever
458		gb->memory.ime = 0;
459		cpu->pc -= 2;
460	} else if (gb->memory.io[REG_KEY1] & 1) {
461		gb->doubleSpeed ^= 1;
462		gb->memory.io[REG_KEY1] &= 1;
463		gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
464	}
465	// TODO: Actually stop
466}
467
468void GBIllegal(struct LR35902Core* cpu) {
469	struct GB* gb = (struct GB*) cpu->master;
470	mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X\n", cpu->pc, cpu->bus);
471	if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
472		struct mDebuggerEntryInfo info = {
473			.address = cpu->pc,
474			.opcode = cpu->bus
475		};
476		mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
477	}
478	// Hang forever
479	gb->memory.ime = 0;
480	--cpu->pc;
481}
482
483bool GBIsROM(struct VFile* vf) {
484	vf->seek(vf, 0x104, SEEK_SET);
485	uint8_t header[4];
486	static const uint8_t knownHeader[4] = { 0xCE, 0xED, 0x66, 0x66};
487
488	if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
489		return false;
490	}
491	if (memcmp(header, knownHeader, sizeof(header))) {
492		return false;
493	}
494	return true;
495}
496
497void GBGetGameTitle(struct GB* gb, char* out) {
498	const struct GBCartridge* cart = NULL;
499	if (gb->memory.rom) {
500		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
501	}
502	if (gb->pristineRom) {
503		cart = (const struct GBCartridge*) &((uint8_t*) gb->pristineRom)[0x100];
504	}
505	if (!cart) {
506		return;
507	}
508	if (cart->oldLicensee != 0x33) {
509		memcpy(out, cart->titleLong, 16);
510	} else {
511		memcpy(out, cart->titleShort, 11);
512	}
513}
514
515void GBGetGameCode(struct GB* gb, char* out) {
516	memset(out, 0, 8);
517	const struct GBCartridge* cart = NULL;
518	if (gb->memory.rom) {
519		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
520	}
521	if (gb->pristineRom) {
522		cart = (const struct GBCartridge*) &((uint8_t*) gb->pristineRom)[0x100];
523	}
524	if (!cart) {
525		return;
526	}
527	if (cart->cgb == 0xC0) {
528		memcpy(out, "CGB-????", 8);
529	} else {
530		memcpy(out, "DMG-????", 8);
531	}
532	if (cart->oldLicensee == 0x33) {
533		memcpy(&out[4], cart->maker, 4);
534	}
535}
536
537void GBFrameEnded(struct GB* gb) {
538	if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
539		struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
540		size_t i;
541		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
542			struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
543			mCheatRefresh(device, cheats);
544		}
545	}
546}