├── .gitignore
├── LICENSE
├── README.md
├── doc
├── images
│ ├── cfg_cons.dot
│ ├── cfg_cons.png
│ ├── cfg_if.dot
│ ├── cfg_if.png
│ ├── cfg_ifelse.dot
│ ├── cfg_ifelse.png
│ ├── cfg_while.dot
│ ├── cfg_while.png
│ ├── graph_stages.dot
│ └── graph_stages.png
└── ocd.md
├── ocd
├── src
├── control_flow.py
├── debug.py
├── decompile.py
├── disassemble.py
├── disassemblers
│ ├── __init__.py
│ ├── libdisassemble
│ │ ├── LICENSE
│ │ ├── README
│ │ ├── __init__.py
│ │ ├── disassemble.py
│ │ └── opcode86.py
│ └── x64.py
├── function_calls.py
├── objdump.py
├── ocd.py
├── output
│ ├── __init__.py
│ ├── c.py
│ ├── conditions.py
│ └── indent.py
└── representation.py
└── tests
├── Makefile
├── test_ack.c
├── test_ack_scanf.c
├── test_add.c
├── test_add_var.c
├── test_block.c
├── test_collapse.c
├── test_collapse2.c
├── test_div_zero.c
├── test_for.c
├── test_for_if.c
├── test_mod_zero.c
├── test_ptr.c
├── test_return_0.c
├── test_sum1.c
├── test_sum2.c
├── test_sum3.c
├── test_sum4.c
├── test_sum5.c
├── test_sum6.c
├── test_sum7.c
├── test_sznurki_alistra.c
├── test_sznurki_drx.c
├── test_variables.c
├── test_while.c
└── test_zero.c
/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore compiled python sources
2 | *.pyc
3 |
4 | # Ignore swap files
5 | *.swp
6 |
7 | # Ignore test executables, but not the sources
8 | tests/test_*
9 | !tests/test_*.c
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2010 Alek Balicki, Luke Zapart
2 |
3 | Permission is hereby granted, free of charge, to any person
4 | obtaining a copy of this software and associated documentation
5 | files (the "Software"), to deal in the Software without
6 | restriction, including without limitation the rights to use,
7 | copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the
9 | Software is furnished to do so, subject to the following
10 | conditions:
11 |
12 | The above copyright notice and this permission notice shall be
13 | included in all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 | OTHER DEALINGS IN THE SOFTWARE.
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ocd - ocd C decompiler
2 |
3 | **ocd** is a C decompiler written in Python, currently supporting decompilation of Linux programs compiled for the x64 architecture.
4 |
5 | The decompiler tries to infer the program structure, performing control and data flow analysis.
6 |
7 | If you'd like to learn how it works, check out my article on [how decompilers work](https://lukezapart.com/how-decompilers-work).
8 |
9 | More in-depth documentation is available in the [doc/ocd.md file](doc/ocd.md).
10 |
11 | ## Quick start
12 |
13 | Run `./ocd program` to decompile `program` (e.g. `./ocd /usr/bin/yes`).
14 |
15 | There are some test programs in the `tests/` directory. To check them out, do `cd tests; make`, then for example run `./ocd tests/test_ack`.
16 |
17 | Run `./ocd --help` to get more options.
18 |
19 | ## Requirements
20 |
21 | * Python 3
22 | * objdump
23 |
24 | ## Notes
25 |
26 | * ocd uses [Immunity libdisassembly v2.0](https://web.archive.org/web/20140209154423/http://www.immunitysec.com/resources-freesoftware.shtml)
27 |
28 | ## Example
29 |
30 |
31 |
32 | ```c
33 | int ack(int m, int n)
34 | {
35 | if (m == 0)
36 | return n + 1;
37 | else
38 | {
39 | if (n == 0)
40 | return ack(m-1, 1);
41 | else
42 | return ack(m-1, ack(m, n-1));
43 | }
44 | }
45 | int main()
46 | {
47 | return printf("%d\n", ack(3, 4));
48 | }
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | ```
62 |
63 | |
64 |
65 | ```c
66 | int ack()
67 | {
68 | var_0 = temp_2;
69 | var_1 = temp_3;
70 | var_2 = var_0 - 0;
71 | if (var2)
72 | {
73 | var_2 = var_1 - 0;
74 | if (var2)
75 | {
76 | temp_4 = ack(temp_5 - 1, ack(var_0, temp_4 - 1));
77 | }
78 | else
79 | {
80 | temp_4 = ack(temp_4 - 1, 1);
81 | }
82 | }
83 | else
84 | {
85 | temp_4 = temp_4 + 1;
86 | }
87 | return temp_4;
88 | }
89 | int main()
90 | {
91 | return unknown_function("%d\n", ack(3, 4));
92 | }
93 | ```
94 |
95 | |
96 | Original code | ocd output |
97 |
98 |
--------------------------------------------------------------------------------
/doc/images/cfg_cons.dot:
--------------------------------------------------------------------------------
1 | digraph cfg_if {
2 | a [label=""];
3 | b [label=""];
4 | c [label=""];
5 | a -> b;
6 | b -> c;
7 | }
8 |
--------------------------------------------------------------------------------
/doc/images/cfg_cons.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/doc/images/cfg_cons.png
--------------------------------------------------------------------------------
/doc/images/cfg_if.dot:
--------------------------------------------------------------------------------
1 | digraph cfg_if {
2 | a [label=""];
3 | b [label=""];
4 | c [label=""];
5 | a -> b;
6 | b -> c;
7 | a -> c;
8 | }
9 |
--------------------------------------------------------------------------------
/doc/images/cfg_if.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/doc/images/cfg_if.png
--------------------------------------------------------------------------------
/doc/images/cfg_ifelse.dot:
--------------------------------------------------------------------------------
1 | digraph cfg_if {
2 | a [label=""];
3 | b [label=""];
4 | c [label=""];
5 | d [label=""];
6 | a -> b;
7 | a -> c;
8 | b -> d;
9 | c -> d;
10 | }
11 |
--------------------------------------------------------------------------------
/doc/images/cfg_ifelse.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/doc/images/cfg_ifelse.png
--------------------------------------------------------------------------------
/doc/images/cfg_while.dot:
--------------------------------------------------------------------------------
1 | digraph cfg_if {
2 | a [label=""];
3 | b [label=""];
4 | c [label=""];
5 | d [label=""];
6 | a -> b;
7 | b -> c;
8 | c -> b;
9 | b -> d;
10 | }
11 |
--------------------------------------------------------------------------------
/doc/images/cfg_while.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/doc/images/cfg_while.png
--------------------------------------------------------------------------------
/doc/images/graph_stages.dot:
--------------------------------------------------------------------------------
1 | digraph graph_stages {
2 | 1 [label="Object dump"];
3 | 2 [label="Disassembly"];
4 | subgraph cluster_cf {
5 | 3 [label="Control flow graph\ngeneration"];
6 | 4 [label="Control flow graph\nreduction"];
7 | label = "Control flow analysis";
8 | style = dotted;
9 | }
10 | subgraph cluster_df {
11 | 5 [label="Variable inference"];
12 | 6 [label="Computation collapse"];
13 | label = "Data flow analysis";
14 | style = dotted;
15 | }
16 | 7 [label="Program output"];
17 | 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7;
18 | }
19 |
--------------------------------------------------------------------------------
/doc/images/graph_stages.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/doc/images/graph_stages.png
--------------------------------------------------------------------------------
/doc/ocd.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | ocd is a C decompiler written in Python, currently supporting decompilation of programs compiled for the x64 architecture. The internal data structures used for instructions are quite universal, so it should be trivial to add additional architectures as they are needed, as well as new output languages. The decompiler performs some inferences as to the program structure (such as control and data flow analysis).
4 |
5 | # Using ocd
6 |
7 | ocd reads a specified object file, performs decompilation on it and prints the results on standard output. It can also output a set of control flow graphs in dot format.
8 |
9 | The usage of the program is as follows:
10 |
11 | Usage: ocd [options] file
12 |
13 | Options:
14 | -h, --help show this help message and exit
15 | -d OPTION, --debug=OPTION
16 | turn debug option on
17 | -g FILE, --graph=FILE
18 | output a control flow graph
19 |
20 |
21 | # Operation
22 |
23 | ## Overview
24 |
25 | The decompilation occurs in stages. The program is built to be modular and each stage is separate.
26 |
27 | 
28 |
29 | ## Object dump
30 |
31 | Currently, ocd executes the GNU utility objdump and retrieves the list of object exports from it.
32 |
33 | ## Disassembly
34 |
35 | ocd supports decompilation of x86-64 and uses a slightly modified library called libdisassemble to disassemble code.
36 |
37 | ## Control flow analysis
38 |
39 | ### Control flow graph generation
40 |
41 | A block of code is a list of instructions.
42 |
43 | **B1** is a subblock of **B2** if **B1** is a sublist of **B2**.
44 |
45 | A block of code **B** is uninterruptible if both of these conditions hold:
46 |
47 | * no instruction jumps to an instruction within **B** other than the first (i.e. the only allowed entry point in **B** is its head)
48 | * no instruction in **B**, other than the last, jumps (i.e. the only exit point in **B** is its last instruction)
49 |
50 | A block of code **B** is maximally uninterruptible if it is interruptible and has both an entry point and an exit point.
51 |
52 | A control flow graph **cfgB** of a code block **B** is a digraph ****. The set of nodes **V** is the set of all maximally uninterruptible subblocks of **B**. An edge ** ∈ E** if and only if there is an instruction in **B1** that jumps to **B2**.
53 |
54 | Generating the cfg of a block of code consists of finding all jumps in the block and then chopping the block into maximally interruptible blocks based on the list of jumps.
55 |
56 | ### Control flow graph reduction
57 |
58 | A cfg of a block of code gives insight into how control flows through the block of code and ideally gives insight into what the program structure was originally.
59 |
60 |
61 |
62 |
63 |
64 |
65 | CFG patterns |
66 |
67 |
68 |  |
69 |  |
70 |
71 |
72 | if |
73 | if/else |
74 |
75 |  |
76 |  |
77 |
78 |
79 | while |
80 | cons |
81 |
82 |
83 |
84 | Logical structures can be recognized by finding patterns in the cfg. The patterns are listed above. The patterns are used to define a decreasing graph rewriting system (not unlike a context-sensitive grammar) in which a single step finds a pattern and contracts it to a single node containing information about the pattern's respective logical structure. Ideally, the fixed point of such a transformation will result in a single node containing the abstract syntax tree of the original program.
85 |
86 | ## Data flow analysis
87 |
88 | ### Variable inference
89 |
90 | In this phase, instruction operands are substituted with newly assigned names.
91 |
92 | ## Computation collapse
93 |
94 | In this phase, the program's computation is analyzed. Dead instructions are removed and others are folded into more coherent expressions. For example,
95 |
96 | a = a + 1
97 | b = a * 2
98 | n = 2
99 | n = b - a
100 |
101 | might be converted into:
102 |
103 | n = (a+1)*2-a+1
104 |
105 | ## Program output
106 |
107 | The program is output recursively on the cfgs of its symbols.
108 |
--------------------------------------------------------------------------------
/ocd:
--------------------------------------------------------------------------------
1 | ./src/ocd.py
--------------------------------------------------------------------------------
/src/control_flow.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 | from itertools import dropwhile, permutations
3 |
4 | graphfile = None
5 |
6 | class Graph:
7 | '''
8 | Basic graph structure based on successor and predecessor lists.
9 | '''
10 | def __init__(self):
11 | '''
12 | Initialize the graph with empty dicts of edges and vertices.
13 | '''
14 | self._pred = defaultdict(list)
15 | self._succ = defaultdict(list)
16 | self._edge_values = {}
17 | self._vertices = {}
18 |
19 | def __str__(self):
20 | '''
21 | Return the string representation of the graph.
22 | '''
23 | return 'Graph(vertices=' + str(self._vertices) + ', pred=' + str(self._pred) + ', succ=' + str(self._succ) + ')'
24 |
25 | def __contains__(self, vertex):
26 | '''
27 | Check if the graph contains a vertex.
28 | '''
29 | v, t = vertex
30 | if t == 'in':
31 | return (v in self._pred)
32 | if t == 'out':
33 | return (v in self._succ)
34 | if t == None:
35 | return (v in self._pred or v in self._succ)
36 |
37 | def successors(self, key):
38 | '''
39 | Return a list of successors for a given vertex.
40 | '''
41 | return self._succ[key]
42 |
43 | def predecessors(self, key):
44 | '''
45 | Return a list of predecessors for a given vertex.
46 | '''
47 | return self._pred[key]
48 |
49 | def vertex(self, k):
50 | '''
51 | Return a vertex.
52 | '''
53 | return self._vertices[k]
54 |
55 | def set_vertex(self, k, v=None):
56 | '''
57 | Set a vertex.
58 | '''
59 | self._vertices[k] = v
60 |
61 | def remove_vertices(self, ks):
62 | '''
63 | Remove vertices, along with edges adjacent to them.
64 | '''
65 | for k in ks:
66 | for p in self._pred[k]:
67 | self._succ[p].remove(k)
68 | for s in self._succ[k]:
69 | self._pred[s].remove(k)
70 | del self._pred[k]
71 | del self._succ[k]
72 | del self._vertices[k]
73 |
74 | def vertices(self):
75 | '''
76 | Return the list of vertices.
77 | '''
78 | return self._vertices
79 |
80 | def deg_in(self, k):
81 | '''
82 | Return the in-degree of a vertex.
83 | '''
84 | return len(self._pred[k])
85 |
86 | def deg_out(self, k):
87 | '''
88 | Return the out-degree of a vertex.
89 | '''
90 | return len(self._succ[k])
91 |
92 | def add_edge(self, v_in, v_out, value=None):
93 | '''
94 | Add an edge to the graph, optionally specifying a value.
95 | '''
96 | self._succ[v_in].append(v_out)
97 | self._pred[v_out].append(v_in)
98 | self._edge_values[(v_in, v_out)] = value
99 |
100 | def move_predecessors(self, v, v_new):
101 | '''
102 | Move edges pointing to a vertex so they point to another.
103 | '''
104 | for pred in self.predecessors(v)[:]:
105 | self.add_edge(pred, v_new, self.edge(pred, v))
106 | self.remove_edge(pred, v)
107 |
108 | def move_successors(self, v, v_new):
109 | '''
110 | Move edges coming out of a vertex so they come out of another.
111 | '''
112 | for succ in self.successors(v)[:]:
113 | self.add_edge(v_new, succ, self.edge(v, succ))
114 | self.remove_edge(v, succ)
115 |
116 | def edge(self, v_in, v_out):
117 | '''
118 | Return an edge.
119 | '''
120 | return self._edge_values[(v_in, v_out)]
121 |
122 | def remove_edge(self, v_in, v_out):
123 | '''
124 | Remove an edge.
125 | '''
126 | self._succ[v_in].remove(v_out)
127 | self._pred[v_out].remove(v_in)
128 | del self._edge_values[(v_in, v_out)]
129 |
130 | def sortedvertices(self):
131 | '''
132 | Return an iterator of sorted vertices (according to their original address).
133 | '''
134 | def key_f(arg):
135 | '''
136 | Use the vertex start address as key.
137 | '''
138 | arg_v, arg_t = arg
139 | a, b = arg_v
140 | return b
141 | return sorted(self.vertices().items(), key=key_f)
142 |
143 | def iterblocks(self):
144 | """
145 | Inorder traversal of graph blocks.
146 |
147 | Yields block and its depth.
148 | """
149 | def traverse(b, depth):
150 | if type(b) is not tuple:
151 | return
152 |
153 | t, v = b
154 | v_type, v_start = t
155 |
156 | if v_type == 'block':
157 | yield v, depth
158 |
159 | else:
160 | for block in v:
161 | for y in traverse(block, depth+1):
162 | yield y
163 |
164 | for v in self.sortedvertices():
165 | for y in traverse(v, 1):
166 | yield y
167 |
168 | def export(self, f, name, random=False):
169 | '''
170 | Export a graph to graphviz format.
171 | '''
172 | def block_label(block_type, block_loc, block):
173 | if block_type == 'block':
174 | return "block\\n{0:x}:{1:x}".format(block_loc, block[-1]['loc'])
175 | else:
176 | return "{0}\\n{1:x}".format(block_type, block_loc)
177 |
178 | if random:
179 | import random
180 | name += '_'+''.join(random.sample('0123456789abcdef', 8))
181 |
182 | f.write("\tsubgraph {0} {{\n".format(name))
183 |
184 | entries = filter(lambda k: self.deg_in(k) == 0, self.vertices())
185 |
186 | f.write("\t\t{0}_entry [label=\"{0}\"];\n".format(name))
187 | for e_type, e_loc in entries:
188 | f.write("\t\t{0}_entry -> {0}_{1}_{2:x};\n".format(name, e_type, e_loc))
189 |
190 | for (block_type, block_loc), block in self.vertices().items():
191 | f.write("\t\t{0}_{1}_{2:x} [label=\"{3}\"];\n".format(name, block_type, block_loc, block_label(block_type, block_loc, block)))
192 | for v_type, v_out in self.successors((block_type, block_loc)):
193 | label = ''
194 | value = self.edge((block_type, block_loc), (v_type, v_out))
195 | if value is not None:
196 | label = '[label="{0}"]'.format(value)
197 | f.write("\t\t{0}_{1}_{2:x} -> {0}_{3}_{4:x} {label};\n".format(name, block_type, block_loc, v_type, v_out, label=label))
198 | f.write("\t}\n")
199 |
200 | def control_flow_graph(function, labels, name):
201 | '''
202 | Analyze the control flow graph (cfg) of the function.
203 | '''
204 |
205 | graph = Graph()
206 | block_acc = []
207 | block_cur = None
208 | block_last = None
209 | block_change = True
210 | pass_through = False
211 | for ins in function:
212 | if ins['loc'] in labels or block_change:
213 | if block_last is not None:
214 | graph.set_vertex(block_last, block_acc)
215 | block_cur = ('block', ins['loc'])
216 | block_acc = []
217 | graph.set_vertex(block_cur)
218 |
219 | if ins['loc'] in labels and pass_through:
220 | # pass-through edge
221 | graph.add_edge(block_last, ('block', ins['loc']))
222 |
223 | block_change = False
224 | pass_through = True
225 |
226 | if ins['ins']['op'] == 'jump': # jumps (and only jumps)
227 | loc_next = ins['loc']+ins['length']
228 | loc_j = loc_next+ins['ins']['dest']['repr']
229 | graph.add_edge(block_cur, ('block', loc_j), ins['ins']['cond'])
230 | block_change = True
231 | if ins['ins']['cond'] != 'true':
232 | graph.add_edge(block_cur, ('block', loc_next))
233 | else:
234 | pass_through = False
235 | block_last = block_cur
236 | block_acc.append(ins)
237 |
238 | graph.set_vertex(block_last, block_acc)
239 |
240 | if graphfile:
241 | graph.export(graphfile, name)
242 |
243 | return graph_transform(graph)
244 |
245 | def flip(x):
246 | '''
247 | flip(x)(f) = f(x)
248 | '''
249 | def f(g):
250 | return g(x)
251 | return f
252 |
253 | def graph_transform(graph):
254 | '''
255 | Perform one step transformations of the graph according to
256 | preset rules until no more transformations can be performed.
257 |
258 | The rewriting system used here is decreasing (i.e. all transformations
259 | decrease the size of the graph), because every transformation rule is
260 | guaranteed to be decreasing, therefore it is total (it will always stop
261 | at some point.
262 |
263 | Transformation rules are functions of the type
264 |
265 | Graph -> (Boolean, Graph)
266 |
267 | The boolean value signifies whether the transformation condition was
268 | satisfied and the transformation was applied successfully.
269 |
270 | If no further transformation can be performed, the process is stopped
271 | and the resulting graph is returned.
272 | '''
273 | def t_trivial(graph):
274 | return False, graph
275 |
276 | def t_while(graph):
277 | for v in graph.vertices():
278 | if graph.deg_out(v) == 2:
279 | succs = graph.successors(v)
280 | for s1, s2 in permutations(succs):
281 | if graph.deg_out(s1) == 1 and graph.deg_in(s1) == 1 and v in graph.successors(s1):
282 | v_type, v_start = v
283 | v_new = ('while', v_start)
284 | condition = graph.edge(v, s1)
285 | v_new_value = (condition, (v, graph.vertex(v)), (s1, graph.vertex(s1)))
286 | graph.set_vertex(v_new, v_new_value)
287 | for pred in graph.predecessors(v):
288 | graph.add_edge(pred, v_new)
289 | graph.add_edge(v_new, s2)
290 | graph.remove_vertices([v,s1])
291 |
292 | return (True, graph)
293 |
294 | return (False, graph)
295 |
296 | def t_if(graph):
297 | for v in graph.vertices():
298 | if graph.deg_out(v) == 2:
299 | succs = graph.successors(v)
300 | for s1, s2 in permutations(succs):
301 | if graph.deg_out(s1) == 1 and graph.deg_in(s1) == 1:
302 | s1_succ = graph.successors(s1)[0]
303 | if s1_succ == s2:
304 | s1_type, s1_start = s1
305 | v_new = ('if', s1_start)
306 | snd = lambda x,y: y
307 | condition = '!'+graph.edge(v, s2)
308 | v_new_value = (condition, (s1, graph.vertex(s1)))
309 | graph.set_vertex(v_new, v_new_value)
310 | graph.add_edge(v, v_new)
311 | graph.add_edge(v_new, s2)
312 | graph.remove_edge(v, s2)
313 | graph.remove_vertices([s1])
314 | return (True, graph)
315 |
316 | return (False, graph)
317 |
318 | def t_ifelse(graph):
319 | for v in graph.vertices():
320 | succs = graph.successors(v)
321 | if len(succs) == 2:
322 | for s, t in permutations(succs):
323 | if graph.edge(v, s) is None:
324 | continue
325 | s_s, t_s = map(graph.successors, succs)
326 | s_p, t_p = map(graph.predecessors, succs)
327 | if [len(x) for x in (s_s, t_s, s_p, t_p)] == [1]*4 and s_s == t_s:
328 | s_type, s_start = s
329 | v_new = ('ifelse', s_start)
330 | condition = graph.edge(v,s)
331 | # modify v
332 | v_new_value = (condition,
333 | (s, graph.vertex(s)), (t, graph.vertex(t)))
334 | graph.set_vertex(v_new, v_new_value)
335 | graph.add_edge(v_new, s_s[0])
336 | graph.add_edge(v, v_new)
337 | graph.remove_vertices([s, t])
338 | return (True, graph)
339 |
340 | return (False, graph)
341 |
342 | def t_cons(graph):
343 | for v in graph.vertices():
344 | if graph.deg_out(v) == 1:
345 | s = graph.successors(v)[0]
346 | if graph.deg_in(s) == 1 and v != s:
347 | v_type, v_start = v
348 | s_type, s_start = s
349 | if v_type == 'cons':
350 | graph.vertex(v).append((s, graph.vertex(s)))
351 | #graph.set_vertex(v, v_value)
352 | for succ in graph.successors(s):
353 | graph.add_edge(v, succ)
354 | graph.remove_vertices([s])
355 | else:
356 | v_new = ('cons', v_start)
357 | v_new_value = [(v, graph.vertex(v)), (s, graph.vertex(s))]
358 | graph.set_vertex(v_new, v_new_value)
359 | graph.move_predecessors(v, v_new)
360 | graph.move_successors(s, v_new)
361 | graph.remove_vertices([v,s])
362 | return (True, graph)
363 |
364 | return (False, graph)
365 |
366 | rules = [t_trivial, t_ifelse, t_if, t_while, t_cons]
367 |
368 | i = dropwhile(lambda x: not x[0], map(flip(graph), rules))
369 | try:
370 | true, graph = i.__next__()
371 | if graphfile:
372 | graph.export(graphfile, 'step', random=True)
373 | return graph_transform(graph)
374 | except StopIteration:
375 | if graphfile:
376 | graph.export(graphfile, 'transformed')
377 | return graph
378 |
--------------------------------------------------------------------------------
/src/debug.py:
--------------------------------------------------------------------------------
1 | '''
2 | Debug module
3 |
4 | Acceptable debug levels: all, graph, misc
5 | '''
6 |
7 | options = ['all', 'graph', 'misc', 'asm_rw']
8 |
9 | __debug = []
10 |
11 | def check(cond):
12 | global __debug
13 | return (cond in __debug or 'all' in __debug)
14 |
15 | def set(cond=None):
16 | global __debug
17 | if cond is None:
18 | cond = 'all'
19 |
20 | __debug.append(cond)
21 |
22 | def sprint(str, cond):
23 | if debug_check(cond):
24 | return str
25 | else:
26 | return ''
27 |
--------------------------------------------------------------------------------
/src/decompile.py:
--------------------------------------------------------------------------------
1 | from control_flow import control_flow_graph
2 | from copy import copy, deepcopy
3 | from itertools import count
4 | import debug
5 | import function_calls
6 | import disassemblers.libdisassemble.opcode86 as opcode86
7 | import re
8 | import representation
9 | import zlib
10 |
11 | def is_constant(x):
12 | '''
13 | Test of the argument is a constant.
14 | '''
15 | return re.match("-?0x.*", x)
16 |
17 | def is_register(x):
18 | '''
19 | Test if the argument is a register.
20 | '''
21 | registers = map(lambda x: x[0], opcode86.regs)
22 | return x in registers
23 |
24 | def get_labels(functions):
25 | '''
26 | Find addresses that need to be labeled.
27 | '''
28 | labels = {}
29 | for function in functions:
30 | for ins in functions[function]:
31 | if ins['ins']['op'] == 'jump':
32 | addr = ins['loc']+ins['length']+ins['ins']['dest']['repr']
33 | labels[addr] = 'loc_{0:x}'.format(addr)
34 |
35 | return labels
36 |
37 | def infer_signature(asm):
38 | '''
39 | Infer the signature of a function.
40 | '''
41 | return ('int', [])
42 |
43 | def variable_inference(cfg):
44 | '''
45 | Infer the variables in code.
46 |
47 | Change all temporary variables (registers) into temp_0, temp_1, etc.
48 | and other variables into var_0, var_1, etc.
49 | '''
50 | def variable_inference_arg(arg):
51 | if 'op' in arg:
52 | variable_inference_ins(arg)
53 | elif arg['value'] in vars:
54 | arg.update(vars[arg['value']])
55 | else:
56 | if arg['w'] or arg['r']:
57 | if arg['r'] and is_constant(arg['value']):
58 | type = 'const'
59 | if arg['value'] == arg['repr']:
60 | repr = int(arg['value'], 16)
61 | else:
62 | repr = arg['repr']
63 | elif is_register(arg['value']):
64 | type = 'temp'
65 | repr = temp_names.__next__()
66 | else:
67 | type = 'var'
68 | repr = var_names.__next__()
69 | info = {'type':type, 'repr':repr, 'value': arg['value']}
70 | vars[arg['value']] = info
71 | arg.update(info)
72 |
73 | def variable_inference_ins(ins):
74 | for k, arg in ins.items():
75 | if k == 'args':
76 | for a in arg:
77 | variable_inference_arg(a)
78 | if k not in ('src', 'dest'):
79 | continue
80 |
81 | variable_inference_arg(ins[k])
82 |
83 |
84 | var_names = new_var_name()
85 | temp_names = new_temp_name()
86 | vars = {}
87 |
88 | for block, depth in cfg.iterblocks():
89 | for i, line in enumerate(block):
90 | variable_inference_ins(line['ins'])
91 |
92 | var_number_indicator = var_names.__next__()
93 | m = re.match( "var_(.*)", var_number_indicator )
94 | return int(m.group(1))
95 |
96 | def computation_collapse(cfg):
97 | '''
98 | Collapse the computation tree in the graph.
99 |
100 | For example, this code:
101 |
102 | a = 5
103 | b = a + 2
104 | c = b * 2
105 |
106 | would be converted to:
107 |
108 | c = (5+2)*2
109 | '''
110 | def is_writable(ins, k):
111 | '''
112 | Check if the argument is writable.
113 | '''
114 | return k in ins and 'w' in ins[k] and ins[k]['w']
115 |
116 | def is_temp_comp(ins, k):
117 | '''
118 | Check if the argument is a temporary.
119 | '''
120 | return k in ins and 'type' in ins[k] and ins[k]['type'] == 'temp'
121 |
122 | def lookup_vars(ins, mem):
123 | '''
124 | Lookup variables in memory.
125 | '''
126 | for k in ('src','dest'):
127 | if k in ins and 'op' in ins[k]:
128 | ins[k] = lookup_vars(ins[k], mem)
129 | elif k != 'dest' and k in ins and 'repr' in ins[k] and ins[k]['repr'] in mem:
130 | ins[k] = mem[ins[k]['repr']]
131 | if 'op' in ins and ins['op'] == 'apply':
132 | for i, arg in enumerate(ins['args']):
133 | ins['args'][i] = lookup_vars({'src': arg}, mem)['src']
134 | return ins
135 |
136 | def collapse_line(line, mem):
137 | '''
138 | Try to collapse a line.
139 | '''
140 | ins = line['ins']
141 | for k in ('dest',):
142 | if k in ins and is_writable(ins, k) and is_temp_comp(ins, k):
143 | key = ins[k]['repr']
144 | mem[key] = lookup_vars(deepcopy(ins), mem)
145 | line['ins'] = lookup_vars(ins, mem)
146 |
147 | def collapse_vertex(vertex, mem):
148 | '''
149 | Collapse a vertex of the cfg.
150 | '''
151 | t, v = vertex
152 | v_type, v_start = t
153 |
154 | if v_type == 'block':
155 | for line in v:
156 | collapse_line(line, mem)
157 |
158 | elif v_type == 'cons':
159 | for block in v:
160 | collapse_vertex(block, mem)
161 |
162 | elif v_type == 'if':
163 | cond, block = v
164 | collapse_vertex(block, deepcopy(mem))
165 |
166 | elif v_type == 'ifelse':
167 | cond, true, false = v
168 | for block in (true, false):
169 | collapse_vertex(block, deepcopy(mem))
170 |
171 | elif v_type == 'while':
172 | cond, pre, loop = v
173 | for block in (pre, loop):
174 | collapse_vertex(block, deepcopy(mem))
175 |
176 | for v in cfg.sortedvertices():
177 | collapse_vertex(v, {})
178 |
179 | def cremate(cfg):
180 | '''
181 | Remove dead instructions.
182 |
183 | Specifically, traverse the code reverse inorder and:
184 | * record every read of a temporary variable
185 | * if you encounter a write to a temporary variable,
186 | erase it from the set
187 |
188 | This way record every necessary write to a temporary variable
189 | and remove the unnecessary ones.
190 | '''
191 |
192 | def get_read_arg(arg):
193 | if 'op' in arg:
194 | return get_read(arg)
195 | if arg['r'] and arg['type'] == 'temp':
196 | return {arg['repr']}
197 |
198 | return set()
199 |
200 | def get_read(ins):
201 | '''
202 | Get the set of variables read from in the instruction.
203 | '''
204 | r = set()
205 | if 'src' in ins:
206 | r |= get_read_arg(ins['src'])
207 | return r
208 |
209 | def get_written(ins):
210 | '''
211 | Get the set of variables written to in the instruction.
212 | '''
213 | w = set()
214 | if 'dest' in ins and ins['dest']['w'] and ins['dest']['type'] == 'temp':
215 | w |= {ins['dest']['repr']}
216 | return w
217 |
218 | def variable_declarations(cfg):
219 | '''
220 | Finds information about used variables and adds the declarations for them.
221 | '''
222 |
223 | def consume_block(block, reads_in):
224 | '''
225 | Try to consume lines in a block of code.
226 | '''
227 | reads = deepcopy(reads_in)
228 | t, v = block
229 | v_type, v_start = t
230 |
231 | if v_type == 'if':
232 | cond, true = v
233 | return consume_block(true, reads)
234 |
235 | if v_type == 'while':
236 | cond, pre, loop = v
237 | reads = consume_block(loop, reads)
238 | return consume_block(pre, reads)
239 |
240 | if v_type == 'cons':
241 | for b in reversed(v):
242 | reads = consume_block(b, reads)
243 |
244 | return reads
245 |
246 | if v_type == 'ifelse':
247 | cond, true, false = v
248 | reads_true = consume_block(true, reads)
249 | reads_false = consume_block(false, reads)
250 | return reads_true | reads_false
251 |
252 | for line in reversed(block[1]):
253 | w = get_written(line['ins'])
254 | r = get_read(line['ins'])
255 | if w <= reads:
256 | pass
257 | else:
258 | line['display'] = False
259 | reads -= w
260 | reads |= r
261 |
262 | return reads
263 |
264 | vars = set()
265 | for vertex in list(cfg.sortedvertices()):
266 | vars |= consume_block(vertex, set())
267 |
268 | return vars
269 |
270 | def new_var_name():
271 | '''
272 | Generator of new variable names.
273 | '''
274 | for n in count(0):
275 | yield "var_{0}".format(n)
276 |
277 | def new_temp_name():
278 | '''
279 | Generator of new temporary variable names.
280 | '''
281 | for n in count(0):
282 | yield "temp_{0}".format(n)
283 |
284 | def add_declarations(cfg, var_number, temps_used):
285 | to_declare = temps_used
286 | for i in range(0, var_number):
287 | to_declare |= set(["var_{0}".format(i)])
288 |
289 | #print(to_declare)
290 |
291 | def decompile_function(asm, labels, name, symbols):
292 | '''
293 | Decompile a function.
294 | '''
295 | signature = infer_signature(asm)
296 |
297 | cfg = control_flow_graph(asm, labels, name)
298 | symbols_rev = {symbols[s]['start']: s for s in symbols}
299 | function_calls.fold(cfg, symbols_rev)
300 |
301 | var_number = variable_inference(cfg)
302 | computation_collapse(cfg)
303 | temps_used = cremate(cfg)
304 | add_declarations(cfg, var_number, temps_used)
305 |
306 | return cfg, signature
307 |
308 | def decompile_functions(functions, symbols):
309 | '''
310 | Decompile all functions.
311 | '''
312 | labels = get_labels(functions)
313 |
314 | decompiled_functions = {}
315 |
316 | for name, symbol in functions.items():
317 | decompiled_functions[name] = decompile_function(functions[name], labels, name, symbols)
318 |
319 | return decompiled_functions
320 |
--------------------------------------------------------------------------------
/src/disassemble.py:
--------------------------------------------------------------------------------
1 | import disassemblers.x64
2 |
3 | def disassemble(buf, virt, sections, binary, arch='x64'):
4 | archs = {
5 | 'x64': disassemblers.x64
6 |
7 | }
8 | return archs[arch].disassemble(buf, virt, sections, binary)
9 |
--------------------------------------------------------------------------------
/src/disassemblers/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/src/disassemblers/__init__.py
--------------------------------------------------------------------------------
/src/disassemblers/libdisassemble/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 2.1, February 1999
3 |
4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc.
5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | [This is the first released version of the Lesser GPL. It also counts
10 | as the successor of the GNU Library Public License, version 2, hence
11 | the version number 2.1.]
12 |
13 | Preamble
14 |
15 | The licenses for most software are designed to take away your
16 | freedom to share and change it. By contrast, the GNU General Public
17 | Licenses are intended to guarantee your freedom to share and change
18 | free software--to make sure the software is free for all its users.
19 |
20 | This license, the Lesser General Public License, applies to some
21 | specially designated software packages--typically libraries--of the
22 | Free Software Foundation and other authors who decide to use it. You
23 | can use it too, but we suggest you first think carefully about whether
24 | this license or the ordinary General Public License is the better
25 | strategy to use in any particular case, based on the explanations below.
26 |
27 | When we speak of free software, we are referring to freedom of use,
28 | not price. Our General Public Licenses are designed to make sure that
29 | you have the freedom to distribute copies of free software (and charge
30 | for this service if you wish); that you receive source code or can get
31 | it if you want it; that you can change the software and use pieces of
32 | it in new free programs; and that you are informed that you can do
33 | these things.
34 |
35 | To protect your rights, we need to make restrictions that forbid
36 | distributors to deny you these rights or to ask you to surrender these
37 | rights. These restrictions translate to certain responsibilities for
38 | you if you distribute copies of the library or if you modify it.
39 |
40 | For example, if you distribute copies of the library, whether gratis
41 | or for a fee, you must give the recipients all the rights that we gave
42 | you. You must make sure that they, too, receive or can get the source
43 | code. If you link other code with the library, you must provide
44 | complete object files to the recipients, so that they can relink them
45 | with the library after making changes to the library and recompiling
46 | it. And you must show them these terms so they know their rights.
47 |
48 | We protect your rights with a two-step method: (1) we copyright the
49 | library, and (2) we offer you this license, which gives you legal
50 | permission to copy, distribute and/or modify the library.
51 |
52 | To protect each distributor, we want to make it very clear that
53 | there is no warranty for the free library. Also, if the library is
54 | modified by someone else and passed on, the recipients should know
55 | that what they have is not the original version, so that the original
56 | author's reputation will not be affected by problems that might be
57 | introduced by others.
58 |
59 | Finally, software patents pose a constant threat to the existence of
60 | any free program. We wish to make sure that a company cannot
61 | effectively restrict the users of a free program by obtaining a
62 | restrictive license from a patent holder. Therefore, we insist that
63 | any patent license obtained for a version of the library must be
64 | consistent with the full freedom of use specified in this license.
65 |
66 | Most GNU software, including some libraries, is covered by the
67 | ordinary GNU General Public License. This license, the GNU Lesser
68 | General Public License, applies to certain designated libraries, and
69 | is quite different from the ordinary General Public License. We use
70 | this license for certain libraries in order to permit linking those
71 | libraries into non-free programs.
72 |
73 | When a program is linked with a library, whether statically or using
74 | a shared library, the combination of the two is legally speaking a
75 | combined work, a derivative of the original library. The ordinary
76 | General Public License therefore permits such linking only if the
77 | entire combination fits its criteria of freedom. The Lesser General
78 | Public License permits more lax criteria for linking other code with
79 | the library.
80 |
81 | We call this license the "Lesser" General Public License because it
82 | does Less to protect the user's freedom than the ordinary General
83 | Public License. It also provides other free software developers Less
84 | of an advantage over competing non-free programs. These disadvantages
85 | are the reason we use the ordinary General Public License for many
86 | libraries. However, the Lesser license provides advantages in certain
87 | special circumstances.
88 |
89 | For example, on rare occasions, there may be a special need to
90 | encourage the widest possible use of a certain library, so that it becomes
91 | a de-facto standard. To achieve this, non-free programs must be
92 | allowed to use the library. A more frequent case is that a free
93 | library does the same job as widely used non-free libraries. In this
94 | case, there is little to gain by limiting the free library to free
95 | software only, so we use the Lesser General Public License.
96 |
97 | In other cases, permission to use a particular library in non-free
98 | programs enables a greater number of people to use a large body of
99 | free software. For example, permission to use the GNU C Library in
100 | non-free programs enables many more people to use the whole GNU
101 | operating system, as well as its variant, the GNU/Linux operating
102 | system.
103 |
104 | Although the Lesser General Public License is Less protective of the
105 | users' freedom, it does ensure that the user of a program that is
106 | linked with the Library has the freedom and the wherewithal to run
107 | that program using a modified version of the Library.
108 |
109 | The precise terms and conditions for copying, distribution and
110 | modification follow. Pay close attention to the difference between a
111 | "work based on the library" and a "work that uses the library". The
112 | former contains code derived from the library, whereas the latter must
113 | be combined with the library in order to run.
114 |
115 | GNU LESSER GENERAL PUBLIC LICENSE
116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
117 |
118 | 0. This License Agreement applies to any software library or other
119 | program which contains a notice placed by the copyright holder or
120 | other authorized party saying it may be distributed under the terms of
121 | this Lesser General Public License (also called "this License").
122 | Each licensee is addressed as "you".
123 |
124 | A "library" means a collection of software functions and/or data
125 | prepared so as to be conveniently linked with application programs
126 | (which use some of those functions and data) to form executables.
127 |
128 | The "Library", below, refers to any such software library or work
129 | which has been distributed under these terms. A "work based on the
130 | Library" means either the Library or any derivative work under
131 | copyright law: that is to say, a work containing the Library or a
132 | portion of it, either verbatim or with modifications and/or translated
133 | straightforwardly into another language. (Hereinafter, translation is
134 | included without limitation in the term "modification".)
135 |
136 | "Source code" for a work means the preferred form of the work for
137 | making modifications to it. For a library, complete source code means
138 | all the source code for all modules it contains, plus any associated
139 | interface definition files, plus the scripts used to control compilation
140 | and installation of the library.
141 |
142 | Activities other than copying, distribution and modification are not
143 | covered by this License; they are outside its scope. The act of
144 | running a program using the Library is not restricted, and output from
145 | such a program is covered only if its contents constitute a work based
146 | on the Library (independent of the use of the Library in a tool for
147 | writing it). Whether that is true depends on what the Library does
148 | and what the program that uses the Library does.
149 |
150 | 1. You may copy and distribute verbatim copies of the Library's
151 | complete source code as you receive it, in any medium, provided that
152 | you conspicuously and appropriately publish on each copy an
153 | appropriate copyright notice and disclaimer of warranty; keep intact
154 | all the notices that refer to this License and to the absence of any
155 | warranty; and distribute a copy of this License along with the
156 | Library.
157 |
158 | You may charge a fee for the physical act of transferring a copy,
159 | and you may at your option offer warranty protection in exchange for a
160 | fee.
161 |
162 | 2. You may modify your copy or copies of the Library or any portion
163 | of it, thus forming a work based on the Library, and copy and
164 | distribute such modifications or work under the terms of Section 1
165 | above, provided that you also meet all of these conditions:
166 |
167 | a) The modified work must itself be a software library.
168 |
169 | b) You must cause the files modified to carry prominent notices
170 | stating that you changed the files and the date of any change.
171 |
172 | c) You must cause the whole of the work to be licensed at no
173 | charge to all third parties under the terms of this License.
174 |
175 | d) If a facility in the modified Library refers to a function or a
176 | table of data to be supplied by an application program that uses
177 | the facility, other than as an argument passed when the facility
178 | is invoked, then you must make a good faith effort to ensure that,
179 | in the event an application does not supply such function or
180 | table, the facility still operates, and performs whatever part of
181 | its purpose remains meaningful.
182 |
183 | (For example, a function in a library to compute square roots has
184 | a purpose that is entirely well-defined independent of the
185 | application. Therefore, Subsection 2d requires that any
186 | application-supplied function or table used by this function must
187 | be optional: if the application does not supply it, the square
188 | root function must still compute square roots.)
189 |
190 | These requirements apply to the modified work as a whole. If
191 | identifiable sections of that work are not derived from the Library,
192 | and can be reasonably considered independent and separate works in
193 | themselves, then this License, and its terms, do not apply to those
194 | sections when you distribute them as separate works. But when you
195 | distribute the same sections as part of a whole which is a work based
196 | on the Library, the distribution of the whole must be on the terms of
197 | this License, whose permissions for other licensees extend to the
198 | entire whole, and thus to each and every part regardless of who wrote
199 | it.
200 |
201 | Thus, it is not the intent of this section to claim rights or contest
202 | your rights to work written entirely by you; rather, the intent is to
203 | exercise the right to control the distribution of derivative or
204 | collective works based on the Library.
205 |
206 | In addition, mere aggregation of another work not based on the Library
207 | with the Library (or with a work based on the Library) on a volume of
208 | a storage or distribution medium does not bring the other work under
209 | the scope of this License.
210 |
211 | 3. You may opt to apply the terms of the ordinary GNU General Public
212 | License instead of this License to a given copy of the Library. To do
213 | this, you must alter all the notices that refer to this License, so
214 | that they refer to the ordinary GNU General Public License, version 2,
215 | instead of to this License. (If a newer version than version 2 of the
216 | ordinary GNU General Public License has appeared, then you can specify
217 | that version instead if you wish.) Do not make any other change in
218 | these notices.
219 |
220 | Once this change is made in a given copy, it is irreversible for
221 | that copy, so the ordinary GNU General Public License applies to all
222 | subsequent copies and derivative works made from that copy.
223 |
224 | This option is useful when you wish to copy part of the code of
225 | the Library into a program that is not a library.
226 |
227 | 4. You may copy and distribute the Library (or a portion or
228 | derivative of it, under Section 2) in object code or executable form
229 | under the terms of Sections 1 and 2 above provided that you accompany
230 | it with the complete corresponding machine-readable source code, which
231 | must be distributed under the terms of Sections 1 and 2 above on a
232 | medium customarily used for software interchange.
233 |
234 | If distribution of object code is made by offering access to copy
235 | from a designated place, then offering equivalent access to copy the
236 | source code from the same place satisfies the requirement to
237 | distribute the source code, even though third parties are not
238 | compelled to copy the source along with the object code.
239 |
240 | 5. A program that contains no derivative of any portion of the
241 | Library, but is designed to work with the Library by being compiled or
242 | linked with it, is called a "work that uses the Library". Such a
243 | work, in isolation, is not a derivative work of the Library, and
244 | therefore falls outside the scope of this License.
245 |
246 | However, linking a "work that uses the Library" with the Library
247 | creates an executable that is a derivative of the Library (because it
248 | contains portions of the Library), rather than a "work that uses the
249 | library". The executable is therefore covered by this License.
250 | Section 6 states terms for distribution of such executables.
251 |
252 | When a "work that uses the Library" uses material from a header file
253 | that is part of the Library, the object code for the work may be a
254 | derivative work of the Library even though the source code is not.
255 | Whether this is true is especially significant if the work can be
256 | linked without the Library, or if the work is itself a library. The
257 | threshold for this to be true is not precisely defined by law.
258 |
259 | If such an object file uses only numerical parameters, data
260 | structure layouts and accessors, and small macros and small inline
261 | functions (ten lines or less in length), then the use of the object
262 | file is unrestricted, regardless of whether it is legally a derivative
263 | work. (Executables containing this object code plus portions of the
264 | Library will still fall under Section 6.)
265 |
266 | Otherwise, if the work is a derivative of the Library, you may
267 | distribute the object code for the work under the terms of Section 6.
268 | Any executables containing that work also fall under Section 6,
269 | whether or not they are linked directly with the Library itself.
270 |
271 | 6. As an exception to the Sections above, you may also combine or
272 | link a "work that uses the Library" with the Library to produce a
273 | work containing portions of the Library, and distribute that work
274 | under terms of your choice, provided that the terms permit
275 | modification of the work for the customer's own use and reverse
276 | engineering for debugging such modifications.
277 |
278 | You must give prominent notice with each copy of the work that the
279 | Library is used in it and that the Library and its use are covered by
280 | this License. You must supply a copy of this License. If the work
281 | during execution displays copyright notices, you must include the
282 | copyright notice for the Library among them, as well as a reference
283 | directing the user to the copy of this License. Also, you must do one
284 | of these things:
285 |
286 | a) Accompany the work with the complete corresponding
287 | machine-readable source code for the Library including whatever
288 | changes were used in the work (which must be distributed under
289 | Sections 1 and 2 above); and, if the work is an executable linked
290 | with the Library, with the complete machine-readable "work that
291 | uses the Library", as object code and/or source code, so that the
292 | user can modify the Library and then relink to produce a modified
293 | executable containing the modified Library. (It is understood
294 | that the user who changes the contents of definitions files in the
295 | Library will not necessarily be able to recompile the application
296 | to use the modified definitions.)
297 |
298 | b) Use a suitable shared library mechanism for linking with the
299 | Library. A suitable mechanism is one that (1) uses at run time a
300 | copy of the library already present on the user's computer system,
301 | rather than copying library functions into the executable, and (2)
302 | will operate properly with a modified version of the library, if
303 | the user installs one, as long as the modified version is
304 | interface-compatible with the version that the work was made with.
305 |
306 | c) Accompany the work with a written offer, valid for at
307 | least three years, to give the same user the materials
308 | specified in Subsection 6a, above, for a charge no more
309 | than the cost of performing this distribution.
310 |
311 | d) If distribution of the work is made by offering access to copy
312 | from a designated place, offer equivalent access to copy the above
313 | specified materials from the same place.
314 |
315 | e) Verify that the user has already received a copy of these
316 | materials or that you have already sent this user a copy.
317 |
318 | For an executable, the required form of the "work that uses the
319 | Library" must include any data and utility programs needed for
320 | reproducing the executable from it. However, as a special exception,
321 | the materials to be distributed need not include anything that is
322 | normally distributed (in either source or binary form) with the major
323 | components (compiler, kernel, and so on) of the operating system on
324 | which the executable runs, unless that component itself accompanies
325 | the executable.
326 |
327 | It may happen that this requirement contradicts the license
328 | restrictions of other proprietary libraries that do not normally
329 | accompany the operating system. Such a contradiction means you cannot
330 | use both them and the Library together in an executable that you
331 | distribute.
332 |
333 | 7. You may place library facilities that are a work based on the
334 | Library side-by-side in a single library together with other library
335 | facilities not covered by this License, and distribute such a combined
336 | library, provided that the separate distribution of the work based on
337 | the Library and of the other library facilities is otherwise
338 | permitted, and provided that you do these two things:
339 |
340 | a) Accompany the combined library with a copy of the same work
341 | based on the Library, uncombined with any other library
342 | facilities. This must be distributed under the terms of the
343 | Sections above.
344 |
345 | b) Give prominent notice with the combined library of the fact
346 | that part of it is a work based on the Library, and explaining
347 | where to find the accompanying uncombined form of the same work.
348 |
349 | 8. You may not copy, modify, sublicense, link with, or distribute
350 | the Library except as expressly provided under this License. Any
351 | attempt otherwise to copy, modify, sublicense, link with, or
352 | distribute the Library is void, and will automatically terminate your
353 | rights under this License. However, parties who have received copies,
354 | or rights, from you under this License will not have their licenses
355 | terminated so long as such parties remain in full compliance.
356 |
357 | 9. You are not required to accept this License, since you have not
358 | signed it. However, nothing else grants you permission to modify or
359 | distribute the Library or its derivative works. These actions are
360 | prohibited by law if you do not accept this License. Therefore, by
361 | modifying or distributing the Library (or any work based on the
362 | Library), you indicate your acceptance of this License to do so, and
363 | all its terms and conditions for copying, distributing or modifying
364 | the Library or works based on it.
365 |
366 | 10. Each time you redistribute the Library (or any work based on the
367 | Library), the recipient automatically receives a license from the
368 | original licensor to copy, distribute, link with or modify the Library
369 | subject to these terms and conditions. You may not impose any further
370 | restrictions on the recipients' exercise of the rights granted herein.
371 | You are not responsible for enforcing compliance by third parties with
372 | this License.
373 |
374 | 11. If, as a consequence of a court judgment or allegation of patent
375 | infringement or for any other reason (not limited to patent issues),
376 | conditions are imposed on you (whether by court order, agreement or
377 | otherwise) that contradict the conditions of this License, they do not
378 | excuse you from the conditions of this License. If you cannot
379 | distribute so as to satisfy simultaneously your obligations under this
380 | License and any other pertinent obligations, then as a consequence you
381 | may not distribute the Library at all. For example, if a patent
382 | license would not permit royalty-free redistribution of the Library by
383 | all those who receive copies directly or indirectly through you, then
384 | the only way you could satisfy both it and this License would be to
385 | refrain entirely from distribution of the Library.
386 |
387 | If any portion of this section is held invalid or unenforceable under any
388 | particular circumstance, the balance of the section is intended to apply,
389 | and the section as a whole is intended to apply in other circumstances.
390 |
391 | It is not the purpose of this section to induce you to infringe any
392 | patents or other property right claims or to contest validity of any
393 | such claims; this section has the sole purpose of protecting the
394 | integrity of the free software distribution system which is
395 | implemented by public license practices. Many people have made
396 | generous contributions to the wide range of software distributed
397 | through that system in reliance on consistent application of that
398 | system; it is up to the author/donor to decide if he or she is willing
399 | to distribute software through any other system and a licensee cannot
400 | impose that choice.
401 |
402 | This section is intended to make thoroughly clear what is believed to
403 | be a consequence of the rest of this License.
404 |
405 | 12. If the distribution and/or use of the Library is restricted in
406 | certain countries either by patents or by copyrighted interfaces, the
407 | original copyright holder who places the Library under this License may add
408 | an explicit geographical distribution limitation excluding those countries,
409 | so that distribution is permitted only in or among countries not thus
410 | excluded. In such case, this License incorporates the limitation as if
411 | written in the body of this License.
412 |
413 | 13. The Free Software Foundation may publish revised and/or new
414 | versions of the Lesser General Public License from time to time.
415 | Such new versions will be similar in spirit to the present version,
416 | but may differ in detail to address new problems or concerns.
417 |
418 | Each version is given a distinguishing version number. If the Library
419 | specifies a version number of this License which applies to it and
420 | "any later version", you have the option of following the terms and
421 | conditions either of that version or of any later version published by
422 | the Free Software Foundation. If the Library does not specify a
423 | license version number, you may choose any version ever published by
424 | the Free Software Foundation.
425 |
426 | 14. If you wish to incorporate parts of the Library into other free
427 | programs whose distribution conditions are incompatible with these,
428 | write to the author to ask for permission. For software which is
429 | copyrighted by the Free Software Foundation, write to the Free
430 | Software Foundation; we sometimes make exceptions for this. Our
431 | decision will be guided by the two goals of preserving the free status
432 | of all derivatives of our free software and of promoting the sharing
433 | and reuse of software generally.
434 |
435 | NO WARRANTY
436 |
437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
446 |
447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
456 | DAMAGES.
457 |
458 | END OF TERMS AND CONDITIONS
459 |
460 |
461 |
--------------------------------------------------------------------------------
/src/disassemblers/libdisassemble/README:
--------------------------------------------------------------------------------
1 | Immunity libdisassembly v2.0
2 | ~~~~~~~~ ~~~~~~~~~~~~~~ ~~~~
3 | http://www.immunitysec.com
4 | June 5, 2007
5 |
6 |
7 | Credits to atlas and Matthew Carpenter
8 | for the 2.0 release!
9 |
10 |
11 | Libdisassembly is simply a python library for disassembling x86 opcodes. It has been made for Immunity's PDB Project (a vulnerability development focused debugger), and is partially based on mammon libdisasm opcode list (http://www.eccentrix.com/members/mammon/). There is still a lot of work to do with the Metadata, but the library tries to return as much information it can get off of an opcode.
12 |
13 | USAGE:
14 |
15 | ie:
16 | $ objdump -x /bin/cat | grep .text
17 | 11 .text 00001e48 08048b00 08048b00 00000b00 2**4
18 | $ ./disassemble.py /bin/cat 0xb00 0x1e48
19 |
20 | Disassembling file /bin/cat at offset: 0x2816
21 | 00002816: mov 0x8(%ebp),%edx
22 | 00002819: mov 0xc(%ebp),%eax
23 | 0000281C: mov %edx,(%esp,1)
24 | [...]
25 |
26 | LIBRARY USAGE:
27 | Getting the string information of an opcode is really simple:
28 |
29 | from disassemble import *
30 | data="\xeb\xfe"
31 | p=Opcode(data)
32 | print p.printOpcode("AT&T")
33 |
34 | The output would be:
35 | jmp 0xfffffffe
36 |
37 | If for example, we want to put that information in a fancy GUI, we could request for a string separated in mnemonic, source, dest (or dest, source) with getOpcode(FORMAT).
38 |
39 | p.getOpcode("AT&T")
40 |
41 | and it will return a table:
42 | ['jmp', '0xfffffffe']
43 |
44 | Metadata info:
45 | ~~~~~~~~ ~~~~~
46 | Every opcode has 3 variables: opcode, source, dest.
47 |
48 | - opcode, is the string of the mnenonic
49 | - source, is an object or None
50 | - dest, is an object or None
51 |
52 | There are 3 types of objects, Register, Address, SIB and Expression. There are a couple of common methods you can use:
53 |
54 | - object.printOpcode(FORMAT), the string representation of the object.
55 | - object.getSize(), size
56 | - object.getType, information of the opcode table.
57 | - object.getSFlag, object permission ("R"ead, "W"rite, e"X"ecute)
58 | - etc (You can browse the source to get more information)
59 |
60 |
--------------------------------------------------------------------------------
/src/disassemblers/libdisassemble/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/src/disassemblers/libdisassemble/__init__.py
--------------------------------------------------------------------------------
/src/disassemblers/libdisassemble/disassemble.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 |
3 |
4 | # Immunity libdisassemble
5 | #
6 | # Most of the functions are ported from the great libdisassm since we
7 | # we are using their opcode map.
8 |
9 | # TODO:
10 | # - Fix the getSize(), doesn't work well with all the opcodes
11 | # - Enhance the metadata info with more information on opcode.
12 | # i.e. we need a way to know if an address is an immediate, a relative offset, etc
13 | # - Fix the jmp (SIB) opcode in at&t that it has different output that the others.
14 | # - support all the PREFIX*
15 |
16 | # NOTE: This is less than a week work, so it might be full of bugs (we love bugs!)
17 | #
18 | # Any question, comments, hate mail: dave@immunitysec.com
19 |
20 |
21 | #
22 | # This library is free software; you can redistribute it and/or
23 | # modify it under the terms of the GNU Lesser General Public
24 | # License as published by the Free Software Foundation; either
25 | # version 2.1 of the License, or (at your option) any later version.
26 | #
27 | # This library is distributed in the hope that it will be useful,
28 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
29 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
30 | # Lesser General Public License for more details.
31 | #
32 | # You should have received a copy of the GNU Lesser General Public
33 | # License along with this library; if not, write to the Free Software
34 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 |
36 | # This code largely copyright Immunity, Inc (2004), parts
37 | # copyright mammon and used under the LGPL by permission
38 |
39 | import disassemblers.libdisassemble.opcode86 as opcode86
40 | import struct
41 | from sys import *
42 |
43 | table86=opcode86.tables86
44 | OP_PERM_MASK = 0x0000007
45 | OP_TYPE_MASK = 0x0000F00
46 | OP_MOD_MASK = 0x00FF000
47 | OP_SEG_MASK = 0x00F0000
48 | OP_SIZE_MASK = 0x0F000000
49 |
50 |
51 | class Mode:
52 | def __init__(self, type, mode=32):
53 | self.type = type #type & 0x700
54 | #self.flag = type & 0x7
55 | self.flag = type & OP_PERM_MASK
56 | self.length = 0
57 | self.mode = mode
58 |
59 | # format "AT&T" or "INTEL"
60 | def printOpcode(self, format, eip=0):
61 | return "Not available"
62 |
63 | def getType(self):
64 | return self.type
65 |
66 | def getSize(self):
67 | return self.length
68 |
69 | def getFlag(self):
70 | return self.flag
71 |
72 | def getSFlag(self):
73 | return ("R", "W", "X")[self.flag/2]
74 |
75 | def getOpSize(self):
76 | return (self.type & OP_SIZE_MASK)
77 |
78 | def getAddrMeth(self):
79 | return (self.type & opcode86.ADDRMETH_MASK)
80 |
81 | class Register(Mode):
82 | def __init__(self, regndx, type=opcode86.OP_REG):
83 | Mode.__init__(self, type)
84 | #print regndx
85 | (self.name, self.detail, self.length)=opcode86.regs[regndx]
86 |
87 | def printOpcode(self, format="INTEL", eip=0):
88 | if format == "INTEL":
89 | return self.name
90 | else:
91 | return "%%%s" % self.name
92 |
93 | def getName(self):
94 | return self.name
95 |
96 | class Address(Mode):
97 | def __init__(self, data, length, type=opcode86.ADDEXP_DISP_OFFSET, signed=1, relative = None):
98 | Mode.__init__(self, type)
99 |
100 | self.signed=signed
101 | self.length = length
102 | #print "'%s' %d %x, %s"%(data, length, type, relative)
103 | fmt = "<"
104 | if self.signed:
105 | fmt += ("b", "h", "l")[length//2]
106 | else:
107 | fmt += ("B", "H", "L")[length//2]
108 |
109 | if (self.getAddrMeth() == opcode86.ADDRMETH_A):
110 | fmt += "H"
111 | length += 2
112 | self.value, self.segment = struct.unpack(fmt, data[:length])
113 | else:
114 | self.value, = struct.unpack(fmt, data[:length])
115 | self.segment = None
116 |
117 | self.relative = relative
118 |
119 |
120 | def printOpcode(self, format="INTEL", eip=0, exp=0):
121 | value = self.value
122 | segment = self.segment
123 |
124 | if (self.relative):
125 | value += eip
126 |
127 | if format == "INTEL":
128 | tmp=""
129 | if (segment):
130 | tmp += "0x%04x:"%(segment)
131 | if self.signed:
132 | if value < 0:
133 | return "%s-0x%x" % (tmp, value * -1)
134 | return "%s0x%x" % (tmp,self.value)
135 | else:
136 | #if self.length == 4 or not self.signed:
137 | return "%s0x%x" % (tmp,self.value)
138 | #else:
139 |
140 | else:
141 | pre=""
142 | #if self.getAddrMeth() == opcode86.ADDRMETH_E and not exp:
143 | if (self.getAddrMeth() == opcode86.ADDRMETH_I or self.getAddrMeth() == opcode86.ADDRMETH_A or self.type & opcode86.OP_IMM) and not exp:
144 | pre+="$"
145 | if segment:
146 | pre = "$0x%04x:%s"%(segment,pre)
147 | if (value < 0):
148 | if (self.signed):
149 | return "%s0x%0x" % (pre, ((1< 0 and tmp:
179 | tmp+="+"
180 | tmp += self.disp.printOpcode(format, eip, 1)
181 | pre=""
182 | optype=self.getOpSize()
183 |
184 | addr_meth=self.getAddrMeth()
185 | if addr_meth == opcode86.ADDRMETH_E:
186 | if optype == opcode86.OPTYPE_b:
187 | pre="BYTE PTR"
188 | elif optype== opcode86.OPTYPE_w:
189 | pre="WORD PTR"
190 | else :
191 | pre="DWORD PTR"
192 | tmp="%s [%s]" % (pre, tmp)
193 | else:
194 | if self.base:
195 | tmp+="(%s)" % self.base.printOpcode(format, eip)
196 | if self.disp:
197 | tmp= "%s%s" % (self.disp.printOpcode(format, eip, 1), tmp)
198 | #tmp="Not available"
199 | return tmp
200 | class SIB(Mode):
201 | def __init__(self, scale, base, index):
202 | self.scale = scale
203 | self.base = base
204 | self.index = index
205 | def printOpcode(self, format="INTEL", eip=0):
206 | tmp=""
207 | if format == "INTEL":
208 | if self.base:
209 | tmp+="%s" % self.base.printOpcode(format, eip)
210 | if self.scale > 1:
211 | tmp+= "*%d" % self.scale
212 | if self.index:
213 | if tmp:
214 | tmp+="+"
215 | tmp+="%s" % self.index.printOpcode(format, eip)
216 | else:
217 | if self.base:
218 | tmp+="%s" % self.base.printOpcode(format, eip)
219 | if self.index:
220 | #if tmp:
221 | #tmp+=","
222 | tmp += ", %s" % self.index.printOpcode(format, eip)
223 | if self.scale:
224 | if (self.scale > 1 or self.index):
225 | tmp+=", %d" % self.scale
226 |
227 | return tmp
228 | return tmp
229 |
230 | class Prefix:
231 | def __init__(self, ndx, ptr):
232 | self.ptr = ptr
233 | self.type = opcode86.prefix_table[ndx]
234 |
235 | def getType(self):
236 | return self.type
237 |
238 | def getName(self):
239 | if self.ptr[6]:
240 | return self.ptr[6]
241 | else:
242 | return ""
243 |
244 | class Opcode:
245 | def __init__(self, data, mode=32):
246 | self.length = 0
247 | self.mode = mode
248 | if mode == 64:
249 | self.addr_size = 4
250 | else:
251 | self.addr_size = mode/8 # 32-bit mode = 4 bytes. 16-bit mode = 2 bytes
252 | self.data = data
253 | self.off = 0
254 | self.source = ""
255 | self.dest = ""
256 | self.aux = ""
257 | self.prefix = []
258 | self.parse(table86[0], self.off)
259 |
260 | def getOpcodetype(self):
261 | return self.opcodetype
262 |
263 | def parse(self, table, off):
264 | """
265 | Opcode.parse() is the core logic of libdisassemble. It recurses through the supplied bytes digesting prefixes and opcodes, and then handles operands.
266 | """
267 | try: ## Crash Gracefully with a "invalid" opcode
268 | self.addr_size = 4
269 | ndx = self.data[off]
270 |
271 | ### This next line slices and dices the opcode to make it fit correctly into the current lookup table.
272 | #
273 | # byte min shift mask
274 | # (tbl_0F, 0, 0xff, 0, 0xff),
275 | # (tbl_80, 3, 0x07, 0, 0xff),
276 | #
277 | # simple subtraction
278 | # shift bits right (eg. >> 4 makes each line in the table valid for 16 numbers... ie 0xc0-0xcf are all one entry in the table)
279 | # mask part of the byte (eg. & 0x7 only makes use of the 00000111 bits...)
280 | if (ndx > table[4]):
281 | table = table86[table[5]] # if the opcode byte falls outside the bounds of accepted values, use the table pointed to as table[5]
282 | ndx = ( (ndx - table[3]) >> table[1]) & table[2]
283 | ptr = table[0][ndx] # index from table
284 |
285 | if ptr[1] == opcode86.INSTR_PREFIX or (ptr[1] & opcode86.INSTR_PREFIX64 and self.mode == 64):
286 | # You can have more than one prefix (!?)
287 | if ptr[0] != 0 and len(self.data) > off and self.data[off+1] == 0x0F:
288 | self.parse(table86[ptr[0]], off+2) # eg. 660Fxx, F20Fxx, F30Fxx, etc...
289 | else:
290 | self.prefix.append( Prefix(ndx, ptr) )
291 | self.parse(table, off+1) # parse next instruction
292 |
293 | return
294 | if ptr[0] != 0:
295 | # > 1 byte length opcode
296 | self.parse(table86[ptr[0]], off+1)
297 | return
298 |
299 | ### End Recursion, we hit a leaf node.
300 |
301 | self.opcode = ptr[6]
302 | self.opcodetype = ptr[1]
303 | self.cpu = ptr[5]
304 | self.off = off + 1 # This instruction
305 |
306 | if table[2] != 0xff: # Is this byte split between opcode and operand? If so, let's not skip over this byte quite yet...
307 | self.off-=1
308 | #print >>stderr,(" opcode = %s\n opcodetype = %x\n cpu = %x\n off = %d"%(ptr[6], ptr[1], ptr[5], off+1))
309 |
310 | n_bytes=0
311 | # src dst aux
312 | values=['', '', '' ]
313 | r = [False]*3
314 | w = [False]*3
315 | #print self.off
316 |
317 | for a in range(2, 5):
318 | ret = (0, None)
319 |
320 | tmp =ptr[a]
321 | addr_meth = tmp & opcode86.ADDRMETH_MASK;
322 | if addr_meth == opcode86.OP_REG:
323 | # what do i supposed to do?
324 | pass
325 |
326 | operand_size = self.get_operand_size(tmp)
327 | #print operand_size
328 | if operand_size == 1:
329 | genreg = opcode86.REG_BYTE_OFFSET
330 | elif operand_size == 2:
331 | genreg = opcode86.REG_WORD_OFFSET
332 | else:
333 | genreg= opcode86.REG_DWORD_OFFSET
334 |
335 | # Begin hashing on the ADDRMETH for this operand. This should determine the number of bytes to advance in the data.
336 | if addr_meth == opcode86.ADDRMETH_E:
337 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, genreg, self.addr_size, tmp)
338 |
339 | elif addr_meth == opcode86.ADDRMETH_M:
340 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, genreg, self.addr_size, tmp)
341 |
342 | elif addr_meth == opcode86.ADDRMETH_N:
343 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, opcode86.REG_MMX_OFFSET, self.addr_size, tmp)
344 |
345 | elif addr_meth == opcode86.ADDRMETH_Q:
346 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, opcode86.REG_MMX_OFFSET, self.addr_size, tmp)
347 |
348 | elif addr_meth == opcode86.ADDRMETH_R:
349 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, genreg, self.addr_size, tmp)
350 |
351 | elif addr_meth == opcode86.ADDRMETH_W:
352 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, opcode86.REG_SIMD_OFFSET, self.addr_size, tmp)
353 |
354 | elif addr_meth == opcode86.ADDRMETH_C:
355 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_reg, opcode86.REG_CTRL_OFFSET, self.addr_size, tmp)
356 |
357 | elif addr_meth == opcode86.ADDRMETH_D:
358 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_reg, opcode86.REG_DEBUG_OFFSET, self.addr_size, tmp)
359 |
360 | elif addr_meth == opcode86.ADDRMETH_G:
361 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_reg, genreg, self.addr_size, tmp)
362 |
363 | elif addr_meth == opcode86.ADDRMETH_P:
364 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_reg, opcode86.REG_MMX_OFFSET, self.addr_size, tmp)
365 |
366 | elif addr_meth == opcode86.ADDRMETH_S:
367 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_reg, opcode86.REG_SEG_OFFSET, self.addr_size, tmp)
368 |
369 | #elif addr_meth == opcode86.ADDRMETH_T: #TEST REGISTERS?:
370 | #ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, opcode86.REG_TEST_OFFSET, self.addr_size, tmp)
371 |
372 | elif addr_meth == opcode86.ADDRMETH_U:
373 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_EA, opcode86.REG_SIMD_OFFSET, self.addr_size, tmp)
374 |
375 | elif addr_meth == opcode86.ADDRMETH_V:
376 | ret=self.get_modrm(self.data[self.off:], opcode86.MODRM_reg, opcode86.REG_SIMD_OFFSET, self.addr_size, tmp)
377 |
378 | elif addr_meth == opcode86.ADDRMETH_A:
379 | ret= (self.addr_size, Address(self.data[self.off:], self.addr_size, tmp, signed=0))
380 |
381 | elif addr_meth == opcode86.ADDRMETH_F:
382 | # eflags, so what?
383 | pass
384 |
385 | elif addr_meth == opcode86.ADDRMETH_I:
386 | if tmp & opcode86.OP_SIGNED:
387 | ret = (operand_size, Address( self.data[self.off+n_bytes:], operand_size, tmp))
388 | #ret = (self.addr_size, Address( self.data[self.off+bytes:], operand_size, tmp))
389 | else:
390 | ret = (operand_size, Address( self.data[self.off+n_bytes:], operand_size,tmp, signed=0))
391 | #ret = (self.addr_size, Address( self.data[self.off+bytes:], operand_size,tmp, signed=0))
392 |
393 | elif addr_meth == opcode86.ADDRMETH_J:
394 | ret = (operand_size, Address( self.data[self.off+n_bytes:], operand_size, tmp, signed=1, relative=True))
395 | #ret = (self.addr_size, Address( self.data[self.off+bytes:], operand_size, tmp, signed=1, relative=True))
396 |
397 | elif addr_meth == opcode86.ADDRMETH_O:
398 | ret = (self.addr_size, Address( self.data[self.off:], self.addr_size, tmp, signed=0))
399 |
400 | elif addr_meth == opcode86.ADDRMETH_X:
401 | ret = (0, Register(6+opcode86.REG_DWORD_OFFSET, tmp))
402 |
403 | elif addr_meth == opcode86.ADDRMETH_Y:
404 | ret = (0, Register(7+opcode86.REG_DWORD_OFFSET, tmp))
405 |
406 | else:
407 | if tmp & opcode86.OP_REG:
408 | regoff = 0
409 | if self.mode == 64 and self.opcodetype in [opcode86.INS_PUSH, opcode86.INS_POP]:
410 | regoff = opcode86.REG_QWORD_OFFSET - opcode86.REG_DWORD_OFFSET
411 | if self.rex('w'):
412 | regoff -= 16
413 | if self.rex('b'):
414 | regoff += 8
415 | ret = (0, Register(ptr[5+a]+regoff, tmp))
416 | elif tmp & opcode86.OP_IMM:
417 | ret = (0, Address(bytes([ptr[5+a]]), 1, signed=0))
418 | else:
419 | ret= (0, None)
420 | if ret[1]:
421 | if isinstance(ret[1], Expression):
422 | ret[1].setPsize(operand_size)
423 | values[a-2]=ret[1]
424 | r[a-2] = (tmp & opcode86.OP_R) != 0
425 | w[a-2] = (tmp & opcode86.OP_W) != 0
426 | n_bytes += ret[0]
427 |
428 | self.source = values[0]
429 | self.dest = values[1]
430 | self.aux = values[2]
431 | self.r = r
432 | self.w = w
433 |
434 | self.off += n_bytes
435 | #self.data = self.data[:self.off]
436 | except IndexError:
437 | output = ""
438 | for i in range(len(self.data)):
439 | output += "%02x"%self.data[i]
440 |
441 | print (("Error Parsing Opcode - Data: %s\t Offset: 0x%x"%(output,self.off)), file=stderr)
442 |
443 | x,y,z = exc_info()
444 | excepthook(x,y,z)
445 |
446 | def getSize(self):
447 | return self.off
448 |
449 | def get_operand_size(self, opflag):
450 | """
451 | get_operand_size() gets the operand size, not the address-size or the size of the opcode itself.
452 | But it's also bastardized, because it manipulates self.addr_size at the top
453 | """
454 | size=self.mode / 8 #initial setting (4 for 32-bit mode)
455 | if self.mode == 64:
456 | size = 4
457 |
458 | flag = opflag & opcode86.OPTYPE_MASK
459 |
460 | #print "flag=%x mode=%d"%(flag,self.mode)
461 | if (flag in opcode86.OPERSIZE.keys()): # lookup the value in the table
462 | size = opcode86.OPERSIZE[flag][size >> 2]
463 |
464 |
465 | for a in self.prefix:
466 | if a.getType() & opcode86.PREFIX_OP_SIZE and size > 2:
467 | size = 2
468 | if a.getType() & opcode86.PREFIX_ADDR_SIZE:
469 | # this simply swaps between 16- to 32-bit (default is determined on a "system-wide" level. This will require changing for 64-bit mode
470 | if (self.addr_size == 2):
471 | self.addr_size = 4
472 | else:
473 | self.addr_size = 2
474 |
475 | return size
476 |
477 | """
478 | ### THIS IS THE OLD LIBDISASSEMBLE CODE...
479 | #print flag
480 | if flag == opcode86.OPTYPE_c:
481 | size = (1,2)[size==4]
482 | elif (flag == opcode86.OPTYPE_a) or (flag == opcode86.OPTYPE_v) or (flag == opcode86.OPTYPE_z):
483 | size = (2,4)[size==4]
484 | elif flag == opcode86.OPTYPE_p:
485 | size = (4,6)[size==4]
486 | elif flag == opcode86.OPTYPE_b:
487 | size = 1
488 | elif flag == opcode86.OPTYPE_w:
489 | size = 2
490 | elif flag == opcode86.OPTYPE_d:
491 | size = 4
492 | elif flag & opcode86.OPTYPE_s:
493 | size = 6
494 | elif flag & opcode86.OPTYPE_q:
495 | size = 8
496 | # - a lot more to add
497 | """
498 |
499 | def get_reg(self, regtable, num):
500 | return regtable[num]
501 |
502 | def get_sib(self, data, mod):
503 | count = 1
504 | sib = data[0]
505 | s=None
506 | #print "SIB: %s" % hex(ord(data[0]))
507 |
508 | scale = (sib >> 6) & 0x3 # XX
509 | index = (sib & 56) >>3 # XXX
510 | base = sib & 0x7 # XXX
511 |
512 | base2 = None
513 | index2= None
514 | #print base, index, scale
515 | # Especial case
516 | if base == 5 and not mod:
517 | base2 = Address(data[1:], 4)
518 | count += 4
519 | else:
520 | if self.rex('b'):
521 | base += 8
522 | base2 = Register(base + 16)
523 |
524 | index2=None
525 | # Yeah, i know, this is really ugly
526 | if index != 4: # ESP
527 | if self.rex('x'):
528 | index += 8
529 | index2=Register( index + 16)
530 | else:
531 | scale = 0
532 | s= SIB( 1<> 6) & 0x3 # XX
543 | reg = (modrm >> 3) & 0x7 # XXX
544 | rm = modrm & 0x7 # XXX
545 |
546 | result = None
547 | disp = None
548 | base = None
549 |
550 | rmoff = 0
551 | regoff = 0
552 | if self.rex('w'):
553 | rmoff -= 16
554 | regoff -= 16
555 | if self.rex('b'):
556 | rmoff += 8
557 | if self.rex('r'):
558 | regoff += 8
559 |
560 | if flags == opcode86.MODRM_EA:
561 | if mod == 3: # 11
562 | result=Register(rm+reg_type+rmoff, type_flag)
563 | elif mod == 0: # 0
564 | if rm == 5:
565 | disp= Address(data[count:], self.addr_size, type_flag)
566 | count+= self.addr_size
567 | elif rm == 4:
568 | (tmpcount, base) =self.get_sib(data[count:], mod)
569 | count+=tmpcount
570 | else:
571 | #print ("mod:%d\t reg:%d\t rm:%d"%(mod,reg,rm))
572 | base=Register(rm+reg_type+rmoff, type_flag)
573 | else:
574 |
575 | if rm ==4:
576 | disp_base = 2
577 | (tmpcount, base) =self.get_sib(data[count:], mod)
578 | count+=tmpcount
579 | else:
580 | disp_base = 1
581 | base=Register(rm+reg_type+rmoff, type_flag)
582 | #print ">BASE: %s" % base.printOpcode()
583 | if mod == 1:
584 | disp= Address(data[disp_base:], 1, type_flag)
585 | count+=1
586 | else:
587 | disp= Address(data[disp_base:], self.addr_size, type_flag)
588 | count+= self.addr_size
589 | if disp or base:
590 | result=Expression(disp, base, type_flag)
591 | else:
592 | result=Register(reg+reg_type+regoff, type_flag)
593 | count=0
594 |
595 | return (count, result)
596 | # FIX:
597 | #
598 | def getOpcode(self, FORMAT, eip = 0):
599 | opcode=[]
600 | if not self.opcode:
601 | return [0]
602 | if FORMAT == "INTEL":
603 | opcode.append("%s" % self.opcode)
604 | #tmp="%-06s %s" % (self.opcode, " " * space)
605 | if self.source:
606 | opcode.append(self.source.printOpcode(FORMAT, eip))
607 | #tmp+=" %s" % self.source.printOpcode(FORMAT, eip)
608 | if self.dest:
609 | opcode.append(self.dest.printOpcode(FORMAT, eip))
610 | #tmp+=", %s" % self.dest.printOpcode(FORMAT, eip)
611 | if self.aux:
612 | opcode.append(self.aux.printOpcode(FORMAT, eip))
613 |
614 | else:
615 | mnemonic = self.opcode
616 | post=[]
617 | if self.source and self.dest:
618 | addr_meth = self.source.getAddrMeth()
619 | optype = self.source.getOpSize()
620 | mnemonic = self.opcode
621 |
622 | if addr_meth == opcode86.ADDRMETH_E and\
623 | not (isinstance(self.source, Register) or\
624 | isinstance(self.dest, Register)):
625 | if optype == opcode86.OPTYPE_b:
626 | mnemonic+="b"
627 | elif optype== opcode86.OPTYPE_w:
628 | mnemonic+=""
629 | else :
630 | mnemonic+="l"
631 |
632 | ##first="%-06s %s" % (mnemonic, " " * space)
633 | post= [self.dest.printOpcode(FORMAT, eip), self.source.printOpcode(FORMAT, eip)]
634 | if self.aux:
635 | post.append(self.aux.printOpcode(FORMAT, eip))
636 | #post = "%s, %s" % (self.dest.printOpcode(FORMAT,eip), self.source.printOpcode(FORMAT, eip))
637 | elif self.source:
638 | #second="%-06s %s" % (mnemonic, " " * space)
639 | opt = self.getOpcodetype()
640 | tmp=""
641 | if (opt== opcode86.INS_CALL or\
642 | opt== opcode86.INS_BRANCH)\
643 | and self.source.getAddrMeth() == opcode86.ADDRMETH_E:
644 |
645 | tmp = "*"
646 | post=[tmp + self.source.printOpcode(FORMAT, eip)]
647 | #post += "%s" % self.source.printOpcode(FORMAT, eip)
648 | opcode = [mnemonic] + post
649 |
650 | return (opcode, self.r, self.w)
651 |
652 | def printOpcode(self, FORMAT, eip = 0, space=6):
653 | opcode=self.getOpcode(FORMAT, eip + self.getSize())
654 | prefix=self.getPrefix();
655 | if opcode[0]==0:
656 | return "invalid"
657 | if len(opcode) ==2:
658 | return "%-08s%s%s" % (prefix+opcode[0], " " * space, opcode[1])
659 | #return "%-08s%s%s" % (prefix+opcode[0], " " * 6, opcode[1])
660 | elif len(opcode) ==3:
661 | return "%-08s%s%s, %s" % (prefix+opcode[0], " " * space, opcode[1], opcode[2])
662 | #return "%-08s%s%s, %s" % (prefix+ opcode[0], " " * 6, opcode[1], opcode[2])
663 | elif len(opcode) ==4:
664 | return "%-08s%s%s, %s, %s" % (prefix+opcode[0], " " * space, opcode[3], opcode[1], opcode[2])
665 | else:
666 | return "%-08s" % (prefix+opcode[0])
667 | return tmp
668 | def rex(self, f):
669 | if self.mode != 64:
670 | return False
671 | b, w, x, r = False, False, False, False
672 | for a in self.prefix:
673 | type = a.getType()
674 | if type & opcode86.PREFIX_REX:
675 | if type & opcode86.PREFIX_REXB:
676 | b = True
677 | if type & opcode86.PREFIX_REXW:
678 | w = True
679 | if type & opcode86.PREFIX_REXX:
680 | x = True
681 | if type & opcode86.PREFIX_REXR:
682 | r = True
683 |
684 | if f == 'w':
685 | return w
686 | if f == 'x':
687 | return x
688 | if f == 'b':
689 | return b
690 | if f == 'r':
691 | return r
692 |
693 | return False
694 |
695 | def getPrefix(self):
696 | prefix=""
697 | for a in self.prefix:
698 | type = a.getType()
699 | if type in [opcode86.PREFIX_LOCK, opcode86.PREFIX_REPNZ, opcode86.PREFIX_REP]:
700 | prefix+= a.getName() + " "
701 | if self.mode == 64:
702 | if (type & opcode86.PREFIX_REX):
703 | rex = ''
704 | if type & opcode86.PREFIX_REXB:
705 | rex += 'b'
706 | if type & opcode86.PREFIX_REXW:
707 | rex += 'w'
708 | if type & opcode86.PREFIX_REXX:
709 | rex += 'x'
710 | if type & opcode86.PREFIX_REXR:
711 | rex += 'r'
712 | if rex:
713 | prefix += 'REX.'+rex+' '
714 | else:
715 | prefix += 'REX '
716 | return prefix
717 | if __name__=="__main__":
718 | # To get this information, just
719 | import sys
720 | if len(sys.argv) != 4:
721 | print ("usage: {} ".format(sys.argv[0]))
722 | print ("\t file:\t file to disassemble")
723 | print ("\t offset:\t offset to beggining of code(hexa)")
724 | print ("\t size:\t amount of bytes to dissasemble (hexa)\n")
725 |
726 |
727 | sys.exit(0)
728 | f=open(sys.argv[1])
729 | offset= int(sys.argv[2], 16)
730 | f.seek( offset )
731 | buf=f.read(int(sys.argv[3], 16) )
732 | off=0
733 | FORMAT="AT&T"
734 | print("Disassembling file %s at offset: 0x%x" % (sys.argv[1], offset))
735 | while 1:
736 | try:
737 | p=Opcode(buf[off:])
738 |
739 | print(" %08X: %s" % (off+offset, p.printOpcode(FORMAT)))
740 | off+=p.getSize()
741 | except ValueError:
742 | break
743 |
--------------------------------------------------------------------------------
/src/disassemblers/x64.py:
--------------------------------------------------------------------------------
1 | from disassemblers.libdisassemble.disassemble import *
2 | import debug
3 |
4 | def repr_ins(ins, r, w, objbounds, sections, binary):
5 | '''
6 | Represent an x64 instruction in the immediate instruction format.
7 | '''
8 | def arg(n):
9 | '''
10 | Helper function for converting arguments.
11 | '''
12 | value = ins[n+1]
13 | arg_repr = value
14 |
15 | if value.startswith('0x'):
16 | val = int(value, 16)
17 | if val >= objbounds[0] and val < objbounds[1]:
18 | '''Likely candidate for a constant'''
19 |
20 | ro = sections['.rodata']
21 | if val >= ro['virt'] and val < ro['virt']+ro['length']:
22 | addr = ro['start']+val-ro['virt']
23 | for i, b in enumerate(binary[addr:]):
24 | if b == 0:
25 | s = binary[addr:addr+i].decode()
26 | s = '"' + repr(s)[1:-1] + '"'
27 | arg_repr = s
28 | break
29 | if i > 100:
30 | break
31 |
32 | return {'value': value, 'repr': arg_repr, 'r': r[n], 'w': w[n]}
33 |
34 | def translate(op):
35 | '''
36 | Some instructions are easy to translate, but have weird names,
37 | for example imul -> mul.
38 | '''
39 | ins[0] = op
40 | return repr_ins(ins, r, w, objbounds, sections, binary)
41 |
42 | def jump_dest():
43 | '''
44 | Calculate a jump operand.
45 | '''
46 | dest = {'type':'const', 'value': ins[1], 'r': True, 'w': False}
47 | try:
48 | dest['repr'] = int(ins[1],16)
49 | except ValueError:
50 | dest['repr'] = ins[1]
51 | return dest
52 |
53 | def parse_addr(addr, r=True, w=False):
54 | '''
55 | Parse the addressing mode (e.g. in a LEA).
56 | '''
57 | addr = addr.strip().strip('[]')
58 |
59 | for op, repr in [('sub', '-'), ('add', '+'), ('mul', '*')]:
60 | parts = addr.partition(repr)
61 | if parts[1]:
62 | return {'op': op, 'dest': parse_addr(parts[0], r, w), 'src': parse_addr(parts[2], r, w)}
63 |
64 | return {'value': addr, 'repr': addr, 'r': r, 'w': w}
65 |
66 |
67 | nop = {'op': 'nop'}
68 |
69 | if ins[0][0] == 'j':
70 | cond = ins[0][1:]
71 | if cond == 'mp':
72 | cond = 'true'
73 | return {'op': 'jump', 'cond': cond, 'dest': jump_dest()}
74 | elif ins[0] == 'call':
75 | return {'op': 'call', 'dest': jump_dest()}
76 | elif ins[0] == 'arpl':
77 | return nop
78 | elif ins[0] == 'cwde':
79 | dest = {'value': 'eax', 'repr': 'eax', 'r': False, 'w': True}
80 | src = {'value': 'ax', 'repr': 'eax', 'r': True, 'w': False}
81 | return {'op': 'mov', 'dest': dest, 'src': src}
82 | elif ins[0] == 'leave':
83 | return nop
84 | elif ins[0] == 'lea':
85 | src = parse_addr(ins[2])
86 | return {'op': 'mov', 'dest': arg(0), 'src': src}
87 | elif ins[0] == 'push':
88 | return nop
89 | elif ins[0] == 'imul':
90 | # libdisassemble bug fix :(
91 | w[0] = True
92 | return translate('mul')
93 | elif ins[0] == 'idiv':
94 | return translate('div')
95 | elif ins[0] == 'cmp':
96 | cmp = {'value': 'cmp', 'repr': 'cmp', 'r': False, 'w': True}
97 | src = {'op': 'sub', 'dest': arg(0), 'src': arg(1)}
98 | return {'op': 'mov', 'dest': cmp, 'src': src}
99 | elif ins[0] == 'test':
100 | cmp = {'value': 'cmp', 'repr': 'cmp', 'r': False, 'w': True}
101 | src = {'op': 'and', 'dest': arg(0), 'src': arg(1)}
102 | return {'op': 'mov', 'dest': cmp, 'src': src}
103 | elif ins[0] == 'ret':
104 | dest = {'value': 'eax', 'repr': 'eax', 'r': True, 'w': False}
105 | return {'op': 'return', 'src': dest}
106 | elif len(ins) == 1:
107 | return {'op': ins[0]}
108 | elif len(ins) == 2:
109 | return {'op': ins[0], 'dest': arg(0)}
110 | elif len(ins) == 3:
111 | return {'op': ins[0], 'dest': arg(0), 'src': arg(1)}
112 | elif len(ins) == 4:
113 | return {'op': ins[0], 'dest': arg(0), 'src': arg(1), 'arg3': arg(2)}
114 |
115 | raise Exception('Bad x64 instruction: '+str(ins))
116 |
117 | def disassemble(buf, virt, sections, binary):
118 | '''
119 | Disassemble a block of x64 code.
120 | '''
121 |
122 | virts = [(sections[sect]['virt'], sections[sect]['length']) for sect in sections if sections[sect]['virt']]
123 | objmin = min(virt[0] for virt in virts)
124 | objmax = max(virt[0]+virt[1] for virt in virts)
125 | objbounds = (objmin, objmax)
126 |
127 | FORMAT="INTEL"
128 | entries = [virt]
129 |
130 | result = {}
131 | while entries:
132 | addr = entries.pop()
133 | off = addr-virt
134 | while off < len(buf):
135 | p = Opcode(buf[off:], mode=64)
136 | pre = p.getPrefix()
137 | length = p.getSize()
138 | try:
139 | ins, r, w = p.getOpcode(FORMAT)
140 | except ValueError:
141 | break
142 | ins = repr_ins(ins, r, w, objbounds, sections, binary)
143 |
144 | if debug.check('asm_rw'):
145 | print(ins, r, w)
146 |
147 | debug_dis = {
148 | 'prefix': pre,
149 | 'binary': buf[off:off+length]
150 | }
151 | result[addr] = {'ins': ins, 'loc': addr, 'length': length, 'debug': debug_dis, 'display': True}
152 | if ins['op'] == 'return':
153 | break
154 | # if ins['op'] == 'call':
155 | # j_addr = addr+length+ins['dest']['repr']
156 | # if j_addr not in result:
157 | # entries.append(j_addr)
158 | if ins['op'] == 'jump':
159 | j_addr = addr+length+ins['dest']['repr']
160 | if j_addr not in result:
161 | entries.append(j_addr)
162 | result[addr]['display'] = False
163 | if ins['cond'] == 'true':
164 | break
165 | off += length
166 | addr += length
167 |
168 | return [result[key] for key in sorted(result.keys())]
169 |
--------------------------------------------------------------------------------
/src/function_calls.py:
--------------------------------------------------------------------------------
1 | from disassemblers.libdisassemble.opcode86 import regs
2 | from copy import deepcopy
3 |
4 | legal_integers = ['rdi', 'rsi', 'rdx', 'rcx', 'r8', 'r9']
5 | legal_sse = ['xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5', 'xmm6', 'xmm7']
6 | legal_other = ['rax']
7 |
8 | def reg_normalize(reg):
9 | '''
10 | Normalize a register to a form independent of its size.
11 | '''
12 | idx = list(map(lambda x: x[0], regs)).index(reg)
13 | return regs[idx&0xF][0]
14 |
15 | class Params:
16 | '''
17 | A data structure that holds the current list of parameters used
18 | and is able to let you know when it ends using some heuristics.
19 | '''
20 | def __init__(self):
21 | self.memory = []
22 | self.integers = []
23 | self.sse = []
24 | self.other = []
25 | self.args = []
26 |
27 | def add(self, reg, arg):
28 | '''
29 | Try to add a register to the list of params.
30 |
31 | If its the next legal register in a list of parameters, it's added
32 | and True is returned. If it isn't, False is returned so that the
33 | function can be wrapped.
34 | '''
35 | arg = deepcopy(arg)
36 | if 'w' in arg:
37 | arg['w'] = False
38 | arg['r'] = True
39 | try:
40 | param = reg_normalize(reg)
41 | except ValueError:
42 | return False
43 | try:
44 | if legal_integers[len(self.integers)] == param:
45 | self.integers.append(reg)
46 | self.args.append(arg)
47 | return True
48 | elif legal_sse[len(self.sse)] == reg:
49 | #fix normalization here
50 | self.sse.append(reg)
51 | self.args.append(arg)
52 | return True
53 | elif legal_other[len(self.other)] == param:
54 | self.other.append(reg)
55 | return True
56 | else:
57 | return False
58 | except IndexError:
59 | return False
60 |
61 | def fold(cfg, symbols):
62 | '''
63 | Fold as many function calls as its possible, infering arguments lists
64 | along the way.
65 | '''
66 | for block, depth in cfg.iterblocks():
67 | inside_call = False
68 | for n, line in enumerate(reversed(block)):
69 | if inside_call:
70 | if 'dest' not in line['ins']:
71 | continue
72 | dest = line['ins']['dest']
73 | param = dest['value']
74 | if call_params.add(param, dest):
75 | pass
76 | else:
77 | apply_ins = {'op': 'apply', 'function': function_name, 'args': call_params.args}
78 | eax = {'value': 'eax', 'repr': 'eax', 'r': False, 'w': True}
79 | mov_ins = {'op': 'mov', 'src': apply_ins, 'dest': eax}
80 | block[len(block)-call_n-1]['ins'] = mov_ins
81 | inside_call = False
82 | call_params = None
83 | if line['ins']['op'] == 'call':
84 | inside_call = True
85 | call_n = n
86 | call_params = Params()
87 | function_name = 'unknown_function'
88 | if 'repr' in line['ins']['dest']:
89 | if type(line['ins']['dest']['repr']) == int:
90 | addr = line['loc']+line['length']+line['ins']['dest']['repr']
91 | if addr in symbols:
92 | function_name = symbols[addr]
93 |
94 |
--------------------------------------------------------------------------------
/src/objdump.py:
--------------------------------------------------------------------------------
1 | from subprocess import Popen, PIPE
2 |
3 | def sections(filename):
4 | sections = {}
5 | p = Popen(["objdump", "-h", filename], stdout=PIPE)
6 | p_out = p.communicate()[0].decode()
7 |
8 | for line in p_out.split('\n'):
9 | words = line.split()
10 | if len(words) > 0 and words[0].isdigit():
11 | sections[words[1]] = {'start': int(words[5], 16), 'length': int(words[2], 16), 'virt': int(words[3],16)}
12 | return sections
13 |
14 | def symbols(filename):
15 | symbols = {}
16 | p = Popen(["objdump", "-t", filename], stdout=PIPE)
17 | p_out = p.communicate()[0].decode()
18 |
19 | for line in p_out.split('\n'):
20 | words = line.split()
21 | if len(words) > 0 and words[1] == 'g' and not words[-1].startswith('_'):
22 | symbols[words[-1]] = {'start': int(words[0], 16), 'length': int(words[-2], 16), 'type': words[2]}
23 |
24 | return symbols
25 |
26 | def objdump(filename):
27 | '''
28 | Find sections and symbols in an object file.
29 | '''
30 | obj_sections = sections(filename)
31 | obj_symbols = symbols(filename)
32 |
33 | return obj_sections, obj_symbols
34 |
--------------------------------------------------------------------------------
/src/ocd.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | from disassemble import disassemble
3 | from decompile import decompile_functions
4 | from objdump import objdump
5 | import control_flow
6 | import debug
7 | import representation
8 |
9 | if __name__=="__main__":
10 | import sys
11 | from optparse import OptionParser
12 |
13 | usage = "usage: %prog [options] file"
14 | parser = OptionParser(usage=usage)
15 | parser.add_option("-d", "--debug", dest="debug", action="append",
16 | help="turn debug option on", default=[], choices=debug.options,
17 | metavar="OPTION")
18 | parser.add_option("-g", "--graph", action="store", dest="graphfile",
19 | metavar="FILE", type="string", help="output a control flow graph")
20 |
21 | options, args = parser.parse_args()
22 |
23 | for option in options.debug:
24 | debug.set(option)
25 |
26 | if len(args) < 1:
27 | parser.print_help()
28 |
29 | sys.exit(0)
30 |
31 | filename = args[0]
32 |
33 | f = open(filename, "rb")
34 | binary = f.read()
35 | f.close()
36 |
37 | sections, symbols = objdump(filename)
38 | text = sections['.text']
39 |
40 | if options.graphfile:
41 | gf = open(options.graphfile, 'w')
42 | gf.write("digraph cfg {\n")
43 | control_flow.graphfile = gf
44 |
45 | functions = {}
46 | if symbols:
47 | for name, symbol in symbols.items():
48 | if not name.startswith('_') and symbol['type'] == 'F':
49 | start = symbol['start']-text['virt']+text['start']
50 | length = symbol['length']
51 | functions[name] = disassemble(binary[start:start+length], symbol['start'], sections, binary)
52 | else:
53 | functions['start'] = disassemble(binary[text['start']:text['start']+text['length']], text['virt'], sections, binary)
54 | symbols['start'] = {'start': text['virt'], 'length': text['length']}
55 |
56 | decompiled_functions = decompile_functions(functions, symbols)
57 |
58 | print(representation.output_functions(decompiled_functions))
59 |
60 | if options.graphfile:
61 | gf.write("}\n")
62 | gf.close()
63 |
--------------------------------------------------------------------------------
/src/output/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drx/ocd/bbab05bcd4e6ec83fbc4e8c30f52babd140cc2dc/src/output/__init__.py
--------------------------------------------------------------------------------
/src/output/c.py:
--------------------------------------------------------------------------------
1 | from output.indent import Indent
2 | from output.conditions import conditions, condition_negs
3 | import debug
4 | import zlib
5 |
6 | def operator(op, precedence):
7 | '''
8 | Helper function for C operators.
9 | '''
10 | return ('{i[dest]} = ', '{i[dest]} '+op+' {i[src]}', precedence)
11 |
12 | ins_table = {
13 | 'add': operator('+', 12),
14 | 'and': operator('&', 8),
15 | 'div': operator('/', 13),
16 | 'mul': operator('*', 13),
17 | 'mov': ('{i[dest]} = ', '{i[src]}', 2),
18 | 'nop': ('', '', 0),
19 | 'return': ('return {i[src]}', '', 0),
20 | 'sar': operator('>>', 11),
21 | 'sal': operator('<<', 11),
22 | 'sub': operator('-', 12),
23 | 'xor': operator('^', 7),
24 | }
25 |
26 | def condition(cond, var='cmp'):
27 | '''
28 | Output a jump condition.
29 | '''
30 | if cond[0] == '!':
31 | cond = condition_negs[cond[1:]]
32 | return conditions[cond].format(cond=var)
33 |
34 | def striplines(s):
35 | '''
36 | Strip empty lines from string.
37 | '''
38 | return '\n'.join(line for line in s.split('\n') if line.strip())
39 |
40 | def repr_int(n):
41 | '''
42 | Get the representation of an integer.
43 |
44 | The representation is chosen based on its Kolmogorov complexity,
45 | i.e. the repr r is chosen which has the minimal value
46 | len(zlib.compress(r)).
47 | '''
48 | reprs = [('{0}','{0}'), ('{0:x}', '0x{0:x}')]
49 | lengths = [len(zlib.compress(r[0].format(n).encode())) for r in reprs]
50 | return reprs[lengths.index(min(lengths))][1].format(n)
51 |
52 |
53 | def output_op(op):
54 | '''
55 | Output an instruction according to it's opcode.
56 | '''
57 | return ins_table[op]
58 |
59 | def output_line(line, indent):
60 | '''
61 | Output a line of code. A line contains an instruction and
62 | some metainformation about that instruction (its location,
63 | etc.)
64 |
65 | The pseudo-EBNF of lines is as follows:
66 |
67 | line = location, debug, instruction
68 | instruction = op, argument*
69 | argument = value, repr | instruction
70 | '''
71 | def output_ins(ins):
72 | '''
73 | Decompile an instruction. Instructions are trees, see
74 | the EBNF for output_line.
75 | '''
76 | repr = {}
77 | prec = {}
78 | for k, arg in ins.items():
79 | if k not in ('src', 'dest'):
80 | continue
81 |
82 | if 'op' in ins[k]:
83 | lhs, rhs, prec[k] = output_ins(ins[k])
84 | repr[k] = rhs
85 | else:
86 | repr[k] = ins[k]['repr']
87 | prec[k] = 20
88 |
89 | if type(repr[k]) == int:
90 | repr[k] = repr_int(repr[k])
91 |
92 | if ins['op'] == 'apply':
93 | lhs = ''
94 | args = []
95 | for arg in ins['args']:
96 | if 'op' in arg:
97 | lhs, rhs, inner_prec = output_ins(arg)
98 | args.append(rhs)
99 | else:
100 | args.append(arg['repr'])
101 | rhs = '{fun}({args})'.format(fun=ins['function'], args=', '.join(args))
102 | outer_prec = 20
103 |
104 | else:
105 | try:
106 | lhs, rhs, outer_prec = output_op(ins['op'])
107 | except KeyError:
108 | lhs, rhs = '', '/* Unsupported immediate instruction: {ins[op]} */'.format(ins=ins)
109 | outer_prec = 20
110 |
111 | for k in dict(repr):
112 | if outer_prec > prec[k]:
113 | repr[k] = '(' + repr[k] + ')'
114 |
115 | return lhs.format(i=repr), rhs.format(i=repr), outer_prec
116 |
117 | lhs, rhs, prec = output_ins(line['ins'])
118 | line_repr = indent.out() + lhs + rhs
119 | if lhs+rhs != '':
120 | line_repr += ';'
121 |
122 | if not line['display']:
123 | line_repr = ''
124 |
125 | if debug.check('misc'):
126 | from binascii import hexlify
127 | line_repr += '\n{indent}{blue}/* {line} */{black}'.format(indent=indent.out(), line=line, blue='\033[94m', black='\033[0m')
128 |
129 | return line_repr
130 |
131 | def output_vertex(vertex, indent=None):
132 | '''
133 | Output a CFG vertex.
134 | '''
135 | key, block = vertex
136 | block_type, block_start = key
137 |
138 | if indent is None:
139 | indent = Indent(1)
140 |
141 | if block_type == 'block':
142 | return '\n'.join(output_line(line, indent) for line in block)
143 |
144 | elif block_type == 'if':
145 | cond, true = block
146 | fmt = ('\n'
147 | '{indent}if ({cond})\n'
148 | '{indent}{{\n'
149 | '{true}\n'
150 | '{indent}}}\n')
151 | return fmt.format(cond=condition(cond), true=output_vertex(true, indent.inc()), indent=indent.out())
152 |
153 | elif block_type == 'ifelse':
154 | cond, true, false = block
155 | fmt = ('\n'
156 | '{indent}if ({cond})\n'
157 | '{indent}{{\n'
158 | '{true}\n'
159 | '{indent}}}\n'
160 | '{indent}else\n'
161 | '{indent}{{\n'
162 | '{false}\n'
163 | '{indent}}}\n')
164 | return fmt.format(cond=condition(cond),
165 | true=output_vertex(true, indent.inc()), false=output_vertex(false, indent.inc()), indent=indent.out())
166 |
167 | elif block_type == 'while':
168 | cond, pre, loop = block
169 | fmt = ('\n'
170 | '{indent}while ({cond})\n'
171 | '{indent}{{\n'
172 | '{loop}\n'
173 | '{pre}\n'
174 | '{indent}}}\n')
175 | return fmt.format(indent=indent.out(), cond=condition(cond),
176 | pre=output_vertex(pre, indent.inc()), loop=output_vertex(loop, indent.inc()))
177 |
178 | elif block_type == 'cons':
179 | out = ''
180 | for b in block:
181 | out += output_vertex(b, indent)
182 | return out
183 |
184 | return '/* Error: unsupported block type */'
185 |
186 | def output_signature(signature, name):
187 | '''
188 | Output the signature of a function.
189 | '''
190 | fun_type, args = signature
191 |
192 | pre = fun_type + ' ' + name + '(' + ', '.join(args) + ')\n{\n'
193 | post = '\n}'
194 | return pre, post
195 |
196 | def output_function(function, name):
197 | '''
198 | Output a function.
199 | '''
200 | cfg, signature = function
201 |
202 | pre, post = output_signature(signature, name)
203 |
204 | innards = '\n/*----*/\n'.join(output_vertex(v) for v in cfg.sortedvertices())
205 |
206 | return pre + innards + post
207 |
208 | def output(functions):
209 | '''
210 | Output everything.
211 | '''
212 | out = ''
213 | for name, function in functions.items():
214 | out += output_function(function, name)
215 | out += '\n'
216 |
217 | return striplines(out)
218 |
--------------------------------------------------------------------------------
/src/output/conditions.py:
--------------------------------------------------------------------------------
1 | condition_negs = {
2 | 'a': 'be', 'ae': 'b', 'b': 'ae', 'be': 'a', 'c': 'a',
3 | 'e': 'ne', 'ne': 'e',
4 | 'g': 'le', 'ge': 'l', 'l': 'ge', 'le': 'g',
5 | 'na': 'a', 'nae': 'ae', 'nb': 'b', 'nbe': 'be', 'nc': 'c',
6 | 'ng': 'g', 'nge': 'ge', 'nl': 'l', 'nle': 'le',
7 | 'no': 'o', 'o': 'no', 's': 'ns', 'ns': 's',
8 | 'p': 'np', 'np': 'p', 'pe': 'np', 'po': 'p',
9 | 'z': 'nz', 'nz': 'z', 'true': 'false', 'false': 'true'
10 | }
11 |
12 | conditions = {
13 | 'a': '{cond} > 0',
14 | 'ae': '{cond} >= 0',
15 | 'b': '{cond} < 0',
16 | 'be': '{cond} <= 0',
17 | 'c': '{cond} <= 0',
18 | 'cxz': '!{cx}',
19 | 'ecxz': '!{ecx}',
20 | 'rcxz': '!{rcx}',
21 | 'e': '!{cond}',
22 | 'g': '{cond} > 0',
23 | 'ge': '{cond} >= 0',
24 | 'l': '{cond} < 0',
25 | 'le': '{cond} <= 0',
26 | 'na': '{cond} <= 0',
27 | 'nae': '{cond} < 0',
28 | 'nb': '{cond} >= 0',
29 | 'nbe': '{cond} > 0',
30 | 'nc': '{cond} >= 0',
31 | 'ne': '!{cond}',
32 | 'ng': '{cond} <= 0',
33 | 'nge': '{cond} < 0',
34 | 'nl': '{cond} >= 0',
35 | 'nle': '{cond} > 0',
36 | 'no': 'no_overflow',
37 | 'np': '{cond} & 1',
38 | 'ns': '({cond}>0)-(cmp<0) == -1',
39 | 'o': 'overflow',
40 | 'p': '!({cond} & 1)',
41 | 'pe': '!({cond} & 1)',
42 | 'po': '{cond} & 1',
43 | 's': '({cond}>0)-(cmp<0) >= 0',
44 | 'nz': '{cond}',
45 | 'z': '!{cond}',
46 | 'true': '1',
47 | 'false': '0',
48 | }
49 |
50 |
--------------------------------------------------------------------------------
/src/output/indent.py:
--------------------------------------------------------------------------------
1 | from copy import copy
2 |
3 | class Indent():
4 | '''
5 | Auto-indentation.
6 | '''
7 | def __init__(self, level=0):
8 | '''
9 | Initialize indentation level.
10 | '''
11 | self.level = level
12 |
13 | def inc(self):
14 | '''
15 | Increment indentation level.
16 | '''
17 | new = copy(self)
18 | new.level += 1
19 | return new
20 |
21 | def out(self):
22 | '''
23 | Output indentation.
24 | '''
25 | return '\t'*self.level
26 |
--------------------------------------------------------------------------------
/src/representation.py:
--------------------------------------------------------------------------------
1 | import output.c
2 |
3 | def output_functions(functions, lang='C'):
4 | '''
5 | Output all functions in a selected language.
6 | '''
7 | langs = {
8 | 'C': output.c
9 | }
10 | return langs[lang].output(functions)
11 |
--------------------------------------------------------------------------------
/tests/Makefile:
--------------------------------------------------------------------------------
1 | CC = gcc
2 | CFLAGS = -std=c99 -Wall -W -O0 -m64
3 |
4 | SOURCES := $(wildcard *.c)
5 | BINARIES := $(patsubst %.c, %, $(SOURCES))
6 |
7 | all: $(BINARIES)
8 |
9 | clean:
10 | rm $(BINARIES)
11 |
--------------------------------------------------------------------------------
/tests/test_ack.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | return printf("%d\n", ack(3, 4) );
4 | }
5 |
6 | int ack(int m, int n)
7 | {
8 | if (m == 0)
9 | {
10 | return n + 1;
11 | }
12 | else
13 | {
14 | if (n == 0)
15 | {
16 | return ack(m - 1, 1);
17 | }
18 | else {
19 | return ack(m - 1, ack(m, n - 1));
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tests/test_ack_scanf.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a, b, r;
4 | r = scanf("%d %d", &a, &b);
5 | r = printf("%d", ack(a, b) );
6 | }
7 |
8 | int ack(int m, int n)
9 | {
10 | if( m == 0 )
11 | { return n + 1; }
12 | else
13 | {
14 | if( n == 0 )
15 | { return ack(m - 1, 1); }
16 | else { return ack(m - 1, ack(m, n - 1)); }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/test_add.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | return 4+2;
4 | }
5 |
--------------------------------------------------------------------------------
/tests/test_add_var.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 4 + 4;
4 | return 0;
5 | }
6 |
--------------------------------------------------------------------------------
/tests/test_block.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int sum=0;
4 | int x = 4;
5 | {
6 | sum+=x;
7 | int x = 3;
8 | {
9 | sum+=x;
10 | int x = 2;
11 | sum+=x;
12 | }
13 | }
14 | sum+=x;
15 | }
16 |
--------------------------------------------------------------------------------
/tests/test_collapse.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 4;
4 | int b = 2;
5 | int c = 3;
6 | int d = 6;
7 | a = (b+c)*d-a;
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_collapse2.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 4;
4 | int b = 2;
5 | int c = 3;
6 | int d = 6;
7 | a = (b+c)*d-a;
8 | b = a - c + a * a + d / b;
9 | }
10 |
--------------------------------------------------------------------------------
/tests/test_div_zero.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 4/0;
4 | }
5 |
--------------------------------------------------------------------------------
/tests/test_for.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 0;
4 | for (int i=0; i<1000; i++)
5 | {
6 | a += i;
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_for_if.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 0;
4 | for (int i=0; i<1000; i++)
5 | {
6 | if (a > 500)
7 | {
8 | a += i;
9 | }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/tests/test_mod_zero.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 4%0;
4 | }
5 |
--------------------------------------------------------------------------------
/tests/test_ptr.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int s = 1;
4 | int *p = &s;
5 | *p = 3;
6 | }
7 |
--------------------------------------------------------------------------------
/tests/test_return_0.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | return 0;
4 | }
5 |
--------------------------------------------------------------------------------
/tests/test_sum1.c:
--------------------------------------------------------------------------------
1 | int sum(int n1)
2 | {
3 | return n1;
4 | }
5 | int main()
6 | {
7 | return sum(100);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sum2.c:
--------------------------------------------------------------------------------
1 | int sum(int n1, int n2)
2 | {
3 | return n1+n2;
4 | }
5 | int main()
6 | {
7 | return sum(1, 10);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sum3.c:
--------------------------------------------------------------------------------
1 | int sum(int n1, int n2, int n3)
2 | {
3 | return n1+n2+n3;
4 | }
5 | int main()
6 | {
7 | return sum(1, 2, 4);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sum4.c:
--------------------------------------------------------------------------------
1 | int sum(int n1, int n2, int n3, int n4)
2 | {
3 | return n1+n2+n3+n4;
4 | }
5 | int main()
6 | {
7 | return sum(1, 2, 4, 8);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sum5.c:
--------------------------------------------------------------------------------
1 | int sum(int n1, int n2, int n3, int n4, int n5)
2 | {
3 | return n1+n2+n3+n4+n5;
4 | }
5 | int main()
6 | {
7 | return sum(1, 2, 4, 8, 16);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sum6.c:
--------------------------------------------------------------------------------
1 | int sum(int n1, int n2, int n3, int n4, int n5, int n6)
2 | {
3 | return n1+n2+n3+n4+n5+n6;
4 | }
5 | int main()
6 | {
7 | return sum(1, 2, 4, 8, 16, 32);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sum7.c:
--------------------------------------------------------------------------------
1 | int sum(int n1, int n2, int n3, int n4, int n5, int n6, int n7)
2 | {
3 | return n1+n2+n3+n4+n5+n6+n7;
4 | }
5 | int main()
6 | {
7 | return sum(1, 2, 4, 8, 16, 32, 64);
8 | }
9 |
--------------------------------------------------------------------------------
/tests/test_sznurki_alistra.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #define SIZE 1000001
4 | #define SIZE05 500001
5 | int a[ SIZE ];
6 | int sum, n, i, count, length, changed, c;
7 | int main()
8 | {
9 | scanf( "%d", &n );
10 | for( i = 0; i < n; ++i )
11 | {
12 | scanf("%d %d", &length, &count);
13 | a[ length ] = count;
14 | }
15 |
16 | for( i = 1; i < SIZE05 ; ++i )
17 | if( a[ i ] )
18 | {
19 | sum += a[ i ] % 2;
20 | a[ 2*i ] += a[ i ] / 2;
21 | }
22 |
23 | for( i = SIZE05 ; i < SIZE; ++i )
24 | {
25 | if( a[ i ] )
26 | {
27 | for (c = 0; a[ i ]; c++)
28 | {
29 | a[ i ] &= a[ i ] - 1;
30 | sum++;
31 | }
32 | }
33 | }
34 | printf( "%d\n", sum );
35 | }
36 |
--------------------------------------------------------------------------------
/tests/test_sznurki_drx.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int sznurki[1000010];
4 | int main()
5 | {
6 | int d, n_d, m, i, out = 0;
7 | scanf("%d", &m);
8 | for (i=0;i500000)
17 | {
18 | for (; n; out++)
19 | n &= n - 1;
20 | }
21 | else
22 | {
23 | if (n > 1)
24 | {
25 | sznurki[2*i] += n/2;
26 | }
27 | if (n%2 == 1) out++;
28 | }
29 | }
30 | printf("%d\n", out);
31 | }
32 |
--------------------------------------------------------------------------------
/tests/test_variables.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 4;
4 | int b = 3;
5 | int c = 2;
6 | }
7 |
--------------------------------------------------------------------------------
/tests/test_while.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int n = 10, m;
4 | while(n > 0)
5 | {
6 | m = printf("n = %d\n", n);
7 | n--;
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/tests/test_zero.c:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | int a = 0;
4 | }
5 |
--------------------------------------------------------------------------------