src/gba/gba-serialize.c (view raw)
1#include "gba-serialize.h"
2
3#include "gba-io.h"
4#include "memory.h"
5
6#include <fcntl.h>
7#include <limits.h>
8#include <stdio.h>
9#include <string.h>
10#include <unistd.h>
11
12const uint32_t GBA_SAVESTATE_MAGIC = 0x01000000;
13
14void GBASerialize(struct GBA* gba, struct GBASerializedState* state) {
15 state->versionMagic = GBA_SAVESTATE_MAGIC;
16
17 memcpy(state->cpu.gprs, gba->cpu.gprs, sizeof(state->cpu.gprs));
18 state->cpu.cpsr = gba->cpu.cpsr;
19 state->cpu.spsr = gba->cpu.spsr;
20 state->cpu.cycles = gba->cpu.cycles;
21 state->cpu.nextEvent = gba->cpu.nextEvent;
22 memcpy(state->cpu.bankedRegisters, gba->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
23 memcpy(state->cpu.bankedSPSRs, gba->cpu.bankedSPSRs, 6 * sizeof(int32_t));
24
25 GBAMemorySerialize(&gba->memory, state);
26 GBAIOSerialize(gba, state);
27 GBAVideoSerialize(&gba->video, state);
28}
29
30void GBADeserialize(struct GBA* gba, struct GBASerializedState* state) {
31 memcpy(gba->cpu.gprs, state->cpu.gprs, sizeof(gba->cpu.gprs));
32 gba->cpu.cpsr = state->cpu.cpsr;
33 gba->cpu.spsr = state->cpu.spsr;
34 gba->cpu.cycles = state->cpu.cycles;
35 gba->cpu.nextEvent = state->cpu.nextEvent;
36 memcpy(gba->cpu.bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
37 memcpy(gba->cpu.bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
38 gba->cpu.executionMode = gba->cpu.cpsr.t ? MODE_THUMB : MODE_ARM;
39 ARMSetPrivilegeMode(&gba->cpu, gba->cpu.cpsr.priv);
40 gba->cpu.memory->setActiveRegion(gba->cpu.memory, gba->cpu.gprs[ARM_PC]);
41
42 GBAMemoryDeserialize(&gba->memory, state);
43 GBAIODeserialize(gba, state);
44 GBAVideoDeserialize(&gba->video, state);
45}
46
47static int _getStateFd(struct GBA* gba, int slot) {
48 char path[PATH_MAX];
49 path[PATH_MAX - 1] = '\0';
50 snprintf(path, PATH_MAX - 1, "%s.ss%d", gba->activeFile, slot);
51 int fd = open(path, O_CREAT | O_RDWR, 0777);
52 if (fd >= 0) {
53 ftruncate(fd, sizeof(struct GBASerializedState));
54 }
55 return fd;
56}
57
58int GBASaveState(struct GBA* gba, int slot) {
59 int fd = _getStateFd(gba, slot);
60 if (fd < 0) {
61 return 0;
62 }
63 struct GBASerializedState* state = GBAMapState(fd);
64 GBASerialize(gba, state);
65 GBADeallocateState(state);
66 close(fd);
67 return 1;
68}
69
70int GBALoadState(struct GBA* gba, int slot) {
71 int fd = _getStateFd(gba, slot);
72 if (fd < 0) {
73 return 0;
74 }
75 struct GBASerializedState* state = GBAMapState(fd);
76 GBADeserialize(gba, state);
77 GBADeallocateState(state);
78 close(fd);
79 return 1;
80}
81
82struct GBASerializedState* GBAMapState(int fd) {
83 return fileMemoryMap(fd, sizeof(struct GBASerializedState), MEMORY_WRITE);
84}
85
86struct GBASerializedState* GBAAloocateState(void) {
87 return anonymousMemoryMap(sizeof(struct GBASerializedState));
88}
89
90void GBADeallocateState(struct GBASerializedState* state) {
91 mappedMemoryFree(state, sizeof(struct GBASerializedState));
92}