all repos — mgba @ d7fc09768d0c5771f11ad4cf1b40851e7a11a6aa

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