Python gdb.lookup_type() Examples

The following are 26 code examples of gdb.lookup_type(). 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: stackframe.py    From gdb_python_api with MIT License 7 votes vote down vote up
def __stackmap(self, frame_items):
        symbolmap = defaultdict(list)
        if not frame_items:
            return symbolmap

        for i in frame_items:
            name = i.symbol().name
            addr = self._frame.read_var(name).address
            if not addr == None:
                # gdb.Value is not "hashable"; keys must be something else
                # so here we use addr converted to int
                sz = i.symbol().type.sizeof
                # mark all dwords in the stack with this symbol
                addr = addr.cast(gdb.lookup_type("void").pointer()) # cast to void*
                # handle sub-dword quantities by just listing everything that overlaps
                for saddr in range(addr, addr+sz, 0x8):
                    symbolmap[int(saddr)].append(i.symbol())
        return symbolmap

# Now create a gdb command that prints the current stack: 
Example #2
Source File: salt.py    From salt with GNU General Public License v3.0 7 votes vote down vote up
def stop(self):
    rdi = gdb.selected_frame().read_register('rdi') #XXX
    return False
    if rdi == 0 or rdi == ZERO_SIZE_PTR or rdi == 0x40000000: #XXX
      return False

    cache = rdi.cast(gdb.lookup_type('struct kmem_cache').pointer()).dereference()
    cache = cache['name'].string()

    name, pid = get_task_info()

    if apply_filter(name, cache):
      trace_info = 'kfree is freeing an object from cache ' + cache  + ' on behalf of process "' + name + '", pid ' + str(pid)
      salt_print(trace_info)
      history.append(('kfree', cache, name, pid))
    return False 
Example #3
Source File: gdb_utils.py    From debugger-utils with MIT License 6 votes vote down vote up
def ty(typename):
    """Return a gdb.Type object represents given `typename`.
    For example, x.cast(ty('Buffer'))"""
    if typename in TYPE_CACHE:
        return TYPE_CACHE[typename]

    m = re.match(r"^(\S*)\s*[*|&]$", typename)
    if m is None:
        tp = gdb.lookup_type(typename)
    else:
        if m.group(1).endswith('*'):
            tp = gdb.lookup_type().pointer()
        else:
            tp = gdb.lookup_type().reference()
    TYPE_CACHE[typename] = tp
    return tp 
Example #4
Source File: gdb_service.py    From pyringe with Apache License 2.0 6 votes vote down vote up
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') 
Example #5
Source File: instrument_srs.py    From gdb_python_api with MIT License 6 votes vote down vote up
def __init__(self, base_addr, size):
        Thread.__init__(self)
        self.base_addr = base_addr  # the vector we are monitoring
        self.size = size            # its size
        self.messages = Queue()     # cross-thread communication
        # store contents of vec
        self.values = []
        int_t = gdb.lookup_type('int')
        for idx in range(0, size):
            self.values.append(int((base_addr + idx).dereference().cast(int_t)))
        self.animations = []

    # Front end code
    # These methods run in the gdb thread in response to breakpoints,
    # and accept gdb.Value objects

    # Updates for instrumented actions 
Example #6
Source File: boundary.py    From ROPMEMU with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        gdb.Command.__init__(self, "boundary", gdb.COMMAND_OBSCURE)
        self.long_int = gdb.lookup_type('unsigned long long')
        self.THRESHOLD = 0x1000 
Example #7
Source File: function.py    From debugger-utils with MIT License 5 votes vote down vote up
def dataType(target, typename):
    'Print data according to type'
    pointer = target['data'].cast(gdb.lookup_type(typename.string()).pointer())
    data = []
    for i in range(int(target['size'])):
        elem = pointer.dereference()
        data.append(str(elem))
        pointer = pointer + 1
    return '{ ' + ' '.join(data) + '}' 
Example #8
Source File: function.py    From debugger-utils with MIT License 5 votes vote down vote up
def invoke(self, target, typename):
        pointer = target['data'].cast(gdb.lookup_type(typename.string()).pointer())
        data = []
        for i in range(int(target['size'])):
            elem = pointer.dereference()
            data.append(str(elem))
            pointer = pointer + 1
        return '{ ' + ' '.join(data) + '}' 
Example #9
Source File: salt.py    From salt with GNU General Public License v3.0 5 votes vote down vote up
def walk_caches():
  """
  walk through all the active kmem caches and collect information about them
  this function fills a data structure, used later by the other walk_* functions
  """
  global salt_caches
  salt_caches = []

  slab_caches = gdb.lookup_global_symbol('slab_caches').value().address
  salt_caches.append(dict())
  salt_caches[-1]['name'] = 'slab_caches'

  start = gdb.Value(int(slab_caches)-list_offset//8).cast(gdb.lookup_type('struct kmem_cache').pointer())
  nxt = get_next_cache(start)
  salt_caches[-1]['next'] = tohex(int(nxt), 64)
  salt_caches.append(dict())
  while True:
    objsize = int(nxt['object_size'])
    salt_caches[-1]['objsize'] = objsize
    offset = int(nxt['offset'])
    salt_caches[-1]['offset'] = offset
    salt_caches[-1]['name'] = nxt['name'].string()
    cpu_slab_offset = int(nxt['cpu_slab'])
    cpu_slab_ptr = gdb.Value(cpu_slab_offset+cpu0_offset).cast(gdb.lookup_type('struct kmem_cache_cpu').pointer())
    cpu_slab = cpu_slab_ptr.dereference()
    free = int(cpu_slab['freelist'])
    salt_caches[-1]['first_free'] = tohex(free, 64)
    salt_caches[-1]['freelist'] = []
    while free:
      free = gdb.Value(free+offset).cast(gdb.lookup_type('uint64_t').pointer()).dereference()
      salt_caches[-1]['freelist'].append(tohex(int(free), 64))
    nxt = get_next_cache(nxt)
    salt_caches[-1]['next'] = tohex(int(nxt), 64)
    if start == nxt:
      break
    else:
      salt_caches.append(dict()) 
Example #10
Source File: salt.py    From salt with GNU General Public License v3.0 5 votes vote down vote up
def get_next_cache(c1):
  """
  given a certain kmem cache, retrieve the memory area relative to the next one
  the code nagivates the struct, computes the address of 'next', then casts it to the correct type
  """
  nxt = c1['list']['next']
  c2 = gdb.Value(int(nxt)-list_offset//8).cast(gdb.lookup_type('struct kmem_cache').pointer())
  return c2 
Example #11
Source File: debugger.py    From angrgdb with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def before_stateshot(self):
        self.vmmap = self._get_vmmap()
        self.base_addr = self.vmmap[0][0]
        sections = self._get_sections()

        for start, end, name in sections:
            if name == load_project().arch.got_section_name:
                self.got = (start, end)
            elif name == ".plt":
                self.plt = (start, end)
            elif name == ".idata":
                self.plt = (start, end)
        self.long_type = gdb.lookup_type("long") 
Example #12
Source File: commands.py    From angrgdb with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _to_int(x):
    try:
        return int(gdb.parse_and_eval(x).cast(gdb.lookup_type("long")))
    except BaseException as e:
        print (e)
        return None 
Example #13
Source File: spmonitor.py    From ROPMEMU with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        gdb.Command.__init__(self, "spmonitor", gdb.COMMAND_OBSCURE)
        self.long_int = gdb.lookup_type('unsigned long long') 
Example #14
Source File: unropandroll.py    From ROPMEMU with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        gdb.Command.__init__(self, "unrop", gdb.COMMAND_OBSCURE)
        self.long_int = gdb.lookup_type('unsigned long long')
        self.hw_context = OrderedDict() 
Example #15
Source File: chuckgetcopyptr.py    From ROPMEMU with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        self.long_int = gdb.lookup_type('unsigned long long') 
        print("--[ ROPMEMU framework - GDB utils ]--\n")
        print("[+] Patching...")
        # necessary patch to make Chuck work
        self.patch = "set *(unsigned long long*)0xffffffff81352d33 = 0xc310c48348"
        gdb.execute("%s" % self.patch)
        # set the breakpoint
        print("[+] Setting the breakpoint...")
        self.msr_gadget_addr = "*0xffffffff810039a0"
        self.sysenter_esp = 0x175
        super(ChuckGetCopyPtr, self).__init__(self.msr_gadget_addr, gdb.BP_BREAKPOINT)
        # Continue
        print("[+] Back to the VM")
        gdb.execute("c") 
Example #16
Source File: python-gdb.py    From copr-sundry with Apache License 2.0 5 votes vote down vote up
def get_attr_dict(self):
        '''
        Get the PyDictObject ptr representing the attribute dictionary
        (or None if there's a problem)
        '''
        try:
            typeobj = self.type()
            dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
            if dictoffset != 0:
                if dictoffset < 0:
                    type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
                    tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
                    if tsize < 0:
                        tsize = -tsize
                    size = _PyObject_VAR_SIZE(typeobj, tsize)
                    dictoffset += size
                    assert dictoffset > 0
                    assert dictoffset % SIZEOF_VOID_P == 0

                dictptr = self._gdbval.cast(_type_char_ptr) + dictoffset
                PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
                dictptr = dictptr.cast(PyObjectPtrPtr)
                return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
        except RuntimeError:
            # Corrupt data somewhere; fail safe
            pass

        # Not found, or some kind of error:
        return None 
Example #17
Source File: python-gdb.py    From copr-sundry with Apache License 2.0 5 votes vote down vote up
def get_gdb_type(cls):
        return gdb.lookup_type(cls._typename).pointer() 
Example #18
Source File: python-gdb.py    From copr-sundry with Apache License 2.0 5 votes vote down vote up
def proxyval(self, visited):
        '''
        Python's Include/longobjrep.h has this declaration:
           struct _longobject {
               PyObject_VAR_HEAD
               digit ob_digit[1];
           };

        with this description:
            The absolute value of a number is equal to
                 SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
            Negative numbers are represented with ob_size < 0;
            zero is represented by ob_size == 0.

        where SHIFT can be either:
            #define PyLong_SHIFT        30
            #define PyLong_SHIFT        15
        '''
        ob_size = long(self.field('ob_size'))
        if ob_size == 0:
            return 0L

        ob_digit = self.field('ob_digit')

        if gdb.lookup_type('digit').sizeof == 2:
            SHIFT = 15L
        else:
            SHIFT = 30L

        digits = [long(ob_digit[i]) * 2**(SHIFT*i)
                  for i in safe_range(abs(ob_size))]
        result = sum(digits)
        if ob_size < 0:
            result = -result
        return result 
Example #19
Source File: python-gdb.py    From copr-sundry with Apache License 2.0 5 votes vote down vote up
def get_attr_dict(self):
        '''
        Get the PyDictObject ptr representing the attribute dictionary
        (or None if there's a problem)
        '''
        try:
            typeobj = self.type()
            dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
            if dictoffset != 0:
                if dictoffset < 0:
                    type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
                    tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
                    if tsize < 0:
                        tsize = -tsize
                    size = _PyObject_VAR_SIZE(typeobj, tsize)
                    dictoffset += size
                    assert dictoffset > 0
                    assert dictoffset % SIZEOF_VOID_P == 0

                dictptr = self._gdbval.cast(_type_char_ptr) + dictoffset
                PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
                dictptr = dictptr.cast(PyObjectPtrPtr)
                return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
        except RuntimeError:
            # Corrupt data somewhere; fail safe
            pass

        # Not found, or some kind of error:
        return None 
Example #20
Source File: python-gdb.py    From copr-sundry with Apache License 2.0 5 votes vote down vote up
def get_gdb_type(cls):
        return gdb.lookup_type(cls._typename).pointer() 
Example #21
Source File: libpython.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def proxyval(self, visited):
        '''
        Python's Include/longobjrep.h has this declaration:
           struct _longobject {
               PyObject_VAR_HEAD
               digit ob_digit[1];
           };

        with this description:
            The absolute value of a number is equal to
                 SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
            Negative numbers are represented with ob_size < 0;
            zero is represented by ob_size == 0.

        where SHIFT can be either:
            #define PyLong_SHIFT        30
            #define PyLong_SHIFT        15
        '''
        ob_size = long(self.field('ob_size'))
        if ob_size == 0:
            return 0L

        ob_digit = self.field('ob_digit')

        if gdb.lookup_type('digit').sizeof == 2:
            SHIFT = 15L
        else:
            SHIFT = 30L

        digits = [long(ob_digit[i]) * 2**(SHIFT*i)
                  for i in safe_range(abs(ob_size))]
        result = sum(digits)
        if ob_size < 0:
            result = -result
        return result 
Example #22
Source File: libpython.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def get_attr_dict(self):
        '''
        Get the PyDictObject ptr representing the attribute dictionary
        (or None if there's a problem)
        '''
        try:
            typeobj = self.type()
            dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
            if dictoffset != 0:
                if dictoffset < 0:
                    type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
                    tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
                    if tsize < 0:
                        tsize = -tsize
                    size = _PyObject_VAR_SIZE(typeobj, tsize)
                    dictoffset += size
                    assert dictoffset > 0
                    assert dictoffset % SIZEOF_VOID_P == 0

                dictptr = self._gdbval.cast(_type_char_ptr) + dictoffset
                PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
                dictptr = dictptr.cast(PyObjectPtrPtr)
                return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
        except RuntimeError:
            # Corrupt data somewhere; fail safe
            pass

        # Not found, or some kind of error:
        return None 
Example #23
Source File: libpython.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def _PyObject_VAR_SIZE(typeobj, nitems):
    if _PyObject_VAR_SIZE._type_size_t is None:
        _PyObject_VAR_SIZE._type_size_t = gdb.lookup_type('size_t')

    return ( ( typeobj.field('tp_basicsize') +
               nitems * typeobj.field('tp_itemsize') +
               (SIZEOF_VOID_P - 1)
             ) & ~(SIZEOF_VOID_P - 1)
           ).cast(_PyObject_VAR_SIZE._type_size_t) 
Example #24
Source File: libpython.py    From pyringe with Apache License 2.0 5 votes vote down vote up
def get_gdb_type(cls):
        return gdb.lookup_type(cls._typename).pointer() 
Example #25
Source File: List.py    From FreeRTOS-GDB with GNU General Public License v2.0 4 votes vote down vote up
def GetElements(self, CastTypeStr = None, startElem = 1 ): 
    """ Get the Elements of the list as an array of 
        gdb.Value type objects. 
        @param CastTypeStr string name of the type of object that 
          we will cast the void *pvOwner elements of the list to. 
          User can also pass a L{gdb.Type} object as the type
          If None, we will simply cast to uint32_t and print these 
          as hex values.
        @param startElem This is a flag to indicate whether 
           we will start getting elements starting at 0 or 1. Note
           that this is to deal with some non-consistent behavior 
           of some of the TCB Task lists.
    """
    if ( self._list != None ):

      CastType = None
      if ( CastTypeStr != None):
        if( type(CastTypeStr) == str ):
          try:
            CastType = gdb.lookup_type(CastTypeStr).pointer()
          except:
            print("Failed to find type: %s" % CastTypeStr)
        elif ( type(CastTypeStr) == gdb.Type): 
          CastType = CastTypeStr.pointer()
          

      resp = [] 
      numElems = self._list['uxNumberOfItems']
      #print("List Elements: %d" % numElems)
      index = self._list['pxIndex']
        
      if ( numElems > 0  and numElems < 200 ):

        if ( startElem == 0 ):
          curr = index
        else:
          curr = index['pxPrevious']

        for i in range(0, numElems):
          owner = curr['pvOwner']


          ownerObj = None
          if ( CastType != None ):
            castObjPtr = owner.cast(CastType)
            castObj = castObjPtr.dereference()
            ownerObj = castObj
          else:     
            ownerUInt = owner.cast(StdTypes.uint32_t)      
            ownerObj = ownerUInt          
          
          itemVal = curr['xItemValue']
          resp.append( (ownerObj, itemVal.cast(StdTypes.uint32_t)) )

          curr = curr['pxPrevious']

      return(resp)
      
    else:
      raise ValueError("Invalid List Object - Possibly Failed to Initialize!") 
Example #26
Source File: stackframe.py    From gdb_python_api with MIT License 4 votes vote down vote up
def __str__(self):
        if not self._frame.is_valid():
            return "<invalid>"
        result = ""
        # some basic frame stats
        if self._frame.function() is not None:
            result = result + "in " + self._frame.function().name
            if self._frame.type() is gdb.INLINE_FRAME:
                # recursively show inlining until we find a "real" parent frame
                result = result + "\ninlined with" + str(FramePrinter(self._frame.older()))
        else:
            result = result + "<unknown function>"
        if (self._frame.type() != gdb.NORMAL_FRAME):
            # IDK what else to do
            return result

        locls = self.__stackmap(self._decorator.frame_locals())
        args = self.__stackmap(self._decorator.frame_args())

        # assuming we are built with -fno-omit-frame-pointer here.  Not sure how to access
        # debug info that could tell us more, otherwise. More info is clearly present in C
        # (otherwise "info frame" could not do its job).

        # Display args
        yellow = "\u001b[33m"
        reset_color = "\u001b[0m"

        # find the address range of our args
        # from there to *(rbp+0x8), exclusive, is the range of possible args
        if args.keys():
            first_arg_addr = max(args.keys())    # the one with the highest address
            result = result + self.__subframe_display(first_arg_addr,
                                                      self._frame.read_register('rbp')+0x8,
                                                      args,
                                                      yellow)

        # *(rbp+0x8) is the stored old IP
        cyan = "\u001b[36m"
        result = result + "\n" + str(self._frame.read_register('rbp')+0x8) + " return address"
        voidstarstar = gdb.lookup_type("void").pointer().pointer()
        old_ip = (self._frame.read_register('rbp')+0x8).cast(voidstarstar).dereference()
        result = result + cyan + " (" + str(old_ip) + ")" + reset_color

        # *(rbp) is the old RBP
        result = result + "\n" + str(self._frame.read_register('rbp')+0x0) + " saved rbp"

        # print rest of stack, displaying locals
        green = "\u001b[32m"
        result = result + self.__subframe_display(self._frame.read_register('rbp')-0x8,
                                                  self._frame.read_register('sp')-0x8,
                                                  locls,
                                                  green)

        result = result + cyan + " <<< top of stack" + reset_color

        return result

    # display a range of stack addresses with colors, and compression of unknown contents as "stuff"