-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathcpu.py
5483 lines (4634 loc) · 203 KB
/
cpu.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
# Copyright (c) 2013, Felipe Andres Manzano
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import sys
import types
import weakref
from functools import wraps, partial
import collections
from capstone import *
from capstone.x86 import *
CapRegisters = ['(INVALID)', 'AH', 'AL', 'AX', 'BH', 'BL', 'BP', 'BPL', 'BX', 'CH', 'CL', 'CS', 'CX', 'DH', 'DI', 'DIL', 'DL', 'DS', 'DX', 'EAX', 'EBP', 'EBX', 'ECX', 'EDI', 'EDX', 'RFLAGS', 'EIP', 'EIZ', 'ES', 'ESI', 'ESP', 'FPSW', 'FS', 'GS', 'IP', 'RAX', 'RBP', 'RBX', 'RCX', 'RDI', 'RDX', 'RIP', 'RIZ', 'RSI', 'RSP', 'SI', 'SIL', 'SP', 'SPL', 'SS', 'CR0', 'CR1', 'CR2', 'CR3', 'CR4', 'CR5', 'CR6', 'CR7', 'CR8', 'CR9', 'CR10', 'CR11', 'CR12', 'CR13', 'CR14', 'CR15', 'DR0', 'DR1', 'DR2', 'DR3', 'DR4', 'DR5', 'DR6', 'DR7', 'FP0', 'FP1', 'FP2', 'FP3', 'FP4', 'FP5', 'FP6', 'FP7', 'K0', 'K1', 'K2', 'K3', 'K4', 'K5', 'K6', 'K7', 'MM0', 'MM1', 'MM2', 'MM3', 'MM4', 'MM5', 'MM6', 'MM7', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15', 'ST0', 'ST1', 'ST2', 'ST3', 'ST4', 'ST5', 'ST6', 'ST7', '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', 'R8B', 'R9B', 'R10B', 'R11B', 'R12B', 'R13B', 'R14B', 'R15B', 'R8D', 'R9D', 'R10D', 'R11D', 'R12D', 'R13D', 'R14D', 'R15D', 'R8W', 'R9W', 'R10W', 'R11W', 'R12W', 'R13W', 'R14W', 'R15W']
from smtlib import ITEBV as ITE, Bool, BitVec, Array, issymbolic, ZEXTEND, SEXTEND, ord, chr, OR, AND, CONCAT, UDIV, UREM, ULT, UGT, ULE, EXTRACT, isconcrete
import logging
logger = logging.getLogger("CPU")
###############################################################################
#Exceptions..
class DecodeException(Exception):
''' You tried to decode an unknown or invalid intruction '''
def __init__(self, pc, bytes, extra):
super(DecodeException,self).__init__("Error decoding instruction @%08x", pc)
self.pc=pc
self.bytes=bytes
self.extra=extra
class InvalidPCException(Exception):
''' Exception raised when you try to execute invalid or not executable memory
'''
def __init__(self, pc):
super(InvalidPCException, self).__init__("Trying to execute invalid memory @%08x", pc)
self.pc=pc
class InstructionNotImplemented(Exception):
''' Exception raised when you try to execute an instruction that is
not yet implemented in the emulator.
Go to cpu.py and add it!
'''
pass
class DivideError(Exception):
''' A division by zero '''
pass
class Interruption(Exception):
''' '''
def __init__(self, N):
super(Interruption,self).__init__("CPU Software Interruption %08x", N)
self.N = N
class Syscall(Exception):
''' '''
def __init__(self):
super(Syscall, self).__init__("CPU Syscall")
class SymbolicLoopException(Exception):
''' '''
def __init__(self, reg_name):
super(SymbolicLoopException, self).__init__("Symbolic Loop")
self.reg_name = reg_name
class SymbolicPCException(Exception):
''' '''
def __init__(self, symbol):
super(SymbolicPCException, self).__init__("Symbolic PC")
self.symbol = symbol
###############################################################################
#Auxiliar decorators...
def memoized(cache_name):
def wrap(old_method):
@wraps(old_method)
def new_method(obj, *args):
cache = getattr(obj, cache_name)
if args in cache:
return cache[args]
else:
value = old_method(obj, *args)
cache[args] = value
return value
return new_method
return wrap
#Instruction decorators
def instruction(old_method):
#This should decorate every instruction implementation
@wraps(old_method)
def new_method(cpu, *args, **kw_args):
cpu.PC += cpu.instruction.size
return old_method(cpu,*args,**kw_args)
return new_method
def rep(old_method):
#This decorate every REP enabled instruction implementation
@wraps(old_method)
def new_method(cpu, *args, **kw_args):
prefix = cpu.instruction.prefix
if (X86_PREFIX_REP in prefix) or (X86_PREFIX_REPNE in prefix):
counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.instruction.addr_size*8]
count = cpu.getRegister(counter_name)
if issymbolic(count):
raise SymbolicLoopException(counter_name)
cpu.IF = count != 0
#Repeate!
if cpu.IF:
old_method(cpu, *args, **kw_args)
count -= 1
#if 'FLAG_REPNZ' in cpu.instruction.flags:
if X86_PREFIX_REP in prefix:
cpu.IF = count !=0 #AND(cpu.ZF == False, count != 0) #true IF means loop
#elif 'FLAG_REPZ' in cpu.instruction.flags:
elif X86_PREFIX_REPNE in prefix:
cpu.IF = cpu.ZF == False #true IF means loop
cpu.setRegister(counter_name, count)
cpu.PC = ITE(cpu.AddressSize, cpu.IF, cpu.PC, cpu.PC + cpu.instruction.size)
#Advance!
else:
cpu.PC = cpu.PC + cpu.instruction.size
else:
cpu.PC += cpu.instruction.size
old_method(cpu, *args,**kw_args)
return new_method
###############################################################################
#register/flag descriptors
class Flag(object):
value = False
def __get__(self, obj, type=None):
return self.value
def __set__(self, obj, value):
assert isinstance(val, (bool,Bool))
self.value = value
class Register16(object):
'''
16 bit register.
'''
value = False
def __get__(self, obj, type=None):
return self.value
def __set__(self, obj, value):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 16)
self.value = value
class Register256(object):
'''
256 bit register.
'''
def __init__(self):
self._YMM = 0
self._cache = {}
def setYMM(self, val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 256)
self._YMM = val
self._cache = {}
return self._YMM
def getYMM(self):
return self._YMM
def setXMM(self, val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 128)
self._YMM = ZEXTEND(val,256) #TODO
self._cache = { 'XMM': val }
return val
def getXMM(self):
return self._cache.setdefault('XMM', EXTRACT(self._YMM,0,128) )
class Register64(object):
'''
64 bit register.
'''
def __init__(self):
self._RX = 0
self._cache = {}
def setRX(self, val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 64)
val = EXTRACT(val, 0, 64)
self._RX = val
self._cache = {}
return val
def getRX(self):
return self._RX
def setEX(self,val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 32)
val = EXTRACT(val, 0, 32)
self._RX = ZEXTEND(val,64)
self._cache = { 'EX': EXTRACT(val, 0,32) }
return val
def getEX(self):
return self._cache.setdefault('EX', EXTRACT(self._RX, 0,32))
def setX(self, val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 16)
val = EXTRACT(val, 0,16)
self._RX = self._RX & 0xFFFFFFFFFFFF0000 | ZEXTEND(val,64)
self._cache = { 'X': val}
return val
def getX(self):
return self._cache.setdefault('X', EXTRACT(self._RX, 0,16))
def setH(self, val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 8)
val = EXTRACT(val, 0,8)
self._RX = self._RX & 0xFFFFFFFFFFFF00FF | ZEXTEND(val,64) << 8
self._cache = {'H': val, 'L': self.getL()}
return val
def getH(self):
return self._cache.setdefault('H', EXTRACT(self._RX, 8,8))
def setL(self, val):
assert isinstance(val, (int,long)) or (isinstance(val, BitVec) and val.size == 8)
val = EXTRACT(val, 0,8)
self._RX = self._RX & 0xFFFFFFFFFFFFFF00 | ZEXTEND(val,64)
self._cache = {'L': val, 'H': self.getH()}
return val
def getL(self):
return self._cache.setdefault('L', EXTRACT(self._RX, 0,8))
def prop(attr, size):
get = eval('lambda self: self.%s.get%s()'%(attr,size))
put = eval('lambda self, value: self.%s.set%s(value)'%(attr,size))
return property (get, put)
###############################################################################
#Main CPU class
class Cpu(object):
'''
A CPU model.
'''
def __init__(self, memory, machine='i386'):
'''
Builds a CPU model.
@param memory: memory object for this CPU.
@param machine: machine code name. Supported machines: C{'i386'} and C{'amd64'}.
'''
assert machine in ['i386','amd64']
#assert machine in ['i386'] , "Platform not supportes by translate"
self.mem = memory #Shall have getchar and putchar methods.
self.icount = 0
self.machine = machine
self.AddressSize = {'i386':32, 'amd64':64}[self.machine]
self.PC_name = {'i386': 'EIP', 'amd64': 'RIP'}[self.machine]
self.STACK_name = {'i386': 'ESP', 'amd64': 'RSP'}[self.machine]
self.FRAME_name = {'i386': 'EBP', 'amd64': 'RBP'}[self.machine]
self.segments = {'GS': {}, 'FS': {}}
#caches
self.instruction_cache = {}
# cache[where] => (value,size)
self.mem_cache = {}
self.mem_cache_used = {}
# Adding convenience methods to Cpu class for accessing registers
for reg in ['RAX', 'RCX', 'RDX', 'RBX', 'RSP', 'RBP', 'RSI', 'RDI', 'R8',
'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15', 'RIP']:
setattr(self, '_%s'%reg, Register64())
for reg in ['_YMM0', '_YMM1', '_YMM2', '_YMM3', '_YMM4', '_YMM5',
'_YMM6', '_YMM7', '_YMM8', '_YMM9', '_YMM10', '_YMM11',
'_YMM12', '_YMM13', '_YMM14', '_YMM15']:
setattr(self, reg, Register256())
for reg in ['ES', 'CS', 'SS', 'DS', 'FS', 'GS' ]:
setattr(self, '%s'%reg, 0)
for reg in ['CF','PF','AF','ZF','SF','DF','OF','IF']:
setattr(self, reg, False)
logger.info("Cpu Initialized.")
RIP = prop('_RIP', 'RX')
EIP = prop('_RIP', 'EX')
IP = prop('_RIP', 'X')
RSP = prop('_RSP', 'RX')
ESP = prop('_RSP', 'EX')
SP = prop('_RSP', 'X')
SPL = prop('_RSP', 'L')
RBP = prop('_RBP', 'RX')
EBP = prop('_RBP', 'EX')
BP = prop('_RBP', 'X')
BPL = prop('_RBP', 'L')
RAX = prop('_RAX', 'RX')
EAX = prop('_RAX', 'EX')
AX = prop('_RAX', 'X')
AH = prop('_RAX', 'H')
AL = prop('_RAX', 'L')
RBX = prop('_RBX', 'RX')
EBX = prop('_RBX', 'EX')
BX = prop('_RBX', 'X')
BH = prop('_RBX', 'H')
BL = prop('_RBX', 'L')
RCX = prop('_RCX', 'RX')
ECX = prop('_RCX', 'EX')
CX = prop('_RCX', 'X')
CH = prop('_RCX', 'H')
CL = prop('_RCX', 'L')
RDX = prop('_RDX', 'RX')
EDX = prop('_RDX', 'EX')
DX = prop('_RDX', 'X')
DH = prop('_RDX', 'H')
DL = prop('_RDX', 'L')
RSI = prop('_RSI', 'RX')
ESI = prop('_RSI', 'EX')
SI = prop('_RSI', 'X')
SIL = prop('_RSI', 'L')
RDI = prop('_RDI', 'RX')
EDI = prop('_RDI', 'EX')
DI = prop('_RDI', 'X')
DIL = prop('_RDI', 'L')
R8 = prop('_R8', 'RX')
R8D = prop('_R8', 'EX')
R8W = prop('_R8', 'X')
R8B = prop('_R8', 'L')
R9 = prop('_R9', 'RX')
R9D = prop('_R9', 'EX')
R9W = prop('_R9', 'X')
R9B = prop('_R9', 'L')
R10 = prop('_R10', 'RX')
R10D = prop('_R10', 'EX')
R10W = prop('_R10', 'X')
R10B = prop('_R10', 'L')
R11 = prop('_R11', 'RX')
R11D = prop('_R11', 'EX')
R11W = prop('_R11', 'X')
R11B = prop('_R11', 'L')
R12 = prop('_R12', 'RX')
R12D = prop('_R12', 'EX')
R12W = prop('_R12', 'X')
R12B = prop('_R12', 'L')
R13 = prop('_R13', 'RX')
R13D = prop('_R13', 'EX')
R13W = prop('_R13', 'X')
R13B = prop('_R13', 'L')
R14 = prop('_R14', 'RX')
R14D = prop('_R14', 'EX')
R14W = prop('_R14', 'X')
R14B = prop('_R14', 'L')
R15 = prop('_R15', 'RX')
R15D = prop('_R15', 'EX')
R15W = prop('_R15', 'X')
R15B = prop('_R15', 'L')
XMM0 = prop('_YMM0', 'XMM')
YMM0 = prop('_YMM0', 'YMM')
XMM1 = prop('_YMM1', 'XMM')
YMM1 = prop('_YMM1', 'YMM')
XMM2 = prop('_YMM2', 'XMM')
YMM2 = prop('_YMM2', 'YMM')
XMM3 = prop('_YMM3', 'XMM')
YMM3 = prop('_YMM3', 'YMM')
XMM4 = prop('_YMM4', 'XMM')
YMM4 = prop('_YMM4', 'YMM')
XMM5 = prop('_YMM5', 'XMM')
YMM5 = prop('_YMM5', 'YMM')
XMM6 = prop('_YMM6', 'XMM')
YMM6 = prop('_YMM6', 'YMM')
XMM7 = prop('_YMM7', 'XMM')
YMM7 = prop('_YMM7', 'YMM')
XMM8 = prop('_YMM8', 'XMM')
YMM8 = prop('_YMM8', 'YMM')
XMM9 = prop('_YMM9', 'XMM')
YMM9 = prop('_YMM9', 'YMM')
XMM10 = prop('_YMM10', 'XMM')
YMM10 = prop('_YMM10', 'YMM')
XMM11 = prop('_YMM11', 'XMM')
YMM11 = prop('_YMM11', 'YMM')
XMM12 = prop('_YMM12', 'XMM')
YMM12 = prop('_YMM12', 'YMM')
XMM13 = prop('_YMM13', 'XMM')
YMM13 = prop('_YMM13', 'YMM')
XMM14 = prop('_YMM14', 'XMM')
YMM14 = prop('_YMM14', 'YMM')
XMM15 = prop('_YMM15', 'XMM')
YMM15 = prop('_YMM15', 'YMM')
def listRegisters(self):
'''
Returns the list of registers for this CPU.
@rtype: list
@return: the list of register names for this CPU.
'''
return ['RAX', 'EAX', 'AX', 'AL', 'AH', 'RCX', 'ECX', 'CX', 'CL', 'CH',
'RDX', 'EDX', 'DX', 'DL', 'DH', 'RBX', 'EBX', 'BX', 'BL', 'BH',
'RSP', 'ESP', 'SP', 'SPL', 'RBP', 'EBP', 'BP', 'BPL', 'RSI',
'ESI', 'SI', 'SIL', 'RDI', 'EDI', 'DI', 'DIL', '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', 'ES', 'CS', 'SS', 'DS',
'FS', 'GS', 'RIP', 'EIP', 'IP','RFLAGS','EFLAGS','FLAGS',
'XMM0', 'XMM1', 'XMM2', 'XMM3', 'XMM4', 'XMM5', 'XMM6', 'XMM7',
'XMM8', 'XMM9', 'XMM10', 'XMM11', 'XMM12', 'XMM13', 'XMM14',
'XMM15', 'YMM0', 'YMM1', 'YMM2', 'YMM3', 'YMM4', 'YMM5', 'YMM6',
'YMM7', 'YMM8', 'YMM9', 'YMM10', 'YMM11', 'YMM12', 'YMM13',
'YMM14', 'YMM15','CF','SF','ZF','OF','AF', 'PF', 'IF']
def setRegister(self, name, value):
'''
Updates a register value
@param name: the register name to update its value
@param value: the new value for the register.
'''
assert name in self.listRegisters()
setattr(self, name, value)
return value
def getRegister(self, name):
'''
Obtains the current value of a register
@rtype: int
@param name: the register name to obtain its value
@return: the value of the register
'''
assert name in self.listRegisters()
return getattr(self, name)
def __getstate__(self):
state = {}
state['machine'] = self.machine
state['icount'] = self.icount
state['regs'] = {}
for name in ['_RAX', '_RCX', '_RDX', '_RBX', '_RSP', '_RBP', '_RSI',
'_RDI', '_R8', '_R9', '_R10', '_R11', '_R12', '_R13',
'_R14', '_R15', '_RIP',
'ES', 'CS', 'SS', 'DS', 'FS', 'GS', 'CF',
'PF','AF','ZF','SF','DF','OF','IF',
'_YMM0', '_YMM1', '_YMM2', '_YMM3', '_YMM4', '_YMM5',
'_YMM6', '_YMM7', '_YMM8', '_YMM9', '_YMM10', '_YMM11',
'_YMM12', '_YMM13', '_YMM14', '_YMM15']:
state['regs'][name] = getattr(self,name)
state['mem'] = self.mem
state['segments'] = self.segments
state['mem_cache'] = self.mem_cache
state['mem_cache_used'] = self.mem_cache_used
return state
def __setstate__(self, state):
self.machine = state['machine']
self.icount = state['icount']
for name in ['_RAX', '_RCX', '_RDX', '_RBX', '_RSP', '_RBP', '_RSI',
'_RDI', '_R8', '_R9', '_R10', '_R11', '_R12', '_R13',
'_R14', '_R15', '_RIP', 'ES', 'CS', 'SS', 'DS', 'FS',
'GS', 'CF', 'PF','AF','ZF','SF','DF','OF','IF', '_YMM0',
'_YMM1', '_YMM2', '_YMM3', '_YMM4', '_YMM5', '_YMM6',
'_YMM7', '_YMM8', '_YMM9', '_YMM10', '_YMM11', '_YMM12',
'_YMM13', '_YMM14', '_YMM15']:
setattr(self, name, state['regs'][name])
self.AddressSize = {'i386':32, 'amd64':64}[self.machine]
self.PC_name = {'i386': 'EIP', 'amd64': 'RIP'}[self.machine]
self.STACK_name = {'i386': 'ESP', 'amd64': 'RSP'}[self.machine]
self.FRAME_name = {'i386': 'EBP', 'amd64': 'RBP'}[self.machine]
self.mem = state['mem']
self.segments = state['segments']
self.mem_cache = state['mem_cache']
self.mem_cache_used = state['mem_cache_used']
self.instruction_cache = {}
_flags={
'CF': 0x00001,
'PF': 0x00004,
'AF': 0x00010,
'ZF': 0x00040,
'SF': 0x00080,
'DF': 0x00400,
'OF': 0x00800,
'IF': 0x10000,
}
base_flags = 0
def setRFLAGS(self, value):
'''
Setter for RFLAGS.
@param value: new value for RFLAGS.
'''
for name, mask in self._flags.items():
setattr(self, name, value & mask !=0)
self.base_flags = value
def getRFLAGS(self):
'''
Getter for RFLAGS.
@rtype: int
@return: current RFLAGS value.
'''
reg = 0
for name, mask in self._flags.items():
reg |= ITE(64, getattr(self, name), mask, 0)
return reg | ZEXTEND(self.base_flags & ~ (0x00001|0x00004|0x00010|0x00040|0x00080|0x00400|0x00800|0x10000), 64)
def getEFLAGS(self):
'''
Getter for EFLAGS.
@rtype: int
@return: current EFLAGS value.
'''
return EXTRACT(self.getRFLAGS(),0,32)
def getFLAGS(self):
'''
Getter for FLAGS.
@rtype: int
@return: current FLAGS value.
'''
return EXTRACT(self.getRFLAGS(),0,16)
RFLAGS = property(getRFLAGS, setRFLAGS)
EFLAGS = property(getEFLAGS, setRFLAGS)
FLAGS = property(getFLAGS, setRFLAGS)
#Special Registers
def getPC(self):
'''
Returns the current program counter.
@rtype: int
@return: the current program counter value.
'''
return getattr(self, self.PC_name)
def setPC(self, value):
'''
Changes the program counter value.
@param value: the new value for the program counter.
'''
return setattr(self, self.PC_name, value)
PC = property(getPC,setPC)
def getSTACK(self):
'''
Returns the stack pointer.
@rtype: int
@return: the current value for the stack pointer.
'''
return self.getRegister(self.STACK_name)
def setSTACK(self, value):
'''
Changes the stack pointer value.
@param value: the new value for the stack pointer.
'''
return self.setRegister(self.STACK_name,value)
STACK = property(getSTACK, setSTACK)
def getFRAME(self):
'''
Returns the base pointer.
@rtype: int
@return: the current value of the base pointer.
'''
return self.getRegister(self.FRAME_name)
def setFRAME(self, value):
'''
Changes the base pointer value.
@param value: the new value for the base pointer.
'''
return self.setRegister(self.FRAME_name,value)
FRAME = property(getFRAME, setFRAME)
def dumpregs(self):
'''
Returns the current registers values.
@rtype: str
@return: a string containing the name and current value for all the registers.
'''
CHEADER = '\033[95m'
CBLUE = '\033[94m'
CGREEN = '\033[92m'
CWARNING = '\033[93m'
CFAIL = '\033[91m'
CEND = '\033[0m'
result = ""
pos = 0
for reg_name in ['RAX', 'RCX', 'RDX', 'RBX', 'RSP', 'RBP', 'RSI', 'RDI', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15', 'RIP',]:
value = getattr(self, reg_name)
if issymbolic(value):
result += "%3s: "%reg_name + CFAIL+"%16s"%value+CEND+''
else:
result += "%3s: 0x%016x"%(reg_name, value)
pos = 0
result += '\n'
pos = 0
for reg_name in ['CF','SF','ZF','OF','AF', 'PF', 'IF']:
value = getattr(self, reg_name)
if issymbolic(value):
result += "%s:"%reg_name + CFAIL+ "%16s"%value+CEND
else:
result += "%s: %1x"%(reg_name, value)
pos = 0
result += '\n'
return result
####################
#Basic Memory Access
def write(self, where, data):
'''
Writes C{data} in the address C{where}.
@param where: address to write the data C{data}.
@param data: the data to write in the address C{where}.
'''
for c in data:
self.store(where, ord(c), 8) #TODO: fix chr/ord redundancy + putcache use
where += 1
def read(self, where, size):
'''
Writes C{data} in the address C{where}.
@param where: address to read the data C{data} from.
@param size: number of bytes.
'''
result = ''
for i in range(size):
result += chr(self.load(where+i,8))
return result
#@putcache("mem_cache")
def store(self, where, expr, size):
'''
Writes a little endian value in memory.
@param where: the address in memory where to store the value.
@param expr: the value to store in memory.
@param size: the amount of bytes to write.
'''
assert size in [8, 16, 32, 64, 128, 256]
for i in xrange(0,size,8):
if i == 0:
self.mem.putchar(where, chr(expr))
else:
self.mem.putchar(where+i/8, chr(expr>>i))
#@getcache("mem_cache")
def load(self, where, size):
'''
Reads a little endian value of C{size} bits from memory at address C{where}.
@rtype: int or L{BitVec}
@param where: the address to read from.
@param size: the number of bits to read.
@return: the value read.
'''
return CONCAT(8, *[ord(self.mem.getchar(where+i/8)) for i in reversed(xrange(0,size,8))])
#expr = 0
#for i in xrange(0,size,8):
# expr = expr | (ZEXTEND(ord(self.mem.getchar(where+i/8)),size) << i)
#return expr
def store_int(self, where, expr):
self.store(where, expr, self.AddressSize)
def load_int(self, where):
return self.load(where, self.AddressSize)
#
def push(cpu, value, size):
'''
Writes a value in the stack.
@param value: the value to put in the stack.
@param size: the size of the value.
'''
assert size in [ 8, 16, cpu.AddressSize ]
cpu.STACK = cpu.STACK-size/8
cpu.store(cpu.STACK, value, size)
def pop(cpu, size):
'''
Gets a value from the stack.
@rtype: int
@param size: the size of the value to consume from the stack.
@return: the value from the stack.
'''
assert size in [ 16, cpu.AddressSize ]
value = cpu.load(cpu.STACK, size)
cpu.STACK = cpu.STACK + size/8
return value
@memoized('instruction_cache') #No dynamic code!!! #TODO!
def getInstructionCapstone(cpu, pc):
text = ''
try:
for i in xrange(0,16):
text += cpu.mem.getchar(pc+i)
except Exception, e:
pass
arch = {'i386': CS_ARCH_X86, 'amd64': CS_ARCH_X86}[cpu.machine]
mode = {'i386': CS_MODE_32, 'amd64': CS_MODE_64}[cpu.machine]
md = Cs(arch, mode)
md.detail = True
md.syntax = 0
instruction = None
for i in md.disasm(text, pc):
instruction = i
break
if instruction is None:
print '-'*60
import pdb
pdb.set_trace()
#Fix/aument opperands so it can access cpu/memory
for op in instruction.operands:
op.read=types.MethodType(cpu.readOperandCapstone, op)
op.write=types.MethodType(cpu.writeOperandCapstone, op)
op.address=types.MethodType(cpu.getOperandAddressCapstone, op)
op.size *= 8
return instruction
def getOperandAddressCapstone(cpu,o):
address = 0
if o.mem.segment != 0:
seg = cpu.instruction.reg_name(o.mem.segment).upper()
if seg in cpu.segments:
address += cpu.segments[seg][cpu.getRegister(seg)]
if o.mem.base != 0:
base = cpu.instruction.reg_name(o.mem.base).upper()
address += cpu.getRegister(base)
if o.mem.index != 0:
index = cpu.instruction.reg_name(o.mem.index).upper()
address += o.mem.scale*cpu.getRegister(index)
if o.mem.disp != 0:
address += o.mem.disp
return address & ((1<<cpu.AddressSize)-1)
def readOperandCapstone(cpu, o):
if o.type == X86_OP_REG:
return cpu.getRegister(cpu.instruction.reg_name(o.reg).upper())
elif o.type == X86_OP_IMM:
return o.imm
elif o.type == X86_OP_MEM:
return cpu.load(o.address(), o.size)
else:
raise NotImplemented("readOperand unknown type", o.type)
def writeOperandCapstone(cpu, o, value):
if o.type == X86_OP_REG:
cpu.setRegister(cpu.instruction.reg_name(o.reg).upper(), value)
elif o.type == X86_OP_MEM:
cpu.store(o.address(), value, o.size)
else:
raise NotImplemented()
return value
#TODO: erradicate stupid flag functions
def calculateFlags(self, op, size, res, arg0=0, arg1=0):
'''
Changes the value of the flags after an operation.
@param op: the operation that was performed.
@param size: the size of the operands.
@param res: the result of the operation.
@param arg0: the first argument of the operation.
@param arg1: the second argument of the operation.
'''
MASK = (1<<size)-1
SIGN_MASK = 1<<(size-1)
res = res & MASK
arg0 = arg0 & MASK
arg1 = arg1 & MASK
'''Carry Flag.
Set if an arithmetic operation generates a carry or a borrow out
of the most-significant bit of the result; cleared otherwise. This flag indi-
cates an overflow condition for unsigned-integer arithmetic. It is also used
in multiple-precision arithmetic.
'''
if op in ['ADC']:
self.CF = OR(ULT(res, arg0), AND(self.CF, res == arg0))
elif op in ['ADD']:
self.CF = OR( ULT(res, arg0), ULT(res, arg1))
elif op in ['CMP', 'SUB']:
self.CF = ULT(arg0, arg1)
elif op in ['SBB']:
self.CF = ULT(arg0, res) | (self.CF & (arg1==MASK))
elif op in ['LOGIC']:
self.CF = False #cleared
elif op in ['NEG']:
self.CF = arg0 != 0
elif op in ['SHL']:
#self.CF = ITE(1, UGT(arg1,size), False, 0 != (arg0 >> (size-arg1))&1)
self.CF = ( ULE(arg1,size)) | ( 0 != (arg0 >> (size-arg1))&1)
elif op in ['SHR']:
if isinstance(arg1, (long,int)) and arg1 > 0 :
self.CF = 0 != ((arg0 >> (arg1 - 1))&1) #Shift one less than normally and keep LSB
else:
#symbol friendly op
self.CF = ITE(1, arg1>0, 0 != ((arg0 >> (arg1 - 1))&1), self.CF) !=0
elif op in ['SAR']:
if arg1>0 :
self.CF = 0 != ((arg0 // ( 1 << (arg1 - 1) ))&1) #Shift(SIGNED) one less than normally and keep LSB
elif op in ['SHL']:
self.CF = 0 != ((arg0 >> (size - arg1)) & 1)
elif op in ['AAA', 'DEC', 'INC']:
pass #undefined / Not Affected
else:
raise NotImplemented()
'''Adjust flag.
Set if an arithmetic operation generates a carry or a borrow
out of bit 3 of the result; cleared otherwise. This flag is used in binary-
coded decimal (BCD) arithmetic.
'''
if op in ['ADC', 'ADD', 'CMP', 'SBB', 'SUB' ]:
self.AF = ((arg0 ^ arg1) ^ res) & 0x10 != 0
elif op in ['DEC']:
self.AF= (res & 0x0f) == 0x0f
elif op in ['INC']:
self.AF= (res & 0x0f) == 0x00
elif op in ['NEG']:
#self.AF=((0 ^ (-res)) ^ res) & 0x10 != 0
self.AF= (res & 0x0f) == 0x00
elif op in ['AAA', 'SHL', 'SAR', 'SHR']:
self.AF = False
pass #undefined
elif op in ['LOGIC']:
self.AF = False
else:
raise NotImplemented()
'''Zero flag.
Set if the result is zero; cleared otherwise.
'''
if op in ['ADC', 'ADD', 'CMP', 'LOGIC', 'NEG', 'DEC', 'INC', 'SBB', 'SUB', 'SHL', 'SHR', 'SAR']:
self.ZF = res == 0
else:
raise NotImplemented()
'''Sign flag.
Set equal to the most-significant bit of the result, which is the
sign bit of a signed integer. (0 indicates a positive value and 1 indicates a
negative value.)
'''
if op in ['ADC', 'ADD', 'LOGIC', 'NEG', 'DEC', 'INC', 'CMP', 'SBB', 'SUB', 'SHL', 'SHR', 'SAR']:
self.SF = (res & SIGN_MASK)!=0
else:
raise NotImplemented()
'''Overflow flag.
Set if the integer result is too large a positive number or
too small a negative number (excluding the sign-bit) to fit in the destina-
tion operand; cleared otherwise. This flag indicates an overflow condition
for signed-integer (two's complement) arithmetic.
'''
if op in ['ADC', 'ADD']:
self.OF = (((arg0 ^ arg1 ^ SIGN_MASK) & (res ^ arg1)) & SIGN_MASK) != 0
elif op in ['CMP', 'SBB', 'SUB']:
sign0 = (arg0 & SIGN_MASK) ==SIGN_MASK
sign1 = (arg1 & SIGN_MASK) ==SIGN_MASK
signr = (res & SIGN_MASK) ==SIGN_MASK
self.OF = AND(sign0 ^ sign1, sign0 ^ signr) #(((arg0 ^ arg1& SIGN_MASK ) & (arg0 ^ res& SIGN_MASK)& SIGN_MASK) & SIGN_MASK) != 0
elif op in ['LOGIC']:
self.OF = False #cleared
elif op in ['DEC']:
self.OF = res == ~SIGN_MASK
elif op in ['INC', 'NEG']:
self.OF = res == SIGN_MASK
elif op in ['SHL']:
self.OF = 0 != ((res ^ arg0) & SIGN_MASK)
elif op in ['SHR']:
self.OF = AND(arg1 == 1, arg0 & SIGN_MASK != 0)
# self.OF = ITE(1,arg1 == 1, 0 != (arg0>>(size-1))&1, False)
elif op in ['SAR']:
self.OF = False
elif op in ['AAA']:
pass #undefined
else:
raise NotImplemented()
'''Parity flag.
Set if the least-significant byte of the result contains an even
number of 1 bits; cleared otherwise.
'''
if op in ['ADC', 'ADD', 'CMP', 'SUB', 'SBB', 'LOGIC', 'NEG', 'DEC', 'INC', 'SHL', 'SHR', 'SAR']:
self.PF = (res ^ res>>1 ^ res>>2 ^ res>>3 ^ res>>4 ^ res>>5 ^ res>>6 ^ res>>7)&1 == 0
else:
raise NotImplemented()
#End calculate flags
def execute(cpu):
''' Decode, and execute one intruction pointed by register PC'''
if not isinstance(cpu.PC, (int,long)):
raise SymbolicPCException(cpu.PC)
if not cpu.mem.isExecutable(cpu.PC):
raise InvalidPCException(cpu.PC)
instruction = cpu.getInstructionCapstone(cpu.PC)
cpu.instruction = instruction #FIX
#Check if we already have an implementation...
name = instruction.insn_name().upper()
if name == 'JNE':
name = 'JNZ'
if name == 'JE':
name = 'JZ'
if name == 'CMOVE':
name = 'CMOVZ'
if name == 'CMOVNE':
name = 'CMOVNZ'
if name in ['MOVUPS', 'MOVABS']:
name = 'MOV'
if instruction.mnemonic.upper() in ['REP MOVSB', 'REP MOVSW', 'REP MOVSD']:
name = 'MOVS'
if name == 'SETNE':
name = 'SETNZ'
if name == 'SETE':
name = 'SETZ'
if name in ['STOSD', 'STOSB' , 'STOSW', 'STOSQ']:
name = 'STOS'
if name in ['SCASD', 'SCASB' , 'SCASW', 'SCASQ']:
name = 'SCAS'
if not hasattr(cpu, name):
raise InstructionNotImplemented( "Instruction %s at %x Not Implemented (text: %s)" %
(name, cpu.PC, str(instruction.bytes).encode('hex')) )
#log
if logger.level == logging.DEBUG :
logger.debug("INSTRUCTION: 0x%016x:\t%s\t%s", instruction.address, instruction.mnemonic, instruction.op_str)
for l in cpu.dumpregs().split('\n'):
logger.debug(l)
implementation = getattr(cpu, name)
implementation(*instruction.operands)
#housekeeping