Python idc.print_insn_mnem() Examples

The following are 17 code examples of idc.print_insn_mnem(). 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 Project: UEFI_RETool   Author: yeggor   File: analyser.py    License: MIT License 6 votes vote down vote up
def _find_est(self, gvar, start, end):
        RAX = 0
        BS_OFFSET = 0x60
        EFI_SYSTEM_TABLE = 'EFI_SYSTEM_TABLE *'
        if self.arch == 'x86':
            BS_OFFSET = 0x3c
        ea = start
        while (ea < end):
            if ((idc.print_insn_mnem(ea) == 'mov')
                    and (idc.get_operand_value(ea, 0) == RAX)
                    and (idc.get_operand_value(ea, 1) == BS_OFFSET)):
                if idc.SetType(gvar, EFI_SYSTEM_TABLE):
                    idc.set_name(gvar, 'gSt_{addr:#x}'.format(addr=gvar))
                    return True
            ea = idc.next_head(ea)
        return False 
Example #2
Source Project: UEFI_RETool   Author: yeggor   File: analyser.py    License: MIT License 6 votes vote down vote up
def get_boot_services(self):
        """found boot services in idb"""
        code = list(idautils.Functions())[0]
        start = idc.get_segm_start(code)
        end = idc.get_segm_end(code)
        ea = start
        while (ea <= end):
            if idc.print_insn_mnem(ea) != 'call':
                ea = idc.next_head(ea)
                continue
            for service_name in self.BOOT_SERVICES_OFFSET:
                # yapf: disable
                if (idc.get_operand_value(ea, 0) == self.BOOT_SERVICES_OFFSET[service_name]):
                    if not self.gBServices[service_name].count(ea):
                        self.gBServices[service_name].append(ea)
            ea = idc.next_head(ea) 
Example #3
Source Project: flare-ida   Author: fireeye   File: code_grafter.py    License: Apache License 2.0 6 votes vote down vote up
def _get_imp_for_register_call(self, va_call, nm=None):
        if idc.print_insn_mnem(va_call) != 'call':
            msg = 'va_call must be the virtual address of a call instruction'
            raise ValueError(msg)

        reg = idc.print_operand(va_call, 0)
        va_mov = mykutils.find_instr(va_call, 'up', 'mov',
                                     [(0, 1, reg), (1, 2, None)])
        if not va_mov:
            return None

        if nm and (nm not in idc.print_operand(va_mov, 1)):
            return None

        va_imp = idc.get_operand_value(va_mov, 1)
        return va_imp 
Example #4
Source Project: flare-ida   Author: fireeye   File: code_grafter.py    License: Apache License 2.0 6 votes vote down vote up
def patch_import(va, target):
    """Patch the import corresponding to the call at @va to point to @target.

    Args:
        va (numbers.Integral): Address of call site for imported function
        target (str): Name or address of new call destination for import entry

    Returns:
        bool: True if successful
    """
    is_call = idc.print_insn_mnem(va) == 'call'

    if is_call:
        opno = 0
    else:
        logger.warn('Not a call instruction at %s' % (phex(va)))
        return False

    if isinstance(target, basestring):
        target = idc.get_name_ea_simple(target)

    patch_pointer_width(idc.get_operand_value(va, opno), target)

    return True 
Example #5
Source Project: idawilli   Author: williballenthin   File: yara_fn.py    License: Apache License 2.0 5 votes vote down vote up
def is_jump(va):
    '''
    return True if the instruction at the given address appears to be a jump.
    '''
    return idc.print_insn_mnem(va).startswith('j') 
Example #6
Source Project: Virtuailor   Author: 0xgalz   File: Main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_bp_to_virtual_calls(cur_addr, end):
    while cur_addr < end:
        if cur_addr == idc.BADADDR:
            break
        elif idc.print_insn_mnem(cur_addr) == 'call' or idc.print_insn_mnem(cur_addr) == 'BLR':
            if True in [idc.print_operand(cur_addr, 0).find(reg) != -1 for reg in REGISTERS]:  # idc.GetOpnd(cur_addr, 0) in REGISTERS:
                cond, bp_address = vtableAddress.write_vtable2file(cur_addr)
                if cond != '':
                    bp_vtable = AddBP.add(bp_address, cond)
        cur_addr = idc.next_head(cur_addr) 
Example #7
Source Project: UEFI_RETool   Author: yeggor   File: analyser.py    License: MIT License 5 votes vote down vote up
def get_protocols(self):
        """found UEFI protocols information in idb"""
        for service_name in self.gBServices:
            for address in self.gBServices[service_name]:
                ea, found = address, False
                if self.arch == 'x86':
                    for _ in range(1, 25):
                        ea = idc.prev_head(ea)
                        if (idc.get_operand_value(ea, 0) > self.base
                                and idc.print_insn_mnem(ea) == 'push'):
                            found = True
                            break
                if self.arch == 'x64':
                    for _ in range(1, 16):
                        ea = idc.prev_head(ea)
                        if (idc.get_operand_value(ea, 1) > self.base
                                and idc.print_insn_mnem(ea) == 'lea'):
                            found = True
                            break
                if not found:
                    continue
                for xref in idautils.DataRefsFrom(ea):
                    if idc.print_insn_mnem(xref):
                        continue
                    if not check_guid(xref):
                        continue
                    cur_guid = get_guid(xref)
                    record = {
                        'address': xref,
                        'service': service_name,
                        'guid': cur_guid,
                    }
                    if not self.Protocols['all'].count(record):
                        self.Protocols['all'].append(record) 
Example #8
Source Project: ida-minsc   Author: arizvisa   File: quicktime.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nextMnemonic(ea, mnem, maxaddr=0xc0*0x1000000):
    res = idc.print_insn_mnem(ea)
    if res == "": return idc.BADADDR
    if res == mnem: return ea
    return nextMnemonic( idc.next_head(ea, maxaddr), mnem, maxaddr ) 
Example #9
Source Project: ida-minsc   Author: arizvisa   File: quicktime.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prevMnemonic(ea, mnem, minaddr=0):
    res = idc.print_insn_mnem(ea)
    #print "%x -> %s"% (ea, res)
    if res == "": return idc.BADADDR
    if res == mnem: return ea
    return prevMnemonic( idc.prev_head(ea, minaddr), mnem, minaddr ) 
Example #10
Source Project: ida-minsc   Author: arizvisa   File: quicktime.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getDispatchCode(ea):
    # get dispatch code out of an instruction
    first, second = (idc.print_operand(ea, 0), idc.get_operand_value(ea, 1))
    if first == 'eax':
        return second
    raise ValueError("Search resulted in address %08x, but instruction '%s' does fulfill requested constraints"% (ea, idc.print_insn_mnem(ea))) 
Example #11
Source Project: ida-minsc   Author: arizvisa   File: quicktime.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def FindLastAssignment(ea, register):
    start,end = database.guessrange(ea)
    while ea > start:
        ea = database.prev(ea)
        m = idc.print_insn_mnem(ea)
        r = idc.print_operand(ea, 0)

        if m == 'mov' and r == register:
            return ea
        continue

    raise ValueError('FindLastAssignment(0x%x, %s) Found no matches'% (ea, register)) 
Example #12
Source Project: flare-ida   Author: fireeye   File: mykutils.py    License: Apache License 2.0 5 votes vote down vote up
def for_each_call_to(callback, va=None):
    """For each xref to va that is a call, pass xref va to callback.

    Falls back to highlighted identifier or current location if va is
    unspecified.
    """
    if not va:
        v = ida_kernwin.get_current_viewer()
        hi = ida_kernwin.get_highlight(v)
        if hi and hi[1]:
            nm = hi[0]
            va = idc.get_name_ea_simple(nm)
            if va >= idaapi.cvar.inf.maxEA:
                va = None

    va = va or idc.here()

    # Obtain and de-duplicate addresses of xrefs that are calls
    callsites = set([x.frm for x in idautils.XrefsTo(va)
                     if idc.print_insn_mnem(x.frm) == 'call'])
    for va in callsites:
        callback(va)


# Instruction operand specification.
#
# Operand types are from ida_ua.o_* e.g. o_reg, o_mem.
# >>> {x: getattr(ida_ua, x) for x in dir(ida_ua) if x.startswith('o_')}
#
# Quick ref:
#   ida_ua.o_reg ==      1: "General Register (al,ax,es,ds...)",
#   ida_ua.o_mem ==      2: "Memory Reference",
#   ida_ua.o_phrase ==   3: "Base + Index",
#   ida_ua.o_displ ==    4: "Base + Index + Displacement",
#   ida_ua.o_imm ==      5: "Immediate",
#   ida_ua.o_far ==      6: "Immediate Far Address",
#   ida_ua.o_near ==     7: "Immediate Near Address",
#   ida_ua.o_idpspec0 == 8: "FPP register",
#   ida_ua.o_idpspec1 == 9: "386 control register",
#   ida_ua.o_idpspec2 == 10: "386 debug register",
#   ida_ua.o_idpspec3 == 11: "386 trace register", 
Example #13
Source Project: flare-ida   Author: fireeye   File: mykutils.py    License: Apache License 2.0 5 votes vote down vote up
def is_conformant_instr(va, mnems, op_specs):
    """Check if instruction at @va conforms to operand specifications list.

    Args:
        va (numbers.Integral): Virtual address of instruction to assess.
        mnems (str or iterable of str): Optional instruction mnemonic(s) to
            check for.
        op_specs (iterable of OpSpec): Iterable containing zero or more operand
            specification tuples (operand position, type, and name).

    Returns:
        True if conformant
        False if nonconformant
    """
    if (not mnems) and (not op_specs):
        msg = 'Must specify either a mnemonic or an operand specification list'
        raise ValueError(msg)

    mnem_current = idc.print_insn_mnem(va)
    if mnems:
        if isinstance(mnems, basestring):
            if mnem_current != mnems:
                return False
        else:
            if mnem_current not in mnems:
                return False

    for spec in op_specs:
        if not is_conformant_operand(va, spec):
            return False

    return True 
Example #14
Source Project: Virtuailor   Author: 0xgalz   File: vtableAddress.py    License: GNU General Public License v3.0 4 votes vote down vote up
def get_con2_var_or_num(i_cnt, cur_addr):
    """
    :param i_cnt: the register of the virtual call
    :param cur_addr: the current address in the memory
    :return: "success" string and the address of the vtable's location. if it fails it sends the reason and -1
    """
    start_addr = idc.get_func_attr(cur_addr, idc.FUNCATTR_START)
    virt_call_addr = cur_addr
    cur_addr = idc.prev_head(cur_addr)
    dct_arch = get_arch_dct()
    if dct_arch == -1:
        return 'Wrong Architechture', "-1", cur_addr

    while cur_addr >= start_addr:
        if idc.print_insn_mnem(cur_addr)[:3] == dct_arch["opcode"] and idc.print_operand(cur_addr, 0) == i_cnt:  # TODO lea ?
            opnd2 = idc.print_operand(cur_addr, 1)
            place = opnd2.find(dct_arch["separator"])
            if place != -1:  # if the function is not the first in the vtable
                register = opnd2[opnd2.find('[') + 1: place]
                if opnd2.find('*') == -1:
                    offset = opnd2[place + dct_arch["val_offset"]: opnd2.find(']')]
                else:
                    offset = "*"
                return register, offset, cur_addr
            else:
                offset = "0"
                if opnd2.find(']') != -1:
                    register = opnd2[opnd2.find('[') + 1: opnd2.find(']')]
                else:
                    register = opnd2
                return register, offset, cur_addr
        elif idc.print_insn_mnem(cur_addr)[:4] == "call":
            intr_func_name = idc.print_operand(cur_addr, 0)
            # In case the code has CFG -> ignores the function call before the virtual calls
            if "guard_check_icall_fptr" not in intr_func_name:
                if "nullsub" not in intr_func_name:
                    # intr_func_name = idc.Demangle(intr_func_name, idc.GetLongPrm(idc.INF_SHORT_DN))
                    print("Warning! At address 0x%08x: The vtable assignment might be in another function (Maybe %s),"
                          " could not place BP." % (virt_call_addr, intr_func_name))
                cur_addr = start_addr
        cur_addr = idc.prev_head(cur_addr)
    return "out of the function", "-1", cur_addr

    return '', 0, cur_addr 
Example #15
Source Project: UEFI_RETool   Author: yeggor   File: analyser.py    License: MIT License 4 votes vote down vote up
def set_types(self):
        """
        handle (EFI_BOOT_SERVICES *) type
        and (EFI_SYSTEM_TABLE *) for x64 images
        """
        RAX = 0
        O_REG = 1
        O_MEM = 2
        EFI_BOOT_SERVICES = 'EFI_BOOT_SERVICES *'
        EFI_SYSTEM_TABLE = 'EFI_SYSTEM_TABLE *'
        empty = True
        for service in self.gBServices:
            for address in self.gBServices[service]:
                ea = address
                num_of_attempts = 10
                for _ in range(num_of_attempts):
                    ea = idc.prev_head(ea)
                    if (idc.print_insn_mnem(ea) == 'mov'
                            and idc.get_operand_type(ea, 1) == O_MEM):
                        if (idc.get_operand_type(ea, 0) == O_REG
                                and idc.get_operand_value(ea, 0) == RAX):
                            gvar = idc.get_operand_value(ea, 1)
                            gvar_type = idc.get_type(gvar)
                            # if (EFI_SYSTEM_TABLE *)
                            if ((gvar_type != 'EFI_SYSTEM_TABLE *')
                                    and (idc.print_operand(
                                        address, 0).find('rax') == 1)):
                                if self._find_est(gvar, ea, address):
                                    # yapf: disable
                                    print('[ {0} ] Type ({type}) successfully applied'.format(
                                            '{addr:#010x}'.format(addr=gvar),
                                            type=EFI_SYSTEM_TABLE))
                                    empty = False
                                    break
                            # otherwise it (EFI_BOOT_SERVICES *)
                            if (gvar_type != 'EFI_BOOT_SERVICES *'
                                    and gvar_type != 'EFI_SYSTEM_TABLE *'):
                                if idc.SetType(gvar, EFI_BOOT_SERVICES):
                                    empty = False
                                    idc.set_name(
                                        gvar,
                                        'gBs_{addr:#x}'.format(addr=gvar))
                                    # yapf: disable
                                    print('[ {0} ] Type ({type}) successfully applied'.format(
                                            '{addr:#010x}'.format(addr=gvar),
                                            type=EFI_BOOT_SERVICES))
                            break
        if empty:
            print(' * list is empty') 
Example #16
Source Project: ps4_module_loader   Author: SocraticBliss   File: ps4_module.py    License: GNU General Public License v3.0 4 votes vote down vote up
def resolve(self, alphabet, nids, symbols, libraries):
    
        if self.INFO > Relocation.R_X86_64_ORBIS_GOTPCREL_LOAD:
            self.INDEX = self.INFO >> 32
            self.INFO &= 0xFF
            symbol = next(value for key, value in enumerate(symbols) if key + 2 == self.INDEX)[1]
        
        # Library
        try:
            lid1 = alphabet[symbol[12:13]]
            
            # [base64]#
            if symbol[13:14] == '#':
                library = libraries[lid1]
            
            # [base64][base64]#
            elif symbol[14:15] == '#':
                lid2 = alphabet[symbol[13:14]]
                library = libraries[lid1 + lid2]
            
            else:
                raise
        
        # Not a NID
        except:
            library = ''
        
        # Function Name (Offset) == Symbol Value + AddEnd (S + A)
        # Library Name  (Offset) == Symbol Value (S)
        real = idc.get_qword(self.OFFSET)
        idc.add_func(real)
        
        # Hacky way to determine if this is the real function...
        real -= 0x6 if idc.print_insn_mnem(real) == 'push' else 0x0
        
        # Resolve the NID...
        idc.set_cmt(real, 'NID: ' + symbol, False)
        function = nids.get(symbol[:11], symbol)
        
        # Rename the Jump Function...
        idc.set_name(self.OFFSET, '__imp_' + function, SN_NOCHECK | SN_NOWARN | SN_FORCE)
        
        # Rename the Real Function...
        idc.set_name(real, function, SN_NOCHECK | SN_NOWARN | SN_FORCE)
        
        try:
            import_node = idaapi.netnode(library, 0, True)
            import_node.supset(ea2node(real), function)
        
            # Requires customized loader.i / ida_loader.py(d)
            idaapi.import_module(library, None, import_node.index(), None, 'linux')
        
        except:
            pass
        
        return self.type() 
Example #17
Source Project: flare-ida   Author: fireeye   File: code_grafter.py    License: Apache License 2.0 4 votes vote down vote up
def patch_call(va, new_nm):
    """Patch the call at @va to target @new_nm.

    Args:
        va (numbers.Integral): Address of the call site
        new_nm (str): Name of the new call destination

    Returns:
        bool: True if successful
    """
    is_call = idc.print_insn_mnem(va) == 'call'

    if is_call:
        opno = 0
        new_asm = 'call %s' % (new_nm)
    else:
        logger.warn('Not a call instruction at %s' % (phex(va)))
        return False

    # Already done?
    if idc.print_operand(va, opno) == new_nm:
        return True

    ok, code = idautils.Assemble(va, new_asm)

    if not ok:
        logger.warn('Failed assembling %s: %s' % (phex(va), new_asm))
        return False

    orig_opcode_len = idc.get_item_size(va)
    new_code_len = len(code)

    if orig_opcode_len < new_code_len:
        logger.warn('Not enough room or wrong opcode type to patch %s: %s' %
                    (phex(va), new_asm))
        return False

    # If we actually have too much room, then add filler
    if orig_opcode_len > new_code_len:
        delta = orig_opcode_len - new_code_len
        code += '\x90' * delta

    idaapi.patch_bytes(va, code)

    return True