Skip to content

Instantly share code, notes, and snippets.

@hugsy
Created September 4, 2014 00:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hugsy/9882f26a8a3323c8ee74 to your computer and use it in GitHub Desktop.
Save hugsy/9882f26a8a3323c8ee74 to your computer and use it in GitHub Desktop.
Using Capstone engine as disassembler in Python-Ptrace
--- ptrace/disasm.c 2014-04-10 10:30:33.000000000 +1200
+++ ptrace/disasm2.c 2014-09-04 12:52:53.425315639 +1200
@@ -4,28 +4,21 @@
try:
from ptrace.cpu_info import CPU_I386, CPU_X86_64
- try:
- from distorm3 import Decode
- if CPU_X86_64:
- from distorm3 import Decode64Bits as DecodeBits
- MAX_INSTR_SIZE = 11
- elif CPU_I386:
- from distorm3 import Decode32Bits as DecodeBits
- MAX_INSTR_SIZE = 8
- else:
- raise ImportError("CPU not supported")
- DISTORM3 = True
- except ImportError as err:
+
DISTORM3 = False
- from ptrace.pydistorm import Decode
+ import capstone
+ print("Using Capstone Engine v.{}".format("-".join([str(x) for x in capstone.version_bind()])))
+
if CPU_X86_64:
- from ptrace.pydistorm import Decode64Bits as DecodeBits
MAX_INSTR_SIZE = 11
+ md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
elif CPU_I386:
- from ptrace.pydistorm import Decode32Bits as DecodeBits
MAX_INSTR_SIZE = 8
+ md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
else:
+ # todo add other archs
raise ImportError("CPU not supported")
+
from ptrace import PtraceError
class Instruction(object):
@@ -41,13 +34,11 @@
- text (str): string representing the whole instruction
"""
def __init__(self, instr):
- if DISTORM3:
- self.address, self.size, self.text, self.hexa = instr
- else:
- self.address = instr.offset
+ self.address = instr.address
+ self.text = "%s %s" % (instr.mnemonic, instr.op_str)
self.size = instr.size
- self.hexa = str(instr.instructionHex)
- self.text = "%s %s" % (instr.mnemonic, instr.operands)
+ self.hexa = "".join( [ "%x"%x for x in instr.bytes] )
+ return
def __str__(self):
return self.text
@@ -57,7 +48,7 @@
Disassemble the specified byte string, where address is the
address of the first instruction.
"""
- for instr in Decode(address, code, DecodeBits):
+ for instr in md.disasm(code, address):
yield Instruction(instr)
def disassembleOne(code, address=0x100):
@@ -65,12 +56,12 @@
Disassemble the first instruction of the byte string, where
address is the address of the instruction.
"""
- for instr in disassemble(code, address):
- return instr
+ for instr in md.disasm(code, address):
+ return Instruction(instr)
raise PtraceError("Unable to disassemble %r" % code)
HAS_DISASSEMBLER = True
+
except (ImportError, OSError) as err:
- # OSError if libdistorm64.so doesn't exist
+ # if failed to import capstone
HAS_DISASSEMBLER = False
-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment