-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathassem1.cpp
More file actions
1902 lines (1795 loc) · 85 KB
/
assem1.cpp
File metadata and controls
1902 lines (1795 loc) · 85 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
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
/**************************** assem1.cpp ********************************
* Author: Agner Fog
* Date created: 2017-04-17
* Last modified: 2021-07-10
* Version: 1.13
* Project: Binary tools for ForwardCom instruction set
* Module: assem.cpp
* Description:
* Module for assembling ForwardCom .as files. Contains:
* pass1(): Split input file into lines and tokens. Remove comments. Find symbol definitions
* pass2(): Handle meta code. Classify lines. Identify symbol names, sections, functions
*
* Copyright 2017-2024 GNU General Public License http://www.gnu.org/licenses
******************************************************************************/
#include "stdafx.h"
const char * allowedInNames = "_$@"; // characters allowed in symbol names (don't allow characters that are used as operators)
const bool allowUTF8 = true; // UTF-8 characters allowed in symbol names
const bool allowNestedComments = true; // allow nested comments: /* /* */ */
// Operator for sorting symbols by name. Used by assembler
// List of operators
SOperator operatorsList[] = {
// name, id, priority
{"(", '(', 1},
{")", ')', 1},
{"[", '[', 1},
{"]", ']', 1},
{"{", '{', 1},
{"}", '}', 1},
{"'", 39, 1},
{"\"", '"', 1}, // "
{"/*", 'c', 1}, // comment begin
{"*/", 'd', 1}, // comment end
{".", '.', 2},
{"!", '!', 3},
{"~", '~', 3},
{"++", '+'+D2, 3},
{"--", '-'+D2, 3},
{"*", '*', 4},
{"/", '/', 4},
{"%", '%', 4},
{"+", '+', 5},
{"-", '-', 5},
{"<<", '<'+D2, 6},
{">>", '>'+D2, 6}, // signed shift right
{">>>", '>'+D3, 6}, // unsigned shift right
{"<", '<', 7},
{"<=", '<'+EQ, 7},
{">", '>', 7},
{">=", '>'+EQ, 7},
{"==", '='+D2, 8},
{"!=", '!'+EQ, 8},
{"&", '&', 9},
{"^", '^', 10},
{"|", '|', 11},
{"&&", '&'+D2, 12},
{"||", '|'+D2, 13},
{"^^", '^'+D2, 13}, // boolean XOR. non-standard operator
{"?", '?', 14},
{":", ':', 14},
{"=", '=', 15},
{"+=", '+'+EQ, 15},
{"-=", '-'+EQ, 15},
{"*=", '*'+EQ, 15},
{"/=", '/'+EQ, 15},
{"%=", '%'+EQ, 15},
{"<<=", '<'+D2+EQ, 15},
{">>=", '>'+D2+EQ, 15}, // signed shift right
{">>>=", '>'+D3+EQ, 15}, // unsigned shift right
{"&=", '&'+EQ, 15},
{"^=", '^'+EQ, 15},
{"|=", '|'+EQ, 15},
{",", ',', 16},
{"//", '/'+D2, 20}, // comment, end of line
{";", ';', 20} // comment, end of line
};
// List of keywords
SKeyword keywordsList[] = {
// name, id
{"section", DIR_SECTION}, // TOK_DIR: section, functions directives
{"function", DIR_FUNCTION},
{"end", DIR_END},
{"public", DIR_PUBLIC},
{"extern", DIR_EXTERN},
// TOK_ATT: attributes of sections, functions and symbols
{"read", ATT_READ}, // readable section
{"write", ATT_WRITE}, // writeable section
{"execute", ATT_EXEC}, // executable section
{"align", ATT_ALIGN}, // align section, data, or code
{"weak", ATT_WEAK}, // weak linking
{"reguse", ATT_REGUSE}, // register use
{"constant", ATT_CONSTANT}, // external constant
{"uninitialized", ATT_UNINIT}, // uninitialized section (BSS)
{"communal", ATT_COMDAT}, // communal section. duplicates and unreferenced sections are removed
{"exception_hand", ATT_EXCEPTION}, // exception handler and stack unroll information
{"event_hand", ATT_EVENT}, // event handler list, including constructors and destructors
{"debug_info", ATT_DEBUG}, // debug information
{"comment_info", ATT_COMMENT}, // comments, including copyright and required libraries
// TOK_TYP: type names
{"int8", TYP_INT8},
{"uint8", TYP_INT8+TYP_UNS},
{"int16", TYP_INT16},
{"uint16", TYP_INT16+TYP_UNS},
{"int32", TYP_INT32},
{"uint32", TYP_INT32+TYP_UNS},
{"int64", TYP_INT64},
{"uint64", TYP_INT64+TYP_UNS},
{"int128", TYP_INT128},
{"uint128", TYP_INT128+TYP_UNS},
{"int", TYP_INT32},
{"uint", TYP_INT32+TYP_UNS},
{"float", TYP_FLOAT32},
{"double", TYP_FLOAT64},
{"float16", TYP_FLOAT16},
{"float32", TYP_FLOAT32},
{"float64", TYP_FLOAT64},
{"float128", TYP_FLOAT128},
{"string", TYP_STRING},
// TOK_OPT: options of instructions and operands
{"mask", OPT_MASK},
{"fallback", OPT_FALLBACK},
{"length", OPT_LENGTH},
{"broadcast", OPT_BROADCAST},
{"limit", OPT_LIMIT},
{"scalar", OPT_SCALAR},
{"options", OPT_OPTIONS},
{"option", OPT_OPTIONS}, // alias
// TOK_REG: register names
{"numcontr", REG_NUMCONTR},
{"threadp", REG_THREADP},
{"datap", REG_DATAP},
{"ip", REG_IP},
{"sp", REG_SP},
// TOK_HLL: high level language keywords
{"if", HLL_IF},
{"else", HLL_ELSE},
{"switch", HLL_SWITCH}, // switch (r1, scratch registers) { case 0: break; ...}
{"case", HLL_CASE},
{"for", HLL_FOR}, // for (r1 = 1; r1 <= r2; r1++) {}
{"in", HLL_IN}, // for (float v1 in [r1-r2], nocheck) // (r2 counts down)
{"while", HLL_WHILE}, // while (r1 > 0) {}
{"do", HLL_DO}, // do {} while ()
{"break", HLL_BREAK}, // break out of switch or loop
{"continue", HLL_CONTINUE}, // continue loop
{"true", HLL_TRUE}, // constant = 1
{"false", HLL_FALSE}, // constant = 0
// temporary additions. will be replaced by macros later:
{"push", HLL_PUSH}, // push registers
{"pop", HLL_POP}, // pop registers
};
// List of register name prefixes
SKeyword registerNames[] = {
// name, id
{"r", REG_R},
{"v", REG_V},
{"spec", REG_SPEC},
{"capab", REG_CAPAB},
{"perf", REG_PERF},
{"sys", REG_SYS}
};
CAssembler::CAssembler() { // Constructor
// Reserve size for buffers
const int estimatedLineLength = 16;
const int estimatedTokensPerLine = 10;
int estimatedNumLines = dataSize() / estimatedLineLength;
lines.setNum(estimatedNumLines);
tokens.setNum(estimatedNumLines * estimatedTokensPerLine);
errors.setOwner(this);
// Initialize and sort lists
initializeWordLists();
ElfFwcShdr nullHeader; // make first section header empty
zeroAllMembers(nullHeader);
sectionHeaders.push(nullHeader);
}
void CAssembler::go() {
// Write feedback text to console
feedBackText1();
// Set default options
if (cmd.codeSizeOption == 0) cmd.codeSizeOption = 1 << 24;
if (cmd.dataSizeOption == 0) cmd.dataSizeOption = 1 << 15;
// initialize options
code_size = cmd.codeSizeOption;
data_size = cmd.dataSizeOption;
do { // This loop is repeated only once. Just convenient to break out of in case of errors
pass = 1;
// Split input file into lines and tokens. Find symbol definitions
pass1();
if (errors.tooMany()) {err.submit(ERR_TOO_MANY_ERRORS); break;}
pass = 2;
// A. Handle metaprogramming directives
// B. Classify lines
// C. Identify symbol names, sections, labels, functions
pass2();
if (errors.tooMany()) {err.submit(ERR_TOO_MANY_ERRORS); break;}
//showTokens(); //!! for debugging only
//showSymbols(); //!! for debugging only
pass = 3;
// Interpret lines. Generate code and data
pass3();
if (errors.tooMany()) {err.submit(ERR_TOO_MANY_ERRORS); break;}
pass = 4;
// Resolve internal cross references, optimize forward references
pass4();
if (errors.tooMany()) {err.submit(ERR_TOO_MANY_ERRORS); break;}
pass = 5;
// Make binary file
pass5();
if (errors.tooMany()) {err.submit(ERR_TOO_MANY_ERRORS); break;}
} while (false);
// output any error messages
errors.outputErrors();
if (errors.numErrors()) cmd.mainReturnValue = 1; // make sure makefile process stops on error
// output object file
outFile.write(cmd.getFilename(cmd.outputFile));
}
// Character can be the start of a symbol name
inline bool nameChar1(char c) {
return ((c | 0x20) >= 'a' && (c | 0x20) <= 'z') || ((c & 0x80) && allowUTF8) || strchr(allowedInNames, c);
}
// Character can be the part of a symbol name
inline bool nameChar2(char c) {
return nameChar1(c) || (c >= '0' && c <= '9');
}
// check if string is a number. Can be decimal, binary, octal, hexadecimal, or floating point
// Returns the length of the part of the string that belongs to the number
uint32_t isNumber(const char * s, int maxlen, bool * isFloat) {
bool is_float = false;
char c = s[0];
if ((c < '0' || c > '9') && (c != '.' || s[1] < '0' || s[1] > '9')) return 0;
int i = 0;
int state = 0;
// 0: begin
// 1: after 0
// 2: after digits 0-9
// 3: after 0x
// 4: after 0b or 0o
// 5: after .
// 6: after E
// 7: after E09
// 8: after E+-
for (i = 0; i < maxlen; i++) {
c = s[i];
char cl = c | 0x20; // upper case letter
if (c == '0' && state == 0) {state = 1; continue;}
if (cl == 'x' && state == 1) {state = 3; continue;}
if ((cl == 'b' || cl == 'o') && state == 1) {state = 4; continue;}
if (c == '.' && state <= 2) {state = 5; is_float = true; continue;}
if (cl == 'e' && (state <= 2 || state == 5)) {state = 6; is_float = true; continue;}
if ((c == '+' || c == '-') && state == 6) {state = 8; continue;}
if (c >= '0' && c <= '9') {
if (state < 2) state = 2;
if (state == 6) state = 7;
continue;
}
if (cl >= 'a' && cl <= 'f' && state == 3) continue;
// Anything else: stop here
break;
}
if (isFloat) *isFloat = is_float; // return isFloat
return i; // return length
}
// Check if string is a register name
uint32_t isRegister(const char * s, uint32_t len) {
uint32_t i, j, nl, num;
for (i = 0; i < TableSize(registerNames); i++) {
if ((s[0] | 0x20) == registerNames[i].name[0]) { // first character match, lower case
nl = (uint32_t)strlen(registerNames[i].name); // length of register name prefix
if (len < nl + 1 || len > nl + 2) continue; // continue search if length wrong
for (j = 0; j < nl; j++) { // check if each character matches
if ((s[j] | 0x20) != registerNames[i].name[j]) { // lower case compare
j = 0xFFFFFFFF; break;
}
}
if (j == 0xFFFFFFFF) continue; // no match
if (s[j] < '0' || s[j] > '9') continue; // not a number
num = s[j] - '0'; // get number, first digit
if (len == nl + 2) { // two digit number
if (s[j+1] < '0' || s[j+1] > '9') continue;// second digit not a number
num = num * 10 + (s[j+1] - '0');
}
if (num >= 32) continue; // number too high
return num + registerNames[i].id; // everyting matches
}
}
return 0; // not found. return 0
}
// write feedback text on stdout
void CAssembler::feedBackText1() {
if (cmd.verbose) {
// Tell what we are doing:
printf("\nAssembling %s to %s", cmd.getFilename(cmd.inputFile), cmd.getFilename(cmd.outputFile));
}
}
// Split input file into lines and tokens. Handle preprocessing directives. Find symbol definitions
void CAssembler::pass1() {
uint32_t n = 0; // offset into assembly file
uint32_t m; // end of current token
int32_t i, f; // temporary
int32_t comment = 0; // 0: normal, 1: inside comment to end of line, 2: inside /* */ comment
uint32_t commentStart = 0; // start position of multiline comment
uint32_t commentStartColumn = 0;// start column of multiline comment
char c; // current character or byte
SToken token = {0}; // current token
SKeyword keywSearch; // record to search for keyword
SOperator opSearch; // record to search for operator
SInstruction instructSearch; // record to search for instruction
SLine line = {0,0,0,0,0,0,0}; // line record
lines.push(line); // empty records for line 0
linei = 1; // start at line 1
numSwitch = 0; // count switch statements
tokens.push(token); // unused token 0
if (dataSize() >= 3 && (get<uint32_t>(0) & 0xFFFFFF) == 0xBFBBEF) {
n += 3; // skip UTF-8 byte order mark
}
line.beginPos = n; // start of line 1
line.firstToken = tokens.numEntries();
line.file = filei;
// loop through file
while (n < dataSize()) {
c = get<char>(n); // get character
// is it space or a control character?
if (uint8_t(c) <= 0x20) {
if (c == ' ' || c == '\t') { // skip space and tab
n++;
continue;
}
if (c == '\r' || c == '\n') { // newline
n++;
if (c == '\r' && get<char>(n) == '\n') n++; // "\r\n" windows newline
if (comment == 1) comment = 0; // end comment
if (n <= dataSize()) {
// finish current line
line.numTokens = tokens.numEntries() - line.firstToken;
line.linenum = linei++;
if (line.numTokens) { // save line if not empty
lines.push(line);
}
// start next line
line.type = 0;
line.file = filei;
line.beginPos = n;
line.firstToken = tokens.numEntries();
}
continue;
}
// illegal control character
token.type = TOK_ERR;
line.type = LINE_ERROR;
comment = 1; // ignore rest of line
m = tokens.push(token); // save error token
errors.report(n, 1, ERR_CONTROL_CHAR);
}
// prepare token of any type
token.pos = n;
token.stringLength = 1;
token.id = 0;
//token.column = n - line.beginPos;
// is it a name?
if (!comment && nameChar1(c)) {
// start of a name
m = n+1;
while (m < dataSize() && nameChar2(get<char>(m))) m++;
// name goes from position n to m-1. make token
token.type = TOK_NAM;
token.pos = n;
token.stringLength = m - n;
// is it a register name
f = isRegister((char*)buf()+n, token.stringLength);
if (f) {
token.type = TOK_REG;
token.id = f;
}
// is it a keyword?
if (token.type == TOK_NAM && m-n < sizeof(keywSearch.name)) {
memcpy(keywSearch.name, buf()+n, m-n);
keywSearch.name[m-n] = 0;
f = keywords.findFirst(keywSearch);
if (f >= 0) { // keyword found
token.id = keywords[f].id;
token.type = keywords[f].id >> 24;
if (token.id == HLL_SWITCH) numSwitch++;
}
}
// is it an instruction?
if (token.type == TOK_NAM && m-n < sizeof(instructSearch.name)) {
memcpy(instructSearch.name, buf()+n, m-n);
instructSearch.name[m-n] = 0;
f = instructionlistNm.findFirst(instructSearch);
if (f >= 0) { // instruction name found
token.type = TOK_INS;
token.id = instructionlistNm[f].id;
}
}
n = m;
tokens.push(token); // save token
continue;
}
// Is it a number?
if (!comment) {
bool isFloat;
f = isNumber((char*)buf() + n, dataSize() - n, &isFloat);
if (f) {
token.type = TOK_NUM + isFloat;
token.id = n; // save number as string. The value is extracted later
token.stringLength = f;
n += f;
tokens.push(token); // save token
continue;
}
}
// is it an operator?
opSearch.name[0] = c;
opSearch.name[1] = 0;
f = operators.findFirst(opSearch);
if (f >= 0) {
// found single-character operator
// make a greedy search for multi-character operators
i = f;
for (i = f+1; (uint32_t)i < operators.numEntries(); i++) {
if (operators[i].name[0] != c) break;
if (memcmp((char*)buf()+n, operators[i].name, strlen(operators[i].name)) == 0) f = i;
}
token.type = TOK_OPR;
token.id = operators[f].id;
token.priority = operators[f].priority;
token.stringLength = (uint32_t)strlen(operators[f].name);
// search for operators that need consideration here
switch (token.id) {
case 39: case '"': // quoted string in single or double quotes
if (comment) break;
// search for end of string
token.type = token.id == 39 ? TOK_CHA : TOK_STR;
token.pos = n + 1;
m = n;
while (true) {
if (get<char>(m+1) == '\r' || get<char>(m+1) == '\n' || m == dataSize()) {
// end of line without matching end quote. multi-line quotes not allowed
token.type = TOK_ERR;
errors.report(token.pos-1, 1, ERR_QUOTE_BEGIN);
comment = 1; // skip rest of line
break;
}
if (get<char>(m+1) == c && get<char>(m) != '\\') { // matching end quote not preceded by escape backslash
token.stringLength = m - n;
n += 2;
break;
}
m++;
}
break;
case '/'+D2: // "//". comment to end of line
if (comment == 0) {
comment = 1;
}
break;
case 'c': // "/*" start of comment
if (comment == 1) {
n += token.stringLength; // skip and don't save token
continue;
}
if (comment == 2) { // nested comment
if (allowNestedComments) {
comment++;
}
else {
token.type = TOK_ERR;
errors.report(n, 2, ERR_COMMENT_BEGIN);
}
break;
}
comment = 2;
commentStart = n; commentStartColumn = n - line.beginPos;
break;
case 'd': // "*/" end of comment
if (comment == 1) {
n += token.stringLength; // skip and don't save token
continue;
}
if (comment == 2) {
comment = 0;
n += token.stringLength; // skip and don't save token
continue;
}
else if (comment > 2 && allowNestedComments) {
comment--;
n += token.stringLength; // skip and don't save token
continue;
}
else {
token.type = TOK_ERR; // unmatched end comment
errors.report(n, 2, ERR_COMMENT_END);
comment = 1;
}
break;
case ';':
// semicolon starts a new pseudo-line
if (comment) break;
// finish current line
tokens.push(token); // the ';' token is used only in for(;;) loops. should be ignored at the end of the line otherwise
n += token.stringLength;
line.numTokens = tokens.numEntries() - line.firstToken;
line.linenum = linei;
if (line.numTokens) { // save line if not empty
lines.push(line);
}
// start next line
line.beginPos = n;
line.firstToken = tokens.numEntries();
continue; // don't save ';' token twice
case '{': case '}':
if (comment) break;
// put each bracket in a separate pseudo-line to ease high level language parsing
// finish current line
line.numTokens = tokens.numEntries() - line.firstToken;
line.linenum = linei;
if (line.numTokens) { // save line if not empty
lines.push(line);
}
// start line with bracket only
line.beginPos = n;
line.firstToken = tokens.numEntries();
tokens.push(token); // save token
n += token.stringLength;
line.numTokens = 1;
lines.push(line);
// start line after bracket
line.beginPos = n;
line.firstToken = tokens.numEntries();
continue;
}
if (comment == 0 && token.type != TOK_ERR) {
// save token unless we are inside a comment or an error has occurred
tokens.push(token); // save token
}
n += token.stringLength;
continue;
}
if (comment) {
// we are inside a comment. Continue search only for end of line or end of comment
n++;
continue;
}
// none of the above. Make token for illegal character
token.type = TOK_ERR;
line.type = LINE_ERROR;
errors.report(n, 1, ERR_ILLEGAL_CHAR);
comment = 1; // ignore rest of line
n++;
}
// finish last line
// tokens.push(token);
line.numTokens = tokens.numEntries() - line.firstToken;
lines.push(line);
// start pseudo line
line.beginPos = n;
line.firstToken = tokens.numEntries();
line.type = 0;
// check for unmatched comment
if (comment >= 2) {
token.type = TOK_ERR;
errors.report(commentStart, commentStartColumn, ERR_COMMENT_BEGIN);
}
// make EOF token in the end
line.type = 0;
line.beginPos = n;
line.firstToken = tokens.numEntries();
line.numTokens = 1;
lines.push(line);
token.pos = n;
token.stringLength = 0;
token.type = TOK_EOF; // end of file
tokens.push(token); // save eof token
}
void CAssembler::interpretSectionDirective() {
// Interpret section directive during pass 2 or 3
// pass 2: identify section name and type, and give it a number
// pass 3: make section header
// to do: nested sections
uint32_t tok; // token number
ElfFWC_Sym2 sym; // symbol record
int32_t sectionsym = 0; // index to symbol record defining current section name
uint32_t state = 0; // 1: after align, 2: after '='
ElfFwcShdr sectionHeader; // section header
zeroAllMembers(sym); // reset symbol
zeroAllMembers(sectionHeader); // reset section header
sectionHeader.sh_type = SHT_PROGBITS; // default section type
sectionFlags = 0;
for (tok = tokenB + 2; tok < tokenB + tokenN; tok++) { // get section attributes
if (tokens[tok].type == TOK_ATT) {
if (tokens[tok].id == ATT_UNINIT && state != 2) {
sectionHeader.sh_type = SHT_NOBITS; // uninitialized section (BSS)
sectionFlags |= SHF_READ | SHF_WRITE;
}
else if (tokens[tok].id == ATT_COMDAT && state != 2) {
sectionHeader.sh_type = SHT_COMDAT; // communal section. duplicates and unreferenced sections are removed
}
else if (tokens[tok].id != ATT_ALIGN && state == 0) {
sectionFlags |= tokens[tok].id & 0xFFFFFF;
if (sectionFlags & SHF_EXEC) sectionFlags |= SHF_IP; // executable section must be IP based
}
else if (tokens[tok].id == ATT_ALIGN && state == 0) {
state = 1;
}
else {
errors.report(tokens[tok]); break;
}
}
else if (tokens[tok].type == TOK_REG && tokens[tok].id == REG_IP && state == 0) sectionFlags |= SHF_IP;
else if (tokens[tok].type == TOK_REG && tokens[tok].id == REG_DATAP && state == 0) sectionFlags |= SHF_DATAP;
else if (tokens[tok].type == TOK_REG && tokens[tok].id == REG_THREADP && state == 0) sectionFlags |= SHF_THREADP;
else if (tokens[tok].type == TOK_OPR && tokens[tok].id == '=' && state == 1) state = 2;
else if (tokens[tok].type == TOK_OPR && tokens[tok].id == ',' && state != 2) ; // comma, ignore
else if (tokens[tok].type == TOK_NUM && state == 2) {
if (pass >= 3) { // alignment value
uint32_t alignm = expression(tok, 1, 0).value.w;
if ((alignm & (alignm - 1)) || alignm > MAX_ALIGN) errors.reportLine(ERR_ALIGNMENT);
else {
sectionHeader.sh_align = bitScanReverse(alignm);
}
}
state = 0;
}
else {
errors.report(tokens[tok]); break;
}
}
// find or define symbol with section name
sectionsym = findSymbol((char*)buf() + tokens[tokenB].pos, tokens[tokenB].stringLength);
if (sectionsym <= 0) {
// symbol not previously defined. Define it now
sym.st_type = STT_SECTION;
sym.st_name = symbolNameBuffer.putStringN((char*)buf() + tokens[tokenB].pos, tokens[tokenB].stringLength);
sym.st_bind = sectionFlags;
sectionsym = addSymbol(sym); // save symbol with section name
}
else {
// symbol already defined. check that it is a section name
if (symbols[sectionsym].st_type != STT_SECTION) {
errors.report(tokens[tokenB].pos, tokens[tokenB].stringLength, ERR_SYMBOL_DEFINED);
}
}
sectionFlags |= SHF_ALLOC;
lines[linei].type = LINE_SECTION; // line is section directive
lines[linei].sectionType = sectionFlags;
if (symbols[sectionsym].st_section == 0) {
// new section. make section header
sectionHeader.sh_name = symbols[sectionsym].st_name;
if (sectionFlags & SHF_EXEC) {
sectionHeader.sh_entsize = 4;
if (sectionHeader.sh_align < 2) sectionHeader.sh_align = 2;
sectionFlags |= SHF_IP;
}
else { // data section
if (!(sectionFlags & (SHF_READ | SHF_WRITE))) sectionFlags |= SHF_READ | SHF_WRITE; // read or write attributes not specified, default is both
if (!(sectionFlags & (SHF_IP | SHF_DATAP | SHF_THREADP))) { // address reference not specified. assume datap if writeable, ip if readonly
if (sectionFlags & SHF_WRITE) sectionFlags |= SHF_DATAP;
else sectionFlags |= SHF_IP;
}
}
sectionHeader.sh_flags = sectionFlags;
section = sectionHeaders.push(sectionHeader);
symbols[sectionsym].st_section = section;
}
else { // this section is seen before
section = symbols[sectionsym].st_section;
if (sectionHeaders[section].sh_align < sectionHeader.sh_align) sectionHeaders[section].sh_align = sectionHeader.sh_align;
if (sectionFlags && (sectionFlags & ~sectionHeaders[section].sh_flags)) errors.reportLine(ERR_SECTION_DIFFERENT_TYPE);
sectionFlags = (uint32_t)sectionHeaders[section].sh_flags;
if (sectionHeader.sh_align > 2) {
// insert alignment code
SCode code;
zeroAllMembers(code);
code.instruction = II_ALIGN;
code.value.u = (int64_t)1 << sectionHeader.sh_align;
code.sizeUnknown = 0x80;
code.section = section;
codeBuffer.push(code);
}
}
}
void CAssembler::interpretFunctionDirective() {
// Interpret function directive during pass 2
uint32_t tok; // token number
ElfFWC_Sym2 sym; // symbol record
zeroAllMembers(sym); // reset symbol
int32_t symi;
symi = findSymbol((char*)buf() + tokens[tokenB].pos, tokens[tokenB].stringLength);
if (symi > 0) {
if (pass == 2) errors.report(tokens[tokenB].pos, tokens[tokenB].stringLength, ERR_SYMBOL_DEFINED); // symbol already defined
}
else {
// define symbol
sym.st_type = STT_FUNC;
sym.st_other = STV_IP;
sym.st_name = symbolNameBuffer.putStringN((char*)buf() + tokens[tokenB].pos, tokens[tokenB].stringLength);
sym.st_bind = 0;
sym.st_section = section;
for (tok = tokenB + 2; tok < tokenB + tokenN; tok++) { // get function attributes
if (tokens[tok].type == TOK_OPR && tokens[tok].id == ',') continue;
if (tokens[tok].id == ATT_WEAK) sym.st_bind |= STB_WEAK;
if (tokens[tok].id == ATT_REGUSE) {
if (tokens[tok+1].id == '=' && tokens[tok+2].type == TOK_NUM) {
tok += 2;
sym.st_reguse1 = expression(tok, 1, 0).value.w;
sym.st_other |= STV_REGUSE;
if (tokens[tok+1].id == ',' && tokens[tok+2].type == TOK_NUM) {
tok += 2;
sym.st_reguse2 = expression(tok, 1, 0).value.w;
}
}
}
else if (tokens[tok].type == TOK_DIR && tokens[tok].id == DIR_PUBLIC) sym.st_bind |= STB_GLOBAL;
else {
errors.report(tokens[tok]); // unexpected token
}
}
symi = addSymbol(sym); // save symbol with function name
}
lines[linei].type = LINE_FUNCTION; // line is function directive
if (pass == 3 && symi) {
// make a label here. The final address will be calculated in pass 4
SCode code; // current instruction code
zeroAllMembers(code); // reset code structure
code.label = symbols[symi].st_name;
code.section = section;
codeBuffer.push(code);
}
}
void CAssembler::interpretEndDirective() {
// Interpret section or function end directive during pass 2
ElfFWC_Sym2 sym; // symbol record
zeroAllMembers(sym); // reset symbol
int32_t symi;
CTextFileBuffer tempBuffer; // temporary storage of names
symi = findSymbol((char*)buf() + tokens[tokenB].pos, tokens[tokenB].stringLength);
if (symi <= 0) {
errors.reportLine(ERR_UNMATCHED_END);
}
else {
if (symbols[symi].st_type == STT_SECTION) {
if (symbols[symi].st_section == section) {
// current section ends here
section = 0; sectionFlags = 0;
}
else {
errors.reportLine(ERR_UNMATCHED_END);
}
}
else if (symbols[symi].st_type == STT_FUNC && pass >= 4) {
symbols[symi].st_unitsize = 4;
// to do: insert size!
//symbols[symi].st_unitsize = ?
// support function(){} syntax. prevent nested functions
}
}
lines[linei].type = LINE_ENDDIR; // line is end directive
}
// Interpret line specifying options
void CAssembler::interpretOptionsLine() {
// Expecting a line of the type:
// "options codesize = 0x10000, datasize = 1 << 20"
uint32_t tok; // token number
uint32_t state = 0; // 0: start, 1: after option name, 2: after equal sign, 3: after expression
const char * optionname = 0;
int option = 0; // 1: codesize, 2: datasize
SExpression val; // value to be assigned
SCode code; // instruction code containing options
for (tok = tokenB + 1; tok < tokenB + tokenN; tok++) {
switch (state) {
case 0: // start. expect name "datasize" or "codesize"
if (tokens[tok].type != TOK_NAM) {
errors.report(tokens[tok]); return; // unexpected token
}
optionname = (char*)buf()+tokens[tok].pos; // tokens[tok].stringLength;
if (strncasecmp_(optionname, "codesize", 8) == 0) option = 1;
else if (strncasecmp_(optionname, "datasize", 8) == 0) option = 2;
else {
errors.report(tokens[tok]); return; // unexpected name
}
state = 1;
break;
case 1: // after name, expecting equal sign
if (tokens[tok].type == TOK_OPR && tokens[tok].id == '=') {
state = 2;
}
else {
errors.report(tokens[tok]); return; // unexpected token
}
break;
case 2: // expect expression
val = expression(tok, tokenB + tokenN - tok, 0); // evaluate number or expression
tok += val.tokens - 1;
if (val.etype != XPR_INT) {
errors.reportLine(ERR_MUST_BE_CONSTANT);
return;
}
zeroAllMembers(code); // reset code structure
switch (option) {
case 1: // set codesize
if (val.value.u == 0) code_size = cmd.codeSizeOption;
else code_size = val.value.u;
code.value.u = code_size;
break;
case 2: // set datasize
if (val.value.u == 0) data_size = cmd.dataSizeOption;
else data_size = val.value.u;
code.value.u = data_size;
break;
}
// This is called only in pass 3. Save this option for pass 4:
code.instruction = II_OPTIONS;
code.section = section;
code.fitNum = option;
code.sizeUnknown = 1;
codeBuffer.push(code);
state = 3;
break;
case 3: // expect comma or nothing
if (tokens[tok].type == TOK_OPR && tokens[tok].id == ',') {
state = 0; // start over after comma
}
else {
errors.report(tokens[tok]); return; // unexpected token
}
}
}
}
// Find symbol by index into symbolNameBuffer. The return value is an index into symbols.
// Symbol indexes may change when new symbols are added to the symbols list, which is sorted by name
uint32_t CAssembler::findSymbol(uint32_t namei) {
ElfFWC_Sym2 sym; // temporary symbol record used for searching
sym.st_name = namei;
return symbols.findFirst(sym); // find symbol by name
}
// Find symbol by name as string. The return value is an index into symbols.
// Symbol indexes may change when new symbols are added to the symbols list, which is sorted by name
uint32_t CAssembler::findSymbol(const char * name, uint32_t len) {
uint32_t saveSize = symbolNameBuffer.dataSize(); // save symbolNameBuffer size for later reset
uint32_t namei = symbolNameBuffer.putStringN(name, len); // put name temporarily into symbolNameBuffer
int32_t symi = findSymbol(namei); // find symbol by name index
symbolNameBuffer.setSize(saveSize); // remove temporary name from symbolNameBuffer
return symi; // return symbol index
}
// Add a symbol to symbols list
uint32_t CAssembler::addSymbol(ElfFWC_Sym2 & sym) {
int32_t f = symbols.findFirst(sym);
if (f >= 0) {
// error: symbol already defined
return 0;
}
else {
return symbols.addUnique(sym);
}
}
// interpret name: options {, name: options}
void CAssembler::interpretExternDirective() {
uint32_t tok; // token number
uint32_t nametok = 0; // last name token
ElfFWC_Sym2 sym; // symbol record
zeroAllMembers(sym); // reset symbol
sym.st_bind = STB_GLOBAL;
// Example: extern name1: int32 weak, name2: function, name3, name4: read
uint32_t state = 0; // 0: after extern or comma,
// 1: after name,
// 2: after colon
// loop through tokens on this line
for (tok = tokenB + 1; tok < tokenB + tokenN; tok++) {
switch (state) {
case 0: // after extern or comma. expecting name
if (tokens[tok].type == TOK_NAM) {
// name encountered
sym.st_name = symbolNameBuffer.putStringN((char*)buf()+tokens[tok].pos, tokens[tok].stringLength);
state = 1; nametok = tok;
}
else errors.report(tokens[tok]);
break;
case 1: // after name. expecting colon or comma
if (tokens[tok].type == TOK_OPR) {
if (tokens[tok].id == ':') {
state = 2;
continue;
}
else if (tokens[tok].id == ',') {
goto COMMA;
}
}
errors.report(tokens[tok]);
break;
case 2: // after colon. expecting attribute or comma or end of line
if (tokens[tok].type == TOK_TYP) {
// symbol size given by type token
uint32_t s = tokens[tok].id & 0xF;
if (s > 4) s -= 3; // float types
sym.st_unitsize = uint32_t(1 << s);
sym.st_unitnum = 1;
}
else if (tokens[tok].type == TOK_ATT || tokens[tok].type == TOK_DIR) {
ATTRIBUTE:
switch (tokens[tok].id) {
case DIR_FUNCTION: case ATT_EXEC: // function or execute
if (sym.st_type) {
errors.report(tokens[tok].pos, tokens[tok].stringLength, ERR_CONFLICT_TYPE);
}
sym.st_type = STT_FUNC;
sym.st_other = STV_IP | STV_EXEC;
break;
case ATT_READ: // read
if (sym.st_type == 0) sym.st_other |= STV_READ;
break;
case ATT_WRITE: // write
if (sym.st_type == STT_FUNC) {
errors.report(tokens[tok].pos, tokens[tok].stringLength, ERR_CONFLICT_TYPE);
}
else {
sym.st_type = STT_OBJECT;
}
break;
case ATT_WEAK: // weak
sym.st_bind = STB_WEAK;
break;
case ATT_CONSTANT: // constant
sym.st_type = STT_CONSTANT;
break;
case ATT_REGUSE:
if (tokens[tok+1].id == '=' && (tokens[tok+2].type == TOK_NUM /*|| tokens[tok+2].type == TOK_OPR)*/)) {
tok += 2;
sym.st_reguse1 = expression(tok, 1, 0).value.w;
sym.st_other |= STV_REGUSE;
if (tokens[tok+1].id == ',' && tokens[tok+2].type == TOK_NUM) {
tok += 2;