-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmixed.py
More file actions
245 lines (213 loc) · 8.45 KB
/
Copy pathmixed.py
File metadata and controls
245 lines (213 loc) · 8.45 KB
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
#!/usr/bin/python
# ---------------------------------------------------------------------
# Be sure to add the python path that points to the LLDB shared library.
#
# # To use this in the embedded python interpreter using "lldb" just
# import it with the full path using the "command script import"
# command
# (lldb) command script import /path/to/step.py
# ---------------------------------------------------------------------
import inspect
import lldb
import optparse
import os
import shlex
import io
import sys
import zipfile
def run_lldb_command(debugger, command):
'''Returns the command status and the command output as a tuple.'''
return_obj = lldb.SBCommandReturnObject()
status = debugger.GetCommandInterpreter().HandleCommand(
command, return_obj, False)
output = return_obj.GetOutput()
error = return_obj.GetError()
if output:
if error:
return (status, output + "\n" + error)
else:
return (status, output)
return (status, error)
def dump_frame_disassembly(frame, options, f):
function = frame.GetFunction()
if not function.IsValid():
f.write('no function for "%s"\n' % (frame.GetFunctionName()))
return
target = frame.GetThread().GetProcess().GetTarget()
dump_disassembly(target, frame, function, options, f)
def dump_disassembly(target, frame, function, options, f):
func_name = function.GetName()
insts = function.GetInstructions(target)
start_idx = 0
end_idx = insts.GetSize()
pc_index = -1
if options.pc:
pc_addr = frame.GetPCAddress()
for (i, inst) in enumerate(insts):
if inst.GetAddress() == pc_addr:
pc_index = i
break
if pc_index == -1:
f.write("error: couldn't locate the PC in instructions.")
return
if pc_index > options.inst_before:
start_idx = pc_index - options.inst_before
if pc_index + options.inst_after < end_idx:
end_idx = pc_index + options.inst_after
prev_name = ''
prev_file = ''
prev_line = 0
for i in range(start_idx, end_idx):
inst = insts.GetInstructionAtIndex(i)
inst_addr = inst.GetAddress()
line_entry = inst_addr.GetLineEntry()
file = line_entry.GetFileSpec().fullpath
line = line_entry.GetLine()
block = inst_addr.GetBlock()
inline_depth = 0
inline_block = block.GetContainingInlinedBlock()
if inline_block.IsValid():
name = inline_block.GetInlinedName()
b = inline_block
while b.IsValid():
inline_depth += 1
inline_parent_block = b.GetParent().GetContainingInlinedBlock()
if inline_parent_block.IsValid():
b = inline_parent_block
else:
break
else:
name = func_name
indent = ' ' * inline_depth
addr = inst_addr.GetLoadAddress(target)
if addr == lldb.LLDB_INVALID_ADDRESS:
addr = inst_addr.GetFileAddress()
disassembly = '%#x: %s %s' % (addr, inst.GetMnemonic(target),
inst.GetOperands(target))
comment = inst.GetComment(target)
if comment:
if len(disassembly) < 72:
spaces = ' ' * (72 - len(disassembly))
disassembly = disassembly + spaces + '# ' + comment
# Print function name, file and line if anything changed
if prev_name != name or prev_file != file or prev_line != line:
if file or line:
f.write('%s%s @ %s:%i\n' % (indent, name, file, line))
else:
f.write('%s%s\n' % (indent, name))
# Print disassembly
if pc_index >= 0:
if pc_index == i:
f.write('-> ')
else:
f.write(' ')
f.write('%s%s\n' % (indent, disassembly))
prev_file = file
prev_line = line
prev_name = name
class Command:
program = 'mixed'
description = ('Simplified output for mixed mode disassembly.')
@classmethod
def register_lldb_command(cls, debugger, module_name):
parser = cls.create_options()
cls.__doc__ = parser.format_help()
# Add any commands contained in this module to LLDB
command = 'command script add -c %s.%s %s' % (module_name,
cls.__name__,
cls.program)
debugger.HandleCommand(command)
print('The "{0}" command has been installed, type "help {0}" or "{0} '
'--help" for detailed help.'.format(cls.program))
@classmethod
def create_options(cls):
usage = "usage: %prog [options]"
# Pass add_help_option = False, since this keeps the command in line
# with lldb commands, and we wire up "help command" to work by
# providing the long & short help methods below.
parser = optparse.OptionParser(
description=cls.description,
prog=cls.program,
usage=usage,
add_help_option=True)
parser.add_option(
'--name',
type='string',
action='append',
dest='names',
help='Specify one or more function names to disassemble.')
parser.add_option(
'--pc',
action='store_true',
dest='pc',
default=False,
help='Disassembly around the PC.')
parser.add_option(
'-B', '--inst-before',
type='int',
dest='inst_before',
default=0,
help=('The number of context instructions to print before a '
'match. Default is 0.'))
parser.add_option(
'-A', '--inst-after',
type='int',
dest='inst_after',
default=4,
help=('The number of context instructions to print after a '
'match. Default is 4.'))
return parser
def get_short_help(self):
return self.description
def get_long_help(self):
return self.help_string
def __init__(self, debugger, unused):
self.parser = self.create_options()
self.help_string = self.parser.format_help()
def __call__(self, debugger, command, exe_ctx, result):
# Use the Shell Lexer to properly parse up command options just like a
# shell would
command_args = shlex.split(command)
try:
(options, args) = self.parser.parse_args(command_args)
except:
# if you don't handle exceptions, passing an incorrect argument to
# the OptionParser will cause LLDB to exit (courtesy of OptParse
# dealing with argument errors by throwing SystemExit)
result.SetError("option parsing failed")
return
target = exe_ctx.GetTarget()
if options.names:
for name in options.names:
sym_ctxs = target.FindFunctions(name)
if sym_ctxs.GetSize() == 0:
result.write('error: no functions found named "%s"\n' %
(name))
continue
for sym_ctx in sym_ctxs:
function = sym_ctx.GetFunction()
if function.IsValid():
dump_disassembly(target, function, result)
result.write('\n')
continue
symbol = sym_ctx.GetSymbol()
if symbol.IsValid():
dump_disassembly(target, symbol, result)
result.write('\n')
continue
result.write('error: no valid function or symbol\n')
else:
frame = exe_ctx.GetFrame()
if not frame.IsValid():
result.SetError("invalid frame")
return
dump_frame_disassembly(frame, options, result)
def __lldb_init_module(debugger, dict):
# Register all classes that have a register_lldb_command method
for _name, cls in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(cls) and callable(getattr(cls,
"register_lldb_command",
None)):
cls.register_lldb_command(debugger, __name__)
if __name__ == '__main__':
command = Command()