Python idc.GetFunctionName() Examples

The following are 30 code examples of idc.GetFunctionName(). 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 idc , or try the search function .
Example #1
Source Project: idasec   Author: RobinDavid   File: generic_analysis.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def post_analysis_stuff(self, results):
        if results.has_formula():
            self.action_selector.addItem(self.parent.HIGHLIGHT_CODE)
            self.action_selector.addItem(self.parent.GRAPH_DEPENDENCY)
            self.formula_area.setText(self.parent.results.formula)
        if results.has_values():
            self.action_selector.addItem(self.parent.DISASS_UNKNOWN_TARGET)
        self.action_selector.setEnabled(True)
        self.action_button.setEnabled(True)

        report = HTMLReport()
        report.add_title("Results", size=3)
        report.add_table_header(["address", "assertion", "status", "values"])
        addr = make_cell("%x" % results.target)
        status = make_cell(results.get_status(), color=results.color, bold=True)
        vals = ""
        for value in results.values:
            flag = idc.GetFlags(value)
            typ = self.type_to_string(flag)
            vals += "%x type:%s seg:%s fun:%s<br/>" % (value, typ, idc.SegName(value), idc.GetFunctionName(value))
        report.add_table_line([addr, make_cell(cgi.escape(results.query)), status, make_cell(vals)])
        report.end_table()
        data = report.generate()
        self.result_area.setHtml(data) 
Example #2
Source Project: IDASynergy   Author: CubicaLabs   File: IDASynergyHooks.py    License: MIT License 6 votes vote down vote up
def __call__(self, f):
        def wrapped_export_f(*args):
            if not globals().has_key("IDP_Hooks") or globals()["IDP_Hooks"] is None:
                from idaapi import IDP_Hooks, UI_Hooks
                from idc import Name, GetFunctionName, GetStrucIdByName, GetConstName, Warning, SetStrucName, GetStrucName
                globals()["IDP_Hooks"] = locals()["IDP_Hooks"]
                globals()["UI_Hooks"] = locals()["UI_Hooks"]
                globals()["Name"] = locals()["Name"]
                globals()["GetFunctionName"] = locals()["GetFunctionName"]
                globals()["GetStrucIdByName"] = locals()["GetStrucIdByName"]
                globals()["GetConstName"] = locals()["GetConstName"]
                globals()["Warning"] = locals()["Warning"]
                globals()["SetStrucName"] = locals()["SetStrucName"]
                globals()["GetStrucName"] = locals()["GetStrucName"]
            return f(*args)
        return wrapped_export_f 
Example #3
Source Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def get_symbol_name(from_ea, ea=None, allow_dummy=False):
  if ea is None:
    ea = from_ea

  global _FORCED_NAMES
  if ea in _FORCED_NAMES:
    return _FORCED_NAMES[ea]

  flags = idc.GetFlags(ea)
  if not allow_dummy and idaapi.has_dummy_name(flags):
    return ""

  name = ""
  try:
    name = name or idc.GetTrueNameEx(from_ea, ea)
  except:
    pass

  try:
    name = name or idc.GetFunctionName(ea)
  except:
    pass

  return name 
Example #4
Source Project: DIE   Author: ynvb   File: IDAConnector.py    License: MIT License 6 votes vote down vote up
def get_function_name(ea):
        """
        Get the real function name
        """
        # Try to demangle
        function_name = idc.Demangle(idc.GetFunctionName(ea), idc.GetLongPrm(idc.INF_SHORT_DN))

        if function_name:
            function_name = function_name.split("(")[0]

        # Function name is not mangled
        if not function_name:
            function_name = idc.GetFunctionName(ea)

        if not function_name:
            function_name = idc.Name(ea)

        # If we still have no function name, make one up. Format is - 'UNKN_FNC_4120000'
        if not function_name:
            function_name = "UNKN_FNC_%s" % hex(ea)

        return function_name 
Example #5
Source Project: Stingray   Author: darx0r   File: Stingray.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_current_function_strings( self ):

        addr_in_func = idc.ScreenEA()
        curr_func = idc.GetFunctionName(addr_in_func)

        funcs = [ addr_in_func ]
        if ConfigStingray.SEARCH_RECURSION_MAXLVL > 0:
            funcs = find_function_callees(  addr_in_func, 
                                            ConfigStingray.SEARCH_RECURSION_MAXLVL  )

        total_strs = []
        for func in funcs:
            strs = find_function_strings(func)
            total_strs += [ s.get_row() for s in strs ]

        return total_strs


# ------------------------------------------------------------------------------ 
Example #6
Source Project: flare-ida   Author: fireeye   File: objc2_xrefs_helper.py    License: Apache License 2.0 6 votes vote down vote up
def add_method_xref(self,xref):
        Message("Adding cross reference to method implementation for %s\n" % GetFunctionName(self.method_pointer))
        
        #TODO: clean this up so it's more clear how we're parsing and patching the instruction
        #TODO: handle other potential instructions that could place a method selref into a register
        #TODO: sanity check what instruction we're actually working with before blindly deciding
        #       it's a 7-byte mov instruction

        add_dref(xref.frm,self.method_pointer,dr_I|XREF_USER)
        
        #offset is a rip-relative offset that gets added to rip and dereferenced
        #when this instruction is executed, rip will be pointing to the next instruction
        #meaning it has been incremented by 7 (the length of the mov instruction)
        offset=self.method_pointer-xref.frm-self.X86_64_MOV_INSTRUCTION_SIZE
        
        #this replaces  mov RSI, &selector with:
        #               mov RSI, &method
        #xref.frm is the address of the mov instruction
        #+3 (4th byte of the instruction)
        #is where the RIP-relative operand is that
        #will get dereferenced as a pointer
        PatchDword(xref.frm+3,offset)
        return ObjcMethodXref(xref.frm,self.method_pointer,xref.to) 
Example #7
Source Project: flare-ida   Author: fireeye   File: objc2_xrefs_helper.py    License: Apache License 2.0 6 votes vote down vote up
def add_method_xref(self,xref):
        Message("Adding cross reference to method implementation for %s\n" % GetFunctionName(self.method_pointer))
        
        add_dref(xref.frm,self.method_pointer,dr_I|XREF_USER)

        offset=self.method_pointer-xref.frm
        
        instruction_bytes=get_bytes(xref.frm,self.ARM64_INSTRUCTION_SIZE)
        #TODO: are there other instructions that could reference a method selector
        #and then move the selector reference into a register?
        arm64_ldr=AArch64LDRInstruction(instruction_bytes)
        
        arm64_ldr.patch_offset(offset)

        PatchDword(xref.frm,arm64_ldr.instruction_int)
        return ObjcMethodXref(xref.frm,self.method_pointer,xref.to) 
Example #8
Source Project: idasec   Author: RobinDavid   File: ida_utils.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, fun_addr):
        super(MyFlowGraph, self).__init__()
        self.fun = idaapi.get_func(fun_addr)
        self.startEA = self.fun.startEA
        self.endEA = self.fun.endEA
        for bb in idaapi.FlowChart(self.fun):
            self.__setitem__(bb.id, MyBasicBlock(bb))
        self._compute_links()
        self.edge_map = self.make_graph()
        self.shortest_path_map = self.dijkstra(self.edge_map)
        self.size = sum([x.size() for x in self.values()])
        self.viewer = MyFlowGraphViewer(self, "Extract(%s)" % idc.GetFunctionName(self.startEA)) 
Example #9
Source Project: idasec   Author: RobinDavid   File: configuration_file.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def set_start_stop(self, ftype):
        assert_ida_available()
        import idc
        import idaapi
        import idautils
        fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1)
                       for x in idautils.Functions()}
        start = idc.BeginEA()
        stop = 0
        if ftype == PE:
            start, stop = fun_mapping["start"]
        else:
            if not idc.isCode(idc.GetFlags(start)):
                if idc.MakeCode(start) == 0:
                    print "Fail to decode instr !"
                idaapi.autoWait()
            if idc.GetFunctionName(start) == "":
                if idc.MakeFunction(start) == 0:
                    print "Fail to create function !"
                idaapi.autoWait()
                fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1)
                               for x in idautils.Functions()}

            if "main" in fun_mapping:
                start, stop = fun_mapping["main"]
            elif "start" in fun_mapping:
                if "__libc_start_main" in fun_mapping:
                    instrs = list(idautils.FuncItems(fun_mapping["start"][0]))
                    instrs.reverse()
                    for inst in instrs:
                        arg1 = idc.GetOperandValue(inst, 0)
                        if idc.GetMnem(inst) == "push":
                            start, stop = arg1, fun_mapping["start"][1]
                            break
                else:
                    start, stop = fun_mapping["start"]
        self.config.start, self.config.stop = start, stop 
Example #10
Source Project: idasec   Author: RobinDavid   File: TraceWidget.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def refresh_trace_view(self):
        index = self.traces_tab.currentIndex()
        try:
            table = self.index_map[index]
            for i in xrange(table.rowCount()):
                addr_item = table.item(i, 1)
                addr = int(addr_item.text(), 0)
                routine_item = table.item(i, 3)
                routine_item.setText(idc.GetFunctionName(addr))
            print "Refresh done"
        except KeyError:
            print "Trace not found" 
Example #11
Source Project: idasec   Author: RobinDavid   File: static_opaque_analysis.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def target_button_clicked(self):
        if self.radio_addr.isChecked():
            self.target_field.setText(hex(idc.here()))
        else:
            self.target_field.setText(idc.GetFunctionName(idc.here()))
# ================================================================================
# ================================================================================


# ==================== Data structures ================== 
Example #12
Source Project: idasec   Author: RobinDavid   File: static_opaque_analysis.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def process_routine(self, rtn_addr, pred_addr=None, rtn_i=1, total_rtn=1):
        if rtn_addr not in self.functions_cfg:
            self.functions_cfg[rtn_addr] = MyFlowGraph(rtn_addr)
        cfg = self.functions_cfg[rtn_addr]
        path_to = self.config_to_path_function(cfg)
        if pred_addr is None:
            candidates = {x for x in idautils.FuncItems(rtn_addr) if idc.GetMnem(x) in cond_jump}
        else:
            candidates = {pred_addr}
        nb_candidates = len(candidates)
        self.functions_candidates[rtn_addr] = set()
        self.functions_spurious_instrs[rtn_addr] = set()

        self.progressbar_loading.reset()
        self.progressbar_loading.setMaximum(len(candidates))

        name = idc.GetFunctionName(rtn_addr)
        self.result_widget.webview.append("\n=> Function:%s\n" % name)

        self.log("[result]", "Start processing function: 0x%x" % rtn_addr)
        for i, addr in zip(xrange(len(candidates)), candidates):
            path = path_to(addr)
            res = self.process_addr(rtn_addr, addr, path)
            if self.STOP:
                return
            elif res is None:
                continue
            dead_br = "/" if res.dead_branch is None else "%x" % res.dead_branch
            self.result_widget.webview.append("%x:\t%s\t\tK:%d\tDead:%s" % (addr, to_status_name(res.status), res.k, dead_br))

            self.result_widget.webview.verticalScrollBar().setValue(self.result_widget.webview.verticalScrollBar().maximum())
            self.loading_stat.setText("Fun: %d/%d  Addr: %d/%d" % (rtn_i, total_rtn, i+1, nb_candidates))

            self.progressbar_loading.setValue(self.progressbar_loading.value()+1)
            self.functions_candidates[rtn_addr].add(addr) 
Example #13
Source Project: idasec   Author: RobinDavid   File: idasec_core.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def update_mapping(self):
        pass
        self.fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1) for x in
                            idautils.Functions()}
        self.seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()} 
Example #14
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 #15
Source Project: IDAngr   Author: andreafioraldi   File: hook_lib_funcs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hook_lib_funcs():
    from angrdbg import load_project
    project = load_project()
    for func in idautils.Functions():
        flags = idc.GetFunctionFlags(func)
        if flags & idc.FUNC_LIB:
            name = idc.GetFunctionName(func)
            simproc = search_simproc(name)
            if simproc is not None:
                print name, simproc
                project.hook_symbol(func, simproc()) 
Example #16
Source Project: fcatalog_client   Author: xorpd   File: ida_ts.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _GetFunctionName(func_addr):
    """
    Should be a thread safe version of GetFunctionName.
    """
    logger.debug('_GetFunctionName')
    return str(idc.GetFunctionName(func_addr)) 
Example #17
Source Project: IDASynergy   Author: CubicaLabs   File: IDASynergyHooks.py    License: MIT License 5 votes vote down vote up
def renamed(self, ea, new_name, local_name):
        struct_id = GetStrucIdByName(GetConstName(ea))
        is_struct = struct_id != 0xffffffffffffffff and struct_id != 0xffffffff
        if is_struct:
            Warning("IDASynergy still does not support renaming of structs.\nBy renaming it, other collaborators will get this struct deleted and a new one added\nIf you want to avoid this, please rename it to its old name.")
            return IDP_Hooks.renamed(self, ea, new_name, local_name)

        if Name(ea) != "" and GetFunctionName(ea) != "": # If renaming a function...
            self.data_io.apply_modification("functions", (ea, new_name))
            return IDP_Hooks.renamed(self, ea, new_name, local_name) 
Example #18
Source Project: IDASynergy   Author: CubicaLabs   File: IDASynergyHooks.py    License: MIT License 5 votes vote down vote up
def add_func(self, func):
        IDP_Hooks.add_func(self, func)
        self.data_io.apply_modification("functions", (func.startEA, GetFunctionName(func.startEA)))
        return 0 
Example #19
Source Project: mcsema   Author: lifting-bits   File: get_cfg.py    License: Apache License 2.0 5 votes vote down vote up
def is_start_of_function(ea):
  """Returns `True` if `ea` is the start of a function."""
  if not is_code(ea):
    return False

  name = idc.GetTrueName(ea) or idc.GetFunctionName(ea)
  return ea == idc.LocByName(name) 
Example #20
Source Project: DIE   Author: ynvb   File: FunctionParser.py    License: MIT License 5 votes vote down vote up
def guessValues(self, rawValue):
        """
        Guess string values
        """
        func = idaapi.get_func(rawValue)
        if func is None:
            return False

        if func.startEA == rawValue:
            func_name = idc.GetFunctionName(rawValue)
            self.addParsedvalue(func_name, 5, "Function", hex(rawValue))
            return True

        return False 
Example #21
Source Project: DIE   Author: ynvb   File: FunctionParser.py    License: MIT License 5 votes vote down vote up
def parseValue(self, rawValue):
        """
        Parse the string value
        @return:
        """
        func = idaapi.get_func(rawValue)
        if func is None:
            return False

        if func.startEA == rawValue:
            func_name = idc.GetFunctionName(rawValue)
            self.addParsedvalue(func_name, 5, "Function", hex(rawValue))
            return True

        return False 
Example #22
Source Project: IDAPython_Note   Author: ExpLife0011   File: 13_注释和重命名.py    License: MIT License 5 votes vote down vote up
def rename_wrapper(name, func_addr):
    if idc.MakeNameEx(func_addr, name, SN_NOWARN):
        print "Function at 0x%x renamed %s" % (func_addr, idc.GetFunctionName(func_addr))
    else:
        print "Rename at 0x%x failed. Function %s is being used." % (func_addr, name)
    return 
Example #23
Source Project: ida_kernelcache   Author: bazad   File: collect_classes.py    License: MIT License 5 votes vote down vote up
def _process_mod_init_func_for_metaclasses(func, found_metaclass):
    """Process a function from the __mod_init_func section for OSMetaClass information."""
    _log(4, 'Processing function {}', idc.GetFunctionName(func))
    def on_BL(addr, reg):
        X0, X1, X3 = reg['X0'], reg['X1'], reg['X3']
        if not (X0 and X1 and X3):
            return
        _log(5, 'Have call to {:#x}({:#x}, {:#x}, ?, {:#x})', addr, X0, X1, X3)
        # OSMetaClass::OSMetaClass(this, className, superclass, classSize)
        if not idc.SegName(X1).endswith("__TEXT.__cstring") or not idc.SegName(X0):
            return
        found_metaclass(X0, idc.GetString(X1), X3, reg['X2'] or None)
    _emulate_arm64(func, idc.FindFuncEnd(func), on_BL=on_BL) 
Example #24
Source Project: Reef   Author: darx0r   File: Reef.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_current_function_xrefs_from( self ):
    
        addr_in_func = idc.ScreenEA()
        curr_func = idc.GetFunctionName( addr_in_func )

        refs = self.find_xrefs_from( addr_in_func )
        return [ ref.get_row( XrefsFromFinder.XREF_TYPE2STR ) for ref in refs ]


# ------------------------------------------------------------------------------ 
Example #25
Source Project: rematch   Author: nirizr   File: widgets.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_func(self, func):
    self.func = func
    text = idc.GetFunctionName(self.func.startEA)
    text = text[:self.text_max] + "..." if len(text) > self.text_max else text
    self.label.setText(text) 
Example #26
Source Project: Stingray   Author: darx0r   File: Stingray.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_row( self ):

        xref = "{}:{:08X}".format(idc.GetFunctionName(self.xref), self.xref)
        addr = "{:08X}".format(self.addr)
        type = String.ASCSTR[self.type]
        string = self.string
        # IDA Chooser doesn't like tuples ... row should be a list
        return list( ConfigStingray.CHOOSER_ROW(xref, addr, type, string) ) 
Example #27
Source Project: Stingray   Author: darx0r   File: Stingray.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_function_callees( func_ea, maxlvl ):

    callees = []
    visited = set()
    pending = set( (func_ea,) )
    lvl = 0

    while len(pending) > 0:
        func_ea = pending.pop()
        visited.add(func_ea)

        func_name = idc.GetFunctionName(func_ea)
        if not func_name: continue
        callees.append(func_ea)

        func_end = idc.FindFuncEnd(func_ea)
        if func_end == idaapi.BADADDR: continue

        lvl +=1
        if lvl >= maxlvl: continue

        all_refs = set()
        for line in idautils.Heads(func_ea, func_end):

            if not ida_bytes.isCode(get_flags(line)): continue

            ALL_XREFS = 0
            refs = idautils.CodeRefsFrom(line, ALL_XREFS)
            refs = set( filter( lambda x: not (x >= func_ea and x <= func_end), 
                                refs) )
            all_refs |= refs

        all_refs -= visited
        pending |= all_refs

    return callees 
Example #28
Source Project: python-idb   Author: williballenthin   File: yara_fn.py    License: Apache License 2.0 5 votes vote down vote up
def format_rules(fva, rules):
    """
    given the address of a function, and the byte signatures for basic blocks in
     the function, format a complete YARA rule that matches all of the
     basic block signatures.
    """
    name = idc.GetFunctionName(fva)

    # some characters aren't valid for YARA rule names
    safe_name = name
    BAD_CHARS = "@ /\\!@#$%^&*()[]{};:'\",./<>?"
    for c in BAD_CHARS:
        safe_name = safe_name.replace(c, "")

    md5 = idautils.GetInputFileMD5()
    ret = []
    ret.append("rule a_%s_%s {" % (md5, safe_name))
    ret.append("  meta:")
    ret.append('    sample_md5 = "%s"' % (md5))
    ret.append('    function_address = "0x%x"' % (fva))
    ret.append('    function_name = "%s"' % (name))
    ret.append("  strings:")
    for rule in rules:
        formatted_rule = " ".join(rule.masked_bytes)
        ret.append("    %s = { %s }" % (rule.name, formatted_rule))
    ret.append("  condition:")
    ret.append("    all of them")
    ret.append("}")
    return "\n".join(ret) 
Example #29
Source Project: IDAmetrics   Author: mxmssh   File: lib_parser.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def find_function(function):
    for seg_ea in idautils.Segments():
        # For each of the functions
        function_ea = seg_ea
        while function_ea != 0xffffffffL:
            function_name = idc.GetFunctionName(function_ea)
            function = function.replace("\n", "")
            function = function.replace("\r", "")
            function = function.replace(" ", "")
            if function.lower() == function_name.lower():
                print "Found function ", function_name
                print hex(function_ea)
                return function_ea
            function_ea = idc.NextFunction(function_ea)  
    return -1 
Example #30
Source Project: IDAmetrics   Author: mxmssh   File: IDAMetrics_static.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, function_ea):
        self.function_name = idc.GetFunctionName(function_ea)
        self.loc_count = 0
        self.bbl_count = 0
        self.condition_count = 0
        self.calls_count = 0
        self.R = 0.0
        self.CC = 0
        self.CL = 0
        self.assign_count = 0
        self.ABC = 0
        self.CC_modified = 0
        self.Pivovarsky = 0
        self.Halstead_basic = Halstead_metric()
        self.Harrison = 0
        self.boundary_values = 0.0
        self.span_metric = 0
        self.vars_local = dict()
        self.vars_args = dict()
        self.Oviedo = 0
        self.Chepin = 0
        self.global_vars_access = 0
        self.global_vars_used = dict()
        self.global_vars_metric = 0.0
        self.bbls_boundaries = dict()
        self.CardnGlass = 0
        self.fan_in_i = 0
        self.fan_in_s = 0
        self.fan_out_i = 0
        self.calls_dict = dict()
        self.fan_out_s = 0
        self.HenrynCafura = 0
        self.Cocol = 0