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 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 case mPERIPH_IMAGE_SOURCE:
483 gb->memory.cam = periph;
484 break;
485 default:
486 return;
487 }
488}
489
490static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
491 struct LR35902Core* cpu = core->cpu;
492 return cpu->memory.load8(cpu, address);
493}
494
495static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
496 struct LR35902Core* cpu = core->cpu;
497 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
498}
499
500static uint32_t _GBCoreBusRead32(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 (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
504}
505
506static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
507 struct LR35902Core* cpu = core->cpu;
508 cpu->memory.store8(cpu, address, value);
509}
510
511static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_t value) {
512 struct LR35902Core* cpu = core->cpu;
513 cpu->memory.store8(cpu, address, value);
514 cpu->memory.store8(cpu, address + 1, value >> 8);
515}
516
517static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
518 struct LR35902Core* cpu = core->cpu;
519 cpu->memory.store8(cpu, address, value);
520 cpu->memory.store8(cpu, address + 1, value >> 8);
521 cpu->memory.store8(cpu, address + 2, value >> 16);
522 cpu->memory.store8(cpu, address + 3, value >> 24);
523}
524
525static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
526 struct LR35902Core* cpu = core->cpu;
527 return GBView8(cpu, address, segment);
528}
529
530static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
531 struct LR35902Core* cpu = core->cpu;
532 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
533}
534
535static uint32_t _GBCoreRawRead32(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 (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
539}
540
541static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
542 struct LR35902Core* cpu = core->cpu;
543 GBPatch8(cpu, address, value, NULL, segment);
544}
545
546static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_t value) {
547 struct LR35902Core* cpu = core->cpu;
548 GBPatch8(cpu, address, value, NULL, segment);
549 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
550}
551
552static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
553 struct LR35902Core* cpu = core->cpu;
554 GBPatch8(cpu, address, value, NULL, segment);
555 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
556 GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
557 GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
558}
559
560size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
561 const struct GB* gb = core->board;
562 switch (gb->model) {
563 case GB_MODEL_DMG:
564 case GB_MODEL_SGB:
565 default:
566 *blocks = _GBMemoryBlocks;
567 return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
568 case GB_MODEL_CGB:
569 case GB_MODEL_AGB:
570 *blocks = _GBCMemoryBlocks;
571 return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
572 }
573}
574
575void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
576 struct GB* gb = core->board;
577 bool isCgb = gb->model >= GB_MODEL_CGB;
578 switch (id) {
579 default:
580 return NULL;
581 case GB_REGION_CART_BANK0:
582 *sizeOut = gb->memory.romSize;
583 return gb->memory.rom;
584 case GB_REGION_VRAM:
585 *sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
586 return gb->video.vram;
587 case GB_REGION_EXTERNAL_RAM:
588 *sizeOut = gb->sramSize;
589 return gb->memory.sram;
590 case GB_REGION_WORKING_RAM_BANK0:
591 *sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
592 return gb->memory.wram;
593 case GB_BASE_OAM:
594 *sizeOut = GB_SIZE_OAM;
595 return gb->video.oam.raw;
596 case GB_BASE_HRAM:
597 *sizeOut = GB_SIZE_HRAM;
598 return gb->memory.hram;
599 }
600}
601
602#ifdef USE_DEBUGGERS
603static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
604 UNUSED(core);
605 switch (type) {
606 case DEBUGGER_CLI:
607 return true;
608 default:
609 return false;
610 }
611}
612
613static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
614 struct GBCore* gbcore = (struct GBCore*) core;
615 struct GB* gb = core->board;
616 if (!gbcore->debuggerPlatform) {
617 struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
618 if (gb->model >= GB_MODEL_CGB) {
619 platform->segments = _GBCSegments;
620 } else {
621 platform->segments = _GBSegments;
622 }
623 gbcore->debuggerPlatform = &platform->d;
624 }
625 return gbcore->debuggerPlatform;
626}
627
628static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
629 return GBCLIDebuggerCreate(core);
630}
631
632static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
633 struct LR35902Core* cpu = core->cpu;
634 if (core->debugger) {
635 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
636 }
637 cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
638 LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
639 core->debugger = debugger;
640}
641
642static void _GBCoreDetachDebugger(struct mCore* core) {
643 struct LR35902Core* cpu = core->cpu;
644 if (core->debugger) {
645 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
646 }
647 cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
648 core->debugger = NULL;
649}
650
651static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
652 core->symbolTable = mDebuggerSymbolTableCreate();
653#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
654 if (!vf) {
655 vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
656 }
657#endif
658 if (!vf) {
659 return;
660 }
661 GBLoadSymbols(core->symbolTable, vf);
662}
663#endif
664
665static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
666 struct GBCore* gbcore = (struct GBCore*) core;
667 if (!gbcore->cheatDevice) {
668 gbcore->cheatDevice = GBCheatDeviceCreate();
669 ((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
670 LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
671 gbcore->cheatDevice->p = core;
672 }
673 return gbcore->cheatDevice;
674}
675
676static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
677 struct GB* gb = core->board;
678 struct VFile* vf = gb->sramVf;
679 if (vf) {
680 *sram = malloc(vf->size(vf));
681 vf->seek(vf, 0, SEEK_SET);
682 return vf->read(vf, *sram, vf->size(vf));
683 }
684 *sram = malloc(gb->sramSize);
685 memcpy(*sram, gb->memory.sram, gb->sramSize);
686 return gb->sramSize;
687}
688
689static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
690 struct GB* gb = core->board;
691 if (!writeback) {
692 struct VFile* vf = VFileMemChunk(sram, size);
693 GBSavedataMask(gb, vf, true);
694 return true;
695 }
696 struct VFile* vf = gb->sramVf;
697 if (vf) {
698 vf->seek(vf, 0, SEEK_SET);
699 return vf->write(vf, sram, size) > 0;
700 }
701 if (size > 0x20000) {
702 size = 0x20000;
703 }
704 GBResizeSram(gb, size);
705 memcpy(gb->memory.sram, sram, size);
706 return true;
707}
708
709static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
710 UNUSED(core);
711 *info = _GBVideoLayers;
712 return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
713}
714
715static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
716 UNUSED(core);
717 *info = _GBAudioChannels;
718 return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
719}
720
721static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
722 struct GB* gb = core->board;
723 switch (id) {
724 case 0:
725 gb->video.renderer->disableBG = !enable;
726 break;
727 case 1:
728 gb->video.renderer->disableOBJ = !enable;
729 break;
730 case 2:
731 gb->video.renderer->disableWIN = !enable;
732 break;
733 default:
734 break;
735 }
736}
737
738static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
739 struct GB* gb = core->board;
740 switch (id) {
741 case 0:
742 case 1:
743 case 2:
744 case 3:
745 gb->audio.forceDisableCh[id] = !enable;
746 break;
747 default:
748 break;
749 }
750}
751
752static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
753 struct GBCore* gbcore = (struct GBCore*) core;
754 struct GB* gb = core->board;
755 gbcore->logContext = context;
756
757 int channelId = mVideoLoggerAddChannel(context);
758 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
759 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
760 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
761 gbcore->proxyRenderer.logger->block = false;
762
763 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
764 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
765}
766
767static void _GBCoreEndVideoLog(struct mCore* core) {
768 struct GBCore* gbcore = (struct GBCore*) core;
769 struct GB* gb = core->board;
770 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
771 free(gbcore->proxyRenderer.logger);
772 gbcore->proxyRenderer.logger = NULL;
773}
774
775struct mCore* GBCoreCreate(void) {
776 struct GBCore* gbcore = malloc(sizeof(*gbcore));
777 struct mCore* core = &gbcore->d;
778 memset(&core->opts, 0, sizeof(core->opts));
779 core->cpu = NULL;
780 core->board = NULL;
781 core->debugger = NULL;
782 core->symbolTable = NULL;
783 core->init = _GBCoreInit;
784 core->deinit = _GBCoreDeinit;
785 core->platform = _GBCorePlatform;
786 core->setSync = _GBCoreSetSync;
787 core->loadConfig = _GBCoreLoadConfig;
788 core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
789 core->setVideoBuffer = _GBCoreSetVideoBuffer;
790 core->getPixels = _GBCoreGetPixels;
791 core->putPixels = _GBCorePutPixels;
792 core->getAudioChannel = _GBCoreGetAudioChannel;
793 core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
794 core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
795 core->setAVStream = _GBCoreSetAVStream;
796 core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
797 core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
798 core->isROM = GBIsROM;
799 core->loadROM = _GBCoreLoadROM;
800 core->loadBIOS = _GBCoreLoadBIOS;
801 core->loadSave = _GBCoreLoadSave;
802 core->loadTemporarySave = _GBCoreLoadTemporarySave;
803 core->loadPatch = _GBCoreLoadPatch;
804 core->unloadROM = _GBCoreUnloadROM;
805 core->checksum = _GBCoreChecksum;
806 core->reset = _GBCoreReset;
807 core->runFrame = _GBCoreRunFrame;
808 core->runLoop = _GBCoreRunLoop;
809 core->step = _GBCoreStep;
810 core->stateSize = _GBCoreStateSize;
811 core->loadState = _GBCoreLoadState;
812 core->saveState = _GBCoreSaveState;
813 core->setKeys = _GBCoreSetKeys;
814 core->addKeys = _GBCoreAddKeys;
815 core->clearKeys = _GBCoreClearKeys;
816 core->frameCounter = _GBCoreFrameCounter;
817 core->frameCycles = _GBCoreFrameCycles;
818 core->frequency = _GBCoreFrequency;
819 core->getGameTitle = _GBCoreGetGameTitle;
820 core->getGameCode = _GBCoreGetGameCode;
821 core->setPeripheral = _GBCoreSetPeripheral;
822 core->busRead8 = _GBCoreBusRead8;
823 core->busRead16 = _GBCoreBusRead16;
824 core->busRead32 = _GBCoreBusRead32;
825 core->busWrite8 = _GBCoreBusWrite8;
826 core->busWrite16 = _GBCoreBusWrite16;
827 core->busWrite32 = _GBCoreBusWrite32;
828 core->rawRead8 = _GBCoreRawRead8;
829 core->rawRead16 = _GBCoreRawRead16;
830 core->rawRead32 = _GBCoreRawRead32;
831 core->rawWrite8 = _GBCoreRawWrite8;
832 core->rawWrite16 = _GBCoreRawWrite16;
833 core->rawWrite32 = _GBCoreRawWrite32;
834 core->listMemoryBlocks = _GBListMemoryBlocks;
835 core->getMemoryBlock = _GBGetMemoryBlock;
836#ifdef USE_DEBUGGERS
837 core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
838 core->debuggerPlatform = _GBCoreDebuggerPlatform;
839 core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
840 core->attachDebugger = _GBCoreAttachDebugger;
841 core->detachDebugger = _GBCoreDetachDebugger;
842 core->loadSymbols = _GBCoreLoadSymbols;
843#endif
844 core->cheatDevice = _GBCoreCheatDevice;
845 core->savedataClone = _GBCoreSavedataClone;
846 core->savedataRestore = _GBCoreSavedataRestore;
847 core->listVideoLayers = _GBCoreListVideoLayers;
848 core->listAudioChannels = _GBCoreListAudioChannels;
849 core->enableVideoLayer = _GBCoreEnableVideoLayer;
850 core->enableAudioChannel = _GBCoreEnableAudioChannel;
851#ifndef MINIMAL_CORE
852 core->startVideoLog = _GBCoreStartVideoLog;
853 core->endVideoLog = _GBCoreEndVideoLog;
854#endif
855 return core;
856}
857
858#ifndef MINIMAL_CORE
859static void _GBVLPStartFrameCallback(void *context) {
860 struct mCore* core = context;
861 struct GBCore* gbcore = (struct GBCore*) core;
862 struct GB* gb = core->board;
863
864 if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
865 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
866 mVideoLogContextRewind(gbcore->logContext, core);
867 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
868 }
869}
870
871static bool _GBVLPInit(struct mCore* core) {
872 struct GBCore* gbcore = (struct GBCore*) core;
873 if (!_GBCoreInit(core)) {
874 return false;
875 }
876 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
877 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
878 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
879 memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
880 gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
881 gbcore->logCallbacks.context = core;
882 core->addCoreCallbacks(core, &gbcore->logCallbacks);
883 return true;
884}
885
886static void _GBVLPDeinit(struct mCore* core) {
887 struct GBCore* gbcore = (struct GBCore*) core;
888 if (gbcore->logContext) {
889 mVideoLogContextDestroy(core, gbcore->logContext);
890 }
891 _GBCoreDeinit(core);
892}
893
894static void _GBVLPReset(struct mCore* core) {
895 struct GBCore* gbcore = (struct GBCore*) core;
896 struct GB* gb = (struct GB*) core->board;
897 if (gb->video.renderer == &gbcore->proxyRenderer.d) {
898 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
899 } else if (gbcore->renderer.outputBuffer) {
900 struct GBVideoRenderer* renderer = &gbcore->renderer.d;
901 GBVideoAssociateRenderer(&gb->video, renderer);
902 }
903
904 LR35902Reset(core->cpu);
905 mVideoLogContextRewind(gbcore->logContext, core);
906 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
907
908 // Make sure CPU loop never spins
909 GBHalt(gb->cpu);
910 gb->memory.ie = 0;
911 gb->memory.ime = false;
912}
913
914static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
915 struct GBCore* gbcore = (struct GBCore*) core;
916 gbcore->logContext = mVideoLogContextCreate(NULL);
917 if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
918 mVideoLogContextDestroy(core, gbcore->logContext);
919 gbcore->logContext = NULL;
920 return false;
921 }
922 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
923 return true;
924}
925
926static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
927 struct GB* gb = (struct GB*) core->board;
928 const struct GBSerializedState* state = buffer;
929
930 gb->timing.root = NULL;
931 gb->model = state->model;
932
933 gb->cpu->pc = GB_BASE_HRAM;
934 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
935
936 GBVideoDeserialize(&gb->video, state);
937 GBIODeserialize(gb, state);
938 GBAudioReset(&gb->audio);
939
940 // Make sure CPU loop never spins
941 GBHalt(gb->cpu);
942 gb->memory.ie = 0;
943 gb->memory.ime = false;
944
945 return true;
946}
947
948static bool _returnTrue(struct VFile* vf) {
949 UNUSED(vf);
950 return true;
951}
952
953struct mCore* GBVideoLogPlayerCreate(void) {
954 struct mCore* core = GBCoreCreate();
955 core->init = _GBVLPInit;
956 core->deinit = _GBVLPDeinit;
957 core->reset = _GBVLPReset;
958 core->loadROM = _GBVLPLoadROM;
959 core->loadState = _GBVLPLoadState;
960 core->isROM = _returnTrue;
961 return core;
962}
963#else
964struct mCore* GBVideoLogPlayerCreate(void) {
965 return false;
966}
967#endif