-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathselfie.c
5170 lines (3968 loc) · 132 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, 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 5k-line C implementation of:
//
// 1. a self-compiling compiler called cstarc 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 cstarc, and
// 3. a tiny C* library called libcstar utilized by cstarc and mipster.
//
// Selfie is kept minimal for simplicity and implemented in a single file.
// There is neither a linker nor an assembler. However, there is a simple
// profiler and disassembler and even a simple 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 data structures, bitwise and Boolean
// operators, and many other features. There are only signed 32-bit
// integers and pointers as well as character and string constants.
// This choice turns out to be helpful for students to understand the
// true role of composite data structures 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.
//
// 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.
int *selfieName = (int*) 0;
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- L I B R A R Y ---------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ----------------------- LIBRARY FUNCTIONS -----------------------
// -----------------------------------------------------------------
void initLibrary();
int twoToThePowerOf(int p);
int leftShift(int n, int b);
int rightShift(int n, int b);
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);
void putCharacter(int character);
void print(int *s);
void println();
void printCharacter(int character);
void printString(int *s);
void exit(int code);
int* malloc(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_HASH = '#';
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 *power_of_two_table;
int INT_MAX; // maximum numerical value of an integer
int INT_MIN; // minimum numerical value of an integer
int *character_buffer; // buffer for reading and writing characters
int *string_buffer; // buffer for string output
int *io_buffer; // buffer for binary I/O
// 0 = O_RDONLY (0x0000)
int O_RDONLY = 0;
// 577 = 0x0241 = O_CREAT (0x0040) | O_WRONLY (0x0001) | O_TRUNC (0x0200)
int O_CREAT_WRONLY_TRUNC = 577; // flags for opening write-only files
// 420 = 00644 = S_IRUSR (00400) | S_IWUSR (00200) | S_IRGRP (00040) | S_IROTH (00004)
int S_IRUSR_IWUSR_IRGRP_IROTH = 420; // flags for rw-r--r-- file permissions
// ------------------------ GLOBAL VARIABLES -----------------------
int *outputName = (int*) 0;
int outputFD = 1;
// ------------------------- INITIALIZATION ------------------------
void initLibrary() {
int i;
power_of_two_table = malloc(31*4);
*power_of_two_table = 1; // 2^0
i = 1;
while (i < 31) {
*(power_of_two_table + i) = *(power_of_two_table + (i - 1)) * 2;
i = i + 1;
}
// computing INT_MAX and INT_MIN without overflows
INT_MAX = (twoToThePowerOf(30) - 1) * 2 + 1;
INT_MIN = -INT_MAX - 1;
character_buffer = malloc(1);
// accommodate at least 32-bit numbers for itoa
string_buffer = malloc(33);
io_buffer = malloc(4);
}
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- 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 isCharacterWhitespace();
int findNextCharacter();
int isCharacterLetter();
int isCharacterDigit();
int isCharacterLetterOrDigitOrUnderscore();
int isNotDoubleQuoteOrEOF();
int identifierStringMatch(int stringIndex);
int identifierOrKeyword();
int 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; // array of 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 constant = 0; // stores numerical value of scanned integer or character
int initialValue = 0; // stores initial value of variable definitions
int mayBeINTMINConstant = 0; // support INT_MIN constant
int isINTMINConstant = 0;
int character; // most recently read character
int symbol; // most recently recognized symbol
int *sourceName = (int*) 0; // name of source file
int sourceFD = 0; // file descriptor of open source file
// ------------------------- INITIALIZATION ------------------------
void initScanner () {
SYMBOLS = malloc(28*4);
*(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;
getCharacter();
getSymbol();
}
// -----------------------------------------------------------------
// ------------------------- SYMBOL TABLE --------------------------
// -----------------------------------------------------------------
void resetGlobalSymbolTable();
void createSymbolTableEntry(int which, int *string, int line, int class, int type, int value, int reference);
int* getSymbolTableEntry(int *string, int class, int *symbol_table);
int isUndefinedProcedure(int *entry);
int reportUndefinedProcedures(int *symbol_table);
int* getNext(int *entry);
int* getString(int *entry);
int getLineNumber(int *entry);
int getClass(int *entry);
int getType(int *entry);
int getValue(int *entry);
int getReference(int *entry);
int getRegister(int *entry);
void setNext(int *entry, int *next);
void setString(int *entry, int *identifier);
void setLineNumber(int *entry, int line);
void setClass(int *entry, int class);
void setType(int *entry, int type);
void setValue(int *entry, int value);
void setReference(int *entry, int reference);
void setRegister(int *entry, int reg);
// ------------------------ GLOBAL CONSTANTS -----------------------
// classes
int VARIABLE = 1;
int FUNCTION = 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;
// ------------------------ GLOBAL VARIABLES -----------------------
// table pointers
int *global_symbol_table = (int*) 0;
int *local_symbol_table = (int*) 0;
// ------------------------- INITIALIZATION ------------------------
void resetGlobalSymbolTable() {
global_symbol_table = (int*) 0;
}
// -----------------------------------------------------------------
// ---------------------------- PARSER -----------------------------
// -----------------------------------------------------------------
int isNotRbraceOrEOF();
int isExpression();
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();
int* putType(int type);
void typeWarning(int expected, int found);
int* getVariable(int *variable);
int load_variable(int *variable);
void load_integer();
void load_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(int returnType);
void gr_statement();
int gr_type();
void gr_variable(int offset);
void gr_initialization(int *name, int offset, int type);
void gr_procedure(int *procedure, int returnType);
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 *currentProcedureName = (int*) 0; // name of currently parsed procedure
// -----------------------------------------------------------------
// ---------------------- MACHINE CODE LIBRARY ---------------------
// -----------------------------------------------------------------
void emitLeftShiftBy(int b);
void emitMainEntry();
// -----------------------------------------------------------------
// --------------------------- COMPILER ----------------------------
// -----------------------------------------------------------------
void compile();
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ------------------- I N T E R F A C E -------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ---------------------------- REGISTER ---------------------------
// -----------------------------------------------------------------
void initRegister();
void printRegister(int reg);
// ------------------------ GLOBAL CONSTANTS -----------------------
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; // array of strings representing registers
// ------------------------- INITIALIZATION ------------------------
void initRegister() {
REGISTERS = malloc(32*4);
*(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);
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);
// -----------------------------------------------------------------
// ---------------------------- DECODER ----------------------------
// -----------------------------------------------------------------
void initDecoder();
void printOpcode(int opcode);
void printFunction(int function);
void decode();
void decodeRFormat();
void decodeIFormat();
void decodeJFormat();
// ------------------------ 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; // array of 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 FCT_TEQ = 52;
int *FUNCTIONS; // array of 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*4);
*(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(53*4);
*(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";
*(FUNCTIONS + FCT_TEQ) = (int) "teq";
}
// -----------------------------------------------------------------
// ----------------------------- CODE ------------------------------
// -----------------------------------------------------------------
int loadBinary(int addr);
void storeBinary(int addr, int instruction);
void storeInstruction(int addr, 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();
void emit();
void 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
// -----------------------------------------------------------------
// --------------------------- SYSCALLS ----------------------------
// -----------------------------------------------------------------
void emitExit();
void syscall_exit();
void emitRead();
void syscall_read();
void emitWrite();
void syscall_write();
void emitOpen();
void syscall_open();
void emitMalloc();
void syscall_malloc();
void emitPutchar();
// ------------------------ GLOBAL CONSTANTS -----------------------
int SYSCALL_EXIT = 4001;
int SYSCALL_READ = 4003;
int SYSCALL_WRITE = 4004;
int SYSCALL_OPEN = 4005;
int SYSCALL_MALLOC = 5001;
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- E M U L A T O R ---------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ---------------------------- MEMORY -----------------------------
// -----------------------------------------------------------------
void initMemory(int bytes);
int tlb(int vaddr);
int loadMemory(int vaddr);
void storeMemory(int vaddr, int data);
// ------------------------ GLOBAL CONSTANTS -----------------------
int MEGABYTE = 1048576;
// ------------------------ GLOBAL VARIABLES -----------------------
int memorySize = 0; // size of memory in bytes
int *memory = (int*) 0; // mipster memory
// ------------------------- INITIALIZATION ------------------------
void initMemory(int bytes) {
if (bytes < 0)
memorySize = 64 * MEGABYTE;
else if (bytes > 1024 * MEGABYTE)
memorySize = 1024 * MEGABYTE;
else
memorySize = bytes;
memory = malloc(memorySize);
}
// -----------------------------------------------------------------
// ------------------------- INSTRUCTIONS --------------------------
// -----------------------------------------------------------------
void fct_syscall();
void fct_nop();
void op_jal();
void op_j();
void op_beq();
void op_bne();
void op_addiu();
void fct_jr();
void fct_mfhi();
void fct_mflo();
void fct_multu();
void fct_divu();
void fct_addu();
void fct_subu();
void op_lw();
void fct_slt();
void op_sw();
void fct_teq();
// -----------------------------------------------------------------
// -------------------------- INTERPRETER --------------------------
// -----------------------------------------------------------------
void initInterpreter();
void resetInterpreter();
void printException(int enumber);
void exception_handler(int enumber);
void fetch();
void execute();
void run();
void up_push(int value);
int up_malloc(int size);
int up_copyString(int *s);
void up_copyArguments(int argc, int *argv);
void copyBinaryToMemory();
int addressWithMaxCounter(int *counters, int max);
int fixedPointRatio(int a, int b);
int printCounters(int total, int *counters, int max);
void printProfile(int *message, int total, int *counters);
void disassemble();
void emulate(int argc, int *argv);
// ------------------------ GLOBAL CONSTANTS -----------------------
int debug_read = 0;
int debug_write = 0;
int debug_open = 0;
int debug_malloc = 0;
int EXCEPTION_SIGNAL = 1;
int EXCEPTION_ADDRESSERROR = 2;
int EXCEPTION_UNKNOWNINSTRUCTION = 3;
int EXCEPTION_HEAPOVERFLOW = 4;
int EXCEPTION_UNKNOWNSYSCALL = 5;
int EXCEPTION_UNKNOWNFUNCTION = 6;
int *EXCEPTIONS; // array of strings representing exceptions
// ------------------------ GLOBAL VARIABLES -----------------------
int *registers; // general purpose registers
int pc = 0; // program counter
int ir = 0; // instruction record
int reg_hi = 0; // hi register for multiplication/division
int reg_lo = 0; // lo register for multiplication/division
int halt = 0; // flag for halting mipster
int interpret = 0;
int debug = 0;
int calls = 0; // total number of executed procedure calls
int *callsPerAddress = (int*) 0; // number of executed calls of each procedure
int loops = 0; // total number of executed loop iterations
int *loopsPerAddress = (int*) 0; // number of executed iterations of each loop
int loads = 0; // total number of executed memory loads
int *loadsPerAddress = (int*) 0; // number of executed loads per load operation
int stores = 0; // total number of executed memory stores
int *storesPerAddress = (int*) 0; // number of executed stores per store operation
// ------------------------- INITIALIZATION ------------------------
void initInterpreter() {
EXCEPTIONS = malloc(7*4);
*(EXCEPTIONS + EXCEPTION_SIGNAL) = (int) "signal";
*(EXCEPTIONS + EXCEPTION_ADDRESSERROR) = (int) "address error";
*(EXCEPTIONS + EXCEPTION_UNKNOWNINSTRUCTION) = (int) "unknown instruction";
*(EXCEPTIONS + EXCEPTION_HEAPOVERFLOW) = (int) "heap overflow";
*(EXCEPTIONS + EXCEPTION_UNKNOWNSYSCALL) = (int) "unknown syscall";
*(EXCEPTIONS + EXCEPTION_UNKNOWNFUNCTION) = (int) "unknown function";
registers = malloc(32*4);
}
void resetInterpreter() {
pc = 0;
reg_hi = 0;
reg_lo = 0;
if (interpret) {
calls = 0;
callsPerAddress = malloc(maxBinaryLength);
loops = 0;
loopsPerAddress = malloc(maxBinaryLength);
loads = 0;
loadsPerAddress = malloc(maxBinaryLength);
stores = 0;
storesPerAddress = malloc(maxBinaryLength);
}
}
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// --------------------- L I B R A R Y ---------------------
// -----------------------------------------------------------------
// *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~ *~*~
// -----------------------------------------------------------------
// ----------------------- LIBRARY FUNCTIONS -----------------------
// -----------------------------------------------------------------
int twoToThePowerOf(int p) {
// assert: 0 <= p < 31
return *(power_of_two_table + p);
}
int leftShift(int n, int b) {
// assert: b >= 0;
if (b > 30)
return 0;
else
return n * twoToThePowerOf(b);
}
int rightShift(int n, int b) {
// assert: b >= 0
if (b > 30)
return 0;
else if (n >= 0)
return n / twoToThePowerOf(b);
else
// works even if n == INT_MIN:
// shift right n with msb reset and then restore msb
return ((n + 1) + INT_MAX) / twoToThePowerOf(b) +
(INT_MAX / twoToThePowerOf(b) + 1);
}
int loadCharacter(int *s, int i) {
// assert: i >= 0
int a;
a = i / 4;
return rightShift(leftShift(*(s + a), 24 - (i % 4) * 8), 24);
}
int* storeCharacter(int *s, int i, int c) {
// assert: i >= 0, all characters are 7-bit
int a;
a = i / 4;
*(s + a) = (*(s + a) - leftShift(loadCharacter(s, i), (i % 4) * 8)) + leftShift(c, (i % 4) * 8);
return s;
}
int stringLength(int *s) {
int i;
i = 0;
while (loadCharacter(s, i) != 0)
i = i + 1;
return i;
}
void stringReverse(int *s) {
int i;
int j;
int tmp;
i = 0;
j = stringLength(s) - 1;
while (i < j) {
tmp = loadCharacter(s, i);
storeCharacter(s, i, loadCharacter(s, j));
storeCharacter(s, j, tmp);
i = i + 1;
j = j - 1;
}
}
int stringCompare(int *s, int *t) {
int i;
i = 0;
while (1)
if (loadCharacter(s, i) == 0)
if (loadCharacter(t, i) == 0)
return 1;
else
return 0;
else if (loadCharacter(s, i) == loadCharacter(t, i))
i = i + 1;
else
return 0;
}
int atoi(int *s) {
int i;
int n;
int c;
i = 0;
n = 0;
c = loadCharacter(s, i);
while (c != 0) {
c = c - '0';
if (c < 0)
return -1;
else if (c > 9)