Python idc.get_bytes() Examples

The following are 11 code examples of idc.get_bytes(). 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: disassembler.py    From vt-ida-plugin with Apache License 2.0 5 votes vote down vote up
def get_bytes(start_addr, end_addr):
    return idc.get_bytes(
        start_addr,
        end_addr - start_addr
        ) 
Example #2
Source File: disassembler.py    From vt-ida-plugin with Apache License 2.0 5 votes vote down vote up
def wildcard_instruction(addr):
    """Replaces bytes related to memory addresses with wildcards.

    Args:
      addr: the address of the current instruction to be wildcarded

    Returns:
      String: hex-encoded representation of the bytes obtained at addr where
              all the operands that refers to memmory addresses are wildcarded.
    """

    pattern = ''
    mask = ida_idp.ph_calcrel(addr)
    mask_str = binascii.hexlify(mask).decode('utf-8')

    logging.debug(
        '[VTGREP] Wildcarding: %s',
        idc.generate_disasm_line(addr, 0)
        )

    current_byte = 0
    index_instr = 0
    pattern = ' '

    while current_byte < len(mask_str):
      if mask_str[current_byte] != '0' or mask_str[current_byte+1] != '0':
        pattern += '?? '
      else:
        instr_bytes = idc.get_bytes(addr+index_instr, 1)
        pattern += binascii.hexlify(instr_bytes).decode('utf-8') + ' '
      current_byte += 2
      index_instr += 1

    logging.debug('[VTGREP] Wildcarded: %s', pattern)

    return pattern 
Example #3
Source File: yara_fn.py    From idawilli with Apache License 2.0 5 votes vote down vote up
def get_segment_buffer(segstart):
    '''
    fetch the bytes of the section that starts at the given address.
    if the entire section cannot be accessed, try smaller regions until it works.
    '''
    segend = idaapi.getseg(segstart).end_ea
    buf = None
    segsize = segend - segstart
    while buf is None:
        buf = idc.get_bytes(segstart, segsize)
        if buf is None:
            segsize -= 0x1000
    return buf 
Example #4
Source File: ida_debugger.py    From IDAngr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_bytes(self, addr, size):
        return idc.get_bytes(addr, size) 
Example #5
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getInstructionBytes(self, offset):
        ins = idautils.DecodeInstruction(offset)
        ins_bytes = ida_bytes.get_bytes(offset, ins.size)
        return ins_bytes 
Example #6
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBinary(self):
        result = b""
        segment = ida_segment.get_first_seg()
        while segment:
            result += ida_bytes.get_bytes(segment.start_ea, segment.end_ea - segment.start_ea)
            segment = ida_segment.get_next_seg(segment.end_ea)
        return result 
Example #7
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getInstructionBytes(self, offset):
        ins = idautils.DecodeInstruction(offset)
        ins_bytes = idc.get_bytes(offset, ins.size)
        return ins_bytes 
Example #8
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBinary(self):
        result = b""
        segment_starts = [ea for ea in idautils.Segments()]
        offsets = []
        start_len = 0
        for start in segment_starts:
            end = idc.SegEnd(start)
            result += idc.get_bytes(start, end - start)
            offsets.append((start, start_len, len(result)))
            start_len = len(result)
        return result 
Example #9
Source File: disassembler.py    From vt-ida-plugin with Apache License 2.0 4 votes vote down vote up
def get_opcodes(addr, strict):
    """Get current bytes of the instruction pointed at addr.

    Args:
      addr: address of the current instruction
      strict: be more restrictive when applying wildcards (True) or not (False)

    Returns:
      String: hex-encoded representation of the bytes obtained at addr
    """

    if strict:
      offsets_types = {idaapi.o_far, idaapi.o_mem, idaapi.o_imm}
    else:
      offsets_types = {idaapi.o_far, idaapi.o_mem}

    pattern = ''
    mnem = idautils.DecodeInstruction(addr)

    if mnem is not None:
      op1_type = mnem.Op1.type
      op2_type = mnem.Op2.type

      logging.debug(
          '[VTGREP] Instruction: %s  [%d, %d, %d]',
          idc.generate_disasm_line(addr, 0),
          mnem.itype,
          op1_type,
          op2_type
          )

      inst_len = idc.get_item_size(addr)
      drefs = [x for x in idautils.DataRefsFrom(addr)]

      # Checks if any operand constains a memory address
      if (drefs and
          ((op1_type == idaapi.o_imm) or (op2_type == idaapi.o_imm)) or
          op1_type in offsets_types or op2_type in offsets_types):
        pattern = Disassembler.wildcard_instruction(addr)
      # Checks if the instruction is a CALL (near or far) or
      # if it's a JMP (excluding near jumps)
      else:
        if ((mnem.itype == idaapi.NN_call) or
            (mnem.itype == idaapi.NN_jmp and op1_type != idaapi.o_near)):
          pattern = Disassembler.wildcard_instruction(addr)
        # In any other case, concatenate the raw bytes to the current string
        else:
          pattern = binascii.hexlify(idc.get_bytes(addr, inst_len))
          pattern = pattern.decode('utf-8')
      return pattern
    else: return 0 
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: mykutils.py    From flare-ida with Apache License 2.0 4 votes vote down vote up
def _emit_fnbytes(emit_instr_cb, header, footer, indent, fva=None, warn=True):
    """Emit function bytes in a format defined by the callback and
    headers/footers provided.

    Warns if any instruction operands are not consistent with
    position-independent code, in which case the user may need to templatize
    the position-dependent portions.
    """
    fva = fva or idc.here()
    fva = idc.get_func_attr(fva, idc.FUNCATTR_START)
    va_end = idc.get_func_attr(fva, idc.FUNCATTR_END)

    # Operand types observed in position-independent code:
    optypes_position_independent = set([
        ida_ua.o_reg,       # 1: General Register (al,ax,es,ds...)
        ida_ua.o_phrase,    # 3: Base + Index
        ida_ua.o_displ,     # 4: Base + Index + Displacement
        ida_ua.o_imm,       # 5: Immediate
        ida_ua.o_near,      # 7: Immediate Near Address
    ])

    # Notably missing because I want to note and handle these if/as they are
    # encountered:
    # 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

    va = fva
    nm = idc.get_name(fva)
    optypes_found = set()
    s = header.format(name=nm)
    while va not in (va_end, idc.BADADDR):
        size = idc.get_item_size(va)
        the_bytes = idc.get_bytes(va, size)

        for i in range(0, 8):
            optype = idc.get_operand_type(va, i)
            if optype:
                optypes_found.add(optype)

        s += indent + emit_instr_cb(va, the_bytes, size)
        va = idc.next_head(va)
    s += footer

    position_dependent = optypes_found - optypes_position_independent
    if position_dependent:
        msg = ('This code may have position-dependent operands (optype %s)' %
               (', '.join([str(o) for o in position_dependent])))
        if warn:
            Warning(msg)
        else:
            logger.warn(msg)

    return s