Python idc.MakeCode() Examples

The following are 14 code examples of idc.MakeCode(). 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: loader.py    From idawasm with Apache License 2.0 6 votes vote down vote up
def load_globals_section(section, p):
    '''
    Specialized handler for the GLOBALS section to mark the initializer as code.
    '''
    ppayload = p + idawasm.common.offset_of(section.data, 'payload')
    pglobals = ppayload + idawasm.common.offset_of(section.data.payload, 'globals')
    pcur = pglobals
    for i, body in enumerate(section.data.payload.globals):
        gname = 'global_%X' % (i)
        # we need a target that people can rename.
        # so lets map `global_N` to the init expr field.
        # this will look like:
        #
        #     global_0        <---- named address we can reference
        #     global_0_init:  <---- fake label line
        #        i32.const    <---- init expression insns
        #        ret
        pinit = pcur + idawasm.common.offset_of(body, 'init')
        idc.MakeName(pinit, gname)
        idc.ExtLinA(pinit, 0, gname + '_init:')
        idc.MakeCode(pinit)

        pcur += idawasm.common.size_of(body) 
Example #2
Source File: configuration_file.py    From idasec with 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 #3
Source File: TraceWidget.py    From idasec with 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 #4
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def disassemble_new_targets(self, _):
        for value in self.results.values:
            flag = idc.GetFlags(value)
            if not idc.isCode(flag) and idc.isUnknown(flag):
                res = idc.MakeCode(value)
                if res == 0:
                    print "Try disassemble at:"+hex(value)+" KO"
                    # TODO: Rollback ?
                else:
                    print "Try disassemble at:"+hex(value)+" Success !"


# ============================= RESULT WIDGET ===============================
# =========================================================================== 
Example #5
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def try_mark_as_code(ea):
  if is_code(ea) and not is_code_by_flags(ea):
    idc.MakeCode(ea)
    idaapi.autoWait()
    return True
  return False 
Example #6
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def try_mark_as_code(ea):
  if is_code(ea) and not is_code_by_flags(ea):
    idc.MakeCode(ea)
    idaapi.auto_wait()
    return True
  return False 
Example #7
Source File: vxhunter_ida.py    From vxhunter with 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 #8
Source File: loader.py    From idawasm with Apache License 2.0 5 votes vote down vote up
def load_elements_section(section, p):
    '''
    Specialized handler for the ELEMENTS section to mark the offset initializer as code.
    '''
    ppayload = p + idawasm.common.offset_of(section.data, 'payload')
    pentries = ppayload + idawasm.common.offset_of(section.data.payload, 'entries')
    pcur = pentries
    for i, body in enumerate(section.data.payload.entries):
        idc.MakeCode(pcur + idawasm.common.offset_of(body, 'offset'))
        pcur += idawasm.common.size_of(body) 
Example #9
Source File: loader.py    From idawasm with Apache License 2.0 5 votes vote down vote up
def load_data_section(section, p):
    '''
    specialized handler for the DATA section to mark the offset initializer as code.
    '''
    ppayload = p + idawasm.common.offset_of(section.data, 'payload')
    pentries = ppayload + idawasm.common.offset_of(section.data.payload, 'entries')
    pcur = pentries
    for i, body in enumerate(section.data.payload.entries):
        idc.MakeCode(pcur + idawasm.common.offset_of(body, 'offset'))
        pcur += idawasm.common.size_of(body) 
Example #10
Source File: Node.py    From grap with MIT License 4 votes vote down vote up
def __init__(self, ea, info, cs):
        """Initialization function."""
        # Init the node structure
        node_t.__init__(self)

        # Check if it's a code instruction
        try:
            is_c = is_code(get_flags(ea))
        except:
            is_c = isCode(GetFlags(ea))
        if not is_c:
            raise CodeException

        #
        # fill node_t struct
        #

        # NodeInfo
        self.info = NodeInfo()
        inst_elements = []

        try:
            size = create_insn(ea)
            bytes = get_bytes(ea, size)
        except:
            size = MakeCode(ea)
            bytes = GetManyBytes(ea, size)

        (address, size, mnemonic, op_str) = next(cs.disasm_lite(bytes, ea, count=1))
        self.info.opcode = mnemonic

        self.info.inst_str = self.info.opcode + " " + op_str

        splitted = op_str.split(", ")
        self.info.nargs = 0

        if len(splitted) >= 1:
            self.info.arg1 = splitted[0]
            self.info.nargs += 1
            if len(splitted) >= 2:
                self.info.arg2 = splitted[1]
                self.info.nargs += 1
                if len(splitted) >= 3:
                    self.info.arg3 = splitted[2]
                    self.info.nargs += 1

        # No node will be root but this is acceptable for CFGs
        self.info.is_root = False

        self.info.address = ea
        self.info.has_address = True

        # node_t
        self.node_id = self._genid() 
Example #11
Source File: ida_utilities.py    From ida_kernelcache with 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 #12
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def fix_vxworks_idb(load_address, vx_version, symbol_table_start, symbol_table_end):
        current_image_base = idaapi.get_imagebase()
        symbol_interval = 16
        if vx_version == 6:
            symbol_interval = 20
        symbol_table_start += load_address
        symbol_table_end += load_address
        ea = symbol_table_start
        shift_address = load_address - current_image_base
        while shift_address >= 0x70000000:
            idaapi.rebase_program(0x70000000, 0x0008)
            shift_address -= 0x70000000
        idaapi.rebase_program(shift_address, 0x0008)
        while ea < symbol_table_end:
            # for VxWorks 6 unknown symbol format
            if idc.Byte(ea + symbol_table_end - 2) == 3:
                ea += symbol_interval
                continue
            offset = 4
            if idaapi.IDA_SDK_VERSION >= 700:
                idc.create_strlit(idc.Dword(ea + offset), idc.BADADDR)
            else:
                idc.MakeStr(idc.Dword(ea + offset), idc.BADADDR)
            sName = idc.GetString(idc.Dword(ea + offset), -1, idc.ASCSTR_C)
            print("Found %s in symbol table" % sName)
            if sName:
                sName_dst = idc.Dword(ea + offset + 4)
                if vx_version == 6:
                    sName_type = idc.Dword(ea + offset + 12)
                else:
                    sName_type = idc.Dword(ea + offset + 8)
                idc.MakeName(sName_dst, sName)
                if sName_type in need_create_function:
                    # flags = idc.GetFlags(ea)
                    print("Start fix Function %s at %s" % (sName, hex(sName_dst)))
                    idc.MakeCode(sName_dst)  # might not need
                    idc.MakeFunction(sName_dst, idc.BADADDR)
            ea += symbol_interval
        print("Fix function by symbol table finish.")
        print("Start IDA auto analysis, depending on the size of the firmware this might take a few minutes.")
        idaapi.autoWait() 
Example #13
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def load_symbols(self, file_data, is_big_endian=True):
        symbol_list = []
        if is_big_endian:
            unpack_format = '>I'
        else:
            unpack_format = '<I'

        symbol_count = struct.unpack(unpack_format, file_data[4:8])[0]
        print("symbol_count: %s" % symbol_count)
        symbol_offset = 8
        string_table_offset = 8 + 8 * symbol_count
        print("string_table_offset: %s" % string_table_offset)
        # get symbols
        for i in range(symbol_count):
            offset = i * 8
            symbol_data = file_data[symbol_offset + offset:symbol_offset + offset + 8]
            flag = ord(symbol_data[0])
            string_offset = struct.unpack(unpack_format, '\x00' + symbol_data[1:4])[0]
            string_offset += string_table_offset
            print("string_offset: %s" % string_offset)
            symbol_name = ""
            while True:
                if file_data[string_offset] != '\x00':
                    symbol_name += file_data[string_offset]
                    string_offset += 1

                else:
                    break
            print("symbol_name: %s" % symbol_name)
            symbol_address = struct.unpack(unpack_format, symbol_data[-4:])[0]
            symbol_list.append([flag, symbol_name, symbol_address])
            # Find TP-Link device loading address with symbols
            if "wrs_kernel_text_start" in symbol_name:
                load_address = symbol_address
                current_image_base = idaapi.get_imagebase()
                shift_address = load_address - current_image_base
                while shift_address >= 0x70000000:
                    idaapi.rebase_program(0x70000000, 0x0008)
                    shift_address -= 0x70000000
                idaapi.rebase_program(shift_address, 0x0008)

        # load symbols
        for symbol_data in symbol_list:
            flag, symbol_name, symbol_address = symbol_data
            idc.MakeName(symbol_address, symbol_name)
            if flag == 0x54:
                if symbol_name:
                    print("Start fix Function %s at %s" % (symbol_name, hex(symbol_address)))
                    idc.MakeCode(symbol_address)  # might not need
                    idc.MakeFunction(symbol_address, idc.BADADDR) 
Example #14
Source File: dsc_fix.py    From dsc_fix with GNU General Public License v3.0 4 votes vote down vote up
def map_shared_bridges(dsc_file, adrfind):
    """ finds branch islands in a given dyld_shared_cache file,
        maps them to IDA's db and extract its addresses """
    dsc_file.seek(0, 2)
    filesize = dsc_file.tell()
    dsc_file.seek(0)
    ACCESS_READ = 1
    a = mmap.mmap(dsc_file.fileno(), length=filesize, access=ACCESS_READ)
    reexp = re.compile("\xcf\xfa\xed\xfe.{340,360}dyld_shared_cache_branch_islands")
    print "[+] scanning dsc for BRANCH ISLANDS"
    # this list will hold all our branch_islands segments
    branch_islands_segments = []
    jmp_to_code = collections.defaultdict(list)
    for ma in reexp.finditer(a):
        print "[+] WRITING BRANCH ISLAND: 0x%08X" % (ma.start())
        fif = FileInFile(dsc_file, ma.start())
        m = MachO_patched(fif)
        if _IN_IDA:
            for seg in m.segments:
                for sec in seg.sections:
                    idc.AddSegEx(sec.addr,
                                 sec.addr + sec.size, 0, 0,
                                 idaapi.saRelPara, idaapi.scPub,
                                 idc.ADDSEG_FILLGAP)
                    name = "branch_islands_%X%s%s" % (ma.start(), seg.segname, sec.sectname)
                    idc.RenameSeg(sec.addr, name)
                    idc.SetSegClass(sec.addr, "CODE")
                    idc.SetSegAddressing(sec.addr, 2)
                    dsc_file.seek(sec.offset)
                    memcpy(sec.addr, dsc_file.read(sec.size))
                    branch_islands_segments.append(sec.addr)
                    # make code
                    codeea = sec.addr
                    print "Going through the code!"
                    while codeea < (sec.addr + sec.size):
                        res = idc.MakeCode(codeea)
                        if not res:
                            print "[!] EA:0x%X ERR while making code" % codeea
                            codeea += 4
                            continue

                        d = idc.GetDisasm(codeea)
                        # if it's a "B     0x4dd13550"
                        if d.startswith("B "):
                            addr = d.split()[1]
                            if addr.startswith("0x"):
                                branchaddr = int(addr, 16)
                                jmp_to_code[branchaddr].append(codeea)
                                #   idc.MakeRptCmt(codeea, "0x%X was taken!" % branchaddr)

                        codeea = idc.FindUnexplored(codeea, idc.SEARCH_DOWN)
    label_and_fix_branch_islands(dsc_file, adrfind, jmp_to_code)