Python idc.get_segm_name() Examples

The following are 23 code examples of idc.get_segm_name(). 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: colorizer.py    From deREferencing with GNU General Public License v3.0 6 votes vote down vote up
def get_area_name(self, ea, val_type):
        name = None
        if val_type == T_CODE:
            fcn_name = idc.get_func_off_str(ea)
            if fcn_name:
                name = fcn_name
            else:
                symbol_name = idaapi.get_name(ea)
                if symbol_name:
                    name = symbol_name
        else:
            symbol_name = idaapi.get_name(ea)
            if symbol_name:
                name = symbol_name

        seg_name = idc.get_segm_name(ea)
        if seg_name is not None:
            if name:
                name = "%s ! %s" % (seg_name, name)
            else:
                name = seg_name
        return name 
Example #2
Source File: get_cfg.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def is_ELF_got_pointer(ea):
  """Returns `True` if this is a pointer to a pointer stored in the
  `.got` section of an ELF binary. For example, `__gmon_start___ptr` is
  a pointer in the `.got` that will be fixed up to contain the address of
  the external function `__gmon_start__`. We don't want to treat
  `__gmon_start___ptr` as external because it is really a sort of local
  variable that will will resolve with a data cross-reference."""
  seg_name = idc.get_segm_name(ea).lower()
  if ".got" not in seg_name:
    return False

  name = get_symbol_name(ea)
  target_ea = get_reference_target(ea)
  target_name = get_true_external_name(get_symbol_name(target_ea))

  if target_name not in name:
    return False

  return is_referenced_by(target_ea, ea) 
Example #3
Source File: exp.py    From run_idat with GNU General Public License v3.0 5 votes vote down vote up
def get_all_func():
    num = 0
    content = []
    for func in idautils.Functions():
        seg_perm = idc.get_segm_attr(func,SEGATTR_PERM)         # 段属性
        if(5 !=seg_perm):
            continue
        seg_name = idc.get_segm_name(func)                      # 段名
        if(".plt" == seg_name):
            continue
        
        func_name = idc.get_func_name(func)                     # 函数名
        func_flags = hex(idc.get_func_attr(func,FUNCATTR_FLAGS))# 函数信息
        func_head = hex(idc.get_func_attr(func,FUNCATTR_START)) # 函数头
        func_end = hex(idc.get_func_attr(func,FUNCATTR_END))    # 函数尾

        l = []
        l.append(num)
        l.append(seg_name)
        l.append(seg_perm)
        l.append(func_name)
        l.append(func_flags)
        l.append(func_head)
        l.append(func_end)
        content.append(l)
        
        num += 1
        #print(l)
    return content
        
# 程序入口 
Example #4
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.magicMask64 = 0xabbadabbad000000
        self.magicMask32 = 0xabba0000
        self.magicMaskMask64 = 0xffffffffffff0000
        self.magicMaskMask32 = 0xffff0000
        self.callMnems = ["call", "jmp", "BL", "BLX", "BLEQ", "BLXEQ", "BLR", "BLREQ", "B"]
        self.objcData = None
        self.objcSelRefs = None
        self.objcMsgRefs = None
        self.objcConst = None
        self.objcClassRefs = None
        self.objcCatList = None
        self.fixedSelXRefs = []
        self.ivarSetters = {}
        self.notIvarSetters = []
        for segVA in idautils.Segments():
            segName = idc.get_segm_name(segVA)
            endVA = idc.get_segm_end(segVA)
            if segName == "__objc_data":
                self.objcData = (segVA, endVA)
            elif segName == "__objc_selrefs":
                self.objcSelRefs = (segVA, endVA)
            elif segName == "__objc_msgrefs":
                self.objcMsgRefs = (segVA, endVA)
            elif segName == "__objc_const":
                self.objcConst = (segVA, endVA)
            elif segName == "__objc_classrefs":
                self.objcClassRefs = (segVA, endVA)
            elif segName == "__objc_catlist":
                self.objcCatList = (segVA, endVA)
        if self.objcSelRefs or self.objcMsgRefs:
            self.processObjc()
        else:
            logging.debug("this Mach-O does not implement any Objective-C classes")
    
    # it appears idc.get_name_ea_simple does not work for selector reference names that end in "_" 
Example #5
Source File: colorizer.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
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

# ----------------------------------------------------------------------- 
Example #6
Source File: as3.py    From ActionScript3 with GNU General Public License v3.0 5 votes vote down vote up
def find(self):

        ea = idc.get_first_seg()

        tags = []
        while (ea != ida_idaapi.BADADDR):
            if (idc.get_segm_name(ea) == "DoABC"):
                name = idc.get_strlit_contents(ea + 0xA)
                tags.append("%d - %s" % (ea, name))

            ea = idc.get_next_seg(ea)
        
        if (tags == []):
            return False

        if (len(tags) > 1):
            app = QtWidgets.QWidget()
            ea, ok = QtWidgets.QInputDialog.getItem(app, "Select DoABC tag", 
                                                    "List of DoABC tags", 
                                                    tags, 0, False)

            if (ea and ok):
                ea = long(ea.split()[0])
            else:
                return False

        else:
            ea = long(tags[0].split()[0])

        Reader.pos = ea

        return True 
Example #7
Source File: functions_plus.py    From functions-plus with MIT License 5 votes vote down vote up
def __init__(self, show_extra_fields):
        self.addr = None
        self.flags = None
        self.show_extra_fields = show_extra_fields
        self.names = [
            'Name', 'Address', 'Segment', 'Length', 'Locals', 'Arguments'
        ]

        self.handlers = {
            0: lambda: None,
            1: lambda: self.fmt(self.addr),
            2: lambda: '{}'.format(idc.get_segm_name(self.addr)),
            3: lambda: self.fmt(idc.get_func_attr(self.addr, idc.FUNCATTR_END) - self.addr),
            4: lambda: self.fmt(idc.get_func_attr(self.addr, idc.FUNCATTR_FRSIZE)),
            5: lambda: self.fmt(idc.get_func_attr(self.addr, idc.FUNCATTR_ARGSIZE))
        }

        if self.show_extra_fields:
            self.names.extend(['R', 'F', 'L', 'S', 'B', 'T', '='])
            # TODO: add Lumina column info
            self.handlers.update({
                6: lambda: self.is_true(not self.flags & idc.FUNC_NORET, 'R'),
                7: lambda: self.is_true(self.flags & idc.FUNC_FAR, 'F'),
                8: lambda: self.is_true(self.flags & idc.FUNC_LIB, 'L'),
                9: lambda: self.is_true(self.flags & idc.FUNC_STATIC, 'S'),
                10: lambda: self.is_true(self.flags & idc.FUNC_FRAME, 'B'),
                11: lambda: self.is_true(idc.get_type(self.addr), 'T'),
                12: lambda: self.is_true(self.flags & idc.FUNC_BOTTOMBP, '=')
            }) 
Example #8
Source File: utils.py    From UEFI_RETool with MIT License 5 votes vote down vote up
def get_header_idb():
    """get file header from idb"""
    if idc.get_segm_name(0) == 'HEADER':
        header = bytearray(
            [idc.get_wide_byte(ea) for ea in range(0, idc.get_segm_end(0))])
        return header
    return bytearray(b'') 
Example #9
Source File: exception.py    From mcsema with 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 #10
Source File: exception.py    From mcsema with 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.get_segm_name(seg_ea)))
  ea = idc.get_segm_start(seg_ea)
  end_ea = idc.get_segm_end(seg_ea)
  while ea != idc.BADADDR and ea < end_ea:
    ea = format_entries(ea) 
Example #11
Source File: util.py    From mcsema with 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 #12
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_constructor_segment(ea):
  """Returns `True` if the segment containing `ea` belongs to global constructor section"""
  seg_ea = idc.get_segm_start(ea)
  seg_name = idc.get_segm_name(seg_ea).lower()
  if seg_name in [".init_array", ".ctor"]:
    return True
  return False 
Example #13
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_external_segment(ea):
  """Returns `True` if the segment containing `ea` looks to be solely containing
  external references."""
  global _NOT_EXTERNAL_SEGMENTS

  seg_ea = idc.get_segm_start(ea)
  if seg_ea in _NOT_EXTERNAL_SEGMENTS:
    return False

  if seg_ea in _EXTERNAL_SEGMENTS:
    return True

  if is_external_segment_by_flags(ea):
    _EXTERNAL_SEGMENTS.add(seg_ea)
    return True

  ext_types = []
  seg_name = idc.get_segm_name(seg_ea).lower()
  
  if IS_ELF:
    if ".got" in seg_name or ".plt" in seg_name:
      _EXTERNAL_SEGMENTS.add(seg_ea)
      return True

  elif IS_PE:
    if ".idata" == seg_name:  # Import table.
      _EXTERNAL_SEGMENTS.add(seg_ea)
      return True

  _NOT_EXTERNAL_SEGMENTS.add(seg_ea)
  return False 
Example #14
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def segment_contains_external_function_pointers(seg_ea):
  """Returns `True` if a segment contains pointers to external functions."""
  try:
    seg_name = idc.get_segm_name(seg_ea)
    return seg_name.lower() in (".idata", ".plt.got")
  except:
    return False 
Example #15
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_invalid_ea(ea):
  """Returns `True` if `ea` is not valid, i.e. it doesn't point into any
  valid segment."""
  if (idc.BADADDR == ea) or \
    (idc.get_segm_name(ea) == "LOAD"):
    return True

  try:
    idc.get_segm_attr(idc.get_segm_start(ea), idc.SEGATTR_TYPE)
    return False  # If we get here, then it must be a valid ea!
  except:
    return True 
Example #16
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_tls_segment(ea):
  try:
    seg_name = idc.get_segm_name(ea)
    return seg_name in (".tbss", ".tdata", ".tls")
  except:
    return False

# Returns `True` if `ea` looks like a thread-local thing. 
Example #17
Source File: bingraph.py    From heap-viewer with GNU General Public License v3.0 5 votes vote down vote up
def bin_info(self, node_title, chunk_addr, chunk, with_size=True):
        line =  idaapi.COLSTR("%s " % node_title, idaapi.SCOLOR_NUMBER)
        line += idaapi.COLSTR("0x%x\n\n" % chunk_addr, idaapi.SCOLOR_INSN)

        chunk_info = ""
        if with_size:
            chunk_info += "size: 0x%x\n" % chunk.size

        chunk_info += "fd: 0x%x - %s\nbk: 0x%x - %s" % (chunk.fd, \
            idc.get_segm_name(chunk.fd), chunk.bk, idc.get_segm_name(chunk.bk))

        line += idaapi.COLSTR(chunk_info, idaapi.SCOLOR_DEFAULT)
        return line 
Example #18
Source File: bingraph.py    From heap-viewer with GNU General Public License v3.0 5 votes vote down vote up
def chunk_info(self, chunk_addr, chunk):
        line =  idaapi.COLSTR("Chunk ", idaapi.SCOLOR_NUMBER)
        line += idaapi.COLSTR("0x%x\n\n" % (chunk_addr), idaapi.SCOLOR_INSN)
        line += idaapi.COLSTR("size: 0x%x\nfd: 0x%x - %s" % \
                (chunk.size, chunk.fd, idc.get_segm_name(chunk.fd)), SCOLOR_DEFAULT)
        return line 
Example #19
Source File: ida_find_ptrs.py    From idawilli with 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 #20
Source File: get_cfg.py    From mcsema with Apache License 2.0 4 votes vote down vote up
def is_ELF_thunk_by_structure(ea):
  """Try to manually identify an ELF thunk by its structure."""
  global _INVALID_THUNK_ADDR

  if ".plt" not in idc.get_segm_name(ea).lower():
    return _INVALID_THUNK_ADDR

  # Scan through looking for a branch, either direct or indirect.
  inst = None
  for i in range(4):  # 1 is good enough for x86, 4 for aarch64.
    inst, _ = decode_instruction(ea)
    if not inst:
      return _INVALID_THUNK_ADDR
    # elif is_direct_jump(inst):
    #   ea = get_direct_branch_target(inst)
    #   inst = None
    elif is_indirect_jump(inst) or is_direct_jump(inst):
      ea = inst.ea
      break
    else:
      ea = inst.ea + inst.size
      inst = None

  if not inst:
    return _INVALID_THUNK_ADDR

  target_ea = get_reference_target(inst.ea)
  if ".got.plt" == idc.get_segm_name(target_ea).lower():
    target_ea = get_reference_target(target_ea)

  # For AArch64, the thunk structure is something like:
  #     .plt:000400470 .atoi
  #     .plt:000400470    ADRP            X16, #off_411000@PAGE
  #     .plt:000400474    LDR             X17, [X16,#off_411000@PAGEOFF]
  #     .plt:000400478    ADD             X16, X16, #off_411000@PAGEOFF
  #     .plt:00040047C    BR              X17 ; atoi
  #
  # With:
  #
  #     extern:000411070 ; int atoi(const char *nptr)
  #     extern:000411070                 IMPORT atoi
  

  # For x86, the thunk structure is something like:
  #   
  #     .plt:00041F10 _qsort      proc near         
  #     .plt:00041F10         jmp   cs:off_31F388
  #     .plt:00041F10 _qsort      endp
  #     
  # With:
  # 
  #     .got.plt:0031F388 off_31F388    dq offset qsort
  #
  # With
  #     extern:0031F388 ; void qsort(void *base, ...)
  #     extern:0031F388                 extrn qsort:near 

  if is_invalid_ea(target_ea):
    return _INVALID_THUNK_ADDR
  
  return True, target_ea 
Example #21
Source File: analyser.py    From UEFI_RETool with MIT License 4 votes vote down vote up
def get_data_guids(self):
        """rename GUIDs in idb"""
        EFI_GUID = 'EFI_GUID *'
        EFI_GUID_ID = idc.get_struc_id('EFI_GUID')
        segments = ['.text', '.data']
        for segment in segments:
            seg_start, seg_end = 0, 0
            for seg in idautils.Segments():
                if idc.get_segm_name(seg) == segment:
                    seg_start = idc.get_segm_start(seg)
                    seg_end = idc.get_segm_end(seg)
                    break
            ea = seg_start
            while (ea <= seg_end - 15):
                prot_name = ''
                if idc.get_name(ea, ida_name.GN_VISIBLE).find('unk_') != -1:
                    find = False
                    cur_guid = []
                    cur_guid.append(idc.get_wide_dword(ea))
                    cur_guid.append(idc.get_wide_word(ea + 4))
                    cur_guid.append(idc.get_wide_word(ea + 6))
                    for addr in range(ea + 8, ea + 16, 1):
                        cur_guid.append(idc.get_wide_byte(addr))
                    if cur_guid == [0] * 11:
                        ea += 1
                        continue
                    for guid_place in [
                            'ami_guids', 'asrock_guids', 'dell_guids',
                            'edk_guids', 'edk2_guids', 'lenovo_guids'
                    ]:
                        for name in self.Protocols[guid_place]:
                            if self.Protocols[guid_place][name] == cur_guid:
                                prot_name = '{}_{:#x}'.format(name, ea)
                                record = {
                                    'address': ea,
                                    'service': 'unknown',
                                    'guid': cur_guid,
                                    'protocol_name': name,
                                    'protocol_place': guid_place
                                }
                                find = True
                                break
                            if find:
                                break
                    if find and (idc.get_name(ea, ida_name.GN_VISIBLE) !=
                                 prot_name):
                        idc.SetType(ea, EFI_GUID)
                        self.apply_struct(ea, 16, EFI_GUID_ID)
                        idc.set_name(ea, prot_name)
                        self.Protocols['data'].append(record)
                ea += 1 
Example #22
Source File: arena.py    From heap-viewer with GNU General Public License v3.0 4 votes vote down vote up
def populate_table(self):
        cur_arena = self.cur_arena
        arena = self.heap.get_arena(cur_arena)
        self.t_top_addr.setText("%#x" % arena.top)
        self.t_last_remainder.setText("%#x" % arena.last_remainder)
        self.t_attached_threads.setText("%d" % arena.attached_threads)

        top_segname = idc.get_segm_name(arena.top)
        if not any(s in top_segname for s in ['heap','debug']):
            self.lbl_top_warning.setVisible(True)
            self.lbl_top_warning.setText("Top points to '%s' segment" % top_segname)
        else:
            self.lbl_top_warning.setVisible(False)

        self.tbl_parsed_heap.clearContents()
        self.tbl_parsed_heap.setRowCount(0)
        self.tbl_parsed_heap.setSortingEnabled(False)

        parsed_heap = self.heap.parse_heap(cur_arena)

        for idx, chunk in enumerate(parsed_heap):
            self.tbl_parsed_heap.insertRow(idx)

            it_address = QtWidgets.QTableWidgetItem("%#x" % chunk['address'])
            it_prev = QtWidgets.QTableWidgetItem("%#x" % chunk['prev'])
            it_size = QtWidgets.QTableWidgetItem("%#x" % chunk['size'])
            it_status = QtWidgets.QTableWidgetItem("%s" % chunk['status'])
            it_fd = QtWidgets.QTableWidgetItem("%#x" % chunk['fd'])
            it_bk = QtWidgets.QTableWidgetItem("%#x" % chunk['bk'])

            if 'Freed' in chunk['status']:
                it_status.setForeground(QtGui.QColor('red'))
            elif chunk['status'] == 'Corrupt':
                it_status.setForeground(QtGui.QColor.fromRgb(213, 94, 0))
                it_status.setFont(self.bold_font)
            else:
                it_status.setForeground(QtGui.QColor('blue'))

            self.tbl_parsed_heap.setItem(idx, 0, it_address)
            self.tbl_parsed_heap.setItem(idx, 1, it_prev)
            self.tbl_parsed_heap.setItem(idx, 2, it_size)
            self.tbl_parsed_heap.setItem(idx, 3, it_status)
            self.tbl_parsed_heap.setItem(idx, 4, it_fd)
            self.tbl_parsed_heap.setItem(idx, 5, it_bk)

        self.tbl_parsed_heap.resizeRowsToContents()
        self.tbl_parsed_heap.resizeColumnsToContents()
        self.tbl_parsed_heap.setSortingEnabled(True)
        self.tbl_parsed_heap.sortByColumn(0, QtCore.Qt.DescendingOrder) 
Example #23
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 4 votes vote down vote up
def getIvarTypeFromFunc(self, eh, va):
        if va in self.ivarSetters:
            return self.ivarSetters[va]
        elif va in self.notIvarSetters:
            return UNKNOWN
        addr = va
        endVa = idc.get_func_attr(va, idc.FUNCATTR_END)
        if endVa - va < 0x20:
            ivarVa = None
            while addr <= endVa:
                srcOpnd = idc.print_operand(addr, 1)
                # if ivar is the src op for an instruction, assume this function will return it
                if eh.arch == unicorn.UC_ARCH_ARM and "_OBJC_IVAR_$_" in srcOpnd:
                    oploc = idc.get_name_ea_simple(
                        srcOpnd[srcOpnd.find("_OBJC_IVAR_$_"):srcOpnd.find(" ")])
                    if oploc != idc.BADADDR:
                        ivarVa = oploc
                        break
                elif eh.arch == unicorn.UC_ARCH_ARM64:
                    for x in idautils.XrefsFrom(addr):
                        if (idc.get_segm_name(x.to) == "__objc_ivar" and
                                idc.get_name(x.to, idc.ida_name.GN_VISIBLE)[:13] == "_OBJC_IVAR_$_"):
                            ivarVa = x.to
                            break
                elif eh.arch == unicorn.UC_ARCH_X86:
                    if "_OBJC_IVAR_$_" in srcOpnd:
                        ivarVa = idc.get_operand_value(addr, 1)
                        break

                addr = idc.next_head(addr, idc.get_inf_attr(idc.INF_MAX_EA))

            if ivarVa:
                for x in idautils.XrefsTo(ivarVa):
                    if x.frm >= self.objcConst[0] and x.frm < self.objcConst[1]:
                        typeStr = eh.getIDBString(
                            eh.derefPtr(x.frm + eh.size_pointer * 2))
                        self.ivarSetters[va] = typeStr[2:-1]
                        logging.debug("%s is an ivar getter function, returning type %s" % (
                            eh.hexString(va), typeStr[2:-1]))
                        return typeStr[2:-1]
            else:
                logging.debug(
                    "%s determined not to be an ivar getter function", eh.hexString(va))
                self.notIvarSetters.append(va)
        else:
            logging.debug(
                "%s determined not to be an ivar getter function", eh.hexString(va))
            self.notIvarSetters.append(va)
        return UNKNOWN


    # returns class or sel name from IDA name