src/gb/gb.c (view raw)
1/* Copyright (c) 2013-2016 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include <mgba/internal/gb/gb.h>
7
8#include <mgba/internal/gb/io.h>
9#include <mgba/internal/gb/mbc.h>
10#include <mgba/internal/sm83/sm83.h>
11
12#include <mgba/core/core.h>
13#include <mgba/core/cheats.h>
14#include <mgba-util/crc32.h>
15#include <mgba-util/memory.h>
16#include <mgba-util/math.h>
17#include <mgba-util/patch.h>
18#include <mgba-util/vfs.h>
19
20#define CLEANUP_THRESHOLD 15
21
22const uint32_t CGB_SM83_FREQUENCY = 0x800000;
23const uint32_t SGB_SM83_FREQUENCY = 0x418B1E;
24
25const uint32_t GB_COMPONENT_MAGIC = 0x400000;
26
27static const uint8_t _knownHeader[4] = { 0xCE, 0xED, 0x66, 0x66};
28
29#define DMG0_BIOS_CHECKSUM 0xC2F5CC97
30#define DMG_BIOS_CHECKSUM 0x59C8598E
31#define MGB_BIOS_CHECKSUM 0xE6920754
32#define SGB_BIOS_CHECKSUM 0xEC8A83B9
33#define SGB2_BIOS_CHECKSUM 0X53D0DD63
34#define CGB_BIOS_CHECKSUM 0x41884E46
35#define AGB_BIOS_CHECKSUM 0xFFD6B0F1
36
37mLOG_DEFINE_CATEGORY(GB, "GB", "gb");
38
39static void GBInit(void* cpu, struct mCPUComponent* component);
40static void GBDeinit(struct mCPUComponent* component);
41static void GBInterruptHandlerInit(struct SM83InterruptHandler* irqh);
42static void GBProcessEvents(struct SM83Core* cpu);
43static void GBSetInterrupts(struct SM83Core* cpu, bool enable);
44static uint16_t GBIRQVector(struct SM83Core* cpu);
45static void GBIllegal(struct SM83Core* cpu);
46static void GBStop(struct SM83Core* cpu);
47
48static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate);
49
50void GBCreate(struct GB* gb) {
51 gb->d.id = GB_COMPONENT_MAGIC;
52 gb->d.init = GBInit;
53 gb->d.deinit = GBDeinit;
54}
55
56static void GBInit(void* cpu, struct mCPUComponent* component) {
57 struct GB* gb = (struct GB*) component;
58 gb->cpu = cpu;
59 gb->sync = NULL;
60
61 GBInterruptHandlerInit(&gb->cpu->irqh);
62 GBMemoryInit(gb);
63
64 gb->video.p = gb;
65 GBVideoInit(&gb->video);
66
67 gb->audio.p = gb;
68 GBAudioInit(&gb->audio, 2048, &gb->memory.io[GB_REG_NR52], GB_AUDIO_DMG); // TODO: Remove magic constant
69
70 gb->sio.p = gb;
71 GBSIOInit(&gb->sio);
72
73 gb->timer.p = gb;
74
75 gb->model = GB_MODEL_AUTODETECT;
76
77 gb->biosVf = NULL;
78 gb->romVf = NULL;
79 gb->sramVf = NULL;
80 gb->sramRealVf = NULL;
81
82 gb->isPristine = false;
83 gb->pristineRomSize = 0;
84 gb->yankedRomSize = 0;
85
86 mCoreCallbacksListInit(&gb->coreCallbacks, 0);
87 gb->stream = NULL;
88
89 mTimingInit(&gb->timing, &gb->cpu->cycles, &gb->cpu->nextEvent);
90 gb->audio.timing = &gb->timing;
91
92 gb->eiPending.name = "GB EI";
93 gb->eiPending.callback = _enableInterrupts;
94 gb->eiPending.context = gb;
95 gb->eiPending.priority = 0;
96}
97
98static void GBDeinit(struct mCPUComponent* component) {
99 struct GB* gb = (struct GB*) component;
100 mTimingDeinit(&gb->timing);
101}
102
103bool GBLoadROM(struct GB* gb, struct VFile* vf) {
104 if (!vf) {
105 return false;
106 }
107 GBUnloadROM(gb);
108 gb->romVf = vf;
109 gb->pristineRomSize = vf->size(vf);
110 vf->seek(vf, 0, SEEK_SET);
111 gb->isPristine = true;
112 gb->memory.rom = vf->map(vf, gb->pristineRomSize, MAP_READ);
113 if (!gb->memory.rom) {
114 return false;
115 }
116 gb->yankedRomSize = 0;
117 gb->memory.romSize = gb->pristineRomSize;
118 gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
119 memset(&gb->memory.mbcState, 0, sizeof(gb->memory.mbcState));
120 GBMBCReset(gb);
121
122 if (gb->cpu) {
123 struct SM83Core* cpu = gb->cpu;
124 cpu->memory.setActiveRegion(cpu, cpu->pc);
125 }
126
127 // TODO: error check
128 return true;
129}
130
131void GBYankROM(struct GB* gb) {
132 gb->yankedRomSize = gb->memory.romSize;
133 gb->yankedMbc = gb->memory.mbcType;
134 gb->memory.romSize = 0;
135 gb->memory.mbcType = GB_MBC_NONE;
136 GBMBCReset(gb);
137
138 if (gb->cpu) {
139 struct SM83Core* cpu = gb->cpu;
140 cpu->memory.setActiveRegion(cpu, cpu->pc);
141 }
142}
143
144static void GBSramDeinit(struct GB* gb) {
145 if (gb->sramVf) {
146 gb->sramVf->unmap(gb->sramVf, gb->memory.sram, gb->sramSize);
147 if (gb->memory.mbcType == GB_MBC3_RTC && gb->sramVf == gb->sramRealVf) {
148 GBMBCRTCWrite(gb);
149 }
150 gb->sramVf = NULL;
151 } else if (gb->memory.sram) {
152 mappedMemoryFree(gb->memory.sram, gb->sramSize);
153 }
154 gb->memory.sram = 0;
155}
156
157bool GBLoadSave(struct GB* gb, struct VFile* vf) {
158 GBSramDeinit(gb);
159 gb->sramVf = vf;
160 gb->sramRealVf = vf;
161 if (gb->sramSize) {
162 GBResizeSram(gb, gb->sramSize);
163 GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
164
165 if (gb->memory.mbcType == GB_MBC3_RTC) {
166 GBMBCRTCRead(gb);
167 }
168 }
169 return vf;
170}
171
172void GBResizeSram(struct GB* gb, size_t size) {
173 if (gb->memory.sram && size <= gb->sramSize) {
174 return;
175 }
176 struct VFile* vf = gb->sramVf;
177 if (vf) {
178 if (vf == gb->sramRealVf) {
179 ssize_t vfSize = vf->size(vf);
180 if (vfSize >= 0 && (size_t) vfSize < size) {
181 uint8_t extdataBuffer[0x100];
182 if (vfSize & 0xFF) {
183 vf->seek(vf, -(vfSize & 0xFF), SEEK_END);
184 vf->read(vf, extdataBuffer, vfSize & 0xFF);
185 }
186 if (gb->memory.sram) {
187 vf->unmap(vf, gb->memory.sram, gb->sramSize);
188 }
189 vf->truncate(vf, size + (vfSize & 0xFF));
190 if (vfSize & 0xFF) {
191 vf->seek(vf, size, SEEK_SET);
192 vf->write(vf, extdataBuffer, vfSize & 0xFF);
193 }
194 gb->memory.sram = vf->map(vf, size, MAP_WRITE);
195 memset(&gb->memory.sram[vfSize], 0xFF, size - vfSize);
196 } else if (size > gb->sramSize || !gb->memory.sram) {
197 if (gb->memory.sram) {
198 vf->unmap(vf, gb->memory.sram, gb->sramSize);
199 }
200 gb->memory.sram = vf->map(vf, size, MAP_WRITE);
201 }
202 } else {
203 if (gb->memory.sram) {
204 vf->unmap(vf, gb->memory.sram, gb->sramSize);
205 }
206 gb->memory.sram = vf->map(vf, size, MAP_READ);
207 }
208 if (gb->memory.sram == (void*) -1) {
209 gb->memory.sram = NULL;
210 }
211 } else if (size) {
212 uint8_t* newSram = anonymousMemoryMap(size);
213 if (gb->memory.sram) {
214 if (size > gb->sramSize) {
215 memcpy(newSram, gb->memory.sram, gb->sramSize);
216 memset(&newSram[gb->sramSize], 0xFF, size - gb->sramSize);
217 } else {
218 memcpy(newSram, gb->memory.sram, size);
219 }
220 mappedMemoryFree(gb->memory.sram, gb->sramSize);
221 } else {
222 memset(newSram, 0xFF, size);
223 }
224 gb->memory.sram = newSram;
225 }
226 if (gb->sramSize < size) {
227 gb->sramSize = size;
228 }
229}
230
231void GBSramClean(struct GB* gb, uint32_t frameCount) {
232 // TODO: Share with GBASavedataClean
233 if (!gb->sramVf) {
234 return;
235 }
236 if (gb->sramDirty & GB_SRAM_DIRT_NEW) {
237 gb->sramDirtAge = frameCount;
238 gb->sramDirty &= ~GB_SRAM_DIRT_NEW;
239 if (!(gb->sramDirty & GB_SRAM_DIRT_SEEN)) {
240 gb->sramDirty |= GB_SRAM_DIRT_SEEN;
241 }
242 } else if ((gb->sramDirty & GB_SRAM_DIRT_SEEN) && frameCount - gb->sramDirtAge > CLEANUP_THRESHOLD) {
243 if (gb->sramMaskWriteback) {
244 GBSavedataUnmask(gb);
245 }
246 if (gb->memory.mbcType == GB_MBC3_RTC) {
247 GBMBCRTCWrite(gb);
248 }
249 gb->sramDirty = 0;
250 if (gb->memory.sram && gb->sramVf->sync(gb->sramVf, gb->memory.sram, gb->sramSize)) {
251 mLOG(GB_MEM, INFO, "Savedata synced");
252 } else {
253 mLOG(GB_MEM, INFO, "Savedata failed to sync!");
254 }
255
256 size_t c;
257 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
258 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
259 if (callbacks->savedataUpdated) {
260 callbacks->savedataUpdated(callbacks->context);
261 }
262 }
263 }
264}
265
266void GBSavedataMask(struct GB* gb, struct VFile* vf, bool writeback) {
267 struct VFile* oldVf = gb->sramVf;
268 GBSramDeinit(gb);
269 if (oldVf && oldVf != gb->sramRealVf) {
270 oldVf->close(oldVf);
271 }
272 gb->sramVf = vf;
273 gb->sramMaskWriteback = writeback;
274 gb->memory.sram = vf->map(vf, gb->sramSize, MAP_READ);
275 GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
276}
277
278void GBSavedataUnmask(struct GB* gb) {
279 if (!gb->sramRealVf || gb->sramVf == gb->sramRealVf) {
280 return;
281 }
282 struct VFile* vf = gb->sramVf;
283 GBSramDeinit(gb);
284 gb->sramVf = gb->sramRealVf;
285 gb->memory.sram = gb->sramVf->map(gb->sramVf, gb->sramSize, MAP_WRITE);
286 if (gb->sramMaskWriteback) {
287 vf->seek(vf, 0, SEEK_SET);
288 vf->read(vf, gb->memory.sram, gb->sramSize);
289 gb->sramMaskWriteback = false;
290 }
291 GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
292 vf->close(vf);
293}
294
295void GBUnloadROM(struct GB* gb) {
296 // TODO: Share with GBAUnloadROM
297 off_t romBase = gb->memory.romBase - gb->memory.rom;
298 if (romBase >= 0 && ((size_t) romBase < gb->memory.romSize || (size_t) romBase < gb->yankedRomSize)) {
299 gb->memory.romBase = NULL;
300 }
301 if (gb->memory.rom && !gb->isPristine) {
302 if (gb->yankedRomSize) {
303 gb->yankedRomSize = 0;
304 }
305 mappedMemoryFree(gb->memory.rom, GB_SIZE_CART_MAX);
306 }
307
308 if (gb->romVf) {
309#ifndef FIXED_ROM_BUFFER
310 gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
311#endif
312 gb->romVf->close(gb->romVf);
313 gb->romVf = NULL;
314 }
315 gb->memory.rom = NULL;
316 gb->memory.mbcType = GB_MBC_AUTODETECT;
317 gb->isPristine = false;
318
319 gb->sramMaskWriteback = false;
320 GBSavedataUnmask(gb);
321 GBSramDeinit(gb);
322 if (gb->sramRealVf) {
323 gb->sramRealVf->close(gb->sramRealVf);
324 }
325 gb->sramRealVf = NULL;
326 gb->sramVf = NULL;
327 if (gb->memory.cam && gb->memory.cam->stopRequestImage) {
328 gb->memory.cam->stopRequestImage(gb->memory.cam);
329 }
330}
331
332void GBSynthesizeROM(struct VFile* vf) {
333 if (!vf) {
334 return;
335 }
336 const struct GBCartridge cart = {
337 .logo = { _knownHeader[0], _knownHeader[1], _knownHeader[2], _knownHeader[3]}
338 };
339
340 vf->seek(vf, 0x100, SEEK_SET);
341 vf->write(vf, &cart, sizeof(cart));
342}
343
344void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
345 gb->biosVf = vf;
346}
347
348void GBApplyPatch(struct GB* gb, struct Patch* patch) {
349 size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
350 if (!patchedSize) {
351 return;
352 }
353 if (patchedSize > GB_SIZE_CART_MAX) {
354 patchedSize = GB_SIZE_CART_MAX;
355 }
356 void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
357 if (!patch->applyPatch(patch, gb->memory.rom, gb->pristineRomSize, newRom, patchedSize)) {
358 mappedMemoryFree(newRom, GB_SIZE_CART_MAX);
359 return;
360 }
361 if (gb->romVf) {
362#ifndef FIXED_ROM_BUFFER
363 gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
364#endif
365 gb->romVf->close(gb->romVf);
366 gb->romVf = NULL;
367 }
368 gb->isPristine = false;
369 if (gb->memory.romBase == gb->memory.rom) {
370 gb->memory.romBase = newRom;
371 }
372 gb->memory.rom = newRom;
373 gb->memory.romSize = patchedSize;
374 gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
375 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
376}
377
378void GBDestroy(struct GB* gb) {
379 GBUnmapBIOS(gb);
380 GBUnloadROM(gb);
381
382 if (gb->biosVf) {
383 gb->biosVf->close(gb->biosVf);
384 gb->biosVf = 0;
385 }
386
387 GBMemoryDeinit(gb);
388 GBAudioDeinit(&gb->audio);
389 GBVideoDeinit(&gb->video);
390 GBSIODeinit(&gb->sio);
391 mCoreCallbacksListDeinit(&gb->coreCallbacks);
392}
393
394void GBInterruptHandlerInit(struct SM83InterruptHandler* irqh) {
395 irqh->reset = GBReset;
396 irqh->processEvents = GBProcessEvents;
397 irqh->setInterrupts = GBSetInterrupts;
398 irqh->irqVector = GBIRQVector;
399 irqh->hitIllegal = GBIllegal;
400 irqh->stop = GBStop;
401 irqh->halt = GBHalt;
402}
403
404static uint32_t _GBBiosCRC32(struct VFile* vf) {
405 ssize_t size = vf->size(vf);
406 if (size <= 0 || size > GB_SIZE_CART_BANK0) {
407 return 0;
408 }
409 void* bios = vf->map(vf, size, MAP_READ);
410 uint32_t biosCrc = doCrc32(bios, size);
411 vf->unmap(vf, bios, size);
412 return biosCrc;
413}
414
415bool GBIsBIOS(struct VFile* vf) {
416 switch (_GBBiosCRC32(vf)) {
417 case DMG_BIOS_CHECKSUM:
418 case DMG0_BIOS_CHECKSUM:
419 case MGB_BIOS_CHECKSUM:
420 case SGB_BIOS_CHECKSUM:
421 case SGB2_BIOS_CHECKSUM:
422 case CGB_BIOS_CHECKSUM:
423 case AGB_BIOS_CHECKSUM:
424 return true;
425 default:
426 return false;
427 }
428}
429
430void GBReset(struct SM83Core* cpu) {
431 struct GB* gb = (struct GB*) cpu->master;
432 gb->memory.romBase = gb->memory.rom;
433 GBDetectModel(gb);
434
435 cpu->b = 0;
436 cpu->d = 0;
437
438 gb->timer.internalDiv = 0;
439
440 gb->cpuBlocked = false;
441 gb->earlyExit = false;
442 gb->doubleSpeed = 0;
443
444 if (gb->yankedRomSize) {
445 gb->memory.romSize = gb->yankedRomSize;
446 gb->memory.mbcType = gb->yankedMbc;
447 gb->yankedRomSize = 0;
448 }
449
450 gb->sgbBit = -1;
451 gb->sgbControllers = 0;
452 gb->sgbCurrentController = 0;
453 gb->currentSgbBits = 0;
454 gb->sgbIncrement = false;
455 memset(gb->sgbPacket, 0, sizeof(gb->sgbPacket));
456
457 mTimingClear(&gb->timing);
458
459 GBMemoryReset(gb);
460
461 if (gb->biosVf) {
462 if (!GBIsBIOS(gb->biosVf)) {
463 gb->biosVf->close(gb->biosVf);
464 gb->biosVf = NULL;
465 } else {
466 GBMapBIOS(gb);
467 cpu->a = 0;
468 cpu->f.packed = 0;
469 cpu->c = 0;
470 cpu->e = 0;
471 cpu->h = 0;
472 cpu->l = 0;
473 cpu->sp = 0;
474 cpu->pc = 0;
475 }
476 }
477
478 GBVideoReset(&gb->video);
479 GBTimerReset(&gb->timer);
480 GBIOReset(gb);
481 if (!gb->biosVf && gb->memory.rom) {
482 GBSkipBIOS(gb);
483 } else {
484 mTimingSchedule(&gb->timing, &gb->timer.event, 0);
485 }
486
487 GBAudioReset(&gb->audio);
488 GBSIOReset(&gb->sio);
489
490 cpu->memory.setActiveRegion(cpu, cpu->pc);
491
492 gb->sramMaskWriteback = false;
493 GBSavedataUnmask(gb);
494}
495
496void GBSkipBIOS(struct GB* gb) {
497 struct SM83Core* cpu = gb->cpu;
498 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
499 int nextDiv = 0;
500
501 switch (gb->model) {
502 case GB_MODEL_AUTODETECT: // Silence warnings
503 gb->model = GB_MODEL_DMG;
504 // Fall through
505 case GB_MODEL_DMG:
506 cpu->a = 1;
507 cpu->f.packed = 0xB0;
508 cpu->c = 0x13;
509 cpu->e = 0xD8;
510 cpu->h = 1;
511 cpu->l = 0x4D;
512 gb->timer.internalDiv = 0xABC;
513 nextDiv = 4;
514 break;
515 case GB_MODEL_SGB:
516 cpu->a = 1;
517 cpu->f.packed = 0x00;
518 cpu->c = 0x14;
519 cpu->e = 0x00;
520 cpu->h = 0xC0;
521 cpu->l = 0x60;
522 gb->timer.internalDiv = 0xD85;
523 nextDiv = 8;
524 break;
525 case GB_MODEL_MGB:
526 cpu->a = 0xFF;
527 cpu->f.packed = 0xB0;
528 cpu->c = 0x13;
529 cpu->e = 0xD8;
530 cpu->h = 1;
531 cpu->l = 0x4D;
532 gb->timer.internalDiv = 0xABC;
533 nextDiv = 4;
534 break;
535 case GB_MODEL_SGB2:
536 cpu->a = 0xFF;
537 cpu->f.packed = 0x00;
538 cpu->c = 0x14;
539 cpu->e = 0x00;
540 cpu->h = 0xC0;
541 cpu->l = 0x60;
542 gb->timer.internalDiv = 0xD84;
543 nextDiv = 8;
544 break;
545 case GB_MODEL_AGB:
546 cpu->b = 1;
547 // Fall through
548 case GB_MODEL_CGB:
549 cpu->a = 0x11;
550 if (gb->model == GB_MODEL_AGB) {
551 cpu->f.packed = 0x00;
552 } else {
553 cpu->f.packed = 0x80;
554 }
555 cpu->c = 0;
556 cpu->h = 0;
557 if (cart->cgb & 0x80) {
558 cpu->d = 0xFF;
559 cpu->e = 0x56;
560 cpu->l = 0x0D;
561 gb->timer.internalDiv = 0x2F0;
562 } else {
563 cpu->e = 0x08;
564 cpu->l = 0x7C;
565 gb->timer.internalDiv = 0x260;
566 gb->model = GB_MODEL_DMG;
567 gb->memory.io[GB_REG_KEY1] = 0xFF;
568 gb->memory.io[GB_REG_BCPS] = 0x88; // Faked writing 4 BG palette entries
569 gb->memory.io[GB_REG_OCPS] = 0x90; // Faked writing 8 OBJ palette entries
570 gb->memory.io[GB_REG_SVBK] = 0xFF;
571 GBVideoDisableCGB(&gb->video);
572 }
573 nextDiv = 0xC;
574 break;
575 }
576
577 cpu->sp = 0xFFFE;
578 cpu->pc = 0x100;
579
580 gb->timer.nextDiv = GB_DMG_DIV_PERIOD * (16 - nextDiv);
581
582 mTimingDeschedule(&gb->timing, &gb->timer.event);
583 mTimingSchedule(&gb->timing, &gb->timer.event, gb->timer.nextDiv);
584
585 GBIOWrite(gb, GB_REG_LCDC, 0x91);
586 gb->memory.io[GB_REG_BANK] = 0x1;
587 GBVideoSkipBIOS(&gb->video);
588
589 if (gb->biosVf) {
590 GBUnmapBIOS(gb);
591 }
592}
593
594void GBMapBIOS(struct GB* gb) {
595 gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
596 gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
597 ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
598 if (gb->memory.rom) {
599 memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
600 if (size > 0x100) {
601 memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
602 }
603 }
604}
605
606void GBUnmapBIOS(struct GB* gb) {
607 if (gb->memory.io[GB_REG_BANK] == 0xFF && gb->memory.romBase != gb->memory.rom) {
608 free(gb->memory.romBase);
609 if (gb->memory.mbcType == GB_MMM01) {
610 GBMBCSwitchBank0(gb, gb->memory.romSize / GB_SIZE_CART_BANK0 - 2);
611 } else {
612 GBMBCSwitchBank0(gb, 0);
613 }
614 }
615 // XXX: Force AGB registers for AGB-mode
616 if (gb->model == GB_MODEL_AGB && gb->cpu->pc == 0x100) {
617 gb->cpu->b = 1;
618 }
619}
620
621void GBDetectModel(struct GB* gb) {
622 if (gb->model != GB_MODEL_AUTODETECT) {
623 return;
624 }
625 if (gb->biosVf) {
626 switch (_GBBiosCRC32(gb->biosVf)) {
627 case DMG_BIOS_CHECKSUM:
628 case DMG0_BIOS_CHECKSUM:
629 gb->model = GB_MODEL_DMG;
630 break;
631 case MGB_BIOS_CHECKSUM:
632 gb->model = GB_MODEL_MGB;
633 break;
634 case SGB_BIOS_CHECKSUM:
635 gb->model = GB_MODEL_SGB;
636 break;
637 case SGB2_BIOS_CHECKSUM:
638 gb->model = GB_MODEL_SGB2;
639 break;
640 case CGB_BIOS_CHECKSUM:
641 gb->model = GB_MODEL_CGB;
642 break;
643 case AGB_BIOS_CHECKSUM:
644 gb->model = GB_MODEL_AGB;
645 break;
646 default:
647 gb->biosVf->close(gb->biosVf);
648 gb->biosVf = NULL;
649 }
650 }
651 if (gb->model == GB_MODEL_AUTODETECT && gb->memory.rom) {
652 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
653 if (cart->cgb & 0x80) {
654 gb->model = GB_MODEL_CGB;
655 } else if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
656 gb->model = GB_MODEL_SGB;
657 } else {
658 gb->model = GB_MODEL_DMG;
659 }
660 }
661
662 switch (gb->model) {
663 case GB_MODEL_DMG:
664 case GB_MODEL_SGB:
665 case GB_MODEL_AUTODETECT: //Silence warnings
666 gb->audio.style = GB_AUDIO_DMG;
667 break;
668 case GB_MODEL_MGB:
669 case GB_MODEL_SGB2:
670 gb->audio.style = GB_AUDIO_MGB;
671 break;
672 case GB_MODEL_AGB:
673 case GB_MODEL_CGB:
674 gb->audio.style = GB_AUDIO_CGB;
675 break;
676 }
677}
678
679int GBValidModels(const uint8_t* bank0) {
680 const struct GBCartridge* cart = (const struct GBCartridge*) &bank0[0x100];
681 int models;
682 if (cart->cgb == 0x80) {
683 models = GB_MODEL_CGB | GB_MODEL_MGB;
684 } else if (cart->cgb == 0xC0) {
685 models = GB_MODEL_CGB;
686 } else {
687 models = GB_MODEL_MGB;
688 }
689 if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
690 models |= GB_MODEL_SGB;
691 }
692 return models;
693}
694
695void GBUpdateIRQs(struct GB* gb) {
696 int irqs = gb->memory.ie & gb->memory.io[GB_REG_IF] & 0x1F;
697 if (!irqs) {
698 gb->cpu->irqPending = false;
699 return;
700 }
701 gb->cpu->halted = false;
702
703 if (!gb->memory.ime) {
704 gb->cpu->irqPending = false;
705 return;
706 }
707 if (gb->cpu->irqPending) {
708 return;
709 }
710 SM83RaiseIRQ(gb->cpu);
711}
712
713void GBProcessEvents(struct SM83Core* cpu) {
714 struct GB* gb = (struct GB*) cpu->master;
715 do {
716 int32_t cycles = cpu->cycles;
717 int32_t nextEvent;
718
719 cpu->cycles = 0;
720 cpu->nextEvent = INT_MAX;
721
722 nextEvent = cycles;
723 do {
724#ifdef USE_DEBUGGERS
725 gb->timing.globalCycles += nextEvent;
726#endif
727 nextEvent = mTimingTick(&gb->timing, nextEvent);
728 } while (gb->cpuBlocked);
729 // This loop cannot early exit until the SM83 run loop properly handles mid-M-cycle-exits
730 cpu->nextEvent = nextEvent;
731
732 if (cpu->halted) {
733 cpu->cycles = cpu->nextEvent;
734 if (!gb->memory.ie || !gb->memory.ime) {
735 break;
736 }
737 }
738 if (gb->earlyExit) {
739 break;
740 }
741 } while (cpu->cycles >= cpu->nextEvent);
742 gb->earlyExit = false;
743 if (gb->cpuBlocked) {
744 cpu->cycles = cpu->nextEvent;
745 }
746}
747
748void GBSetInterrupts(struct SM83Core* cpu, bool enable) {
749 struct GB* gb = (struct GB*) cpu->master;
750 mTimingDeschedule(&gb->timing, &gb->eiPending);
751 if (!enable) {
752 gb->memory.ime = false;
753 GBUpdateIRQs(gb);
754 } else {
755 mTimingSchedule(&gb->timing, &gb->eiPending, 4 * cpu->tMultiplier);
756 }
757}
758
759uint16_t GBIRQVector(struct SM83Core* cpu) {
760 struct GB* gb = (struct GB*) cpu->master;
761 int irqs = gb->memory.ie & gb->memory.io[GB_REG_IF];
762
763 if (irqs & (1 << GB_IRQ_VBLANK)) {
764 gb->memory.io[GB_REG_IF] &= ~(1 << GB_IRQ_VBLANK);
765 return GB_VECTOR_VBLANK;
766 }
767 if (irqs & (1 << GB_IRQ_LCDSTAT)) {
768 gb->memory.io[GB_REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
769 return GB_VECTOR_LCDSTAT;
770 }
771 if (irqs & (1 << GB_IRQ_TIMER)) {
772 gb->memory.io[GB_REG_IF] &= ~(1 << GB_IRQ_TIMER);
773 return GB_VECTOR_TIMER;
774 }
775 if (irqs & (1 << GB_IRQ_SIO)) {
776 gb->memory.io[GB_REG_IF] &= ~(1 << GB_IRQ_SIO);
777 return GB_VECTOR_SIO;
778 }
779 if (irqs & (1 << GB_IRQ_KEYPAD)) {
780 gb->memory.io[GB_REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
781 return GB_VECTOR_KEYPAD;
782 }
783 return 0;
784}
785
786static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate) {
787 UNUSED(timing);
788 UNUSED(cyclesLate);
789 struct GB* gb = user;
790 gb->memory.ime = true;
791 GBUpdateIRQs(gb);
792}
793
794void GBHalt(struct SM83Core* cpu) {
795 struct GB* gb = (struct GB*) cpu->master;
796 if (!(gb->memory.ie & gb->memory.io[GB_REG_IF] & 0x1F)) {
797 cpu->cycles = cpu->nextEvent;
798 cpu->halted = true;
799 } else if (!gb->memory.ime) {
800 mLOG(GB, GAME_ERROR, "HALT bug");
801 cpu->executionState = SM83_CORE_HALT_BUG;
802 }
803}
804
805void GBStop(struct SM83Core* cpu) {
806 struct GB* gb = (struct GB*) cpu->master;
807 if (gb->model >= GB_MODEL_CGB && gb->memory.io[GB_REG_KEY1] & 1) {
808 gb->doubleSpeed ^= 1;
809 gb->cpu->tMultiplier = 2 - gb->doubleSpeed;
810 gb->memory.io[GB_REG_KEY1] = 0;
811 gb->memory.io[GB_REG_KEY1] |= gb->doubleSpeed << 7;
812 } else {
813 int sleep = ~(gb->memory.io[GB_REG_JOYP] & 0x30);
814 size_t c;
815 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
816 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
817 if (sleep && callbacks->sleep) {
818 callbacks->sleep(callbacks->context);
819 } else if (callbacks->shutdown) {
820 callbacks->shutdown(callbacks->context);
821 }
822 }
823 }
824}
825
826void GBIllegal(struct SM83Core* cpu) {
827 struct GB* gb = (struct GB*) cpu->master;
828 mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X", cpu->pc, cpu->bus);
829#ifdef USE_DEBUGGERS
830 if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
831 struct mDebuggerEntryInfo info = {
832 .address = cpu->pc,
833 .type.bp.opcode = cpu->bus
834 };
835 mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
836 }
837#endif
838 // Hang forever
839 gb->memory.ime = 0;
840 --cpu->pc;
841}
842
843bool GBIsROM(struct VFile* vf) {
844 if (!vf) {
845 return false;
846 }
847 vf->seek(vf, 0x104, SEEK_SET);
848 uint8_t header[4];
849
850 if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
851 return false;
852 }
853 if (memcmp(header, _knownHeader, sizeof(header))) {
854 return false;
855 }
856 return true;
857}
858
859void GBGetGameTitle(const struct GB* gb, char* out) {
860 const struct GBCartridge* cart = NULL;
861 if (gb->memory.rom) {
862 cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
863 }
864 if (!cart) {
865 return;
866 }
867 if (cart->oldLicensee != 0x33) {
868 memcpy(out, cart->titleLong, 16);
869 } else {
870 memcpy(out, cart->titleShort, 11);
871 }
872}
873
874void GBGetGameCode(const struct GB* gb, char* out) {
875 memset(out, 0, 8);
876 const struct GBCartridge* cart = NULL;
877 if (gb->memory.rom) {
878 cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
879 }
880 if (!cart) {
881 return;
882 }
883 if (cart->cgb == 0xC0) {
884 memcpy(out, "CGB-????", 8);
885 } else {
886 memcpy(out, "DMG-????", 8);
887 }
888 if (cart->oldLicensee == 0x33) {
889 memcpy(&out[4], cart->maker, 4);
890 }
891}
892
893void GBFrameStarted(struct GB* gb) {
894 GBTestKeypadIRQ(gb);
895
896 size_t c;
897 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
898 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
899 if (callbacks->videoFrameStarted) {
900 callbacks->videoFrameStarted(callbacks->context);
901 }
902 }
903}
904
905void GBFrameEnded(struct GB* gb) {
906 GBSramClean(gb, gb->video.frameCounter);
907
908 if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
909 struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
910 size_t i;
911 for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
912 struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
913 mCheatRefresh(device, cheats);
914 }
915 }
916
917 // TODO: Move to common code
918 if (gb->stream && gb->stream->postVideoFrame) {
919 const color_t* pixels;
920 size_t stride;
921 gb->video.renderer->getPixels(gb->video.renderer, &stride, (const void**) &pixels);
922 gb->stream->postVideoFrame(gb->stream, pixels, stride);
923 }
924
925 size_t c;
926 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
927 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
928 if (callbacks->videoFrameEnded) {
929 callbacks->videoFrameEnded(callbacks->context);
930 }
931 }
932}
933
934enum GBModel GBNameToModel(const char* model) {
935 if (strcasecmp(model, "DMG") == 0) {
936 return GB_MODEL_DMG;
937 } else if (strcasecmp(model, "CGB") == 0) {
938 return GB_MODEL_CGB;
939 } else if (strcasecmp(model, "AGB") == 0) {
940 return GB_MODEL_AGB;
941 } else if (strcasecmp(model, "SGB") == 0) {
942 return GB_MODEL_SGB;
943 } else if (strcasecmp(model, "MGB") == 0) {
944 return GB_MODEL_MGB;
945 } else if (strcasecmp(model, "SGB2") == 0) {
946 return GB_MODEL_SGB2;
947 }
948 return GB_MODEL_AUTODETECT;
949}
950
951const char* GBModelToName(enum GBModel model) {
952 switch (model) {
953 case GB_MODEL_DMG:
954 return "DMG";
955 case GB_MODEL_SGB:
956 return "SGB";
957 case GB_MODEL_MGB:
958 return "MGB";
959 case GB_MODEL_SGB2:
960 return "SGB2";
961 case GB_MODEL_CGB:
962 return "CGB";
963 case GB_MODEL_AGB:
964 return "AGB";
965 default:
966 case GB_MODEL_AUTODETECT:
967 return NULL;
968 }
969}