blob: 2872d96e2c67d68f9893aa2be91849de5d0d44da [file] [log] [blame]
Greg Clayton3d39f832012-04-03 21:35:43 +00001#!/usr/bin/python
2
3#----------------------------------------------------------------------
4# Be sure to add the python path that points to the LLDB shared library.
5#
6# To use this in the embedded python interpreter using "lldb":
7#
8# cd /path/containing/crashlog.py
9# lldb
10# (lldb) script import crashlog
11# "crashlog" command installed, type "crashlog --help" for detailed help
12# (lldb) crashlog ~/Library/Logs/DiagnosticReports/a.crash
13#
14# The benefit of running the crashlog command inside lldb in the
15# embedded python interpreter is when the command completes, there
16# will be a target with all of the files loaded at the locations
17# described in the crash log. Only the files that have stack frames
18# in the backtrace will be loaded unless the "--load-all" option
19# has been specified. This allows users to explore the program in the
20# state it was in right at crash time.
21#
22# On MacOSX csh, tcsh:
23# ( setenv PYTHONPATH /path/to/LLDB.framework/Resources/Python ; ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash )
24#
25# On MacOSX sh, bash:
26# PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash
27#----------------------------------------------------------------------
28
29import lldb
30import commands
31import optparse
32import os
33import plistlib
34import re
35import shlex
36import sys
37import time
38import uuid
39
40class Address:
41 """Class that represents an address that will be symbolicated"""
42 def __init__(self, target, load_addr):
43 self.target = target
44 self.load_addr = load_addr # The load address that this object represents
45 self.so_addr = None # the resolved lldb.SBAddress (if any), named so_addr for section/offset address
46 self.sym_ctx = None # The cached symbol context for this address
47 self.description = None # Any original textual description of this address to be used as a backup in case symbolication fails
48 self.symbolication = None # The cached symbolicated string that describes this address
49 self.inlined = False
50 def __str__(self):
51 s = "%#16.16x" % (self.load_addr)
52 if self.symbolication:
53 s += " %s" % (self.symbolication)
54 elif self.description:
55 s += " %s" % (self.description)
56 elif self.so_addr:
57 s += " %s" % (self.so_addr)
58 return s
59
60 def resolve_addr(self):
61 if self.so_addr == None:
62 self.so_addr = self.target.ResolveLoadAddress (self.load_addr)
63 return self.so_addr
64
65 def is_inlined(self):
66 return self.inlined
67
68 def get_symbol_context(self):
69 if self.sym_ctx == None:
70 sb_addr = self.resolve_addr()
71 if sb_addr:
72 self.sym_ctx = self.target.ResolveSymbolContextForAddress (sb_addr, lldb.eSymbolContextEverything)
73 else:
74 self.sym_ctx = lldb.SBSymbolContext()
75 return self.sym_ctx
76
77 def get_instructions(self):
78 sym_ctx = self.get_symbol_context()
79 if sym_ctx:
80 function = sym_ctx.GetFunction()
81 if function:
82 return function.GetInstructions(self.target)
83 return sym_ctx.GetSymbol().GetInstructions(self.target)
84 return None
85
86 def symbolicate(self):
87 if self.symbolication == None:
88 self.symbolication = ''
89 self.inlined = False
90 sym_ctx = self.get_symbol_context()
91 if sym_ctx:
92 module = sym_ctx.GetModule()
93 if module:
94 self.symbolication += module.GetFileSpec().GetFilename() + '`'
95 function_start_load_addr = -1
96 function = sym_ctx.GetFunction()
97 block = sym_ctx.GetBlock()
98 line_entry = sym_ctx.GetLineEntry()
99 symbol = sym_ctx.GetSymbol()
100 inlined_block = block.GetContainingInlinedBlock();
101 if function:
102 self.symbolication += function.GetName()
103
104 if inlined_block:
105 self.inlined = True
106 self.symbolication += ' [inlined] ' + inlined_block.GetInlinedName();
107 block_range_idx = inlined_block.GetRangeIndexForBlockAddress (self.so_addr)
108 if block_range_idx < lldb.UINT32_MAX:
109 block_range_start_addr = inlined_block.GetRangeStartAddress (block_range_idx)
110 function_start_load_addr = block_range_start_addr.GetLoadAddress (self.target)
111 if function_start_load_addr == -1:
112 function_start_load_addr = function.GetStartAddress().GetLoadAddress (self.target)
113 elif symbol:
114 self.symbolication += symbol.GetName()
115 function_start_load_addr = symbol.GetStartAddress().GetLoadAddress (self.target)
116 else:
117 self.symbolication = ''
118 return False
119
120 # Dump the offset from the current function or symbol if it is non zero
121 function_offset = self.load_addr - function_start_load_addr
122 if function_offset > 0:
123 self.symbolication += " + %u" % (function_offset)
124 elif function_offset < 0:
125 self.symbolication += " %i (invalid negative offset, file a bug) " % function_offset
126
127 # Print out any line information if any is available
128 if line_entry.GetFileSpec():
129 self.symbolication += ' at %s' % line_entry.GetFileSpec().GetFilename()
130 self.symbolication += ':%u' % line_entry.GetLine ()
131 column = line_entry.GetColumn()
132 if column > 0:
133 self.symbolication += ':%u' % column
134 return True
135 return False
136
137class Section:
138 """Class that represents an load address range"""
139 sect_info_regex = re.compile('(?P<name>[^=]+)=(?P<range>.*)')
140 addr_regex = re.compile('^\s*(?P<start>0x[0-9A-Fa-f]+)\s*$')
141 range_regex = re.compile('^\s*(?P<start>0x[0-9A-Fa-f]+)\s*(?P<op>[-+])\s*(?P<end>0x[0-9A-Fa-f]+)\s*$')
142
143 def __init__(self, start_addr = None, end_addr = None, name = None):
144 self.start_addr = start_addr
145 self.end_addr = end_addr
146 self.name = name
147
148 def contains(self, addr):
149 return self.start_addr <= addr and addr < self.end_addr;
150
151 def set_from_string(self, s):
152 match = self.sect_info_regex.match (s)
153 if match:
154 self.name = match.group('name')
155 range_str = match.group('range')
156 addr_match = self.addr_regex.match(range_str)
157 if addr_match:
158 self.start_addr = int(addr_match.group('start'), 16)
159 self.end_addr = None
160 return True
161
162 range_match = self.range_regex.match(range_str)
163 if range_match:
164 self.start_addr = int(range_match.group('start'), 16)
165 self.end_addr = int(range_match.group('end'), 16)
166 op = range_match.group('op')
167 if op == '+':
168 self.end_addr += self.start_addr
169 return True
170 print 'error: invalid section info string "%s"' % s
171 print 'Valid section info formats are:'
172 print 'Format Example Description'
173 print '--------------------- -----------------------------------------------'
174 print '<name>=<base> __TEXT=0x123000 Section from base address only'
175 print '<name>=<base>-<end> __TEXT=0x123000-0x124000 Section from base address and end address'
176 print '<name>=<base>+<size> __TEXT=0x123000+0x1000 Section from base address and size'
177 return False
178
179 def __str__(self):
180 if self.name:
181 if self.end_addr != None:
182 if self.start_addr != None:
183 return "%s=[0x%16.16x - 0x%16.16x)" % (self.name, self.start_addr, self.end_addr)
184 else:
185 if self.start_addr != None:
186 return "%s=0x%16.16x" % (self.name, self.start_addr)
187 return self.name
188 return "<invalid>"
189
190class Image:
191 """A class that represents an executable image and any associated data"""
192
193 def __init__(self, path, uuid = None):
194 self.path = path
195 self.resolved_path = None
196 self.uuid = uuid
197 self.section_infos = list()
198 self.identifier = None
199 self.version = None
200 self.arch = None
201 self.module = None
202 self.symfile = None
203 self.slide = None
204
205 def dump(self, prefix):
206 print "%s%s" % (prefix, self)
207
208 def __str__(self):
Greg Clayton9d010422012-05-04 20:44:14 +0000209 s = "%s %s %s" % (self.get_uuid(), self.version, self.get_resolved_path())
Greg Clayton3d39f832012-04-03 21:35:43 +0000210 for section_info in self.section_infos:
211 s += ", %s" % (section_info)
212 if self.slide != None:
213 s += ', slide = 0x%16.16x' % self.slide
214 return s
215
216 def add_section(self, section):
217 #print "added '%s' to '%s'" % (section, self.path)
218 self.section_infos.append (section)
219
220 def get_section_containing_load_addr (self, load_addr):
221 for section_info in self.section_infos:
222 if section_info.contains(load_addr):
223 return section_info
224 return None
225
226 def get_resolved_path(self):
227 if self.resolved_path:
228 return self.resolved_path
229 elif self.path:
230 return self.path
231 return None
232
233 def get_resolved_path_basename(self):
234 path = self.get_resolved_path()
235 if path:
236 return os.path.basename(path)
237 return None
238
239 def symfile_basename(self):
240 if self.symfile:
241 return os.path.basename(self.symfile)
242 return None
243
244 def has_section_load_info(self):
245 return self.section_infos or self.slide != None
246
247 def load_module(self, target):
248 # Load this module into "target" using the section infos to
249 # set the section load addresses
250 if self.has_section_load_info():
251 if target:
252 if self.module:
253 if self.section_infos:
254 num_sections_loaded = 0
255 for section_info in self.section_infos:
256 if section_info.name:
257 section = self.module.FindSection (section_info.name)
258 if section:
259 error = target.SetSectionLoadAddress (section, section_info.start_addr)
260 if error.Success():
261 num_sections_loaded += 1
262 else:
263 return 'error: %s' % error.GetCString()
264 else:
265 return 'error: unable to find the section named "%s"' % section_info.name
266 else:
267 return 'error: unable to find "%s" section in "%s"' % (range.name, self.get_resolved_path())
268 if num_sections_loaded == 0:
269 return 'error: no sections were successfully loaded'
270 else:
271 err = target.SetModuleLoadAddress(self.module, self.slide)
272 if err.Fail():
273 return err.GetCString()
274 return None
275 else:
276 return 'error: invalid module'
277 else:
278 return 'error: invalid target'
279 else:
280 return 'error: no section infos'
281
282 def add_module(self, target):
283 '''Add the Image described in this object to "target" and load the sections if "load" is True.'''
284 if target:
Greg Clayton3d39f832012-04-03 21:35:43 +0000285 # Try and find using UUID only first so that paths need not match up
Greg Claytond8056e22012-05-11 00:30:14 +0000286 uuid_str = self.get_normalized_uuid_string()
287 if uuid_str:
288 self.module = target.AddModule (None, None, uuid_str)
Greg Clayton3d39f832012-04-03 21:35:43 +0000289 if not self.module:
Greg Clayton4c983c82012-04-20 23:31:27 +0000290 self.locate_module_and_debug_symbols ()
291 resolved_path = self.get_resolved_path()
Greg Claytond8056e22012-05-11 00:30:14 +0000292 self.module = target.AddModule (resolved_path, self.arch, uuid_str, self.symfile)
Greg Clayton3d39f832012-04-03 21:35:43 +0000293 if not self.module:
Greg Clayton4c983c82012-04-20 23:31:27 +0000294 return 'error: unable to get module for (%s) "%s"' % (self.arch, self.get_resolved_path())
Greg Clayton3d39f832012-04-03 21:35:43 +0000295 if self.has_section_load_info():
296 return self.load_module(target)
297 else:
298 return None # No sections, the module was added to the target, so success
299 else:
300 return 'error: invalid target'
301
302 def locate_module_and_debug_symbols (self):
303 # By default, just use the paths that were supplied in:
304 # self.path
305 # self.resolved_path
306 # self.module
307 # self.symfile
308 # Subclasses can inherit from this class and override this function
309 return True
310
311 def get_uuid(self):
Greg Claytond8056e22012-05-11 00:30:14 +0000312 if not self.uuid and self.module:
Greg Clayton3d39f832012-04-03 21:35:43 +0000313 self.uuid = uuid.UUID(self.module.GetUUIDString())
314 return self.uuid
315
Greg Claytond8056e22012-05-11 00:30:14 +0000316 def get_normalized_uuid_string(self):
317 if self.uuid:
318 return str(self.uuid).upper()
319 return None
320
Greg Clayton3d39f832012-04-03 21:35:43 +0000321 def create_target(self):
322 '''Create a target using the information in this Image object.'''
323 if self.locate_module_and_debug_symbols ():
324 resolved_path = self.get_resolved_path();
325 path_spec = lldb.SBFileSpec (resolved_path)
326 #result.PutCString ('plist[%s] = %s' % (uuid, self.plist))
327 error = lldb.SBError()
328 target = lldb.debugger.CreateTarget (resolved_path, self.arch, None, False, error);
329 if target:
330 self.module = target.FindModule(path_spec)
331 if self.has_section_load_info():
332 err = self.load_module(target)
333 if err:
334 print 'ERROR: ', err
335 return target
336 else:
337 print 'error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path)
338 else:
339 print 'error: unable to locate main executable (%s) "%s"' % (self.arch, self.path)
340 return None
341
342class Symbolicator:
343
344 def __init__(self):
345 """A class the represents the information needed to symbolicate addresses in a program"""
346 self.target = None
347 self.images = list() # a list of images to be used when symbolicating
348
349
350 def __str__(self):
351 s = "Symbolicator:\n"
352 if self.target:
353 s += "Target = '%s'\n" % (self.target)
354 s += "Target modules:'\n"
355 for m in self.target.modules:
356 print m
357 s += "Images:\n"
358 for image in self.images:
359 s += ' %s\n' % (image)
360 return s
361
362 def find_images_with_identifier(self, identifier):
363 images = list()
364 for image in self.images:
365 if image.identifier == identifier:
366 images.append(image)
367 return images
368
369 def find_image_containing_load_addr(self, load_addr):
370 for image in self.images:
371 if image.contains_addr (load_addr):
372 return image
373 return None
374
375 def create_target(self):
376 if self.target:
377 return self.target
378
379 if self.images:
380 for image in self.images:
381 self.target = image.create_target ()
382 if self.target:
383 return self.target
384 return None
385
386 def symbolicate(self, load_addr):
387 if self.target:
388 symbolicated_address = Address(self.target, load_addr)
389 if symbolicated_address.symbolicate ():
390
391 if symbolicated_address.so_addr:
392 symbolicated_addresses = list()
393 symbolicated_addresses.append(symbolicated_address)
394 # See if we were able to reconstruct anything?
395 while 1:
396 inlined_parent_so_addr = lldb.SBAddress()
397 inlined_parent_sym_ctx = symbolicated_address.sym_ctx.GetParentOfInlinedScope (symbolicated_address.so_addr, inlined_parent_so_addr)
398 if not inlined_parent_sym_ctx:
399 break
400 if not inlined_parent_so_addr:
401 break
402
403 symbolicated_address = Address(self.target, inlined_parent_so_addr.GetLoadAddress(self.target))
404 symbolicated_address.sym_ctx = inlined_parent_sym_ctx
405 symbolicated_address.so_addr = inlined_parent_so_addr
406 symbolicated_address.symbolicate ()
407
408 # push the new frame onto the new frame stack
409 symbolicated_addresses.append (symbolicated_address)
410
411 if symbolicated_addresses:
412 return symbolicated_addresses
413 return None
414
415
416def disassemble_instructions (target, instructions, pc, insts_before_pc, insts_after_pc, non_zeroeth_frame):
417 lines = list()
418 pc_index = -1
419 comment_column = 50
420 for inst_idx, inst in enumerate(instructions):
421 inst_pc = inst.GetAddress().GetLoadAddress(target);
422 if pc == inst_pc:
423 pc_index = inst_idx
424 mnemonic = inst.GetMnemonic (target)
425 operands = inst.GetOperands (target)
426 comment = inst.GetComment (target)
427 #data = inst.GetData (target)
428 lines.append ("%#16.16x: %8s %s" % (inst_pc, mnemonic, operands))
429 if comment:
430 line_len = len(lines[-1])
431 if line_len < comment_column:
432 lines[-1] += ' ' * (comment_column - line_len)
433 lines[-1] += "; %s" % comment
434
435 if pc_index >= 0:
436 # If we are disassembling the non-zeroeth frame, we need to backup the PC by 1
437 if non_zeroeth_frame and pc_index > 0:
438 pc_index = pc_index - 1
439 if insts_before_pc == -1:
440 start_idx = 0
441 else:
442 start_idx = pc_index - insts_before_pc
443 if start_idx < 0:
444 start_idx = 0
445 if insts_before_pc == -1:
446 end_idx = inst_idx
447 else:
448 end_idx = pc_index + insts_after_pc
449 if end_idx > inst_idx:
450 end_idx = inst_idx
451 for i in range(start_idx, end_idx+1):
452 if i == pc_index:
453 print ' -> ', lines[i]
454 else:
455 print ' ', lines[i]
456
457def print_module_section_data (section):
458 print section
459 section_data = section.GetSectionData()
460 if section_data:
461 ostream = lldb.SBStream()
462 section_data.GetDescription (ostream, section.GetFileAddress())
463 print ostream.GetData()
464
465def print_module_section (section, depth):
466 print section
467 if depth > 0:
468 num_sub_sections = section.GetNumSubSections()
469 for sect_idx in range(num_sub_sections):
470 print_module_section (section.GetSubSectionAtIndex(sect_idx), depth - 1)
471
472def print_module_sections (module, depth):
473 for sect in module.section_iter():
474 print_module_section (sect, depth)
475
476def print_module_symbols (module):
477 for sym in module:
478 print sym
479
480def Symbolicate(command_args):
481
482 usage = "usage: %prog [options] <addr1> [addr2 ...]"
483 description='''Symbolicate one or more addresses using LLDB's python scripting API..'''
484 parser = optparse.OptionParser(description=description, prog='crashlog.py',usage=usage)
485 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='display verbose debug info', default=False)
486 parser.add_option('-p', '--platform', type='string', metavar='platform', dest='platform', help='specify one platform by name')
487 parser.add_option('-f', '--file', type='string', metavar='file', dest='file', help='Specify a file to use when symbolicating')
488 parser.add_option('-a', '--arch', type='string', metavar='arch', dest='arch', help='Specify a architecture to use when symbolicating')
489 parser.add_option('-s', '--slide', type='int', metavar='slide', dest='slide', help='Specify the slide to use on the file specified with the --file option', default=None)
490 parser.add_option('--section', type='string', action='append', dest='section_strings', help='specify <sect-name>=<start-addr> or <sect-name>=<start-addr>-<end-addr>')
491 try:
492 (options, args) = parser.parse_args(command_args)
493 except:
494 return
495 symbolicator = Symbolicator()
496 images = list();
497 if options.file:
498 image = Image(options.file);
499 image.arch = options.arch
500 # Add any sections that were specified with one or more --section options
501 if options.section_strings:
502 for section_str in options.section_strings:
503 section = Section()
504 if section.set_from_string (section_str):
505 image.add_section (section)
506 else:
507 sys.exit(1)
508 if options.slide != None:
509 image.slide = options.slide
510 symbolicator.images.append(image)
511
512 target = symbolicator.create_target()
513 if options.verbose:
514 print symbolicator
515 if target:
516 for addr_str in args:
517 addr = int(addr_str, 0)
518 symbolicated_addrs = symbolicator.symbolicate(addr)
519 for symbolicated_addr in symbolicated_addrs:
520 print symbolicated_addr
521 print
522 else:
523 print 'error: no target for %s' % (symbolicator)
524
525if __name__ == '__main__':
526 # Create a new debugger instance
527 lldb.debugger = lldb.SBDebugger.Create()
528 Symbolicate (sys.argv[1:])