blob: 76e4e297a44c4ef4fdb5bd56eb07d2dc293b6faf [file] [log] [blame]
Johnny Chen1605cf62010-09-08 22:54:46 +00001"""
Johnny Chenb51d87d2010-10-07 21:38:28 +00002This LLDB module contains miscellaneous utilities.
Johnny Chen30e48502011-05-13 21:55:30 +00003Some of the test suite takes advantage of the utility functions defined here.
4They can also be useful for general purpose lldb scripting.
Johnny Chen1605cf62010-09-08 22:54:46 +00005"""
6
7import lldb
Johnny Chen0bfa8592011-03-23 20:28:59 +00008import os, sys
Johnny Chened5f04e2010-10-15 23:33:18 +00009import StringIO
Johnny Chen1605cf62010-09-08 22:54:46 +000010
Johnny Chen8a3b54e2011-04-26 23:07:40 +000011# ===================================================
12# Utilities for locating/checking executable programs
13# ===================================================
Johnny Chen979cb5d2011-04-26 22:53:38 +000014
Johnny Chen0bfa8592011-03-23 20:28:59 +000015def is_exe(fpath):
Johnny Chenefdc26a2011-04-26 23:10:15 +000016 """Returns True if fpath is an executable."""
Johnny Chen0bfa8592011-03-23 20:28:59 +000017 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
18
Johnny Chen0bfa8592011-03-23 20:28:59 +000019def which(program):
Johnny Chenefdc26a2011-04-26 23:10:15 +000020 """Returns the full path to a program; None otherwise."""
Johnny Chen0bfa8592011-03-23 20:28:59 +000021 fpath, fname = os.path.split(program)
22 if fpath:
23 if is_exe(program):
24 return program
25 else:
26 for path in os.environ["PATH"].split(os.pathsep):
27 exe_file = os.path.join(path, program)
28 if is_exe(exe_file):
29 return exe_file
30 return None
31
Johnny Chen51ed1b62011-03-03 19:14:00 +000032# ===================================================
33# Disassembly for an SBFunction or an SBSymbol object
34# ===================================================
35
36def disassemble(target, function_or_symbol):
37 """Disassemble the function or symbol given a target.
38
39 It returns the disassembly content in a string object.
40 """
41 buf = StringIO.StringIO()
42 insts = function_or_symbol.GetInstructions(target)
Johnny Chend643c082011-04-28 22:57:01 +000043 for i in insts:
Johnny Chen51ed1b62011-03-03 19:14:00 +000044 print >> buf, i
45 return buf.getvalue()
46
Johnny Chen4c70f282011-03-02 01:36:45 +000047# ==========================================================
48# Integer (byte size 1, 2, 4, and 8) to bytearray conversion
49# ==========================================================
50
51def int_to_bytearray(val, bytesize):
52 """Utility function to convert an integer into a bytearray.
53
Johnny Chend2765fc2011-03-02 20:54:22 +000054 It returns the bytearray in the little endian format. It is easy to get the
55 big endian format, just do ba.reverse() on the returned object.
Johnny Chen4c70f282011-03-02 01:36:45 +000056 """
Johnny Chenf4c0d1d2011-03-30 17:54:35 +000057 import struct
Johnny Chen4c70f282011-03-02 01:36:45 +000058
59 if bytesize == 1:
60 return bytearray([val])
61
62 # Little endian followed by a format character.
63 template = "<%c"
64 if bytesize == 2:
65 fmt = template % 'h'
66 elif bytesize == 4:
67 fmt = template % 'i'
68 elif bytesize == 4:
69 fmt = template % 'q'
70 else:
71 return None
72
Johnny Chenf4c0d1d2011-03-30 17:54:35 +000073 packed = struct.pack(fmt, val)
Johnny Chen4c70f282011-03-02 01:36:45 +000074 return bytearray(map(ord, packed))
75
76def bytearray_to_int(bytes, bytesize):
77 """Utility function to convert a bytearray into an integer.
78
Johnny Chend2765fc2011-03-02 20:54:22 +000079 It interprets the bytearray in the little endian format. For a big endian
80 bytearray, just do ba.reverse() on the object before passing it in.
Johnny Chen4c70f282011-03-02 01:36:45 +000081 """
Johnny Chenf4c0d1d2011-03-30 17:54:35 +000082 import struct
Johnny Chen4c70f282011-03-02 01:36:45 +000083
84 if bytesize == 1:
Filipe Cabecinhas1ee6d9f2012-07-06 16:20:13 +000085 return bytes[0]
Johnny Chen4c70f282011-03-02 01:36:45 +000086
87 # Little endian followed by a format character.
88 template = "<%c"
89 if bytesize == 2:
90 fmt = template % 'h'
91 elif bytesize == 4:
92 fmt = template % 'i'
93 elif bytesize == 4:
94 fmt = template % 'q'
95 else:
96 return None
97
Johnny Chenf4c0d1d2011-03-30 17:54:35 +000098 unpacked = struct.unpack(fmt, str(bytes))
Johnny Chen4c70f282011-03-02 01:36:45 +000099 return unpacked[0]
100
101
Johnny Chenbc1a93e2011-04-23 00:13:34 +0000102# ==============================================================
103# Get the description of an lldb object or None if not available
104# ==============================================================
Johnny Chenbdc36bd2011-04-25 20:23:05 +0000105def get_description(obj, option=None):
106 """Calls lldb_obj.GetDescription() and returns a string, or None.
107
Johnny Chenecd4feb2011-10-14 00:42:25 +0000108 For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra
109 option can be passed in to describe the detailed level of description
110 desired:
Johnny Chenbdc36bd2011-04-25 20:23:05 +0000111 o lldb.eDescriptionLevelBrief
112 o lldb.eDescriptionLevelFull
113 o lldb.eDescriptionLevelVerbose
114 """
115 method = getattr(obj, 'GetDescription')
Johnny Chenbc1a93e2011-04-23 00:13:34 +0000116 if not method:
117 return None
Johnny Chenecd4feb2011-10-14 00:42:25 +0000118 tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint)
Johnny Chen8a0d8972011-09-27 21:27:19 +0000119 if isinstance(obj, tuple):
Johnny Chenbdc36bd2011-04-25 20:23:05 +0000120 if option is None:
121 option = lldb.eDescriptionLevelBrief
122
Johnny Chenbc1a93e2011-04-23 00:13:34 +0000123 stream = lldb.SBStream()
124 if option is None:
125 success = method(stream)
126 else:
127 success = method(stream, option)
128 if not success:
129 return None
130 return stream.GetData()
131
132
Johnny Chen168a61a2010-10-22 21:31:03 +0000133# =================================================
134# Convert some enum value to its string counterpart
135# =================================================
Johnny Chenbe683bc2010-10-07 22:15:58 +0000136
Johnny Chen47342d52011-04-27 17:43:07 +0000137def state_type_to_str(enum):
Johnny Chenbe683bc2010-10-07 22:15:58 +0000138 """Returns the stateType string given an enum."""
139 if enum == lldb.eStateInvalid:
Johnny Chen59b84772010-10-18 15:46:54 +0000140 return "invalid"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000141 elif enum == lldb.eStateUnloaded:
Johnny Chen59b84772010-10-18 15:46:54 +0000142 return "unloaded"
Johnny Chen42da4da2011-03-05 01:20:11 +0000143 elif enum == lldb.eStateConnected:
144 return "connected"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000145 elif enum == lldb.eStateAttaching:
Johnny Chen59b84772010-10-18 15:46:54 +0000146 return "attaching"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000147 elif enum == lldb.eStateLaunching:
Johnny Chen59b84772010-10-18 15:46:54 +0000148 return "launching"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000149 elif enum == lldb.eStateStopped:
Johnny Chen59b84772010-10-18 15:46:54 +0000150 return "stopped"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000151 elif enum == lldb.eStateRunning:
Johnny Chen59b84772010-10-18 15:46:54 +0000152 return "running"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000153 elif enum == lldb.eStateStepping:
Johnny Chen59b84772010-10-18 15:46:54 +0000154 return "stepping"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000155 elif enum == lldb.eStateCrashed:
Johnny Chen59b84772010-10-18 15:46:54 +0000156 return "crashed"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000157 elif enum == lldb.eStateDetached:
Johnny Chen59b84772010-10-18 15:46:54 +0000158 return "detached"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000159 elif enum == lldb.eStateExited:
Johnny Chen59b84772010-10-18 15:46:54 +0000160 return "exited"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000161 elif enum == lldb.eStateSuspended:
Johnny Chen59b84772010-10-18 15:46:54 +0000162 return "suspended"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000163 else:
Johnny Chen42da4da2011-03-05 01:20:11 +0000164 raise Exception("Unknown StateType enum")
Johnny Chenbe683bc2010-10-07 22:15:58 +0000165
Johnny Chen47342d52011-04-27 17:43:07 +0000166def stop_reason_to_str(enum):
Johnny Chenbe683bc2010-10-07 22:15:58 +0000167 """Returns the stopReason string given an enum."""
168 if enum == lldb.eStopReasonInvalid:
Johnny Chen59b84772010-10-18 15:46:54 +0000169 return "invalid"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000170 elif enum == lldb.eStopReasonNone:
Johnny Chen59b84772010-10-18 15:46:54 +0000171 return "none"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000172 elif enum == lldb.eStopReasonTrace:
Johnny Chen59b84772010-10-18 15:46:54 +0000173 return "trace"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000174 elif enum == lldb.eStopReasonBreakpoint:
Johnny Chen59b84772010-10-18 15:46:54 +0000175 return "breakpoint"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000176 elif enum == lldb.eStopReasonWatchpoint:
Johnny Chen59b84772010-10-18 15:46:54 +0000177 return "watchpoint"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000178 elif enum == lldb.eStopReasonSignal:
Johnny Chen59b84772010-10-18 15:46:54 +0000179 return "signal"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000180 elif enum == lldb.eStopReasonException:
Johnny Chen59b84772010-10-18 15:46:54 +0000181 return "exception"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000182 elif enum == lldb.eStopReasonPlanComplete:
Johnny Chen59b84772010-10-18 15:46:54 +0000183 return "plancomplete"
Johnny Chenbe683bc2010-10-07 22:15:58 +0000184 else:
Johnny Chen42da4da2011-03-05 01:20:11 +0000185 raise Exception("Unknown StopReason enum")
Johnny Chenbe683bc2010-10-07 22:15:58 +0000186
Johnny Chene7082612011-09-28 00:51:00 +0000187def symbol_type_to_str(enum):
188 """Returns the symbolType string given an enum."""
189 if enum == lldb.eSymbolTypeInvalid:
190 return "invalid"
191 elif enum == lldb.eSymbolTypeAbsolute:
192 return "absolute"
Johnny Chene7082612011-09-28 00:51:00 +0000193 elif enum == lldb.eSymbolTypeCode:
194 return "code"
195 elif enum == lldb.eSymbolTypeData:
196 return "data"
197 elif enum == lldb.eSymbolTypeTrampoline:
198 return "trampoline"
199 elif enum == lldb.eSymbolTypeRuntime:
200 return "runtime"
201 elif enum == lldb.eSymbolTypeException:
202 return "exception"
203 elif enum == lldb.eSymbolTypeSourceFile:
204 return "sourcefile"
205 elif enum == lldb.eSymbolTypeHeaderFile:
206 return "headerfile"
207 elif enum == lldb.eSymbolTypeObjectFile:
208 return "objectfile"
209 elif enum == lldb.eSymbolTypeCommonBlock:
210 return "commonblock"
211 elif enum == lldb.eSymbolTypeBlock:
212 return "block"
213 elif enum == lldb.eSymbolTypeLocal:
214 return "local"
215 elif enum == lldb.eSymbolTypeParam:
216 return "param"
217 elif enum == lldb.eSymbolTypeVariable:
218 return "variable"
219 elif enum == lldb.eSymbolTypeVariableType:
220 return "variabletype"
221 elif enum == lldb.eSymbolTypeLineEntry:
222 return "lineentry"
223 elif enum == lldb.eSymbolTypeLineHeader:
224 return "lineheader"
225 elif enum == lldb.eSymbolTypeScopeBegin:
226 return "scopebegin"
227 elif enum == lldb.eSymbolTypeScopeEnd:
228 return "scopeend"
229 elif enum == lldb.eSymbolTypeAdditional:
230 return "additional"
231 elif enum == lldb.eSymbolTypeCompiler:
232 return "compiler"
233 elif enum == lldb.eSymbolTypeInstrumentation:
234 return "instrumentation"
235 elif enum == lldb.eSymbolTypeUndefined:
236 return "undefined"
237
Johnny Chen47342d52011-04-27 17:43:07 +0000238def value_type_to_str(enum):
Johnny Chen2c8d1592010-11-03 21:37:58 +0000239 """Returns the valueType string given an enum."""
240 if enum == lldb.eValueTypeInvalid:
241 return "invalid"
242 elif enum == lldb.eValueTypeVariableGlobal:
243 return "global_variable"
244 elif enum == lldb.eValueTypeVariableStatic:
245 return "static_variable"
246 elif enum == lldb.eValueTypeVariableArgument:
247 return "argument_variable"
248 elif enum == lldb.eValueTypeVariableLocal:
249 return "local_variable"
250 elif enum == lldb.eValueTypeRegister:
251 return "register"
252 elif enum == lldb.eValueTypeRegisterSet:
253 return "register_set"
254 elif enum == lldb.eValueTypeConstResult:
255 return "constant_result"
256 else:
Johnny Chen42da4da2011-03-05 01:20:11 +0000257 raise Exception("Unknown ValueType enum")
Johnny Chen2c8d1592010-11-03 21:37:58 +0000258
Johnny Chenbe683bc2010-10-07 22:15:58 +0000259
Johnny Chen168a61a2010-10-22 21:31:03 +0000260# ==================================================
Jim Ingham431d8392012-09-22 00:05:11 +0000261# Utility functions for setting breakpoints
262# ==================================================
263
264def run_break_set_by_file_and_line (test, file_name, line_number, extra_options = None, num_expected_locations = 1, loc_exact=False, module_name=None):
265 """Set a breakpoint by file and line, returning the breakpoint number.
266
267 If extra_options is not None, then we append it to the breakpoint set command.
268
269 If num_expected_locations is -1 we check that we got AT LEAST one location, otherwise we check that num_expected_locations equals the number of locations.
270
271 If loc_exact is true, we check that there is one location, and that location must be at the input file and line number."""
272
273 if file_name == None:
274 command = 'breakpoint set -l %d'%(line_number)
275 else:
276 command = 'breakpoint set -f "%s" -l %d'%(file_name, line_number)
277
Greg Clayton2fcbf6e2013-01-08 00:01:36 +0000278 if module_name:
279 command += " --shlib '%s'" % (module_name)
280
Jim Ingham431d8392012-09-22 00:05:11 +0000281 if extra_options:
282 command += " " + extra_options
283
284 break_results = run_break_set_command (test, command)
285
286 if num_expected_locations == 1 and loc_exact:
287 check_breakpoint_result (test, break_results, num_locations=num_expected_locations, file_name = file_name, line_number = line_number, module_name=module_name)
288 else:
289 check_breakpoint_result (test, break_results, num_locations = num_expected_locations)
290
291 return get_bpno_from_match (break_results)
292
293def run_break_set_by_symbol (test, symbol, extra_options = None, num_expected_locations = -1, sym_exact = False, module_name=None):
294 """Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line.
295
296 If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match."""
297 command = 'breakpoint set -n "%s"'%(symbol)
Greg Clayton2fcbf6e2013-01-08 00:01:36 +0000298
299 if module_name:
300 command += " --shlib '%s'" % (module_name)
301
Jim Ingham431d8392012-09-22 00:05:11 +0000302 if extra_options:
303 command += " " + extra_options
304
305 break_results = run_break_set_command (test, command)
306
307 if num_expected_locations == 1 and sym_exact:
308 check_breakpoint_result (test, break_results, num_locations = num_expected_locations, symbol_name = symbol, module_name=module_name)
309 else:
310 check_breakpoint_result (test, break_results, num_locations = num_expected_locations)
311
312 return get_bpno_from_match (break_results)
313
314def run_break_set_by_selector (test, selector, extra_options = None, num_expected_locations = -1, module_name=None):
315 """Set a breakpoint by selector. Common options are the same as run_break_set_by_file_and_line."""
316
Greg Clayton2fcbf6e2013-01-08 00:01:36 +0000317 command = 'breakpoint set -S "%s"' % (selector)
318
319 if module_name:
320 command += ' --shlib "%s"' % (module_name)
321
Jim Ingham431d8392012-09-22 00:05:11 +0000322 if extra_options:
323 command += " " + extra_options
324
325 break_results = run_break_set_command (test, command)
326
327 if num_expected_locations == 1:
328 check_breakpoint_result (test, break_results, num_locations = num_expected_locations, symbol_name = selector, symbol_match_exact=False, module_name=module_name)
329 else:
330 check_breakpoint_result (test, break_results, num_locations = num_expected_locations)
331
332 return get_bpno_from_match (break_results)
333
334def run_break_set_by_regexp (test, regexp, extra_options=None, num_expected_locations=-1):
335 """Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line."""
336
337 command = 'breakpoint set -r "%s"'%(regexp)
338 if extra_options:
339 command += " " + extra_options
340
341 break_results = run_break_set_command (test, command)
342
343 check_breakpoint_result (test, break_results, num_locations=num_expected_locations)
344
345 return get_bpno_from_match (break_results)
346
347def run_break_set_by_source_regexp (test, regexp, extra_options=None, num_expected_locations=-1):
348 """Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line."""
349 command = 'breakpoint set -p "%s"'%(regexp)
350 if extra_options:
351 command += " " + extra_options
352
353 break_results = run_break_set_command (test, command)
354
355 check_breakpoint_result (test, break_results, num_locations=num_expected_locations)
356
357 return get_bpno_from_match (break_results)
358
359def run_break_set_command (test, command):
360 """Run the command passed in - it must be some break set variant - and analyze the result.
361 Returns a dictionary of information gleaned from the command-line results.
362 Will assert if the breakpoint setting fails altogether.
363
364 Dictionary will contain:
365 bpno - breakpoint of the newly created breakpoint, -1 on error.
366 num_locations - number of locations set for the breakpoint.
367
368 If there is only one location, the dictionary MAY contain:
369 file - source file name
370 line_no - source line number
371 symbol - symbol name
372 inline_symbol - inlined symbol name
373 offset - offset from the original symbol
374 module - module
375 address - address at which the breakpoint was set."""
376
377 patterns = [r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>[0-9]+) locations\.$",
378 r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>no) locations \(pending\)\.",
379 r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>[+\-]{0,1}[^+]+)( \+ (?P<offset>[0-9]+)){0,1}( \[inlined\] (?P<inline_symbol>.*)){0,1} at (?P<file>[^:]+):(?P<line_no>[0-9]+), address = (?P<address>0x[0-9a-fA-F]+)$",
380 r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>.*)( \+ (?P<offset>[0-9]+)){0,1}, address = (?P<address>0x[0-9a-fA-F]+)$"]
381 match_object = test.match (command, patterns)
382 break_results = match_object.groupdict()
Jim Ingham431d8392012-09-22 00:05:11 +0000383
384 # We always insert the breakpoint number, setting it to -1 if we couldn't find it
385 # Also, make sure it gets stored as an integer.
386 if not 'bpno' in break_results:
387 break_results['bpno'] = -1
388 else:
389 break_results['bpno'] = int(break_results['bpno'])
390
391 # We always insert the number of locations
392 # If ONE location is set for the breakpoint, then the output doesn't mention locations, but it has to be 1...
393 # We also make sure it is an integer.
394
395 if not 'num_locations' in break_results:
396 num_locations = 1
397 else:
398 num_locations = break_results['num_locations']
399 if num_locations == 'no':
400 num_locations = 0
401 else:
402 num_locations = int(break_results['num_locations'])
403
404 break_results['num_locations'] = num_locations
405
406 if 'line_no' in break_results:
407 break_results['line_no'] = int(break_results['line_no'])
408
409 return break_results
410
411def get_bpno_from_match (break_results):
412 return int (break_results['bpno'])
413
414def check_breakpoint_result (test, break_results, file_name=None, line_number=-1, symbol_name=None, symbol_match_exact=True, module_name=None, offset=-1, num_locations=-1):
415
416 out_num_locations = break_results['num_locations']
417
Jim Ingham431d8392012-09-22 00:05:11 +0000418 if num_locations == -1:
419 test.assertTrue (out_num_locations > 0, "Expecting one or more locations, got none.")
420 else:
421 test.assertTrue (num_locations == out_num_locations, "Expecting %d locations, got %d."%(num_locations, out_num_locations))
422
423 if file_name:
424 out_file_name = ""
425 if 'file' in break_results:
426 out_file_name = break_results['file']
427 test.assertTrue (file_name == out_file_name, "Breakpoint file name '%s' doesn't match resultant name '%s'."%(file_name, out_file_name))
428
429 if line_number != -1:
430 out_file_line = -1
431 if 'line_no' in break_results:
432 out_line_number = break_results['line_no']
433
434 test.assertTrue (line_number == out_line_number, "Breakpoint line number %s doesn't match resultant line %s."%(line_number, out_line_number))
435
436 if symbol_name:
437 out_symbol_name = ""
438 # Look first for the inlined symbol name, otherwise use the symbol name:
439 if 'inline_symbol' in break_results and break_results['inline_symbol']:
440 out_symbol_name = break_results['inline_symbol']
441 elif 'symbol' in break_results:
442 out_symbol_name = break_results['symbol']
443
444 if symbol_match_exact:
445 test.assertTrue(symbol_name == out_symbol_name, "Symbol name '%s' doesn't match resultant symbol '%s'."%(symbol_name, out_symbol_name))
446 else:
447 test.assertTrue(out_symbol_name.find(symbol_name) != -1, "Symbol name '%s' isn't in resultant symbol '%s'."%(symbol_name, out_symbol_name))
448
449 if module_name:
450 out_nodule_name = None
451 if 'module' in break_results:
452 out_module_name = break_results['module']
453
454 test.assertTrue (module_name.find(out_module_name) != -1, "Symbol module name '%s' isn't in expected module name '%s'."%(out_module_name, module_name))
455
456# ==================================================
Johnny Chen168a61a2010-10-22 21:31:03 +0000457# Utility functions related to Threads and Processes
458# ==================================================
Johnny Chenbe683bc2010-10-07 22:15:58 +0000459
Johnny Chene428d332011-04-25 22:04:05 +0000460def get_stopped_threads(process, reason):
Johnny Chen5aba3f52011-05-26 21:53:05 +0000461 """Returns the thread(s) with the specified stop reason in a list.
462
463 The list can be empty if no such thread exists.
464 """
Johnny Chene428d332011-04-25 22:04:05 +0000465 threads = []
Johnny Chend643c082011-04-28 22:57:01 +0000466 for t in process:
Johnny Chene428d332011-04-25 22:04:05 +0000467 if t.GetStopReason() == reason:
468 threads.append(t)
469 return threads
470
471def get_stopped_thread(process, reason):
472 """A convenience function which returns the first thread with the given stop
473 reason or None.
474
475 Example usages:
476
477 1. Get the stopped thread due to a breakpoint condition
478
479 ...
480 from lldbutil import get_stopped_thread
Johnny Chen3d8ae462011-06-15 22:14:12 +0000481 thread = get_stopped_thread(process, lldb.eStopReasonPlanComplete)
Greg Clayton166b89f2013-03-19 17:59:30 +0000482 self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
Johnny Chene428d332011-04-25 22:04:05 +0000483 ...
484
485 2. Get the thread stopped due to a breakpoint
486
487 ...
488 from lldbutil import get_stopped_thread
Johnny Chen3d8ae462011-06-15 22:14:12 +0000489 thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
Greg Clayton166b89f2013-03-19 17:59:30 +0000490 self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
Johnny Chene428d332011-04-25 22:04:05 +0000491 ...
492
493 """
494 threads = get_stopped_threads(process, reason)
495 if len(threads) == 0:
496 return None
497 return threads[0]
498
Johnny Chen318aaa02011-04-25 23:38:13 +0000499def get_threads_stopped_at_breakpoint (process, bkpt):
500 """ For a stopped process returns the thread stopped at the breakpoint passed in bkpt"""
501 stopped_threads = []
502 threads = []
503
504 stopped_threads = get_stopped_threads (process, lldb.eStopReasonBreakpoint)
505
506 if len(stopped_threads) == 0:
507 return threads
508
509 for thread in stopped_threads:
Johnny Chenec954922011-12-22 20:21:46 +0000510 # Make sure we've hit our breakpoint...
Johnny Chen318aaa02011-04-25 23:38:13 +0000511 break_id = thread.GetStopReasonDataAtIndex (0)
512 if break_id == bkpt.GetID():
513 threads.append(thread)
514
515 return threads
516
517def continue_to_breakpoint (process, bkpt):
518 """ Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None"""
519 process.Continue()
520 if process.GetState() != lldb.eStateStopped:
521 return None
522 else:
523 return get_threads_stopped_at_breakpoint (process, bkpt)
524
Johnny Chen69af39d2011-03-09 23:45:56 +0000525def get_caller_symbol(thread):
526 """
527 Returns the symbol name for the call site of the leaf function.
528 """
529 depth = thread.GetNumFrames()
530 if depth <= 1:
531 return None
532 caller = thread.GetFrameAtIndex(1).GetSymbol()
533 if caller:
534 return caller.GetName()
535 else:
536 return None
537
538
Johnny Chen318aaa02011-04-25 23:38:13 +0000539def get_function_names(thread):
Johnny Chen1605cf62010-09-08 22:54:46 +0000540 """
541 Returns a sequence of function names from the stack frames of this thread.
542 """
543 def GetFuncName(i):
Johnny Chen64abe462011-06-20 00:26:39 +0000544 return thread.GetFrameAtIndex(i).GetFunctionName()
Johnny Chen1605cf62010-09-08 22:54:46 +0000545
546 return map(GetFuncName, range(thread.GetNumFrames()))
547
548
Johnny Chen318aaa02011-04-25 23:38:13 +0000549def get_symbol_names(thread):
Johnny Chenb51d87d2010-10-07 21:38:28 +0000550 """
551 Returns a sequence of symbols for this thread.
552 """
553 def GetSymbol(i):
554 return thread.GetFrameAtIndex(i).GetSymbol().GetName()
555
556 return map(GetSymbol, range(thread.GetNumFrames()))
557
558
Johnny Chen318aaa02011-04-25 23:38:13 +0000559def get_pc_addresses(thread):
Johnny Chenb51d87d2010-10-07 21:38:28 +0000560 """
561 Returns a sequence of pc addresses for this thread.
562 """
563 def GetPCAddress(i):
564 return thread.GetFrameAtIndex(i).GetPCAddress()
565
566 return map(GetPCAddress, range(thread.GetNumFrames()))
567
568
Johnny Chen318aaa02011-04-25 23:38:13 +0000569def get_filenames(thread):
Johnny Chen1605cf62010-09-08 22:54:46 +0000570 """
571 Returns a sequence of file names from the stack frames of this thread.
572 """
573 def GetFilename(i):
574 return thread.GetFrameAtIndex(i).GetLineEntry().GetFileSpec().GetFilename()
575
576 return map(GetFilename, range(thread.GetNumFrames()))
577
578
Johnny Chen318aaa02011-04-25 23:38:13 +0000579def get_line_numbers(thread):
Johnny Chen1605cf62010-09-08 22:54:46 +0000580 """
581 Returns a sequence of line numbers from the stack frames of this thread.
582 """
583 def GetLineNumber(i):
584 return thread.GetFrameAtIndex(i).GetLineEntry().GetLine()
585
586 return map(GetLineNumber, range(thread.GetNumFrames()))
587
588
Johnny Chen318aaa02011-04-25 23:38:13 +0000589def get_module_names(thread):
Johnny Chen1605cf62010-09-08 22:54:46 +0000590 """
591 Returns a sequence of module names from the stack frames of this thread.
592 """
593 def GetModuleName(i):
594 return thread.GetFrameAtIndex(i).GetModule().GetFileSpec().GetFilename()
595
596 return map(GetModuleName, range(thread.GetNumFrames()))
597
598
Johnny Chen318aaa02011-04-25 23:38:13 +0000599def get_stack_frames(thread):
Johnny Chen88866ac2010-09-09 00:55:07 +0000600 """
601 Returns a sequence of stack frames for this thread.
602 """
603 def GetStackFrame(i):
604 return thread.GetFrameAtIndex(i)
605
606 return map(GetStackFrame, range(thread.GetNumFrames()))
607
608
Johnny Chen318aaa02011-04-25 23:38:13 +0000609def print_stacktrace(thread, string_buffer = False):
Johnny Chen1605cf62010-09-08 22:54:46 +0000610 """Prints a simple stack trace of this thread."""
Johnny Chen30425e92010-10-07 18:52:48 +0000611
Johnny Chened5f04e2010-10-15 23:33:18 +0000612 output = StringIO.StringIO() if string_buffer else sys.stdout
Johnny Chenb51d87d2010-10-07 21:38:28 +0000613 target = thread.GetProcess().GetTarget()
614
Johnny Chen1605cf62010-09-08 22:54:46 +0000615 depth = thread.GetNumFrames()
616
Johnny Chen318aaa02011-04-25 23:38:13 +0000617 mods = get_module_names(thread)
618 funcs = get_function_names(thread)
619 symbols = get_symbol_names(thread)
620 files = get_filenames(thread)
621 lines = get_line_numbers(thread)
622 addrs = get_pc_addresses(thread)
Johnny Chen30425e92010-10-07 18:52:48 +0000623
Johnny Chenad5fd402010-10-25 19:13:52 +0000624 if thread.GetStopReason() != lldb.eStopReasonInvalid:
Johnny Chen47342d52011-04-27 17:43:07 +0000625 desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason())
Johnny Chenad5fd402010-10-25 19:13:52 +0000626 else:
627 desc = ""
628 print >> output, "Stack trace for thread id={0:#x} name={1} queue={2} ".format(
629 thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc
Johnny Chen1605cf62010-09-08 22:54:46 +0000630
Johnny Chenb51d87d2010-10-07 21:38:28 +0000631 for i in range(depth):
632 frame = thread.GetFrameAtIndex(i)
633 function = frame.GetFunction()
Johnny Chen1605cf62010-09-08 22:54:46 +0000634
Johnny Chenb51d87d2010-10-07 21:38:28 +0000635 load_addr = addrs[i].GetLoadAddress(target)
Johnny Chen960ce122011-05-25 19:06:18 +0000636 if not function:
Johnny Chenb51d87d2010-10-07 21:38:28 +0000637 file_addr = addrs[i].GetFileAddress()
Johnny Chen49f3d812011-06-16 22:07:48 +0000638 start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress()
639 symbol_offset = file_addr - start_addr
640 print >> output, " frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format(
641 num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset)
Johnny Chenb51d87d2010-10-07 21:38:28 +0000642 else:
Johnny Chen49f3d812011-06-16 22:07:48 +0000643 print >> output, " frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format(
Johnny Chen64abe462011-06-20 00:26:39 +0000644 num=i, addr=load_addr, mod=mods[i],
645 func='%s [inlined]' % funcs[i] if frame.IsInlined() else funcs[i],
Johnny Chen7d4c7fe2011-07-13 22:34:29 +0000646 file=files[i], line=lines[i],
647 args=get_args_as_string(frame, showFuncName=False) if not frame.IsInlined() else '()')
Johnny Chenb51d87d2010-10-07 21:38:28 +0000648
649 if string_buffer:
Johnny Chened5f04e2010-10-15 23:33:18 +0000650 return output.getvalue()
Johnny Chenb51d87d2010-10-07 21:38:28 +0000651
652
Johnny Chen318aaa02011-04-25 23:38:13 +0000653def print_stacktraces(process, string_buffer = False):
Johnny Chenb51d87d2010-10-07 21:38:28 +0000654 """Prints the stack traces of all the threads."""
655
Johnny Chened5f04e2010-10-15 23:33:18 +0000656 output = StringIO.StringIO() if string_buffer else sys.stdout
Johnny Chenb51d87d2010-10-07 21:38:28 +0000657
Greg Clayton0a19a1b2012-02-04 02:27:34 +0000658 print >> output, "Stack traces for " + str(process)
Johnny Chenb51d87d2010-10-07 21:38:28 +0000659
Johnny Chen311b1d62011-05-05 18:50:56 +0000660 for thread in process:
661 print >> output, print_stacktrace(thread, string_buffer=True)
Johnny Chen30425e92010-10-07 18:52:48 +0000662
663 if string_buffer:
Johnny Chened5f04e2010-10-15 23:33:18 +0000664 return output.getvalue()
Johnny Chen185e2c12011-05-08 17:25:27 +0000665
666# ===================================
667# Utility functions related to Frames
668# ===================================
669
Johnny Chenabb3b2d2011-05-12 00:32:41 +0000670def get_parent_frame(frame):
671 """
672 Returns the parent frame of the input frame object; None if not available.
673 """
674 thread = frame.GetThread()
675 parent_found = False
676 for f in thread:
677 if parent_found:
678 return f
679 if f.GetFrameID() == frame.GetFrameID():
680 parent_found = True
681
682 # If we reach here, no parent has been found, return None.
683 return None
684
Johnny Chen49f3d812011-06-16 22:07:48 +0000685def get_args_as_string(frame, showFuncName=True):
Johnny Chenabb3b2d2011-05-12 00:32:41 +0000686 """
687 Returns the args of the input frame object as a string.
688 """
689 # arguments => True
690 # locals => False
691 # statics => False
692 # in_scope_only => True
693 vars = frame.GetVariables(True, False, False, True) # type of SBValueList
694 args = [] # list of strings
695 for var in vars:
696 args.append("(%s)%s=%s" % (var.GetTypeName(),
697 var.GetName(),
Greg Clayton0fb0bcc2011-08-03 22:57:10 +0000698 var.GetValue()))
Johnny Chen960ce122011-05-25 19:06:18 +0000699 if frame.GetFunction():
Johnny Chenbbc18b62011-05-13 00:44:49 +0000700 name = frame.GetFunction().GetName()
Johnny Chen960ce122011-05-25 19:06:18 +0000701 elif frame.GetSymbol():
Johnny Chenbbc18b62011-05-13 00:44:49 +0000702 name = frame.GetSymbol().GetName()
703 else:
704 name = ""
Johnny Chen49f3d812011-06-16 22:07:48 +0000705 if showFuncName:
706 return "%s(%s)" % (name, ", ".join(args))
707 else:
708 return "(%s)" % (", ".join(args))
709
Johnny Chen185e2c12011-05-08 17:25:27 +0000710def print_registers(frame, string_buffer = False):
Johnny Chenb2998772011-05-08 18:55:37 +0000711 """Prints all the register sets of the frame."""
Johnny Chen185e2c12011-05-08 17:25:27 +0000712
713 output = StringIO.StringIO() if string_buffer else sys.stdout
714
Greg Clayton0a19a1b2012-02-04 02:27:34 +0000715 print >> output, "Register sets for " + str(frame)
Johnny Chen185e2c12011-05-08 17:25:27 +0000716
Johnny Chen728255b2011-05-10 19:21:13 +0000717 registerSet = frame.GetRegisters() # Return type of SBValueList.
718 print >> output, "Frame registers (size of register set = %d):" % registerSet.GetSize()
719 for value in registerSet:
Johnny Chen185e2c12011-05-08 17:25:27 +0000720 #print >> output, value
721 print >> output, "%s (number of children = %d):" % (value.GetName(), value.GetNumChildren())
722 for child in value:
Greg Clayton0fb0bcc2011-08-03 22:57:10 +0000723 print >> output, "Name: %s, Value: %s" % (child.GetName(), child.GetValue())
Johnny Chen185e2c12011-05-08 17:25:27 +0000724
725 if string_buffer:
726 return output.getvalue()
Johnny Chen728255b2011-05-10 19:21:13 +0000727
728def get_registers(frame, kind):
729 """Returns the registers given the frame and the kind of registers desired.
730
731 Returns None if there's no such kind.
732 """
733 registerSet = frame.GetRegisters() # Return type of SBValueList.
734 for value in registerSet:
735 if kind.lower() in value.GetName().lower():
736 return value
737
738 return None
739
740def get_GPRs(frame):
741 """Returns the general purpose registers of the frame as an SBValue.
742
Johnny Chenfd1175c2011-05-10 23:01:44 +0000743 The returned SBValue object is iterable. An example:
744 ...
745 from lldbutil import get_GPRs
746 regs = get_GPRs(frame)
747 for reg in regs:
748 print "%s => %s" % (reg.GetName(), reg.GetValue())
749 ...
Johnny Chen728255b2011-05-10 19:21:13 +0000750 """
751 return get_registers(frame, "general purpose")
752
753def get_FPRs(frame):
754 """Returns the floating point registers of the frame as an SBValue.
755
Johnny Chenfd1175c2011-05-10 23:01:44 +0000756 The returned SBValue object is iterable. An example:
757 ...
758 from lldbutil import get_FPRs
759 regs = get_FPRs(frame)
760 for reg in regs:
761 print "%s => %s" % (reg.GetName(), reg.GetValue())
762 ...
Johnny Chen728255b2011-05-10 19:21:13 +0000763 """
764 return get_registers(frame, "floating point")
765
766def get_ESRs(frame):
767 """Returns the exception state registers of the frame as an SBValue.
768
Johnny Chenfd1175c2011-05-10 23:01:44 +0000769 The returned SBValue object is iterable. An example:
770 ...
771 from lldbutil import get_ESRs
772 regs = get_ESRs(frame)
773 for reg in regs:
774 print "%s => %s" % (reg.GetName(), reg.GetValue())
775 ...
Johnny Chen728255b2011-05-10 19:21:13 +0000776 """
777 return get_registers(frame, "exception state")
Johnny Chen084fd892011-07-22 00:47:58 +0000778
Johnny Chen8c062762011-07-22 00:51:54 +0000779# ======================================
780# Utility classes/functions for SBValues
781# ======================================
Johnny Chen084fd892011-07-22 00:47:58 +0000782
783class BasicFormatter(object):
Johnny Chen638ebcf2011-07-22 22:01:35 +0000784 """The basic formatter inspects the value object and prints the value."""
Johnny Chen084fd892011-07-22 00:47:58 +0000785 def format(self, value, buffer=None, indent=0):
786 if not buffer:
787 output = StringIO.StringIO()
788 else:
789 output = buffer
Johnny Chen638ebcf2011-07-22 22:01:35 +0000790 # If there is a summary, it suffices.
791 val = value.GetSummary()
792 # Otherwise, get the value.
793 if val == None:
794 val = value.GetValue()
795 if val == None and value.GetNumChildren() > 0:
796 val = "%s (location)" % value.GetLocation()
797 print >> output, "{indentation}({type}) {name} = {value}".format(
Johnny Chen084fd892011-07-22 00:47:58 +0000798 indentation = ' ' * indent,
799 type = value.GetTypeName(),
800 name = value.GetName(),
Johnny Chen638ebcf2011-07-22 22:01:35 +0000801 value = val)
Johnny Chen084fd892011-07-22 00:47:58 +0000802 return output.getvalue()
803
804class ChildVisitingFormatter(BasicFormatter):
Johnny Chen638ebcf2011-07-22 22:01:35 +0000805 """The child visiting formatter prints the value and its immediate children.
806
807 The constructor takes a keyword arg: indent_child, which defaults to 2.
808 """
809 def __init__(self, indent_child=2):
810 """Default indentation of 2 SPC's for the children."""
811 self.cindent = indent_child
Johnny Chen084fd892011-07-22 00:47:58 +0000812 def format(self, value, buffer=None):
813 if not buffer:
814 output = StringIO.StringIO()
815 else:
816 output = buffer
817
818 BasicFormatter.format(self, value, buffer=output)
819 for child in value:
Johnny Chen638ebcf2011-07-22 22:01:35 +0000820 BasicFormatter.format(self, child, buffer=output, indent=self.cindent)
821
822 return output.getvalue()
823
824class RecursiveDecentFormatter(BasicFormatter):
825 """The recursive decent formatter prints the value and the decendents.
826
827 The constructor takes two keyword args: indent_level, which defaults to 0,
828 and indent_child, which defaults to 2. The current indentation level is
829 determined by indent_level, while the immediate children has an additional
830 indentation by inden_child.
831 """
832 def __init__(self, indent_level=0, indent_child=2):
833 self.lindent = indent_level
834 self.cindent = indent_child
835 def format(self, value, buffer=None):
836 if not buffer:
837 output = StringIO.StringIO()
838 else:
839 output = buffer
840
841 BasicFormatter.format(self, value, buffer=output, indent=self.lindent)
842 new_indent = self.lindent + self.cindent
843 for child in value:
844 if child.GetSummary() != None:
845 BasicFormatter.format(self, child, buffer=output, indent=new_indent)
846 else:
847 if child.GetNumChildren() > 0:
848 rdf = RecursiveDecentFormatter(indent_level=new_indent)
849 rdf.format(child, buffer=output)
850 else:
851 BasicFormatter.format(self, child, buffer=output, indent=new_indent)
Johnny Chen084fd892011-07-22 00:47:58 +0000852
853 return output.getvalue()