1#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===#
2#
3#                     The LLVM Compiler Infrastructure
4#
5# This file is distributed under the University of Illinois Open Source
6# License. See LICENSE.TXT for details.
7#
8#===------------------------------------------------------------------------===#
9
10from ctypes import CFUNCTYPE
11from ctypes import POINTER
12from ctypes import addressof
13from ctypes import byref
14from ctypes import c_byte
15from ctypes import c_char_p
16from ctypes import c_int
17from ctypes import c_size_t
18from ctypes import c_ubyte
19from ctypes import c_uint64
20from ctypes import c_void_p
21from ctypes import cast
22
23from .common import LLVMObject
24from .common import c_object_p
25from .common import get_library
26
27__all__ = [
28    'Disassembler',
29]
30
31lib = get_library()
32callbacks = {}
33
34class Disassembler(LLVMObject):
35    """Represents a disassembler instance.
36
37    Disassembler instances are tied to specific "triple," which must be defined
38    at creation time.
39
40    Disassembler instances can disassemble instructions from multiple sources.
41    """
42    def __init__(self, triple):
43        """Create a new disassembler instance.
44
45        The triple argument is the triple to create the disassembler for. This
46        is something like 'i386-apple-darwin9'.
47        """
48        ptr = lib.LLVMCreateDisasm(c_char_p(triple), c_void_p(None), c_int(0),
49                callbacks['op_info'](0), callbacks['symbol_lookup'](0))
50        if not ptr.contents:
51            raise Exception('Could not obtain disassembler for triple: %s' %
52                            triple)
53
54        LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisasmDispose)
55
56    def get_instruction(self, source, pc=0):
57        """Obtain the next instruction from an input source.
58
59        The input source should be a str or bytearray or something that
60        represents a sequence of bytes.
61
62        This function will start reading bytes from the beginning of the
63        source.
64
65        The pc argument specifies the address that the first byte is at.
66
67        This returns a 2-tuple of:
68
69          long number of bytes read. 0 if no instruction was read.
70          str representation of instruction. This will be the assembly that
71            represents the instruction.
72        """
73        buf = cast(c_char_p(source), POINTER(c_ubyte))
74        out_str = cast((c_byte * 255)(), c_char_p)
75
76        result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)),
77                                           c_uint64(pc), out_str, 255)
78
79        return (result, out_str.value)
80
81    def get_instructions(self, source, pc=0):
82        """Obtain multiple instructions from an input source.
83
84        This is like get_instruction() except it is a generator for all
85        instructions within the source. It starts at the beginning of the
86        source and reads instructions until no more can be read.
87
88        This generator returns 3-tuple of:
89
90          long address of instruction.
91          long size of instruction, in bytes.
92          str representation of instruction.
93        """
94        source_bytes = c_char_p(source)
95        out_str = cast((c_byte * 255)(), c_char_p)
96
97        # This could probably be written cleaner. But, it does work.
98        buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents
99        offset = 0
100        address = pc
101        end_address = pc + len(source)
102        while address < end_address:
103            b = cast(addressof(buf) + offset, POINTER(c_ubyte))
104            result = lib.LLVMDisasmInstruction(self, b,
105                    c_uint64(len(source) - offset), c_uint64(address),
106                    out_str, 255)
107
108            if result == 0:
109                break
110
111            yield (address, result, out_str.value)
112
113            address += result
114            offset += result
115
116
117def register_library(library):
118    library.LLVMCreateDisasm.argtypes = [c_char_p, c_void_p, c_int,
119        callbacks['op_info'], callbacks['symbol_lookup']]
120    library.LLVMCreateDisasm.restype = c_object_p
121
122    library.LLVMDisasmDispose.argtypes = [Disassembler]
123
124    library.LLVMDisasmInstruction.argtypes = [Disassembler, POINTER(c_ubyte),
125            c_uint64, c_uint64, c_char_p, c_size_t]
126    library.LLVMDisasmInstruction.restype = c_size_t
127
128callbacks['op_info'] = CFUNCTYPE(c_int, c_void_p, c_uint64, c_uint64, c_uint64,
129                                 c_int, c_void_p)
130callbacks['symbol_lookup'] = CFUNCTYPE(c_char_p, c_void_p, c_uint64,
131                                       POINTER(c_uint64), c_uint64,
132                                       POINTER(c_char_p))
133
134register_library(lib)
135