forked from TheThirdOne/rars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Assembler.java
1326 lines (1245 loc) · 69.4 KB
/
Assembler.java
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rars.assembler;
import rars.*;
import rars.riscv.hardware.AddressErrorException;
import rars.riscv.hardware.Memory;
import rars.riscv.BasicInstruction;
import rars.riscv.ExtendedInstruction;
import rars.riscv.Instruction;
import rars.util.Binary;
import rars.util.SystemIO;
import java.util.ArrayList;
import java.util.Collections;
import java.io.UnsupportedEncodingException;
/*
Copyright (c) 2003-2012, Pete Sanderson and Kenneth Vollmar
Developed by Pete Sanderson (psanderson@otterbein.edu)
and Kenneth Vollmar (kenvollmar@missouristate.edu)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(MIT license, http://www.opensource.org/licenses/mit-license.html)
*/
/**
* An Assembler is capable of assembling a RISCV program. It has only one public
* method, <tt>assemble()</tt>, which implements a two-pass assembler. It
* translates RISCV source code into binary machine code.
*
* @author Pete Sanderson
* @version August 2003
**/
public class Assembler {
private ErrorList errors;
private boolean inDataSegment; // status maintained by parser
private boolean inMacroSegment; // status maintained by parser, true if in
// macro definition segment
private int externAddress;
private boolean autoAlign;
private Directives dataDirective;
private RISCVprogram fileCurrentlyBeingAssembled;
private TokenList globalDeclarationList;
private AddressSpace textAddress;
private AddressSpace dataAddress;
private DataSegmentForwardReferences currentFileDataSegmentForwardReferences,
accumulatedDataSegmentForwardReferences;
/**
* Get list of assembler errors and warnings
*
* @return ErrorList of any assembler errors and warnings.
*/
public ErrorList getErrorList() {
return errors;
}
/**
* Parse and generate machine code for the given program. All source
* files must have already been tokenized.
*
* @param tokenizedProgramFiles An ArrayList of RISCVprogram objects, each produced from a
* different source code file, representing the program source.
* @param extendedAssemblerEnabled A boolean value that if true permits use of extended (pseudo)
* instructions in the source code. If false, these are flagged
* as errors.
* @param warningsAreErrors A boolean value - true means assembler warnings will be
* considered errors and terminate the assemble; false means the
* assembler will produce warning message but otherwise ignore
* warnings.
* @return An ArrayList representing the assembled program. Each member of
* the list is a ProgramStatement object containing the source,
* intermediate, and machine binary representations of a program
* statement. Returns null if incoming array list is null or empty.
* @see ProgramStatement
**/
public ArrayList<ProgramStatement> assemble(ArrayList<RISCVprogram> tokenizedProgramFiles, boolean extendedAssemblerEnabled,
boolean warningsAreErrors) throws AssemblyException {
if (tokenizedProgramFiles == null || tokenizedProgramFiles.size() == 0)
return null;
textAddress = new AddressSpace(Memory.textBaseAddress);
dataAddress = new AddressSpace(Memory.dataBaseAddress);
externAddress = Memory.externBaseAddress;
currentFileDataSegmentForwardReferences = new DataSegmentForwardReferences();
accumulatedDataSegmentForwardReferences = new DataSegmentForwardReferences();
Globals.symbolTable.clear();
Globals.memory.clear();
ArrayList<ProgramStatement> machineList = new ArrayList<>();
this.errors = new ErrorList();
if (Globals.debug)
System.out.println("Assembler first pass begins:");
// PROCESS THE FIRST ASSEMBLY PASS FOR ALL SOURCE FILES BEFORE PROCEEDING
// TO SECOND PASS. THIS ASSURES ALL SYMBOL TABLES ARE CORRECTLY BUILT.
// THERE IS ONE GLOBAL SYMBOL TABLE (for identifiers declared .globl) PLUS
// ONE LOCAL SYMBOL TABLE FOR EACH SOURCE FILE.
for (RISCVprogram program : tokenizedProgramFiles) {
if (errors.errorLimitExceeded())
break;
this.fileCurrentlyBeingAssembled = program;
// List of labels declared ".globl". new list for each file assembled
this.globalDeclarationList = new TokenList();
// Parser begins by default in text segment until directed otherwise.
this.inDataSegment = false;
// Macro segment will be started by .macro directive
this.inMacroSegment = false;
// Default is to align data from directives on appropriate boundary (word, half, byte)
// This can be turned off for remainder of current data segment with ".align 0"
this.autoAlign = true;
// Default data directive is .word for 4 byte data items
this.dataDirective = Directives.WORD;
// Clear out (initialize) symbol table related structures.
fileCurrentlyBeingAssembled.getLocalSymbolTable().clear();
currentFileDataSegmentForwardReferences.clear();
// sourceList is an ArrayList of String objects, one per source line.
// tokenList is an ArrayList of TokenList objects, one per source line;
// each ArrayList in tokenList consists of Token objects.
ArrayList<SourceLine> sourceLineList = fileCurrentlyBeingAssembled.getSourceLineList();
ArrayList<TokenList> tokenList = fileCurrentlyBeingAssembled.getTokenList();
ArrayList<ProgramStatement> parsedList = fileCurrentlyBeingAssembled.createParsedList();
// each file keeps its own macro definitions
MacroPool macroPool = fileCurrentlyBeingAssembled.createMacroPool();
// FIRST PASS OF ASSEMBLER VERIFIES SYNTAX, GENERATES SYMBOL TABLE,
// INITIALIZES DATA SEGMENT
ArrayList<ProgramStatement> statements;
for (int i = 0; i < tokenList.size(); i++) {
if (errors.errorLimitExceeded())
break;
for (Token t : tokenList.get(i)) {
// record this token's original source program and line #. Differs from final, if .include used
t.setOriginal(sourceLineList.get(i).getRISCVprogram(), sourceLineList.get(i).getLineNumber());
}
statements = this.parseLine(tokenList.get(i),
sourceLineList.get(i).getSource(),
sourceLineList.get(i).getLineNumber(),
extendedAssemblerEnabled);
if (statements != null) {
parsedList.addAll(statements);
}
}
if (inMacroSegment) {
errors.add(new ErrorMessage(fileCurrentlyBeingAssembled,
fileCurrentlyBeingAssembled.getLocalMacroPool().getCurrent().getFromLine(),
0, "Macro started but not ended (no .end_macro directive)"));
}
// move ".globl" symbols from local symtab to global
this.transferGlobals();
// Attempt to resolve forward label references that were discovered in operand fields
// of data segment directives in current file. Those that are not resolved after this
// call are either references to global labels not seen yet, or are undefined.
// Cannot determine which until all files are parsed, so copy unresolved entries
// into accumulated list and clear out this one for re-use with the next source file.
currentFileDataSegmentForwardReferences.resolve(fileCurrentlyBeingAssembled
.getLocalSymbolTable());
accumulatedDataSegmentForwardReferences.add(currentFileDataSegmentForwardReferences);
currentFileDataSegmentForwardReferences.clear();
} // end of first-pass loop for each RISCVprogram
// Have processed all source files. Attempt to resolve any remaining forward label
// references from global symbol table. Those that remain unresolved are undefined
// and require error message.
accumulatedDataSegmentForwardReferences.resolve(Globals.symbolTable);
accumulatedDataSegmentForwardReferences.generateErrorMessages(errors);
// Throw collection of errors accumulated through the first pass.
if (errors.errorsOccurred()) {
throw new AssemblyException(errors);
}
if (Globals.debug)
System.out.println("Assembler second pass begins");
// SECOND PASS OF ASSEMBLER GENERATES BASIC ASSEMBLER THEN MACHINE CODE.
// Generates basic assembler statements...
for (RISCVprogram program : tokenizedProgramFiles) {
if (errors.errorLimitExceeded())
break;
this.fileCurrentlyBeingAssembled = program;
ArrayList<ProgramStatement> parsedList = fileCurrentlyBeingAssembled.getParsedList();
for (ProgramStatement statement : parsedList) {
statement.buildBasicStatementFromBasicInstruction(errors);
if (errors.errorsOccurred()) {
throw new AssemblyException(errors);
}
if (statement.getInstruction() instanceof BasicInstruction) {
machineList.add(statement);
} else {
// It is a pseudo-instruction:
// 1. Fetch its basic instruction template list
// 2. For each template in the list,
// 2a. substitute operands from source statement
// 2b. tokenize the statement generated by 2a.
// 2d. call parseLine() to generate basic instrction
// 2e. add returned programStatement to the list
// The templates, and the instructions generated by filling
// in the templates, are specified
// in basic format (e.g. mnemonic register reference zero
// already translated to x0).
// So the values substituted into the templates need to be
// in this format. Since those
// values come from the original source statement, they need
// to be translated before
// substituting. The next method call will perform this
// translation on the original
// source statement. Despite the fact that the original
// statement is a pseudo
// instruction, this method performs the necessary
// translation correctly.
// TODO: consider making this recursive
ExtendedInstruction inst = (ExtendedInstruction) statement.getInstruction();
String basicAssembly = statement.getBasicAssemblyStatement();
int sourceLine = statement.getSourceLine();
TokenList theTokenList = new Tokenizer().tokenizeLine(sourceLine,
basicAssembly, errors, false);
// ////////////////////////////////////////////////////////////////////////////
// If we are using compact memory config and there is a compact expansion, use it
ArrayList<String> templateList;
templateList = inst.getBasicIntructionTemplateList();
// subsequent ProgramStatement constructor needs the correct text segment address.
textAddress.set(statement.getAddress());
// Will generate one basic instruction for each template in the list.
int PC = textAddress.get(); // Save the starting PC so that it can be used for PC relative stuff
for (int instrNumber = 0; instrNumber < templateList.size(); instrNumber++) {
String instruction = ExtendedInstruction.makeTemplateSubstitutions(
this.fileCurrentlyBeingAssembled,
templateList.get(instrNumber), theTokenList, PC);
// All substitutions have been made so we have generated
// a valid basic instruction!
if (Globals.debug)
System.out.println("PSEUDO generated: " + instruction);
// For generated instruction: tokenize, build program
// statement, add to list.
TokenList newTokenList = new Tokenizer().tokenizeLine(sourceLine,
instruction, errors, false);
ArrayList<Instruction> instrMatches = this.matchInstruction(newTokenList.get(0));
Instruction instr = OperandFormat.bestOperandMatch(newTokenList,
instrMatches);
// Only first generated instruction is linked to original source
ProgramStatement ps = new ProgramStatement(
this.fileCurrentlyBeingAssembled,
(instrNumber == 0) ? statement.getSource() : "", newTokenList,
newTokenList, instr, textAddress.get(), statement.getSourceLine());
textAddress.increment(Instruction.INSTRUCTION_LENGTH);
ps.buildBasicStatementFromBasicInstruction(errors);
machineList.add(ps);
} // end of FOR loop, repeated for each template in list.
} // end of ELSE part for extended instruction.
} // end of assembler second pass.
}
if (Globals.debug)
System.out.println("Code generation begins");
///////////// THIRD MAJOR STEP IS PRODUCE MACHINE CODE FROM ASSEMBLY //////////
// Generates machine code statements from the list of basic assembler statements
// and writes the statement to memory.
for (ProgramStatement statement : machineList) {
if (errors.errorLimitExceeded())
break;
statement.buildMachineStatementFromBasicStatement(errors);
if (Globals.debug)
System.out.println(statement);
try {
Globals.memory.setStatement(statement.getAddress(), statement);
} catch (AddressErrorException e) {
Token t = statement.getOriginalTokenList().get(0);
errors.add(new ErrorMessage(t.getSourceProgram(), t.getSourceLine(), t
.getStartPos(), "Invalid address for text segment: " + e.getAddress()));
}
}
// Aug. 24, 2005 Ken Vollmar
// Ensure that I/O "file descriptors" are initialized for a new program run
SystemIO.resetFiles();
// DPS 6 Dec 2006:
// We will now sort the ArrayList of ProgramStatements by getAddress() value.
// This is for display purposes, since they have already been stored to Memory.
// Use of .ktext and .text with address operands has two implications:
// (1) the addresses may not be ordered at this point. Requires unsigned int
// sort because kernel addresses are negative. See special Comparator.
// (2) It is possible for two instructions to be placed at the same address.
// Such occurances will be flagged as errors.
// Yes, I would not have to sort here if I used SortedSet rather than ArrayList
// but in case of duplicate I like having both statements handy for error message.
Collections.sort(machineList);
catchDuplicateAddresses(machineList, errors);
if (errors.errorsOccurred() || errors.warningsOccurred() && warningsAreErrors) {
throw new AssemblyException(errors);
}
return machineList;
} // assemble()
// //////////////////////////////////////////////////////////////////////
// Will check for duplicate text addresses, which can happen inadvertantly when using
// operand on .text directive. Will generate error message for each one that occurs.
private void catchDuplicateAddresses(ArrayList<ProgramStatement> instructions, ErrorList errors) {
for (int i = 0; i < instructions.size() - 1; i++) {
ProgramStatement ps1 = instructions.get(i);
ProgramStatement ps2 = instructions.get(i + 1);
if (ps1.getAddress() == ps2.getAddress()) {
errors.add(new ErrorMessage(ps2.getSourceProgram(), ps2.getSourceLine(), 0,
"Duplicate text segment address: "
+ rars.venus.NumberDisplayBaseChooser.formatUnsignedInteger(ps2
.getAddress(), (Globals.getSettings()
.getBooleanSetting(Settings.Bool.DISPLAY_ADDRESSES_IN_HEX)) ? 16 : 10)
+ " already occupied by " + ps1.getSourceFile() + " line "
+ ps1.getSourceLine() + " (caused by use of "
+ ((Memory.inTextSegment(ps2.getAddress())) ? ".text" : ".ktext")
+ " operand)"));
}
}
}
/**
* This method parses one line of RISCV source code. It works with the list
* of tokens, but original source is also provided. It also carries out
* directives, which includes initializing the data segment. This method is
* invoked in the assembler first pass.
*
* @param tokenList
* @param source
* @param sourceLineNumber
* @param extendedAssemblerEnabled
* @return ArrayList of ProgramStatements because parsing a macro expansion
* request will return a list of ProgramStatements expanded
*/
private ArrayList<ProgramStatement> parseLine(TokenList tokenList, String source,
int sourceLineNumber, boolean extendedAssemblerEnabled) {
ArrayList<ProgramStatement> ret = new ArrayList<>();
ProgramStatement programStatement;
TokenList tokens = this.stripComment(tokenList);
// Labels should not be processed in macro definition segment.
MacroPool macroPool = fileCurrentlyBeingAssembled.getLocalMacroPool();
if (inMacroSegment) {
detectLabels(tokens, macroPool.getCurrent());
} else {
stripLabels(tokens);
}
if (tokens.isEmpty())
return null;
// Grab first (operator) token...
Token token = tokens.get(0);
TokenTypes tokenType = token.getType();
// Let's handle the directives here...
if (tokenType == TokenTypes.DIRECTIVE) {
this.executeDirective(tokens);
return null;
}
// don't parse if in macro segment
if (inMacroSegment)
return null;
// SPIM-style macro calling:
TokenList parenFreeTokens = tokens;
if (tokens.size() > 2 && tokens.get(1).getType() == TokenTypes.LEFT_PAREN
&& tokens.get(tokens.size() - 1).getType() == TokenTypes.RIGHT_PAREN) {
parenFreeTokens = (TokenList) tokens.clone();
parenFreeTokens.remove(tokens.size() - 1);
parenFreeTokens.remove(1);
}
Macro macro = macroPool.getMatchingMacro(parenFreeTokens, sourceLineNumber);//parenFreeTokens.get(0).getSourceLine());
// expand macro if this line is a macro expansion call
if (macro != null) {
tokens = parenFreeTokens;
// get unique id for this expansion
int counter = macroPool.getNextCounter();
if (macroPool.pushOnCallStack(token)) {
errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, tokens.get(0)
.getSourceLine(), 0, "Detected a macro expansion loop (recursive reference). "));
} else {
// for (int i = macro.getFromLine() + 1; i < macro.getToLine(); i++) {
// String substituted = macro.getSubstitutedLine(i, tokens, counter, errors);
// TokenList tokenList2 = fileCurrentlyBeingAssembled.getTokenizer().tokenizeLine(
// i, substituted, errors);
// // If token list getProcessedLine() is not empty, then .eqv was performed and it contains the modified source.
// // Put it into the line to be parsed, so it will be displayed properly in text segment display. DPS 23 Jan 2013
// if (tokenList2.getProcessedLine().length() > 0)
// substituted = tokenList2.getProcessedLine();
// // recursively parse lines of expanded macro
// ArrayList<ProgramStatement> statements = parseLine(tokenList2, "<" + (i-macro.getFromLine()+macro.getOriginalFromLine()) + "> "
// + substituted.trim(), sourceLineNumber, extendedAssemblerEnabled);
// if (statements != null)
// ret.addAll(statements);
// }
for (int i = macro.getFromLine() + 1; i < macro.getToLine(); i++) {
String substituted = macro.getSubstitutedLine(i, tokens, counter, errors);
TokenList tokenList2 = fileCurrentlyBeingAssembled.getTokenizer().tokenizeLine(
i, substituted, errors);
// If token list getProcessedLine() is not empty, then .eqv was performed and it contains the modified source.
// Put it into the line to be parsed, so it will be displayed properly in text segment display. DPS 23 Jan 2013
if (tokenList2.getProcessedLine().length() > 0)
substituted = tokenList2.getProcessedLine();
// recursively parse lines of expanded macro
ArrayList<ProgramStatement> statements = parseLine(tokenList2, "<" + (i - macro.getFromLine() + macro.getOriginalFromLine()) + "> "
+ substituted.trim(), sourceLineNumber, extendedAssemblerEnabled);
if (statements != null)
ret.addAll(statements);
}
macroPool.popFromCallStack();
}
return ret;
}
// TODO: check what gcc and clang generated assembly looks like currently
// DPS 14-July-2008
// Yet Another Hack: detect unrecognized directive. MARS recognizes the same directives
// as SPIM but other MIPS assemblers recognize additional directives. Compilers such
// as MIPS-directed GCC generate assembly code containing these directives. We'd like
// the opportunity to ignore them and continue. Tokenizer would categorize an unrecognized
// directive as an TokenTypes.IDENTIFIER because it would not be matched as a directive and
// MIPS labels can start with '.' NOTE: this can also be handled by including the
// ignored directive in the Directives.java list. There is already a mechanism in place
// for generating a warning there. But I cannot anticipate the names of all directives
// so this will catch anything, including a misspelling of a valid directive (which is
// a nice thing to do).
if (tokenType == TokenTypes.IDENTIFIER && token.getValue().charAt(0) == '.') {
errors.add(new ErrorMessage(ErrorMessage.WARNING, token.getSourceProgram(), token
.getSourceLine(), token.getStartPos(), "RARS does not recognize the "
+ token.getValue() + " directive. Ignored."));
return null;
}
// The directives with lists (.byte, .double, .float, .half, .word, .ascii, .asciiz)
// should be able to extend the list over several lines. Since this method assembles
// only one source line, state information must be stored from one invocation to
// the next, to sense the context of this continuation line. That state information
// is contained in this.dataDirective (the current data directive).
//
if (this.inDataSegment && // 30-Dec-09 DPS Added data segment guard...
(tokenType == TokenTypes.PLUS
|| // because invalid instructions were being caught...
tokenType == TokenTypes.MINUS
|| // here and reported as a directive in text segment!
tokenType == TokenTypes.QUOTED_STRING || tokenType == TokenTypes.IDENTIFIER
|| TokenTypes.isIntegerTokenType(tokenType) || TokenTypes
.isFloatingTokenType(tokenType))) {
this.executeDirectiveContinuation(tokens);
return null;
}
// If we are in the text segment, the variable "token" must now refer to
// an OPERATOR
// token. If not, it is either a syntax error or the specified operator
// is not
// yet implemented.
if (!this.inDataSegment) {
ArrayList<Instruction> instrMatches = this.matchInstruction(token);
if (instrMatches == null)
return ret;
// OK, we've got an operator match, let's check the operands.
Instruction inst = OperandFormat.bestOperandMatch(tokens, instrMatches);
// Here's the place to flag use of extended (pseudo) instructions
// when setting disabled.
if (inst instanceof ExtendedInstruction && !extendedAssemblerEnabled) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(),
"Extended (pseudo) instruction or format not permitted. See Settings."));
}
if (OperandFormat.tokenOperandMatch(tokens, inst, errors)) {
programStatement = new ProgramStatement(this.fileCurrentlyBeingAssembled, source,
tokenList, tokens, inst, textAddress.get(), sourceLineNumber);
// instruction length is 4 for all basic instruction, varies for extended instruction
// Modified to permit use of compact expansion if address fits
// in 15 bits. DPS 4-Aug-2009
int instLength = inst.getInstructionLength();
textAddress.increment(instLength);
ret.add(programStatement);
return ret;
}
}
return null;
} // parseLine()
private void detectLabels(TokenList tokens, Macro current) {
if (tokenListBeginsWithLabel(tokens))
current.addLabel(tokens.get(0).getValue());
}
// //////////////////////////////////////////////////////////////////////////////////
// Pre-process the token list for a statement by stripping off any comment.
// NOTE: the ArrayList parameter is not modified; a new one is cloned and
// returned.
private TokenList stripComment(TokenList tokenList) {
if (tokenList.isEmpty())
return tokenList;
TokenList tokens = (TokenList) tokenList.clone();
// If there is a comment, strip it off.
int last = tokens.size() - 1;
if (tokens.get(last).getType() == TokenTypes.COMMENT) {
tokens.remove(last);
}
return tokens;
} // stripComment()
/**
* Pre-process the token list for a statement by stripping off any label, if
* either are present. Any label definition will be recorded in the symbol
* table. NOTE: the ArrayList parameter will be modified.
*/
private void stripLabels(TokenList tokens) {
// If there is a label, handle it here and strip it off.
boolean thereWasLabel = this.parseAndRecordLabel(tokens);
if (thereWasLabel) {
tokens.remove(0); // Remove the IDENTIFIER.
tokens.remove(0); // Remove the COLON, shifted to 0 by previous remove
}
}
// //////////////////////////////////////////////////////////////////////////////////
// Parse and record label, if there is one. Note the identifier and its colon are
// two separate tokens, since they may be separated by spaces in source code.
private boolean parseAndRecordLabel(TokenList tokens) {
if (tokens.size() < 2) {
return false;
} else {
Token token = tokens.get(0);
if (tokenListBeginsWithLabel(tokens)) {
if (token.getType() == TokenTypes.OPERATOR) {
// an instruction name was used as label (e.g. lw:), so change its token type
token.setType(TokenTypes.IDENTIFIER);
}
fileCurrentlyBeingAssembled.getLocalSymbolTable().addSymbol(token,
(this.inDataSegment) ? dataAddress.get() : textAddress.get(),
this.inDataSegment, this.errors);
return true;
} else {
return false;
}
}
} // parseLabel()
private boolean tokenListBeginsWithLabel(TokenList tokens) {
// 2-July-2010. DPS. Remove prohibition of operator names as labels
if (tokens.size() < 2)
return false;
return (tokens.get(0).getType() == TokenTypes.IDENTIFIER || tokens.get(0).getType() == TokenTypes.OPERATOR)
&& tokens.get(1).getType() == TokenTypes.COLON;
}
// /////////////////////////////////////////////////////////////////////////////
// This source code line is a directive, not a instruction. Let's carry it out.
private void executeDirective(TokenList tokens) {
Token token = tokens.get(0);
Directives direct = Directives.matchDirective(token.getValue());
if (Globals.debug)
System.out.println("line " + token.getSourceLine() + " is directive " + direct);
if (direct == null) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(), token
.getStartPos(), "\"" + token.getValue()
+ "\" directive is invalid or not implemented in RARS"));
return;
} else if (direct == Directives.EQV) { /* EQV added by DPS 11 July 2012 */
// Do nothing. This was vetted and processed during tokenizing.
} else if (direct == Directives.MACRO) {
if (tokens.size() < 2) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" directive requires at least one argument."));
return;
}
if (tokens.get(1).getType() != TokenTypes.IDENTIFIER) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
tokens.get(1).getStartPos(), "Invalid Macro name \""
+ tokens.get(1).getValue() + "\""));
return;
}
if (inMacroSegment) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "Nested macros are not allowed"));
return;
}
inMacroSegment = true;
MacroPool pool = fileCurrentlyBeingAssembled.getLocalMacroPool();
pool.beginMacro(tokens.get(1));
for (int i = 2; i < tokens.size(); i++) {
Token arg = tokens.get(i);
if (arg.getType() == TokenTypes.RIGHT_PAREN
|| arg.getType() == TokenTypes.LEFT_PAREN)
continue;
if (!Macro.tokenIsMacroParameter(arg.getValue(), true)) {
errors.add(new ErrorMessage(arg.getSourceProgram(), arg.getSourceLine(),
arg.getStartPos(), "Invalid macro argument '" + arg.getValue() + "'"));
return;
}
pool.getCurrent().addArg(arg.getValue());
}
} else if (direct == Directives.END_MACRO) {
if (tokens.size() > 1) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "invalid text after .END_MACRO"));
return;
}
if (!inMacroSegment) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), ".END_MACRO without .MACRO"));
return;
}
inMacroSegment = false;
fileCurrentlyBeingAssembled.getLocalMacroPool().commitMacro(token);
} else if (inMacroSegment) {
// should not parse lines even directives in macro segment
return;
} else if (direct == Directives.DATA) {
this.inDataSegment = true;
this.autoAlign = true;
if (tokens.size() > 1 && TokenTypes.isIntegerTokenType(tokens.get(1).getType())) {
this.dataAddress.set(Binary.stringToInt(tokens.get(1).getValue())); // KENV 1/6/05
}
} else if (direct == Directives.TEXT) {
this.inDataSegment = false;
if (tokens.size() > 1 && TokenTypes.isIntegerTokenType(tokens.get(1).getType())) {
this.textAddress.set(Binary.stringToInt(tokens.get(1).getValue())); // KENV 1/6/05
}
} else if (direct == Directives.WORD || direct == Directives.HALF
|| direct == Directives.BYTE || direct == Directives.FLOAT
|| direct == Directives.DOUBLE) {
this.dataDirective = direct;
if (passesDataSegmentCheck(token) && tokens.size() > 1) { // DPS
// 11/20/06, added text segment prohibition
storeNumeric(tokens, direct, errors);
}
} else if (direct == Directives.ASCII || direct == Directives.ASCIZ || direct == Directives.STRING) {
this.dataDirective = direct;
if (passesDataSegmentCheck(token)) {
storeStrings(tokens, direct, errors);
}
} else if (direct == Directives.ALIGN) {
if (passesDataSegmentCheck(token)) {
if (tokens.size() != 2) {
errors.add(new ErrorMessage(token.getSourceProgram(),
token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()
+ "\" requires one operand"));
return;
}
if (!TokenTypes.isIntegerTokenType(tokens.get(1).getType())
|| Binary.stringToInt(tokens.get(1).getValue()) < 0) {
errors.add(new ErrorMessage(token.getSourceProgram(),
token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()
+ "\" requires a non-negative integer"));
return;
}
int value = Binary.stringToInt(tokens.get(1).getValue()); // KENV 1/6/05
if (value == 0) {
this.autoAlign = false;
} else {
this.dataAddress.set(this.alignToBoundary(this.dataAddress.get(),
(int) Math.pow(2, value)));
}
}
} else if (direct == Directives.SPACE) {
// TODO: add a fill type option
// .space 90, 1 should fill memory with 90 bytes with the values 1
if (passesDataSegmentCheck(token)) {
if (tokens.size() != 2) {
errors.add(new ErrorMessage(token.getSourceProgram(),
token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()
+ "\" requires one operand"));
return;
}
if (!TokenTypes.isIntegerTokenType(tokens.get(1).getType())
|| Binary.stringToInt(tokens.get(1).getValue()) < 0) {
errors.add(new ErrorMessage(token.getSourceProgram(),
token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()
+ "\" requires a non-negative integer"));
return;
}
int value = Binary.stringToInt(tokens.get(1).getValue()); // KENV 1/6/05
this.dataAddress.increment(value);
}
} else if (direct == Directives.EXTERN) {
if (tokens.size() != 3) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" directive requires two operands (label and size)."));
return;
}
if (!TokenTypes.isIntegerTokenType(tokens.get(2).getType())
|| Binary.stringToInt(tokens.get(2).getValue()) < 0) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" requires a non-negative integer size"));
return;
}
int size = Binary.stringToInt(tokens.get(2).getValue());
// If label already in global symtab, do nothing. If not, add it right now.
if (Globals.symbolTable.getAddress(tokens.get(1).getValue()) == SymbolTable.NOT_FOUND) {
Globals.symbolTable.addSymbol(tokens.get(1), this.externAddress,
true, errors);
this.externAddress += size;
}
} else if (direct == Directives.GLOBL) {
if (tokens.size() < 2) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" directive requires at least one argument."));
return;
}
// SPIM limits .globl list to one label, why not extend it to a list?
for (int i = 1; i < tokens.size(); i++) {
// Add it to a list of labels to be processed at the end of the
// pass. At that point, transfer matching symbol definitions from
// local symbol table to global symbol table.
Token label = tokens.get(i);
if (label.getType() != TokenTypes.IDENTIFIER) {
errors.add(new ErrorMessage(token.getSourceProgram(),
token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()
+ "\" directive argument must be label."));
return;
}
globalDeclarationList.add(label);
}
} else {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(), token
.getStartPos(), "\"" + token.getValue()
+ "\" directive recognized but not yet implemented."));
}
} // executeDirective()
// //////////////////////////////////////////////////////////////////////////////
// Process the list of .globl labels, if any, declared and defined in this file.
// We'll just move their symbol table entries from local symbol table to global
// symbol table at the end of the first assembly pass.
private void transferGlobals() {
for (int i = 0; i < globalDeclarationList.size(); i++) {
Token label = globalDeclarationList.get(i);
Symbol symtabEntry = fileCurrentlyBeingAssembled.getLocalSymbolTable().getSymbol(
label.getValue());
if (symtabEntry == null) {
errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, label.getSourceLine(),
label.getStartPos(), "\"" + label.getValue()
+ "\" declared global label but not defined."));
} else {
if (Globals.symbolTable.getAddress(label.getValue()) != SymbolTable.NOT_FOUND) {
errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, label.getSourceLine(),
label.getStartPos(), "\"" + label.getValue()
+ "\" already defined as global in a different file."));
} else {
fileCurrentlyBeingAssembled.getLocalSymbolTable().removeSymbol(label);
Globals.symbolTable.addSymbol(label, symtabEntry.getAddress(),
symtabEntry.getType(), errors);
}
}
}
}
// //////////////////////////////////////////////////////////////////////////////////
// This source code line, if syntactically correct, is a continuation of a
// directive list begun on on previous line.
private void executeDirectiveContinuation(TokenList tokens) {
Directives direct = this.dataDirective;
if (direct == Directives.WORD || direct == Directives.HALF || direct == Directives.BYTE
|| direct == Directives.FLOAT || direct == Directives.DOUBLE) {
if (tokens.size() > 0) {
storeNumeric(tokens, direct, errors);
}
} else if (direct == Directives.ASCII || direct == Directives.ASCIZ || direct == Directives.STRING) {
if (passesDataSegmentCheck(tokens.get(0))) {
storeStrings(tokens, direct, errors);
}
}
} // executeDirectiveContinuation()
// //////////////////////////////////////////////////////////////////////////////////
// Given token, find the corresponding Instruction object. If token was not
// recognized as OPERATOR, there is a problem.
private ArrayList<Instruction> matchInstruction(Token token) {
if (token.getType() != TokenTypes.OPERATOR) {
if (token.getSourceProgram().getLocalMacroPool()
.matchesAnyMacroName(token.getValue()))
this.errors.add(new ErrorMessage(token.getSourceProgram(), token
.getSourceLine(), token.getStartPos(), "forward reference or invalid parameters for macro \""
+ token.getValue() + "\""));
else
this.errors.add(new ErrorMessage(token.getSourceProgram(), token
.getSourceLine(), token.getStartPos(), "\"" + token.getValue()
+ "\" is not a recognized operator"));
return null;
}
ArrayList<Instruction> inst = Globals.instructionSet.matchOperator(token.getValue());
if (inst == null) { // This should NEVER happen...
this.errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "Internal Assembler error: \"" + token.getValue()
+ "\" tokenized OPERATOR then not recognized"));
}
return inst;
} // matchInstruction()
// //////////////////////////////////////////////////////////////////////////////////
// Processes the .word/.half/.byte/.float/.double directive.
// Can also handle "directive continuations", e.g. second or subsequent line
// of a multiline list, which does not contain the directive token. Just pass the
// current directive as argument.
private void storeNumeric(TokenList tokens, Directives directive, ErrorList errors) {
Token token = tokens.get(0);
// A double-check; should have already been caught...removed ".word" exemption 11/20/06
assert passesDataSegmentCheck(token);
// Correctly handles case where this is a "directive continuation" line.
int tokenStart = 0;
if (token.getType() == TokenTypes.DIRECTIVE)
tokenStart = 1;
// Set byte length in memory of each number (e.g. WORD is 4, BYTE is 1, etc)
int lengthInBytes = DataTypes.getLengthInBytes(directive);
// Handle the "value : n" format, which replicates the value "n" times.
if (tokens.size() == 4 && tokens.get(2).getType() == TokenTypes.COLON) {
Token valueToken = tokens.get(1);
Token repetitionsToken = tokens.get(3);
// DPS 15-jul-08, allow ":" for repetition for all numeric
// directives (originally just .word)
// Conditions for correctly-formed replication:
// (integer directive AND integer value OR floating directive AND
// (integer value OR floating value))
// AND integer repetition value
if (!(Directives.isIntegerDirective(directive)
&& TokenTypes.isIntegerTokenType(valueToken.getType()) || Directives
.isFloatingDirective(directive)
&& (TokenTypes.isIntegerTokenType(valueToken.getType()) || TokenTypes
.isFloatingTokenType(valueToken.getType())))
|| !TokenTypes.isIntegerTokenType(repetitionsToken.getType())) {
errors.add(new ErrorMessage(fileCurrentlyBeingAssembled,
valueToken.getSourceLine(), valueToken.getStartPos(),
"malformed expression"));
return;
}
int repetitions = Binary.stringToInt(repetitionsToken.getValue()); // KENV 1/6/05
if (repetitions <= 0) {
errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, repetitionsToken
.getSourceLine(), repetitionsToken.getStartPos(),
"repetition factor must be positive"));
return;
}
if (this.inDataSegment) {
if (this.autoAlign) {
this.dataAddress
.set(this.alignToBoundary(this.dataAddress.get(), lengthInBytes));
}
for (int i = 0; i < repetitions; i++) {
if (Directives.isIntegerDirective(directive)) {
storeInteger(valueToken, directive, errors);
} else {
storeRealNumber(valueToken, directive, errors);
}
}
}
return;
}
// if not in ".word w : n" format, must just be list of one or more values.
for (int i = tokenStart; i < tokens.size(); i++) {
token = tokens.get(i);
if (Directives.isIntegerDirective(directive)) {
storeInteger(token, directive, errors);
}
if (Directives.isFloatingDirective(directive)) {
storeRealNumber(token, directive, errors);
}
}
} // storeNumeric()
// //////////////////////////////////////////////////////////////////////////////
// Store integer value given integer (word, half, byte) directive.
// Called by storeNumeric()
// NOTE: The token itself may be a label, in which case the correct action is
// to store the address of that label (into however many bytes specified).
private void storeInteger(Token token, Directives directive, ErrorList errors) {
int lengthInBytes = DataTypes.getLengthInBytes(directive);
if (TokenTypes.isIntegerTokenType(token.getType())) {
int value = Binary.stringToInt(token.getValue());
int fullvalue = value;
// DPS 4-Jan-2013. Overriding 6-Jan-2005 KENV changes.
// If value is out of range for the directive, will simply truncate
// the leading bits (includes sign bits). This is what SPIM does.
// But will issue a warning (not error) which SPIM does not do.
if (directive == Directives.BYTE) {
value = value & 0x000000FF;
} else if (directive == Directives.HALF) {
value = value & 0x0000FFFF;
}
if (DataTypes.outOfRange(directive, fullvalue)) {
errors.add(new ErrorMessage(ErrorMessage.WARNING, token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" is out-of-range for a signed value and possibly truncated"));
}
if (this.inDataSegment) {
writeToDataSegment(value, lengthInBytes, token, errors);
}
/*
* NOTE of 11/20/06. "try" below will always throw exception b/c you
* cannot use Memory.set() with text segment addresses and the
* "not valid address" produced here is misleading. Added data
* segment check prior to this point, so this "else" will never be
* executed. I'm leaving it in just in case MARS in the future adds
* capability of writing to the text segment (e.g. ability to
* de-assemble a binary value into its corresponding MIPS
* instruction)
*/
else {
try {
Globals.memory.set(this.textAddress.get(), value, lengthInBytes);
} catch (AddressErrorException e) {
errors.add(new ErrorMessage(token.getSourceProgram(),
token.getSourceLine(), token.getStartPos(), "\""
+ this.textAddress.get()
+ "\" is not a valid text segment address"));
return;
}
this.textAddress.increment(lengthInBytes);
}
} // end of "if integer token type"
else if (token.getType() == TokenTypes.IDENTIFIER) {
if (this.inDataSegment) {
int value = fileCurrentlyBeingAssembled.getLocalSymbolTable()
.getAddressLocalOrGlobal(token.getValue());
if (value == SymbolTable.NOT_FOUND) {
// Record value 0 for now, then set up backpatch entry
int dataAddress = writeToDataSegment(0, lengthInBytes, token, errors);
currentFileDataSegmentForwardReferences.add(dataAddress, lengthInBytes, token);
} else { // label already defined, so write its address
writeToDataSegment(value, lengthInBytes, token, errors);
}
} // Data segment check done previously, so this "else" will not be.
// See 11/20/06 note above.
else {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" label as directive operand not permitted in text segment"));
}
} // end of "if label"
else {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(), token
.getStartPos(), "\"" + token.getValue()
+ "\" is not a valid integer constant or label"));
}
}// storeInteger
// //////////////////////////////////////////////////////////////////////////////
// Store real (fixed or floating point) value given floating (float, double) directive.
// Called by storeNumeric()
private void storeRealNumber(Token token, Directives directive, ErrorList errors) {
int lengthInBytes = DataTypes.getLengthInBytes(directive);
double value;
if (token.getValue().equals("Inf")) {
value = Float.POSITIVE_INFINITY;
} else if (token.getValue().equals("-Inf")) {
value = Float.NEGATIVE_INFINITY;
} else if (TokenTypes.isIntegerTokenType(token.getType())
|| TokenTypes.isFloatingTokenType(token.getType())) {
try {
value = Double.parseDouble(token.getValue());
} catch (NumberFormatException nfe) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" is not a valid floating point constant"));
return;
}
if (DataTypes.outOfRange(directive, value)) {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(),
token.getStartPos(), "\"" + token.getValue()
+ "\" is an out-of-range value"));
return;
}
} else {
errors.add(new ErrorMessage(token.getSourceProgram(), token.getSourceLine(), token
.getStartPos(), "\"" + token.getValue()
+ "\" is not a valid floating point constant"));