-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathasm_processor.py
1530 lines (1398 loc) · 66.8 KB
/
asm_processor.py
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
#!/usr/bin/env python3
import argparse
from collections import namedtuple
from io import StringIO
import os
from pathlib import Path
import re
import struct
import sys
import tempfile
MAX_FN_SIZE = 100
SLOW_CHECKS = False
EI_NIDENT = 16
EI_CLASS = 4
EI_DATA = 5
EI_VERSION = 6
EI_OSABI = 7
EI_ABIVERSION = 8
STN_UNDEF = 0
SHN_UNDEF = 0
SHN_ABS = 0xfff1
SHN_COMMON = 0xfff2
SHN_XINDEX = 0xffff
SHN_LORESERVE = 0xff00
STT_NOTYPE = 0
STT_OBJECT = 1
STT_FUNC = 2
STT_SECTION = 3
STT_FILE = 4
STT_COMMON = 5
STT_TLS = 6
STB_LOCAL = 0
STB_GLOBAL = 1
STB_WEAK = 2
STV_DEFAULT = 0
STV_INTERNAL = 1
STV_HIDDEN = 2
STV_PROTECTED = 3
SHT_NULL = 0
SHT_PROGBITS = 1
SHT_SYMTAB = 2
SHT_STRTAB = 3
SHT_RELA = 4
SHT_HASH = 5
SHT_DYNAMIC = 6
SHT_NOTE = 7
SHT_NOBITS = 8
SHT_REL = 9
SHT_SHLIB = 10
SHT_DYNSYM = 11
SHT_INIT_ARRAY = 14
SHT_FINI_ARRAY = 15
SHT_PREINIT_ARRAY = 16
SHT_GROUP = 17
SHT_SYMTAB_SHNDX = 18
SHT_MIPS_GPTAB = 0x70000003
SHT_MIPS_DEBUG = 0x70000005
SHT_MIPS_REGINFO = 0x70000006
SHT_MIPS_OPTIONS = 0x7000000d
SHF_WRITE = 0x1
SHF_ALLOC = 0x2
SHF_EXECINSTR = 0x4
SHF_MERGE = 0x10
SHF_STRINGS = 0x20
SHF_INFO_LINK = 0x40
SHF_LINK_ORDER = 0x80
SHF_OS_NONCONFORMING = 0x100
SHF_GROUP = 0x200
SHF_TLS = 0x400
R_MIPS_32 = 2
R_MIPS_26 = 4
R_MIPS_HI16 = 5
R_MIPS_LO16 = 6
MIPS_DEBUG_ST_STATIC = 2
MIPS_DEBUG_ST_PROC = 6
MIPS_DEBUG_ST_BLOCK = 7
MIPS_DEBUG_ST_END = 8
MIPS_DEBUG_ST_FILE = 11
MIPS_DEBUG_ST_STATIC_PROC = 14
MIPS_DEBUG_ST_STRUCT = 26
MIPS_DEBUG_ST_UNION = 27
MIPS_DEBUG_ST_ENUM = 28
class ElfFormat:
def __init__(self, is_big_endian):
self.is_big_endian = is_big_endian
self.struct_char = ">" if is_big_endian else "<"
def pack(self, fmt, *args):
return struct.pack(self.struct_char + fmt, *args)
def unpack(self, fmt, data):
return struct.unpack(self.struct_char + fmt, data)
class ElfHeader:
"""
typedef struct {
unsigned char e_ident[EI_NIDENT];
Elf32_Half e_type;
Elf32_Half e_machine;
Elf32_Word e_version;
Elf32_Addr e_entry;
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf32_Word e_flags;
Elf32_Half e_ehsize;
Elf32_Half e_phentsize;
Elf32_Half e_phnum;
Elf32_Half e_shentsize;
Elf32_Half e_shnum;
Elf32_Half e_shstrndx;
} Elf32_Ehdr;
"""
def __init__(self, data):
self.e_ident = data[:EI_NIDENT]
assert self.e_ident[EI_CLASS] == 1 # 32-bit
self.fmt = ElfFormat(is_big_endian=(self.e_ident[EI_DATA] == 2))
self.e_type, self.e_machine, self.e_version, self.e_entry, self.e_phoff, self.e_shoff, self.e_flags, self.e_ehsize, self.e_phentsize, self.e_phnum, self.e_shentsize, self.e_shnum, self.e_shstrndx = self.fmt.unpack('HHIIIIIHHHHHH', data[EI_NIDENT:])
assert self.e_type == 1 # relocatable
assert self.e_machine == 8 # MIPS I Architecture
assert self.e_phoff == 0 # no program header
assert self.e_shoff != 0 # section header
assert self.e_shstrndx != SHN_UNDEF
def to_bin(self):
return self.e_ident + self.fmt.pack('HHIIIIIHHHHHH', self.e_type,
self.e_machine, self.e_version, self.e_entry, self.e_phoff,
self.e_shoff, self.e_flags, self.e_ehsize, self.e_phentsize,
self.e_phnum, self.e_shentsize, self.e_shnum, self.e_shstrndx)
class Symbol:
"""
typedef struct {
Elf32_Word st_name;
Elf32_Addr st_value;
Elf32_Word st_size;
unsigned char st_info;
unsigned char st_other;
Elf32_Half st_shndx;
} Elf32_Sym;
"""
def __init__(self, fmt, data, strtab, name=None):
self.fmt = fmt
self.st_name, self.st_value, self.st_size, st_info, self.st_other, self.st_shndx = fmt.unpack('IIIBBH', data)
assert self.st_shndx != SHN_XINDEX, "too many sections (SHN_XINDEX not supported)"
self.st_bind = st_info >> 4
self.st_type = st_info & 0xf
self.name = name if name is not None else strtab.lookup_str(self.st_name)
self.st_visibility = self.st_other & 3
@staticmethod
def from_parts(fmt, st_name, st_value, st_size, st_info, st_other, st_shndx, strtab, name):
header = fmt.pack('IIIBBH', st_name, st_value, st_size, st_info, st_other, st_shndx)
return Symbol(fmt, header, strtab, name)
def to_bin(self):
st_info = (self.st_bind << 4) | self.st_type
return self.fmt.pack('IIIBBH', self.st_name, self.st_value, self.st_size, st_info, self.st_other, self.st_shndx)
class Relocation:
def __init__(self, fmt, data, sh_type):
self.fmt = fmt
self.sh_type = sh_type
if sh_type == SHT_REL:
self.r_offset, r_info = fmt.unpack('II', data)
else:
self.r_offset, r_info, self.r_addend = fmt.unpack('III', data)
self.sym_index = r_info >> 8
self.rel_type = r_info & 0xff
def to_bin(self):
r_info = (self.sym_index << 8) | self.rel_type
if self.sh_type == SHT_REL:
return self.fmt.pack('II', self.r_offset, r_info)
else:
return self.fmt.pack('III', self.r_offset, r_info, self.r_addend)
class Section:
"""
typedef struct {
Elf32_Word sh_name;
Elf32_Word sh_type;
Elf32_Word sh_flags;
Elf32_Addr sh_addr;
Elf32_Off sh_offset;
Elf32_Word sh_size;
Elf32_Word sh_link;
Elf32_Word sh_info;
Elf32_Word sh_addralign;
Elf32_Word sh_entsize;
} Elf32_Shdr;
"""
def __init__(self, fmt, header, data, index):
self.fmt = fmt
self.sh_name, self.sh_type, self.sh_flags, self.sh_addr, self.sh_offset, self.sh_size, self.sh_link, self.sh_info, self.sh_addralign, self.sh_entsize = fmt.unpack('IIIIIIIIII', header)
assert not self.sh_flags & SHF_LINK_ORDER
if self.sh_entsize != 0:
assert self.sh_size % self.sh_entsize == 0
if self.sh_type == SHT_NOBITS:
self.data = b''
else:
self.data = data[self.sh_offset:self.sh_offset + self.sh_size]
self.index = index
self.relocated_by = []
@staticmethod
def from_parts(fmt, sh_name, sh_type, sh_flags, sh_link, sh_info, sh_addralign, sh_entsize, data, index):
header = fmt.pack('IIIIIIIIII', sh_name, sh_type, sh_flags, 0, 0, len(data), sh_link, sh_info, sh_addralign, sh_entsize)
return Section(fmt, header, data, index)
def lookup_str(self, index):
assert self.sh_type == SHT_STRTAB
to = self.data.find(b'\0', index)
assert to != -1
return self.data[index:to].decode('latin1')
def add_str(self, string):
assert self.sh_type == SHT_STRTAB
ret = len(self.data)
self.data += string.encode('latin1') + b'\0'
return ret
def is_rel(self):
return self.sh_type == SHT_REL or self.sh_type == SHT_RELA
def header_to_bin(self):
if self.sh_type != SHT_NOBITS:
self.sh_size = len(self.data)
return self.fmt.pack('IIIIIIIIII', self.sh_name, self.sh_type, self.sh_flags, self.sh_addr, self.sh_offset, self.sh_size, self.sh_link, self.sh_info, self.sh_addralign, self.sh_entsize)
def init_relocs(self):
assert self.is_rel()
entries = []
for i in range(0, self.sh_size, self.sh_entsize):
entries.append(Relocation(self.fmt, self.data[i:i+self.sh_entsize], self.sh_type))
self.relocations = entries
def relocate_mdebug(self, original_offset):
assert self.sh_type == SHT_MIPS_DEBUG
new_data = bytearray(self.data)
shift_by = self.sh_offset - original_offset
# Update the file-relative offsets in the Symbolic HDRR
hdrr_magic, hdrr_vstamp, hdrr_ilineMax, hdrr_cbLine, \
hdrr_cbLineOffset, hdrr_idnMax, hdrr_cbDnOffset, hdrr_ipdMax, \
hdrr_cbPdOffset, hdrr_isymMax, hdrr_cbSymOffset, hdrr_ioptMax, \
hdrr_cbOptOffset, hdrr_iauxMax, hdrr_cbAuxOffset, hdrr_issMax, \
hdrr_cbSsOffset, hdrr_issExtMax, hdrr_cbSsExtOffset, hdrr_ifdMax, \
hdrr_cbFdOffset, hdrr_crfd, hdrr_cbRfdOffset, hdrr_iextMax, \
hdrr_cbExtOffset = self.fmt.unpack("HHIIIIIIIIIIIIIIIIIIIIIII", self.data[0:0x60])
assert hdrr_magic == 0x7009, "Invalid magic value for .mdebug symbolic header"
if hdrr_cbLine: hdrr_cbLineOffset += shift_by
if hdrr_idnMax: hdrr_cbDnOffset += shift_by
if hdrr_ipdMax: hdrr_cbPdOffset += shift_by
if hdrr_isymMax: hdrr_cbSymOffset += shift_by
if hdrr_ioptMax: hdrr_cbOptOffset += shift_by
if hdrr_iauxMax: hdrr_cbAuxOffset += shift_by
if hdrr_issMax: hdrr_cbSsOffset += shift_by
if hdrr_issExtMax: hdrr_cbSsExtOffset += shift_by
if hdrr_ifdMax: hdrr_cbFdOffset += shift_by
if hdrr_crfd: hdrr_cbRfdOffset += shift_by
if hdrr_iextMax: hdrr_cbExtOffset += shift_by
new_data[0:0x60] = self.fmt.pack("HHIIIIIIIIIIIIIIIIIIIIIII", hdrr_magic, hdrr_vstamp, hdrr_ilineMax, hdrr_cbLine, \
hdrr_cbLineOffset, hdrr_idnMax, hdrr_cbDnOffset, hdrr_ipdMax, \
hdrr_cbPdOffset, hdrr_isymMax, hdrr_cbSymOffset, hdrr_ioptMax, \
hdrr_cbOptOffset, hdrr_iauxMax, hdrr_cbAuxOffset, hdrr_issMax, \
hdrr_cbSsOffset, hdrr_issExtMax, hdrr_cbSsExtOffset, hdrr_ifdMax, \
hdrr_cbFdOffset, hdrr_crfd, hdrr_cbRfdOffset, hdrr_iextMax, \
hdrr_cbExtOffset)
self.data = bytes(new_data)
class ElfFile:
def __init__(self, data):
self.data = data
assert data[:4] == b'\x7fELF', "not an ELF file"
self.elf_header = ElfHeader(data[0:52])
self.fmt = self.elf_header.fmt
offset, size = self.elf_header.e_shoff, self.elf_header.e_shentsize
null_section = Section(self.fmt, data[offset:offset + size], data, 0)
num_sections = self.elf_header.e_shnum or null_section.sh_size
self.sections = [null_section]
for i in range(1, num_sections):
ind = offset + i * size
self.sections.append(Section(self.fmt, data[ind:ind + size], data, i))
symtab = None
for s in self.sections:
if s.sh_type == SHT_SYMTAB:
assert not symtab
symtab = s
assert symtab is not None
self.symtab = symtab
self.sym_strtab = self.sections[symtab.sh_link]
self.symbol_entries = ElfFile.init_symbols(symtab, self.sym_strtab)
shstr = self.sections[self.elf_header.e_shstrndx]
for s in self.sections:
s.name = shstr.lookup_str(s.sh_name)
if s.is_rel():
self.sections[s.sh_info].relocated_by.append(s)
s.init_relocs()
@staticmethod
def init_symbols(symtab, strtab):
assert symtab.sh_type == SHT_SYMTAB
assert symtab.sh_entsize == 16
syms = []
for i in range(0, symtab.sh_size, symtab.sh_entsize):
syms.append(Symbol(symtab.fmt, symtab.data[i:i+symtab.sh_entsize], strtab))
return syms
def find_symbol(self, name):
for s in self.symbol_entries:
if s.name == name:
return (s.st_shndx, s.st_value)
return None
def find_symbol_in_section(self, name, section):
pos = self.find_symbol(name)
assert pos is not None
assert pos[0] == section.index
return pos[1]
def find_section(self, name):
for s in self.sections:
if s.name == name:
return s
return None
def add_section(self, name, sh_type, sh_flags, sh_link, sh_info, sh_addralign, sh_entsize, data):
shstr = self.sections[self.elf_header.e_shstrndx]
sh_name = shstr.add_str(name)
s = Section.from_parts(self.fmt, sh_name=sh_name, sh_type=sh_type,
sh_flags=sh_flags, sh_link=sh_link, sh_info=sh_info,
sh_addralign=sh_addralign, sh_entsize=sh_entsize, data=data,
index=len(self.sections))
self.sections.append(s)
s.name = name
return s
def drop_mdebug_gptab(self):
# We can only drop sections at the end, since otherwise section
# references might be wrong. Luckily, these sections typically are.
while self.sections[-1].sh_type in [SHT_MIPS_DEBUG, SHT_MIPS_GPTAB]:
self.sections.pop()
def write(self, filename):
outfile = open(filename, 'wb')
outidx = 0
def write_out(data):
nonlocal outidx
outfile.write(data)
outidx += len(data)
def pad_out(align):
if align and outidx % align:
write_out(b'\0' * (align - outidx % align))
self.elf_header.e_shnum = len(self.sections)
write_out(self.elf_header.to_bin())
for s in self.sections:
if s.sh_type != SHT_NOBITS and s.sh_type != SHT_NULL:
pad_out(s.sh_addralign)
old_offset = s.sh_offset
s.sh_offset = outidx
if s.sh_type == SHT_MIPS_DEBUG and s.sh_offset != old_offset:
# The .mdebug section has moved, relocate offsets
s.relocate_mdebug(old_offset)
write_out(s.data)
pad_out(4)
self.elf_header.e_shoff = outidx
for s in self.sections:
write_out(s.header_to_bin())
outfile.seek(0)
outfile.write(self.elf_header.to_bin())
outfile.close()
def is_temp_name(name):
return name.startswith('_asmpp_')
# https://stackoverflow.com/a/241506
def re_comment_replacer(match):
s = match.group(0)
if s[0] in "/#":
return " "
else:
return s
re_comment_or_string = re.compile(
r'#.*|/\*.*?\*/|"(?:\\.|[^\\"])*"'
)
class Failure(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class GlobalState:
def __init__(self, min_instr_count, skip_instr_count, use_jtbl_for_rodata, prelude_if_late_rodata, mips1, pascal):
# A value that hopefully never appears as a 32-bit rodata constant (or we
# miscompile late rodata). Increases by 1 in each step.
self.late_rodata_hex = 0xE0123456
self.valuectr = 0
self.namectr = 0
self.min_instr_count = min_instr_count
self.skip_instr_count = skip_instr_count
self.use_jtbl_for_rodata = use_jtbl_for_rodata
self.prelude_if_late_rodata = prelude_if_late_rodata
self.mips1 = mips1
self.pascal = pascal
def next_late_rodata_hex(self):
dummy_bytes = struct.pack('>I', self.late_rodata_hex)
if (self.late_rodata_hex & 0xffff) == 0:
# Avoid lui
self.late_rodata_hex += 1
self.late_rodata_hex += 1
return dummy_bytes
def make_name(self, cat):
self.namectr += 1
return '_asmpp_{}{}'.format(cat, self.namectr)
def func_prologue(self, name):
if self.pascal:
return " ".join([
"procedure {}();".format(name),
"type",
" pi = ^integer;",
" pf = ^single;",
" pd = ^double;",
"var",
" vi: pi;",
" vf: pf;",
" vd: pd;",
"begin",
" vi := vi;",
" vf := vf;",
" vd := vd;",
])
else:
return 'void {}(void) {{'.format(name)
def func_epilogue(self):
if self.pascal:
return "end;"
else:
return "}"
def pascal_assignment(self, tp, val):
self.valuectr += 1
address = (8 * self.valuectr) & 0x7FFF
return 'v{} := p{}({}); v{}^ := {};'.format(tp, tp, address, tp, val)
Function = namedtuple('Function', ['text_glabels', 'asm_conts', 'late_rodata_dummy_bytes', 'jtbl_rodata_size', 'late_rodata_asm_conts', 'fn_desc', 'data'])
class GlobalAsmBlock:
def __init__(self, fn_desc):
self.fn_desc = fn_desc
self.cur_section = '.text'
self.asm_conts = []
self.late_rodata_asm_conts = []
self.late_rodata_alignment = 0
self.late_rodata_alignment_from_content = False
self.text_glabels = []
self.fn_section_sizes = {
'.text': 0,
'.data': 0,
'.bss': 0,
'.rodata': 0,
'.late_rodata': 0,
}
self.fn_ins_inds = []
self.glued_line = ''
self.num_lines = 0
def fail(self, message, line=None):
context = self.fn_desc
if line:
context += ", at line \"" + line + "\""
raise Failure(message + "\nwithin " + context)
def count_quoted_size(self, line, z, real_line, output_enc):
line = line.encode(output_enc).decode('latin1')
in_quote = False
has_comma = True
num_parts = 0
ret = 0
i = 0
digits = "0123456789" # 0-7 would be more sane, but this matches GNU as
while i < len(line):
c = line[i]
i += 1
if not in_quote:
if c == '"':
in_quote = True
if z and not has_comma:
self.fail(".asciiz with glued strings is not supported due to GNU as version diffs")
num_parts += 1
elif c == ',':
has_comma = True
else:
if c == '"':
in_quote = False
has_comma = False
continue
ret += 1
if c != '\\':
continue
if i == len(line):
self.fail("backslash at end of line not supported", real_line)
c = line[i]
i += 1
# (if c is in "bfnrtv", we have a real escaped literal)
if c == 'x':
# hex literal, consume any number of hex chars, possibly none
while i < len(line) and line[i] in digits + "abcdefABCDEF":
i += 1
elif c in digits:
# octal literal, consume up to two more digits
it = 0
while i < len(line) and line[i] in digits and it < 2:
i += 1
it += 1
if in_quote:
self.fail("unterminated string literal", real_line)
if num_parts == 0:
self.fail(".ascii with no string", real_line)
return ret + num_parts if z else ret
def align2(self):
while self.fn_section_sizes[self.cur_section] % 2 != 0:
self.fn_section_sizes[self.cur_section] += 1
def align4(self):
while self.fn_section_sizes[self.cur_section] % 4 != 0:
self.fn_section_sizes[self.cur_section] += 1
def add_sized(self, size, line):
if self.cur_section in ['.text', '.late_rodata']:
if size % 4 != 0:
self.fail("size must be a multiple of 4", line)
if size < 0:
self.fail("size cannot be negative", line)
self.fn_section_sizes[self.cur_section] += size
if self.cur_section == '.text':
if not self.text_glabels:
self.fail(".text block without an initial glabel", line)
self.fn_ins_inds.append((self.num_lines - 1, size // 4))
def process_line(self, line, output_enc):
self.num_lines += 1
if line.endswith('\\'):
self.glued_line += line[:-1]
return
line = self.glued_line + line
self.glued_line = ''
real_line = line
line = re.sub(re_comment_or_string, re_comment_replacer, line)
line = line.strip()
line = re.sub(r'^[a-zA-Z0-9_]+:\s*', '', line)
changed_section = False
emitting_double = False
if (line.startswith('glabel ') or line.startswith('jlabel ')) and self.cur_section == '.text':
self.text_glabels.append(line.split()[1])
if not line:
pass # empty line
elif line.startswith('glabel ') or line.startswith('dlabel ') or line.startswith('jlabel ') or line.startswith('endlabel ') or (' ' not in line and line.endswith(':')):
pass # label
elif line.startswith('.section') or line in ['.text', '.data', '.rdata', '.rodata', '.bss', '.late_rodata']:
# section change
self.cur_section = '.rodata' if line == '.rdata' else line.split(',')[0].split()[-1]
if self.cur_section not in ['.data', '.text', '.rodata', '.late_rodata', '.bss']:
self.fail("unrecognized .section directive", real_line)
changed_section = True
elif line.startswith('.late_rodata_alignment'):
if self.cur_section != '.late_rodata':
self.fail(".late_rodata_alignment must occur within .late_rodata section", real_line)
value = int(line.split()[1])
if value not in [4, 8]:
self.fail(".late_rodata_alignment argument must be 4 or 8", real_line)
if self.late_rodata_alignment and self.late_rodata_alignment != value:
self.fail(".late_rodata_alignment alignment assumption conflicts with earlier .double directive. Make sure to provide explicit alignment padding.")
self.late_rodata_alignment = value
changed_section = True
elif line.startswith('.incbin'):
self.add_sized(int(line.split(',')[-1].strip(), 0), real_line)
elif line.startswith('.word') or line.startswith('.gpword') or line.startswith('.float'):
self.align4()
self.add_sized(4 * len(line.split(',')), real_line)
elif line.startswith('.double'):
self.align4()
if self.cur_section == '.late_rodata':
align8 = self.fn_section_sizes[self.cur_section] % 8
# Automatically set late_rodata_alignment, so the generated C code uses doubles.
# This gives us correct alignment for the transferred doubles even when the
# late_rodata_alignment is wrong, e.g. for non-matching compilation.
if not self.late_rodata_alignment:
self.late_rodata_alignment = 8 - align8
self.late_rodata_alignment_from_content = True
elif self.late_rodata_alignment != 8 - align8:
if self.late_rodata_alignment_from_content:
self.fail("found two .double directives with different start addresses mod 8. Make sure to provide explicit alignment padding.", real_line)
else:
self.fail(".double at address that is not 0 mod 8 (based on .late_rodata_alignment assumption). Make sure to provide explicit alignment padding.", real_line)
self.add_sized(8 * len(line.split(',')), real_line)
emitting_double = True
elif line.startswith('.space'):
self.add_sized(int(line.split()[1], 0), real_line)
elif line.startswith('.balign'):
align = int(line.split()[1])
if align != 4:
self.fail("only .balign 4 is supported", real_line)
self.align4()
elif line.startswith('.align'):
align = int(line.split()[1])
if align != 2:
self.fail("only .align 2 is supported", real_line)
self.align4()
elif line.startswith('.asci'):
z = (line.startswith('.asciz') or line.startswith('.asciiz'))
self.add_sized(self.count_quoted_size(line, z, real_line, output_enc), real_line)
elif line.startswith('.byte'):
self.add_sized(len(line.split(',')), real_line)
elif line.startswith('.half') or line.startswith('.hword') or line.startswith(".short"):
self.align2()
self.add_sized(2*len(line.split(',')), real_line)
elif line.startswith('.size'):
pass
elif line.startswith('.'):
# .macro, ...
self.fail("asm directive not supported", real_line)
else:
# Unfortunately, macros are hard to support for .rodata --
# we don't know how how space they will expand to before
# running the assembler, but we need that information to
# construct the C code. So if we need that we'll either
# need to run the assembler twice (at least in some rare
# cases), or change how this program is invoked.
# Similarly, we can't currently deal with pseudo-instructions
# that expand to several real instructions.
if self.cur_section != '.text':
self.fail("instruction or macro call in non-.text section? not supported", real_line)
self.add_sized(4, real_line)
if self.cur_section == '.late_rodata':
if not changed_section:
if emitting_double:
self.late_rodata_asm_conts.append(".align 0")
self.late_rodata_asm_conts.append(real_line)
if emitting_double:
self.late_rodata_asm_conts.append(".align 2")
else:
self.asm_conts.append(real_line)
def finish(self, state):
src = [''] * (self.num_lines + 1)
late_rodata_dummy_bytes = []
jtbl_rodata_size = 0
late_rodata_fn_output = []
num_instr = self.fn_section_sizes['.text'] // 4
if self.fn_section_sizes['.late_rodata'] > 0:
# Generate late rodata by emitting unique float constants.
# This requires 3 instructions for each 4 bytes of rodata.
# If we know alignment, we can use doubles, which give 3
# instructions for 8 bytes of rodata.
size = self.fn_section_sizes['.late_rodata'] // 4
skip_next = False
needs_double = (self.late_rodata_alignment != 0)
extra_mips1_nop = False
if state.pascal:
jtbl_size = 9 if state.mips1 else 8
jtbl_min_rodata_size = 2
else:
jtbl_size = 11 if state.mips1 else 9
jtbl_min_rodata_size = 5
for i in range(size):
if skip_next:
skip_next = False
continue
# Jump tables give 9 instructions (11 with -mips1) for >= 5 words of rodata,
# and should be emitted when:
# - -O2 or -O2 -g3 are used, which give the right codegen
# - we have emitted our first .float/.double (to ensure that we find the
# created rodata in the binary)
# - we have emitted our first .double, if any (to ensure alignment of doubles
# in shifted rodata sections)
# - we have at least 5 words of rodata left to emit (otherwise IDO does not
# generate a jump table)
# - we have at least 10 more instructions to go in this function (otherwise our
# function size computation will be wrong since the delay slot goes unused)
if (not needs_double and state.use_jtbl_for_rodata and i >= 1 and
size - i >= jtbl_min_rodata_size and
num_instr - len(late_rodata_fn_output) >= jtbl_size + 1):
if state.pascal:
cases = "\n".join("{}: ;".format(case) for case in range(size - i))
line = "case 0 of " + cases + " otherwise end;"
else:
cases = " ".join("case {}:".format(case) for case in range(size - i))
line = "switch (*(volatile int*)0) { " + cases + " ; }"
late_rodata_fn_output.append(line)
late_rodata_fn_output.extend([""] * (jtbl_size - 1))
jtbl_rodata_size = (size - i) * 4
extra_mips1_nop = i != 2
break
dummy_bytes = state.next_late_rodata_hex()
late_rodata_dummy_bytes.append(dummy_bytes)
if self.late_rodata_alignment == 4 * ((i + 1) % 2 + 1) and i + 1 < size:
dummy_bytes2 = state.next_late_rodata_hex()
late_rodata_dummy_bytes.append(dummy_bytes2)
fval, = struct.unpack('>d', dummy_bytes + dummy_bytes2)
if state.pascal:
line = state.pascal_assignment('d', fval)
else:
line = '*(volatile double*)0 = {};'.format(fval)
late_rodata_fn_output.append(line)
skip_next = True
needs_double = False
if state.mips1:
# mips1 does not have ldc1/sdc1
late_rodata_fn_output.append('')
late_rodata_fn_output.append('')
extra_mips1_nop = False
else:
fval, = struct.unpack('>f', dummy_bytes)
if state.pascal:
line = state.pascal_assignment('f', fval)
else:
line = '*(volatile float*)0 = {}f;'.format(fval)
late_rodata_fn_output.append(line)
extra_mips1_nop = True
late_rodata_fn_output.append('')
late_rodata_fn_output.append('')
if state.mips1 and extra_mips1_nop:
late_rodata_fn_output.append('')
text_name = None
if self.fn_section_sizes['.text'] > 0 or late_rodata_fn_output:
text_name = state.make_name('func')
src[0] = state.func_prologue(text_name)
src[self.num_lines] = state.func_epilogue()
instr_count = self.fn_section_sizes['.text'] // 4
if instr_count < state.min_instr_count:
self.fail("too short .text block")
tot_emitted = 0
tot_skipped = 0
fn_emitted = 0
fn_skipped = 0
skipping = True
rodata_stack = late_rodata_fn_output[::-1]
for (line, count) in self.fn_ins_inds:
for _ in range(count):
if (fn_emitted > MAX_FN_SIZE and instr_count - tot_emitted > state.min_instr_count and
(not rodata_stack or rodata_stack[-1])):
# Don't let functions become too large. When a function reaches 284
# instructions, and -O2 -framepointer flags are passed, the IRIX
# compiler decides it is a great idea to start optimizing more.
# Also, Pascal cannot handle too large functions before it runs out
# of unique statements to write.
fn_emitted = 0
fn_skipped = 0
skipping = True
src[line] += (' ' + state.func_epilogue() + ' ' +
state.func_prologue(state.make_name('large_func')) + ' ')
if (
skipping and
fn_skipped < state.skip_instr_count +
(state.prelude_if_late_rodata if rodata_stack else 0)
):
fn_skipped += 1
tot_skipped += 1
else:
skipping = False
if rodata_stack:
src[line] += rodata_stack.pop()
elif state.pascal:
src[line] += state.pascal_assignment('i', '0')
else:
src[line] += '*(volatile int*)0 = 0;'
tot_emitted += 1
fn_emitted += 1
if rodata_stack:
size = len(late_rodata_fn_output) // 3
available = instr_count - tot_skipped
self.fail(
"late rodata to text ratio is too high: {} / {} must be <= 1/3\n"
"add .late_rodata_alignment (4|8) to the .late_rodata "
"block to double the allowed ratio."
.format(size, available))
rodata_name = None
if self.fn_section_sizes['.rodata'] > 0:
if state.pascal:
self.fail(".rodata isn't supported with Pascal for now")
rodata_name = state.make_name('rodata')
src[self.num_lines] += ' const char {}[{}] = {{1}};'.format(rodata_name, self.fn_section_sizes['.rodata'])
data_name = None
if self.fn_section_sizes['.data'] > 0:
data_name = state.make_name('data')
if state.pascal:
line = ' var {}: packed array[1..{}] of char := [otherwise: 0];'.format(data_name, self.fn_section_sizes['.data'])
else:
line = ' char {}[{}] = {{1}};'.format(data_name, self.fn_section_sizes['.data'])
src[self.num_lines] += line
bss_name = None
if self.fn_section_sizes['.bss'] > 0:
if state.pascal:
self.fail(".bss isn't supported with Pascal")
bss_name = state.make_name('bss')
src[self.num_lines] += ' char {}[{}];'.format(bss_name, self.fn_section_sizes['.bss'])
fn = Function(
text_glabels=self.text_glabels,
asm_conts=self.asm_conts,
late_rodata_dummy_bytes=late_rodata_dummy_bytes,
jtbl_rodata_size=jtbl_rodata_size,
late_rodata_asm_conts=self.late_rodata_asm_conts,
fn_desc=self.fn_desc,
data={
'.text': (text_name, self.fn_section_sizes['.text']),
'.data': (data_name, self.fn_section_sizes['.data']),
'.rodata': (rodata_name, self.fn_section_sizes['.rodata']),
'.bss': (bss_name, self.fn_section_sizes['.bss']),
})
return src, fn
cutscene_data_regexpr = re.compile(r"CutsceneData (.|\n)*\[\] = {")
float_regexpr = re.compile(r"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f")
def repl_float_hex(m):
return str(struct.unpack(">I", struct.pack(">f", float(m.group(0).strip().rstrip("f"))))[0])
Opts = namedtuple('Opts', ['opt', 'framepointer', 'mips1', 'kpic', 'pascal', 'input_enc', 'output_enc', 'encode_cutscene_data_floats'])
def parse_source(f, opts, out_dependencies, print_source=None):
if opts.opt in ['O1', 'O2']:
if opts.framepointer:
min_instr_count = 6
skip_instr_count = 5
else:
min_instr_count = 2
skip_instr_count = 1
elif opts.opt == 'O0':
if opts.framepointer:
min_instr_count = 8
skip_instr_count = 8
else:
min_instr_count = 4
skip_instr_count = 4
elif opts.opt == 'g':
if opts.framepointer:
min_instr_count = 7
skip_instr_count = 7
else:
min_instr_count = 4
skip_instr_count = 4
elif opts.opt == 'g3':
if opts.framepointer:
min_instr_count = 4
skip_instr_count = 4
else:
min_instr_count = 2
skip_instr_count = 2
else:
raise Failure("must pass one of -g, -O0, -O1, -O2, -O2 -g3")
prelude_if_late_rodata = 0
if opts.kpic:
# Without optimizations, the PIC prelude always takes up 3 instructions.
# With optimizations, the prelude is optimized out if there's no late rodata.
if opts.opt in ('g3', 'O2'):
prelude_if_late_rodata = 3
else:
min_instr_count += 3
skip_instr_count += 3
use_jtbl_for_rodata = False
if opts.opt in ['O2', 'g3'] and not opts.framepointer and not opts.kpic:
use_jtbl_for_rodata = True
state = GlobalState(min_instr_count, skip_instr_count, use_jtbl_for_rodata, prelude_if_late_rodata, opts.mips1, opts.pascal)
output_enc = opts.output_enc
global_asm = None
asm_functions = []
base_fname = f.name
output_lines = [
'#line 1 "' + base_fname + '"'
]
is_cutscene_data = False
is_early_include = False
for line_no, raw_line in enumerate(f, 1):
raw_line = raw_line.rstrip()
line = raw_line.lstrip()
# Print exactly one output line per source line, to make compiler
# errors have correct line numbers. These will be overridden with
# reasonable content further down.
output_lines.append('')
if global_asm is not None:
if line.startswith(')'):
src, fn = global_asm.finish(state)
if state.pascal:
# Pascal has a 1600-character line length limit, so some
# of the lines we emit may be broken up. Correct for that
# using a #line directive.
src[-1] += '\n#line ' + str(line_no + 1)
for i, line2 in enumerate(src):
output_lines[start_index + i] = line2
asm_functions.append(fn)
global_asm = None
else:
global_asm.process_line(raw_line, output_enc)
elif line in ("GLOBAL_ASM(", "#pragma GLOBAL_ASM("):
global_asm = GlobalAsmBlock("GLOBAL_ASM block at line " + str(line_no))
start_index = len(output_lines)
elif (
(line.startswith('GLOBAL_ASM("') or line.startswith('#pragma GLOBAL_ASM("'))
and line.endswith('")')
) or (
(line.startswith('INCLUDE_ASM("') or line.startswith('INCLUDE_RODATA("'))
and '",' in line
and line.endswith(");")
):
prologue = []
if line.startswith("INCLUDE_"):
# INCLUDE_ASM("path/to", functionname);
before, after = line.split('",', 1)
fname = before[before.index("(") + 2 :] + "/" + after.strip()[:-2] + ".s"
if line.startswith("INCLUDE_RODATA"):
prologue = [".section .rodata"]
else:
# GLOBAL_ASM("path/to/file.s")
fname = line[line.index("(") + 2 : -2]
ext_global_asm = GlobalAsmBlock(fname)
for line2 in prologue:
ext_global_asm.process_line(line2, output_enc)
try:
f = open(fname, encoding=opts.input_enc)
except FileNotFoundError:
# The GLOBAL_ASM block might be surrounded by an ifdef, so it's
# not clear whether a missing file actually represents a compile
# error. Pass the responsibility for determining that on to the
# compiler by emitting a bad include directive. (IDO treats
# #error as a warning for some reason.)
output_lines[-1] = '#include "GLOBAL_ASM:' + fname + '"'
continue
with f:
for line2 in f:
ext_global_asm.process_line(line2.rstrip(), output_enc)
src, fn = ext_global_asm.finish(state)
if state.pascal:
# Pascal has a 1600-character line length limit, so avoid putting
# everything on the same line.
src.append('#line ' + str(line_no + 1))
output_lines[-1] = '\n'.join(src)
else:
output_lines[-1] = ''.join(src)