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/lr35902/lr35902.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_LR35902_FREQUENCY = 0x800000;
23const uint32_t SGB_LR35902_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 LR35902InterruptHandler* irqh);
41static void GBProcessEvents(struct LR35902Core* cpu);
42static void GBSetInterrupts(struct LR35902Core* cpu, bool enable);
43static uint16_t GBIRQVector(struct LR35902Core* cpu);
44static void GBIllegal(struct LR35902Core* cpu);
45static void GBStop(struct LR35902Core* 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 LR35902Core* 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 LR35902Core* 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 LR35902InterruptHandler* 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 LR35902Core* cpu) {
414 struct GB* gb = (struct GB*) cpu->master;
415 gb->memory.romBase = gb->memory.rom;
416 GBDetectModel(gb);
417
418 if (gb->biosVf) {
419 if (!GBIsBIOS(gb->biosVf)) {
420 gb->biosVf->close(gb->biosVf);
421 gb->biosVf = NULL;
422 } else {
423 GBMapBIOS(gb);
424 cpu->a = 0;
425 cpu->f.packed = 0;
426 cpu->c = 0;
427 cpu->e = 0;
428 cpu->h = 0;
429 cpu->l = 0;
430 cpu->sp = 0;
431 cpu->pc = 0;
432 }
433 }
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 GBVideoReset(&gb->video);
461 GBTimerReset(&gb->timer);
462 if (!gb->biosVf) {
463 GBSkipBIOS(gb);
464 } else {
465 mTimingSchedule(&gb->timing, &gb->timer.event, 0);
466 }
467
468 GBIOReset(gb);
469 GBAudioReset(&gb->audio);
470 GBSIOReset(&gb->sio);
471
472 cpu->memory.setActiveRegion(cpu, cpu->pc);
473
474 gb->sramMaskWriteback = false;
475 GBSavedataUnmask(gb);
476}
477
478void GBSkipBIOS(struct GB* gb) {
479 struct LR35902Core* cpu = gb->cpu;
480 int nextDiv = 0;
481
482 switch (gb->model) {
483 case GB_MODEL_AUTODETECT: // Silence warnings
484 gb->model = GB_MODEL_DMG;
485 // Fall through
486 case GB_MODEL_DMG:
487 cpu->a = 1;
488 cpu->f.packed = 0xB0;
489 cpu->c = 0x13;
490 cpu->e = 0xD8;
491 cpu->h = 1;
492 cpu->l = 0x4D;
493 gb->timer.internalDiv = 0xABC;
494 nextDiv = 4;
495 break;
496 case GB_MODEL_SGB:
497 cpu->a = 1;
498 cpu->f.packed = 0x00;
499 cpu->c = 0x14;
500 cpu->e = 0x00;
501 cpu->h = 0xC0;
502 cpu->l = 0x60;
503 gb->timer.internalDiv = 0xABC;
504 nextDiv = 4;
505 break;
506 case GB_MODEL_MGB:
507 cpu->a = 0xFF;
508 cpu->f.packed = 0xB0;
509 cpu->c = 0x13;
510 cpu->e = 0xD8;
511 cpu->h = 1;
512 cpu->l = 0x4D;
513 gb->timer.internalDiv = 0xABC;
514 nextDiv = 4;
515 break;
516 case GB_MODEL_SGB2:
517 cpu->a = 0xFF;
518 cpu->f.packed = 0x00;
519 cpu->c = 0x14;
520 cpu->e = 0x00;
521 cpu->h = 0xC0;
522 cpu->l = 0x60;
523 gb->timer.internalDiv = 0xABC;
524 nextDiv = 4;
525 break;
526 case GB_MODEL_AGB:
527 cpu->a = 0x11;
528 cpu->b = 1;
529 cpu->f.packed = 0x00;
530 cpu->c = 0;
531 cpu->e = 0x08;
532 cpu->h = 0;
533 cpu->l = 0x7C;
534 gb->timer.internalDiv = 0x1EA;
535 nextDiv = 0xC;
536 break;
537 case GB_MODEL_CGB:
538 cpu->a = 0x11;
539 cpu->f.packed = 0x80;
540 cpu->c = 0;
541 cpu->e = 0x08;
542 cpu->h = 0;
543 cpu->l = 0x7C;
544 gb->timer.internalDiv = 0x1EA;
545 nextDiv = 0xC;
546 break;
547 }
548
549 cpu->sp = 0xFFFE;
550 cpu->pc = 0x100;
551
552 mTimingDeschedule(&gb->timing, &gb->timer.event);
553 mTimingSchedule(&gb->timing, &gb->timer.event, 0);
554
555 GBIOWrite(gb, REG_LCDC, 0x91);
556
557 if (gb->biosVf) {
558 GBUnmapBIOS(gb);
559 }
560}
561
562void GBMapBIOS(struct GB* gb) {
563 gb->biosVf->seek(gb->biosVf, 0, SEEK_SET);
564 gb->memory.romBase = malloc(GB_SIZE_CART_BANK0);
565 ssize_t size = gb->biosVf->read(gb->biosVf, gb->memory.romBase, GB_SIZE_CART_BANK0);
566 memcpy(&gb->memory.romBase[size], &gb->memory.rom[size], GB_SIZE_CART_BANK0 - size);
567 if (size > 0x100) {
568 memcpy(&gb->memory.romBase[0x100], &gb->memory.rom[0x100], sizeof(struct GBCartridge));
569 }
570}
571
572void GBUnmapBIOS(struct GB* gb) {
573 if (gb->memory.romBase < gb->memory.rom || gb->memory.romBase > &gb->memory.rom[gb->memory.romSize - 1]) {
574 free(gb->memory.romBase);
575 gb->memory.romBase = gb->memory.rom;
576 }
577 // XXX: Force AGB registers for AGB-mode
578 if (gb->model == GB_MODEL_AGB && gb->cpu->pc == 0x100) {
579 gb->cpu->b = 1;
580 }
581}
582
583void GBDetectModel(struct GB* gb) {
584 if (gb->model != GB_MODEL_AUTODETECT) {
585 return;
586 }
587 if (gb->biosVf) {
588 switch (_GBBiosCRC32(gb->biosVf)) {
589 case DMG_BIOS_CHECKSUM:
590 case DMG_2_BIOS_CHECKSUM:
591 gb->model = GB_MODEL_DMG;
592 break;
593 case MGB_BIOS_CHECKSUM:
594 gb->model = GB_MODEL_MGB;
595 break;
596 case SGB_BIOS_CHECKSUM:
597 gb->model = GB_MODEL_SGB;
598 break;
599 case SGB2_BIOS_CHECKSUM:
600 gb->model = GB_MODEL_SGB2;
601 break;
602 case CGB_BIOS_CHECKSUM:
603 gb->model = GB_MODEL_CGB;
604 break;
605 default:
606 gb->biosVf->close(gb->biosVf);
607 gb->biosVf = NULL;
608 }
609 }
610 if (gb->model == GB_MODEL_AUTODETECT && gb->memory.rom) {
611 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
612 if (cart->cgb & 0x80) {
613 gb->model = GB_MODEL_CGB;
614 } else if (cart->sgb == 0x03 && cart->oldLicensee == 0x33) {
615 gb->model = GB_MODEL_SGB;
616 } else {
617 gb->model = GB_MODEL_DMG;
618 }
619 }
620
621 switch (gb->model) {
622 case GB_MODEL_DMG:
623 case GB_MODEL_SGB:
624 case GB_MODEL_AUTODETECT: //Silence warnings
625 gb->audio.style = GB_AUDIO_DMG;
626 break;
627 case GB_MODEL_MGB:
628 case GB_MODEL_SGB2:
629 gb->audio.style = GB_AUDIO_MGB;
630 break;
631 case GB_MODEL_AGB:
632 case GB_MODEL_CGB:
633 gb->audio.style = GB_AUDIO_CGB;
634 break;
635 }
636}
637
638void GBUpdateIRQs(struct GB* gb) {
639 int irqs = gb->memory.ie & gb->memory.io[REG_IF] & 0x1F;
640 if (!irqs) {
641 gb->cpu->irqPending = false;
642 return;
643 }
644 gb->cpu->halted = false;
645
646 if (!gb->memory.ime) {
647 gb->cpu->irqPending = false;
648 return;
649 }
650 if (gb->cpu->irqPending) {
651 return;
652 }
653 LR35902RaiseIRQ(gb->cpu);
654}
655
656void GBProcessEvents(struct LR35902Core* cpu) {
657 struct GB* gb = (struct GB*) cpu->master;
658 do {
659 int32_t cycles = cpu->cycles;
660 int32_t nextEvent;
661
662 cpu->cycles = 0;
663 cpu->nextEvent = INT_MAX;
664
665 nextEvent = cycles;
666 do {
667 nextEvent = mTimingTick(&gb->timing, nextEvent);
668 } while (gb->cpuBlocked);
669 cpu->nextEvent = nextEvent;
670
671 if (cpu->halted) {
672 cpu->cycles = cpu->nextEvent;
673 if (!gb->memory.ie || !gb->memory.ime) {
674 break;
675 }
676 }
677 if (gb->earlyExit) {
678 break;
679 }
680 } while (cpu->cycles >= cpu->nextEvent);
681 gb->earlyExit = false;
682}
683
684void GBSetInterrupts(struct LR35902Core* cpu, bool enable) {
685 struct GB* gb = (struct GB*) cpu->master;
686 mTimingDeschedule(&gb->timing, &gb->eiPending);
687 if (!enable) {
688 gb->memory.ime = false;
689 GBUpdateIRQs(gb);
690 } else {
691 mTimingSchedule(&gb->timing, &gb->eiPending, 4);
692 }
693}
694
695uint16_t GBIRQVector(struct LR35902Core* cpu) {
696 struct GB* gb = (struct GB*) cpu->master;
697 int irqs = gb->memory.ie & gb->memory.io[REG_IF];
698
699 if (irqs & (1 << GB_IRQ_VBLANK)) {
700 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_VBLANK);
701 return GB_VECTOR_VBLANK;
702 }
703 if (irqs & (1 << GB_IRQ_LCDSTAT)) {
704 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_LCDSTAT);
705 return GB_VECTOR_LCDSTAT;
706 }
707 if (irqs & (1 << GB_IRQ_TIMER)) {
708 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_TIMER);
709 return GB_VECTOR_TIMER;
710 }
711 if (irqs & (1 << GB_IRQ_SIO)) {
712 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_SIO);
713 return GB_VECTOR_SIO;
714 }
715 if (irqs & (1 << GB_IRQ_KEYPAD)) {
716 gb->memory.io[REG_IF] &= ~(1 << GB_IRQ_KEYPAD);
717 return GB_VECTOR_KEYPAD;
718 }
719 return 0;
720}
721
722static void _enableInterrupts(struct mTiming* timing, void* user, uint32_t cyclesLate) {
723 UNUSED(timing);
724 UNUSED(cyclesLate);
725 struct GB* gb = user;
726 gb->memory.ime = true;
727 GBUpdateIRQs(gb);
728}
729
730void GBHalt(struct LR35902Core* cpu) {
731 struct GB* gb = (struct GB*) cpu->master;
732 if (!(gb->memory.ie & gb->memory.io[REG_IF] & 0x1F)) {
733 cpu->cycles = cpu->nextEvent;
734 cpu->halted = true;
735 } else if (gb->model < GB_MODEL_CGB) {
736 mLOG(GB, STUB, "Unimplemented HALT bug");
737 }
738}
739
740void GBStop(struct LR35902Core* cpu) {
741 struct GB* gb = (struct GB*) cpu->master;
742 if (cpu->bus) {
743 mLOG(GB, GAME_ERROR, "Hit illegal stop at address %04X:%02X", cpu->pc, cpu->bus);
744 }
745 if (gb->memory.io[REG_KEY1] & 1) {
746 gb->doubleSpeed ^= 1;
747 gb->audio.timingFactor = gb->doubleSpeed + 1;
748 gb->memory.io[REG_KEY1] = 0;
749 gb->memory.io[REG_KEY1] |= gb->doubleSpeed << 7;
750 } else if (cpu->bus) {
751#ifdef USE_DEBUGGERS
752 if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
753 struct mDebuggerEntryInfo info = {
754 .address = cpu->pc - 1,
755 .type.bp.opcode = 0x1000 | cpu->bus
756 };
757 mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
758 }
759#endif
760 // Hang forever
761 gb->memory.ime = 0;
762 cpu->pc -= 2;
763 }
764 // TODO: Actually stop
765}
766
767void GBIllegal(struct LR35902Core* cpu) {
768 struct GB* gb = (struct GB*) cpu->master;
769 mLOG(GB, GAME_ERROR, "Hit illegal opcode at address %04X:%02X", cpu->pc, cpu->bus);
770#ifdef USE_DEBUGGERS
771 if (cpu->components && cpu->components[CPU_COMPONENT_DEBUGGER]) {
772 struct mDebuggerEntryInfo info = {
773 .address = cpu->pc,
774 .type.bp.opcode = cpu->bus
775 };
776 mDebuggerEnter((struct mDebugger*) cpu->components[CPU_COMPONENT_DEBUGGER], DEBUGGER_ENTER_ILLEGAL_OP, &info);
777 }
778#endif
779 // Hang forever
780 gb->memory.ime = 0;
781 --cpu->pc;
782}
783
784bool GBIsROM(struct VFile* vf) {
785 if (!vf) {
786 return false;
787 }
788 vf->seek(vf, 0x104, SEEK_SET);
789 uint8_t header[4];
790
791 if (vf->read(vf, &header, sizeof(header)) < (ssize_t) sizeof(header)) {
792 return false;
793 }
794 if (memcmp(header, _knownHeader, sizeof(header))) {
795 return false;
796 }
797 return true;
798}
799
800void GBGetGameTitle(const struct GB* gb, char* out) {
801 const struct GBCartridge* cart = NULL;
802 if (gb->memory.rom) {
803 cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
804 }
805 if (!cart) {
806 return;
807 }
808 if (cart->oldLicensee != 0x33) {
809 memcpy(out, cart->titleLong, 16);
810 } else {
811 memcpy(out, cart->titleShort, 11);
812 }
813}
814
815void GBGetGameCode(const struct GB* gb, char* out) {
816 memset(out, 0, 8);
817 const struct GBCartridge* cart = NULL;
818 if (gb->memory.rom) {
819 cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
820 }
821 if (!cart) {
822 return;
823 }
824 if (cart->cgb == 0xC0) {
825 memcpy(out, "CGB-????", 8);
826 } else {
827 memcpy(out, "DMG-????", 8);
828 }
829 if (cart->oldLicensee == 0x33) {
830 memcpy(&out[4], cart->maker, 4);
831 }
832}
833
834void GBFrameStarted(struct GB* gb) {
835 GBTestKeypadIRQ(gb);
836
837 size_t c;
838 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
839 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
840 if (callbacks->videoFrameStarted) {
841 callbacks->videoFrameStarted(callbacks->context);
842 }
843 }
844}
845
846void GBFrameEnded(struct GB* gb) {
847 GBSramClean(gb, gb->video.frameCounter);
848
849 if (gb->cpu->components && gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
850 struct mCheatDevice* device = (struct mCheatDevice*) gb->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
851 size_t i;
852 for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
853 struct mCheatSet* cheats = *mCheatSetsGetPointer(&device->cheats, i);
854 mCheatRefresh(device, cheats);
855 }
856 }
857
858 // TODO: Move to common code
859 if (gb->stream && gb->stream->postVideoFrame) {
860 const color_t* pixels;
861 size_t stride;
862 gb->video.renderer->getPixels(gb->video.renderer, &stride, (const void**) &pixels);
863 gb->stream->postVideoFrame(gb->stream, pixels, stride);
864 }
865
866 size_t c;
867 for (c = 0; c < mCoreCallbacksListSize(&gb->coreCallbacks); ++c) {
868 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gb->coreCallbacks, c);
869 if (callbacks->videoFrameEnded) {
870 callbacks->videoFrameEnded(callbacks->context);
871 }
872 }
873}
874
875enum GBModel GBNameToModel(const char* model) {
876 if (strcasecmp(model, "DMG") == 0) {
877 return GB_MODEL_DMG;
878 } else if (strcasecmp(model, "CGB") == 0) {
879 return GB_MODEL_CGB;
880 } else if (strcasecmp(model, "AGB") == 0) {
881 return GB_MODEL_AGB;
882 } else if (strcasecmp(model, "SGB") == 0) {
883 return GB_MODEL_SGB;
884 } else if (strcasecmp(model, "MGB") == 0) {
885 return GB_MODEL_MGB;
886 } else if (strcasecmp(model, "SGB2") == 0) {
887 return GB_MODEL_SGB2;
888 }
889 return GB_MODEL_AUTODETECT;
890}
891
892const char* GBModelToName(enum GBModel model) {
893 switch (model) {
894 case GB_MODEL_DMG:
895 return "DMG";
896 case GB_MODEL_SGB:
897 return "SGB";
898 case GB_MODEL_MGB:
899 return "MGB";
900 case GB_MODEL_SGB2:
901 return "SGB2";
902 case GB_MODEL_CGB:
903 return "CGB";
904 case GB_MODEL_AGB:
905 return "AGB";
906 default:
907 case GB_MODEL_AUTODETECT:
908 return NULL;
909 }
910}