blob: 8f10be84f10a452a5768d099d971e4a6d7ef0ae9 [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):
209 s = "%s %s" % (self.get_uuid(), self.get_resolved_path())
210 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
286 if self.uuid:
287 self.module = target.AddModule (None, None, str(self.uuid))
288 if not self.module:
Greg Clayton4c983c82012-04-20 23:31:27 +0000289 self.locate_module_and_debug_symbols ()
290 resolved_path = self.get_resolved_path()
291 print 'target.AddModule (path="%s", arch="%s", uuid=%s, symfile="%s")' % (resolved_path, self.arch, self.uuid, self.symfile)
292 self.module = target.AddModule (resolved_path, self.arch, self.uuid)#, 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):
312 if not self.uuid:
313 self.uuid = uuid.UUID(self.module.GetUUIDString())
314 return self.uuid
315
316 def create_target(self):
317 '''Create a target using the information in this Image object.'''
318 if self.locate_module_and_debug_symbols ():
319 resolved_path = self.get_resolved_path();
320 path_spec = lldb.SBFileSpec (resolved_path)
321 #result.PutCString ('plist[%s] = %s' % (uuid, self.plist))
322 error = lldb.SBError()
323 target = lldb.debugger.CreateTarget (resolved_path, self.arch, None, False, error);
324 if target:
325 self.module = target.FindModule(path_spec)
326 if self.has_section_load_info():
327 err = self.load_module(target)
328 if err:
329 print 'ERROR: ', err
330 return target
331 else:
332 print 'error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path)
333 else:
334 print 'error: unable to locate main executable (%s) "%s"' % (self.arch, self.path)
335 return None
336
337class Symbolicator:
338
339 def __init__(self):
340 """A class the represents the information needed to symbolicate addresses in a program"""
341 self.target = None
342 self.images = list() # a list of images to be used when symbolicating
343
344
345 def __str__(self):
346 s = "Symbolicator:\n"
347 if self.target:
348 s += "Target = '%s'\n" % (self.target)
349 s += "Target modules:'\n"
350 for m in self.target.modules:
351 print m
352 s += "Images:\n"
353 for image in self.images:
354 s += ' %s\n' % (image)
355 return s
356
357 def find_images_with_identifier(self, identifier):
358 images = list()
359 for image in self.images:
360 if image.identifier == identifier:
361 images.append(image)
362 return images
363
364 def find_image_containing_load_addr(self, load_addr):
365 for image in self.images:
366 if image.contains_addr (load_addr):
367 return image
368 return None
369
370 def create_target(self):
371 if self.target:
372 return self.target
373
374 if self.images:
375 for image in self.images:
376 self.target = image.create_target ()
377 if self.target:
378 return self.target
379 return None
380
381 def symbolicate(self, load_addr):
382 if self.target:
383 symbolicated_address = Address(self.target, load_addr)
384 if symbolicated_address.symbolicate ():
385
386 if symbolicated_address.so_addr:
387 symbolicated_addresses = list()
388 symbolicated_addresses.append(symbolicated_address)
389 # See if we were able to reconstruct anything?
390 while 1:
391 inlined_parent_so_addr = lldb.SBAddress()
392 inlined_parent_sym_ctx = symbolicated_address.sym_ctx.GetParentOfInlinedScope (symbolicated_address.so_addr, inlined_parent_so_addr)
393 if not inlined_parent_sym_ctx:
394 break
395 if not inlined_parent_so_addr:
396 break
397
398 symbolicated_address = Address(self.target, inlined_parent_so_addr.GetLoadAddress(self.target))
399 symbolicated_address.sym_ctx = inlined_parent_sym_ctx
400 symbolicated_address.so_addr = inlined_parent_so_addr
401 symbolicated_address.symbolicate ()
402
403 # push the new frame onto the new frame stack
404 symbolicated_addresses.append (symbolicated_address)
405
406 if symbolicated_addresses:
407 return symbolicated_addresses
408 return None
409
410
411def disassemble_instructions (target, instructions, pc, insts_before_pc, insts_after_pc, non_zeroeth_frame):
412 lines = list()
413 pc_index = -1
414 comment_column = 50
415 for inst_idx, inst in enumerate(instructions):
416 inst_pc = inst.GetAddress().GetLoadAddress(target);
417 if pc == inst_pc:
418 pc_index = inst_idx
419 mnemonic = inst.GetMnemonic (target)
420 operands = inst.GetOperands (target)
421 comment = inst.GetComment (target)
422 #data = inst.GetData (target)
423 lines.append ("%#16.16x: %8s %s" % (inst_pc, mnemonic, operands))
424 if comment:
425 line_len = len(lines[-1])
426 if line_len < comment_column:
427 lines[-1] += ' ' * (comment_column - line_len)
428 lines[-1] += "; %s" % comment
429
430 if pc_index >= 0:
431 # If we are disassembling the non-zeroeth frame, we need to backup the PC by 1
432 if non_zeroeth_frame and pc_index > 0:
433 pc_index = pc_index - 1
434 if insts_before_pc == -1:
435 start_idx = 0
436 else:
437 start_idx = pc_index - insts_before_pc
438 if start_idx < 0:
439 start_idx = 0
440 if insts_before_pc == -1:
441 end_idx = inst_idx
442 else:
443 end_idx = pc_index + insts_after_pc
444 if end_idx > inst_idx:
445 end_idx = inst_idx
446 for i in range(start_idx, end_idx+1):
447 if i == pc_index:
448 print ' -> ', lines[i]
449 else:
450 print ' ', lines[i]
451
452def print_module_section_data (section):
453 print section
454 section_data = section.GetSectionData()
455 if section_data:
456 ostream = lldb.SBStream()
457 section_data.GetDescription (ostream, section.GetFileAddress())
458 print ostream.GetData()
459
460def print_module_section (section, depth):
461 print section
462 if depth > 0:
463 num_sub_sections = section.GetNumSubSections()
464 for sect_idx in range(num_sub_sections):
465 print_module_section (section.GetSubSectionAtIndex(sect_idx), depth - 1)
466
467def print_module_sections (module, depth):
468 for sect in module.section_iter():
469 print_module_section (sect, depth)
470
471def print_module_symbols (module):
472 for sym in module:
473 print sym
474
475def Symbolicate(command_args):
476
477 usage = "usage: %prog [options] <addr1> [addr2 ...]"
478 description='''Symbolicate one or more addresses using LLDB's python scripting API..'''
479 parser = optparse.OptionParser(description=description, prog='crashlog.py',usage=usage)
480 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='display verbose debug info', default=False)
481 parser.add_option('-p', '--platform', type='string', metavar='platform', dest='platform', help='specify one platform by name')
482 parser.add_option('-f', '--file', type='string', metavar='file', dest='file', help='Specify a file to use when symbolicating')
483 parser.add_option('-a', '--arch', type='string', metavar='arch', dest='arch', help='Specify a architecture to use when symbolicating')
484 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)
485 parser.add_option('--section', type='string', action='append', dest='section_strings', help='specify <sect-name>=<start-addr> or <sect-name>=<start-addr>-<end-addr>')
486 try:
487 (options, args) = parser.parse_args(command_args)
488 except:
489 return
490 symbolicator = Symbolicator()
491 images = list();
492 if options.file:
493 image = Image(options.file);
494 image.arch = options.arch
495 # Add any sections that were specified with one or more --section options
496 if options.section_strings:
497 for section_str in options.section_strings:
498 section = Section()
499 if section.set_from_string (section_str):
500 image.add_section (section)
501 else:
502 sys.exit(1)
503 if options.slide != None:
504 image.slide = options.slide
505 symbolicator.images.append(image)
506
507 target = symbolicator.create_target()
508 if options.verbose:
509 print symbolicator
510 if target:
511 for addr_str in args:
512 addr = int(addr_str, 0)
513 symbolicated_addrs = symbolicator.symbolicate(addr)
514 for symbolicated_addr in symbolicated_addrs:
515 print symbolicated_addr
516 print
517 else:
518 print 'error: no target for %s' % (symbolicator)
519
520if __name__ == '__main__':
521 # Create a new debugger instance
522 lldb.debugger = lldb.SBDebugger.Create()
523 Symbolicate (sys.argv[1:])