-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasm.cpp
More file actions
484 lines (419 loc) · 12.3 KB
/
asm.cpp
File metadata and controls
484 lines (419 loc) · 12.3 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Krishkumar
// 2401CS83
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <cstdint>
#include <algorithm>
#include <iomanip>
using namespace std;
// Instruction format: 8-bit opcode, 24-bit signed operand
enum OperandType
{
NONE,
VALUE,
OFFSET
};
struct OpcodeEntry
{
int code;
OperandType type;
};
map<string, OpcodeEntry> opcodeTable = {
{"ldc", {0, VALUE}},
{"adc", {1, VALUE}},
{"ldl", {2, VALUE}}, // SP-relative offset — not PC-relative
{"stl", {3, VALUE}}, // SP-relative offset — not PC-relative
{"ldnl", {4, VALUE}}, // A-relative offset — not PC-relative
{"stnl", {5, VALUE}}, // A-relative offset — not PC-relative
{"add", {6, NONE}},
{"sub", {7, NONE}},
{"shl", {8, NONE}},
{"shr", {9, NONE}},
{"adj", {10, VALUE}},
{"a2sp", {11, NONE}},
{"sp2a", {12, NONE}},
{"call", {13, OFFSET}}, // PC-relative
{"return", {14, NONE}},
{"brz", {15, OFFSET}}, // PC-relative
{"brlz", {16, OFFSET}}, // PC-relative
{"br", {17, OFFSET}}, // PC-relative
{"HALT", {18, NONE}}};
struct ParsedLine
{
string label;
string mnemonic;
string operand;
string sourceLine;
int lineNumber;
};
map<string, int> symbolTable;
vector<ParsedLine> parsedLines;
vector<uint32_t> machineCode;
vector<string> errors;
vector<string> rawLines; // original source lines
vector<int> lineAddressMap; // PC for each parsedLine entry
ofstream logFile;
static void logOut(const string &msg)
{
cout << msg;
if (logFile.is_open())
logFile << msg;
}
static void logErr(const string &msg)
{
cerr << msg;
if (logFile.is_open())
logFile << msg;
}
// trim whitespace
static string trim(const string &s)
{
size_t start = s.find_first_not_of(" \t\r\n");
if (start == string::npos)
return "";
size_t end = s.find_last_not_of(" \t\r\n");
return s.substr(start, end - start + 1);
}
static bool isValidLabel(const string &name)
{
if (name.empty())
return false;
// Must start with letter or underscore
if (!isalpha((unsigned char)name[0]) && name[0] != '_')
return false;
for (size_t i = 1; i < name.size(); i++)
{
if (!isalnum((unsigned char)name[i]) && name[i] != '_')
return false;
}
return true;
}
static bool parseNumber(const string &s, int32_t &value)
{
if (s.empty())
return false;
try
{
size_t pos = 0;
if (s.size() > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
{
value = static_cast<int32_t>(stoul(s, &pos, 16));
}
else if (s[0] == '-' || s[0] == '+')
{
value = static_cast<int32_t>(stol(s, &pos, 10));
}
else
{
value = static_cast<int32_t>(stoul(s, &pos, 10));
}
return pos == s.size();
}
catch (...)
{
return false;
}
}
// 1. readFile()
bool readFile(const string &filename)
{
ifstream fin(filename);
if (!fin.is_open())
{
logErr("Error: cannot open file '" + filename + "'\n");
return false;
}
string line;
while (getline(fin, line))
{
rawLines.push_back(line);
}
fin.close();
return true;
}
// 2. parseLine()
ParsedLine parseLine(const string &raw, int lineNumber)
{
ParsedLine p;
p.sourceLine = raw;
p.lineNumber = lineNumber;
// Strip comment (everything from ';' onward)
string line = raw;
size_t commentPos = line.find(';');
if (commentPos != string::npos)
line = line.substr(0, commentPos);
line = trim(line);
if (line.empty())
return p;
// Tokenise by whitespace
istringstream iss(line);
vector<string> tokens;
string tok;
while (iss >> tok)
tokens.push_back(tok);
int idx = 0;
// Check for label (token ending with ':')
if (!tokens.empty() && tokens[0].back() == ':')
{
p.label = tokens[0].substr(0, tokens[0].size() - 1);
idx = 1;
}
// Mnemonic
if (idx < (int)tokens.size())
{
p.mnemonic = tokens[idx];
idx++;
}
// Operand (rest of tokens joined)
if (idx < (int)tokens.size())
{
p.operand = tokens[idx];
for (int i = idx + 1; i < (int)tokens.size(); i++)
p.operand += " " + tokens[i];
}
return p;
}
// 3. buildSymbolTable() — Pass 1
bool buildSymbolTable()
{
int pc = 0;
for (int i = 0; i < (int)rawLines.size(); i++)
{
ParsedLine p = parseLine(rawLines[i], i + 1);
if (!p.label.empty())
{
if (!isValidLabel(p.label))
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Invalid label name '" + p.label + "'");
}
else if (symbolTable.count(p.label))
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Duplicate label '" + p.label + "'");
}
else
{
if (p.mnemonic == "SET")
{
int32_t val;
if (parseNumber(p.operand, val))
{
symbolTable[p.label] = val;
}
else
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Invalid number '" + p.operand + "'");
}
}
else
{
symbolTable[p.label] = pc;
}
}
}
if (!p.mnemonic.empty() && p.mnemonic != "SET")
{
if (p.mnemonic != "data" && opcodeTable.find(p.mnemonic) == opcodeTable.end())
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Invalid mnemonic '" + p.mnemonic + "'");
}
else
{
pc++;
}
}
parsedLines.push_back(p);
}
return errors.empty();
}
// 4. secondPassGenerateCode() — Pass 2
bool secondPassGenerateCode()
{
int pc = 0;
for (auto &p : parsedLines)
{
if (p.mnemonic.empty() || p.mnemonic == "SET")
continue;
lineAddressMap.push_back(pc);
if (p.mnemonic == "data")
{
int32_t val = 0;
if (!p.operand.empty())
{
if (!parseNumber(p.operand, val))
{
if (symbolTable.count(p.operand))
{
val = symbolTable[p.operand];
}
else
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Undefined label or invalid number '" +
p.operand + "'");
}
}
}
machineCode.push_back(static_cast<uint32_t>(val));
pc++;
continue;
}
auto it = opcodeTable.find(p.mnemonic);
if (it == opcodeTable.end())
{
machineCode.push_back(0);
pc++;
continue;
}
int opcode = it->second.code;
OperandType opType = it->second.type;
int32_t operandVal = 0;
if (opType == NONE && !p.operand.empty())
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Unexpected operand for '" + p.mnemonic + "'");
}
if (opType != NONE)
{
if (p.operand.empty())
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Missing operand for '" + p.mnemonic + "'");
}
else if (p.operand.find(',') != string::npos)
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Malformed operand '" + p.operand + "'");
}
else if (!parseNumber(p.operand, operandVal))
{
if (symbolTable.count(p.operand))
{
operandVal = symbolTable[p.operand];
if (opType == OFFSET)
{
operandVal = operandVal - (pc + 1);
}
}
else if (isValidLabel(p.operand))
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Undefined label '" + p.operand + "'");
}
else
{
errors.push_back("Line " + to_string(p.lineNumber) +
": Invalid number '" + p.operand + "'");
}
}
}
uint32_t word = ((uint32_t)(opcode & 0xFF) << 24) |
((uint32_t)(operandVal) & 0x00FFFFFF);
machineCode.push_back(word);
pc++;
}
return errors.empty();
}
// 5. writeObjectFile()
bool writeObjectFile(const string &filename)
{
ofstream fout(filename, ios::binary);
if (!fout.is_open())
{
logErr("Error: cannot create object file '" + filename + "'\n");
return false;
}
for (uint32_t word : machineCode)
{
fout.write(reinterpret_cast<const char *>(&word), sizeof(uint32_t));
}
fout.close();
return true;
}
// 6. writeListingFile()
bool writeListingFile(const string &filename)
{
ofstream fout(filename);
if (!fout.is_open())
{
logErr("Error: cannot create listing file '" + filename + "'\n");
return false;
}
int codeIdx = 0;
for (auto &p : parsedLines)
{
if (p.mnemonic.empty() || p.mnemonic == "SET")
{
fout << " " << p.sourceLine << endl;
}
else
{
uint32_t word = machineCode[codeIdx];
int addr = lineAddressMap[codeIdx];
fout << hex << setw(8) << setfill('0') << addr << " "
<< hex << setw(8) << setfill('0') << word << " "
<< p.sourceLine << endl;
codeIdx++;
}
}
fout.close();
return true;
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
cerr << "Usage: asm <source.asm>" << endl;
return 1;
}
string srcFile = argv[1];
// Derive base name (strip extension)
string baseName = srcFile;
size_t dotPos = baseName.rfind('.');
if (dotPos != string::npos)
baseName = baseName.substr(0, dotPos);
// Open log file early so ALL output (errors included) is captured
string logFilename = baseName + ".log";
logFile.open(logFilename);
if (!logFile.is_open())
{
cerr << "Warning: cannot create log file '" << logFilename << "'" << endl;
}
// Log header
logOut("Assembler log for: " + srcFile + "\n");
logOut("\n");
if (!readFile(srcFile))
{
logFile.close();
return 1;
}
buildSymbolTable();
secondPassGenerateCode();
if (!errors.empty())
{
for (auto &e : errors)
logErr("ERROR: " + e + "\n");
ostringstream oss;
oss << errors.size() << " error(s) found. No output files produced.\n";
logErr(oss.str());
logFile.close();
return 1;
}
string objFile = baseName + ".obj";
string lstFile = baseName + ".lst";
writeObjectFile(objFile);
writeListingFile(lstFile);
logOut("Assembly successful.\n");
logOut("Object file : " + objFile + "\n");
logOut("Listing file: " + lstFile + "\n");
logOut("Log file : " + logFilename + "\n");
logFile.close();
return 0;
}