Python idautils.Segments() Examples

The following are 30 code examples of idautils.Segments(). 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 idautils , or try the search function .
Example #1
Source Project: python-idb   Author: williballenthin   File: dump_section_list.py    License: Apache License 2.0 8 votes vote down vote up
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) 
Example #2
Source 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 #3
Source 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 #4
Source Project: ida_kernelcache   Author: bazad   File: stub.py    License: MIT License 6 votes vote down vote up
def initialize_stub_symbols(make_thunk=True):
    """Populate IDA with information about the stubs in an iOS kernelcache.

    Search through the kernelcache for stubs (__stubs sections) and rename each stub function
    according to the target function it calls.

    Arm64 only.

    Options:
        make_thunk: Set the thunk attribute for each stub function. Default is True.
    """
    next_stub = internal.make_name_generator(kernelcache_stub_suffix)
    for ea in idautils.Segments():
        segname = idc.SegName(ea)
        if not segname.endswith('__stubs'):
            continue
        _log(3, 'Processing segment {}', segname)
        _process_stubs_section(ea, make_thunk, next_stub) 
Example #5
Source Project: ida_kernelcache   Author: bazad   File: kernel.py    License: MIT License 6 votes vote down vote up
def _find_prelink_info_segments():
    """Find all candidate __PRELINK_INFO segments (or sections).

    We try to identify any IDA segments with __PRELINK_INFO in the name so that this function will
    work both before and after automatic rename. A more reliable method would be parsing the
    Mach-O.
    """
    segments = []
    # Gather a list of all the possible segments.
    for seg in idautils.Segments():
        name = idc.SegName(seg)
        if '__PRELINK_INFO' in name or name == '__info':
            segments.append(seg)
    if len(segments) < 1:
        _log(0, 'Could not find any __PRELINK_INFO segment candidates')
    elif len(segments) > 1:
        _log(1, 'Multiple segment names contain __PRELINK_INFO: {}',
                [idc.SegName(seg) for seg in segments])
    return segments 
Example #6
Source Project: bnida   Author: zznop   File: ida_export.py    License: MIT License 6 votes vote down vote up
def get_line_comments():
    """
    Iterate through every address in a segment and check for comments

    :return: Dict containing line comments
    """

    last_comment = ''
    comments = {}
    for ea in idautils.Segments():
        segm = ida_segment.getseg(ea)
        name = ida_segment.get_segm_name(segm)
        if name == 'LOAD':
            continue

        for i in range(segm.start_ea, segm.end_ea):
            comment = get_single_line_comment(i)
            if comment and comment != last_comment:
                comments[i] = comment
                last_comment = comment

    return comments 
Example #7
Source Project: bnida   Author: zznop   File: ida_export.py    License: MIT License 6 votes vote down vote up
def get_sections():
    """
    Get section names and start/end addrs from IDA database

    :return: Dict containing section info
    """

    sections = {}
    for ea in idautils.Segments():
        segm = ida_segment.getseg(ea)
        name = ida_segment.get_segm_name(segm)
        if name == 'LOAD':
            continue

        curr = {}
        curr['start']  = segm.start_ea
        curr['end']    = segm.end_ea
        sections[name] = curr

    return sections 
Example #8
Source Project: flare-ida   Author: fireeye   File: jayutils.py    License: Apache License 2.0 6 votes vote down vote up
def getx86CodeSize(ea=None):
    '''
    For a given EA, finds the code size. Returns 16 for-16bit, 32 for 32-bit, or 64 for 64-bit.
    If no EA is given, searches through all segments for a code segment to use.
    '''
    if using_ida7api:
        return getx86CodeSize_ida7(ea)
    if ea is None:
        for seg in idautils.Segments():
            if idc.GetSegmentAttr(seg, idc.SEGATTR_TYPE) == idc.SEG_CODE:
                ea = seg
                break
    if ea is None:
        raise RuntimeError('Could not find code segment to use for getx86CodeSize')
    bitness = idc.GetSegmentAttr(ea, idc.SEGATTR_BITNESS)
    if bitness == 0:
        return 16
    elif bitness == 1:
        return 32
    elif bitness == 2:
        return 64
    raise RuntimeError('Bad bitness') 
Example #9
Source 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 #10
Source 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 #11
Source Project: Karta   Author: CheckPointSW   File: ida_api.py    License: MIT License 5 votes vote down vote up
def numSegments(self):
        """Return the number of the segments in the binary.

        Return Value:
            number of segments in the binary
        """
        return len(list(idautils.Segments()))

    # Overridden base function 
Example #12
Source Project: idawilli   Author: williballenthin   File: ida_find_ptrs.py    License: Apache License 2.0 5 votes vote down vote up
def enum_segments():
    for segstart in idautils.Segments():
        segend = idc.get_segm_end(segstart)
        segname = idc.get_segm_name(segstart)
        yield segstart, segend, segname 
Example #13
Source Project: idawilli   Author: williballenthin   File: yara_fn.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example #14
Source Project: idawilli   Author: williballenthin   File: color.py    License: Apache License 2.0 5 votes vote down vote up
def enum_segments():
    for ea in idautils.Segments():
        seg = ida_segment.getseg(ea)
        yield Segment(seg.start_ea, seg.end_ea, seg.name) 
Example #15
Source Project: fcatalog_client   Author: xorpd   File: fcatalog_plugin.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save_sstring(s):
    """
    Save a short string inside the idb.
    """
    min_segment_addr = min(list(idautils.Segments()))
    # Keep the string as a regular comment on the first instruction:
    idc.MakeComm(min_segment_addr,s) 
Example #16
Source Project: fcatalog_client   Author: xorpd   File: fcatalog_plugin.py    License: GNU General Public License v3.0 5 votes vote down vote up
def load_sstring():
    """
    Load a short string from the idb.
    """
    min_segment_addr = min(list(idautils.Segments()))
    return idc.GetCommentEx(min_segment_addr,0) 
Example #17
Source Project: ida_haru   Author: TakahiroHaruyama   File: yara_fn.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example #18
Source Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def get_destructor_segment():
  """Returns the start address of the global destructor section"""
  for seg_ea in idautils.Segments():
    seg_name = idc.SegName(seg_ea).lower()
    if seg_name in [".fini_array", ".dtor"]:
      return seg_ea; 
Example #19
Source Project: mcsema   Author: lifting-bits   File: exception.py    License: Apache License 2.0 5 votes vote down vote up
def recover_exception_table():
  """ Recover the CIE and FDE entries from the segment .eh_frame
  """
  seg_eas = [ea for ea in idautils.Segments() if not is_invalid_ea(ea)]
  
  for seg_ea in seg_eas:
    seg_name = idc.SegName(seg_ea)
    if seg_name in [".eh_frame", "__eh_frame"]:
      recover_frame_entries(seg_ea)
      break

  recover_rtti() 
Example #20
Source 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 #21
Source Project: mcsema   Author: lifting-bits   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def get_destructor_segment():
  """Returns the start address of the global destructor section"""
  for seg_ea in idautils.Segments():
    seg_name = idc.get_segm_name(seg_ea).lower()
    if seg_name in [".fini_array", ".dtor"]:
      return seg_ea; 
Example #22
Source Project: mcsema   Author: lifting-bits   File: exception.py    License: Apache License 2.0 5 votes vote down vote up
def recover_exception_table():
  """ Recover the CIE and FDE entries from the segment .eh_frame
  """
  seg_eas = [ea for ea in idautils.Segments() if not is_invalid_ea(ea)]
  
  for seg_ea in seg_eas:
    seg_name = idc.get_segm_name(seg_ea)
    if seg_name in [".eh_frame", "__eh_frame"]:
      recover_frame_entries(seg_ea)
      break 
Example #23
Source 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 #24
Source Project: miasm   Author: cea-sec   File: bin_stream_ida.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getlen(self):
        # Lazy version
        if hasattr(self, "_getlen"):
            return self._getlen
        max_addr = get_segm_end(list(Segments())[-1]  - (self.offset - self.base_address))
        self._getlen = max_addr
        return max_addr 
Example #25
Source 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 #26
Source Project: ida_kernelcache   Author: bazad   File: collect_classes.py    License: MIT License 5 votes vote down vote up
def _collect_metaclasses():
    """Collect OSMetaClass information from all kexts in the kernelcache."""
    # Collect associations from class names to metaclass instances and vice versa.
    metaclass_to_classname_builder = _OneToOneMapFactory()
    metaclass_to_class_size      = dict()
    metaclass_to_meta_superclass = dict()
    def found_metaclass(metaclass, classname, class_size, meta_superclass):
        metaclass_to_classname_builder.add_link(metaclass, classname)
        metaclass_to_class_size[metaclass]      = class_size
        metaclass_to_meta_superclass[metaclass] = meta_superclass
    for ea in idautils.Segments():
        segname = idc.SegName(ea)
        if not _should_process_segment(ea, segname):
            continue
        _log(2, 'Processing segment {}', segname)
        _process_mod_init_func_section_for_metaclasses(ea, found_metaclass)
    # Filter out any class name (and its associated metaclasses) that has multiple metaclasses.
    # This can happen when multiple kexts define a class but only one gets loaded.
    def bad_classname(classname, metaclasses):
        _log(0, 'Class {} has multiple metaclasses: {}', classname,
                ', '.join(['{:#x}'.format(mc) for mc in metaclasses]))
    # Filter out any metaclass (and its associated class names) that has multiple class names. I
    # have no idea why this would happen.
    def bad_metaclass(metaclass, classnames):
        _log(0, 'Metaclass {:#x} has multiple classes: {}', metaclass,
                ', '.join(classnames))
    # Return the final dictionary of metaclass info.
    metaclass_to_classname = metaclass_to_classname_builder.build(bad_metaclass, bad_classname)
    metaclass_info = dict()
    for metaclass, classname in metaclass_to_classname.items():
        meta_superclass = metaclass_to_meta_superclass[metaclass]
        superclass_name = metaclass_to_classname.get(meta_superclass, None)
        metaclass_info[metaclass] = classes.ClassInfo(classname, metaclass, None, None,
                metaclass_to_class_size[metaclass], superclass_name, meta_superclass)
    return metaclass_info 
Example #27
Source Project: ida_kernelcache   Author: bazad   File: offset.py    License: MIT License 5 votes vote down vote up
def initialize_offset_symbols():
    """Populate IDA with information about the offsets in an iOS kernelcache.

    Search through the kernelcache for global offset tables (__got sections), convert each offset
    into an offset type in IDA, and rename each offset according to its target.

    This function does nothing in the newer 12-merged format kernelcache.
    """
    next_offset = internal.make_name_generator(kernelcache_offset_suffix)
    for ea in idautils.Segments():
        segname = idc.SegName(ea)
        if not segname.endswith('__got'):
            continue
        _log(2, 'Processing segment {}', segname)
        _process_offsets_section(ea, next_offset) 
Example #28
Source 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 #29
Source Project: bap-ida-python   Author: BinaryAnalysisPlatform   File: ida.py    License: MIT License 5 votes vote down vote up
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") 
Example #30
Source 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)))