Skip to content

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

# count functions
log( 'count %dn' % 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:
    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:

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.



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 []
        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())]
4 People found this is helpful