-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoader.cpp
More file actions
260 lines (227 loc) · 8.43 KB
/
Copy pathLoader.cpp
File metadata and controls
260 lines (227 loc) · 8.43 KB
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// ============================================================
// LOADER PROCESSING
// ============================================================
// Purpose: LOADING & EXECUTION PHASE
// Simulates an OS loader + CPU executing the program.
// – load() : place instructions into virtual memory
// – execute() : fetch-decode-execute loop
// ============================================================
#include "Assembler.h"
#include "Linker.h"
#include "Loader.h"
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <cmath> // for numeric operations
// CONSTRUCTOR
Loader::Loader() : pc_(0), running_(false) {}
// LOAD – place linked instructions into virtual memory and set PC
void Loader::load(const std::vector<AsmInstruction>& instructions) {
memory_ = instructions;
pc_ = 0;
running_ = true;
// Skip runtime stubs and find "main:" entry point
for (int i = 0; i < (int)memory_.size(); i++) {
if (memory_[i].opcode == "main:") {
pc_ = i + 1; // Start executing after the main: label
break;
}
}
std::cout << " [LOADER] Loaded " << memory_.size()
<< " instructions into virtual memory.\n";
std::cout << " [LOADER] Program counter set to 0x"
<< std::hex << pc_ << std::dec << "\n";
}
// EVAL – evaluate an operand (register, variable, or literal)
double Loader::eval(const std::string& operand) {
if (operand.empty()) return 0.0;
// String literal – return 0 (printing handled separately)
if (!operand.empty() && operand[0] == '"') return 0.0;
// Check if it is a known variable
if (variables_.count(operand)) return variables_[operand];
// Check if it is a known register
if (registers_.count(operand)) return registers_[operand];
// Try to parse as a numeric literal
try {
return std::stod(operand);
} catch (...) {
return 0.0; // Unknown operand defaults to 0
}
}
// STORE – store a value into a register or variable
void Loader::store(const std::string& dest, double val) {
// Registers start with 'E' or 'R' (e.g. EAX, ECX, R8)
bool isReg = (!dest.empty() &&
(dest[0] == 'E' || dest[0] == 'R' || dest == "AL"));
if (isReg) {
registers_[dest] = val;
} else {
variables_[dest] = val; // User variable
}
}
// STEP – execute one instruction at PC
void Loader::step() {
if (pc_ >= (int)memory_.size()) {
running_ = false;
return;
}
const AsmInstruction& instr = memory_[pc_];
std::string op = instr.opcode;
std::string dest = instr.dest;
std::string src = instr.src;
// LABELS: skip them (they are just markers, not executable instructions)
if (!op.empty() && op.back() == ':') {
pc_++;
return;
}
// DIRECTIVES: skip them (handled at link time, not runtime)
if (op == ".section" || op == ".global" || op == "main:") {
pc_++;
return;
}
// MOV / MOVZX: dest = src (MOVZX treated same for simplicity)
if (op == "MOV" || op == "MOVZX") {
store(dest, eval(src));
pc_++;
return;
}
// ADD: dest += src
if (op == "ADD") {
store(dest, eval(dest) + eval(src));
pc_++;
return;
}
// SUB: dest -= src
if (op == "SUB") {
store(dest, eval(dest) - eval(src));
pc_++;
return;
}
// IMUL: dest *= src
if (op == "IMUL") {
store(dest, eval(dest) * eval(src));
pc_++;
return;
}
// IDIV: dest = floor(dest / src) with division by zero check
if (op == "IDIV") {
double divisor = eval(dest);
if (divisor == 0) throw std::runtime_error("Division by zero");
store("EAX", std::floor(eval("EAX") / divisor));
pc_++;
return;
}
// CMP: set FLAGS = dest - src (for conditional jumps)
if (op == "CMP") {
registers_["FLAGS"] = eval(dest) - eval(src);
pc_++;
return;
}
// SETcc: set AL = 1 if condition met, else 0 (using FLAGS from CMP)
if (op == "SETE") { store("AL", registers_["FLAGS"] == 0 ? 1 : 0); pc_++; return; }
if (op == "SETNE") { store("AL", registers_["FLAGS"] != 0 ? 1 : 0); pc_++; return; }
if (op == "SETL") { store("AL", registers_["FLAGS"] < 0 ? 1 : 0); pc_++; return; }
if (op == "SETG") { store("AL", registers_["FLAGS"] > 0 ? 1 : 0); pc_++; return; }
if (op == "SETLE") { store("AL", registers_["FLAGS"] <= 0 ? 1 : 0); pc_++; return; }
if (op == "SETGE") { store("AL", registers_["FLAGS"] >= 0 ? 1 : 0); pc_++; return; }
// JMP: unconditional jump to label
if (op == "JMP") {
// Search memory for the label
for (int i = 0; i < (int)memory_.size(); i++) {
if (memory_[i].opcode == dest + ":") {
pc_ = i + 1; // Land on instruction after label
return;
}
}
pc_++; // Label not found (shouldn't happen)
return;
}
// JE: jump if equal (FLAGS == 0)
if (op == "JE") {
if (registers_["FLAGS"] == 0) {
for (int i = 0; i < (int)memory_.size(); i++) {
if (memory_[i].opcode == dest + ":") {
pc_ = i + 1;
return;
}
}
}
pc_++;
return;
}
// CALL print_val: special case to handle our print_val runtime stub
if (op == "CALL" && dest == "print_val") {
// EAX holds the value to print (set by MOV EAX, <val>)
// We also look back at the last MOV to find the original name
double val = eval("EAX");
std::cout << " >>> OUTPUT: " << val << "\n";
pc_++;
return;
}
// PRINT: print the value of dest (can be a variable, register, or string literal)
if (op == "PRINT") {
double val = eval(dest); // dest holds the operand for PRINT
// If dest is a string literal, print the string
if (!dest.empty() && dest[0] == '"') {
std::cout << " >>> OUTPUT: " << dest.substr(1, dest.size()-2) << "\n";
} else {
std::cout << " >>> OUTPUT: " << val << "\n";
}
pc_++;
return;
}
// RETURN: end of main function, stop execution
if (op == "RET" || op == "RETURN") {
running_ = false; // Simplified: return from main = exit
pc_++;
return;
}
// PUSH/POP/CDQ/INT/CALL: for simplicity, we treat these as no-ops in this simulation
if (op == "PUSH" || op == "POP" || op == "CDQ" ||
op == "INT" || op == "CALL") {
pc_++; // Simulate as no-op for our purposes
return;
}
// HALT: stop execution immediately
if (op == "HALT" || op == "INT") {
running_ = false;
return;
}
// UNKNOWN OPCODE: print a warning and skip
std::cout << " [LOADER] Warning: unknown opcode '" << op << "' at 0x"
<< std::hex << pc_ << std::dec << " - skipping\n";
pc_++;
}
// EXECUTE – run the fetch-decode-execute loop until program halts or step limit reached
void Loader::execute() {
std::cout << " [LOADER] Starting execution...\n\n";
int steps = 0;
const int MAX_STEPS = 100000; // Guard against infinite loops
while (running_ && steps < MAX_STEPS) {
step();
steps++;
}
if (steps >= MAX_STEPS) {
std::cout << " [LOADER] Execution halted: step limit reached.\n";
} else {
std::cout << "\n [LOADER] Execution complete after "
<< steps << " steps.\n";
}
}
// PRINT MEMORY MAP – show the first 20 instructions in virtual memory
void Loader::printMemoryMap() const {
std::cout << "\n Virtual Memory Map (first 20 entries):\n";
std::cout << " +----------+----------------------------------+\n";
std::cout << " | Address | Instruction |\n";
std::cout << " +----------+----------------------------------+\n";
int limit = std::min((int)memory_.size(), 20);
for (int i = 0; i < limit; i++) {
std::cout << " | 0x" << std::hex << std::setw(4) << std::setfill('0') << i
<< std::dec << std::setfill(' ')
<< " | " << std::setw(32) << std::left
<< memory_[i].toString().substr(0, 32) << " |\n";
}
if ((int)memory_.size() > 20)
std::cout << " | ... | (" << memory_.size()-20 << " more) |\n";
std::cout << " +----------+----------------------------------+\n\n";
}