Python 2/3 compatibility: from __future__ import print_function

Differential Revision: https://reviews.llvm.org/D59580

llvm-svn: 356695
This commit is contained in:
Serge Guelton 2019-03-21 18:27:40 +00:00
parent 05ea3a6be3
commit 525cd59f5a
50 changed files with 725 additions and 666 deletions

View File

@ -2,6 +2,7 @@
import StringIO import StringIO
from __future__ import print_function
def binary(n, width=None): def binary(n, width=None):
""" """
@ -77,7 +78,7 @@ def utob(debugger, command_line, result, dict):
if width < 0: if width < 0:
width = 0 width = 0
except: except:
print utob.__doc__ print(utob.__doc__)
return return
if len(args) > 2: if len(args) > 2:
@ -87,12 +88,12 @@ def utob(debugger, command_line, result, dict):
bits = binary(n, width) bits = binary(n, width)
if not bits: if not bits:
print "insufficient width value: %d" % width print("insufficient width value: %d" % width)
return return
if verbose and width > 0: if verbose and width > 0:
pos = positions(width) pos = positions(width)
print ' ' + ' '.join(pos) print(' ' + ' '.join(pos))
print ' %s' % str(bits) print(' %s' % str(bits))
def itob(debugger, command_line, result, dict): def itob(debugger, command_line, result, dict):
@ -107,7 +108,7 @@ def itob(debugger, command_line, result, dict):
if width < 0: if width < 0:
width = 0 width = 0
except: except:
print itob.__doc__ print(itob.__doc__)
return return
if len(args) > 2: if len(args) > 2:
@ -117,9 +118,9 @@ def itob(debugger, command_line, result, dict):
bits = twos_complement(n, width) bits = twos_complement(n, width)
if not bits: if not bits:
print "insufficient width value: %d" % width print("insufficient width value: %d" % width)
return return
if verbose and width > 0: if verbose and width > 0:
pos = positions(width) pos = positions(width)
print ' ' + ' '.join(pos) print(' ' + ' '.join(pos))
print ' %s' % str(bits) print(' %s' % str(bits))

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import sys import sys
import os import os
import lldb import lldb
@ -23,7 +24,7 @@ def do_import(debugger, modname):
def pyimport_cmd(debugger, args, result, dict): def pyimport_cmd(debugger, args, result, dict):
"""Import a Python module given its full path""" """Import a Python module given its full path"""
print 'WARNING: obsolete feature - use native command "command script import"' print('WARNING: obsolete feature - use native command "command script import"')
if args == "": if args == "":
return "no module path given" return "no module path given"
if not (os.sep in args): if not (os.sep in args):

View File

@ -1,4 +1,5 @@
"""Utility for changing directories and execution of commands in a subshell.""" """Utility for changing directories and execution of commands in a subshell."""
from __future__ import print_function
import os import os
import shlex import shlex
@ -29,14 +30,14 @@ def chdir(debugger, args, result, dict):
elif new_dir == '-': elif new_dir == '-':
if not Holder.prev_dir(): if not Holder.prev_dir():
# Bad directory, not changing. # Bad directory, not changing.
print "bad directory, not changing" print("bad directory, not changing")
return return
else: else:
new_dir = Holder.prev_dir() new_dir = Holder.prev_dir()
Holder.swap(os.getcwd()) Holder.swap(os.getcwd())
os.chdir(new_dir) os.chdir(new_dir)
print "Current working directory: %s" % os.getcwd() print("Current working directory: %s" % os.getcwd())
def system(debugger, command_line, result, dict): def system(debugger, command_line, result, dict):
@ -49,10 +50,10 @@ def system(debugger, command_line, result, dict):
output, error = process.communicate() output, error = process.communicate()
retcode = process.poll() retcode = process.poll()
if output and error: if output and error:
print "stdout=>\n", output print("stdout=>\n", output)
print "stderr=>\n", error print("stderr=>\n", error)
elif output: elif output:
print output print(output)
elif error: elif error:
print error print(error)
print "retcode:", retcode print("retcode:", retcode)

View File

@ -1,4 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import cmd import cmd
import optparse import optparse
@ -391,18 +392,18 @@ if __name__ == '__main__':
def print_mtime_error(result, dmap_mtime, actual_mtime): def print_mtime_error(result, dmap_mtime, actual_mtime):
print >>result, ("error: modification time in debug map (%#08.8x) doesn't " print("error: modification time in debug map (%#08.8x) doesn't "
"match the .o file modification time (%#08.8x)" % ( "match the .o file modification time (%#08.8x)" % (
dmap_mtime, actual_mtime)) dmap_mtime, actual_mtime), file=result)
def print_file_missing_error(result, path): def print_file_missing_error(result, path):
print >>result, "error: file \"%s\" doesn't exist" % (path) print("error: file \"%s\" doesn't exist" % (path), file=result)
def print_multiple_object_matches(result, object_name, mtime, matches): def print_multiple_object_matches(result, object_name, mtime, matches):
print >>result, ("error: multiple matches for object '%s' with with " print("error: multiple matches for object '%s' with with "
"modification time %#08.8x:" % (object_name, mtime)) "modification time %#08.8x:" % (object_name, mtime), file=result)
Archive.dump_header(f=result) Archive.dump_header(f=result)
for match in matches: for match in matches:
match.dump(f=result, flat=True) match.dump(f=result, flat=True)
@ -411,15 +412,15 @@ def print_multiple_object_matches(result, object_name, mtime, matches):
def print_archive_object_error(result, object_name, mtime, archive): def print_archive_object_error(result, object_name, mtime, archive):
matches = archive.find(object_name, f=result) matches = archive.find(object_name, f=result)
if len(matches) > 0: if len(matches) > 0:
print >>result, ("error: no objects have a modification time that " print("error: no objects have a modification time that "
"matches %#08.8x for '%s'. Potential matches:" % ( "matches %#08.8x for '%s'. Potential matches:" % (
mtime, object_name)) mtime, object_name), file=result)
Archive.dump_header(f=result) Archive.dump_header(f=result)
for match in matches: for match in matches:
match.dump(f=result, flat=True) match.dump(f=result, flat=True)
else: else:
print >>result, "error: no object named \"%s\" found in archive:" % ( print("error: no object named \"%s\" found in archive:" % (
object_name) object_name), file=result)
Archive.dump_header(f=result) Archive.dump_header(f=result)
for match in archive.objects: for match in archive.objects:
match.dump(f=result, flat=True) match.dump(f=result, flat=True)
@ -496,13 +497,13 @@ or whose modification times don't match in the debug map of an executable.'''
dmap_mtime = int(str(symbol).split('value = ') dmap_mtime = int(str(symbol).split('value = ')
[1].split(',')[0], 16) [1].split(',')[0], 16)
if not options.errors: if not options.errors:
print >>result, '%s' % (path) print('%s' % (path), file=result)
if os.path.exists(path): if os.path.exists(path):
actual_mtime = int(os.stat(path).st_mtime) actual_mtime = int(os.stat(path).st_mtime)
if dmap_mtime != actual_mtime: if dmap_mtime != actual_mtime:
num_errors += 1 num_errors += 1
if options.errors: if options.errors:
print >>result, '%s' % (path), print('%s' % (path), end=' ', file=result)
print_mtime_error(result, dmap_mtime, print_mtime_error(result, dmap_mtime,
actual_mtime) actual_mtime)
elif path[-1] == ')': elif path[-1] == ')':
@ -510,13 +511,13 @@ or whose modification times don't match in the debug map of an executable.'''
if not archive_path and not object_name: if not archive_path and not object_name:
num_errors += 1 num_errors += 1
if options.errors: if options.errors:
print >>result, '%s' % (path), print('%s' % (path), end=' ', file=result)
print_file_missing_error(path) print_file_missing_error(path)
continue continue
if not os.path.exists(archive_path): if not os.path.exists(archive_path):
num_errors += 1 num_errors += 1
if options.errors: if options.errors:
print >>result, '%s' % (path), print('%s' % (path), end=' ', file=result)
print_file_missing_error(archive_path) print_file_missing_error(archive_path)
continue continue
if archive_path in archives: if archive_path in archives:
@ -527,30 +528,30 @@ or whose modification times don't match in the debug map of an executable.'''
matches = archive.find(object_name, dmap_mtime) matches = archive.find(object_name, dmap_mtime)
num_matches = len(matches) num_matches = len(matches)
if num_matches == 1: if num_matches == 1:
print >>result, '1 match' print('1 match', file=result)
obj = matches[0] obj = matches[0]
if obj.date != dmap_mtime: if obj.date != dmap_mtime:
num_errors += 1 num_errors += 1
if options.errors: if options.errors:
print >>result, '%s' % (path), print('%s' % (path), end=' ', file=result)
print_mtime_error(result, dmap_mtime, obj.date) print_mtime_error(result, dmap_mtime, obj.date)
elif num_matches == 0: elif num_matches == 0:
num_errors += 1 num_errors += 1
if options.errors: if options.errors:
print >>result, '%s' % (path), print('%s' % (path), end=' ', file=result)
print_archive_object_error(result, object_name, print_archive_object_error(result, object_name,
dmap_mtime, archive) dmap_mtime, archive)
elif num_matches > 1: elif num_matches > 1:
num_errors += 1 num_errors += 1
if options.errors: if options.errors:
print >>result, '%s' % (path), print('%s' % (path), end=' ', file=result)
print_multiple_object_matches(result, print_multiple_object_matches(result,
object_name, object_name,
dmap_mtime, matches) dmap_mtime, matches)
if num_errors > 0: if num_errors > 0:
print >>result, "%u errors found" % (num_errors) print("%u errors found" % (num_errors), file=result)
else: else:
print >>result, "No errors detected in debug map" print("No errors detected in debug map", file=result)
def __lldb_init_module(debugger, dict): def __lldb_init_module(debugger, dict):

View File

@ -9,6 +9,8 @@
# (lldb) command script import /path/to/cmdtemplate.py # (lldb) command script import /path/to/cmdtemplate.py
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
from __future__ import print_function
import inspect import inspect
import lldb import lldb
import optparse import optparse
@ -124,7 +126,7 @@ class FrameStatCommand:
options.inscope) options.inscope)
variables_count = variables_list.GetSize() variables_count = variables_list.GetSize()
if variables_count == 0: if variables_count == 0:
print >> result, "no variables here" print("no variables here", file=result)
return return
total_size = 0 total_size = 0
for i in range(0, variables_count): for i in range(0, variables_count):
@ -132,9 +134,9 @@ class FrameStatCommand:
variable_type = variable.GetType() variable_type = variable.GetType()
total_size = total_size + variable_type.GetByteSize() total_size = total_size + variable_type.GetByteSize()
average_size = float(total_size) / variables_count average_size = float(total_size) / variables_count
print >>result, ("Your frame has %d variables. Their total size " print("Your frame has %d variables. Their total size "
"is %d bytes. The average size is %f bytes") % ( "is %d bytes. The average size is %f bytes" % (
variables_count, total_size, average_size) variables_count, total_size, average_size), file=result)
# not returning anything is akin to returning success # not returning anything is akin to returning success

View File

@ -17,6 +17,8 @@
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import commands import commands
from __future__ import print_function
import optparse import optparse
import os import os
import shlex import shlex
@ -94,9 +96,9 @@ def parse_log_file(file, options):
handy when trying to figure out why some operation in the debugger is taking handy when trying to figure out why some operation in the debugger is taking
a long time during a preset set of debugger commands.''' a long time during a preset set of debugger commands.'''
print '#----------------------------------------------------------------------' print('#----------------------------------------------------------------------')
print "# Log file: '%s'" % file print("# Log file: '%s'" % file)
print '#----------------------------------------------------------------------' print('#----------------------------------------------------------------------')
timestamp_regex = re.compile('(\s*)([1-9][0-9]+\.[0-9]+)([^0-9].*)$') timestamp_regex = re.compile('(\s*)([1-9][0-9]+\.[0-9]+)([^0-9].*)$')
@ -114,10 +116,10 @@ def parse_log_file(file, options):
else: else:
base_time = curr_time base_time = curr_time
print '%s%.6f %+.6f%s' % (match.group(1), curr_time - base_time, delta, match.group(3)) print('%s%.6f %+.6f%s' % (match.group(1), curr_time - base_time, delta, match.group(3)))
last_time = curr_time last_time = curr_time
else: else:
print line print(line)
if __name__ == '__main__': if __name__ == '__main__':
@ -131,4 +133,4 @@ else:
# Add any commands contained in this module to LLDB # Add any commands contained in this module to LLDB
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
'command script add -f delta.parse_time_log parse_time_log') 'command script add -f delta.parse_time_log parse_time_log')
print 'The "parse_time_log" command is now installed and ready for use, type "parse_time_log --help" for more information' print('The "parse_time_log" command is now installed and ready for use, type "parse_time_log --help" for more information')

View File

@ -4,6 +4,8 @@
# decisions it did and providing some useful context information that can # decisions it did and providing some useful context information that can
# be used for improving the formatter # be used for improving the formatter
from __future__ import print_function
import lldb import lldb
@ -32,7 +34,7 @@ def read_memory(process, location, size):
if x < size - 2: if x < size - 2:
data = data + ":" data = data + ":"
except Exception as e: except Exception as e:
print e print(e)
return data return data
@ -57,7 +59,7 @@ def diagnose_nsstring_Command_Impl(debugger, command, result, internal_dict):
nsstring = frame.EvaluateExpression(command, options) nsstring = frame.EvaluateExpression(command, options)
else: else:
nsstring = target.EvaluateExpression(command, options) nsstring = target.EvaluateExpression(command, options)
print >>result, str(nsstring) print(str(nsstring), file=result)
nsstring_address = nsstring.GetValueAsUnsigned(0) nsstring_address = nsstring.GetValueAsUnsigned(0)
if nsstring_address == 0: if nsstring_address == 0:
return "unable to obtain the string - cannot proceed" return "unable to obtain the string - cannot proceed"
@ -103,7 +105,7 @@ struct $__lldb__CFString {\
expression = expression + "*(($__lldb__CFString*) %d)" % nsstring_address expression = expression + "*(($__lldb__CFString*) %d)" % nsstring_address
# print expression # print expression
dumped = target.EvaluateExpression(expression, options) dumped = target.EvaluateExpression(expression, options)
print >>result, str(dumped) print(str(dumped), file=result)
little_endian = (target.byte_order == lldb.eByteOrderLittle) little_endian = (target.byte_order == lldb.eByteOrderLittle)
ptr_size = target.addr_size ptr_size = target.addr_size
@ -119,8 +121,8 @@ struct $__lldb__CFString {\
lldb.eDynamicCanRunTarget).GetTypeName() == "NSPathStore2") lldb.eDynamicCanRunTarget).GetTypeName() == "NSPathStore2")
has_null = (info_bits & 8) == 8 has_null = (info_bits & 8) == 8
print >>result, "\nInfo=%d\nMutable=%s\nInline=%s\nExplicit=%s\nUnicode=%s\nSpecial=%s\nNull=%s\n" % \ print("\nInfo=%d\nMutable=%s\nInline=%s\nExplicit=%s\nUnicode=%s\nSpecial=%s\nNull=%s\n" % \
(info_bits, "yes" if is_mutable else "no", "yes" if is_inline else "no", "yes" if has_explicit_length else "no", "yes" if is_unicode else "no", "yes" if is_special else "no", "yes" if has_null else "no") (info_bits, "yes" if is_mutable else "no", "yes" if is_inline else "no", "yes" if has_explicit_length else "no", "yes" if is_unicode else "no", "yes" if is_special else "no", "yes" if has_null else "no"), file=result)
explicit_length_offset = 0 explicit_length_offset = 0
if not has_null and has_explicit_length and not is_special: if not has_null and has_explicit_length and not is_special:
@ -135,13 +137,13 @@ struct $__lldb__CFString {\
explicit_length_offset = 0 explicit_length_offset = 0
if explicit_length_offset == 0: if explicit_length_offset == 0:
print >>result, "There is no explicit length marker - skipping this step\n" print("There is no explicit length marker - skipping this step\n", file=result)
else: else:
explicit_length_offset = nsstring_address + explicit_length_offset explicit_length_offset = nsstring_address + explicit_length_offset
explicit_length = process.ReadUnsignedFromMemory( explicit_length = process.ReadUnsignedFromMemory(
explicit_length_offset, 4, error) explicit_length_offset, 4, error)
print >>result, "Explicit length location is at 0x%x - read value is %d\n" % ( print("Explicit length location is at 0x%x - read value is %d\n" % (
explicit_length_offset, explicit_length) explicit_length_offset, explicit_length), file=result)
if is_mutable: if is_mutable:
location = 2 * ptr_size + nsstring_address location = 2 * ptr_size + nsstring_address
@ -152,7 +154,7 @@ struct $__lldb__CFString {\
location = 2 * ptr_size + nsstring_address location = 2 * ptr_size + nsstring_address
if is_inline: if is_inline:
if not has_explicit_length: if not has_explicit_length:
print >>result, "Unicode & Inline & !Explicit is a new combo - no formula for it" print("Unicode & Inline & !Explicit is a new combo - no formula for it", file=result)
else: else:
location += ptr_size location += ptr_size
else: else:
@ -166,18 +168,18 @@ struct $__lldb__CFString {\
else: else:
location = 2 * ptr_size + nsstring_address location = 2 * ptr_size + nsstring_address
location = process.ReadPointerFromMemory(location, error) location = process.ReadPointerFromMemory(location, error)
print >>result, "Expected data location: 0x%x\n" % (location) print("Expected data location: 0x%x\n" % (location), file=result)
print >>result, "1K of data around location: %s\n" % read_memory( print("1K of data around location: %s\n" % read_memory(
process, location, 1024) process, location, 1024), file=result)
print >>result, "5K of data around string pointer: %s\n" % read_memory( print("5K of data around string pointer: %s\n" % read_memory(
process, nsstring_address, 1024 * 5) process, nsstring_address, 1024 * 5), file=result)
def __lldb_init_module(debugger, internal_dict): def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand( debugger.HandleCommand(
"command script add -f %s.diagnose_nsstring_Command_Impl diagnose-nsstring" % "command script add -f %s.diagnose_nsstring_Command_Impl diagnose-nsstring" %
__name__) __name__)
print 'The "diagnose-nsstring" command has been installed, type "help diagnose-nsstring" for detailed help.' print('The "diagnose-nsstring" command has been installed, type "help diagnose-nsstring" for detailed help.')
__lldb_init_module(lldb.debugger, None) __lldb_init_module(lldb.debugger, None)
__lldb_init_module = None __lldb_init_module = None

View File

@ -5,6 +5,7 @@
# information about the stack frames, and tries an alternate unwind # information about the stack frames, and tries an alternate unwind
# algorithm, that will help to understand why lldb's unwind algorithm # algorithm, that will help to understand why lldb's unwind algorithm
# did not succeed. # did not succeed.
from __future__ import print_function
import optparse import optparse
import lldb import lldb
@ -39,7 +40,7 @@ def backtrace_print_frame(target, frame_num, addr, fp):
module_description = '%s %s' % ( module_description = '%s %s' % (
module_filename, module_uuid_str) module_filename, module_uuid_str)
except Exception: except Exception:
print '%2d: pc==0x%-*x fp==0x%-*x' % (frame_num, addr_width, addr_for_printing, addr_width, fp) print('%2d: pc==0x%-*x fp==0x%-*x' % (frame_num, addr_width, addr_for_printing, addr_width, fp))
return return
sym_ctx = target.ResolveSymbolContextForAddress( sym_ctx = target.ResolveSymbolContextForAddress(
@ -47,9 +48,9 @@ def backtrace_print_frame(target, frame_num, addr, fp):
if sym_ctx.IsValid() and sym_ctx.GetSymbol().IsValid(): if sym_ctx.IsValid() and sym_ctx.GetSymbol().IsValid():
function_start = sym_ctx.GetSymbol().GetStartAddress().GetLoadAddress(target) function_start = sym_ctx.GetSymbol().GetStartAddress().GetLoadAddress(target)
offset = addr - function_start offset = addr - function_start
print '%2d: pc==0x%-*x fp==0x%-*x %s %s + %d' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description, sym_ctx.GetSymbol().GetName(), offset) print('%2d: pc==0x%-*x fp==0x%-*x %s %s + %d' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description, sym_ctx.GetSymbol().GetName(), offset))
else: else:
print '%2d: pc==0x%-*x fp==0x%-*x %s' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description) print('%2d: pc==0x%-*x fp==0x%-*x %s' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description))
return sbaddr.GetModule() return sbaddr.GetModule()
# A simple stack walk algorithm that follows the frame chain. # A simple stack walk algorithm that follows the frame chain.
@ -78,7 +79,7 @@ def simple_backtrace(debugger):
this_module = backtrace_print_frame( this_module = backtrace_print_frame(
target, 0, cur_thread.GetFrameAtIndex(0).GetPC(), initial_fp) target, 0, cur_thread.GetFrameAtIndex(0).GetPC(), initial_fp)
print_stack_frame(process, initial_fp) print_stack_frame(process, initial_fp)
print "" print("")
if this_module is not None: if this_module is not None:
module_list.append(this_module) module_list.append(this_module)
if cur_thread.GetNumFrames() < 2: if cur_thread.GetNumFrames() < 2:
@ -94,7 +95,7 @@ def simple_backtrace(debugger):
address_list.append(cur_pc) address_list.append(cur_pc)
this_module = backtrace_print_frame(target, frame_num, cur_pc, cur_fp) this_module = backtrace_print_frame(target, frame_num, cur_pc, cur_fp)
print_stack_frame(process, cur_fp) print_stack_frame(process, cur_fp)
print "" print("")
if this_module is not None: if this_module is not None:
module_list.append(this_module) module_list.append(this_module)
frame_num = frame_num + 1 frame_num = frame_num + 1
@ -119,7 +120,7 @@ def simple_backtrace(debugger):
cur_fp = next_fp cur_fp = next_fp
this_module = backtrace_print_frame(target, frame_num, cur_pc, cur_fp) this_module = backtrace_print_frame(target, frame_num, cur_pc, cur_fp)
print_stack_frame(process, cur_fp) print_stack_frame(process, cur_fp)
print "" print("")
if this_module is not None: if this_module is not None:
module_list.append(this_module) module_list.append(this_module)
return [module_list, address_list] return [module_list, address_list]
@ -139,7 +140,7 @@ def print_stack_frame(process, fp):
addr + (i * addr_size), error) addr + (i * addr_size), error)
outline += " 0x%x" % address outline += " 0x%x" % address
i += 1 i += 1
print outline print(outline)
except Exception: except Exception:
return return
@ -180,39 +181,39 @@ def diagnose_unwind(debugger, command, result, dict):
modules_seen = [] modules_seen = []
addresses_seen = [] addresses_seen = []
print 'LLDB version %s' % debugger.GetVersionString() print('LLDB version %s' % debugger.GetVersionString())
print 'Unwind diagnostics for thread %d' % thread.GetIndexID() print('Unwind diagnostics for thread %d' % thread.GetIndexID())
print "" print("")
print "=============================================================================================" print("=============================================================================================")
print "" print("")
print "OS plugin setting:" print("OS plugin setting:")
debugger.HandleCommand( debugger.HandleCommand(
"settings show target.process.python-os-plugin-path") "settings show target.process.python-os-plugin-path")
print "" print("")
print "Live register context:" print("Live register context:")
thread.SetSelectedFrame(0) thread.SetSelectedFrame(0)
debugger.HandleCommand("register read") debugger.HandleCommand("register read")
print "" print("")
print "=============================================================================================" print("=============================================================================================")
print "" print("")
print "lldb's unwind algorithm:" print("lldb's unwind algorithm:")
print "" print("")
frame_num = 0 frame_num = 0
for frame in thread.frames: for frame in thread.frames:
if not frame.IsInlined(): if not frame.IsInlined():
this_module = backtrace_print_frame( this_module = backtrace_print_frame(
target, frame_num, frame.GetPC(), frame.GetFP()) target, frame_num, frame.GetPC(), frame.GetFP())
print_stack_frame(process, frame.GetFP()) print_stack_frame(process, frame.GetFP())
print "" print("")
if this_module is not None: if this_module is not None:
modules_seen.append(this_module) modules_seen.append(this_module)
addresses_seen.append(frame.GetPC()) addresses_seen.append(frame.GetPC())
frame_num = frame_num + 1 frame_num = frame_num + 1
print "" print("")
print "=============================================================================================" print("=============================================================================================")
print "" print("")
print "Simple stack walk algorithm:" print("Simple stack walk algorithm:")
print "" print("")
(module_list, address_list) = simple_backtrace(debugger) (module_list, address_list) = simple_backtrace(debugger)
if module_list and module_list is not None: if module_list and module_list is not None:
modules_seen += module_list modules_seen += module_list
@ -220,11 +221,11 @@ def diagnose_unwind(debugger, command, result, dict):
addresses_seen = set(addresses_seen) addresses_seen = set(addresses_seen)
addresses_seen.update(set(address_list)) addresses_seen.update(set(address_list))
print "" print("")
print "=============================================================================================" print("=============================================================================================")
print "" print("")
print "Modules seen in stack walks:" print("Modules seen in stack walks:")
print "" print("")
modules_already_seen = set() modules_already_seen = set()
for module in modules_seen: for module in modules_seen:
if module is not None and module.GetFileSpec().GetFilename() is not None: if module is not None and module.GetFileSpec().GetFilename() is not None:
@ -235,18 +236,18 @@ def diagnose_unwind(debugger, command, result, dict):
modules_already_seen.add( modules_already_seen.add(
module.GetFileSpec().GetFilename()) module.GetFileSpec().GetFilename())
print "" print("")
print "=============================================================================================" print("=============================================================================================")
print "" print("")
print "Disassembly ofaddresses seen in stack walks:" print("Disassembly ofaddresses seen in stack walks:")
print "" print("")
additional_addresses_to_disassemble = addresses_seen additional_addresses_to_disassemble = addresses_seen
for frame in thread.frames: for frame in thread.frames:
if not frame.IsInlined(): if not frame.IsInlined():
print "--------------------------------------------------------------------------------------" print("--------------------------------------------------------------------------------------")
print "" print("")
print "Disassembly of %s, frame %d, address 0x%x" % (frame.GetFunctionName(), frame.GetFrameID(), frame.GetPC()) print("Disassembly of %s, frame %d, address 0x%x" % (frame.GetFunctionName(), frame.GetFrameID(), frame.GetPC()))
print "" print("")
if target.triple[ if target.triple[
0:6] == "x86_64" or target.triple[ 0:6] == "x86_64" or target.triple[
0:4] == "i386": 0:4] == "i386":
@ -261,10 +262,10 @@ def diagnose_unwind(debugger, command, result, dict):
frame.GetPC()) frame.GetPC())
for address in list(additional_addresses_to_disassemble): for address in list(additional_addresses_to_disassemble):
print "--------------------------------------------------------------------------------------" print("--------------------------------------------------------------------------------------")
print "" print("")
print "Disassembly of 0x%x" % address print("Disassembly of 0x%x" % address)
print "" print("")
if target.triple[ if target.triple[
0:6] == "x86_64" or target.triple[ 0:6] == "x86_64" or target.triple[
0:4] == "i386": 0:4] == "i386":
@ -273,16 +274,16 @@ def diagnose_unwind(debugger, command, result, dict):
else: else:
debugger.HandleCommand('disassemble -a 0x%x' % address) debugger.HandleCommand('disassemble -a 0x%x' % address)
print "" print("")
print "=============================================================================================" print("=============================================================================================")
print "" print("")
additional_addresses_to_show_unwind = addresses_seen additional_addresses_to_show_unwind = addresses_seen
for frame in thread.frames: for frame in thread.frames:
if not frame.IsInlined(): if not frame.IsInlined():
print "--------------------------------------------------------------------------------------" print("--------------------------------------------------------------------------------------")
print "" print("")
print "Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID()) print("Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID()))
print "" print("")
debugger.HandleCommand( debugger.HandleCommand(
'image show-unwind -a "0x%x"' % frame.GetPC()) 'image show-unwind -a "0x%x"' % frame.GetPC())
if frame.GetPC() in additional_addresses_to_show_unwind: if frame.GetPC() in additional_addresses_to_show_unwind:
@ -290,10 +291,10 @@ def diagnose_unwind(debugger, command, result, dict):
frame.GetPC()) frame.GetPC())
for address in list(additional_addresses_to_show_unwind): for address in list(additional_addresses_to_show_unwind):
print "--------------------------------------------------------------------------------------" print("--------------------------------------------------------------------------------------")
print "" print("")
print "Unwind instructions for 0x%x" % address print("Unwind instructions for 0x%x" % address)
print "" print("")
debugger.HandleCommand( debugger.HandleCommand(
'image show-unwind -a "0x%x"' % address) 'image show-unwind -a "0x%x"' % address)
@ -310,4 +311,4 @@ def create_diagnose_unwind_options():
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
'command script add -f %s.diagnose_unwind diagnose-unwind' % 'command script add -f %s.diagnose_unwind diagnose-unwind' %
__name__) __name__)
print 'The "diagnose-unwind" command has been installed, type "help diagnose-unwind" for detailed help.' print('The "diagnose-unwind" command has been installed, type "help diagnose-unwind" for detailed help.')

View File

@ -71,7 +71,7 @@ def AddLLDBToSysPathOnMacOSX():
lldb_framework_path = GetLLDBFrameworkPath() lldb_framework_path = GetLLDBFrameworkPath()
if lldb_framework_path is None: if lldb_framework_path is None:
print "Couldn't find LLDB.framework" print("Couldn't find LLDB.framework")
sys.exit(-1) sys.exit(-1)
sys.path.append(lldb_framework_path + "/Resources/Python") sys.path.append(lldb_framework_path + "/Resources/Python")
@ -86,13 +86,13 @@ import lldb
debugger = lldb.SBDebugger.Create() debugger = lldb.SBDebugger.Create()
if debugger.IsValid() == False: if debugger.IsValid() == False:
print "Couldn't create an SBDebugger" print("Couldn't create an SBDebugger")
sys.exit(-1) sys.exit(-1)
target = debugger.CreateTargetWithFileAndArch(None, arg_ns.arch) target = debugger.CreateTargetWithFileAndArch(None, arg_ns.arch)
if target.IsValid() == False: if target.IsValid() == False:
print "Couldn't create an SBTarget for architecture " + arg_ns.arch print("Couldn't create an SBTarget for architecture " + arg_ns.arch)
sys.exit(-1) sys.exit(-1)
@ -103,8 +103,8 @@ def ResetLogFile(log_file):
def PrintByteArray(log_file, byte_array): def PrintByteArray(log_file, byte_array):
for byte in byte_array: for byte in byte_array:
print >>log_file, hex(byte) + " ", print(hex(byte) + " ", end=' ', file=log_file)
print >>log_file print(file=log_file)
class SequentialInstructionProvider: class SequentialInstructionProvider:
@ -119,7 +119,7 @@ class SequentialInstructionProvider:
def PrintCurrentState(self, ret): def PrintCurrentState(self, ret):
ResetLogFile(self.m_log_file) ResetLogFile(self.m_log_file)
print >>self.m_log_file, self.m_value print(self.m_value, file=self.m_log_file)
PrintByteArray(self.m_log_file, ret) PrintByteArray(self.m_log_file, ret)
def GetNextInstruction(self): def GetNextInstruction(self):
@ -215,16 +215,16 @@ for inst_bytes in instruction_provider:
remaining_time = float( remaining_time = float(
total_num_instructions - num_instructions_logged) * ( total_num_instructions - num_instructions_logged) * (
float(elapsed_time) / float(num_instructions_logged)) float(elapsed_time) / float(num_instructions_logged))
print str(datetime.timedelta(seconds=remaining_time)) print(str(datetime.timedelta(seconds=remaining_time)))
num_instructions_logged = num_instructions_logged + 1 num_instructions_logged = num_instructions_logged + 1
inst_list = target.GetInstructions(fake_address, inst_bytes) inst_list = target.GetInstructions(fake_address, inst_bytes)
if not inst_list.IsValid(): if not inst_list.IsValid():
print >>log_file, "Invalid instruction list" print("Invalid instruction list", file=log_file)
continue continue
inst = inst_list.GetInstructionAtIndex(0) inst = inst_list.GetInstructionAtIndex(0)
if not inst.IsValid(): if not inst.IsValid():
print >>log_file, "Invalid instruction" print("Invalid instruction", file=log_file)
continue continue
instr_output_stream = lldb.SBStream() instr_output_stream = lldb.SBStream()
inst.GetDescription(instr_output_stream) inst.GetDescription(instr_output_stream)
print >>log_file, instr_output_stream.GetData() print(instr_output_stream.GetData(), file=log_file)

View File

@ -15,12 +15,12 @@ import sys
def disassemble_instructions(insts): def disassemble_instructions(insts):
for i in insts: for i in insts:
print i print(i)
def usage(): def usage():
print "Usage: disasm.py [-n name] executable-image" print("Usage: disasm.py [-n name] executable-image")
print " By default, it breaks at and disassembles the 'main' function." print(" By default, it breaks at and disassembles the 'main' function.")
sys.exit(0) sys.exit(0)
if len(sys.argv) == 2: if len(sys.argv) == 2:
@ -43,7 +43,7 @@ debugger = lldb.SBDebugger.Create()
debugger.SetAsync(False) debugger.SetAsync(False)
# Create a target from a file and arch # Create a target from a file and arch
print "Creating a target for '%s'" % exe print("Creating a target for '%s'" % exe)
target = debugger.CreateTargetWithFileAndArch(exe, lldb.LLDB_ARCH_DEFAULT) target = debugger.CreateTargetWithFileAndArch(exe, lldb.LLDB_ARCH_DEFAULT)
@ -52,7 +52,7 @@ if target:
main_bp = target.BreakpointCreateByName( main_bp = target.BreakpointCreateByName(
fname, target.GetExecutable().GetFilename()) fname, target.GetExecutable().GetFilename())
print main_bp print(main_bp)
# Launch the process. Since we specified synchronous mode, we won't return # Launch the process. Since we specified synchronous mode, we won't return
# from this function until we hit the breakpoint at main # from this function until we hit the breakpoint at main
@ -62,24 +62,24 @@ if target:
if process: if process:
# Print some simple process info # Print some simple process info
state = process.GetState() state = process.GetState()
print process print(process)
if state == lldb.eStateStopped: if state == lldb.eStateStopped:
# Get the first thread # Get the first thread
thread = process.GetThreadAtIndex(0) thread = process.GetThreadAtIndex(0)
if thread: if thread:
# Print some simple thread info # Print some simple thread info
print thread print(thread)
# Get the first frame # Get the first frame
frame = thread.GetFrameAtIndex(0) frame = thread.GetFrameAtIndex(0)
if frame: if frame:
# Print some simple frame info # Print some simple frame info
print frame print(frame)
function = frame.GetFunction() function = frame.GetFunction()
# See if we have debug info (a function) # See if we have debug info (a function)
if function: if function:
# We do have a function, print some info for the # We do have a function, print some info for the
# function # function
print function print(function)
# Now get all instructions for this function and print # Now get all instructions for this function and print
# them # them
insts = function.GetInstructions(target) insts = function.GetInstructions(target)
@ -91,35 +91,35 @@ if target:
if symbol: if symbol:
# We do have a symbol, print some info for the # We do have a symbol, print some info for the
# symbol # symbol
print symbol print(symbol)
# Now get all instructions for this symbol and # Now get all instructions for this symbol and
# print them # print them
insts = symbol.GetInstructions(target) insts = symbol.GetInstructions(target)
disassemble_instructions(insts) disassemble_instructions(insts)
registerList = frame.GetRegisters() registerList = frame.GetRegisters()
print "Frame registers (size of register set = %d):" % registerList.GetSize() print("Frame registers (size of register set = %d):" % registerList.GetSize())
for value in registerList: for value in registerList:
# print value # print value
print "%s (number of children = %d):" % (value.GetName(), value.GetNumChildren()) print("%s (number of children = %d):" % (value.GetName(), value.GetNumChildren()))
for child in value: for child in value:
print "Name: ", child.GetName(), " Value: ", child.GetValue() print("Name: ", child.GetName(), " Value: ", child.GetValue())
print "Hit the breakpoint at main, enter to continue and wait for program to exit or 'Ctrl-D'/'quit' to terminate the program" print("Hit the breakpoint at main, enter to continue and wait for program to exit or 'Ctrl-D'/'quit' to terminate the program")
next = sys.stdin.readline() next = sys.stdin.readline()
if not next or next.rstrip('\n') == 'quit': if not next or next.rstrip('\n') == 'quit':
print "Terminating the inferior process..." print("Terminating the inferior process...")
process.Kill() process.Kill()
else: else:
# Now continue to the program exit # Now continue to the program exit
process.Continue() process.Continue()
# When we return from the above function we will hopefully be at the # When we return from the above function we will hopefully be at the
# program exit. Print out some process info # program exit. Print out some process info
print process print(process)
elif state == lldb.eStateExited: elif state == lldb.eStateExited:
print "Didn't hit the breakpoint at main, program has exited..." print("Didn't hit the breakpoint at main, program has exited...")
else: else:
print "Unexpected process state: %s, killing process..." % debugger.StateAsCString(state) print("Unexpected process state: %s, killing process..." % debugger.StateAsCString(state))
process.Kill() process.Kill()

View File

@ -29,7 +29,7 @@ class FileExtract:
elif b == '<' or b == '>' or b == '@' or b == '=': elif b == '<' or b == '>' or b == '@' or b == '=':
self.byte_order = b self.byte_order = b
else: else:
print "error: invalid byte order specified: '%s'" % b print("error: invalid byte order specified: '%s'" % b)
def is_in_memory(self): def is_in_memory(self):
return False return False

View File

@ -16,11 +16,11 @@ def disassemble(debugger, command, result, dict):
inst_offset = inst_addr - start_addr inst_offset = inst_addr - start_addr
comment = inst.comment comment = inst.comment
if comment: if comment:
print "<%s + %-4u> 0x%x %8s %s ; %s" % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands, comment) print("<%s + %-4u> 0x%x %8s %s ; %s" % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands, comment))
else: else:
print "<%s + %-4u> 0x%x %8s %s" % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands) print("<%s + %-4u> 0x%x %8s %s" % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands))
# Install the command when the module gets imported # Install the command when the module gets imported
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
'command script add -f gdb_disassemble.disassemble gdb-disassemble') 'command script add -f gdb_disassemble.disassemble gdb-disassemble')
print 'Installed "gdb-disassemble" command for disassembly' print('Installed "gdb-disassemble" command for disassembly')

View File

@ -299,7 +299,7 @@ def stop_gdb_log(debugger, command, result, dict):
options.symbolicator = lldb.utils.symbolication.Symbolicator() options.symbolicator = lldb.utils.symbolication.Symbolicator()
options.symbolicator.target = lldb.target options.symbolicator.target = lldb.target
else: else:
print "error: can't symbolicate without a target" print("error: can't symbolicate without a target")
if not g_log_file: if not g_log_file:
result.PutCString( result.PutCString(
@ -314,7 +314,7 @@ def stop_gdb_log(debugger, command, result, dict):
else: else:
result.PutCString(usage) result.PutCString(usage)
else: else:
print 'error: the GDB packet log file "%s" does not exist' % g_log_file print('error: the GDB packet log file "%s" does not exist' % g_log_file)
def is_hex_byte(str): def is_hex_byte(str):
@ -584,11 +584,11 @@ def get_thread_from_thread_suffix(str):
def cmd_qThreadStopInfo(options, cmd, args): def cmd_qThreadStopInfo(options, cmd, args):
packet = Packet(args) packet = Packet(args)
tid = packet.get_hex_uint('big') tid = packet.get_hex_uint('big')
print "get_thread_stop_info (tid = 0x%x)" % (tid) print("get_thread_stop_info (tid = 0x%x)" % (tid))
def cmd_stop_reply(options, cmd, args): def cmd_stop_reply(options, cmd, args):
print "get_last_stop_info()" print("get_last_stop_info()")
return False return False
@ -611,69 +611,69 @@ def rsp_stop_reply(options, cmd, cmd_args, rsp):
elif key == 'jthreads' or key == 'jstopinfo': elif key == 'jthreads' or key == 'jstopinfo':
key_value_pair[1] = binascii.unhexlify(key_value_pair[1]) key_value_pair[1] = binascii.unhexlify(key_value_pair[1])
key_value_pairs.insert(0, ['signal', signo]) key_value_pairs.insert(0, ['signal', signo])
print 'stop_reply():' print('stop_reply():')
dump_key_value_pairs(key_value_pairs) dump_key_value_pairs(key_value_pairs)
elif stop_type == 'W': elif stop_type == 'W':
exit_status = packet.get_hex_uint8() exit_status = packet.get_hex_uint8()
print 'stop_reply(): exit (status=%i)' % exit_status print('stop_reply(): exit (status=%i)' % exit_status)
elif stop_type == 'O': elif stop_type == 'O':
print 'stop_reply(): stdout = "%s"' % packet.str print('stop_reply(): stdout = "%s"' % packet.str)
def cmd_unknown_packet(options, cmd, args): def cmd_unknown_packet(options, cmd, args):
if args: if args:
print "cmd: %s, args: %s", cmd, args print("cmd: %s, args: %s", cmd, args)
else: else:
print "cmd: %s", cmd print("cmd: %s", cmd)
return False return False
def cmd_qSymbol(options, cmd, args): def cmd_qSymbol(options, cmd, args):
if args == ':': if args == ':':
print 'ready to serve symbols' print('ready to serve symbols')
else: else:
packet = Packet(args) packet = Packet(args)
symbol_addr = packet.get_hex_uint('big') symbol_addr = packet.get_hex_uint('big')
if symbol_addr is None: if symbol_addr is None:
if packet.skip_exact_string(':'): if packet.skip_exact_string(':'):
symbol_name = packet.get_hex_ascii_str() symbol_name = packet.get_hex_ascii_str()
print 'lookup_symbol("%s") -> symbol not available yet' % (symbol_name) print('lookup_symbol("%s") -> symbol not available yet' % (symbol_name))
else: else:
print 'error: bad command format' print('error: bad command format')
else: else:
if packet.skip_exact_string(':'): if packet.skip_exact_string(':'):
symbol_name = packet.get_hex_ascii_str() symbol_name = packet.get_hex_ascii_str()
print 'lookup_symbol("%s") -> 0x%x' % (symbol_name, symbol_addr) print('lookup_symbol("%s") -> 0x%x' % (symbol_name, symbol_addr))
else: else:
print 'error: bad command format' print('error: bad command format')
def cmd_QSetWithHexString(options, cmd, args): def cmd_QSetWithHexString(options, cmd, args):
print '%s("%s")' % (cmd[:-1], binascii.unhexlify(args)) print('%s("%s")' % (cmd[:-1], binascii.unhexlify(args)))
def cmd_QSetWithString(options, cmd, args): def cmd_QSetWithString(options, cmd, args):
print '%s("%s")' % (cmd[:-1], args) print('%s("%s")' % (cmd[:-1], args))
def cmd_QSetWithUnsigned(options, cmd, args): def cmd_QSetWithUnsigned(options, cmd, args):
print '%s(%i)' % (cmd[:-1], int(args)) print('%s(%i)' % (cmd[:-1], int(args)))
def rsp_qSymbol(options, cmd, cmd_args, rsp): def rsp_qSymbol(options, cmd, cmd_args, rsp):
if len(rsp) == 0: if len(rsp) == 0:
print "Unsupported" print("Unsupported")
else: else:
if rsp == "OK": if rsp == "OK":
print "No more symbols to lookup" print("No more symbols to lookup")
else: else:
packet = Packet(rsp) packet = Packet(rsp)
if packet.skip_exact_string("qSymbol:"): if packet.skip_exact_string("qSymbol:"):
symbol_name = packet.get_hex_ascii_str() symbol_name = packet.get_hex_ascii_str()
print 'lookup_symbol("%s")' % (symbol_name) print('lookup_symbol("%s")' % (symbol_name))
else: else:
print 'error: response string should start with "qSymbol:": respnse is "%s"' % (rsp) print('error: response string should start with "qSymbol:": respnse is "%s"' % (rsp))
def cmd_qXfer(options, cmd, args): def cmd_qXfer(options, cmd, args):
# $qXfer:features:read:target.xml:0,1ffff#14 # $qXfer:features:read:target.xml:0,1ffff#14
print "read target special data %s" % (args) print("read target special data %s" % (args))
return True return True
@ -710,12 +710,12 @@ def rsp_qXfer(options, cmd, cmd_args, rsp):
reg_info.info[ reg_info.info[
'bitsize'] = reg_element.attrib['bitsize'] 'bitsize'] = reg_element.attrib['bitsize']
g_register_infos.append(reg_info) g_register_infos.append(reg_info)
print 'XML for "%s":' % (data[2]) print('XML for "%s":' % (data[2]))
ET.dump(xml_root) ET.dump(xml_root)
def cmd_A(options, cmd, args): def cmd_A(options, cmd, args):
print 'launch process:' print('launch process:')
packet = Packet(args) packet = Packet(args)
while True: while True:
arg_len = packet.get_number() arg_len = packet.get_number()
@ -729,50 +729,50 @@ def cmd_A(options, cmd, args):
if not packet.skip_exact_string(','): if not packet.skip_exact_string(','):
break break
arg_value = packet.get_hex_ascii_str(arg_len) arg_value = packet.get_hex_ascii_str(arg_len)
print 'argv[%u] = "%s"' % (arg_idx, arg_value) print('argv[%u] = "%s"' % (arg_idx, arg_value))
def cmd_qC(options, cmd, args): def cmd_qC(options, cmd, args):
print "query_current_thread_id()" print("query_current_thread_id()")
def rsp_qC(options, cmd, cmd_args, rsp): def rsp_qC(options, cmd, cmd_args, rsp):
packet = Packet(rsp) packet = Packet(rsp)
if packet.skip_exact_string("QC"): if packet.skip_exact_string("QC"):
tid = packet.get_thread_id() tid = packet.get_thread_id()
print "current_thread_id = %#x" % (tid) print("current_thread_id = %#x" % (tid))
else: else:
print "current_thread_id = old thread ID" print("current_thread_id = old thread ID")
def cmd_query_packet(options, cmd, args): def cmd_query_packet(options, cmd, args):
if args: if args:
print "%s%s" % (cmd, args) print("%s%s" % (cmd, args))
else: else:
print "%s" % (cmd) print("%s" % (cmd))
return False return False
def rsp_ok_error(rsp): def rsp_ok_error(rsp):
print "rsp: ", rsp print("rsp: ", rsp)
def rsp_ok_means_supported(options, cmd, cmd_args, rsp): def rsp_ok_means_supported(options, cmd, cmd_args, rsp):
if rsp == 'OK': if rsp == 'OK':
print "%s%s is supported" % (cmd, cmd_args) print("%s%s is supported" % (cmd, cmd_args))
elif rsp == '': elif rsp == '':
print "%s%s is not supported" % (cmd, cmd_args) print("%s%s is not supported" % (cmd, cmd_args))
else: else:
print "%s%s -> %s" % (cmd, cmd_args, rsp) print("%s%s -> %s" % (cmd, cmd_args, rsp))
def rsp_ok_means_success(options, cmd, cmd_args, rsp): def rsp_ok_means_success(options, cmd, cmd_args, rsp):
if rsp == 'OK': if rsp == 'OK':
print "success" print("success")
elif rsp == '': elif rsp == '':
print "%s%s is not supported" % (cmd, cmd_args) print("%s%s is not supported" % (cmd, cmd_args))
else: else:
print "%s%s -> %s" % (cmd, cmd_args, rsp) print("%s%s -> %s" % (cmd, cmd_args, rsp))
def dump_key_value_pairs(key_value_pairs): def dump_key_value_pairs(key_value_pairs):
@ -786,42 +786,42 @@ def dump_key_value_pairs(key_value_pairs):
value = key_value_pair[1] value = key_value_pair[1]
unhex_value = get_hex_string_if_all_printable(value) unhex_value = get_hex_string_if_all_printable(value)
if unhex_value: if unhex_value:
print "%*s = %s (%s)" % (max_key_len, key, value, unhex_value) print("%*s = %s (%s)" % (max_key_len, key, value, unhex_value))
else: else:
print "%*s = %s" % (max_key_len, key, value) print("%*s = %s" % (max_key_len, key, value))
def rsp_dump_key_value_pairs(options, cmd, cmd_args, rsp): def rsp_dump_key_value_pairs(options, cmd, cmd_args, rsp):
if rsp: if rsp:
print '%s response:' % (cmd) print('%s response:' % (cmd))
packet = Packet(rsp) packet = Packet(rsp)
key_value_pairs = packet.get_key_value_pairs() key_value_pairs = packet.get_key_value_pairs()
dump_key_value_pairs(key_value_pairs) dump_key_value_pairs(key_value_pairs)
else: else:
print "not supported" print("not supported")
def cmd_c(options, cmd, args): def cmd_c(options, cmd, args):
print "continue()" print("continue()")
return False return False
def cmd_s(options, cmd, args): def cmd_s(options, cmd, args):
print "step()" print("step()")
return False return False
def cmd_qSpeedTest(options, cmd, args): def cmd_qSpeedTest(options, cmd, args):
print("qSpeedTest: cmd='%s', args='%s'" % (cmd, args)) print(("qSpeedTest: cmd='%s', args='%s'" % (cmd, args)))
def rsp_qSpeedTest(options, cmd, cmd_args, rsp): def rsp_qSpeedTest(options, cmd, cmd_args, rsp):
print("qSpeedTest: rsp='%s' cmd='%s', args='%s'" % (rsp, cmd, args)) print(("qSpeedTest: rsp='%s' cmd='%s', args='%s'" % (rsp, cmd, args)))
def cmd_vCont(options, cmd, args): def cmd_vCont(options, cmd, args):
if args == '?': if args == '?':
print "%s: get supported extended continue modes" % (cmd) print("%s: get supported extended continue modes" % (cmd))
else: else:
got_other_threads = 0 got_other_threads = 0
s = '' s = ''
@ -846,9 +846,9 @@ def cmd_vCont(options, cmd, args):
else: else:
s += 'thread 0x%4.4x: %s' % (tid, action) s += 'thread 0x%4.4x: %s' % (tid, action)
if got_other_threads: if got_other_threads:
print "extended_continue (%s)" % (s) print("extended_continue (%s)" % (s))
else: else:
print "extended_continue (%s, other-threads: suspend)" % (s) print("extended_continue (%s, other-threads: suspend)" % (s))
return False return False
@ -874,47 +874,47 @@ def rsp_vCont(options, cmd, cmd_args, rsp):
s += 'stop' s += 'stop'
# else: # else:
# s += 'unrecognized vCont mode: ', str(mode) # s += 'unrecognized vCont mode: ', str(mode)
print s print(s)
elif rsp: elif rsp:
if rsp[0] == 'T' or rsp[0] == 'S' or rsp[0] == 'W' or rsp[0] == 'X': if rsp[0] == 'T' or rsp[0] == 'S' or rsp[0] == 'W' or rsp[0] == 'X':
rsp_stop_reply(options, cmd, cmd_args, rsp) rsp_stop_reply(options, cmd, cmd_args, rsp)
return return
if rsp[0] == 'O': if rsp[0] == 'O':
print "stdout: %s" % (rsp) print("stdout: %s" % (rsp))
return return
else: else:
print "not supported (cmd = '%s', args = '%s', rsp = '%s')" % (cmd, cmd_args, rsp) print("not supported (cmd = '%s', args = '%s', rsp = '%s')" % (cmd, cmd_args, rsp))
def cmd_vAttach(options, cmd, args): def cmd_vAttach(options, cmd, args):
(extra_command, args) = string.split(args, ';') (extra_command, args) = string.split(args, ';')
if extra_command: if extra_command:
print "%s%s(%s)" % (cmd, extra_command, args) print("%s%s(%s)" % (cmd, extra_command, args))
else: else:
print "attach(pid = %u)" % int(args, 16) print("attach(pid = %u)" % int(args, 16))
return False return False
def cmd_qRegisterInfo(options, cmd, args): def cmd_qRegisterInfo(options, cmd, args):
print 'query_register_info(reg_num=%i)' % (int(args, 16)) print('query_register_info(reg_num=%i)' % (int(args, 16)))
return False return False
def rsp_qRegisterInfo(options, cmd, cmd_args, rsp): def rsp_qRegisterInfo(options, cmd, cmd_args, rsp):
global g_max_register_info_name_len global g_max_register_info_name_len
print 'query_register_info(reg_num=%i):' % (int(cmd_args, 16)), print('query_register_info(reg_num=%i):' % (int(cmd_args, 16)), end=' ')
if len(rsp) == 3 and rsp[0] == 'E': if len(rsp) == 3 and rsp[0] == 'E':
g_max_register_info_name_len = 0 g_max_register_info_name_len = 0
for reg_info in g_register_infos: for reg_info in g_register_infos:
name_len = len(reg_info.name()) name_len = len(reg_info.name())
if g_max_register_info_name_len < name_len: if g_max_register_info_name_len < name_len:
g_max_register_info_name_len = name_len g_max_register_info_name_len = name_len
print' DONE' print(' DONE')
else: else:
packet = Packet(rsp) packet = Packet(rsp)
reg_info = RegisterInfo(packet.get_key_value_pairs()) reg_info = RegisterInfo(packet.get_key_value_pairs())
g_register_infos.append(reg_info) g_register_infos.append(reg_info)
print reg_info print(reg_info)
return False return False
@ -923,7 +923,7 @@ def cmd_qThreadInfo(options, cmd, args):
query_type = 'first' query_type = 'first'
else: else:
query_type = 'subsequent' query_type = 'subsequent'
print 'get_current_thread_list(type=%s)' % (query_type) print('get_current_thread_list(type=%s)' % (query_type))
return False return False
@ -934,20 +934,20 @@ def rsp_qThreadInfo(options, cmd, cmd_args, rsp):
tids = packet.split_hex(';', 'big') tids = packet.split_hex(';', 'big')
for i, tid in enumerate(tids): for i, tid in enumerate(tids):
if i: if i:
print ',', print(',', end=' ')
print '0x%x' % (tid), print('0x%x' % (tid), end=' ')
print print()
elif response_type == 'l': elif response_type == 'l':
print 'END' print('END')
def rsp_hex_big_endian(options, cmd, cmd_args, rsp): def rsp_hex_big_endian(options, cmd, cmd_args, rsp):
if rsp == '': if rsp == '':
print "%s%s is not supported" % (cmd, cmd_args) print("%s%s is not supported" % (cmd, cmd_args))
else: else:
packet = Packet(rsp) packet = Packet(rsp)
uval = packet.get_hex_uint('big') uval = packet.get_hex_uint('big')
print '%s: 0x%x' % (cmd, uval) print('%s: 0x%x' % (cmd, uval))
def cmd_read_mem_bin(options, cmd, args): def cmd_read_mem_bin(options, cmd, args):
@ -956,7 +956,7 @@ def cmd_read_mem_bin(options, cmd, args):
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
comma = packet.get_char() comma = packet.get_char()
size = packet.get_hex_uint('big') size = packet.get_hex_uint('big')
print 'binary_read_memory (addr = 0x%16.16x, size = %u)' % (addr, size) print('binary_read_memory (addr = 0x%16.16x, size = %u)' % (addr, size))
return False return False
@ -965,7 +965,7 @@ def rsp_mem_bin_bytes(options, cmd, cmd_args, rsp):
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
comma = packet.get_char() comma = packet.get_char()
size = packet.get_hex_uint('big') size = packet.get_hex_uint('big')
print 'memory:' print('memory:')
if size > 0: if size > 0:
dump_hex_memory_buffer(addr, rsp) dump_hex_memory_buffer(addr, rsp)
@ -975,7 +975,7 @@ def cmd_read_memory(options, cmd, args):
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
comma = packet.get_char() comma = packet.get_char()
size = packet.get_hex_uint('big') size = packet.get_hex_uint('big')
print 'read_memory (addr = 0x%16.16x, size = %u)' % (addr, size) print('read_memory (addr = 0x%16.16x, size = %u)' % (addr, size))
return False return False
@ -987,10 +987,10 @@ def dump_hex_memory_buffer(addr, hex_byte_str):
while uval is not None: while uval is not None:
if ((idx % 16) == 0): if ((idx % 16) == 0):
if ascii: if ascii:
print ' ', ascii print(' ', ascii)
ascii = '' ascii = ''
print '0x%x:' % (addr + idx), print('0x%x:' % (addr + idx), end=' ')
print '%2.2x' % (uval), print('%2.2x' % (uval), end=' ')
if 0x20 <= uval and uval < 0x7f: if 0x20 <= uval and uval < 0x7f:
ascii += '%c' % uval ascii += '%c' % uval
else: else:
@ -998,7 +998,7 @@ def dump_hex_memory_buffer(addr, hex_byte_str):
uval = packet.get_hex_uint8() uval = packet.get_hex_uint8()
idx = idx + 1 idx = idx + 1
if ascii: if ascii:
print ' ', ascii print(' ', ascii)
ascii = '' ascii = ''
@ -1006,13 +1006,13 @@ def cmd_write_memory(options, cmd, args):
packet = Packet(args) packet = Packet(args)
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
if packet.get_char() != ',': if packet.get_char() != ',':
print 'error: invalid write memory command (missing comma after address)' print('error: invalid write memory command (missing comma after address)')
return return
size = packet.get_hex_uint('big') size = packet.get_hex_uint('big')
if packet.get_char() != ':': if packet.get_char() != ':':
print 'error: invalid write memory command (missing colon after size)' print('error: invalid write memory command (missing colon after size)')
return return
print 'write_memory (addr = 0x%16.16x, size = %u, data:' % (addr, size) print('write_memory (addr = 0x%16.16x, size = %u, data:' % (addr, size))
dump_hex_memory_buffer(addr, packet.str) dump_hex_memory_buffer(addr, packet.str)
return False return False
@ -1021,25 +1021,25 @@ def cmd_alloc_memory(options, cmd, args):
packet = Packet(args) packet = Packet(args)
byte_size = packet.get_hex_uint('big') byte_size = packet.get_hex_uint('big')
if packet.get_char() != ',': if packet.get_char() != ',':
print 'error: invalid allocate memory command (missing comma after address)' print('error: invalid allocate memory command (missing comma after address)')
return return
print 'allocate_memory (byte-size = %u (0x%x), permissions = %s)' % (byte_size, byte_size, packet.str) print('allocate_memory (byte-size = %u (0x%x), permissions = %s)' % (byte_size, byte_size, packet.str))
return False return False
def rsp_alloc_memory(options, cmd, cmd_args, rsp): def rsp_alloc_memory(options, cmd, cmd_args, rsp):
packet = Packet(rsp) packet = Packet(rsp)
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
print 'addr = 0x%x' % addr print('addr = 0x%x' % addr)
def cmd_dealloc_memory(options, cmd, args): def cmd_dealloc_memory(options, cmd, args):
packet = Packet(args) packet = Packet(args)
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
if packet.get_char() != ',': if packet.get_char() != ',':
print 'error: invalid allocate memory command (missing comma after address)' print('error: invalid allocate memory command (missing comma after address)')
else: else:
print 'deallocate_memory (addr = 0x%x, permissions = %s)' % (addr, packet.str) print('deallocate_memory (addr = 0x%x, permissions = %s)' % (addr, packet.str))
return False return False
@ -1085,21 +1085,21 @@ def cmd_read_one_reg(options, cmd, args):
if tid is not None: if tid is not None:
s += ', tid = 0x%4.4x' % (tid) s += ', tid = 0x%4.4x' % (tid)
s += ')' s += ')'
print s print(s)
return False return False
def rsp_read_one_reg(options, cmd, cmd_args, rsp): def rsp_read_one_reg(options, cmd, cmd_args, rsp):
packet = Packet(cmd_args) packet = Packet(cmd_args)
reg_num = packet.get_hex_uint('big') reg_num = packet.get_hex_uint('big')
print get_register_name_equal_value(options, reg_num, rsp) print(get_register_name_equal_value(options, reg_num, rsp))
def cmd_write_one_reg(options, cmd, args): def cmd_write_one_reg(options, cmd, args):
packet = Packet(args) packet = Packet(args)
reg_num = packet.get_hex_uint('big') reg_num = packet.get_hex_uint('big')
if packet.get_char() != '=': if packet.get_char() != '=':
print 'error: invalid register write packet' print('error: invalid register write packet')
else: else:
name = None name = None
hex_value_str = packet.get_hex_chars() hex_value_str = packet.get_hex_chars()
@ -1112,7 +1112,7 @@ def cmd_write_one_reg(options, cmd, args):
if tid is not None: if tid is not None:
s += ', tid = 0x%4.4x' % (tid) s += ', tid = 0x%4.4x' % (tid)
s += ')' s += ')'
print s print(s)
return False return False
@ -1122,7 +1122,7 @@ def dump_all_regs(packet):
hex_value_str = packet.get_hex_chars(nibble_size) hex_value_str = packet.get_hex_chars(nibble_size)
if hex_value_str is not None: if hex_value_str is not None:
value = reg_info.get_value_from_hex_string(hex_value_str) value = reg_info.get_value_from_hex_string(hex_value_str)
print '%*s = %s' % (g_max_register_info_name_len, reg_info.name(), value) print('%*s = %s' % (g_max_register_info_name_len, reg_info.name(), value))
else: else:
return return
@ -1132,9 +1132,9 @@ def cmd_read_all_regs(cmd, cmd_args):
packet.get_char() # toss the 'g' command character packet.get_char() # toss the 'g' command character
tid = get_thread_from_thread_suffix(packet.str) tid = get_thread_from_thread_suffix(packet.str)
if tid is not None: if tid is not None:
print 'read_all_register(thread = 0x%4.4x)' % tid print('read_all_register(thread = 0x%4.4x)' % tid)
else: else:
print 'read_all_register()' print('read_all_register()')
return False return False
@ -1145,7 +1145,7 @@ def rsp_read_all_regs(options, cmd, cmd_args, rsp):
def cmd_write_all_regs(options, cmd, args): def cmd_write_all_regs(options, cmd, args):
packet = Packet(args) packet = Packet(args)
print 'write_all_registers()' print('write_all_registers()')
dump_all_regs(packet) dump_all_regs(packet)
return False return False
@ -1165,7 +1165,7 @@ def cmd_bp(options, cmd, args):
bp_size = packet.get_hex_uint('big') bp_size = packet.get_hex_uint('big')
s += g_bp_types[bp_type] s += g_bp_types[bp_type]
s += " (addr = 0x%x, size = %u)" % (bp_addr, bp_size) s += " (addr = 0x%x, size = %u)" % (bp_addr, bp_size)
print s print(s)
return False return False
@ -1173,22 +1173,22 @@ def cmd_mem_rgn_info(options, cmd, args):
packet = Packet(args) packet = Packet(args)
packet.get_char() # skip ':' character packet.get_char() # skip ':' character
addr = packet.get_hex_uint('big') addr = packet.get_hex_uint('big')
print 'get_memory_region_info (addr=0x%x)' % (addr) print('get_memory_region_info (addr=0x%x)' % (addr))
return False return False
def cmd_kill(options, cmd, args): def cmd_kill(options, cmd, args):
print 'kill_process()' print('kill_process()')
return False return False
def cmd_jThreadsInfo(options, cmd, args): def cmd_jThreadsInfo(options, cmd, args):
print 'jThreadsInfo()' print('jThreadsInfo()')
return False return False
def cmd_jGetLoadedDynamicLibrariesInfos(options, cmd, args): def cmd_jGetLoadedDynamicLibrariesInfos(options, cmd, args):
print 'jGetLoadedDynamicLibrariesInfos()' print('jGetLoadedDynamicLibrariesInfos()')
return False return False
@ -1210,9 +1210,9 @@ def decode_packet(s, start_index=0):
def rsp_json(options, cmd, cmd_args, rsp): def rsp_json(options, cmd, cmd_args, rsp):
print '%s() reply:' % (cmd) print('%s() reply:' % (cmd))
json_tree = json.loads(rsp) json_tree = json.loads(rsp)
print json.dumps(json_tree, indent=4, separators=(',', ': ')) print(json.dumps(json_tree, indent=4, separators=(',', ': ')))
def rsp_jGetLoadedDynamicLibrariesInfos(options, cmd, cmd_args, rsp): def rsp_jGetLoadedDynamicLibrariesInfos(options, cmd, cmd_args, rsp):
@ -1387,26 +1387,26 @@ def parse_gdb_log(file, options):
packet = m.group('packet') packet = m.group('packet')
sys.stdout.write(options.colors.green()) sys.stdout.write(options.colors.green())
if not options.quiet and not hide_next_response: if not options.quiet and not hide_next_response:
print '# ', line print('# ', line)
sys.stdout.write(options.colors.reset()) sys.stdout.write(options.colors.reset())
# print 'direction = "%s", packet = "%s"' % (direction, packet) # print 'direction = "%s", packet = "%s"' % (direction, packet)
if packet[0] == '+': if packet[0] == '+':
if is_command: if is_command:
print '-->', print('-->', end=' ')
else: else:
print '<--', print('<--', end=' ')
if not options.quiet: if not options.quiet:
print 'ACK' print('ACK')
continue continue
elif packet[0] == '-': elif packet[0] == '-':
if is_command: if is_command:
print '-->', print('-->', end=' ')
else: else:
print '<--', print('<--', end=' ')
if not options.quiet: if not options.quiet:
print 'NACK' print('NACK')
continue continue
elif packet[0] == '$': elif packet[0] == '$':
m = packet_contents_name_regex.match(packet) m = packet_contents_name_regex.match(packet)
@ -1415,7 +1415,7 @@ def parse_gdb_log(file, options):
idx = line_index + 1 idx = line_index + 1
while idx < num_lines: while idx < num_lines:
if not options.quiet and not hide_next_response: if not options.quiet and not hide_next_response:
print '# ', lines[idx] print('# ', lines[idx])
multiline_packet += lines[idx] multiline_packet += lines[idx]
m = packet_contents_name_regex.match(multiline_packet) m = packet_contents_name_regex.match(multiline_packet)
if m: if m:
@ -1426,9 +1426,9 @@ def parse_gdb_log(file, options):
idx += 1 idx += 1
if m: if m:
if is_command: if is_command:
print '-->', print('-->', end=' ')
else: else:
print '<--', print('<--', end=' ')
contents = decode_packet(m.group(1)) contents = decode_packet(m.group(1))
if is_command: if is_command:
hide_next_response = False hide_next_response = False
@ -1458,11 +1458,11 @@ def parse_gdb_log(file, options):
gdb_remote_commands[last_command]['rsp']( gdb_remote_commands[last_command]['rsp'](
options, last_command, last_command_args, contents) options, last_command, last_command_args, contents)
else: else:
print 'error: invalid packet: "', packet, '"' print('error: invalid packet: "', packet, '"')
else: else:
print '???' print('???')
else: else:
print '## ', line print('## ', line)
match = timestamp_regex.match(line) match = timestamp_regex.match(line)
if match: if match:
curr_time = float(match.group(2)) curr_time = float(match.group(2))
@ -1491,16 +1491,16 @@ def parse_gdb_log(file, options):
min_time = delta min_time = delta
if not options or not options.quiet: if not options or not options.quiet:
print '%s%.6f %+.6f%s' % (match.group(1), print('%s%.6f %+.6f%s' % (match.group(1),
curr_time - base_time, curr_time - base_time,
delta, delta,
match.group(3)) match.group(3)))
last_time = curr_time last_time = curr_time
# else: # else:
# print line # print line
(average, std_dev) = calculate_mean_and_standard_deviation(all_packet_times) (average, std_dev) = calculate_mean_and_standard_deviation(all_packet_times)
if average and std_dev: if average and std_dev:
print '%u packets with average packet time of %f and standard deviation of %f' % (len(all_packet_times), average, std_dev) print('%u packets with average packet time of %f and standard deviation of %f' % (len(all_packet_times), average, std_dev))
if packet_total_times: if packet_total_times:
total_packet_time = 0.0 total_packet_time = 0.0
total_packet_count = 0 total_packet_count = 0
@ -1512,14 +1512,14 @@ def parse_gdb_log(file, options):
for key, vvv in packet_counts.items(): for key, vvv in packet_counts.items():
total_packet_count += vvv total_packet_count += vvv
print '#------------------------------------------------------------' print('#------------------------------------------------------------')
print '# Packet timing summary:' print('# Packet timing summary:')
print '# Totals: time = %6f, count = %6d' % (total_packet_time, print('# Totals: time = %6f, count = %6d' % (total_packet_time,
total_packet_count) total_packet_count))
print '# Min packet time: time = %6f' % (min_time) print('# Min packet time: time = %6f' % (min_time))
print '#------------------------------------------------------------' print('#------------------------------------------------------------')
print '# Packet Time (sec) Percent Count Latency' print('# Packet Time (sec) Percent Count Latency')
print '#------------------------- ----------- ------- ------ -------' print('#------------------------- ----------- ------- ------ -------')
if options and options.sort_count: if options and options.sort_count:
res = sorted( res = sorted(
packet_counts, packet_counts,
@ -1537,9 +1537,9 @@ def parse_gdb_log(file, options):
packet_percent = ( packet_percent = (
packet_total_time / total_packet_time) * 100.0 packet_total_time / total_packet_time) * 100.0
packet_count = packet_counts[item] packet_count = packet_counts[item]
print " %24s %11.6f %5.2f%% %6d %9.6f" % ( print(" %24s %11.6f %5.2f%% %6d %9.6f" % (
item, packet_total_time, packet_percent, packet_count, item, packet_total_time, packet_percent, packet_count,
float(packet_total_time) / float(packet_count)) float(packet_total_time) / float(packet_count)))
if options.plot: if options.plot:
plot_latencies(packet_times) plot_latencies(packet_times)
@ -1593,7 +1593,7 @@ if __name__ == '__main__':
try: try:
(options, args) = parser.parse_args(sys.argv[1:]) (options, args) = parser.parse_args(sys.argv[1:])
except: except:
print 'error: argument error' print('error: argument error')
sys.exit(1) sys.exit(1)
options.colors = TerminalColors(options.color) options.colors = TerminalColors(options.color)
@ -1603,18 +1603,18 @@ if __name__ == '__main__':
lldb.debugger = lldb.SBDebugger.Create() lldb.debugger = lldb.SBDebugger.Create()
import lldb.macosx.crashlog import lldb.macosx.crashlog
options.symbolicator = lldb.macosx.crashlog.CrashLog(options.crashlog) options.symbolicator = lldb.macosx.crashlog.CrashLog(options.crashlog)
print '%s' % (options.symbolicator) print('%s' % (options.symbolicator))
# This script is being run from the command line, create a debugger in case we are # This script is being run from the command line, create a debugger in case we are
# going to use any debugger functions in our function. # going to use any debugger functions in our function.
if len(args): if len(args):
for file in args: for file in args:
print '#----------------------------------------------------------------------' print('#----------------------------------------------------------------------')
print "# GDB remote log file: '%s'" % file print("# GDB remote log file: '%s'" % file)
print '#----------------------------------------------------------------------' print('#----------------------------------------------------------------------')
parse_gdb_log_file(file, options) parse_gdb_log_file(file, options)
if options.symbolicator: if options.symbolicator:
print '%s' % (options.symbolicator) print('%s' % (options.symbolicator))
else: else:
parse_gdb_log(sys.stdin, options) parse_gdb_log(sys.stdin, options)
@ -1627,4 +1627,4 @@ else:
'command script add -f gdbremote.start_gdb_log start_gdb_log') 'command script add -f gdbremote.start_gdb_log start_gdb_log')
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
'command script add -f gdbremote.stop_gdb_log stop_gdb_log') 'command script add -f gdbremote.stop_gdb_log stop_gdb_log')
print 'The "start_gdb_log" and "stop_gdb_log" commands are now installed and ready for use, type "start_gdb_log --help" or "stop_gdb_log --help" for more information' print('The "start_gdb_log" and "stop_gdb_log" commands are now installed and ready for use, type "start_gdb_log --help" or "stop_gdb_log --help" for more information')

View File

@ -7,6 +7,7 @@
# For the shells sh, bash: # For the shells sh, bash:
# PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python ./globals.py <path> [<path> ...] # PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python ./globals.py <path> [<path> ...]
#---------------------------------------------------------------------- #----------------------------------------------------------------------
from __future__ import print_function
import lldb import lldb
import commands import commands
@ -46,22 +47,22 @@ def get_globals(raw_path, options):
# Print results for anything that matched # Print results for anything that matched
for global_variable in global_variable_list: for global_variable in global_variable_list:
# returns the global variable name as a string # returns the global variable name as a string
print 'name = %s' % global_variable.name print('name = %s' % global_variable.name)
# Returns the variable value as a string # Returns the variable value as a string
print 'value = %s' % global_variable.value print('value = %s' % global_variable.value)
print 'type = %s' % global_variable.type # Returns an lldb.SBType object print('type = %s' % global_variable.type) # Returns an lldb.SBType object
# Returns an lldb.SBAddress (section offset # Returns an lldb.SBAddress (section offset
# address) for this global # address) for this global
print 'addr = %s' % global_variable.addr print('addr = %s' % global_variable.addr)
# Returns the file virtual address for this # Returns the file virtual address for this
# global # global
print 'file_addr = 0x%x' % global_variable.addr.file_addr print('file_addr = 0x%x' % global_variable.addr.file_addr)
# returns the global variable value as a string # returns the global variable value as a string
print 'location = %s' % global_variable.location print('location = %s' % global_variable.location)
# Returns the size in bytes of this global # Returns the size in bytes of this global
# variable # variable
print 'size = %s' % global_variable.size print('size = %s' % global_variable.size)
print print()
def globals(command_args): def globals(command_args):

View File

@ -1,3 +1,5 @@
from __future__ import print_function
import lldb import lldb
import re import re
@ -193,4 +195,4 @@ if lldb.debugger:
# Module is being run inside the LLDB interpreter # Module is being run inside the LLDB interpreter
jump.__doc__ = usage_string() jump.__doc__ = usage_string()
lldb.debugger.HandleCommand('command script add -f jump.jump jump') lldb.debugger.HandleCommand('command script add -f jump.jump jump')
print 'The "jump" command has been installed, type "help jump" or "jump <ENTER>" for detailed help.' print('The "jump" command has been installed, type "help jump" or "jump <ENTER>" for detailed help.')

View File

@ -1,4 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import lldb import lldb
import optparse import optparse
@ -61,14 +62,14 @@ class DumpLineTables:
result.SetError('no module found that matches "%s".' % (module_path)) result.SetError('no module found that matches "%s".' % (module_path))
return return
num_cus = module.GetNumCompileUnits() num_cus = module.GetNumCompileUnits()
print >>result, 'Module: "%s"' % (module.file.fullpath), print('Module: "%s"' % (module.file.fullpath), end=' ', file=result)
if num_cus == 0: if num_cus == 0:
print >>result, 'no debug info.' print('no debug info.', file=result)
continue continue
print >>result, 'has %u compile units:' % (num_cus) print('has %u compile units:' % (num_cus), file=result)
for cu_idx in range(num_cus): for cu_idx in range(num_cus):
cu = module.GetCompileUnitAtIndex(cu_idx) cu = module.GetCompileUnitAtIndex(cu_idx)
print >>result, ' Compile Unit: %s' % (cu.file.fullpath) print(' Compile Unit: %s' % (cu.file.fullpath), file=result)
for line_idx in range(cu.GetNumLineEntries()): for line_idx in range(cu.GetNumLineEntries()):
line_entry = cu.GetLineEntryAtIndex(line_idx) line_entry = cu.GetLineEntryAtIndex(line_idx)
start_file_addr = line_entry.addr.file_addr start_file_addr = line_entry.addr.file_addr
@ -163,19 +164,19 @@ path when setting breakpoints.
result.SetError('no module found that matches "%s".' % (module_path)) result.SetError('no module found that matches "%s".' % (module_path))
return return
num_cus = module.GetNumCompileUnits() num_cus = module.GetNumCompileUnits()
print >>result, 'Module: "%s"' % (module.file.fullpath), print('Module: "%s"' % (module.file.fullpath), end=' ', file=result)
if num_cus == 0: if num_cus == 0:
print >>result, 'no debug info.' print('no debug info.', file=result)
continue continue
print >>result, 'has %u compile units:' % (num_cus) print('has %u compile units:' % (num_cus), file=result)
for i in range(num_cus): for i in range(num_cus):
cu = module.GetCompileUnitAtIndex(i) cu = module.GetCompileUnitAtIndex(i)
print >>result, ' Compile Unit: %s' % (cu.file.fullpath) print(' Compile Unit: %s' % (cu.file.fullpath), file=result)
if options.support_files: if options.support_files:
num_support_files = cu.GetNumSupportFiles() num_support_files = cu.GetNumSupportFiles()
for j in range(num_support_files): for j in range(num_support_files):
path = cu.GetSupportFileAtIndex(j).fullpath path = cu.GetSupportFileAtIndex(j).fullpath
print >>result, ' file[%u]: %s' % (j, path) print(' file[%u]: %s' % (j, path), file=result)
def __lldb_init_module(debugger, dict): def __lldb_init_module(debugger, dict):
@ -187,5 +188,5 @@ def __lldb_init_module(debugger, dict):
DumpLineTables.command_name)) DumpLineTables.command_name))
debugger.HandleCommand( debugger.HandleCommand(
'command script add -c %s.DumpFiles %s' % (__name__, DumpFiles.command_name)) 'command script add -c %s.DumpFiles %s' % (__name__, DumpFiles.command_name))
print 'The "%s" and "%s" commands have been installed.' % (DumpLineTables.command_name, print('The "%s" and "%s" commands have been installed.' % (DumpLineTables.command_name,
DumpFiles.command_name) DumpFiles.command_name))

View File

@ -539,19 +539,19 @@ def tk_variable_display(debugger, command, result, dict):
sys.argv = ['tk-variables'] sys.argv = ['tk-variables']
target = debugger.GetSelectedTarget() target = debugger.GetSelectedTarget()
if not target: if not target:
print >>result, "invalid target" print("invalid target", file=result)
return return
process = target.GetProcess() process = target.GetProcess()
if not process: if not process:
print >>result, "invalid process" print("invalid process", file=result)
return return
thread = process.GetSelectedThread() thread = process.GetSelectedThread()
if not thread: if not thread:
print >>result, "invalid thread" print("invalid thread", file=result)
return return
frame = thread.GetSelectedFrame() frame = thread.GetSelectedFrame()
if not frame: if not frame:
print >>result, "invalid frame" print("invalid frame", file=result)
return return
# Parse command line args # Parse command line args
command_args = shlex.split(command) command_args = shlex.split(command)
@ -573,11 +573,11 @@ def tk_process_display(debugger, command, result, dict):
sys.argv = ['tk-process'] sys.argv = ['tk-process']
target = debugger.GetSelectedTarget() target = debugger.GetSelectedTarget()
if not target: if not target:
print >>result, "invalid target" print("invalid target", file=result)
return return
process = target.GetProcess() process = target.GetProcess()
if not process: if not process:
print >>result, "invalid process" print("invalid process", file=result)
return return
# Parse command line args # Parse command line args
columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0}, columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0},
@ -598,7 +598,7 @@ def tk_target_display(debugger, command, result, dict):
sys.argv = ['tk-target'] sys.argv = ['tk-target']
target = debugger.GetSelectedTarget() target = debugger.GetSelectedTarget()
if not target: if not target:
print >>result, "invalid target" print("invalid target", file=result)
return return
# Parse command line args # Parse command line args
columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0}, columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0},

View File

@ -1,4 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import cmd import cmd
import dict_utils import dict_utils
@ -187,11 +188,11 @@ def dump_memory(base_addr, data, hex_bytes_len, num_per_line):
while i < hex_bytes_len: while i < hex_bytes_len:
if ((i / 2) % num_per_line) == 0: if ((i / 2) % num_per_line) == 0:
if i > 0: if i > 0:
print ' %s' % (ascii_str) print(' %s' % (ascii_str))
ascii_str = '' ascii_str = ''
print '0x%8.8x:' % (addr + i), print('0x%8.8x:' % (addr + i), end=' ')
hex_byte = hex_bytes[i:i + 2] hex_byte = hex_bytes[i:i + 2]
print hex_byte, print(hex_byte, end=' ')
int_byte = int(hex_byte, 16) int_byte = int(hex_byte, 16)
ascii_char = '%c' % (int_byte) ascii_char = '%c' % (int_byte)
if int_byte >= 32 and int_byte < 127: if int_byte >= 32 and int_byte < 127:
@ -204,8 +205,8 @@ def dump_memory(base_addr, data, hex_bytes_len, num_per_line):
padding = num_per_line - ((i / 2) % num_per_line) padding = num_per_line - ((i / 2) % num_per_line)
else: else:
padding = 0 padding = 0
print '%*s%s' % (padding * 3 + 1, '', ascii_str) print('%*s%s' % (padding * 3 + 1, '', ascii_str))
print print()
class TerminalColors: class TerminalColors:
@ -371,11 +372,11 @@ def dump_hex_bytes(addr, s, bytes_per_line=16):
for ch in s: for ch in s:
if (i % bytes_per_line) == 0: if (i % bytes_per_line) == 0:
if line: if line:
print line print(line)
line = '%#8.8x: ' % (addr + i) line = '%#8.8x: ' % (addr + i)
line += "%02X " % ord(ch) line += "%02X " % ord(ch)
i += 1 i += 1
print line print(line)
def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16): def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16):
@ -404,7 +405,7 @@ def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16):
mismatch = ch_a != ch_b mismatch = ch_a != ch_b
if (i % bytes_per_line) == 0: if (i % bytes_per_line) == 0:
if line: if line:
print line print(line)
line = '%#8.8x: ' % (addr + i) line = '%#8.8x: ' % (addr + i)
if mismatch: if mismatch:
line += tty_colors.red() line += tty_colors.red()
@ -413,7 +414,7 @@ def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16):
line += tty_colors.default() line += tty_colors.default()
i += 1 i += 1
print line print(line)
class Mach: class Mach:
@ -533,11 +534,11 @@ class Mach:
# f.close() # f.close()
except IOError as xxx_todo_changeme: except IOError as xxx_todo_changeme:
(errno, strerror) = xxx_todo_changeme.args (errno, strerror) = xxx_todo_changeme.args
print "I/O error({0}): {1}".format(errno, strerror) print("I/O error({0}): {1}".format(errno, strerror))
except ValueError: except ValueError:
print "Could not convert data to an integer." print("Could not convert data to an integer.")
except: except:
print "Unexpected error:", sys.exc_info()[0] print("Unexpected error:", sys.exc_info()[0])
raise raise
def compare(self, rhs): def compare(self, rhs):
@ -625,56 +626,56 @@ class Mach:
self.archs[i].mach.unpack(data, skinny_magic) self.archs[i].mach.unpack(data, skinny_magic)
def compare(self, rhs): def compare(self, rhs):
print 'error: comparing two universal files is not supported yet' print('error: comparing two universal files is not supported yet')
return False return False
def dump(self, options): def dump(self, options):
if options.dump_header: if options.dump_header:
print print()
print "Universal Mach File: magic = %s, nfat_arch = %u" % (self.magic, self.nfat_arch) print("Universal Mach File: magic = %s, nfat_arch = %u" % (self.magic, self.nfat_arch))
print print()
if self.nfat_arch > 0: if self.nfat_arch > 0:
if options.dump_header: if options.dump_header:
self.archs[0].dump_header(True, options) self.archs[0].dump_header(True, options)
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].dump_flat(options) self.archs[i].dump_flat(options)
if options.dump_header: if options.dump_header:
print print()
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].mach.dump(options) self.archs[i].mach.dump(options)
def dump_header(self, dump_description=True, options=None): def dump_header(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].mach.dump_header(True, options) self.archs[i].mach.dump_header(True, options)
print print()
def dump_load_commands(self, dump_description=True, options=None): def dump_load_commands(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].mach.dump_load_commands(True, options) self.archs[i].mach.dump_load_commands(True, options)
print print()
def dump_sections(self, dump_description=True, options=None): def dump_sections(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].mach.dump_sections(True, options) self.archs[i].mach.dump_sections(True, options)
print print()
def dump_section_contents(self, options): def dump_section_contents(self, options):
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].mach.dump_section_contents(options) self.archs[i].mach.dump_section_contents(options)
print print()
def dump_symtab(self, dump_description=True, options=None): def dump_symtab(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
self.archs[i].mach.dump_symtab(True, options) self.archs[i].mach.dump_symtab(True, options)
print print()
def dump_symbol_names_matching_regex(self, regex, file=None): def dump_symbol_names_matching_regex(self, regex, file=None):
for i in range(self.nfat_arch): for i in range(self.nfat_arch):
@ -698,24 +699,24 @@ class Mach:
def dump_header(self, dump_description=True, options=None): def dump_header(self, dump_description=True, options=None):
if options.verbose: if options.verbose:
print "CPU SUBTYPE OFFSET SIZE ALIGN" print("CPU SUBTYPE OFFSET SIZE ALIGN")
print "---------- ---------- ---------- ---------- ----------" print("---------- ---------- ---------- ---------- ----------")
else: else:
print "ARCH FILEOFFSET FILESIZE ALIGN" print("ARCH FILEOFFSET FILESIZE ALIGN")
print "---------- ---------- ---------- ----------" print("---------- ---------- ---------- ----------")
def dump_flat(self, options): def dump_flat(self, options):
if options.verbose: if options.verbose:
print "%#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (self.arch.cpu, self.arch.sub, self.offset, self.size, self.align) print("%#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (self.arch.cpu, self.arch.sub, self.offset, self.size, self.align))
else: else:
print "%-10s %#8.8x %#8.8x %#8.8x" % (self.arch, self.offset, self.size, self.align) print("%-10s %#8.8x %#8.8x %#8.8x" % (self.arch, self.offset, self.size, self.align))
def dump(self): def dump(self):
print " cputype: %#8.8x" % self.arch.cpu print(" cputype: %#8.8x" % self.arch.cpu)
print "cpusubtype: %#8.8x" % self.arch.sub print("cpusubtype: %#8.8x" % self.arch.sub)
print " offset: %#8.8x" % self.offset print(" offset: %#8.8x" % self.offset)
print " size: %#8.8x" % self.size print(" size: %#8.8x" % self.size)
print " align: %#8.8x" % self.align print(" align: %#8.8x" % self.align)
def __str__(self): def __str__(self):
return "Mach.Universal.ArchInfo: %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % ( return "Mach.Universal.ArchInfo: %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (
@ -906,21 +907,21 @@ class Mach:
return lc return lc
def compare(self, rhs): def compare(self, rhs):
print "\nComparing:" print("\nComparing:")
print "a) %s %s" % (self.arch, self.path) print("a) %s %s" % (self.arch, self.path))
print "b) %s %s" % (rhs.arch, rhs.path) print("b) %s %s" % (rhs.arch, rhs.path))
result = True result = True
if self.type == rhs.type: if self.type == rhs.type:
for lhs_section in self.sections[1:]: for lhs_section in self.sections[1:]:
rhs_section = rhs.get_section_by_section(lhs_section) rhs_section = rhs.get_section_by_section(lhs_section)
if rhs_section: if rhs_section:
print 'comparing %s.%s...' % (lhs_section.segname, lhs_section.sectname), print('comparing %s.%s...' % (lhs_section.segname, lhs_section.sectname), end=' ')
sys.stdout.flush() sys.stdout.flush()
lhs_data = lhs_section.get_contents(self) lhs_data = lhs_section.get_contents(self)
rhs_data = rhs_section.get_contents(rhs) rhs_data = rhs_section.get_contents(rhs)
if lhs_data and rhs_data: if lhs_data and rhs_data:
if lhs_data == rhs_data: if lhs_data == rhs_data:
print 'ok' print('ok')
else: else:
lhs_data_len = len(lhs_data) lhs_data_len = len(lhs_data)
rhs_data_len = len(rhs_data) rhs_data_len = len(rhs_data)
@ -938,51 +939,51 @@ class Mach:
# result = False # result = False
# else: # else:
result = False result = False
print 'error: sections differ' print('error: sections differ')
# print 'a) %s' % (lhs_section) # print 'a) %s' % (lhs_section)
# dump_hex_byte_string_diff(0, lhs_data, rhs_data) # dump_hex_byte_string_diff(0, lhs_data, rhs_data)
# print 'b) %s' % (rhs_section) # print 'b) %s' % (rhs_section)
# dump_hex_byte_string_diff(0, rhs_data, lhs_data) # dump_hex_byte_string_diff(0, rhs_data, lhs_data)
elif lhs_data and not rhs_data: elif lhs_data and not rhs_data:
print 'error: section data missing from b:' print('error: section data missing from b:')
print 'a) %s' % (lhs_section) print('a) %s' % (lhs_section))
print 'b) %s' % (rhs_section) print('b) %s' % (rhs_section))
result = False result = False
elif not lhs_data and rhs_data: elif not lhs_data and rhs_data:
print 'error: section data missing from a:' print('error: section data missing from a:')
print 'a) %s' % (lhs_section) print('a) %s' % (lhs_section))
print 'b) %s' % (rhs_section) print('b) %s' % (rhs_section))
result = False result = False
elif lhs_section.offset or rhs_section.offset: elif lhs_section.offset or rhs_section.offset:
print 'error: section data missing for both a and b:' print('error: section data missing for both a and b:')
print 'a) %s' % (lhs_section) print('a) %s' % (lhs_section))
print 'b) %s' % (rhs_section) print('b) %s' % (rhs_section))
result = False result = False
else: else:
print 'ok' print('ok')
else: else:
result = False result = False
print 'error: section %s is missing in %s' % (lhs_section.sectname, rhs.path) print('error: section %s is missing in %s' % (lhs_section.sectname, rhs.path))
else: else:
print 'error: comaparing a %s mach-o file with a %s mach-o file is not supported' % (self.type, rhs.type) print('error: comaparing a %s mach-o file with a %s mach-o file is not supported' % (self.type, rhs.type))
result = False result = False
if not result: if not result:
print 'error: mach files differ' print('error: mach files differ')
return result return result
def dump_header(self, dump_description=True, options=None): def dump_header(self, dump_description=True, options=None):
if options.verbose: if options.verbose:
print "MAGIC CPU SUBTYPE FILETYPE NUM CMDS SIZE CMDS FLAGS" print("MAGIC CPU SUBTYPE FILETYPE NUM CMDS SIZE CMDS FLAGS")
print "---------- ---------- ---------- ---------- -------- ---------- ----------" print("---------- ---------- ---------- ---------- -------- ---------- ----------")
else: else:
print "MAGIC ARCH FILETYPE NUM CMDS SIZE CMDS FLAGS" print("MAGIC ARCH FILETYPE NUM CMDS SIZE CMDS FLAGS")
print "------------ ---------- -------------- -------- ---------- ----------" print("------------ ---------- -------------- -------- ---------- ----------")
def dump_flat(self, options): def dump_flat(self, options):
if options.verbose: if options.verbose:
print "%#8.8x %#8.8x %#8.8x %#8.8x %#8u %#8.8x %#8.8x" % (self.magic, self.arch.cpu, self.arch.sub, self.filetype.value, self.ncmds, self.sizeofcmds, self.flags.bits) print("%#8.8x %#8.8x %#8.8x %#8.8x %#8u %#8.8x %#8.8x" % (self.magic, self.arch.cpu, self.arch.sub, self.filetype.value, self.ncmds, self.sizeofcmds, self.flags.bits))
else: else:
print "%-12s %-10s %-14s %#8u %#8.8x %s" % (self.magic, self.arch, self.filetype, self.ncmds, self.sizeofcmds, self.flags) print("%-12s %-10s %-14s %#8u %#8.8x %s" % (self.magic, self.arch, self.filetype, self.ncmds, self.sizeofcmds, self.flags))
def dump(self, options): def dump(self, options):
if options.dump_header: if options.dump_header:
@ -998,27 +999,27 @@ class Mach:
if len(self.symbols): if len(self.symbols):
self.dump_sections(False, options) self.dump_sections(False, options)
else: else:
print "No symbols" print("No symbols")
if options.find_mangled: if options.find_mangled:
self.dump_symbol_names_matching_regex(re.compile('^_?_Z')) self.dump_symbol_names_matching_regex(re.compile('^_?_Z'))
def dump_header(self, dump_description=True, options=None): def dump_header(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
print "Mach Header" print("Mach Header")
print " magic: %#8.8x %s" % (self.magic.value, self.magic) print(" magic: %#8.8x %s" % (self.magic.value, self.magic))
print " cputype: %#8.8x %s" % (self.arch.cpu, self.arch) print(" cputype: %#8.8x %s" % (self.arch.cpu, self.arch))
print " cpusubtype: %#8.8x" % self.arch.sub print(" cpusubtype: %#8.8x" % self.arch.sub)
print " filetype: %#8.8x %s" % (self.filetype.get_enum_value(), self.filetype.get_enum_name()) print(" filetype: %#8.8x %s" % (self.filetype.get_enum_value(), self.filetype.get_enum_name()))
print " ncmds: %#8.8x %u" % (self.ncmds, self.ncmds) print(" ncmds: %#8.8x %u" % (self.ncmds, self.ncmds))
print " sizeofcmds: %#8.8x" % self.sizeofcmds print(" sizeofcmds: %#8.8x" % self.sizeofcmds)
print " flags: %#8.8x %s" % (self.flags.bits, self.flags) print(" flags: %#8.8x %s" % (self.flags.bits, self.flags))
def dump_load_commands(self, dump_description=True, options=None): def dump_load_commands(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
for lc in self.commands: for lc in self.commands:
print lc print(lc)
def get_section_by_name(self, name): def get_section_by_name(self, name):
for section in self.sections: for section in self.sections:
@ -1034,12 +1035,12 @@ class Mach:
def dump_sections(self, dump_description=True, options=None): def dump_sections(self, dump_description=True, options=None):
if dump_description: if dump_description:
print self.description() print(self.description())
num_sections = len(self.sections) num_sections = len(self.sections)
if num_sections > 1: if num_sections > 1:
self.sections[1].dump_header() self.sections[1].dump_header()
for sect_idx in range(1, num_sections): for sect_idx in range(1, num_sections):
print "%s" % self.sections[sect_idx] print("%s" % self.sections[sect_idx])
def dump_section_contents(self, options): def dump_section_contents(self, options):
saved_section_to_disk = False saved_section_to_disk = False
@ -1075,19 +1076,19 @@ class Mach:
data.seek(data_offset) data.seek(data_offset)
outfile.write(data.read_size(data_size)) outfile.write(data.read_size(data_size))
else: else:
print "Saving section %s to '%s'" % (sectname, options.outfile) print("Saving section %s to '%s'" % (sectname, options.outfile))
outfile.write(sect_bytes) outfile.write(sect_bytes)
outfile.close() outfile.close()
saved_section_to_disk = True saved_section_to_disk = True
else: else:
print "error: you can only save a single section to disk at a time, skipping section '%s'" % (sectname) print("error: you can only save a single section to disk at a time, skipping section '%s'" % (sectname))
else: else:
print 'section %s:\n' % (sectname) print('section %s:\n' % (sectname))
section.dump_header() section.dump_header()
print '%s\n' % (section) print('%s\n' % (section))
dump_memory(0, sect_bytes, options.max_count, 16) dump_memory(0, sect_bytes, options.max_count, 16)
else: else:
print 'error: no section named "%s" was found' % (sectname) print('error: no section named "%s" was found' % (sectname))
def get_segment(self, segname): def get_segment(self, segname):
if len(self.segments) == 1 and self.segments[0].segname == '': if len(self.segments) == 1 and self.segments[0].segname == '':
@ -1125,20 +1126,20 @@ class Mach:
nlist.unpack(self, self.data, lc_symtab) nlist.unpack(self, self.data, lc_symtab)
self.symbols.append(nlist) self.symbols.append(nlist)
else: else:
print "no LC_SYMTAB" print("no LC_SYMTAB")
def dump_symtab(self, dump_description=True, options=None): def dump_symtab(self, dump_description=True, options=None):
self.get_symtab() self.get_symtab()
if dump_description: if dump_description:
print self.description() print(self.description())
for i, symbol in enumerate(self.symbols): for i, symbol in enumerate(self.symbols):
print '[%5u] %s' % (i, symbol) print('[%5u] %s' % (i, symbol))
def dump_symbol_names_matching_regex(self, regex, file=None): def dump_symbol_names_matching_regex(self, regex, file=None):
self.get_symtab() self.get_symtab()
for symbol in self.symbols: for symbol in self.symbols:
if symbol.name and regex.search(symbol.name): if symbol.name and regex.search(symbol.name):
print symbol.name print(symbol.name)
if file: if file:
file.write('%s\n' % (symbol.name)) file.write('%s\n' % (symbol.name))
@ -1247,11 +1248,11 @@ class Mach:
def dump_header(self): def dump_header(self):
if self.is_64: if self.is_64:
print "INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 RESERVED3 NAME" print("INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 RESERVED3 NAME")
print "===== ------------------ ------------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------" print("===== ------------------ ------------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------")
else: else:
print "INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 NAME" print("INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 NAME")
print "===== ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------" print("===== ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------")
def __str__(self): def __str__(self):
if self.is_64: if self.is_64:
@ -1682,7 +1683,7 @@ class Mach:
def default(self, line): def default(self, line):
'''Catch all for unknown command, which will exit the interpreter.''' '''Catch all for unknown command, which will exit the interpreter.'''
print "uknown command: %s" % line print("uknown command: %s" % line)
return True return True
def do_q(self, line): def do_q(self, line):
@ -1813,10 +1814,10 @@ if __name__ == '__main__':
(options, mach_files) = parser.parse_args() (options, mach_files) = parser.parse_args()
if options.extract_modules: if options.extract_modules:
if options.section_names: if options.section_names:
print "error: can't use --section option with the --extract-modules option" print("error: can't use --section option with the --extract-modules option")
exit(1) exit(1)
if not options.outfile: if not options.outfile:
print "error: the --output=FILE option must be specified with the --extract-modules option" print("error: the --output=FILE option must be specified with the --extract-modules option")
exit(1) exit(1)
options.section_names.append("__apple_ast") options.section_names.append("__apple_ast")
if options.compare: if options.compare:
@ -1827,14 +1828,14 @@ if __name__ == '__main__':
mach_b.parse(mach_files[1]) mach_b.parse(mach_files[1])
mach_a.compare(mach_b) mach_a.compare(mach_b)
else: else:
print 'error: --compare takes two mach files as arguments' print('error: --compare takes two mach files as arguments')
else: else:
if not (options.dump_header or options.dump_load_commands or options.dump_symtab or options.dump_sections or options.find_mangled or options.section_names): if not (options.dump_header or options.dump_load_commands or options.dump_symtab or options.dump_sections or options.find_mangled or options.section_names):
options.dump_header = True options.dump_header = True
options.dump_load_commands = True options.dump_load_commands = True
if options.verbose: if options.verbose:
print 'options', options print('options', options)
print 'mach_files', mach_files print('mach_files', mach_files)
for path in mach_files: for path in mach_files:
mach = Mach() mach = Mach()
mach.parse(path) mach.parse(path)

View File

@ -10,6 +10,8 @@
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import commands import commands
from __future__ import print_function
import platform import platform
import os import os
import re import re
@ -44,11 +46,11 @@ except ImportError:
except ImportError: except ImportError:
pass pass
else: else:
print 'imported lldb from: "%s"' % (lldb_python_dir) print('imported lldb from: "%s"' % (lldb_python_dir))
success = True success = True
break break
if not success: 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) sys.exit(1)
import commands import commands
@ -197,9 +199,9 @@ def memfind_command(debugger, command, result, dict):
def print_error(str, show_usage, result): def print_error(str, show_usage, result):
print >>result, str print(str, file=result)
if show_usage: if show_usage:
print >>result, create_memfind_options().format_help() print(create_memfind_options().format_help(), file=result)
def memfind(target, options, args, result): def memfind(target, options, args, result):
@ -233,44 +235,44 @@ def memfind(target, options, args, result):
return return
if not options.data: if not options.data:
print >>result, 'error: no data specified to search for' print('error: no data specified to search for', file=result)
return return
if not target: if not target:
print >>result, 'error: invalid target' print('error: invalid target', file=result)
return return
process = target.process process = target.process
if not process: if not process:
print >>result, 'error: invalid process' print('error: invalid process', file=result)
return return
error = lldb.SBError() error = lldb.SBError()
bytes = process.ReadMemory(start_addr, options.size, error) bytes = process.ReadMemory(start_addr, options.size, error)
if error.Success(): if error.Success():
num_matches = 0 num_matches = 0
print >>result, "Searching memory range [%#x - %#x) for" % ( print("Searching memory range [%#x - %#x) for" % (
start_addr, end_addr), start_addr, end_addr), end=' ', file=result)
for byte in options.data: for byte in options.data:
print >>result, '%2.2x' % ord(byte), print('%2.2x' % ord(byte), end=' ', file=result)
print >>result print(file=result)
match_index = string.find(bytes, options.data) match_index = string.find(bytes, options.data)
while match_index != -1: while match_index != -1:
num_matches = num_matches + 1 num_matches = num_matches + 1
print >>result, '%#x: %#x + %u' % (start_addr + print('%#x: %#x + %u' % (start_addr +
match_index, start_addr, match_index) match_index, start_addr, match_index), file=result)
match_index = string.find(bytes, options.data, match_index + 1) match_index = string.find(bytes, options.data, match_index + 1)
if num_matches == 0: if num_matches == 0:
print >>result, "error: no matches found" print("error: no matches found", file=result)
else: else:
print >>result, 'error: %s' % (error.GetCString()) print('error: %s' % (error.GetCString()), file=result)
if __name__ == '__main__': if __name__ == '__main__':
print 'error: this script is designed to be used within the embedded script interpreter in LLDB' print('error: this script is designed to be used within the embedded script interpreter in LLDB')
elif getattr(lldb, 'debugger', None): elif getattr(lldb, 'debugger', None):
memfind_command.__doc__ = create_memfind_options().format_help() memfind_command.__doc__ = create_memfind_options().format_help()
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
'command script add -f memory.memfind_command memfind') 'command script add -f memory.memfind_command memfind')
print '"memfind" command installed, use the "--help" option for detailed help' print('"memfind" command installed, use the "--help" option for detailed help')

View File

@ -9,6 +9,8 @@
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import commands import commands
from __future__ import print_function
import optparse import optparse
import os import os
import platform import platform
@ -50,11 +52,11 @@ except ImportError:
except ImportError: except ImportError:
pass pass
else: else:
print 'imported lldb from: "%s"' % (lldb_python_dir) print('imported lldb from: "%s"' % (lldb_python_dir))
success = True success = True
break break
if not success: 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) sys.exit(1)
@ -179,7 +181,7 @@ class TestCase:
error = lldb.SBError() error = lldb.SBError()
self.process = self.target.Launch(self.launch_info, error) self.process = self.target.Launch(self.launch_info, error)
if not error.Success(): if not error.Success():
print "error: %s" % error.GetCString() print("error: %s" % error.GetCString())
if self.process: if self.process:
self.process.GetBroadcaster().AddListener(self.listener, self.process.GetBroadcaster().AddListener(self.listener,
lldb.SBProcess.eBroadcastBitStateChanged | lldb.SBProcess.eBroadcastBitInterrupt) lldb.SBProcess.eBroadcastBitStateChanged | lldb.SBProcess.eBroadcastBitInterrupt)
@ -194,7 +196,7 @@ class TestCase:
if self.listener.WaitForEvent(lldb.UINT32_MAX, process_event): if self.listener.WaitForEvent(lldb.UINT32_MAX, process_event):
state = lldb.SBProcess.GetStateFromEvent(process_event) state = lldb.SBProcess.GetStateFromEvent(process_event)
if self.verbose: if self.verbose:
print "event = %s" % (lldb.SBDebugger.StateAsCString(state)) print("event = %s" % (lldb.SBDebugger.StateAsCString(state)))
if lldb.SBProcess.GetRestartedFromEvent(process_event): if lldb.SBProcess.GetRestartedFromEvent(process_event):
continue continue
if state == lldb.eStateInvalid or state == lldb.eStateDetached or state == lldb.eStateCrashed or state == lldb.eStateUnloaded or state == lldb.eStateExited: if state == lldb.eStateInvalid or state == lldb.eStateDetached or state == lldb.eStateCrashed or state == lldb.eStateUnloaded or state == lldb.eStateExited:
@ -213,46 +215,46 @@ class TestCase:
stop_reason = thread.GetStopReason() stop_reason = thread.GetStopReason()
if self.verbose: if self.verbose:
print "tid = %#x pc = %#x " % (thread.GetThreadID(), frame.GetPC()), print("tid = %#x pc = %#x " % (thread.GetThreadID(), frame.GetPC()), end=' ')
if stop_reason == lldb.eStopReasonNone: if stop_reason == lldb.eStopReasonNone:
if self.verbose: if self.verbose:
print "none" print("none")
elif stop_reason == lldb.eStopReasonTrace: elif stop_reason == lldb.eStopReasonTrace:
select_thread = True select_thread = True
if self.verbose: if self.verbose:
print "trace" print("trace")
elif stop_reason == lldb.eStopReasonPlanComplete: elif stop_reason == lldb.eStopReasonPlanComplete:
select_thread = True select_thread = True
if self.verbose: if self.verbose:
print "plan complete" print("plan complete")
elif stop_reason == lldb.eStopReasonThreadExiting: elif stop_reason == lldb.eStopReasonThreadExiting:
if self.verbose: if self.verbose:
print "thread exiting" print("thread exiting")
elif stop_reason == lldb.eStopReasonExec: elif stop_reason == lldb.eStopReasonExec:
if self.verbose: if self.verbose:
print "exec" print("exec")
elif stop_reason == lldb.eStopReasonInvalid: elif stop_reason == lldb.eStopReasonInvalid:
if self.verbose: if self.verbose:
print "invalid" print("invalid")
elif stop_reason == lldb.eStopReasonException: elif stop_reason == lldb.eStopReasonException:
select_thread = True select_thread = True
if self.verbose: if self.verbose:
print "exception" print("exception")
fatal = True fatal = True
elif stop_reason == lldb.eStopReasonBreakpoint: elif stop_reason == lldb.eStopReasonBreakpoint:
select_thread = True select_thread = True
bp_id = thread.GetStopReasonDataAtIndex(0) bp_id = thread.GetStopReasonDataAtIndex(0)
bp_loc_id = thread.GetStopReasonDataAtIndex(1) bp_loc_id = thread.GetStopReasonDataAtIndex(1)
if self.verbose: if self.verbose:
print "breakpoint id = %d.%d" % (bp_id, bp_loc_id) print("breakpoint id = %d.%d" % (bp_id, bp_loc_id))
elif stop_reason == lldb.eStopReasonWatchpoint: elif stop_reason == lldb.eStopReasonWatchpoint:
select_thread = True select_thread = True
if self.verbose: if self.verbose:
print "watchpoint id = %d" % (thread.GetStopReasonDataAtIndex(0)) print("watchpoint id = %d" % (thread.GetStopReasonDataAtIndex(0)))
elif stop_reason == lldb.eStopReasonSignal: elif stop_reason == lldb.eStopReasonSignal:
select_thread = True select_thread = True
if self.verbose: if self.verbose:
print "signal %d" % (thread.GetStopReasonDataAtIndex(0)) print("signal %d" % (thread.GetStopReasonDataAtIndex(0)))
if select_thread and not selected_thread: if select_thread and not selected_thread:
self.thread = thread self.thread = thread
@ -339,7 +341,7 @@ class TesterTestCase(TestCase):
def BreakpointHit(self, thread): def BreakpointHit(self, thread):
bp_id = thread.GetStopReasonDataAtIndex(0) bp_id = thread.GetStopReasonDataAtIndex(0)
loc_id = thread.GetStopReasonDataAtIndex(1) loc_id = thread.GetStopReasonDataAtIndex(1)
print "Breakpoint %i.%i hit: %s" % (bp_id, loc_id, thread.process.target.FindBreakpointByID(bp_id)) print("Breakpoint %i.%i hit: %s" % (bp_id, loc_id, thread.process.target.FindBreakpointByID(bp_id)))
thread.StepOver() thread.StepOver()
def PlanComplete(self, thread): def PlanComplete(self, thread):
@ -374,9 +376,9 @@ class TesterTestCase(TestCase):
while not self.done: while not self.done:
self.WaitForNextProcessEvent() self.WaitForNextProcessEvent()
else: else:
print "error: failed to launch process" print("error: failed to launch process")
else: else:
print "error: failed to create target with '%s'" % (args[0]) print("error: failed to create target with '%s'" % (args[0]))
print('Total time = %.03f sec.' % total_time.interval) print('Total time = %.03f sec.' % total_time.interval)
@ -386,7 +388,7 @@ if __name__ == '__main__':
test.Run(sys.argv[1:]) test.Run(sys.argv[1:])
mem = MemoryMeasurement(os.getpid()) mem = MemoryMeasurement(os.getpid())
mem.Measure() mem.Measure()
print str(mem) print(str(mem))
lldb.SBDebugger.Terminate() lldb.SBDebugger.Terminate()
# print "sleeeping for 100 seconds" # print "sleeeping for 100 seconds"
# time.sleep(100) # time.sleep(100)

View File

@ -9,6 +9,8 @@
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import commands import commands
from __future__ import print_function
import optparse import optparse
import os import os
import platform import platform
@ -46,18 +48,18 @@ except ImportError:
except ImportError: except ImportError:
pass pass
else: else:
print 'imported lldb from: "%s"' % (lldb_python_dir) print('imported lldb from: "%s"' % (lldb_python_dir))
success = True success = True
break break
if not success: 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) sys.exit(1)
def print_threads(process, options): def print_threads(process, options):
if options.show_threads: if options.show_threads:
for thread in process: for thread in process:
print '%s %s' % (thread, thread.GetFrameAtIndex(0)) print('%s %s' % (thread, thread.GetFrameAtIndex(0)))
def run_commands(command_interpreter, commands): def run_commands(command_interpreter, commands):
@ -65,9 +67,9 @@ def run_commands(command_interpreter, commands):
for command in commands: for command in commands:
command_interpreter.HandleCommand(command, return_obj) command_interpreter.HandleCommand(command, return_obj)
if return_obj.Succeeded(): if return_obj.Succeeded():
print return_obj.GetOutput() print(return_obj.GetOutput())
else: else:
print return_obj print(return_obj)
if options.stop_on_error: if options.stop_on_error:
break break
@ -241,17 +243,17 @@ def main(argv):
if options.run_count == 1: if options.run_count == 1:
attach_info = lldb.SBAttachInfo(options.attach_pid) attach_info = lldb.SBAttachInfo(options.attach_pid)
else: else:
print "error: --run-count can't be used with the --attach-pid option" print("error: --run-count can't be used with the --attach-pid option")
sys.exit(1) sys.exit(1)
elif not options.attach_name is None: elif not options.attach_name is None:
if options.run_count == 1: if options.run_count == 1:
attach_info = lldb.SBAttachInfo( attach_info = lldb.SBAttachInfo(
options.attach_name, options.attach_wait) options.attach_name, options.attach_wait)
else: else:
print "error: --run-count can't be used with the --attach-name option" print("error: --run-count can't be used with the --attach-name option")
sys.exit(1) sys.exit(1)
else: else:
print 'error: a program path for a program to debug and its arguments are required' print('error: a program path for a program to debug and its arguments are required')
sys.exit(1) sys.exit(1)
# Create a new debugger instance # Create a new debugger instance
@ -261,7 +263,7 @@ def main(argv):
# Create a target from a file and arch # Create a target from a file and arch
if exe: if exe:
print "Creating a target for '%s'" % exe print("Creating a target for '%s'" % exe)
error = lldb.SBError() error = lldb.SBError()
target = debugger.CreateTarget( target = debugger.CreateTarget(
exe, options.arch, options.platform, True, error) exe, options.arch, options.platform, True, error)
@ -283,26 +285,26 @@ def main(argv):
if launch_info: if launch_info:
if options.run_count == 1: if options.run_count == 1:
print 'Launching "%s"...' % (exe) print('Launching "%s"...' % (exe))
else: else:
print 'Launching "%s"... (launch %u of %u)' % (exe, run_idx + 1, options.run_count) print('Launching "%s"... (launch %u of %u)' % (exe, run_idx + 1, options.run_count))
process = target.Launch(launch_info, error) process = target.Launch(launch_info, error)
else: else:
if options.attach_pid != -1: if options.attach_pid != -1:
print 'Attaching to process %i...' % (options.attach_pid) print('Attaching to process %i...' % (options.attach_pid))
else: else:
if options.attach_wait: if options.attach_wait:
print 'Waiting for next to process named "%s" to launch...' % (options.attach_name) print('Waiting for next to process named "%s" to launch...' % (options.attach_name))
else: else:
print 'Attaching to existing process named "%s"...' % (options.attach_name) print('Attaching to existing process named "%s"...' % (options.attach_name))
process = target.Attach(attach_info, error) process = target.Attach(attach_info, error)
# Make sure the launch went ok # Make sure the launch went ok
if process and process.GetProcessID() != lldb.LLDB_INVALID_PROCESS_ID: if process and process.GetProcessID() != lldb.LLDB_INVALID_PROCESS_ID:
pid = process.GetProcessID() pid = process.GetProcessID()
print 'Process is %i' % (pid) print('Process is %i' % (pid))
if attach_info: if attach_info:
# continue process if we attached as we won't get an # continue process if we attached as we won't get an
# initial event # initial event
@ -319,19 +321,19 @@ def main(argv):
state = lldb.SBProcess.GetStateFromEvent(event) state = lldb.SBProcess.GetStateFromEvent(event)
if state == lldb.eStateInvalid: if state == lldb.eStateInvalid:
# Not a state event # Not a state event
print 'process event = %s' % (event) print('process event = %s' % (event))
else: else:
print "process state changed event: %s" % (lldb.SBDebugger.StateAsCString(state)) print("process state changed event: %s" % (lldb.SBDebugger.StateAsCString(state)))
if state == lldb.eStateStopped: if state == lldb.eStateStopped:
if stop_idx == 0: if stop_idx == 0:
if launch_info: if launch_info:
print "process %u launched" % (pid) print("process %u launched" % (pid))
run_commands( run_commands(
command_interpreter, ['breakpoint list']) command_interpreter, ['breakpoint list'])
else: else:
print "attached to process %u" % (pid) print("attached to process %u" % (pid))
for m in target.modules: for m in target.modules:
print m print(m)
if options.breakpoints: if options.breakpoints:
for bp in options.breakpoints: for bp in options.breakpoints:
debugger.HandleCommand( debugger.HandleCommand(
@ -342,74 +344,74 @@ def main(argv):
command_interpreter, options.launch_commands) command_interpreter, options.launch_commands)
else: else:
if options.verbose: if options.verbose:
print "process %u stopped" % (pid) print("process %u stopped" % (pid))
run_commands( run_commands(
command_interpreter, options.stop_commands) command_interpreter, options.stop_commands)
stop_idx += 1 stop_idx += 1
print_threads(process, options) print_threads(process, options)
print "continuing process %u" % (pid) print("continuing process %u" % (pid))
process.Continue() process.Continue()
elif state == lldb.eStateExited: elif state == lldb.eStateExited:
exit_desc = process.GetExitDescription() exit_desc = process.GetExitDescription()
if exit_desc: if exit_desc:
print "process %u exited with status %u: %s" % (pid, process.GetExitStatus(), exit_desc) print("process %u exited with status %u: %s" % (pid, process.GetExitStatus(), exit_desc))
else: else:
print "process %u exited with status %u" % (pid, process.GetExitStatus()) print("process %u exited with status %u" % (pid, process.GetExitStatus()))
run_commands( run_commands(
command_interpreter, options.exit_commands) command_interpreter, options.exit_commands)
done = True done = True
elif state == lldb.eStateCrashed: elif state == lldb.eStateCrashed:
print "process %u crashed" % (pid) print("process %u crashed" % (pid))
print_threads(process, options) print_threads(process, options)
run_commands( run_commands(
command_interpreter, options.crash_commands) command_interpreter, options.crash_commands)
done = True done = True
elif state == lldb.eStateDetached: elif state == lldb.eStateDetached:
print "process %u detached" % (pid) print("process %u detached" % (pid))
done = True done = True
elif state == lldb.eStateRunning: elif state == lldb.eStateRunning:
# process is running, don't say anything, # process is running, don't say anything,
# we will always get one of these after # we will always get one of these after
# resuming # resuming
if options.verbose: if options.verbose:
print "process %u resumed" % (pid) print("process %u resumed" % (pid))
elif state == lldb.eStateUnloaded: elif state == lldb.eStateUnloaded:
print "process %u unloaded, this shouldn't happen" % (pid) print("process %u unloaded, this shouldn't happen" % (pid))
done = True done = True
elif state == lldb.eStateConnected: elif state == lldb.eStateConnected:
print "process connected" print("process connected")
elif state == lldb.eStateAttaching: elif state == lldb.eStateAttaching:
print "process attaching" print("process attaching")
elif state == lldb.eStateLaunching: elif state == lldb.eStateLaunching:
print "process launching" print("process launching")
else: else:
print 'event = %s' % (event) print('event = %s' % (event))
else: else:
# timeout waiting for an event # timeout waiting for an event
print "no process event for %u seconds, killing the process..." % (options.event_timeout) print("no process event for %u seconds, killing the process..." % (options.event_timeout))
done = True done = True
# Now that we are done dump the stdout and stderr # Now that we are done dump the stdout and stderr
process_stdout = process.GetSTDOUT(1024) process_stdout = process.GetSTDOUT(1024)
if process_stdout: if process_stdout:
print "Process STDOUT:\n%s" % (process_stdout) print("Process STDOUT:\n%s" % (process_stdout))
while process_stdout: while process_stdout:
process_stdout = process.GetSTDOUT(1024) process_stdout = process.GetSTDOUT(1024)
print process_stdout print(process_stdout)
process_stderr = process.GetSTDERR(1024) process_stderr = process.GetSTDERR(1024)
if process_stderr: if process_stderr:
print "Process STDERR:\n%s" % (process_stderr) print("Process STDERR:\n%s" % (process_stderr))
while process_stderr: while process_stderr:
process_stderr = process.GetSTDERR(1024) process_stderr = process.GetSTDERR(1024)
print process_stderr print(process_stderr)
process.Kill() # kill the process process.Kill() # kill the process
else: else:
if error: if error:
print error print(error)
else: else:
if launch_info: if launch_info:
print 'error: launch failed' print('error: launch failed')
else: else:
print 'error: attach failed' print('error: attach failed')
lldb.SBDebugger.Terminate() lldb.SBDebugger.Terminate()

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import sys import sys
import inspect import inspect
from collections import OrderedDict from collections import OrderedDict
@ -229,17 +230,17 @@ def disable():
class LoggingTracer: class LoggingTracer:
def callEvent(self, frame): def callEvent(self, frame):
print "call " + frame.getName() + " from " + frame.getCaller().getName() + " @ " + str(frame.getCaller().getLineNumber()) + " args are " + str(frame.getArgumentInfo()) print("call " + frame.getName() + " from " + frame.getCaller().getName() + " @ " + str(frame.getCaller().getLineNumber()) + " args are " + str(frame.getArgumentInfo()))
def lineEvent(self, frame): def lineEvent(self, frame):
print "running " + frame.getName() + " @ " + str(frame.getLineNumber()) + " locals are " + str(frame.getLocals()) + " in " + frame.getFileName() print("running " + frame.getName() + " @ " + str(frame.getLineNumber()) + " locals are " + str(frame.getLocals()) + " in " + frame.getFileName())
def returnEvent(self, frame, retval): def returnEvent(self, frame, retval):
print "return from " + frame.getName() + " value is " + str(retval) + " locals are " + str(frame.getLocals()) print("return from " + frame.getName() + " value is " + str(retval) + " locals are " + str(frame.getLocals()))
def exceptionEvent(self, frame, exception): def exceptionEvent(self, frame, exception):
print "exception %s %s raised from %s @ %s" % (exception.getType(), str(exception.getValue()), frame.getName(), frame.getLineNumber()) print("exception %s %s raised from %s @ %s" % (exception.getType(), str(exception.getValue()), frame.getName(), frame.getLineNumber()))
print "tb: " + str(exception.getTraceback()) print("tb: " + str(exception.getTraceback()))
# the same functionality as LoggingTracer, but with a little more # the same functionality as LoggingTracer, but with a little more
# lldb-specific smarts # lldb-specific smarts
@ -251,10 +252,10 @@ class LLDBAwareTracer:
if frame.getName() == "<module>": if frame.getName() == "<module>":
return return
if frame.getName() == "run_one_line": if frame.getName() == "run_one_line":
print "call run_one_line(%s)" % (frame.getArgumentInfo().getArgs()["input_string"]) print("call run_one_line(%s)" % (frame.getArgumentInfo().getArgs()["input_string"]))
return return
if "Python.framework" in frame.getFileName(): if "Python.framework" in frame.getFileName():
print "call into Python at " + frame.getName() print("call into Python at " + frame.getName())
return return
if frame.getName() == "__init__" and frame.getCaller().getName( if frame.getName() == "__init__" and frame.getCaller().getName(
) == "run_one_line" and frame.getCaller().getLineNumber() == 101: ) == "run_one_line" and frame.getCaller().getLineNumber() == 101:
@ -270,16 +271,16 @@ class LLDBAwareTracer:
else: else:
strout += " from " + frame.getCaller().getName() + " @ " + \ strout += " from " + frame.getCaller().getName() + " @ " + \
str(frame.getCaller().getLineNumber()) + " args are " + str(frame.getArgumentInfo()) str(frame.getCaller().getLineNumber()) + " args are " + str(frame.getArgumentInfo())
print strout print(strout)
def lineEvent(self, frame): def lineEvent(self, frame):
if frame.getName() == "<module>": if frame.getName() == "<module>":
return return
if frame.getName() == "run_one_line": if frame.getName() == "run_one_line":
print "running run_one_line(%s) @ %s" % (frame.getArgumentInfo().getArgs()["input_string"], frame.getLineNumber()) print("running run_one_line(%s) @ %s" % (frame.getArgumentInfo().getArgs()["input_string"], frame.getLineNumber()))
return return
if "Python.framework" in frame.getFileName(): if "Python.framework" in frame.getFileName():
print "running into Python at " + frame.getName() + " @ " + str(frame.getLineNumber()) print("running into Python at " + frame.getName() + " @ " + str(frame.getLineNumber()))
return return
strout = "running " + frame.getName() + " @ " + str(frame.getLineNumber()) + \ strout = "running " + frame.getName() + " @ " + str(frame.getLineNumber()) + \
" locals are " " locals are "
@ -292,16 +293,16 @@ class LLDBAwareTracer:
else: else:
strout = strout + str(frame.getLocals()) strout = strout + str(frame.getLocals())
strout = strout + " in " + frame.getFileName() strout = strout + " in " + frame.getFileName()
print strout print(strout)
def returnEvent(self, frame, retval): def returnEvent(self, frame, retval):
if frame.getName() == "<module>": if frame.getName() == "<module>":
return return
if frame.getName() == "run_one_line": if frame.getName() == "run_one_line":
print "return from run_one_line(%s) return value is %s" % (frame.getArgumentInfo().getArgs()["input_string"], retval) print("return from run_one_line(%s) return value is %s" % (frame.getArgumentInfo().getArgs()["input_string"], retval))
return return
if "Python.framework" in frame.getFileName(): if "Python.framework" in frame.getFileName():
print "return from Python at " + frame.getName() + " return value is " + str(retval) print("return from Python at " + frame.getName() + " return value is " + str(retval))
return return
strout = "return from " + frame.getName() + " return value is " + \ strout = "return from " + frame.getName() + " return value is " + \
str(retval) + " locals are " str(retval) + " locals are "
@ -314,13 +315,13 @@ class LLDBAwareTracer:
else: else:
strout = strout + str(frame.getLocals()) strout = strout + str(frame.getLocals())
strout = strout + " in " + frame.getFileName() strout = strout + " in " + frame.getFileName()
print strout print(strout)
def exceptionEvent(self, frame, exception): def exceptionEvent(self, frame, exception):
if frame.getName() == "<module>": if frame.getName() == "<module>":
return return
print "exception %s %s raised from %s @ %s" % (exception.getType(), str(exception.getValue()), frame.getName(), frame.getLineNumber()) print("exception %s %s raised from %s @ %s" % (exception.getType(), str(exception.getValue()), frame.getName(), frame.getLineNumber()))
print "tb: " + str(exception.getTraceback()) print("tb: " + str(exception.getTraceback()))
def f(x, y=None): def f(x, y=None):
@ -336,7 +337,7 @@ def g(x):
def print_keyword_args(**kwargs): def print_keyword_args(**kwargs):
# kwargs is a dict of the keyword args passed to the function # kwargs is a dict of the keyword args passed to the function
for key, value in kwargs.items(): for key, value in kwargs.items():
print "%s = %s" % (key, value) print("%s = %s" % (key, value))
def total(initial=5, *numbers, **keywords): def total(initial=5, *numbers, **keywords):

View File

@ -93,6 +93,8 @@
# #
# (lldb) thread step-scripted -C scripted_step.StepWithPlan # (lldb) thread step-scripted -C scripted_step.StepWithPlan
from __future__ import print_function
import lldb import lldb
@ -186,13 +188,13 @@ class StepCheckingCondition:
a_var = frame.FindVariable("a") a_var = frame.FindVariable("a")
if not a_var.IsValid(): if not a_var.IsValid():
print "A was not valid." print("A was not valid.")
return True return True
error = lldb.SBError() error = lldb.SBError()
a_value = a_var.GetValueAsSigned(error) a_value = a_var.GetValueAsSigned(error)
if not error.Success(): if not error.Success():
print "A value was not good." print("A value was not good.")
return True return True
if a_value == 20: if a_value == 20:
@ -239,6 +241,6 @@ class FinishPrintAndContinue:
frame_0 = self.thread.frames[0] frame_0 = self.thread.frames[0]
rax_value = frame_0.FindRegister("rax") rax_value = frame_0.FindRegister("rax")
if rax_value.GetError().Success(): if rax_value.GetError().Success():
print "RAX on exit: ", rax_value.GetValue() print("RAX on exit: ", rax_value.GetValue())
else: else:
print "Couldn't get rax value:", rax_value.GetError().GetCString() print("Couldn't get rax value:", rax_value.GetError().GetCString())

View File

@ -1,4 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import lldb import lldb
import shlex import shlex
@ -10,12 +11,12 @@ def check_shadow_command(debugger, command, exe_ctx, result, dict):
process = exe_ctx.GetProcess() process = exe_ctx.GetProcess()
state = process.GetState() state = process.GetState()
if state != lldb.eStateStopped: if state != lldb.eStateStopped:
print >>result, "process must be stopped, state is %s" % lldb.SBDebugger.StateAsCString( print("process must be stopped, state is %s" % lldb.SBDebugger.StateAsCString(
state) state), file=result)
return return
frame = exe_ctx.GetFrame() frame = exe_ctx.GetFrame()
if not frame: if not frame:
print >>result, "invalid frame" print("invalid frame", file=result)
return return
# Parse command line args # Parse command line args
command_args = shlex.split(command) command_args = shlex.split(command)
@ -50,9 +51,9 @@ def check_shadow_command(debugger, command, exe_ctx, result, dict):
for name in shadow_dict.keys(): for name in shadow_dict.keys():
shadow_vars = shadow_dict[name] shadow_vars = shadow_dict[name]
if len(shadow_vars) > 1: if len(shadow_vars) > 1:
print '"%s" is shadowed by the following declarations:' % (name) print('"%s" is shadowed by the following declarations:' % (name))
num_shadowed_variables += 1 num_shadowed_variables += 1
for shadow_var in shadow_vars: for shadow_var in shadow_vars:
print >>result, str(shadow_var.GetDeclaration()) print(str(shadow_var.GetDeclaration()), file=result)
if num_shadowed_variables == 0: if num_shadowed_variables == 0:
print >>result, 'no variables are shadowed' print('no variables are shadowed', file=result)

View File

@ -1,4 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import lldb import lldb
import shlex import shlex
@ -6,10 +7,10 @@ import shlex
def dump_module_sources(module, result): def dump_module_sources(module, result):
if module: if module:
print >> result, "Module: %s" % (module.file) print("Module: %s" % (module.file), file=result)
for compile_unit in module.compile_units: for compile_unit in module.compile_units:
if compile_unit.file: if compile_unit.file:
print >> result, " %s" % (compile_unit.file) print(" %s" % (compile_unit.file), file=result)
def info_sources(debugger, command, result, dict): def info_sources(debugger, command, result, dict):
@ -28,4 +29,4 @@ def __lldb_init_module(debugger, dict):
# Add any commands contained in this module to LLDB # Add any commands contained in this module to LLDB
debugger.HandleCommand( debugger.HandleCommand(
'command script add -f sources.info_sources info_sources') 'command script add -f sources.info_sources info_sources')
print 'The "info_sources" command has been installed, type "help info_sources" or "info_sources --help" for detailed help.' print('The "info_sources" command has been installed, type "help info_sources" or "info_sources --help" for detailed help.')

View File

@ -1,5 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import lldb import lldb
import commands import commands
import optparse import optparse
@ -30,7 +30,7 @@ def stack_frames(debugger, command, result, dict):
frame_info = {} frame_info = {}
for thread in process: for thread in process:
last_frame = None last_frame = None
print "thread %u" % (thread.id) print("thread %u" % (thread.id))
for frame in thread.frames: for frame in thread.frames:
if last_frame: if last_frame:
frame_size = 0 frame_size = 0
@ -43,7 +43,7 @@ def stack_frames(debugger, command, result, dict):
else: else:
# First frame that has a valid size # First frame that has a valid size
first_frame_size = last_frame.fp - last_frame.sp first_frame_size = last_frame.fp - last_frame.sp
print "<%#7x> %s" % (first_frame_size, last_frame) print("<%#7x> %s" % (first_frame_size, last_frame))
if first_frame_size: if first_frame_size:
name = last_frame.name name = last_frame.name
if name not in frame_info: if name not in frame_info:
@ -53,7 +53,7 @@ def stack_frames(debugger, command, result, dict):
else: else:
# Second or higher frame # Second or higher frame
frame_size = frame.fp - last_frame.fp frame_size = frame.fp - last_frame.fp
print "<%#7x> %s" % (frame_size, frame) print("<%#7x> %s" % (frame_size, frame))
if frame_size > 0: if frame_size > 0:
name = frame.name name = frame.name
if name not in frame_info: if name not in frame_info:
@ -61,9 +61,9 @@ def stack_frames(debugger, command, result, dict):
else: else:
frame_info[name] += frame_size frame_info[name] += frame_size
last_frame = frame last_frame = frame
print frame_info print(frame_info)
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
"command script add -f stacks.stack_frames stack_frames") "command script add -f stacks.stack_frames stack_frames")
print "A new command called 'stack_frames' was added, type 'stack_frames --help' for more information." print("A new command called 'stack_frames' was added, type 'stack_frames --help' for more information.")

View File

@ -10,6 +10,8 @@
#---------------------------------------------------------------------- #----------------------------------------------------------------------
import commands import commands
from __future__ import print_function
import platform import platform
import os import os
import re import re
@ -45,11 +47,11 @@ except ImportError:
except ImportError: except ImportError:
pass pass
else: else:
print 'imported lldb from: "%s"' % (lldb_python_dir) print('imported lldb from: "%s"' % (lldb_python_dir))
success = True success = True
break break
if not success: 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) sys.exit(1)
import commands import commands
@ -157,7 +159,7 @@ be verified in all specified modules.
def verify_type(target, options, type): def verify_type(target, options, type):
print type print(type)
typename = type.GetName() typename = type.GetName()
# print 'type: %s' % (typename) # print 'type: %s' % (typename)
(end_offset, padding) = verify_type_recursive( (end_offset, padding) = verify_type_recursive(
@ -167,11 +169,11 @@ def verify_type(target, options, type):
# last_member_padding = byte_size - end_offset # last_member_padding = byte_size - end_offset
# print '%+4u <%u> padding' % (end_offset, last_member_padding) # print '%+4u <%u> padding' % (end_offset, last_member_padding)
# padding += last_member_padding # padding += last_member_padding
print 'Total byte size: %u' % (byte_size) print('Total byte size: %u' % (byte_size))
print 'Total pad bytes: %u' % (padding) print('Total pad bytes: %u' % (padding))
if padding > 0: if padding > 0:
print 'Padding percentage: %2.2f %%' % ((float(padding) / float(byte_size)) * 100.0) print('Padding percentage: %2.2f %%' % ((float(padding) / float(byte_size)) * 100.0))
print print()
def verify_type_recursive( def verify_type_recursive(
@ -186,9 +188,9 @@ def verify_type_recursive(
typename = type.GetName() typename = type.GetName()
byte_size = type.GetByteSize() byte_size = type.GetByteSize()
if member_name and member_name != typename: if member_name and member_name != typename:
print '%+4u <%3u> %s%s %s;' % (base_offset, byte_size, ' ' * depth, typename, member_name) print('%+4u <%3u> %s%s %s;' % (base_offset, byte_size, ' ' * depth, typename, member_name))
else: else:
print '%+4u {%3u} %s%s' % (base_offset, byte_size, ' ' * depth, typename) print('%+4u {%3u} %s%s' % (base_offset, byte_size, ' ' * depth, typename))
for type_regex in options.skip_type_regexes: for type_regex in options.skip_type_regexes:
match = type_regex.match(typename) match = type_regex.match(typename)
@ -211,13 +213,13 @@ def verify_type_recursive(
if member_idx == 0 and member_offset == target.GetAddressByteSize( if member_idx == 0 and member_offset == target.GetAddressByteSize(
) and type.IsPolymorphicClass(): ) and type.IsPolymorphicClass():
ptr_size = target.GetAddressByteSize() ptr_size = target.GetAddressByteSize()
print '%+4u <%3u> %s__vtbl_ptr_type * _vptr;' % (prev_end_offset, ptr_size, ' ' * (depth + 1)) print('%+4u <%3u> %s__vtbl_ptr_type * _vptr;' % (prev_end_offset, ptr_size, ' ' * (depth + 1)))
prev_end_offset = ptr_size prev_end_offset = ptr_size
else: else:
if prev_end_offset < member_total_offset: if prev_end_offset < member_total_offset:
member_padding = member_total_offset - prev_end_offset member_padding = member_total_offset - prev_end_offset
padding = padding + member_padding padding = padding + member_padding
print '%+4u <%3u> %s<PADDING>' % (prev_end_offset, member_padding, ' ' * (depth + 1)) print('%+4u <%3u> %s<PADDING>' % (prev_end_offset, member_padding, ' ' * (depth + 1)))
if member_is_class_or_struct: if member_is_class_or_struct:
(prev_end_offset, (prev_end_offset,
@ -232,18 +234,18 @@ def verify_type_recursive(
prev_end_offset = member_total_offset + member_byte_size prev_end_offset = member_total_offset + member_byte_size
member_typename = member_type.GetName() member_typename = member_type.GetName()
if member.IsBitfield(): if member.IsBitfield():
print '%+4u <%3u> %s%s:%u %s;' % (member_total_offset, member_byte_size, ' ' * (depth + 1), member_typename, member.GetBitfieldSizeInBits(), member_name) print('%+4u <%3u> %s%s:%u %s;' % (member_total_offset, member_byte_size, ' ' * (depth + 1), member_typename, member.GetBitfieldSizeInBits(), member_name))
else: else:
print '%+4u <%3u> %s%s %s;' % (member_total_offset, member_byte_size, ' ' * (depth + 1), member_typename, member_name) print('%+4u <%3u> %s%s %s;' % (member_total_offset, member_byte_size, ' ' * (depth + 1), member_typename, member_name))
if prev_end_offset < byte_size: if prev_end_offset < byte_size:
last_member_padding = byte_size - prev_end_offset last_member_padding = byte_size - prev_end_offset
print '%+4u <%3u> %s<PADDING>' % (prev_end_offset, last_member_padding, ' ' * (depth + 1)) print('%+4u <%3u> %s<PADDING>' % (prev_end_offset, last_member_padding, ' ' * (depth + 1)))
padding += last_member_padding padding += last_member_padding
else: else:
if type.IsPolymorphicClass(): if type.IsPolymorphicClass():
ptr_size = target.GetAddressByteSize() ptr_size = target.GetAddressByteSize()
print '%+4u <%3u> %s__vtbl_ptr_type * _vptr;' % (prev_end_offset, ptr_size, ' ' * (depth + 1)) print('%+4u <%3u> %s__vtbl_ptr_type * _vptr;' % (prev_end_offset, ptr_size, ' ' * (depth + 1)))
prev_end_offset = ptr_size prev_end_offset = ptr_size
prev_end_offset = base_offset + byte_size prev_end_offset = base_offset + byte_size
@ -274,17 +276,17 @@ def parse_all_struct_class_types(debugger, command, result, dict):
error = lldb.SBError() error = lldb.SBError()
target = debugger.CreateTarget(f, None, None, False, error) target = debugger.CreateTarget(f, None, None, False, error)
module = target.GetModuleAtIndex(0) module = target.GetModuleAtIndex(0)
print "Parsing all types in '%s'" % (module) print("Parsing all types in '%s'" % (module))
types = module.GetTypes(lldb.eTypeClassClass | lldb.eTypeClassStruct) types = module.GetTypes(lldb.eTypeClassClass | lldb.eTypeClassStruct)
for t in types: for t in types:
print t print(t)
print "" print("")
def verify_types(target, options): def verify_types(target, options):
if not target: if not target:
print 'error: invalid target' print('error: invalid target')
return return
modules = list() modules = list()
@ -301,24 +303,24 @@ def verify_types(target, options):
if modules: if modules:
for module in modules: for module in modules:
print 'module: %s' % (module.file) print('module: %s' % (module.file))
if options.typenames: if options.typenames:
for typename in options.typenames: for typename in options.typenames:
types = module.FindTypes(typename) types = module.FindTypes(typename)
if types.GetSize(): if types.GetSize():
print 'Found %u types matching "%s" in "%s"' % (len(types), typename, module.file) print('Found %u types matching "%s" in "%s"' % (len(types), typename, module.file))
for type in types: for type in types:
verify_type(target, options, type) verify_type(target, options, type)
else: else:
print 'error: no type matches "%s" in "%s"' % (typename, module.file) print('error: no type matches "%s" in "%s"' % (typename, module.file))
else: else:
types = module.GetTypes( types = module.GetTypes(
lldb.eTypeClassClass | lldb.eTypeClassStruct) lldb.eTypeClassClass | lldb.eTypeClassStruct)
print 'Found %u types in "%s"' % (len(types), module.file) print('Found %u types in "%s"' % (len(types), module.file))
for type in types: for type in types:
verify_type(target, options, type) verify_type(target, options, type)
else: else:
print 'error: no modules' print('error: no modules')
if __name__ == '__main__': if __name__ == '__main__':
debugger = lldb.SBDebugger.Create() debugger = lldb.SBDebugger.Create()
@ -331,7 +333,7 @@ if __name__ == '__main__':
# sys.exit(1) # sys.exit(1)
if options.debug: if options.debug:
print "Waiting for debugger to attach to process %d" % os.getpid() print("Waiting for debugger to attach to process %d" % os.getpid())
os.kill(os.getpid(), signal.SIGSTOP) os.kill(os.getpid(), signal.SIGSTOP)
for path in args: for path in args:
@ -346,11 +348,11 @@ if __name__ == '__main__':
True, True,
error) error)
if error.Fail(): if error.Fail():
print error.GetCString() print(error.GetCString())
continue continue
verify_types(target, options) verify_types(target, options)
elif getattr(lldb, 'debugger', None): elif getattr(lldb, 'debugger', None):
lldb.debugger.HandleCommand( lldb.debugger.HandleCommand(
'command script add -f types.check_padding_command check_padding') 'command script add -f types.check_padding_command check_padding')
print '"check_padding" command installed, use the "--help" option for detailed help' print('"check_padding" command installed, use the "--help" option for detailed help')

View File

@ -18,6 +18,8 @@ for more information about dictionary.c go to
http://lldb.llvm.org/scripting.html http://lldb.llvm.org/scripting.html
""" """
from __future__ import print_function
def DFS(root, word, cur_path): def DFS(root, word, cur_path):
""" """
@ -110,7 +112,7 @@ def print_tree(root):
int(root.GetChildAtIndex(1).GetValue(), 16) != 0): int(root.GetChildAtIndex(1).GetValue(), 16) != 0):
print_tree(root.GetChildAtIndex(1)) print_tree(root.GetChildAtIndex(1))
print root.GetChildAtIndex(0).GetSummary() print(root.GetChildAtIndex(0).GetSummary())
if (root.GetChildAtIndex(2).GetValue() is not None) and ( if (root.GetChildAtIndex(2).GetValue() is not None) and (
int(root.GetChildAtIndex(2).GetValue(), 16) != 0): int(root.GetChildAtIndex(2).GetValue(), 16) != 0):

View File

@ -5,6 +5,8 @@ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
See https://llvm.org/LICENSE.txt for license information. See https://llvm.org/LICENSE.txt for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
""" """
from __future__ import print_function
# summary provider for CF(Mutable)BitVector # summary provider for CF(Mutable)BitVector
import lldb import lldb
import ctypes import ctypes
@ -169,11 +171,11 @@ def GetSummary_Impl(valobj):
else: else:
wrapper = CFBitVectorUnknown_SummaryProvider( wrapper = CFBitVectorUnknown_SummaryProvider(
valobj, class_data.sys_params) valobj, class_data.sys_params)
print actual_name print(actual_name)
else: else:
wrapper = CFBitVectorUnknown_SummaryProvider( wrapper = CFBitVectorUnknown_SummaryProvider(
valobj, class_data.sys_params) valobj, class_data.sys_params)
print name_string print(name_string)
statistics.metric_hit( statistics.metric_hit(
'unknown_class', 'unknown_class',
valobj.GetName() + valobj.GetName() +

View File

@ -7,6 +7,9 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
""" """
# example summary provider for NSNumber # example summary provider for NSNumber
# the real summary is now C++ code built into LLDB # the real summary is now C++ code built into LLDB
from __future__ import print_function
import lldb import lldb
import ctypes import ctypes
import lldb.runtime.objc.objc_runtime import lldb.runtime.objc.objc_runtime
@ -250,7 +253,7 @@ def NSNumber_SummaryProvider(valobj, dict):
try: try:
summary = provider.value() summary = provider.value()
except Exception as foo: except Exception as foo:
print foo print(foo)
# except: # except:
summary = None summary = None
logger >> "got summary " + str(summary) logger >> "got summary " + str(summary)

View File

@ -5,6 +5,8 @@
# 'command script import host_art_bt.py' # 'command script import host_art_bt.py'
# 'host_art_bt' # 'host_art_bt'
from __future__ import print_function
import sys import sys
import re import re
@ -27,7 +29,7 @@ def host_art_bt(debugger, command, result, internal_dict):
# Get function/filename/lineno from symbol context # Get function/filename/lineno from symbol context
symbol = frame.GetSymbol() symbol = frame.GetSymbol()
if not symbol: if not symbol:
print 'No symbol info for compiled Java frame: ', frame print('No symbol info for compiled Java frame: ', frame)
sys.exit(1) sys.exit(1)
line_entry = frame.GetLineEntry() line_entry = frame.GetLineEntry()
prettified_frames.append({ prettified_frames.append({
@ -55,10 +57,10 @@ def host_art_bt(debugger, command, result, internal_dict):
art_method_name = process.ReadCStringFromMemory( art_method_name = process.ReadCStringFromMemory(
art_method_name_data, art_method_name_size + 1, error) art_method_name_data, art_method_name_size + 1, error)
if not error.Success: if not error.Success:
print 'Failed to read method name' print('Failed to read method name')
sys.exit(1) sys.exit(1)
if art_method_name != symbol.GetName(): if art_method_name != symbol.GetName():
print 'Function names in native symbol and art runtime stack do not match: ', symbol.GetName(), ' != ', art_method_name print('Function names in native symbol and art runtime stack do not match: ', symbol.GetName(), ' != ', art_method_name)
art_frame_index = art_frame_index + 1 art_frame_index = art_frame_index + 1
break break
art_frame_index = art_frame_index + 1 art_frame_index = art_frame_index + 1
@ -78,7 +80,7 @@ def host_art_bt(debugger, command, result, internal_dict):
while True: while True:
lldb_frame_index = lldb_frame_index + 1 lldb_frame_index = lldb_frame_index + 1
if lldb_frame_index >= thread.GetNumFrames(): if lldb_frame_index >= thread.GetNumFrames():
print 'ArtMethod::Invoke not found below art_quick_invoke_stub/art_quick_invoke_static_stub' print('ArtMethod::Invoke not found below art_quick_invoke_stub/art_quick_invoke_static_stub')
sys.exit(1) sys.exit(1)
frame = thread.GetFrameAtIndex(lldb_frame_index) frame = thread.GetFrameAtIndex(lldb_frame_index)
if frame.GetSymbol() and frame.GetSymbol().GetName( if frame.GetSymbol() and frame.GetSymbol().GetName(
@ -86,7 +88,7 @@ def host_art_bt(debugger, command, result, internal_dict):
lldb_frame_index = lldb_frame_index + 1 lldb_frame_index = lldb_frame_index + 1
break break
else: else:
print 'Invalid frame below compiled Java frame: ', frame print('Invalid frame below compiled Java frame: ', frame)
elif frame.GetSymbol() and frame.GetSymbol().GetName() == 'art_quick_generic_jni_trampoline': elif frame.GetSymbol() and frame.GetSymbol().GetName() == 'art_quick_generic_jni_trampoline':
# Interpreted JNI frame for x86_64 # Interpreted JNI frame for x86_64
@ -131,7 +133,7 @@ def host_art_bt(debugger, command, result, internal_dict):
while True: while True:
lldb_frame_index = lldb_frame_index + 1 lldb_frame_index = lldb_frame_index + 1
if lldb_frame_index >= thread.GetNumFrames(): if lldb_frame_index >= thread.GetNumFrames():
print 'ArtMethod::Invoke not found below art_quick_invoke_stub/art_quick_invoke_static_stub' print('ArtMethod::Invoke not found below art_quick_invoke_stub/art_quick_invoke_static_stub')
sys.exit(1) sys.exit(1)
frame = thread.GetFrameAtIndex(lldb_frame_index) frame = thread.GetFrameAtIndex(lldb_frame_index)
if frame.GetSymbol() and frame.GetSymbol().GetName( if frame.GetSymbol() and frame.GetSymbol().GetName(
@ -139,14 +141,14 @@ def host_art_bt(debugger, command, result, internal_dict):
lldb_frame_index = lldb_frame_index + 1 lldb_frame_index = lldb_frame_index + 1
break break
else: else:
print 'Invalid frame below compiled Java frame: ', frame print('Invalid frame below compiled Java frame: ', frame)
elif frame.GetSymbol() and re.search(r'art::interpreter::', frame.GetSymbol().GetName()): elif frame.GetSymbol() and re.search(r'art::interpreter::', frame.GetSymbol().GetName()):
# Interpreted Java frame # Interpreted Java frame
while True: while True:
lldb_frame_index = lldb_frame_index + 1 lldb_frame_index = lldb_frame_index + 1
if lldb_frame_index >= thread.GetNumFrames(): if lldb_frame_index >= thread.GetNumFrames():
print 'art::interpreter::Execute not found in interpreter frame' print('art::interpreter::Execute not found in interpreter frame')
sys.exit(1) sys.exit(1)
frame = thread.GetFrameAtIndex(lldb_frame_index) frame = thread.GetFrameAtIndex(lldb_frame_index)
if frame.GetSymbol() and frame.GetSymbol().GetName( if frame.GetSymbol() and frame.GetSymbol().GetName(
@ -188,7 +190,7 @@ def host_art_bt(debugger, command, result, internal_dict):
file_name = process.ReadCStringFromMemory( file_name = process.ReadCStringFromMemory(
file_name_data, file_name_size + 1, error) file_name_data, file_name_size + 1, error)
if not error.Success(): if not error.Success():
print 'Failed to read source file name' print('Failed to read source file name')
sys.exit(1) sys.exit(1)
prettified_frames.append({ prettified_frames.append({
@ -205,7 +207,7 @@ def host_art_bt(debugger, command, result, internal_dict):
while True: while True:
lldb_frame_index = lldb_frame_index + 1 lldb_frame_index = lldb_frame_index + 1
if lldb_frame_index >= thread.GetNumFrames(): if lldb_frame_index >= thread.GetNumFrames():
print 'Can not get past interpreter native frames' print('Can not get past interpreter native frames')
sys.exit(1) sys.exit(1)
frame = thread.GetFrameAtIndex(lldb_frame_index) frame = thread.GetFrameAtIndex(lldb_frame_index)
if frame.GetSymbol() and not re.search( if frame.GetSymbol() and not re.search(
@ -229,7 +231,7 @@ def host_art_bt(debugger, command, result, internal_dict):
}) })
for prettified_frame in prettified_frames: for prettified_frame in prettified_frames:
print prettified_frame['function'], prettified_frame['file'], prettified_frame['line'] print(prettified_frame['function'], prettified_frame['file'], prettified_frame['line'])
def __lldb_init_module(debugger, internal_dict): def __lldb_init_module(debugger, internal_dict):

View File

@ -250,7 +250,7 @@ def should_build_llvm():
def do_symlink(source_path, link_path): def do_symlink(source_path, link_path):
print "Symlinking " + source_path + " to " + link_path print("Symlinking " + source_path + " to " + link_path)
if os.path.islink(link_path): if os.path.islink(link_path):
os.remove(link_path) os.remove(link_path)
if not os.path.exists(link_path): if not os.path.exists(link_path):
@ -376,12 +376,12 @@ def cmake_flags():
def run_cmake(cmake_build_dir, ninja_binary_path): def run_cmake(cmake_build_dir, ninja_binary_path):
cmake_binary = find_cmake() cmake_binary = find_cmake()
print "found cmake binary: using \"{}\"".format(cmake_binary) print("found cmake binary: using \"{}\"".format(cmake_binary))
command_line = [cmake_binary] + cmake_flags() + [ command_line = [cmake_binary] + cmake_flags() + [
"-DCMAKE_MAKE_PROGRAM={}".format(ninja_binary_path), "-DCMAKE_MAKE_PROGRAM={}".format(ninja_binary_path),
llvm_source_path()] llvm_source_path()]
print "running cmake like so: ({}) in dir ({})".format(command_line, cmake_build_dir) print("running cmake like so: ({}) in dir ({})".format(command_line, cmake_build_dir))
subprocess.check_call( subprocess.check_call(
command_line, command_line,
@ -413,7 +413,7 @@ def build_ninja_if_needed():
"ninja", os.environ["PATH"].split(os.pathsep)) "ninja", os.environ["PATH"].split(os.pathsep))
if ninja_binary_path: if ninja_binary_path:
# It's on the path. cmake will find it. We're good. # It's on the path. cmake will find it. We're good.
print "found ninja here: \"{}\"".format(ninja_binary_path) print("found ninja here: \"{}\"".format(ninja_binary_path))
return ninja_binary_path return ninja_binary_path
# Figure out if we need to build it. # Figure out if we need to build it.
@ -422,7 +422,7 @@ def build_ninja_if_needed():
if not is_executable(ninja_binary_path): if not is_executable(ninja_binary_path):
# Build ninja # Build ninja
command_line = ["python", "configure.py", "--bootstrap"] command_line = ["python", "configure.py", "--bootstrap"]
print "building ninja like so: ({}) in dir ({})".format(command_line, ninja_build_dir) print("building ninja like so: ({}) in dir ({})".format(command_line, ninja_build_dir))
subprocess.check_call( subprocess.check_call(
command_line, command_line,
cwd=ninja_build_dir, cwd=ninja_build_dir,

View File

@ -17,14 +17,14 @@ import sys
import lldbbuild import lldbbuild
if len(sys.argv) != 3: if len(sys.argv) != 3:
print "usage: " + sys.argv[0] + " TARGET_DIR LLVM_BUILD_DIR" print("usage: " + sys.argv[0] + " TARGET_DIR LLVM_BUILD_DIR")
sys.exit(1) sys.exit(1)
target_dir = sys.argv[1] target_dir = sys.argv[1]
llvm_build_dir = lldbbuild.expected_package_build_path_for("llvm") llvm_build_dir = lldbbuild.expected_package_build_path_for("llvm")
if not os.path.isdir(target_dir): if not os.path.isdir(target_dir):
print target_dir + " doesn't exist" print(target_dir + " doesn't exist")
sys.exit(1) sys.exit(1)
if not os.path.isdir(llvm_build_dir): if not os.path.isdir(llvm_build_dir):
@ -40,19 +40,19 @@ if not os.path.isdir(llvm_build_dir):
llvm_build_dir = re.sub("-watchos-", "-bridgeos-", llvm_build_dir) llvm_build_dir = re.sub("-watchos-", "-bridgeos-", llvm_build_dir)
if not os.path.isdir(llvm_build_dir): if not os.path.isdir(llvm_build_dir):
print llvm_build_dir + " doesn't exist" print(llvm_build_dir + " doesn't exist")
sys.exit(1) sys.exit(1)
resources = os.path.join(target_dir, "LLDB.framework", "Resources") resources = os.path.join(target_dir, "LLDB.framework", "Resources")
if not os.path.isdir(resources): if not os.path.isdir(resources):
print resources + " must exist" print(resources + " must exist")
sys.exit(1) sys.exit(1)
clang_dir = os.path.join(llvm_build_dir, "lib", "clang") clang_dir = os.path.join(llvm_build_dir, "lib", "clang")
if not os.path.isdir(clang_dir): if not os.path.isdir(clang_dir):
print clang_dir + " must exist" print(clang_dir + " must exist")
sys.exit(1) sys.exit(1)
version_dir = None version_dir = None
@ -63,18 +63,18 @@ for subdir in os.listdir(clang_dir):
break break
if version_dir is None: if version_dir is None:
print "Couldn't find a subdirectory of the form #(.#)... in " + clang_dir print("Couldn't find a subdirectory of the form #(.#)... in " + clang_dir)
sys.exit(1) sys.exit(1)
if not os.path.isdir(version_dir): if not os.path.isdir(version_dir):
print version_dir + " is not a directory" print(version_dir + " is not a directory")
sys.exit(1) sys.exit(1)
# Just checking... we're actually going to copy all of version_dir # Just checking... we're actually going to copy all of version_dir
include_dir = os.path.join(version_dir, "include") include_dir = os.path.join(version_dir, "include")
if not os.path.isdir(include_dir): if not os.path.isdir(include_dir):
print version_dir + " is not a directory" print(version_dir + " is not a directory")
sys.exit(1) sys.exit(1)
clang_resources = os.path.join(resources, "Clang") clang_resources = os.path.join(resources, "Clang")

View File

@ -193,4 +193,4 @@ build_bot = LLDBBuildBot(build_directory_path=arg_dict["build_path"],
try: try:
build_bot.Run() build_bot.Run()
except BuildError as err: except BuildError as err:
print err print(err)

View File

@ -30,7 +30,7 @@ import sys
def copy_one_file(dest_dir, source_dir, filename): def copy_one_file(dest_dir, source_dir, filename):
source_path = os.path.join(source_dir, filename) source_path = os.path.join(source_dir, filename)
dest_path = os.path.join(dest_dir, filename) dest_path = os.path.join(dest_dir, filename)
print 'Copying file %s ==> %s...' % (source_path, dest_path) print('Copying file %s ==> %s...' % (source_path, dest_path))
shutil.copyfile(source_path, dest_path) shutil.copyfile(source_path, dest_path)
@ -49,14 +49,14 @@ def copy_named_files(
def copy_subdirectory(dest_dir, source_dir, subdir): def copy_subdirectory(dest_dir, source_dir, subdir):
dest_dir = os.path.join(dest_dir, subdir) dest_dir = os.path.join(dest_dir, subdir)
source_dir = os.path.join(source_dir, subdir) source_dir = os.path.join(source_dir, subdir)
print 'Copying directory %s ==> %s...' % (source_dir, dest_dir) print('Copying directory %s ==> %s...' % (source_dir, dest_dir))
shutil.copytree(source_dir, dest_dir) shutil.copytree(source_dir, dest_dir)
def copy_distro(dest_dir, dest_subdir, source_dir, source_prefix): def copy_distro(dest_dir, dest_subdir, source_dir, source_prefix):
dest_dir = os.path.join(dest_dir, dest_subdir) dest_dir = os.path.join(dest_dir, dest_subdir)
print 'Copying distribution %s ==> %s' % (source_dir, dest_dir) print('Copying distribution %s ==> %s' % (source_dir, dest_dir))
os.mkdir(dest_dir) os.mkdir(dest_dir)
PCbuild_dir = os.path.join(source_dir, 'PCbuild') PCbuild_dir = os.path.join(source_dir, 'PCbuild')
@ -65,7 +65,7 @@ def copy_distro(dest_dir, dest_subdir, source_dir, source_prefix):
# First copy the files that go into the root of the new distribution. This # First copy the files that go into the root of the new distribution. This
# includes the Python executables, python27(_d).dll, and relevant PDB # includes the Python executables, python27(_d).dll, and relevant PDB
# files. # files.
print 'Copying Python executables...' print('Copying Python executables...')
copy_named_files( copy_named_files(
dest_dir, PCbuild_dir, ['w9xpopen'], [ dest_dir, PCbuild_dir, ['w9xpopen'], [
'exe', 'pdb'], False) 'exe', 'pdb'], False)
@ -79,11 +79,11 @@ def copy_distro(dest_dir, dest_subdir, source_dir, source_prefix):
copy_named_files(dest_dir, PCbuild_dir, ['python27'], ['dll', 'pdb'], True) copy_named_files(dest_dir, PCbuild_dir, ['python27'], ['dll', 'pdb'], True)
# Next copy everything in the Include directory. # Next copy everything in the Include directory.
print 'Copying Python include directory' print('Copying Python include directory')
copy_subdirectory(dest_dir, source_dir, 'Include') copy_subdirectory(dest_dir, source_dir, 'Include')
# Copy Lib folder (builtin Python modules) # Copy Lib folder (builtin Python modules)
print 'Copying Python Lib directory' print('Copying Python Lib directory')
copy_subdirectory(dest_dir, source_dir, 'Lib') copy_subdirectory(dest_dir, source_dir, 'Lib')
# Copy tools folder. These are probably not necessary, but we copy them anyway to # Copy tools folder. These are probably not necessary, but we copy them anyway to
@ -115,13 +115,13 @@ def copy_distro(dest_dir, dest_subdir, source_dir, source_prefix):
# Copy builtin extension modules (pyd files) # Copy builtin extension modules (pyd files)
dlls_dir = os.path.join(dest_dir, 'DLLs') dlls_dir = os.path.join(dest_dir, 'DLLs')
os.mkdir(dlls_dir) os.mkdir(dlls_dir)
print 'Copying DLLs directory' print('Copying DLLs directory')
copy_named_files(dlls_dir, PCbuild_dir, pyd_names, ['pyd', 'pdb'], True) copy_named_files(dlls_dir, PCbuild_dir, pyd_names, ['pyd', 'pdb'], True)
# Copy libs folder (implibs for the pyd files) # Copy libs folder (implibs for the pyd files)
libs_dir = os.path.join(dest_dir, 'libs') libs_dir = os.path.join(dest_dir, 'libs')
os.mkdir(libs_dir) os.mkdir(libs_dir)
print 'Copying libs directory' print('Copying libs directory')
copy_named_files(libs_dir, PCbuild_dir, pyd_names, ['lib'], False) copy_named_files(libs_dir, PCbuild_dir, pyd_names, ['lib'], False)
copy_named_files(libs_dir, PCbuild_dir, ['python27'], ['lib'], True) copy_named_files(libs_dir, PCbuild_dir, ['python27'], ['lib'], True)
@ -153,18 +153,18 @@ args.source = os.path.normpath(args.source)
args.dest = os.path.normpath(args.dest) args.dest = os.path.normpath(args.dest)
if not os.path.exists(args.source): if not os.path.exists(args.source):
print 'The source directory %s does not exist. Exiting...' print('The source directory %s does not exist. Exiting...')
sys.exit(1) sys.exit(1)
if os.path.exists(args.dest): if os.path.exists(args.dest):
if not args.overwrite: if not args.overwrite:
print 'The destination directory \'%s\' already exists and --overwrite was not specified. Exiting...' % args.dest print('The destination directory \'%s\' already exists and --overwrite was not specified. Exiting...' % args.dest)
sys.exit(1) sys.exit(1)
while not args.silent: while not args.silent:
print 'Ok to recursively delete \'%s\' and all contents (Y/N)? Choosing Y will permanently delete the contents.' % args.dest print('Ok to recursively delete \'%s\' and all contents (Y/N)? Choosing Y will permanently delete the contents.' % args.dest)
result = str.upper(sys.stdin.read(1)) result = str.upper(sys.stdin.read(1))
if result == 'N': if result == 'N':
print 'Unable to copy files to the destination. The destination already exists.' print('Unable to copy files to the destination. The destination already exists.')
sys.exit(1) sys.exit(1)
elif result == 'Y': elif result == 'Y':
break break

View File

@ -16,9 +16,9 @@ def extract_exe_symbol_names(arch, exe_path, match_str):
if command_output: if command_output:
return command_output[0:-1].split("'\n") return command_output[0:-1].split("'\n")
else: else:
print 'error: command returned no output' print('error: command returned no output')
else: else:
print 'error: command failed with exit status %i\n command: %s' % (command_exit_status, command) print('error: command failed with exit status %i\n command: %s' % (command_exit_status, command))
return list() return list()
@ -76,12 +76,12 @@ def verify_api(all_args):
else: else:
sys.exit(1) sys.exit(1)
else: else:
print 'error: must specify one or more architectures with the --arch option' print('error: must specify one or more architectures with the --arch option')
sys.exit(4) sys.exit(4)
if options.verbose: if options.verbose:
print "API symbols:" print("API symbols:")
for (i, external_symbol) in enumerate(api_external_symbols): for (i, external_symbol) in enumerate(api_external_symbols):
print "[%u] %s" % (i, external_symbol) print("[%u] %s" % (i, external_symbol))
api_regex = None api_regex = None
if options.api_regex_str: if options.api_regex_str:
@ -89,7 +89,7 @@ def verify_api(all_args):
for arch in options.archs: for arch in options.archs:
for exe_path in args: for exe_path in args:
print 'Verifying (%s) "%s"...' % (arch, exe_path) print('Verifying (%s) "%s"...' % (arch, exe_path))
exe_errors = 0 exe_errors = 0
undefined_symbols = extract_exe_symbol_names( undefined_symbols = extract_exe_symbol_names(
arch, exe_path, "( UNDF EXT)") arch, exe_path, "( UNDF EXT)")
@ -98,18 +98,18 @@ def verify_api(all_args):
match = api_regex.search(undefined_symbol) match = api_regex.search(undefined_symbol)
if not match: if not match:
if options.verbose: if options.verbose:
print 'ignoring symbol: %s' % (undefined_symbol) print('ignoring symbol: %s' % (undefined_symbol))
continue continue
if undefined_symbol in api_external_symbols: if undefined_symbol in api_external_symbols:
if options.verbose: if options.verbose:
print 'verified symbol: %s' % (undefined_symbol) print('verified symbol: %s' % (undefined_symbol))
else: else:
print 'missing symbol: %s' % (undefined_symbol) print('missing symbol: %s' % (undefined_symbol))
exe_errors += 1 exe_errors += 1
if exe_errors: if exe_errors:
print 'error: missing %u API symbols from %s' % (exe_errors, options.libraries) print('error: missing %u API symbols from %s' % (exe_errors, options.libraries))
else: else:
print 'success' print('success')
if __name__ == '__main__': if __name__ == '__main__':
verify_api(sys.argv[1:]) verify_api(sys.argv[1:])

View File

@ -11,6 +11,8 @@ Usage:
4. git svn dcommit [--commit-url https://id@llvm.org/svn/llvm-project/lldb/trunk] 4. git svn dcommit [--commit-url https://id@llvm.org/svn/llvm-project/lldb/trunk]
""" """
from __future__ import print_function
import os import os
import re import re
import sys import sys
@ -19,8 +21,8 @@ import StringIO
def usage(problem_file=None): def usage(problem_file=None):
if problem_file: if problem_file:
print "%s is not a file" % problem_file print("%s is not a file" % problem_file)
print "Usage: convert.py raw-message-source [raw-message-source2 ...]" print("Usage: convert.py raw-message-source [raw-message-source2 ...]")
sys.exit(0) sys.exit(0)
@ -29,7 +31,7 @@ def do_convert(file):
Then for each line ('From: ' header included), replace the dos style CRLF Then for each line ('From: ' header included), replace the dos style CRLF
end-of-line with unix style LF end-of-line. end-of-line with unix style LF end-of-line.
""" """
print "converting %s ..." % file print("converting %s ..." % file)
with open(file, 'r') as f_in: with open(file, 'r') as f_in:
content = f_in.read() content = f_in.read()
@ -50,12 +52,12 @@ def do_convert(file):
else: else:
from_header_seen = True from_header_seen = True
print >> new_content, line print(line, file=new_content)
with open(file, 'w') as f_out: with open(file, 'w') as f_out:
f_out.write(new_content.getvalue()) f_out.write(new_content.getvalue())
print "done" print("done")
def main(): def main():

View File

@ -12,6 +12,8 @@ Some of the test suite takes advantage of the utility functions defined here.
They can also be useful for general purpose lldb scripting. They can also be useful for general purpose lldb scripting.
""" """
from __future__ import print_function
import lldb import lldb
import os import os
import sys import sys
@ -53,7 +55,7 @@ def disassemble(target, function_or_symbol):
buf = StringIO.StringIO() buf = StringIO.StringIO()
insts = function_or_symbol.GetInstructions(target) insts = function_or_symbol.GetInstructions(target)
for i in insts: for i in insts:
print >> buf, i print(i, file=buf)
return buf.getvalue() return buf.getvalue()
# ========================================================== # ==========================================================
@ -790,8 +792,8 @@ def print_stacktrace(thread, string_buffer=False):
desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason()) desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason())
else: else:
desc = "" desc = ""
print >> output, "Stack trace for thread id={0:#x} name={1} queue={2} ".format( print("Stack trace for thread id={0:#x} name={1} queue={2} ".format(
thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc, file=output)
for i in range(depth): for i in range(depth):
frame = thread.GetFrameAtIndex(i) frame = thread.GetFrameAtIndex(i)
@ -802,13 +804,13 @@ def print_stacktrace(thread, string_buffer=False):
file_addr = addrs[i].GetFileAddress() file_addr = addrs[i].GetFileAddress()
start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress() start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress()
symbol_offset = file_addr - start_addr symbol_offset = file_addr - start_addr
print >> output, " frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format( print(" frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format(
num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset) num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset), file=output)
else: else:
print >> output, " frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format( print(" frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format(
num=i, addr=load_addr, mod=mods[i], func='%s [inlined]' % num=i, addr=load_addr, mod=mods[i], func='%s [inlined]' %
funcs[i] if frame.IsInlined() else funcs[i], file=files[i], line=lines[i], args=get_args_as_string( funcs[i] if frame.IsInlined() else funcs[i], file=files[i], line=lines[i], args=get_args_as_string(
frame, showFuncName=False) if not frame.IsInlined() else '()') frame, showFuncName=False) if not frame.IsInlined() else '()'), file=output)
if string_buffer: if string_buffer:
return output.getvalue() return output.getvalue()
@ -819,10 +821,10 @@ def print_stacktraces(process, string_buffer=False):
output = StringIO.StringIO() if string_buffer else sys.stdout output = StringIO.StringIO() if string_buffer else sys.stdout
print >> output, "Stack traces for " + str(process) print("Stack traces for " + str(process), file=output)
for thread in process: for thread in process:
print >> output, print_stacktrace(thread, string_buffer=True) print(print_stacktrace(thread, string_buffer=True), file=output)
if string_buffer: if string_buffer:
return output.getvalue() return output.getvalue()
@ -879,18 +881,18 @@ def print_registers(frame, string_buffer=False):
output = StringIO.StringIO() if string_buffer else sys.stdout output = StringIO.StringIO() if string_buffer else sys.stdout
print >> output, "Register sets for " + str(frame) print("Register sets for " + str(frame), file=output)
registerSet = frame.GetRegisters() # Return type of SBValueList. registerSet = frame.GetRegisters() # Return type of SBValueList.
print >> output, "Frame registers (size of register set = %d):" % registerSet.GetSize( print("Frame registers (size of register set = %d):" % registerSet.GetSize(
) ), file=output)
for value in registerSet: for value in registerSet:
#print >> output, value #print >> output, value
print >> output, "%s (number of children = %d):" % ( print("%s (number of children = %d):" % (
value.GetName(), value.GetNumChildren()) value.GetName(), value.GetNumChildren()), file=output)
for child in value: for child in value:
print >> output, "Name: %s, Value: %s" % ( print("Name: %s, Value: %s" % (
child.GetName(), child.GetValue()) child.GetName(), child.GetValue()), file=output)
if string_buffer: if string_buffer:
return output.getvalue() return output.getvalue()
@ -970,11 +972,11 @@ class BasicFormatter(object):
val = value.GetValue() val = value.GetValue()
if val is None and value.GetNumChildren() > 0: if val is None and value.GetNumChildren() > 0:
val = "%s (location)" % value.GetLocation() val = "%s (location)" % value.GetLocation()
print >> output, "{indentation}({type}) {name} = {value}".format( print("{indentation}({type}) {name} = {value}".format(
indentation=' ' * indent, indentation=' ' * indent,
type=value.GetTypeName(), type=value.GetTypeName(),
name=value.GetName(), name=value.GetName(),
value=val) value=val), file=output)
return output.getvalue() return output.getvalue()

View File

@ -54,7 +54,7 @@ def handle_args(driver, argv):
pid = int(options.pid) pid = int(options.pid)
driver.attachProcess(ui, pid) driver.attachProcess(ui, pid)
except ValueError: except ValueError:
print "Error: expecting integer PID, got '%s'" % options.pid print("Error: expecting integer PID, got '%s'" % options.pid)
elif options.core is not None: elif options.core is not None:
if not os.path.exists(options.core): if not os.path.exists(options.core):
raise Exception( raise Exception(

View File

@ -8,6 +8,7 @@ Example:
svn log -v | grep-svn-log.py '^ D.+why_are_you_missing.h$' svn log -v | grep-svn-log.py '^ D.+why_are_you_missing.h$'
""" """
from __future__ import print_function
import fileinput import fileinput
import re import re
@ -32,7 +33,7 @@ class Log(StringIO.StringIO):
"""Add a line to the content, if there is a previous line, commit it.""" """Add a line to the content, if there is a previous line, commit it."""
global separator global separator
if self.prev_line is not None: if self.prev_line is not None:
print >> self, self.prev_line print(self.prev_line, file=self)
self.prev_line = a_line self.prev_line = a_line
self.separator_added = (a_line == separator) self.separator_added = (a_line == separator)
@ -42,13 +43,13 @@ class Log(StringIO.StringIO):
def reset(self): def reset(self):
"""Forget about the previous lines entered.""" """Forget about the previous lines entered."""
StringIO.StringIO.__init__(self) io.StringIO.__init__(self)
self.prev_line = None self.prev_line = None
def finish(self): def finish(self):
"""Call this when you're finished with populating content.""" """Call this when you're finished with populating content."""
if self.prev_line is not None: if self.prev_line is not None:
print >> self, self.prev_line print(self.prev_line, file=self)
self.prev_line = None self.prev_line = None
@ -70,7 +71,7 @@ def grep(regexp):
# is encountered. At which point, we can return the log content. # is encountered. At which point, we can return the log content.
if line == separator: if line == separator:
log.finish() log.finish()
print log.getvalue() print(log.getvalue())
return return
log.add_line(line) log.add_line(line)
@ -85,7 +86,7 @@ def grep(regexp):
def main(): def main():
if len(sys.argv) != 2: if len(sys.argv) != 2:
print usage print(usage)
sys.exit(0) sys.exit(0)
regexp = re.compile(sys.argv[1]) regexp = re.compile(sys.argv[1])

View File

@ -54,7 +54,7 @@ class RsyncOverSsh(transfer.protocol.Protocol):
for spec in transfer_specs: for spec in transfer_specs:
cmd = self.build_rsync_command(spec, dry_run) cmd = self.build_rsync_command(spec, dry_run)
if self.options.verbose: if self.options.verbose:
print "executing the following command:\n{}".format(cmd) print("executing the following command:\n{}".format(cmd))
result = subprocess.call( result = subprocess.call(
cmd, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr) cmd, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
if result != 0: if result != 0:

View File

@ -148,7 +148,7 @@ def get_configuration(options, rcdata, config_name):
def create_transfer_agent(options, configuration): def create_transfer_agent(options, configuration):
transfer_class_spec = configuration.get_value("transfer_class") transfer_class_spec = configuration.get_value("transfer_class")
if options.verbose: if options.verbose:
print "specified transfer class: '{}'".format(transfer_class_spec) print("specified transfer class: '{}'".format(transfer_class_spec))
# Load the module (possibly package-qualified). # Load the module (possibly package-qualified).
components = transfer_class_spec.split(".") components = transfer_class_spec.split(".")
@ -250,7 +250,7 @@ def main():
rc_filename = find_appropriate_rcfile(options) rc_filename = find_appropriate_rcfile(options)
if rc_filename: if rc_filename:
if options.verbose: if options.verbose:
print "reading rc data from file '{}'".format(rc_filename) print("reading rc data from file '{}'".format(rc_filename))
rcdata = read_rcfile(rc_filename) rcdata = read_rcfile(rc_filename)
else: else:
sys.stderr.write("no rcfile specified, cannot guess configuration") sys.stderr.write("no rcfile specified, cannot guess configuration")

View File

@ -6,6 +6,8 @@ and display the disassembly result.
""" """
from __future__ import print_function
import os import os
import sys import sys
from optparse import OptionParser from optparse import OptionParser
@ -107,7 +109,7 @@ def do_llvm_mc_disassembly(
os.linesep)[-1].partition('>:')[2].strip() os.linesep)[-1].partition('>:')[2].strip()
# print "\nbytes:", memory_dump # print "\nbytes:", memory_dump
disasm_str = prev_line.partition('>:')[2] disasm_str = prev_line.partition('>:')[2]
print >> mc_input, '%s # %s' % (memory_dump, disasm_str) print('%s # %s' % (memory_dump, disasm_str), file=mc_input)
# We're done with the processing. Assign the current line to be # We're done with the processing. Assign the current line to be
# prev_line. # prev_line.
@ -123,7 +125,7 @@ def do_llvm_mc_disassembly(
f.write(mc_input.getvalue()) f.write(mc_input.getvalue())
mc_cmd = '%s -disassemble %s disasm-input.txt' % (mc, mc_options) mc_cmd = '%s -disassemble %s disasm-input.txt' % (mc, mc_options)
print "\nExecuting command:", mc_cmd print("\nExecuting command:", mc_cmd)
os.system(mc_cmd) os.system(mc_cmd)
# And invoke llvm-mc with the just recorded file. # And invoke llvm-mc with the just recorded file.
@ -217,12 +219,12 @@ Usage: %prog [options]
llvm_mc_options = opts.llvm_mc_options llvm_mc_options = opts.llvm_mc_options
# We have parsed the options. # We have parsed the options.
print "gdb commands:", gdb_commands print("gdb commands:", gdb_commands)
print "gdb options:", gdb_options print("gdb options:", gdb_options)
print "executable:", executable print("executable:", executable)
print "function:", function print("function:", function)
print "llvm-mc:", llvm_mc print("llvm-mc:", llvm_mc)
print "llvm-mc options:", llvm_mc_options print("llvm-mc options:", llvm_mc_options)
do_llvm_mc_disassembly( do_llvm_mc_disassembly(
gdb_commands, gdb_commands,

View File

@ -5,6 +5,8 @@ Run lldb to disassemble all the available functions for an executable image.
""" """
from __future__ import print_function
import os import os
import re import re
import sys import sys
@ -18,7 +20,7 @@ def setupSysPath():
# Get the directory containing the current script. # Get the directory containing the current script.
scriptPath = sys.path[0] scriptPath = sys.path[0]
if not scriptPath.endswith(os.path.join('utils', 'test')): if not scriptPath.endswith(os.path.join('utils', 'test')):
print "This script expects to reside in lldb's utils/test directory." print("This script expects to reside in lldb's utils/test directory.")
sys.exit(-1) sys.exit(-1)
# This is our base name component. # This is our base name component.
@ -63,8 +65,8 @@ def setupSysPath():
lldbPath = baiPath2 lldbPath = baiPath2
if not lldbPath: if not lldbPath:
print 'This script requires lldb.py to be in either ' + dbgPath + ',', print('This script requires lldb.py to be in either ' + dbgPath + ',', end=' ')
print relPath + ', or ' + baiPath print(relPath + ', or ' + baiPath)
sys.exit(-1) sys.exit(-1)
# This is to locate the lldb.py module. Insert it right after sys.path[0]. # This is to locate the lldb.py module. Insert it right after sys.path[0].
@ -74,15 +76,15 @@ def setupSysPath():
def run_command(ci, cmd, res, echo=True): def run_command(ci, cmd, res, echo=True):
if echo: if echo:
print "run command:", cmd print("run command:", cmd)
ci.HandleCommand(cmd, res) ci.HandleCommand(cmd, res)
if res.Succeeded(): if res.Succeeded():
if echo: if echo:
print "run_command output:", res.GetOutput() print("run_command output:", res.GetOutput())
else: else:
if echo: if echo:
print "run command failed!" print("run command failed!")
print "run_command error:", res.GetError() print("run_command error:", res.GetError())
def do_lldb_disassembly(lldb_commands, exe, disassemble_options, num_symbols, def do_lldb_disassembly(lldb_commands, exe, disassemble_options, num_symbols,
@ -135,7 +137,7 @@ def do_lldb_disassembly(lldb_commands, exe, disassemble_options, num_symbols,
if symbols: if symbols:
for i in range(len(symbols)): for i in range(len(symbols)):
if verbose: if verbose:
print "symbol:", symbols[i] print("symbol:", symbols[i])
yield symbols[i] yield symbols[i]
else: else:
limited = True if num != -1 else False limited = True if num != -1 else False
@ -146,7 +148,7 @@ def do_lldb_disassembly(lldb_commands, exe, disassemble_options, num_symbols,
stream = lldb.SBStream() stream = lldb.SBStream()
for m in target.module_iter(): for m in target.module_iter():
if verbose: if verbose:
print "module:", m print("module:", m)
for s in m: for s in m:
if limited and count >= num: if limited and count >= num:
return return
@ -159,18 +161,18 @@ def do_lldb_disassembly(lldb_commands, exe, disassemble_options, num_symbols,
# If we come here, we're ready to disassemble the symbol. # If we come here, we're ready to disassemble the symbol.
if verbose: if verbose:
print "symbol:", s.GetName() print("symbol:", s.GetName())
if IsCodeType(s): if IsCodeType(s):
if limited: if limited:
count = count + 1 count = count + 1
if verbose: if verbose:
print "returning symbol:", s.GetName() print("returning symbol:", s.GetName())
yield s.GetName() yield s.GetName()
if verbose: if verbose:
print "start address:", s.GetStartAddress() print("start address:", s.GetStartAddress())
print "end address:", s.GetEndAddress() print("end address:", s.GetEndAddress())
s.GetDescription(stream) s.GetDescription(stream)
print "symbol description:", stream.GetData() print("symbol description:", stream.GetData())
stream.Clear() stream.Clear()
# Disassembly time. # Disassembly time.
@ -273,13 +275,13 @@ Usage: %prog [options]
# We have parsed the options. # We have parsed the options.
if not quiet_disassembly: if not quiet_disassembly:
print "lldb commands:", lldb_commands print("lldb commands:", lldb_commands)
print "executable:", executable print("executable:", executable)
print "disassemble options:", disassemble_options print("disassemble options:", disassemble_options)
print "quiet disassembly output:", quiet_disassembly print("quiet disassembly output:", quiet_disassembly)
print "num of symbols to disassemble:", num_symbols print("num of symbols to disassemble:", num_symbols)
print "symbols to disassemble:", symbols_to_disassemble print("symbols to disassemble:", symbols_to_disassemble)
print "regular expression of symbols to disassemble:", re_symbol_pattern print("regular expression of symbols to disassemble:", re_symbol_pattern)
setupSysPath() setupSysPath()
do_lldb_disassembly(lldb_commands, executable, disassemble_options, do_lldb_disassembly(lldb_commands, executable, disassemble_options,

View File

@ -5,6 +5,8 @@ Run llvm-mc interactively.
""" """
from __future__ import print_function
import os import os
import sys import sys
from optparse import OptionParser from optparse import OptionParser
@ -105,8 +107,8 @@ Usage: %prog [options]
llvm_mc_options = opts.llvm_mc_options llvm_mc_options = opts.llvm_mc_options
# We have parsed the options. # We have parsed the options.
print "llvm-mc:", llvm_mc print("llvm-mc:", llvm_mc)
print "llvm-mc options:", llvm_mc_options print("llvm-mc options:", llvm_mc_options)
llvm_mc_loop(llvm_mc, llvm_mc_options) llvm_mc_loop(llvm_mc, llvm_mc_options)

View File

@ -7,6 +7,8 @@ The code for sending of the directory is copied from
http://docs.python.org/library/email-examples.html. http://docs.python.org/library/email-examples.html.
""" """
from __future__ import print_function
import os import os
import sys import sys
import shutil import shutil
@ -33,7 +35,7 @@ def runTestsuite(testDir, sessDir, envs=None):
list = env.split('=') list = env.split('=')
var = list[0].strip() var = list[0].strip()
val = list[1].strip() val = list[1].strip()
print var + "=" + val print(var + "=" + val)
os.environ[var] = val os.environ[var] = val
import shlex import shlex

View File

@ -5,6 +5,8 @@ Run lldb disassembler on all the binaries specified by a combination of root dir
and path pattern. and path pattern.
""" """
from __future__ import print_function
import os import os
import sys import sys
import subprocess import subprocess
@ -68,7 +70,7 @@ def walk_and_invoke(sdk_root, path_regexp, suffix, num_symbols):
command = template % ( command = template % (
scriptPath, path, num_symbols if num_symbols > 0 else 1000) scriptPath, path, num_symbols if num_symbols > 0 else 1000)
print "Running %s" % (command) print("Running %s" % (command))
os.system(command) os.system(command)
@ -130,10 +132,10 @@ and path pattern.
suffix = opts.suffix suffix = opts.suffix
num_symbols = opts.num_symbols num_symbols = opts.num_symbols
print "Root directory for SDK symbols:", root_dir print("Root directory for SDK symbols:", root_dir)
print "Regular expression for the binaries:", path_pattern print("Regular expression for the binaries:", path_pattern)
print "Suffix of the binaries to look for:", suffix print("Suffix of the binaries to look for:", suffix)
print "num of symbols to disassemble:", num_symbols print("num of symbols to disassemble:", num_symbols)
walk_and_invoke(root_dir, path_regexp, suffix, num_symbols) walk_and_invoke(root_dir, path_regexp, suffix, num_symbols)

View File

@ -5,6 +5,8 @@ Run a program via lldb until it fails.
The lldb executable is located via your PATH env variable, if not specified. The lldb executable is located via your PATH env variable, if not specified.
""" """
from __future__ import print_function
import os import os
import sys import sys
from optparse import OptionParser from optparse import OptionParser
@ -65,7 +67,7 @@ def do_lldb_launch_loop(lldb_command, exe, exe_options):
break break
elif index == 2: elif index == 2:
# Something went wrong. # Something went wrong.
print "TIMEOUT occurred:", str(lldb) print("TIMEOUT occurred:", str(lldb))
# Give control of lldb shell to the user. # Give control of lldb shell to the user.
lldb.interact() lldb.interact()
@ -120,9 +122,9 @@ The lldb executable is located via your PATH env variable, if not specified.\
exe_options = opts.exe_options exe_options = opts.exe_options
# We have parsed the options. # We have parsed the options.
print "lldb command:", lldb_command print("lldb command:", lldb_command)
print "executable:", exe print("executable:", exe)
print "executable options:", exe_options print("executable options:", exe_options)
do_lldb_launch_loop(lldb_command, exe, exe_options) do_lldb_launch_loop(lldb_command, exe, exe_options)

View File

@ -3,6 +3,8 @@
# This file defines the layer that talks to lldb # This file defines the layer that talks to lldb
# #
from __future__ import print_function
import os import os
import re import re
import sys import sys
@ -164,7 +166,7 @@ class LLDBController(object):
self.ui.activate() self.ui.activate()
self.pid = self.process.GetProcessID() self.pid = self.process.GetProcessID()
print "Attached to %s (pid=%d)" % (process_name, self.pid) print("Attached to %s (pid=%d)" % (process_name, self.pid))
def doDetach(self): def doDetach(self):
if self.process is not None and self.process.IsValid(): if self.process is not None and self.process.IsValid():
@ -196,7 +198,7 @@ class LLDBController(object):
self.process.GetBroadcaster().AddListener( self.process.GetBroadcaster().AddListener(
self.processListener, lldb.SBProcess.eBroadcastBitStateChanged) self.processListener, lldb.SBProcess.eBroadcastBitStateChanged)
print "Launched %s %s (pid=%d)" % (exe, args, self.pid) print("Launched %s %s (pid=%d)" % (exe, args, self.pid))
if not stop_at_entry: if not stop_at_entry:
self.doContinue() self.doContinue()
@ -323,7 +325,7 @@ class LLDBController(object):
if success: if success:
self.ui.update(self.target, "", self, goto_file) self.ui.update(self.target, "", self, goto_file)
if len(output) > 0 and print_on_success: if len(output) > 0 and print_on_success:
print output print(output)
else: else:
sys.stderr.write(output) sys.stderr.write(output)

View File

@ -1,6 +1,8 @@
# LLDB UI state in the Vim user interface. # LLDB UI state in the Vim user interface.
from __future__ import print_function
import os import os
import re import re
import sys import sys
@ -143,7 +145,7 @@ class UI:
if curname is not None and is_same_file(curname, fname): if curname is not None and is_same_file(curname, fname):
move_cursor(line, 0) move_cursor(line, 0)
elif move_cursor: elif move_cursor:
print "FIXME: not sure where to move cursor because %s != %s " % (vim.current.buffer.name, fname) print("FIXME: not sure where to move cursor because %s != %s " % (vim.current.buffer.name, fname))
def update_breakpoints(self, target, buffers): def update_breakpoints(self, target, buffers):
""" Decorates buffer with signs corresponding to breakpoints in target. """ """ Decorates buffer with signs corresponding to breakpoints in target. """
@ -219,7 +221,7 @@ class UI:
self.update_pc(process, self.get_user_buffers, goto_file) self.update_pc(process, self.get_user_buffers, goto_file)
if status is not None and len(status) > 0: if status is not None and len(status) > 0:
print status print(status)
def haveBreakpoint(self, file, line): def haveBreakpoint(self, file, line):
""" Returns True if we have a breakpoint at file:line, False otherwise """ """ Returns True if we have a breakpoint at file:line, False otherwise """