Python idautils.CodeRefsTo() Examples

The following are 18 code examples of idautils.CodeRefsTo(). 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 also want to check out all available functions/classes of the module idautils , or try the search function .
Example #1
Source Project: IDAmetrics   Author: mxmssh   File: IDAMetrics_static.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_henryncafura_metric(self, function_ea, function_metrics):
        '''
        The function performs evaluation of Henry&Cafura metric
        @function_ea - function entry address
        @function_metrics - function_metrics structure
        @return - Henry&Cafura metric
        '''
        function_metrics.fan_out_s = len(function_metrics.calls_dict)
        refs_to = idautils.CodeRefsTo(function_ea, 0)
        function_metrics.fan_in_s = sum(1 for y in refs_to)

        (count, function_metrics.vars_args) = self.get_function_args_count(function_ea, function_metrics.vars_local)

        # check input args
        (read, write) = self.get_unique_vars_read_write_count(function_metrics.vars_args)
        function_metrics.fan_in_i += read
        function_metrics.fan_out_i += write
        # check global variables list
        (read, write) = self.get_unique_vars_read_write_count(function_metrics.global_vars_used)
        function_metrics.fan_in_i += read
        function_metrics.fan_out_i += write

        fan_in = function_metrics.fan_in_s + function_metrics.fan_in_i
        fan_out = function_metrics.fan_out_s + function_metrics.fan_out_i
        return function_metrics.CC + pow((fan_in + fan_out), 2) 
Example #2
Source Project: flare-ida   Author: fireeye   File: argtracker_example2.py    License: Apache License 2.0 6 votes vote down vote up
def getArgs():
    '''
    Phase 1:
    For each xref to the string decoder, use argracker to grab the interesting
    arguments. Print them out as a list of tuples that will be used in phase 2.
    '''


    decStringFunc = 0x10002F6C
    vw = c_jayutils.loadWorkspace(c_jayutils.getInputFilepath())
    logger.info('Loaded workspace')
    tracker = c_argtracker.ArgTracker(vw)
    interestingXrefs = idautils.CodeRefsTo(decStringFunc, 1)

    for xref in interestingXrefs:
        argsList = tracker.getPushArgs(xref, 2, ['eax', 'ecx', 'edi'])
        if len(argsList) == 0:
            logger.error('Unable to get push args at: 0x%08x', xref)
        for argDict in argsList:
            locVa, strLoc = argDict[1]
            lenVa, strLen = argDict['edi']
            keyVa, key = argDict['eax']
            print '(0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x),' % (
                xref, strLoc, locVa, strLen, lenVa, keyVa, key
            ) 
Example #3
Source Project: idasec   Author: RobinDavid   File: ida_utils.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def safe_path_to(self, addr):
        path = self.full_path_to(addr)  # Start from the full path
        i = -1
        for ea, k in zip(path, range(len(path))):  # Compute i such that it is safe
            nb_preds = len([x for x in idautils.CodeRefsTo(ea, True)])
            if nb_preds > 1:
                i = k
            elif idc.GetDisasm(ea).startswith("call"):
                i = k+1
        print i
        if i == -1:
            return path
        else:
            return path[i:] 
Example #4
Source Project: idasec   Author: RobinDavid   File: opaque_analysis.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def propagate_dead_code(self, ea, op_map):
        prevs = [x for x in idautils.CodeRefsTo(ea, True) if x not in self.marked_addresses and
                 not self.dead_br_of_op(ea, x, op_map)]
        if prevs:  # IF there is no legit predecessors
            idc.SetColor(ea, idc.CIC_ITEM, 0x0000ff)
            self.marked_addresses[ea] = None
            succs = [x for x in idautils.CodeRefsFrom(ea, True)]
            for succ in succs:
                self.propagate_dead_code(succ, op_map)
        else:
            return 
Example #5
Source Project: win_driver_plugin   Author: FSecureLABS   File: win_driver_plugin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_dispatch_by_cfg():
    """ 
    Finds the functions in the binary which are not directly called anywhere and counts how many other functions they call,
    returing all functions which call > 0 other functions but are not called themselves. As a dispatch function is not normally directly
    called but will normally many other functions this is a fairly good way to guess which function it is.
    """
        
    out = []
    called = set()
    caller = dict()
    # Loop through all the functions in the binary
    for function_ea in idautils.Functions():
        flags = idc.get_func_flags(function_ea)
        # skip library functions
        if flags & idc.FUNC_LIB:
            continue
        f_name = idc.GetFunctionName(function_ea)
        # For each of the incoming references
        for ref_ea in idautils.CodeRefsTo(function_ea, 0):
            called.add(f_name)
            # Get the name of the referring function
            caller_name = idc.GetFunctionName(ref_ea)
            if caller_name not in caller.keys():
                caller[caller_name] = 1
            else:
                caller[caller_name] += 1
    while True:
        if len(caller.keys()) == 0:
            break
        potential = max(caller, key=caller.get)
        if potential not in called:
            out.append(potential)
        del caller[potential]
    return out 
Example #6
Source Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def has_flow_to_code(ea):
  """Returns `True` if there are any control flows to the instruction at 
  `ea`."""
  return _reference_checker(ea, cref_finder=idautils.CodeRefsTo) 
Example #7
Source Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def has_flow_to_code(ea):
  """Returns `True` if there are any control flows to the instruction at 
  `ea`."""
  return _reference_checker(ea, cref_finder=idautils.CodeRefsTo) 
Example #8
Source Project: Sark   Author: tmr232   File: function.py    License: MIT License 5 votes vote down vote up
def crefs_to(self):
        """Source addresses of code xrefs to this function."""
        return idautils.CodeRefsTo(self.start_ea, 1) 
Example #9
Source Project: Sark   Author: tmr232   File: line.py    License: MIT License 5 votes vote down vote up
def crefs_to(self):
        """Source addresses of data references to this line."""
        return idautils.CodeRefsTo(self.ea, 1) 
Example #10
Source Project: ida-batch_decompile   Author: tintinweb   File: ida_batch_decompile.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_coderefs(self):
        return (IdaLocation(frm) for frm in idautils.CodeRefsTo(self.at, 0)) 
Example #11
Source Project: malware-research   Author: eset   File: OL_OSX_decryptor.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def activate(self, ctx):
        for pfn_idx in ctx.chooser_selection:
            pfn = ida_funcs.getn_func(pfn_idx)
            if pfn:
                xrefs = [x for x in idautils.CodeRefsTo(pfn.start_ea, 0)]
                for xref in list(set(xrefs)):
                    cfunc = idaapi.decompile(xref)
                    if cfunc:
                        xref_args = get_args(cfunc, xref, self.var_prop)
                        self.callback(xref, cfunc, xref_args)
        return 1 
Example #12
Source Project: smda   Author: danielplohmann   File: IdaInterface.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getCodeInRefs(self, offset):
        return [(ref_from, offset) for ref_from in idautils.CodeRefsTo(offset, True)] 
Example #13
Source Project: smda   Author: danielplohmann   File: IdaInterface.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getCodeInRefs(self, offset):
        return [(ref_from, offset) for ref_from in idautils.CodeRefsTo(offset, True)] 
Example #14
Source Project: flare-ida   Author: fireeye   File: argtracker_example1.py    License: Apache License 2.0 5 votes vote down vote up
def handleCreateThread(ea):
    logger.debug('handleCreateThread: starting up 0x%08x', ea)
    vw = c_jayutils.loadWorkspace(c_jayutils.getInputFilepath())
    logger.info('Loaded workspace')
    tracker = c_argtracker.ArgTracker(vw)
    interestingXrefs = idautils.CodeRefsTo(ea, 1)

    for xref in interestingXrefs:
        argsList = tracker.getPushArgs(xref, 7)
        if len(argsList) == 0:
            logger.error('Unable to get push args at: 0x%08x', xref)
        else:
            for argDict in argsList:
                loadVa, funcVa = argDict[3]
                print 'Found: 0x%08x: 0x%08x' % (loadVa, funcVa) 
Example #15
Source 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 #16
Source 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 #17
Source Project: flare-ida   Author: fireeye   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def make_import_names_callback(library_calls, library_addr):
    """ Return a callback function used by idaapi.enum_import_names(). """
    def callback(ea, name, ordinal):
        """ Callback function to retrieve code references to library calls. """
        library_calls[name] = []
        library_addr[name] = ea
        for ref in idautils.CodeRefsTo(ea, 0):
            library_calls[name].append(ref)
        return True  # True -> Continue enumeration
    return callback 
Example #18
Source Project: IDAmetrics   Author: mxmssh   File: IDAMetrics_static.py    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get_function_args_count(self, function_ea, local_vars):
        """
        The function returns count of function arguments
        @function_ea - function entry point
        @local_vars - local variables dictionary
        @return - function arguments count
        """
        # i#9 Now, we can't identify fastcall functions.

        function_args_count = 0
        args_dict = dict()
        for local_var in local_vars:
            usage_list = local_vars.get(local_var, None)
            if usage_list == None:
                print "WARNING: empty usage list for ", local_var
                continue
            for head in usage_list:
                ops = self.get_instr_operands(int(head, 16))
                for idx, (op,type) in enumerate(ops):
                    if op.count("+") == 1:
                        value = idc.GetOperandValue(int (head, 16), idx)
                        if value < (15 * ARGUMENT_SIZE) and "ebp" in op:
                            args_dict.setdefault(local_var, []).append(head)
                    elif op.count("+") == 2:
                        if "arg" in local_var:
                            args_dict.setdefault(local_var, []).append(head)
                    else:
                        continue

        function_args_count = len(args_dict)
        if function_args_count:
            return function_args_count, args_dict

        #TODO Check previous algorithm here
        f_end = idc.FindFuncEnd(function_ea)
        f_end = idc.PrevHead(f_end, 0)
        instr_mnem = idc.GetMnem(f_end)
        #stdcall ?
        if "ret" in instr_mnem:
            ops = self.get_instr_operands(f_end)
            if len(ops) == 1:
                for op,type in ops:
                    op = op.replace("h", "")
                    function_args_count = int(op,16)/ARGUMENT_SIZE
                    return function_args_count, args_dict
        #cdecl ?
        refs = idautils.CodeRefsTo(function_ea, 0)
        for ref in refs:
            #trying to find add esp,x signature after call
            head = idc.NextHead(ref, 0xFFFFFFFF)
            if head:
                disasm = idc.GetDisasm(head)
                if "add" in disasm and "esp," in disasm:
                    ops = self.get_instr_operands(head)
                    op,type = ops[1]
                    if op:
                        op = op.replace("h", "")
                        function_args_count = int(op,16)/ARGUMENT_SIZE
                        return function_args_count, args_dict
        return function_args_count, args_dict