forked from patois/genmc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenmc.py
384 lines (330 loc) · 12.9 KB
/
genmc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# genmc - Display Hex-Rays Microcode
#
# Requires IDA and decompiler(s) >= 7.3
#
# Based on code/ideas from:
# - vds13.py from Hexrays SDK
# - https://github.com/RolfRolles/HexRaysDeob
# - https://github.com/NeatMonster/MCExplorer
__author__ = "Dennis Elser"
# -----------------------------------------------------------------------------
import os, shutil, errno
import ida_idaapi
import ida_bytes
import ida_range
import ida_kernwin as kw
import ida_hexrays as hr
import ida_funcs
import ida_diskio
import ida_ida
import ida_graph
import ida_lines
PLUGIN_NAME = "genmc"
# -----------------------------------------------------------------------------
def get_mcode_name(mcode):
"""returns the name of the mcode_t passed in parameter."""
for x in dir(hr):
if x.startswith('m_'):
if mcode == getattr(hr, x):
return x
return None
# -----------------------------------------------------------------------------
def get_mopt_name(mopt):
"""returns the name of the mopt_t passed in parameter."""
for x in dir(hr):
if x.startswith('mop_'):
if mopt == getattr(hr, x):
return x
return None
# -----------------------------------------------------------------------------
def is_plugin():
"""returns True if this script is executed from within an IDA plugins
directory, False otherwise."""
return "__plugins__" in __name__
# -----------------------------------------------------------------------------
def get_target_dir():
"""returns destination path for plugin installation."""
base = os.path.join(
ida_diskio.get_user_idadir(),
"plugins")
return os.path.join(base, PLUGIN_NAME+".py")
# -----------------------------------------------------------------------------
def is_installed():
"""checks whether script is present in designated plugins directory."""
return os.path.isfile(get_target_dir())
# -----------------------------------------------------------------------------
SELF = __file__
def install_plugin():
"""Installs script to IDA userdir as a plugin."""
if is_plugin():
kw.msg("Command not available. Plugin already installed.\n")
return False
src = SELF
if is_installed():
btnid = kw.ask_yn(kw.ASKBTN_NO, "File exists. Replace?")
if btnid is not kw.ASKBTN_YES:
return False
dst = get_target_dir()
usrdir = os.path.dirname(dst)
kw.msg("Copying script from \"%s\" to \"%s\" ..." % (src, usrdir))
if not os.path.exists(usrdir):
try:
os.path.makedirs(usrdir)
except OSError as e:
if e.errno != errno.EEXIST:
kw.msg("failed (mkdir)!\n")
return False
try:
shutil.copy(src, dst)
except:
kw.msg("failed (copy)!\n")
return False
kw.msg("done!\nPlease restart this IDA instance now.\n")
return True
# -----------------------------------------------------------------------------
def is_ida_version(requested):
"""Checks minimum required IDA version."""
rv = requested.split(".")
kv = kw.get_kernel_version().split(".")
count = min(len(rv), len(kv))
if not count:
return False
for i in xrange(count):
if int(kv[i]) < int(rv[i]):
return False
return True
# -----------------------------------------------------------------------------
def is_compatible():
"""Checks whether script is compatible with current IDA and
decompiler versions."""
min_ida_ver = "7.3"
return is_ida_version(min_ida_ver) and hr.init_hexrays_plugin()
# -----------------------------------------------------------------------------
class printer_t(hr.vd_printer_t):
"""Converts microcode output to an array of strings."""
def __init__(self, *args):
hr.vd_printer_t.__init__(self)
self.mc = []
def get_mc(self):
return self.mc
def _print(self, indent, line):
self.mc.append(line)
return 1
# -----------------------------------------------------------------------------
class microcode_insnviewer_t(ida_graph.GraphViewer):
"""Displays the graph view of Hex-Rays microcode."""
def __init__(self, mba, mmat_name, fn_name, block, serial):
title = "Microinstruction: %s - %d.%d (%s)" % (fn_name, block, serial, mmat_name)
ida_graph.GraphViewer.__init__(self, title, True)
self.mblock = mba.get_mblock(block)
self.minsn = self.get_minsn(serial)
def get_minsn(self, serial):
curr = self.mblock.head
for i in range(serial):
curr = curr.next
return curr
def _insert_mop(self, mop, parent):
if mop.t == 0:
return -1
text = get_mopt_name(mop.t) + '\n' + mop._print()
node_id = self.AddNode(text)
self.AddEdge(parent, node_id)
if mop.t == hr.mop_d: # result of another instruction
dst_id = self._insert_minsn(mop.d)
self.AddEdge(node_id, dst_id)
elif mop.t == hr.mop_f: # list of arguments
for arg in mop.f.args:
self._insert_mop(arg, node_id)
elif mop.t == hr.mop_a: # mop_addr_t: address of operand
self._insert_mop(mop.a, node_id)
elif mop.t == hr.mop_p: # operand pair
self._insert_mop(mop.pair.lop, node_id)
self._insert_mop(mop.pair.hop, node_id)
return node_id
def _insert_minsn(self, minsn):
text = get_mcode_name(minsn.opcode) + '\n' + minsn._print()
node_id = self.AddNode(text)
self._insert_mop(minsn.l, node_id)
self._insert_mop(minsn.r, node_id)
self._insert_mop(minsn.d, node_id)
return node_id
def OnRefresh(self):
self.Clear()
self._insert_minsn(self.minsn)
return True
def OnGetText(self, node_id):
return self._nodes[node_id]
# -----------------------------------------------------------------------------
class microcode_graphviewer_t(ida_graph.GraphViewer):
"""Displays the graph view of Hex-Rays microcode."""
def __init__(self, mba, title):
title = "Microcode graph: %s" % title
ida_graph.GraphViewer.__init__(self, title, True)
self._mba = mba
self._mba.set_mba_flags(hr.MBA_SHORT)
if mba.maturity == hr.MMAT_GENERATED or mba.maturity == hr.MMAT_PREOPTIMIZED:
mba.build_graph()
def OnRefresh(self):
self.Clear()
qty = self._mba.qty
for src in range(qty):
self.AddNode(src)
for src in range(qty):
mblock = self._mba.get_mblock(src)
for dest in mblock.succset:
self.AddEdge(src, dest)
return True
def OnGetText(self, node):
mblock = self._mba.get_mblock(node)
vp = hr.qstring_printer_t(None, True)
mblock._print(vp)
return vp.s
# -----------------------------------------------------------------------------
class microcode_viewer_t(kw.simplecustviewer_t):
"""Creates a widget that displays Hex-Rays microcode."""
def Create(self, mba, title, mmat_name, fn_name, lines = []):
self.title = "Microcode: %s" % title
self._mba = mba
self.mmat_name = mmat_name
self.fn_name = fn_name
if not kw.simplecustviewer_t.Create(self, self.title):
return False
for line in lines:
self.AddLine(line)
return True
def OnKeydown(self, vkey, shift):
if shift == 0 and vkey == ord("G"):
microcode_graphviewer_t(self._mba, self.title).Show()
return True
elif shift == 0 and vkey == ord("I"):
widget = self.GetWidget()
line = kw.get_custom_viewer_curline(widget, False)
line = ida_lines.tag_remove(line)
if '.' in line:
block, serial = line.split('.')[:2]
serial = serial.strip().split(' ')[0]
microcode_insnviewer_t(self._mba, self.mmat_name, self.fn_name, int(block), int(serial)).Show()
return True
return False
# -----------------------------------------------------------------------------
def ask_desired_maturity():
"""Displays a dialog which lets the user choose a maturity level
of the microcode to generate."""
maturity_levels = [
["MMAT_GENERATED", hr.MMAT_GENERATED],
["MMAT_PREOPTIMIZED", hr.MMAT_PREOPTIMIZED],
["MMAT_LOCOPT", hr.MMAT_LOCOPT],
["MMAT_CALLS", hr.MMAT_CALLS],
["MMAT_GLBOPT1", hr.MMAT_GLBOPT1],
["MMAT_GLBOPT2", hr.MMAT_GLBOPT2],
["MMAT_GLBOPT3", hr.MMAT_GLBOPT3],
["MMAT_LVARS", hr.MMAT_LVARS]]
class MaturityForm(kw.Form):
def __init__(self):
self.title = "Display Microcode"
form = ("STARTITEM {id:mat_lvl}\n"
"%s\n"
" \n"
"<Maturity level:{mat_lvl}>\n\n"
"<##Options##Output includes comments:{flags_short}>{chkgroup_flags}>\n\n" %
self.title)
dropdown_ctl = kw.Form.DropdownListControl(
[text for text, _ in maturity_levels])
chk_ctl = kw.Form.ChkGroupControl(("flags_short",))
controls = {"mat_lvl": dropdown_ctl,
"chkgroup_flags": chk_ctl}
kw.Form.__init__(self, form, controls)
form = MaturityForm()
form, args = form.Compile()
form.flags_short.checked = True
ok = form.Execute()
mmat = None
text = None
flags = 0
if ok == 1:
text, mmat = maturity_levels[form.mat_lvl.value]
flags |= 0 if form.flags_short.checked else hr.MBA_SHORT
form.Free()
return (text, mmat, flags)
# -----------------------------------------------------------------------------
def show_microcode():
"""Generates and displays microcode for an address range.
An address range can be a selection of code or that of
the current function."""
sel, sea, eea = kw.read_range_selection(None)
pfn = ida_funcs.get_func(kw.get_screen_ea())
if not sel and not pfn:
return (False, "Position cursor within a function or select range")
fn_name = ida_funcs.get_func_name(pfn.start_ea)
if not sel and pfn:
sea = pfn.start_ea
eea = pfn.end_ea
addr_fmt = "%016x" if ida_ida.inf_is_64bit() else "%08x"
F = ida_bytes.get_flags(sea)
if not ida_bytes.is_code(F):
return (False, "The selected range must start with an instruction")
text, mmat, mba_flags = ask_desired_maturity()
if text is None and mmat is None:
return (True, "Cancelled")
hf = hr.hexrays_failure_t()
mbr = hr.mba_ranges_t()
mbr.ranges.push_back(ida_range.range_t(sea, eea))
ml = hr.mlist_t()
mba = hr.gen_microcode(mbr, hf, ml, hr.DECOMP_WARNINGS, mmat)
if not mba:
return (False, "0x%s: %s" % (addr_fmt % hf.errea, hf.str))
vp = printer_t()
mba.set_mba_flags(mba_flags)
mba._print(vp)
mcv = microcode_viewer_t()
if not mcv.Create(mba, "0x%s-0x%s (%s)" % (addr_fmt % sea, addr_fmt % eea, text), text, fn_name, vp.get_mc()):
return (False, "Error creating viewer")
mcv.Show()
return (True,
"Successfully generated microcode for 0x%s..0x%s" % (addr_fmt % sea, addr_fmt % eea))
# -----------------------------------------------------------------------------
def create_mc_widget():
"""Checks minimum requirements for the script/plugin to be able to run.
Displays microcode or in case of failure, displays error message.
This function acts as the main entry point that is invoked if the
code is run as a script or as a plugin."""
if not is_compatible():
kw.msg("%s: Unsupported IDA / Hex-rays version\n" % (PLUGIN_NAME))
return False
success, message = show_microcode()
output = kw.msg if success else kw.warning
output("%s: %s\n" % (PLUGIN_NAME, message))
return success
# -----------------------------------------------------------------------------
class genmc(ida_idaapi.plugin_t):
"""Class that is required for the code to be recognized as
a plugin by IDA."""
flags = 0
comment = "Display microcode"
help = comment
wanted_name = PLUGIN_NAME
wanted_hotkey = "Ctrl-Shift-M"
def init(self):
return (ida_idaapi.PLUGIN_OK if
is_compatible() else ida_idaapi.PLUGIN_SKIP)
def run(self, arg):
create_mc_widget()
def term(self):
pass
# -----------------------------------------------------------------------------
def PLUGIN_ENTRY():
"""Entry point of this code if launched as a plugin."""
return genmc()
# -----------------------------------------------------------------------------
def SCRIPT_ENTRY():
"""Entry point of this code if launched as a script."""
if not is_plugin():
if not is_installed():
kw.msg(("%s: Available commands:\n"
"[+] \"install_plugin()\" - install script to ida_userdir/plugins\n") % (
PLUGIN_NAME))
create_mc_widget()
return True
return False
# -----------------------------------------------------------------------------
SCRIPT_ENTRY()