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