Python idc.SegEnd() Examples

The following are 28 code examples for showing how to use idc.SegEnd(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module idc , or try the search function .

Example 1
Project: idasec   Author: RobinDavid   File: configuration_file.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def create_call_map(self, ftype):
        assert_ida_available()
        import idc
        import idautils
        seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()}
        imports = seg_mapping[".idata"] if ftype == PE else seg_mapping['.plt']
        start, stop = seg_mapping[".text"]
        current = start
        while current <= stop:
            inst = current
            if idc.GetMnem(inst) in ["call", "jmp"]:
                value = idc.GetOperandValue(inst, 0)
                name = idc.GetOpnd(inst, 0)
                if imports[0] <= value <= imports[1]:
                    entry = self.config.call_map.add()
                    entry.address = inst
                    entry.name = name
            current = idc.NextHead(current, stop) 
Example 2
Project: ida_kernelcache   Author: bazad   File: offset.py    License: MIT License 6 votes vote down vote up
def initialize_data_offsets():
    """Convert offsets in data segments into offsets in IDA.

    Segment names must be initialized with segments.initialize_segments() first.
    """
    # Normally, for user-space programs, this operation would be dangerous because there's a good
    # chance that a valid userspace address would happen to show up in regular program data that is
    # not actually an address. However, since kernel addresses are numerically much larger, the
    # chance of this happening is much less.
    for seg in idautils.Segments():
        name = idc.SegName(seg)
        if not (name.endswith('__DATA_CONST.__const') or name.endswith('__got')
                or name.endswith('__DATA.__data')):
            continue
        for word, ea in idau.ReadWords(seg, idc.SegEnd(seg), addresses=True):
            if idau.is_mapped(word, value=False):
                idc.OpOff(ea, 0, 0) 
Example 3
Project: ida_kernelcache   Author: bazad   File: segment.py    License: MIT License 6 votes vote down vote up
def _initialize_kext_regions():
    """Get region information for each kext based on iOS 12's __PRELINK_INFO.__kmod_start.

    NOTE: This only accounts for __TEXT_EXEC, not the other segments."""
    kmod_start = idc.SegByBase(idc.SegByName('__PRELINK_INFO.__kmod_start'))
    if kmod_start == idc.BADADDR:
        return
    for kmod in idau.ReadWords(kmod_start, idc.SegEnd(kmod_start)):
        _log(1, 'Found kmod {:x}', kmod)
        segments = list(_macho_segments_and_sections(kmod))
        if len(segments) != 1:
            _log(0, 'Skipping unrecognized kmod {:x}', kmod)
            continue
        segname, segstart, segend, sects = segments[0]
        if segname != '__TEXT_EXEC' or len(sects) != 1:
            _log(0, 'Skipping unrecognized kmod {:x}', kmod)
            continue
        kmod_name = 'kext.{:x}'.format(kmod)
        _log(1, 'Adding module:  {:x} - {:x}  {}', segstart, segend, kmod_name)
        _kext_regions.append((segstart, segend, kmod_name)) 
Example 4
Project: ida_kernelcache   Author: bazad   File: tagged_pointers.py    License: MIT License 6 votes vote down vote up
def tagged_pointer_next(ea, tp, end=None):
    assert ea
    # First try to get the offset to the next link.
    if tp:
        link_offset = tagged_pointer_link(tagged_pointer_tag(tp))
        if link_offset:
            return ea + link_offset
        # Skip the current tagged pointer in preparation for scanning.
        ea += idau.WORD_SIZE
    # We don't have a link. Do a forward scan until we find the next tagged pointer.
    _log(3, 'Scanning for next tagged pointer')
    if end is None:
        end = idc.SegEnd(ea)
    for value, value_ea in idau.ReadWords(ea, end, step=4, addresses=True):
        if is_tagged_pointer(value):
            return value_ea
    # If we didn't find any tagged pointers at all, return None.
    return None 
Example 5
Project: flare-ida   Author: fireeye   File: stackstrings.py    License: Apache License 2.0 6 votes vote down vote up
def getFuncRanges(ea, doAllFuncs):
    if using_ida7api:
        return getFuncRanges_ida7(ea, doAllFuncs)
    if doAllFuncs:
        funcs = []
        funcGen = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
        for i in funcGen:
            funcs.append(i)
        funcRanges = []
        for i in range(len(funcs) - 1):
            funcRanges.append( (funcs[i], funcs[i+1]) )
        funcRanges.append( (funcs[-1], idc.SegEnd(ea)) )
        return funcRanges
    else:
        #just get the range of the current function
        fakeRanges = [( idc.GetFunctionAttr(idc.here(), idc.FUNCATTR_START), idc.GetFunctionAttr(idc.here(), idc.FUNCATTR_END)), ]
        return fakeRanges 
Example 6
Project: flare-ida   Author: fireeye   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def get_segment_end_ea(ea):
    """ Return address where next MSDN info can be written to in added
    segment.

    Argument:
    ea -- effective address within added segment where search starts
    """
    addr = ea
    while idc.GetCommentEx(addr, 0) is not None:
        addr = addr + 1
    if addr > idc.SegEnd(ea):
        g_logger.debug('Address {} out of segment bounds. Expanding segment.'
                       .format(hex(addr)))
        try:
            expand_segment(ea)
        except FailedToExpandSegmentException as e:
            g_logger.warning(e.message)
            raise e
    else:
        return addr 
Example 7
Project: lua_re   Author: feicong   File: luac_proc.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def init_seginfo(self):
        #print("seg len:%d\n" % len(list(idautils.Segments())))
        for seg in idautils.Segments():
            segname = idc.SegName(seg)
            if segname.startswith('func_'):
                self.segstarts[idc.SegStart(seg)] = segname
                self.segends[idc.SegEnd(seg)] = segname
                #print("segname:%s\n" % segname)
                #print("add_func() called ret:%d" % add_func(idc.SegStart(seg), idc.SegEnd(seg))) 
Example 8
Project: idasec   Author: RobinDavid   File: idasec_core.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def update_mapping(self):
        pass
        self.fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1) for x in
                            idautils.Functions()}
        self.seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()} 
Example 9
Project: mcsema   Author: lifting-bits   File: exception.py    License: Apache License 2.0 5 votes vote down vote up
def recover_frame_entries(seg_ea):
  if seg_ea == idc.BADADDR:
    return

  DEBUG("Recover entries from section : {}".format(idc.SegName(seg_ea)))
  ea = idc.SegStart(seg_ea)
  end_ea = idc.SegEnd(seg_ea)
  while ea != idc.BADADDR and ea < end_ea:
    ea = format_entries(ea) 
Example 10
Project: mcsema   Author: lifting-bits   File: get_cfg.py    License: Apache License 2.0 5 votes vote down vote up
def find_default_function_heads():
  """Loop through every function, to discover the heads of all blocks that
  IDA recognizes. This will populate some global sets in `flow.py` that
  will help distinguish block heads."""
  func_heads = set()
  for seg_ea in idautils.Segments():
    seg_type = idc.GetSegmentAttr(seg_ea, idc.SEGATTR_TYPE)
    if seg_type != idc.SEG_CODE:
      continue

    for func_ea in idautils.Functions(seg_ea, idc.SegEnd(seg_ea)):
      if is_code_by_flags(func_ea):
        func_heads.add(func_ea)

  return func_heads 
Example 11
Project: DIE   Author: ynvb   File: BpHandler.py    License: MIT License 5 votes vote down vote up
def setBPs(self):
        """
        Set breakpoints on all CALL and RET instructions in all of the executable sections.
        """
        for seg_ea in idautils.Segments():
            for head in idautils.Heads(seg_ea, idc.SegEnd(seg_ea)):
                if idc.isCode(idc.GetFlags(head)):
                    # Add BP if instruction is a CALL
                    if is_call(head):
                        self.addBP(head) 
Example 12
Project: idsearch   Author: xorpd   File: idb_indexer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def iter_lines():
    """
    Iterate through all line addresses in the IDB
    Yields addresses of all lines.
    """
    for ea in idautils.Segments():
        seg_start = idc.SegStart(ea)
        seg_end = idc.SegEnd(ea)

        cur_addr = seg_start
        while (cur_addr < seg_end) and (cur_addr != idaapi.BADADDR):
            yield cur_addr
            cur_addr = idc.NextHead(cur_addr) 
Example 13
Project: ida_kernelcache   Author: bazad   File: collect_classes.py    License: MIT License 5 votes vote down vote up
def _process_mod_init_func_section_for_metaclasses(segstart, found_metaclass):
    """Process a __mod_init_func section for OSMetaClass information."""
    segend = idc.SegEnd(segstart)
    for func in idau.ReadWords(segstart, segend):
        _process_mod_init_func_for_metaclasses(func, found_metaclass) 
Example 14
Project: ida_kernelcache   Author: bazad   File: collect_classes.py    License: MIT License 5 votes vote down vote up
def _process_const_section_for_vtables(segstart, metaclass_info, found_vtable):
    """Process a __const section to search for virtual method tables."""
    segend = idc.SegEnd(segstart)
    addr = segstart
    while addr < segend:
        possible, length = vtable.vtable_length(addr, segend, scan=True)
        if possible:
            metaclass = _get_vtable_metaclass(addr, metaclass_info)
            if metaclass:
                _log(4, 'Vtable at address {:#x} has metaclass {:#x}', addr, metaclass)
                found_vtable(metaclass, addr, length)
        addr += length * idau.WORD_SIZE 
Example 15
Project: ida_kernelcache   Author: bazad   File: offset.py    License: MIT License 5 votes vote down vote up
def _process_offsets_section(segstart, next_offset):
    """Process all the offsets in a __got section."""
    for offset, ea in idau.ReadWords(segstart, idc.SegEnd(segstart), addresses=True):
        if not offset_name_target(idau.get_ea_name(ea)):
            # This is not a previously named offset.
            if idau.is_mapped(offset, value=False):
                _process_offset(offset, ea, next_offset)
            else:
                _log(-1, 'Offset {:#x} at address {:#x} is unmapped', offset, ea) 
Example 16
Project: ida_kernelcache   Author: bazad   File: stub.py    License: MIT License 5 votes vote down vote up
def _process_stubs_section(segstart, make_thunk, next_stub):
    """Process all the functions in a __stubs section."""
    segend = idc.SegEnd(segstart)
    # We'll go through each address and check if it has a reference. If it does, it is likely a
    # stub. As long as the address doesn't already have a stub name, process it.
    for ea in idau.Addresses(segstart, segend, step=1):
        if idc.isRef(idc.GetFlags(ea)) and not stub_name_target(idau.get_ea_name(ea)):
            _process_possible_stub(ea, make_thunk, next_stub) 
Example 17
Project: ida_kernelcache   Author: bazad   File: tagged_pointers.py    License: MIT License 5 votes vote down vote up
def untag_pointers():
    _log(2, 'Starting tagged pointer conversion')
    for seg in idautils.Segments():
        untag_pointers_in_range(idc.SegStart(seg), idc.SegEnd(seg))
    _log(2, 'Tagged pointer conversion complete') 
Example 18
Project: bap-ida-python   Author: BinaryAnalysisPlatform   File: ida.py    License: MIT License 5 votes vote down vote up
def addresses():
    """Generate all mapped addresses."""
    for s in idautils.Segments():
        ea = idc.SegStart(s)
        while ea < idc.SegEnd(s):
            yield ea
            ea = idaapi.nextaddr(ea) 
Example 19
Project: bap-ida-python   Author: BinaryAnalysisPlatform   File: ida.py    License: MIT License 5 votes vote down vote up
def output_symbols(out):
    """Dump symbols."""
    try:
        from idaapi import get_func_name2 as get_func_name
        # Since get_func_name is deprecated (at least from IDA 6.9)
    except ImportError:
        from idaapi import get_func_name
        # Older versions of IDA don't have get_func_name2
        # so we just use the older name get_func_name

    def func_name_propagate_thunk(ea):
        current_name = get_func_name(ea)
        if current_name[0].isalpha():
            return current_name
        func = idaapi.get_func(ea)
        temp_ptr = idaapi.ea_pointer()
        ea_new = idaapi.BADADDR
        if func.flags & idaapi.FUNC_THUNK == idaapi.FUNC_THUNK:
            ea_new = idaapi.calc_thunk_func_target(func, temp_ptr.cast())
        if ea_new != idaapi.BADADDR:
            ea = ea_new
        propagated_name = get_func_name(ea) or ''  # Ensure it is not `None`
        if len(current_name) > len(propagated_name) > 0:
            return propagated_name
        else:
            return current_name
            # Fallback to non-propagated name for weird times that IDA gives
            #     a 0 length name, or finds a longer import name

    for ea in idautils.Segments():
        fs = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
        for f in fs:
            out.write('("%s" 0x%x 0x%x)\n' % (
                func_name_propagate_thunk(f),
                idc.GetFunctionAttr(f, idc.FUNCATTR_START),
                idc.GetFunctionAttr(f, idc.FUNCATTR_END))) 
Example 20
Project: apiscout   Author: danielplohmann   File: IdaProxy.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getSegEnd(self, ea):
        if idaapi.IDA_SDK_VERSION < 700:
            return idc.SegEnd(ea)
        else:
            return idc.get_segm_end(ea) 
Example 21
Project: smda   Author: danielplohmann   File: IdaInterface.py    License: 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 22
Project: flare-ida   Author: fireeye   File: objc2_xrefs_helper.py    License: Apache License 2.0 5 votes vote down vote up
def find_all_segments(self,segment_names):
        segments={name:None for name in segment_names}
        for seg_va in Segments():
            seg_name=SegName(seg_va)
            if seg_name in segment_names:
                segments[seg_name]=(seg_va,SegEnd(seg_va))
        return segments 
Example 23
Project: flare-ida   Author: fireeye   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def get_end_of_last_segment():
    """ Return the last segment's end address. """
    last_ea = 0
    for segment in idautils.Segments():
        if idc.SegEnd(segment) > last_ea:
            last_ea = idc.SegEnd(segment)
    return last_ea 
Example 24
Project: flare-ida   Author: fireeye   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def expand_segment(ea):
    """ Expand last segment so it can hold more MSDN argument information.

    Argument:
    ea -- effective address within last segment
    """
    start = idc.SegStart(ea)
    end = idc.SegEnd(ea)
    if end != get_end_of_last_segment():
        raise FailedToExpandSegmentException('Can only expand last segment.')
    if start == idaapi.BADADDR or end == idaapi.BADADDR:
        raise FailedToExpandSegmentException('Invalid start or end address.')
    new_end = end + NEW_SEGMENT_SIZE / 2
    if not idc.SetSegBounds(ea, start, new_end, idaapi.SEGMOD_KEEP):
        raise FailedToExpandSegmentException('Setting segment bounds failed.') 
Example 25
Project: flare-ida   Author: fireeye   File: shellcode_hash_search.py    License: Apache License 2.0 5 votes vote down vote up
def processAllSegments(self):
        for seg in idautils.Segments():
            if using_ida7api:
                segStart = idc.get_segm_start(seg)
                segEnd = idc.get_segm_end(seg)
            else:
                segStart = idc.SegStart(seg)
                segEnd = idc.SegEnd(seg)

            if self.params.searchPushArgs:
                self.lookForOpArgs(segStart, segEnd)
            if self.params.searchDwordArray:
                self.lookForDwordArray(segStart, segEnd) 
Example 26
Project: flare-ida   Author: fireeye   File: shellcode_hash_search.py    License: Apache License 2.0 5 votes vote down vote up
def promptForRange(self):
        # Only run if QT not available, so not bothering with ida7 check
        #check if a range has already been selected - if so skip prompt
        if using_ida7api:
            selstart = idc.read_selection_start()
            selend = idc.read_selection_end()
            segstart = idc.get_segm_start(idc.here())
            segend = idc.get_segm_end(idc.here())
        else:
            selstart = idc.SelStart()
            selend = idc.SelEnd()
            seg = idc.SegStart(idc.here())
            self.params.endAddr = idc.SegEnd(idc.here())

        if selstart != idc.BADADDR:
            self.params.startAddr = selstart
            self.params.endAddr = selend
            logger.info('Processing range 0x%08x - 0x%08x', self.params.startAddr, self.params.endAddr)
        else:
            self.params.startAddr = segstart
            self.params.endAddr = segend
            logger.info('Processing current segment only')

###################################################################
#
################################################################### 
Example 27
Project: flare-ida   Author: fireeye   File: jayutils.py    License: Apache License 2.0 5 votes vote down vote up
def isValidPointer(va):
    if using_ida7api:
        return isValidPointer_ida7(va)
    for segStart in idautils.Segments():
        if (va >= segStart) and (va < idc.SegEnd(segStart)):
            return True
    return False 
Example 28
Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 4 votes vote down vote up
def get_function_bounds(ea):
  """Get the bounds of the function containing `ea`. We want to discover jump
  table targets that are missed by IDA, and it's possible that they aren't
  marked as being part of the current function, and perhaps are after the
  assumed range of the current function. Ideally they will fall before the
  beginning of the next function, though.

  We need to be pretty careful with the case that one function tail-calls
  another. IDA will sometimes treat the end of the tail-called function
  (e.g. a thunk) as if it is the end of the caller. For this reason, we start
  with loose bounds using the prev/next functions, then try to narrow with
  the bounds of the function containing `ea`.

  TODO(pag): Handle discontinuous regions (e.g. because of function chunks).
             It may be worth to return an object here that can we queried
             for membership using the `__in__` method.
  """
  seg_start, seg_end = idc.SegStart(ea), idc.SegEnd(ea)
  min_ea = seg_start
  max_ea = seg_end

  if is_invalid_ea(min_ea) or not is_code(ea):
    return ea, ea

  # Get an upper bound using the next function.
  next_func_ea = idc.NextFunction(ea)
  if not is_invalid_ea(next_func_ea):
    max_ea = min(next_func_ea, max_ea)

  # Get a lower bound using the previous function.
  prev_func_ea = idc.PrevFunction(ea)
  if not is_invalid_ea(prev_func_ea):
    min_ea = max(min_ea, prev_func_ea)
    prev_func = idaapi.get_func(prev_func_ea)
    if prev_func and prev_func.endEA < ea:
      min_ea = max(min_ea, prev_func.endEA)

  # Try to tighten the bounds using the function containing `ea`.
  func = idaapi.get_func(ea)
  if func:
    min_ea = max(min_ea, func.startEA)
    max_ea = min(max_ea, func.endEA)

  return min_ea, max_ea