Search code examples
pythonreverse-engineeringida

Convert instructions to op code bytes in python script for IDA Pro


I need to convert into op code bytes the instructions that I have disassembled but I can't find a function that lets me do it, I've tried idc.get_bytes but it doesn't seem to work.

This is my python script:

import sys
import idc
import idautils

f = open(idc.ARGV[1], 'w') if len(idc.ARGV) > 1 else sys.stdout
log = f.write

# log current file path
log(idc.get_input_file_path() + '\n')

# wait for auto-analysis to complete
idc.auto_wait()

# count functions
log( 'count %d\n' % len(list(idautils.Functions())) )

for func in idautils.Functions():
    flags = idc.get_func_attr(func, FUNCATTR_FLAGS)
    if flags & FUNC_LIB or flags & FUNC_THUNK:
        continue
    dism_addr = list(idautils.FuncItems(func))
    for line in dism_addr:
        #log(idc.print_insn_mnem(line) + '\n' )
        disass = idc.generate_disasm_line(line, 0)
        log(disass + '\n' )

# if logging to a file, close it and exit IDA Pro
if f != sys.stdout:
    f.close()
    idc.qexit(0)

I'm using this script with the batch mode of IDA Pro 7.7sp1, can you suggest me a method to do it? Thank you in advance.


Solution

  • So, something like this?

    def GetFuncHeads(funcea=None):
        """
        Get all heads in a function
    
        @param funcea: any address in the function
        """
        func = ida_funcs.get_func(funcea)
        if not func:
            return []
        else:
            funcea = func.start_ea
    
        ea = funcea
    
        heads = []
        for start, end in idautils.Chunks(funcea):
            heads.extend([head for head in idautils.Heads(start, end)])
    
        return heads
    
    def GetInsnLen(ea):
        insn = ida_ua.insn_t()
        inslen = ida_ua.decode_insn(insn, ea)
        if inslen:
            return inslen
        return 0
    
    opcodes = [idc.get_bytes(ea, GetInsnLen(ea)) for ea in GetFuncHeads(here())]