all repos — mgba @ 6ab7e178be1cd076965b035276e66491c41ee454

mGBA Game Boy Advance Emulator

src/gb/core.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/gb/core.h>
  7
  8#include <mgba/core/core.h>
  9#include <mgba/internal/debugger/symbols.h>
 10#include <mgba/internal/gb/cheats.h>
 11#include <mgba/internal/gb/debugger/symbols.h>
 12#include <mgba/internal/gb/extra/cli.h>
 13#include <mgba/internal/gb/io.h>
 14#include <mgba/internal/gb/gb.h>
 15#include <mgba/internal/gb/mbc.h>
 16#include <mgba/internal/gb/overrides.h>
 17#include <mgba/internal/gb/renderers/software.h>
 18#include <mgba/internal/gb/renderers/proxy.h>
 19#include <mgba/internal/gb/serialize.h>
 20#include <mgba/internal/lr35902/lr35902.h>
 21#include <mgba/internal/lr35902/debugger/debugger.h>
 22#include <mgba-util/crc32.h>
 23#include <mgba-util/memory.h>
 24#include <mgba-util/patch.h>
 25#include <mgba-util/vfs.h>
 26
 27static const struct mCoreChannelInfo _GBVideoLayers[] = {
 28	{ 0, "bg", "Background", NULL },
 29	{ 1, "obj", "Objects", NULL },
 30	{ 2, "win", "Window", NULL },
 31};
 32
 33static const struct mCoreChannelInfo _GBAudioChannels[] = {
 34	{ 0, "ch1", "Channel 1", "Square/Sweep" },
 35	{ 1, "ch2", "Channel 2", "Square" },
 36	{ 2, "ch3", "Channel 3", "PCM" },
 37	{ 3, "ch4", "Channel 4", "Noise" },
 38};
 39
 40static const struct LR35902Segment _GBSegments[] = {
 41	{ .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
 42	{ .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
 43	{ 0 }
 44};
 45
 46static const struct LR35902Segment _GBCSegments[] = {
 47	{ .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
 48	{ .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
 49	{ .name = "WRAM", .start = GB_BASE_WORKING_RAM_BANK1, .end = 0xE000 },
 50	{ .name = "VRAM", .start = GB_BASE_VRAM, .end = GB_BASE_EXTERNAL_RAM },
 51	{ 0 }
 52};
 53
 54static const struct mCoreMemoryBlock _GBMemoryBlocks[] = {
 55	{ -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
 56	{ GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
 57	{ GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 58	{ GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
 59	{ GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2 , GB_SIZE_WORKING_RAM_BANK0 * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 60	{ GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 61	{ GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 62	{ GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 63};
 64
 65static const struct mCoreMemoryBlock _GBCMemoryBlocks[] = {
 66	{ -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
 67	{ GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
 68	{ GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 1 },
 69	{ GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
 70	{ GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2, GB_SIZE_WORKING_RAM_BANK0 * 8, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 7 },
 71	{ GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 72	{ GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 73	{ GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
 74};
 75
 76struct mVideoLogContext;
 77struct GBCore {
 78	struct mCore d;
 79	struct GBVideoSoftwareRenderer renderer;
 80	struct GBVideoProxyRenderer proxyRenderer;
 81	struct mVideoLogContext* logContext;
 82	struct mCoreCallbacks logCallbacks;
 83	uint8_t keys;
 84	struct mCPUComponent* components[CPU_COMPONENT_MAX];
 85	const struct Configuration* overrides;
 86	struct mDebuggerPlatform* debuggerPlatform;
 87	struct mCheatDevice* cheatDevice;
 88};
 89
 90static bool _GBCoreInit(struct mCore* core) {
 91	struct GBCore* gbcore = (struct GBCore*) core;
 92
 93	struct LR35902Core* cpu = anonymousMemoryMap(sizeof(struct LR35902Core));
 94	struct GB* gb = anonymousMemoryMap(sizeof(struct GB));
 95	if (!cpu || !gb) {
 96		free(cpu);
 97		free(gb);
 98		return false;
 99	}
100	core->cpu = cpu;
101	core->board = gb;
102	gbcore->overrides = NULL;
103	gbcore->debuggerPlatform = NULL;
104	gbcore->cheatDevice = NULL;
105
106	GBCreate(gb);
107	memset(gbcore->components, 0, sizeof(gbcore->components));
108	LR35902SetComponents(cpu, &gb->d, CPU_COMPONENT_MAX, gbcore->components);
109	LR35902Init(cpu);
110	mRTCGenericSourceInit(&core->rtc, core);
111	gb->memory.rtc = &core->rtc.d;
112
113	GBVideoSoftwareRendererCreate(&gbcore->renderer);
114	gbcore->renderer.outputBuffer = NULL;
115
116	gbcore->keys = 0;
117	gb->keySource = &gbcore->keys;
118
119#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
120	mDirectorySetInit(&core->dirs);
121#endif
122	
123	return true;
124}
125
126static void _GBCoreDeinit(struct mCore* core) {
127	LR35902Deinit(core->cpu);
128	GBDestroy(core->board);
129	mappedMemoryFree(core->cpu, sizeof(struct LR35902Core));
130	mappedMemoryFree(core->board, sizeof(struct GB));
131#if defined USE_DEBUGGERS && (!defined(MINIMAL_CORE) || MINIMAL_CORE < 2)
132	mDirectorySetDeinit(&core->dirs);
133	if (core->symbolTable) {
134		mDebuggerSymbolTableDestroy(core->symbolTable);
135	}
136#endif
137
138	struct GBCore* gbcore = (struct GBCore*) core;
139	free(gbcore->debuggerPlatform);
140	if (gbcore->cheatDevice) {
141		mCheatDeviceDestroy(gbcore->cheatDevice);
142	}
143	free(gbcore->cheatDevice);
144	mCoreConfigFreeOpts(&core->opts);
145	free(core);
146}
147
148static enum mPlatform _GBCorePlatform(const struct mCore* core) {
149	UNUSED(core);
150	return PLATFORM_GB;
151}
152
153static void _GBCoreSetSync(struct mCore* core, struct mCoreSync* sync) {
154	struct GB* gb = core->board;
155	gb->sync = sync;
156}
157
158static void _GBCoreLoadConfig(struct mCore* core, const struct mCoreConfig* config) {
159	UNUSED(config);
160
161	struct GB* gb = core->board;
162	if (core->opts.mute) {
163		gb->audio.masterVolume = 0;
164	} else {
165		gb->audio.masterVolume = core->opts.volume;
166	}
167	gb->video.frameskip = core->opts.frameskip;
168
169	int color;
170	if (mCoreConfigGetIntValue(config, "gb.pal[0]", &color)) {
171		GBVideoSetPalette(&gb->video, 0, color);
172	}
173	if (mCoreConfigGetIntValue(config, "gb.pal[1]", &color)) {
174		GBVideoSetPalette(&gb->video, 1, color);
175	}
176	if (mCoreConfigGetIntValue(config, "gb.pal[2]", &color)) {
177		GBVideoSetPalette(&gb->video, 2, color);
178	}
179	if (mCoreConfigGetIntValue(config, "gb.pal[3]", &color)) {
180		GBVideoSetPalette(&gb->video, 3, color);
181	}
182
183	mCoreConfigCopyValue(&core->config, config, "gb.bios");
184	mCoreConfigCopyValue(&core->config, config, "gbc.bios");
185
186#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
187	struct GBCore* gbcore = (struct GBCore*) core;
188	gbcore->overrides = mCoreConfigGetOverridesConst(config);
189#endif
190}
191
192static void _GBCoreDesiredVideoDimensions(struct mCore* core, unsigned* width, unsigned* height) {
193	struct GB* gb = core->board;
194	if (!gb || gb->model != GB_MODEL_SGB) {
195		*width = GB_VIDEO_HORIZONTAL_PIXELS;
196		*height = GB_VIDEO_VERTICAL_PIXELS;
197	} else {
198		*width = 256;
199		*height = 224;
200	}
201}
202
203static void _GBCoreSetVideoBuffer(struct mCore* core, color_t* buffer, size_t stride) {
204	struct GBCore* gbcore = (struct GBCore*) core;
205	gbcore->renderer.outputBuffer = buffer;
206	gbcore->renderer.outputBufferStride = stride;
207}
208
209static void _GBCoreGetPixels(struct mCore* core, const void** buffer, size_t* stride) {
210	struct GBCore* gbcore = (struct GBCore*) core;
211	gbcore->renderer.d.getPixels(&gbcore->renderer.d, stride, buffer);
212}
213
214static void _GBCorePutPixels(struct mCore* core, const void* buffer, size_t stride) {
215	struct GBCore* gbcore = (struct GBCore*) core;
216	gbcore->renderer.d.putPixels(&gbcore->renderer.d, stride, buffer);
217}
218
219static struct blip_t* _GBCoreGetAudioChannel(struct mCore* core, int ch) {
220	struct GB* gb = core->board;
221	switch (ch) {
222	case 0:
223		return gb->audio.left;
224	case 1:
225		return gb->audio.right;
226	default:
227		return NULL;
228	}
229}
230
231static void _GBCoreSetAudioBufferSize(struct mCore* core, size_t samples) {
232	struct GB* gb = core->board;
233	GBAudioResizeBuffer(&gb->audio, samples);
234}
235
236static size_t _GBCoreGetAudioBufferSize(struct mCore* core) {
237	struct GB* gb = core->board;
238	return gb->audio.samples;
239}
240
241static void _GBCoreAddCoreCallbacks(struct mCore* core, struct mCoreCallbacks* coreCallbacks) {
242	struct GB* gb = core->board;
243	*mCoreCallbacksListAppend(&gb->coreCallbacks) = *coreCallbacks;
244}
245
246static void _GBCoreClearCoreCallbacks(struct mCore* core) {
247	struct GB* gb = core->board;
248	mCoreCallbacksListClear(&gb->coreCallbacks);
249}
250
251static void _GBCoreSetAVStream(struct mCore* core, struct mAVStream* stream) {
252	struct GB* gb = core->board;
253	gb->stream = stream;
254	if (stream && stream->videoDimensionsChanged) {
255		stream->videoDimensionsChanged(stream, GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
256	}
257}
258
259static bool _GBCoreLoadROM(struct mCore* core, struct VFile* vf) {
260	return GBLoadROM(core->board, vf);
261}
262
263static bool _GBCoreLoadBIOS(struct mCore* core, struct VFile* vf, int type) {
264	UNUSED(type);
265	GBLoadBIOS(core->board, vf);
266	return true;
267}
268
269static bool _GBCoreLoadSave(struct mCore* core, struct VFile* vf) {
270	return GBLoadSave(core->board, vf);
271}
272
273static bool _GBCoreLoadTemporarySave(struct mCore* core, struct VFile* vf) {
274	struct GB* gb = core->board;
275	GBSavedataMask(gb, vf, false);
276	return true; // TODO: Return a real value
277}
278
279static bool _GBCoreLoadPatch(struct mCore* core, struct VFile* vf) {
280	if (!vf) {
281		return false;
282	}
283	struct Patch patch;
284	if (!loadPatch(vf, &patch)) {
285		return false;
286	}
287	GBApplyPatch(core->board, &patch);
288	return true;
289}
290
291static void _GBCoreUnloadROM(struct mCore* core) {
292	struct GBCore* gbcore = (struct GBCore*) core;
293	struct LR35902Core* cpu = core->cpu;
294	if (gbcore->cheatDevice) {
295		LR35902HotplugDetach(cpu, CPU_COMPONENT_CHEAT_DEVICE);
296		cpu->components[CPU_COMPONENT_CHEAT_DEVICE] = NULL;
297		mCheatDeviceDestroy(gbcore->cheatDevice);
298		gbcore->cheatDevice = NULL;
299	}
300	return GBUnloadROM(core->board);
301}
302
303static void _GBCoreChecksum(const struct mCore* core, void* data, enum mCoreChecksumType type) {
304	struct GB* gb = (struct GB*) core->board;
305	switch (type) {
306	case CHECKSUM_CRC32:
307		memcpy(data, &gb->romCrc32, sizeof(gb->romCrc32));
308		break;
309	}
310	return;
311}
312
313static void _GBCoreReset(struct mCore* core) {
314	struct GBCore* gbcore = (struct GBCore*) core;
315	struct GB* gb = (struct GB*) core->board;
316	if (gbcore->renderer.outputBuffer) {
317		GBVideoAssociateRenderer(&gb->video, &gbcore->renderer.d);
318	}
319
320	if (gb->memory.rom) {
321		struct GBCartridgeOverride override;
322		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
323		override.headerCrc32 = doCrc32(cart, sizeof(*cart));
324		if (GBOverrideFind(gbcore->overrides, &override)) {
325			GBOverrideApply(gb, &override);
326		}
327	}
328
329#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
330	if (!gb->biosVf && core->opts.useBios) {
331		struct VFile* bios = NULL;
332		bool found = false;
333		if (core->opts.bios) {
334			bios = VFileOpen(core->opts.bios, O_RDONLY);
335			if (bios && GBIsBIOS(bios)) {
336				found = true;
337			} else if (bios) {
338				bios->close(bios);
339				bios = NULL;
340			}
341		}
342		if (!found) {
343			GBDetectModel(gb);
344			const char* configPath = NULL;
345
346			switch (gb->model) {
347			case GB_MODEL_DMG:
348			case GB_MODEL_SGB: // TODO
349				configPath = mCoreConfigGetValue(&core->config, "gb.bios");
350				break;
351			case GB_MODEL_CGB:
352			case GB_MODEL_AGB:
353				configPath = mCoreConfigGetValue(&core->config, "gbc.bios");
354				break;
355			default:
356				break;
357			};
358			if (configPath) {
359				bios = VFileOpen(configPath, O_RDONLY);
360			}
361			if (bios && GBIsBIOS(bios)) {
362				found = true;
363			} else if (bios) {
364				bios->close(bios);
365				bios = NULL;
366			}
367		}
368		if (!found) {
369			char path[PATH_MAX];
370			mCoreConfigDirectory(path, PATH_MAX);
371			switch (gb->model) {
372			case GB_MODEL_DMG:
373			case GB_MODEL_SGB: // TODO
374				strncat(path, PATH_SEP "gb_bios.bin", PATH_MAX - strlen(path));
375				break;
376			case GB_MODEL_CGB:
377			case GB_MODEL_AGB:
378				strncat(path, PATH_SEP "gbc_bios.bin", PATH_MAX - strlen(path));
379				break;
380			default:
381				break;
382			};
383			bios = VFileOpen(path, O_RDONLY);
384			if (bios && GBIsBIOS(bios)) {
385				found = true;
386			} else if (bios) {
387				bios->close(bios);
388				bios = NULL;
389			}
390		}
391		if (bios) {
392			GBLoadBIOS(gb, bios);
393		}
394	}
395#endif
396
397	LR35902Reset(core->cpu);
398}
399
400static void _GBCoreRunFrame(struct mCore* core) {
401	struct GB* gb = core->board;
402	int32_t frameCounter = gb->video.frameCounter;
403	while (gb->video.frameCounter == frameCounter) {
404		LR35902Run(core->cpu);
405	}
406}
407
408static void _GBCoreRunLoop(struct mCore* core) {
409	LR35902Run(core->cpu);
410}
411
412static void _GBCoreStep(struct mCore* core) {
413	struct LR35902Core* cpu = core->cpu;
414	do {
415		LR35902Tick(cpu);
416	} while (cpu->executionState != LR35902_CORE_FETCH);
417}
418
419static size_t _GBCoreStateSize(struct mCore* core) {
420	UNUSED(core);
421	return sizeof(struct GBSerializedState);
422}
423
424static bool _GBCoreLoadState(struct mCore* core, const void* state) {
425	return GBDeserialize(core->board, state);
426}
427
428static bool _GBCoreSaveState(struct mCore* core, void* state) {
429	struct LR35902Core* cpu = core->cpu;
430	while (cpu->executionState != LR35902_CORE_FETCH) {
431		LR35902Tick(cpu);
432	}
433	GBSerialize(core->board, state);
434	return true;
435}
436
437static void _GBCoreSetKeys(struct mCore* core, uint32_t keys) {
438	struct GBCore* gbcore = (struct GBCore*) core;
439	gbcore->keys = keys;
440	GBTestKeypadIRQ(core->board);
441}
442
443static void _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
444	struct GBCore* gbcore = (struct GBCore*) core;
445	gbcore->keys |= keys;
446	GBTestKeypadIRQ(core->board);
447}
448
449static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
450	struct GBCore* gbcore = (struct GBCore*) core;
451	gbcore->keys &= ~keys;
452}
453
454static int32_t _GBCoreFrameCounter(const struct mCore* core) {
455	const struct GB* gb = core->board;
456	return gb->video.frameCounter;
457}
458
459static int32_t _GBCoreFrameCycles(const  struct mCore* core) {
460	UNUSED(core);
461	return GB_VIDEO_TOTAL_LENGTH;
462}
463
464static int32_t _GBCoreFrequency(const struct mCore* core) {
465	UNUSED(core);
466	// TODO: GB differences
467	return DMG_LR35902_FREQUENCY;
468}
469
470static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
471	GBGetGameTitle(core->board, title);
472}
473
474static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
475	GBGetGameCode(core->board, title);
476}
477
478static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
479	struct GB* gb = core->board;
480	switch (type) {
481	case mPERIPH_ROTATION:
482		gb->memory.rotation = periph;
483		break;
484	case mPERIPH_RUMBLE:
485		gb->memory.rumble = periph;
486		break;
487	case mPERIPH_IMAGE_SOURCE:
488		gb->memory.cam = periph;
489		break;
490	default:
491		return;
492	}
493}
494
495static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
496	struct LR35902Core* cpu = core->cpu;
497	return cpu->memory.load8(cpu, address);
498}
499
500static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
501	struct LR35902Core* cpu = core->cpu;
502	return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
503}
504
505static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
506	struct LR35902Core* cpu = core->cpu;
507	return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
508	       (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
509}
510
511static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
512	struct LR35902Core* cpu = core->cpu;
513	cpu->memory.store8(cpu, address, value);
514}
515
516static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_t value) {
517	struct LR35902Core* cpu = core->cpu;
518	cpu->memory.store8(cpu, address, value);
519	cpu->memory.store8(cpu, address + 1, value >> 8);
520}
521
522static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
523	struct LR35902Core* cpu = core->cpu;
524	cpu->memory.store8(cpu, address, value);
525	cpu->memory.store8(cpu, address + 1, value >> 8);
526	cpu->memory.store8(cpu, address + 2, value >> 16);
527	cpu->memory.store8(cpu, address + 3, value >> 24);
528}
529
530static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
531	struct LR35902Core* cpu = core->cpu;
532	return GBView8(cpu, address, segment);
533}
534
535static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
536	struct LR35902Core* cpu = core->cpu;
537	return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
538}
539
540static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
541	struct LR35902Core* cpu = core->cpu;
542	return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
543	       (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
544}
545
546static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
547	struct LR35902Core* cpu = core->cpu;
548	GBPatch8(cpu, address, value, NULL, segment);
549}
550
551static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_t value) {
552	struct LR35902Core* cpu = core->cpu;
553	GBPatch8(cpu, address, value, NULL, segment);
554	GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
555}
556
557static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
558	struct LR35902Core* cpu = core->cpu;
559	GBPatch8(cpu, address, value, NULL, segment);
560	GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
561	GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
562	GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
563}
564
565size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
566	const struct GB* gb = core->board;
567	switch (gb->model) {
568	case GB_MODEL_DMG:
569	case GB_MODEL_SGB:
570	default:
571		*blocks = _GBMemoryBlocks;
572		return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
573	case GB_MODEL_CGB:
574	case GB_MODEL_AGB:
575		*blocks = _GBCMemoryBlocks;
576		return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
577	}
578}
579
580void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
581	struct GB* gb = core->board;
582	bool isCgb = gb->model >= GB_MODEL_CGB;
583	switch (id) {
584	default:
585		return NULL;
586	case GB_REGION_CART_BANK0:
587		*sizeOut = gb->memory.romSize;
588		return gb->memory.rom;
589	case GB_REGION_VRAM:
590		*sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
591		return gb->video.vram;
592	case GB_REGION_EXTERNAL_RAM:
593		*sizeOut = gb->sramSize;
594		return gb->memory.sram;
595	case GB_REGION_WORKING_RAM_BANK0:
596		*sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
597		return gb->memory.wram;
598	case GB_BASE_OAM:
599		*sizeOut = GB_SIZE_OAM;
600		return gb->video.oam.raw;
601	case GB_BASE_HRAM:
602		*sizeOut = GB_SIZE_HRAM;
603		return gb->memory.hram;
604	}
605}
606
607#ifdef USE_DEBUGGERS
608static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
609	UNUSED(core);
610	switch (type) {
611	case DEBUGGER_CLI:
612		return true;
613	default:
614		return false;
615	}
616}
617
618static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
619	struct GBCore* gbcore = (struct GBCore*) core;
620	struct GB* gb = core->board;
621	if (!gbcore->debuggerPlatform) {
622		struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
623		if (gb->model >= GB_MODEL_CGB) {
624			platform->segments = _GBCSegments;
625		} else {
626			platform->segments = _GBSegments;
627		}
628		gbcore->debuggerPlatform = &platform->d;
629	}
630	return gbcore->debuggerPlatform;
631}
632
633static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
634	return GBCLIDebuggerCreate(core);
635}
636
637static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
638	struct LR35902Core* cpu = core->cpu;
639	if (core->debugger) {
640		LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
641	}
642	cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
643	LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
644	core->debugger = debugger;
645}
646
647static void _GBCoreDetachDebugger(struct mCore* core) {
648	struct LR35902Core* cpu = core->cpu;
649	if (core->debugger) {
650		LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
651	}
652	cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
653	core->debugger = NULL;
654}
655
656static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
657	core->symbolTable = mDebuggerSymbolTableCreate();
658#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
659	if (!vf) {
660		vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
661	}
662#endif
663	if (!vf) {
664		return;
665	}
666	GBLoadSymbols(core->symbolTable, vf);
667}
668#endif
669
670static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
671	struct GBCore* gbcore = (struct GBCore*) core;
672	if (!gbcore->cheatDevice) {
673		gbcore->cheatDevice = GBCheatDeviceCreate();
674		((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
675		LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
676		gbcore->cheatDevice->p = core;
677	}
678	return gbcore->cheatDevice;
679}
680
681static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
682	struct GB* gb = core->board;
683	struct VFile* vf = gb->sramVf;
684	if (vf) {
685		*sram = malloc(vf->size(vf));
686		vf->seek(vf, 0, SEEK_SET);
687		return vf->read(vf, *sram, vf->size(vf));
688	}
689	*sram = malloc(gb->sramSize);
690	memcpy(*sram, gb->memory.sram, gb->sramSize);
691	return gb->sramSize;
692}
693
694static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
695	struct GB* gb = core->board;
696	if (!writeback) {
697		struct VFile* vf = VFileMemChunk(sram, size);
698		GBSavedataMask(gb, vf, true);
699		return true;
700	}
701	struct VFile* vf = gb->sramVf;
702	if (vf) {
703		vf->seek(vf, 0, SEEK_SET);
704		return vf->write(vf, sram, size) > 0;
705	}
706	if (size > 0x20000) {
707		size = 0x20000;
708	}
709	GBResizeSram(gb, size);
710	memcpy(gb->memory.sram, sram, size);
711	return true;
712}
713
714static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
715	UNUSED(core);
716	*info = _GBVideoLayers;
717	return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
718}
719
720static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
721	UNUSED(core);
722	*info = _GBAudioChannels;
723	return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
724}
725
726static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
727	struct GB* gb = core->board;
728	switch (id) {
729	case 0:
730		gb->video.renderer->disableBG = !enable;
731		break;
732	case 1:
733		gb->video.renderer->disableOBJ = !enable;
734		break;
735	case 2:
736		gb->video.renderer->disableWIN = !enable;
737		break;
738	default:
739		break;
740	}
741}
742
743static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
744	struct GB* gb = core->board;
745	switch (id) {
746	case 0:
747	case 1:
748	case 2:
749	case 3:
750		gb->audio.forceDisableCh[id] = !enable;
751		break;
752	default:
753		break;
754	}
755}
756
757static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
758	struct GBCore* gbcore = (struct GBCore*) core;
759	struct GB* gb = core->board;
760	gbcore->logContext = context;
761
762	int channelId = mVideoLoggerAddChannel(context);
763	gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
764	mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
765	mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
766	gbcore->proxyRenderer.logger->block = false;
767
768	GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
769	GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
770}
771
772static void _GBCoreEndVideoLog(struct mCore* core) {
773	struct GBCore* gbcore = (struct GBCore*) core;
774	struct GB* gb = core->board;
775	GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
776	free(gbcore->proxyRenderer.logger);
777	gbcore->proxyRenderer.logger = NULL;
778}
779
780struct mCore* GBCoreCreate(void) {
781	struct GBCore* gbcore = malloc(sizeof(*gbcore));
782	struct mCore* core = &gbcore->d;
783	memset(&core->opts, 0, sizeof(core->opts));
784	core->cpu = NULL;
785	core->board = NULL;
786	core->debugger = NULL;
787	core->symbolTable = NULL;
788	core->init = _GBCoreInit;
789	core->deinit = _GBCoreDeinit;
790	core->platform = _GBCorePlatform;
791	core->setSync = _GBCoreSetSync;
792	core->loadConfig = _GBCoreLoadConfig;
793	core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
794	core->setVideoBuffer = _GBCoreSetVideoBuffer;
795	core->getPixels = _GBCoreGetPixels;
796	core->putPixels = _GBCorePutPixels;
797	core->getAudioChannel = _GBCoreGetAudioChannel;
798	core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
799	core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
800	core->setAVStream = _GBCoreSetAVStream;
801	core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
802	core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
803	core->isROM = GBIsROM;
804	core->loadROM = _GBCoreLoadROM;
805	core->loadBIOS = _GBCoreLoadBIOS;
806	core->loadSave = _GBCoreLoadSave;
807	core->loadTemporarySave = _GBCoreLoadTemporarySave;
808	core->loadPatch = _GBCoreLoadPatch;
809	core->unloadROM = _GBCoreUnloadROM;
810	core->checksum = _GBCoreChecksum;
811	core->reset = _GBCoreReset;
812	core->runFrame = _GBCoreRunFrame;
813	core->runLoop = _GBCoreRunLoop;
814	core->step = _GBCoreStep;
815	core->stateSize = _GBCoreStateSize;
816	core->loadState = _GBCoreLoadState;
817	core->saveState = _GBCoreSaveState;
818	core->setKeys = _GBCoreSetKeys;
819	core->addKeys = _GBCoreAddKeys;
820	core->clearKeys = _GBCoreClearKeys;
821	core->frameCounter = _GBCoreFrameCounter;
822	core->frameCycles = _GBCoreFrameCycles;
823	core->frequency = _GBCoreFrequency;
824	core->getGameTitle = _GBCoreGetGameTitle;
825	core->getGameCode = _GBCoreGetGameCode;
826	core->setPeripheral = _GBCoreSetPeripheral;
827	core->busRead8 = _GBCoreBusRead8;
828	core->busRead16 = _GBCoreBusRead16;
829	core->busRead32 = _GBCoreBusRead32;
830	core->busWrite8 = _GBCoreBusWrite8;
831	core->busWrite16 = _GBCoreBusWrite16;
832	core->busWrite32 = _GBCoreBusWrite32;
833	core->rawRead8 = _GBCoreRawRead8;
834	core->rawRead16 = _GBCoreRawRead16;
835	core->rawRead32 = _GBCoreRawRead32;
836	core->rawWrite8 = _GBCoreRawWrite8;
837	core->rawWrite16 = _GBCoreRawWrite16;
838	core->rawWrite32 = _GBCoreRawWrite32;
839	core->listMemoryBlocks = _GBListMemoryBlocks;
840	core->getMemoryBlock = _GBGetMemoryBlock;
841#ifdef USE_DEBUGGERS
842	core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
843	core->debuggerPlatform = _GBCoreDebuggerPlatform;
844	core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
845	core->attachDebugger = _GBCoreAttachDebugger;
846	core->detachDebugger = _GBCoreDetachDebugger;
847	core->loadSymbols = _GBCoreLoadSymbols;
848#endif
849	core->cheatDevice = _GBCoreCheatDevice;
850	core->savedataClone = _GBCoreSavedataClone;
851	core->savedataRestore = _GBCoreSavedataRestore;
852	core->listVideoLayers = _GBCoreListVideoLayers;
853	core->listAudioChannels = _GBCoreListAudioChannels;
854	core->enableVideoLayer = _GBCoreEnableVideoLayer;
855	core->enableAudioChannel = _GBCoreEnableAudioChannel;
856#ifndef MINIMAL_CORE
857	core->startVideoLog = _GBCoreStartVideoLog;
858	core->endVideoLog = _GBCoreEndVideoLog;
859#endif
860	return core;
861}
862
863#ifndef MINIMAL_CORE
864static void _GBVLPStartFrameCallback(void *context) {
865	struct mCore* core = context;
866	struct GBCore* gbcore = (struct GBCore*) core;
867	struct GB* gb = core->board;
868
869	if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
870		GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
871		mVideoLogContextRewind(gbcore->logContext, core);
872		GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
873	}
874}
875
876static bool _GBVLPInit(struct mCore* core) {
877	struct GBCore* gbcore = (struct GBCore*) core;
878	if (!_GBCoreInit(core)) {
879		return false;
880	}
881	gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
882	mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
883	GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
884	memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
885	gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
886	gbcore->logCallbacks.context = core;
887	core->addCoreCallbacks(core, &gbcore->logCallbacks);
888	return true;
889}
890
891static void _GBVLPDeinit(struct mCore* core) {
892	struct GBCore* gbcore = (struct GBCore*) core;
893	if (gbcore->logContext) {
894		mVideoLogContextDestroy(core, gbcore->logContext);
895	}
896	_GBCoreDeinit(core);
897}
898
899static void _GBVLPReset(struct mCore* core) {
900	struct GBCore* gbcore = (struct GBCore*) core;
901	struct GB* gb = (struct GB*) core->board;
902	if (gb->video.renderer == &gbcore->proxyRenderer.d) {
903		GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
904	} else if (gbcore->renderer.outputBuffer) {
905		struct GBVideoRenderer* renderer = &gbcore->renderer.d;
906		GBVideoAssociateRenderer(&gb->video, renderer);
907	}
908
909	LR35902Reset(core->cpu);
910	mVideoLogContextRewind(gbcore->logContext, core);
911	GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
912
913	// Make sure CPU loop never spins
914	GBHalt(gb->cpu);
915	gb->memory.ie = 0;
916	gb->memory.ime = false;
917}
918
919static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
920	struct GBCore* gbcore = (struct GBCore*) core;
921	gbcore->logContext = mVideoLogContextCreate(NULL);
922	if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
923		mVideoLogContextDestroy(core, gbcore->logContext);
924		gbcore->logContext = NULL;
925		return false;
926	}
927	mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
928	return true;
929}
930
931static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
932	struct GB* gb = (struct GB*) core->board;
933	const struct GBSerializedState* state = buffer;
934
935	gb->timing.root = NULL;
936	gb->model = state->model;
937
938	gb->cpu->pc = GB_BASE_HRAM;
939	gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
940
941	GBVideoDeserialize(&gb->video, state);
942	GBIODeserialize(gb, state);
943	GBAudioReset(&gb->audio);
944
945	// Make sure CPU loop never spins
946	GBHalt(gb->cpu);
947	gb->memory.ie = 0;
948	gb->memory.ime = false;
949
950	return true;
951}
952
953static bool _returnTrue(struct VFile* vf) {
954	UNUSED(vf);
955	return true;
956}
957
958struct mCore* GBVideoLogPlayerCreate(void) {
959	struct mCore* core = GBCoreCreate();
960	core->init = _GBVLPInit;
961	core->deinit = _GBVLPDeinit;
962	core->reset = _GBVLPReset;
963	core->loadROM = _GBVLPLoadROM;
964	core->loadState = _GBVLPLoadState;
965	core->isROM = _returnTrue;
966	return core;
967}
968#else
969struct mCore* GBVideoLogPlayerCreate(void) {
970	return false;
971}
972#endif