-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathopt.py
2231 lines (1788 loc) · 62.4 KB
/
opt.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
import copy
import bb
import emu
from common import *
from op_classes import *
INSTR_SEPARATOR = "#"
assert(len(INSTR_SEPARATOR) == 1) #code below assumes that :P
NULL_PAIR = (0, None)
g_watched_dbb_addr = 0x405880
# remove unnecessary uncond. jumps
def contract_graph(root):
bb_to_ubb = dict()
visited = set()
jmping_to = dfs(root, f_jmping_to)
jmping_to[root] = set([root])
new_root = contract_graph_rec(root, bb_to_ubb, visited, jmping_to)
dfs(root, f_verify)
return new_root
def f_verify(acc, node, children):
if acc == False:
return acc
acc = node.verify()
if not acc:
for x in node.body:
print hex(x)
print "c1:", hex(node.child1.get_addr()), "c2:", hex(node.child2.get_addr())
assert(False)
return acc
def f_jmping_to(acc, node, children):
if not acc:
acc = dict()
for c in children:
acc = set_jmpto(acc, c, node)
return acc
def set_jmpto(jmps, c, n):
try:
jmps[c].add(n)
except:
jmps[c] = set([n])
return jmps
def dump(l):
for x in l:
print hex(x)
def merge_ubb(ubb, node, bb_to_ubb):
if not ubb:
ubb = bb.BB()
ubb.merge(node)
bb_to_ubb[node] = ubb
return ubb
def contract_2children(node, c1, c2, contract_lambda):
r1 = contract_lambda(c1)
r2 = contract_lambda(c2)
assert(r1 != r2)
node.child1 = r1
node.child2 = r2
return node
def contract_1child(cur_ubb, child, bb_to_ubb, jmping_to):
ref_count = len(jmping_to[child])
if ref_count == 1:
cur_ubb = merge_ubb(cur_ubb, child, bb_to_ubb)
elif ref_count > 1:
new = merge_ubb(None, child, bb_to_ubb)
cur_ubb.child1 = new
cur_ubb = new
#ref_count == 0 -> error
else:
assert(False)
return cur_ubb
def contract_graph_rec(node, bb_to_ubb, visited, jmping_to):
if node in visited:
return bb_to_ubb[node]
contract_lambda = lambda n: contract_graph_rec(n, bb_to_ubb, visited, jmping_to)
new_node = merge_ubb(None, node, bb_to_ubb)
root = new_node
while node not in visited:
visited.add(node)
c1, c2 = node.child1, node.child2
if c1 != None and c2 != None:
new_node = contract_2children(new_node, c1, c2, contract_lambda)
break
elif c1 != None:
node = c1
if node in visited:
new_node.child1 = bb_to_ubb[node]
break
new_node = contract_1child(new_node, node, bb_to_ubb, jmping_to)
elif c1==None and c2==None:
break
else:
assert(False)
return root
##################################################
# compiler optimizations for DBBs
##################################################
def run_all_opts(dbb):
prev_len = len(dbb.body)
chances = 2
dbb_addr = g_watched_dbb_addr
while True:
dirty = False
if dbb.get_addr() == dbb_addr:
print "$ before peephole $"
print dbb.dump()
print "-"*5
dbb, mutated = peephole(dbb)
dirty |= mutated
if dbb.get_addr() == dbb_addr:
print "$ before constant_propagation_one $"
print dbb.dump()
print "-"*5
dbb, mutated = constant_propagation_one(dbb)
dirty |= mutated
if dbb.get_addr() == dbb_addr:
print "$ before dead_code_elim_one $"
print dbb.dump()
print "-"*5
# number of instructions does not change, so we need a flag
dbb, mutated = cascading_movs(dbb)
dirty |= mutated
dbb = dead_code_elim_one(dbb)
dbb = push_pop_pairs(dbb)
dbb = stack_trick(dbb)
dbb = folding(dbb)
dbb = handle_mem_ops(dbb)
cur_len = len(dbb.body)
if (prev_len == cur_len) and not dirty:
break
prev_len = cur_len
#print [v for v in sorted(stats.items(), key=lambda(k,v): (-v,k))]
return dbb
# handle sequences of:
# mov [mem], X
# op [mem], Y
# -> mov [mem], X op Y
# handles only continouus sequences
# non-cont. have a lot of complications
def handle_mem_ops(dbb):
class MemOp:
def __init__(self, op, bits, value):
self.regs = op.regs
self.text = op.text
self.bits = bits
self.value = value
def new_value(self, v):
self.value = v
new_body = []
mem_ops = dict()
ctx = Ctx()
for instr in dbb.body:
if instr.op1 == None or instr.op1.type != O_MEM:
new_body.append(instr)
kill = []
for opnd_text, mop in mem_ops.iteritems():
if mop.regs & instr.modified_regs:
kill.append(opnd_text)
for opnd_text in kill:
del mem_ops[opnd_text]
#kill everything, we don't want any sideeffects
mem_ops = dict()
elif instr.op1 and instr.op1.type == O_MEM:
op1 = instr.op1
if instr.mnem == "mov" and instr.op2 and instr.op2.type == O_IMM:
mop = MemOp(op1, instr.bits, instr.op2.imm)
mem_ops[mop.text] = mop
new_body.append(instr)
continue
cur_mop = None
for text, mop in mem_ops.iteritems():
if op1.text == mop.text:
cur_mop = mop
break
if cur_mop and instr.bits != cur_mop.bits:
del mem_ops[cur_mop.text]
cur_mop = None
if not cur_mop or (instr.op2 and instr.op2.type != O_IMM):
new_body.append(instr)
continue
cur_value = cur_mop.value
ctx.set_reg(EAX, cur_value)
eax_opnd = Opnd(EAX)
instr.op1 = eax_opnd
instr.eval(ctx)
new_value = None
if ctx.is_known(EAX):
new_value = ctx.get_reg(EAX)
if new_value != None:
new_op = Opnd(new_value)
new_instr = Mov(FAKE_INSTR_ADDR, "mov", op1, new_op, bits=instr.bits)
prev_i = new_body[-1]
#delete last mov, if it assigns to the same location
if prev_i.mnem == "mov" and prev_i.op1.type == O_MEM and prev_i.op2.type == O_IMM and prev_i.op1.text == new_instr.op1.text:
new_body.pop()
cur_mop.new_value(new_value)
else:
instr.op1 = op1
new_instr = instr
del mem_ops[cur_mop.text]
print "failed:", instr.dump()
new_body.append(new_instr)
else:
assert(False)
dbb.set_body(new_body)
return dbb
def is_mov_reg_reg(instr):
return instr.mnem == "mov" and instr.op1 and instr.op2 and instr.op1.type == instr.op2.type == O_REG
def can_be_updated(instr, equals):
if instr.mnem not in ["mov", "add", "sub", "xor", "or", "and"]:
return False
if instr.op2.type != O_REG:
return False
read_reg = instr.op2.reg
if read_reg in equals.keys():
return True
return False
def oldest_ancestor(equals, old_reg):
reg = old_reg
while reg in equals:
reg = equals[reg]
return reg
def update_regs(instr, equals):
assert(instr.op2.type == O_REG)
old_reg = instr.op2.reg
new_reg = oldest_ancestor(equals, old_reg)
new_op2 = Opnd(new_reg)
instr.update_ops(instr.op1, new_op2)
return instr
def update_equals(equals, mod_reg):
mod_regs = REG_UNSET_AFFECTED[mod_reg][mod_reg]
inv_dict = dict()
for k,v in equals.iteritems():
if v in inv_dict:
inv_dict[v].add(k)
else:
inv_dict[v] = set([k])
for m_reg in mod_regs:
if m_reg in equals:
del equals[m_reg]
if m_reg in inv_dict:
keys = inv_dict[m_reg]
else:
continue
for key in keys:
if key in equals:
del equals[key]
else:
print "update_equals:", equals, key
return equals
# mov reg1, reg2
# mov reg3, reg1
# ...
# -> mov reg3, reg2
def cascading_movs(dbb):
dirty = False
equals = dict()
for instr in dbb.body:
if can_be_updated(instr, equals):
instr = update_regs(instr, equals)
dirty = True
if is_mov_reg_reg(instr):
reg1 = instr.op1.reg
reg2 = instr.op2.reg
if reg1 == reg2:
continue
equals = update_equals(equals, reg1)
equals[reg1] = reg2
continue
mod_regs = instr.modified_regs
for mod_reg in mod_regs:
equals = update_equals(equals, mod_reg)
#everything was updated in place
return dbb, dirty
# per one basic block
def constant_propagation_one(dbb):
ctx = Ctx()
new_body = []
dirty = False
for instr in dbb.body:
#ctx is modified
did_eval = False
substituted = False
if instr.eval(ctx):
"""
print "eval ok"
print ctx.values
print instr.dump()
"""
new = instr.equivalent_mov(ctx)
did_eval = True
if new != instr:
substituted = True
elif instr.can_substitue(ctx):
new = instr.substitute_reg(ctx)
substituted = True
else:
new = instr
if isinstance(instr, Xchg) and did_eval:
#Xchg returns a list
#bleh :p
if isinstance(instr, Xchg):
assert(type(new) == list)
new_body += new
else:
new_body.append(new)
if substituted:
dirty = True
dbb.set_body(new_body)
return dbb, dirty
def certainly_dead(possibly_dead, reg):
dead = set()
affected = REG_RESET_AFFECTED[reg]
for instr in possibly_dead:
if instr.op1.reg in affected[reg]:
dead.add(instr)
return dead
def is_mov_reg(instr):
return instr.mnem == "mov" and instr.op1.type == O_REG
def is_pop_reg(instr):
return instr.mnem == "pop" and instr.op1.type == O_REG
def possibly_alive(possibly_dead, read_regs):
alive = set()
affected = set()
for reg in read_regs:
affected |= REG_RESET_AFFECTED[reg][reg]
for instr in possibly_dead:
if instr.op1.reg in affected:
alive.add(instr)
return alive
def is_add_reg(instr):
return instr.mnem == "add" and instr.op1.type == O_REG
def is_xchg_reg_reg(instr):
return instr.mnem == "xchg" and instr.op1.type == instr.op2.type == O_REG
# special case dead code elim
# per one basic block
# mov reg, smth
# ... (reg is not used)
# mov reg, smth | pop reg (reg is killed)
# -> remove first mov
#FIXME: handling Peep_add_reg_mem is slow
def dead_code_elim_one(dbb):
possibly_dead = set()
dead = set()
#instruction -> reason for being alive (instruction)
alive_tree = dict()
for instr in dbb.body:
new_maybe_dead = None
# do not kill mov reg, [esp+X]
# this may be an unoptimized POP
# seems like a bug in CV, for example:
# pop cx / pop ax / pop ax / div cx
if is_mov_reg(instr):
if instr.op2.type != O_MEM or "esp" not in instr.op2.regs:
new_maybe_dead = instr
#this is a dirty hack to handle Peep_add_reg_mem
elif is_add_reg(instr):
new_maybe_dead = instr
if instr not in dead:
read_regs = instr.read_regs
alive = possibly_alive(possibly_dead, read_regs)
possibly_dead -= alive
if is_mov_reg(instr) or is_pop_reg(instr):
just_died = certainly_dead(possibly_dead, instr.op1.reg)
possibly_dead -= just_died
dead |= just_died
if new_maybe_dead:
possibly_dead.add(new_maybe_dead)
new_body = filter(lambda instr: instr not in dead, dbb.body)
dbb.set_body(new_body)
return dbb
def has_two_ops(instr):
return instr.op1 != None and instr.op2 != None
# handling this "correclty" requires tracking states of all bits in a register :(
# hopefully this is enough..
# push ecx
# mov cl, X
# not ecx|cx -> this gets changed to not cl
# OP reg, cl
# ...
# pop ecx
class Peep_partially_defined:
def __init__(self):
self.pattern = r"push ([a-z]+)#mov [abcdl]{2}, [^#]+#(not|neg|inc|dec) [a-z]+#.*?pop \1"
self.regexp = re.compile(self.pattern)
self.instr_count = None
def run(self, body, body_str_lambda):
new = []
rep_instr = None
push_i = body[0]
mov_i = body[1]
op_i = body[2]
reg = push_i.op1.reg
if op_i.op1.reg not in REG_TO_REG_SET[reg]:
return NULL_PAIR
#nothing to do in this case
if op_i.op1.reg == mov_i.op1.reg:
return NULL_PAIR
op_reg = op_i.op1.reg
mov_reg = mov_i.op1.reg
assert(mov_reg in REG_8BIT)
for i,instr in enumerate(body[3:]):
new.append(instr)
if instr.mnem == "pop" and instr.op1.reg == reg:
break
if op_reg in instr.read_regs:
return NULL_PAIR
op_i.update_ops(Opnd(mov_reg), None, bits=8)
#print "Peep_partially_defined:", op_i.dump()
#print body_str_lambda
return (len(new), new)
# mov reg, [esp]
# add esp, 4|2
# -> pop reg
# special case:
# mov esp, [esp]
# add esp, 4
# -> pop esp / add esp, 4
class Peep_pop_reg:
def __init__(self):
self.pattern = "mov\s+([a-z]+?), \[esp\]#add\s+esp, [0-9a-fA-F]+h?"
self.regexp = re.compile(self.pattern)
self.instr_count = 2
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
add = chunk[1]
if add.op2.type != O_IMM:
return NULL_PAIR
#you can't pop a 8bit reg :p
if i1.op1.reg in REG_8BIT:
return NULL_PAIR
imm = add.op2.imm
bits = i1.bits
if bits == 16:
stack_fix = -2
elif bits == 32:
stack_fix = -4
else:
assert(False)
off = imm + stack_fix
assert(off >= 0)
new_instrs = [Pop(FAKE_INSTR_ADDR, "pop", i1.op1, None)]
new_op2 = None
if i1.op1.reg == ESP:
new_op2 = Opnd(off+4)
elif off != 0:
new_op2 = Opnd(off)
if new_op2:
new_instrs += [Add(FAKE_INSTR_ADDR, "add", add.op1, new_op2)]
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# sub esp, CONST } push CONST
# mov [esp], reg|const
# -> push reg
class Peep_push_reg:
def __init__(self):
self.pattern = "(sub esp, [0-9a-fA-F]+h?|push\s+(small|[0-9a-fA-F]+h?))#mov\s+\[esp\], [^\[#]+($|#)"
self.regexp = re.compile(self.pattern)
self.instr_count = 2
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
i2 = chunk[1]
new_instrs = [Push(FAKE_INSTR_ADDR, "push", i2.op2, None, bits=i2.bits)]
if i1.mnem == "sub":
if i1.op2.type != O_IMM:
return NULL_PAIR
bits = i2.bits
if bits == 16:
stack_fix = -2
elif bits == 32:
stack_fix = -4
else:
assert(False)
off = i1.op2.imm + stack_fix
if off < 0:
return NULL_PAIR
if off != 0:
i1.update_ops(i1.op1, Opnd(off))
new_instrs = [i1] + new_instrs
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# xor reg, [esp]
# xor [esp], reg
# xor reg, [esp]
# -> xchg reg, [esp]
class Peep_xor_trick:
def __init__(self):
self.pat1 = "xor\s+([a-z]+), \[esp\]#xor\s+\[esp\], ([a-z]+)#xor\s+([a-z]+), \[esp\]"
self.pat2 = "xor\s+\[esp\], ([a-z]+)#xor\s+([a-z]+), \[esp\]#xor\s+\[esp\], ([a-z]+)"
self.regexp1 = re.compile(self.pat1)
self.regexp2 = re.compile(self.pat2)
self.pattern = "(%s|%s)"%(self.pat1, self.pat2)
self.regexp = re.compile(self.pattern)
self.instr_count = 3
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
if i1.op1.type == O_REG:
new_op1 = i1.op1
elif i1.op2.type == O_REG:
new_op1 = i1.op2
else:
assert(False)
new_op2 = Opnd("[esp]")
new_instrs = [Xchg(FAKE_INSTR_ADDR, "xchg", new_op1, new_op2)]
return (self.instr_count, new_instrs)
(replaced, new_instrs) = peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp1)
if replaced == 0:
(replaced, new_instrs) = peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp2)
return (replaced, new_instrs)
# push smth
# pop smth
# -> mov smth, smth
class Peep_push_mov:
def __init__(self):
self.pattern = "push\s+[^#]+#pop\s+.*"
self.regexp = re.compile(self.pattern)
self.instr_count = 2
def run(self, body, body_str_lambda):
def f_eval(chunk):
p1 = chunk[0]
p2 = chunk[1]
#print p1.dump(), p2.dump()
if p1.op1.type == O_MEM and p2.op1.type == O_MEM:
assert(False)
return (0, None)
#push eax / pop eax -> nop
if p1.op1.type == p2.op1.type == O_REG and p1.op1.reg == p2.op1.reg:
new_instrs = []
else:
new_instrs = [Mov(FAKE_INSTR_ADDR, "mov", p2.op1, p1.op1)]
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# push reg
# mov reg, esp
# add reg, 4
# (add|sub) reg, 2|4
# xchg reg, [esp]
# pop esp
# -> (add|sub) esp, 2|4
class Peep_add_esp:
def __init__(self):
self.pat1 = "push\s+[a-z]+#mov\s+[a-z]+, esp#add\s+[a-z]+, 4#(add|sub)\s+[a-z]+, (2|4)#xchg\s+[a-z]+, \[esp\]#(pop\s+esp|mov\s+esp, \[esp\])"
self.pat2 = "push\s+[a-z]+#mov\s+[a-z]+, esp#add\s+[a-z]+, 4#(add|sub)\s+[a-z]+, (2|4)#push\s+[a-z]+#mov\s+[a-z]+, \[esp\+4\]#pop\s+\[esp\]#pop\s+esp"
self.regexp1 = re.compile(self.pat1)
self.regexp2 = re.compile(self.pat2)
self.pattern = "(%s|%s)"%(self.pat1, self.pat2)
self.regexp = re.compile(self.pattern)
self.instr_count1 = 6
self.instr_count2 = 8
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
i4 = chunk[3]
i5 = chunk[4]
assert(i1.op1.type == O_REG and i4.op2.type == O_IMM)
reg = i1.op1.reg
imm = i4.op2.imm
new_op1 = Opnd("esp")
new_op2 = Opnd(imm)
mnem = i4.mnem
if mnem == "add":
new_instrs = [Add(FAKE_INSTR_ADDR, "add", new_op1, new_op2)]
elif mnem == "sub":
new_instrs = [Sub(FAKE_INSTR_ADDR, "sub", new_op1, new_op2)]
else:
print "impossible mnem:", mnem
assert(False)
if i5.mnem == "xchg":
icount = self.instr_count1
elif i5.mnem == "push":
icount = self.instr_count2
return (icount, new_instrs)
(replaced, new_instrs) = peep(body, body_str_lambda, f_eval, self.instr_count1, self.regexp1)
if replaced == 0:
(replaced, new_instrs) = peep(body, body_str_lambda, f_eval, self.instr_count2, self.regexp2)
return (replaced, new_instrs)
# push reg
# mov reg, esp
# add reg, 4+X
# xchg reg, [esp]
# pop esp
# -> add esp, X
class Peep_add_esp2:
def __init__(self):
self.pattern = r"push\s+([a-z]+)#mov\s+\1, esp#add\s+\1, [0-9a-fA-F]+h?#xchg\s+\1, \[esp\]#(pop\s+esp|mov\s+esp, \[esp\])"
self.regexp = re.compile(self.pattern)
self.instr_count = 5
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
i3 = chunk[2]
esp_op = Opnd("esp")
assert(i1.op1.type == O_REG)
assert(i3.op2.type == O_IMM)
new_imm = i3.op2.imm - 4
assert(-4 <= new_imm and new_imm <= 4)
if new_imm < 0:
new_op2 = Opnd(-new_imm)
new_instr = Sub(FAKE_INSTR_ADDR, "sub", esp_op, new_op2)
else:
new_op2 = Opnd(new_imm)
new_instr = Add(FAKE_INSTR_ADDR, "add", esp_op, new_op2)
new_instrs = [new_instr]
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# mov reg2, CONST1
# xchg reg1, reg2
# mov reg1, CONST2
# xchg reg1, reg2
# -> mov reg2, CONST2
class Peep_double_mov_xchg:
def __init__(self):
self.pattern = "mov\s+[a-z]+, [0-9a-fA-F]+h?#xchg\s+[a-z]+, [a-z]+#mov\s+[a-z]+, [0-9a-fA-F]+h?#xchg\s+[a-z]+, [a-z]+"
self.regexp = re.compile(self.pattern)
self.instr_count = 4
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
i3 = chunk[2]
assert(i1.op1.type == O_REG)
assert(i3.op2.type == O_IMM)
new_instrs = [Mov(FAKE_INSTR_ADDR, "mov", i1.op1, i3.op2)]
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# push smth1
# op [esp](, CONST)
# pop smth2
# -> mov smth2, smth1 / op smth2, CONST
# GOTCHA:
# push esp
# (add|sub) [esp], X
# pop reg
# -> mov reg, esp / op reg, X-4
class Peep_push_op_pop:
def __init__(self):
self.pattern = "push\s+[^#]+#(add|xor|sub|not|neg|inc|dec)\s+\[esp(\+1)?\](, [0-9a-fA-F]+h?)?#pop\s+[^#]+(#|$)"
self.regexp = re.compile(self.pattern)
self.instr_count = 3
def run(self, body, body_str_lambda):
def tricky_push_pop(op_i, push_i):
new_instrs = []
reg = push_i.op1.reg
idx = op_i.op1.mem_idx
assert(idx in [0,1])
reg_set = REG_TO_REG_SET[reg]
if idx == 0:
letter = "l"
elif idx == 1:
letter = "h"
else:
assert(False)
hits = filter(lambda reg: reg[1]==letter, reg_set)
assert(hits)
new_reg = hits[0]
#print "old_reg:", reg
#print "new_reg:", new_reg
new_op1 = Opnd(new_reg)
new_op2 = None
if has_two_ops(op_i):
new_op2 = Opnd(op_i.op2.text_org)
op_i.update_ops(new_op1, new_op2)
new_instrs = [op_i]
return new_instrs
def f_eval(chunk):
i1 = chunk[0]
i2 = chunk[1]
i3 = chunk[2]
both_mem = i1.op1.type == O_MEM and i3.op1.type == O_MEM
both_same_mem = both_mem and (i1.op1.text == i3.op1.text)
if both_mem and not both_same_mem:
return NULL_PAIR
#ah can be recognized as a number
if i2.op2 and i2.op2.type != O_IMM:
return NULL_PAIR
if i1.bits != i2.bits:
if i2.op1.mem_idx in [0, 1]:
if i2.bits == 8:
if i1.op1.type == i3.op1.type == O_REG and i1.op1.reg == i3.op1.reg:
new_instrs = tricky_push_pop(i2, i1)
return (self.instr_count, new_instrs)
else:
return NULL_PAIR
elif i2.bits == 16:
return NULL_PAIR
new_instrs = []
if not both_same_mem:
new_instrs = [Mov(FAKE_INSTR_ADDR, "mov", i3.op1, i1.op1)]
new_op1 = None
new_op2 = None
if i1.op1.type == O_REG and i1.op1.reg in ["sp", "esp"]:
assert(i2.mnem in ["add", "sub"])
assert(i2.op2.type == O_IMM)
fix = 4
if i1.op1.reg == "sp":
fix = 2
new_op1 = Opnd(i3.op1.text_org)
new_op2 = Opnd(i2.op2.imm - fix)
elif has_two_ops(i2):
#it's a bad idea to share Opnd classes between instructions...
new_op1 = Opnd(i3.op1.text_org)
new_op2 = Opnd(i2.op2.text_org)
else:
new_op1 = Opnd(i3.op1.text_org)
i2.update_ops(new_op1, new_op2)
new_instrs += [i2]
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
#push small 0
#sub byte ptr [esp], 40h (optional)
#mov ah, [esp]
#add esp, 2
#->mov ah, 0 / sub ah, 40h
class Peep_push_small:
def __init__(self):
self.pattern = "push [0-9a-fA-F]+h?#((add|xor|sub|not|neg|inc|dec) \[esp(\+1)?\](, [0-9a-fA-F]+h?)?#)?mov [a-z]+, \[esp\]#add esp, (2|4)"
self.regexp = re.compile(self.pattern)
self.instr_count = 4
def run(self, body, body_str_lambda):
def is_ok(push_i, mov_i):
if push_i.op1.type != O_IMM:
return False
if mov_i.op1.type == O_REG and mov_i.op1.reg not in REG_8BIT:
return False
return True
def f_eval(chunk):
snd = chunk[1]
if snd.mnem != "mov":
return f_eval1(chunk)
push_i = chunk[0]
mov_i = snd
if not is_ok(push_i, mov_i):
return NULL_PAIR
imm = push_i.op1.imm & 0xFF
imm_op = Opnd(imm)
new_instrs = [Mov(FAKE_INSTR_ADDR, "mov", mov_i.op1, imm_op)]
return (self.instr_count-1, new_instrs)
def f_eval1(chunk):
push_i = chunk[0]
op_i = chunk[1]
mov_i = chunk[2]
add_i = chunk[3]
if not is_ok(push_i, mov_i) or (op_i.op2 and op_i.op2.type != O_IMM):
return NULL_PAIR
imm = push_i.op1.imm
if op_i.op1.mem_type == O_MEM_REG_PLUS_INDEX:
idx = op_i.op1.mem_idx
if idx == 0:
imm = imm & 0xFF
elif idx == 1:
imm = imm >> 8
else:
print "bad idx:", idx
assert(False)
else:
assert(False)
imm_op = Opnd(imm)
new_instrs = [Mov(FAKE_INSTR_ADDR, "mov", mov_i.op1, imm_op)]
#don't share Opnd classes between instructions
new_op1 = Opnd(mov_i.op1.text_org)
new_op2 = None
if has_two_ops(op_i):
new_op2 = Opnd(op_i.op2.text_org)
op_i.update_ops(new_op1, new_op2)
new_instrs += [op_i]
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# xor reg/mem, const1
# xor reg/mem, const2
# -> xor reg/mem, const1 xor const2
# these are rare enough to make it a peephole opt.
class Peep_xors:
def __init__(self):
self.pattern = r"xor\s+([^,]+), [0-9a-fA-F]+h?#xor\s+\1, [0-9a-fA-F]+h?"
self.regexp = re.compile(self.pattern)
self.instr_count = 2
def run(self, body, body_str_lambda):
def f_eval(chunk):
i1 = chunk[0]
i2 = chunk[1]
#if i1.op1.text != i2.op1.text:
# return (0, None)
#FIXME: ah as number
if i1.op2.type != O_IMM or i2.op2.type != O_IMM:
return NULL_PAIR
new_imm = i1.op2.imm ^ i2.op2.imm
if new_imm != 0:
new_op2 = Opnd(new_imm)
new_instrs = [Xor(FAKE_INSTR_ADDR, "xor", i1.op1, new_op2, i1.bits)]
else:
new_instrs = []
return (self.instr_count, new_instrs)
return peep(body, body_str_lambda, f_eval, self.instr_count, self.regexp)
# mov reg, CONST
# add reg1, reg2
# op [reg1], smth
# -> op [reg2+CONST], smth
# in order to correcly handle many consecutive op [reg1], X,
# we need to push mov/add down, since new op [reg1], X may emerge below