Python源码示例:idaapi.getseg()

示例1
def seg_by_addr(self, addr):
        ida_seg = idaapi.getseg(addr)
        name = "<no name>"
        if ida_seg is not None:
            name = ida_seg.name
        if self.vmmap is None:
            self._get_vmmap()
        for start, end, perms, n in self.vmmap:
            if addr >= start and addr < end:
                if n == "": n = name
                return self.angrdbg_mod.Segment(n, start, end, perms)
        # fallback on ida segs
        perms = 0
        perms |= SEG_PROT_R if ida_seg.perm & idaapi.SEGPERM_READ else 0
        perms |= SEG_PROT_W if ida_seg.perm & idaapi.SEGPERM_WRITE else 0
        perms |= SEG_PROT_X if ida_seg.perm & idaapi.SEGPERM_EXEC else 0
        return self.angrdbg_mod.Segment(ida_seg.name, ida_seg.start_ea, ida_seg.end_ea, perms) 
示例2
def print_section_list():
    for s in idautils.Segments():
        seg = idaapi.getseg(s)
        print("%s" % idc.SegName(s))
        print(" - start address: 0x%x" % seg.startEA)
        print(" - sclass: 0x%x" % seg.sclass)
        print(" - orgbase: 0x%x" % seg.orgbase)
        print(" - flags: 0x%x" % seg.flags)
        print(" - align: 0x%x" % seg.align)
        print(" - comb: 0x%x" % seg.comb)
        print(" - perm: 0x%x" % seg.perm)
        print(" - bitness: 0x%x" % seg.bitness)
        print(" - sel: 0x%x" % seg.sel)
        # print(' - defsr: 0x%x' % seg.defsr)
        print(" - type: 0x%x" % seg.type)
        print(" - color: 0x%x" % seg.color) 
示例3
def _Assemble(ea, line):
    """
    Please refer to Assemble() - INTERNAL USE ONLY
    """
    if type(line) == types.StringType:
        lines = [line]
    else:
        lines = line
    ret = []
    for line in lines:
        seg = idaapi.getseg(ea)
        if not seg:
            return (False, "No segment at ea")
        ip  = ea - (idaapi.ask_selector(seg.sel) << 4)
        buf = idaapi.AssembleLine(ea, seg.sel, ip, seg.bitness, line)
        if not buf:
            return (False, "Assembler failed: " + line)
        ea += len(buf)
        ret.append(buf)

    if len(ret) == 1:
        ret = ret[0]
    return (True, ret) 
示例4
def get_offset_name(ea):
    # Try and get the function name
    try:
        func = get_func(ea)
        name = idaapi.get_ea_name(func.start_ea)
        name = demangle(name, 0x60) # MNG_NOTYPE | MNG_NORETTYPE
        if name:
            offset = ea - func.start_ea
            if offset:
                return '{}+{:X}'.format(name, offset)
            return name
    except exceptions.SarkNoFunction:
        pass

    # If that failed, use the segment name instead.
    segment = idaapi.getseg(ea)
    name = idaapi.get_segm_name(segment)
    offset_format = '{{:0{}X}}'.format(get_native_size() * 2)
    ea_text = offset_format.format(ea)
    if name:
        return '{}:{}'.format(name, ea_text)

    # Nothing found, simply return the address
    return ea_text 
示例5
def is_mapped(ea, size=1, value=True):
    """Check if the given address is mapped.

    Specify a size greater than 1 to check if an address range is mapped.

    Arguments:
        ea: The linear address to check.

    Options:
        size: The number of bytes at ea to check. Default is 1.
        value: Only consider an address mapped if it has a value. For example, the contents of a
            bss section exist but don't have a static value. If value is False, consider such
            addresses as mapped. Default is True.

    Notes:
        This function is currently a hack: It only checks the first and last byte.
    """
    if size < 1:
        raise ValueError('Invalid argument: size={}'.format(size))
    # HACK: We only check the first and last byte, not all the bytes in between.
    if value:
        return idc.isLoaded(ea) and (size == 1 or idc.isLoaded(ea + size - 1))
    else:
        return idaapi.getseg(ea) and (size == 1 or idaapi.getseg(ea + size - 1)) 
示例6
def Code(*args):
    """
    Enumerate code bytes

    @param <range>: see getrange

    @return: list of addresses of code bytes

    Example::

        for ea in Code():
            MakeUnkn(ea, DOUNK_EXPAND)
            Wait()

    Will delete all code in the selected area.


        len(list(MakeUnkn(ea, DOUNK_EXPAND) and Wait() for ea in enumerators.Code(idaapi.getseg(here()))))

    will delete all code in the current segment, and can be pasted in the command area of ida

    """
    (first, last)= getrange(args)

    ea= first
    # explicitly testing first byte, since find_code
    # implicitly sets SEARCH_NEXT flag
    if ea<last and not idaapi.is_code(idaapi.get_full_flags(ea)):
        ea= idaapi.find_code(ea, idaapi.SEARCH_DOWN)
    while ea!=idaapi.BADADDR and ea<last:
        yield ea
        ea= idaapi.find_code(ea, idaapi.SEARCH_DOWN) 
示例7
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 
示例8
def get_segments():
    '''
    fetch the segments in the current executable.
    '''
    for segstart in idautils.Segments():
         segend = idaapi.getseg(segstart).end_ea
         segsize = segend - segstart
         segname = str(idc.SegName(segstart)).rstrip('\x00')
         segbuf = get_segment_buffer(segstart)
         yield Segment(segstart, segend, segname, segbuf) 
示例9
def seg_by_addr(self, addr):
        ida_seg = idaapi.getseg(addr)
        if ida_seg is None:
            return None
        perms = 0
        perms |= SEG_PROT_R if ida_seg.perm & idaapi.SEGPERM_READ else 0
        perms |= SEG_PROT_W if ida_seg.perm & idaapi.SEGPERM_WRITE else 0
        perms |= SEG_PROT_X if ida_seg.perm & idaapi.SEGPERM_EXEC else 0
        return self.angrdbg_mod.Segment(ida_seg.name, ida_seg.start_ea, ida_seg.end_ea, perms) 
示例10
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 and segsize > 0:
        buf = GetManyBytes(segstart, segsize)
        if buf is None:
            segsize -= 0x1000
    return buf 
示例11
def get_segments():
    '''
    fetch the segments in the current executable.
    '''
    for segstart in idautils.Segments():
         segend = idaapi.getseg(segstart).end_ea
         segsize = segend - segstart
         segname = str(SegName(segstart)).rstrip('\x00')
         segbuf = get_segment_buffer(segstart)
         yield Segment(segstart, segend, segname, segbuf) 
示例12
def recover_region(M, region_name, region_ea, region_end_ea, exported_vars):
  """Recover the data and cross-references from a segment. The data of a
  segment is stored verbatim within the protobuf, and accompanied by a
  series of variable and cross-reference entries."""

  seg_name = idc.SegName(region_ea)

  DEBUG("Recovering region {} [{:x}, {:x}) in segment {}".format(
      region_name, region_ea, region_end_ea, seg_name))

  seg = idaapi.getseg(region_ea)

  # An item spans two regions. This may mean that there's a reference into
  # the middle of an item. This happens with strings.
  item_size = idc.ItemSize(region_end_ea - 1)
  if 1 < item_size:
    DEBUG("  ERROR: Segment should probably include {} more bytes".format(
        item_size - 1))

  S = M.segments.add()
  S.ea = region_ea
  S.data = read_bytes_slowly(region_ea, region_end_ea)
  S.read_only = (seg.perm & idaapi.SEGPERM_WRITE) == 0
  S.is_external = is_external_segment_by_flags(region_ea)
  S.is_thread_local = is_tls_segment(region_ea)
  S.name = seg_name.format('utf-8')
  S.is_exported = region_ea in exported_vars

  if region_name != seg_name:
    S.variable_name = region_name.format('utf-8')

  DEBUG_PUSH()
  recover_region_cross_references(M, S, region_ea, region_end_ea)
  recover_region_variables(M, S, region_ea, region_end_ea, exported_vars)
  DEBUG_POP() 
示例13
def recover_region(M, region_name, region_ea, region_end_ea, exported_vars):
  """Recover the data and cross-references from a segment. The data of a
  segment is stored verbatim within the protobuf, and accompanied by a
  series of variable and cross-reference entries."""

  seg_name = idc.get_segm_name(region_ea)

  DEBUG("Recovering region {} [{:x}, {:x}) in segment {}".format(
      region_name, region_ea, region_end_ea, seg_name))

  seg = idaapi.getseg(region_ea)

  # An item spans two regions. This may mean that there's a reference into
  # the middle of an item. This happens with strings.
  item_size = idc.get_item_size(region_end_ea - 1)
  if 1 < item_size:
    DEBUG("  ERROR: Segment should probably include {} more bytes".format(
        item_size - 1))

  S = M.segments.add()
  S.ea = region_ea
  S.data = read_bytes_slowly(region_ea, region_end_ea)
  S.read_only = (seg.perm & idaapi.SEGPERM_WRITE) == 0
  S.is_external = is_external_segment_by_flags(region_ea)
  S.is_thread_local = is_tls_segment(region_ea)
  S.name = seg_name.format('utf-8')
  S.is_exported = region_ea in exported_vars

  if region_name != seg_name:
    S.variable_name = region_name.format('utf-8')

  DEBUG_PUSH()
  recover_region_cross_references(M, S, region_ea, region_end_ea)
  recover_region_variables(M, S, region_ea, region_end_ea, exported_vars)
  DEBUG_POP() 
示例14
def __init__(self, ea=UseCurrentAddress, name=None, index=None, segment_t=None):
        """Wrapper around IDA segments.

        There are 3 ways to get a segment - by name, ea or index. Only use one.

        Args:
            ea - address in the segment
            name - name of the segment
            index - index of the segment
        """
        if sum((ea not in (self.UseCurrentAddress, None), name is not None, index is not None,
                segment_t is not None,)) > 1:
            raise ValueError((
                                 "Expected only one (ea, name, index or segment_t)."
                                 " Got (ea={!r}, name={!r}, index={!r}, segment_t={!r})"
                             ).format(ea,
                                      name,
                                      index,
                                      segment_t))


        elif segment_t is not None:
            seg = segment_t

        elif name is not None:
            seg = idaapi.get_segm_by_name(name)

        elif index is not None:
            seg = idaapi.getnseg(index)

        elif ea == self.UseCurrentAddress:
            seg = idaapi.getseg(idc.here())

        elif ea is None:
            raise ValueError("`None` is not a valid address. To use the current screen ea, "
                             "use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`.")

        else:
            seg = idaapi.getseg(ea)

        self._segment = seg 
示例15
def output_segments(out):
    """Dump binary segmentation."""
    info = idaapi.get_inf_structure()
    size = "r32" if info.is_32bit else "r64"
    out.writelines(('(', info.get_proc_name()[1], ' ', size, ' ('))
    for seg in idautils.Segments():
        out.write("\n({} {} {:d} ({:#x} {:d}))".format(
            get_segm_name(seg),
            "code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
            idaapi.get_fileregion_offset(seg),
            seg, idaapi.getseg(seg).size()))
    out.write("))\n") 
示例16
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).endEA
    buf = None
    segsize = segend - segstart
    while buf is None:
        buf = idc.GetManyBytes(segstart, segsize - 1)
        if buf is None:
            segsize -= 0x1000
    return buf 
示例17
def get_segments():
    """
    fetch the segments in the current executable.
    """
    for segstart in idautils.Segments():
        segend = idaapi.getseg(segstart).endEA
        segsize = segend - segstart
        segname = str(idc.SegName(segstart)).rstrip("\x00")
        segbuf = get_segment_buffer(segstart)
        yield Segment(segstart, segend, segname, segbuf) 
示例18
def by_address(ea):
    '''Return the segment that contains the specified `ea`.'''
    seg = idaapi.getseg(interface.address.within(ea))
    if seg is None:
        raise E.SegmentNotFoundError(u"{:s}.by_address({:#x}) : Unable to locate segment containing the specified address.".format(__name__, ea))
    return seg 
示例19
def segment(cls):
        '''Return the current segment.'''
        ea = cls.address()
        return idaapi.getseg(ea) 
示例20
def analyze (payload):
    for n in xrange (payload.get_number_of_items()):
        ea = payload.get_item(n).ea
        seg = idaapi.getseg(ea)
        if seg and ((seg.perm & idaapi.SEGPERM_EXEC) != 0):
            payload.get_item(n).type = Item.TYPE_CODE 
示例21
def get_stack_segment():
    thread_id = idaapi.get_current_thread()
    tib_ea = get_thread_tib(thread_id)
    if tib_ea:
        offset = m.ptr_size * 2
        stack_limit = m.get_ptr(tib_ea + offset)
        return idaapi.getseg(stack_limit)
    return None 
示例22
def get_value_type(ea):
    addr_type = T_VALUE

    if not idaapi.is_loaded(ea):
        return addr_type

    segm_name = idc.get_segm_name(ea)
    segm = idaapi.getseg(ea)
    flags = idc.get_full_flags(ea)
    is_code = idc.is_code(flags)

    if "stack" in segm_name.lower() or \
    (dbg.stack_segm and dbg.stack_segm.start_ea == segm.start_ea):
        addr_type = T_STACK

    elif "heap" in segm_name.lower():
        addr_type = T_HEAP

    elif segm is not None:
        if not is_code and segm.perm & idaapi.SEGPERM_READ and \
        segm.perm & idaapi.SEGPERM_WRITE and \
        segm.perm & idaapi.SEGPERM_EXEC:
            addr_type = T_RWX

        elif is_code or \
        (segm.perm & idaapi.SEGPERM_READ and segm.perm & idaapi.SEGPERM_EXEC):
            addr_type = T_CODE

        elif segm.perm & idaapi.SEGPERM_READ and \
        segm.perm & idaapi.SEGPERM_WRITE:
            addr_type = T_DATA

        elif segm.perm & idaapi.SEGPERM_READ:
            addr_type = T_RODATA

    return addr_type

# ----------------------------------------------------------------------- 
示例23
def update_content_viewers(self, n=None):
        if n is None:
            n = self.GetLineNo()

        item = self.get_item(n)

        self.dav.clear()
        self.hv.clear()
        self.iv.clear()

        if item is not None:
            if item.type == Item.TYPE_CODE:
                # get disassembly and hex stream
                dis = self.payload.da.get_disasm(item.ea)
                for line in dis:
                    self.dav.add_line(line[0])
                    self.hv.add_line(line[1])

                # get various info
                seg = idaapi.getseg(item.ea)
                if seg:
                    name = idaapi.get_true_segm_name(seg)
                    perm = seg.perm
                    ltype = "ld" if seg.is_loader_segm() else "dbg"
                    ea_start = seg.startEA
                    ea_end = seg.endEA

                    perms = ""
                    perms += "R" if perm & idaapi.SEGPERM_READ != 0 else "."
                    perms += "W" if perm & idaapi.SEGPERM_WRITE != 0 else "."
                    perms += "X" if perm & idaapi.SEGPERM_EXEC != 0 else "."
                    self.iv.add_line("<%s> [%X - %X], %s, [%s]" % (name, ea_start, ea_end, ltype, perms))
            else:
                stype = GetStringType(item.ea)
                if stype is not None:
                    scontent = GetString(item.ea, -1, stype)
                    if scontent != None and len(scontent):
                        self.dav.add_line(idaapi.COLSTR("\"%s\"" % scontent, idaapi.SCOLOR_DSTR))
                        # length = idaapi.get_max_ascii_length(item.ea, stype, idaapi.ALOPT_IGNHEADS)
                        # self.hv.add_line()
                else:
                    scontent = GetString(item.ea, -1, ASCSTR_C)
                    if scontent != None and len(scontent):
                        self.dav.add_line("\"%s\"" % scontent)

        self.dav.update()
        self.hv.update()
        self.iv.update()