Python idc.GetFlags() Examples

The following are 17 code examples of idc.GetFlags(). 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: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 6 votes vote down vote up
def post_analysis_stuff(self, results):
        if results.has_formula():
            self.action_selector.addItem(self.parent.HIGHLIGHT_CODE)
            self.action_selector.addItem(self.parent.GRAPH_DEPENDENCY)
            self.formula_area.setText(self.parent.results.formula)
        if results.has_values():
            self.action_selector.addItem(self.parent.DISASS_UNKNOWN_TARGET)
        self.action_selector.setEnabled(True)
        self.action_button.setEnabled(True)

        report = HTMLReport()
        report.add_title("Results", size=3)
        report.add_table_header(["address", "assertion", "status", "values"])
        addr = make_cell("%x" % results.target)
        status = make_cell(results.get_status(), color=results.color, bold=True)
        vals = ""
        for value in results.values:
            flag = idc.GetFlags(value)
            typ = self.type_to_string(flag)
            vals += "%x type:%s seg:%s fun:%s<br/>" % (value, typ, idc.SegName(value), idc.GetFunctionName(value))
        report.add_table_line([addr, make_cell(cgi.escape(results.query)), status, make_cell(vals)])
        report.end_table()
        data = report.generate()
        self.result_area.setHtml(data) 
Example #2
Source File: IDAMetrics_static.py    From IDAmetrics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_bbl_head(self, head):
        """
        The function returns address of the head instruction
        for the basic block.
        @head - address of arbitrary instruction in the basic block.
        @return - head address of the basic block.
        """

        while 1:
            prev_head = idc.PrevHead(head, 0)
            if isFlow(idc.GetFlags(prev_head)):
                head = prev_head
                if prev_head >= SegEnd(head):
                    raise Exception("Can't identify bbl head")
                continue
            else:
                if prev_head == hex(0xffffffffL):
                    return head
                else:
                    return prev_head
                break 
Example #3
Source File: lib_parser.py    From IDAmetrics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_list_of_function_instr(addr, mode):
    #TODO follow subcalls MODE_INSTRUMENT_SUBCALLS
    f_start = addr
    f_end = idc.FindFuncEnd(addr)
    chunks = enumerate_function_chunks(f_start)
    list_of_addr = list()
    image_base = idaapi.get_imagebase(addr)
    for chunk in chunks:
        for head in idautils.Heads(chunk[0], chunk[1]):
            # If the element is an instruction
            if head == hex(0xffffffffL):
                raise Exception("Invalid head for parsing")
            if isCode(idc.GetFlags(head)):
                head = head - image_base
                head = str(hex(head))
                head = head.replace("L", "")
                head = head.replace("0x", "")
                list_of_addr.append(head)
    return list_of_addr 
Example #4
Source File: util.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def get_symbol_name(from_ea, ea=None, allow_dummy=False):
  if ea is None:
    ea = from_ea

  global _FORCED_NAMES
  if ea in _FORCED_NAMES:
    return _FORCED_NAMES[ea]

  flags = idc.GetFlags(ea)
  if not allow_dummy and idaapi.has_dummy_name(flags):
    return ""

  name = ""
  try:
    name = name or idc.GetTrueNameEx(from_ea, ea)
  except:
    pass

  try:
    name = name or idc.GetFunctionName(ea)
  except:
    pass

  return name 
Example #5
Source File: util.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def is_internal_code(ea):
  if is_invalid_ea(ea):
    return False

  if is_external_segment(ea):
    return False
  
  if is_code(ea):
    return True

  # find stray 0x90 (NOP) bytes in .text that IDA 
  # thinks are data items.
  flags = idc.GetFlags(ea)
  if idaapi.isAlign(flags):
    if not try_mark_as_code(ea):
      return False
    return True

  return False 
Example #6
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def read_bytes_slowly(start, end):
  bytestr = []
  for i in xrange(start, end):
    if idc.hasValue(idc.GetFlags(i)):
      bt = idc.Byte(i)
      bytestr.append(chr(bt))
    else:
      bytestr.append("\x00")
  return "".join(bytestr) 
Example #7
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_code_by_flags(ea):
  if not is_code(ea):
    return False

  flags = idc.GetFlags(ea)
  return idc.isCode(flags) 
Example #8
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def make_xref(from_ea, to_ea, xref_constructor, xref_size):
  """Force the data at `from_ea` to reference the data at `to_ea`."""
  if not idc.GetFlags(to_ea) or is_invalid_ea(to_ea):
    DEBUG("  Not making reference (A) from {:x} to {:x}".format(from_ea, to_ea))
    return

  make_head(from_ea)

  if is_code(from_ea):
    _CREFS_FROM[from_ea].add(to_ea)
    _CREFS_TO[to_ea].add(from_ea)
  else:
    _DREFS_FROM[from_ea].add(to_ea)
    _DREFS_TO[to_ea].add(from_ea)

  # If we can't make a head, then it probably means that we're at the
  # end of the binary, e.g. the last thing in the `.extern` segment.
  if not make_head(from_ea + xref_size):
    assert idc.BADADDR == idc.SegStart(from_ea + xref_size)

  idaapi.do_unknown_range(from_ea, xref_size, idc.DOUNK_EXPAND)
  xref_constructor(from_ea)
  if not is_code_by_flags(from_ea):
    idc.add_dref(from_ea, to_ea, idc.XREF_USER|idc.dr_O)
  else: 
    DEBUG("  Not making reference (B) from {:x} to {:x}".format(from_ea, to_ea)) 
Example #9
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def is_head(ea):
  return idc.isHead(idc.GetFlags(ea))

# Make the data at `ea` into a head. 
Example #10
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def make_head(ea):
  flags = idc.GetFlags(ea)
  if not idc.isHead(flags):
    idc.SetFlags(ea, flags | idc.FF_DATA)
    idaapi.autoWait()
    return is_head(ea)
  return True 
Example #11
Source File: exception.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def make_array(ea, size):
  if ea != idc.BADADDR and ea != 0:
    flags = idc.GetFlags(ea)
    if not idc.isByte(flags) or idc.ItemSize(ea) != 1:
      idc.MakeUnknown(ea, 1, idc.DOUNK_SIMPLE)
      idc.MakeByte(ea)
    idc.MakeArray(ea, size) 
Example #12
Source File: exception.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def find_xrefs(addr):
  lrefs = list(idautils.DataRefsTo(addr))
  if len(lrefs) == 0:
    lrefs = list(idautils.refs(addr, first, next))

  lrefs = [r for r in lrefs if not idc.isCode(idc.GetFlags(r))]
  return lrefs 
Example #13
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fix_code(start_address, end_address):
        # Todo: There might be some data in the range of codes.
        offset = start_address
        while offset <= end_address:
            offset = idc.NextAddr(offset)
            flags = idc.GetFlags(offset)
            if not idc.isCode(flags):
                # Todo: Check should use MakeCode or MakeFunction
                # idc.MakeCode(offset)
                idc.MakeFunction(offset) 
Example #14
Source File: ready_patterns.py    From HRAST with MIT License 5 votes vote down vote up
def rename_struct_field_as_func_name(idx, ctx):
    import idc
    import ida_bytes
    obj = ctx.get_memref('stroff')
    print "%x" % obj.ea
    ti = idaapi.opinfo_t()
    f = idc.GetFlags(obj.ea)
    if idaapi.get_opinfo(obj.ea, 0, f, ti):
        print("tid=%08x - %s" % (ti.tid, idaapi.get_struc_name(ti.tid)))
    print "Offset: {}".format(obj.offset)
    import ida_struct
    obj2 = ctx.get_obj('fcn')
    print "%x" % obj2.addr
    name_str = ida_name.get_name(obj2.addr)
    print "Name {}".format(name_str)
    ida_struct.set_member_name(ida_struct.get_struc(ti.tid), obj.offset, name_str)
    return False




#==============================
# Test case for BindExpr
# So it just saves all condition expressions from
# all if without else
#============================== 
Example #15
Source File: generic_analysis.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def disassemble_new_targets(self, _):
        for value in self.results.values:
            flag = idc.GetFlags(value)
            if not idc.isCode(flag) and idc.isUnknown(flag):
                res = idc.MakeCode(value)
                if res == 0:
                    print "Try disassemble at:"+hex(value)+" KO"
                    # TODO: Rollback ?
                else:
                    print "Try disassemble at:"+hex(value)+" Success !"


# ============================= RESULT WIDGET ===============================
# =========================================================================== 
Example #16
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def fix_vxworks_idb(load_address, vx_version, symbol_table_start, symbol_table_end):
        current_image_base = idaapi.get_imagebase()
        symbol_interval = 16
        if vx_version == 6:
            symbol_interval = 20
        symbol_table_start += load_address
        symbol_table_end += load_address
        ea = symbol_table_start
        shift_address = load_address - current_image_base
        while shift_address >= 0x70000000:
            idaapi.rebase_program(0x70000000, 0x0008)
            shift_address -= 0x70000000
        idaapi.rebase_program(shift_address, 0x0008)
        while ea < symbol_table_end:
            # for VxWorks 6 unknown symbol format
            if idc.Byte(ea + symbol_table_end - 2) == 3:
                ea += symbol_interval
                continue
            offset = 4
            if idaapi.IDA_SDK_VERSION >= 700:
                idc.create_strlit(idc.Dword(ea + offset), idc.BADADDR)
            else:
                idc.MakeStr(idc.Dword(ea + offset), idc.BADADDR)
            sName = idc.GetString(idc.Dword(ea + offset), -1, idc.ASCSTR_C)
            print("Found %s in symbol table" % sName)
            if sName:
                sName_dst = idc.Dword(ea + offset + 4)
                if vx_version == 6:
                    sName_type = idc.Dword(ea + offset + 12)
                else:
                    sName_type = idc.Dword(ea + offset + 8)
                idc.MakeName(sName_dst, sName)
                if sName_type in need_create_function:
                    # flags = idc.GetFlags(ea)
                    print("Start fix Function %s at %s" % (sName, hex(sName_dst)))
                    idc.MakeCode(sName_dst)  # might not need
                    idc.MakeFunction(sName_dst, idc.BADADDR)
            ea += symbol_interval
        print("Fix function by symbol table finish.")
        print("Start IDA auto analysis, depending on the size of the firmware this might take a few minutes.")
        idaapi.autoWait() 
Example #17
Source File: Node.py    From grap with MIT License 4 votes vote down vote up
def __init__(self, ea, info, cs):
        """Initialization function."""
        # Init the node structure
        node_t.__init__(self)

        # Check if it's a code instruction
        try:
            is_c = is_code(get_flags(ea))
        except:
            is_c = isCode(GetFlags(ea))
        if not is_c:
            raise CodeException

        #
        # fill node_t struct
        #

        # NodeInfo
        self.info = NodeInfo()
        inst_elements = []

        try:
            size = create_insn(ea)
            bytes = get_bytes(ea, size)
        except:
            size = MakeCode(ea)
            bytes = GetManyBytes(ea, size)

        (address, size, mnemonic, op_str) = next(cs.disasm_lite(bytes, ea, count=1))
        self.info.opcode = mnemonic

        self.info.inst_str = self.info.opcode + " " + op_str

        splitted = op_str.split(", ")
        self.info.nargs = 0

        if len(splitted) >= 1:
            self.info.arg1 = splitted[0]
            self.info.nargs += 1
            if len(splitted) >= 2:
                self.info.arg2 = splitted[1]
                self.info.nargs += 1
                if len(splitted) >= 3:
                    self.info.arg3 = splitted[2]
                    self.info.nargs += 1

        # No node will be root but this is acceptable for CFGs
        self.info.is_root = False

        self.info.address = ea
        self.info.has_address = True

        # node_t
        self.node_id = self._genid()