Python idc.MakeComm() Examples

The following are 17 code examples of idc.MakeComm(). 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: create_tab_table.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def activate(self, ctx):
		# get item and remove 
		ind = ctx.chooser_selection.at(0)
		ioctl = self.items[ind - 1]
		pos = int(ioctl[0], 16)
		define = ioctl[5]
		global ioctl_tracker
		code = None
		for (addr, val) in ioctl_tracker.ioctls:
			if addr == pos:
				code = val
				break
		# Get current comment for this instruction and remove the C define from it, if present
		comment = idc.Comment(pos)
		comment = comment.replace(define, "")
		idc.MakeComm(pos, comment)
		# Remove the ioctl from the valid list and add it to the invalid list to avoid 'find_all_ioctls' accidentally re-indexing it.
		ioctl_tracker.remove_ioctl(pos, code) 
Example #2
Source File: jni_translate.py    From IDAPythonEmbeddedToolkit with MIT License 6 votes vote down vote up
def match_blx(ea, disasm):
  """process instruction that does the indirect call to JNIEnv function.

  E.g BLX     R4.

  Args:
   ea: (int) current address
   disasm: (str) disassembly of the current instruction.

  Returns:
   True or False depending on whether instruction loads the function ptr.
  """
  global regs_offsets, regs_loads, jnienv, num, called_blx
  disasm = remove_comment_from_disasm(disasm)
  callee = disasm.split("BLX")[1].strip()
  if callee in regs_offsets and str(regs_offsets[callee]) in jnienv:
    idc.MakeComm(ea, str(jnienv[str(regs_offsets[callee])]))
    num += 1
  regs_offsets[callee] = -1
  regs_loads[callee] = False
  called_blx = True 
Example #3
Source File: __init__.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def rename_argument(ea, function, argument, arg_description_format):
    """ Rename function's argument comment at ea based on config string. """
    fields = {
        "function_name": function.name,
        "function_dll":  function.dll,
        "argument_name": argument.name,
    }
    new_arg = arg_description_format.format(**fields).encode('utf-8')
    idc.MakeComm(ea, new_arg) 
Example #4
Source File: TraceWidget.py    From idasec with GNU Lesser General Public License v2.1 5 votes vote down vote up
def disassemble_from_trace(self):
        try:
            index = self.traces_tab.currentIndex()
            trace = self.core.traces[self.id_map[index]]

            self.disassemble_button.setFlat(True)
            found_match = False
            for k, inst in trace.instrs.items():
                if k in trace.metas:
                    for name, arg1, arg2 in trace.metas[k]:
                        if name == "wave":
                            self.parent.log("LOG", "Wave n°%d encountered at (%s,%x) stop.." % (arg1, k, inst.address))
                            prev_inst = trace.instrs[k-1]
                            idc.MakeComm(prev_inst.address, "Jump into Wave %d" % arg1)
                            self.disassemble_button.setFlat(False)
                            return
                # TODO: Check that the address is in the address space of the program
                if not idc.isCode(idc.GetFlags(inst.address)):
                    found_match = True
                    # TODO: Add an xref with the previous instruction
                    self.parent.log("LOG", "Addr:%x not decoded as an instruction" % inst.address)
                    if idc.MakeCode(inst.address) == 0:
                        self.parent.log("ERROR", "Fail to decode at:%x" % inst.address)
                    else:
                        idaapi.autoWait()
                        self.parent.log("SUCCESS", "Instruction decoded at:%x" % inst.address)

            if not found_match:
                self.parent.log("LOG", "All instruction are already decoded")
            self.disassemble_button.setFlat(False)
        except KeyError:
            print "No trace found to use" 
Example #5
Source File: __init__.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def add_arg_descr(function, segment_ea, arg_description_format):
    """ Name address in added segment annotated with argument descriptions.

    Arguments:
    function -- function object
    segment_ea -- start looking for empty byte to annotate from this ea

    Return:
    next possible free address to add information to
    """
    # No arguments
    if len(function.arguments) == 0:
        return segment_ea
    for argument in function.arguments:
        try:
            free_ea = get_segment_end_ea(segment_ea)
        except FailedToExpandSegmentException as e:
            raise e

        fields = {
            "function_name": function.name,
            "function_dll":  function.dll,
            "argument_name": argument.name,
        }
        name = arg_description_format.format(**fields).encode('utf-8')
        if not name_exists(name):
            g_logger.debug(' Adding name {} at {}'.format(name, hex(free_ea)))
            idaapi.set_name(free_ea, name)
            description = argument.description[:MAX_ARG_DESCR_LEN]
            idc.MakeComm(free_ea, format_comment(description))
        else:
            g_logger.debug(' Name %s already exists' % name)
    return (free_ea + 1) 
Example #6
Source File: __init__.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def add_fct_descr(ea, function, rep):
    """ Insert a (repeatable) comment describing the function at ea.

    Arguments:
    ea -- effective address where the comment is added
    function -- function object holding data
    rep -- add repeatable comment (True/False)
    """
    descr = format_comment(function.description) + '\n' + \
        format_comment('RETURN VALUE: ' + function.returns)
    # Both functions do not return
    if rep:
        idc.MakeRptCmt(ea, descr)
    else:
        idc.MakeComm(ea, descr) 
Example #7
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 #8
Source File: argtracker_example2.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def processStuff(results):
    '''
    Phase 2:
    For each argument tuple, decode the string and apply 
    '''
    for cVa, strLoc, locVa, strLen, lenVa, constVa, const1 in results:
        #logger.info('Trying to process 0x%08x: 0x%08x (0x%08x) 0x%04x (0x%08x) 0x%08x (0x%08x)', cVa, strLoc, locVa, strLen, lenVa, const1, constVa)
        try:
            decString = decodeString(strLoc, strLen, const1)
            #logger.infoHex(decString, '0x%08x: %s', strLoc, decString)

            decStringOrig = decString
            if decString.find('\x00\x00') >= 0:
                decString = decString[:decString.find('\x00\x00')]
            if c_jayutils.isWideString(decString):
                decString = c_jayutils.extractBasicWideString(decString)
            if decString.find('\x00') >= 0:
                decString = decString[:decString.find('\x00')]
            idc.MakeUnkn(strLoc, idc.DOUNK_SIMPLE)
            print '0x%08x: %s' % (strLoc, decString)
            #logger.infoHex(decStringOrig, '0x%08x: %s', strLoc, decString)
            idc.MakeRptCmt(strLoc, decString)
            idc.MakeComm(locVa, decString)
        except Exception, err:
            logger.exception('Error processing entry: %s', str(err))

# stuff1 tuples are of the form: 
# callEa, strLoc, locVa, strLen, lenVa, const1, constVa 
Example #9
Source File: idaplugin.py    From flare-floss with Apache License 2.0 5 votes vote down vote up
def append_comment(ea, s, repeatable=False):
    '''
    add the given string as a (possibly repeating) comment to the given address.
    does not add the comment if it already exists.
    adds the comment on its own line.

    Args:
      ea (int): the address at which to add the comment.
      s (str): the comment text.
      repeatable (bool): if True, set a repeatable comment.

    Raises:
      UnicodeEncodeError: if the given string is not ascii.
    '''
    # see: http://blogs.norman.com/2011/security-research/improving-ida-analysis-of-x64-exception-handling

    s = s.encode('ascii')

    if repeatable:
        string = idc.RptCmt(ea)
    else:
        string = idc.Comment(ea)

    if not string:
        string = s  # no existing comment
    else:
        if s in string:  # ignore duplicates
            return
        string = string + "\\n" + s

    if repeatable:
        idc.MakeRptCmt(ea, string)
    else:
        idc.MakeComm(ea, string) 
Example #10
Source File: OL_OSX_decryptor.py    From malware-research with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_comment(cfunc, s, ea):
    idc.MakeComm(ea, s)
    tl = idaapi.treeloc_t()
    tl.ea = ea
    tl.itp = idaapi.ITP_SEMI
    cfunc.set_user_cmt(tl, s)
    cfunc.save_user_cmts()

# Generic function arguments extraction methods 
Example #11
Source File: ida_gef.py    From GdbPlugins with GNU General Public License v3.0 5 votes vote down vote up
def MakeComm(self, address, comment):
        """ MakeComm(int addr, string comment) => None
        Add a comment to the current IDB at the location `address`.
        Example: ida MakeComm 0x40000 "Important call here!"
        """
        addr = long(address, 16) if ishex(address) else long(address)
        return idc.MakeComm(addr, comment) 
Example #12
Source File: calls.py    From idataco with GNU General Public License v3.0 5 votes vote down vote up
def removeMarkup(self, ea, force=False):
        if ea in self._marked_up or force:
            log.debug("Removing color")
            idc.SetColor(ea, idc.CIC_FUNC, 0xffffff)
            idc.SetColor(ea, idc.CIC_ITEM, 0xffffff)
            idc.MakeComm(ea, "")
            log.debug("Removing posterior lines")
            i = 0
            while idc.LineB(ea, i):
                idc.DelExtLnB(ea, i)
                i += 1 
Example #13
Source File: calls.py    From idataco with GNU General Public License v3.0 5 votes vote down vote up
def addPosterior(self, markup_ea, logged_api_name, called_api_name, args):
        log.debug("Adding posterior lines")
        idc.MakeComm(markup_ea, str(called_api_name))
        idc.ExtLinB(markup_ea, 0, "api: {}".format(logged_api_name))
        ln = 1
        for arg in re.split("\r?\n", args.strip()):
            idc.ExtLinB(markup_ea, ln, str(arg.strip()))
            ln += 1 
Example #14
Source File: fcatalog_plugin.py    From fcatalog_client with GNU General Public License v3.0 5 votes vote down vote up
def save_sstring(s):
    """
    Save a short string inside the idb.
    """
    min_segment_addr = min(list(idautils.Segments()))
    # Keep the string as a regular comment on the first instruction:
    idc.MakeComm(min_segment_addr,s) 
Example #15
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def activate(self, ctx):
        pos = idc.ScreenEA()
        # Get current comment for this instruction and remove the C define from it, if present
        comment = idc.Comment(pos)
        code = get_operand_value(pos)
        define = ioctl_decoder.get_define(code)
        comment = comment.replace(define, "")
        idc.MakeComm(pos, comment)
        # Remove the ioctl from the valid list and add it to the invalid list to avoid 'find_all_ioctls' accidently re-indexing it.
        ioctl_tracker.remove_ioctl(pos, code) 
Example #16
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_comment(pos, string):
    """
    Creates a comment with contents `string` at address `pos`.
    If the address is already commented append the new comment to the existing comment
    """
    
    current_comment = idc.Comment(pos)
    if not current_comment:
        idc.MakeComm(pos, string)
    elif string not in current_comment:
        idc.MakeComm(pos, current_comment + " " + string) 
Example #17
Source File: loader.py    From idawasm with Apache License 2.0 4 votes vote down vote up
def load_struc(struc, p, path):
    '''
    Load the given structure into the current IDA Pro at the given offset.

    Example::

        load_struc(sections[0].data, 0x0, 'foo-section')

    Args:
      struc (wasm.Structure): the structure to load.
      p (int): the effective address at which to load.
      path (str): the namespaced name of the given structure.

    Returns:
      int: the next offset following the loaded structure.
    '''
    for field in idawasm.common.get_fields(struc):
        # build names like: `sections:2:payload:entries:0:module_str`
        name = path + ':' + field.name

        # recurse into nested structures
        if idawasm.common.is_struc(field.value):
            p = load_struc(field.value, p, name)

        # recurse into lists of structures
        elif (isinstance(field.value, list)
              and len(field.value) > 0
              and idawasm.common.is_struc(field.value[0])):

            for i, v in enumerate(field.value):
                p = load_struc(v, p, name + ':' + str(i))

        # emit primitive types
        else:
            # add annotations like follows:
            #
            #     imports:002D sections:2:payload:entries:0:module_len         <--- Add line prior to element.
            #     imports:002D                 db 3                    ;; 0x3  <--- Render element for human.
            #     imports:002E sections:2:payload:entries:0:module_str
            #     imports:002E                 db 0x65 ;; e            ;; env  <--- Pull out strings and lists nicely.
            #     imports:002F                 db 0x6E ;; n
            #     imports:0030                 db 0x76 ;; v

            # add line prior to element
            idc.ExtLinA(p, 0, name)

            # if primitive integer element, set it as such
            if isinstance(field.value, int):
                MakeN(p, field.size)

            # add comment containing human-readable representation
            idc.MakeComm(p, format_value(name, field.value).encode('utf-8'))

            p += field.size

    return p