Added the ability to disassembly GDB remote packets with the python file. This will make it easier to symbolicate the packet log output since we can use the lldb.utils.symbolication package module to symbolicate register values.

llvm-svn: 157835
This commit is contained in:
Greg Clayton 2012-06-01 20:23:54 +00:00
parent 56d756dc33
commit 8ebb9a8564
1 changed files with 821 additions and 22 deletions

View File

@ -19,17 +19,156 @@
import commands import commands
import optparse import optparse
import os import os
import shlex
import re import re
import shlex
import string
import sys
import tempfile import tempfile
log_file = '' class TerminalColors:
'''Simple terminal colors class'''
def __init__(self, file = sys.stdout, enabled = True):
self.file = file
# TODO: discover terminal type from "file" and disable if
# it can't handle the color codes
self.enabled = enabled
def reset(self):
'''Reset all terminal colors and formatting.'''
if self.enabled:
self.file.write("\x1b[0m");
def bold(self, on = True):
'''Enable or disable bold depending on the "on" paramter.'''
if self.enabled:
if on:
self.file.write("\x1b[1m");
else:
self.file.write("\x1b[22m");
def italics(self, on = True):
'''Enable or disable italics depending on the "on" paramter.'''
if self.enabled:
if on:
self.file.write("\x1b[3m");
else:
self.file.write("\x1b[23m");
def underline(self, on = True):
'''Enable or disable underline depending on the "on" paramter.'''
if self.enabled:
if on:
self.file.write("\x1b[4m");
else:
self.file.write("\x1b[24m");
def inverse(self, on = True):
'''Enable or disable inverse depending on the "on" paramter.'''
if self.enabled:
if on:
self.file.write("\x1b[7m");
else:
self.file.write("\x1b[27m");
def strike(self, on = True):
'''Enable or disable strike through depending on the "on" paramter.'''
if self.enabled:
if on:
self.file.write("\x1b[9m");
else:
self.file.write("\x1b[29m");
def black(self, fg = True):
'''Set the foreground or background color to black.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[30m");
else:
self.file.write("\x1b[40m");
def red(self, fg = True):
'''Set the foreground or background color to red.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[31m");
else:
self.file.write("\x1b[41m");
def green(self, fg = True):
'''Set the foreground or background color to green.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[32m");
else:
self.file.write("\x1b[42m");
def yellow(self, fg = True):
'''Set the foreground or background color to yellow.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[43m");
else:
self.file.write("\x1b[33m");
def blue(self, fg = True):
'''Set the foreground or background color to blue.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[34m");
else:
self.file.write("\x1b[44m");
def magenta(self, fg = True):
'''Set the foreground or background color to magenta.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[35m");
else:
self.file.write("\x1b[45m");
def cyan(self, fg = True):
'''Set the foreground or background color to cyan.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[36m");
else:
self.file.write("\x1b[46m");
def white(self, fg = True):
'''Set the foreground or background color to white.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[37m");
else:
self.file.write("\x1b[47m");
def default(self, fg = True):
'''Set the foreground or background color to the default.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
self.file.write("\x1b[39m");
else:
self.file.write("\x1b[49m");
#----------------------------------------------------------------------
# Global variables
#----------------------------------------------------------------------
g_log_file = ''
g_byte_order = 'little'
def start_gdb_log(debugger, command, result, dict): def start_gdb_log(debugger, command, result, dict):
'''Start logging GDB remote packets by enabling logging with timestamps and '''Start logging GDB remote packets by enabling logging with timestamps and
thread safe logging. Follow a call to this function with a call to "stop_gdb_log" thread safe logging. Follow a call to this function with a call to "stop_gdb_log"
in order to dump out the commands.''' in order to dump out the commands.'''
global log_file global g_log_file
command_args = shlex.split(command) command_args = shlex.split(command)
usage = "usage: start_gdb_log [options] [<LOGFILEPATH>]" usage = "usage: start_gdb_log [options] [<LOGFILEPATH>]"
description='''The command enables GDB remote packet logging with timestamps. The packets will be logged to <LOGFILEPATH> if supplied, or a temporary file will be used. Logging stops when stop_gdb_log is called and the packet times will description='''The command enables GDB remote packet logging with timestamps. The packets will be logged to <LOGFILEPATH> if supplied, or a temporary file will be used. Logging stops when stop_gdb_log is called and the packet times will
@ -41,18 +180,18 @@ def start_gdb_log(debugger, command, result, dict):
except: except:
return return
if log_file: if g_log_file:
result.PutCString ('error: logging is already in progress with file "%s"', log_file) result.PutCString ('error: logging is already in progress with file "%s"', g_log_file)
else: else:
args_len = len(args) args_len = len(args)
if args_len == 0: if args_len == 0:
log_file = tempfile.mktemp() g_log_file = tempfile.mktemp()
elif len(args) == 1: elif len(args) == 1:
log_file = args[0] g_log_file = args[0]
if log_file: if g_log_file:
debugger.HandleCommand('log enable --threadsafe --timestamp --file "%s" gdb-remote packets' % log_file); debugger.HandleCommand('log enable --threadsafe --timestamp --file "%s" gdb-remote packets' % g_log_file);
result.PutCString ("GDB packet logging enable with log file '%s'\nUse the 'stop_gdb_log' command to stop logging and show packet statistics." % log_file) result.PutCString ("GDB packet logging enable with log file '%s'\nUse the 'stop_gdb_log' command to stop logging and show packet statistics." % g_log_file)
return return
result.PutCString ('error: invalid log file path') result.PutCString ('error: invalid log file path')
@ -63,7 +202,7 @@ def stop_gdb_log(debugger, command, result, dict):
to "start_gdb_log" and normalize the timestamps to be relative to the first to "start_gdb_log" and normalize the timestamps to be relative to the first
timestamp in the log file. Also print out statistics for how long each timestamp in the log file. Also print out statistics for how long each
command took to allow performance bottlenecks to be determined.''' command took to allow performance bottlenecks to be determined.'''
global log_file global g_log_file
# Any commands whose names might be followed by more valid C identifier # Any commands whose names might be followed by more valid C identifier
# characters must be listed here # characters must be listed here
command_args = shlex.split(command) command_args = shlex.split(command)
@ -78,19 +217,613 @@ def stop_gdb_log(debugger, command, result, dict):
except: except:
return return
if not log_file: if not g_log_file:
result.PutCString ('error: logging must have been previously enabled with a call to "stop_gdb_log"') result.PutCString ('error: logging must have been previously enabled with a call to "stop_gdb_log"')
elif os.path.exists (log_file): elif os.path.exists (g_log_file):
if len(args) == 0: if len(args) == 0:
debugger.HandleCommand('log disable gdb-remote packets'); debugger.HandleCommand('log disable gdb-remote packets');
result.PutCString ("GDB packet logging disabled. Logged packets are in '%s'" % log_file) result.PutCString ("GDB packet logging disabled. Logged packets are in '%s'" % g_log_file)
parse_gdb_log_file (log_file, options) parse_gdb_log_file (g_log_file, options)
log_file = None g_log_file = None
else: else:
result.PutCString (usage) result.PutCString (usage)
else: else:
print 'error: the GDB packet log file "%s" does not exist' % log_file print 'error: the GDB packet log file "%s" does not exist' % g_log_file
def is_hex_byte(str):
if len(str) == 2:
return str[0] in string.hexdigits and str[1] in string.hexdigits;
return False
# global register info list
g_register_infos = list()
g_max_register_info_name_len = 0
class RegisterInfo:
"""Class that represents register information"""
def __init__(self, kvp):
self.info = dict()
for kv in kvp:
key = kv[0]
value = kv[1]
self.info[key] = value
def name(self):
'''Get the name of the register.'''
if self.info and 'name' in self.info:
return self.info['name']
return None
def bit_size(self):
'''Get the size in bits of the register.'''
if self.info and 'bitsize' in self.info:
return int(self.info['bitsize'])
return 0
def byte_size(self):
'''Get the size in bytes of the register.'''
return self.bit_size() / 8
def get_value_from_hex_string(self, hex_str):
'''Dump the register value given a native byte order encoded hex ASCII byte string.'''
encoding = self.info['encoding']
bit_size = self.bit_size()
packet = Packet(hex_str)
if encoding == 'uint':
uval = packet.get_hex_uint(g_byte_order)
if bit_size == 8:
return '0x%2.2x' % (uval)
elif bit_size == 16:
return '0x%4.4x' % (uval)
elif bit_size == 32:
return '0x%8.8x' % (uval)
elif bit_size == 64:
return '0x%16.16x' % (uval)
bytes = list();
uval = packet.get_hex_uint8()
while uval != None:
bytes.append(uval)
uval = packet.get_hex_uint8()
value_str = '0x'
if g_byte_order == 'little':
bytes.reverse()
for byte in bytes:
value_str += '%2.2x' % byte
return '%s' % (value_str)
def __str__(self):
'''Dump the register info key/value pairs'''
s = ''
for key in self.info.keys():
if s:
s += ', '
s += "%s=%s " % (key, self.info[key])
return s
class Packet:
"""Class that represents a packet that contains string data"""
def __init__(self, packet_str):
self.str = packet_str
def peek_char(self):
ch = 0
if self.str:
ch = self.str[0]
return ch
def get_char(self):
ch = 0
if self.str:
ch = self.str[0]
self.str = self.str[1:]
return ch
def get_hex_uint8(self):
if self.str and len(self.str) >= 2 and self.str[0] in string.hexdigits and self.str[1] in string.hexdigits:
uval = int(self.str[0:2], 16)
self.str = self.str[2:]
return uval
return None
def get_hex_uint16(self, byte_order):
uval = 0
if byte_order == 'big':
uval |= self.get_hex_uint8() << 8
uval |= self.get_hex_uint8()
else:
uval |= self.get_hex_uint8()
uval |= self.get_hex_uint8() << 8
return uval
def get_hex_uint32(self, byte_order):
uval = 0
if byte_order == 'big':
uval |= self.get_hex_uint8() << 24
uval |= self.get_hex_uint8() << 16
uval |= self.get_hex_uint8() << 8
uval |= self.get_hex_uint8()
else:
uval |= self.get_hex_uint8()
uval |= self.get_hex_uint8() << 8
uval |= self.get_hex_uint8() << 16
uval |= self.get_hex_uint8() << 24
return uval
def get_hex_uint64(self, byte_order):
uval = 0
if byte_order == 'big':
uval |= self.get_hex_uint8() << 56
uval |= self.get_hex_uint8() << 48
uval |= self.get_hex_uint8() << 40
uval |= self.get_hex_uint8() << 32
uval |= self.get_hex_uint8() << 24
uval |= self.get_hex_uint8() << 16
uval |= self.get_hex_uint8() << 8
uval |= self.get_hex_uint8()
else:
uval |= self.get_hex_uint8()
uval |= self.get_hex_uint8() << 8
uval |= self.get_hex_uint8() << 16
uval |= self.get_hex_uint8() << 24
uval |= self.get_hex_uint8() << 32
uval |= self.get_hex_uint8() << 40
uval |= self.get_hex_uint8() << 48
uval |= self.get_hex_uint8() << 56
return uval
def get_hex_chars(self, n = 0):
str_len = len(self.str)
if n == 0:
# n was zero, so we need to determine all hex chars and
# stop when we hit the end of the string of a non-hex character
while n < str_len and self.str[n] in string.hexdigits:
n = n + 1
else:
if n > str_len:
return None # Not enough chars
# Verify all chars are hex if a length was specified
for i in range(n):
if self.str[i] not in string.hexdigits:
return None # Not all hex digits
if n == 0:
return None
hex_str = self.str[0:n]
self.str = self.str[n:]
return hex_str
def get_hex_uint(self, byte_order, n = 0):
if byte_order == 'big':
hex_str = self.get_hex_chars(n)
if hex_str == None:
return None
return int(hex_str, 16)
else:
uval = self.get_hex_uint8()
if uval == None:
return None
uval_result = 0
shift = 0
while uval != None:
uval_result |= (uval << shift)
shift += 8
uval = self.get_hex_uint8()
return uval_result
def get_key_value_pairs(self):
kvp = list()
key_value_pairs = string.split(self.str, ';')
for key_value_pair in key_value_pairs:
if len(key_value_pair):
kvp.append(string.split(key_value_pair, ':'))
return kvp
def split(self, ch):
return string.split(self.str, ch)
def split_hex(self, ch, byte_order):
hex_values = list()
strings = string.split(self.str, ch)
for str in strings:
hex_values.append(Packet(str).get_hex_uint(byte_order))
return hex_values
def __str__(self):
return self.str
def __len__(self):
return len(self.str)
g_thread_suffix_regex = re.compile(';thread:([0-9a-fA-F]+);')
def get_thread_from_thread_suffix(str):
if str:
match = g_thread_suffix_regex.match (str)
if match:
return int(match.group(1), 16)
return None
def cmd_stop_reply(command, args):
print "get_last_stop_info()"
def rsp_stop_reply(cmd, cmd_args, rsp):
global g_byte_order
packet = Packet(rsp)
stop_type = packet.get_char()
if stop_type == 'T' or stop_type == 'S':
signo = packet.get_hex_uint8()
print ' signal = %i' % signo
key_value_pairs = packet.get_key_value_pairs()
for key_value_pair in key_value_pairs:
key = key_value_pair[0]
value = key_value_pair[1]
if is_hex_byte(key):
reg_num = Packet(key).get_hex_uint8()
if reg_num < len(g_register_infos):
reg_info = g_register_infos[reg_num]
print ' ' + reg_info.name() + ' = ' + reg_info.get_value_from_hex_string (value)
else:
reg_value = Packet(value).get_hex_uint(g_byte_order)
print ' reg(%u) = 0x%x' % (reg_num, reg_value)
else:
print ' %s = %s' % (key, value)
elif stop_type == 'W':
exit_status = packet.get_hex_uint8()
print 'exit (status=%i)' % exit_status
elif stop_type == 'O':
print 'stdout = %s' % packet.str
def cmd_unknown_packet(cmd, args):
if args:
print "cmd: %s, args: %s", cmd, args
else:
print "cmd: %s", cmd
def cmd_query_packet(command, args):
if args:
print "query: %s, args: %s" % (command, args)
else:
print "query: %s" % (command)
def rsp_ok_error(rsp):
print "rsp: ", rsp
def rsp_ok_means_supported(cmd, cmd_args, rsp):
if rsp == 'OK':
print "%s%s is supported" % (cmd, cmd_args)
elif rsp == '':
print "%s%s is not supported" % (cmd, cmd_args)
else:
print "%s%s -> %s" % (cmd, cmd_args, rsp)
def rsp_ok_means_success(cmd, cmd_args, rsp):
if rsp == 'OK':
print "success"
elif rsp == '':
print "%s%s is not supported" % (cmd, cmd_args)
else:
print "%s%s -> %s" % (cmd, cmd_args, rsp)
def rsp_dump_key_value_pairs(cmd, cmd_args, rsp):
if rsp:
packet = Packet(rsp)
key_value_pairs = packet.get_key_value_pairs()
for key_value_pair in key_value_pairs:
key = key_value_pair[0]
value = key_value_pair[1]
print " %s = %s" % (key, value)
else:
print "not supported"
def cmd_vCont(cmd, args):
if args == '?':
print "%s: get supported extended continue modes" % (cmd)
else:
got_other_threads = 0
s = ''
for thread_action in string.split(args[1:], ';'):
(short_action, thread) = string.split(thread_action, ':')
tid = int(thread, 16)
if short_action == 'c':
action = 'continue'
elif short_action == 's':
action = 'step'
elif short_action[0] == 'C':
action = 'continue with signal 0x%s' % (short_action[1:])
elif short_action == 'S':
action = 'step with signal 0x%s' % (short_action[1:])
else:
action = short_action
if s:
s += ', '
if tid == -1:
got_other_threads = 1
s += 'other-threads:'
else:
s += 'thread 0x%4.4x: %s' % (tid, action)
if got_other_threads:
print "extended_continue (%s)" % (s)
else:
print "extended_continue (%s, other-threads: suspend)" % (s)
def rsp_vCont(cmd, cmd_args, rsp):
if cmd_args == '?':
# Skip the leading 'vCont;'
rsp = rsp[6:]
modes = string.split(rsp, ';')
s = "%s: supported extended continue modes include: " % (cmd)
for i, mode in enumerate(modes):
if i:
s += ', '
if mode == 'c':
s += 'continue'
elif mode == 'C':
s += 'continue with signal'
elif mode == 's':
s += 'step'
elif mode == 'S':
s += 'step with signal'
else:
s += 'unrecognized vCont mode: ', mode
print s
elif rsp:
if rsp[0] == 'T' or rsp[0] == 'S' or rsp[0] == 'W' or rsp[0] == 'X':
rsp_stop_reply (cmd, cmd_args, rsp)
return
if rsp[0] == 'O':
print "stdout: %s" % (rsp)
return
else:
print "not supported (cmd = '%s', args = '%s', rsp = '%s')" % (cmd, cmd_args, rsp)
def cmd_vAttach(cmd, args):
(extra_command, args) = string.split(args, ';')
if extra_command:
print "%s%s(%s)" % (cmd, extra_command, args)
else:
print "attach_pid(%s)" % args
def cmd_qRegisterInfo(cmd, args):
print 'query_register_info(reg_num=%i)' % (int(args, 16))
def rsp_qRegisterInfo(cmd, cmd_args, rsp):
global g_max_register_info_name_len
print 'query_register_info(reg_num=%i):' % (int(cmd_args, 16)),
if len(rsp) == 3 and rsp[0] == 'E':
g_max_register_info_name_len = 0
for reg_info in g_register_infos:
name_len = len(reg_info.name())
if g_max_register_info_name_len < name_len:
g_max_register_info_name_len = name_len
print' DONE'
else:
packet = Packet(rsp)
reg_info = RegisterInfo(packet.get_key_value_pairs())
g_register_infos.append(reg_info)
print reg_info
def cmd_qThreadInfo(cmd, args):
if cmd == 'qfThreadInfo':
query_type = 'first'
else:
query_type = 'subsequent'
print 'get_current_thread_list(type=%s)' % (query_type)
def rsp_qThreadInfo(cmd, cmd_args, rsp):
packet = Packet(rsp)
response_type = packet.get_char()
if response_type == 'm':
tids = packet.split_hex(';', 'big')
for i, tid in enumerate(tids):
if i:
print ',',
print '0x%x' % (tid),
print
elif response_type == 'l':
print 'END'
def rsp_hex_big_endian(cmd, cmd_args, rsp):
packet = Packet(rsp)
uval = packet.get_hex_uint('big')
print '%s: 0x%x' % (cmd, uval)
def cmd_read_memory(cmd, args):
packet = Packet(args)
addr = packet.get_hex_uint('big')
comma = packet.get_char()
size = packet.get_hex_uint('big')
print 'read_memory (addr = 0x%x, size = %u)' % (addr, size)
def dump_hex_memory_buffer(addr, hex_byte_str):
packet = Packet(hex_byte_str)
idx = 0
ascii = ''
uval = packet.get_hex_uint8()
while uval != None:
if ((idx % 16) == 0):
if ascii:
print ' ', ascii
ascii = ''
print '0x%x:' % (addr + idx),
print '%2.2x' % (uval),
if 0x20 <= uval and uval < 0x7f:
ascii += '%c' % uval
else:
ascii += '.'
uval = packet.get_hex_uint8()
idx = idx + 1
if ascii:
print ' ', ascii
ascii = ''
def cmd_write_memory(cmd, args):
packet = Packet(args)
addr = packet.get_hex_uint('big')
if packet.get_char() != ',':
print 'error: invalid write memory command (missing comma after address)'
return
size = packet.get_hex_uint('big')
if packet.get_char() != ':':
print 'error: invalid write memory command (missing colon after size)'
return
print 'write_memory (addr = 0x%x, size = %u, data:' % (addr, size)
dump_hex_memory_buffer (addr, packet.str)
def cmd_alloc_memory(cmd, args):
packet = Packet(args)
byte_size = packet.get_hex_uint('big')
if packet.get_char() != ',':
print 'error: invalid allocate memory command (missing comma after address)'
return
print 'allocate_memory (byte-size = %u (0x%x), permissions = %s)' % (byte_size, byte_size, packet.str)
def rsp_alloc_memory(cmd, cmd_args, rsp):
packet = Packet(rsp)
addr = packet.get_hex_uint('big')
print 'addr = 0x%x' % addr
def cmd_dealloc_memory(cmd, args):
packet = Packet(args)
addr = packet.get_hex_uint('big')
if packet.get_char() != ',':
print 'error: invalid allocate memory command (missing comma after address)'
return
print 'deallocate_memory (addr = 0x%x, permissions = %s)' % (addr, packet.str)
def rsp_memory_bytes(cmd, cmd_args, rsp):
addr = Packet(cmd_args).get_hex_uint('big')
dump_hex_memory_buffer (addr, rsp)
def get_register_name_equal_value(reg_num, hex_value_str):
if reg_num < len(g_register_infos):
reg_info = g_register_infos[reg_num]
return reg_info.name() + ' = ' + reg_info.get_value_from_hex_string (hex_value_str)
else:
reg_value = Packet(hex_value_str).get_hex_uint(g_byte_order)
return 'reg(%u) = 0x%x' % (reg_num, reg_value)
def cmd_read_one_reg(cmd, args):
packet = Packet(args)
reg_num = packet.get_hex_uint('big')
tid = get_thread_from_thread_suffix (packet.str)
name = None
if reg_num < len(g_register_infos):
name = g_register_infos[reg_num].name ()
if packet.str:
packet.get_char() # skip ;
thread_info = packet.get_key_value_pairs()
tid = int(thread_info[0][1], 16)
s = 'read_register (reg_num=%u' % reg_num
if name:
s += ' (%s)' % (name)
if tid != None:
s += ', tid = 0x%4.4x' % (tid)
s += ')'
print s
def rsp_read_one_reg(cmd, cmd_args, rsp):
packet = Packet(cmd_args)
reg_num = packet.get_hex_uint('big')
print get_register_name_equal_value (reg_num, rsp)
def cmd_write_one_reg(cmd, args):
packet = Packet(args)
reg_num = packet.get_hex_uint('big')
if packet.get_char() != '=':
print 'error: invalid register write packet'
else:
name = None
hex_value_str = packet.get_hex_chars()
tid = get_thread_from_thread_suffix (packet.str)
s = 'write_register (reg_num=%u' % reg_num
if name:
s += ' (%s)' % (name)
s += ', value = '
s += get_register_name_equal_value(reg_num, hex_value_str)
if tid != None:
s += ', tid = 0x%4.4x' % (tid)
s += ')'
print s
def dump_all_regs(packet):
for reg_info in g_register_infos:
nibble_size = reg_info.bit_size() / 4
hex_value_str = packet.get_hex_chars(nibble_size)
if hex_value_str != None:
value = reg_info.get_value_from_hex_string (hex_value_str)
print '%*s = %s' % (g_max_register_info_name_len, reg_info.name(), value)
else:
return
def cmd_read_all_regs(cmd, cmd_args):
packet = Packet(cmd_args)
packet.get_char() # toss the 'g' command character
tid = get_thread_from_thread_suffix (packet.str)
if tid != None:
print 'read_all_register(thread = 0x%4.4x)' % tid
else:
print 'read_all_register()'
def rsp_read_all_regs(cmd, cmd_args, rsp):
packet = Packet(rsp)
dump_all_regs (packet)
def cmd_write_all_regs(cmd, args):
packet = Packet(args)
print 'write_all_registers()'
dump_all_regs (packet)
g_bp_types = [ "software_bp", "hardware_bp", "write_wp", "read_wp", "access_wp" ]
def cmd_bp(cmd, args):
if cmd == 'Z':
s = 'set_'
else:
s = 'clear_'
packet = Packet (args)
bp_type = packet.get_hex_uint('big')
packet.get_char() # Skip ,
bp_addr = packet.get_hex_uint('big')
packet.get_char() # Skip ,
bp_size = packet.get_hex_uint('big')
s += g_bp_types[bp_type]
s += " (addr = 0x%x, size = %u)" % (bp_addr, bp_size)
print s
def cmd_mem_rgn_info(cmd, args):
packet = Packet(args)
packet.get_char() # skip ':' character
addr = packet.get_hex_uint('big')
print 'get_memory_region_info (addr=0x%x)' % (addr)
def cmd_kill(cmd, args):
print 'kill_process()'
gdb_remote_commands = {
'\\?' : { 'cmd' : cmd_stop_reply , 'rsp' : rsp_stop_reply , 'name' : "stop reply pacpket"},
'QStartNoAckMode' : { 'cmd' : cmd_query_packet , 'rsp' : rsp_ok_means_supported , 'name' : "query if no ack mode is supported"},
'QThreadSuffixSupported' : { 'cmd' : cmd_query_packet , 'rsp' : rsp_ok_means_supported , 'name' : "query if thread suffix is supported" },
'QListThreadsInStopReply' : { 'cmd' : cmd_query_packet , 'rsp' : rsp_ok_means_supported , 'name' : "query if threads in stop reply packets are supported" },
'qHostInfo' : { 'cmd' : cmd_query_packet , 'rsp' : rsp_dump_key_value_pairs, 'name' : "get host information" },
'vCont' : { 'cmd' : cmd_vCont , 'rsp' : rsp_vCont , 'name' : "extended continue command" },
'vAttach' : { 'cmd' : cmd_vAttach , 'rsp' : rsp_stop_reply , 'name' : "attach to process" },
'qRegisterInfo' : { 'cmd' : cmd_qRegisterInfo , 'rsp' : rsp_qRegisterInfo , 'name' : "query register info" },
'qfThreadInfo' : { 'cmd' : cmd_qThreadInfo , 'rsp' : rsp_qThreadInfo , 'name' : "get current thread list" },
'qsThreadInfo' : { 'cmd' : cmd_qThreadInfo , 'rsp' : rsp_qThreadInfo , 'name' : "get current thread list" },
'qShlibInfoAddr' : { 'cmd' : cmd_query_packet , 'rsp' : rsp_hex_big_endian , 'name' : "get shared library info address" },
'qMemoryRegionInfo' : { 'cmd' : cmd_mem_rgn_info , 'rsp' : rsp_dump_key_value_pairs, 'name' : "get memory region information" },
'm' : { 'cmd' : cmd_read_memory , 'rsp' : rsp_memory_bytes , 'name' : "read memory" },
'M' : { 'cmd' : cmd_write_memory , 'rsp' : rsp_ok_means_success , 'name' : "write memory" },
'_M' : { 'cmd' : cmd_alloc_memory , 'rsp' : rsp_alloc_memory , 'name' : "allocate memory" },
'_m' : { 'cmd' : cmd_dealloc_memory, 'rsp' : rsp_ok_means_success , 'name' : "deallocate memory" },
'p' : { 'cmd' : cmd_read_one_reg , 'rsp' : rsp_read_one_reg , 'name' : "read single register" },
'P' : { 'cmd' : cmd_write_one_reg , 'rsp' : rsp_ok_means_success , 'name' : "write single register" },
'g' : { 'cmd' : cmd_read_all_regs , 'rsp' : rsp_read_all_regs , 'name' : "read all registers" },
'G' : { 'cmd' : cmd_write_all_regs, 'rsp' : rsp_ok_means_success , 'name' : "write all registers" },
'z' : { 'cmd' : cmd_bp , 'rsp' : rsp_ok_means_success , 'name' : "clear breakpoint or watchpoint" },
'Z' : { 'cmd' : cmd_bp , 'rsp' : rsp_ok_means_success , 'name' : "set breakpoint or watchpoint" },
'k' : { 'cmd' : cmd_kill , 'rsp' : rsp_stop_reply , 'name' : "kill process" },
}
def parse_gdb_log_file(file, options): def parse_gdb_log_file(file, options):
'''Parse a GDB log file that was generated by enabling logging with: '''Parse a GDB log file that was generated by enabling logging with:
(lldb) log enable --threadsafe --timestamp --file <FILE> gdb-remote packets (lldb) log enable --threadsafe --timestamp --file <FILE> gdb-remote packets
@ -104,6 +837,11 @@ def parse_gdb_log_file(file, options):
tricky_commands = [ 'qRegisterInfo' ] tricky_commands = [ 'qRegisterInfo' ]
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].*)$')
packet_name_regex = re.compile('([A-Za-z_]+)[^a-z]') packet_name_regex = re.compile('([A-Za-z_]+)[^a-z]')
packet_transmit_name_regex = re.compile('(?P<direction>send|read) packet: (?P<packet>.*)')
packet_contents_name_regex = re.compile('\$([^#]+)#[0-9a-fA-F]{2}')
packet_names_regex_str = '(' + '|'.join(gdb_remote_commands.keys()) + ')(.*)';
packet_names_regex = re.compile(packet_names_regex_str);
base_time = 0.0 base_time = 0.0
last_time = 0.0 last_time = 0.0
packet_send_time = 0.0 packet_send_time = 0.0
@ -112,7 +850,54 @@ def parse_gdb_log_file(file, options):
packet_count = {} packet_count = {}
file = open(file) file = open(file)
lines = file.read().splitlines() lines = file.read().splitlines()
last_command = None
last_command_args = None
last_command_packet = None
for line in lines: for line in lines:
m = packet_transmit_name_regex.search(line)
if m:
direction = m.group('direction')
is_command = direction == 'send'
packet = m.group('packet')
options.colors.green()
if options.quiet:
if is_command:
print '-->', packet
else:
print '<--', packet
else:
print '# ', line
options.colors.reset()
#print 'direction = "%s", packet = "%s"' % (direction, packet)
if packet[0] == '+':
print 'ACK'
elif packet[0] == '-':
print 'NACK'
elif packet[0] == '$':
m = packet_contents_name_regex.match(packet)
if m:
contents = m.group(1)
if is_command:
m = packet_names_regex.match (contents)
if m:
last_command = m.group(1)
last_command_args = m.group(2)
last_command_packet = contents
gdb_remote_commands[last_command]['cmd'](last_command, last_command_args)
else:
last_command = None
last_command_args = None
last_command_packet = None
elif last_command:
gdb_remote_commands[last_command]['rsp'](last_command, last_command_args, contents)
else:
print 'error: invalid packet: "', packet, '"'
else:
print '???'
else:
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))
@ -142,8 +927,8 @@ def parse_gdb_log_file(file, options):
if not options or not options.quiet: if not options or not options.quiet:
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 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
@ -179,14 +964,28 @@ def parse_gdb_log_file(file, options):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
usage = "usage: gdbremote [options]"
description='''The command disassembles a GDB remote packet log.'''
parser = optparse.OptionParser(description=description, prog='gdbremote',usage=usage)
parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='display verbose debug info', default=False)
parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='display verbose debug info', default=False)
parser.add_option('-C', '--color', action='store_true', dest='color', help='add terminal colors', default=False)
parser.add_option('-c', '--sort-by-count', action='store_true', dest='sort_count', help='display verbose debug info', default=False)
try:
(options, args) = parser.parse_args(sys.argv[1:])
except:
print 'error: argument error'
sys.exit(1)
options.colors = TerminalColors(sys.stdout, options.color)
# 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.
for file in sys.argv[1:]: 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, None) parse_gdb_log_file (file, options)
else: else:
import lldb import lldb
if lldb.debugger: if lldb.debugger: