Python idc.BADADDR Examples

The following are 30 code examples of idc.BADADDR(). 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: interesting_xor.py    From idataco with GNU General Public License v3.0 6 votes vote down vote up
def find_interesting_xors(self):
        next_xor = idc.FindText(idc.MinEA(), idc.SEARCH_DOWN|idc.SEARCH_NEXT, 0, 0, "xor")
        while next_xor != idc.BADADDR:
            if idc.GetOpnd(next_xor, 0) != idc.GetOpnd(next_xor, 1):
                entry = {"func":"", "addr": next_xor, "loop":False, "disasm": idc.GetDisasm(next_xor)}
                func = idaapi.get_func(next_xor)
                if func:
                    entry["func"] = idaapi.get_name(idc.BADADDR, func.startEA)
                    heads = idautils.Heads(next_xor, func.endEA)
                    lxors = []
                    for head in heads:
                        if idc.GetMnem(head).startswith('j'):
                            jmp_addr = idc.GetOperandValue(head,0)
                            if jmp_addr < next_xor and jmp_addr > func.startEA:
                                entry["loop"] = True
                                break
                self._interesting_xors.append(entry)
            next_xor = idc.FindText(idc.NextHead(next_xor), idc.SEARCH_DOWN|idc.SEARCH_NEXT, 0, 0, "xor") 
Example #2
Source File: ida_utilities.py    From ida_kernelcache with MIT License 6 votes vote down vote up
def get_ea_name(ea, fromaddr=idc.BADADDR, true=False, user=False):
    """Get the name of an address.

    This function returns the name associated with the byte at the specified address.

    Arguments:
        ea: The linear address whose name to find.

    Options:
        fromaddr: The referring address. Default is BADADDR. Some addresses have a
            location-specific name (for example, labels within a function). If fromaddr is not
            BADADDR, then this function will try to retrieve the name of ea from fromaddr's
            perspective. The global name will be returned if no location-specific name is found.
        true: Retrieve the true name rather than the display name. Default is False.
        user: Return "" if the name is not a user name.

    Returns:
        The name of the address or "".
    """
    if user and not idc.hasUserName(idc.GetFlags(ea)):
        return ""
    if true:
        return idc.GetTrueNameEx(fromaddr, ea)
    else:
        return idc.NameEx(fromaddr, ea) 
Example #3
Source File: util.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def read_leb128(ea, signed):
  """ Read LEB128 encoded data
  """
  val = 0
  shift = 0
  while True:
    byte = idc.Byte(ea)
    val |= (byte & 0x7F) << shift
    shift += 7
    ea += 1
    if (byte & 0x80) == 0:
      break

    if shift > 64:
      DEBUG("Bad leb128 encoding at {0:x}".format(ea - shift/7))
      return idc.BADADDR

  if signed and (byte & 0x40):
    val -= (1<<shift)
  return val, ea 
Example #4
Source File: segment.py    From ida_kernelcache with 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 #5
Source File: ida_utilities.py    From ida_kernelcache with MIT License 6 votes vote down vote up
def get_name_ea(name, fromaddr=idc.BADADDR):
    """Get the address of a name.

    This function returns the linear address associated with the given name.

    Arguments:
        name: The name to look up.

    Options:
        fromaddr: The referring address. Default is BADADDR. Some addresses have a
            location-specific name (for example, labels within a function). If fromaddr is not
            BADADDR, then this function will try to retrieve the address of the name from
            fromaddr's perspective. If name is not a local name, its address as a global name will
            be returned.

    Returns:
        The address of the name or BADADDR.
    """
    return idc.LocByNameEx(fromaddr, name) 
Example #6
Source File: ptmalloc.py    From heap-viewer with GNU General Public License v3.0 6 votes vote down vote up
def find_malloc_par():
    mp_ = idc.get_name_ea_simple("mp_")
    if mp_ != idc.BADADDR:
        return mp_

    segm = idaapi.get_segm_by_name("[heap]")
    if segm is None:
        return None

    offset = get_struct_offsets(malloc_par()).get('sbrk_base')
    sbrk_base = segm.start_ea
    ea = idc.get_segm_start(get_name_ea_simple("_IO_2_1_stdin_"))
    end_ea = idc.get_segm_end(ea)

    while ea < end_ea:
        ptr = config.get_ptr(ea)
        if idaapi.is_loaded(ptr) and ptr == sbrk_base:
            return (ea-offset)
        ea += config.ptr_size

    return None

# -------------------------------------------------------------------------- 
Example #7
Source File: exception.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def format_lsda_actions(action_tbl, act_ea, type_addr, type_enc, act_id):
  """ Recover the exception actions and type info
  """
  action_list = []
  if action_tbl == idc.BADADDR:
    return

  DEBUG("start action ea : {:x}".format(act_ea))
  while True:
    ar_filter,ea2 = read_enc_value(act_ea, DW_EH_PE_sleb128)
    ar_disp,  ea3 = read_enc_value(ea2, DW_EH_PE_sleb128)
  
    if ar_filter > 0:
      type_slot = type_addr - ar_filter * enc_size(type_enc)
      type_ea, eatmp = read_enc_value(type_slot, type_enc)
      DEBUG("catch type typeinfo = {:x} {} {}".format(type_ea, get_symbol_name(type_ea), ar_filter))
      action_list.append((ar_disp, ar_filter, type_ea))

    #DEBUG(" format_lsda_actions ea {:x}: ar_disp[{}]: {} ({:x})".format(act_ea, act_id, ar_disp, ar_filter))
    if ar_disp == 0:
      break

    act_ea = ea2 + ar_disp

  return action_list 
Example #8
Source File: calls.py    From idataco with GNU General Public License v3.0 6 votes vote down vote up
def markupCategories(self):
        checked = []
        last_ea = idc.BADADDR
        for cat, cb in self._checkbox_map.items():
            if cb.isChecked():
                checked.append(cat)
        for i in range(self._call_table.rowCount()):
            if self._call_table.item(i, 0).text() in checked:
                markup_ea = int(self._call_table.item(i, 1).text(), 16)
                if markup_ea and markup_ea != idc.BADADDR and markup_ea != last_ea and markup_ea not in self._marked_up:
                    last_ea = markup_ea
                    self.markupEa(markup_ea)
                    api_name = self._call_table.item(i, 3).text()
                    args = self._call_table.item(i, 6).text()
                    self.addposterior(markup_ea, api_name, args)
                    self._marked_up.add(markup_ea)
                    if self.parent.cuckoo_version.startswith("1.3"):
                        try:
                            markup_parent_ea = int(self._call_table.item(i, 2).text(), 16)
                            self.markupEa(markup_parent_ea)
                            self._marked_up.add(markup_parent_ea)
                        except ValueError:
                            pass 
Example #9
Source File: exception.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def get_typeinfo_refs(name, ea):
  if ea == idc.BADADDR:
    return

  ea2 = ea
  if idaapi.is_spec_ea(ea2):
    xrefs = find_xrefs(ea2)
    ea2 += get_address_size_in_bytes()*2
    xrefs.extend(find_xrefs(ea2))
  else:
    ea2 += get_address_size_in_bytes()*2
    xrefs = find_xrefs(ea2)

  for x in xrefs:
    if not is_invalid_ea(x):
      value = read_pointer(x)
      offset = value - ea if value > ea else 0
      RTTI_REFERENCE_TABLE[x] = _create_reference_object(name, ea, offset)
      ea3 = get_si_type_info(x) 
Example #10
Source File: function.py    From Sark with MIT License 6 votes vote down vote up
def __init__(self, ea=UseCurrentAddress, name=None):
        if name is not None and ea != self.UseCurrentAddress:
            raise ValueError(("Either supply a name or an address (ea). "
                              "Not both. (ea={!r}, name={!r})").format(ea, name))

        elif name is not None:
            ea = idc.get_name_ea_simple(name)
            if ea == idc.BADADDR:
                raise exceptions.SarkNoFunction(
                    "The supplied name does not belong to an existing function. "
                    "(name = {!r})".format(name))

        elif ea == self.UseCurrentAddress:
            ea = idc.here()

        elif ea is None:
            raise ValueError("`None` is not a valid address. To use the current screen ea, "
                             "use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`.")

        elif isinstance(ea, Line):
            ea = ea.ea
        self._func = get_func(ea)
        self._comments = Comments(self) 
Example #11
Source File: FunctionViewEx.py    From DIE with MIT License 6 votes vote down vote up
def itemDoubleClickSlot(self, index):
        """
        TreeView DoubleClicked Slot.
        @param index: QModelIndex object of the clicked tree index item.
        @return:
        """
        function = index.data(role=DIE.UI.Function_Role)
        if function is not None:

            ea = function.function_start
            if function.is_lib_func:
                ea = function.proto_ea

            if ea is not None and ea is not idc.BADADDR:
                idc.Jump(ea)
                return True

        func_context = index.data(role=DIE.UI.FunctionContext_Role)
        if func_context is not None:
            ea = func_context.calling_ea
            if ea is not None and ea is not idc.BADADDR:
                idc.Jump(ea)
                return True 
Example #12
Source File: util.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def read_leb128(ea, signed):
  """ Read LEB128 encoded data
  """
  val = 0
  shift = 0
  while True:
    byte = idc.get_wide_byte(ea)
    val |= (byte & 0x7F) << shift
    shift += 7
    ea += 1
    if (byte & 0x80) == 0:
      break

    if shift > 64:
      DEBUG("Bad leb128 encoding at {0:x}".format(ea - shift/7))
      return idc.BADADDR

  if signed and (byte & 0x40):
    val -= (1<<shift)
  return val, ea 
Example #13
Source File: idaxml.py    From GhIDA with Apache License 2.0 6 votes vote down vote up
def export_bookmarks(self):
        """
        Exports marked location descriptions as BOOKMARK elements.
        """
        found = False
        timer = time.clock()
        for slot in range(0, 1025):
            address = idc.get_bookmark(slot)
            description = idc.get_bookmark_desc(slot)
            if address == BADADDR:
                continue
            if description == None:
                continue
            if found == False:
                found = True
                self.update_status(BOOKMARKS)
                self.start_element(BOOKMARKS, True)
            self.start_element(BOOKMARK)
            self.write_address_attribute(ADDRESS, address)
            self.write_attribute(DESCRIPTION, description)
            self.close_tag()
        if found:
            self.end_element(BOOKMARKS)
            self.display_cpu_time(timer) 
Example #14
Source File: IDAConnector.py    From DIE with MIT License 6 votes vote down vote up
def get_function_end_address(ea):
    """
    Get function end address
    @param ea: function start_ea.
    @return: The function end ea. If no function end ea found returns None.
    """
    try:
        if ea is None:
            return None

        func_attr_end = idc.GetFunctionAttr(ea, idc.FUNCATTR_END)
        if func_attr_end == idc.BADADDR:
            return None

        return idc.PrevHead(func_attr_end, ea)

    except Exception as ex:
        raise RuntimeError("Count not locate end address for function %s: %s" % (hex(ea), ex)) 
Example #15
Source File: IDAConnector.py    From DIE with MIT License 6 votes vote down vote up
def get_function_start_address(ea):
    """
    Get function start address
    @param ea: ea from within the function boundaries.
    @return: The function start ea. If function start was not found return current ea.
    """
    try:
        if ea is None:
            return None

        start_adrs = idc.GetFunctionAttr(ea, idc.FUNCATTR_START)
        if start_adrs != idc.BADADDR:
            return start_adrs

        return ea

    except Exception as ex:
        raise RuntimeError("Count not locate start address for function %s: %s" % (hex(ea), ex)) 
Example #16
Source File: ida_api.py    From Karta with MIT License 6 votes vote down vote up
def findImmediate(self, range_start, range_end, value):
        """Return all of the places (in the range) in which the immediate value was found.

        Args:
            range_start (int): ea of the range's start
            range_end (int): ea of the range's end
            value (int): value of the searched immediate

        Return Value:
            collection of ea's in which the value was found
        """
        search_pos = range_start
        while search_pos < range_end:
            match_ea, garbage = ida_search.find_imm(search_pos, idc.SEARCH_DOWN, value)
            search_pos = match_ea + 1
            # Filter out mismatches
            if match_ea == idc.BADADDR:
                break
            # return the correct result to the caller
            yield match_ea

    # Overridden base function 
Example #17
Source File: klfdb.py    From ActionScript3 with GNU General Public License v3.0 6 votes vote down vote up
def find_functions(self):

		code_start = get_segm_by_name(".text").start_ea
		code_end = get_segm_by_name(".text").end_ea
		
		for name in self.signatures:
		
			found = False
			for sig in self.signatures[name]:
				
				pos = find_binary(code_start, code_end, sig, 16, SEARCH_DOWN)
		
				if (pos != idc.BADADDR):
					set_name(pos, name, SN_NOCHECK | SN_NOWARN | SN_FORCE)
					found = True
					break
		
			if (not found):
				print('Failed to find signature of "%s"' % name)
				return False
		
		return True 
Example #18
Source File: 16_输入与输出.py    From IDAPython_Note with MIT License 5 votes vote down vote up
def checkBounds(self):
        if self.start is idc.BADADDR or self.end is idc.BADADDR:
            self.status = False 
Example #19
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getMinorDispatchTableAddress(ea):
    """find address of last lea in function"""
    start = idc.get_func_attr(ea, idc.FUNCATTR_START)
    end = idc.prev_head( idc.get_func_attr(ea, idc.FUNCATTR_END), start)
    res = prevMnemonic(end, 'lea', start)
    assert res != idc.BADADDR
    return idc.get_operand_value(res, 1) 
Example #20
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prevMnemonic(ea, mnem, minaddr=0):
    res = idc.print_insn_mnem(ea)
    #print "%x -> %s"% (ea, res)
    if res == "": return idc.BADADDR
    if res == mnem: return ea
    return prevMnemonic( idc.prev_head(ea, minaddr), mnem, minaddr ) 
Example #21
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fix_ascii(self, address):
        string_table_start_address = self.get_string_table_start_address(address)
        string_address = string_table_start_address
        while True:
            if string_address:
                print("Start Make string at address: %s" % hex(string_address))
                if idaapi.IDA_SDK_VERSION >= 700:
                    idc.create_strlit(string_address, idc.BADADDR)
                else:
                    idc.MakeStr(string_address, idc.BADADDR)
                string_address = self.get_next_ascii_string_address(string_address)
            else:
                break 
Example #22
Source File: quicktime.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getMajorDispatchTableAddress():
    """find quicktime major dispatch table"""
    res = idc.get_name_ea_simple('theQuickTimeDispatcher')
    res = nextMnemonic(res, 'lea', idc.get_func_attr(res, idc.FUNCATTR_END))
    assert res != idc.BADADDR
    return idc.get_operand_value(res, 1) 
Example #23
Source File: custom.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
def resolve_expr(self, expr):
        res = None
        try:
            expr = re.sub(r'[(|)]', '', expr)
            res = int(expr, 16)
        except ValueError:
            segm = idaapi.get_segm_by_name(expr)
            if segm:
                res = segm.start_ea
            else:
                ea = idaapi.str2ea(expr)
                if ea != idc.BADADDR:
                    res = ea
        return res 
Example #24
Source File: stack.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
def reload_info(self):
        if not dbg.is_process_suspended():
            return False

        base_addr = None
        if self.base_expr is None:
            base_addr = idc.get_reg_value(dbg.registers.stack)
        else:
            base_addr = idaapi.str2ea(self.base_expr)
            if base_addr == idc.BADADDR:
                idaapi.warning("Invalid base expr: %s" % self.base_expr)
                return False

            if not idaapi.is_loaded(base_addr):
                idaapi.warning("Memory address is not loaded: $#x" % base_addr)
                return False

        self.ClearLines()
        dbg.set_thread_info()

        try:
            segm_end = idc.get_segm_end(base_addr)
            n_entries = config.n_stack_entries or ((segm_end-base_addr) // dbg.ptr_size)

            for i in range(n_entries):
                offset = i * dbg.ptr_size
                ptr = base_addr + offset

                if not idaapi.is_loaded(ptr):
                    break

                value = dbg.get_ptr(ptr)
                self.add_line("%02d:%04X  %s" % (i, offset, self.parse_value(ptr)))

        except Exception as e:
            idaapi.warning(str(e))
            return False
        return True 
Example #25
Source File: Main.py    From Virtuailor with GNU General Public License v3.0 5 votes vote down vote up
def add_bp_to_virtual_calls(cur_addr, end):
    while cur_addr < end:
        if cur_addr == idc.BADADDR:
            break
        elif idc.print_insn_mnem(cur_addr) == 'call' or idc.print_insn_mnem(cur_addr) == 'BLR':
            if True in [idc.print_operand(cur_addr, 0).find(reg) != -1 for reg in REGISTERS]:  # idc.GetOpnd(cur_addr, 0) in REGISTERS:
                cond, bp_address = vtableAddress.write_vtable2file(cur_addr)
                if cond != '':
                    bp_vtable = AddBP.add(bp_address, cond)
        cur_addr = idc.next_head(cur_addr) 
Example #26
Source File: symbol_exec.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def symbolic_exec():
    from miasm.ir.symbexec import SymbolicExecutionEngine
    from miasm.core.bin_stream_ida import bin_stream_ida

    from utils import guess_machine

    start, end = idc.read_selection_start(), idc.read_selection_end()

    bs = bin_stream_ida()
    machine = guess_machine(addr=start)

    mdis = machine.dis_engine(bs)

    if start == idc.BADADDR and end == idc.BADADDR:
        start = idc.get_screen_ea()
        end = idc.next_head(start) # Get next instruction address

    mdis.dont_dis = [end]
    asmcfg = mdis.dis_multiblock(start)
    ira = machine.ira(loc_db=mdis.loc_db)
    ircfg = ira.new_ircfg_from_asmcfg(asmcfg)

    print("Run symbolic execution...")
    sb = SymbolicExecutionEngine(ira, machine.mn.regs.regs_init)
    sb.run_at(ircfg, start)
    modified = {}

    for dst, src in sb.modified(init_state=machine.mn.regs.regs_init):
        modified[dst] = src

    view = symbolicexec_t()
    all_views.append(view)
    if not view.Create(modified, machine, mdis.loc_db,
                       "Symbolic Execution - 0x%x to 0x%x"
                       % (start, idc.prev_head(end))):
        return

    view.Show()


# Support ida 6.9 and ida 7 
Example #27
Source File: internal.py    From ida_kernelcache with MIT License 5 votes vote down vote up
def make_name_generator(suffix, max_count=999999):
    """Create a unique name generator using the specified template factory."""
    next_index_dict = defaultdict(lambda: 1)
    def get_next(name):
        assert name, 'Invalid symbol name passed to name generator'
        assert suffix not in name, 'Symbol name passed to name generator already contains suffix'
        template = name + suffix
        for index in xrange(next_index_dict[name], max_count):
            new_name = template + str(index)
            if idau.get_name_ea(new_name) == idc.BADADDR:
                next_index_dict[name] = index
                return new_name
        new_index_dict[name] = max_count
        return None
    return get_next 
Example #28
Source File: get_cfg.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def find_main_in_ELF_file():
  """Tries to automatically find the `main` function if we haven't found it
  yet. IDA recognizes the pattern of `_start` calling `__libc_start_main` in
  ELF binaries, where one of the parameters is the `main` function. IDA will
  helpfully comment it as such."""

  start_ea = idc.get_name_ea_simple("_start")
  if is_invalid_ea(start_ea):
    start_ea = idc.get_name_ea_simple("start")
    if is_invalid_ea(start_ea):
      return idc.BADADDR

  for begin_ea, end_ea in idautils.Chunks(start_ea):
    for inst_ea in Heads(begin_ea, end_ea):
      comment = idc.GetCommentEx(inst_ea, 0)
      if comment and "main" in comment:
        for main_ea in xrefs_from(inst_ea):
          if not is_code(main_ea):
            continue

          # Sometimes the `main` function isn't identified as code. This comes
          # up when there are some alignment bytes in front of `main`.
          try_mark_as_code(main_ea)
          if is_code_by_flags(main_ea):
            try_mark_as_function(main_ea)

          main = idaapi.get_func(main_ea)
          if not main:
            continue

          if main and main.start_ea == main_ea:
            set_symbol_name(main_ea, "main")
            DEBUG("Found main at {:x}".format(main_ea))
            return main_ea

  return idc.BADADDR 
Example #29
Source File: get_cfg.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def try_get_thunk_name(ea):
  """Try to figure out if a function is actually a thunk, i.e. a function
  that represents a 'local' definition for an external function. Thunks work
  by having the local function jump through a function pointer that is
  resolved at runtime."""
  global _ELF_THUNKS, _NOT_ELF_THUNKS, _INVALID_THUNK

  if ea in _ELF_THUNKS:
    return _ELF_THUNKS[ea]

  if ea in _NOT_ELF_THUNKS:
    _NOT_ELF_THUNKS.add(ea)
    return _INVALID_THUNK

  # Try two approaches to detecting whether or not
  # something is a thunk.
  is_thunk = False
  target_ea = idc.BADADDR
  if IS_ELF:
    is_thunk, target_ea = is_ELF_thunk_by_structure(ea)

  if not is_thunk:
    is_thunk, target_ea = is_thunk_by_flags(ea)
  
  if not is_thunk:
    _NOT_ELF_THUNKS.add(ea)
    return _INVALID_THUNK

  else:
    name = get_function_name(target_ea)
    name = undecorate_external_name(name)
    name = get_true_external_name(name)
    ret = (is_thunk, target_ea, name)
    _ELF_THUNKS[ea] = ret
    return ret 
Example #30
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)