Python idc.BADADDR Examples

The following are 30 code examples for showing how to use idc.BADADDR(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module idc , or try the search function .

Example 1
Project: Karta   Author: CheckPointSW   File: ida_api.py    License: 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 2
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: 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 3
Project: heap-viewer   Author: danigargu   File: ptmalloc.py    License: 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 4
Project: mcsema   Author: lifting-bits   File: util.py    License: 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 5
Project: mcsema   Author: lifting-bits   File: exception.py    License: 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 6
Project: mcsema   Author: lifting-bits   File: exception.py    License: 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 7
Project: mcsema   Author: lifting-bits   File: util.py    License: 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 8
Project: DIE   Author: ynvb   File: IDAConnector.py    License: 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 9
Project: DIE   Author: ynvb   File: IDAConnector.py    License: 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 10
Project: DIE   Author: ynvb   File: FunctionViewEx.py    License: 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 11
Project: Sark   Author: tmr232   File: function.py    License: 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 12
Project: ida_kernelcache   Author: bazad   File: ida_utilities.py    License: 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 13
Project: ida_kernelcache   Author: bazad   File: ida_utilities.py    License: 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 14
Project: ida_kernelcache   Author: bazad   File: segment.py    License: 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 15
Project: idataco   Author: jjo-sec   File: calls.py    License: 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 16
Project: idataco   Author: jjo-sec   File: interesting_xor.py    License: 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 17
Project: ActionScript3   Author: KasperskyLab   File: klfdb.py    License: 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
Project: idasec   Author: RobinDavid   File: ida_utils.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _fill_instrs(self):
        cur_addr = self.startEA
        while cur_addr != idc.BADADDR:
            self.instrs.append(cur_addr)
            cur_addr = idc.NextHead(cur_addr, self.endEA) 
Example 19
Project: idasec   Author: RobinDavid   File: static_opaque_analysis.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def serialize(self):
        s = str(self.target_field.text())
        if self.radio_addr.isChecked():
            try:
                int(s, 16)
            except ValueError:
                print "Bad address given"
                return None
        elif self.radio_routine.isChecked():
            addr = idc.LocByName(s)
            if addr == idc.BADADDR:
                print "Bad function name given"
                return None
        return specific_parameters_t() 
Example 20
Project: idasec   Author: RobinDavid   File: static_opaque_analysis.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def run(self):
        # -- GUI stuff
        self.result_widget.set_actions_visible_and_enabled(False)
        self.set_progress_visible(True)
        # -----------

        # Refill the configuration file
        if self.configuration.ksteps != 0 and self.config_widget.radio_path_routine.isChecked():
            self.k = self.configuration.ksteps  # Use the ksteps given if making the path on the whole routine

        self.result_widget.webview.append("### Opaque predicates Detection ###\n")

        self.configuration.analysis_name = "static opaque"
        self.configuration.additional_parameters.typeid = self.configuration.additional_parameters.STANDARD

        target_val = str(self.config_widget.target_field.text())
        start_tps = time.time()
        if self.config_widget.radio_addr.isChecked():
            addr = utils.to_addr(target_val)
            self.process_routine(idaapi.get_func(addr).startEA, pred_addr=addr)
        elif self.config_widget.radio_routine.isChecked():
            addr = idc.LocByName(target_val)
            if addr == idc.BADADDR:
                addr = utils.to_addr(target_val)
            self.process_routine(addr)
        elif self.config_widget.radio_program.isChecked():
            self.process_program()
        else:
            pass

        self.exec_time_total = time.time() - start_tps - self.exec_time_dep
        self.analyse_finished = True
        self.broker.terminate()

        # -- GUI stuff
        self.result_widget.set_actions_visible_and_enabled(True)
        self.set_progress_visible(False)
        # ------------
        self.analysis_terminated() 
Example 21
Project: Karta   Author: CheckPointSW   File: analyzer.py    License: MIT License 5 votes vote down vote up
def __init__(self, logger, num_bits, is_elf, data_fptr_alignment=4, mixed_code_and_data=False):
        """Create the analyzer's base class instance.

        Args:
            logger (logger): logger instance
            num_bits (int): bitness of the CPU (32 bits by default)
            data_fptr_alignment (int, optional): byte alignment needed for global fptrs (4 by default)
            mixed_code_and_data (bool, optional): True iff the main code section includes RO data constants (False by default)
        """
        self.logger = logger
        self._num_bits = num_bits
        self._is_elf = is_elf
        self.data_fptr_alignment = data_fptr_alignment
        self._mixed_code_and_data = mixed_code_and_data
        if num_bits == 64:
            self._address_parse_fn = idc.get_qword
            self._address_make_fn = lambda x: ida_bytes.create_data(x, idc.FF_QWORD, 8, idc.BADADDR)
            self.address_pack_format = "Q"
        elif num_bits == 32:
            self._address_parse_fn = idc.get_wide_dword
            self._address_make_fn = lambda x: ida_bytes.create_data(x, idc.FF_DWORD, 4, idc.BADADDR)
            self.address_pack_format = "L"
        else:
            self._address_parse_fn = idc.get_wide_word
            self._address_make_fn = lambda x: ida_bytes.create_data(x, idc.FF_WORD, 2, idc.BADADDR)
            self.address_pack_format = "H"
        # fields to be linked later on
        self.func_classifier = None
        self.fptr_identifier = None
        self.str_identifier = None
        self.locals_identifier = None
        self.switch_identifier = None
        # code types
        self._active_code_types = list(self.codeTypes()) 
Example 22
Project: idawilli   Author: williballenthin   File: ida_find_ptrs.py    License: Apache License 2.0 5 votes vote down vote up
def find_pointers(start, end):
    for va in range(start, end-0x4):
        ptr = idc.get_wide_dword(va)
        if idc.get_segm_start(ptr) == idc.BADADDR:
            continue

        yield va, ptr 
Example 23
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def export_comments(self):
        """
        Exports all comments in the IDA database as <COMMENT> elements.
        """
        addr = self.min_ea
        if ida_bytes.has_cmt(idc.get_full_flags(addr)) == False:
            addr = ida_bytes.next_that(addr, self.max_ea, ida_bytes.has_cmt)
        if (addr == BADADDR):
            return
        self.update_status(COMMENTS)
        timer = time.clock()
        self.start_element(COMMENTS, True)
        while (addr != BADADDR):
            cmt = idc.get_cmt(addr, False)
            if (cmt != None):
                self.export_comment(addr, "end-of-line", cmt)
            cmt = idc.get_cmt(addr, True)
            if (cmt != None):
                self.export_comment(addr, "repeatable", cmt)
            addr = ida_bytes.next_that(addr, self.max_ea, ida_bytes.has_cmt)
        addr = self.min_ea
        if ida_bytes.has_extra_cmts(idc.get_full_flags(addr)) == False:
            addr = ida_bytes.next_that(
                addr, self.max_ea, ida_bytes.has_extra_cmts)
        while (addr != BADADDR):
            extra = idc.get_extra_cmt(addr, idc.E_PREV)
            if (extra != None):
                self.export_extra_comment(addr, "pre", idc.E_PREV)
            extra = idc.get_extra_cmt(addr, idc.E_NEXT)
            if (extra != None):
                self.export_extra_comment(addr, "post", idc.E_NEXT)
            addr = ida_bytes.next_that(
                addr, self.max_ea, ida_bytes.has_extra_cmts)
        self.export_c_comments()
        self.end_element(COMMENTS)
        self.display_cpu_time(timer) 
Example 24
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def export_markup(self):
        """
        Exports markup for instructions and data items including references
        and manual instructions and operands.
        """
        self.update_status(MARKUP)
        timer = time.clock()
        self.start_element(MARKUP, True)
        addr = self.min_ea
        while addr != BADADDR:
            f = idc.get_full_flags(addr)
            if self.options.MemoryReferences.checked == True:
                if ida_bytes.has_xref(f) == True:
                    self.export_user_memory_reference(addr)
                if ida_bytes.is_off(f, ida_bytes.OPND_ALL) == True:
                    self.export_memory_references(addr)
            if (self.options.Functions.checked == True and
                    self.options.StackReferences.checked == True and
                    ida_bytes.is_stkvar(f, ida_bytes.OPND_ALL) == True):
                self.export_stack_reference(addr)
            if (self.options.DataTypes.checked == True and
                    ida_bytes.is_enum(f, ida_bytes.OPND_ALL) == True):
                self.export_enum_references(addr)
            if self.options.Manual.checked == True:
                # TODO: Ask about OPND_ALL and retrieving additional manual operands
                # if ida_bytes.is_forced_operand(addr, ida_bytes.OPND_ALL) ==
                # True:
                if (ida_bytes.is_forced_operand(addr, 0) == True or
                        ida_bytes.is_forced_operand(addr, 1) == True):
                    self.export_manual_operand(addr)
                if ida_bytes.is_manual_insn(addr) == True:
                    self.export_manual_instruction(addr)
            addr = idc.next_head(addr, self.max_ea)
        self.end_element(MARKUP)
        self.display_cpu_time(timer) 
Example 25
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def export_symbol_table(self):
        """
        Exports user-defined and non-default names as SYMBOL elements.
        """
        addr = self.min_ea
        if ida_bytes.has_any_name(idc.get_full_flags(addr)) == False:
            addr = ida_bytes.next_that(
                addr, self.max_ea, ida_bytes.has_any_name)
        if addr == BADADDR:
            return
        self.update_status(SYMBOL_TABLE)
        self.start_element(SYMBOL_TABLE, True)
        timer = time.clock()
        while addr != BADADDR:
            # only export meaningful names (user and auto)
            f = idc.get_full_flags(addr)
            if (ida_bytes.has_user_name(f) == True or
                    ida_bytes.has_auto_name(f) == True):
                # check for global name
                name = self.get_symbol_name(addr)
                if name != None and len(name) > 0:
                    self.export_symbol(addr, name)
                # check for local name
                if ida_nalt.has_lname(addr):
                    name = idc.get_name(addr, idc.GN_LOCAL)
                    if name != None and len(name) > 0:
                        self.export_symbol(addr, name, 'local')
            # get next address with any name
            addr = ida_bytes.next_that(addr, self.max_ea,
                                       ida_bytes.has_any_name)
        self.end_element(SYMBOL_TABLE)
        self.display_cpu_time(timer) 
Example 26
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def get_address(self, element, attr):
        """
        Returns the address value for an element.

        Args:
            element: XML element object.
            attr: String containing the address attribute name.

        Returns:
            Numeric value representing the address.
        """
        addrstr = element.get(attr)
        if '::' in addrstr:
            # overlayed addresses not currently handled
            return BADADDR
        elif ':' in addrstr:
            [segstr, offset_str] = string.split(addrstr, ':')
            offset = int(offset_str, 16)
            if self.is_int(segstr) == True:
                sgmt = int(segstr, 16)
                addr = (sgmt << 4) + offset
            else:
                # multiple address spaces not currently implemented
                addr = BADADDR
            return addr
        else:
            return int(element.get(attr), 16) 
Example 27
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def import_bookmark(self, bookmark):
        """
        Processes a BOOKMARK element.

        Args:
            bookmark: XML element object containing bookmark data.
        """
        if self.options.Bookmarks.checked == False:
            return
        try:
            addr = self.get_address(bookmark, ADDRESS)
            if self.has_attribute(bookmark, TYPE):
                typ = self.get_attribute(bookmark, TYPE)
            category = ''
            if self.has_attribute(bookmark, CATEGORY):
                category = self.get_attribute(bookmark, CATEGORY)
            description = ''
            if self.has_attribute(bookmark, DESCRIPTION):
                description = self.get_attribute(bookmark, DESCRIPTION)
            if idc.is_mapped(addr) == False:
                msg = ("import_bookmark: address %X not enabled in database"
                       % addr)
                print(msg)
                return
            self.update_counter(BOOKMARK)
            for slot in range(ida_moves.MAX_MARK_SLOT):
                ea = idc.get_bookmark(slot)
                if ea == BADADDR:
                    idc.put_bookmark(addr, 0, 0, 0, slot, description)
                    break
        except:
            msg = "** Exception occurred in import_bookmark **"
            print("\n" + msg + "\n", sys.exc_type, sys.exc_value) 
Example 28
Project: GhIDA   Author: Cisco-Talos   File: idaxml.py    License: Apache License 2.0 5 votes vote down vote up
def import_equate_group(self, equate_group):
        """
        Processes EQUATE_GROUP as IDA enumeration type.

        Args:
            equate_group: XML element containing the group name and
                equate definitions.
        """
        if self.options.DataTypes.checked == False:
            return
        msg = EQUATE_GROUP
        name = ''
        if self.has_attribute(equate_group, NAME):
            name = self.get_attribute(equate_group, NAME)
        bf = ''
        if self.has_attribute(equate_group, BIT_FIELD):
            bf = self.get_attribute(equate_group, BIT_FIELD)
        eid = idc.add_enum(BADADDR, name, ida_bytes.hex_flag())
        idc.set_enum_bf(eid, (bf == 'yes'))
        self.update_counter(EQUATE_GROUP)
        regcmt = equate_group.find(REGULAR_CMT)
        if regcmt != None:
            idc.set_enum_cmt(eid, regcmt.text, False)
            self.update_counter(EQUATE_GROUP + ':' + REGULAR_CMT)
        rptcmt = equate_group.find(REPEATABLE_CMT)
        if rptcmt != None:
            idc.set_enum_cmt(eid, rptcmt.text, True)
            self.update_counter(EQUATE_GROUP + ':' + REPEATABLE_CMT)
        equates = equate_group.findall(EQUATE)
        for equate in equates:
            self.import_equate(equate, eid)
        bit_masks = equate_group.findall(BIT_MASK)
        for bit_mask in bit_masks:
            self.import_bit_mask(bit_mask, eid) 
Example 29
Project: heap-viewer   Author: danigargu   File: ptmalloc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_main_arena():
    main_arena = idc.get_name_ea_simple("main_arena") # from libc6-dbg
    if main_arena != idc.BADADDR:
        return main_arena

    ea = idc.get_segm_start(idc.get_name_ea_simple("_IO_2_1_stdin_"))
    end_ea = idc.get_segm_end(ea)

    # &main_arena->next
    offsets = {
        4: [1088, 1096], # 32 bits
        8: [2152, 2160]  # 64 bits
    }[config.ptr_size]

    if ea == idc.BADADDR or end_ea == idc.BADADDR:
        return None

    while ea < end_ea:
        ptr = config.get_ptr(ea) # ptr to main_arena
        if idaapi.is_loaded(ptr) and ptr < ea:
            if (ea-ptr) in offsets:
                return ptr
        ea += config.ptr_size
    return None

# -------------------------------------------------------------------------- 
Example 30
Project: heap-viewer   Author: danigargu   File: chunk.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_chunk_address(self):
        addr_str = self.t_chunk_addr.text()
        if sys.version_info < (3, 0):
            addr_str = addr_str.encode("utf-8")
        addr = idaapi.str2ea(addr_str)

        if addr == idc.BADADDR:
            return None
        return addr