def run(self, arg): # Get the highlighted identifier id = idaapi.get_highlighted_identifier() if not id: print "No identifier was highlighted" return import webbrowser try: import feedparser except: idaapi.warning('Feedparser package not installed') return id = self.sanitize_name(id) print "Looking up '%s' in MSDN online" % id d = feedparser.parse( "http://social.msdn.microsoft.com/Search/Feed.aspx?locale=en-us&format=RSS&Query=%s" % id) if len(d['entries']) > 0: url = d['entries'][0].link webbrowser.open_new_tab(url) else: print "API documentation not found for: %s" % id
def activate(self, ctx): if regFu.isHighlightedEffective(): addr = regFu.getOffset() simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.getMemoryValue(0x%x)");' % addr) print('effective addr 0x%x value %s' % (addr, simicsString)) value = getHex(simicsString) else: highlighted = idaapi.get_highlighted_identifier() addr = getHex(highlighted) if addr is None: print('ModMemoryHandler unable to parse hex from %s' % highlighted) return simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.getMemoryValue(0x%x)");' % addr) print('addr 0x%x value %s' % (addr, simicsString)) value = getHex(simicsString) # Sample form from kernwin.hpp s = """Modify memory Address: %$ <~E~nter value:S:32:16::> """ num = Form.NumericArgument('N', value=value) ok = idaapi.AskUsingForm(s, Form.NumericArgument('$', addr).arg, num.arg) if ok == 1: print("You entered: %x" % num.value) simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.writeWord(0x%x, 0x%x)");' % (addr, num.value)) time.sleep(1) idc.RefreshDebuggerMemory()
def trackRegister(self): highlighted = idaapi.get_highlighted_identifier() if highlighted is None or highlighted not in self.reg_list: print('%s not in reg list' % highlighted) c = Choose([], "back track to source of selected register", 1) c.width = 50 c.list = self.reg_list chose = c.choose() if chose == 0: print('user canceled') return else: highlighted = self.reg_list[chose - 1] print 'backtrack to source of to %s...' % highlighted command = "@cgc.revTaintReg('%s')" % highlighted simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = gdbProt.getEIPWhenStopped(2) #gdbProt.stepWait() self.signalClient() curAddr = idc.GetRegValue(self.PC) print( 'Current instruction (0x%x) is as far back as we can trace reg %s' % (curAddr, highlighted)) self.showSimicsMessage() bookmark_list = self.bookmark_view.updateBookmarkView() return eip
def get_highlighted_identifier(): if not hasattr(idaapi, "get_highlighted_identifier"): thing = idaapi.get_highlight(idaapi.get_current_viewer()) if thing and thing[1]: return thing[0] else: return idaapi.get_highlighted_identifier()
def finish_populating_tform_popup(self, form, popup): # Or here, after the popup is done being populated by its owner. # We will attach our action to the context menu # for the 'Functions window' widget. # The action will be be inserted in a submenu of # the context menu, named 'Others'. if idaapi.get_tform_type(form) == idaapi.BWN_CALL_STACK: #line = form.GetCurrentLine() pass elif idaapi.get_tform_type(form) == idaapi.BWN_DISASM: #regs =['eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp', 'esp', 'ax', 'bx', 'cx', 'dx', 'ah', 'al', 'bh', 'bl', 'ch', 'cl', 'dh', 'dl'] regs = idaapi.ph_get_regnames() idaapi.attach_action_to_popup(form, popup, "revCursor:action", 'RESim/') idaapi.attach_action_to_popup(form, popup, "dis:action", 'RESim/') highlighted = idaapi.get_highlighted_identifier() if highlighted is not None: if highlighted in regs: idaapi.attach_action_to_popup(form, popup, "modReg:action", 'RESim/') else: addr = getHex(highlighted) if addr is not None or regFu.isHighlightedEffective(): idaapi.attach_action_to_popup(form, popup, "rev:action", 'RESim/') idaapi.attach_action_to_popup(form, popup, "dataWatch:action", 'RESim/') idaapi.attach_action_to_popup(form, popup, "revData:action", 'RESim/') idaapi.attach_action_to_popup(form, popup, "modMemory:action", 'RESim/') idaapi.attach_action_to_popup(form, popup, "stringMemory:action", 'RESim/')
def wroteToRegister(self): highlighted = idaapi.get_highlighted_identifier() ''' if highlighted is None or highlighted not in self.reg_list: print('%s not in reg list' % highlighted) c=idaapi.Choose([], "Run backward until selected register modified", 1) c.width=50 c.list = self.reg_list chose = c.choose() if chose == 0: print('user canceled') return else: highlighted = self.reg_list[chose-1] ''' print 'Looking for a write to %s...' % highlighted command = "@cgc.revToModReg('%s')" % highlighted simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = None if self.checkNoRev(simicsString): eip = gdbProt.getEIPWhenStopped() self.signalClient() else: return curAddr = idc.GetRegValue(self.PC) print('Current instruction (0x%x) wrote to reg %s' % (curAddr, highlighted)) return eip
def run(): try: current_function = sark.Function() except sark.exceptions.SarkNoFunction: log("Cannot xref registers outside of functions.") return #register_name = idaapi.get_highlighted_identifier() # TypeError: in method 'get_highlight', argument 1 of type 'TWidget *' register_name = idaapi.get_highlighted_identifier(idaapi.get_current_tform()) # ida7.0 must give TWidget* try: register_id = get_register_identifier(register_name) except sark.exceptions.SarkInvalidRegisterName: log("Highlight a register to xref") return choose = RegisterReferencesView(current_function.name, register_name) for line in current_function.lines: if has_register_reference(line.insn, register_id): choose.add_xref(line.ea) choose.show()
def activate(self, ctx): if self.action == ACTION_HX_REMOVERETTYPE: if IDA7: vdui = idaapi.get_widget_vdui(ctx.widget) else: vdui = idaapi.get_tform_vdui(ctx.form) self.remove_rettype(vdui) vdui.refresh_ctext() elif self.action == ACTION_HX_COPYEA: ea = idaapi.get_screen_ea() if ea != idaapi.BADADDR: copy_to_clip("0x%X" % ea) print "Address 0x%X has been copied to clipboard" % ea elif self.action == ACTION_HX_COPYNAME: if IDA7: name = idaapi.get_highlight(idaapi.get_current_viewer())[0] else: name = idaapi.get_highlighted_identifier() if name: copy_to_clip(name) print "%s has been copied to clipboard" % name else: return 0 return 1
def activate(self, ctx): if self.action == ACTION_HX_REMOVERETTYPE: if IDA7: vdui = idaapi.get_widget_vdui(ctx.widget) else: vdui = idaapi.get_tform_vdui(ctx.form) self.remove_rettype(vdui) vdui.refresh_ctext() elif self.action == ACTION_HX_COPYEA: ea = idaapi.get_screen_ea() if ea != idaapi.BADADDR: copy_to_clip("0x%X" % ea) print("Address 0x%X has been copied to clipboard" % ea) elif self.action == ACTION_HX_COPYNAME: if IDA7: name = idaapi.get_highlight(idaapi.get_current_viewer())[0] else: name = idaapi.get_highlighted_identifier() if name: copy_to_clip(name) print("%s has been copied to clipboard" % name) elif self.action == ACTION_HX_GOTOCLIP: loc = parse_location(clip_text()) print("Goto location 0x%x" % loc) Jump(loc) else: return 0 return 1
def registerMath(): retval = None if regFu.isHighlightedEffective(): retval = regFu.getOffset() else: #regs =['eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp'] highlighted = idaapi.get_highlighted_identifier() retval = None if highlighted is not None: print 'highlighted is %s' % highlighted if highlighted in reg_list: retval = idc.GetRegValue(highlighted) else: try: retval = int(highlighted, 16) except: pass if retval is None: for reg in reg_list: if highlighted.startswith(reg): rest = highlighted[len(reg):] value = None try: value = int(rest[1:]) except: pass if value is not None: if rest.startswith('+'): regvalue = idc.GetRegValue(reg) retval = regvalue + value elif rest.startswith('-'): regvalue = idc.GetRegValue(reg) retval = regvalue - value return retval
def revTo(self): highlighted = idaapi.get_highlighted_identifier() addr = reHooks.getHex(highlighted) command = '@cgc.revToAddr(0x%x, extra_back=0)' % (addr) #print('cmd: %s' % command) simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % command) eip = gdbProt.getEIPWhenStopped() self.isim.signalClient()
def jump_to_calibr(): ident = idaapi.get_highlighted_identifier() if ident == None: ea = ScreenEA() addr = Word(ea + 2) else: addr = int(ident.rstrip('h'), 16) phAddr = page_addr_to_phis(addr) Jump(phAddr)
def __init__(self): super(Ui_FindVirtualCallDialog, self).__init__() self.d = QtGui.QDialog() self.setupUi(self.d) self.selected_text = idaapi.get_highlighted_identifier() self.ok_btn.clicked.connect(self.ok_btn_clicked) self.cancel_btn.clicked.connect(self.cancel_btn_clicked) visual_style.set(self.d)
def isHighlightedEffective(): ip = idc.ScreenEA() instr = idc.GetDisasm(ip) if '[' in instr: val = instr.split('[', 1)[1].split(']')[0] highlighted = idaapi.get_highlighted_identifier() if highlighted in val: return True else: return False
def show_highlighted_function_strings(): identifier = idaapi.get_highlighted_identifier() if not identifier: return try: function = sark.Function(name=identifier) show_function_strings(function) except sark.exceptions.SarkNoFunction: idaapi.msg("[FunctionStrings] {!r} is not a function.\n".format(identifier))
def activate(self, ctx): highlighted = idaapi.get_highlighted_identifier() addr = getHex(highlighted) count = idc.AskStr(last_data_watch_count, 'number of bytes to watch?') if count is None: return print('watch %s bytes from 0x%x' % (count, addr)) simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.watchData(0x%x, 0x%s)");' % (addr, count)) eip = gdbProt.getEIPWhenStopped() self.isim.signalClient() self.isim.showSimicsMessage()
def symbol(cls): '''Return the current highlighted symbol name.''' if idaapi.__version__ < 7.0: return idaapi.get_highlighted_identifier() # IDA 7.0 way of getting the currently selected text viewer = idaapi.get_current_viewer() res = idaapi.get_highlight(viewer) if res and res[1]: return res[0] return res
def getHighlight(): if idaapi.IDA_SDK_VERSION <= 699: retval = idaapi.get_highlighted_identifier() else: v = ida_kernwin.get_current_viewer() t = ida_kernwin.get_highlight(v) retval = None if t is None: print('Nothing highlighted in viewer %s' % str(v)) else: retval, flags = t return retval
def __init__(self): super(Ui_FindTextDialog, self).__init__() self.d = QtGui.QDialog() self.setupUi(self.d) self.selected_text = idaapi.get_highlighted_identifier() self.ok_btn.clicked.connect(self.ok_btn_clicked) self.cancel_btn.clicked.connect(self.cancel_btn_clicked) self.only_named_functions.setVisible(False) visual_style.set(self.d)
def activate(self, ctx): highlighted = idaapi.get_highlighted_identifier() current = idc.GetRegValue(highlighted) default = '%x' % current print('default %s' % default) #prompt = 'Value to write to %s (in hex, no prefix)' % highlighted #print('prompt is %s' % prompt) #enc = prompt.encode('utf-8') value = idc.AskStr(default, 'reg value ?') if value is None: return reg_param = "'%s'" % highlighted simicsString = gdbProt.Evalx('SendGDBMonitor("@cgc.writeRegValue(%s, 0x%s)");' % (reg_param, value))
def activate(self, ctx): # Load Needed NIDs... NEEDED_NIDS = load_nids('plugins', NEEDED) #print('Needed NIDs: %s' % NEEDED_NIDS) # Get the name from IDA... name = idaapi.get_highlighted_identifier() if name is None: print('# Error: Please select a valid string in IDA...') return 1 # Make the NID... symbol = sha1(name.encode() + uhx('518D64A635DED8C1E6B039B1C3E55230')).digest() id = struct.unpack('<Q', symbol[:8])[0] nid = base64enc(uhx('%016x' % id), b'+-').rstrip(b'=') print('%s %s' % (nid, name)) # If the NID is Needed and isn't in our list, add it! if nid in NEEDED_NIDS: print('# Found a missing NID!') # Add the NID and name to our dictionary... NEW_NIDS[nid] = name #print(NEW_NIDS) # Update the Aerolib file... save_nids('loaders', AEROLIB, NEW_NIDS) print('# Successfully updated aerolib.csv!') # Remove the nid from the New list... # Next remove the NID... NEW_NIDS.pop(nid) #print(NEW_NIDS) NEEDED_NIDS.remove(nid) #print(NEEDED_NIDS) # Update the Needed file... save_nids('plugins', NEEDED, NEEDED_NIDS) print('# Successfully updated needed_nids.txt!') print( '---------------------------------------------------------------------------------------------' ) return 1
def getOffset(): ''' Assuming an offset, e.g., "var_11" is highlighted, and assuming bp is proper, get the calculated address. ''' retval = None ip = idc.ScreenEA() print('ip is 0x%x' % ip) highlighted = idaapi.get_highlighted_identifier() print('highlighted is %s' % highlighted) ov0 = idc.GetOpnd(ip, 0) ov1 = idc.GetOpnd(ip, 1) print('op0 %s op1 %s' % (ov0, ov1)) if highlighted in ov0: index = 0 want = ov0 else: index = 1 want = ov1 ''' Convert to numberic from symbol ''' idc.OpSeg(ip, index) if '[' in want and '+' in want or '-' in want: op = idc.GetOpnd(ip, index) print('op is %s' % op) val = op.split('[', 1)[1].split(']')[0] print('val %s' % val) if '+' in val: reg, value = val.split('+') else: reg, value = val.split('-') reg_val = idc.GetRegValue(reg) try: value = value.strip('h') value = int(value, 16) except: print('unable to parse int from %s' % value) idc.OpStkvar(ip, 0) return retval if '+' in val: retval = reg_val + value else: retval = reg_val - value print('effective addr is 0x%x' % retval) ''' Convert back to symbol, e.g., var_11''' idc.OpStkvar(ip, index) return retval
def activate(self, ctx): highlighted = idaapi.get_highlighted_identifier() addr = getHex(highlighted) count = self.last_data_watch_count addr, count = getAddrCount('watch memory', addr, count) if count is None: return print('watch %d bytes from 0x%x' % (count, addr)) self.last_data_watch_count = count simicsString = gdbProt.Evalx( 'SendGDBMonitor("@cgc.watchData(0x%x, %s)");' % (addr, count)) eip = gdbProt.getEIPWhenStopped() self.isim.signalClient() self.isim.showSimicsMessage()
def __init__(self): super(QuickMenu, self).__init__() self.d = QtGui.QDialog() self.button_clicked = None self.setupUi(self.d) self.selected_text = idaapi.get_highlighted_identifier() self.reload_headers_btn.clicked.connect( self.reload_headers_btn_clicked) self.goto_btn.clicked.connect(self.goto_btn_clicked) self.find_in_headers_btn.clicked.connect( self.find_in_headers_btn_clicked) self.find_in_decompiled_menu = QtGui.QMenu("", self.d) self.find_text_action = self.find_in_decompiled_menu.addAction( "Text/Var") self.find_virtual_call_action = self.find_in_decompiled_menu.addAction( "Virtual Call") self.find_text_action.triggered.connect(self.find_text_btn_clicked) self.find_virtual_call_action.triggered.connect( self.findvcall_btn_clicked) self.find_in_decompiled_btn.setMenu(self.find_in_decompiled_menu) self.rename_menu = QtGui.QMenu("", self.d) self.rename_class_action = self.rename_menu.addAction("Class") self.rename_class_action.triggered.connect(self.rename_class_clicked) self.rename_var_action = self.rename_menu.addAction("Variable") self.rename_var_action.triggered.connect(self.rename_btn_clicked) self.rename_btn.setMenu(self.rename_menu) self.create_menu = QtGui.QMenu("", self.d) self.create_class_action = self.create_menu.addAction("Class") self.create_var_action = self.create_menu.addAction("Variable") self.create_vtable_action = self.create_menu.addAction("VTable struct") self.create_class_action.triggered.connect( self.create_class_btn_clicked) self.create_var_action.triggered.connect(self.create_var_btn_clicked) self.create_vtable_action.triggered.connect( self.create_vtable_btn_clicked) self.create_btn.setMenu(self.create_menu) visual_style.set(self.d)
def __init__(self): super(Ui_CreateVTableDialog, self).__init__() txt = idaapi.get_highlighted_identifier() print txt start_ea = decompiled.get_ea(txt) if txt else idc.here() print start_ea self.d = QtGui.QDialog() self.setupUi(self.d) self.ok_btn.clicked.connect(self.ok_btn_clicked) self.cancel_btn.clicked.connect(self.cancel_btn_clicked) self.name_edit.textChanged.connect(self.name_changed) self.prefix_name.textChanged.connect(self.prefix_changed) self.header_file_cb.clicked.connect(self.header_cb_switched) visual_style.set(self.d) self.vtable = decompiled.VirtualTable(start_ea) self.redraw()
def highlight_symbol_in_DECOMP(): """ Select a symbol in the IDA DISASM view, highlight the corresponding symbol in DECOMP view. """ # print("GhIDA:: [DEBUG] highlight_symbol_in_DECOMP called") symbol = idaapi.get_highlighted_identifier() if not symbol: return converted_symbol = from_ida_to_ghidra_syntax_conversion(symbol) decompiler_widget = idaapi.find_widget('Decompiled Function') if converted_symbol: # Update IDA DECOMP view idaapi.set_highlight(decompiler_widget, converted_symbol, 1) else: idaapi.set_highlight(decompiler_widget, 'aaabbbccc', 1) return
def decode(): ea = ScreenEA() if ea == idaapi.BADADDR: idaapi.msg(PLUGIN_NAME + " ERROR: Could not get get_screen_ea()") return str_id = idaapi.get_highlighted_identifier() if not str_id: idaapi.msg(PLUGIN_NAME + " ERROR: No Ioctl Code highlighted!") return try: if str_id[-1] == 'h': code = int(str_id[:-1], 16) elif str_id[-1] == 'o': code = int(str_id[:-1], 8) elif str_id[-1] == 'b': code = int(str_id[:-1], 2) else: code = int(str_id) except ValueError: idaapi.msg(PLUGIN_NAME + " ERROR: Not a valid Ioctl Code: " + str(str_id)) return try: decoder = IOCTL_Decoder(code) ioctl_data = decoder.decode() #print decoded IOCTL to cli msg_string = "That IOCTL decodes to: \n\tDevice: %s \n\tFunction: %s \n\tAccess: %s \n\tMethod: %s" idaapi.msg(msg_string % (ioctl_data["device"], ioctl_data["function"], ioctl_data["access"], ioctl_data["method"])) #add decoded IOCTL as comment comment_string = "dwIoControlCode: \n\t\tDevice: %s \n\t\tFunction: %s \n\t\tAccess: %s \n\t\tMethod: %s" idaapi.set_cmt( ea, comment_string % (ioctl_data["device"], ioctl_data["function"], ioctl_data["access"], ioctl_data["method"]), 0) except Exception as e: idaapi.msg(PLUGIN_NAME + " ERROR: " + str(e)) return
def activate(self, ctx): if regFu.isHighlightedEffective(): addr = regFu.getOffset() simicsString = gdbProt.Evalx( 'SendGDBMonitor("@cgc.getMemoryValue(0x%x)");' % addr) print('effective addr 0x%x value %s' % (addr, simicsString)) value = simicsString else: highlighted = idaapi.get_highlighted_identifier() addr = getHex(highlighted) if addr is None: print('ModMemoryHandler unable to parse hex from %s' % highlighted) return simicsString = gdbProt.Evalx( 'SendGDBMonitor("@cgc.getMemoryValue(0x%x)");' % addr) print('addr 0x%x value %s' % (addr, simicsString)) value = simicsString # Sample form from kernwin.hpp s = """Modify memory Address: %$ <~E~nter value:t40:80:50::> """ ti = idaapi.textctrl_info_t(value) ok = idaapi.AskUsingForm( s, Form.NumericArgument('$', addr).arg, idaapi.pointer(idaapi.c_void_p.from_address(ti.clink_ptr))) ''' string = Form.StringArgument(value) ok = idaapi.AskUsingForm(s, Form.NumericArgument('$', addr).arg, string.arg) ''' if ok == 1: arg = "'%s'" % ti.text.strip() print("You entered: %s <%s>" % (ti.text, arg)) cmd = "@cgc.writeString(0x%x, %s)" % (addr, arg) print cmd simicsString = gdbProt.Evalx('SendGDBMonitor("%s");' % (cmd)) time.sleep(1) idc.RefreshDebuggerMemory()
def activate(self, ctx): if self.action == ACTION_HX_REMOVERETTYPE: vdui = idaapi.get_tform_vdui(ctx.form) self.remove_rettype(vdui) vdui.refresh_ctext() elif self.action == ACTION_HX_COPYEA: vdui = idaapi.get_tform_vdui(ctx.form) ea = vdui.item.get_ea() if ea != idaapi.BADADDR: copy_to_clip("0x%X" % ea) print "Address 0x%X has been copied to clipboard" % ea elif self.action == ACTION_HX_COPYNAME: name = idaapi.get_highlighted_identifier() if name: copy_to_clip(name) print "%s has been copied to clipboard" % name else: return 0 return 1
def rename_immediate(): highlighted = idaapi.get_highlighted_identifier() try: desired = int(highlighted, 0) except (ValueError, TypeError): desired = None value = idc.AskLong(get_common_value(desired), "Const Value") if value is None: return name = idc.AskStr("", "Constant Name") if name is None: return try: enum = sark.Enum('GlobalConstants') except sark.exceptions.EnumNotFound: enum = sark.add_enum('GlobalConstants') enum.members.add(name, value) apply_enum_by_name(enum, name)
def openMsdnPageInBrowser(): # Get the highlighted identifier searchTerm = idaapi.get_highlighted_identifier() # Get the address ea = ScreenEA() # Make sure we have something highlighted if not searchTerm: print "(msdnGrab) Error: No identifier to use as search term was highlighted." return None # Select "language" languages = ['Win32 API', 'C/C++'] chooser = QuietChooser([], "(Open in browser) Language to query", 1) # Get a modal Choose instance chooser.list = languages # List to choose from chooser.width = 40 # Set the width ch = chooser.choose() # Run the chooser # Decode the selection if (chooser.list[ch-1] == 'Win32 API'): searchType = _SEARCHTYPE_WIN32API elif (chooser.list[ch-1] == 'C/C++'): searchType = _SEARCHTYPE_C else: print '(msdnGrab) Error: Invalid language type selection made.' return None # Handle IDA's naming conventions for the identifier searchTerm = searchTerm.replace('__imp_', '') print '(msdnGrab) Using search term: %s' % searchTerm # Get the MSDN page URL msdnUrl = grabMsdnPageFromGoogle(searchTerm, searchType) if (msdnUrl is None): print '(msdnGrab) Error: Could not find a suitable MSDN page.' return None # Launch the browser webbrowser.open(msdnUrl)
def launch(self): text = idaapi.get_highlighted_identifier() parse_result = parse_c_str(text) self.old_var_name_edit.setText(parse_result.varname) l = self.field_to_struct_table.get(parse_result.varname,[]) if len(l) == 1: self.class_cb.setEditText(l[0]) new_var = "m_" + decompiled.struct_name_hint(l[0]) + "_unkn_var_" index = 1 while "%s%s"%(new_var,index) in self.old_struct.names(): index+=1 new_var = "%s%s"%(new_var,index) self.newvar_name_edit.setText(parse_result.newtype + " " + new_var) else: self.newvar_name_edit.setText(parse_result.newtype + " m_unkn_var_1") self.array_index_edit.setText(str(parse_result.arr_index)) self.d.exec_()
def run(self, arg): # Get the highlighted identifier id = idaapi.get_highlighted_identifier() if not id: print "No identifier was highlighted" return import webbrowser try: import feedparser except: idaapi.warning('Feedparser package not installed') return id = self.sanitize_name(id) print "Looking up '%s' in MSDN online" % id d = feedparser.parse("http://social.msdn.microsoft.com/Search/Feed.aspx?locale=en-us&format=RSS&Query=%s" % id) if len(d['entries']) > 0: url = d['entries'][0].link webbrowser.open_new_tab(url) else: print "API documentation not found for: %s" % id
def symbol(cls): """Return the symbol name directly under the cursor""" return idaapi.get_highlighted_identifier()
def symbol(cls): '''Return the current highlighted symbol name.''' return idaapi.get_highlighted_identifier()
def grabDefinitionFromMsdn(searchType): # Get the highlighted identifier searchTerm = idaapi.get_highlighted_identifier() # Get the address ea = ScreenEA() # Make sure we have something highlighted if not searchTerm: print "(msdnGrab) Error: No identifier to use as search term was highlighted." return None # Handle IDA's naming conventions for the identifier searchTerm = searchTerm.replace('__imp_', '') print '(msdnGrab) Using search term: %s' % searchTerm # Get the MSDN page URL msdnUrl = grabMsdnPageFromGoogle(searchTerm, searchType) while (msdnUrl is None): # Try again, in case underscores are causing trouble if (searchTerm.startswith('_')): searchTerm = searchTerm[1:] print '(msdnGrab) Using search term: %s' % searchTerm msdnUrl = grabMsdnPageFromGoogle(searchTerm, searchType) else: print '(msdnGrab) Error: Could not find a suitable MSDN page.' return None # Read the page opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] page = opener.open(msdnUrl).read() page = page.replace('\xc2\xa0', ' ') soup = bs4.BeautifulSoup(page) # Find the first (code) definition dbgPrint('Searching for code...') code = 'No code found.' for code in soup.findAll('pre'): code = stripBlankLines(stripTags(code)) dbgPrint('Code found: \n%s' % code) if (code != ''): break code = code.replace('\r', '') # Find the description dbgPrint('Searching for description...') desc = 'No description found.' for desc in soup.findAll('p'): desc = stripBlankLines(stripTags(desc)).strip() dbgPrint('Description found: \n%s' % desc) if (desc != '' and 'updated' not in desc.lower() and 'applies to' not in desc.lower() and 'rated this helpful' not in desc.lower() and not desc.startswith('[') and not desc.endswith(']') ): break # Pretty format the description desc = stripBlankLines(stripTags(desc)) # Find the actual library call codeReferences = list(XrefsFrom(ea, 1)) if (codeReferences == []): nextEa = ea else: nextEa = codeReferences[0].to # Put it as a repeatable comment (don't clobber existing comment) print '(msdnGrab) Setting repeatable comment at 0x%s:' % str(hex(nextEa)) print desc print code print '' if ('data' in idc.SegName(nextEa)): ''' Assume we're in an external library. The behavior of GetFunctionCmt() and RptCmt() is different. The check for None and '' is for robustness, although it looks quirky. Handles both cases. Nothing will fail otherwise, just that the output will have a double line space when it's not needed. ''' existingComment = idc.RptCmt(nextEa) if (existingComment is None or existingComment == ''): existingComment = '' else: existingComment = existingComment + '\n\n' idc.MakeRptCmt(nextEa, existingComment + multiLineString(desc) + '\n\n' + code) else: ''' Assume we're in code. The behavior of GetFunctionCmt() and RptCmt() is different. The check for None and '' is for robustness, although it looks quirky. Handles both cases. Nothing will fail otherwise, just that the output will have a double line space when it's not needed. ''' existingComment = idc.GetFunctionCmt(nextEa, COMMENT_REPEATABLE) if (existingComment is None or existingComment == ''): existingComment = '' else: existingComment = existingComment + '\n\n' idc.SetFunctionCmt(nextEa, existingComment + multiLineString(desc) + '\n\n' + code, COMMENT_REPEATABLE) # Refresh the screen idc.Refresh()
def _profile_function(self): current_ea = ScreenEA() current_function = idc.GetFunctionName(current_ea) current_function_ea = idc.LocByName(current_function) if current_function: self.function = current_function ea = start_ea = idc.GetFunctionAttr(current_function_ea, idc.FUNCATTR_START) end_ea = idc.GetFunctionAttr(current_function_ea, idc.FUNCATTR_END) self.highlighted = idaapi.get_highlighted_identifier() while ea < end_ea and ea != idc.BADADDR and self.highlighted: i = 0 match = False optype = self.READ comment = None idaapi.decode_insn(ea) mnem = idc.GetMnem(ea) if self.highlighted in mnem: match = True elif idaapi.is_call_insn(ea): for xref in idautils.XrefsFrom(ea): if xref.type != 21: name = idc.Name(xref.to) if name and self.highlighted in name: match = True break else: while True: opnd = idc.GetOpnd(ea, i) if opnd: if self.highlighted in opnd: match = True if (idaapi.insn_t_get_canon_feature(idaapi.cmd.itype) & self.OPND_WRITE_FLAGS[i]): optype = self.WRITE i += 1 else: break if not match: comment = idc.GetCommentEx(ea, 0) if comment and self.highlighted in comment: match = True else: comment = idc.GetCommentEx(ea, 1) if comment and self.highlighted in comment: match = True else: comment = None if match: if ea > current_ea: direction = self.DOWN elif ea < current_ea: direction = self.UP else: direction = self.THIS self.xrefs[ea] = { 'offset' : idc.GetFuncOffset(ea), 'mnem' : mnem, 'type' : optype, 'direction' : direction, 'text' : idc.GetDisasm(ea), } ea += idaapi.cmd.size