all repos — mgba @ 49a2a01f89a06839548d71b163534cd2d476d605

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	GBMemoryDeinit(gb);
225	GBVideoDeinit(&gb->video);
226	GBSIODeinit(&gb->sio);
227}
228
229void GBInterruptHandlerInit(struct LR35902InterruptHandler* irqh) {
230	irqh->reset = GBReset;
231	irqh->processEvents = GBProcessEvents;
232	irqh->setInterrupts = GBSetInterrupts;
233	irqh->hitIllegal = GBIllegal;
234	irqh->stop = GBStop;
235	irqh->halt = GBHalt;
236}
237
238void GBReset(struct LR35902Core* cpu) {
239	struct GB* gb = (struct GB*) cpu->master;
240
241	if (gb->biosVf) {
242		gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
243		gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
244		ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
245		uint32_t biosCrc = doCrc32(gb->memory.romBase, size);
246		switch (biosCrc) {
247		case 0x59C8598E:
248			gb->model = GB_MODEL_DMG;
249			gb->audio.style = GB_AUDIO_DMG;
250			break;
251		case 0x41884E46:
252			gb->model = GB_MODEL_CGB;
253			gb->audio.style = GB_AUDIO_CGB;
254			break;
255		default:
256			free(gb->memory.romBase);
257			gb->memory.romBase = gb->memory.rom;
258			gb->biosVf = NULL;
259			break;
260		}
261
262		memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
263		if (size > 0x100) {
264			memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
265		}
266
267		cpu->a = 0;
268		cpu->f.packed = 0;
269		cpu->c = 0;
270		cpu->e = 0;
271		cpu->h = 0;
272		cpu->l = 0;
273		cpu->sp = 0;
274		cpu->pc = 0;
275	}
276	if (!gb->biosVf) {
277		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
278		if (cart->cgb & 0x80) {
279			gb->model = GB_MODEL_CGB;
280			gb->audio.style = GB_AUDIO_CGB;
281			cpu->a = 0x11;
282			cpu->f.packed = 0x80;
283			cpu->c = 0;
284			cpu->e = 0x08;
285			cpu->h = 0;
286			cpu->l = 0x7C;
287		} else {
288			// TODO: SGB
289			gb->model = GB_MODEL_DMG;
290			gb->audio.style = GB_AUDIO_DMG;
291			cpu->a = 1;
292			cpu->f.packed = 0xB0;
293			cpu->c = 0x13;
294			cpu->e = 0xD8;
295			cpu->h = 1;
296			cpu->l = 0x4D;
297		}
298
299		cpu->sp = 0xFFFE;
300		cpu->pc = 0x100;
301	}
302
303	cpu->b = 0;
304	cpu->d = 0;
305
306	gb->eiPending = INT_MAX;
307	gb->doubleSpeed = 0;
308
309	cpu->memory.setActiveRegion(cpu, cpu->pc);
310
311	if (gb->yankedRomSize) {
312		gb->memory.romSize = gb->yankedRomSize;
313		gb->yankedRomSize = 0;
314	}
315	GBMemoryReset(gb);
316	GBVideoReset(&gb->video);
317	GBTimerReset(&gb->timer);
318	GBIOReset(gb);
319	GBAudioReset(&gb->audio);
320	GBSIOReset(&gb->sio);
321
322	GBSavedataUnmask(gb);
323}
324
325void GBUpdateIRQs(struct GB* gb) {
326	int irqs = gb->memory.ie & gb->memory.io[REG_IF];
327	if (!irqs) {
328		return;
329	}
330	gb->cpu->halted = false;
331
332	if (!gb->memory.ime || gb->cpu->irqPending) {
333		return;
334	}
335
336	if (irqs & (1 << GB_IRQ_VBLANK)) {
337		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_VBLANK);
338		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
339		return;
340	}
341	if (irqs & (1 << GB_IRQ_LCDSTAT)) {
342		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_LCDSTAT);
343		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
344		return;
345	}
346	if (irqs & (1 << GB_IRQ_TIMER)) {
347		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_TIMER);
348		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
349		return;
350	}
351	if (irqs & (1 << GB_IRQ_SIO)) {
352		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_SIO);
353		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
354		return;
355	}
356	if (irqs & (1 << GB_IRQ_KEYPAD)) {
357		LR35902RaiseIRQ(gb->cpu, GB_VECTOR_KEYPAD);
358		gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
359	}
360}
361
362void GBProcessEvents(struct LR35902Core* cpu) {
363	struct GB* gb = (struct GB*) cpu->master;
364	do {
365		int32_t cycles = cpu->nextEvent;
366		int32_t nextEvent = INT_MAX;
367		int32_t testEvent;
368
369		if (gb->eiPending != INT_MAX) {
370			gb->eiPending -= cycles;
371			if (gb->eiPending <= 0) {
372				gb->memory.ime = true;
373				GBUpdateIRQs(gb);
374				gb->eiPending = INT_MAX;
375			} else {
376				nextEvent = gb->eiPending;
377			}
378		}
379
380		testEvent = GBVideoProcessEvents(&gb->video, cycles >> gb->doubleSpeed);
381		if (testEvent != INT_MAX) {
382			testEvent <<= gb->doubleSpeed;
383			if (testEvent < nextEvent) {
384				nextEvent = testEvent;
385			}
386		}
387
388		testEvent = GBAudioProcessEvents(&gb->audio, cycles >> gb->doubleSpeed);
389		if (testEvent != INT_MAX) {
390			testEvent <<= gb->doubleSpeed;
391			if (testEvent < nextEvent) {
392				nextEvent = testEvent;
393			}
394		}
395
396		testEvent = GBTimerProcessEvents(&gb->timer, cycles);
397		if (testEvent < nextEvent) {
398			nextEvent = testEvent;
399		}
400
401		testEvent = GBSIOProcessEvents(&gb->sio, cycles);
402		if (testEvent < nextEvent) {
403			nextEvent = testEvent;
404		}
405
406		testEvent = GBMemoryProcessEvents(gb, cycles);
407		if (testEvent < nextEvent) {
408			nextEvent = testEvent;
409		}
410
411		cpu->cycles -= cycles;
412		cpu->nextEvent = nextEvent;
413
414		if (cpu->halted) {
415			cpu->cycles = cpu->nextEvent;
416		}
417	} while (cpu->cycles >= cpu->nextEvent);
418}
419
420void GBSetInterrupts(struct LR35902Core* cpu, bool enable) {
421	struct GB* gb = (struct GB*) cpu->master;
422	if (!enable) {
423		gb->memory.ime = enable;
424		gb->eiPending = INT_MAX;
425		GBUpdateIRQs(gb);
426	} else {
427		if (cpu->nextEvent > cpu->cycles + 4) {
428			cpu->nextEvent = cpu->cycles + 4;
429		}
430		gb->eiPending = cpu->cycles + 4;
431	}
432}
433
434void GBHalt(struct LR35902Core* cpu) {
435	if (!cpu->irqPending) {
436		cpu->cycles = cpu->nextEvent;
437		cpu->halted = true;
438	}
439}
440
441void GBStop(struct LR35902Core* cpu) {
442	struct GB* gb = (struct GB*) cpu->master;
443	if (cpu->bus) {
444		mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X\n", cpu->pc, cpu->bus);
445		if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
446			struct mDebuggerEntryInfo info = {
447				.address = cpu->pc - 1,
448				.opcode = 0x1000 | cpu->bus
449			};
450			mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
451		}
452		// Hang forever
453		gb->memory.ime = 0;
454		cpu->pc -= 2;
455	} else if (gb->memory.io[REG_KEY1] & 1) {
456		gb->doubleSpeed ^= 1;
457		gb->memory.io[REG_KEY1] &= 1;
458		gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
459	}
460	// TODO: Actually stop
461}
462
463void GBIllegal(struct LR35902Core* cpu) {
464	struct GB* gb = (struct GB*) cpu->master;
465	mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X\n", cpu->pc, cpu->bus);
466	if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
467		struct mDebuggerEntryInfo info = {
468			.address = cpu->pc,
469			.opcode = cpu->bus
470		};
471		mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
472	}
473	// Hang forever
474	gb->memory.ime = 0;
475	--cpu->pc;
476}
477
478bool GBIsROM(struct VFile* vf) {
479	vf->seek(vf, 0x104, SEEK_SET);
480	uint8_t header[4];
481	static const uint8_t knownHeader[4] = { 0xCE, 0xED, 0x66, 0x66};
482
483	if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
484		return false;
485	}
486	if (memcmp(header, knownHeader, sizeof(header))) {
487		return false;
488	}
489	return true;
490}
491
492void GBGetGameTitle(struct GB* gb, char* out) {
493	const struct GBCartridge* cart = NULL;
494	if (gb->memory.rom) {
495		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
496	}
497	if (gb->pristineRom) {
498		cart = (const struct GBCartridge*) &((uint8_t*) gb->pristineRom)[0x100];
499	}
500	if (!cart) {
501		return;
502	}
503	if (cart->oldLicensee != 0x33) {
504		memcpy(out, cart->titleLong, 16);
505	} else {
506		memcpy(out, cart->titleShort, 11);
507	}
508}
509
510void GBGetGameCode(struct GB* gb, char* out) {
511	memset(out, 0, 8);
512	const struct GBCartridge* cart = NULL;
513	if (gb->memory.rom) {
514		cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
515	}
516	if (gb->pristineRom) {
517		cart = (const struct GBCartridge*) &((uint8_t*) gb->pristineRom)[0x100];
518	}
519	if (!cart) {
520		return;
521	}
522	if (cart->cgb == 0xC0) {
523		memcpy(out, "CGB-????", 8);
524	} else {
525		memcpy(out, "DMG-????", 8);
526	}
527	if (cart->oldLicensee == 0x33) {
528		memcpy(&out[4], cart->maker, 4);
529	}
530}
531
532void GBFrameEnded(struct GB* gb) {
533	if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
534		struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
535		size_t i;
536		for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
537			struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
538			mCheatRefresh(device, cheats);
539		}
540	}
541}