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