This repository was archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathREIL.py
3345 lines (2061 loc) · 92.4 KB
/
REIL.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 sys, os, json, base64, unittest, copy
from abc import ABCMeta, abstractmethod
from sets import Set
# REIL constants
from IR import *
from symbolic import *
# supported arhitectures
from arch import x86, arm
arm_thumb = lambda addr: addr | 1
# architecture constants
ARCH_X86 = 0
ARCH_ARM = 1
# log_init() mask constants
LOG_INFO = 0x00000001 # regular message
LOG_WARN = 0x00000002 # error
LOG_ERR = 0x00000004 # warning
LOG_BIN = 0x00000008 # instruction bytes
LOG_ASM = 0x00000010 # instruction assembly code
LOG_VEX = 0x00000020 # instruction VEX code
LOG_BIL = 0x00000040 # instruction BAP IL code
# enable all debug messages
LOG_ALL = 0x7fffffff
# disable all debug messages
LOG_NONE = 0
LOG_MASK = None
LOG_PATH = None
# translator logging options
def log_init(log_mask, log_path = None):
global LOG_MASK, LOG_PATH
LOG_MASK, LOG_PATH = log_mask, log_path
def log_get():
global LOG_MASK, LOG_PATH
log_mask, log_path = LOG_MASK, LOG_PATH
env_path = os.getenv('REIL_LOG_PATH')
env_mask = os.getenv('REIL_LOG_MASK')
log_path = log_path if env_path is None else env_path
log_mask = log_mask if env_mask is None else int(env_mask, 16)
return log_mask, log_path
class Error(Exception):
pass
class StorageError(Error):
def __init__(self, addr, inum):
self.addr, self.inum = addr, inum
def __str__(self):
return 'Error while reading instruction %s.%.2d from storage' % (hex(self.addr), self.inum)
class ReadError(StorageError):
def __init__(self, addr):
self.addr, self.inum = addr, 0
def __str__(self):
return 'Error while reading instruction %s' % hex(self.addr)
class ParseError(Error):
def __str__(self):
return 'Error while deserializing instruction %s' % hex(self.addr)
def get_arch(arch):
try:
return { ARCH_X86: x86,
ARCH_ARM: arm }[ arch ]
except KeyError:
raise Error('Architecture #%d is unknown' % arch)
class Arg(object):
def __init__(self, t = None, size = None, name = None, val = None):
serialized = None
if isinstance(t, tuple):
# tuple with raw data from translator
serialized, t = t, None
self.type = A_NONE if t is None else t
self.size, self.name, self.val = size, name, val
# unserialize argument data
if serialized:
if not self.unserialize(serialized):
raise Error('Invalid serialized data')
def __hash__(self):
return hash(( self.type, self.size, self.name, self.val ))
def __eq__(self, other):
return ( self.type, self.size, self.name, self.val ) == \
( other.type, other.size, other.name, other.val )
def __ne__(self, other):
return not self == other
def __str__(self):
mkstr = lambda val: '%s:%s' % (val, self.size_name())
if self.type == A_NONE: return ''
elif self.type == A_REG: return mkstr(self.name)
elif self.type == A_TEMP: return mkstr(self.name)
elif self.type == A_CONST: return mkstr('%x' % self.get_val())
elif self.type == A_LOC: return '%x.%.2x' % self.val
def get_val(self):
mkval = lambda mask: long(self.val & mask)
if self.type != A_CONST:
raise Error('get_val() is available only for A_CONST')
if self.size == U1: return 0 if mkval(0x1) == 0 else 1
elif self.size == U8: return mkval(0xff)
elif self.size == U16: return mkval(0xffff)
elif self.size == U32: return mkval(0xffffffff)
elif self.size == U64: return mkval(0xffffffffffffffff)
def is_var(self):
# check for temporary or target architecture register
return self.type == A_REG or self.type == A_TEMP
def size_name(self):
return REIL_NAMES_SIZE[self.size]
def serialize(self):
if self.type == A_NONE: return ()
elif self.type == A_CONST: return ( self.type, self.size, self.val )
elif self.type in [ A_REG, A_TEMP ]: return ( self.type, self.size, self.name )
elif self.type == A_LOC: return ( self.type, self.val )
def unserialize(self, data):
if len(data) == 3:
self.type, self.size = Arg_type(data), Arg_size(data)
if self.size not in [ U1, U8, U16, U32, U64 ]:
return False
if self.type == A_REG: self.name = Arg_name(data)
elif self.type == A_TEMP: self.name = Arg_name(data)
elif self.type == A_CONST: self.val = Arg_val(data)
else:
return False
elif len(data) == 2:
self.type = Arg_type(data)
addr, inum = Arg_loc(data)
if self.type == A_LOC:
self.val = ( addr, inum )
else:
return False
elif len(data) == 0:
self.type = A_NONE
else: return False
return True
def to_symbolic(self, insn, in_state = None):
if self.type == A_REG or self.type == A_TEMP:
name = self.name
if self.type == A_TEMP:
# use uniqe names for temp registers of each machine instruction
name += '_%x' % insn.addr
# register value
arg = SymVal(name, self.size, is_temp = self.type == A_TEMP)
if in_state is not None:
# return expression for this register if state is available
try: arg = in_state[arg]
except KeyError: pass
return arg
elif self.type == A_CONST:
# constant value
return SymConst(self.get_val(), self.size)
elif self.type == A_LOC:
# jump location
return SymIRAddr(*self.val)
else: return None
class Insn(object):
ATTR_DEFS = (( IATTR_FLAGS, 0 ), # optional REIL flags
)
class IRAddr(tuple):
def __str__(self):
return '%.x.%.2x' % self
def __init__(self, op = None, attr = None, size = None, ir_addr = None,
a = None, b = None, c = None):
json = serialized = None
if isinstance(op, basestring):
# json string
json = op
op = None
elif isinstance(op, tuple):
# tuple with raw data from translator
serialized = op
op = None
self.init_attr(attr)
self.op = I_NONE if op is None else op
self.size = 0 if size is None else size
self.addr, self.inum = 0L, 0
if ir_addr is not None:
self.addr, self.inum = ir_addr
self.a = Arg() if a is None else a
self.b = Arg() if b is None else b
self.c = Arg() if c is None else c
# unserialize instruction data
if json: serialized = InsnJson().from_json(json)
if serialized: self.unserialize(serialized)
def __hash__(self):
return hash(( self.addr, self.inum, self.op,
hash(self.a), hash(self.b), hash(self.c) ))
def __eq__(self, other):
return ( self.addr, self.inum, self.op, self.a, self.b, self.c ) == \
( other.addr, other.inum, other.op, other.a, other.b, other.c )
def __ne__(self, other):
return not self == other
def __str__(self):
return self.to_str(show_bin = False, show_asm = False)
def to_str(self, show_bin = False, show_asm = True):
ret = ''
show_asm = show_asm and self.has_attr(IATTR_ASM)
show_bin = show_bin and self.has_attr(IATTR_BIN)
show_hdr = show_asm or show_bin
if show_hdr: ret += ';\n'
if show_asm:
mnem, args = self.get_attr(IATTR_ASM)
ret += ('; asm: %s %s' % (mnem, args)).strip()
if self.op == I_UNK:
# print source and destination register arguments for unknown instruction
src = self.get_attr(IATTR_SRC) if self.has_attr(IATTR_SRC) else []
dst = self.get_attr(IATTR_DST) if self.has_attr(IATTR_DST) else []
if len(src) > 0 or len(dst) > 0:
info = []
to_str = lambda arg: Arg_name(arg)
if len(src) > 0: info.append('reads: ' + ', '.join(map(to_str, src)))
if len(dst) > 0: info.append('writes: ' + ', '.join(map(to_str, dst)))
ret += ' -- %s' % '; '.join(info)
ret += '\n'
if not show_bin:
ret += '; len: %d\n' % self.size
if show_bin:
ret += '; data (%d): %s\n' % (self.size,
' '.join(map(lambda b: '%.2x' % ord(b), self.get_attr(IATTR_BIN))))
if show_hdr: ret += ';\n'
return ret + '%.8x.%.2x %7s %16s, %16s, %16s' % \
(self.addr, self.inum, self.op_name(), \
self.a, self.b, self.c)
def op_name(self):
return REIL_NAMES_INSN[self.op]
def ir_addr(self):
return self.IRAddr(( self.addr, self.inum ))
def serialize(self):
info = ( self.addr, self.size )
args = ( self.a.serialize(), self.b.serialize(), self.c.serialize() )
return ( info, self.inum, self.op, args, self.attr.copy() )
def unserialize(self, data):
self.init_attr(Insn_attr(data))
self.addr, self.inum, self.size = Insn_addr(data), Insn_inum(data), Insn_size(data)
self.op = Insn_op(data)
if self.op > len(REIL_INSN) - 1:
raise ParseError(self.addr)
args = Insn_args(data)
if len(args) != 3:
raise ParseError(self.addr)
if not self.a.unserialize(args[0]) or \
not self.b.unserialize(args[1]) or \
not self.c.unserialize(args[2]):
raise ParseError(self.addr)
return self
def init_attr(self, attr):
self.attr = {} if attr is None else attr
# initialize missing attributes with default values
for name, val in self.ATTR_DEFS:
if not self.has_attr(name): self.set_attr(name, val)
def get_attr(self, name):
return self.attr[name]
def set_attr(self, name, val):
self.attr[name] = val
def has_attr(self, name):
return self.attr.has_key(name)
def set_flag(self, val):
self.set_attr(IATTR_FLAGS, self.get_attr(IATTR_FLAGS) | val)
def del_flag(self, val):
self.set_attr(IATTR_FLAGS, self.get_attr(IATTR_FLAGS) & ~val)
def has_flag(self, val):
return self.get_attr(IATTR_FLAGS) & val != 0
def args(self):
return self.src() + self.dst()
def dst(self, get_all = False):
ret = []
if self.op not in [ I_UNK, I_NONE ]:
if get_all: cond = lambda arg: arg.type != A_NONE
else: cond = lambda arg: arg.is_var()
if self.op != I_JCC and self.op != I_STM and \
cond(self.c): ret.append(self.c)
if self.op == I_UNK and self.has_attr(IATTR_DST):
# get operands information from attributes
ret = map(lambda a: Arg(a), self.get_attr(IATTR_DST))
return ret
def src(self, get_all = False):
ret = []
if self.op not in [ I_UNK, I_NONE ]:
if get_all: cond = lambda arg: arg.type != A_NONE
else: cond = lambda arg: arg.is_var()
if cond(self.a): ret.append(self.a)
if cond(self.b): ret.append(self.b)
if (self.op == I_JCC or self.op == I_STM) and \
cond(self.c): ret.append(self.c)
if self.op == I_UNK and self.has_attr(IATTR_DST):
# get operands information from attributes
ret = map(lambda a: Arg(a), self.get_attr(IATTR_SRC))
return ret
def to_symbolic(self, in_state = None):
# copy input state to output state
out_state = SymState() if in_state is None else in_state.clone()
# skip instructions that doesn't update output state
if not self.op in [ I_NONE, I_UNK ]:
# convert instruction arguments to symbolic expressions
a = self.a.to_symbolic(self, out_state)
b = self.b.to_symbolic(self, out_state)
c = self.c.to_symbolic(self)
# move a value to the register
if self.op == I_STR: out_state.update(c, a)
# memory read/write
elif self.op == I_STM: out_state.update_mem_w(c, a, self.a.size)
elif self.op == I_LDM: out_state.update_mem_r(c, a, self.c.size)
# jump
elif self.op == I_JCC:
if not self.c.type in [ A_CONST, A_LOC ]:
c = out_state.get(c)
if isinstance(c, SymConst):
# make IR addr from numeric constant
c = SymIRAddr(c.val, 0)
if self.a.type == A_CONST:
# unconditional
if self.a.get_val() != 0: out_state.update(SymIP(), c)
else:
true, false = c, SymIRAddr(*self.next())
assert true is not None and false is not None
# conditional
out_state.update(SymIP(), SymCond(a, true, false))
# other instructions
else: out_state.update(c, a.to_exp(self.op, b))
return out_state
def next(self):
if self.has_attr(IATTR_NEXT):
# force to use next instruction that was set in attributes
return self.get_attr(IATTR_NEXT)
if self.has_flag(IOPT_RET):
# end of function
return None
elif self.op == I_JCC and \
self.a.type == A_CONST and self.a.get_val() != 0 and \
not self.has_flag(IOPT_CALL):
# unconditional jump
return None
elif self.has_flag(IOPT_ASM_END):
# go to first IR instruction of next assembly instruction
return self.IRAddr(( self.next_asm(), 0 ))
else:
# go to next IR instruction of current assembly instruction
return self.IRAddr(( self.addr, self.inum + 1 ))
def next_asm(self):
# address of the next assembly instruction
return self.addr + self.size
def jcc_loc(self):
if self.op == I_JCC and self.c.type == A_CONST:
return self.IRAddr(( self.c.get_val(), 0 ))
elif self.op == I_JCC and self.c.type == A_LOC:
return self.IRAddr(self.c.val)
else:
return None
def clone(self):
return Insn(self.serialize())
def eliminate(self):
self.op, self.args = I_NONE, {}
self.a = Arg(A_NONE)
self.b = Arg(A_NONE)
self.c = Arg(A_NONE)
self.set_flag(IOPT_ELIMINATED)
class TestInsn(unittest.TestCase):
def setUp(self):
attr = { IATTR_FLAGS: IOPT_ASM_END }
# raw representation of the test instruction
self.test_data = ((0, 2), 0, I_STR, ((A_REG, U32, 'R_ECX'), (),
(A_REG, U32, 'R_EAX')), attr)
# make test instruction
self.test_insn = Insn(op = I_STR, size = 2, ir_addr = ( 0, 0 ), \
a = Arg(A_REG, U32, 'R_ECX'), c = Arg(A_REG, U32, 'R_EAX'), \
attr = attr)
def test_serialize(self):
# check instruction serialization
data = self.test_insn.serialize()
assert self.test_data == data
# check instruction unserialization
insn_1, insn_2 = Insn(), Insn(self.test_data)
insn_1.unserialize(data)
assert insn_1.serialize() == insn_2.serialize() == self.test_data
def test_clone(self):
# check instruction cloning
insn_1 = self.test_insn.clone()
assert insn_1.serialize() == self.test_data
def test_src_dst(self):
# check source and destination args
assert self.test_insn.src() == [ self.test_insn.a ] and \
self.test_insn.dst() == [ self.test_insn.c ]
def test_next(self):
# check next instruction address
insn_1 = Insn(size = 4, ir_addr = (10, 0))
insn_2 = Insn(size = 4, ir_addr = (10, 1), attr = { IATTR_FLAGS: IOPT_ASM_END })
assert insn_1.next() == (10, 1) and insn_2.next() == (14, 0)
insn_2.set_attr(IATTR_NEXT, (10, 2))
assert insn_2.next() == (10, 2)
def test_to_symbolic(self):
sym = Insn(op = I_STR, \
a = Arg(A_REG, U32, 'R_ECX'), \
c = Arg(A_REG, U32, 'R_EAX')).to_symbolic()
eax = sym[SymVal('R_EAX', U32)]
# check for valid store
assert eax == SymAny() == SymVal('R_ECX', U32)
sym = Insn(op = I_ADD, \
a = Arg(A_REG, U32, 'R_ECX'), \
b = Arg(A_REG, U32, 'R_EAX'), \
c = Arg(A_REG, U32, 'R_EAX')).to_symbolic()
eax = sym[SymVal('R_EAX', U32)]
# check for valid arythmetic expression
assert eax == SymAny() \
== SymAny() + SymAny() \
== SymVal('R_EAX', U32) + SymAny() \
== SymVal('R_ECX', U32) + SymAny() \
== SymVal('R_EAX', U32) + SymVal('R_ECX', U32)
sym = Insn(op = I_STM, \
a = Arg(A_REG, U32, 'R_EAX'), \
c = Arg(A_REG, U32, 'R_ECX')).to_symbolic()
ecx = sym[SymPtr(SymVal('R_ECX', U32))]
# check for valid memory write expression
assert ecx == SymAny() == SymVal('R_EAX', U32)
sym = Insn(op = I_LDM, \
a = Arg(A_REG, U32, 'R_ECX'), \
c = Arg(A_REG, U32, 'R_EAX')).to_symbolic()
eax = sym[SymVal('R_EAX', U32)]
# check for valid memory read expression
assert eax == SymAny() \
== SymPtr(SymAny()) \
== SymPtr(SymVal('R_ECX', U32))
class TestSymState(unittest.TestCase):
def test_remove_temp_regs(self):
sym = Insn(op = I_STR, \
a = Arg(A_REG, U32, 'R_EAX'), \
c = Arg(A_REG, U32, 'R_ECX')).to_symbolic()
sym = Insn(op = I_ADD, \
a = Arg(A_REG, U32, 'R_EAX'), \
c = Arg(A_TEMP, U32, 'V_01')).to_symbolic(sym)
sym.remove_temp_regs()
assert sym.arg_out() == [ SymVal('R_ECX') ]
def test_slice(self):
sym = Insn(op = I_STR, \
a = Arg(A_REG, U32, 'R_EAX'), \
c = Arg(A_REG, U32, 'R_ECX')).to_symbolic()
sym = Insn(op = I_ADD, \
a = Arg(A_REG, U32, 'R_EBX'), \
b = Arg(A_CONST, U32, val = 1), \
c = Arg(A_REG, U32, 'R_EDX')).to_symbolic(sym)
sym.slice(val_out = [ 'R_ECX' ])
assert sym.arg_out() == [ SymVal('R_ECX') ]
sym.slice(val_in = [ 'R_EBX' ])
assert sym.arg_out() == []
class InsnJson():
def to_json(self, insn):
insn = insn.serialize() if isinstance(insn, Insn) else insn
attr = Insn_attr(insn)
if attr.has_key(IATTR_BIN):
# JSON doesn't support binary data
attr[IATTR_BIN] = base64.b64encode(attr[IATTR_BIN])
# JSON doesn't support numeric keys
attr = [ (key, val) for key, val in attr.items() ]
return json.dumps(( ( Insn_addr(insn), Insn_size(insn) ), \
Insn_inum(insn), Insn_op(insn), Insn_args(insn), attr ))
def from_json(self, data):
attr_new = {}
# make serialized argument from json data
arg = lambda a: ( Arg_type(a), \
Arg_size(a), \
Arg_val(a) if Arg_type(a) == A_CONST else Arg_name(a) ) if len(a) > 0 else ()
insn = json.loads(data)
attr = Insn_attr(insn)
args = ( arg(Insn_args(insn)[0]), \
arg(Insn_args(insn)[1]), \
arg(Insn_args(insn)[2]) )
for key, val in attr:
attr_new[key] = val
if attr_new.has_key(IATTR_BIN):
# get instruction binary data from base64
attr_new[IATTR_BIN] = base64.b64decode(attr_new[IATTR_BIN])
# return raw instruction data
return ( ( Insn_addr(insn), Insn_size(insn) ), \
Insn_inum(insn), Insn_op(insn), args, attr_new )
class TestInsnJson(unittest.TestCase):
def setUp(self):
attr = { IATTR_FLAGS: IOPT_ASM_END }
# raw representation of the test instruction
self.test_data = ((0, 2), 0, I_STR, ((A_REG, U32, 'R_ECX'), (),
(A_REG, U32, 'R_EAX')), attr)
# json representation of the test instruction
self.json_data = '[[0, 2], 0, %d, [[%d, %d, "%s"], [], [%d, %d, "%s"]], [[%d, %d]]]' % \
(I_STR, A_REG, U32, 'R_ECX', \
A_REG, U32, 'R_EAX',
IATTR_FLAGS, IOPT_ASM_END)
# make test instruction
self.test_insn = Insn(op = I_STR, size = 2, ir_addr = ( 0, 0 ), \
a = Arg(A_REG, U32, 'R_ECX'), c = Arg(A_REG, U32, 'R_EAX'), \
attr = attr)
def test(self):
js = InsnJson()
# check json producing
assert json.loads(self.json_data) == json.loads(js.to_json(self.test_insn))
assert json.loads(self.json_data) == json.loads(js.to_json(self.test_data))
# check json parsing
assert js.from_json(self.json_data) == self.test_data
class InsnList(list):
def __str__(self):
return '\n'.join(map(lambda insn: insn.to_str(show_asm = True, show_bin = True), self)) + '\n'
def sort(self):
super(InsnList, self).sort(key = lambda insn: insn.ir_addr())
def get_range(self, first, last = None):
if len(self) == 0: return InsnList()
# use first instruction by default
first = self[0].ir_addr() if first is None else first
first = first if isinstance(first, tuple) else ( first, None )
# query one machine instruction if last wasn't specified
last = last if last is None else last
last = last if isinstance(last, tuple) else ( last, None )
ret, start = [], False
first = ( first[0], 0 ) if first[1] is None else first
for insn in self:
addr = insn.ir_addr()
# check for start of the range
if addr == first: start = True
if start: ret.append(insn)
if addr == last or \
(last[1] is None and addr[0] == last[0] and insn.has_flag(IOPT_ASM_END)):
# end of the range
break
return InsnList(ret)
def to_symbolic(self, in_state = None, temp_regs = True):
out_state = None if in_state is None else in_state.copy()
# update symbolic state with each instruction
for insn in self: out_state = insn.to_symbolic(out_state)
# remove temp registers from output state
if not temp_regs: out_state.remove_temp_regs()
return out_state
class TestInsnList(unittest.TestCase):
arch = ARCH_X86
def setUp(self):
import translator
self.tr = translator.Translator(self.arch)
from pyopenreil.utils import asm
self.asm = asm.Compiler(self.arch)
self.storage = CodeStorageMem(self.arch)
def test_get_range(self):
# add test data to the storage
self.storage.clear()
self.storage.put_insn(self.tr.to_reil(self.asm.compile('add eax, ecx'), addr = 0L))
# get InsnList instance
insn = self.storage.get_insn(0)
a = insn.get_range(None, last = None)
b = insn.get_range(None, last = 0)
c = insn.get_range(0, last = None)
d = insn.get_range(0, last = 0)
# check get_range with different combinations of None args
assert a == b == c == d
b = insn.get_range((0, 1), last = None)
c = insn.get_range(None, last = (0, 4))
d = insn.get_range((0, 1), last = (0, 4))
# check get_range with different ranges
assert a[1:] == b and a[:5] == c and a[1:5] == d
def test_to_symbolic(self):
# add test data to the storage
self.storage.clear()
self.storage.put_insn(self.tr.to_reil(self.asm.compile('add eax, ecx'), addr = 0L))
self.storage.put_insn(self.tr.to_reil(self.asm.compile('inc eax'), addr = 2L))
# get InsnList instance with both machine instructions
insn = InsnList(self.storage.get_insn(0) + self.storage.get_insn(2))
# get symbolic representation of EAX value
sym = insn.to_symbolic()
eax = sym[SymVal('R_EAX', U32)]
# check for valid expression
assert eax == SymVal('R_EAX', U32) + SymVal('R_ECX', U32) + SymConst(1, U32)
# expressions fuzzy matching
assert eax == SymVal('R_EAX', U32) + SymAny() + SymAny() \
== SymVal('R_EAX', U32) + SymVal('R_ECX', U32) + SymAny()
class BasicBlock(InsnList):
def __init__(self, insn_list):
super(BasicBlock, self).__init__(insn_list)
self.first, self.last = insn_list[0], insn_list[-1]
self.ir_addr = self.first.ir_addr()
self.size = self.last.addr + self.last.size - self.ir_addr[0]
def __str__(self):
return self.to_str(show_header = True, show_symbolic = True)
def to_str(self, show_header = True, show_symbolic = False):
ret = InsnList.__str__(self)
if show_header:
ret = '; BB %s : %s\n' % (self.first.ir_addr(), self.last.ir_addr()) + \
'; ' + '-' * 32 + '\n' + ret
if show_symbolic:
ret += '; ' + '-' * 32 + '\n'
for item in str(self.to_symbolic(temp_regs = False)).strip().split('\n'):
ret += '; %s\n' % item
return ret
def get_successors(self):
return self.last.next(), self.last.jcc_loc()
class TestBasicBlock(unittest.TestCase):
def test_x86(self):
arch = ARCH_X86
code = ( 'jne _l',
'nop',
'_l: ret' )
# create translator
from pyopenreil.utils import asm
tr = CodeStorageTranslator(asm.Reader(arch, code))
# translate basic block
bb = tr.get_bb(0)
print bb
# get successors
lhs, rhs = bb.get_successors()
# check for valid next instructions of JNE
assert lhs == Insn.IRAddr(( tr.get_insn(( 0, 0 )).size, 0 ))
assert rhs == Insn.IRAddr(( tr.get_insn(( 0, 0 )).size + 1, 0 ))
def test_thumb(self):
arch = ARCH_ARM
code = (
'push {r7}',
'cmp r0, #0',
'beq _l',
'movs r1, #1',
'_l: pop {r7}',
'mov pc, lr' )
# create translator
from pyopenreil.utils import asm
tr = CodeStorageTranslator(asm.Reader(arch, code, thumb = True))
# translate basic block
bb = tr.get_bb(arm_thumb(0))
print bb
# get successors
lhs, rhs = bb.get_successors()
# check for valid next instructions of JNE
assert lhs == Insn.IRAddr(( 0x05, 4 ))
assert rhs == Insn.IRAddr(( 0x09, 0 ))