Python idc.set_cmt() Examples

The following are 14 code examples of idc.set_cmt(). 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: idaxml.py    From GhIDA with Apache License 2.0 6 votes vote down vote up
def import_comment(self, comment):
        """
        Processes a COMMENT element by creating the comment at the address.

        Args:
            comment: XML element containing the comment address, type,
                and text.
        """
        if self.options.Comments.checked == False:
            return
        addr = self.get_address(comment, ADDRESS)
        ctype = self.get_attribute(comment, TYPE)
        text = comment.text
        if ctype == 'pre':
            ida_lines.add_extra_cmt(addr, True, text)
        elif ctype == 'end-of-line':
            idc.set_cmt(addr, text, False)
        elif ctype == 'repeatable':
            idc.set_cmt(addr, text, True)
        elif ctype == 'post':
            ida_lines.add_extra_cmt(addr, False, text)
        self.update_counter(COMMENT + ':' + ctype) 
Example #2
Source File: ps4_module.py    From ps4_module_loader with GNU General Public License v3.0 6 votes vote down vote up
def resolve(self, address, nids, symbol):
    
        # Resolve the NID...
        idc.set_cmt(self.VALUE, 'NID: ' + symbol, False)
        function = nids.get(symbol[:11], symbol)
        
        #print('Function: %s | number: %s' % (function, idaapi.get_func_num(self.VALUE)))
        if idaapi.get_func_num(self.VALUE) > 0:
            idc.del_func(self.VALUE)
        
        if self.VALUE > 0:
            idc.add_func(self.VALUE)
            idc.add_entry(self.VALUE, self.VALUE, function, True)
            idc.set_name(self.VALUE, function, SN_NOCHECK | SN_NOWARN | SN_FORCE)
            idc.set_cmt(address, '%s | %s' % (function, self.info()), False)
        
    

# PROGRAM START

# Open File Dialog... 
Example #3
Source File: ironstrings.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def append_comment(va, new_cmt, repeatable=False):
    """
    Append a comment to an address in IDA Pro.
    :param va: comment address
    :param new_cmt: comment string
    :param repeatable: if True, append as repeatable comment
    :return: True if success
    """
    cmt = idc.get_cmt(va, repeatable)
    if not cmt:
        # no existing comment
        cmt = new_cmt
    else:
        if new_cmt in cmt:
            # comment already exists
            return True
        cmt = cmt + "\n" + new_cmt
    return idc.set_cmt(va, cmt, repeatable) 
Example #4
Source File: depgraph.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def clean_lines():
    "Remove previous comments"
    global comments
    for offset in comments:
        idc.set_color(offset, idc.CIC_ITEM, 0xffffff)
        idc.set_cmt(offset, "", 0)
    comments = {} 
Example #5
Source File: depgraph.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def treat_element():
    "Display an element"
    global graphs, comments, sol_nb, settings, addr, ir_arch, ircfg

    try:
        graph = next(graphs)
    except StopIteration:
        comments = {}
        print("Done: %d solutions" % (sol_nb))
        return

    sol_nb += 1
    print("Get graph number %02d" % sol_nb)
    filename = os.path.join(tempfile.gettempdir(), "solution_0x%08x_%02d.dot" % (addr, sol_nb))
    print("Dump the graph to %s" % filename)
    open(filename, "w").write(graph.graph.dot())

    for node in graph.relevant_nodes:
        try:
            offset = ircfg.blocks[node.loc_key][node.line_nb].instr.offset
        except IndexError:
            print("Unable to highlight %s" % node)
            continue
        comments[offset] = comments.get(offset, []) + [node.element]
        idc.set_color(offset, idc.CIC_ITEM, settings.color)

    if graph.has_loop:
        print('Graph has dependency loop: symbolic execution is inexact')
    else:
        print("Possible value: %s" % next(iter(viewvalues(graph.emul(ir_arch)))))

    for offset, elements in viewitems(comments):
        idc.set_cmt(offset, ", ".join(map(str, elements)), 0) 
Example #6
Source File: analyser.py    From UEFI_RETool with MIT License 5 votes vote down vote up
def make_comments(self):
        """make comments in idb"""
        EFI_BOOT_SERVICES_ID = idc.get_struc_id('EFI_BOOT_SERVICES')
        self.get_boot_services()
        empty = True
        for service in self.gBServices:
            for address in self.gBServices[service]:
                message = 'EFI_BOOT_SERVICES->{0}'.format(service)
                idc.set_cmt(address, message, 0)
                idc.op_stroff(address, 0, EFI_BOOT_SERVICES_ID, 0)
                empty = False
                print('[ {ea} ] {message}'.format(
                    ea='{addr:#010x}'.format(addr=address), message=message))
        if empty:
            print(' * list is empty') 
Example #7
Source File: ps4_module.py    From ps4_module_loader with GNU General Public License v3.0 5 votes vote down vote up
def process(self, nids, symbols):
    
        if self.INFO > Relocation.R_X86_64_ORBIS_GOTPCREL_LOAD:
            self.INDEX = self.INFO >> 32
            self.INFO &= 0xFF
            
            # Symbol Value + AddEnd (S + A)
            if self.type() == 'R_X86_64_64':
                self.INDEX += self.ADDEND
            
            if self.type() != 'R_X86_64_DTPMOD64':
                symbol = next(value for key, value in enumerate(symbols) if key + 2 == self.INDEX)[1]
        
        # String (Offset) == Base + AddEnd (B + A)
        if self.type() == 'R_X86_64_RELATIVE':
            idaapi.put_qword(self.OFFSET, self.ADDEND)
            idaapi.create_data(self.OFFSET, FF_QWORD, 0x8, BADNODE)
        
        # TLS Object
        elif self.type() in ['R_X86_64_DTPMOD64', 'R_X86_64_DTPOFF64']:
            idc.set_name(self.OFFSET, 'tls_access_struct', SN_NOCHECK | SN_NOWARN | SN_FORCE)
        
        # Object
        else:
            # Resolve the NID...
            idc.set_cmt(self.OFFSET, 'NID: ' + symbol, False)
            object = nids.get(symbol[:11], symbol)
            
            # Rename the Object...
            idc.set_name(self.OFFSET, object, SN_NOCHECK | SN_NOWARN | SN_FORCE)
            idaapi.create_data(self.OFFSET, FF_QWORD, 0x8, BADNODE)
        
        return self.type() 
Example #8
Source File: klfdb.py    From ActionScript3 with GNU General Public License v3.0 5 votes vote down vote up
def set_jit_info(self, method_id, start):

		end = self.get_func_end(start)

		if (end < start or end - start > self.jit_max_size):
			return

		method = next((x for x in self.as3dump if x["id"] == method_id), None)

		if (method is None):
			return

		stackvars = self.get_stack_vars(start, end)
		save_eip = self.get_save_eip(method, stackvars)

		ea = start
		while (ea < end):
	
			if ("ebp" in idc.print_operand(ea, 0) and idc.get_operand_type(ea, 1) == idc.o_imm):
	
				op0 = idc.get_operand_value(ea, 0)
				op1 = idc.get_operand_value(ea, 1)
	
				if (op0 == save_eip):
					idc.set_cmt(ea, method["instructions"][op1], 0)
		
			ea += idc.get_item_size(ea) 
Example #9
Source File: objc2_analyzer.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def processMsgSend(self, eh, address, id, sel, clsName, isInstance, selref, selXref, userData):
        logging.debug("addr: %s id: %s sel: %s clsName: %s isInstance: %s selRef: %s selXref: %s" % (eh.hexString(0 if address == None else address), id, sel, clsName, isInstance, eh.hexString(0 if selref == None else selref), eh.hexString(0 if selXref == None else selXref)))
        if sel:
            idc.set_cmt(address, "[%s %s]" % (id, sel), 0)
        if sel and id != UNKNOWN:
            # as a convenience, if sel is "new", fix xref to "init"
            if sel == "new" and clsName in userData["classes"]:
                if (len(filter(lambda x: idc.get_name(x, idc.ida_name.GN_VISIBLE) == "selRef_init", map(lambda x: x[0],
                        userData["classes"][clsName]["instance"]))) > 0):
                    selref = filter(lambda x: idc.get_name(x, idc.ida_name.GN_VISIBLE) == "selRef_init", map(
                        lambda x: x[0], userData["classes"][clsName]["instance"]))[0]
                    isInstance = True
            if selXref and selXref not in self.fixedSelXRefs:
                self.fixXref(eh, userData["classes"], clsName, selref,
                        isInstance, selXref, address, userData) 
Example #10
Source File: stackstrings.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def main(doAllFuncs=True):
    #doAllFuncs=False
    #jayutils.configLogger(__name__, logging.DEBUG)
    jayutils.configLogger(__name__, logging.INFO)
    logger = jayutils.getLogger('stackstrings')
    logger.debug('Starting up now')
    filePath = jayutils.getInputFilepath()
    if filePath is None:
        self.logger.info('No input file provided. Stopping')
        return
    vw = jayutils.loadWorkspace(filePath)
    ea = idc.here()
    res = -1
    if using_ida7api:
        res = idc.ask_yn(0, 'Use basic-block local aggregator')
    else:
        res = idc.AskYN(0, 'Use basic-block local aggregator')
    if res == idaapi.ASKBTN_CANCEL:
        print 'User canceled'
        return
    uselocalagg = (res == 1)
    ranges = getFuncRanges(ea, doAllFuncs)
    for funcStart, funcEnd in ranges:
        try:
            logger.debug('Starting on function: 0x%x', funcStart)
            stringList = runStrings(vw, funcStart, uselocalagg)    
            for node, string in stringList:
                if isLikelyFalsePositiveString(string):
                    #if it's very likely a FP, skip annotating
                    continue
                print '0x%08x: %s' % (node[0], string)
                #print '0x%08x: 0x%08x: %s %s' % (node[0], node[1], binascii.hexlify(string), string)
                if using_ida7api:
                    idc.set_cmt(node[0], string.strip(), 0)
                else:
                    idc.MakeComm(node[0], string.strip())
        except Exception, err:
            logger.exception('Error during parse: %s', str(err)) 
Example #11
Source File: shellcode_hash_search.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def markupLine(self, loc, sym, useDecompiler = False):
        comm = '%s!%s' % (sym.libName, sym.symbolName)
        logger.debug("Making comment @ 0x%08x: %s", loc, comm)
        if using_ida7api:
            idc.set_cmt(loc, str(comm), False)
            if useDecompiler and idaapi.get_func(loc) != None:
                self.addDecompilerComment(loc, str(comm))
        else:
            idc.MakeComm(loc, str(comm)) 
Example #12
Source File: ctype_propagation.py    From miasm with GNU General Public License v2.0 4 votes vote down vote up
def eval_updt_irblock(self, irb, step=False):
        """
        Symbolic execution of the @irb on the current state
        @irb: irblock instance
        @step: display intermediate steps
        """

        offset2cmt = {}
        for index, assignblk in enumerate(irb):
            if set(assignblk) == set([self.ir_arch.IRDst, self.ir_arch.pc]):
                # Don't display on jxx
                continue
            instr = assignblk.instr
            tmp_r = assignblk.get_r()
            tmp_w = assignblk.get_w()

            todo = set()

            # Replace PC with value to match IR args
            pc_fixed = {self.ir_arch.pc: m2_expr.ExprInt(instr.offset + instr.l, self.ir_arch.pc.size)}
            inputs = tmp_r
            inputs.update(arg for arg in tmp_w if arg.is_mem())
            for arg in inputs:
                arg = expr_simp(arg.replace_expr(pc_fixed))
                if arg in tmp_w and not arg.is_mem():
                    continue
                todo.add(arg)

            for expr in todo:
                if expr.is_int():
                    continue
                for c_str, c_type in self.chandler.expr_to_c_and_types(expr, self.symbols):
                    expr = self.cst_propag_link.get((irb.loc_key, index), {}).get(expr, expr)
                    offset2cmt.setdefault(instr.offset, set()).add(
                        "\n%s: %s\n%s" % (expr, c_str, c_type)
                    )
            self.eval_updt_assignblk(assignblk)
        for offset, value in viewitems(offset2cmt):
            idc.set_cmt(offset, '\n'.join(value), 0)
            print("%x\n" % offset, '\n'.join(value))

        return self.eval_expr(self.ir_arch.IRDst) 
Example #13
Source File: ps4_module.py    From ps4_module_loader with GNU General Public License v3.0 4 votes vote down vote up
def resolve(self, alphabet, nids, symbols, libraries):
    
        if self.INFO > Relocation.R_X86_64_ORBIS_GOTPCREL_LOAD:
            self.INDEX = self.INFO >> 32
            self.INFO &= 0xFF
            symbol = next(value for key, value in enumerate(symbols) if key + 2 == self.INDEX)[1]
        
        # Library
        try:
            lid1 = alphabet[symbol[12:13]]
            
            # [base64]#
            if symbol[13:14] == '#':
                library = libraries[lid1]
            
            # [base64][base64]#
            elif symbol[14:15] == '#':
                lid2 = alphabet[symbol[13:14]]
                library = libraries[lid1 + lid2]
            
            else:
                raise
        
        # Not a NID
        except:
            library = ''
        
        # Function Name (Offset) == Symbol Value + AddEnd (S + A)
        # Library Name  (Offset) == Symbol Value (S)
        real = idc.get_qword(self.OFFSET)
        idc.add_func(real)
        
        # Hacky way to determine if this is the real function...
        real -= 0x6 if idc.print_insn_mnem(real) == 'push' else 0x0
        
        # Resolve the NID...
        idc.set_cmt(real, 'NID: ' + symbol, False)
        function = nids.get(symbol[:11], symbol)
        
        # Rename the Jump Function...
        idc.set_name(self.OFFSET, '__imp_' + function, SN_NOCHECK | SN_NOWARN | SN_FORCE)
        
        # Rename the Real Function...
        idc.set_name(real, function, SN_NOCHECK | SN_NOWARN | SN_FORCE)
        
        try:
            import_node = idaapi.netnode(library, 0, True)
            import_node.supset(ea2node(real), function)
        
            # Requires customized loader.i / ida_loader.py(d)
            idaapi.import_module(library, None, import_node.index(), None, 'linux')
        
        except:
            pass
        
        return self.type() 
Example #14
Source File: code_grafter.py    From flare-ida with Apache License 2.0 4 votes vote down vote up
def _patchCalls(self):
        def do_patch_call(va):
            retval = False
            stub_loc = idc.get_name_ea_simple(self._stubname(nm))

            # Preserve original disassembly and format new comment
            old_target = idc.print_operand(va, 0)
            orig_cmt = idc.get_cmt(va, 0) or ''
            new_cmt = '%s\n\t%s' % (g_patched_call_cmt, idc.GetDisasm(va))

            if idc.get_operand_type(va, 0) == ida_ua.o_mem:
                retval = patch_import(va, self._stubname(nm))
                new_cmt += '\n%s %s to %s)' % (g_cmt_pointed, old_target,
                                               self._stubname(nm))
            elif idc.get_operand_type(va, 0) == ida_ua.o_reg:
                va_imp = self._get_imp_for_register_call(va, nm)
                if va_imp:
                    patch_pointer_width(va_imp, stub_loc)
                    retval = True
                else:
                    logger.warn('Could not find import to patch call at %s' %
                                (phex(va)))

            else:  # Usually optype 7 otherwise
                # Won't work if displacement exceeds 32-bit operand size
                call_offset_loc = va + idc.get_item_size(va)
                if abs(call_offset_loc - stub_loc) > 0x100000000:
                    msg = ('Call site at %s too far from %s (%s)' %
                           (phex(va), self._stubname(nm), phex(stub_loc)))
                    raise CodeGraftingDisplacementError(msg)
                retval = patch_call(va, self._stubname(nm))

            if retval:
                if orig_cmt:
                    new_cmt += '\n%s' % (orig_cmt)
                idc.set_cmt(va, new_cmt, 0)
                ida_xref.add_cref(va, stub_loc, ida_xref.fl_CN)

            return retval

        for names in self._emu_stubs.keys():
            for nm in names:
                va = idc.get_name_ea_simple(nm)
                mykutils.for_each_call_to(do_patch_call, va)

        for nm, aliases in g_allocators_aliases.items():
            for alias in aliases:
                # do_patch_call closure will turn <nm> into stub_<nm>
                mykutils.for_each_call_to(do_patch_call,
                                          idc.get_name_ea_simple(alias))