Python idc.FUNCATTR_START Examples

The following are 13 code examples of idc.FUNCATTR_START(). 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 idc , or try the search function .
Example #1
Source File: IDAConnector.py    From DIE with 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 #2
Source File: stackstrings.py    From flare-ida with 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 #3
Source File: collect_variable.py    From mcsema with 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 #4
Source File: collect_variable.py    From mcsema with 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.get_func_attr(func_ea, idc.FUNCATTR_FRAME):
    return

  functions = list()
  f_name = get_symbol_name(func_ea)
  f_ea = idc.get_func_attr(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 #5
Source File: Main.py    From Virtuailor with GNU General Public License v3.0 5 votes vote down vote up
def get_xref_code_to_func(func_addr):
    a = idautils.XrefsTo(func_addr, 1)
    addr = {}
    for xref in a:
        frm = xref.frm  # ea in func
        start = idc.get_func_attr(frm, idc.FUNCATTR_START)  # to_xref func addr
        func_name = idc.get_func_name(start)  # to_xref func name
        addr[func_name] = [xref.iscode, start]
    return addr 
Example #6
Source File: ida_utilities.py    From ida_kernelcache with 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
Source File: ida.py    From bap-ida-python with 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
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getMinorDispatchTableAddress(ea):
    """find address of last lea in function"""
    start = idc.get_func_attr(ea, idc.FUNCATTR_START)
    end = idc.prev_head( idc.get_func_attr(ea, idc.FUNCATTR_END), start)
    res = prevMnemonic(end, 'lea', start)
    assert res != idc.BADADDR
    return idc.get_operand_value(res, 1) 
Example #9
Source File: argtracker_example1.py    From flare-ida with 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 #10
Source File: stackstrings.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def getFuncRanges_ida7(ea, doAllFuncs):
    if doAllFuncs:
        funcs = []
        funcGen = idautils.Functions(idc.get_segm_start(ea), idc.get_segm_end(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.get_segm_end(ea)) )
        return funcRanges
    else:
        #just get the range of the current function
        fakeRanges = [( idc.get_func_attr(idc.here(), idc.FUNCATTR_START), idc.get_func_attr(idc.here(), idc.FUNCATTR_END)), ]
        return fakeRanges 
Example #11
Source File: argtracker.py    From flare-ida with 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 #12
Source File: vtableAddress.py    From Virtuailor with GNU General Public License v3.0 4 votes vote down vote up
def get_con2_var_or_num(i_cnt, cur_addr):
    """
    :param i_cnt: the register of the virtual call
    :param cur_addr: the current address in the memory
    :return: "success" string and the address of the vtable's location. if it fails it sends the reason and -1
    """
    start_addr = idc.get_func_attr(cur_addr, idc.FUNCATTR_START)
    virt_call_addr = cur_addr
    cur_addr = idc.prev_head(cur_addr)
    dct_arch = get_arch_dct()
    if dct_arch == -1:
        return 'Wrong Architechture', "-1", cur_addr

    while cur_addr >= start_addr:
        if idc.print_insn_mnem(cur_addr)[:3] == dct_arch["opcode"] and idc.print_operand(cur_addr, 0) == i_cnt:  # TODO lea ?
            opnd2 = idc.print_operand(cur_addr, 1)
            place = opnd2.find(dct_arch["separator"])
            if place != -1:  # if the function is not the first in the vtable
                register = opnd2[opnd2.find('[') + 1: place]
                if opnd2.find('*') == -1:
                    offset = opnd2[place + dct_arch["val_offset"]: opnd2.find(']')]
                else:
                    offset = "*"
                return register, offset, cur_addr
            else:
                offset = "0"
                if opnd2.find(']') != -1:
                    register = opnd2[opnd2.find('[') + 1: opnd2.find(']')]
                else:
                    register = opnd2
                return register, offset, cur_addr
        elif idc.print_insn_mnem(cur_addr)[:4] == "call":
            intr_func_name = idc.print_operand(cur_addr, 0)
            # In case the code has CFG -> ignores the function call before the virtual calls
            if "guard_check_icall_fptr" not in intr_func_name:
                if "nullsub" not in intr_func_name:
                    # intr_func_name = idc.Demangle(intr_func_name, idc.GetLongPrm(idc.INF_SHORT_DN))
                    print("Warning! At address 0x%08x: The vtable assignment might be in another function (Maybe %s),"
                          " could not place BP." % (virt_call_addr, intr_func_name))
                cur_addr = start_addr
        cur_addr = idc.prev_head(cur_addr)
    return "out of the function", "-1", cur_addr

    return '', 0, cur_addr 
Example #13
Source File: argtracker.py    From flare-ida with 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)