Python ida_funcs.get_func() Examples

The following are 23 code examples of ida_funcs.get_func(). 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 ida_funcs , or try the search function .
Example #1
Source File: graph_ir.py    From miasm with GNU General Public License v2.0 6 votes vote down vote up
def function_graph_ir():
    # Get settings
    settings = GraphIRForm()
    ret = settings.Execute()
    if not ret:
        return

    func = ida_funcs.get_func(idc.get_screen_ea())
    func_addr = func.start_ea

    build_graph(
        func_addr,
        settings.cScope.value,
        simplify=settings.cOptions.value & OPTION_GRAPH_CODESIMPLIFY,
        dontmodstack=settings.cOptions.value & OPTION_GRAPH_DONTMODSTACK,
        loadint=settings.cOptions.value & OPTION_GRAPH_LOADMEMINT,
        verbose=False
    )
    return 
Example #2
Source File: filter.py    From IDArling with GNU General Public License v3.0 6 votes vote down vote up
def _set_tooltip(self, obj, ev):
        cursors = self._plugin.config["cursors"]
        if not cursors["funcs"]:
            return

        obj.setToolTip("")
        index = obj.parent().indexAt(ev.pos())
        func_ea = int(index.sibling(index.row(), 2).data(), 16)
        func = ida_funcs.get_func(func_ea)

        # Find the corresponding username
        for name, user in self._plugin.core.get_users().items():
            if ida_funcs.func_contains(func, user["ea"]):
                # Set the tooltip
                obj.setToolTip(name)
                break 
Example #3
Source File: hooks.py    From IDArling with GNU General Public License v3.0 6 votes vote down vote up
def _hxe_callback(self, event, *_):
        if not self._installed:
            return 0

        if event == ida_hexrays.hxe_func_printed:
            ea = ida_kernwin.get_screen_ea()
            func = ida_funcs.get_func(ea)
            if func is None:
                return

            if self._func_ea != func.start_ea:
                self._func_ea = func.start_ea
                self._labels = HexRaysHooks._get_user_labels(self._func_ea)
                self._cmts = HexRaysHooks._get_user_cmts(self._func_ea)
                self._iflags = HexRaysHooks._get_user_iflags(self._func_ea)
                self._lvar_settings = HexRaysHooks._get_user_lvar_settings(
                    self._func_ea
                )
                self._numforms = HexRaysHooks._get_user_numforms(self._func_ea)
            self._send_user_labels(func.start_ea)
            self._send_user_cmts(func.start_ea)
            self._send_user_iflags(func.start_ea)
            self._send_user_lvar_settings(func.start_ea)
            self._send_user_numforms(func.start_ea)
        return 0 
Example #4
Source File: mountain.py    From IDACyber with MIT License 6 votes vote down vote up
def on_process_buffer(self, buffers, addr, size, mouse_offs):
        colors = []
        goffs = 0
        for mapped, buf in buffers:
            if mapped:
                for offs in range(len(buf)):
                    r = g = b = 0
                    c = buf[offs] & 0xFF
                    ea = addr + goffs + offs
                    f = get_func(ea)
                    if f:
                        g = b = c
                    elif self._is_string(ea):
                        g = c
                    else:
                        r = g = b = c
                    colors.append((True, qRgb(r, g, b)))
            else:
                for i in range(len(buf)):
                    colors.append((False, None))
            goffs += len(buf)
        return colors 
Example #5
Source File: sms.py    From IDACyber with MIT License 6 votes vote down vote up
def _get_frame(self):
        result = False
        sp = get_sp_val()
        ip = get_ip_val()

        if ip and sp:
            f = get_func(ip)
            if f:
                frame = get_frame(f)
                if frame:
                    self.framesize = get_struc_size(frame)
                    n = frame.memqty
                    frame_offs = f.frregs + f.frsize
                    self.ea = sp - get_spd(f, ip) - frame_offs
                    for i in range(n):
                        m = frame.get_member(i)
                        if m:
                            lvar_name = get_member_name(m.id)
                            lvar_ea = self.ea + m.soff
                            lvar_size = m.eoff - m.soff
                            self.members[lvar_ea] = (lvar_name, m.soff, lvar_size, frame_offs)
                    result = True
        return result 
Example #6
Source File: widgets.py    From rematch with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, text_max_length=30, **kwargs):
    super(QFunctionSelect, self).__init__(**kwargs)

    self.text_max = text_max_length
    self.func = None

    self.label = QtWidgets.QPushButton()
    self.label.clicked.connect(self.label_clicked)
    self.label.setFlat(True)
    self.btn = QtWidgets.QPushButton("...")
    self.btn.setMaximumWidth(20)
    self.btn.clicked.connect(self.btn_clicked)

    current_func = ida_funcs.get_func(idc.ScreenEA())
    if current_func:
      self.set_func(current_func)

    layout = QtWidgets.QHBoxLayout()
    layout.setContentsMargins(0, 0, 0, 0)
    layout.addWidget(self.label)
    layout.addWidget(self.btn)
    layout.setStretch(0, 1)
    self.setLayout(layout) 
Example #7
Source File: basicblocksize_hist.py    From rematch with GNU General Public License v3.0 6 votes vote down vote up
def data(self):
    sizes_hist = defaultdict(int)
    seen = set()

    for node in ida_gdl.FlowChart(ida_funcs.get_func(self.offset)):
      if node.id in seen:
        continue
      seen.add(node.id)

      node_size = node.endEA - node.startEA
      sizes_hist[node_size] += 1

    if sum(sizes_hist.values()) < 5:
      return None

    return sizes_hist 
Example #8
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBlocks(self, function_offset):
        blocks = []
        function_chart = idaapi.FlowChart(idaapi.get_func(function_offset))
        for block in function_chart:
            extracted_block = []
            for instruction in idautils.Heads(block.startEA, block.endEA):
                if idc.isCode(idc.GetFlags(instruction)):
                    extracted_block.append(instruction)
            if extracted_block:
                blocks.append(extracted_block)
        return sorted(blocks) 
Example #9
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBlocks(self, function_offset):
        blocks = []
        function_chart = ida_gdl.FlowChart(ida_funcs.get_func(function_offset))
        for block in function_chart:
            extracted_block = []
            for instruction in idautils.Heads(block.start_ea, block.end_ea):
                if ida_bytes.is_code(ida_bytes.get_flags(instruction)):
                    extracted_block.append(instruction)
            if extracted_block:
                blocks.append(extracted_block)
        return sorted(blocks) 
Example #10
Source File: crawl.py    From IDACyber with MIT License 5 votes vote down vote up
def on_process_buffer(self, buffers, addr, size, mouse_offs):
        colors = []
        head = BADADDR
        tail = BADADDR
        goffs = 0

        for mapped, buf in buffers:
            if mapped:
                if mouse_offs is not None:
                    if self.switch == 0: # data
                        head = get_item_head(addr + mouse_offs)
                        tail = get_item_end(addr + mouse_offs)
                    else: # code
                        f = get_func(addr + mouse_offs)
                        if f:
                            head = f.start_ea
                            tail = f.end_ea

                for pos in range(len(buf)):
                    c = buf[pos] & 0xFF
                    
                    highlight = False
                    if mouse_offs is not None:
                        if addr + pos + goffs >= head and addr + pos + goffs < tail:
                            highlight = True
                    if self.last_sel:
                        lhead, lsize = self.last_sel
                        if addr + pos + goffs >= lhead and addr + pos + goffs < lhead+lsize:
                            highlight = True
                    if highlight:
                        colors.append((True, qRgb(c, 0xFF, self.hl_color)))
                    else:
                        colors.append((True, qRgb(c, 0, 0)))
            else:
                for pos in range(len(buf)):
                    colors.append((False, None))
            goffs += len(buf)
        return colors 
Example #11
Source File: crawl.py    From IDACyber with MIT License 5 votes vote down vote up
def _get_func_name(self, ea):
        f = get_func(ea)
        if f:
            return get_func_name(f.start_ea)
        return None 
Example #12
Source File: yara_fn.py    From python-idb with Apache License 2.0 5 votes vote down vote up
def get_function(va):
    """
    return va for first instruction in function that contains given va.
    """
    return ida_funcs.get_func(va).startEA 
Example #13
Source File: yara_fn.py    From python-idb with Apache License 2.0 5 votes vote down vote up
def get_basic_blocks(fva):
    """
    return sequence of `BasicBlock` instances for given function.
    """
    ret = []
    func = ida_funcs.get_func(fva)
    if func is None:
        return ret

    for bb in idaapi.FlowChart(func):
        ret.append(BasicBlock(va=bb.startEA, size=bb.endEA - bb.startEA))

    return ret 
Example #14
Source File: assembly.py    From rematch with GNU General Public License v3.0 5 votes vote down vote up
def data(self):
    func = ida_funcs.get_func(self.offset)

    def clean(asm):
      """This removes markers of function offsets, including hidden variable
      length offsets that are of different length on 32 and 64 bit address IDA.
      Otherwise, IDA of different offset lengths will truncate incorrect number
      of bytes"""
      hex_chars = int(log(ida_idaapi.BADADDR + 1, 2) / 4)
      pattern = "\x01\\([0-9a-zA-Z]{%s}(.*?)\x02\\)" % hex_chars
      replace = r"\g<1>"
      return re.sub(pattern, replace, asm)

    # make sure only nodes inside the function are accounted for
    # this solves cascaded functions (when multiple functions share same ends)
    def node_contained(node):
      return (ida_funcs.func_contains(func, node.startEA) and
              ida_funcs.func_contains(func, node.endEA - 1))
    nodes = filter(node_contained, ida_gdl.FlowChart(func))
    node_ids = map(lambda n: n.id, nodes)

    nodes_data = []
    for node in nodes:
      assembly = [clean(ida_lines.generate_disasm_line(ea))
                    for ea in idautils.Heads(node.startEA, node.endEA)]
      successive_nodes = [succ.id
                            for succ in node.succs()
                            if succ.id in node_ids]
      serialized_node = {'id': node.id, 'type': node.type,
                         'start': node.startEA, 'end': node.endEA,
                         'successive': successive_nodes, 'assembly': assembly}
      nodes_data.append(serialized_node)

    return nodes_data 
Example #15
Source File: basicblock_adjacency.py    From rematch with GNU General Public License v3.0 5 votes vote down vote up
def data(self):
    adjacencies = {}
    seen = set()

    for node in ida_gdl.FlowChart(ida_funcs.get_func(self.offset)):
      if node.id in seen:
        continue
      seen.add(node.id)

      adjacencies[node.id] = [succ.id for succ in node.succs()]

    if len(adjacencies) > 1:
      return adjacencies
    else:
      return None 
Example #16
Source File: events.py    From IDArling with GNU General Public License v3.0 5 votes vote down vote up
def refresh_pseudocode_view(ea):
        """Refreshes the pseudocode view in IDA."""
        names = ["Pseudocode-%c" % chr(ord("A") + i) for i in range(5)]
        for name in names:
            widget = ida_kernwin.find_widget(name)
            if widget:
                vu = ida_hexrays.get_widget_vdui(widget)

                # Check if the address is in the same function
                func_ea = vu.cfunc.entry_ea
                func = ida_funcs.get_func(func_ea)
                if ida_funcs.func_contains(func, ea):
                    vu.refresh_view(True) 
Example #17
Source File: events.py    From IDArling with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
        func = ida_funcs.get_func(self.start_ea_func)
        ida_funcs.remove_func_tail(func, self.tail_ea) 
Example #18
Source File: events.py    From IDArling with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
        func = ida_funcs.get_func(self.start_ea_func)
        ida_funcs.append_func_tail(func, self.start_ea_tail, self.end_ea_tail) 
Example #19
Source File: painter.py    From IDArling with GNU General Public License v3.0 5 votes vote down vote up
def data(self, index, role=Qt.DisplayRole):
            # Check if disabled by the user
            cursors = self._plugin.config["cursors"]
            if role == Qt.BackgroundRole and cursors["funcs"]:
                func_ea = int(index.sibling(index.row(), 2).data(), 16)
                func = ida_funcs.get_func(func_ea)
                for user in self._plugin.core.get_users().values():
                    if ida_funcs.func_contains(func, user["ea"]):
                        r, g, b = StatusWidget.ida_to_python(user["color"])
                        return QColor(StatusWidget.python_to_qt(r, g, b))
            index = self._model.index(index.row(), index.column())
            return self._model.data(index, role) 
Example #20
Source File: idaxml.py    From GhIDA with Apache License 2.0 5 votes vote down vote up
def export_stack_reference(self, addr):
        """
        Exports references to stack variables at the address.

        Args:
            addr: Integer containing instruction address.
        """
        f = idc.get_full_flags(addr)
        for op in range(ida_ida.UA_MAXOP):
            if idc.is_code(f) == True and ida_bytes.is_stkvar(f, op) == True:
                insn = ida_ua.insn_t()
                ida_ua.decode_insn(insn, addr)
                opnd = insn.ops[op]
                # TODO:How to handle opnd.type for stack references
                optype = opnd.type
                if optype == idc.o_void:
                    continue
                # TODO:How to handle op_t_get_addr for stack references
                SV = ida_frame.get_stkvar(insn, opnd, opnd.value)
                if SV == None:
                    continue
                (sv, actval) = SV
                function = ida_funcs.get_func(addr)
                self.start_element(STACK_REFERENCE)
                self.write_address_attribute(ADDRESS, addr)
                self.write_numeric_attribute(OPERAND_INDEX, op, 10)
                offset = opnd.addr
                spoff = offset - function.frregs
                if offset > 0x7FFFFFFF:
                    offset -= 0x100000000
                if spoff > 0x7FFFFFFF:
                    spoff -= 0x100000000
                self.write_numeric_attribute(STACK_PTR_OFFSET, spoff,
                                             16, True)
                if (function.flags & idc.FUNC_FRAME) != 0:
                    self.write_numeric_attribute(FRAME_PTR_OFFSET,
                                                 offset, 16, True)
                self.close_tag() 
Example #21
Source File: events.py    From IDArling with GNU General Public License v3.0 4 votes vote down vote up
def __call__(self):
        new_ranges = {r[0]: r for r in self.sreg_ranges}
        old_ranges = {r[0]: r for r in SgrChanged.get_sreg_ranges(self.rg)}

        start_eas = sorted(
            set(list(new_ranges.keys()) + list(old_ranges.keys()))
        )
        for start_ea in start_eas:
            new_range = new_ranges.get(start_ea, None)
            old_range = old_ranges.get(start_ea, None)

            if new_range and not old_range:
                _, __, val, tag = new_range
                ida_segregs.split_sreg_range(start_ea, self.rg, val, tag, True)

            if not new_range and old_range:
                ida_segregs.del_sreg_range(start_ea, self.rg)

            if new_range and old_range:
                _, __, new_val, new_tag = new_range
                _, __, old_val, old_tag = old_range
                if new_val != old_val or new_tag != old_tag:
                    ida_segregs.split_sreg_range(
                        start_ea, self.rg, new_val, new_tag, True
                    )

        ida_kernwin.request_refresh(ida_kernwin.IWID_SEGREGS)


# class GenRegvarDefEvent(Event):
#    __event__ = "gen_regvar_def"
#
#    def __init__(self, ea, canonical_name, new_name, cmt):
#        super(GenRegvarDefEvent, self).__init__()
#        self.ea = ea
#        self.canonical_name = Event.decode(canonical_name)
#        self.new_name = Event.decode(new_name)
#        self.cmt = Event.decode(cmt)
#
#    def __call__(self):
#        func = ida_funcs.get_func(self.ea)
#        ida_frame.add_regvar(
#            func,
#            func.start_ea,
#            func.end_ea,
#            Event.encode(self.canonical_name),
#            Event.encode(self.new_name),
#            Event.encode(self.cmt),
#        ) 
Example #22
Source File: idaxml.py    From GhIDA with Apache License 2.0 4 votes vote down vote up
def import_function(self, function):
        """
        Creates a function using the FUNCTION attributes.

        Args:
            function: XML element containing the function address and
                attributes.
        """
        if self.options.Functions.checked == False:
            return
        try:
            entry_point = self.get_address(function, ENTRY_POINT)
            name = ''
            if self.has_attribute(function, NAME):
                name = self.get_attribute(function, NAME)
            libfunc = 'n'
            if self.has_attribute(function, LIBRARY_FUNCTION):
                libfunc = self.get_attribute(function, LIBRARY_FUNCTION)
            if idc.is_mapped(entry_point) == False:
                msg = ("import_function: address %X not enabled in database"
                       % entry_point)
                print(msg)
                return
            idc.add_func(entry_point, BADADDR)
            self.update_counter(FUNCTION)
            func = ida_funcs.get_func(entry_point)
            if libfunc == 'y':
                func.flags |= idc.FUNC_LIB
            ranges = function.findall(ADDRESS_RANGE)
            for addr_range in ranges:
                (start, end) = self.import_address_range(addr_range)
                ida_funcs.append_func_tail(func, start, end)
            # TODO: auto_wait is probably not needed...
            if AUTO_WAIT:
                ida_auto.auto_wait()
            regcmt = function.find(REGULAR_CMT)
            if regcmt != None:
                self.update_counter(FUNCTION + ':' + REGULAR_CMT)
                ida_funcs.set_func_cmt(func, regcmt.text, False)
            rptcmt = function.find(REPEATABLE_CMT)
            if rptcmt != None:
                self.update_counter(FUNCTION + ':' + REPEATABLE_CMT)
                ida_funcs.set_func_cmt(func, rptcmt.text, True)
            typecmt = function.find(TYPEINFO_CMT)
            if typecmt != None:
                self.update_counter(FUNCTION + ':' + TYPEINFO_CMT)
                # TODO: TYPECMTs
                #idc.SetType(entry_point, typecmt.text + ';')
            sf = function.find(STACK_FRAME)
            if sf != None:
                self.import_stack_frame(sf, func)
            register_vars = function.findall(REGISTER_VAR)
            for register_var in register_vars:
                self.import_register_var(register_var, func)
        except:
            msg = "** Exception occurred in import_function **"
            print("\n" + msg + "\n", sys.exc_type, sys.exc_value) 
Example #23
Source File: idaxml.py    From GhIDA with Apache License 2.0 4 votes vote down vote up
def export_functions(self):
        """
        Exports information about all functions. 
        """
        functions = idautils.Functions()
        if functions == None:
            return
        self.update_status(FUNCTIONS)
        timer = time.clock()
        self.start_element(FUNCTIONS, True)
        for addr in functions:
            function = ida_funcs.get_func(addr)
            if ida_segment.is_spec_ea(function.start_ea) == True:
                continue
            self.start_element(FUNCTION)
            self.write_address_attribute(ENTRY_POINT, function.start_ea)
            if ida_bytes.has_user_name(idc.get_full_flags(addr)) == True:
                name = self.get_symbol_name(addr)
                if name != None and len(name) > 0:
                    self.write_attribute(NAME, name)
            if function.flags & idc.FUNC_LIB != 0:
                self.write_attribute(LIBRARY_FUNCTION, "y")
            self.close_tag(True)
            fchunks = idautils.Chunks(addr)
            for (startEA, endEA) in fchunks:
                self.start_element(ADDRESS_RANGE)
                self.write_address_attribute(START, startEA)
                self.write_address_attribute(END, endEA - 1)
                self.close_tag()
            regcmt = ida_funcs.get_func_cmt(function, False)
            if regcmt != None:
                self.export_regular_cmt(regcmt)
            rptcmt = ida_funcs.get_func_cmt(function, True)
            if rptcmt != None:
                self.export_repeatable_cmt(rptcmt)
            demangled = ida_name.get_demangled_name(addr,
                                                    DEMANGLED_TYPEINFO,
                                                    self.inf.demnames, True)
            if demangled != None and demangled == "'string'":
                demangled = None
            outbuf = ''
            # TODO: How to handle print_type for function typeinfo cmts
            #outbuf = idaapi.print_type(addr, False)
            has_typeinfo = (demangled != None or (outbuf != None and
                                                  len(outbuf) > 0))
            if demangled != None:
                self.export_typeinfo_cmt(demangled)
            elif has_typeinfo == True:
                self.export_typeinfo_cmt(outbuf[:-1])
            self.export_stack_frame(function)
            self.end_element(FUNCTION)
        self.end_element(FUNCTIONS)
        self.display_cpu_time(timer)