Python idaapi.get_inf_structure() Examples

The following are 30 code examples of idaapi.get_inf_structure(). 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: Util.py    From VMAttack with MIT License 6 votes vote down vote up
def get_arch_dynamic():
    """
    Determine the execution environments architecture.
    :return: 'x64' or 'x86' if arch could be determined, else None
    """
    info = idaapi.get_inf_structure()
    if info.is_64bit():
        return 64
    elif info.is_32bit():
        return 32
    else:
        env = idaapi.dbg_get_registers()
        if env[17][0] == 'RAX':
            return 64
        elif env[17][0] == 'EAX':
            return 32
        else:
            return None


###############################
# LIB DETECTION FUNCTIONALITY #
############################### 
Example #2
Source File: mkyara_plugin.py    From mkYARA with GNU General Public License v3.0 6 votes vote down vote up
def get_arch_info():
    info = idaapi.get_inf_structure()
    proc = info.procName.lower()
    bits = get_inf_structure_bitness(info)
    instruction_set = None
    instruction_mode = None

    if proc == 'metapc':
        instruction_set = CS_ARCH_X86
        if bits == 16:
            instruction_mode = CS_MODE_16
        elif bits == 32:
            instruction_mode = CS_MODE_32
        elif bits == 64:
            instruction_mode = CS_MODE_64
    return instruction_set, instruction_mode 
Example #3
Source File: payload.py    From DrGadget with MIT License 6 votes vote down vote up
def __init__(self):      
        self.flags = idaapi.ph_get_flag()
        # instead of checking ph flags, should __EA64__ be used?
        self.is_64bit = (self.flags & idaapi.PR_USE64) != 0
        self.is_32bit = (self.flags & idaapi.PR_USE32) != 0
        self.is_stack_up = (self.flags & idaapi.PR_STACK_UP) != 0
        self.id = idaapi.ph_get_id()
        self.is_assemble_supported = (self.flags & idaapi.PR_ASSEMBLE) != 0
        self.is_delayslot_proc = (self.flags & idaapi.PR_DELAYED) != 0
        
        # processor default ret instruction (icode, not opcode!)
        self.ret_icodes = [idaapi.ph_get_icode_return()]

        # ptrsize in bytes
        self.ptrsize = 2
        if self.is_32bit:
            self.ptrsize = 4
        if self.is_64bit:
            self.ptrsize = 8

        self.ptrsize_pyfmt_mapper = {2:"H", 4:"I", 8:"Q"}        
        self.ptrsize_mask_mapper = {2:0xFFFF, 4:0xFFFFFFFF, 8:0xFFFFFFFFFFFFFFFF}
        self.datafmt_mapper = {2:"%04X", 4:"%08X", 8:"%016X"}
        self.endianness = idaapi.get_inf_structure().mf 
Example #4
Source File: IDAConnector.py    From DIE with MIT License 6 votes vote down vote up
def get_native_size():
    """
    Get the native OS size
    @return: 16, 32, 64 value indicating the native size or None if failed.
    """
    try:
        inf = idaapi.get_inf_structure()
        if inf.is_32bit():
            return 32
        elif inf.is_64bit():
            return 64
        else:
            # Native size is neither 32 or 64 bit. assuming 16 bit.
            return 16

    except Exception as ex:
        raise RuntimeError("Could not Could not retrieve native OS size: %s" %ex) 
Example #5
Source File: dbg.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
def initialize():
    if m.initialized:
        return
        
    info = idaapi.get_inf_structure()
    if info.is_64bit():
        m.ptr_size = 8
        m.get_ptr = idc.get_qword
        m.mem_fmt = "%016X"
        m.pack_fmt = "<Q"
    elif info.is_32bit():
        m.ptr_size = 4
        m.get_ptr = idc.get_wide_dword
        m.mem_fmt = "%08X"
        m.pack_fmt = "<L"

    m.cpu_name = info.procname.lower()
    m.is_be = idaapi.cvar.inf.is_be()
    m.filetype = info.filetype
    m.is_pefile = (m.filetype == idaapi.f_PE)
    m.thread_id = idaapi.get_current_thread()

    if m.cpu_name == "metapc":
        m.registers = {
            4: regs.x86,
            8: regs.x64
        }[m.ptr_size]

    elif m.cpu_name.startswith("arm"):
        m.registers = {
            4: regs.arm,
            8: regs.aarch64
        }[m.ptr_size]
    elif m.cpu_name.startswith("mips"):
        m.registers = regs.mips

    m.initialized = True

# ----------------------------------------------------------------------- 
Example #6
Source File: dbg.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
def supported_cpu():
    info = idaapi.get_inf_structure()
    cpuname = info.procname.lower()
    if cpuname == "metapc" or cpuname.startswith("arm") or cpuname.startswith("mips"):
        return True
    return False 
Example #7
Source File: dbg.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
def get_hardware_info():
    is_be = idaapi.cvar.inf.mf
    info = idaapi.get_inf_structure()
    cpuname = info.procname.lower()
    #TODO 
Example #8
Source File: dbg.py    From deREferencing with GNU General Public License v3.0 5 votes vote down vote up
def get_ptrsize():
    info = idaapi.get_inf_structure()
    ptr_size = None
    if info.is_64bit():
        ptr_size = 8
    elif info.is_32bit():
        ptr_size = 4
    return ptr_size 
Example #9
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBitness(self):
        # https://reverseengineering.stackexchange.com/a/11398
        bits = None
        info = idaapi.get_inf_structure()
        if info.is_64bit():
            bits = 64
        elif info.is_32bit():
            bits = 32
        else:
            bits = 16
        return bits 
Example #10
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getArchitecture(self):
        # https://reverseengineering.stackexchange.com/a/11398
        info = idaapi.get_inf_structure()
        procname = info.procName
        if procname in self._processor_map:
            return self._processor_map[procname]
        else:
            raise ValueError("Unsupported Architecture") 
Example #11
Source File: objc2_xrefs_helper.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def detect_arch():
    #heuristically determine what architecture we're on
    #only x86-64 and arm64 are supported
    is_le=False
    bits=0
    info = get_inf_structure()
    arch=ARCH_UNKNOWN
    if info.is_64bit():
        bits=64
    elif info.is_32bit():
        bits=32
    else:
        bits=16

    if not info.is_be():
        is_le=True

    procname=info.procName
    if bits==64 and is_le:
        if procname=="ARM":
            Message("Detected architecture: arm64\n")
            arch=ARCH_ARM64
        elif procname=="metapc":
            Message("Detected architecture: x86_64\n")
            arch=ARCH_X86_64

    return arch 
Example #12
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getBitness(self):
        # https://reverseengineering.stackexchange.com/a/11398
        bits = None
        info = ida_idaapi.get_inf_structure()
        if info.is_64bit():
            bits = 64
        elif info.is_32bit():
            bits = 32
        else:
            bits = 16
        return bits 
Example #13
Source File: IdaInterface.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getArchitecture(self):
        # https://reverseengineering.stackexchange.com/a/11398
        info = ida_idaapi.get_inf_structure()
        procname = info.procName
        if procname in self._processor_map:
            return self._processor_map[procname]
        else:
            raise ValueError("Unsupported Architecture") 
Example #14
Source File: drop.py    From DROP-IDA-plugin with GNU General Public License v3.0 5 votes vote down vote up
def database_inited(self, is_new_db, idc_script):
        # A file was loaded, reset vars
        self.plugin.filename = idaapi.get_input_file_path()
        self.plugin.cfg = None
        self.plugin.angr_proj = None
        self.plugin.global_vars = None
        self.plugin.opaque_predicates = dict()
        self.plugin.extra_constraints = dict()
        self.plugin.symbolic_vars = dict()

        # Check if it (still) exists
        if not isfile(self.plugin.filename):
            print("### Drop error: original input file no longer exists, unable to load it into angr. ###")
            return

        # Load the file into angr
        try:
            # This is a bit inefficient, but figure out if it's PIC by loading twice
            p = angr.Project(self.plugin.filename, load_options={'auto_load_libs': False})
            if p.loader.main_bin.pic:
                # Load with IDA's imagebase as base_addr
                base_addr = idaapi.get_imagebase()
            else:
                # Load with 0 as base_addr
                base_addr = 0
            del p
            self.plugin.angr_proj = angr.Project(self.plugin.filename,
                load_options={'auto_load_libs': False, 'main_opts': {
                    'custom_base_addr': base_addr}})

            # get and store the file bitness
            # Don't use idaapi.get_inf_structure().is_32bit(), it will give True for MIPS64...
            self.plugin.bitness = self.plugin.angr_proj.arch.bits

            # Save the list of all recognized variables in .bss, .data and .rodata (TODO: why these? any others?)
            # TODO: Other segments as well?
            self.plugin.global_vars = [var for s in sark.segments() for var in get_segment_names(s) if s.name in [".bss", ".data", ".rodata"]]
            print("### Loaded file into angr succesfully! ###")
        except:
            import traceback
            print("ERROR: Failed to load file into angr: {}".format(traceback.format_exc())) 
Example #15
Source File: mykutils.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def get_bitness():
    """Get the architecture bit width of this IDB."""
    inf = idaapi.get_inf_structure()
    return 64 if inf.is_64bit() else 32 if inf.is_32bit() else 16 
Example #16
Source File: ui.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def graphview(cls):
        '''Returns true if the current function is being viewed in graph view mode.'''
        res = idaapi.get_inf_structure()
        if idaapi.__version__ < 7.0:
            return res.graph_view != 0
        return res.is_graph_view() 
Example #17
Source File: _interface.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __bounds__(cls):
        info = idaapi.get_inf_structure()
        return info.minEA, info.maxEA 
Example #18
Source File: code_grafter.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def __init__(self, cpu=None, bits=None):
        self.cpu = cpu or idaapi.get_inf_structure().procname
        self.bits = bits or mykutils.get_bitness()

        self._emu_stubs = {
            ('IsDebuggerPresent',): self.get_fnbytes('retn0'),
            ('InitializeCriticalSection', 'EnterCriticalSection',
             'LeaveCriticalSection', 'DeleteCriticalSection',
             'EncodePointer', 'DecodePointer'):
                self.get_fnbytes('retn0_1arg'),
            ('FlsSetValue', '___acrt_FlsSetValue@8'):
                self.get_fnbytes('retn1_2arg'),
            ('FlsGetValue', '___acrt_FlsGetValue@4'):
                self.get_fnbytes('retn1_1arg'),
            ('setlocale', '_setlocale', '__setlocale'):
                self.get_fnbytes('setlocale'),
            ('wsetlocale', '_wsetlocale', '__wsetlocale',):
                self.get_fnbytes('wsetlocale'),
            ('GetLastError',): self.get_fnbytes('retn0'),
            ('SetLastError',): self.get_fnbytes('retn0_1arg'),
            ('CreateThread',): self.get_fnbytes('retn1_6arg'),
            ('free', '_free', '??3@YAXPAX@Z'): self.get_fnbytes('retn0'),
            ('HeapFree',): self.get_fnbytes('retn0_3arg'),
            ('strcpy', '_strcpy'): self.get_fnbytes('strcpy'),
            ('strlen',): self.get_fnbytes('strlen'),
            ('lstrlenA',): self.get_fnbytes('strlen'),
            ('memcpy', '_memcpy'): self.get_fnbytes('memcpy'),
            ('memset', '_memset'): self.get_fnbytes('memset'),
        } 
Example #19
Source File: _interface.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __newprc__(cls, pnum):
        info = idaapi.get_inf_structure()
        bits = 64 if info.is_64bit() else 32 if info.is_32bit() else None
        if bits is None: return

        typemap.integermap[None] = typemap.integermap[bits/8]
        typemap.decimalmap[None] = typemap.decimalmap[bits/8]
        typemap.ptrmap[None] = typemap.ptrmap[bits/8]
        typemap.stringmap[None] = typemap.stringmap[str] 
Example #20
Source File: ida.py    From bap-ida-python with MIT License 5 votes vote down vote up
def output_segments(out):
    """Dump binary segmentation."""
    info = idaapi.get_inf_structure()
    size = "r32" if info.is_32bit else "r64"
    out.writelines(('(', info.get_proc_name()[1], ' ', size, ' ('))
    for seg in idautils.Segments():
        out.write("\n({} {} {:d} ({:#x} {:d}))".format(
            get_segm_name(seg),
            "code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
            idaapi.get_fileregion_offset(seg),
            seg, idaapi.getseg(seg).size()))
    out.write("))\n") 
Example #21
Source File: vtableAddress.py    From Virtuailor with GNU General Public License v3.0 5 votes vote down vote up
def get_processor_architecture():
    arch = "Intel"
    info = idaapi.get_inf_structure()
    if info.procName == "ARM":
        arch = "ARM"
    if info.is_64bit():
        return arch, True
    elif info.is_32bit():
        return arch, False
    else:
        return "Error", False 
Example #22
Source File: analyzer_factory.py    From Karta with MIT License 5 votes vote down vote up
def createAnalyzer(logger, is_elf):
    """Create a CPU-based analyzer to be used by the program.

    Args:
        logger (logger): logger instance
        is_elf (bool): True iff analysing an ELF file

    Return Value:
        Created analyzer instance (None if CPU isn't supported yet)
    """
    # Code taken from:
    # https://reverseengineering.stackexchange.com/questions/11396/how-to-get-the-cpu-architecture-via-idapython
    # Kudos to tmr232
    info = idaapi.get_inf_structure()
    if info.is_64bit():
        bits = 64
    elif info.is_32bit():
        bits = 32
    # quite rare
    else:
        bits = 16

    # At the moment we don't care about the processors endianness.

    # Check if we support this CPU
    proc_name = info.procName
    logger.info("Processor: %s, %dbit", proc_name, bits)
    if proc_name not in analyzers_factory:
        logger.error("Processor %s is NOT supported yet :(", proc_name)
        return None
    # Can now create the analyzer instance
    return analyzers_factory[proc_name](logger, bits, is_elf) 
Example #23
Source File: x64dbgida.py    From x64dbgida with MIT License 5 votes vote down vote up
def get_file_mask():
    mask = "*.dd32"
    if idaapi.get_inf_structure().is_64bit():
        mask = "*.dd64"
    return mask 
Example #24
Source File: Graph.py    From grap with MIT License 5 votes vote down vote up
def extract(self):
        """Extract the control flow graph from the binary."""
        # Allocate a new graph
        self.graph = graph_alloc(0)
        
        # Initialize binary info
        self.info = get_inf_structure()
        
        # Initialize Capstone
        if self.info.is_64bit():
            mode = capstone.CS_MODE_64
        else:
            mode = capstone.CS_MODE_32
        self.capstone = capstone.Cs(capstone.CS_ARCH_X86, mode)
        
        # Get the Entry Point
        entry = None
        try:
            start_ea = self.info.start_ea
            if start_ea != 0xffffffff:
                entry = start_ea
        except:
            try:
                entry = BeginEA()
            except:
                pass
                
        if entry is None:
            print("WARNING: Could not determine entrypoint")
        else:
            self.dis(ea=entry, is_child1=None, ifrom=None)

        # Scan all the functions
        for ea in Functions():
            self.dis(ea=ea, is_child1=None, ifrom=None)

        update_children_fathers_number(self.graph)

        # Information
        print("%s graph has %d nodes" % (get_root_filename(),
                                         self.graph.nodes.size)) 
Example #25
Source File: misc.py    From heap-viewer with GNU General Public License v3.0 5 votes vote down vote up
def get_arch_ptrsize():
    info = idaapi.get_inf_structure() 
    ptr_size = None  
    if info.is_64bit():
        ptr_size = 8
    elif info.is_32bit():
        ptr_size = 4
    else:
        raise Exception("Invalid arch")
    return ptr_size

# -------------------------------------------------------------------------- 
Example #26
Source File: collect_variable.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def get_native_size():
  info = idaapi.get_inf_structure()
  if info.is_64bit():
    return 8
  elif info.is_32bit():
    return 4
  else:
    return 2 
Example #27
Source File: collect_variable.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def get_native_size():
  info = idaapi.get_inf_structure()
  if info.is_64bit():
    return 8
  elif info.is_32bit():
    return 4
  else:
    return 2 
Example #28
Source File: IDAConnector.py    From DIE with MIT License 5 votes vote down vote up
def get_proc_type():
    """
    Get processor type
    @return: Returns the processor type or None on failure.
    """
    try:
        inf = idaapi.get_inf_structure()
        return inf.procName()

    except Exception as ex:
        raise RuntimeError("Could not retrieve processor type: %s" %ex) 
Example #29
Source File: core.py    From Sark with MIT License 5 votes vote down vote up
def get_native_size():
    """Get the native word size in normal 8-bit bytes."""
    info = idaapi.get_inf_structure()
    if info.is_64bit():
        return 8
    elif info.is_32bit():
        return 4
    else:
        return 2 
Example #30
Source File: instruction.py    From Sark with MIT License 5 votes vote down vote up
def _initialize(self):
        if self.op_t.type not in (idaapi.o_displ, idaapi.o_phrase):
            raise exceptions.OperandNotPhrase('Operand is not of type o_phrase or o_displ.')

        proc_name = idaapi.get_inf_structure().procName
        if proc_name != 'metapc':
            raise exceptions.PhraseProcessorNotSupported(
                'Phrase analysis not supported for processor {}'.format(proc_name))

        specflag1 = self.op_t.specflag1
        specflag2 = self.op_t.specflag2
        scale = 1 << ((specflag2 & 0xC0) >> 6)
        offset = self.op_t.addr

        if specflag1 == 0:
            index = None
            base_ = self.op_t.reg
        elif specflag1 == 1:
            index = (specflag2 & 0x38) >> 3
            base_ = (specflag2 & 0x07) >> 0

            if self.op_t.reg == 0xC:
                if base_ & 4:
                    base_ += 8
                if index & 4:
                    index += 8
        else:
            raise exceptions.PhraseNotSupported('o_displ, o_phrase : Not implemented yet : %x' % specflag1)

        # HACK: This is a really ugly hack. For some reason, phrases of the form `[esp + ...]` (`sp`, `rsp` as well)
        # set both the `index` and the `base` to `esp`. This is not significant, as `esp` cannot be used as an
        # index, but it does cause issues with the parsing.
        # This is only relevant to Intel architectures.
        if (index == base_ == idautils.procregs.sp.reg) and (scale == 1):
            index = None

        self.scale = scale
        self.index_id = index
        self.base_id = base_
        self.offset = offset