Esempio n. 1
0
    def make_function(self, object_version, address):
        #
        # call the architecture dependent plugin  ###########
        #
        self.arch_plugin.make_function_prehook(object_version, address)

        flags = object_version.get_object_flags()
        size = object_version.get_size()
        # create function if not already exist

        current_flags = idc.GetFlags(address)
        # if ea is func
        func = idaapi.get_func(address)
        if not idaapi.isFunc(current_flags) or (func is not None and
                                                (func.startEA != address)):
            logger.debug(
                "MakeFunction at 0x%08X : flags=0x%08X, current_flags=0x%08X" %
                (address, flags, current_flags))

            if func is not None:
                logger.debug(
                    "                                       "
                    "func.startEA[0x%08X]!=address func.endEA[0x%08X]!=(address+size[0x%08X])  "
                    % (func.startEA, func.endEA, size))
            if not idc.MakeFunction(address):
                if not idc.isLoaded(address):
                    logger.error(
                        "Failed at idc.MakeFunction at 0x%08X : data not loaded"
                        % address)
                else:
                    logger.error("Failed at idc.MakeFunction at 0x%08X" %
                                 address)
                    self.clear_function(object_version, address)
                    if not idc.MakeFunction(address):
                        logger.error("Failed at idc.MakeFunction at 0x%08X" %
                                     address)

                        #             idc.MakeUnknown(address, size, DOUNK_SIMPLE)
            if idc.AnalyzeArea(address, address + 1) != 1:
                logger.error("[0x%08X] idc.AnalyzeArea failed" % address)

                #             if(idc.AnalyzeArea(address, address+size) != 1):
                #                 logger.error("[0x%08X] idc.AnalyzeArea failed" % address)
                #             if(address == 0x0000000000411558):
                #                 raise Exception()
        if flags is not None:
            idc.SetFunctionFlags(address, flags)

        self.set_type(object_version, address)

        #
        # call the architecture dependent plugin  ###########
        #
        self.arch_plugin.make_function_posthook(object_version, address)
Esempio n. 2
0
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
Esempio n. 3
0
def force_create_function(loc):
    """
    Similar to create_function above, but a little more hackish (maybe). Makes a lot of assumptions about there
    being defined code, i.e. not obfsucated code. However, won't create a function that does not include the
    desired location, which will need to be fixed at a later date.

    :param loc: Location a function is needed at

    :return: True if function is created, False otherwise
    """
    # Do a couple sanity checks.
    if idaapi.get_func(loc):
        append_debug('There\'s already a function here!')
        return False
    elif idc.isAlign(idc.GetFlags(loc)) or idc.GetMnem(loc) == 'nop' or \
            (idaapi.isData(idc.GetFlags(loc)) and idc.Byte(loc) == 0x90):
        append_debug('Can\'t make a function out of aligns and/or nops!')
        return False

    start = _force_find_start(loc)
    end = _find_force_end(loc)
    if idc.MakeFunction(start, end):
        append_debug('Created a function 0x%X - 0x%X.' % (start, end))
        return True
    else:
        append_debug('Failed to create a function 0x%X - 0x%X.' % (start, end))
        return False
def resolve_unknown_functions():
	proc_name = get_proc_name()
	if proc_name.startswith("mips"):
		prolog_pattern = FUNCTION_PROLOGS.get(proc_name, "BAD ARCH")
	elif proc_name.startswith("ARM"):
		prolog_pattern = FUNCTION_PROLOGS.get(proc_name, "BAD ARCH")
	else:
		# TODO: support another arch
		return

	ea = get_start_ea(idaapi.SEG_CODE)
	if ea == idc.BADADDR:
		ea = idc.FirstSeg()
	cur_seg_end = idc.SegEnd(ea)

	while ea != idc.BADADDR:
		if ea < cur_seg_end and idc.GetSegmentAttr(ea, idc.SEGATTR_TYPE) == idaapi.SEG_CODE:
			if idc.GetFunctionFlags(ea) == -1:
				# not function
				raw_data_hex = read_addr(ea)
				if re.match(prolog_pattern, raw_data_hex.decode('hex')):
					idc.MakeFunction(ea)
			ea = ea + 4
		else:
			ea = idc.NextSeg(ea)
			cur_seg_end = idc.SegEnd(ea)
Esempio n. 5
0
    def codeify(self, ea=idc.BADADDR):
        func_count = 0
        code_count = 0

        if ea == idc.BADADDR:
            ea = self.get_start_ea(self.CODE)
            if ea == idc.BADADDR:
                ea = idc.FirstSeg()

        self.say("\nLooking for undefined code starting at: %s:0x%X" %
                 (idc.SegName(ea), ea))

        while ea != idc.BADADDR:
            try:
                if idc.GetSegmentAttr(ea, idc.SEGATTR_TYPE) == self.CODE:
                    if idc.GetFunctionName(ea) != '':
                        ea = idc.FindFuncEnd(ea)
                        continue
                    else:
                        if idc.MakeFunction(ea):
                            func_count += 1
                        elif idc.MakeCode(ea):
                            code_count += 1
            except:
                pass

            ea = idc.NextAddr(ea)

        self.say("Created %d new functions and %d new code blocks\n" %
                 (func_count, code_count))
def define_functions():
    native_rvas = [
        0x1930,
        0x3A90,
        0x44b0,
    ]
    native_rvas = [(0x400000 + x) for x in native_rvas]

    for ea in native_rvas:

        if ea == 0x401930:
            # undefine and force convert to code as IDA doesn't analyse it at first
            print "Defining fcn GODDAG at 0x%x" % ea
            print "Making", ea, "unknown and defining it to code..."
            idc.MakeUnkn(ea, 1)
            idc.MakeCode(ea)
            idc.MakeUnkn(ea + 8, 1)
            idc.MakeCode(ea + 7)
        else:
            if ea == 0x403A90:
                fcn_name = "NativeGRUNDTAL_NORRVIKEN"
                print "Defining fcn %s at 0x%x" % (fcn_name, ea)
            elif ea == 0x4044B0:
                fcn_name = "FYRKANTIGImpl"
                print "Defining fcn %s at 0x%x" % (fcn_name, ea)

            idc.MakeFunction(ea)
            idc.MakeNameEx(ea, fcn_name, idc.SN_NOWARN)
Esempio n. 7
0
    def codeify(self, ea=idc.BADADDR):
        func_count = 0
        code_count = 0

        if ea == idc.BADADDR:
            ea = self.get_start_ea(self.CODE)
            if ea == idc.BADADDR:
                ea = idc.FirstSeg()

        print "\nLooking for undefined code starting at: %s:0x%X" % (
            idc.SegName(ea), ea)

        if self.get_start_ea(self.DATA) == idc.BADADDR:
            print "WARNING: No data segments defined! I don't know where the code segment ends and the data segment begins."

        while ea != idc.BADADDR:
            try:
                if idc.GetSegmentAttr(ea, idc.SEGATTR_TYPE) == self.CODE:
                    if idc.GetFunctionName(ea) != '':
                        ea = idc.FindFuncEnd(ea)
                        continue
                    else:
                        if idc.MakeFunction(ea):
                            func_count += 1
                        elif idc.MakeCode(ea):
                            code_count += 1
            except:
                pass

            ea = idc.NextAddr(ea)

        print "Created %d new functions and %d new code blocks\n" % (
            func_count, code_count)
    def check_address(address):
        # Checks if given address contains virtual table. Returns True if more than 2 function pointers found
        # Also if table's addresses point to code in executable section, than tries to make functions at that addresses
        if helper.is_code_ea(address):
            return False

        if not idaapi.get_name(address):
            return False

        functions_count = 0
        while True:
            func_address = helper.get_ptr(address)
            # print "[INFO] Address 0x{0:08X}".format(func_address)
            if helper.is_code_ea(func_address) or helper.is_imported_ea(
                    func_address):
                functions_count += 1
                address += const.EA_SIZE
            else:
                segment = idaapi.getseg(func_address)
                if segment and segment.perm & idaapi.SEGPERM_EXEC:
                    idc.MakeUnknown(func_address, 1, idaapi.DOUNK_SIMPLE)
                    if idc.MakeFunction(func_address):
                        functions_count += 1
                        address += const.EA_SIZE
                        continue
                break
            idaapi.autoWait()
        return functions_count
Esempio n. 9
0
def ida_make_function(location):
    '''
    Description:
        From the first non-function byte, attempt to make a function.

    Input:
        location - The EA at which IDA should attempt to make a function.

    Output:
        True if it succeeded, False otherwise.
    '''
    function_start = location
    ea = location
    while not (idaapi.get_func(ea) or idc.isAlign(idc.GetFlags(ea))):
        function_start = ea
        ea = idc.PrevHead(ea)
    function_start = _un_nop(function_start, idc.NextHead)

    if idc.MakeFunction(function_start):
        last_mnem = idc.GetMnem(
            idc.ItemHead(idaapi.get_func(function_start).endEA - 1))
        if 'ret' not in last_mnem and 'jmp' not in last_mnem:
            idc.DelFunction(function_start)
            append_debug(
                'Created a function at 0x%X, but there wasn\'t a jmp or ret at the end.'
                % function_start)
            return False
        else:
            append_debug('Created a function 0x%X.' % function_start)
            return True
    else:
        return False
Esempio n. 10
0
def ida_main():
    import idc

    filepath = idc.AskFile(0, "*.map", "Load a Dolphin emulator symbol map")
    if filepath is None:
        return
    symbol_map = load_dolphin_map(filepath)

    for symbol in symbol_map:
        addr = int(symbol.vaddr, 16)
        size = int(symbol.size, 16)
        idc.MakeUnknown(addr, size, 0)
        if symbol.section in [".init", ".text"]:
            idc.MakeCode(addr)
            success = idc.MakeFunction(
                addr, idc.BADADDR if not size else (addr + size))
        else:
            success = idc.MakeData(addr, idc.FF_BYTE, size, 0)

        if not success:
            idc.Message("Can't apply properties for symbol:"
                        " {0.vaddr} - {0.name}\n".format(symbol))

        flags = idc.SN_NOCHECK | idc.SN_PUBLIC
        if symbol.name.startswith("zz_"):
            flags |= idc.SN_AUTO | idc.SN_WEAK
        else:
            flags |= idc.SN_NON_AUTO
        idc.MakeNameEx(addr, symbol.name, flags)
def do_rename(line):
	presplitline = line.split("|") #use : for joker, | for jtool2 (joker has been deprecated per the forums
	address = presplitline[0]
	newName = presplitline[1].replace("\r", "").replace("\n", "")
	address = int(address,16) #16 = base
	#print "%s %s" % (address,newName)
	idc.MakeName(address, newName)
	idc.MakeFunction(address)
Esempio n. 12
0
def findUnidentifiedFunctions():
    # just get all not-function code and convert it to functions
    next = idaapi.cvar.inf.minEA
    while next != idaapi.BADADDR:
        next = idaapi.find_not_func(next, SEARCH_DOWN)
        flags = idaapi.getFlags(next)
        if idaapi.isCode(flags):
            idc.MakeFunction(next)
def make_func(func, name):
    t_reg = func & 1  # 0 = ARM, 1 = THUMB
    func -= t_reg
    for i in range(4):
        idc.SetReg(func + i, "T", t_reg)
    idc.MakeFunction(func)
    if name:
        idc.MakeName(func, name)
Esempio n. 14
0
def define_functions():
    # The function first searches for all user defined functions, reads
    # the opcodes and searches for that opcodes in the rest of the file.
    #
    # You can extend this by adding more disassembled instructions that
    # make you believe are function prologues.
    #
    # Obviously not any PUSH is a function start, this is only a filter
    # against erroneously defined functions. So if you define a function
    # that starts with other instruction (and you think there could be
    # other functions that start with that instruction), just add it here.
    prologues = ["STMFD", "push", "PUSH", "mov", "MOV"]

    print "Finding all signatures"
    #ea= 0
    ea = 0x11800000
    #ea = 0x10000000

    opcodes = set()
    if idc.SegStart(ea) == 0xFFFFFFFF:
        print "Wrong segment address set!"
        return

    for funcea in idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea)):
        # Get the opcode
        start_opcode = idc.Dword(funcea)

        # Get the disassembled text
        dis_text = idc.GetDisasm(funcea)
        we_like_it = False

        # Filter possible errors on manually defined functions
        for prologue in prologues:
            if prologue in dis_text:
                we_like_it = True

        # If it passes the filter, add the opcode to the search list.
        if we_like_it:
            opcodes.add(start_opcode)

    print "# different opcodes: %x" % (len(opcodes))
    while len(opcodes) > 0:
        # Search for this opcode in the rest of the file
        opcode_bin = opcodes.pop()
        opcode_str = " ".join(
            x.encode("hex") for x in struct.pack("<L", opcode_bin))
        print "Searching for " + opcode_str
        matches = find_all(opcode_str)
        for matchea in matches:
            # If the opcode is found in a non-function
            if not idc.GetFunctionName(matchea):
                # Try to make code and function
                print "Function at " + hex(matchea)
                idc.MakeCode(matchea)
                idc.MakeFunction(matchea)

    print "We're done!"
Esempio n. 15
0
 def threads(self):
     for thread in self["mem_areas"][0]['threads']: 
         fname = idc.GetFunctionName(thread["tfunc"])
         if len(fname) == 0:
             if idc.MakeFunction(thread["tfunc"]) == 0:
                 fname = "0x%x" % thread["tfunc"]
             else:
                 fname = idc.GetFunctionName(thread["tfunc"])
         yield fname, thread["tfunc"], thread["tid"]
Esempio n. 16
0
def do_rename(line):
    splitted = line.split()
    strname = splitted[0]
    straddr = splitted[1].replace("\r", "").replace("\n", "")

    eaaddr = int(straddr, 16)
    idc.MakeCode(eaaddr)
    idc.MakeFunction(eaaddr)
    idc.MakeNameEx(int(straddr, 16), strname, idc.SN_NOWARN)
Esempio n. 17
0
def parse_pclntable(module_data):
    pPcHeader = module_data.pPcHeader
    pc_header = parse_pc_header(pMem=pPcHeader)
    ptrSize = pc_header.ptrSize
    numberOfFuncs = pc_header.nFunc

    log._info("Number of Functions : %d" % numberOfFuncs)

    pclntable_start = module_data.pPclnTable
    cur_addr = pclntable_start
    for idx in range(numberOfFuncs):
        cur_addr = pclntable_start + (2 * ptrSize) * idx
        func_rva = common.mem_read_integer(addr=cur_addr, read_size=ptrSize)
        _func_structure_offset = common.mem_read_integer(addr=cur_addr +
                                                         ptrSize,
                                                         read_size=ptrSize)
        _func_addr = pclntable_start + _func_structure_offset

        if not idc.GetFunctionName(func_rva):
            log._info("Unk Func @0x%x" % func_rva)
            idc.MakeUnkn(func_rva, idc.DOUNK_EXPAND)
            idaapi.autoWait()
            idc.MakeCode(func_rva)
            idaapi.autoWait()
            if idc.MakeFunction(func_rva):
                idaapi.autoWait()
                log._info("Create Func @0x%x" % func_rva)

        _func = parse__func(pMem=_func_addr)
        #args=_func.args
        #func_id=_func.args

        func_name_addr = module_data.pFuncNameTable + _func.nameoff
        func_name = idc.GetString(func_name_addr)
        if func_name:
            clean_func_name = utils.clean_function_name(func_name)
            log._info("@0x%x Name : [%s]" % (func_rva, func_name))
            idc.MakeComm(func_rva, "@0x" + str(hex(func_rva)) + " entry")
            idaapi.autoWait()

            if idc.MakeStr(func_name_addr,
                           func_name_addr + len(func_name) + 1):
                idaapi.autoWait()
            else:
                log._error("@0x%x Name : [%s] Failed..." %
                           (func_rva, func_name))

        _func_addr = idaapi.get_func(func_rva)
        if _func_addr is not None:
            if idc.MakeNameEx(_func_addr.startEA,
                              func_name,
                              flags=idaapi.SN_FORCE):
                idaapi.autoWait()
                log._info("@0x%x Name : [%s]" % (func_rva, func_name))
            else:
                log._error("@0x%x Name : [%s] Failed..." %
                           (func_rva, func_name))
Esempio n. 18
0
 def makePointedFunctions(self):
     """Modify the code and tell IDA that our code fptrs should point to the beginning of functions."""
     # We want the list in descending function order
     fptrs_couples = list(self._ref_ptrs.items())
     fptrs_couples.sort(key=lambda x: x[0], reverse=True)
     # Now we can iterate it
     for func_ea, code_type in fptrs_couples:
         self._analyzer.setCodeType(func_ea, func_ea + 1, code_type)
         idc.MakeFunction(func_ea)
Esempio n. 19
0
 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)
Esempio n. 20
0
def main():
    base_addr = 0
    ea = 0
    idc.MakeFunction(ea)

    # heuristic
    while (true):
        mnemonic = idc.GetMnem(ea)

        if "LDR" in mnemonic:
            base_str = idc.GetOpnd(ea, 1)
            base_addr = int(base_str.split("=")[1], 16)

            break

        ea += 4

    print("[+] rebasing to address 0x%x" % (base_addr))
    idc.rebase_program(base_addr, idc.MSF_FIXONCE)
    idaapi.autoWait()

    segment_start = base_addr
    segment_end = idc.GetSegmentAttr(segment_start, idc.SEGATTR_END)

    ea = segment_start

    print("[+] searching and defining functions")

    while ea != idc.BADADDR:
        ea = idc.FindBinary(ea, idc.SEARCH_DOWN, "BF A9", 16)

        if ea != idc.BADADDR:
            ea = ea - 2

            if (ea % 4) == 0 and idc.GetFlags(ea) < 0x200:
                # print("[+] defining a function at 0x%x" % (ea))
                idc.MakeFunction(ea)

            ea = ea + 4

    idc.AnalyzeArea(segment_start, segment_end)
    idaapi.autoWait()
Esempio n. 21
0
def init(tests):
    # workaround ida 6.95 function chunks which should really be functions
    for ea in [0x6718f260, 0x671a5250]:
        numrefs = idc.GetFchunkAttr(ea, idc.FUNCATTR_REFQTY)
        if numrefs <= 1:
            continue
        for idx in range(numrefs, 0, -1):
            idc.RemoveFchunk(idc.GetFchunkReferer(ea, idx - 1), ea)
        idc.MakeFunction(ea)
    idc.Wait()
    YaCo.start_tests()
Esempio n. 22
0
def create_function(location, find_start=True):
    '''
    Description:
        Attempts to create a function using IDA's builtin functionality. If that fails build a
        assuming a start instruction of "push ebp", "push esp", "push esi", or "push edi" and an
        end instruction of "retn" (C2 or C3), excluding aligns and nops.

    Input:
        location - An address that should be within a function
        find_start - When False, assume location is the start of the function

    Output:
        True if it made a function, False otherwise.
    '''
    # Do a couple sanity checks.
    if idaapi.get_func(location):
        append_debug('There\'s already a function here! (0x%X)' % location)
        return False
    elif idc.isAlign(idc.GetFlags(location)) or idc.GetMnem(location) == 'nop' or \
            (idaapi.isData(idc.GetFlags(location)) and idc.Byte(location) == 0x90):
        append_debug('Can\'t make a function out of aligns and/or nops!')
        return False

    # Trace up as far as possible and have IDA do its thing.
    if ida_make_function(location):
        return True

    # Attempt to find the function ourselves.
    function_starts = _find_function_start(location) if find_start else [
        location
    ]
    function_ends = _find_function_end(location)

    found_func = None
    if function_ends and function_starts:
        for function_start, function_end in itertools.product(
                function_starts, function_ends):
            if function_start < function_end:
                if idc.MakeFunction(function_start, function_end):
                    append_debug('Created a function 0x%X - 0x%X.' %
                                 (function_start, function_end))
                    found_func = (function_start, function_end)
                    break  # Don't return here in case we have to split it yet.
                else:
                    append_debug(
                        'Tried to create a function 0x%X - 0x%X, but IDA wouldn\'t do it.'
                        % (function_start, function_end))

    if found_func:
        split_funcs(*found_func)
        return True

    append_debug('Failed to find function based on location 0x%X.' % location)
    return False
Esempio n. 23
0
 def makeFuncsFromPreamble(funcpreamble, startea=idc.FirstSeg(), endea = idaapi.BADADDR):
     """ This method makes functions everywhere that the sequence 'funpreamble' is found.
         NOTE: this method is generally unsafe, because it will attempt to make functions where
         there may be no function.  Use it with caution.
     """
     ea = startea
     i = 0
     while (ea != idaapi.BADADDR and ea < endea):
         ea = idc.FindBinary(ea, SEARCH_DOWN, funcpreamble)
         idc.MakeFunction(ea)
         idc.Wait()
         ea = ea + 1 # idc.FindBinary(ea) returns ea if ea matches, silly
Esempio n. 24
0
    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)
Esempio n. 25
0
def do_rename(l):
    splitted = l.split()
    straddr = splitted[0]
    strname = splitted[1].replace("\r", "").replace("\n", "")

    if straddr.find(":") != -1:  #assuming form segment:offset
        #removing segment, offset should be unique, if it isn't so, we should handle it differently
        straddr = straddr.split(":")[1]

    eaaddr = int(straddr, 16)
    idc.MakeCode(eaaddr)
    idc.MakeFunction(eaaddr)
    idc.MakeNameEx(int(straddr, 16), strname, idc.SN_NOWARN)
Esempio n. 26
0
def rebuild_functions_from_prologues():
    segm = idaapi.get_segm_by_name("__text")
    seg_start = segm.startEA
    seg_end = segm.endEA
    print ("Segment Address : 0x%08x-0x%08x"%(seg_start, seg_end))
    cursor = seg_start
    while cursor < seg_end:
        #print ("Cursor Offset : 0x%08x"%cursor)
        #cursor = idaapi.find_not_func(cursor, 0x1)
        #print Byte(cursor)
        if (Byte(cursor) == 0x55 and Byte(cursor+1) == 0x48 and Byte(cursor+2) == 0x89):
            idc.MakeFunction(cursor)
        cursor += 1
Esempio n. 27
0
def search_functions():
    # For each segment
    for segment in idautils.Segments():
        # For each byte in the address range of the segment
        for byte_addr in range(segment, idc.SegEnd(segment)):
            # Fetch byte
            dis_text = idc.GetDisasm(byte_addr)
            peekahead_dis_text = idc.GetDisasm(byte_addr + 1)
            if "7Ch" in dis_text and "0F2h" in peekahead_dis_text:
                idc.MakeCode(byte_addr)
                idc.MakeFunction(byte_addr)

    print "End of file reached"
Esempio n. 28
0
def split_funcs(startEA, endEA):
    '''
    Description:
        Attempt to split the function we created into a bunch of smaller functions based on
        aligns we find in the middle of the func. If we do successfully split, recurse on
        the remainder of the original function.

    Input:
        startEA - The beginning of the function
        endEA - The end of the function

    Output:
        The IDB is updated with the resulting functions
    '''
    ea = startEA
    while ea < endEA:
        # We found an align so delete the function and try to make 2 new ones in its place.
        if idaapi.isAlign(idc.GetFlags(ea)) and idc.DelFunction(startEA):
            # Make the first function.
            if idc.MakeFunction(startEA, _un_nop(ea, idc.NextHead)):
                # We found an align, now get past them.
                while idaapi.isAlign(idc.GetFlags(ea)):
                    ea += idc.ItemSize(ea)

                # Make the second function and recurse to ensure it doesn't need split too.
                if idc.MakeFunction(_un_nop(ea, idc.PrevHead), endEA):
                    append_debug('Split 0x%X - 0x%X at 0x%X.' %
                                 (startEA, endEA, ea))
                    split_funcs(ea, endEA)
                    return
                else:  # We failed to make the second function, so delete the first.
                    idc.DelFunction(startEA)

            # Splitting failed - rebuild the original function.
            idc.MakeFunction(startEA, endEA)
            append_debug('Almost split 0x%X - 0x%X at 0x%X.' %
                         (startEA, endEA, ea))

        ea += idc.ItemSize(ea)
Esempio n. 29
0
    def make_funcs_from_prof(self, binprof):
        """
		Creates funcs in IDA, base on callgrind func EAs
		from one callgrind profile
		"""

        count = 0

        for i in binprof.keys():
            ea = int(i)
            if idc.MakeFunction(ea, idc.FindFuncEnd(ea)):
                count += 1
        return count
Esempio n. 30
0
def add_to_ida(line):

    splitted = line.split(':')

    if len(splitted) <= 0:
        return # Invalid

    address = splitted[0]
    name = splitted[1]

    address = int(address, 16)

    idc.MakeCode(address)
    idc.MakeFunction(address)
    idc.MakeNameEx(address, name, 0x100)