all repos — mgba @ 126afa12d9ac4bbbc1d2db423aafb6ccf6dcf5a1

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