Python idc.isCode() Examples

The following are 19 code examples for showing how to use idc.isCode(). 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module idc , or try the search function .

Example 1
Project: idasec   Author: RobinDavid   File: TraceWidget.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def colorize_trace(self):
        try:
            index = self.traces_tab.currentIndex()
            trace = self.core.traces[self.id_map[index]]
            if self.colorized:
                self.colorize_button.setText("Colorize trace")
                color = 0xffffff
            else:
                self.colorize_button.setText("Uncolorize trace")
                self.colorize_button.setFlat(True)
                color = 0x98FF98
            for inst in trace.instrs.values():
                if idc.isCode(idc.GetFlags(inst.address)):
                    idc.SetColor(inst.address, idc.CIC_ITEM, color)
            if not self.colorized:
                self.colorize_button.setFlat(False)
                self.colorized = True
            else:
                self.colorized = False

        except KeyError:
            print "No trace found" 
Example 2
Project: idasec   Author: RobinDavid   File: TraceWidget.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def heatmap_trace(self):
        try:
            index = self.traces_tab.currentIndex()
            trace = self.core.traces[self.id_map[index]]
            if self.heatmaped:
                self.heatmap_button.setText("Heatmap")
                color = lambda x: 0xffffff
            else:
                self.heatmap_button.setText("Heatmap undo")
                self.heatmap_button.setFlat(True)
                hit_map = trace.address_hit_count
                color_map = self.compute_step_map(set(hit_map.values()))
                print color_map
                color = lambda x: color_map[hit_map[x]]
            for inst in trace.instrs.values():
                if idc.isCode(idc.GetFlags(inst.address)):
                    c = color(inst.address)
                    idc.SetColor(inst.address, idc.CIC_ITEM, c)
            if not self.heatmaped:
                self.heatmap_button.setFlat(False)
                self.heatmaped = True
            else:
                self.heatmaped = False
        except KeyError:
            print "No trace found" 
Example 3
Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def sign_extend(x, b):
  m = 1 << (b - 1)
  x = x & ((1 << b) - 1)
  return (x ^ m) - m

# Returns `True` if `ea` belongs to some code segment.
#
# TODO(pag): This functon is extra aggressive, in that it doesn't strictly
#            trust the `idc.isCode`. I have observed cases where data in
#            `.bss` is treated as code and I am not sure why. Perhaps adding
#            a reference to the data did this.
#
#            I think it has something to do with ELF thunks, e.g. entries in
#            the `.plt` section. When I made this function stricter,
#            `mcsema-lift` would report issues where it needed to add tail-calls
#            to externals. 
Example 4
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 5
Project: idasec   Author: RobinDavid   File: TraceWidget.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def disassemble_from_trace(self):
        try:
            index = self.traces_tab.currentIndex()
            trace = self.core.traces[self.id_map[index]]

            self.disassemble_button.setFlat(True)
            found_match = False
            for k, inst in trace.instrs.items():
                if k in trace.metas:
                    for name, arg1, arg2 in trace.metas[k]:
                        if name == "wave":
                            self.parent.log("LOG", "Wave n°%d encountered at (%s,%x) stop.." % (arg1, k, inst.address))
                            prev_inst = trace.instrs[k-1]
                            idc.MakeComm(prev_inst.address, "Jump into Wave %d" % arg1)
                            self.disassemble_button.setFlat(False)
                            return
                # TODO: Check that the address is in the address space of the program
                if not idc.isCode(idc.GetFlags(inst.address)):
                    found_match = True
                    # TODO: Add an xref with the previous instruction
                    self.parent.log("LOG", "Addr:%x not decoded as an instruction" % inst.address)
                    if idc.MakeCode(inst.address) == 0:
                        self.parent.log("ERROR", "Fail to decode at:%x" % inst.address)
                    else:
                        idaapi.autoWait()
                        self.parent.log("SUCCESS", "Instruction decoded at:%x" % inst.address)

            if not found_match:
                self.parent.log("LOG", "All instruction are already decoded")
            self.disassemble_button.setFlat(False)
        except KeyError:
            print "No trace found to use" 
Example 6
Project: idasec   Author: RobinDavid   File: MainWidget.py    License: 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 7
Project: idasec   Author: RobinDavid   File: generic_analysis.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def type_to_string(t):
        if idc.isCode(t):
            return "C"
        elif idc.isData(t):
            return "D"
        elif idc.isTail(t):
            return "T"
        elif idc.isUnknown(t):
            return "Ukn"
        else:
            return "Err" 
Example 8
Project: idasec   Author: RobinDavid   File: idasec_core.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def compute_nb_instr(self):
        return 0  # FIXME: by iterating all segments
        count = 0
        start, stop = self.seg_mapping[".text"]  # TODO: Iterate all executable segs
        current = start
        while current <= stop:
            if idc.isCode(idc.GetFlags(current)):
                count += 1
            current = idc.NextHead(current, stop)
        return count 
Example 9
Project: idawilli   Author: williballenthin   File: hint_calls.py    License: Apache License 2.0 5 votes vote down vote up
def get_custom_viewer_hint(self, view, place):
        try:
            tform = idaapi.get_current_tform()
            if idaapi.get_tform_type(tform) != idaapi.BWN_DISASM:
                return None

            curline = idaapi.get_custom_viewer_curline(view, True)
            
            # sometimes get_custom_viewer_place() returns [x, y] and sometimes [place_t, x, y].
            # we want the place_t.
            viewer_place = idaapi.get_custom_viewer_place(view, True)
            if len(viewer_place) != 3:
                return None

            _, x, y = viewer_place
            ea = place.toea()

            # "color" is a bit of misnomer: its the type of the symbol currently hinted
            color = get_color_at_char(curline, x)
            if color != idaapi.COLOR_ADDR:
                return None

            # grab the FAR references to code (not necessarilty a branch/call/jump by itself)
            far_code_references = [xref.to for xref in idautils.XrefsFrom(ea, ida_xref.XREF_FAR) 
                                   if idc.isCode(idc.GetFlags(xref.to))]
            if len(far_code_references) != 1:
                return None

            fva = far_code_references[0]

            # ensure its actually a function
            if not idaapi.get_func(fva):
                return None

            # this magic constant is the number of "important lines" to display by default.
            # the remaining lines get shown if you scroll down while the hint is displayed, revealing more lines.
            return render_function_hint(fva), DEFAULT_IMPORTANT_LINES_NUM
        except Exception as e:
            logger.warning('unexpected exception: %s. Get in touch with @williballenthin.', e, exc_info=True)
            return None 
Example 10
Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def is_code_by_flags(ea):
  if not is_code(ea):
    return False

  flags = idc.GetFlags(ea)
  return idc.isCode(flags) 
Example 11
Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def crefs_from(ea, only_one=False, check_fixup=True):
  flags = idc.GetFlags(ea)
  if not idc.isCode(flags):
    return

  fixup_ea = idc.BADADDR
  seen = False
  has_one = only_one
  if check_fixup:
    fixup_ea = idc.GetFixupTgtOff(ea)
    if not is_invalid_ea(fixup_ea) and is_code(fixup_ea):
      seen = only_one
      has_one = True
      yield fixup_ea

    if has_one and _stop_looking_for_xrefs(ea):
      return

  for target_ea in _xref_generator(ea, idaapi.get_first_cref_from, idaapi.get_next_cref_from):
    if target_ea != fixup_ea and not is_invalid_ea(target_ea):
      seen = only_one
      yield target_ea
      if seen:
        return

  if not seen and ea in _CREFS_FROM:
    for target_ea in _CREFS_FROM[ea]:
      seen = only_one
      yield target_ea
      if seen:
        return 
Example 12
Project: mcsema   Author: lifting-bits   File: exception.py    License: Apache License 2.0 5 votes vote down vote up
def find_xrefs(addr):
  lrefs = list(idautils.DataRefsTo(addr))
  if len(lrefs) == 0:
    lrefs = list(idautils.refs(addr, first, next))

  lrefs = [r for r in lrefs if not idc.isCode(idc.GetFlags(r))]
  return lrefs 
Example 13
Project: DIE   Author: ynvb   File: BpHandler.py    License: MIT License 5 votes vote down vote up
def setBPs(self):
        """
        Set breakpoints on all CALL and RET instructions in all of the executable sections.
        """
        for seg_ea in idautils.Segments():
            for head in idautils.Heads(seg_ea, idc.SegEnd(seg_ea)):
                if idc.isCode(idc.GetFlags(head)):
                    # Add BP if instruction is a CALL
                    if is_call(head):
                        self.addBP(head) 
Example 14
Project: DIE   Author: ynvb   File: BpHandler.py    License: MIT License 5 votes vote down vote up
def get_called_func_data(self, ea):
        """
        Try to get the called function name and address.
        @param ea: Address to the CALL instruction
        @return: On success a tuple of called function data (Function_ea, Demangled_Function_Name).
        otherwise (None,None) tuple will be returned
        """
        try:
            func_name = None
            call_dest = None

            if idc.isCode(idc.GetFlags(ea)):
                if is_call(ea):
                    operand_type = idc.GetOpType(ea, 0)
                    if operand_type in (5, 6, 7, 2):
                        call_dest = idc.GetOperandValue(ea, 0)  # Call destination
                        func_name = get_function_name(call_dest).lower()

            return call_dest, func_name

        except Exception as ex:
            self.logger.exception("Failed to get called function data: %s", ex)
            return None, None

    ###############################################################################################
    #   Dynamic (RunTime) Breakpoints 
Example 15
Project: DIE   Author: ynvb   File: BpHandler.py    License: MIT License 5 votes vote down vote up
def walk_function(self, ea):
        """
        Walk function and place breakpoints on every call function found within it.
        @param ea: An effective address within the function.
        @return: True if function walked succeeded or False otherwise
        """
        try:
            function_name = get_function_name(ea)
            self.logger.debug("Walking function %s at address %s for breakpoints", function_name, hex(ea))

            if function_name in self.walked_functions:
                self.logger.debug("No breakpoints will be set in function %s, "
                                  "since it was already walked before.", function_name)
                return True

            # Add function to walked function list
            self.walked_functions[function_name] = ea

            # function = sark.Function(ea)
            # for line in function.lines:
            #     if line.is_code and line.insn.is_call:
            #         self.addBP(line.ea)
            start_adrs = get_function_start_address(ea)
            end_adrs = get_function_end_address(ea)

            # Walk function and place breakpoints on every call instruction found.
            for head in idautils.Heads(start_adrs, end_adrs):
                if idc.isCode(idc.GetFlags(head)):
                    # Add BP if instruction is a CALL
                    if is_call(head):
                        self.addBP(head)

            self.logger.debug("Function %s was successfully walked for breakpoints", function_name)
            return True

        except Exception as ex:
            self.logger.exception("Failed walking function at address %s for breakpoints.", hex(ea))
            return False 
Example 16
Project: vxhunter   Author: PAGalaxyLab   File: vxhunter_ida.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fix_code(start_address, end_address):
        # Todo: There might be some data in the range of codes.
        offset = start_address
        while offset <= end_address:
            offset = idc.NextAddr(offset)
            flags = idc.GetFlags(offset)
            if not idc.isCode(flags):
                # Todo: Check should use MakeCode or MakeFunction
                # idc.MakeCode(offset)
                idc.MakeFunction(offset) 
Example 17
Project: smda   Author: danielplohmann   File: IdaInterface.py    License: 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 18
Project: ida_kernelcache   Author: bazad   File: ida_utilities.py    License: MIT License 4 votes vote down vote up
def _convert_address_to_function(func):
    """Convert an address that IDA has classified incorrectly into a proper function."""
    # If everything goes wrong, we'll try to restore this function.
    orig = idc.FirstFuncFchunk(func)
    # If the address is not code, let's undefine whatever it is.
    if not idc.isCode(idc.GetFlags(func)):
        if not is_mapped(func):
            # Well, that's awkward.
            return False
        item    = idc.ItemHead(func)
        itemend = idc.ItemEnd(func)
        if item != idc.BADADDR:
            _log(1, 'Undefining item {:#x} - {:#x}', item, itemend)
            idc.MakeUnkn(item, idc.DOUNK_EXPAND)
            idc.MakeCode(func)
            # Give IDA a chance to analyze the new code or else we won't be able to create a
            # function.
            idc.Wait()
            idc.AnalyseArea(item, itemend)
    else:
        # Just try removing the chunk from its current function. IDA can add it to another function
        # automatically, so make sure it's removed from all functions by doing it in loop until it
        # fails.
        for i in range(1024):
            if not idc.RemoveFchunk(func, func):
                break
    # Now try making a function.
    if idc.MakeFunction(func) != 0:
        return True
    # This is a stubborn chunk. Try recording the list of chunks, deleting the original function,
    # creating the new function, then re-creating the original function.
    if orig != idc.BADADDR:
        chunks = list(idautils.Chunks(orig))
        if idc.DelFunction(orig) != 0:
            # Ok, now let's create the new function, and recreate the original.
            if idc.MakeFunction(func) != 0:
                if idc.MakeFunction(orig) != 0:
                    # Ok, so we created the functions! Now, if any of the original chunks are not
                    # contained in a function, we'll abort and undo.
                    if all(idaapi.get_func(start) for start, end in chunks):
                        return True
            # Try to undo the damage.
            for start, _ in chunks:
                idc.DelFunction(start)
    # Everything we've tried so far has failed. If there was originally a function, try to restore
    # it.
    if orig != idc.BADADDR:
        _log(0, 'Trying to restore original function {:#x}', orig)
        idc.MakeFunction(orig)
    return False 
Example 19
Project: idataco   Author: jjo-sec   File: imports.py    License: GNU General Public License v3.0 4 votes vote down vote up
def renameDword(self):
        proc_addr = self._import_table.item(self._import_table.currentRow(), 3).text()
        proc_name = str(self._import_table.item(self._import_table.currentRow(), 2).text())
        renamed = 0
        if proc_addr:
            try:
                proc_addr = int(proc_addr, 16)
                proc_bin_str = " ".join([x.encode("hex") for x in struct.pack("<I", proc_addr)])
                next_dword = idc.FindBinary(idc.MinEA(), idc.SEARCH_DOWN|idc.SEARCH_NEXT, proc_bin_str)
                while next_dword != idc.BADADDR:
                    log.debug("Trying to fix-up 0x{:08x}".format(next_dword))
                    # DWORDs can be "inaccessible" for many reasons and it requires "breaking up" the data blobs
                    # and manually fixing them

                    # Reason 1: In a dword array in an unknown section
                    if idc.isUnknown(next_dword):
                        idc.MakeUnkn(next_dword, idc.DOUNK_EXPAND)
                        idc.MakeDword(next_dword)
                    # Reason 2: In a dword array in a data section
                    elif idc.isData(next_dword):
                        hd = idc.ItemHead(next_dword)
                        idc.MakeDword(hd)
                        idc.MakeDword(next_dword)
                    # Reason 3: In a dword array in a code section (validate via "dd <dword>,")
                    elif idc.isCode(next_dword) and idc.GetDisasm(next_dword).startswith("dd "):
                        hd = idc.ItemHead(next_dword)
                        idc.MakeDword(hd)
                        idc.MakeDword(next_dword)

                    # Only perform
                    if idc.Name(next_dword).startswith(("off_", "dword_")) or idc.Name(next_dword) == "":
                        success = idc.MakeNameEx(next_dword, proc_name, idc.SN_NOWARN|idc.SN_NON_AUTO)
                        i = 0
                        new_proc_name = proc_name
                        while not success and i < 10:
                            new_proc_name = "{}{}".format(proc_name, i)
                            success = idc.MakeNameEx(next_dword, new_proc_name, idc.SN_NOWARN|idc.SN_NON_AUTO)
                            i += 1
                        if success:
                            renamed += 1
                            item = self._import_table.item(self._import_table.currentRow(), 5)
                            item.setText("{}, {}".format(str(item.text()), new_proc_name))
                            log.debug("DWORD @ 0x{:08x} now has name {}".format(next_dword, new_proc_name))
                        else:
                            log.error("Unable to auto-rename successfully, terminating search")
                            break
                    else: log.debug("Value at 0x{:08x} does not meet renaming requirements".format(next_dword))
                    next_dword = idc.FindBinary(next_dword+4, idc.SEARCH_DOWN|idc.SEARCH_NEXT, proc_bin_str)
            except Exception, e:
                log.error("Error encountered: {}".format(e))
            log.debug("Renamed {:d} instances of {}".format(renamed, proc_name))