Python idc.GetFunctionAttr() Examples

The following are 11 code examples for showing how to use idc.GetFunctionAttr(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module idc , or try the search function .

Example 1
Project: fcatalog_client   Author: xorpd   File: ida_ts.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _get_func_length(func_addr):
    """
    Return function's length.
    """
    logger.debug('_get_func_length: {}'.format(func_addr))
    # First check if this is a chunked function.
    # If so, we abort.
    if _is_func_chunked(func_addr):
        return None
        # raise FCatalogClientError('Function {:X} is chunked. Can not calculate'
        #        ' length.'.format(func_addr))

    # Get the end of the function:
    func_end = idc.GetFunctionAttr(func_addr,idc.FUNCATTR_END)

    if func_end < func_addr:
        return None
        # raise FCatalogClientError('Function {:X} has end lower than start'.\
        #        format(func_addr))

    # Calculate length and return:
    return func_end - func_addr 
Example 2
Project: DIE   Author: ynvb   File: IDAConnector.py    License: MIT License 6 votes vote down vote up
def get_function_start_address(ea):
    """
    Get function start address
    @param ea: ea from within the function boundaries.
    @return: The function start ea. If function start was not found return current ea.
    """
    try:
        if ea is None:
            return None

        start_adrs = idc.GetFunctionAttr(ea, idc.FUNCATTR_START)
        if start_adrs != idc.BADADDR:
            return start_adrs

        return ea

    except Exception as ex:
        raise RuntimeError("Count not locate start address for function %s: %s" % (hex(ea), ex)) 
Example 3
Project: DIE   Author: ynvb   File: IDAConnector.py    License: MIT License 6 votes vote down vote up
def get_function_end_address(ea):
    """
    Get function end address
    @param ea: function start_ea.
    @return: The function end ea. If no function end ea found returns None.
    """
    try:
        if ea is None:
            return None

        func_attr_end = idc.GetFunctionAttr(ea, idc.FUNCATTR_END)
        if func_attr_end == idc.BADADDR:
            return None

        return idc.PrevHead(func_attr_end, ea)

    except Exception as ex:
        raise RuntimeError("Count not locate end address for function %s: %s" % (hex(ea), ex)) 
Example 4
Project: flare-ida   Author: fireeye   File: stackstrings.py    License: Apache License 2.0 6 votes vote down vote up
def getFuncRanges(ea, doAllFuncs):
    if using_ida7api:
        return getFuncRanges_ida7(ea, doAllFuncs)
    if doAllFuncs:
        funcs = []
        funcGen = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
        for i in funcGen:
            funcs.append(i)
        funcRanges = []
        for i in range(len(funcs) - 1):
            funcRanges.append( (funcs[i], funcs[i+1]) )
        funcRanges.append( (funcs[-1], idc.SegEnd(ea)) )
        return funcRanges
    else:
        #just get the range of the current function
        fakeRanges = [( idc.GetFunctionAttr(idc.here(), idc.FUNCATTR_START), idc.GetFunctionAttr(idc.here(), idc.FUNCATTR_END)), ]
        return fakeRanges 
Example 5
Project: mcsema   Author: lifting-bits   File: collect_variable.py    License: Apache License 2.0 5 votes vote down vote up
def recover_variables(F, func_ea, blockset):
  """ Recover the stack variables from the function. It also collect
      the instructions referring to the stack variables.
  """
  # Checks for the stack frame; return if it is None
  if not is_code_by_flags(func_ea) or \
      not idc.GetFrame(func_ea):
    return

  functions = list()
  f_name = get_symbol_name(func_ea)
  f_ea = idc.GetFunctionAttr(func_ea, idc.FUNCATTR_START)
  f_vars = collect_function_vars(func_ea, blockset)
  functions.append({"ea":f_ea, "name":f_name, "stackArgs":f_vars})

  for offset in f_vars.keys():
    if f_vars[offset]["safe"] is False:
      continue

    var = F.stack_vars.add()
    var.sp_offset = offset
    var.name = f_vars[offset]["name"]
    var.size = f_vars[offset]["size"]
    for i in f_vars[offset]["writes"]:
      r = var.ref_eas.add()
      r.inst_ea = i["ea"]
      r.offset = i["offset"]

    for i in f_vars[offset]["reads"]:
      r = var.ref_eas.add()
      r.inst_ea = i["ea"]
      r.offset = i["offset"] 
Example 6
Project: ida_kernelcache   Author: bazad   File: ida_utilities.py    License: MIT License 5 votes vote down vote up
def is_function_start(ea):
    """Return True if the address is the start of a function."""
    return idc.GetFunctionAttr(ea, idc.FUNCATTR_START) == ea 
Example 7
Project: bap-ida-python   Author: BinaryAnalysisPlatform   File: ida.py    License: MIT License 5 votes vote down vote up
def output_symbols(out):
    """Dump symbols."""
    try:
        from idaapi import get_func_name2 as get_func_name
        # Since get_func_name is deprecated (at least from IDA 6.9)
    except ImportError:
        from idaapi import get_func_name
        # Older versions of IDA don't have get_func_name2
        # so we just use the older name get_func_name

    def func_name_propagate_thunk(ea):
        current_name = get_func_name(ea)
        if current_name[0].isalpha():
            return current_name
        func = idaapi.get_func(ea)
        temp_ptr = idaapi.ea_pointer()
        ea_new = idaapi.BADADDR
        if func.flags & idaapi.FUNC_THUNK == idaapi.FUNC_THUNK:
            ea_new = idaapi.calc_thunk_func_target(func, temp_ptr.cast())
        if ea_new != idaapi.BADADDR:
            ea = ea_new
        propagated_name = get_func_name(ea) or ''  # Ensure it is not `None`
        if len(current_name) > len(propagated_name) > 0:
            return propagated_name
        else:
            return current_name
            # Fallback to non-propagated name for weird times that IDA gives
            #     a 0 length name, or finds a longer import name

    for ea in idautils.Segments():
        fs = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
        for f in fs:
            out.write('("%s" 0x%x 0x%x)\n' % (
                func_name_propagate_thunk(f),
                idc.GetFunctionAttr(f, idc.FUNCATTR_START),
                idc.GetFunctionAttr(f, idc.FUNCATTR_END))) 
Example 8
Project: flare-ida   Author: fireeye   File: argtracker_example1.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    beginThreadExLoc = idc.LocByName('_beginthreadex')
    if beginThreadExLoc == idc.BADADDR:
        print 'Function "_beginthreadex" not found. Returning'
        return
    for xref in idautils.CodeRefsTo(beginThreadExLoc, 1):
        if getFunctionArgumentCount(xref) == 7:
            print 'Found likely MyCreateThread: 0x%08x' % xref
            handleCreateThread(idc.GetFunctionAttr(xref, idc.FUNCATTR_START)) 
Example 9
Project: flare-ida   Author: fireeye   File: argtracker.py    License: Apache License 2.0 5 votes vote down vote up
def analyzeTracker(self, baseEntry, va, num, regs):
        funcStart = idc.GetFunctionAttr(va, idc.FUNCATTR_START)
        initState = TrackerState(self, baseEntry, num, regs)
        count = 0
        ret = []
        touched = set()
        self.queue = [ (va, initState) ]
        while len(self.queue) != 0:
            if count > self.maxIters:
                self.logger.error('Max graph traveral iterations reached: (0x%08x) %d. Stopping early. Consider increasing ArgTracker maxIters (unless this is a bug)', va, count)
                break
            cVa, cState = self.queue.pop(0)
            touched.add(cVa)
            #self.logger.debug('Examining 0x%08x: %s', cVa, str(cState))
            #self.logger.debug('Current tempMapping: 0x%08x %s', cVa, pprint.pformat(cState.tempMapping))
            try:
                cState.processWriteLog(self, cVa)
                #self.logger.debug('writelog 0x%08x done', cVa)
                cState.processRegMon(self, cVa)
                #self.logger.debug('regmon 0x%08x done', cVa)
            except Exception, err:
                self.logger.exception('Error in process: %s', str(err))
                return []
            if cState.isComplete():
                #self.logger.debug('Yep, appending')
                ret.append(cState.resultArgs)
            else:
                if cVa == funcStart:
                    #self.logger.debug('Skipping xref queueing: hit function start')
                    pass
                else:
                    #self.logger.debug('Not complete: queuing prev items')
                    for ref in idautils.CodeRefsTo(cVa, True):
                        if ref in touched:
                            #self.logger.debug('Skip queueing (touched) 0x%08x -> 0x%08x', cVa, ref)
                            pass
                        else:
                            #self.logger.debug('Queueing 0x%08x -> 0x%08x', cVa, ref)
                            self.queue.append( (ref, cState.copy()) )
            count += 1 
Example 10
Project: mcsema   Author: lifting-bits   File: collect_variable.py    License: Apache License 2.0 4 votes vote down vote up
def build_stack_variable(func_ea):
  stack_vars = dict()

  frame = idc.GetFrame(func_ea)
  if not frame:
    return stack_vars

  f_name = get_symbol_name(func_ea)
  #grab the offset of the stored frame pointer, so that
  #we can correlate offsets correctly in referent code
  # e.g., EBP+(-0x4) will match up to the -0x4 offset
  delta = idc.GetMemberOffset(frame, " s")
  if delta == -1:
    delta = 0

  if f_name not in _FUNC_UNSAFE_LIST:
    offset = idc.GetFirstMember(frame)
    while -1 != _signed_from_unsigned(offset):
      member_name = idc.GetMemberName(frame, offset)
      if member_name is None:
        offset = idc.GetStrucNextOff(frame, offset)
        continue
      if (member_name == " r" or member_name == " s"):
        offset = idc.GetStrucNextOff(frame, offset)
        continue

      member_size = idc.GetMemberSize(frame, offset)
      if offset >= delta:
        offset = idc.GetStrucNextOff(frame, offset)
        continue

      member_flag = idc.GetMemberFlag(frame, offset)
      flag_str = _get_flags_from_bits(member_flag)
      member_offset = offset-delta
      stack_vars[member_offset] = {"name": member_name,
                                  "size": member_size,
                                  "flags": flag_str,
                                  "writes": list(),
                                  "referent": list(),
                                  "reads": list(),
                                  "safe": False }

      offset = idc.GetStrucNextOff(frame, offset)
  else:
    offset = idc.GetFirstMember(frame)
    frame_size = idc.GetFunctionAttr(func_ea, idc.FUNCATTR_FRSIZE)
    flag_str = ""
    member_offset = _signed_from_unsigned(offset) - delta
    stack_vars[member_offset] = {"name": f_name,
                                 "size": frame_size,
                                 "flags": flag_str,
                                 "writes": list(),
                                 "referent": list(),
                                 "reads": list(),
                                 "safe": False }

  return stack_vars 
Example 11
Project: flare-ida   Author: fireeye   File: argtracker.py    License: Apache License 2.0 4 votes vote down vote up
def getPushArgs(self, va, num, regs=None):
        '''
        num -> first arg is 1, 2nd is 2, ...
        
        Returns a list of dicts whose key is the arg number (starting at 1, 2.. num)
        Each dict for a stack argument is a write log tuple (pc, va bytes)
        Each dict for a registry is a tuple (pc, value)
        
        '''
        if regs is None:
            regs = []
        count = 0
        touched = []

        #func = self.vw.getFunction(va)
        #if func is None:
        #    self.logger.error('Could not get function start from vw 0x%08x -> has analysis been done???', va)
        #    return []
        funcStart = idc.GetFunctionAttr(va, idc.FUNCATTR_START)
        #if func != funcStart:
        #    self.logger.error('IDA & vivisect disagree over function start. Needs to be addressed before process')
        #    self.logger.error(' IDA: 0x%08x. vivisect: 0x%08x', funcStart, func)
        #    return []
        #map a every (?) va in a function to the pathnode it was found in
        if funcStart != self.lastFunc:
            emu = self.vw.getEmulator(True, True)
            self.logger.debug('Generating va_write_map for function 0x%08x', funcStart)
            self.regMon = RegMonitor(regs)
            emu.setEmulationMonitor(self.regMon)
            emu.runFunction(funcStart, maxhit=1, maxloop=1)
            #cache the last va_write_map for a given function
            self.va_write_map = {}
            self.va_read_map = {}
            self.lastFunc = funcStart
            jayutils.path_bfs(emu.path, build_emu_va_map, res=self.va_write_map, emu=emu, logtype='writelog')
            jayutils.path_bfs(emu.path, build_emu_va_map, res=self.va_read_map, emu=emu, logtype='readlog')
        else:
            self.logger.debug('Using cached va_write_map')
        #self.logger.debug('Len va_write_map: %d', len(self.va_write_map))
        #for cVa, wlog in self.va_write_map.items():
        #    self.logger.debug('0x%08x: %s', cVa, formatWriteLogEntry(wlog))

        baseEntry = self.va_write_map.get(va, None)
        if baseEntry is None:
            self.logger.error('Node does not have write log. Requires a call instruction (which writes to the stack) for this to work: 0x%08x', va)
            return []
        self.startSp = baseEntry[1]
        return self.analyzeTracker(baseEntry, va, num, regs)