Python idaapi.BADADDR Examples

The following are 30 code examples of idaapi.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 idaapi , or try the search function .
Example #1
Source File: _interface.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dissolve(cls, flag, typeid, size):
        '''Convert the specified `flag`, `typeid`, and `size` into a pythonic type.'''
        FF_STRUCT = idaapi.FF_STRUCT if hasattr(idaapi, 'FF_STRUCT') else idaapi.FF_STRU
        dt = flag & cls.FF_MASKSIZE
        sf = -1 if flag & idaapi.FF_SIGN == idaapi.FF_SIGN else +1
        if dt == FF_STRUCT and isinstance(typeid, six.integer_types):
            # FIXME: figure out how to fix this recursive module dependency
            t = sys.modules.get('structure', __import__('structure')).by_identifier(typeid)
            sz = t.size
            return t if sz == size else [t, size // sz]
        if dt not in cls.inverted:
            raise internal.exceptions.InvalidTypeOrValueError(u"{:s}.dissolve({!r}, {!r}, {!r}) : Unable to locate a pythonic type that matches the specified flag.".format('.'.join(('internal', __name__, cls.__name__)), dt, typeid, size))

        t, sz = cls.inverted[dt]
        # if the type and size are the same, then it's a string or pointer type
        if not isinstance(sz, six.integer_types):
            count = size // idaapi.get_data_elsize(idaapi.BADADDR, dt, idaapi.opinfo_t())
            return [t, count] if count > 1 else t
        # if the size matches, then we assume it's a single element
        elif sz == size:
            return t, (sz*sf)
        # otherwise it's an array
        return [(t, sz*sf), size // sz] 
Example #2
Source File: core.py    From Sark with MIT License 6 votes vote down vote up
def fix_addresses(start=None, end=None):
    """Set missing addresses to start and end of IDB.

    Take a start and end addresses. If an address is None or `BADADDR`,
    return start or end addresses of the IDB instead.

    Args
        start: Start EA. Use `None` to get IDB start.
        end:  End EA. Use `None` to get IDB end.

    Returns:
        (start, end)
    """
    if start in (None, idaapi.BADADDR):
        start = idaapi.cvar.inf.minEA

    if end in (None, idaapi.BADADDR):
        end = idaapi.cvar.inf.maxEA

    return start, end 
Example #3
Source File: structure.py    From Sark with MIT License 6 votes vote down vote up
def create_struct(name):
    """Create a structure.

    Args:
        name: The structure's name

    Returns:
        The sturct ID

    Raises:
        exceptions.SarkStructAlreadyExists: A struct with the same name already exists
        exceptions.SarkCreationFailed:  Struct creation failed
    """
    sid = idaapi.get_struc_id(name)
    if sid != idaapi.BADADDR:
        # The struct already exists.
        raise exceptions.SarkStructAlreadyExists("A struct names {!r} already exists.".format(name))

    sid = idaapi.add_struc(idaapi.BADADDR, name, 0)
    if sid == idaapi.BADADDR:
        raise exceptions.SarkStructCreationFailed("Struct creation failed.")

    return sid 
Example #4
Source File: ida_integration.py    From lighthouse with MIT License 6 votes vote down vote up
def _uninstall_load_file(self):
        """
        Remove the 'File->Load file->Code coverage file...' menu entry.
        """

        # remove the entry from the File-> menu
        result = idaapi.detach_action_from_menu(
            "File/Load file/",
            self.ACTION_LOAD_FILE
        )
        if not result:
            return False

        # unregister the action
        result = idaapi.unregister_action(self.ACTION_LOAD_FILE)
        if not result:
            return False

        # delete the entry's icon
        idaapi.free_custom_icon(self._icon_id_file)
        self._icon_id_file = idaapi.BADADDR

        logger.info("Uninstalled the 'Code coverage file' menu entry") 
Example #5
Source File: ida_integration.py    From lighthouse with MIT License 6 votes vote down vote up
def _uninstall_load_batch(self):
        """
        Remove the 'File->Load file->Code coverage batch...' menu entry.
        """

        # remove the entry from the File-> menu
        result = idaapi.detach_action_from_menu(
            "File/Load file/",
            self.ACTION_LOAD_BATCH
        )
        if not result:
            return False

        # unregister the action
        result = idaapi.unregister_action(self.ACTION_LOAD_BATCH)
        if not result:
            return False

        # delete the entry's icon
        idaapi.free_custom_icon(self._icon_id_batch)
        self._icon_id_batch = idaapi.BADADDR

        logger.info("Uninstalled the 'Code coverage batch' menu entry") 
Example #6
Source File: ida_integration.py    From lighthouse with MIT License 6 votes vote down vote up
def _uninstall_open_coverage_xref(self):
        """
        Remove the right click 'Coverage Xref' context menu entry.
        """
        self._ui_hooks.unhook()

        # unregister the action
        result = idaapi.unregister_action(self.ACTION_COVERAGE_XREF)
        if not result:
            return False

        # delete the entry's icon
        idaapi.free_custom_icon(self._icon_id_xref)
        self._icon_id_xref = idaapi.BADADDR

        logger.info("Uninstalled the 'Coverage Xref' menu entry") 
Example #7
Source File: structure.py    From Sark with MIT License 6 votes vote down vote up
def get_struct(name):
    """Get a struct by it's name.

    Args:
        name: The name of the struct

    Returns:
        The struct's id

    Raises:
        exceptions.SarkStructNotFound: is the struct does not exist.
    """
    sid = idaapi.get_struc_id(name)
    if sid == idaapi.BADADDR:
        raise exceptions.SarkStructNotFound()

    return sid 
Example #8
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 #9
Source File: CallStackWalk.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def IsPrevInsnCall(ea):
    """
    Given a return address, this function tries to check if previous instruction
    is a CALL instruction
    """
    global CallPattern
    if ea == idaapi.BADADDR or ea < 10:
        return None

    for delta, opcodes in CallPattern:
        # assume caller's ea
        caller = ea + delta
        # get the bytes
        bytes = [x for x in GetDataList(caller, len(opcodes), 1)]
        # do we have a match? is it a call instruction?
        if bytes == opcodes and idaapi.is_call_insn(caller):
            return caller
    return None

# ----------------------------------------------------------------------- 
Example #10
Source File: idautils.py    From dumpDex with Apache License 2.0 6 votes vote down vote up
def StructMembers(sid):
    """
    Get a list of structure members information (or stack vars if given a frame).

    @param sid: ID of the structure.

    @return: List of tuples (offset, name, size)

    @note: If 'sid' does not refer to a valid structure,
           an exception will be raised.
    @note: This will not return 'holes' in structures/stack frames;
           it only returns defined structure members.
    """
    m = idc.GetFirstMember(sid)
    if m == -1:
        raise Exception("No structure with ID: 0x%x" % sid)
    while (m != idaapi.BADADDR):
        name = idc.GetMemberName(sid, m)
        if name:
            yield (m, name, idc.GetMemberSize(sid, m))
        m = idc.GetStrucNextOff(sid, m) 
Example #11
Source File: idautils.py    From dumpDex with Apache License 2.0 6 votes vote down vote up
def Heads(start=None, end=None):
    """
    Get a list of heads (instructions or data)

    @param start: start address (default: inf.minEA)
    @param end:   end address (default: inf.maxEA)

    @return: list of heads between start and end
    """
    if not start: start = idaapi.cvar.inf.minEA
    if not end:   end = idaapi.cvar.inf.maxEA

    ea = start
    if not idc.isHead(idc.GetFlags(ea)):
        ea = idaapi.next_head(ea, end)
    while ea != idaapi.BADADDR:
        yield ea
        ea = idaapi.next_head(ea, end) 
Example #12
Source File: hexrays.py    From bap-ida-python with MIT License 6 votes vote down vote up
def extract_addresses(self):
        '''A set of addresses associated with the line'''
        anchor = idaapi.ctree_anchor_t()
        line = copy(self.widget.line)
        addresses = set()

        while len(line) > 0:
            skipcode_index = idaapi.tag_skipcode(line)
            if skipcode_index == 0:  # No code found
                line = line[1:]  # Skip one character ahead
            else:
                if tag_addrcode(line):
                    addr_tag = int(line[2:skipcode_index], 16)
                    anchor.value = addr_tag
                    if anchor.is_citem_anchor() \
                       and not anchor.is_blkcmt_anchor():
                        address = self.parent.treeitems.at(addr_tag).ea
                        if address != idaapi.BADADDR:
                            addresses.add(address)
                line = line[skipcode_index:]  # Skip the colorcodes
        return addresses 
Example #13
Source File: enumerators.py    From idascripts with MIT License 6 votes vote down vote up
def NotTails(*args):
    """
    Enumerate array items

    @param <range>: see getrange

    @return: list of all not-tails

    Note that NotTails includes all Heads plus all undefined bytes

    """
    (first, last)= getrange(args)

    ea= first
    if ea<last and idaapi.is_tail(idaapi.get_full_flags(ea)):
        ea= idaapi.next_not_tail(ea)
    while ea!=BADADDR and ea<last:
        yield ea
        ea= idaapi.next_not_tail(ea) 
Example #14
Source File: enumerators.py    From idascripts with MIT License 6 votes vote down vote up
def Heads(*args):
    """
    Enumerate array items

    @param <range>: see getrange

    @return: list of all heads

    """
    (first, last)= getrange(args)

    ea= first
    if ea<last and not idaapi.is_head(idaapi.get_full_flags(ea)):
        ea= idaapi.next_head(ea, last)
    while ea!=BADADDR and ea<last:
        yield ea
        ea= idaapi.next_head(ea, last) 
Example #15
Source File: enumerators.py    From idascripts with MIT License 6 votes vote down vote up
def BytesThat(*args):
    """
    Enumerate array items

    @param <range>: see getrange
    @param callable: function which tests the flags

    @return: list of all addresses where callable(GetFlags(ea)) is True

    """
    (first, last)= getrange(args)
    i= getcallablepos(args)
    if i<0:
        raise Exception("missing callable")

    callable= args[i]

    ea= first
    if ea<last and not callable(idaapi.get_full_flags(ea)):
        ea= idaapi.nextthat(ea, last, callable)
    while ea!=BADADDR and ea<last:
        yield ea
        ea= idaapi.nextthat(ea, last, callable) 
Example #16
Source File: enumerators.py    From idascripts with MIT License 6 votes vote down vote up
def Addrs(*args):
    """
    Enumerate all addresses

    @param <range>: see getrange

    @return: list of all addresses in range

    """
    (first, last)= getrange(args)

    # note: problem when using range(...) for ea>=2^31
    # TODO: problem when last == BADADDR
    ea = first
    while ea!=BADADDR and ea<last:
        yield ea
        ea = idc.NextAddr(ea) 
Example #17
Source File: LazyIDA.py    From LazyIDA with MIT License 6 votes vote down vote up
def callback(self, event, *args):
        if event == idaapi.hxe_populating_popup:
            form, phandle, vu = args
            if vu.item.citype == idaapi.VDI_FUNC or (vu.item.citype == idaapi.VDI_EXPR and vu.item.e.is_expr() and vu.item.e.type.is_funcptr()):
                idaapi.attach_action_to_popup(form, phandle, ACTION_HX_REMOVERETTYPE, None)
        elif event == idaapi.hxe_double_click:
            vu, shift_state = args
            # auto jump to target if clicked item is xxx->func();
            if vu.item.citype == idaapi.VDI_EXPR and vu.item.e.is_expr():
                expr = idaapi.tag_remove(vu.item.e.print1(None))
                if "->" in expr:
                    # find target function
                    name = expr.split("->")[-1]
                    addr = idc.get_name_ea_simple(name)
                    if addr == idaapi.BADADDR:
                        # try class::function
                        e = vu.item.e
                        while e.x:
                            e = e.x
                        addr = idc.get_name_ea_simple("%s::%s" % (str(e.type).split()[0], name))

                    if addr != idaapi.BADADDR:
                        idc.jumpto(addr)
                        return 1
        return 0 
Example #18
Source File: LazyIDA.py    From LazyIDA with MIT License 6 votes vote down vote up
def activate(self, ctx):
        if self.action == ACTION_HX_REMOVERETTYPE:
            vdui = idaapi.get_widget_vdui(ctx.widget)
            self.remove_rettype(vdui)
            vdui.refresh_ctext()
        elif self.action == ACTION_HX_COPYEA:
            ea = idaapi.get_screen_ea()
            if ea != idaapi.BADADDR:
                copy_to_clip("0x%X" % ea)
                print("Address 0x%X has been copied to clipboard" % ea)
        elif self.action == ACTION_HX_COPYNAME:
            name = idaapi.get_highlight(idaapi.get_current_viewer())[0]
            if name:
                copy_to_clip(name)
                print("%s has been copied to clipboard" % name)
        elif self.action == ACTION_HX_GOTOCLIP:
            loc = parse_location(clip_text())
            print("Goto location 0x%x" % loc)
            idc.jumpto(loc)
        else:
            return 0

        return 1 
Example #19
Source File: enumeration.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def value(cls, mid, value, **bitmask):
        """Set the `value` for the enumeration `member` belonging to `enum`.

        If the integer `bitmask` is specified, then use it as a bitmask. Otherwise assume all bits are set.
        """
        if not interface.node.is_identifier(mid):
            raise E.MemberNotFoundError(u"{:s}.value({:#x}, {:#x}) : Unable to locate member by the specified identifier.".format('.'.join((__name__, cls.__name__)), mid, value))
        bmask = bitmask.get('bitmask', idaapi.BADADDR & cls.mask(mid))
        return idaapi.set_enum_member_value(mid, value, bmask) 
Example #20
Source File: Stingray.py    From Stingray with GNU General Public License v3.0 5 votes vote down vote up
def find_function_callees( func_ea, maxlvl ):

    callees = []
    visited = set()
    pending = set( (func_ea,) )
    lvl = 0

    while len(pending) > 0:
        func_ea = pending.pop()
        visited.add(func_ea)

        func_name = idc.GetFunctionName(func_ea)
        if not func_name: continue
        callees.append(func_ea)

        func_end = idc.FindFuncEnd(func_ea)
        if func_end == idaapi.BADADDR: continue

        lvl +=1
        if lvl >= maxlvl: continue

        all_refs = set()
        for line in idautils.Heads(func_ea, func_end):

            if not ida_bytes.isCode(get_flags(line)): continue

            ALL_XREFS = 0
            refs = idautils.CodeRefsFrom(line, ALL_XREFS)
            refs = set( filter( lambda x: not (x >= func_ea and x <= func_end), 
                                refs) )
            all_refs |= refs

        all_refs -= visited
        pending |= all_refs

    return callees 
Example #21
Source File: _interface.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def resolve(cls, pythonType):
        '''Convert the provided `pythonType` into IDA's `(flag, typeid, size)`.'''
        struc_flag = idaapi.struflag if idaapi.__version__ < 7.0 else idaapi.stru_flag

        sz, count = None, 1

        # figure out what format pythonType is in
        if isinstance(pythonType, ().__class__):
            (t, sz), count = pythonType, 1
            table = cls.typemap[t]
            flag, typeid = table[abs(sz) if t in {int, long, float, type} else t]

        # an array, which requires us to recurse...
        elif isinstance(pythonType, [].__class__):
            res, count = pythonType
            flag, typeid, sz = cls.resolve(res)

        # if it's a structure, pass it through.
        # FIXME: figure out how to fix this recursive module dependency
        elif isinstance(pythonType, sys.modules.get('structure', __import__('structure')).structure_t):
            flag, typeid, sz = struc_flag(), pythonType.id, pythonType.size

        # default size that we can lookup in the typemap table
        else:
            table = cls.typemap[pythonType]
            flag, typeid = table[None]

            typeid = idaapi.BADADDR if typeid < 0 else typeid
            opinfo = idaapi.opinfo_t()
            opinfo.tid = typeid
            return flag, typeid, idaapi.get_data_elsize(idaapi.BADADDR, flag, opinfo)

        typeid = idaapi.BADADDR if typeid < 0 else typeid
        return flag|(idaapi.FF_SIGN if sz < 0 else 0), typeid, abs(sz)*count 
Example #22
Source File: Stingray.py    From Stingray with GNU General Public License v3.0 5 votes vote down vote up
def find_function_strings( func_ea ):

    end_ea = idc.FindFuncEnd(func_ea)
    if end_ea == idaapi.BADADDR: return

    strings = []
    for line in idautils.Heads(func_ea, end_ea):
        refs = idautils.DataRefsFrom(line)
        for ref in refs:
            try:
                strings.append( String(line, ref) )
            except StringParsingException:
                continue

    return strings 
Example #23
Source File: enumeration.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def by_name(name):
    '''Return the identifier for the enumeration with the given `name`.'''
    res = idaapi.get_enum(utils.string.to(name))
    if res == idaapi.BADADDR:
        raise E.EnumerationNotFoundError(u"{:s}.by_name({!r}) : Unable to locate enumeration by the name \"{:s}\".".format(__name__, name, utils.string.escape(name, '"')))
    return res 
Example #24
Source File: OL_OSX_decryptor.py    From malware-research with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def search_binary(binary_string):
    for i in range(idaapi.get_segm_qty()):
        segm = idaapi.getnseg(i)
        current_ea = segm.startEA
        while True:
            current_ea = idaapi.find_binary(current_ea + 1, segm.endEA, binary_string, 16, idaapi.SEARCH_DOWN)
            if current_ea == idaapi.BADADDR:
                break
            return current_ea
    return 0 
Example #25
Source File: structure.py    From rematch with GNU General Public License v3.0 5 votes vote down vote up
def apply(cls, data):
    struct_id = ida_struct.add_struc(idaapi.BADADDR, data['name'],
                                     data['union'])
    if 'comment' in data and data['comment']:
      ida_struct.set_struc_cmt(struct_id, data['comment'], False)
    if 'repeatable_comment' in data and data['comment']:
      ida_struct.set_struc_cmt(struct_id, data['repeatable_comment'], True)

    if 'members' in data and data['members']:
      struct = ida_struct.get_struc(struct_id)
      for member_idx, member_data in data['members']:
        cls.apply_member(struct, member_data) 
Example #26
Source File: structure.py    From rematch with GNU General Public License v3.0 5 votes vote down vote up
def data(self):
    # if idx is None this is called for the pre-apply data identity validation
    # we'll return None so data will definitely not match
    if self.idx is None:
      return None

    struc_id = ida_struct.get_struc_by_idx(self.idx)
    struct = ida_struct.get_struc(struc_id)

    # Skip TIL structures
    if struct.from_til():
      return None

    # Skip empty structures
    if not struct.memqty:
      return None

    d = {}
    d['name'] = ida_struct.get_struc_name(struc_id)
    d['comment'] = ida_struct.get_struc_cmt(struc_id, False)
    d['repeatable_comment'] = ida_struct.get_struc_cmt(struc_id, False)
    d['size'] = ida_struct.get_struc_size(struct)
    d['union'] = ida_struct.is_union(struc_id)
    # TODO: struct alignment, hidden, listed

    d['members'] = {}
    member_idx = 0
    while member_idx not in (-1, idaapi.BADADDR):
        member = struct.get_member(member_idx)
        d['members'][member_idx] = self.member_data(member)
        member_idx = ida_struct.get_next_member_idx(struct, member.soff)

    return d 
Example #27
Source File: watch.py    From WatchDBG-IDA with MIT License 5 votes vote down vote up
def convertVarName(varstr):
    addr = ida_kernwin.str2ea(varstr)
    if addr != idaapi.BADADDR:
        return addr
    
    return 0 
Example #28
Source File: bap_functions.py    From bap-ida-python with MIT License 5 votes vote down vote up
def add_starts(self, bap):
        syms = []
        for line in bap.syms:
            heappush(syms, int(line, 16))
        for i in range(len(syms)):
            idaapi.add_func(heappop(syms), idaapi.BADADDR)
        idc.Refresh()
        idaapi.refresh_idaview_anyway() 
Example #29
Source File: ida.py    From bap-ida-python with 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))) 
Example #30
Source File: LazyIDA.py    From LazyIDA with MIT License 5 votes vote down vote up
def activate(self, ctx):
        if self.action == ACTION_COPYEA:
            ea = idc.get_screen_ea()
            if ea != idaapi.BADADDR:
                copy_to_clip("0x%X" % ea)
                print("Address 0x%X has been copied to clipboard" % ea)
        elif self.action == ACTION_GOTOCLIP:
            loc = parse_location(clip_text())
            if loc != idaapi.BADADDR:
                print("Goto location 0x%x" % loc)
                idc.jumpto(loc)
        return 1