all repos — mgba @ 1f8c1bcdfa8a8fc8b2094870208d8b445627ea1e

mGBA Game Boy Advance Emulator

src/gba/gba-serialize.c (view raw)

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