Python gdb.selected_inferior() Examples

The following are 12 code examples of gdb.selected_inferior(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gdb , or try the search function .
Example #1
Source File: gdb_service.py    From pyringe with Apache License 2.0 6 votes vote down vote up
def Detach(self):
    """Detaches from the inferior. If not attached, this is a no-op."""
    # We have to work around the python APIs weirdness :\
    if not self.IsAttached():
      return None
    # Gdb doesn't drain any pending SIGINTs it may have sent to the inferior
    # when it simply detaches. We can do this by letting the inferior continue,
    # and gdb will intercept any SIGINT that's still to-be-delivered; as soon as
    # we do so however, we may lose control of gdb (if we're running in
    # synchronous mode). So we queue an interruption and continue gdb right
    # afterwards, it will waitpid() for its inferior and collect all signals
    # that may have been queued.
    pid = gdb.selected_inferior().pid
    self.Interrupt([pid, None, None])
    self.Continue([pid, None, None])
    result = gdb.execute('detach', to_string=True)
    if not result:
      return None
    return result 
Example #2
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def fake_fast(addr,size):
    if not get_heap_info():
        print("Can't find heap info")
        return
    result = []
    idx = fastbin_idx(size)
    chunk_size = size & 0xfffffffffffffff8
    start = addr - chunk_size
    chunk_data = gdb.selected_inferior().read_memory(start, chunk_size)
    for offset in range(chunk_size-4):
        fake_size = u32(chunk_data[offset:offset+4])
        if fastbin_idx(fake_size) == idx :
            if ((fake_size & 2 == 2) and (fake_size & 4 == 4)) or (fake_size & 4 == 0) :
                padding = addr - (start+offset-capsize) - capsize*2
                result.append((start+offset-capsize,padding))
    return result 
Example #3
Source File: gdb_service.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def current_line(self):
    if self.is_optimized_out():
      return '(frame information optimized out)'
    filename = self.filename()
    inferior_cwd = '/proc/%d/cwd' % gdb.selected_inferior().pid
    if filename.startswith('/dev/fd/'):
      filename.replace('/dev/fd/',
                       '/proc/%d/fd/' % gdb.selected_inferior().pid,
                       1)
    else:
      filename = os.path.join(inferior_cwd, filename)
    try:
      sourcefile = self.OpenFile(filename)
    except IOError:
      # couldn't find the file, let's try extracting the path from the frame
      filename = self.extract_filename()
      if filename.endswith('.pyc'):
        filename = filename[:-1]
      try:
        sourcefile = self.OpenFile(filename)
      except IOError:
        return '<file not available>'
    for _ in xrange(self.current_line_num()):
      line = sourcefile.readline()
    sourcefile.close()
    return line if line else '<file not available>' 
Example #4
Source File: gdb_service.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def IsAttached(self):
    # The gdb python api is somewhat... weird.
    inf = gdb.selected_inferior()
    if inf.is_valid() and inf.pid and inf.threads():
      return True
    return False 
Example #5
Source File: gdb_service.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def _GetGdbThreadMapping(self, position):
    """Gets a mapping from python tid to gdb thread num.

    There's no way to get the thread ident from a gdb thread.  We only get the
    "ID of the thread, as assigned by GDB", which is completely useless for
    everything except talking to gdb.  So in order to translate between these
    two, we have to execute 'info threads' and parse its output. Note that this
    may only work on linux, and only when python was compiled to use pthreads.
    It may work elsewhere, but we won't guarantee it.

    Args:
      position: array of pid, tid, framedepth specifying the requested position.
    Returns:
      A dictionary of the form {python_tid: gdb_threadnum}.
    """

    if len(gdb.selected_inferior().threads()) == 1:
      # gdb's output for info threads changes and only displays PID. We cheat.
      return {position[1]: 1}
    # example:
    #   8    Thread 0x7f0a637fe700 (LWP 11894) "test.py" 0x00007f0a69563e63 in
    #   select () from /usr/lib64/libc.so.6
    thread_line_regexp = r'\s*\**\s*([0-9]+)\s+[a-zA-Z]+\s+([x0-9a-fA-F]+)\s.*'
    output = gdb.execute('info threads', to_string=True)
    matches = [re.match(thread_line_regexp, line) for line
               in output.split('\n')[1:]]
    return {int(match.group(2), 16): int(match.group(1))
            for match in matches if match} 
Example #6
Source File: inferiors.py    From gxf with MIT License 5 votes vote down vote up
def get_selected_inferior():
    return gdb.selected_inferior() 
Example #7
Source File: strongdb.py    From strongdb with GNU General Public License v3.0 5 votes vote down vote up
def is_debuggee_running(self):
        return gdb.selected_inferior().pid != 0 
Example #8
Source File: debugger.py    From angrgdb with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
        self.inferior = gdb.selected_inferior()
        self.pid = 0
        self.base_addr = None
        self.efl_map = {}
        self.efl_map['CF'] = 1 << 0
        self.efl_map['PF'] = 1 << 2
        self.efl_map['AF'] = 1 << 4
        self.efl_map['ZF'] = 1 << 6
        self.efl_map['SF'] = 1 << 7
        self.efl_map['TF'] = 1 << 8
        self.efl_map['IF'] = 1 << 9
        self.efl_map['DF'] = 1 << 10
        self.efl_map['OF'] = 1 << 11 
Example #9
Source File: unicorn_trace.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def write_memory(self, start, buffer):
        inf = gdb.selected_inferior()
        inf.write_memory(start, b"%s" % buffer) 
Example #10
Source File: unicorn_trace.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def read_memory(self, start, size):
        inf = gdb.selected_inferior()
        try:
            bs = inf.read_memory(start, size)
        except gdb.MemoryError:
            bs = "\0" * size
        return b"%s" % bs 
Example #11
Source File: enforce.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def do(self):
        global allowed_writes
        a = allowed_writes[self.stage.stagename][self.num]
        if not len(a.search(self.start, self.end)) == 1:
            gdb.write("#CAUGHT INVALID WRITE pc %x (%x-%x) substage %s (%s)\n" % (self.pc,
                                                                                  self.start,
                                                                                  self.end,
                                                                                  self.name,
                                                                                  self.num),
                      gdb.STDOUT)
            global do_halt
            if do_halt:
                pid = gdb.selected_inferior().pid
                os.kill(pid, signal.SIGINT) 
Example #12
Source File: gdb_service.py    From pyringe with Apache License 2.0 4 votes vote down vote up
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))