Python idaapi.decompile() Examples

The following are 14 code examples of idaapi.decompile(). 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: shellcode_hash_search.py    From flare-ida with Apache License 2.0 7 votes vote down vote up
def addDecompilerComment(self, loc, comment):
        cfunc = idaapi.decompile(loc)
        eamap = cfunc.get_eamap()
        decompObjAddr = eamap[loc][0].ea
        tl = idaapi.treeloc_t()
        tl.ea = decompObjAddr
        commentSet = False
        for itp in range (idaapi.ITP_SEMI, idaapi.ITP_COLON):
            tl.itp = itp
            cfunc.set_user_cmt(tl, comment)
            cfunc.save_user_cmts()
            unused = cfunc.__str__()
            if not cfunc.has_orphan_cmts():
                commentSet = True
                cfunc.save_user_cmts()
                break
            cfunc.del_orphan_cmts()
        if not commentSet:
            print ("pseudo comment error at %08x" % loc) 
Example #2
Source File: ida_batch_decompile.py    From ida-batch_decompile with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        files_decompiled = []
        self._init_target()

        if self.chk_decompile_imports:
            self.init_tempdir()
            if self.chk_decompile_imports_recursive:
                pass
            for image_type, image_name, image_path in self.enumerate_import_images():
                try:
                    self.exec_ida_batch_decompile(target = image_path, output = self.output_path,
                                                  annotate_stackvar_size = self.chk_annotate_stackvar_size,
                                                  annotate_xrefs = self.chk_annotate_xrefs,
                                                  imports = self.chk_decompile_imports,
                                                  recursive = self.chk_decompile_imports_recursive,
                                                  experimental_decomile_cgraph = self.chk_decompile_alternative)
                    files_decompiled.append(image_path)
                except subprocess.CalledProcessError, cpe:
                    logger.warning("[!] failed to decompile %r - %r" % (image_path, cpe))

            self.remove_tempdir() 
Example #3
Source File: ida_batch_decompile.py    From ida-batch_decompile with GNU General Public License v3.0 6 votes vote down vote up
def exec_ida_batch_decompile(self, target, output, annotate_stackvar_size, annotate_xrefs, imports, recursive,
                                 experimental_decomile_cgraph):
        logger.debug("[+] batch decompile %r" % target)
        # todo: pass commandlines,
        # todo parse commandline
        script_args = ['--output=%s' % output]
        if annotate_stackvar_size:
            script_args.append("--annotate-stackvar-size")
        if annotate_xrefs:
            script_args.append("--annotate-xrefs")
        if imports:
            script_args.append("--imports")
        if recursive:
            script_args.append("--recursive")
        if experimental_decomile_cgraph:
            script_args.append("--experimental-decompile-cgraph")

        script_args = ['\\"%s\\"' % a for a in script_args]
        command = "%s %s" % (self.my_path, ' '.join(script_args))
        self._exec_ida_batch(target, command) 
Example #4
Source File: function.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def decompile(cls, ea):
        '''(UNSTABLE) Returns the decompiled code of the basic block at the address `ea`.'''
        source = idaapi.decompile(ea)

        res = itertools.imap(functools.partial(operator.__getitem__, source.eamap), cls.iterate(ea))
        res = itertools.chain(*res)
        formatted = reduce(lambda t, c: t if t[-1].ea == c.ea else t+[c], res, [next(res)])

        res = []
        # FIXME: This has been pretty damn unstable in my tests.
        try:
            for fmt in formatted:
                res.append( fmt.print1(source.__deref__()) )
        except TypeError: pass
        res = itertools.imap(idaapi.tag_remove, res)
        return '\n'.join(map(utils.string.of, res)) 
Example #5
Source File: fn_fuzzy.py    From ida_haru with Apache License 2.0 5 votes vote down vote up
def set_decomplier_cmt(ea, cmt):
    cfunc = idaapi.decompile(ea)
    tl = idaapi.treeloc_t()
    tl.ea = ea
    tl.itp = idaapi.ITP_SEMI
    if cfunc:
      cfunc.set_user_cmt(tl, cmt)
      cfunc.save_user_cmts()
    else:
      error("Decompile failed: {:#x}".formart(ea)) 
Example #6
Source File: ida_batch_decompile.py    From ida-batch_decompile with GNU General Public License v3.0 5 votes vote down vote up
def decompile(self):
        """ decompile function
        """
        try:
            return idaapi.decompile(self.at)
        except idaapi.DecompilationFailure, e:
            return repr(str(e)) 
Example #7
Source File: ida_batch_decompile.py    From ida-batch_decompile with GNU General Public License v3.0 5 votes vote down vote up
def decompile_all(self, outfile=None):
        outfile = self._get_suggested_output_filename(outfile or self.target_path)
        logger.warning(outfile)
        logger.debug("[+] trying to decompile %r as %r" % (self.target_file,
                                                           os.path.split(outfile)[1]))
        IdaHelper.decompile_full(outfile)
        logger.debug("[+] finished decompiling %r as %r" % (self.target_file,
                                                            os.path.split(outfile)[1])) 
Example #8
Source File: ida_batch_decompile.py    From ida-batch_decompile with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, idbctrl, enumerate_imports=True, enumerate_other=False):
        self.idbctrl = idbctrl
        self.EChooser = TestEmbeddedChooserClass("Batch Decompile", flags=Choose2.CH_MULTI)
        self.propagateItems(enumerate_imports=enumerate_imports, enumerate_other=enumerate_other)
        Form.__init__(self,
                      r"""Ida Batch Decompile ...
{FormChangeCb}
<##Target    :{target}>
<##OutputPath:{outputPath}>
<##Annotate StackVar Size:{chkAnnotateStackVars}>
<##Annotate Func XRefs   :{chkAnnotateXrefs}>
<##Process Imports       :{chkDecompileImports}>
<##Cgraph (experimental) :{chkDecompileAlternative}>{cGroup1}>


<##Scan Target Directory:{btnLoad}> <##Recursive:{chkDecompileImportsRecursive}>{cGroup2}>
<##Decompile!:{btnProcessFiles}>
<Please select items to decompile:{cEChooser}>


""", {
                          'target': Form.FileInput(swidth=50, open=True, value=idbctrl.target_path),
                          'outputPath': Form.DirInput(swidth=50, value=idbctrl.output_path),
                          'cGroup1': Form.ChkGroupControl(("chkAnnotateStackVars", "chkAnnotateXrefs",
                                                           "chkDecompileImports",
                                                           "chkDecompileAlternative")),
                          'cGroup2': Form.ChkGroupControl(("chkDecompileImportsRecursive", )),
                          'FormChangeCb': Form.FormChangeCb(self.OnFormChange),
                          'btnLoad':  Form.ButtonInput(self.OnButtonLoad),
                          'btnProcessFiles': Form.ButtonInput(self.OnButtonProcess),
                          'cEChooser': Form.EmbeddedChooserControl(self.EChooser),
                      })
        self.Compile() 
Example #9
Source File: hexrays.py    From bap-ida-python with MIT License 5 votes vote down vote up
def find_cfunc(ea):
    """Get cfuncptr_t from EA."""
    func = idaapi.get_func(ea)
    if func:
        return idaapi.decompile(func) 
Example #10
Source File: OL_OSX_decryptor.py    From malware-research with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def activate(self, ctx):
        for pfn_idx in ctx.chooser_selection:
            pfn = ida_funcs.getn_func(pfn_idx)
            if pfn:
                xrefs = [x for x in idautils.CodeRefsTo(pfn.start_ea, 0)]
                for xref in list(set(xrefs)):
                    cfunc = idaapi.decompile(xref)
                    if cfunc:
                        xref_args = get_args(cfunc, xref, self.var_prop)
                        self.callback(xref, cfunc, xref_args)
        return 1 
Example #11
Source File: function.py    From ida-minsc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decompile(cls):
        '''(UNSTABLE) Returns the decompiled code of the basic block at the current address.'''
        return cls.decompile(ui.current.address()) 
Example #12
Source File: LazyIDA.py    From LazyIDA with MIT License 4 votes vote down vote up
def remove_rettype(self, vu):
        if vu.item.citype == idaapi.VDI_FUNC:
            # current function
            ea = vu.cfunc.entry_ea
            old_func_type = idaapi.tinfo_t()
            if not vu.cfunc.get_func_type(old_func_type):
                return False
        elif vu.item.citype == idaapi.VDI_EXPR and vu.item.e.is_expr() and vu.item.e.type.is_funcptr():
            # call xxx
            ea = vu.item.get_ea()
            old_func_type = idaapi.tinfo_t()

            func = idaapi.get_func(ea)
            if func:
                try:
                    cfunc = idaapi.decompile(func)
                except idaapi.DecompilationFailure:
                    return False

                if not cfunc.get_func_type(old_func_type):
                    return False
            else:
                return False
        else:
            return False

        fi = idaapi.func_type_data_t()
        if ea != idaapi.BADADDR and old_func_type.get_func_details(fi):
            # Return type is already void
            if fi.rettype.is_decl_void():
                # Restore ret type
                if ea not in self.ret_type:
                    return True
                ret = self.ret_type[ea]
            else:
                # Save ret type and change it to void
                self.ret_type[ea] = fi.rettype
                ret = idaapi.BT_VOID

            # Create new function info with new rettype
            fi.rettype = idaapi.tinfo_t(ret)

            # Create new function type with function info
            new_func_type = idaapi.tinfo_t()
            new_func_type.create_func(fi)

            # Apply new function type
            if idaapi.apply_tinfo(ea, new_func_type, idaapi.TINFO_DEFINITE):
                return vu.refresh_view(True)

        return False 
Example #13
Source File: utils.py    From UEFI_RETool with MIT License 4 votes vote down vote up
def set_hexrays_comment(address, text):
    """set comment in decompiled code"""
    cfunc = idaapi.decompile(address)
    tl = idaapi.treeloc_t()
    tl.ea = address
    tl.itp = idaapi.ITP_SEMI
    cfunc.set_user_cmt(tl, text)
    cfunc.save_user_cmts() 
Example #14
Source File: __init__.py    From hrdev with MIT License 4 votes vote down vote up
def run(self):
        '''Start the plugin.'''

        if not idaapi.init_hexrays_plugin():
            print "HRDEV Error: Failed to initialise Hex-Rays plugin."
            return

        function_name = idaapi.get_func_name(idaapi.get_screen_ea())
        demangled_name = self.tools.demangle_name(function_name)

        src = idaapi.decompile(idaapi.get_screen_ea())

        file_name = '{}.cpp'.format(self.tools.to_file_name(demangled_name))
        cache_path = os.path.sep.join([tempfile.gettempdir(),
                                       'hrdev_cache',
                                       self._bin_name])

        # Create required directories if they dont exist
        tmp_dir_path = os.path.sep.join([tempfile.gettempdir(), 'hrdev_cache'])
        if not os.path.isdir(tmp_dir_path):
            os.mkdir(tmp_dir_path)

        if not os.path.isdir(cache_path):
            os.mkdir(cache_path)

        complete_path = os.path.sep.join([cache_path, file_name])
        idaapi.msg("HRDEV cache path: {}\n".format(complete_path))

        # Check if file is already in cache
        if not os.path.isfile(complete_path) or \
           self.config_main.getboolean('etc', 'disable_cache'):
            self.tools.save_file(complete_path, str(src))

        self.tools.set_file_path(complete_path)

        lvars = {}
        for v in src.lvars:
            _type = idaapi.print_tinfo('', 0, 0, idaapi.PRTYPE_1LINE, v.tif, '', '')
            lvars[str(v.name)] = "{} {} {}".\
                format(_type, str(v.name), str(v.cmt))

        max_title = self.config_main.getint('etc', 'max_title')
        self.gui = hrdev_plugin.include.gui.Canvas(self.config_main,
                                                   self.config_theme,
                                                   self.tools,
                                                   lvars,
                                                   demangled_name[:max_title])
        self.gui.Show('HRDEV')

        self.parser = hrdev_plugin.include.syntax.Parser(self, lvars)
        self.parser.run(complete_path)
        return