blob: 1fba5929655c36ba3cc93b7c8b608fe594b51fbe [file] [log] [blame]
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +08001#!/usr/bin/env python
2
3# Capstone Python bindings, by Nguyen Anh Quynnh <aquynh@gmail.com>
4
5from capstone import *
6from capstone.mips import *
7
8MIPS_CODE = "\x0C\x10\x00\x97\x00\x00\x00\x00\x24\x02\x00\x0c\x8f\xa2\x00\x00\x34\x21\x34\x56"
9MIPS_CODE2 = "\x56\x34\x21\x34\xc2\x17\x01\x00"
10
11all_tests = (
12 (CS_ARCH_MIPS, CS_MODE_32 + CS_MODE_BIG_ENDIAN, MIPS_CODE, "MIPS-32 (Big-endian)"),
13 (CS_ARCH_MIPS, CS_MODE_64 + CS_MODE_LITTLE_ENDIAN, MIPS_CODE2, "MIPS-64-EL (Little-endian)"),
14)
15
danghvu1a7c4492013-11-27 22:51:11 -060016def to_hex(s):
17 return " ".join("0x" + "{0:x}".format(ord(c)).zfill(2) for c in s) # <-- Python 3 is OK
18
19def to_x(s):
20 from struct import pack
21 if not s: return '0'
22 x = pack(">q", s).encode('hex')
23 while x[0] == '0': x = x[1:]
24 return x
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080025
Nguyen Anh Quynh520c3612013-12-06 15:26:07 +080026### Test class Cs
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080027def test_class():
28 def print_insn_detail(insn):
29 # print address, mnemonic and operands
30 print("0x%x:\t%s\t%s" %(insn.address, insn.mnemonic, insn.op_str))
31
32 if len(insn.operands) > 0:
33 print("\top_count: %u" %len(insn.operands))
danghvu1a7c4492013-11-27 22:51:11 -060034 c = -1
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080035 for i in insn.operands:
36 c += 1
37 if i.type == MIPS_OP_REG:
38 print("\t\toperands[%u].type: REG = %s" %(c, insn.reg_name(i.value.reg)))
39 if i.type == MIPS_OP_IMM:
danghvu1a7c4492013-11-27 22:51:11 -060040 print("\t\toperands[%u].type: IMM = 0x%s" %(c, to_x(i.value.imm)))
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080041 if i.type == MIPS_OP_MEM:
42 print("\t\toperands[%u].type: MEM" %c)
43 if i.value.mem.base != 0:
44 print("\t\t\toperands[%u].mem.base: REG = %s" \
45 %(c, insn.reg_name(i.value.mem.base)))
46 if i.value.mem.disp != 0:
danghvu1a7c4492013-11-27 22:51:11 -060047 print("\t\t\toperands[%u].mem.disp: 0x%s" \
48 %(c, to_x(i.value.mem.disp)))
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080049
50
51 for (arch, mode, code, comment) in all_tests:
danghvu1a7c4492013-11-27 22:51:11 -060052 print("*" * 16)
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080053 print("Platform: %s" %comment)
danghvu1a7c4492013-11-27 22:51:11 -060054 print("Code: %s" % to_hex(code))
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080055 print("Disasm:")
danghvu1a7c4492013-11-27 22:51:11 -060056
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080057 try:
Nguyen Anh Quynh520c3612013-12-06 15:26:07 +080058 md = Cs(arch, mode)
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080059 for insn in md.disasm(code, 0x1000):
60 print_insn_detail(insn)
61 print
danghvu1a7c4492013-11-27 22:51:11 -060062
63 print "0x%x:\n" %(insn.address + insn.size)
Nguyen Anh Quynh26ee41a2013-11-27 12:11:31 +080064 except:
65 print("ERROR: Arch or mode unsupported!")
66
67
68test_class()