-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselfie.c
7087 lines (5438 loc) · 172 KB
/
selfie.c
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
// Copyright (c) 2015-2017, the Selfie Project authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is
// governed by a BSD license that can be found in the LICENSE file.
//
// Selfie is a project of the Computational Systems Group at the
// Department of Computer Sciences of the University of Salzburg
// in Austria. For further information and code please refer to:
//
// http://selfie.cs.uni-salzburg.at
//
// The Selfie Project provides an educational platform for teaching
// undergraduate and graduate students the design and implementation
// of programming languages and runtime systems. The focus is on the
// construction of compilers, libraries, operating systems, and even
// virtual machine monitors. The common theme is to identify and
// resolve self-reference in systems code which is seen as the key
// challenge when teaching systems engineering, hence the name.
//
// Selfie is a fully self-referential 7k-line C implementation of:
//
// 1. a self-compiling compiler called starc that compiles
// a tiny but powerful subset of C called C Star (C*) to
// a tiny but powerful subset of MIPS32 called MIPSter,
// 2. a self-executing emulator called mipster that executes
// MIPSter code including itself when compiled with starc,
// 3. a self-hosting hypervisor called hypster which is based on
// a tiny microkernel implemented in mipster and provides
// MIPSter virtual machines that can host all of selfie,
// that is, starc, mipster, and hypster itself, and
// 4. a tiny C* library called libcstar utilized by selfie.
//
// Selfie is kept minimal for simplicity and implemented in a single file.
// There is a simple linker, disassembler, profiler, and debugger as well as
// minimal operating system support in the form of MIPS32 o32 system calls
// built into the emulator.
//
// C* is a tiny Turing-complete subset of C that includes dereferencing
// (the * operator) but excludes composite data types, bitwise and Boolean
// operators, and many other features. There are only signed 32-bit
// integers and 32-bit pointers as well as character and string literals.
// This choice turns out to be helpful for students to understand the
// true role of composite data types such as arrays and records.
// Bitwise operations are implemented in libcstar using signed integer
// arithmetics helping students gain true understanding of two's complement.
// C* is supposed to be close to the minimum necessary for implementing
// a self-compiling, single-pass, recursive-descent compiler. C* can be
// taught in around two weeks of classes depending on student background.
//
// The compiler can readily be extended to compile features missing in C*
// and to improve performance of the generated code. The compiler generates
// MIPSter executables that can directly be executed by the emulator or
// written to a file in a simple, custom-defined format. Support of standard
// MIPS32 ELF binaries should be easy but remains future work.
//
// MIPSter is a tiny Turing-complete subset of the MIPS32 instruction set.
// It only features arithmetic, memory, and control-flow instructions but
// neither bitwise nor byte-level instructions. MIPSter can be properly
// explained in a single week of classes.
//
// The emulator implements minimal operating system support that is meant
// to be extended by students, first as part of the emulator, and then
// ported to run on top of it, similar to an actual operating system or
// virtual machine monitor. The fact that the emulator can execute itself
// helps exposing the self-referential nature of that challenge. In fact,
// selfie goes one step further by implementing microkernel functionality
// as part of the emulator and a hypervisor that can run as part of the
// emulator as well as on top of it, all with the same code.
//
// Selfie is the result of many years of teaching systems engineering.
// The design of the compiler is inspired by the Oberon compiler of
// Professor Niklaus Wirth from ETH Zurich. The design of the selfie
// microkernel is inspired by microkernels of Professor Jochen Liedtke
// from University of Karlsruhe.
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- L I B R A R Y ---------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ----------------------- BUILTIN PROCEDURES ----------------------
// -----------------------------------------------------------------
void exit(int code);
int read(int fd, int* buffer, int bytesToRead);
int write(int fd, int* buffer, int bytesToWrite);
int open(int* filename, int flags, int mode);
int* malloc(int size);
// -----------------------------------------------------------------
// ----------------------- LIBRARY PROCEDURES ----------------------
// -----------------------------------------------------------------
void initLibrary();
void resetLibrary();
int twoToThePowerOf(int p);
int leftShift(int n, int b);
int rightShift(int n, int b);
int loadCharacter(int* s, int i);
int* storeCharacter(int* s, int i, int c);
int stringLength(int* s);
void stringReverse(int* s);
int stringCompare(int* s, int* t);
int atoi(int* s);
int* itoa(int n, int* s, int b, int a, int p);
int fixedPointRatio(int a, int b);
void putCharacter(int c);
void print(int* s);
void println();
void printCharacter(int c);
void printString(int* s);
void printInteger(int n);
void printFixedPointPercentage(int a, int b);
void printFixedPointRatio(int a, int b);
void printHexadecimal(int n, int a);
void printOctal(int n, int a);
void printBinary(int n, int a);
int roundUp(int n, int m);
int* zalloc(int size);
// ------------------------ GLOBAL CONSTANTS -----------------------
int CHAR_EOF = -1; // end of file
int CHAR_TAB = 9; // ASCII code 9 = tabulator
int CHAR_LF = 10; // ASCII code 10 = line feed
int CHAR_CR = 13; // ASCII code 13 = carriage return
int CHAR_SPACE = ' ';
int CHAR_SEMICOLON = ';';
int CHAR_PLUS = '+';
int CHAR_DASH = '-';
int CHAR_ASTERISK = '*';
int CHAR_SLASH = '/';
int CHAR_UNDERSCORE = '_';
int CHAR_EQUAL = '=';
int CHAR_LPARENTHESIS = '(';
int CHAR_RPARENTHESIS = ')';
int CHAR_LBRACE = '{';
int CHAR_RBRACE = '}';
int CHAR_COMMA = ',';
int CHAR_LT = '<';
int CHAR_GT = '>';
int CHAR_EXCLAMATION = '!';
int CHAR_PERCENTAGE = '%';
int CHAR_SINGLEQUOTE = 39; // ASCII code 39 = '
int CHAR_DOUBLEQUOTE = '"';
int SIZEOFINT = 4; // must be the same as WORDSIZE
int SIZEOFINTSTAR = 4; // must be the same as WORDSIZE
int* power_of_two_table;
int INT_MAX; // maximum numerical value of a signed 32-bit integer
int INT_MIN; // minimum numerical value of a signed 32-bit integer
int INT16_MAX; // maximum numerical value of a signed 16-bit integer
int INT16_MIN; // minimum numerical value of a signed 16-bit integer
int maxFilenameLength = 128;
int* character_buffer; // buffer for reading and writing characters
int* integer_buffer; // buffer for printing integers
int* filename_buffer; // buffer for opening files
int* binary_buffer; // buffer for binary I/O
// flags for opening read-only files
// LINUX: 0 = 0x0000 = O_RDONLY (0x0000)
// MAC: 0 = 0x0000 = O_RDONLY (0x0000)
// WINDOWS: 32768 = 0x8000 = _O_BINARY (0x8000) | _O_RDONLY (0x0000)
// since LINUX/MAC do not seem to mind about _O_BINARY set
// we use the WINDOWS flags as default
int O_RDONLY = 32768;
// flags for opening write-only files
// MAC: 1537 = 0x0601 = O_CREAT (0x0200) | O_TRUNC (0x0400) | O_WRONLY (0x0001)
int MAC_O_CREAT_TRUNC_WRONLY = 1537;
// LINUX: 577 = 0x0241 = O_CREAT (0x0040) | O_TRUNC (0x0200) | O_WRONLY (0x0001)
int LINUX_O_CREAT_TRUNC_WRONLY = 577;
// WINDOWS: 33537 = 0x8301 = _O_BINARY (0x8000) | _O_CREAT (0x0100) | _O_TRUNC (0x0200) | _O_WRONLY (0x0001)
int WINDOWS_O_BINARY_CREAT_TRUNC_WRONLY = 33537;
// flags for rw-r--r-- file permissions
// 420 = 00644 = S_IRUSR (00400) | S_IWUSR (00200) | S_IRGRP (00040) | S_IROTH (00004)
// these flags seem to be working for LINUX, MAC, and WINDOWS
int S_IRUSR_IWUSR_IRGRP_IROTH = 420;
// ------------------------ GLOBAL VARIABLES -----------------------
int numberOfWrittenCharacters = 0;
int* outputName = (int*) 0;
int outputFD = 1;
// ------------------------- INITIALIZATION ------------------------
void initLibrary() {
int i;
// powers of two table with 31 entries for 2^0 to 2^30
// avoiding overflow for 2^31 and larger numbers with 32-bit signed integers
power_of_two_table = malloc(31 * SIZEOFINT);
*power_of_two_table = 1; // 2^0 == 1
i = 1;
while (i < 31) {
// compute powers of two incrementally using this recurrence relation
*(power_of_two_table + i) = *(power_of_two_table + (i - 1)) * 2;
i = i + 1;
}
// compute INT_MAX and INT_MIN without integer overflows
INT_MAX = (twoToThePowerOf(30) - 1) * 2 + 1;
INT_MIN = -INT_MAX - 1;
INT16_MAX = twoToThePowerOf(15) - 1;
INT16_MIN = -INT16_MAX - 1;
// allocate and touch to make sure memory is mapped for read calls
character_buffer = malloc(1);
*character_buffer = 0;
// accommodate at least 32-bit numbers for itoa, no mapping needed
integer_buffer = malloc(33);
// does not need to be mapped
filename_buffer = malloc(maxFilenameLength);
// allocate and touch to make sure memory is mapped for read calls
binary_buffer = malloc(SIZEOFINT);
*binary_buffer = 0;
}
void resetLibrary() {
numberOfWrittenCharacters = 0;
}
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- C O M P I L E R ---------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ---------------------------- SCANNER ----------------------------
// -----------------------------------------------------------------
void initScanner();
void resetScanner();
void printSymbol(int symbol);
void printLineNumber(int* message, int line);
void syntaxErrorMessage(int* message);
void syntaxErrorCharacter(int character);
void getCharacter();
int isCharacterNewLine();
int isCharacterWhitespace();
int findNextCharacter();
int isCharacterLetter();
int isCharacterDigit();
int isCharacterLetterOrDigitOrUnderscore();
int isCharacterNotDoubleQuoteOrNewLineOrEOF();
int identifierStringMatch(int stringIndex);
int identifierOrKeyword();
void getSymbol();
// ------------------------ GLOBAL CONSTANTS -----------------------
int SYM_EOF = -1; // end of file
int SYM_IDENTIFIER = 0; // identifier
int SYM_INTEGER = 1; // integer
int SYM_VOID = 2; // VOID
int SYM_INT = 3; // INT
int SYM_SEMICOLON = 4; // ;
int SYM_IF = 5; // IF
int SYM_ELSE = 6; // ELSE
int SYM_PLUS = 7; // +
int SYM_MINUS = 8; // -
int SYM_ASTERISK = 9; // *
int SYM_DIV = 10; // /
int SYM_EQUALITY = 11; // ==
int SYM_ASSIGN = 12; // =
int SYM_LPARENTHESIS = 13; // (
int SYM_RPARENTHESIS = 14; // )
int SYM_LBRACE = 15; // {
int SYM_RBRACE = 16; // }
int SYM_WHILE = 17; // WHILE
int SYM_RETURN = 18; // RETURN
int SYM_COMMA = 19; // ,
int SYM_LT = 20; // <
int SYM_LEQ = 21; // <=
int SYM_GT = 22; // >
int SYM_GEQ = 23; // >=
int SYM_NOTEQ = 24; // !=
int SYM_MOD = 25; // %
int SYM_CHARACTER = 26; // character
int SYM_STRING = 27; // string
int* SYMBOLS; // strings representing symbols
int maxIdentifierLength = 64; // maximum number of characters in an identifier
int maxIntegerLength = 10; // maximum number of characters in an integer
int maxStringLength = 128; // maximum number of characters in a string
// ------------------------ GLOBAL VARIABLES -----------------------
int lineNumber = 1; // current line number for error reporting
int* identifier = (int*) 0; // stores scanned identifier as string
int* integer = (int*) 0; // stores scanned integer as string
int* string = (int*) 0; // stores scanned string
int literal = 0; // stores numerical value of scanned integer or character
int mayBeINTMIN = 0; // allow INT_MIN if '-' was scanned before
int isINTMIN = 0; // flag to indicate that INT_MIN was scanned
int character; // most recently read character
int numberOfReadCharacters = 0;
int symbol; // most recently recognized symbol
int numberOfIgnoredCharacters = 0;
int numberOfComments = 0;
int numberOfScannedSymbols = 0;
int* sourceName = (int*) 0; // name of source file
int sourceFD = 0; // file descriptor of open source file
// ------------------------- INITIALIZATION ------------------------
void initScanner () {
SYMBOLS = malloc(28 * SIZEOFINTSTAR);
*(SYMBOLS + SYM_IDENTIFIER) = (int) "identifier";
*(SYMBOLS + SYM_INTEGER) = (int) "integer";
*(SYMBOLS + SYM_VOID) = (int) "void";
*(SYMBOLS + SYM_INT) = (int) "int";
*(SYMBOLS + SYM_SEMICOLON) = (int) ";";
*(SYMBOLS + SYM_IF) = (int) "if";
*(SYMBOLS + SYM_ELSE) = (int) "else";
*(SYMBOLS + SYM_PLUS) = (int) "+";
*(SYMBOLS + SYM_MINUS) = (int) "-";
*(SYMBOLS + SYM_ASTERISK) = (int) "*";
*(SYMBOLS + SYM_DIV) = (int) "/";
*(SYMBOLS + SYM_EQUALITY) = (int) "==";
*(SYMBOLS + SYM_ASSIGN) = (int) "=";
*(SYMBOLS + SYM_LPARENTHESIS) = (int) "(";
*(SYMBOLS + SYM_RPARENTHESIS) = (int) ")";
*(SYMBOLS + SYM_LBRACE) = (int) "{";
*(SYMBOLS + SYM_RBRACE) = (int) "}";
*(SYMBOLS + SYM_WHILE) = (int) "while";
*(SYMBOLS + SYM_RETURN) = (int) "return";
*(SYMBOLS + SYM_COMMA) = (int) ",";
*(SYMBOLS + SYM_LT) = (int) "<";
*(SYMBOLS + SYM_LEQ) = (int) "<=";
*(SYMBOLS + SYM_GT) = (int) ">";
*(SYMBOLS + SYM_GEQ) = (int) ">=";
*(SYMBOLS + SYM_NOTEQ) = (int) "!=";
*(SYMBOLS + SYM_MOD) = (int) "%";
*(SYMBOLS + SYM_CHARACTER) = (int) "character";
*(SYMBOLS + SYM_STRING) = (int) "string";
character = CHAR_EOF;
symbol = SYM_EOF;
}
void resetScanner() {
lineNumber = 1;
numberOfReadCharacters = 0;
getCharacter();
numberOfIgnoredCharacters = 0;
numberOfComments = 0;
numberOfScannedSymbols = 0;
getSymbol();
}
// -----------------------------------------------------------------
// ------------------------- SYMBOL TABLE --------------------------
// -----------------------------------------------------------------
void resetSymbolTables();
void createSymbolTableEntry(int which, int* string, int line, int class, int type, int value, int address);
int* searchSymbolTable(int* entry, int* string, int class);
int* getScopedSymbolTableEntry(int* string, int class);
int isUndefinedProcedure(int* entry);
int reportUndefinedProcedures();
// symbol table entry:
// +----+---------+
// | 0 | next | pointer to next entry
// | 1 | string | identifier string, string literal
// | 2 | line# | source line number
// | 3 | class | VARIABLE, PROCEDURE, STRING
// | 4 | type | INT_T, INTSTAR_T, VOID_T
// | 5 | value | VARIABLE: initial value
// | 6 | address | VARIABLE: offset, PROCEDURE: address, STRING: offset
// | 7 | scope | REG_GP, REG_FP
// +----+---------+
int* getNextEntry(int* entry) { return (int*) *entry; }
int* getString(int* entry) { return (int*) *(entry + 1); }
int getLineNumber(int* entry) { return *(entry + 2); }
int getClass(int* entry) { return *(entry + 3); }
int getType(int* entry) { return *(entry + 4); }
int getValue(int* entry) { return *(entry + 5); }
int getAddress(int* entry) { return *(entry + 6); }
int getScope(int* entry) { return *(entry + 7); }
void setNextEntry(int* entry, int* next) { *entry = (int) next; }
void setString(int* entry, int* identifier) { *(entry + 1) = (int) identifier; }
void setLineNumber(int* entry, int line) { *(entry + 2) = line; }
void setClass(int* entry, int class) { *(entry + 3) = class; }
void setType(int* entry, int type) { *(entry + 4) = type; }
void setValue(int* entry, int value) { *(entry + 5) = value; }
void setAddress(int* entry, int address) { *(entry + 6) = address; }
void setScope(int* entry, int scope) { *(entry + 7) = scope; }
// ------------------------ GLOBAL CONSTANTS -----------------------
// classes
int VARIABLE = 1;
int PROCEDURE = 2;
int STRING = 3;
// types
int INT_T = 1;
int INTSTAR_T = 2;
int VOID_T = 3;
// symbol tables
int GLOBAL_TABLE = 1;
int LOCAL_TABLE = 2;
int LIBRARY_TABLE = 3;
// ------------------------ GLOBAL VARIABLES -----------------------
// table pointers
int* global_symbol_table = (int*) 0;
int* local_symbol_table = (int*) 0;
int* library_symbol_table = (int*) 0;
int numberOfGlobalVariables = 0;
int numberOfProcedures = 0;
int numberOfStrings = 0;
// ------------------------- INITIALIZATION ------------------------
void resetSymbolTables() {
global_symbol_table = (int*) 0;
local_symbol_table = (int*) 0;
library_symbol_table = (int*) 0;
numberOfGlobalVariables = 0;
numberOfProcedures = 0;
numberOfStrings = 0;
}
// -----------------------------------------------------------------
// ---------------------------- PARSER -----------------------------
// -----------------------------------------------------------------
void resetParser();
int isNotRbraceOrEOF();
int isExpression();
int isLiteral();
int isStarOrDivOrModulo();
int isPlusOrMinus();
int isComparison();
int lookForFactor();
int lookForStatement();
int lookForType();
void save_temporaries();
void restore_temporaries(int numberOfTemporaries);
void syntaxErrorSymbol(int expected);
void syntaxErrorUnexpected();
void printType(int type);
void typeWarning(int expected, int found);
int* getVariable(int* variable);
int load_variable(int* variable);
void load_integer(int value);
void load_string(int* string);
int help_call_codegen(int* entry, int* procedure);
void help_procedure_prologue(int localVariables);
void help_procedure_epilogue(int parameters);
int gr_call(int* procedure);
int gr_factor();
int gr_term();
int gr_simpleExpression();
int gr_expression();
void gr_while();
void gr_if();
void gr_return();
void gr_statement();
int gr_type();
void gr_variable(int offset);
int gr_initialization(int type);
void gr_procedure(int* procedure, int type);
void gr_cstar();
// ------------------------ GLOBAL VARIABLES -----------------------
int allocatedTemporaries = 0; // number of allocated temporaries
int allocatedMemory = 0; // number of bytes for global variables and strings
int returnBranches = 0; // fixup chain for return statements
int returnType = 0; // return type of currently parsed procedure
int mainJump = 0; // address where JAL instruction to main procedure is
int numberOfCalls = 0;
int numberOfAssignments = 0;
int numberOfWhile = 0;
int numberOfIf = 0;
int numberOfReturn = 0;
// ------------------------- INITIALIZATION ------------------------
void resetParser() {
numberOfCalls = 0;
numberOfAssignments = 0;
numberOfWhile = 0;
numberOfIf = 0;
numberOfReturn = 0;
}
// -----------------------------------------------------------------
// ---------------------- MACHINE CODE LIBRARY ---------------------
// -----------------------------------------------------------------
void emitLeftShiftBy(int b);
void emitMainEntry();
void bootstrapCode();
// -----------------------------------------------------------------
// --------------------------- COMPILER ----------------------------
// -----------------------------------------------------------------
void selfie_compile();
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ------------------- I N T E R F A C E -------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ---------------------------- REGISTER ---------------------------
// -----------------------------------------------------------------
void initRegister();
void printRegister(int reg);
// ------------------------ GLOBAL CONSTANTS -----------------------
int NUMBEROFREGISTERS = 32;
int REG_ZR = 0;
int REG_AT = 1;
int REG_V0 = 2;
int REG_V1 = 3;
int REG_A0 = 4;
int REG_A1 = 5;
int REG_A2 = 6;
int REG_A3 = 7;
int REG_T0 = 8;
int REG_T1 = 9;
int REG_T2 = 10;
int REG_T3 = 11;
int REG_T4 = 12;
int REG_T5 = 13;
int REG_T6 = 14;
int REG_T7 = 15;
int REG_S0 = 16;
int REG_S1 = 17;
int REG_S2 = 18;
int REG_S3 = 19;
int REG_S4 = 20;
int REG_S5 = 21;
int REG_S6 = 22;
int REG_S7 = 23;
int REG_T8 = 24;
int REG_T9 = 25;
int REG_K0 = 26;
int REG_K1 = 27;
int REG_GP = 28;
int REG_SP = 29;
int REG_FP = 30;
int REG_RA = 31;
int* REGISTERS; // strings representing registers
// ------------------------- INITIALIZATION ------------------------
void initRegister() {
REGISTERS = malloc(NUMBEROFREGISTERS * SIZEOFINTSTAR);
*(REGISTERS + REG_ZR) = (int) "$zero";
*(REGISTERS + REG_AT) = (int) "$at";
*(REGISTERS + REG_V0) = (int) "$v0";
*(REGISTERS + REG_V1) = (int) "$v1";
*(REGISTERS + REG_A0) = (int) "$a0";
*(REGISTERS + REG_A1) = (int) "$a1";
*(REGISTERS + REG_A2) = (int) "$a2";
*(REGISTERS + REG_A3) = (int) "$a3";
*(REGISTERS + REG_T0) = (int) "$t0";
*(REGISTERS + REG_T1) = (int) "$t1";
*(REGISTERS + REG_T2) = (int) "$t2";
*(REGISTERS + REG_T3) = (int) "$t3";
*(REGISTERS + REG_T4) = (int) "$t4";
*(REGISTERS + REG_T5) = (int) "$t5";
*(REGISTERS + REG_T6) = (int) "$t6";
*(REGISTERS + REG_T7) = (int) "$t7";
*(REGISTERS + REG_S0) = (int) "$s0";
*(REGISTERS + REG_S1) = (int) "$s1";
*(REGISTERS + REG_S2) = (int) "$s2";
*(REGISTERS + REG_S3) = (int) "$s3";
*(REGISTERS + REG_S4) = (int) "$s4";
*(REGISTERS + REG_S5) = (int) "$s5";
*(REGISTERS + REG_S6) = (int) "$s6";
*(REGISTERS + REG_S7) = (int) "$s7";
*(REGISTERS + REG_T8) = (int) "$t8";
*(REGISTERS + REG_T9) = (int) "$t9";
*(REGISTERS + REG_K0) = (int) "$k0";
*(REGISTERS + REG_K1) = (int) "$k1";
*(REGISTERS + REG_GP) = (int) "$gp";
*(REGISTERS + REG_SP) = (int) "$sp";
*(REGISTERS + REG_FP) = (int) "$fp";
*(REGISTERS + REG_RA) = (int) "$ra";
}
// -----------------------------------------------------------------
// ---------------------------- ENCODER ----------------------------
// -----------------------------------------------------------------
int encodeRFormat(int opcode, int rs, int rt, int rd, int function);
int encodeIFormat(int opcode, int rs, int rt, int immediate);
int encodeJFormat(int opcode, int instr_index);
// -----------------------------------------------------------------
// ---------------------------- DECODER ----------------------------
// -----------------------------------------------------------------
void initDecoder();
int getOpcode(int instruction);
int getRS(int instruction);
int getRT(int instruction);
int getRD(int instruction);
int getFunction(int instruction);
int getImmediate(int instruction);
int getInstrIndex(int instruction);
int signExtend(int immediate);
void decodeRFormat();
void decodeIFormat();
void decodeJFormat();
void decode();
void printOpcode(int opcode);
void printFunction(int function);
// ------------------------ GLOBAL CONSTANTS -----------------------
int OP_SPECIAL = 0;
int OP_J = 2;
int OP_JAL = 3;
int OP_BEQ = 4;
int OP_BNE = 5;
int OP_ADDIU = 9;
int OP_LW = 35;
int OP_SW = 43;
int* OPCODES; // strings representing MIPS opcodes
int FCT_NOP = 0;
int FCT_JR = 8;
int FCT_SYSCALL = 12;
int FCT_MFHI = 16;
int FCT_MFLO = 18;
int FCT_MULTU = 25;
int FCT_DIVU = 27;
int FCT_ADDU = 33;
int FCT_SUBU = 35;
int FCT_SLT = 42;
int* FUNCTIONS; // strings representing MIPS functions
// ------------------------ GLOBAL VARIABLES -----------------------
int opcode = 0;
int rs = 0;
int rt = 0;
int rd = 0;
int immediate = 0;
int function = 0;
int instr_index = 0;
// ------------------------- INITIALIZATION ------------------------
void initDecoder() {
OPCODES = malloc(44 * SIZEOFINTSTAR);
*(OPCODES + OP_SPECIAL) = (int) "nop";
*(OPCODES + OP_J) = (int) "j";
*(OPCODES + OP_JAL) = (int) "jal";
*(OPCODES + OP_BEQ) = (int) "beq";
*(OPCODES + OP_BNE) = (int) "bne";
*(OPCODES + OP_ADDIU) = (int) "addiu";
*(OPCODES + OP_LW) = (int) "lw";
*(OPCODES + OP_SW) = (int) "sw";
FUNCTIONS = malloc(43 * SIZEOFINTSTAR);
*(FUNCTIONS + FCT_NOP) = (int) "nop";
*(FUNCTIONS + FCT_JR) = (int) "jr";
*(FUNCTIONS + FCT_SYSCALL) = (int) "syscall";
*(FUNCTIONS + FCT_MFHI) = (int) "mfhi";
*(FUNCTIONS + FCT_MFLO) = (int) "mflo";
*(FUNCTIONS + FCT_MULTU) = (int) "multu";
*(FUNCTIONS + FCT_DIVU) = (int) "divu";
*(FUNCTIONS + FCT_ADDU) = (int) "addu";
*(FUNCTIONS + FCT_SUBU) = (int) "subu";
*(FUNCTIONS + FCT_SLT) = (int) "slt";
}
// -----------------------------------------------------------------
// ----------------------------- CODE ------------------------------
// -----------------------------------------------------------------
int loadBinary(int baddr);
void storeBinary(int baddr, int instruction);
void emitInstruction(int instruction);
void emitRFormat(int opcode, int rs, int rt, int rd, int function);
void emitIFormat(int opcode, int rs, int rt, int immediate);
void emitJFormat(int opcode, int instr_index);
void fixup_relative(int fromAddress);
void fixup_absolute(int fromAddress, int toAddress);
void fixlink_absolute(int fromAddress, int toAddress);
int copyStringToBinary(int* s, int a);
void emitGlobalsStrings();
int openWriteOnly(int* name);
void selfie_output();
int* touch(int* memory, int length);
void selfie_load();
// ------------------------ GLOBAL CONSTANTS -----------------------
int maxBinaryLength = 131072; // 128KB
// ------------------------ GLOBAL VARIABLES -----------------------
int* binary = (int*) 0; // binary of emitted instructions
int binaryLength = 0; // length of binary in bytes incl. globals & strings
int codeLength = 0; // length of code portion of binary in bytes
int* binaryName = (int*) 0; // file name of binary
int* sourceLineNumber = (int*) 0; // source line number per emitted instruction
int* assemblyName = (int*) 0; // name of assembly file
int assemblyFD = 0; // file descriptor of open assembly file
// -----------------------------------------------------------------
// ----------------------- MIPSTER SYSCALLS ------------------------
// -----------------------------------------------------------------
void emitExit();
void implementExit();
void emitRead();
void implementRead();
void emitWrite();
void implementWrite();
void emitOpen();
int down_loadString(int* table, int vaddr, int* s);
void implementOpen();
void emitMalloc();
void implementMalloc();
// ------------------------ GLOBAL CONSTANTS -----------------------
int debug_read = 0;
int debug_write = 0;
int debug_open = 0;
int debug_malloc = 0;
int SYSCALL_EXIT = 4001;
int SYSCALL_READ = 4003;
int SYSCALL_WRITE = 4004;
int SYSCALL_OPEN = 4005;
int SYSCALL_MALLOC = 4045;
// -----------------------------------------------------------------
// ----------------------- HYPSTER SYSCALLS ------------------------
// -----------------------------------------------------------------
void emitID();
void implementID();
int selfie_ID();
void emitCreate();
int doCreate(int parentID);
void implementCreate();
int selfie_create();
void emitSwitch();
int doSwitch(int toID);
void implementSwitch();
int mipster_switch(int toID);
int selfie_switch(int toID);
void emitStatus();
void implementStatus();
int selfie_status();
void emitDelete();
void doDelete(int ID);
void implementDelete();
void selfie_delete(int ID);
void emitMap();
void doMap(int ID, int page, int frame);
void implementMap();
void selfie_map(int ID, int page, int frame);
// ------------------------ GLOBAL CONSTANTS -----------------------
int debug_create = 0;
int debug_switch = 0;
int debug_status = 0;
int debug_delete = 0;
int debug_map = 0;
int SYSCALL_ID = 4901;
int SYSCALL_CREATE = 4902;
int SYSCALL_SWITCH = 4903;
int SYSCALL_STATUS = 4904;
int SYSCALL_DELETE = 4905;
int SYSCALL_MAP = 4906;
int mipster = 0; // flag for forcing to use mipster rather than hypster
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- E M U L A T O R ---------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ---------------------------- MEMORY -----------------------------
// -----------------------------------------------------------------
void initMemory(int megabytes);
int loadPhysicalMemory(int* paddr);
void storePhysicalMemory(int* paddr, int data);
int getFrameForPage(int* table, int page);
int isPageMapped(int* table, int page);
int isValidVirtualAddress(int vaddr);
int getPageOfVirtualAddress(int vaddr);
int isVirtualAddressMapped(int* table, int vaddr);
int* tlb(int* table, int vaddr);
int loadVirtualMemory(int* table, int vaddr);
void storeVirtualMemory(int* table, int vaddr, int data);
void mapAndStoreVirtualMemory(int* table, int vaddr, int data);
// ------------------------ GLOBAL CONSTANTS -----------------------
int debug_tlb = 0;
int MEGABYTE = 1048576;
int VIRTUALMEMORYSIZE = 67108864; // 64MB of virtual memory
int WORDSIZE = 4; // must be the same as SIZEOFINT and SIZEOFINTSTAR
int PAGESIZE = 4096; // we use standard 4KB pages
int PAGEBITS = 12; // 2^12 == 4096
// ------------------------ GLOBAL VARIABLES -----------------------
int pageFrameMemory = 0; // size of memory for frames in bytes
// ------------------------- INITIALIZATION ------------------------
void initMemory(int megabytes) {
if (megabytes < 0)
megabytes = 0;
else if (megabytes > 64)
megabytes = 64;
pageFrameMemory = megabytes * MEGABYTE;
}
// -----------------------------------------------------------------
// ------------------------- INSTRUCTIONS --------------------------
// -----------------------------------------------------------------
void fct_nop();
void fct_addu();
void fct_subu();
void fct_multu();
void fct_divu();
void fct_mfhi();
void fct_mflo();
void fct_slt();
void fct_jr();
void fct_syscall();
void op_addiu();
void op_lw();
void op_sw();
void op_beq();
void op_bne();
void op_jal();
void op_j();
// -----------------------------------------------------------------
// -------------------------- INTERPRETER --------------------------
// -----------------------------------------------------------------
void initInterpreter();
void resetInterpreter();
void printException(int exception);
int encodeException(int exception, int parameter);
int decodeExceptionNumber(int status);
int decodeExceptionParameter(int status);
void printStatus(int status);
void throwException(int exception, int parameter);