我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用idaapi.getseg()。
def enum_segm(self): i = 0 for ea in idautils.Segments(): seg = idaapi.getseg(ea) SigmName = idc.SegName(ea) startA = idc.SegStart(ea) endA = idc.SegEnd(ea) className = idaapi.get_segm_class(seg) seg_radio = SegmRadio(SigmName, startA, endA, className) self.segm.append((SigmName, startA, endA, className)) self.segm_vbox.addWidget(seg_radio) self.segm_vbox.addStretch(1) if i == 0: i = 1 seg_radio.toggle() return self.segm_vbox
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)
def DeleteAll(): """ Delete all segments, instructions, comments, i.e. everything except values of bytes. """ ea = idaapi.cvar.inf.minEA # Brute-force nuke all info from all the heads while ea != BADADDR and ea <= idaapi.cvar.inf.maxEA: idaapi.del_local_name(ea) idaapi.del_global_name(ea) func = idaapi.get_func(ea) if func: idaapi.del_func_cmt(func, False) idaapi.del_func_cmt(func, True) idaapi.del_func(ea) idaapi.del_hidden_area(ea) seg = idaapi.getseg(ea) if seg: idaapi.del_segment_cmt(seg, False) idaapi.del_segment_cmt(seg, True) idaapi.del_segm(ea, idaapi.SEGDEL_KEEP | idaapi.SEGDEL_SILENT) ea = idaapi.next_head(ea, idaapi.cvar.inf.maxEA)
def SegName(ea): """ Get name of a segment @param ea: any address in the segment @return: "" - no segment at the specified address """ seg = idaapi.getseg(ea) if not seg: return "" else: name = idaapi.get_true_segm_name(seg) if not name: return "" else: return name
def SetSegAddressing(ea, bitness): """ Change segment addressing @param ea: any address in the segment @param bitness: 0: 16bit, 1: 32bit, 2: 64bit @return: success (boolean) """ seg = idaapi.getseg(ea) if not seg: return False seg.bitness = bitness return True
def SetSegDefReg(ea, reg, value): """ Set default segment register value for a segment @param ea: any address in the segment if no segment is present at the specified address then all segments will be affected @param reg: name of segment register @param value: default value of the segment register. -1-undefined. """ seg = idaapi.getseg(ea) reg = idaapi.str2reg(reg); if seg and reg >= 0: return idaapi.SetDefaultRegisterValue(seg, reg, value) else: return False
def SetSegmentType(segea, segtype): """ Set segment type @param segea: any address within segment @param segtype: new segment type: @return: !=0 - ok """ seg = idaapi.getseg(segea) if not seg: return False seg.type = segtype return seg.update()
def MoveSegm(ea, to, flags): """ Move a segment to a new address This function moves all information to the new address It fixes up address sensitive information in the kernel The total effect is equal to reloading the segment to the target address @param ea: any address within the segment to move @param to: new segment start address @param flags: combination MFS_... constants @returns: MOVE_SEGM_... error code """ seg = idaapi.getseg(ea) if not seg: return MOVE_SEGM_PARAM return idaapi.move_segm(seg, to, flags)
def tables_from_heuristics(require_rtti=False): ''' Yields addresses of VTableGroups found via heuristic methods ''' for s in idautils.Segments(): seg = idaapi.getseg(s) if seg is None: continue if seg.type != idaapi.SEG_DATA: continue ea = seg.startEA while ea < seg.endEA: try: table = VTableGroup(ea) if require_rtti is True and ea.typeinfo is not None: yield ea elif require_rtti is False: yield ea ea += table.size except ValueError: # Assume vtables are aligned ea += TARGET_ADDRESS_SIZE
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( idaapi.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")
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) if buf is None: segsize -= 0x1000 return buf
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)
def segment(cls): """Current segment""" ea = cls.address() return idaapi.getseg(ea)
def by_address(ea): '''Return the segment that contains the specified ``ea``.''' s = idaapi.getseg(interface.address.within(ea)) if s is None: raise LookupError("{:s}.by_address({:x}) : Unable to locate segment".format(__name__, ea)) return s
def check_address(address): # Checks if given address contains virtual table. Returns True if more than 2 function pointers found # Also if table's addresses point to code in executable section, than tries to make functions at that addresses functions_count = 0 while True: func_address = idaapi.get_64bit(address) if Const.EA64 else idaapi.get_32bit(address) # print "[INFO] Address 0x{0:08X}".format(func_address) if Helper.is_code_ea(func_address) or Helper.is_imported_ea(func_address): functions_count += 1 address += Const.EA_SIZE else: segment = idaapi.getseg(func_address) if segment and segment.perm & idaapi.SEGPERM_EXEC: idc.MakeUnknown(func_address, 1, idaapi.DOUNK_SIMPLE) if idc.MakeFunction(func_address): functions_count += 1 address += Const.EA_SIZE continue break idaapi.autoWait() return functions_count
def setupUI(self): ea = idc.ScreenEA() seg = idaapi.getseg(ea) SigmName = idc.SegName(ea) startA = idc.SegStart(ea) endA = idc.SegEnd(ea) className = idaapi.get_segm_class(seg) self.setWindowTitle("Jumper--%s %s %s" % (hex(ea - startA).upper(), SigmName, className)) self.groupBox.setLayout(self.enum_segm()) search_hbox = QHBoxLayout() search_hbox.addWidget(QLabel("search")) search_hbox.addWidget(self.search_edit) offset_hbox = QHBoxLayout() offset_hbox.addWidget(QLabel("offset")) offset_hbox.addWidget(self.off_edit) self.scroll = QScrollArea() self.scroll.setWidgetResizable(True) # Set to make the inner widget resize with scroll area self.scroll.setWidget(self.groupBox) globle_vbox = QVBoxLayout(self) globle_vbox.addWidget(self.scroll) globle_vbox.addLayout(search_hbox) globle_vbox.addLayout(offset_hbox) btn_layout = QHBoxLayout() jump = QPushButton("jump") jump.clicked.connect(self.jump_click) get_offset = QPushButton("offset") get_offset.clicked.connect(self.get_cur_offset) btn_layout.addWidget(jump) btn_layout.addWidget(get_offset) globle_vbox.addLayout(btn_layout) self.search_edit.textChanged.connect(self.search_changed)
def get_cur_offset(self): ea = idc.ScreenEA() seg = idaapi.getseg(ea) SigmName = idc.SegName(ea) startA = idc.SegStart(ea) self.off_edit.setText(hex(ea - startA).upper()) self.search_edit.setText(SigmName)
def SegStart(ea): """ Get start address of a segment @param ea: any address in the segment @return: start of segment BADADDR - the specified address doesn't belong to any segment """ seg = idaapi.getseg(ea) if not seg: return BADADDR else: return seg.startEA
def SegEnd(ea): """ Get end address of a segment @param ea: any address in the segment @return: end of segment (an address past end of the segment) BADADDR - the specified address doesn't belong to any segment """ seg = idaapi.getseg(ea) if not seg: return BADADDR else: return seg.endEA
def SetSegClass(ea, segclass): """ Change class of the segment @param ea: any address in the segment @param segclass: new class of the segment @return: success (boolean) """ seg = idaapi.getseg(ea) if not seg: return False return idaapi.set_segm_class(seg, segclass)
def GetSegmentAttr(segea, attr): """ Get segment attribute @param segea: any address within segment @param attr: one of SEGATTR_... constants """ seg = idaapi.getseg(segea) assert seg, "could not find segment at 0x%x" % segea if attr in [ SEGATTR_ES, SEGATTR_CS, SEGATTR_SS, SEGATTR_DS, SEGATTR_FS, SEGATTR_GS ]: return idaapi.get_defsr(seg, _SEGATTRMAP[attr]) else: return _IDC_GetAttr(seg, _SEGATTRMAP, attr)
def GetColor(ea, what): """ Get item color @param ea: address of the item @param what: type of the item (one of CIC_* constants) @return: color code in RGB (hex 0xBBGGRR) """ if what not in [ CIC_ITEM, CIC_FUNC, CIC_SEGM ]: raise ValueError, "'what' must be one of CIC_ITEM, CIC_FUNC and CIC_SEGM" if what == CIC_ITEM: return idaapi.get_item_color(ea) if what == CIC_FUNC: func = idaapi.get_func(ea) if func: return func.color else: return DEFCOLOR if what == CIC_SEGM: seg = idaapi.getseg(ea) if seg: return seg.color else: return DEFCOLOR # color item codes:
def SetColor(ea, what, color): """ Set item color @param ea: address of the item @param what: type of the item (one of CIC_* constants) @param color: new color code in RGB (hex 0xBBGGRR) @return: success (True or False) """ if what not in [ CIC_ITEM, CIC_FUNC, CIC_SEGM ]: raise ValueError, "'what' must be one of CIC_ITEM, CIC_FUNC and CIC_SEGM" if what == CIC_ITEM: return idaapi.set_item_color(ea, color) if what == CIC_FUNC: func = idaapi.get_func(ea) if func: func.color = color return bool(idaapi.update_func(func)) else: return False if what == CIC_SEGM: seg = idaapi.getseg(ea) if seg: seg.color = color return bool(seg.update()) else: return False #-------------------------------------------------------------------------- # X M L #--------------------------------------------------------------------------
def SanityChecks(): seg = FirstSeg() if SegName(seg) != GetInputFile().replace(' ', '_'): dlg = AskYN(0, "Name of the first segment for main module ('" + SegName(seg) + "') doesn't\nmatch main module's name ('" + GetInputFile() + "').\n\n" + "In order for the FridaLink to function correctly (i.e. resolve\nsymbols and load additional modules) this segment name\nshould be updated.\n\n" + "Update first segment name to '" + GetInputFile() + "'?") if dlg == 1: set_segm_name(getseg(seg), GetInputFile()) Wait() fl_log("FridaLink: set first sector name for main binary to '" + GetInputFile() + "'\n")
def tables_from_names(): ''' Yields addresses of VtableGroups if binary is not stripped ''' for n in idautils.Names(): seg = idaapi.getseg(n[0]) if seg is None or seg.type != idaapi.SEG_DATA: continue if is_vtable_name(n[1]) is True: yield n[0]
def is_in_executable_segment(ea): if idaapi.getseg(ea) is None: return False return idaapi.getseg(ea).perm & idaapi.SEGPERM_EXEC
def in_same_segment(addr1, addr2): return (idaapi.getseg(addr1) is not None and idaapi.getseg(addr2) is not None and idaapi.getseg(addr1).startEA == idaapi.getseg(addr2).startEA)
def new(offset, size, name, **kwds): """Create a segment at ``offset`` with ``size`` and name it according to ``name``. ``bits`` can be used to specify the bit size of the segment ``comb`` can be used to specify any flags (idaapi.sc*) ``align`` can be used to specify paragraph alignment (idaapi.sa*) ``org`` specifies the origin of the segment (must be paragraph aligned due to ida) """ s = idaapi.get_segm_by_name(name) if s is not None: logging.fatal("{:s}.new({:x}, {:x}, {!r}, {!r}) : a segment with the specified name already exists : {:s}".format(__name__, offset, size, name, kwds, name)) return None bits = kwds.get( 'bits', 32 if idaapi.getseg(offset) is None else idaapi.getseg(offset).abits()) # FIXME: use disassembler default bit length instead of 32 if bits == 16: ## create a selector with the requested origin org = kwds.get('org',0) if org&0xf > 0: logging.fatal("{:s}.new({:x}, {:x}, {!r}, {!r}) : origin (.org) is not aligned to the size of a paragraph (0x10) : {:x}".format(__name__, offset, size, name, kwds, org)) return None para = offset/16 sel = idaapi.allocate_selector(para) idaapi.set_selector(sel, (para-kwds.get('org',0)/16)&0xffffffff) else: ## auto-create a selector for everything else sel = idaapi.setup_selector(kwds['selector']) if 'selector' in kwds else idaapi.find_free_selector() # create segment. ripped from idc s = idaapi.segment_t() s.startEA = offset s.endEA = offset+size s.sel = sel s.bitness = {16:0,32:1,64:2}[bits] s.comb = kwds.get('comb', idaapi.scPub) # public s.align = kwds.get('align', idaapi.saRelByte) # paragraphs res = idaapi.add_segm_ex(s, name, "", idaapi.ADDSEG_NOSREG|idaapi.ADDSEG_SPARSE) if res == 0: logging.warn("{:s}.new({:x}, {:x}, {!r}, {!r}) : unable to add a new segment".format(__name__, offset, size, name, kwds)) res = idaapi.del_selector(sel) #assert res != 0 return None return s
def LoadModule(platform, name, path): global g_NextLibBase if platform is not None: os_type = platform[:3] if os_type == "iOS": # check if it is custom or system framework app_idx = path.find(".app") if app_idx >=0: # custom framework local_path = path[app_idx+4:] bin_path = os.path.dirname(get_input_file_path()) path = bin_path + local_path else: # system framework os_ver = platform[4:] home = os.path.expanduser("~") path = home + "/Library/Developer/Xcode/iOS DeviceSupport/" + os_ver + "/Symbols" + path # check if framework exists if os.path.exists(path) == False: fl_log("FridaLink: invalid path [ " + path + " ]\n") return fl_log("FridaLink: loading module '" + name + "' from [ " + path + " ]\n") res = load_loader_module(None, "macho", str(path), False) if res != 0: Wait() seg = get_segm_by_name("HEADER").startEA set_segm_name(getseg(seg), name) Wait() fl_log("FridaLink: set first sector name for loaded module to '" + name + "'\n") if seg < g_AppBase: fl_log("FridaLink: move module '" + name + "' to " + ('0x%012x' % g_NextLibBase) + "\n") # Move back all segments before main one (usually for OSX modules) while seg < g_AppBase: fl_log((' 0x%012x' % SegStart(seg)) + " -> " + ('0x%012x' % (SegStart(seg) + g_NextLibBase)) + ": " + SegName(seg) + "\n") MoveSegm(SegStart(seg), SegStart(seg) + g_NextLibBase, 0) Wait() seg = FirstSeg() g_NextLibBase += kModuleAlignment fl_log("FridaLink: next module base = " + ("0x%012x" % g_NextLibBase) + "\n")