forked from cloudwego/asm2asm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asm2asm.py
executable file
·2628 lines (2192 loc) · 85.2 KB
/
asm2asm.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
# -*- coding: utf-8 -*-
import os
import sys
import string
import itertools
import functools
from typing import Any
from typing import Dict
from typing import List
from typing import Type
from typing import Tuple
from typing import Union
from typing import Callable
from typing import Iterable
from typing import Optional
from peachpy import x86_64
from peachpy.x86_64 import generic
from peachpy.x86_64 import XMMRegister
from peachpy.x86_64.operand import is_rel32
from peachpy.x86_64.operand import MemoryOperand
from peachpy.x86_64.operand import MemoryAddress
from peachpy.x86_64.operand import RIPRelativeOffset
from peachpy.x86_64.instructions import Instruction as PInstr
from peachpy.x86_64.instructions import BranchInstruction
### Instruction Parser (GAS Syntax) ###
class Label:
name: str
offs: Optional[int]
def __init__(self, name: str):
self.name = name
self.offs = None
def __str__(self):
return self.name
def __repr__(self):
if self.offs is None:
return '{LABEL %s (unresolved)}' % self.name
else:
return '{LABEL %s (offset: %d)}' % (self.name, self.offs)
def resolve(self, offs: int):
self.offs = offs
class Index:
base : 'Register'
scale : int
def __init__(self, base: 'Register', scale: int = 1):
self.base = base
self.scale = scale
def __str__(self):
if self.scale == 1:
return ',%s' % self.base
elif self.scale >= 2:
return ',%s,%d' % (self.base, self.scale)
else:
raise RuntimeError('invalid parser state: invalid scale')
def __repr__(self):
if self.scale == 1:
return repr(self.base)
elif self.scale >= 2:
return '%d * %r' % (self.scale, self.base)
else:
raise RuntimeError('invalid parser state: invalid scale')
class Memory:
base : Optional['Register']
disp : Optional['Displacement']
index : Optional[Index]
def __init__(self, base: Optional['Register'], disp: Optional['Displacement'], index: Optional[Index]):
self.base = base
self.disp = disp
self.index = index
self._validate()
def __str__(self):
return '%s(%s%s)' % (
'' if self.disp is None else self.disp,
'' if self.base is None else self.base,
'' if self.index is None else self.index
)
def __repr__(self):
return '{MEM %r%s%s}' % (
'' if self.base is None else self.base,
'' if self.index is None else ' + ' + repr(self.index),
'' if self.disp is None else ' + ' + repr(self.disp)
)
def _validate(self):
if self.base is None and self.index is None:
raise SyntaxError('either base or index must be specified')
class Register:
reg: str
def __init__(self, reg: str):
self.reg = reg.lower()
def __str__(self):
return '%' + self.reg
def __repr__(self):
return '{REG %s}' % self.reg
@functools.cached_property
def native(self) -> x86_64.registers.Register:
if self.reg == 'rip':
raise SyntaxError('%rip is not directly accessible')
else:
return getattr(x86_64.registers, self.reg)
class Immediate:
val: int
ref: str
def __init__(self, val: int):
self.ref = ''
self.val = val
def __str__(self):
return '$%d' % self.val
def __repr__(self):
return '{IMM bin:%s, oct:%s, dec:%d, hex:%s}' % (
bin(self.val)[2:],
oct(self.val)[2:],
self.val,
hex(self.val)[2:],
)
class Reference:
ref: str
disp: int
off: Optional[int]
def __init__(self, ref: str, disp: int = 0):
self.ref = ref
self.disp = disp
self.off = None
def __str__(self):
if self.off is None:
return self.ref
else:
return '$' + str(self.off)
def __repr__(self):
if self.off is None:
return '{REF %s + %d (unresolved)}' % (self.ref, self.disp)
else:
return '{REF %s + %d (offset: %d)}' % (self.ref, self.disp, self.off)
@property
def offset(self) -> int:
if self.off is None:
raise SyntaxError('unresolved reference to ' + repr(self.ref))
else:
return self.off
def resolve(self, off: int):
self.off = self.disp + off
Operand = Union[
Label,
Memory,
Register,
Immediate,
Reference,
]
Displacement = Union[
Immediate,
Reference,
]
TOKEN_END = 0
TOKEN_REG = 1
TOKEN_IMM = 2
TOKEN_NUM = 3
TOKEN_NAME = 4
TOKEN_PUNC = 5
REGISTERS = {
'rax' , 'eax' , 'ax' , 'al' , 'ah' ,
'rbx' , 'ebx' , 'bx' , 'bl' , 'bh' ,
'rcx' , 'ecx' , 'cx' , 'cl' , 'ch' ,
'rdx' , 'edx' , 'dx' , 'dl' , 'dh' ,
'rsi' , 'esi' , 'si' , 'sil' ,
'rdi' , 'edi' , 'di' , 'dil' ,
'rbp' , 'ebp' , 'bp' , 'bpl' ,
'rsp' , 'esp' , 'sp' , 'spl' ,
'r8' , 'r8d' , 'r8w' , 'r8b' ,
'r9' , 'r9d' , 'r9w' , 'r9b' ,
'r10' , 'r10d' , 'r10w' , 'r10b' ,
'r11' , 'r11d' , 'r11w' , 'r11b' ,
'r12' , 'r12d' , 'r12w' , 'r12b' ,
'r13' , 'r13d' , 'r13w' , 'r13b' ,
'r14' , 'r14d' , 'r14w' , 'r14b' ,
'r15' , 'r15d' , 'r15w' , 'r15b' ,
'mm0' , 'mm1' , 'mm2' , 'mm3' , 'mm4' , 'mm5' , 'mm6' , 'mm7' ,
'xmm0' , 'xmm1' , 'xmm2' , 'xmm3' , 'xmm4' , 'xmm5' , 'xmm6' , 'xmm7' ,
'xmm8' , 'xmm9' , 'xmm10' , 'xmm11' , 'xmm12' , 'xmm13' , 'xmm14' , 'xmm15' ,
'xmm16' , 'xmm17' , 'xmm18' , 'xmm19' , 'xmm20' , 'xmm21' , 'xmm22' , 'xmm23' ,
'xmm24' , 'xmm25' , 'xmm26' , 'xmm27' , 'xmm28' , 'xmm29' , 'xmm30' , 'xmm31' ,
'ymm0' , 'ymm1' , 'ymm2' , 'ymm3' , 'ymm4' , 'ymm5' , 'ymm6' , 'ymm7' ,
'ymm8' , 'ymm9' , 'ymm10' , 'ymm11' , 'ymm12' , 'ymm13' , 'ymm14' , 'ymm15' ,
'ymm16' , 'ymm17' , 'ymm18' , 'ymm19' , 'ymm20' , 'ymm21' , 'ymm22' , 'ymm23' ,
'ymm24' , 'ymm25' , 'ymm26' , 'ymm27' , 'ymm28' , 'ymm29' , 'ymm30' , 'ymm31' ,
'zmm0' , 'zmm1' , 'zmm2' , 'zmm3' , 'zmm4' , 'zmm5' , 'zmm6' , 'zmm7' ,
'zmm8' , 'zmm9' , 'zmm10' , 'zmm11' , 'zmm12' , 'zmm13' , 'zmm14' , 'zmm15' ,
'zmm16' , 'zmm17' , 'zmm18' , 'zmm19' , 'zmm20' , 'zmm21' , 'zmm22' , 'zmm23' ,
'zmm24' , 'zmm25' , 'zmm26' , 'zmm27' , 'zmm28' , 'zmm29' , 'zmm30' , 'zmm31' ,
'rip' ,
}
class Token:
tag: int
val: Union[int, str]
def __init__(self, tag: int, val: Union[int, str]):
self.val = val
self.tag = tag
@classmethod
def end(cls):
return cls(TOKEN_END, '')
@classmethod
def reg(cls, reg: str):
return cls(TOKEN_REG, reg)
@classmethod
def imm(cls, imm: int):
return cls(TOKEN_IMM, imm)
@classmethod
def num(cls, num: int):
return cls(TOKEN_NUM, num)
@classmethod
def name(cls, name: str):
return cls(TOKEN_NAME, name)
@classmethod
def punc(cls, punc: str):
return cls(TOKEN_PUNC, punc)
def __repr__(self):
if self.tag == TOKEN_END:
return '<END>'
elif self.tag == TOKEN_REG:
return '<REG %s>' % self.val
elif self.tag == TOKEN_IMM:
return '<IMM %d>' % self.val
elif self.tag == TOKEN_NUM:
return '<NUM %d>' % self.val
elif self.tag == TOKEN_NAME:
return '<NAME %s>' % repr(self.val)
elif self.tag == TOKEN_PUNC:
return '<PUNC %s>' % repr(self.val)
else:
return '<UNK:%d %r>' % (self.tag, self.val)
class Tokenizer:
pos: int
src: str
def __init__(self, src: str):
self.pos = 0
self.src = src
@property
def _ch(self) -> str:
return self.src[self.pos]
@property
def _eof(self) -> bool:
return self.pos >= len(self.src)
def _rch(self) -> str:
ret, self.pos = self.src[self.pos], self.pos + 1
return ret
def _rid(self, s: str, allow_dot: bool) -> str:
while not self._eof and (self._ch == '_' or self._ch.isalnum() or (allow_dot and self._ch == '.')):
s += self._rch()
else:
return s
def _reg(self) -> Token:
if self._eof:
raise SyntaxError('unexpected EOF when parsing register names')
else:
return self._regx()
def _imm(self) -> Token:
if self._eof:
raise SyntaxError('unexpected EOF when parsing immediate values')
else:
return self._immx(self._rch())
def _regx(self) -> Token:
nch = self._rch()
reg = self._rid(nch, allow_dot = False).lower()
# check for register names
if reg not in REGISTERS:
raise SyntaxError('invalid register: ' + reg)
else:
return Token.reg(reg)
def _immv(self, ch: str) -> int:
while not self._eof and self._ch in string.digits:
ch += self._rch()
else:
return int(ch)
def _immx(self, ch: str) -> Token:
if ch.isdigit():
return Token.imm(self._immv(ch))
elif ch == '-':
return Token.imm(-self._immv(self._rch()))
else:
raise SyntaxError('unexpected character when parsing immediate value: ' + ch)
def _name(self, ch: str) -> Token:
return Token.name(self._rid(ch, allow_dot = True))
def _read(self, ch: str) -> Token:
if ch == '%':
return self._reg()
elif ch == '$':
return self._imm()
elif ch == '-':
return Token.num(-self._immv(self._rch()))
elif ch == '+':
return Token.num(self._immv(self._rch()))
elif ch.isdigit():
return Token.num(self._immv(ch))
elif ch.isidentifier():
return self._name(ch)
elif ch in ('(', ')', ',', '*'):
return Token.punc(ch)
else:
raise SyntaxError('invalid character: ' + repr(ch))
def next(self) -> Token:
while not self._eof and self._ch.isspace():
self.pos += 1
else:
return Token.end() if self._eof else self._read(self._rch())
class Instruction:
comments: str
mnemonic: str
operands: List[Operand]
def __init__(self, mnemonic: str, operands: List[Operand]):
self.comments = ''
self.operands = operands
self.mnemonic = mnemonic.lower()
def __str__(self):
ops = ', '.join(map(str, self.operands))
com = self.comments and ' /* %s */' % self.comments
# ordinal instructions
if not self.is_branch:
return '%-12s %s%s' % (self.mnemonic, ops, com)
elif len(self.operands) != 1:
raise SyntaxError('invalid branch instruction: ' + self.mnemonic)
elif isinstance(self.operands[0], Label):
return '%-12s %s%s' % (self.mnemonic, ops, com)
else:
return '%-12s *%s%s' % (self.mnemonic, ops, com)
def __repr__(self):
return '{INSTR %s: %s%s}' % (
self.mnemonic,
', '.join(map(repr, self.operands)),
self.comments and ' (%s)' % self.comments
)
class Basic:
@staticmethod
def INT3(*args, **kwargs):
return x86_64.INT(3, *args, **kwargs)
@staticmethod
def MOVQ(*args, **kwargs):
if not any(isinstance(v, XMMRegister) for v in args):
return x86_64.MOV(*args, **kwargs)
else:
return x86_64.MOVQ(*args, **kwargs)
class BitShift:
op: Type[PInstr]
def __init__(self, op: Type[PInstr]):
self.op = op
def __call__(self, *args, **kwargs):
if len(args) != 1:
return self.op(*args, **kwargs)
else:
return self.op(*args, 1, **kwargs)
class VectorCompare:
fn: int
op: Type[PInstr]
def __init__(self, op: Type[PInstr], fn: int):
self.fn = fn
self.op = op
def __call__(self, *args, **kwargs):
return self.op(*args, self.fn, **kwargs)
__instr_map__ = {
'INT3' : Basic.INT3,
'SALB' : BitShift(x86_64.SAL),
'SALW' : BitShift(x86_64.SAL),
'SALL' : BitShift(x86_64.SAL),
'SALQ' : BitShift(x86_64.SAL),
'SARB' : BitShift(x86_64.SAR),
'SARW' : BitShift(x86_64.SAR),
'SARL' : BitShift(x86_64.SAR),
'SARQ' : BitShift(x86_64.SAR),
'SHLB' : BitShift(x86_64.SHL),
'SHLW' : BitShift(x86_64.SHL),
'SHLL' : BitShift(x86_64.SHL),
'SHLQ' : BitShift(x86_64.SHL),
'SHRB' : BitShift(x86_64.SHR),
'SHRW' : BitShift(x86_64.SHR),
'SHRL' : BitShift(x86_64.SHR),
'SHRQ' : BitShift(x86_64.SHR),
'MOVQ' : Basic.MOVQ,
'CBTW' : x86_64.CBW,
'CWTL' : x86_64.CWDE,
'CLTQ' : x86_64.CDQE,
'MOVZBW' : x86_64.MOVZX,
'MOVZBL' : x86_64.MOVZX,
'MOVZWL' : x86_64.MOVZX,
'MOVZBQ' : x86_64.MOVZX,
'MOVZWQ' : x86_64.MOVZX,
'MOVSBW' : x86_64.MOVSX,
'MOVSBL' : x86_64.MOVSX,
'MOVSWL' : x86_64.MOVSX,
'MOVSBQ' : x86_64.MOVSX,
'MOVSWQ' : x86_64.MOVSX,
'MOVSLQ' : x86_64.MOVSXD,
'MOVABSQ' : x86_64.MOV,
'VCMPEQPS' : VectorCompare(x86_64.VCMPPS, 0x00),
'VCMPTRUEPS' : VectorCompare(x86_64.VCMPPS, 0x0f),
}
@functools.cached_property
def _instr(self) -> Union[Type[PInstr], Callable[..., PInstr]]:
name = self.mnemonic.upper()
func = self.__instr_map__.get(name)
# not found, resolve as x86_64 instruction
if func is None:
func = getattr(x86_64, name, None)
# try with size suffix removed (only for generic instructions)
if func is None and name[-1] in 'BWLQ':
func = getattr(generic, name[:-1], func)
# still not found, it should be an error
if func is None:
raise SyntaxError('unknown instruction: ' + self.mnemonic)
else:
return func
@property
def jmptab(self) -> Optional[str]:
if self.mnemonic == 'leaq' and isinstance(self.operands[0], Memory) and self.operands[0].base.reg == 'rip':
dis = self.operands[0].disp
if dis and dis.ref.find(CLANG_JUMPTABLE_LABLE) != -1:
return dis.ref
@property
def _instr_size(self) -> Optional[int]:
ops = self.operands
key = self.mnemonic.upper()
# special case of sign/zero extension instructions
if key in self.__instr_size__:
return self.__instr_size__[key]
# check for register operands
for op in ops:
if isinstance(op, Register):
return None
# check for size suffix, and this only applies to generic instructions
if key[-1] not in self.__size_map__ or not hasattr(generic, key[:-1]):
raise SyntaxError('ambiguous operand sizes')
else:
return self.__size_map__[key[-1]]
__size_map__ = {
'B': 1,
'W': 2,
'L': 4,
'Q': 8,
}
__instr_size__ = {
'MOVZBW' : 1,
'MOVZBL' : 1,
'MOVZWL' : 2,
'MOVZBQ' : 1,
'MOVZWQ' : 2,
'MOVSBW' : 1,
'MOVSBL' : 1,
'MOVSWL' : 2,
'MOVSBQ' : 1,
'MOVSWQ' : 2,
'MOVSLQ' : 4,
}
@staticmethod
def _encode_r32(ins: PInstr) -> bytes:
ret = [fn(ins.operands) for _, fn in ins.encodings]
ret.sort(key = len)
return ret[-1]
@classmethod
def _encode_ins(cls, ins: PInstr, force_rel32: bool = False) -> bytes:
if not isinstance(ins, BranchInstruction):
return ins.encode()
elif not is_rel32(ins.operands[0]) or not force_rel32:
return ins.encode()
else:
return cls._encode_r32(ins)
def _encode_rel(self, rel: Label, sizing: bool, offset: int) -> RIPRelativeOffset:
if rel.offs is not None:
return RIPRelativeOffset(rel.offs)
elif sizing:
return RIPRelativeOffset(offset)
else:
raise SyntaxError('unresolved reference to name: ' + rel.name)
def _encode_mem(self, mem: Memory, sizing: bool, offset: int) -> MemoryOperand:
if mem.base is not None and mem.base.reg == 'rip':
return self._encode_mem_rip(mem, sizing, offset)
else:
return self._encode_mem_std(mem, sizing, offset)
def _encode_mem_rip(self, mem: Memory, sizing: bool, offset: int) -> MemoryOperand:
if mem.disp is None:
return MemoryOperand(RIPRelativeOffset(0))
elif mem.index is not None:
raise SyntaxError('%rip relative addresing does not support indexing')
elif isinstance(mem.disp, Immediate):
return MemoryOperand(RIPRelativeOffset(mem.disp.val))
elif isinstance(mem.disp, Reference):
return MemoryOperand(RIPRelativeOffset(offset if sizing else mem.disp.offset))
else:
raise RuntimeError('illegal memory displacement')
def _encode_mem_std(self, mem: Memory, sizing: bool, offset: int) -> MemoryOperand:
disp = 0
base = None
index = None
scale = None
# add optional base
if mem.base is not None:
base = mem.base.native
# add optional indexing
if mem.index is not None:
scale = mem.index.scale
index = mem.index.base.native
# add optional displacement
if mem.disp is not None:
if isinstance(mem.disp, Immediate):
disp = mem.disp.val
elif isinstance(mem.disp, Reference):
disp = offset if sizing else mem.disp.offset
else:
raise RuntimeError('illegal memory displacement')
# construct the memory address
return MemoryOperand(
size = self._instr_size,
address = MemoryAddress(base, index, scale, disp),
)
def _encode_operands(self, sizing: bool, offset: int) -> Iterable[Any]:
for op in self.operands:
if isinstance(op, Label):
yield self._encode_rel(op, sizing, offset)
elif isinstance(op, Memory):
yield self._encode_mem(op, sizing, offset)
elif isinstance(op, Register):
yield op.native
elif isinstance(op, Immediate):
yield op.val
else:
raise SyntaxError('cannot encode %s as operand' % repr(op))
def _encode_branch_rel(self, rel: Label) -> str:
if rel.offs is not None:
return self._encode_normal_instr()
else:
raise RuntimeError('invalid relative branching instruction')
def _raw_branch_rel(self, rel: Label) -> bytes:
if rel.offs is not None:
return self._raw_normal_instr()
else:
raise RuntimeError('invalid relative branching instruction')
def _encode_branch_mem(self, mem: Memory) -> str:
raise NotImplementedError('not implemented: memory indirect jump')
def _raw_branch_mem(self, mem: Memory) -> bytes:
raise NotImplementedError('not implemented: memory indirect jump')
def _encode_branch_reg(self, reg: Register) -> str:
if reg.reg == 'rip':
raise SyntaxError('%rip cannot be used as a jump target')
elif self.mnemonic != 'jmpq':
raise SyntaxError('invalid indirect jump for instruction: ' + self.mnemonic)
else:
return x86_64.JMP(reg.native).format('go')
def _raw_branch_reg(self, reg: Register) -> bytes:
if reg.reg == 'rip':
raise SyntaxError('%rip cannot be used as a jump target')
elif self.mnemonic != 'jmpq':
raise SyntaxError('invalid indirect jump for instruction: ' + self.mnemonic)
else:
return x86_64.JMP(reg.native).encode()
def _encode_branch_instr(self) -> str:
if len(self.operands) != 1:
raise RuntimeError('illegal branch instruction')
elif isinstance(self.operands[0], Label):
return self._encode_branch_rel(self.operands[0])
elif isinstance(self.operands[0], Memory):
return self._encode_branch_mem(self.operands[0])
elif isinstance(self.operands[0], Register):
return self._encode_branch_reg(self.operands[0])
else:
raise RuntimeError('invalid operand type ' + repr(self.operands[0]))
def _raw_branch_instr(self) -> str:
if len(self.operands) != 1:
raise RuntimeError('illegal branch instruction')
elif isinstance(self.operands[0], Label):
return self._raw_branch_rel(self.operands[0])
elif isinstance(self.operands[0], Memory):
return self._raw_branch_mem(self.operands[0])
elif isinstance(self.operands[0], Register):
return self._raw_branch_reg(self.operands[0])
else:
raise RuntimeError('invalid operand type ' + repr(self.operands[0]))
def _encode_normal_instr(self) -> str:
ops = self._encode_operands(False, 0)
ret = self._instr(*list(ops)[::-1])
# encode all instructions as raw bytes
if not self.is_branch_label:
return self.encode(self._encode_ins(ret), str(self))
else:
return self.encode(self._encode_ins(ret, force_rel32 = True), '%s, $%s(%%rip)' % (self, self.operands[0].offs))
def _raw_normal_instr(self) -> str:
ops = self._encode_operands(False, 0)
ret = self._instr(*list(ops)[::-1])
# encode all instructions as raw bytes
if not self.is_branch_label:
return self._encode_ins(ret)
else:
return self._encode_ins(ret, force_rel32 = True)
@property
def size(self) -> int:
return self.encoded_size(0)
@functools.cached_property
def encoded(self) -> str:
if self.is_branch:
return self._encode_branch_instr()
else:
return self._encode_normal_instr()
def raw(self) -> bytes:
if self.is_branch:
return self._raw_branch_instr()
else:
return self._raw_normal_instr()
@functools.cached_property
def is_return(self) -> bool:
return self._instr is x86_64.RET
@functools.cached_property
def is_invoke(self) -> bool:
return self._instr is x86_64.CALL
@functools.cached_property
def is_branch(self) -> bool:
try:
return self.is_invoke or issubclass(self._instr, BranchInstruction)
except TypeError:
return False
@functools.cached_property
def is_jmp(self) -> bool:
return self._instr is x86_64.JMP
@functools.cached_property
def is_jmpq(self) -> bool:
return self.mnemonic == 'jmpq'
@property
def is_branch_label(self) -> bool:
return self.is_branch and isinstance(self.operands[0], Label)
def encoded_size(self, offset: int) -> int:
op = self._encode_operands(True, offset)
return len(self._encode_ins(self._instr(*list(op)[::-1]), force_rel32 = True))
@classmethod
def parse(cls, line: str) -> 'Instruction':
lex = Tokenizer(line)
ntk = lex.next()
# the first token must be a name
if ntk.tag != TOKEN_NAME:
raise SyntaxError('mnemonic expected, got ' + repr(ntk))
else:
return cls(ntk.val, cls._parse_operands(lex))
@staticmethod
def encode(buf: bytes, comments: str = '') -> str:
i = 0
r = []
n = len(buf)
# try "QUAD" first
while i < n - 7:
r.append('QUAD $0x%016x' % int.from_bytes(buf[i:i + 8], 'little'))
i += 8
# then "LONG"
while i < n - 3:
r.append('LONG $0x%08x' % int.from_bytes(buf[i:i + 4], 'little'))
i += 4
# then "SHORT"
while i < n - 1:
r.append('WORD $0x%04x' % int.from_bytes(buf[i:i + 2], 'little'))
i += 2
# then "BYTE"
while i < n:
r.append('BYTE $0x%02x' % buf[i])
i += 1
# join them together, and attach the comment if any
if not comments:
return '; '.join(r)
else:
return '%s // %s' % ('; '.join(r), comments)
Reg = Optional[Register]
Disp = Optional[Displacement]
@classmethod
def _parse_mend(cls, ntk: Token, base: Reg, index: Register, scale: int, disp: Disp) -> Operand:
if ntk.tag != TOKEN_PUNC or ntk.val != ')':
raise SyntaxError('")" expected, got ' + repr(ntk))
else:
return Memory(base, disp, Index(index, scale))
@classmethod
def _parse_base(cls, lex: Tokenizer, ntk: Token, disp: Disp) -> Operand:
if ntk.tag == TOKEN_REG:
return cls._parse_idelim(lex, lex.next(), Register(ntk.val), disp)
elif ntk.tag == TOKEN_PUNC and ntk.val == ',':
return cls._parse_ibase(lex, lex.next(), None, disp)
else:
raise SyntaxError('register expected, got ' + repr(ntk))
@classmethod
def _parse_ibase(cls, lex: Tokenizer, ntk: Token, base: Reg, disp: Disp) -> Operand:
if ntk.tag != TOKEN_REG:
raise SyntaxError('register expected, got ' + repr(ntk))
else:
return cls._parse_sdelim(lex, lex.next(), base, Register(ntk.val), disp)
@classmethod
def _parse_idelim(cls, lex: Tokenizer, ntk: Token, base: Reg, disp: Disp) -> Operand:
if ntk.tag == TOKEN_END:
raise SyntaxError('unexpected EOF when parsing memory operands')
elif ntk.tag == TOKEN_PUNC and ntk.val == ')':
return Memory(base, disp, None)
elif ntk.tag == TOKEN_PUNC and ntk.val == ',':
return cls._parse_ibase(lex, lex.next(), base, disp)
else:
raise SyntaxError('"," or ")" expected, got ' + repr(ntk))
@classmethod
def _parse_iscale(cls, lex: Tokenizer, ntk: Token, base: Reg, index: Register, disp: Disp) -> Operand:
if ntk.tag != TOKEN_NUM:
raise SyntaxError('integer expected, got ' + repr(ntk))
elif ntk.val not in (1, 2, 4, 8):
raise SyntaxError('indexing scale can only be 1, 2, 4 or 8')
else:
return cls._parse_mend(lex.next(), base, index, ntk.val, disp)
@classmethod
def _parse_sdelim(cls, lex: Tokenizer, ntk: Token, base: Reg, index: Register, disp: Disp) -> Operand:
if ntk.tag == TOKEN_END:
raise SyntaxError('unexpected EOF when parsing memory operands')
elif ntk.tag == TOKEN_PUNC and ntk.val == ')':
return Memory(base, disp, Index(index))
elif ntk.tag == TOKEN_PUNC and ntk.val == ',':
return cls._parse_iscale(lex, lex.next(), base, index, disp)
else:
raise SyntaxError('"," or ")" expected, got ' + repr(ntk))
@classmethod
def _parse_refmem(cls, lex: Tokenizer, ntk: Token, ref: str) -> Operand:
if ntk.tag == TOKEN_END:
return Label(ref)
elif ntk.tag == TOKEN_PUNC and ntk.val == '(' :
return cls._parse_memory(lex, ntk, Reference(ref, 0))
elif ntk.tag == TOKEN_NUM:
ntk = lex.next()
if ntk.tag == TOKEN_PUNC and ntk.val == '(':
return cls._parse_refmem(lex, ntk, Reference(ref, ntk.val))
raise SyntaxError(f'identifier "{ref}" must either be a label or a displacement reference')
@classmethod
def _parse_memory(cls, lex: Tokenizer, ntk: Token, disp: Optional[Displacement]) -> Operand:
if ntk.tag != TOKEN_PUNC or ntk.val != '(':
raise SyntaxError('"(" expected, got ' + repr(ntk))
else:
return cls._parse_base(lex, lex.next(), disp)
@classmethod
def _parse_operand(cls, lex: Tokenizer, ntk: Token, can_indir: bool = True) -> Operand:
if ntk.tag == TOKEN_REG:
return Register(ntk.val)
elif ntk.tag == TOKEN_IMM:
return Immediate(ntk.val)
elif ntk.tag == TOKEN_NUM:
return cls._parse_memory(lex, lex.next(), Immediate(ntk.val))
elif ntk.tag == TOKEN_NAME:
return cls._parse_refmem(lex, lex.next(), ntk.val)
elif ntk.tag == TOKEN_PUNC and ntk.val == '(':
return cls._parse_memory(lex, ntk, None)
elif ntk.tag == TOKEN_PUNC and ntk.val == '*' and can_indir:
return cls._parse_operand(lex, lex.next(), False)
else:
raise SyntaxError('invalid token: ' + repr(ntk))
@classmethod
def _parse_operands(cls, lex: Tokenizer) -> List[Operand]:
ret = []
ntk = lex.next()
# check for empty operand
if ntk.tag == TOKEN_END:
return []
# parse every operand
while True:
ret.append(cls._parse_operand(lex, ntk))
ntk = lex.next()
# check for the ',' delimiter or the end of input
if ntk.tag == TOKEN_PUNC and ntk.val == ',':
ntk = lex.next()
elif ntk.tag != TOKEN_END:
raise SyntaxError('"," expected, got ' + repr(ntk))
else:
return ret
### Prototype Parser ###
ARGS_ORDER_C = [
Register('rdi'),
Register('rsi'),
Register('rdx'),
Register('rcx'),
Register('r8'),
Register('r9'),
]
ARGS_ORDER_GO = [
Register('rax'),
Register('rbx'),
Register('rcx'),
Register('rdi'),
Register('rsi'),
Register('r8'),
]
FPARGS_ORDER = [
Register('xmm0'),
Register('xmm1'),
Register('xmm2'),
Register('xmm3'),
Register('xmm4'),
Register('xmm5'),
Register('xmm6'),
Register('xmm7'),
]
class Parameter:
name : str
size : int
creg : Register
goreg: Register
def __init__(self, name: str, size: int, reg: Register, goreg: Register):
self.creg = reg
self.goreg = reg
self.name = name
self.size = size
def __repr__(self):
return '<ARG %s(%d): %s>' % (self.name, self.size, self.creg)
class Pcsp:
entry: int
maxpc: int
out : List[Tuple[int, int]]
pc : int
sp : int
def __init__(self, entry: int):
self.out = []
self.maxpc = entry
self.entry = entry
self.pc = entry
self.sp = 0
def __str__(self) -> str:
ret = '[][2]uint32{\n'
for pc, sp in self.out:
ret += ' {%d, %d},\n' % (pc, sp)
return ret + ' }'
def optimize(self):
# push the last record
self.out.append((self.pc - self.entry, self.sp))
# sort by pc
self.out.sort(key=lambda x: x[0])
# NOTICE: first pair {1, 0} to be compitable with golang
tmp = [(1, 0)]
lpc, lsp = 0, -1
for pc, sp in self.out:
# sp changed, push new record
if pc != lpc and sp != lsp:
tmp.append((pc, sp))
# sp unchanged, replace with the higher pc
if pc != lpc and sp == lsp:
if len(tmp) > 0:
tmp.pop(-1)
tmp.append((pc, sp))
lpc, lsp = pc, sp
self.out = tmp
def update(self, dpc: int, dsp: int):
self.out.append((self.pc - self.entry, self.sp))
self.pc += dpc
self.sp += dsp
if self.pc > self.maxpc:
self.maxpc = self.pc
class Prototype: