forked from xarantolus/ax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
t.py
1232 lines (1002 loc) · 43.9 KB
/
t.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
from __future__ import annotations
import abc
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
import traceback
import unittest
from curses.ascii import isspace
from multiprocessing.dummy import Pool
from typing import Literal, Final
import pyperclip
from tqdm import tqdm
xmmword_registers = ["xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"]
qword_registers = ["rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"rsp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"]
dword_registers = ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp",
"esp", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"]
word_registers = ["ax", "bx", "cx", "dx", "si", "di", "bp", "sp",
"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"]
byte_registers = ["al", "ah", "bl", "bh", "cl", "ch", "dl", "dh", "sil", "dil",
"bpl", "spl", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"]
registers: Final[list[str]] = xmmword_registers + qword_registers + dword_registers + word_registers + byte_registers
FLAG_CF: Final[int] = 0x0001
FLAG_PF: Final[int] = 0x0004
FLAG_ZF: Final[int] = 0x0040
FLAG_SF: Final[int] = 0x0080
FLAG_OF: Final[int] = 0x0800
OUTPUT_FLAGS_TO_ANALYZE = [
(FLAG_CF, "CF"),
(FLAG_PF, "PF"),
(FLAG_ZF, "ZF"),
(FLAG_SF, "SF"),
(FLAG_OF, "OF"),
]
FLAGS = OUTPUT_FLAGS_TO_ANALYZE
class ParseError(Exception):
pass
def check_temp_dir():
# test if /dev/shm is available by writing a file
temp_dir_filesystem = "/dev/shm"
delete_at_exit = False
try:
with open(os.path.join(temp_dir_filesystem, "test"), "w") as f:
f.write("test")
os.remove(os.path.join(temp_dir_filesystem, "test"))
except:
temp_dir_filesystem = tempfile.gettempdir()
delete_at_exit = True
print("WARNING: /dev/shm not available, using non-RAM " + temp_dir_filesystem)
return temp_dir_filesystem, delete_at_exit
temp_dir_filesystem, delete_at_exit = check_temp_dir()
class Operand(abc.ABC):
name: str
base_register: RegisterOperand
@abc.abstractmethod
def size(self) -> Literal[1, 2, 4, 8, 16]:
...
def size_letter(self):
size = self.size()
if size == 1:
return "b"
elif size == 2:
return "w"
elif size == 4:
return "d"
elif size == 8:
return "q"
elif size == 16:
return "x"
else:
# illegal argument
raise ValueError("size must be 1, 2, 4 or 8")
class RegisterOperand(Operand):
def __init__(self, name: str):
name = name.lower()
if name not in registers:
raise ParseError("Unknown register: " + str(name))
self.name = name
def is_xmm(self):
return self.name in xmmword_registers
def size(self):
if self.name in xmmword_registers:
return 16
if self.name in qword_registers:
return 8
if self.name in dword_registers:
return 4
if self.name in word_registers:
return 2
if self.name in byte_registers:
return 1
raise ValueError("Unknown register: " + str(self.name))
def __eq__(self, other):
return self.name == other.name
def __str__(self):
return self.name
class ImmediateOperand(Operand):
def __init__(self, number: str | int):
if isinstance(number, str):
try:
number = int(number, base=0)
except ValueError:
raise ParseError("Invalid immediate value: " + number)
self.number = number
def hexify(self, target: Operand):
if pow(2, target.size() * 8) <= self.number:
raise ValueError(f"Number {hex(self.number)} too big for target register {target.name}")
# larger than 2^64?
if target.size() == 16:
return hex(self.number) + "u128"
elif self.number >= 2147483647:
if target.size() == 4:
return hex(self.number) + "u32"
return hex(self.number) + "u64"
else:
return hex(self.number)
def size(self):
raise ValueError("ImmediateOperand has no size")
def __eq__(self, other):
return self.number == other.number
def __str__(self):
return hex(self.number)
class MemoryOperand(Operand):
def __init__(
self,
base_register: RegisterOperand | str,
offset: int = 0,
scale: int = 1,
index_register: RegisterOperand | str | None = None,
size: Literal[1, 2, 4, 8, 16] = None
):
self.base_register = base_register if isinstance(base_register, RegisterOperand) else RegisterOperand(base_register)
self.offset = offset
self.scale = scale
self.index_register = index_register if isinstance(index_register, RegisterOperand) else RegisterOperand(index_register) if index_register is not None else None
if size not in [1, 2, 4, 8, 16, None]:
raise ParseError("Invalid size: " + str(size))
self._size = size
def size(self):
return self._size
def __eq__(self, other: MemoryOperand) -> bool:
return self.base_register == other.base_register and \
self.offset == other.offset and \
self.scale == other.scale and \
self.index_register == other.index_register and \
self._size == other._size
def __str__(self) -> str:
size_prefix = ""
if self._size == 1:
size_prefix = "byte ptr "
elif self._size == 2:
size_prefix = "word ptr "
elif self._size == 4:
size_prefix = "dword ptr "
elif self._size == 8:
size_prefix = "qword ptr "
elif self._size == 16:
# TODO: this is e.g. wrong for movd xmm3, [rax]
size_prefix = "xmmword ptr "
if self.index_register is None:
return f"{size_prefix}[{self.base_register.name}]" if self.offset == 0 else \
f"{size_prefix}[{self.base_register.name}+{self.offset}]"
if self.offset == 0:
return f"{size_prefix}[{self.base_register.name}+{self.scale}*{self.index_register.name}]" \
if self.scale != 1 \
else f"{size_prefix}[{self.base_register.name}+{self.index_register.name}]"
raise ValueError("cannot have offset and index register")
@staticmethod
def parse(argument: str, other_operand: Operand | None) -> MemoryOperand:
original_argument = argument
argument = argument.lower()
# parse GNU Assembler syntax memory operands
if argument.startswith("byte ptr"):
size = 1
argument = argument[8:]
elif argument.startswith("word ptr"):
size = 2
argument = argument[8:]
elif argument.startswith("dword ptr"):
size = 4
argument = argument[9:]
elif argument.startswith("qword ptr"):
size = 8
argument = argument[9:]
elif argument.startswith("xword ptr"):
size = 16
argument = argument[9:]
elif argument.startswith("xmmword ptr"):
size = 16
argument = argument[11:]
elif argument.startswith("dqword ptr"):
size = 16
argument = argument[10:]
elif argument.startswith("ptr"):
if other_operand is None:
raise ParseError("Cannot parse memory operand: " + original_argument)
size = other_operand.size()
argument = argument[3:]
else:
if other_operand is None:
raise ParseError("Cannot parse memory operand: " + original_argument)
size = other_operand.size()
argument = argument.strip()
if argument.startswith("[") and argument.endswith("]"):
argument = argument[1:-1]
argument = argument.strip()
# parse base register
for register in registers:
if argument.startswith(register):
base_register = register
argument = argument[len(register):]
if RegisterOperand(base_register).size() == 16:
raise ParseError("Cannot use XMM register as base register: " + original_argument)
break
else:
base_register = None
argument = argument.strip()
# parse offset
if argument.startswith("+") or argument.startswith("-"):
# parse however digits are there
offset = str(argument[0])
argument = argument[1:]
argument = argument.strip()
for char in argument:
if char.isdigit():
offset += char # TODO: what if it has two digits?
elif isspace(char):
continue
else:
break
argument = argument[len(offset) - 1:]
offset = int(offset, base=0)
else:
offset = 0
argument = argument.strip()
# parse scale
if argument.startswith("*"):
scale = offset
offset = 0
argument = argument[1:]
else:
scale = 1
argument = argument.strip()
# parse index register
for register in registers:
if argument.startswith(register):
index_register = register
argument = argument[len(register):]
break
else:
index_register = None
if len(argument) > 0:
raise ParseError(f"Could not parse memory argument: {original_argument}(rest is {argument})\n"
"Note that the parser is very basic and cares about order")
return MemoryOperand(base_register, offset, scale, index_register, size)
class Instruction:
def __init__(
self,
mnemonic: str,
arguments: list[Operand],
additional_imm: ImmediateOperand | None,
implicit: list[Operand] | None = None
):
if implicit is None:
implicit = []
self.mnemonic = mnemonic.lower()
self.arguments = arguments
self.implicit_arguments = implicit
# currently only 0-2 operands are supported
assert len(self.arguments) + len(self.implicit_arguments) <= 2
self.additional_imm = additional_imm
def set_implicit(self, implicit: list[Operand]):
self.implicit_arguments = implicit
assert len(self.arguments) + len(self.implicit_arguments) <= 2
@staticmethod
def parse_operand(argument: str, other_operand: Operand | None):
# try to parse as register
try:
return RegisterOperand(argument)
except ParseError:
pass
# try to parse as immediate
try:
return ImmediateOperand(argument)
except ParseError:
pass
# try to parse as memory
try:
return MemoryOperand.parse(argument, other_operand)
except ParseError:
pass
raise ParseError("Could not parse operand: " + argument)
@staticmethod
def parse(argument: str) -> Instruction:
# parse GNU Assembler syntax instructions, e.g.
# mov rax, 0x5
# mov rax, [rsp+8]
# mov [rsp+4*rcx], rax
# push rax
# pop al
# movups xmm0, [rsp+8]
# ret
# split into mnemonic and arguments
parts = argument.split(maxsplit=1)
mnemonic = parts[0].lower()
if len(parts) == 1:
return Instruction(mnemonic, [], None)
# now split at the comma, but ignore commas in brackets
operands = []
current_argument = ""
bracket_level = 0
for char in parts[1]:
if char == "[":
bracket_level += 1
elif char == "]":
bracket_level -= 1
elif char == "," and bracket_level == 0:
operands.append(current_argument.strip())
current_argument = ""
continue
current_argument += char
operands.append(current_argument.strip())
parsed_operands = []
additional_immediate = None
if len(operands) == 1:
parsed_operands.append(Instruction.parse_operand(operands[0], None))
elif len(operands) == 2:
try:
first_operand = Instruction.parse_operand(operands[0], None)
second_operand = Instruction.parse_operand(operands[1], first_operand)
except ParseError:
second_operand = Instruction.parse_operand(operands[1], None)
first_operand = Instruction.parse_operand(operands[0], second_operand)
parsed_operands.append(first_operand)
parsed_operands.append(second_operand)
elif len(operands) == 3:
try:
first_operand = Instruction.parse_operand(operands[0], None)
second_operand = Instruction.parse_operand(operands[1], first_operand)
except ParseError:
second_operand = Instruction.parse_operand(operands[1], None)
first_operand = Instruction.parse_operand(operands[0], second_operand)
additional_immediate = ImmediateOperand(operands[2])
parsed_operands.append(first_operand)
parsed_operands.append(second_operand)
else:
raise ValueError("Too many operands")
return Instruction(mnemonic, parsed_operands, additional_immediate)
def __eq__(self, other):
return self.mnemonic == other.mnemonic and self.arguments == other.arguments
def __str__(self) -> str:
if len(self.arguments) == 0:
assert self.additional_imm is None
return self.mnemonic
elif len(self.arguments) == 1:
assert self.additional_imm is None
return f"{self.mnemonic} {self.arguments[0]}"
elif len(self.arguments) == 2:
if self.additional_imm is None:
return f"{self.mnemonic} {self.arguments[0]}, {self.arguments[1]}"
else:
return f"{self.mnemonic} {self.arguments[0]}, {self.arguments[1]}, {self.additional_imm}"
else:
raise ValueError("str not implement for Instruction with more than 2 operands")
class Tests(unittest.TestCase):
def test_parse_memory_operand(self):
self.assertEqual(MemoryOperand.parse(
"[rsp+8* Rcx]", RegisterOperand("al")),
MemoryOperand("rsp", 0, 8, "rcx", 1),
)
self.assertEqual(MemoryOperand.parse(
"byte ptr [rax]", RegisterOperand("rax")),
MemoryOperand("rax", 0, 1, None, 1),
"byte ptr [rax]"
)
self.assertEqual(MemoryOperand.parse(
"qword ptr [rsp+8]", RegisterOperand("rcx")),
MemoryOperand("rsp", 8, 1, None, 8),
"qword ptr [rsp+8]")
self.assertEqual(MemoryOperand.parse(
"qword ptr [rsp+ 8]", RegisterOperand("rcx")),
MemoryOperand("rsp", 8, 1, None, 8),
"qword ptr [rsp+ 8]")
self.assertEqual(MemoryOperand.parse(
"qword ptr [rsp + 8]", RegisterOperand("rcx")),
MemoryOperand("rsp", 8, 1, None, 8),
"qword ptr [rsp + 8]")
self.assertEqual(MemoryOperand.parse(
"[rsp+4*rcx]", RegisterOperand("al")),
MemoryOperand("rsp", 0, 4, "rcx", 1),
"[rsp+4*rcx]"
)
self.assertEqual(MemoryOperand.parse(
"[rsp]", RegisterOperand("xmm0")),
MemoryOperand("rsp", 0, 1, None, 16),
)
with self.assertRaises(ParseError):
MemoryOperand.parse("[xmm0]", RegisterOperand("rax"))
with self.assertRaises(ParseError):
MemoryOperand.parse("[xmm16+8*rcx]", RegisterOperand("rax"))
def test_parse_register_operand(self):
op = RegisterOperand("rax")
self.assertEqual(op.name, "rax")
self.assertEqual(op.size(), 8)
op = RegisterOperand("r11B")
self.assertEqual(op.name, "r11b")
self.assertEqual(op.size(), 1)
def test_immediate_operand(self):
op = ImmediateOperand(0x5)
self.assertEqual(op.number, 0x5)
self.assertEqual(op.hexify(RegisterOperand("rax")), "0x5")
op = ImmediateOperand(0x80000000)
self.assertEqual(op.number, 0x80000000)
self.assertEqual(op.hexify(RegisterOperand("rax")), "0x80000000u64")
self.assertEqual(op.hexify(RegisterOperand("eax")), "0x80000000u32")
with self.assertRaises(Exception):
op.hexify(RegisterOperand("ax"))
op = ImmediateOperand(2**64)
self.assertEqual(op.hexify(RegisterOperand("xmm0")), "0x10000000000000000u128")
def test_parse_instruction(self):
instr = Instruction.parse("mov rax, 0x5")
self.assertEqual(instr.mnemonic, "mov")
self.assertEqual(instr.arguments[0].name, "rax")
self.assertEqual(instr.arguments[1].number, 0x5)
instr = Instruction.parse("mov rax, [rsp+8]")
self.assertEqual(instr.mnemonic, "mov")
self.assertEqual(instr.arguments[0].name, "rax")
self.assertEqual(instr.arguments[1].base_register, RegisterOperand("rsp"))
self.assertEqual(instr.arguments[1].offset, 8)
instr = Instruction.parse("mov [rsp+4*rcx], rax")
self.assertEqual(instr.mnemonic, "mov")
self.assertEqual(instr.arguments[0].base_register, RegisterOperand("rsp"))
self.assertEqual(instr.arguments[0].offset, 0)
self.assertEqual(instr.arguments[0].scale, 4)
self.assertEqual(instr.arguments[0].index_register, RegisterOperand("rcx"))
self.assertEqual(instr.arguments[1].name, "rax")
instr = Instruction.parse("push rax")
self.assertEqual(instr.mnemonic, "push")
self.assertEqual(instr.arguments[0].name, "rax")
instr = Instruction.parse("pop al")
self.assertEqual(instr.mnemonic, "pop")
self.assertEqual(instr.arguments[0].name, "al")
instr = Instruction.parse("ret")
self.assertEqual(instr.mnemonic, "ret")
self.assertEqual(instr.arguments, [])
instr = Instruction.parse("movups xmm0, [rsp]")
self.assertEqual(instr.mnemonic, "movups")
self.assertEqual(instr.arguments[0].name, "xmm0")
self.assertEqual(instr.arguments[1].base_register, RegisterOperand("rsp"))
instr = Instruction.parse("pshufd xmm0, xmm3, 0x7")
self.assertEqual(instr.mnemonic, "pshufd")
self.assertEqual(instr.arguments[0].name, "xmm0")
self.assertEqual(instr.arguments[1].name, "xmm3")
self.assertEqual(instr.additional_imm, ImmediateOperand(0x7))
def assemble(instruction: Instruction | str) -> list[str]:
# create temporary directory
with tempfile.TemporaryDirectory(prefix="ax_assemble", dir="/dev/shm") as tmpdir:
# write assembly code to file
assembly_path = os.path.join(tmpdir, "a.asm")
with open(assembly_path, "w", encoding='utf8') as f:
f.write(f""".intel_syntax noprefix
main:
.word 0x1020
.word 0x3040
.word 0x1020
.word 0x3040
.word 0x1020
.word 0x3040
.word 0x1020
.word 0x3040
{instruction}
.word 0x1020
.word 0x3040
.word 0x1020
.word 0x3040
.word 0x1020
.word 0x3040
.word 0x1020
.word 0x3040
""")
# assemble to binary
binary_path = os.path.join(tmpdir, "a.bin")
subprocess.run(["as", "-o", binary_path, assembly_path])
with open(binary_path, "rb") as f:
binary = f.read()
marker = b"\x20\x10\x40\x30\x20\x10\x40\x30\x20\x10\x40\x30\x20\x10\x40\x30"
# find offset of main
binary_start = binary.find(marker) + len(marker)
binary_end = binary.rfind(marker)
hex_arr = []
for b in binary[binary_start:binary_end]:
hex_arr.append(hex(b))
return hex_arr
def test_id(instruction: Instruction | str, flags_set, inputs=None):
def map_flags(f):
# remove the FLAG_ prefix from each flag
return [x[5:] for x in f]
# generate name from instruction string and flags set, but replaces spaces and commas with _
test_name = f"{instruction}_{'_'.join(map_flags(flags_set))}"
if isinstance(instruction, Instruction) and len(instruction.implicit_arguments) > 0 and inputs is not None:
test_name += f"_{'_'.join([f'{op}_{inputs[i + len(instruction.arguments)]}' for i, op in enumerate(instruction.implicit_arguments)])}"
# only keep alphanumerial characters
test_name = re.sub(r'\W+', '_', test_name)
# replace consecutive _ with only one
test_name = re.sub(r'_+', '_', test_name)
return test_name.strip("_").lower()
def flag_to_literal(flag: str | int):
# if string return as is
if isinstance(flag, str):
return flag
lit = ""
for (v, k) in FLAGS:
if flag & v:
lit += ("" if lit == "" else " | ") + f"FLAG_{k}"
return lit
def joinflags(flags: list[str | int] | int, separator: str = " | ") -> str:
if isinstance(flags, int):
return flag_to_literal(flags).replace(" | ", separator)
return separator.join(list(map(flag_to_literal, flags))) if len(flags) > 0 else "0"
def flags_to_str(set: list[str], notset: list[str]):
return f"{joinflags(set)}; {joinflags(notset)}"
class Input:
def __init__(self, values: list[int], flags: list[int] | int):
self.values = values
self.flags = flags
class TestCase:
def __init__(
self,
assembled: list[str],
instruction: Instruction,
set_flags: list[str],
flags_not_set: list[str],
args: Input,
expected_values: list[int]
):
self.instruction = instruction if isinstance(instruction, Instruction) else Instruction.parse(instruction)
assert isinstance(self.instruction, Instruction)
assert len(args.values) == len(expected_values)
self.assembled_bytes = assembled
self.flags_set = set_flags
self.flags_not_set = flags_not_set
self.args = args
self.expected_values = expected_values
GOOD_TEST_VALUES = list(dict.fromkeys(
[
0x0,
0x1,
7,
8,
15,
16,
17,
31,
32,
33,
63,
64,
65,
0x7f,
0x80,
0xff,
0x100,
0x100,
0x7fff,
0x8000,
0x10000,
0x7fffffff,
0x80000000,
0x100000000,
0x7fffffffffffffff,
0x8000000000000000,
# 128 bit values
0x10000000000000000,
0x7fffffffffffffffffffffffffffffff,
0xffffffffffffffffffffffffffffffff,
]
+ # powers of 2
[2 ** i for i in range(64)]
))
@staticmethod
def dynamic_operands(i: Instruction) -> list[Operand]:
return list(filter(lambda o: not isinstance(o, ImmediateOperand), i.arguments + i.implicit_arguments))
@staticmethod
def permutate_with_flags(inputs: list[list[int]], flags_to_permutate: list[int]) -> list[Input]:
if len(flags_to_permutate) == 0:
return [Input(i, 0) for i in inputs]
permut = [0]
for f in flags_to_permutate:
permut += [x | f for x in permut]
return [Input(i, f) for i in inputs for f in permut]
@staticmethod
def generate_inputs(dynamic_operands: list[Operand]) -> list[list[int]]:
dynamic_operands = len(dynamic_operands)
if dynamic_operands == 0:
return [[]]
elif dynamic_operands == 1:
return [[v] for v in TestCase.GOOD_TEST_VALUES] + \
[[i] for i in range(0, 1024)] + \
[[random.randint(0, 2 ** 64)] for _ in range(50)]
elif dynamic_operands == 2:
return ([[v1, v2]
for v1 in TestCase.GOOD_TEST_VALUES for v2 in TestCase.GOOD_TEST_VALUES]
# random values and good test values
+ [[random.randint(0, 2 ** 64), v]
for v in TestCase.GOOD_TEST_VALUES]
+ [[v, random.randint(0, 2 ** 64)]
for v in TestCase.GOOD_TEST_VALUES]
# 50 random combinations
+ [[random.randint(0, 2 ** 64), random.randint(0, 2 ** 64)]
for _ in range(50)])
else:
raise NotImplementedError("Too many dynamic operands")
@staticmethod
def auto_learn_flags(i: Instruction, result_only: bool, flags_to_permutate: list[int]) -> list:
dynamic_operands = TestCase.dynamic_operands(i)
inputs = TestCase.generate_inputs(dynamic_operands)
with_flags = TestCase.permutate_with_flags(inputs, flags_to_permutate)
return TestCase.learn_flags(i, with_flags, result_only)
NEWLINE = "\n"
last_exception = None
@staticmethod
def learn_single_flags(
i: int,
assembled: list[str],
instruction: Instruction,
args: Input,
tmpdir: str
) -> TestCase | None:
try:
setup_code = []
dynamic_operands = TestCase.dynamic_operands(instruction)
idx = 0
for arg in dynamic_operands:
if isinstance(arg, RegisterOperand):
if arg.is_xmm():
label = f".Larg_{idx}"
setup_code.append(".data")
setup_code.append(f"{label}:")
setup_code.append(f".quad {args.values[idx] & 0xffffffffffffffff}")
setup_code.append(f".quad {args.values[idx] >> 64}")
setup_code.append(".text")
setup_code.append(f"movups {arg}, [rip + {label}]")
else:
setup_code.append(f"mov {arg}, {args.values[idx]}")
idx += 1
elif isinstance(arg, MemoryOperand):
# write memory operands to the stack
if arg.base_register != RegisterOperand("rsp"):
setup_code.append(f"mov {arg.base_register}, rsp")
if arg.index_register is not None:
setup_code.append(f"mov {arg.index_register}, 0")
if arg.size() < 16:
setup_code.append(
f"mov {arg}, {args.values[idx]}")
else:
# similar to above
setup_code.append(".data")
setup_code.append(f".Larg_{idx}:")
setup_code.append(f".quad {args.values[idx] & 0xffffffffffffffff}")
setup_code.append(f".quad {args.values[idx] >> 64}")
setup_code.append(".text")
# here we have to use a temp xmm0 because it's a memory operand
# and for that we also have to save xmm0
setup_code.append("sub rsp, 16; movdqu [rsp], xmm0")
setup_code.append(f"movups xmm0, [rip + .Larg_{idx}]")
setup_code.append(f"movups {arg}, xmm0")
setup_code.append("movdqu xmm0, [rsp]; add rsp, 16")
idx += 1
else:
raise ValueError("invalid dynamic operand" + str(arg))
assert idx == len(dynamic_operands), "Not all dynamic operands were used in setup"
assert len(dynamic_operands) <= 2, "Too many dynamic operands"
assembly_path = os.path.join(tmpdir, f"{i}.asm")
def get_rax(op):
return {1: 'al', 2: 'ax', 4: 'eax', 8: 'rax'}[op.size()]
def generate_save_code(op, idx):
if (isinstance(op, RegisterOperand) and op.is_xmm()) or op.size() == 16:
# use xmm0 as temporary register
return f"""
sub rsp, 16
movdqu [rsp], xmm0
movups xmm0, {op}
movdqu [rip+output_val{idx}], xmm0
movdqu xmm0, [rsp]
add rsp, 16"""
else:
temp_reg = get_rax(op)
return f"""push rax
mov {temp_reg}, {op}
mov [rip+output_val{idx}], {temp_reg}
pop rax"""
generated_code = f""".intel_syntax noprefix
.data
rflags_dest: .space 8
output_val0: .space 16
output_val1: .space 16
.text
.global _start
_start:
# Setup
{TestCase.NEWLINE.join(setup_code)}
push rax
# Reset flags
mov rax, {hex(args.flags) if args.flags else 0}
push rax
POPFQ
pop rax # We can do this because push/pop doesn't affect flags
# Run the actual instruction we care about
{instruction}
push rax
# Save flag state
PUSHFQ
pop rax # load flags into rax
mov [rflags_dest], rax
pop rax
# Now read the output values
{generate_save_code(dynamic_operands[0], 0) if len(dynamic_operands) > 0 else ''}
{generate_save_code(dynamic_operands[1], 1) if len(dynamic_operands) > 1 else ''}
mov rax, 1
mov rdi, 1
lea rsi, [rip+rflags_dest]
mov rdx, 40
syscall
mov rax, 60
mov rdi, 0
syscall
"""
with open(assembly_path, "w", encoding='utf8') as f:
f.write(generated_code)
# assemble with as
object_path = os.path.join(tmpdir, f"{i}.o")
subprocess.run(["as", "-moperand-check=error", "-o", object_path, assembly_path],
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, check=True)
# We instantly remove non-needed things as in the devcontainer /dev/shm is very limited
os.remove(assembly_path)
# turn into executable with gcc, symbol _start
executable_path = os.path.join(tmpdir, f"{i}")
subprocess.run(["gcc", "-m64", "-nostdlib", "-static",
"-o", executable_path, object_path], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, check=True)
os.remove(object_path)
# run executable and capture 8 + 2 * 16 = 40 bytes of output
output = subprocess.run([executable_path], stdout=subprocess.PIPE).stdout
os.remove(executable_path)
assert len(output) == 40, "Output is not 40 bytes long"
rflags = int.from_bytes(output[:8], byteorder="little", signed=False)
# find out which flags were set
set_flags, flags_not_set = [], []
for flag, flag_name in OUTPUT_FLAGS_TO_ANALYZE:
if rflags & flag:
set_flags.append("FLAG_" + flag_name)
else:
flags_not_set.append("FLAG_" + flag_name)
if len(dynamic_operands) == 0:
return TestCase(
assembled,
instruction,
set_flags,
flags_not_set,
Input([], []),
[]
)
elif len(dynamic_operands) == 1:
output_op_val1 = int.from_bytes(
output[8:8+dynamic_operands[0].size()], byteorder="little", signed=False)
return TestCase(
assembled,
instruction,
set_flags,
flags_not_set,
args,
[output_op_val1],
)
elif len(dynamic_operands) == 2:
output_op_val1 = int.from_bytes(
output[8:8+dynamic_operands[0].size()], byteorder="little", signed=False)
output_op_val2 = int.from_bytes(
output[24:24+dynamic_operands[1].size()], byteorder="little", signed=False)
return TestCase(
assembled,
instruction,
set_flags,
flags_not_set,
args,
[output_op_val1, output_op_val2],
)
else:
raise ValueError("invalid number of dynamic operands")
except subprocess.CalledProcessError:
# include stack trace
TestCase.last_exception = f"""Error while running testcase {i}:
Code:
{generated_code or "None"}
Exception:
{traceback.format_exc()}
"""
return None
@staticmethod
def learn_flags(instruction: Instruction, input_args: list[Input], result_only: bool) -> list[TestCase]:
results: list[TestCase] = []
assembled = assemble(instruction)
def is_new(flags_set, flags_not_set, input_flags):
if result_only:
return True
for ts in results:
if ts.flags_set == flags_set and ts.flags_not_set == flags_not_set and ts.args.flags == input_flags:
return False
return True
with tempfile.TemporaryDirectory(prefix="ax_flag_learner", dir="/dev/shm") as tmpdir:
def imap_func(input: tuple[int, Input]):
return TestCase.learn_single_flags(input[0], assembled, instruction, input[1], tmpdir)