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[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}
252
253void GBSavedataMask(struct GB* gb, struct VFile* vf, bool writeback) {
254 struct VFile* oldVf = gb->sramVf;
255 GBSramDeinit(gb);
256 if (oldVf && oldVf != gb->sramRealVf) {
257 oldVf->close(oldVf);
258 }
259 gb->sramVf = vf;
260 gb->sramMaskWriteback = writeback;
261 gb->memory.sram = vf->map(vf, gb->sramSize, MAP_READ);
262 GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
263}
264
265void GBSavedataUnmask(struct GB* gb) {
266 if (!gb->sramRealVf || gb->sramVf == gb->sramRealVf) {
267 return;
268 }
269 struct VFile* vf = gb->sramVf;
270 GBSramDeinit(gb);
271 gb->sramVf = gb->sramRealVf;
272 gb->memory.sram = gb->sramVf->map(gb->sramVf, gb->sramSize, MAP_WRITE);
273 if (gb->sramMaskWriteback) {
274 vf->seek(vf, 0, SEEK_SET);
275 vf->read(vf, gb->memory.sram, gb->sramSize);
276 gb->sramMaskWriteback = false;
277 }
278 GBMBCSwitchSramBank(gb, gb->memory.sramCurrentBank);
279 vf->close(vf);
280}
281
282void GBUnloadROM(struct GB* gb) {
283 // TODO: Share with GBAUnloadROM
284 if (gb->memory.rom && gb->memory.romBase != gb->memory.rom && !gb->isPristine) {
285 free(gb->memory.romBase);
286 }
287 if (gb->memory.rom && !gb->isPristine) {
288 if (gb->yankedRomSize) {
289 gb->yankedRomSize = 0;
290 }
291 mappedMemoryFree(gb->memory.rom, GB_SIZE_CART_MAX);
292 }
293
294 if (gb->romVf) {
295#ifndef FIXED_ROM_BUFFER
296 gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
297#endif
298 gb->romVf->close(gb->romVf);
299 gb->romVf = NULL;
300 }
301 gb->memory.rom = NULL;
302 gb->memory.mbcType = GB_MBC_AUTODETECT;
303 gb->isPristine = false;
304
305 gb->sramMaskWriteback = false;
306 GBSramDeinit(gb);
307 if (gb->sramRealVf) {
308 gb->sramRealVf->close(gb->sramRealVf);
309 }
310 gb->sramRealVf = NULL;
311 gb->sramVf = NULL;
312 if (gb->memory.cam && gb->memory.cam->stopRequestImage) {
313 gb->memory.cam->stopRequestImage(gb->memory.cam);
314 }
315}
316
317void GBSynthesizeROM(struct VFile* vf) {
318 if (!vf) {
319 return;
320 }
321 const struct GBCartridge cart = {
322 .logo = { _knownHeader[0], _knownHeader[1], _knownHeader[2], _knownHeader[3]}
323 };
324
325 vf->seek(vf, 0x100, SEEK_SET);
326 vf->write(vf, &cart, sizeof(cart));
327}
328
329void GBLoadBIOS(struct GB* gb, struct VFile* vf) {
330 gb->biosVf = vf;
331}
332
333void GBApplyPatch(struct GB* gb, struct Patch* patch) {
334 size_t patchedSize = patch->outputSize(patch, gb->memory.romSize);
335 if (!patchedSize) {
336 return;
337 }
338 if (patchedSize > GB_SIZE_CART_MAX) {
339 patchedSize = GB_SIZE_CART_MAX;
340 }
341 void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
342 if (!patch->applyPatch(patch, gb->memory.rom, gb->pristineRomSize, newRom, patchedSize)) {
343 mappedMemoryFree(newRom, GB_SIZE_CART_MAX);
344 return;
345 }
346 if (gb->romVf) {
347#ifndef FIXED_ROM_BUFFER
348 gb->romVf->unmap(gb->romVf, gb->memory.rom, gb->pristineRomSize);
349#endif
350 gb->romVf->close(gb->romVf);
351 gb->romVf = NULL;
352 }
353 gb->isPristine = false;
354 if (gb->memory.romBase == gb->memory.rom) {
355 gb->memory.romBase = newRom;
356 }
357 gb->memory.rom = newRom;
358 gb->memory.romSize = patchedSize;
359 gb->romCrc32 = doCrc32(gb->memory.rom, gb->memory.romSize);
360 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
361}
362
363void GBDestroy(struct GB* gb) {
364 GBUnloadROM(gb);
365
366 if (gb->biosVf) {
367 gb->biosVf->close(gb->biosVf);
368 gb->biosVf = 0;
369 }
370
371 GBMemoryDeinit(gb);
372 GBAudioDeinit(&gb->audio);
373 GBVideoDeinit(&gb->video);
374 GBSIODeinit(&gb->sio);
375 mCoreCallbacksListDeinit(&gb->coreCallbacks);
376}
377
378void GBInterruptHandlerInit(struct SM83InterruptHandler* irqh) {
379 irqh->reset = GBReset;
380 irqh->processEvents = GBProcessEvents;
381 irqh->setInterrupts = GBSetInterrupts;
382 irqh->irqVector = GBIRQVector;
383 irqh->hitIllegal = GBIllegal;
384 irqh->stop = GBStop;
385 irqh->halt = GBHalt;
386}
387
388static uint32_t _GBBiosCRC32(struct VFile* vf) {
389 ssize_t size = vf->size(vf);
390 if (size <= 0 || size > GB_SIZE_CART_BANK0) {
391 return 0;
392 }
393 void* bios = vf->map(vf, size, MAP_READ);
394 uint32_t biosCrc = doCrc32(bios, size);
395 vf->unmap(vf, bios, size);
396 return biosCrc;
397}
398
399bool GBIsBIOS(struct VFile* vf) {
400 switch (_GBBiosCRC32(vf)) {
401 case DMG_BIOS_CHECKSUM:
402 case DMG_2_BIOS_CHECKSUM:
403 case MGB_BIOS_CHECKSUM:
404 case SGB_BIOS_CHECKSUM:
405 case SGB2_BIOS_CHECKSUM:
406 case CGB_BIOS_CHECKSUM:
407 return true;
408 default:
409 return false;
410 }
411}
412
413void GBReset(struct SM83Core* cpu) {
414 struct GB* gb = (struct GB*) cpu->master;
415 gb->memory.romBase = gb->memory.rom;
416 GBDetectModel(gb);
417
418 cpu->b = 0;
419 cpu->d = 0;
420
421 gb->timer.internalDiv = 0;
422
423 gb->cpuBlocked = false;
424 gb->earlyExit = false;
425 gb->doubleSpeed = 0;
426
427 if (gb->yankedRomSize) {
428 gb->memory.romSize = gb->yankedRomSize;
429 gb->memory.mbcType = gb->yankedMbc;
430 gb->yankedRomSize = 0;
431 }
432
433 gb->sgbBit = -1;
434 gb->sgbControllers = 0;
435 gb->sgbCurrentController = 0;
436 gb->currentSgbBits = 0;
437 gb->sgbIncrement = false;
438 memset(gb->sgbPacket, 0, sizeof(gb->sgbPacket));
439
440 mTimingClear(&gb->timing);
441
442 GBMemoryReset(gb);
443
444 if (gb->biosVf) {
445 if (!GBIsBIOS(gb->biosVf)) {
446 gb->biosVf->close(gb->biosVf);
447 gb->biosVf = NULL;
448 } else {
449 GBMapBIOS(gb);
450 cpu->a = 0;
451 cpu->f.packed = 0;
452 cpu->c = 0;
453 cpu->e = 0;
454 cpu->h = 0;
455 cpu->l = 0;
456 cpu->sp = 0;
457 cpu->pc = 0;
458 }
459 }
460
461 GBVideoReset(&gb->video);
462 GBTimerReset(&gb->timer);
463 if (!gb->biosVf) {
464 GBSkipBIOS(gb);
465 } else {
466 mTimingSchedule(&gb->timing, &gb->timer.event, 0);
467 }
468
469 GBIOReset(gb);
470 GBAudioReset(&gb->audio);
471 GBSIOReset(&gb->sio);
472
473 cpu->memory.setActiveRegion(cpu, cpu->pc);
474
475 gb->sramMaskWriteback = false;
476 GBSavedataUnmask(gb);
477}
478
479void GBSkipBIOS(struct GB* gb) {
480 struct SM83Core* cpu = gb->cpu;
481 int nextDiv = 0;
482
483 switch (gb->model) {
484 case GB_MODEL_AUTODETECT: // Silence warnings
485 gb->model = GB_MODEL_DMG;
486 // Fall through
487 case GB_MODEL_DMG:
488 cpu->a = 1;
489 cpu->f.packed = 0xB0;
490 cpu->c = 0x13;
491 cpu->e = 0xD8;
492 cpu->h = 1;
493 cpu->l = 0x4D;
494 gb->timer.internalDiv = 0xABC;
495 nextDiv = 4;
496 break;
497 case GB_MODEL_SGB:
498 cpu->a = 1;
499 cpu->f.packed = 0x00;
500 cpu->c = 0x14;
501 cpu->e = 0x00;
502 cpu->h = 0xC0;
503 cpu->l = 0x60;
504 gb->timer.internalDiv = 0xABC;
505 nextDiv = 4;
506 break;
507 case GB_MODEL_MGB:
508 cpu->a = 0xFF;
509 cpu->f.packed = 0xB0;
510 cpu->c = 0x13;
511 cpu->e = 0xD8;
512 cpu->h = 1;
513 cpu->l = 0x4D;
514 gb->timer.internalDiv = 0xABC;
515 nextDiv = 4;
516 break;
517 case GB_MODEL_SGB2:
518 cpu->a = 0xFF;
519 cpu->f.packed = 0x00;
520 cpu->c = 0x14;
521 cpu->e = 0x00;
522 cpu->h = 0xC0;
523 cpu->l = 0x60;
524 gb->timer.internalDiv = 0xABC;
525 nextDiv = 4;
526 break;
527 case GB_MODEL_AGB:
528 cpu->a = 0x11;
529 cpu->b = 1;
530 cpu->f.packed = 0x00;
531 cpu->c = 0;
532 cpu->e = 0x08;
533 cpu->h = 0;
534 cpu->l = 0x7C;
535 gb->timer.internalDiv = 0x1EA;
536 nextDiv = 0xC;
537 break;
538 case GB_MODEL_CGB:
539 cpu->a = 0x11;
540 cpu->f.packed = 0x80;
541 cpu->c = 0;
542 cpu->e = 0x08;
543 cpu->h = 0;
544 cpu->l = 0x7C;
545 gb->timer.internalDiv = 0x1EA;
546 nextDiv = 0xC;
547 break;
548 }
549
550 cpu->sp = 0xFFFE;
551 cpu->pc = 0x100;
552
553 mTimingDeschedule(&gb->timing, &gb->timer.event);
554 mTimingSchedule(&gb->timing, &gb->timer.event, 0);
555
556 GBIOWrite(gb, REG_LCDC, 0x91);
557
558 if (gb->biosVf) {
559 GBUnmapBIOS(gb);
560 }
561}
562
563void GBMapBIOS(struct GB* gb) {
564 gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
565 uint8_t* oldRomBase = gb->memory.romBase;
566 gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
567 ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
568 memcpy(&gb->memory.romBase[size], &oldRomBase[size], GB_SIZE_CART_BANK0 - size);
569 if (size > 0x100) {
570 memcpy(&gb->memory.romBase[0x100], &oldRomBase[0x100], sizeof(struct GBCartridge));
571 }
572}
573
574void GBUnmapBIOS(struct GB* gb) {
575 if (gb->memory.romBase < gb->memory.rom || gb->memory.romBase > &gb->memory.rom[gb->memory.romSize - 1]) {
576 free(gb->memory.romBase);
577 if (gb->memory.mbcType == GB_MMM01) {
578 GBMBCSwitchBank0(gb, gb->memory.romSize / GB_SIZE_CART_BANK0 - 2);
579 } else {
580 GBMBCSwitchBank0(gb, 0);
581 }
582 }
583 // XXX: Force AGB registers for AGB-mode
584 if (gb->model == GB_MODEL_AGB && gb->cpu->pc == 0x100) {
585 gb->cpu->b = 1;
586 }
587}
588
589void GBDetectModel(struct GB* gb) {
590 if (gb->model != GB_MODEL_AUTODETECT) {
591 return;
592 }
593 if (gb->biosVf) {
594 switch (_GBBiosCRC32(gb->biosVf)) {
595 case DMG_BIOS_CHECKSUM:
596 case DMG_2_BIOS_CHECKSUM:
597 gb->model = GB_MODEL_DMG;
598 break;
599 case MGB_BIOS_CHECKSUM:
600 gb->model = GB_MODEL_MGB;
601 break;
602 case SGB_BIOS_CHECKSUM:
603 gb->model = GB_MODEL_SGB;
604 break;
605 case SGB2_BIOS_CHECKSUM:
606 gb->model = GB_MODEL_SGB2;
607 break;
608 case CGB_BIOS_CHECKSUM:
609 gb->model = GB_MODEL_CGB;
610 break;
611 default:
612 gb->biosVf->close(gb->biosVf);
613 gb->biosVf = NULL;
614 }
615 }
616 if (gb->model == GB_MODEL_AUTODETECT && gb->memory.rom) {
617 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
618 if (cart->cgb & 0x80) {
619 gb->model = GB_MODEL_CGB;
620 } else if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
621 gb->model = GB_MODEL_SGB;
622 } else {
623 gb->model = GB_MODEL_DMG;
624 }
625 }
626
627 switch (gb->model) {
628 case GB_MODEL_DMG:
629 case GB_MODEL_SGB:
630 case GB_MODEL_AUTODETECT: //Silence warnings
631 gb->audio.style = GB_AUDIO_DMG;
632 break;
633 case GB_MODEL_MGB:
634 case GB_MODEL_SGB2:
635 gb->audio.style = GB_AUDIO_MGB;
636 break;
637 case GB_MODEL_AGB:
638 case GB_MODEL_CGB:
639 gb->audio.style = GB_AUDIO_CGB;
640 break;
641 }
642}
643
644void GBUpdateIRQs(struct GB* gb) {
645 int irqs = gb->memory.ie & gb->memory.io[REG_IF] & 0x1F;
646 if (!irqs) {
647 gb->cpu->irqPending = false;
648 return;
649 }
650 gb->cpu->halted = false;
651
652 if (!gb->memory.ime) {
653 gb->cpu->irqPending = false;
654 return;
655 }
656 if (gb->cpu->irqPending) {
657 return;
658 }
659 SM83RaiseIRQ(gb->cpu);
660}
661
662void GBProcessEvents(struct SM83Core* cpu) {
663 struct GB* gb = (struct GB*) cpu->master;
664 do {
665 int32_t cycles = cpu->cycles;
666 int32_t nextEvent;
667
668 cpu->cycles = 0;
669 cpu->nextEvent = INT_MAX;
670
671 nextEvent = cycles;
672 do {
673 nextEvent = mTimingTick(&gb->timing, nextEvent);
674 } while (gb->cpuBlocked);
675 cpu->nextEvent = nextEvent;
676
677 if (cpu->halted) {
678 cpu->cycles = cpu->nextEvent;
679 if (!gb->memory.ie || !gb->memory.ime) {
680 break;
681 }
682 }
683 if (gb->earlyExit) {
684 break;
685 }
686 } while (cpu->cycles >= cpu->nextEvent);
687 gb->earlyExit = false;
688}
689
690void GBSetInterrupts(struct SM83Core* cpu, bool enable) {
691 struct GB* gb = (struct GB*) cpu->master;
692 mTimingDeschedule(&gb->timing, &gb->eiPending);
693 if (!enable) {
694 gb->memory.ime = false;
695 GBUpdateIRQs(gb);
696 } else {
697 mTimingSchedule(&gb->timing, &gb->eiPending, 4);
698 }
699}
700
701uint16_t GBIRQVector(struct SM83Core* cpu) {
702 struct GB* gb = (struct GB*) cpu->master;
703 int irqs = gb->memory.ie & gb->memory.io[REG_IF];
704
705 if (irqs & (1 << GB_IRQ_VBLANK)) {
706 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
707 return GB_VECTOR_VBLANK;
708 }
709 if (irqs & (1 << GB_IRQ_LCDSTAT)) {
710 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
711 return GB_VECTOR_LCDSTAT;
712 }
713 if (irqs & (1 << GB_IRQ_TIMER)) {
714 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
715 return GB_VECTOR_TIMER;
716 }
717 if (irqs & (1 << GB_IRQ_SIO)) {
718 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
719 return GB_VECTOR_SIO;
720 }
721 if (irqs & (1 << GB_IRQ_KEYPAD)) {
722 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
723 return GB_VECTOR_KEYPAD;
724 }
725 return 0;
726}
727
728static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate) {
729 UNUSED(timing);
730 UNUSED(cyclesLate);
731 struct GB* gb = user;
732 gb->memory.ime = true;
733 GBUpdateIRQs(gb);
734}
735
736void GBHalt(struct SM83Core* cpu) {
737 struct GB* gb = (struct GB*) cpu->master;
738 if (!(gb->memory.ie & gb->memory.io[REG_IF] & 0x1F)) {
739 cpu->cycles = cpu->nextEvent;
740 cpu->halted = true;
741 } else if (gb->model < GB_MODEL_CGB) {
742 mLOG(GB, STUB, "Unimplemented HALT bug");
743 }
744}
745
746void GBStop(struct SM83Core* cpu) {
747 struct GB* gb = (struct GB*) cpu->master;
748 if (cpu->bus) {
749 mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X", cpu->pc, cpu->bus);
750 }
751 if (gb->memory.io[REG_KEY1] & 1) {
752 gb->doubleSpeed ^= 1;
753 gb->audio.timingFactor = gb->doubleSpeed + 1;
754 gb->memory.io[REG_KEY1] = 0;
755 gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
756 } else if (cpu->bus) {
757#ifdef USE_DEBUGGERS
758 if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
759 struct mDebuggerEntryInfo info = {
760 .address = cpu->pc - 1,
761 .type.bp.opcode = 0x1000 | cpu->bus,
762 };
763 mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
764 }
765#endif
766 // Hang forever
767 gb->memory.ime = 0;
768 cpu->pc -= 2;
769 }
770 // TODO: Actually stop
771}
772
773void GBIllegal(struct SM83Core* cpu) {
774 struct GB* gb = (struct GB*) cpu->master;
775 mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X", cpu->pc, cpu->bus);
776#ifdef USE_DEBUGGERS
777 if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
778 struct mDebuggerEntryInfo info = {
779 .address = cpu->pc,
780 .type.bp.opcode = cpu->bus
781 };
782 mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
783 }
784#endif
785 // Hang forever
786 gb->memory.ime = 0;
787 --cpu->pc;
788}
789
790bool GBIsROM(struct VFile* vf) {
791 if (!vf) {
792 return false;
793 }
794 vf->seek(vf, 0x104, SEEK_SET);
795 uint8_t header[4];
796
797 if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
798 return false;
799 }
800 if (memcmp(header, _knownHeader, sizeof(header))) {
801 return false;
802 }
803 return true;
804}
805
806void GBGetGameTitle(const struct GB* gb, char* out) {
807 const struct GBCartridge* cart = NULL;
808 if (gb->memory.rom) {
809 cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
810 }
811 if (!cart) {
812 return;
813 }
814 if (cart->oldLicensee != 0x33) {
815 memcpy(out, cart->titleLong, 16);
816 } else {
817 memcpy(out, cart->titleShort, 11);
818 }
819}
820
821void GBGetGameCode(const struct GB* gb, char* out) {
822 memset(out, 0, 8);
823 const struct GBCartridge* cart = NULL;
824 if (gb->memory.rom) {
825 cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
826 }
827 if (!cart) {
828 return;
829 }
830 if (cart->cgb == 0xC0) {
831 memcpy(out, "CGB-????", 8);
832 } else {
833 memcpy(out, "DMG-????", 8);
834 }
835 if (cart->oldLicensee == 0x33) {
836 memcpy(&out[4], cart->maker, 4);
837 }
838}
839
840void GBFrameStarted(struct GB* gb) {
841 GBTestKeypadIRQ(gb);
842
843 size_t c;
844 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
845 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
846 if (callbacks->videoFrameStarted) {
847 callbacks->videoFrameStarted(callbacks->context);
848 }
849 }
850}
851
852void GBFrameEnded(struct GB* gb) {
853 GBSramClean(gb, gb->video.frameCounter);
854
855 if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
856 struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
857 size_t i;
858 for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
859 struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
860 mCheatRefresh(device, cheats);
861 }
862 }
863
864 // TODO: Move to common code
865 if (gb->stream && gb->stream->postVideoFrame) {
866 const color_t* pixels;
867 size_t stride;
868 gb->video.renderer->getPixels(gb->video.renderer, &stride, (const void**) &pixels);
869 gb->stream->postVideoFrame(gb->stream, pixels, stride);
870 }
871
872 size_t c;
873 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
874 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
875 if (callbacks->videoFrameEnded) {
876 callbacks->videoFrameEnded(callbacks->context);
877 }
878 }
879}
880
881enum GBModel GBNameToModel(const char* model) {
882 if (strcasecmp(model, "DMG") == 0) {
883 return GB_MODEL_DMG;
884 } else if (strcasecmp(model, "CGB") == 0) {
885 return GB_MODEL_CGB;
886 } else if (strcasecmp(model, "AGB") == 0) {
887 return GB_MODEL_AGB;
888 } else if (strcasecmp(model, "SGB") == 0) {
889 return GB_MODEL_SGB;
890 } else if (strcasecmp(model, "MGB") == 0) {
891 return GB_MODEL_MGB;
892 } else if (strcasecmp(model, "SGB2") == 0) {
893 return GB_MODEL_SGB2;
894 }
895 return GB_MODEL_AUTODETECT;
896}
897
898const char* GBModelToName(enum GBModel model) {
899 switch (model) {
900 case GB_MODEL_DMG:
901 return "DMG";
902 case GB_MODEL_SGB:
903 return "SGB";
904 case GB_MODEL_MGB:
905 return "MGB";
906 case GB_MODEL_SGB2:
907 return "SGB2";
908 case GB_MODEL_CGB:
909 return "CGB";
910 case GB_MODEL_AGB:
911 return "AGB";
912 default:
913 case GB_MODEL_AUTODETECT:
914 return NULL;
915 }
916}