# PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash
#----------------------------------------------------------------------
-from __future__ import print_function
-from builtins import str
-from builtins import map
-from builtins import range
-from builtins import object
-import subprocess
+import commands
import cmd
import datetime
import glob
platform_system = platform.system()
if platform_system == 'Darwin':
# On Darwin, try the currently selected Xcode directory
- xcode_dir = subprocess.getoutput("xcode-select --print-path")
+ xcode_dir = commands.getoutput("xcode-select --print-path")
if xcode_dir:
lldb_python_dirs.append(
os.path.realpath(
except ImportError:
pass
else:
- print('imported lldb from: "%s"' % (lldb_python_dir))
+ print 'imported lldb from: "%s"' % (lldb_python_dir)
success = True
break
if not success:
- print("error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly")
+ print "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"
sys.exit(1)
from lldb.utils import symbolication
'(0x[0-9a-fA-F]+)[-\s]+(0x[0-9a-fA-F]+)\s+[+]?(.+?)\s+(\(.+\))?\s?(<([-0-9a-fA-F]+)>)? (.*)')
empty_line_regex = re.compile('^$')
- class Thread(object):
+ class Thread:
"""Class that represents a thread in a darwin crash log"""
def __init__(self, index, app_specific_backtrace):
def dump(self, prefix):
if self.app_specific_backtrace:
- print("%Application Specific Backtrace[%u] %s" % (prefix, self.index, self.reason))
+ print "%Application Specific Backtrace[%u] %s" % (prefix, self.index, self.reason)
else:
- print("%sThread[%u] %s" % (prefix, self.index, self.reason))
+ print "%sThread[%u] %s" % (prefix, self.index, self.reason)
if self.frames:
- print("%s Frames:" % (prefix))
+ print "%s Frames:" % (prefix)
for frame in self.frames:
frame.dump(prefix + ' ')
if self.registers:
- print("%s Registers:" % (prefix))
- for reg in list(self.registers.keys()):
- print("%s %-5s = %#16.16x" % (prefix, reg, self.registers[reg]))
+ print "%s Registers:" % (prefix)
+ for reg in self.registers.keys():
+ print "%s %-5s = %#16.16x" % (prefix, reg, self.registers[reg])
def dump_symbolicated(self, crash_log, options):
this_thread_crashed = self.app_specific_backtrace
if options.crashed_only and this_thread_crashed == False:
return
- print("%s" % self)
+ print "%s" % self
#prev_frame_index = -1
display_frame_idx = -1
for frame_idx, frame in enumerate(self.frames):
symbolicated_frame_address_idx = 0
for symbolicated_frame_address in symbolicated_frame_addresses:
display_frame_idx += 1
- print('[%3u] %s' % (frame_idx, symbolicated_frame_address))
+ print '[%3u] %s' % (frame_idx, symbolicated_frame_address)
if (options.source_all or self.did_crash(
)) and display_frame_idx < options.source_frames and options.source_context:
source_context = options.source_context
# Indent the source a bit
indent_str = ' '
join_str = '\n' + indent_str
- print('%s%s' % (indent_str, join_str.join(source_text.split('\n'))))
+ print '%s%s' % (indent_str, join_str.join(source_text.split('\n')))
if symbolicated_frame_address_idx == 0:
if disassemble:
instructions = symbolicated_frame_address.get_instructions()
if instructions:
- print()
+ print
symbolication.disassemble_instructions(
crash_log.get_target(),
instructions,
options.disassemble_before,
options.disassemble_after,
frame.index > 0)
- print()
+ print
symbolicated_frame_address_idx += 1
else:
- print(frame)
+ print frame
def add_ident(self, ident):
if ident not in self.idents:
s += ' %s' % self.reason
return s
- class Frame(object):
+ class Frame:
"""Class that represents a stack frame in a thread in a darwin crash log"""
def __init__(self, index, pc, description):
return "[%3u] 0x%16.16x" % (self.index, self.pc)
def dump(self, prefix):
- print("%s%s" % (prefix, str(self)))
+ print "%s%s" % (prefix, str(self))
class DarwinImage(symbolication.Image):
"""Class that represents a binary images in a darwin crash log"""
dsymForUUIDBinary = os.path.expanduser('~rc/bin/dsymForUUID')
if not os.path.exists(dsymForUUIDBinary):
- dsymForUUIDBinary = subprocess.getoutput('which dsymForUUID')
+ dsymForUUIDBinary = commands.getoutput('which dsymForUUID')
dwarfdump_uuid_regex = re.compile(
'UUID: ([-0-9a-fA-F]+) \(([^\(]+)\) .*')
self.version = version
def find_matching_slice(self):
- dwarfdump_cmd_output = subprocess.getoutput(
+ dwarfdump_cmd_output = commands.getoutput(
'dwarfdump --uuid "%s"' % self.path)
self_uuid = self.get_uuid()
for line in dwarfdump_cmd_output.splitlines():
# Mark this as resolved so we don't keep trying
self.resolved = True
uuid_str = self.get_normalized_uuid_string()
- print('Getting symbols for %s %s...' % (uuid_str, self.path), end=' ')
+ print 'Getting symbols for %s %s...' % (uuid_str, self.path),
if os.path.exists(self.dsymForUUIDBinary):
dsym_for_uuid_command = '%s %s' % (
self.dsymForUUIDBinary, uuid_str)
- s = subprocess.getoutput(dsym_for_uuid_command)
+ s = commands.getoutput(dsym_for_uuid_command)
if s:
try:
plist_root = plistlib.readPlistFromString(s)
except:
- print(("Got exception: ", sys.exc_info()[1], " handling dsymForUUID output: \n", s))
+ print("Got exception: ", sys.exc_value, " handling dsymForUUID output: \n", s)
raise
if plist_root:
plist = plist_root[uuid_str]
pass
if (self.resolved_path and os.path.exists(self.resolved_path)) or (
self.path and os.path.exists(self.path)):
- print('ok')
+ print 'ok'
# if self.resolved_path:
# print ' exe = "%s"' % self.resolved_path
# if self.symfile:
thread.frames.append(CrashLog.Frame(int(frame_match.group(1)), int(
frame_match.group(3), 0), frame_match.group(4)))
else:
- print('error: frame regex failed for line: "%s"' % line)
+ print 'error: frame regex failed for line: "%s"' % line
elif parse_mode == PARSE_MODE_IMAGES:
image_match = self.image_regex_uuid.search(line)
if image_match:
uuid.UUID(img_uuid), img_path)
self.images.append(image)
else:
- print("error: image regex failed for: %s" % line)
+ print "error: image regex failed for: %s" % line
elif parse_mode == PARSE_MODE_THREGS:
stripped_line = line.strip()
f.close()
def dump(self):
- print("Crash Log File: %s" % (self.path))
+ print "Crash Log File: %s" % (self.path)
if self.backtraces:
- print("\nApplication Specific Backtraces:")
+ print "\nApplication Specific Backtraces:"
for thread in self.backtraces:
thread.dump(' ')
- print("\nThreads:")
+ print "\nThreads:"
for thread in self.threads:
thread.dump(' ')
- print("\nImages:")
+ print "\nImages:"
for image in self.images:
image.dump(' ')
return self.target
# We weren't able to open the main executable as, but we can still
# symbolicate
- print('crashlog.create_target()...2')
+ print 'crashlog.create_target()...2'
if self.idents:
for ident in self.idents:
image = self.find_image_with_identifier(ident)
self.target = image.create_target()
if self.target:
return self.target # success
- print('crashlog.create_target()...3')
+ print 'crashlog.create_target()...3'
for image in self.images:
self.target = image.create_target()
if self.target:
return self.target # success
- print('crashlog.create_target()...4')
- print('error: unable to locate any executables from the crash log')
+ print 'crashlog.create_target()...4'
+ print 'error: unable to locate any executables from the crash log'
return self.target
def get_target(self):
def usage():
- print("Usage: lldb-symbolicate.py [-n name] executable-image")
+ print "Usage: lldb-symbolicate.py [-n name] executable-image"
sys.exit(0)
def default(self, line):
'''Catch all for unknown command, which will exit the interpreter.'''
- print("uknown command: %s" % line)
+ print "uknown command: %s" % line
return True
def do_q(self, line):
if idx < len(self.crash_logs):
SymbolicateCrashLog(self.crash_logs[idx], options)
else:
- print('error: crash log index %u is out of range' % (idx))
+ print 'error: crash log index %u is out of range' % (idx)
else:
# No arguments, symbolicate all crash logs using the options
# provided
'''Dump a list of all crash logs that are currently loaded.
USAGE: list'''
- print('%u crash logs are loaded:' % len(self.crash_logs))
+ print '%u crash logs are loaded:' % len(self.crash_logs)
for (crash_log_idx, crash_log) in enumerate(self.crash_logs):
- print('[%u] = %s' % (crash_log_idx, crash_log.path))
+ print '[%u] = %s' % (crash_log_idx, crash_log.path)
def do_image(self, line):
'''Dump information about one or more binary images in the crash log given an image basename, or all images if no arguments are provided.'''
if fullpath_search:
if image.get_resolved_path() == image_path:
matches_found += 1
- print('[%u] ' % (crash_log_idx), image)
+ print '[%u] ' % (crash_log_idx), image
else:
image_basename = image.get_resolved_path_basename()
if image_basename == image_path:
matches_found += 1
- print('[%u] ' % (crash_log_idx), image)
+ print '[%u] ' % (crash_log_idx), image
if matches_found == 0:
for (image_idx, image) in enumerate(crash_log.images):
resolved_image_path = image.get_resolved_path()
if resolved_image_path and string.find(
image.get_resolved_path(), image_path) >= 0:
- print('[%u] ' % (crash_log_idx), image)
+ print '[%u] ' % (crash_log_idx), image
else:
for crash_log in self.crash_logs:
for (image_idx, image) in enumerate(crash_log.images):
- print('[%u] %s' % (image_idx, image))
+ print '[%u] %s' % (image_idx, image)
return False
# print 'crash_log_file = "%s"' % crash_log_file
crash_log = CrashLog(crash_log_file)
if crash_log.error:
- print(crash_log.error)
+ print crash_log.error
continue
if options.debug:
crash_log.dump()
if not crash_log.images:
- print('error: no images in crash log "%s"' % (crash_log))
+ print 'error: no images in crash log "%s"' % (crash_log)
continue
else:
crash_logs.append(crash_log)
(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
out_file.write(
'OS Version: Mac OS X %s (%s)\n' %
- (platform.mac_ver()[0], subprocess.getoutput('sysctl -n kern.osversion')))
+ (platform.mac_ver()[0], commands.getoutput('sysctl -n kern.osversion')))
out_file.write('Report Version: 9\n')
for thread_idx in range(process.num_threads):
thread = process.thread[thread_idx]
def SymbolicateCrashLog(crash_log, options):
if crash_log.error:
- print(crash_log.error)
+ print crash_log.error
return
if options.debug:
crash_log.dump()
if not crash_log.images:
- print('error: no images in crash log')
+ print 'error: no images in crash log'
return
if options.dump_image_list:
- print("Binary Images:")
+ print "Binary Images:"
for image in crash_log.images:
if options.verbose:
- print(image.debug_dump())
+ print image.debug_dump()
else:
- print(image)
+ print image
target = crash_log.create_target()
if not target:
for image in images:
images_to_load.append(image)
else:
- print('error: can\'t find image for identifier "%s"' % ident)
+ print 'error: can\'t find image for identifier "%s"' % ident
else:
for ident in crash_log.idents:
images = crash_log.find_images_with_identifier(ident)
for image in images:
images_to_load.append(image)
else:
- print('error: can\'t find image for identifier "%s"' % ident)
+ print 'error: can\'t find image for identifier "%s"' % ident
for image in images_to_load:
if image not in loaded_images:
err = image.add_module(target)
if err:
- print(err)
+ print err
else:
# print 'loaded %s' % image
loaded_images.append(image)
if crash_log.backtraces:
for thread in crash_log.backtraces:
thread.dump_symbolicated(crash_log, options)
- print()
+ print
for thread in crash_log.threads:
thread.dump_symbolicated(crash_log, options)
- print()
+ print
def CreateSymbolicateCrashLogOptions(
return
if options.debug:
- print('command_args = %s' % command_args)
- print('options', options)
- print('args', args)
+ print 'command_args = %s' % command_args
+ print 'options', options
+ print 'args', args
if options.debug_delay > 0:
- print("Waiting %u seconds for debugger to attach..." % options.debug_delay)
+ print "Waiting %u seconds for debugger to attach..." % options.debug_delay
time.sleep(options.debug_delay)
error = lldb.SBError()
'command script add -f lldb.macosx.crashlog.Symbolicate crashlog')
lldb.debugger.HandleCommand(
'command script add -f lldb.macosx.crashlog.save_crashlog save_crashlog')
- print('"crashlog" and "save_crashlog" command installed, use the "--help" option for detailed help')
+ print '"crashlog" and "save_crashlog" command installed, use the "--help" option for detailed help'
# PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash
#----------------------------------------------------------------------
-from __future__ import print_function
-from builtins import str
-from builtins import range
-from builtins import object
import lldb
-import subprocess
+import commands
import optparse
import os
import plistlib
import uuid
-class Address(object):
+class Address:
"""Class that represents an address that will be symbolicated"""
def __init__(self, target, load_addr):
return False
-class Section(object):
+class Section:
"""Class that represents an load address range"""
sect_info_regex = re.compile('(?P<name>[^=]+)=(?P<range>.*)')
addr_regex = re.compile('^\s*(?P<start>0x[0-9A-Fa-f]+)\s*$')
if op == '+':
self.end_addr += self.start_addr
return True
- print('error: invalid section info string "%s"' % s)
- print('Valid section info formats are:')
- print('Format Example Description')
- print('--------------------- -----------------------------------------------')
- print('<name>=<base> __TEXT=0x123000 Section from base address only')
- print('<name>=<base>-<end> __TEXT=0x123000-0x124000 Section from base address and end address')
- print('<name>=<base>+<size> __TEXT=0x123000+0x1000 Section from base address and size')
+ print 'error: invalid section info string "%s"' % s
+ print 'Valid section info formats are:'
+ print 'Format Example Description'
+ print '--------------------- -----------------------------------------------'
+ print '<name>=<base> __TEXT=0x123000 Section from base address only'
+ print '<name>=<base>-<end> __TEXT=0x123000-0x124000 Section from base address and end address'
+ print '<name>=<base>+<size> __TEXT=0x123000+0x1000 Section from base address and size'
return False
def __str__(self):
return "<invalid>"
-class Image(object):
+class Image:
"""A class that represents an executable image and any associated data"""
def __init__(self, path, uuid=None):
return obj
def dump(self, prefix):
- print("%s%s" % (prefix, self))
+ print "%s%s" % (prefix, self)
def debug_dump(self):
- print('path = "%s"' % (self.path))
- print('resolved_path = "%s"' % (self.resolved_path))
- print('resolved = %i' % (self.resolved))
- print('unavailable = %i' % (self.unavailable))
- print('uuid = %s' % (self.uuid))
- print('section_infos = %s' % (self.section_infos))
- print('identifier = "%s"' % (self.identifier))
- print('version = %s' % (self.version))
- print('arch = %s' % (self.arch))
- print('module = %s' % (self.module))
- print('symfile = "%s"' % (self.symfile))
- print('slide = %i (0x%x)' % (self.slide, self.slide))
+ print 'path = "%s"' % (self.path)
+ print 'resolved_path = "%s"' % (self.resolved_path)
+ print 'resolved = %i' % (self.resolved)
+ print 'unavailable = %i' % (self.unavailable)
+ print 'uuid = %s' % (self.uuid)
+ print 'section_infos = %s' % (self.section_infos)
+ print 'identifier = "%s"' % (self.identifier)
+ print 'version = %s' % (self.version)
+ print 'arch = %s' % (self.arch)
+ print 'module = %s' % (self.module)
+ print 'symfile = "%s"' % (self.symfile)
+ print 'slide = %i (0x%x)' % (self.slide, self.slide)
def __str__(self):
s = ''
if self.has_section_load_info():
err = self.load_module(target)
if err:
- print('ERROR: ', err)
+ print 'ERROR: ', err
return target
else:
- print('error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path))
+ print 'error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path)
else:
- print('error: unable to locate main executable (%s) "%s"' % (self.arch, self.path))
+ print 'error: unable to locate main executable (%s) "%s"' % (self.arch, self.path)
return None
-class Symbolicator(object):
+class Symbolicator:
def __init__(self):
"""A class the represents the information needed to symbolicate addresses in a program"""
if symbolicated_addresses:
return symbolicated_addresses
else:
- print('error: no target in Symbolicator')
+ print 'error: no target in Symbolicator'
return None
end_idx = inst_idx
for i in range(start_idx, end_idx + 1):
if i == pc_index:
- print(' -> ', lines[i])
+ print ' -> ', lines[i]
else:
- print(' ', lines[i])
+ print ' ', lines[i]
def print_module_section_data(section):
- print(section)
+ print section
section_data = section.GetSectionData()
if section_data:
ostream = lldb.SBStream()
section_data.GetDescription(ostream, section.GetFileAddress())
- print(ostream.GetData())
+ print ostream.GetData()
def print_module_section(section, depth):
- print(section)
+ print section
if depth > 0:
num_sub_sections = section.GetNumSubSections()
for sect_idx in range(num_sub_sections):
def print_module_symbols(module):
for sym in module:
- print(sym)
+ print sym
def Symbolicate(command_args):
target = symbolicator.create_target()
if options.verbose:
- print(symbolicator)
+ print symbolicator
if target:
for addr_str in args:
addr = int(addr_str, 0)
symbolicated_addrs = symbolicator.symbolicate(
addr, options.verbose)
for symbolicated_addr in symbolicated_addrs:
- print(symbolicated_addr)
- print()
+ print symbolicated_addr
+ print
else:
- print('error: no target for %s' % (symbolicator))
+ print 'error: no target for %s' % (symbolicator)
if __name__ == '__main__':
# Create a new debugger instance