1#!/usr/bin/env python
2
3# Capstone Python bindings, by Nguyen Anh Quynnh <aquynh@gmail.com>
4
5from __future__ import print_function
6from capstone import *
7from capstone.sparc import *
8from xprint import to_hex, to_x_32
9
10
11SPARC_CODE = b"\x80\xa0\x40\x02\x85\xc2\x60\x08\x85\xe8\x20\x01\x81\xe8\x00\x00\x90\x10\x20\x01\xd5\xf6\x10\x16\x21\x00\x00\x0a\x86\x00\x40\x02\x01\x00\x00\x00\x12\xbf\xff\xff\x10\xbf\xff\xff\xa0\x02\x00\x09\x0d\xbf\xff\xff\xd4\x20\x60\x00\xd4\x4e\x00\x16\x2a\xc2\x80\x03"
12SPARCV9_CODE = b"\x81\xa8\x0a\x24\x89\xa0\x10\x20\x89\xa0\x1a\x60\x89\xa0\x00\xe0"
13
14all_tests = (
15        (CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN, SPARC_CODE, "Sparc"),
16        (CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN+CS_MODE_V9, SPARCV9_CODE, "SparcV9"),
17)
18
19
20def print_insn_detail(insn):
21    # print address, mnemonic and operands
22    print("0x%x:\t%s\t%s" % (insn.address, insn.mnemonic, insn.op_str))
23
24    # "data" instruction generated by SKIPDATA option has no detail
25    if insn.id == 0:
26        return
27
28    if len(insn.operands) > 0:
29        print("\top_count: %u" % len(insn.operands))
30        c = 0
31        for i in insn.operands:
32            if i.type == SPARC_OP_REG:
33                print("\t\toperands[%u].type: REG = %s" % (c, insn.reg_name(i.reg)))
34            if i.type == SPARC_OP_IMM:
35                print("\t\toperands[%u].type: IMM = 0x%s" % (c, to_x_32(i.imm)))
36            if i.type == SPARC_OP_MEM:
37                print("\t\toperands[%u].type: MEM" % c)
38                if i.mem.base != 0:
39                    print("\t\t\toperands[%u].mem.base: REG = %s" \
40                        % (c, insn.reg_name(i.mem.base)))
41                if i.mem.index != 0:
42                    print("\t\t\toperands[%u].mem.index: REG = %s" \
43                        % (c, insn.reg_name(i.mem.index)))
44                if i.mem.disp != 0:
45                    print("\t\t\toperands[%u].mem.disp: 0x%s" \
46                        % (c, to_x_32(i.mem.disp)))
47            c += 1
48
49    if insn.cc:
50        print("\tCode condition: %u" % insn.cc)
51    if insn.hint:
52        print("\tHint code: %u" % insn.hint)
53
54
55# ## Test class Cs
56def test_class():
57    for (arch, mode, code, comment) in all_tests:
58        print("*" * 16)
59        print("Platform: %s" % comment)
60        print("Code: %s" % to_hex(code))
61        print("Disasm:")
62
63        try:
64            md = Cs(arch, mode)
65            md.detail = True
66            for insn in md.disasm(code, 0x1000):
67                print_insn_detail(insn)
68                print ()
69            print("0x%x:\n" % (insn.address + insn.size))
70        except CsError as e:
71            print("ERROR: %s" %e)
72
73
74if __name__ == '__main__':
75    test_class()
76