-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem.c
144 lines (112 loc) · 2.57 KB
/
mem.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <ctype.h>
#include "mem.h"
#include "panic.h"
void mem_init(mem_t *mem, bool read_only_cartridge)
{
int i;
int j;
for (j = 0; j < MEM_CART_BANKS; j++) {
for (i = 0; i < MEM_SIZE_CART; i++) {
mem->cart[j][i] = 0x00;
}
}
for (i = 0; i < MEM_SIZE_RAM; i++) {
mem->ram[i] = 0x00;
}
mem->read_only_cartridge = read_only_cartridge;
mem->bank = 0;
}
uint8_t mem_read(mem_t *mem, uint16_t address)
{
if (address < 0x8000) {
return mem->cart[mem->bank][address];
} else {
return mem->ram[address - 0x8000];
}
}
void mem_write(mem_t *mem, uint16_t address, uint8_t value)
{
if (address < 0x8000) {
if (mem->read_only_cartridge) {
panic("Memory write to read-only cartridge area: 0x%04x\n", address);
return;
}
mem->cart[mem->bank][address] = value;
} else {
mem->ram[address - 0x8000] = value;
}
}
int mem_load_from_file(mem_t *mem, const char *filename, uint16_t address)
{
FILE *fh;
int c;
fh = fopen(filename, "rb");
if (fh == NULL) {
return -1;
}
while ((c = fgetc(fh)) != EOF) {
mem->cart[mem->bank][address] = c;
address++;
if (address >= MEM_SIZE_CART) {
address = 0;
mem->bank++;
if (mem->bank >= MEM_CART_BANKS) {
break;
}
}
}
if (mem->bank > 1) {
mem->bank = 0x3F; /* Bank-switched cartridge, boot from last bank. */
} else {
mem->bank = 0; /* Regular cartridge, boot from first/only bank. */
}
fclose(fh);
return 0;
}
static void mem_dump_16(FILE *fh, mem_t *mem, uint16_t start, uint16_t end)
{
int i;
uint16_t address;
uint8_t value;
fprintf(fh, "%04x ", start & 0xFFF0);
/* Hex */
for (i = 0; i < 16; i++) {
address = (start & 0xFFF0) + i;
value = mem_read(mem, address);
if ((address >= start) && (address <= end)) {
fprintf(fh, "%02x ", value);
} else {
fprintf(fh, " ");
}
if (i % 4 == 3) {
fprintf(fh, " ");
}
}
/* Character */
for (i = 0; i < 16; i++) {
address = (start & 0xFFF0) + i;
value = mem_read(mem, address);
if ((address >= start) && (address <= end)) {
if (isprint(value)) {
fprintf(fh, "%c", value);
} else {
fprintf(fh, ".");
}
} else {
fprintf(fh, " ");
}
}
fprintf(fh, "\n");
}
void mem_dump(FILE *fh, mem_t *mem, uint16_t start, uint16_t end)
{
int i;
mem_dump_16(fh, mem, start, end);
for (i = (start & 0xFFF0) + 16; i <= end; i += 16) {
mem_dump_16(fh, mem, i, end);
}
}