-
Notifications
You must be signed in to change notification settings - Fork 0
/
sim.c
113 lines (100 loc) · 2.72 KB
/
sim.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
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "sim.h"
#include "isa.h"
static struct CPUState cpu_state;
static struct MemoryRegion mem_region[NB_REGIONS] = {
{MEM_TEXT_START, MEM_TEXT_SIZE, NULL},
{MEM_DATA_START, MEM_DATA_SIZE, NULL},
};
void initialize()
{
int i;
reset_cpu();
for (i = 0; i < NB_REGIONS; i++) {
mem_region[i].mem = malloc(sizeof(uint8_t) * mem_region[i].size);
memset(mem_region[i].mem, 0, sizeof(uint8_t) * mem_region[i].size);
}
}
void reset_cpu()
{
int i;
cpu_state.CPSR = 0x00;
for (i = 0; i < NB_REGS; i++) {
cpu_state.regs[i] = 0x00;
}
cpu_state.regs[PC] = mem_region[MEM_TEXT].start;
cpu_state.halted = 0;
}
/** Find memory region of an address */
static struct MemoryRegion * find_mem_region(uint32_t address) {
for (int i = 0; i < NB_REGIONS; i++) {
if (mem_region[i].start <= address &&
address < (mem_region[i].start + mem_region[i].size)) {
return &mem_region[i];
}
}
return NULL;
}
void mem_write_8(uint32_t address, uint8_t data)
{
struct MemoryRegion *region = find_mem_region(address);
assert(region != NULL);
uint32_t offset = address - region->start;
region->mem[offset] = data;
}
uint8_t mem_read_8(uint32_t address)
{
struct MemoryRegion *region = find_mem_region(address);
assert(region != NULL);
uint32_t offset = address - region->start;
return region->mem[offset];
}
void mem_write_32(uint32_t address, uint32_t data)
{
struct MemoryRegion *region = find_mem_region(address);
assert(region != NULL);
uint32_t offset = address - region->start;
region->mem[offset+0] = (data >> 24) & 0xFF;
region->mem[offset+1] = (data >> 16) & 0xFF;
region->mem[offset+2] = (data >> 8) & 0xFF;
region->mem[offset+3] = (data >> 0) & 0xFF;
}
uint32_t mem_read_32(uint32_t address)
{
struct MemoryRegion *region = find_mem_region(address);
assert(region != NULL);
uint32_t offset = address - region->start;
return
(region->mem[offset+0] << 24) |
(region->mem[offset+1] << 16) |
(region->mem[offset+2] << 8) |
(region->mem[offset+3] << 0);
}
void load_program(FILE *fp)
{
uint32_t instruction;
uint32_t addr = mem_region[MEM_TEXT].start;
while (fscanf(fp, "%x\n", &instruction) != EOF) {
mem_write_32(addr, instruction);
addr += 4;
}
}
int cpu_cycle()
{
if (!cpu_state.halted) {
cpu_state = process_instruction(cpu_state);
}
return -cpu_state.halted;
}
struct CPUState get_cpu_state()
{
return cpu_state;
}
void set_reg(uint8_t reg_num, uint16_t data)
{
cpu_state.regs[reg_num] = data;
}