Python源码示例:gdb.error()
示例1
def Refresh():
"""looks up symbols within the inferior and caches their names / values.
If debugging information is only partial, this method does its best to
find as much information as it can, validation can be done using
IsSymbolFileSane.
"""
try:
GdbCache.DICT = gdb.lookup_type('PyDictObject').pointer()
GdbCache.TYPE = gdb.lookup_type('PyTypeObject').pointer()
except gdb.error as err:
# The symbol file we're using doesn't seem to provide type information.
pass
interp_head_name = GdbCache.FuzzySymbolLookup('interp_head')
if interp_head_name:
GdbCache.INTERP_HEAD = gdb.parse_and_eval(interp_head_name)
else:
# As a last resort, ask the inferior about it.
GdbCache.INTERP_HEAD = gdb.parse_and_eval('PyInterpreterState_Head()')
GdbCache.PENDINGBUSY = GdbCache.FuzzySymbolLookup('pendingbusy')
GdbCache.PENDINGCALLS_TO_DO = GdbCache.FuzzySymbolLookup('pendingcalls_to_do')
示例2
def get_reg(self, name):
if name == "efl" or name == "eflags":
value = 0
for f in self.efl_map:
if f in str(gdb.parse_and_eval("$eflags")):
value |= self.efl_map[f]
return value
else:
reg_val = gdb.parse_and_eval("$" + name)
if reg_val.type.code == gdb.TYPE_CODE_UNION: #SSE
value = 0
for i in range(8):
try:
v = int(reg_val["v8_int32"][i].cast(self.long_type)) << i * 32
except gdb.error:
break
value |= v
return value
else:
return int(reg_val.cast(self.long_type))
示例3
def print_stack(self):
def repr_stack(stack, sp):
for line in stack.splitlines():
addr, values = line.split(':')
values = values.split()
if addr == sp:
top = values[0]
rest = ' '.join(values[1:])
line = '==> {} {} {}'.format(
red(addr), red(top, back='green'),
yellow(rest))
else:
line = ' {} {}'.format(
red(addr), cyan(' '.join(values)))
print(line)
try:
stack = self.get_stack()
except IOError as error:
self.logger.error(error)
else:
repr_stack(stack, self.get_reg(self.env.SP))
print()
示例4
def print_asm(self):
command = 'u {} l10'.format(self.env.IP)
try:
asms = self.execute(command)
except self.pykd.DbgException as error:
self.logger.error(error)
else:
ip = self.pykd.reg(self.env.IP)
for line in asms.splitlines()[1:]:
try:
address, opcode, ins = line.split(None, 2)
except ValueError as error:
print(red('{}: {}'.format(line, error)))
else:
line = '{:25} {:25} {}'.format(
cyan(address, res=False),
yellow(opcode, res=False), red(ins))
if int(address, 16) == ip:
print(Back.GREEN + line)
else:
print(line)
示例5
def __init__(self, name, controller, stage, no_rec):
self.name = name
self.no_rec = no_rec
self.stage = stage
self.depth = 0
self.plugin = controller.subcommand_parsers[self.plugin_name].plugin
try:
i = gdb.execute("x/x %s" % self.name, to_string=True).split()[0]
except gdb.error as e:
controller.gdb_print("%s cannot set breakpoint for %s\n" % (e,
self.name),
self.plugin.name)
return
i = re.sub(':', '', i)
self.fnloc = long(i, 0)
spec = "*(0x%x)" % self.fnloc
self.line = re.sub(":",
"::",
pure_utils.addr2line(self.fnloc,
stage.elf)) if self.plugin._sourceinfo else ""
gdb_tools.TargetBreak.__init__(self, spec, controller, True, stage)
示例6
def invoke(self, arg, from_tty):
result = gdb.execute('mo leak full', False, True)
while result.find('are definitely lost in loss record') is -1:
try:
gdb.execute('step', to_string = True) # QUIETLY step
except gdb.error:
print('error while stepping') # BOZO handle
break
result = gdb.execute('mo leak full', False, True)
print('loss report:\n%s'%result)
print('leak first noticed at:\n')
gdb.execute('bt')
示例7
def invoke (self, arg, from_tty):
try:
print(FramePrinter(gdb.newest_frame()))
except gdb.error:
print("gdb got an error. Maybe we are not currently running?")
示例8
def FuzzySymbolLookup(symbol_name):
try:
gdb.parse_and_eval(symbol_name)
return symbol_name
except gdb.error as err:
# No symbol in current context. We might be dealing with static symbol
# disambiguation employed by compilers. For example, on debian's current
# python build, the 'interp_head' symbol (which we need) has been renamed
# to 'interp_head.42174'. This mangling is of course compiler-specific.
# We try to get around it by using gdb's built-in regex support when
# looking up variables
# Format:
# All variables matching regular expression "<symbol_name>":
#
# File <source_file>:
# <Type><real_symbol_name>;
#
# Non-debugging symbols:
# 0x<address> <real_symbol_name>
# We're only interested in <real_symbol_name>. The latter part
# ('Non-debugging symbols') is only relevant if debugging info is partial.
listing = gdb.execute('info variables %s' % symbol_name, to_string=True)
# sigh... We want whatever was in front of ;, but barring any *s.
# If you are a compiler dev who mangles symbols using ';' and '*',
# you deserve this breakage.
mangled_name = (re.search(r'\**(\S+);$', listing, re.MULTILINE)
or re.search(r'^0x[0-9a-fA-F]+\s+(\S+)$', listing, re.MULTILINE))
if not mangled_name:
raise err
try:
gdb.parse_and_eval('\'%s\'' % mangled_name.group(1))
return '\'%s\'' % mangled_name.group(1)
except gdb.error:
# We could raise this, but the original exception will likely describe
# the problem better
raise err
示例9
def Attach(self, position):
pos = [position[0], position[1], None]
# Using ExecuteRaw here would throw us into an infinite recursion, we have
# to side-step it.
gdb.execute('attach ' + str(pos[0]), to_string=True)
try:
# Shortcut for handling single-threaded python applications if we've got
# the right symbol file loaded already
GdbCache.Refresh()
self.selected_tstate = self._ThreadPtrs(pos)[0]
except gdb.error:
pass
示例10
def show_error(e):
"""
Decorate a function so it masks tracebacks when debug=False
"""
if gxf.basics.debug:
# Gdb can't give us a full traceback. If this is a tty
# or if error occured during argument parsing we do it.
print("%s" % (traceback.format_exc(),), end="")
print(e)
if not gxf.basics.debug:
print(" If that's weird check `python gxf.basics.debug = True`")
示例11
def get_stack(self):
wide = '32wx' if self.env.BITS == 32 else '16gx'
command = 'x/{} ${}'.format(wide, self.env.SP)
try:
output = self.execute(command)
except gdb.error:
raise IOError()
else:
return output
示例12
def get_pc_asm(self):
command = 'x/i ${}'.format(self.env.IP)
try:
output = self.execute(command)
except self.gdb.MemoryError as error:
self.logger.debug('Original error: %s', error)
sp = self.get_reg(self.env.SP)
pattern = error.args[0].split()[-1]
self.logger.debug('sp: %s pattern: %s', sp, pattern)
raise IOError(sp, pattern)
else:
return output
示例13
def get_reg(self, name):
command = 'info registers {}'.format(name)
try:
output = self.execute(command)
except gdb.error as error:
self.logger.error(error)
return None
else:
return output.split()[-2]
示例14
def step(self):
command = 'stepi'
try:
self.execute(command)
except self.gdb.MemoryError as error:
self.logger.error(error)
raise IOError
示例15
def get_pc_asm(self):
self.logger.debug('ip: %s', self.get_reg(self.env.IP))
try:
output = self.pykd.disasm().opmnemo()
except self.pykd.DbgException as error:
self.logger.error('Original error: %s', error)
pattern = self.get_reg(self.env.IP)
sp = self.get_reg(self.env.SP)
self.logger.debug('sp: %s pattern: %s', sp, pattern)
raise IOError(sp, pattern)
else:
return output
示例16
def print_stack(self):
command = 'dd {}-0x40'.format(self.env.SP)
try:
values = self.execute(command)
except self.pykd.DbgException as error:
self.logger.error(error)
else:
sp = self.pykd.reg(self.env.SP)
for line in values.splitlines():
if int(line.split()[0], 16) == sp:
print(red(line))
else:
print(cyan(line))
示例17
def print_reg(self):
try:
ip = hex(self.pykd.getIP()).strip('L')
sp = hex(self.pykd.getSP())
bp = self.get_reg(self.env.BP)
except self.pykd.DbgException as error:
self.logger.error(error)
else:
print('{}: {} {}: {} {}: {}'.format(
self.env.IP.upper(), red(ip),
self.env.SP.upper(), yellow(sp),
self.env.BP.upper(), cyan(bp)))
示例18
def go(self, args):
if self.gone:
return
self.gone = True
gdb.events.exited.connect(self.gdb_exit)
self.finalize(args)
if not self.run_standalone:
stage = self.stage_order[0]
else:
class LocalStage():
def __init__(self, elf):
self.elf = elf
self.entrypoint = pure_utils.get_entrypoint(elf)
self.exitpc = -1
self.stagename = "local"
stage = LocalStage(gdb.current_progspace().filename)
s = self.prepare_stage(stage, False)
self.set_mode()
stage_entered = False
try:
if self.get_reg_value('pc', True) == s.breakpoint.companion.addr:
self.gdb_print("First stage already entered\n")
stage_entered = True
except gdb.error:
pass
if stage_entered and not self.run_standalone:
self.gdb_print("Calling breakpoint hook\n")
s.stop()
s.continue_stage()
self.gdb_print("ready to go\n")
if not args.prepare_only:
if args.run_not_cont:
gdb.execute("r")
else:
gdb.execute("c")
示例19
def settable(cls, name, c):
try:
i = gdb.execute("x/x %s" % name, to_string=True).split()[0]
except gdb.error as e:
#c.gdb_print("%s cannot set breakpoint for %s\n" % (e,
# name), "calltrace")
return False
return True
示例20
def _breakInFunctions(node):
breakpoints = []
# If the child is an "unexposed expression" find its child.
if node.kind.is_unexposed():
# Flag error if none or more than one
if len(list(node.get_children())) != 1:
raise RuntimeError('Unexposed expression at line %d has more than one child, unsure how to handle'%node.location.line)
node = next(node.get_children())
if node.kind.is_unexposed():
raise RuntimeError('parent and child AST nodes both unexposed at line %d'%node.location.line)
if node.kind == CursorKind.CALL_EXPR:
# check for member function call
body = StepUser._getMemberBody(node)
if body is None:
# maybe it's a plain function
body = StepUser._getFunctionBody(node)
if body:
# implement breakpoint pattern match here:
if re.match(StepUser.stepRegex, getFuncName(body.semantic_parent)):
body = None
else:
# try lambda
body = StepUser._getLambdaBody(node)
if body:
first_stmt = next(body.get_children())
breakpoints.append((first_stmt.location.file.name, first_stmt.location.line))
# walk through the children
for arg in node.get_arguments():
breakpoints = breakpoints + StepUser._breakInFunctions(arg)
if node.kind == CursorKind.DECL_REF_EXPR:
# probably an object argument
# check type against regex
decl = node.referenced.type.get_declaration()
if not re.match(StepUser.stepRegex, getFuncName(decl)):
# locate member function bodies and breakpoint
members = [next(x.get_children()) for x in StepUser._getMethodBodies(decl)]
breakpoints = breakpoints + [(x.location.file.name, x.location.line) for x in members]
return breakpoints
示例21
def EnsureGdbPosition(self, pid, tid, frame_depth):
"""Make sure our position matches the request.
Args:
pid: The process ID of the target process
tid: The python thread ident of the target thread
frame_depth: The 'depth' of the requested frame in the frame stack
Raises:
PositionUnavailableException: If the requested process, thread or frame
can't be found or accessed.
"""
position = [pid, tid, frame_depth]
if not pid:
return
if not self.IsAttached():
try:
self.Attach(position)
except gdb.error as exc:
raise PositionUnavailableException(exc.message)
if gdb.selected_inferior().pid != pid:
self.Detach()
try:
self.Attach(position)
except gdb.error as exc:
raise PositionUnavailableException(exc.message)
if tid:
tstate_head = GdbCache.INTERP_HEAD['tstate_head']
for tstate in self._IterateChainedList(tstate_head, 'next'):
if tid == tstate['thread_id']:
self.selected_tstate = tstate
break
else:
raise PositionUnavailableException('Thread %s does not exist.' %
str(tid))
stack_head = self.selected_tstate['frame']
if frame_depth is not None:
frames = list(self._IterateChainedList(stack_head, 'f_back'))
frames.reverse()
try:
self.selected_frame = frames[frame_depth]
except IndexError:
raise PositionUnavailableException('Stack is not %s frames deep' %
str(frame_depth + 1))
示例22
def IsSymbolFileSane(self, position):
"""Performs basic sanity check by trying to look up a bunch of symbols."""
pos = [position[0], None, None]
self.EnsureGdbPosition(*pos)
try:
if GdbCache.DICT and GdbCache.TYPE and GdbCache.INTERP_HEAD:
# pylint: disable=pointless-statement
tstate = GdbCache.INTERP_HEAD['tstate_head']
tstate['thread_id']
frame = tstate['frame']
frame_attrs = ['f_back',
'f_locals',
'f_localsplus',
'f_globals',
'f_builtins',
'f_lineno',
'f_lasti']
for attr_name in frame_attrs:
# This lookup shouldn't throw an exception
frame[attr_name]
code = frame['f_code']
code_attrs = ['co_name',
'co_filename',
'co_nlocals',
'co_varnames',
'co_lnotab',
'co_firstlineno']
for attr_name in code_attrs:
# Same as above, just checking whether the lookup succeeds.
code[attr_name]
# if we've gotten this far, we should be fine, as it means gdb managed
# to look up values for all of these. They might still be null, the
# symbol file might still be bogus, but making gdb check for null values
# and letting it run into access violations is the best we can do. We
# haven't checked any of the python types (dict, etc.), but this symbol
# file seems to be useful for some things, so let's give it our seal of
# approval.
return True
except gdb.error:
return False
# looks like the initial GdbCache refresh failed. That's no good.
return False