forked from simonlindholm/decomp-permuter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_randomizer.py
70 lines (59 loc) · 1.91 KB
/
main_randomizer.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
from compiler import Compiler
from scorer import Scorer
from randomizer import Randomizer
import sys
from pycparser import parse_file
filename = sys.argv[1]
target_o = sys.argv[2]
compile_cmd = sys.argv[3]
assert target_o.endswith('.o')
compiler = Compiler(compile_cmd, False)
scorer = Scorer(target_o)
def score(source):
cand_o = compiler.compile(source)
return scorer.score(cand_o)
ctr = 0
def write_high_scorer(source):
global ctr
while True:
ctr += 1
try:
fname = f'output-{ctr}.c'
with open(fname, 'x') as f:
f.write(source)
break
except FileExistsError:
pass
print(f"wrote to {fname}")
def main():
start_ast = parse_file(filename, use_cpp=False)
randomizer = Randomizer(start_ast)
source = randomizer.get_current_source()
base_score, base_hash = score(source)
hashes = {base_hash}
if base_score == scorer.PENALTY_INF:
print("unable to compile original .c file")
exit(1)
print(f"base score = {base_score}")
iteration = 0
errors = 0
while True:
randomizer.permute()
source = randomizer.get_current_source()
new_score, new_hash = score(source)
iteration += 1
if new_hash is None:
errors += 1
disp_score = 'inf' if new_score == scorer.PENALTY_INF else new_score
sys.stdout.write("\b"*10 + " "*10 + f"\riteration {iteration}, {errors} errors, score = {disp_score}")
sys.stdout.flush()
if new_score < base_score or (new_score == base_score and new_hash not in hashes):
hashes.add(new_hash)
print()
if new_score < base_score:
print("found a better score!!")
else:
print("found different asm with same score", new_hash)
source = randomizer.get_current_source()
write_high_scorer(source)
main()