Python idc.here() Examples

The following are 30 code examples of idc.here(). 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: mykutils.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def emit_fnbytes_c(fva=None, warn=True):
    """Emit function bytes as C code with disassembly in comments.

    Args:
        fva (numbers.Integral): function virtual address.
            Defaults to here() if that is the start of a function, else
            defaults to the start of the function that here() is a part of.
        warn (bool): enable interactive warnings

    Returns:
        str: C code you can spruce up and paste into a script.
    """

    header = 'unsigned char *instrs_{name} = {{\n'
    footer = '};'
    indent = '\t'

    def _emit_instr_for_c(va, the_bytes, size):
        disas = idc.GetDisasm(va)
        buf = ''.join(['\\x%s' % (binascii.hexlify(c)) for c in the_bytes])
        return '"%s" /* %s */\n' % (buf, disas)

    return _emit_fnbytes(_emit_instr_for_c, header, footer, indent, fva, warn) 
Example #2
Source File: mykutils.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def emit_fnbytes_python(fva=None, warn=True):
    """Emit function bytes as Python code with disassembly in comments.

    Args:
        fva (numbers.Integral): function virtual address.
            Defaults to here() if that is the start of a function, else
            defaults to the start of the function that here() is a part of.
        warn (bool): enable interactive warnings

    Returns:
        str: Python code you can spruce up and paste into a script.
    """
    header = 'instrs_{name} = (\n'
    footer = ')'
    indent = '    '

    def _emit_instr_python(va, the_bytes, size):
        disas = idc.GetDisasm(va)
        return "'%s' # %s\n" % (binascii.hexlify(the_bytes), disas)

    return _emit_fnbytes(_emit_instr_python, header, footer, indent, fva, warn) 
Example #3
Source File: struct_typer.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def stripNumberedName(name):
    '''Remove trailing unique ID like IDA does for same names'''
    idx = len(name) -1
    while idx >= 0:
        if (name[idx] == '_'):
            if (len(name)-1) == idx:
                #last char is '_', not allowed so return name
                return name
            else:
                #encountered a '_', strip here
                return name[:idx]
        if name[idx] in g_NUMBERS:
            #still processing tail
            pass
        else:
            #encountered unexpected sequence, just return name
            return name
        idx -= 1
    return name 
Example #4
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 #5
Source File: meaningful.py    From Sark with MIT License 6 votes vote down vote up
def show_highlighted_function_meaningful():
    line = sark.Line()
    meaningful_displayed = False
    for xref in line.xrefs_from:
        try:
            if xref.type.is_flow:
                continue

            function = sark.Function(xref.to)
            show_meaningful_in_function(function)
            meaningful_displayed = True

        except sark.exceptions.SarkNoFunction:
            pass

    if not meaningful_displayed:
        idaapi.msg("[FunctionStrings] No function referenced by current line: 0x{:08X}.\n".format(idc.here())) 
Example #6
Source File: line.py    From Sark with MIT License 6 votes vote down vote up
def __init__(self, ea=UseCurrentAddress, name=None):
        if name is not None and ea != self.UseCurrentAddress:
            raise ValueError(("Either supply a name or an address (ea). "
                              "Not both. (ea={!r}, name={!r})").format(ea, name))

        elif name is not None:
            ea = idc.get_name_ea_simple(name)

        elif ea == self.UseCurrentAddress:
            ea = idc.here()

        elif ea is None:
            raise ValueError("`None` is not a valid address. To use the current screen ea, "
                             "use `Line(ea=Line.UseCurrentAddress)` or supply no `ea`.")

        self._ea = idaapi.get_item_head(ea)
        self._comments = Comments(self._ea) 
Example #7
Source File: function.py    From Sark with MIT License 6 votes vote down vote up
def __init__(self, ea=UseCurrentAddress, name=None):
        if name is not None and ea != self.UseCurrentAddress:
            raise ValueError(("Either supply a name or an address (ea). "
                              "Not both. (ea={!r}, name={!r})").format(ea, name))

        elif name is not None:
            ea = idc.get_name_ea_simple(name)
            if ea == idc.BADADDR:
                raise exceptions.SarkNoFunction(
                    "The supplied name does not belong to an existing function. "
                    "(name = {!r})".format(name))

        elif ea == self.UseCurrentAddress:
            ea = idc.here()

        elif ea is None:
            raise ValueError("`None` is not a valid address. To use the current screen ea, "
                             "use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`.")

        elif isinstance(ea, Line):
            ea = ea.ea
        self._func = get_func(ea)
        self._comments = Comments(self) 
Example #8
Source File: MainWidget.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def decode_here_clicked(self):
        inst = idc.here()
        if not idc.isCode(idc.GetFlags(inst)):
            print "Not code instruction"
        else:
            raw = idc.GetManyBytes(inst, idc.NextHead(inst)-inst)
            s = to_hex(raw)
            self.decode_ir(s) 
Example #9
Source File: mykutils.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def for_each_call_to(callback, va=None):
    """For each xref to va that is a call, pass xref va to callback.

    Falls back to highlighted identifier or current location if va is
    unspecified.
    """
    if not va:
        v = ida_kernwin.get_current_viewer()
        hi = ida_kernwin.get_highlight(v)
        if hi and hi[1]:
            nm = hi[0]
            va = idc.get_name_ea_simple(nm)
            if va >= idaapi.cvar.inf.maxEA:
                va = None

    va = va or idc.here()

    # Obtain and de-duplicate addresses of xrefs that are calls
    callsites = set([x.frm for x in idautils.XrefsTo(va)
                     if idc.print_insn_mnem(x.frm) == 'call'])
    for va in callsites:
        callback(va)


# Instruction operand specification.
#
# Operand types are from ida_ua.o_* e.g. o_reg, o_mem.
# >>> {x: getattr(ida_ua, x) for x in dir(ida_ua) if x.startswith('o_')}
#
# Quick ref:
#   ida_ua.o_reg ==      1: "General Register (al,ax,es,ds...)",
#   ida_ua.o_mem ==      2: "Memory Reference",
#   ida_ua.o_phrase ==   3: "Base + Index",
#   ida_ua.o_displ ==    4: "Base + Index + Displacement",
#   ida_ua.o_imm ==      5: "Immediate",
#   ida_ua.o_far ==      6: "Immediate Far Address",
#   ida_ua.o_near ==     7: "Immediate Near Address",
#   ida_ua.o_idpspec0 == 8: "FPP register",
#   ida_ua.o_idpspec1 == 9: "386 control register",
#   ida_ua.o_idpspec2 == 10: "386 debug register",
#   ida_ua.o_idpspec3 == 11: "386 trace register", 
Example #10
Source File: stackstrings.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def main(doAllFuncs=True):
    #doAllFuncs=False
    #jayutils.configLogger(__name__, logging.DEBUG)
    jayutils.configLogger(__name__, logging.INFO)
    logger = jayutils.getLogger('stackstrings')
    logger.debug('Starting up now')
    filePath = jayutils.getInputFilepath()
    if filePath is None:
        self.logger.info('No input file provided. Stopping')
        return
    vw = jayutils.loadWorkspace(filePath)
    ea = idc.here()
    res = -1
    if using_ida7api:
        res = idc.ask_yn(0, 'Use basic-block local aggregator')
    else:
        res = idc.AskYN(0, 'Use basic-block local aggregator')
    if res == idaapi.ASKBTN_CANCEL:
        print 'User canceled'
        return
    uselocalagg = (res == 1)
    ranges = getFuncRanges(ea, doAllFuncs)
    for funcStart, funcEnd in ranges:
        try:
            logger.debug('Starting on function: 0x%x', funcStart)
            stringList = runStrings(vw, funcStart, uselocalagg)    
            for node, string in stringList:
                if isLikelyFalsePositiveString(string):
                    #if it's very likely a FP, skip annotating
                    continue
                print '0x%08x: %s' % (node[0], string)
                #print '0x%08x: 0x%08x: %s %s' % (node[0], node[1], binascii.hexlify(string), string)
                if using_ida7api:
                    idc.set_cmt(node[0], string.strip(), 0)
                else:
                    idc.MakeComm(node[0], string.strip())
        except Exception, err:
            logger.exception('Error during parse: %s', str(err)) 
Example #11
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 #12
Source File: vtableAddress.py    From Virtuailor with GNU General Public License v3.0 5 votes vote down vote up
def get_local_var_value_64(loc_var_name):
    frame = ida_frame.get_frame(idc.here())
    loc_var = ida_struct.get_member_by_name(frame, loc_var_name)
    loc_var_start = loc_var.soff
    loc_var_ea = loc_var_start + idc.get_reg_value("RSP")
    loc_var_value = idc.read_dbg_qword(loc_var_ea)  # in case the variable is 32bit, just use get_wide_dword() instead
    return loc_var_value 
Example #13
Source File: mkyara_plugin.py    From mkYARA with GNU General Public License v3.0 5 votes vote down vote up
def get_selection():
    start = idc.read_selection_start()
    end = idc.read_selection_end()
    if idaapi.BADADDR in (start, end):
        ea = idc.here()
        start = idaapi.get_item_head(ea)
        end = idaapi.get_item_end(ea)
    return start, end 
Example #14
Source File: function_strings.py    From Sark with MIT License 5 votes vote down vote up
def show_current_function_strings():
    try:
        function = sark.Function(idc.here())
        show_function_strings(function)

    except sark.exceptions.SarkNoFunction:
        idaapi.msg("[FunctionStrings] No function at 0x{:08X}.\n".format(idc.here())) 
Example #15
Source File: segment.py    From Sark with MIT License 5 votes vote down vote up
def __init__(self, ea=UseCurrentAddress, name=None, index=None, segment_t=None):
        """Wrapper around IDA segments.

        There are 3 ways to get a segment - by name, ea or index. Only use one.

        Args:
            ea - address in the segment
            name - name of the segment
            index - index of the segment
        """
        if sum((ea not in (self.UseCurrentAddress, None), name is not None, index is not None,
                segment_t is not None,)) > 1:
            raise ValueError((
                                 "Expected only one (ea, name, index or segment_t)."
                                 " Got (ea={!r}, name={!r}, index={!r}, segment_t={!r})"
                             ).format(ea,
                                      name,
                                      index,
                                      segment_t))


        elif segment_t is not None:
            seg = segment_t

        elif name is not None:
            seg = idaapi.get_segm_by_name(name)

        elif index is not None:
            seg = idaapi.getnseg(index)

        elif ea == self.UseCurrentAddress:
            seg = idaapi.getseg(idc.here())

        elif ea is None:
            raise ValueError("`None` is not a valid address. To use the current screen ea, "
                             "use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`.")

        else:
            seg = idaapi.getseg(ea)

        self._segment = seg 
Example #16
Source File: function.py    From Sark with MIT License 5 votes vote down vote up
def create(ea=UseCurrentAddress):
        if ea == Function.UseCurrentAddress:
            ea = idc.here()

        if Function.is_function(ea):
            raise exceptions.SarkFunctionExists("Function already exists")

        if not add_func(ea):
            raise exceptions.SarkAddFunctionFailed("Failed to add function")

        return Function(ea) 
Example #17
Source File: base.py    From Sark with MIT License 5 votes vote down vote up
def get_selection(always=True):
    start = idc.read_selection_start()
    end = idc.read_selection_end()

    if idaapi.BADADDR in (start, end):
        if not always:
            raise exceptions.SarkNoSelection()

        ea = idc.here()
        start = idaapi.get_item_head(ea)
        end = idaapi.get_item_end(ea)

    return Selection(start, end) 
Example #18
Source File: DIE.py    From DIE with MIT License 5 votes vote down vote up
def go_here(self):
        self.debugAPI.start_debug(idc.here(), None, auto_start=True) 
Example #19
Source File: utility.py    From GhIDA with Apache License 2.0 5 votes vote down vote up
def get_current_address():
    """
    Get the hex address of the function.
    """
    ca = idc.here()
    func = idaapi.get_func(ca)
    if not func:
        print("GhIDA:: [!] Error: function not found.")
        return None

    # Get function start address
    ea = func.start_ea
    ea = hex(ea).strip("0x").strip("L")
    return ea 
Example #20
Source File: enumerators.py    From idascripts with MIT License 5 votes vote down vote up
def ArrayItems(*args):
    """
    Enumerate array items

    @param ea:    address of the array you want the items enumerated, defaults to here()

    @return: list of each item in the array.

    Example::

        for ea in ArrayItems():
           pname= GetString(Dword(ea))
           MakeName(Dword(ea+4)&~1, "task_%s" % pname)
           MakeName(Dword(ea+8), "taskinfo_%s" % pame)
           MakeName(Dword(ea+12), "stack_%s" % pame)


    Assuming the cursor is on an array of structs, in which the
    first struct item points to a name, this will name the other
    items in the struct.
    """
    ea = args[0] if len(args)>0 else idc.here()

    s= idc.ItemSize(ea)
    ss= idaapi.get_data_elsize(ea, idaapi.get_full_flags(ea))

    n= s/ss

    for i in xrange(n):
        yield ea+i*ss 
Example #21
Source File: enumerators.py    From idascripts with MIT License 5 votes vote down vote up
def Code(*args):
    """
    Enumerate code bytes

    @param <range>: see getrange

    @return: list of addresses of code bytes

    Example::

        for ea in Code():
            MakeUnkn(ea, DOUNK_EXPAND)
            Wait()

    Will delete all code in the selected area.


        len(list(MakeUnkn(ea, DOUNK_EXPAND) and Wait() for ea in enumerators.Code(idaapi.getseg(here()))))

    will delete all code in the current segment, and can be pasted in the command area of ida

    """
    (first, last)= getrange(args)

    ea= first
    # explicitly testing first byte, since find_code
    # implicitly sets SEARCH_NEXT flag
    if ea<last and not idaapi.is_code(idaapi.get_full_flags(ea)):
        ea= idaapi.find_code(ea, idaapi.SEARCH_DOWN)
    while ea!=idaapi.BADADDR and ea<last:
        yield ea
        ea= idaapi.find_code(ea, idaapi.SEARCH_DOWN) 
Example #22
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def target_addr_button_clicked(self):
        ea = idc.here()
        self.target_addr_field.setText(hex(ea))
        cmt = idc.RptCmt(ea)
        if cmt is not None:
            if cmt.startswith("//@assert:"):
                expr = cmt.split(":")[1].lstrip()
                self.dba_expr_field.setText(expr) 
Example #23
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def restrict_to_button_clicked(self):
        self.restrict_to_field.setText(hex(idc.here())) 
Example #24
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def restrict_from_button_clicked(self):
        self.restrict_from_field.setText(hex(idc.here())) 
Example #25
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def to_button_clicked(self):
        self.to_field.setText(hex(idc.here())) 
Example #26
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def from_button_clicked(self):
        self.from_field.setText(hex(idc.here())) 
Example #27
Source File: static_opaque_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def highlight_spurious(self, enabled):
        print "Highlight spurious clicked !"
        curr_fun = idaapi.get_func(idc.here()).startEA
        cfg = self.functions_cfg[curr_fun]
        color = 0xFFFFFF if enabled else 0x507cff
        for bb in [x for x in cfg.values() if x.is_alive()]:  # Iterate only alive basic blocks
            for i, st in bb.instrs_status.items():
                if st == Status.DEAD:  # Instructions dead in alive basic blocks are spurious
                    idc.SetColor(i, idc.CIC_ITEM, color)
        self.actions[HIGHLIGHT_SPURIOUS_CALCULUS] = (self.highlight_spurious, not enabled)
        self.result_widget.action_selector_changed(HIGHLIGHT_SPURIOUS_CALCULUS) 
Example #28
Source File: static_opaque_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def highlight_dead_code(self, enabled):
        curr_fun = idaapi.get_func(idc.here()).startEA
        cfg = self.functions_cfg[curr_fun]
        # for cfg in self.functions_cfg.values():
        for bb in cfg.values():
            color = {Status.DEAD: 0x5754ff, Status.ALIVE: 0x98FF98, Status.UNKNOWN: 0xaa0071}[bb.status]
            color = 0xFFFFFF if enabled else color
            for i in bb:
                idc.SetColor(i, idc.CIC_ITEM, color)
        self.actions[HIGHLIGHT_DEAD_CODE] = (self.highlight_dead_code, not enabled)
        self.result_widget.action_selector_changed(HIGHLIGHT_DEAD_CODE) 
Example #29
Source File: static_opaque_analysis.py    From idasec with 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 #30
Source File: StandardParamWidget.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def target_button_clicked(self):
        self.target_field.setText(hex(idc.here()))