forked from jserv/amacc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamacc.c
1707 lines (1611 loc) · 58.9 KB
/
amacc.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
// Another Mini ARM C Compiler (AMaCC)
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
char *p, *lp; // current position in source code
char *data, *_data; // data/bss pointer
char *ops; // opcodes
int *e, *le, *text; // current position in emitted code
int *cas; // case statement patch-up pointer
int *brks; // break statement patch-up pointer
int *def; // default statement patch-up pointer
int *tsize; // array (indexed by type) of type sizes
int tnew; // next available type
int tk; // current token
int ival; // current token value
int ty; // current expression type
int loc; // local variable offset
int line; // current line number
int src; // print source and assembly flag
int verbose; // print executed instructions
int elf; // print ELF format
int elf_fd;
int rodata_align_off;
// identifier
struct ident_s {
int tk;
int hash;
char *name;
int class;
int type;
int val;
int stype;
int hclass;
int htype;
int hval;
} *id, // currently parsed identifier
*sym; // symbol table (simple list of identifiers)
struct member_s {
struct ident_s *id;
int offset;
int type;
struct member_s *next;
} **members; // array (indexed by type) of struct member lists
// tokens and classes (operators last and in precedence order)
enum {
Num = 128, Fun, Sys, Glo, Loc, Id,
Break, Case, Char, Default, Else, Enum, If, Int, Return, Sizeof,
Struct, Switch, For, While,
Assign, Cond,
Lor, Lan, Or, Xor, And,
Eq, Ne, Lt, Gt, Le, Ge,
Shl, Shr, Add, Sub, Mul, Inc, Dec, Dot, Arrow, Brak
};
// opcodes
enum {
LEA ,IMM ,JMP ,JSR ,BZ ,BNZ ,ENT ,ADJ ,LEV ,LI ,LC ,SI ,SC ,PSH ,
OR ,XOR ,AND ,EQ ,NE ,LT ,GT ,LE ,GE ,SHL ,SHR ,ADD ,SUB ,MUL ,
OPEN,READ,WRIT,CLOS,PRTF,MALC,MSET,MCMP,MCPY,MMAP,DSYM,BSCH,CLCA,EXIT
};
// types
enum { CHAR, INT, PTR = 256, PTR2 = 512 };
// ELF generation
char **plt_func_addr;
void next()
{
char *pp;
while ((tk = *p)) {
++p;
if ((tk >= 'a' && tk <= 'z') || (tk >= 'A' && tk <= 'Z') ||
(tk == '_')) {
pp = p - 1;
while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') || (*p == '_'))
tk = tk * 147 + *p++;
tk = (tk << 6) + (p - pp);
id = sym;
while (id->tk) {
if (tk == id->hash &&
!memcmp(id->name, pp, p - pp)) {
tk = id->tk;
return;
}
id = id + 1;
}
id->name = pp;
id->hash = tk;
tk = id->tk = Id;
return;
}
else if (tk >= '0' && tk <= '9') {
if ((ival = tk - '0')) {
while (*p >= '0' && *p <= '9')
ival = ival * 10 + *p++ - '0';
}
else if (*p == 'x' || *p == 'X') {
while ((tk = *++p) &&
((tk >= '0' && tk <= '9') ||
(tk >= 'a' && tk <= 'f') ||
(tk >= 'A' && tk <= 'F')))
ival = ival * 16 + (tk & 15) + (tk >= 'A' ? 9 : 0);
}
else {
while (*p >= '0' && *p <= '7')
ival = ival * 8 + *p++ - '0';
}
tk = Num;
return;
}
switch (tk) {
case '\n':
if (src) {
printf("%d: %.*s", line, p - lp, lp);
lp = p;
while (le < e) {
printf("%8.4s", &ops[*++le * 5]);
if (*le <= ADJ) printf(" %d\n", *++le); else printf("\n");
}
}
++line;
case ' ':
case '\t':
case '\v':
case '\f':
case '\r':
break;
case '/':
if (*p == '/') { // comment
case '#':
while (*p != 0 && *p != '\n') ++p;
} else {
// Div is not supported
return;
}
break;
case '\'':
case '"':
pp = data;
while (*p != 0 && *p != tk) {
if ((ival = *p++) == '\\') {
switch (ival = *p++) {
case 'n': ival = '\n'; break;
case 't': ival = '\t'; break;
case 'v': ival = '\v'; break;
case 'f': ival = '\f'; break;
case 'r': ival = '\r';
}
}
if (tk == '"') *data++ = ival;
}
++p;
// if .text too big rodata v_addr will overlap it, add that to stay away from .text
if (tk == '"') ival = (int) pp; else tk = Num;
return;
case '=': if (*p == '=') { ++p; tk = Eq; } else tk = Assign; return;
case '+': if (*p == '+') { ++p; tk = Inc; } else tk = Add; return;
case '-': if (*p == '-') { ++p; tk = Dec; }
else if (*p == '>') { ++p; tk = Arrow; }
else tk = Sub; return;
case '!': if (*p == '=') { ++p; tk = Ne; } return;
case '<': if (*p == '=') { ++p; tk = Le; }
else if (*p == '<') { ++p; tk = Shl; }
else tk = Lt; return;
case '>': if (*p == '=') { ++p; tk = Ge; }
else if (*p == '>') { ++p; tk = Shr; }
else tk = Gt; return;
case '|': if (*p == '|') { ++p; tk = Lor; }
else tk = Or; return;
case '&': if (*p == '&') { ++p; tk = Lan; }
else tk = And; return;
case '^': tk = Xor; return;
case '*': tk = Mul; return;
case '[': tk = Brak; return;
case '?': tk = Cond; return;
case '.': tk = Dot; return;
default: return;
}
}
}
char fatal(char *msg) { printf("%d: %s\n", line, msg); exit(-1); }
void expr(int lev)
{
int t, *b, sz;
struct ident_s *d;
struct member_s *m;
switch (tk) {
case 0: fatal("unexpected eof in expression");
case Num: *++e = IMM; *++e = ival; next(); ty = INT; break;
case '"':
*++e = IMM; *++e = ival; next();
while (tk == '"') next();
data = (char *)(((int) data + sizeof(int)) & (-sizeof(int)));
ty = PTR;
break;
case Sizeof:
next();
if (tk == '(')
next();
else fatal("open paren expected in sizeof");
ty = INT;
switch (tk) {
case Int: next(); break;
case Char: next(); ty = CHAR; break;
case Struct:
next();
if (tk != Id) fatal("bad struct type");
ty = id->stype; next(); break;
}
while (tk == Mul) { next(); ty = ty + PTR; }
if (tk == ')')
next();
else fatal("close paren expected in sizeof");
*++e = IMM; *++e = ty >= PTR ? sizeof(int) : tsize[ty];
ty = INT;
break;
case Id:
d = id; next();
if (tk == '(') {
next();
t = 0;
while (tk != ')') {
expr(Assign); *++e = PSH; ++t;
if (tk == ',') next();
}
next();
switch (d->class) {
case Sys: *++e = d->val; break;
case Fun: *++e = JSR; *++e = d->val; break;
default: fatal("bad function call");
}
if (t) { *++e = ADJ; *++e = t; }
ty = d->type;
}
else if (d->class == Num) { *++e = IMM; *++e = d->val; ty = INT; }
else {
switch (d->class) {
case Loc: *++e = LEA; *++e = loc - d->val; break;
case Glo: *++e = IMM; *++e = d->val; break;
default: fatal("undefined variable");
}
if ((ty = d->type) <= INT || ty >= PTR)
*++e = (ty == CHAR) ? LC : LI;
}
break;
case '(':
next();
if (tk == Int || tk == Char || tk == Struct) {
switch (tk) {
case Int: next(); t = INT; break;
case Char: next(); t = CHAR; break;
default:
next();
if (tk != Id) fatal("bad struct type");
t = id->stype; next(); break;
}
while (tk == Mul) { next(); t = t + PTR; }
if (tk == ')') next();
else fatal("bad cast");
expr(Inc);
ty = t;
}
else {
expr(Assign);
if (tk == ')') next();
else fatal("close paren expected");
}
break;
case Mul:
next(); expr(Inc);
if (ty > INT) ty = ty - PTR;
else fatal("bad dereference");
if (ty <= INT || ty >= PTR) *++e = (ty == CHAR) ? LC : LI;
break;
case And:
next(); expr(Inc);
if (*e == LC || *e == LI) --e;
ty = ty + PTR;
break;
case '!':
next(); expr(Inc);
*++e = PSH; *++e = IMM; *++e = 0; *++e = EQ; ty = INT;
break;
case '~':
next(); expr(Inc);
*++e = PSH; *++e = IMM; *++e = -1; *++e = XOR; ty = INT;
break;
case Add:
next(); expr(Inc); ty = INT;
break;
case Sub:
next(); *++e = IMM;
if (tk == Num) { *++e = -ival; next(); }
else { *++e = -1; *++e = PSH; expr(Inc); *++e = MUL; }
ty = INT;
break;
case Inc:
case Dec:
t = tk; next(); expr(Inc);
switch (*e) {
case LC: *e = PSH; *++e = LC; break;
case LI: *e = PSH; *++e = LI; break;
default: fatal("bad lvalue in pre-increment");
}
*++e = PSH;
*++e = IMM;
*++e = ty >= PTR2 ? sizeof(int) :
(ty >= PTR) ? tsize[ty - PTR] : 1;
*++e = (t == Inc) ? ADD : SUB;
*++e = (ty == CHAR) ? SC : SI;
break;
default: fatal("bad expression");
}
while (tk >= lev) { // top down operator precedence
t = ty;
switch (tk) {
case Assign:
next();
if (*e == LC || *e == LI) *e = PSH;
else fatal("bad lvalue in assignment");
expr(Assign); *++e = ((ty = t) == CHAR) ? SC : SI;
break;
case Cond:
next();
*++e = BZ; b = ++e;
expr(Assign);
if (tk == ':') next();
else fatal("conditional missing colon");
*b = (int)(e + 3); *++e = JMP; b = ++e;
expr(Cond);
*b = (int)(e + 1);
break;
case Lor:
next(); *++e = BNZ; b = ++e;
expr(Lan); *b = (int)(e + 1); ty = INT;
break;
case Lan: next(); *++e = BZ; b = ++e;
expr(Or); *b = (int)(e + 1); ty = INT;
break;
case Or: next(); *++e = PSH;
expr(Xor); *++e = OR; ty = INT;
break;
case Xor: next(); *++e = PSH;
expr(And); *++e = XOR; ty = INT;
break;
case And: next(); *++e = PSH;
expr(Eq); *++e = AND; ty = INT;
break;
case Eq:
next(); *++e = PSH;
expr(Lt); *++e = EQ; ty = INT;
break;
case Ne:
next(); *++e = PSH;
expr(Lt); *++e = NE; ty = INT;
break;
case Lt: next(); *++e = PSH;
expr(Shl); *++e = LT; ty = INT;
break;
case Gt: next(); *++e = PSH; expr(Shl); *++e = GT; ty = INT; break;
case Le: next(); *++e = PSH; expr(Shl); *++e = LE; ty = INT; break;
case Ge: next(); *++e = PSH; expr(Shl); *++e = GE; ty = INT; break;
case Shl: next(); *++e = PSH; expr(Add); *++e = SHL; ty = INT; break;
case Shr: next(); *++e = PSH; expr(Add); *++e = SHR; ty = INT; break;
case Add:
next(); *++e = PSH; expr(Mul);
sz = (ty = t) >= PTR2 ? sizeof(int) :
ty >= PTR ? tsize[ty - PTR] : 1;
if (sz > 1) { *++e = PSH; *++e = IMM; *++e = sz; *++e = MUL; }
*++e = ADD;
break;
case Sub:
next(); *++e = PSH; expr(Mul);
sz = t >= PTR2 ? sizeof(int) :
t >= PTR ? tsize[t - PTR] : 1;
if (t == ty && sz > 1) {
*++e = SUB; *++e = PSH; *++e = IMM; *++e = sz; *++e = SUB;
ty = INT;
} else if (sz > 1) {
*++e = PSH; *++e = IMM; *++e = sz; *++e = MUL; *++e = SUB;
} else *++e = SUB;
ty = t;
break;
case Mul:
next(); *++e = PSH; expr(Inc); *++e = MUL; ty = INT;
break;
case Inc:
case Dec:
if (*e == LC) { *e = PSH; *++e = LC; }
else if (*e == LI) { *e = PSH; *++e = LI; }
else fatal("bad lvalue in post-increment");
sz = ty >= PTR2 ? sizeof(int) :
ty >= PTR ? tsize[ty - PTR] : 1;
*++e = PSH; *++e = IMM; *++e = sz;
*++e = (tk == Inc) ? ADD : SUB;
*++e = (ty == CHAR) ? SC : SI;
*++e = PSH; *++e = IMM; *++e = sz;
*++e = (tk == Inc) ? SUB : ADD;
next();
break;
case Dot:
ty = ty + PTR;
case Arrow:
if (ty <= PTR+INT || ty >= PTR2) fatal("structure expected");
next();
if (tk != Id) fatal("structure member expected");
m = members[ty - PTR]; while (m && m->id != id) m = m->next;
if (!m) fatal("structure member not found");
if (m->offset) {
*++e = PSH; *++e = IMM; *++e = m->offset; *++e = ADD;
}
ty = m->type;
if (ty <= INT || ty >= PTR) *++e = (ty == CHAR) ? LC : LI;
next();
break;
case Brak:
next(); *++e = PSH; expr(Assign);
if (tk == ']') next();
else fatal("close bracket expected");
if (t < PTR) fatal("pointer type expected");
sz = (t = t - PTR) >= PTR ? sizeof(int) : tsize[t];
if (sz > 1) { *++e = PSH; *++e = IMM; *++e = sz; *++e = MUL; }
*++e = ADD;
if ((ty = t) <= INT || ty >= PTR) *++e = (ty == CHAR) ? LC : LI;
break;
default:
printf("%d: compiler error tk=%d\n", line, tk); exit(-1);
}
}
}
void stmt()
{
int *a, *b, *d;
int *x, *y, *z;
int i;
switch (tk) {
case If:
next();
if (tk == '(') next();
else fatal("open paren expected");
expr(Assign);
if (tk == ')') next();
else fatal("close paren expected");
*++e = BZ; b = ++e;
stmt();
if (tk == Else) {
*b = (int)(e + 3); *++e = JMP; b = ++e;
next();
stmt();
}
*b = (int)(e + 1);
return;
case While:
next();
a = e + 1;
if (tk == '(') next();
else fatal("open paren expected");
expr(Assign);
if (tk == ')') next();
else fatal("close paren expected");
*++e = BZ; b = ++e;
stmt();
*++e = JMP; *++e = (int)a;
*b = (int)(e + 1);
return;
case Switch:
next();
if (tk == '(') next();
else fatal("open paren expected");
expr(Assign);
if (tk == ')') next();
else fatal("close paren expected");
a = cas; *++e = JMP; cas = ++e;
b = brks; d = def; brks = def = 0;
stmt();
*cas = def ? (int)def : (int)(e + 1); cas = a;
while (brks) { a = (int *)*brks; *brks = (int)(e + 1); brks = a; }
brks = b; def = d;
return;
case Case:
*++e = JMP; ++e;
*e = (int)(e + 7); *++e = PSH; i = *cas; *cas = (int)e;
next();
expr(Or);
if (e[-1] != IMM) fatal("bad case immediate");
*e = *e - i; *++e = SUB; *++e = BNZ; cas = ++e; *e = i + e[-3];
if (tk == ':') next();
else fatal("colon expected");
stmt();
return;
case Break:
next();
if (tk == ';') next();
else fatal("semicolon expected");
*++e = JMP; *++e = (int)brks; brks = e;
return;
case Default:
next();
if (tk == ':') next();
else fatal("colon expected");
def = e + 1;
stmt();
return;
case Return:
next();
if (tk != ';') expr(Assign);
*++e = LEV;
if (tk == ';') next();
else fatal("semicolon expected");
return;
case For:
next();
if (tk == '(') next();
else fatal("open paren expected");
expr(Assign);
while (tk == ',') {
next();
expr(Assign);
}
if (tk == ';') next();
else fatal("semicolon expected");
a = e + 1;
expr(Assign);
if (tk == ';') next();
else fatal("semicolon expected");
*++e = BZ; b = ++e;
x = e + 1; // Points to entry of for loop afterthought
expr(Assign);
while (tk == ',') {
next();
expr(Assign);
}
if (tk == ')') next();
else fatal("close paren expected");
y = e + 1; // Points to entry of for loop body
stmt();
z = e + 1; // Points to entry of jmp command
*++e = JMP; *++e = (int) a;
*b = (int) (e + 1);
// Swaps body chunk and afterthought chunk
//
// We parse it as:
// Init -> Cond -> Bz -> After -> Body -> Jmp
//
// But we want it to be:
// Init -> Cond -> Bz -> Body -> After -> Jmp
memcpy((void *) ((int) e + 4), x, (int) y - (int) x);
memcpy(x, y, (int) z - (int) y);
memcpy((void *) ((int) x + (int) z - (int) y),
(void *) ((int) e + 4), (int)y - (int) x);
memset((void *) ((int) e + 4), 0, (int)y - (int) x);
return;
case '{':
next();
while (tk != '}') stmt();
next();
return;
case ';':
next();
return;
default:
expr(Assign);
if (tk == ';') next();
else fatal("semicolon expected");
}
}
void die(char *msg) { printf("codegen: %s\n", msg); exit(2); }
int *codegen(int *jitmem, int *jitmap, int reloc)
{
int *pc;
int i, tmp, genpool;
int *je, *tje; // current position in emitted native code
int *immloc, *il, *iv, *imm0;
char neg_char;
int neg_int;
immloc = il = malloc(1024 * 4);
iv = malloc(1024 * 4);
imm0 = 0;
genpool = 0;
neg_char = 255;
neg_int = neg_char;
// first pass: emit native code
pc = text + 1; je = jitmem; line = 0;
while (pc <= e) {
i = *pc;
if (verbose) {
printf("%p -> %p: %8.4s", pc, je, &ops[i * 5]);
if (i <= ADJ) printf(" %d\n", pc[1]); else printf("\n");
}
jitmap[((int) pc++ - (int) text) >> 2] = (int) je;
switch (i) {
case LEA:
tmp = *pc++;
if (tmp >= 64 || tmp <= -64) {
printf("jit: LEA %d out of bounds\n", tmp); exit(6);
}
if (tmp >= 0)
*je++ = 0xe28b0000 | tmp * 4; // add r0, fp, #(tmp)
else
*je++ = 0xe24b0000 | (-tmp) * 4; // sub r0, fp, #(tmp)
break;
case IMM:
tmp = *pc++;
if (0 <= tmp && tmp < 256)
*je++ = 0xe3a00000 + tmp; // mov r0, #(tmp)
else { if (!imm0) imm0 = je; *il++ = (int)(je++); *iv++ = tmp;}
break;
case JSR:
case JMP:
pc++; je++; // postponed till second pass
break;
case BZ:
case BNZ:
*je++ = 0xe3500000; pc++; je++; // cmp r0, #0
break;
case ENT:
*je++ = 0xe92d4800; *je++ = 0xe28db000; // push {fp, lr}; add fp, sp, #0
tmp = *pc++; if (tmp) *je++ = 0xe24dd000 | (tmp * 4); // sub sp, sp, #(tmp * 4)
if (tmp >= 64 || tmp < 0) {
printf("jit: ENT %d out of bounds\n", tmp); exit(6);
}
break;
case ADJ:
*je++ = 0xe28dd000 + *pc++ * 4; // add sp, sp, #(tmp * 4)
break;
case LEV:
*je++ = 0xe28bd000; *je++ = 0xe8bd8800; // add sp, fp, #0; pop {fp, pc}
break;
case LI:
*je++ = 0xe5900000; // ldr r0, [r0]
break;
case LC:
*je++ = 0xe5d00000; if (neg_int < 0) *je++ = 0xe6af0070; // ldrb r0, [r0]; (sxtb r0, r0)
break;
case SI:
*je++ = 0xe49d1004; *je++ = 0xe5810000; // pop {r1}; str r0, [r1]
break;
case SC:
*je++ = 0xe49d1004; *je++ = 0xe5c10000; // pop {r1}; strb r0, [r1]
break;
case PSH:
*je++ = 0xe52d0004; // push {r0}
break;
case OR:
*je++ = 0xe49d1004; *je++ = 0xe1810000; // pop {r1}; orr r0, r1, r0
break;
case XOR:
*je++ = 0xe49d1004; *je++ = 0xe0210000; // pop {r1}; eor r0, r1, r0
break;
case AND:
*je++ = 0xe49d1004; *je++ = 0xe0010000; // pop {r1}; and r0, r1, r0
break;
case SHL:
*je++ = 0xe49d1004; *je++ = 0xe1a00011; // pop {r1}; lsl r0, r1, r0
break;
case SHR:
*je++ = 0xe49d1004; *je++ = 0xe1a00051; // pop {r1}; asr r0, r1, r0
break;
case ADD:
*je++ = 0xe49d1004; *je++ = 0xe0800001; // pop {r1}; add r0, r0, r1
break;
case SUB:
*je++ = 0xe49d1004; *je++ = 0xe0410000; // pop {r1}; sub r0, r1, r0
break;
case MUL:
*je++ = 0xe49d1004; *je++ = 0xe0000091; // pop {r1}; mul r0, r1, r0
break;
case CLCA:
*je++ = 0xe59d0004; *je++ = 0xe59d1000; // ldr r0, [sp, #4]
// ldr r1, [sp]
*je++ = 0xe3a0780f; *je++ = 0xe2877002; // mov r7, #0xf0000
// add r7, r7, #2
*je++ = 0xe3a02000; *je++ = 0xef000000; // mov r2, #0
// svc 0
break;
default:
if (EQ <= i && i <= GE) {
*je++ = 0xe49d1004; *je++ = 0xe1510000; // pop {r1}; cmp r1, r0
if (i <= NE) { je[0] = 0x03a00000; je[1] = 0x13a00000; } // moveq r0, #0; movne r0, #0
else if (i == LT || i == GE) { je[0] = 0xb3a00000; je[1] = 0xa3a00000; } // movlt r0, #0; movge r0, #0
else { je[0] = 0xc3a00000; je[1] = 0xd3a00000; } // movgt r0, #0; movle r0, #0
if (i == EQ || i == LT || i == GT) je[0] = je[0] | 1;
else je[1] = je[1] | 1;
je = je + 2;
break;
}
else if (i >= OPEN) {
switch (i) {
case OPEN:
tmp = (int) (elf ? plt_func_addr[0] : dlsym(0, "open"));
break;
case READ:
tmp = (int) (elf ? plt_func_addr[1] : dlsym(0, "read"));
break;
case WRIT:
tmp = (int) (elf ? plt_func_addr[2] : dlsym(0, "write"));
break;
case CLOS:
tmp = (int) (elf ? plt_func_addr[3] : dlsym(0, "close"));
break;
case PRTF:
tmp = (int) (elf ? plt_func_addr[4] : dlsym(0, "printf"));
break;
case MALC:
tmp = (int) (elf ? plt_func_addr[5] : dlsym(0, "malloc"));
break;
case MSET:
tmp = (int) (elf ? plt_func_addr[6] : dlsym(0, "memset"));
break;
case MCMP:
tmp = (int) (elf ? plt_func_addr[7] : dlsym(0, "memcmp"));
break;
case MCPY:
tmp = (int) (elf ? plt_func_addr[8] : dlsym(0, "memcpy"));
break;
case MMAP:
tmp = (int) (elf ? plt_func_addr[9] : dlsym(0, "mmap"));
break;
case DSYM:
tmp = (int) (elf ? plt_func_addr[10] : dlsym(0, "dlsym"));
break;
case BSCH:
tmp = (int) (elf ? plt_func_addr[11] : dlsym(0, "bsearch"));
break;
case EXIT:
tmp = (int) (elf ? plt_func_addr[13] : dlsym(0, "exit"));
break;
default:
printf("unrecognized code %d\n", i);
return 0;
}
if (*pc++ != ADJ) die("no ADJ after native proc!");
i = *pc;
if (i > 10) die("no support for 10+ arguments!");
while (i > 0) *je++ = 0xe49d0004 | (--i << 12); // pop r(i-1)
i = *pc++;
if (i > 4) *je++ = 0xe92d03f0; // push {r4-r9}
*je++ = 0xe28fe000; // add lr, pc, #0
if (!imm0) imm0 = je;
*il++ = (int)je++ + 1;
*iv++ = tmp;
if (i > 4) *je++ = 0xe28dd018; // add sp, sp, #24
break;
}
else { printf("code generation failed for %d!\n", i); return 0; }
}
if (imm0) {
if (i == LEV) genpool = 1;
else if ((int) je > (int) imm0 + 3000) {
tje = je++; genpool = 2;
}
}
if (genpool) {
if (verbose) printf("POOL %d %d %d\n", genpool,
il - immloc, je - imm0);
*iv = 0;
while (il > immloc) {
tmp = *--il;
if ((int) je > tmp + 4096 + 8) die("can't reach the pool");
iv--; if (iv[0] == iv[1]) je--;
if (tmp & 1)
*(int *) (tmp - 1) = 0xe59ff000 | ((int) je - tmp - 7);
// ldr pc, [pc, #..]
else
*(int *) tmp = 0xe59f0000 | ((int) je - tmp - 8);
// ldr r0, [pc, #..]
*je++ = *iv;
}
if (genpool == 2) { // jump past the pool
tmp = ((int) je - (int) tje - 8) >> 2;
*tje = 0xea000000 | (tmp & 0x00ffffff); // b #(je)
}
imm0 = 0;
genpool = 0;
}
}
if (il > immloc) die("code is not terminated by a LEV");
tje = je;
// second pass
pc = text + 1;
while (pc <= e) {
je = (int *) jitmap[((int) pc - (int) text) >> 2]; i = *pc++;
if (i == JSR || i == JMP || i == BZ || i == BNZ) {
switch (i) {
case JSR:
*je = 0xeb000000; // bl #(tmp)
break;
case JMP:
*je = 0xea000000; // bl #(tmp)
break;
case BZ:
*++je = 0x0a000000; // beq #(tmp)
break;
case BNZ:
*++je = 0x1a000000; // bne #(tmp)
break;
}
tmp = *pc++;
*je = *je |
(((jitmap[(tmp - (int) text) >> 2] - (int) je - 8) >> 2) &
0x00ffffff);
}
else if (i < LEV) { ++pc; }
}
return tje;
}
enum {
_PROT_EXEC = 4, _PROT_READ = 1, _PROT_WRITE = 2,
_MAP_PRIVATE = 2, _MAP_ANON = 32
};
int jit(int poolsz, int *start, int argc, char **argv)
{
char *jitmem; // executable memory for JIT-compiled native code
int *je, *tje, *_start, retval, *jitmap, *res;
// setup JIT memory
jitmem = mmap(0, poolsz, _PROT_EXEC | _PROT_READ | _PROT_WRITE,
_MAP_PRIVATE | _MAP_ANON, -1, 0);
if (!jitmem) {
printf("could not mmap(%d) jit executable memory\n", poolsz);
return -1;
}
if (src) return 1;
jitmap = (int *) (jitmem + (poolsz >> 1));
je = (int *) jitmem;
*je++ = (int) &retval;
*je++ = argc;
*je++ = (int) argv;
_start = je;
*je++ = 0xe92d5ff0; // push {r4-r12, lr}
*je++ = 0xe51f0014; // ldr r0, [pc, #-20] ; argc
*je++ = 0xe51f1014; // ldr r1, [pc, #-20] ; argv
*je++ = 0xe52d0004; // push {r0}
*je++ = 0xe52d1004; // push {r1}
tje = je++; // bl jitmain
*je++ = 0xe51f502c; // ldr r5, [pc, #-44] ; retval
*je++ = 0xe5850000; // str r0, [r5]
*je++ = 0xe28dd008; // add sp, sp, #8
*je++ = 0xe8bd9ff0; // pop {r4-r12, pc}
if (!(je = codegen(je, jitmap, 0))) return 1;
if (je >= jitmap) die("jitmem too small");
*tje = 0xeb000000 |
(((jitmap[((int) start - (int) text) >> 2] -
(int) tje - 8) >> 2) &
0x00ffffff);
// hack to jump into specific function pointer
__clear_cache(jitmem, je);
res = bsearch(&sym, sym, 1, 1, (void *) _start);
if (((void *) 0) != res) return 0; return -1; // make compiler happy
}
int ELF32_ST_INFO(int b, int t) { return (b << 4) + (t & 0xf); }
enum { PHDR_SIZE = 32, SHDR_SIZE = 40, SYM_SIZE = 16 };
struct Elf32_Shdr {
int sh_name; // [Elf32_Word] Section name (index into string table)
int sh_type; // [Elf32_Word] Section type (SHT_*)
int sh_flags; // [Elf32_Word] Section flags (SHF_*)
int sh_addr; // [Elf32_Addr] Address where section is to be loaded
int sh_offset; // [Elf32_Off] File offset of section data, in bytes
int sh_size; // [Elf32_Word] Size of section, in bytes
int sh_link; // [Elf32_Word] Section type-specific header table
// index link
int sh_info; // [Elf32_Word] Section type-specific extra information
int sh_addralign; // [Elf32_Word] Section address alignment
int sh_entsize; // [Elf32_Word] Size of records contained within
// the section
};
enum {
// Special section indices
SHN_UNDEF = 0, // Undefined, missing, irrelevant, or meaningless
// Section types
SHT_NULL = 0, // No associated section (inactive entry)
SHT_PROGBITS = 1, // Program-defined contents
SHT_STRTAB = 3, // String table
SHT_DYNAMIC = 6, // Information for dynamic linking
SHT_REL = 9, // Relocation entries; no explicit addends
SHT_DYNSYM = 11, // Symbol table
// Section flags
SHF_WRITE = 0x1,
SHF_ALLOC = 0x2,
SHF_EXECINSTR = 0x4,
};
// Symbol table entries for ELF32
struct Elf32_Sym {
int st_name; // [Elf32_Word] Symbol name (index into string table)
int st_value; // [Elf32_Addr] Value or address associated with the symbol
int st_size; // [Elf32_Word] Size of the symbol
char st_info; // [unsigned] Symbol's type and binding attributes
char st_other;// [unsigned] Must be zero; reserved
char st_shndx, st_shndx_1, st_shndx_2, st_shndx_3; // [Elf32_Half]
// Which section (header table index) it's defined
};
enum {
// Symbol bindings
STB_LOCAL = 0, // Local symbol, not visible outside obj file
// containing def
STB_GLOBAL = 1, // Global symbol, visible to all object files
// being combined
// Symbol types
STT_NOTYPE = 0, // Symbol's type is not specified
STT_FUNC = 2, // Symbol is executable code (function, etc.)
// Symbol number
STN_UNDEF = 0
};
// Program header for ELF32
struct Elf32_Phdr {
int p_type; // [Elf32_Word] Type of segment
int p_offset; // [Elf32_Off] File offset where segment is located, in bytes
int p_vaddr; // [Elf32_Addr] Virtual address of beginning of segment
int p_paddr; // [Elf32_Addr] Physical address of beginning of segment
// (OS-specific)
int p_filesz; // [Elf32_Word] Number of bytes in file image of segment
// (may be zero)
int p_memsz; // [Elf32_Word] Number of bytes in mem image of segment
// (may be zero)
int p_flags; // [Elf32_Word] Segment flags
int p_align; // [Elf32_Word] Segment alignment constraint
};
// Segment types
enum {
PT_NULL = 0, // Unused segment
PT_LOAD = 1, // Loadable segment
PT_DYNAMIC = 2, // Dynamic linking information
PT_INTERP = 3, // Interpreter pathname
// Segment flag bits
PF_X = 1, // Execute
PF_W = 2, // Write
PF_R = 4, // Read
// Dynamic table entry tags
DT_NULL = 0, // Marks end of dynamic array
DT_NEEDED = 1, // String table offset of needed library
DT_PLTRELSZ = 2, // Size of relocation entries in PLT
DT_PLTGOT = 3, // Address associated with linkage table
DT_STRTAB = 5, // Address of dynamic string table
DT_SYMTAB = 6, // Address of dynamic symbol table
DT_STRSZ = 10, // Total size of the string table
DT_SYMENT = 11, // Size of a symbol table entry
DT_REL = 17, // Address of relocation table (Rel entries)
DT_RELSZ = 18, // Size of Rel relocation table
DT_RELENT = 19, // Size of a Rel relocation entry
DT_PLTREL = 20, // Type of relocation entry used for linking
DT_JMPREL = 23, // Address of relocations associated with PLT
};
int PT_idx, SH_idx, sym_idx;
int gen_PT(char *ptr, int type, int offset, int addr, int size,
int flag, int align)
{
struct Elf32_Phdr *phdr;
phdr = (struct Elf32_Phdr *) ptr;
phdr->p_type = type;
phdr->p_offset = offset;
phdr->p_vaddr = addr;
phdr->p_paddr = addr;
phdr->p_filesz = size;
phdr->p_memsz = size;
phdr->p_flags = flag;
phdr->p_align = align;