Debian Codegraph @

ptrace/disasm.py

raw
1 """
2 Disassembler: only enabled if HAS_DISASSEMBLER is True.
3 """
4
5 try:
6 from ptrace.cpu_info import CPU_I386, CPU_X86_64
7 try:
8 from distorm3 import Decode
9 if CPU_X86_64:
10 from distorm3 import Decode64Bits as DecodeBits
11 MAX_INSTR_SIZE = 11
12 elif CPU_I386:
13 from distorm3 import Decode32Bits as DecodeBits
14 MAX_INSTR_SIZE = 8
15 else:
16 raise ImportError("CPU not supported")
17 DISTORM3 = True
18 except ImportError:
19 DISTORM3 = False
20 from ptrace.pydistorm import Decode
21 if CPU_X86_64:
22 from ptrace.pydistorm import Decode64Bits as DecodeBits
23 MAX_INSTR_SIZE = 11
24 elif CPU_I386:
25 from ptrace.pydistorm import Decode32Bits as DecodeBits
26 MAX_INSTR_SIZE = 8
27 else:
28 raise ImportError("CPU not supported")
29 from ptrace import PtraceError
30
31 class Instruction(object):
32 """
33 A CPU instruction.
34
35 Attributes:
36 - address (int): address of the instruction
37 - size (int): size of the instruction in bytes
38 - mnemonic (str): name of the instruction
39 - operands (str): string describing the operands
40 - hexa (str): bytes of the instruction as an hexadecimal string
41 - text (str): string representing the whole instruction
42 """
43
44 def __init__(self, instr):
45 if DISTORM3:
46 self.address, self.size, self.text, self.hexa = instr
47 else:
48 self.address = instr.offset
49 self.size = instr.size
50 self.hexa = str(instr.instructionHex)
51 self.text = "%s %s" % (instr.mnemonic, instr.operands)
52
53 def __str__(self):
54 return self.text
55
56 def disassemble(code, address=0x100):
57 """
58 Disassemble the specified byte string, where address is the
59 address of the first instruction.
60 """
61 for instr in Decode(address, code, DecodeBits):
62 yield Instruction(instr)
63
64 def disassembleOne(code, address=0x100):
65 """
66 Disassemble the first instruction of the byte string, where
67 address is the address of the instruction.
68 """
69 for instr in disassemble(code, address):
70 return instr
71 raise PtraceError("Unable to disassemble %r" % code)
72
73 HAS_DISASSEMBLER = True
74 except (ImportError, OSError):
75 # OSError if libdistorm64.so doesn't exist
76 HAS_DISASSEMBLER = False