src/gba/gba.c (view raw)
1/* Copyright (c) 2013-2015 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 "gba.h"
7
8#include "arm/decoder.h"
9#include "arm/isa-inlines.h"
10
11#include "gba/bios.h"
12#include "gba/cheats.h"
13#include "gba/io.h"
14#include "gba/rr/rr.h"
15#include "gba/supervisor/thread.h"
16#include "gba/serialize.h"
17#include "gba/sio.h"
18
19#include "util/crc32.h"
20#include "util/memory.h"
21#include "util/math.h"
22#include "util/patch.h"
23#include "util/vfs.h"
24
25const uint32_t GBA_ARM7TDMI_FREQUENCY = 0x1000000;
26const uint32_t GBA_COMPONENT_MAGIC = 0x1000000;
27
28static const size_t GBA_ROM_MAGIC_OFFSET = 3;
29static const uint8_t GBA_ROM_MAGIC[] = { 0xEA };
30
31static const size_t GBA_MB_MAGIC_OFFSET = 0xC0;
32
33static void GBAInit(struct ARMCore* cpu, struct ARMComponent* component);
34static void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh);
35static void GBAProcessEvents(struct ARMCore* cpu);
36static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles);
37static void GBAHitStub(struct ARMCore* cpu, uint32_t opcode);
38static void GBAIllegal(struct ARMCore* cpu, uint32_t opcode);
39static void GBABreakpoint(struct ARMCore* cpu, int immediate);
40
41static bool _setSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t* opcode);
42static bool _clearSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t opcode);
43
44
45#ifdef _3DS
46extern uint32_t* romBuffer;
47extern size_t romBufferSize;
48#endif
49
50void GBACreate(struct GBA* gba) {
51 gba->d.id = GBA_COMPONENT_MAGIC;
52 gba->d.init = GBAInit;
53 gba->d.deinit = 0;
54}
55
56static void GBAInit(struct ARMCore* cpu, struct ARMComponent* component) {
57 struct GBA* gba = (struct GBA*) component;
58 gba->cpu = cpu;
59 gba->debugger = 0;
60 gba->sync = 0;
61
62 GBAInterruptHandlerInit(&cpu->irqh);
63 GBAMemoryInit(gba);
64 GBASavedataInit(&gba->memory.savedata, 0);
65
66 gba->video.p = gba;
67 GBAVideoInit(&gba->video);
68
69 gba->audio.p = gba;
70 GBAAudioInit(&gba->audio, GBA_AUDIO_SAMPLES);
71
72 GBAIOInit(gba);
73
74 gba->sio.p = gba;
75 GBASIOInit(&gba->sio);
76
77 gba->timersEnabled = 0;
78 memset(gba->timers, 0, sizeof(gba->timers));
79
80 gba->springIRQ = 0;
81 gba->keySource = 0;
82 gba->rotationSource = 0;
83 gba->luminanceSource = 0;
84 gba->rtcSource = 0;
85 gba->rumble = 0;
86 gba->rr = 0;
87
88 gba->romVf = 0;
89 gba->biosVf = 0;
90
91 gba->logHandler = 0;
92 gba->logLevel = GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL;
93 gba->stream = 0;
94 gba->keyCallback = 0;
95 gba->stopCallback = 0;
96
97 gba->biosChecksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
98
99 gba->idleOptimization = IDLE_LOOP_REMOVE;
100 gba->idleLoop = IDLE_LOOP_NONE;
101
102 gba->realisticTiming = true;
103 gba->hardCrash = true;
104
105 gba->performingDMA = false;
106
107 gba->pristineRom = 0;
108 gba->pristineRomSize = 0;
109}
110
111void GBAUnloadROM(struct GBA* gba) {
112 if (gba->memory.rom && gba->pristineRom != gba->memory.rom) {
113 if (gba->yankedRomSize) {
114 gba->yankedRomSize = 0;
115 }
116 mappedMemoryFree(gba->memory.rom, SIZE_CART0);
117 }
118 gba->memory.rom = 0;
119
120 if (gba->romVf) {
121#ifndef _3DS
122 gba->romVf->unmap(gba->romVf, gba->pristineRom, gba->pristineRomSize);
123#endif
124 gba->pristineRom = 0;
125 gba->romVf = 0;
126 }
127
128 GBASavedataDeinit(&gba->memory.savedata);
129 gba->idleLoop = IDLE_LOOP_NONE;
130}
131
132void GBADestroy(struct GBA* gba) {
133 GBAUnloadROM(gba);
134
135 if (gba->biosVf) {
136 gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
137 }
138
139 GBAMemoryDeinit(gba);
140 GBAVideoDeinit(&gba->video);
141 GBAAudioDeinit(&gba->audio);
142 GBASIODeinit(&gba->sio);
143 gba->rr = 0;
144}
145
146void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
147 irqh->reset = GBAReset;
148 irqh->processEvents = GBAProcessEvents;
149 irqh->swi16 = GBASwi16;
150 irqh->swi32 = GBASwi32;
151 irqh->hitIllegal = GBAIllegal;
152 irqh->readCPSR = GBATestIRQ;
153 irqh->hitStub = GBAHitStub;
154 irqh->bkpt16 = GBABreakpoint;
155 irqh->bkpt32 = GBABreakpoint;
156}
157
158void GBAReset(struct ARMCore* cpu) {
159 ARMSetPrivilegeMode(cpu, MODE_IRQ);
160 cpu->gprs[ARM_SP] = SP_BASE_IRQ;
161 ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
162 cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
163 ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
164 cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
165
166 struct GBA* gba = (struct GBA*) cpu->master;
167 if (!gba->rr || (!gba->rr->isPlaying(gba->rr) && !gba->rr->isRecording(gba->rr))) {
168 GBASavedataUnmask(&gba->memory.savedata);
169 }
170
171 if (gba->yankedRomSize) {
172 gba->memory.romSize = gba->yankedRomSize;
173 gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
174 gba->yankedRomSize = 0;
175 }
176 GBAMemoryReset(gba);
177 GBAVideoReset(&gba->video);
178 GBAAudioReset(&gba->audio);
179 GBAIOInit(gba);
180
181 GBASIOReset(&gba->sio);
182
183 gba->timersEnabled = 0;
184 memset(gba->timers, 0, sizeof(gba->timers));
185
186 gba->lastJump = 0;
187 gba->haltPending = false;
188 gba->idleDetectionStep = 0;
189 gba->idleDetectionFailures = 0;
190}
191
192void GBASkipBIOS(struct GBA* gba) {
193 struct ARMCore* cpu = gba->cpu;
194 if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
195 if (gba->memory.rom) {
196 cpu->gprs[ARM_PC] = BASE_CART0;
197 } else {
198 cpu->gprs[ARM_PC] = BASE_WORKING_RAM;
199 }
200 int currentCycles = 0;
201 ARM_WRITE_PC;
202 }
203}
204
205static void GBAProcessEvents(struct ARMCore* cpu) {
206 do {
207 struct GBA* gba = (struct GBA*) cpu->master;
208 int32_t cycles = cpu->nextEvent;
209 int32_t nextEvent = INT_MAX;
210 int32_t testEvent;
211#ifndef NDEBUG
212 if (cycles < 0) {
213 GBALog(gba, GBA_LOG_FATAL, "Negative cycles passed: %i", cycles);
214 }
215#endif
216
217 gba->bus = cpu->prefetch[1];
218 if (cpu->executionMode == MODE_THUMB) {
219 gba->bus |= cpu->prefetch[1] << 16;
220 }
221
222 if (gba->springIRQ) {
223 ARMRaiseIRQ(cpu);
224 gba->springIRQ = 0;
225 }
226
227 testEvent = GBAVideoProcessEvents(&gba->video, cycles);
228 if (testEvent < nextEvent) {
229 nextEvent = testEvent;
230 }
231
232 testEvent = GBAAudioProcessEvents(&gba->audio, cycles);
233 if (testEvent < nextEvent) {
234 nextEvent = testEvent;
235 }
236
237 testEvent = GBATimersProcessEvents(gba, cycles);
238 if (testEvent < nextEvent) {
239 nextEvent = testEvent;
240 }
241
242 testEvent = GBAMemoryRunDMAs(gba, cycles);
243 if (testEvent < nextEvent) {
244 nextEvent = testEvent;
245 }
246
247 testEvent = GBASIOProcessEvents(&gba->sio, cycles);
248 if (testEvent < nextEvent) {
249 nextEvent = testEvent;
250 }
251
252 cpu->cycles -= cycles;
253 cpu->nextEvent = nextEvent;
254
255 if (cpu->halted) {
256 cpu->cycles = cpu->nextEvent;
257 }
258 } while (cpu->cycles >= cpu->nextEvent);
259}
260
261static int32_t GBATimersProcessEvents(struct GBA* gba, int32_t cycles) {
262 int32_t nextEvent = INT_MAX;
263 if (gba->timersEnabled) {
264 struct GBATimer* timer;
265 struct GBATimer* nextTimer;
266
267 timer = &gba->timers[0];
268 if (GBATimerFlagsIsEnable(timer->flags)) {
269 timer->nextEvent -= cycles;
270 timer->lastEvent -= cycles;
271 while (timer->nextEvent <= 0) {
272 timer->lastEvent = timer->nextEvent;
273 timer->nextEvent += timer->overflowInterval;
274 gba->memory.io[REG_TM0CNT_LO >> 1] = timer->reload;
275 timer->oldReload = timer->reload;
276
277 if (GBATimerFlagsIsDoIrq(timer->flags)) {
278 GBARaiseIRQ(gba, IRQ_TIMER0);
279 }
280
281 if (gba->audio.enable) {
282 if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 0) {
283 GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
284 }
285
286 if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 0) {
287 GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
288 }
289 }
290
291 nextTimer = &gba->timers[1];
292 if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
293 ++gba->memory.io[REG_TM1CNT_LO >> 1];
294 if (!gba->memory.io[REG_TM1CNT_LO >> 1]) {
295 nextTimer->nextEvent = 0;
296 }
297 }
298 }
299 nextEvent = timer->nextEvent;
300 }
301
302 timer = &gba->timers[1];
303 if (GBATimerFlagsIsEnable(timer->flags)) {
304 timer->nextEvent -= cycles;
305 timer->lastEvent -= cycles;
306 if (timer->nextEvent <= 0) {
307 timer->lastEvent = timer->nextEvent;
308 timer->nextEvent += timer->overflowInterval;
309 gba->memory.io[REG_TM1CNT_LO >> 1] = timer->reload;
310 timer->oldReload = timer->reload;
311
312 if (GBATimerFlagsIsDoIrq(timer->flags)) {
313 GBARaiseIRQ(gba, IRQ_TIMER1);
314 }
315
316 if (gba->audio.enable) {
317 if ((gba->audio.chALeft || gba->audio.chARight) && gba->audio.chATimer == 1) {
318 GBAAudioSampleFIFO(&gba->audio, 0, timer->lastEvent);
319 }
320
321 if ((gba->audio.chBLeft || gba->audio.chBRight) && gba->audio.chBTimer == 1) {
322 GBAAudioSampleFIFO(&gba->audio, 1, timer->lastEvent);
323 }
324 }
325
326 if (GBATimerFlagsIsCountUp(timer->flags)) {
327 timer->nextEvent = INT_MAX;
328 }
329
330 nextTimer = &gba->timers[2];
331 if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
332 ++gba->memory.io[REG_TM2CNT_LO >> 1];
333 if (!gba->memory.io[REG_TM2CNT_LO >> 1]) {
334 nextTimer->nextEvent = 0;
335 }
336 }
337 }
338 if (timer->nextEvent < nextEvent) {
339 nextEvent = timer->nextEvent;
340 }
341 }
342
343 timer = &gba->timers[2];
344 if (GBATimerFlagsIsEnable(timer->flags)) {
345 timer->nextEvent -= cycles;
346 timer->lastEvent -= cycles;
347 if (timer->nextEvent <= 0) {
348 timer->lastEvent = timer->nextEvent;
349 timer->nextEvent += timer->overflowInterval;
350 gba->memory.io[REG_TM2CNT_LO >> 1] = timer->reload;
351 timer->oldReload = timer->reload;
352
353 if (GBATimerFlagsIsDoIrq(timer->flags)) {
354 GBARaiseIRQ(gba, IRQ_TIMER2);
355 }
356
357 if (GBATimerFlagsIsCountUp(timer->flags)) {
358 timer->nextEvent = INT_MAX;
359 }
360
361 nextTimer = &gba->timers[3];
362 if (GBATimerFlagsIsCountUp(nextTimer->flags)) {
363 ++gba->memory.io[REG_TM3CNT_LO >> 1];
364 if (!gba->memory.io[REG_TM3CNT_LO >> 1]) {
365 nextTimer->nextEvent = 0;
366 }
367 }
368 }
369 if (timer->nextEvent < nextEvent) {
370 nextEvent = timer->nextEvent;
371 }
372 }
373
374 timer = &gba->timers[3];
375 if (GBATimerFlagsIsEnable(timer->flags)) {
376 timer->nextEvent -= cycles;
377 timer->lastEvent -= cycles;
378 if (timer->nextEvent <= 0) {
379 timer->lastEvent = timer->nextEvent;
380 timer->nextEvent += timer->overflowInterval;
381 gba->memory.io[REG_TM3CNT_LO >> 1] = timer->reload;
382 timer->oldReload = timer->reload;
383
384 if (GBATimerFlagsIsDoIrq(timer->flags)) {
385 GBARaiseIRQ(gba, IRQ_TIMER3);
386 }
387
388 if (GBATimerFlagsIsCountUp(timer->flags)) {
389 timer->nextEvent = INT_MAX;
390 }
391 }
392 if (timer->nextEvent < nextEvent) {
393 nextEvent = timer->nextEvent;
394 }
395 }
396 }
397 return nextEvent;
398}
399
400void GBAAttachDebugger(struct GBA* gba, struct ARMDebugger* debugger) {
401 debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
402 debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
403 gba->debugger = debugger;
404 gba->cpu->components[GBA_COMPONENT_DEBUGGER] = &debugger->d;
405 ARMHotplugAttach(gba->cpu, GBA_COMPONENT_DEBUGGER);
406}
407
408void GBADetachDebugger(struct GBA* gba) {
409 gba->debugger = 0;
410 ARMHotplugDetach(gba->cpu, GBA_COMPONENT_DEBUGGER);
411 gba->cpu->components[GBA_COMPONENT_DEBUGGER] = 0;
412}
413
414bool GBALoadMB(struct GBA* gba, struct VFile* vf, const char* fname) {
415 GBAUnloadROM(gba);
416 gba->romVf = vf;
417 gba->pristineRomSize = vf->size(vf);
418 vf->seek(vf, 0, SEEK_SET);
419 if (gba->pristineRomSize > SIZE_WORKING_RAM) {
420 gba->pristineRomSize = SIZE_WORKING_RAM;
421 }
422#ifdef _3DS
423 gba->pristineRom = 0;
424 if (gba->pristineRomSize <= romBufferSize) {
425 gba->pristineRom = romBuffer;
426 vf->read(vf, romBuffer, gba->pristineRomSize);
427 }
428#else
429 gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
430#endif
431 if (!gba->pristineRom) {
432 GBALog(gba, GBA_LOG_WARN, "Couldn't map ROM");
433 return false;
434 }
435 gba->yankedRomSize = 0;
436 gba->activeFile = fname;
437 gba->memory.romSize = 0;
438 gba->memory.romMask = 0;
439 gba->romCrc32 = doCrc32(gba->pristineRom, gba->pristineRomSize);
440 return true;
441}
442
443bool GBALoadROM(struct GBA* gba, struct VFile* vf, struct VFile* sav, const char* fname) {
444 GBAUnloadROM(gba);
445 gba->romVf = vf;
446 gba->pristineRomSize = vf->size(vf);
447 vf->seek(vf, 0, SEEK_SET);
448 if (gba->pristineRomSize > SIZE_CART0) {
449 gba->pristineRomSize = SIZE_CART0;
450 }
451#ifdef _3DS
452 gba->pristineRom = 0;
453 if (gba->pristineRomSize <= romBufferSize) {
454 gba->pristineRom = romBuffer;
455 vf->read(vf, romBuffer, gba->pristineRomSize);
456 }
457#else
458 gba->pristineRom = vf->map(vf, gba->pristineRomSize, MAP_READ);
459#endif
460 if (!gba->pristineRom) {
461 GBALog(gba, GBA_LOG_WARN, "Couldn't map ROM");
462 return false;
463 }
464 gba->yankedRomSize = 0;
465 gba->memory.rom = gba->pristineRom;
466 gba->activeFile = fname;
467 gba->memory.romSize = gba->pristineRomSize;
468 gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
469 gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
470 GBASavedataInit(&gba->memory.savedata, sav);
471 GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
472 return true;
473 // TODO: error check
474}
475
476void GBAYankROM(struct GBA* gba) {
477 gba->yankedRomSize = gba->memory.romSize;
478 gba->memory.romSize = 0;
479 gba->memory.romMask = 0;
480 GBARaiseIRQ(gba, IRQ_GAMEPAK);
481}
482
483void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
484 gba->biosVf = vf;
485 uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
486 if (!bios) {
487 GBALog(gba, GBA_LOG_WARN, "Couldn't map BIOS");
488 return;
489 }
490 gba->memory.bios = bios;
491 gba->memory.fullBios = 1;
492 uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
493 GBALog(gba, GBA_LOG_DEBUG, "BIOS Checksum: 0x%X", checksum);
494 if (checksum == GBA_BIOS_CHECKSUM) {
495 GBALog(gba, GBA_LOG_INFO, "Official GBA BIOS detected");
496 } else if (checksum == GBA_DS_BIOS_CHECKSUM) {
497 GBALog(gba, GBA_LOG_INFO, "Official GBA (DS) BIOS detected");
498 } else {
499 GBALog(gba, GBA_LOG_WARN, "BIOS checksum incorrect");
500 }
501 gba->biosChecksum = checksum;
502 if (gba->memory.activeRegion == REGION_BIOS) {
503 gba->cpu->memory.activeRegion = gba->memory.bios;
504 }
505 // TODO: error check
506}
507
508void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
509 size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
510 if (!patchedSize || patchedSize > SIZE_CART0) {
511 return;
512 }
513 gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
514 if (!patch->applyPatch(patch, gba->pristineRom, gba->pristineRomSize, gba->memory.rom, patchedSize)) {
515 mappedMemoryFree(gba->memory.rom, patchedSize);
516 gba->memory.rom = gba->pristineRom;
517 return;
518 }
519 gba->memory.romSize = patchedSize;
520 gba->memory.romMask = SIZE_CART0 - 1;
521 gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
522}
523
524void GBATimerUpdateRegister(struct GBA* gba, int timer) {
525 struct GBATimer* currentTimer = &gba->timers[timer];
526 if (GBATimerFlagsIsEnable(currentTimer->flags) && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
527 int32_t prefetchSkew = 0;
528 if (gba->memory.lastPrefetchedPc - gba->memory.lastPrefetchedLoads * WORD_SIZE_THUMB >= (uint32_t) gba->cpu->gprs[ARM_PC]) {
529 prefetchSkew = (gba->memory.lastPrefetchedPc - gba->cpu->gprs[ARM_PC]) * (gba->cpu->memory.activeSeqCycles16 + 1) / WORD_SIZE_THUMB;
530 }
531 // Reading this takes two cycles (1N+1I), so let's remove them preemptively
532 gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent - 2 + prefetchSkew) >> GBATimerFlagsGetPrescaleBits(currentTimer->flags));
533 }
534}
535
536void GBATimerWriteTMCNT_LO(struct GBA* gba, int timer, uint16_t reload) {
537 gba->timers[timer].reload = reload;
538 gba->timers[timer].overflowInterval = (0x10000 - gba->timers[timer].reload) << GBATimerFlagsGetPrescaleBits(gba->timers[timer].flags);
539}
540
541void GBATimerWriteTMCNT_HI(struct GBA* gba, int timer, uint16_t control) {
542 struct GBATimer* currentTimer = &gba->timers[timer];
543 GBATimerUpdateRegister(gba, timer);
544
545 unsigned oldPrescale = GBATimerFlagsGetPrescaleBits(currentTimer->flags);
546 switch (control & 0x0003) {
547 case 0x0000:
548 currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 0);
549 break;
550 case 0x0001:
551 currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 6);
552 break;
553 case 0x0002:
554 currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 8);
555 break;
556 case 0x0003:
557 currentTimer->flags = GBATimerFlagsSetPrescaleBits(currentTimer->flags, 10);
558 break;
559 }
560 currentTimer->flags = GBATimerFlagsTestFillCountUp(currentTimer->flags, control & 0x0004);
561 currentTimer->flags = GBATimerFlagsTestFillDoIrq(currentTimer->flags, control & 0x0040);
562 currentTimer->overflowInterval = (0x10000 - currentTimer->reload) << GBATimerFlagsGetPrescaleBits(currentTimer->flags);
563 bool wasEnabled = GBATimerFlagsIsEnable(currentTimer->flags);
564 currentTimer->flags = GBATimerFlagsTestFillEnable(currentTimer->flags, control & 0x0080);
565 if (!wasEnabled && GBATimerFlagsIsEnable(currentTimer->flags)) {
566 if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
567 currentTimer->nextEvent = gba->cpu->cycles + currentTimer->overflowInterval;
568 } else {
569 currentTimer->nextEvent = INT_MAX;
570 }
571 gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->reload;
572 currentTimer->oldReload = currentTimer->reload;
573 currentTimer->lastEvent = gba->cpu->cycles;
574 gba->timersEnabled |= 1 << timer;
575 } else if (wasEnabled && !GBATimerFlagsIsEnable(currentTimer->flags)) {
576 if (!GBATimerFlagsIsCountUp(currentTimer->flags)) {
577 gba->memory.io[(REG_TM0CNT_LO + (timer << 2)) >> 1] = currentTimer->oldReload + ((gba->cpu->cycles - currentTimer->lastEvent) >> oldPrescale);
578 }
579 gba->timersEnabled &= ~(1 << timer);
580 } else if (GBATimerFlagsGetPrescaleBits(currentTimer->flags) != oldPrescale && !GBATimerFlagsIsCountUp(currentTimer->flags)) {
581 // FIXME: this might be before present
582 currentTimer->nextEvent = currentTimer->lastEvent + currentTimer->overflowInterval;
583 }
584
585 if (currentTimer->nextEvent < gba->cpu->nextEvent) {
586 gba->cpu->nextEvent = currentTimer->nextEvent;
587 }
588};
589
590void GBAWriteIE(struct GBA* gba, uint16_t value) {
591 if (value & (1 << IRQ_KEYPAD)) {
592 GBALog(gba, GBA_LOG_STUB, "Keypad interrupts not implemented");
593 }
594
595 if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
596 ARMRaiseIRQ(gba->cpu);
597 }
598}
599
600void GBAWriteIME(struct GBA* gba, uint16_t value) {
601 if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
602 ARMRaiseIRQ(gba->cpu);
603 }
604}
605
606void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
607 gba->memory.io[REG_IF >> 1] |= 1 << irq;
608 gba->cpu->halted = 0;
609
610 if (gba->memory.io[REG_IME >> 1] && (gba->memory.io[REG_IE >> 1] & 1 << irq)) {
611 ARMRaiseIRQ(gba->cpu);
612 }
613}
614
615void GBATestIRQ(struct ARMCore* cpu) {
616 struct GBA* gba = (struct GBA*) cpu->master;
617 if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
618 gba->springIRQ = 1;
619 gba->cpu->nextEvent = gba->cpu->cycles;
620 }
621}
622
623void GBAHalt(struct GBA* gba) {
624 gba->cpu->nextEvent = gba->cpu->cycles;
625 gba->cpu->halted = 1;
626}
627
628void GBAStop(struct GBA* gba) {
629 if (!gba->stopCallback) {
630 return;
631 }
632 gba->cpu->nextEvent = gba->cpu->cycles;
633 gba->stopCallback->stop(gba->stopCallback);
634}
635
636static void _GBAVLog(struct GBA* gba, enum GBALogLevel level, const char* format, va_list args) {
637 struct GBAThread* threadContext = GBAThreadGetContext();
638 enum GBALogLevel logLevel = GBA_LOG_ALL;
639
640 if (gba) {
641 logLevel = gba->logLevel;
642 }
643
644 if (threadContext) {
645 logLevel = threadContext->logLevel;
646 gba = threadContext->gba;
647 }
648
649 if (!(level & logLevel) && level != GBA_LOG_FATAL) {
650 return;
651 }
652
653 if (level == GBA_LOG_FATAL && gba) {
654 gba->cpu->nextEvent = 0;
655 }
656
657 if (threadContext) {
658 if (level == GBA_LOG_FATAL) {
659 MutexLock(&threadContext->stateMutex);
660 threadContext->state = THREAD_CRASHED;
661 MutexUnlock(&threadContext->stateMutex);
662 }
663 }
664 if (gba && gba->logHandler) {
665 gba->logHandler(threadContext, level, format, args);
666 return;
667 }
668
669 vprintf(format, args);
670 printf("\n");
671
672 if (level == GBA_LOG_FATAL && !threadContext) {
673 abort();
674 }
675}
676
677void GBALog(struct GBA* gba, enum GBALogLevel level, const char* format, ...) {
678 va_list args;
679 va_start(args, format);
680 _GBAVLog(gba, level, format, args);
681 va_end(args);
682}
683
684void GBADebuggerLogShim(struct ARMDebugger* debugger, enum DebuggerLogLevel level, const char* format, ...) {
685 struct GBA* gba = 0;
686 if (debugger->cpu) {
687 gba = (struct GBA*) debugger->cpu->master;
688 }
689
690 enum GBALogLevel gbaLevel;
691 switch (level) {
692 default: // Avoids compiler warning
693 case DEBUGGER_LOG_DEBUG:
694 gbaLevel = GBA_LOG_DEBUG;
695 break;
696 case DEBUGGER_LOG_INFO:
697 gbaLevel = GBA_LOG_INFO;
698 break;
699 case DEBUGGER_LOG_WARN:
700 gbaLevel = GBA_LOG_WARN;
701 break;
702 case DEBUGGER_LOG_ERROR:
703 gbaLevel = GBA_LOG_ERROR;
704 break;
705 }
706 va_list args;
707 va_start(args, format);
708 _GBAVLog(gba, gbaLevel, format, args);
709 va_end(args);
710}
711
712bool GBAIsROM(struct VFile* vf) {
713 if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
714 return false;
715 }
716 uint8_t signature[sizeof(GBA_ROM_MAGIC)];
717 if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
718 return false;
719 }
720 if (GBAIsBIOS(vf)) {
721 return false;
722 }
723 return memcmp(signature, GBA_ROM_MAGIC, sizeof(signature)) == 0;
724}
725
726bool GBAIsMB(struct VFile* vf) {
727 if (!GBAIsROM(vf)) {
728 return false;
729 }
730 if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
731 return false;
732 }
733 uint8_t signature[sizeof(uint32_t)];
734 if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
735 return false;
736 }
737 uint32_t opcode;
738 LOAD_32(opcode, 0, signature);
739 struct ARMInstructionInfo info;
740 ARMDecodeARM(opcode, &info);
741 if (info.branchType != ARM_BRANCH) {
742 return false;
743 }
744 if (info.op1.immediate <= 0) {
745 return false;
746 } else if (info.op1.immediate != 24) {
747 return true;
748 }
749 // Found a libgba-linked cart...these are a bit harder to detect.
750 return false;
751}
752
753bool GBAIsBIOS(struct VFile* vf) {
754 if (vf->seek(vf, 0, SEEK_SET) < 0) {
755 return false;
756 }
757 uint8_t interruptTable[7 * 4];
758 if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
759 return false;
760 }
761 int i;
762 for (i = 0; i < 7; ++i) {
763 if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
764 return false;
765 }
766 }
767 return true;
768}
769
770void GBAGetGameCode(struct GBA* gba, char* out) {
771 if (!gba->memory.rom) {
772 out[0] = '\0';
773 return;
774 }
775 memcpy(out, &((struct GBACartridge*) gba->memory.rom)->id, 4);
776}
777
778void GBAGetGameTitle(struct GBA* gba, char* out) {
779 if (gba->memory.rom) {
780 memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
781 return;
782 }
783 if (gba->pristineRom) {
784 memcpy(out, &((struct GBACartridge*) gba->pristineRom)->title, 12);
785 return;
786 }
787 strncpy(out, "(BIOS)", 12);
788}
789
790void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
791 struct GBA* gba = (struct GBA*) cpu->master;
792 enum GBALogLevel level = GBA_LOG_ERROR;
793 if (gba->debugger) {
794 level = GBA_LOG_STUB;
795 struct DebuggerEntryInfo info = {
796 .address = _ARMPCAddress(cpu),
797 .opcode = opcode
798 };
799 ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
800 }
801 GBALog(gba, level, "Stub opcode: %08x", opcode);
802}
803
804void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
805 struct GBA* gba = (struct GBA*) cpu->master;
806 if (!gba->yankedRomSize) {
807 GBALog(gba, GBA_LOG_WARN, "Illegal opcode: %08x", opcode);
808 }
809 if (gba->debugger) {
810 struct DebuggerEntryInfo info = {
811 .address = _ARMPCAddress(cpu),
812 .opcode = opcode
813 };
814 ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_ILLEGAL_OP, &info);
815 } else {
816 ARMRaiseUndefined(cpu);
817 }
818}
819
820void GBABreakpoint(struct ARMCore* cpu, int immediate) {
821 struct GBA* gba = (struct GBA*) cpu->master;
822 if (immediate >= GBA_COMPONENT_MAX) {
823 return;
824 }
825 switch (immediate) {
826 case GBA_COMPONENT_DEBUGGER:
827 if (gba->debugger) {
828 struct DebuggerEntryInfo info = {
829 .address = _ARMPCAddress(cpu)
830 };
831 ARMDebuggerEnter(gba->debugger, DEBUGGER_ENTER_BREAKPOINT, &info);
832 }
833 break;
834 case GBA_COMPONENT_CHEAT_DEVICE:
835 if (gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
836 struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
837 struct GBACheatHook* hook = 0;
838 size_t i;
839 for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
840 struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
841 if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
842 GBACheatRefresh(device, cheats);
843 hook = cheats->hook;
844 }
845 }
846 if (hook) {
847 ARMRunFake(cpu, hook->patchedOpcode);
848 }
849 }
850 break;
851 default:
852 break;
853 }
854}
855
856void GBAFrameStarted(struct GBA* gba) {
857 UNUSED(gba);
858
859 struct GBAThread* thread = GBAThreadGetContext();
860 if (!thread) {
861 return;
862 }
863
864 if (thread->rewindBuffer) {
865 --thread->rewindBufferNext;
866 if (thread->rewindBufferNext <= 0) {
867 thread->rewindBufferNext = thread->rewindBufferInterval;
868 GBARecordFrame(thread);
869 }
870 }
871}
872
873void GBAFrameEnded(struct GBA* gba) {
874 GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
875
876 if (gba->rr) {
877 gba->rr->nextFrame(gba->rr);
878 }
879
880 if (gba->cpu->components && gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE]) {
881 struct GBACheatDevice* device = (struct GBACheatDevice*) gba->cpu->components[GBA_COMPONENT_CHEAT_DEVICE];
882 size_t i;
883 for (i = 0; i < GBACheatSetsSize(&device->cheats); ++i) {
884 struct GBACheatSet* cheats = *GBACheatSetsGetPointer(&device->cheats, i);
885 if (!cheats->hook) {
886 GBACheatRefresh(device, cheats);
887 }
888 }
889 }
890
891 if (gba->stream && gba->stream->postVideoFrame) {
892 gba->stream->postVideoFrame(gba->stream, gba->video.renderer);
893 }
894
895 if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
896 GBAHardwarePlayerUpdate(gba);
897 }
898
899 struct GBAThread* thread = GBAThreadGetContext();
900 if (!thread) {
901 return;
902 }
903
904 if (thread->frameCallback) {
905 thread->frameCallback(thread);
906 }
907}
908
909void GBASetBreakpoint(struct GBA* gba, struct ARMComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
910 size_t immediate;
911 for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
912 if (gba->cpu->components[immediate] == component) {
913 break;
914 }
915 }
916 if (immediate == gba->cpu->numComponents) {
917 return;
918 }
919 if (mode == MODE_ARM) {
920 int32_t value;
921 int32_t old;
922 value = 0xE1200070;
923 value |= immediate & 0xF;
924 value |= (immediate & 0xFFF0) << 4;
925 GBAPatch32(gba->cpu, address, value, &old);
926 *opcode = old;
927 } else {
928 int16_t value;
929 int16_t old;
930 value = 0xBE00;
931 value |= immediate & 0xFF;
932 GBAPatch16(gba->cpu, address, value, &old);
933 *opcode = (uint16_t) old;
934 }
935}
936
937void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
938 if (mode == MODE_ARM) {
939 GBAPatch32(gba->cpu, address, opcode, 0);
940 } else {
941 GBAPatch16(gba->cpu, address, opcode, 0);
942 }
943}
944
945#if (!defined(USE_PTHREADS) && !defined(_WIN32)) || defined(DISABLE_THREADING)
946struct GBAThread* GBAThreadGetContext(void) {
947 return 0;
948}
949#endif
950
951static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
952 GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d, address, mode, opcode);
953 return true;
954}
955
956static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
957 GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
958 return true;
959}