def saveTypeMenu(self): """Open an input dialog to save the current type definiton""" type_defs = blackboxprotobuf.known_messages.keys() type_defs.insert(0, "New...") selection = JOptionPane.showInputDialog( self._component, "Select name for type", "Type selection", JOptionPane.PLAIN_MESSAGE, None, type_defs, None) if selection is None: return elif selection == "New...": selection = JOptionPane.showInputDialog("Enter new name") blackboxprotobuf.known_messages[selection] = self.message_type self._extender.suite_tab.updateList()
def getBlockOccupiedByLocoFromUser(self, loc): # get a list of occupied blocks with no values blist = ['not in use'] for blockName in (SOUTH_SIDINGS + NORTH_SIDINGS + [NORTH_REVERSE_LOOP, SOUTH_REVERSE_LOOP, 'North Link']): blk = blocks.getBlock(blockName) if blk.getState() != OCCUPIED: continue if blk.getValue() is not None and blk.getValue() != "": continue blist.append(blockName) # put up a dropbox for the user to select the block self.debug("getting block from user") b = JOptionPane.showInputDialog(None, "Select starting block for " + loc.nameAndAddress(), "Choose block", JOptionPane.QUESTION_MESSAGE, None, blist, 'not in use') if b is None: # User cancelled return False if b != "not in use": # set the block loc.setBlock(b) elif b == 'multi': raise RuntimeError("loco", loc.nameAndAddress(), "is in more than one block")
def checkForRetiringLocos(self): m = memories.provideMemory("IMRETIRELOCO") if m.getValue() is not None and m.getValue() != "" and m.getValue() != 0: # put up a dropbox for the user to select the loco b = JOptionPane.showInputDialog(None, "Select loco to retire", "Loco to retire", JOptionPane.QUESTION_MESSAGE, None, map(lambda l: l.nameAndAddress(), self.locos), self.locos[0].nameAndAddress()) if b is None: # User cancelled sen = sensors.getSensor("Retire Loco") sen.setKnownState(INACTIVE) return False for l in self.locos: if l.nameAndAddress() == b: # found the loco self.debug("retiring loco " + b) # see if this loco is on a journey for m in self.memories: bits = m.split('-') self.debug("bit[1]: " + bits[1]) if int(bits[1]) == l.dccAddr: # set a memory so the journey picks it up mem = memories.provideMemory('IMRETIREDLOCO') self.debug("setting IMRETIREDLOCO to value " + str(l.dccAddr)) mem.setValue(l.dccAddr) else: self.debug(bits[1] + " != " + str(l.dccAddr)) self.locos.remove(l) self.retiredlocos.append(l) sen = sensors.getSensor("Retire Loco") sen.setKnownState(INACTIVE)
def checkForNewLocos(self): m = memories.provideMemory("IMNEWLOCO") if m.getValue() is not None and m.getValue() != "" and m.getValue() != 0: addr = JOptionPane.showInputDialog("DCC address of new loco:") if addr != "" and addr is not None and int(addr) > 0: loc = self.getNewLoco(int(addr)) try: loc.rosterEntry() except: self.debug("no roster entry for address " + str(addr)) # incorrect dcc addr self.locos.remove(loc) del loc return try: self.getLocoThrottle(loc) except RuntimeError: # idiot at the keyboard entered wrong dcc addr self.locos.remove(loc) del loc return loc.emergencyStop() b = loc.initBlock() if b is None: if self.getBlockOccupiedByLocoFromUser(loc) is not False: if loc.block is not None: self.locos.append(loc) m.setValue(None) sen = sensors.getSensor("Add Loco") sen.setKnownState(INACTIVE)
def vulnNameChanged(self): if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "": self.addButton.setText("Update") elif self.addButton.getText() != "Add": options = ["Create a new vulnerability", "Change current vulnerability name"] n = JOptionPane.showOptionDialog(None, "Would you like to?", "Vulnerability Name", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, None, options, options[0]); if n == 0: self.clearVulnerabilityTab(False) self.addButton.setText("Add") else: newName = JOptionPane.showInputDialog( None, "Enter new name:", "Vulnerability Name", JOptionPane.PLAIN_MESSAGE, None, None, self.vulnName.getText()) row = self.logTable.getSelectedRow() old = self.logTable.getValueAt(row,1) self.changeVulnName(newName,old)
def getInputRoleClick(self, e): newRole = JOptionPane.showInputDialog(self._splitpane, "Enter New Role:") if not newRole is None: self._db.getOrCreateRole(newRole) self._userTable.redrawTable() self._messageTable.redrawTable()
def setPayload(self, event): proto = 0 httpRequestResponse = self.context.getSelectedMessages() for currentRequest in httpRequestResponse: parentFrame = JFrame() cmd = JOptionPane.showInputDialog( parentFrame, "File path to read from remote host. Ex:/etc/passwd") headers = list( self._helpers.analyzeRequest(currentRequest).getHeaders()) newMessage = self._helpers.buildHttpMessage(headers, None) if currentRequest.getHttpService().getProtocol() == 'https': proto = 1 hp = str( self._helpers.analyzeRequest( currentRequest.getRequest()).getHeaders()) for p in self._helpers.analyzeRequest( currentRequest.getRequest()).getParameters(): if p.getName() not in hp: if 'lumPrevParams' in p.getName(): newParam = self._helpers.buildParameter( p.getName(), PAYLOAD.format(cmd), IParameter.PARAM_BODY) newMessage = self._helpers.addParameter( newMessage, newParam) else: newParam = self._helpers.buildParameter( p.getName(), p.getValue(), IParameter.PARAM_BODY) newMessage = self._helpers.addParameter( newMessage, newParam) self._callbacks.sendToRepeater( currentRequest.getHttpService().getHost(), currentRequest.getHttpService().getPort(), proto, newMessage, None)
def obtain_prefixes(self): self.sourceDir = DirectoryChooser( "Choose directory to load stack from").getDirectory() os.chdir(self.sourceDir) curdir = os.getcwd() listdire = os.listdir(curdir) prefixlist = [] prefix_len = JOptionPane.showInputDialog( None, "how long is the file prefix to group by?(integer value only)") for name in listdire: if ".tif" in name: prefixname = name[:int(prefix_len)] prefixlist.append(prefixname) unique_prefix = sorted(set(prefixlist)) self.pref_dict = {} for a in unique_prefix: pref_list = [] for b in listdire: if b.startswith(a): pref_list.append(b) self.pref_dict[a] = pref_list return self.pref_dict
def go(self): self.initTracks() # set jeckstatus() old_status = self.getJackStatus() mem = memories.provideMemory('IMJACKSTATUS') mem.setValue(NORMAL) # If there's a loco on the North Link then that one needs to be # moved before any of the others. This var keeps track of which # loco it is northLinkLoco = None # gather up the locos addresses = [] for t in self.tracks: for b in t.blocks: blk = blocks.getBlock(b) self.debug('checking block ' + b) if blk.getState() == OCCUPIED: addr = blk.getValue() if addr is None or addr == '': addr = JOptionPane.showInputDialog("DCC addr of loco in: " + blk.getUserName()) addr = int(addr) if not addr in addresses: self.debug("getting loco for " + str(addr)) l = loco.Loco(addr) self.debug("getting throttle for " + str(addr)) self.getLocoThrottle(l) self.locos.append(l) l.setBlock(blk) addresses.append(addr) if blk.getUserName() == 'North Link': northLinkLoco = l # keep looping until we've gone through the whole list # and failed on all of them locolist = self.locos[:] if northLinkLoco and northLinkLoco in locolist: # move it to the front of the queue locolist.remove(northLinkLoco) locolist.insert(0, northLinkLoco) keepGoing = True while keepGoing: keepGoing = False for l in locolist: if l.isInSidings(): continue self.debug("trying to move " + l.nameAndAddress()) self.loco = l rc = self.moveToASiding() if rc: locolist.remove(l) keepGoing = True mem = memories.provideMemory('IMJACKSTATUS') mem.setValue(old_status) return False
def alpha_combo(): Phases.InstallPhase = JOP.showInputDialog(None, "Which phase of the installation do you want?", "Phase", JOP.QUESTION_MESSAGE, None, Settings.tInstallPhaseE, Settings.tInstallPhaseE[0])
def decode_session(self, invocation): secret_key = JOptionPane.showInputDialog(None, "secret_key:", "input", JOptionPane.QUESTION_MESSAGE) invMessage = invocation.getSelectedMessages() request = invMessage[0].getRequest().tostring() select_msg_index = invocation.getSelectionBounds() select_cookie = request[select_msg_index[0]:select_msg_index[1]] decode(select_cookie, secret_key)
def setCols(self, event): try: text = JOptionPane.showInputDialog(self.view.frame, 'Specify the number of columns in the grid:', "Set column count", JOptionPane.PLAIN_MESSAGE, None, None, None) self.cols = int(text) if self.cols < 1: self.cols = 1 except: self.cols = None
def setRows(self, event): try: text = JOptionPane.showInputDialog(self.view.frame, 'Specify the number of rows in the grid:', "Set row count", JOptionPane.PLAIN_MESSAGE, None, None, None) self.rows = int(text) if self.rows < 1: self.rows = 1 except: pass
def translate(query, src, dst): global key if src == 'Automatic': src = 'auto' else: src = langs.get(src) dst = langs.get(dst) query = cb.helpers.urlEncode(query) if key == '': key = JOptionPane.showInputDialog( 'Please enter a valid Google Cloud Translation API key to continue.\n' 'See the source code for details of how the key can be hardcoded.\n\n' 'If you wish to use this extension without an API key, just click OK.' ) if key == "" or key == "GoogleTranslateAPI": # -- Google Translate API key = "GoogleTranslateAPI" host = 'translate.googleapis.com' path = 'translate_a/single' params = 'client=gtx&dt=t&ie=UTF-8&oe=UTF-8&sl=%s&tl=%s&q=%s' % ( src, dst, query) def result(r): return r[0][0][0] def result_src(r): return r[2] # -- End Google Translate API else: # -- Google Cloud Translation API if src == 'auto': src = '' params = 'format=text&source=%s&target=%s&q=%s&key=%s' % ( src, dst, query, key) host = 'translation.googleapis.com' path = 'language/translate/v2' def result(r): return r['data']['translations'][0]['translatedText'] if src == '': def result_src( r): return r['data']['translations'][0]['detectedSourceLanguage'] else: def result_src(r): return src # -- End Google Cloud Translation API url = URL('https://%s/%s?%s' % (host, path, params)) request = cb.helpers.buildHttpRequest(url) request = cb.helpers.toggleRequestMethod(request) service = cb.helpers.buildHttpService(host, 443, 'https') requested = cb.callbacks.makeHttpRequest(service, request) response = cb.helpers.bytesToString(requested.getResponse()) info = cb.helpers.analyzeResponse(response) body = response[info.getBodyOffset():] data = json.loads(body) return(result(data), next(key for key, value in langs.items() if value == result_src(data)))
def mouseClicked(self, s, g) : x = JOptionPane.showInputDialog(self.client_state, "Type your text here:") if x is None: x = '' bout = ByteArrayOutputStream() eout = EscapingOutputStream(bout) eout.write(x) y = bout.toString() return self._getmetadata() + "|" + "(%d,%d)|%s " % (s.x, s.y, y)
def watchVariable(self): """ Opens a dialog, asking the user to add a variable to the watcher. """ var = JOptionPane.showInputDialog(self.gui, "Please enter a variable to watch.", "Watcher", JOptionPane.INFORMATION_MESSAGE, None, None, "") if var is not None: self.watcher.addVariable(var)
def clickhere(event): lst.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION print "clicked" selecteditems = lst.selectedValues[:] #print selecteditems closeQuery = JOptionPane.showInputDialog( None, "You have selected " + "\n" + str(selecteditems) + "\n" + "Proceed?") frame.setVisible(False)
def ask_for_value(title, message, initial_value, is_value_array): value = JOptionPane.showInputDialog( UIHelpers._get_parent_frame(), message, title, JOptionPane.PLAIN_MESSAGE, None, None, InfrastructureHelpers.join(initial_value) if is_value_array else initial_value) if value is not None and is_value_array: return InfrastructureHelpers.split(value) return value
def getUserDropdownSelection(title, message, selectionElements): elementStrings = [e.getQualifiedName() for e in selectionElements] input = JOptionPane.showInputDialog(None, message, title, JOptionPane.PLAIN_MESSAGE, None, elementStrings, None) if input is not None: index = elementStrings.index(input) return selectionElements[index] return input
def Find( self, event ) : result = JOptionPane.showInputDialog( self.frame, # parentComponent 'Text to be found:' # message text ) self.table.getModel().setFindText( result ) self.table.getRowSorter().setRowFilter( sectionFilter() )
def input(self, message='Please enter your name:'): """Get the player's name""" from javax.swing import JOptionPane answer = (JOptionPane.showInputDialog(frame, message)) if answer: return answer elif answer == "": return "Unknown" else: return answer
def input(self, message, options=None, default=0, title="GeoGebra", message_type='question'): message_type = message_types[message_type] if options is not None: if isinstance(options, basestring): options = options.split("/") default = options[default] return JOptionPane.showInputDialog( self.api.appFrame, message, title, message_type, None, options, default or "" )
def main(): code_version = '24Aug2021' # Get the config file stored on Github. # This allows new scripts to be added without this script needing to be replaced on every PC/Server Watershed remote_repo = "https://raw.githubusercontent.com/usace/rts-utils/master" remote_config = get_remote_data( remote_repo + '/script_downloader/downloader_config.json') # Verify remote data was returned, otherwise exit if remote_config == False: errMsg = 'Failed to read remote config file.\n' JOptionPane.showMessageDialog(None, errMsg, "Config Error", JOptionPane.ERROR_MESSAGE) return appConfig = json.loads(remote_config) # Check to see if script downloader needs to be updated (by itself) fileVersion = appConfig['version'] code_version_dt = datetime.datetime.strptime(code_version, '%d%b%Y') file_version_dt = datetime.datetime.strptime(fileVersion, '%d%b%Y') if code_version_dt < file_version_dt: msg = "Script Downloader is out of date, please update using this script.\nLatest version: "\ +appConfig['version']+'\nYour version: '+code_version JOptionPane.showMessageDialog(None, msg, "Version Check", JOptionPane.ERROR_MESSAGE) else: print('Script Downloader Version is current.') choices = appConfig['scripts'].keys() choices.sort() selection = JOptionPane.showInputDialog( None, # dialog parent component "Select the script to downloader", # message "Script Downloader - v" + code_version, # title JOptionPane.PLAIN_MESSAGE, # message type (sets default icon) None, # icon to override default choices, # list of selections choices[0]) # initial selection # If cancel was clicked if selection is None: return script_filename = appConfig['scripts'][selection]['filename'] script_downloader(remote_repo, selection, appConfig) print("Script complete")
def managePlugins(self): try: self.installer.checkPluginDirectory() plugins = self.installer.getAllPluginInfo() if not plugins: JOptionPane.showMessageDialog( self.parentWindow, "No plugins are installed.\n" "If you have a plugin that you wish to install, " "select \"Install Plugin...\" from the \"File\" menu.", TITLE, JOptionPane.ERROR_MESSAGE) return pluginsByDisplay = dict( (info['display'] + ' - ' + info['status'], info) for info in plugins.values()) pluginNames = pluginsByDisplay.keys() pluginNames.sort() while True: name = JOptionPane.showInputDialog( self.parentWindow, "Here are the installed plugins.\n" "Select a plugin to see its description or uninstall it.", TITLE, JOptionPane.QUESTION_MESSAGE, None, pluginNames, pluginNames[0]) if name is None or name not in pluginsByDisplay: return info = pluginsByDisplay[name] message = info['longDescription'] + '\n' + info['note'] if info['isInstalled']: choice = JOptionPane.showOptionDialog( self.parentWindow, message, TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, None, ["OK", "Uninstall"], "OK") if choice == JOptionPane.NO_OPTION: if not self.confirm( "Are you sure you want to uninstall\n%s?" % info['display']): return self.installer.uninstall(info) self.notifyDone("%s was removed." % info['title']) return else: JOptionPane.showMessageDialog( self.parentWindow, message, TITLE, JOptionPane.INFORMATION_MESSAGE) except (EnvironmentError, InvalidPluginError), exc: self.showErrorMessage(exc)
def managePlugins(self): try: self.installer.checkPluginDirectory() plugins = self.installer.getAllPluginInfo() if not plugins: JOptionPane.showMessageDialog(self.parentWindow, "No plugins are installed.\n" "If you have a plugin that you wish to install, " "select \"Install Plugin...\" from the \"File\" menu.", TITLE, JOptionPane.ERROR_MESSAGE ) return pluginsByDisplay = dict((info['display'] + ' - ' + info['status'], info) for info in plugins.values()) pluginNames = pluginsByDisplay.keys() pluginNames.sort() while True: name = JOptionPane.showInputDialog(self.parentWindow, "Here are the installed plugins.\n" "Select a plugin to see its description or uninstall it.", TITLE, JOptionPane.QUESTION_MESSAGE, None, pluginNames, pluginNames[0] ) if name is None or name not in pluginsByDisplay: return info = pluginsByDisplay[name] message = info['longDescription'] + '\n' + info['note'] if info['isInstalled']: choice = JOptionPane.showOptionDialog(self.parentWindow, message, TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, None, ["OK", "Uninstall"], "OK" ) if choice == JOptionPane.NO_OPTION: if not self.confirm("Are you sure you want to uninstall\n%s?" % info['display']): return self.installer.uninstall(info) self.notifyDone("%s was removed." % info['title']) return else: JOptionPane.showMessageDialog(self.parentWindow, message, TITLE, JOptionPane.INFORMATION_MESSAGE ) except (EnvironmentError, InvalidPluginError), exc: self.showErrorMessage(exc)
def set_value(self, event): try: example = ','.join(['%1.1f' % random.uniform(-5, 5) for i in range(len(self.sliders))]) text = JOptionPane.showInputDialog(self.view.frame, 'Enter input value. \nExample: %s' % example, "Set value", JOptionPane.PLAIN_MESSAGE, None, None, None) v = eval(text) if isinstance(v, (int, float)): v = [v] if len(v) > len(self.sliders): v = v[:len(self.sliders)] for i, vv in enumerate(v): self.set_slider_value(i, vv) except: self.release_value(event)
def add_typedef(self): type_name = JOptionPane.showInputDialog("Enter new name") # Error out if already defined if type_name in default_config.known_types: JOptionPane.showMessageDialog( self._component, 'Message type "%s" already exists' % type_name, ) return self._extension.open_typedef_editor( {}, self.create_save_callback(type_name))
def saveHeaders(self, event): savedHeadersTitle = JOptionPane.showInputDialog( "Please provide saved headers title:") self._extender.savedHeaders.append({ 'title': savedHeadersTitle, 'headers': self._extender.replaceString.getText() }) self._extender.savedHeadersTitlesCombo.setModel( DefaultComboBoxModel(self.getSavedHeadersTitles())) self._extender.savedHeadersTitlesCombo.getModel().setSelectedItem( savedHeadersTitle)
def getFileName(latestDir,ff = ""): ff = JOptionPane.showInputDialog( None, "Output Filename", "What are we naming this scenario?", JOptionPane.PLAIN_MESSAGE, None, None, ff) if ff and len(ff) > 0: if not ff.endswith(".xml"): ff+=".xml" return latestDir + os.sep + ff return None
def new_session(self, evt): """Listener for New Session button.""" name = JOptionPane.showInputDialog(None, "Name the new session:", "Session name") if name != None: from_request = JOptionPane.showConfirmDialog(None, "Create session from current request?", "From current request?", JOptionPane.YES_NO_OPTION) self._extender.sm.new_session(name) self.refresh_sessions() # let user select parameters for new session if from_request == JOptionPane.OK_OPTION: dialog = SessionFromRequestDialog(self) dialog.setVisible(True)
def run(x): gl.clearLog() project = Application.getInstance().getProjectsManager().getActiveProject() SEM = project.getSymbolElementMap() possibilities = None id = JOptionPane.showInputDialog( None, "Element ID", "Find Element", JOptionPane.PLAIN_MESSAGE, None, possibilities, None) if id and len(id)>0: id = id.strip() id = id.lstrip("sig") gl.log("looking for %s" % id) try: element = project.getElementByID(id) except: MPUtils.handleException("Can't find an element matching this ID.") return if not element: gl.log("Can't find element matching this ID.") return gl.log("Found Element with ID = " + str(id) + ": ") try: gl.log(" Name: %s" % element.name) except: try: gl.log(" HumanName: %s" % element.humanName) except: pass gl.log(" Type: %s" % element.humanType) try: symbols = SEM.getAllPresentationElements(element) except: MPUtils.handleException("Can't find symbols matching this ID.") return if symbols: if len(symbols)>1: for s in symbols: if s: gl.log("MULTIPLE SYMBOLS!! " + str(s) + " in diagram " + str(s.getDiagramPresentationElement())) else: gl.log("MULTIPLE SYMBOLS!! " + str(s) ) gl.log("choosing first symbol") if len(symbols)>0: sym = symbols[0] if sym: diagram = sym.getDiagramPresentationElement() diagram.open() sym.setSelected(True) else: gl.log("wtf?") else: gl.log("No symbols found for componentId=" + str(id)) else: gl.log("barrrf")
def hilightText(self, event): result = JOptionPane.showInputDialog( self.frame, # parentComponent 'What text do you want to highlight?' # message text ) if result != None: self.textField.setText(result) index = self.tabs.getSelectedIndex() name = self.tabs.getTitleAt(index) self.hilightTextPane(self.tPanes[name][0], result) if len(self.tPanes[name]) > 1: table = self.tPanes[name][1] table.getCellRenderer(0, 0).setHiText(result) table.repaint()
def set_fixed_y(self, event): example = '%s,%s' % (-self.last_maxy, self.last_maxy) text = JOptionPane.showInputDialog(self.view.frame, 'Enter y-axis range. \nExample: %s' % example, "Set Y-Axis Range", JOptionPane.PLAIN_MESSAGE, None, None, None) if text == '': self.fixed_y = None else: try: v = eval(text) if isinstance(v, (int, float)): v = [v, v] if len(v) > 2: v = v[:2] self.fixed_y = v except: self.fixed_y = None
def unwatchVariable(self): """ Opens a dialog, asking the user to remove a variable from the watcher. """ allVars = self.watcher.variablesToTrack if len(allVars) > 0: var = JOptionPane.showInputDialog(self.gui, "Choose a variable to stop watching.", "Watcher", JOptionPane.INFORMATION_MESSAGE, None, allVars, allVars[0]) if var is not None: self.watcher.removeVariable(var) else: JOptionPane.showMessageDialog(self.gui, "There are no variables being watched.", "Watcher", JOptionPane.ERROR_MESSAGE)
def __init__(self): self.events = [] self.timeScale = float(3.0) #animation sped up by this factor ts = JOptionPane.showInputDialog(None, "Increase speed by factor of...", "Set Timescale", JOptionPane.PLAIN_MESSAGE, None, None, "3.0") try: if ts and float(ts): self.timeScale = float(ts) except: pass gl.log("using timescale: %s" % str(self.timeScale)) self.frame = None if usingDialogs: self.frame = Application.getInstance().getMainFrame()
def new_session(self, evt): """Listener for New Session button.""" name = JOptionPane.showInputDialog(None, "Name the new session:", "Session name") if name != None: from_request = JOptionPane.showConfirmDialog( None, "Create session from current request?", "From current request?", JOptionPane.YES_NO_OPTION) self._extender.sm.new_session(name) self.refresh_sessions() # let user select parameters for new session if from_request == JOptionPane.OK_OPTION: dialog = SessionFromRequestDialog(self) dialog.setVisible(True)
def modifyHeader(self, x): if x.getSource().text == 'inputIP': # 通过获取当前点击的子菜单的 text 属性,确定当前需要执行的 command ip = JOptionPane.showInputDialog("Pls input ur ip:"); self.addIPs(ip) elif x.getSource().text == '127.0.0.1': self.addIPs("127.0.0.1") elif x.getSource().text == 'randomIP': a = str(int(random.uniform(1, 255))) b = str(int(random.uniform(1, 255))) c = str(int(random.uniform(1, 255))) d = str(int(random.uniform(1, 255))) ip = a + "." + b + "." + c + "." + d self.addIPs(ip)
def modifyHeader(self, x): if x.getSource( ).text == 'inputIP': # 通过获取当前点击的子菜单的 text 属性,确定当前需要执行的 command ip = JOptionPane.showInputDialog("Pls input ur ip:") self.addIPs(ip) elif x.getSource().text == '127.0.0.1': self.addIPs("127.0.0.1") elif x.getSource().text == '0x2130706433': self.addIPs("2130706433") elif x.getSource().text == 'randomIP': IPS = [] for hs in add_headers: IPS.append(inet_ntoa(pack('I', randint(1, 0xffffffff)))) self.addIPs(IPS)
def loadTypeMenu(self): """Open an input menu dialog to load a type definition""" type_defs = blackboxprotobuf.known_messages.keys() selection = JOptionPane.showInputDialog( self._component, "Select type", "Type selection", JOptionPane.PLAIN_MESSAGE, None, type_defs, None) if selection is None: return message_type = blackboxprotobuf.known_messages[selection] try: self.applyType(message_type) except Exception as exc: self._callbacks.printError(traceback.format_exc()) JOptionPane.showMessageDialog(self._component, "Error applying type: " + str(exc))
def __init__(self): self.events = [] self.timeScale = float(3.0) #animation sped up by this factor ts = JOptionPane.showInputDialog( None, "Increase speed by factor of...", "Set Timescale", JOptionPane.PLAIN_MESSAGE, None, None, "3.0") try: if ts and float(ts): self.timeScale = float(ts) except: pass gl.log("using timescale: %s" % str(self.timeScale)) self.frame = None if usingDialogs: self.frame = Application.getInstance().getMainFrame();
def ask_topt(server, fetcher, token): code = JOptionPane.showInputDialog( None, "TOTP Code:", "Please enter your TOTP code", JOptionPane.PLAIN_MESSAGE, None, None, "", ) data = {"token": token, "code": code.strip()} url = "{}/account/totp".format(server) response = fetcher.post(url, data).json() if "code" in response: raise APIException(response["code"], response["message"]) return response["token"]
def Find(self, event): table = self.table cols = table.getColumnModel().getColumnCount() model = table.getModel() result = JOptionPane.showInputDialog( self.frame, # parentComponent 'Text to be found:' # message text ) model.setFindText(result) for row in range(model.getRowCount()): visible = model.getValueAt(row, 0).startswith('_') if result and not visible: for col in range(cols): val = model.getValueAt(row, col) if val.find(result) > -1: visible = 1 break model.setRowVisible(row, visible) table.getRowSorter().setRowFilter(sectionFilter())
def set_value(self, event): key_count = len(self.vocab.keys) try: text = JOptionPane.showInputDialog(self.view.frame, 'Enter the symbolic value to represent.\nFor example: "a*b+0.3*(c*d+e)*~f"', "Set semantic pointer", JOptionPane.PLAIN_MESSAGE, None, None, None) v = self.vocab.parse(text) except: self.release_value(event) return if isinstance(v, (int, float)): v = [v] * self.vocab.dimensions else: v = v.v self.fixed_value = v self.popup_release.setEnabled(True) self.view.forced_origins[(self.name, 'X', None)] = self.fixed_value if key_count != len(self.vocab.keys): self.view.refresh_hrrs()
def option_pane(title, message, options, default=None, index_only=True): if default == None: default = options[0] elif index_only: default = options[default] selection = JOptionPane.showInputDialog( frame, message, title, JOptionPane.INFORMATION_MESSAGE, None, # for Java null options, default) # must be in options, otherwise 1st is shown if selection: if index_only: return options.index(selection) else: return selection
def setPayload(self, event): proto = 0 httpRequestResponse = self.context.getSelectedMessages() for currentRequest in httpRequestResponse: parentFrame = JFrame() cmd = JOptionPane.showInputDialog(parentFrame, "Insert the RCE you want to execute on remote target") requestInfo = self._helpers.analyzeRequest(currentRequest) bodyBytes = currentRequest.getRequest()[requestInfo.getBodyOffset():] bodyStr = self._helpers.bytesToString(bodyBytes) headers = requestInfo.getHeaders() newHeaders = list(headers) for header in newHeaders: if 'content-type' in header.lower(): newHeaders.remove(header) newHeaders.append('Content-Type: {0}'.format(PAYLOAD.format(cmd))) newMessage = self._helpers.buildHttpMessage(newHeaders, bodyStr) host = currentRequest.getHttpService().getHost() port = currentRequest.getHttpService().getPort() if currentRequest.getHttpService().getProtocol() == 'https': proto = 1 self._callbacks.sendToRepeater(host, port, proto, newMessage, None)
def actionPerformed(self, e): vulns = [] for i in range(0,self._extender._log.size()): vulns.append(self._extender._log.get(i).getName()) vulnName = self._extender.vulnName.getText() selectedVuln = JOptionPane.showInputDialog( None, "Select related vulnerability:\n", "PT Manager", JOptionPane.PLAIN_MESSAGE, None, vulns, vulnName) if selectedVuln != None: if self._messageInfo.getRequest() != None: self._extender.saveRequestResponse('request',self._messageInfo.getRequest(),selectedVuln) if self._messageInfo.getResponse() != None: self._extender.saveRequestResponse('response',self._messageInfo.getResponse(),selectedVuln) self._extender.loadVulnerability(self._extender._log.get(vulns.index(vulnName)))
def main(): #if you want you can change to 720 or 1080, but is not garantee that it will find it resolution = "480" movieNameList = [] if len(sys.argv) > 1: if (sys.argv[1] == "-h"): print "usages: ./trailerDownloader.py" print "OR" print "usage: ./trailerDownloader.py listOfMovie.txt" sys.exit(0) source = open(sys.argv[1], 'r') movieNameList = source.readlines() source.close() else: movieName = raw_input("Name of the movie : ") movieNameList.append(movieName) from javax.swing import JOptionPane movieName = JOptionPane.showInputDialog(getMainFrame(), 'Please input movie name you want to add.', 'Add movie', JOptionPane.QUESTION_MESSAGE) if movieName == None: return print "Searching for '"+movieName+"'..." movieUrl = getMovieUrl(movieName,resolution) if movieUrl: try: print "starting to download : "+ movieUrl cmd = 'wget -U QuickTime/7.6.2 ' + movieUrl os.system(cmd) except e: print "Error when trying to download : " + movieName else: print "movie not found"
from javax.swing import JOptionPane movieName = JOptionPane.showInputDialog(getMainFrame(), 'Please input movie name you want to add.', 'Add movie', JOptionPane.QUESTION_MESSAGE) if movieName != None: addMovie(movieName);
def input(self, message=''): '''Convert from Java''' from javax.swing import JOptionPane return JOptionPane.showInputDialog(frame, message)
def run(self): global filepath gl.log("running MagicDrawAnimator2") mode = 0 if mode == 0: #filepath = "c:\\Users\\bclement\\git\\bae\\simulationSnapshot.Scenario_medium_2012.txt" #filepath = "c:\\Users\\bclement\\Desktop\\large6.txt" #filepath = "c:\\Users\\bclement\\Desktop\\foo12.txt" #filepath = "/Users/mjackson/Desktop/testSim.txt" gl.log("default filepath = %s" % filepath) filepath = JOptionPane.showInputDialog( None, "Select File to Animate", "Select File", JOptionPane.PLAIN_MESSAGE, None, None, filepath) gl.log("reading events from " + filepath) self.events = [] try: f = open(filepath,"r") except: gl.log("can't find file @ %s" % filepath) return lastTime = float(0.0) latestTime = float(-1.0e20) earliestTime = float(1.0e20) gl.log( "MagicDrawAnimator2: before simulation, loading events from " + str(filepath) ) print( "MagicDrawAnimator2: before simulation, loading events from " + str(filepath) ) for line in f.readlines(): gl.log("read line = " + line) x = re.search("(\d*)[^0-9: \t\n\r\f\v]*\s*:\s*\S*\s*(\S*) -> (\S*)\s*(\S*) ==>",line) y = re.search("(\S*) -> (\S*)\s*(\S*) ==>",line) if x: eventTime=float(x.groups()[0]) lastTime = eventTime action=x.groups()[2] cid = x.groups()[3] ctype = x.groups()[1] #gl.log("%s %s (%s)" % (action.upper(), cid, ctype)) elif y: eventTime=lastTime action=y.groups()[1] cid = y.groups()[2] ctype = y.groups()[0] #gl.log("%s %s (%s)" % (action.upper(), cid, ctype)) elif line.startswith("---"): gl.log(line) continue else: continue #gl.log("%s %s (%s)" % (action.upper(), cid, ctype)) if any([x in cid for x in ["Main"]]): #gl.log(" ---> Skipping - can't animate Main") continue if re.search("(_)?Activity(_.*)?(?!\S)",ctype): #gl.log(" ---> Skipping - can't animate the Activity object!") continue try: if eventTime < earliestTime: earliestTime = eventTime if eventTime > latestTime: latestTime = eventTime evt = event(eventTime,action,cid,ctype) try: self.events.append(evt) except: gl.log("NESTED ARGHHHHH") except: gl.log("ARRGHHH") print( "MagicDrawAnimator2: finished loading events from " + str(filepath) ) gl.log( "MagicDrawAnimator2: finished loading events from " + str(filepath) ) elementsNotEnded = [] try: mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2() #self.playEvents(mda) if self.timeScale == 0.0: gl.log("*** ZERO TIMESCALE: setting timeScale to 1.0") self.timeScale = 1.0 if usingDialogs: JOptionPane.showMessageDialog(self.frame,"Click ok to start simulation.") #simulatedDuration = (float(latestTime) - float(earliestTime))/ float(self.timeScale) simulatedDuration = (latestTime - earliestTime)/ self.timeScale lastTime = earliestTime elapsedTime = earliestTime simStartTime = earliestTime / self.timeScale #start at time of first event elapsedSimTime = simStartTime #start at time of first event zeroTime = time.time() except: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() gl.log("*** EXCEPTION:") messages=traceback.format_exception(exceptionType, exceptionValue, exceptionTraceback) for message in messages: gl.log(message) print("MagicDrawAnimator2: starting simulation with timeScale = " \ + str(self.timeScale) + "; last event at " + str(latestTime) \ + " scaling to " + str(simulatedDuration) + " seconds") gl.log("MagicDrawAnimator2: starting simulation with timeScale = " \ + str(self.timeScale) + "; last event at " + str(latestTime) \ + " scaling to " + str(simulatedDuration) + " seconds") try: for evt in self.events: #gl.log("EVENT at " + str(evt.eventTime)) #Sprint("EVENT at " + str(evt.eventTime)) try: timeOfNextEvent = (float(evt.eventTime) + 0.0) / self.timeScale except: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() gl.log("*** EXCEPTION:") messages=traceback.format_exception(exceptionType, exceptionValue, exceptionTraceback) for message in messages: gl.log(message) #print("1") if evt.eventTime != lastTime: mda.doThePaint() #paint all events occurring at the previous event time lastTime = float(evt.eventTime) #print("2") if timeOfNextEvent > elapsedSimTime: print("sleeping sim time of next event(" + str(timeOfNextEvent) \ + ") - elapsed sim time(" + str(elapsedSimTime) + ") = " \ + str(timeOfNextEvent - elapsedSimTime) + " seconds") gl.log("sleeping sim time of next event(" + str(timeOfNextEvent) \ + ") - elapsed sim time(" + str(elapsedSimTime) + ") = " \ + str(timeOfNextEvent - elapsedSimTime) + " seconds") if (timeOfNextEvent - elapsedSimTime) > 300: gl.log("found time jump > 300") break time.sleep( timeOfNextEvent - elapsedSimTime ) if "TimeVaryingMap" in evt.componentId: try: val = evt.action.split("=")[1] except: val = evt.action gl.log(" ---> (%s) SETTING VALUE of %s: %s" % (evt.eventTime,evt.componentType,val)) elif evt.componentType.startswith("sig") and "ObjectFlow" in evt.componentId: sid = evt.componentType.strip("sig") if "null" in evt.action and sid in elementsNotEnded: gl.log(" ---> (%s) ENDING SIGNAL %s" % (evt.eventTime,sid)) mda.end(sid) elementsNotEnded.remove(sid) elif "null" not in evt.action: gl.log(" ---> (%s) STARTING SIGNAL %s ==> %s" % (evt.eventTime,sid,evt.action)) txt = "" try: txt = evt.action.split("=")[1] except: txt = evt.action mda.start(sid,txt) if sid not in elementsNotEnded: elementsNotEnded.append(sid) elif "start" in evt.action: gl.log(" ---> (%s) STARTING" % evt.eventTime) mda.start(evt.componentId) if evt.componentId not in elementsNotEnded: elementsNotEnded.append(evt.componentId) elif "end" in evt.action: gl.log(" ---> (%s) ENDING" % evt.eventTime) mda.end(evt.componentId) if evt.componentId in elementsNotEnded: elementsNotEnded.remove(evt.componentId) t = time.time() elapsedSimTime = t - zeroTime + simStartTime elapsedTime = self.timeScale * elapsedSimTime gl.log("Debug: elapsed time = " + str(elapsedSimTime)) except: self.handleException() if len(elementsNotEnded)>0: gl.log("Ending Still-Active Events:") for e in elementsNotEnded: gl.log(" ending %s " % e) try: mda.end(e) except: self.handleException() mda.doThePaint() else: gl.log("All Events Completed") gl.log("DONE") elif mode == 1: e = "_17_0_2_edc0357_1352328158277_34448_20209" mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2() gl.log("Starting e (%s)" % e) mda.start(e,"Porpoise Hork") mda.doThePaint() i = 3 while i > 0: i-=1 gl.log(".") time.sleep(1) gl.log("ending e") mda.end(e) mda.doThePaint() elif mode == 2: try: mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2() e = "_17_0_2_edc0357_1352328158277_34448_20209" # in the usePower activity gl.log("Starting e (%s)" % e) mda.start(e) mda.doThePaint() tb = None pem = PresentationElementsManager.getInstance() sm = SessionManager.getInstance() try: sym = mda.gimmeTheSymbol(e) midPoint = sym.getMiddlePoint() sm.createSession("make box!") try: parentPM = sym.getPropertyManager() c = Color.GREEN tb = pem.createTextBox(sym,midPoint) newBounds = Rectangle(15,15) newBounds.setLocation(midPoint) pem.reshapeShapeElement(tb,newBounds) pem.setText(tb," gobblelkajdlfkjakj") pem.setPresentationElementProperties(tb, parentPM) sm.closeSession() except: sm.cancelSession() self.handleException() except: self.handleException() i = 3 while i > 0: i-=1 gl.log(".") time.sleep(1) gl.log("ending e") mda.end(e) if tb: sm.createSession("deleteBox!") try: pem.deletePresentationElement(tb) sm.closeSession() except: sm.cancelSession() self.handleException() mda.doThePaint() except: self.handleException()
def gen_form(self, event): data = self._msgs[0].getResponse() resp = self.helpers.analyzeResponse(data) forms = list(get_forms(data[resp.getBodyOffset():].tostring())) if len(forms) == 0: print("No Forms") return data = self._msgs[0].getRequest() req = self.helpers.analyzeRequest(data) headers = req.getHeaders() if len(forms) > 1: possibilities = ["{0}: {1} ({2})".format(i+1, f.name, f.action) for i, f in enumerate(forms)]; s = JOptionPane.showInputDialog( None, "Select a form:", "Multiple Forms found", JOptionPane.QUESTION_MESSAGE, None, possibilities, possibilities[0]); if not s: return form = forms[possibilities.index(s)] else: form = forms[0] path = headers[0].split(' ')[1] #url = req.getUrl() if form.action.startswith('/'): pass #if url.getHost() in path: # u2 = URL(url.getProtocol(), # url.getHost(), # url.getPort(), # form.action) # path = u2.toString() else: path = path.split('?', 1)[0] if path.endswith('/'): path += form.action else: path = path.rsplit('/', 1)[0] + '/' + form.action values = [] for name, value in form.values: if value is None: value = '' values.append("{0}={1}".format(quote_plus(name), quote_plus(value))) data = '&'.join(values) if form.method == 'get': if '?' in path: path += '&' + data else: path += '?' + data data = "" req_headers = ["{0} {1} {2}".format(form.method.upper(), path, headers[0].rsplit(' ', 1)[1])] req_headers += headers[1:] req = self.helpers.buildHttpMessage( req_headers, self.helpers.stringToBytes(data) ) class CookieParam(burp.IParameter): def __init__(self, name, value): self._name = name self._value= value def getType(self): return 2 def getName(self): return self._name def getValue(self): return self._value def getNameStart(self): return -1 getNameEnd = getNameStart getValueStart = getNameStart getValueEnd = getValueStart for cookie in resp.getCookies(): param = CookieParam(cookie.getName(), cookie.getValue()) req = self.helpers.removeParameter(req, param) req = self.helpers.addParameter(req, param) self._msgs[0].setRequest(req)
def main(): binNaviProxy = StandAlone.getPluginInterface() binNaviProxy.databaseManager.addDatabase("","com.mysql.jdbc.Driver","localhost","BINNAVI1","binnavi","binnavi",False,False) db=binNaviProxy.databaseManager.databases[0] db.connect() db.load() mods=db.getModules() ### initiate dialogBox to setect the module that should be used. ###################################################### frame = JFrame('BinNavi Module Selector',layout=BorderLayout(), defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (1500, 800) ) frame2 = JFrame('Function Selector',layout=BorderLayout(), defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (30, 30) ) frame2.setFocusableWindowState(False) frame2.setFocusable(False) frame2.setAlwaysOnTop(False) #convert the module list into the string to be used in the TextBox. textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods) textStr=''.join(textTemp) tx=JTextArea(textStr) tx.setLineWrap(True); tx.setWrapStyleWord(True); frame.add(tx,BorderLayout.PAGE_START) frame.visible = True modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module", "Module selector"); #Open the module returned by the index bfname=mods[int(modInd)] # this modules correxponds to the chosen module bfname.load() funcViews=bfname.views #textTemp2 = ["[%d]%s"%(i,j) for i in range(len(funcViews)) for j in funcViews] textTemp2=map((lambda x,y:"[%d]%s"%(x,y.toString()[5:18])),range(len(funcViews)),funcViews) textStr1=''.join(textTemp2) ## remove the older text from the frame view frame.remove(tx) frame.update(frame.getGraphics()) frame.visible = False ## create a new textArea with the string made from all the functions' name txStr=JTextArea(textStr1) #tx.setsrcollOffset(20) txStr.setLineWrap(True); txStr.setWrapStyleWord(True); frame.add(txStr,BorderLayout.PAGE_START) frame.update(frame.getGraphics()) frame.visible = True funcInd = JOptionPane.showInputDialog(frame2, "Enter the index of the function", "Function selector"); ###################################################### bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function bffunc.load() frame2.setVisible(False) dispose(frame2) bfReil=bffunc.getReilCode() # this is the REIL code of the function bfReilGraph=bfReil.getGraph() instGraph = InstructionGraph.create(bfReilGraph) time.clock() results=doAnalysis(instGraph) totalTime=time.clock() #print "resultsLen", len([r for r in results]) print "**** printing results *******\n" print "Total time:", totalTime, '\n' numNode=0 for n in instGraph: numNode+=numNode nIn=list(results.getState(n).inVal) nIn.sort(key=itemgetter(0)) nOut=list(results.getState(n).out) nOut.sort(key=itemgetter(0)) print '@@ ',n.getInstruction(),'\n' print '\t In', nIn, '\n' print '\t OUT', nOut, '\n' print '\t memory: ',results.getState(n).memoryWritten, '\n' print "++++ Total instructions: %d +++++\n"%numNode #finally close the view of the function bffunc.close() #print bffunc.isLoaded() #junky=raw_input("function closed. enter any charater") print "Done! Closing the module selector window" frame.setVisible(False) dispose(frame)
def _showChoiceDialog(self, title, text, choices): return JOptionPane.showInputDialog( self.parentWindow, text, title, JOptionPane.INFORMATION_MESSAGE, None, choices, choices[0] )
def run(self): global filepath try: mode = 0 if mode == 0: mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2() #filepath = "c:\\Users\\bclement\\Desktop\\medium2.txt" #filepath = "c:\\Users\\bclement\\git\\bae\\simulationSnapshot.Scenario_Smaller_2012.txt" #filepath = "c:\\Users\\bclement\\git\\bae\\Smaller2012_2.console.txt" #filepath = "/Users/mjackson/Desktop/MedSim.txt" gl.log("default filepath = %s" % filepath) #possibilities = None filepath = JOptionPane.showInputDialog( None, "Element ID", "Find Element", JOptionPane.PLAIN_MESSAGE, None, None, filepath) gl.log("reading events from " + filepath) try: f = open(filepath,"r") except: gl.log("can't find file @ %s" % filepath) return lastTime = 0 elementsNotEnded = [] for line in f.readlines(): #gl.log("read line = " + line) #x = re.search(" (\S*) -> (\S*)\s*(\S*) ==>",line) x = re.search("(\d*)[^0-9: \t\n\r\f\v]*\s*:\s*\S*\s*(\S*) -> (\S*)\s*(\S*) ==>",line) y = re.search("(\S*) -> (\S*)\s*(\S*) ==>",line) if x: eventTime=x.groups()[0] action=x.groups()[2] cid = x.groups()[3] ctype = x.groups()[1] elif y: eventTime=lastTime action=y.groups()[1] cid = y.groups()[2] ctype = y.groups()[0] elif line.startswith("---"): gl.log(line) continue else: continue if eventTime != lastTime: mda.doThePaint() lastTime = eventTime time.sleep(self.timeStep) gl.log("%s: %s %s (%s)" % (eventTime, action.upper(), cid, ctype)) if any([x in cid for x in ["Main","TimeVaryingMap"]]): gl.log(" ---> Skipping - can't animate Main or TimeVaryingMap") continue if re.search("(_)?Activity(_.*)?(?!\S)",ctype): gl.log(" ---> Skipping - can't animate the Activity object!") continue if ctype.startswith("sig") and "ObjectFlow" in cid: sid = ctype.strip("sig") if "null" in action and sid in elementsNotEnded: gl.log(" ---> ENDING SIGNAL %s" % sid) mda.end(sid) elementsNotEnded.remove(sid) elif "null" not in action: gl.log(" ---> STARTING SIGNAL %s" % sid) mda.start(sid) if sid not in elementsNotEnded: elementsNotEnded.append(sid) elif "start" in action: gl.log(" ---> STARTING") mda.start(cid) if cid not in elementsNotEnded: elementsNotEnded.append(cid) elif "end" in action: gl.log(" ---> ENDING") mda.end(cid) if cid in elementsNotEnded: elementsNotEnded.remove(cid) time.sleep(self.timeStep) mda.doThePaint() gl.log("sleeping 3 seconds before reset") time.sleep(3) for sig in elementsNotEnded: gl.log("ending %s " % sig) mda.end(sig) mda.doThePaint() elif mode == 1: e = "_17_0_5_edc0357_1346893970422_843838_14398" mda = MagicDrawAnimatorUtils2.MagicDrawAnimator2() gl.log("Starting e (%s)" % e) mda.start(e) i = 3 while i > 0: i-=1 gl.log(".") time.sleep(self.timeStep) gl.log("ending e") mda.end(e) mda.doThePaint() except: MPUtils.handleException()
def input_dialog(message): return JOptionPane.showInputDialog(None, message, "User action required", JOptionPane.QUESTION_MESSAGE)
def main(): ''' Main function that implements main algorithm ''' # a file where some log will be created which says how many functions are discovered etc. logFile=raw_input("Enter the name of log file") # this is provided as an extra file which is a pickled file comtains a list of functions # that are found to be BOP. Its main purpose is: if you want to use these functions for some # other analysis, just load this file and viola!!! fileBOP=raw_input("Enter the file name (full path) to store (Pickled) BOP function's name: ") interestingFuncs={} # dictionary of interesting functions interestingFuncsLOC={} # dictionary of LOC in interesting functions binNaviProxy = StandAlone.getPluginInterface() ################## place to set database connectivity parameter ######### binNaviProxy.databaseManager.addDatabase("","org.postgresql.Driver","localhost","DataBase_name","user","password",False,False) ######################################################################## db=binNaviProxy.databaseManager.databases[0] db.connect() db.load() mods=db.getModules() ### initiate dialogBox to setect the module that should be used. ###################################################### frame = JFrame('BinNavi Module Selector',layout=BorderLayout(), defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (500, 500) ) frame2 = JFrame('Function Selector',layout=BorderLayout(), defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (30, 30) ) #convert the module list into the string to be used in the TextBox. ## This gives a very ugly box to select the required function (yes, I am bit lazy to learn Java Swing!!). textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods) textStr=''.join(textTemp) tx=JTextArea(textStr) tx.setLineWrap(True); tx.setWrapStyleWord(True); frame.add(tx,BorderLayout.PAGE_START) frame.visible = True modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module", "Module selector"); #Open the module returned by the index bfname=mods[int(modInd)] # this modules correxponds to the chosen module bfname.load() funcViews=bfname.views frame2.setVisible(False) dispose(frame2) ###################################################### analyzedFunctions = 0 totalDiscoveredLoops=0 totalInterestingLoops=0 time.clock() for funcInd in range(1,len(funcViews)): BBnum=funcViews[funcInd].getNodeCount() if BBnum <4: print "skipped" continue #do not analyse function if num of BB less than 4 print 'analyzing %s'%funcViews[funcInd].getName() dominatingSets={}#dictionary to keep dominating nodes of a node bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function bffunc.load() try: bfReil=bffunc.getReilCode() # this is the REIL code of the function except: print "error in getReilCode()" bffunc.close() gc.collect() continue bfReilGraph=bfReil.getGraph() try: #dominatorTree = GraphAlgorithms.getDominatorTree(bfReilGraph, findRoot(bfReilGraph.getNodes())) #only for BinNavi v 3.0 dominatorTree = GraphAlgorithms.getDominatorTree(bfReilGraph, findRoot(bfReilGraph.getNodes()),None) except: print "dominator tree problem.. continue with the next function" bffunc.close() gc.collect() continue fillDominatingSets(dominatorTree.getRootNode(), dominatingSets, None) # let us find loops in this function finalLoops=findLoops(bfReilGraph,dominatingSets) if finalLoops ==None: bffunc.close() gc.collect() continue analyzedFunctions = analyzedFunctions +1 totalDiscoveredLoops = totalDiscoveredLoops + len(finalLoops) # check if the loops are potential candidates for being interesting. # this is done by checking if there are atleast 2 STM statements in each loop. #print "privious length", len(finalLoops) if len(finalLoops)== 0: bffunc.close() gc.collect() continue for lp in finalLoops.keys(): countSTM=0 for lpn in finalLoops[lp]: inst=lpn.getInstructions() for i in inst: if i.getMnemonic() == 'stm': countSTM=countSTM+1 if countSTM >0: break if countSTM <= 0: del finalLoops[lp] #print "latest length", len(finalLoops) if len(finalLoops)== 0: bffunc.close() gc.collect() continue instGraph = InstructionGraph.create(bfReilGraph) interestingFuncs[funcViews[funcInd].getName()]=[] for k in finalLoops.keys(): print 'analysing loop at %s-%s'%(k[0],k[1]) if k[0] == k[1]: print "skipping this loop as src= dest" continue #check to skip very big loops i.e. loops having 100 BB if len(finalLoops[k]) > 100: print "very big loop, skipping!" continue if isInteresting(finalLoops[k],instGraph) ==True: totalInterestingLoops = totalInterestingLoops + 1 interestingFuncs[funcViews[funcInd].getName()].append(k) interestingFuncsLOC[str(funcViews[funcInd].getName())]=sum([len(x.getInstructions()) for x in (getCodeNodes(bffunc.getGraph()))]) print 'loop at %s IS interesting.'%k[0] else: print 'loop at %s is NOT interesting.'%k[0] #finally close the view of the function bffunc.close() gc.collect() #print bffunc.isLoaded() #junky=raw_input("function closed. enter any charater") totalTime=time.clock() # remove the function entries that do not have any interesting loops for ky in interestingFuncs.keys(): if len(interestingFuncs[ky]) == 0: del interestingFuncs[ky] # write the results in a file # outFile=open(logFile,'w') outFile.write('########## Global Results ###########\n') outFile.write('Total Functions in the module: ') outFile.write(str(len(funcViews))) outFile.write('\nTotal Analyzed Functions in the module: ') outFile.write(str(analyzedFunctions)) outFile.write('\nTotal Interesting Functions in the module: ') outFile.write(str(len(interestingFuncs))) outFile.write('\nTotal loops discovered in the module: ') outFile.write(str(totalDiscoveredLoops)) outFile.write('\nTotal INTERESTING loops discovered in the module: ') outFile.write(str(totalInterestingLoops)) outFile.write('\nTotal Time: ') outFile.write(str(totalTime)) outFile.write('\n') outFile.write('########## Global Results ###########\n') for k in interestingFuncs.keys(): outFile.write("%s: %s: %d"%(str(k), "LOC", interestingFuncsLOC[k])) outFile.write('\n') for l in interestingFuncs[k]: outFile.write('\t') outFile.write(str(l)) outFile.write('\n') outFile.close() # before we save these BOPS, we include few widely known BOPs which are given int eh following list knownBOPs = ['strcpy', 'strncpy', 'memcpy','wcscpy'] for fn in knownBOPs: interestingFuncs[fn] = [] # save the function name as pickled objects fileBOPFd=open(fileBOP+'.pkl', 'w') pickle.dump(interestingFuncs.keys(), fileBOPFd) fileBOPFd.close() print "[*] Pickled in the file %s"%fileBOP+'.pkl' print "Done! Closing the module selector window" frame.setVisible(False) dispose(frame)