-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathassembler.cpp
756 lines (676 loc) · 21.4 KB
/
assembler.cpp
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
#include "assembler.h"
#include "emulator.h"
/*
* Constructor
*/
Assembler::Assembler(const char* data, int length) {
// Copying the program code into the buffer
assemblyCode=new char[length+1];
memcpy(assemblyCode,data,length);
assemblyCode[length]='\0';
assemblyCodeLength=length;
// Creating an empty label list along with addresses for each label
labelList=new char*[65536];
labelAddresses=new unsigned short[65536];
labelListLength=0;
// Initializing an empty array to hold the rawAssembly
rawAssembly=new char[262144];
rawAssembly[0]='\0';
}
/*
* Destructor
*/
Assembler::~Assembler() {
// Deleting all used memory
delete[] assemblyCode;
delete[] labelAddresses;
for(int i=0;i<labelListLength;i++)
delete[] labelList[i];
delete[] labelList;
delete[] rawAssembly;
}
/*
* Replaces all tabs with spaces in "assemblyCode"
*/
void Assembler::removeTabs(char *assemblyCode, int length) {
for(int i=0;i<length;i++)
if(assemblyCode[i]=='\t')
assemblyCode[i]=' ';
}
/*
* Removes all double spaces in "assemblyCode"
*/
void Assembler::removeSpaces(char *assemblyCode, int &length) {
// Create empty buffer memory for the returned string and copy the first element
char* buffer=new char[length+1];
int i,j=1;
buffer[0]=assemblyCode[0];
// Go through "assemblyCode" and copy all characters that are not
// preceeded by a space
for(i=1;i<length;i++) {
if(assemblyCode[i]==' ' && assemblyCode[i-1]==' ')
continue;
else
buffer[j++]=assemblyCode[i];
}
// Terminate the string
buffer[j]='\0';
// Copy the temporary buffer to "assemblyCode" and delete it from the heap
strcpy(assemblyCode,buffer);
delete[] buffer;
length=j;
}
/*
* Fixes all new characters to \n
*/
void Assembler::fixNewLineCharacters(char *assemblyCode, int &length) {
// Create empty buffer memory for the returned string
char* buffer=new char[length+1];
int i,j=0;
// Copy all characters except for \r
// Replace \r\n with \n and single \r with \n
for(i=0;i<length;i++) {
if(i<length-1 && assemblyCode[i]=='\r' && assemblyCode[i+1]=='\n')
buffer[j++]=assemblyCode[++i];
else if(assemblyCode[i]=='\r')
buffer[j++]='\n';
else
buffer[j++]=assemblyCode[i];
}
// Terminate the string
buffer[j]='\0';
// Copy the temporary buffer to "assemblyCode" and delete it from the heap
memcpy(assemblyCode,buffer,j+1);
delete[] buffer;
length=j;
}
/*
* Removes all comments
*/
void Assembler::removeComments(char *assemblyCode, int &length) {
// Create empty buffer memory for the returned string
char* buffer=new char[length+1];
int i,j=0;
// Copy everything except the characters between ';' and '\n'
for(i=0;i<length;i++) {
if(assemblyCode[i]==';') {
// Start from the i-th character and keep on until we reach a new line
// or the end of the "assemblyCode"
while(assemblyCode[i++]!='\n' && i<length);
if(i<length) buffer[j++]='\n';
// Go back one character since i will increase again in the for
i--;
}
else
buffer[j++]=assemblyCode[i];
}
// Terminate the string
buffer[j]='\0';
// Copy the temporary buffer to "assemblyCode" and delete it from the heap
memcpy(assemblyCode,buffer,j+1);
delete[] buffer;
length=j;
}
/*
* Removes all empty lines
*/
void Assembler::removeEmptyLines(char *assemblyCode, int &length, int *actualLine) {
// Create empty buffer memory for the returned string
// and keep track of what line every character belonged to
// (used for error messages)
char* buffer=new char[length+1];
int* oldLineNumbers=new int[length+1];
int i,j=0;
// Remove all lines that consist of just '\n' or ' ' and '\n'
for(i=0;i<length;i++) {
if(i>0 && assemblyCode[i]=='\n' && assemblyCode[i-1]=='\n')
continue;
else if(i>0 && i<length-1 && assemblyCode[i]==' ' && assemblyCode[i-1]=='\n' && assemblyCode[i+1]=='\n') {
i++;
continue;
}
else if(i==0 && i<length-1 && assemblyCode[i]=='\n' && assemblyCode[i+1]=='\n')
continue;
else {
buffer[j]=assemblyCode[i];
oldLineNumbers[j++]=actualLine[i];
}
}
// Remove if the end of the file is a new line followed by just a space character
// or if the end of the file is just a new line
if(buffer[j-1]=='\n' && buffer[j-2]==' ')
j-=2;
else if(buffer[j-1]=='\n')
j--;
// Terminate the string
buffer[j]='\0';
// Copy the temporary buffer to "assemblyCode",
// the corresponding line numbers to "actualLine"
// and delete them from the heap
memcpy(assemblyCode,buffer,j+1);
memcpy(actualLine,oldLineNumbers,sizeof(int)*j);
delete[] buffer;
delete[] oldLineNumbers;
length=j;
}
/*
* Returns an std::string containing the compiled assembly
*/
std::string Assembler::readAssembly() {
return std::string(rawAssembly);
}
/*
* Checks the formatting of an RRR instruction with 3 arguments
* Returns an error number, check printError for explanation
*/
int Assembler::checkRRR3(char *arg, int argl, char ®1, char ®2, char ®3) {
int result;
int comma1,comma2;
comma1=findNextCharacter(arg,argl,',',0);
if(comma1==-1) {
return 4;
}
comma2=findNextCharacter(arg,argl,',',comma1+1);
if(comma2==-1) {
return 4;
}
result=getRegister(arg,0,comma1,reg1);
if(result!=0) {
return result;
}
result=getRegister(arg,comma1+1,comma2,reg2);
if(result!=0) {
return result;
}
result=getRegister(arg,comma2+1,argl,reg3);
if(result!=0) {
return result;
}
return 0;
}
/*
* Checks the formatting of an RRR instruction with 2 arguments
* Returns an error number, check printError for explanation
*/
int Assembler::checkRRR2(char *arg, int argl, char ®1, char ®2) {
int result;
int comma;
comma=findNextCharacter(arg,argl,',',0);
if(comma==-1) {
return 4;
}
result=getRegister(arg,0,comma,reg1);
if(result!=0) {
return result;
}
result=getRegister(arg,comma+1,argl,reg2);
if(result!=0) {
return result;
}
return 0;
}
/*
* Checks the formatting of an RX instruction with 1 argument
* Returns an error number, check printError for explanation
*/
int Assembler::checkRX1(char *arg, int argl, char ®1, unsigned short &addr) {
int result;
result=getMemoryLocation(arg,0,argl,reg1,addr);
if(result!=0) {
return result;
}
return 0;
}
/*
* Checks the formatting of an RX instruction with 2 arguments
* Returns an error number, check printError for explanation
*/
int Assembler::checkRX2(char *arg, int argl, char ®1, char ®2, unsigned short &addr) {
int result;
int comma;
comma=findNextCharacter(arg,argl,',',0);
if(comma==-1) {
return 4;
}
result=getRegister(arg,0,comma,reg1);
if(result!=0) {
return result;
}
result=getMemoryLocation(arg,comma+1,argl,reg2,addr);
if(result!=0) {
return result;
}
return 0;
}
/*
* Converts an integer error to a meaningful string with an added line number
*/
void Assembler::printError(int result,int lineError,char* fp) {
if(result==1) sprintf(fp,"Unexpected argument - R expected on line %d!\n",lineError);
if(result==2) sprintf(fp,"Unexpected argument - register expected on line %d!\n",lineError);
if(result==3) sprintf(fp,"Unexpected argument - comma expected on line %d!\n",lineError);
if(result==4) sprintf(fp,"Unexpected/invalid argument - line %d!\n",lineError);
if(result==5) sprintf(fp,"Memory address not found - line %d!\n",lineError);
}
/*
* Translates an instruction and its arguments to a compiled hexadecimal representation
*/
bool Assembler::translateInstruction(char *instrName, char *instrArgs, int instrArgsLength, char *fp, int lineError) {
// getInstructionType returns the type of instruction where
// 1 = RRR instruction with 3 arguments (e.g. add R1,R2,R3)
// 2 = RRR instruction with 2 arguments (e.g. cmp R1,R2)
// 3 = RX instruction with 2 arguments (e.g. lea R1,label[R2])
// 4 = RX instruction with 1 argument (e.g. jump label[R1])
// 5 = data instruction
int t=getInstructionType(instrName);
int result;
if(t==1) {
char reg1,reg2,reg3;
result=checkRRR3(instrArgs,instrArgsLength,reg1,reg2,reg3);
if(result!=0) {
printError(result,lineError,fp);
return false;
}
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"%c%c%c%c",getRRR(instrName),reg1,reg2,reg3);
return true;
}
if(t==2) {
char reg1,reg2;
result=checkRRR2(instrArgs,instrArgsLength,reg1,reg2);
if(result!=0) {
printError(result,lineError,fp);
return false;
}
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"%c0%c%c",getRRR(instrName),reg1,reg2);
return true;
}
if(t==3) {
char reg1,reg2;
unsigned short addr;
result=checkRX2(instrArgs,instrArgsLength,reg1,reg2,addr);
if(result!=0) {
printError(result,lineError,fp);
return false;
}
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"f%c%c%c",reg1,reg2,getRX(instrName));
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"%04hx",addr);
return true;
}
if(t==4) {
char reg1;
unsigned short addr;
result=checkRX1(instrArgs,instrArgsLength,reg1,addr);
if(result!=0) {
printError(result,lineError,fp);
return false;
}
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"f%c%c%c",getJump(instrName),reg1,getRX(instrName));
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"%04hx",addr);
return true;
}
if(t==5) {
if(instrArgs[0]=='$') {
if(instrArgsLength!=5) {
sprintf(fp,"Invalid number of arguments supplied for data - line %d!\n",lineError);
return false;
}
else {
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"%c%c%c%c",instrArgs[1],instrArgs[2],instrArgs[3],instrArgs[4]);
}
}
else {
int ti=0;
if(instrArgs[0]=='-') ti++;
int num=0;
while(ti<instrArgsLength) {
if(instrArgs[ti]<'0' || instrArgs[ti]>'9') {
sprintf(fp,"Invalid character supplied for data - line %d!\n",lineError);
return false;
}
num=num*10+(instrArgs[ti++]-'0');
}
if(instrArgs[0]=='-') num=-num;
char temp[64];
sprintf(temp,"%04hx",(short)(num));
sprintf(fp+strlen(fp),"%04hx",lineError);
sprintf(fp+strlen(fp),"%c%c%c%c",temp[0],temp[1],temp[2],temp[3]);
}
return true;
}
return false;
}
/*
* Assembles the "assemblyCode" passed to the class
* and stores the result in "rawAssembly"
*/
void Assembler::assemble() {
int i,curLine=1;
int* lines=new int[assemblyCodeLength]; // Temporary array that keeps track of which line each character was on, used in showing errors
char* originalAssemblyCode = new char[assemblyCodeLength];
int originalAssemblyCodeLength = assemblyCodeLength;
memcpy(originalAssemblyCode,assemblyCode,originalAssemblyCodeLength*sizeof(char));
// Converts the human-readable assembly to a format the machine understands better
removeTabs(assemblyCode,assemblyCodeLength); // Replaces tabs with spaces
removeSpaces(assemblyCode,assemblyCodeLength); // Removes all double spaces
fixNewLineCharacters(assemblyCode,assemblyCodeLength); // Replaces \r\n and \r with \n
removeComments(assemblyCode,assemblyCodeLength); // Removes all comments
// Fill the line information array
for(i=0;i<assemblyCodeLength;i++) {
lines[i]=curLine;
if(assemblyCode[i]=='\n')
curLine++;
}
removeEmptyLines(assemblyCode,assemblyCodeLength,lines); // Removes empty lines
i=0;
int memoryAddress=0;
int error=0;
// Fetches all label names and makes sure instructions are valid
// Works line by line
while(i<assemblyCodeLength) {
char labelName[1024];
int labelLength=0;
char instrName[1024];
int instrLength=0;
int state=0;
// Parses label name
while(1) {
if(assemblyCode[i]==' ')
break;
if(assemblyCode[i]=='\n' || i==assemblyCodeLength) {
state=1;
break;
}
labelName[labelLength++]=assemblyCode[i];
i++;
}
labelName[labelLength]='\0';
// Error checking
if(labelLength!=0) {
labelList[labelListLength]=new char[1024];
labelAddresses[labelListLength]=memoryAddress;
strcpy(labelList[labelListLength],labelName);
labelListLength++;
}
// In case of a line ending, the instruction must be on the next line
if(state==1) {
i++;
continue;
}
// Skips the space after the label
i++;
// Parses instruction name
while(1) {
if(assemblyCode[i]==' ')
break;
if(assemblyCode[i]=='\n' || i==assemblyCodeLength) {
state=1;
break;
}
instrName[instrLength++]=tolower(assemblyCode[i]);
i++;
}
instrName[instrLength]='\0';
// In case of a line ending or end of file, we let the next while-loop handle the error
if(state==1) {
i++;
continue;
}
// Error checking
int instrType=getInstructionType(instrName);
if(instrType==-1) {
if(i>=assemblyCodeLength) {
i=assemblyCodeLength-1;
}
sprintf(rawAssembly,"Invalid instruction %s on line %d\n",instrName,lines[i]);
error=1;
break;
}
else if(instrType==1 || instrType==2 || instrType==5) {
memoryAddress++;
}
else {
memoryAddress+=2;
}
// Skipping the rest of the line
while(assemblyCode[i]!='\n' && i<assemblyCodeLength) i++;
// Skip the \n
i++;
}
// Error checking
if(error) {
delete[] originalAssemblyCode;
delete[] lines;
return;
}
sprintf(rawAssembly,"ASM03");
sprintf(rawAssembly+strlen(rawAssembly),"%d-",originalAssemblyCodeLength);
for(i=0;i<originalAssemblyCodeLength;i++) {
sprintf(rawAssembly+strlen(rawAssembly),"%c",originalAssemblyCode[i]);
}
// Back to the first character
i=0;
// Convert assembly to machine code
while(i<assemblyCodeLength) {
char instrName[1024];
int instrLength=0;
char instrArgs[1024];
int instrArgsLength=0;
int state=0;
// Parses label name
while(1) {
if(assemblyCode[i]==' ')
break;
if(assemblyCode[i]=='\n' || i==assemblyCodeLength) {
state=1;
break;
}
i++;
}
// In case of a line ending, the instruction is on the next row
if(state==1) {
i++;
continue;
}
// Skip the space after the label name
i++;
// Parses instruction name
while(1) {
if(assemblyCode[i]==' ')
break;
if(assemblyCode[i]=='\n' || i==assemblyCodeLength) {
state=1;
break;
}
instrName[instrLength++]=tolower(assemblyCode[i]);
i++;
}
instrName[instrLength]='\0';
// In case of an empty instruction, just skip the line (very weird corner case)
if(state==1 && instrLength==0) {
i++;
continue;
}
// In case of a non-empty instruction with no arguments
if(state==1) {
if(i>=assemblyCodeLength) {
i=assemblyCodeLength-1;
}
sprintf(rawAssembly,"Arguments expected for instruction %s on line %d\n",instrName,lines[i]);
error=1;
break;
}
// Error checking
int instrType=getInstructionType(instrName);
if(instrType==-1) {
if(i>=assemblyCodeLength) {
i=assemblyCodeLength-1;
}
sprintf(rawAssembly,"Invalid instruction %s on line %d\n",instrName,lines[i]);
error=1;
break;
}
// Skip the space after the instruction name
i++;
// Parses instruction arguments
while(1) {
if(assemblyCode[i]==' ')
break;
if(assemblyCode[i]=='\n' || i==assemblyCodeLength) {
state=1;
break;
}
instrArgs[instrArgsLength++]=assemblyCode[i];
i++;
}
instrArgs[instrArgsLength]='\0';
// Error checking
if(state==1 && instrArgsLength==0) {
if(i>=assemblyCodeLength) {
i=assemblyCodeLength-1;
}
sprintf(rawAssembly,"Arguments expected for instruction %s on line %d\n",instrName,lines[i]);
error=1;
break;
}
// Tries to translate the instruction to machine code
if(!translateInstruction(instrName,instrArgs,instrArgsLength,rawAssembly,lines[i])) {
error=1;
break;
}
// Skips the rest of the line (corner cases again)
while(assemblyCode[i]!='\n' && i<assemblyCodeLength) i++;
// Skips the new line character
i++;
}
// Memory management
delete[] originalAssemblyCode;
delete[] lines;
}
/*
* Finds the first occurence of "character" between "pos" and "argl" in "arg"
*/
int Assembler::findNextCharacter(char *arg, int argl, char character, int pos=0) {
while(pos<argl) {
if(arg[pos++]==character) {
return pos-1;
}
}
return -1;
}
/*
* Converts a string representation of a register (Rxx) to a hexadecimal number
* Returns 0 on success and non-zero on failure, check printError for more details
*/
int Assembler::getRegister(char *arg, int start, int end, char& reg) {
int length=end-start;
if(length<2 || length>3) {
return 4;
}
if(arg[start]!='R') {
return 1;
}
if(isdigit(arg[start+1])) {
if(length==3 && isdigit(arg[start+2])) {
int decimal=(arg[start+1]-'0')*10+(arg[start+2]-'0');
if(decimal<0 || decimal>15) {
return 4;
}
char temp[10];
sprintf(temp,"%x",decimal);
reg=temp[0];
}
else if(length==2) {
reg=arg[start+1];
}
else {
return 2;
}
}
else {
return 2;
}
return 0;
}
/*
* Converts a string representation of a memory location (label[Rxx]) to a hexadecimal number and an address location
* Returns 0 on success and non-zero on failure, check printError for more details
*/
int Assembler::getMemoryLocation(char *arg, int start, int end, char ®, unsigned short &addr) {
if(end-start<5) { // a[R0]
return 4;
}
int openbracket=findNextCharacter(arg,end,'[',start);
if(openbracket==-1) {
return 4;
}
int closebracket=findNextCharacter(arg,end,']',openbracket+1);
if(closebracket==-1) {
return 4;
}
char lookFor[1024];
int lookForLength=0;
for(int i=start;i<openbracket;i++) {
lookFor[lookForLength++]=arg[i];
}
lookFor[lookForLength]='\0';
int result;
if((result=getRegister(arg,openbracket+1,closebracket,reg))!=0) {
return result;
}
if(lookForLength==0) {
return 4;
}
if(isdigit(lookFor[0])) {
int returnNumber=0;
for(int i=0;i<lookForLength;i++) {
if(!isdigit(lookFor[i])) {
return 4;
}
returnNumber=returnNumber*10+(lookFor[i]-'0');
}
addr=returnNumber;
}
else if(lookFor[0]=='$') {
if(lookForLength!=5) {
return 4;
}
int returnNumber=0;
for(int i=1;i<lookForLength;i++) {
if(!(isdigit(lookFor[i]) || (lookFor[i]>='a' && lookFor[i]<='f'))) {
return 4;
}
returnNumber=returnNumber*16+Emulator::hex2dec(lookFor[i]);
}
addr=returnNumber;
}
else if(lookFor[0]=='-') {
int returnNumber=0;
for(int i=1;i<lookForLength;i++) {
if(!isdigit(lookFor[i])) {
return 4;
}
returnNumber=returnNumber*10+(lookFor[i]-'0');
}
addr=-returnNumber;
}
else {
addr=0xffff;
for(int i=0;i<labelListLength;i++) {
if(strcmp(lookFor,labelList[i])==0) {
addr=labelAddresses[i];
break;
}
}
if(addr==0xffff) {
return 5;
}
}
return 0;
}