def run(generators, number, repeat=1): print("Calculating speeds for first %d primes..." % number) template = "\r ...%d of %d %s" heading = """\ Generator Elapsed Speed (sec) (primes/sec) ==============================================================""" records = [] timer = Stopwatch() # For measuring the total elapsed time. timer.start() N = len(generators) for i, generator in enumerate(generators): name = generator.__module__ + '.' + generator.__name__ sys.stdout.write((template % (i + 1, N, name)).ljust(69)) sys.stdout.flush() t = trial(generator, number, repeat) records.append((number / t, t, name)) timer.stop() sys.stdout.write("\r%-69s\n" % "Done!") print('Total elapsed time: %.1f seconds' % timer.elapsed) print('') records.sort() print(heading) for speed, elapsed, name in records: print("%-36s %4.2f %8.1f" % (name, elapsed, speed)) print('==============================================================\n')
def run_binary(input_file, input_msg, args, success_exit_code, cwd, env): cmd = [os.path.abspath(input_file)] if args: cmd.extend(shlex.split(args)) try: proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env) except OSError: traceback.print_exc() print(" binary: {}".format(cmd)) return False ret = False # set 15 min timeout which should be more than enough for simple binaries to finish timer = threading.Timer(60 * 15, proc.kill) try: timer.start() output = proc.communicate(input=input_msg) if not timer.isAlive(): print('run_binary timed out') print('cmd: {}'.format(' '.join(cmd))) elif proc.returncode != success_exit_code: print('[-] run_binary return code was {}, expected {}'.format( proc.returncode, success_exit_code)) print('cmd: {}'.format(' '.join(cmd))) else: ret = output finally: timer.cancel() return ret
def run(generators, number, repeat=1): print ("Calculating speeds for first %d primes..." % number) template = "\r ...%d of %d %s" heading = """\ Generator Elapsed Speed (sec) (primes/sec) ==============================================================""" records = [] timer = Stopwatch() # For measuring the total elapsed time. timer.start() N = len(generators) for i, generator in enumerate(generators): name = generator.__module__ + '.' + generator.__name__ sys.stdout.write((template % (i+1, N, name)).ljust(69)) sys.stdout.flush() t = trial(generator, number, repeat) records.append((number/t, t, name)) timer.stop() sys.stdout.write("\r%-69s\n" % "Done!") print ('Total elapsed time: %.1f seconds' % timer.elapsed) print ('') records.sort() print (heading) for speed, elapsed, name in records: print ("%-36s %4.2f %8.1f" % (name, elapsed, speed)) print ('==============================================================\n')
def time_limit(seconds): timer = threading.Timer(seconds, lambda: _thread.interrupt_main()) timer.start() try: yield except KeyboardInterrupt: raise TimeoutException() finally: # if the action ends in specified time, timer is canceled timer.cancel()
def trial(generator, count, repeat=1): timer = Stopwatch() best = YEAR100 for i in range(repeat): it = generator() timer.reset() timer.start() # Go to the count-th prime as fast as possible. p = next(islice(it, count - 1, count)) timer.stop() best = min(best, timer.elapsed) return best
def trial(generator, count, repeat=1): timer = Stopwatch() best = YEAR100 for i in range(repeat): it = generator() timer.reset() timer.start() # Go to the count-th prime as fast as possible. p = next(islice(it, count-1, count)) timer.stop() best = min(best, timer.elapsed) return best
def run_taint_attack(input_file, build_dir, output_file, log_dir, taint_backend, text_section, report_dict): text_section_arg = '--text-section {},{}'.format( text_section[0], text_section[1]) if text_section else '' if taint_backend == "python": cmd = [ log_dir, "--binary", input_file, "--output", output_file, "-v", ] from taint.run import main as taint_main return taint_main(cmd) patches_path = os.path.join(build_dir, 'patches.json') cmd = [ TAINT_CPP_PATH, log_dir, "--fail-emulation-allowed", "--json-output", patches_path, "-v", # "-vv" ] if text_section_arg: cmd.append(text_section_arg) # if run_cmd(cmd) is not True: # return False try: proc = subprocess.Popen(cmd) except OSError: traceback.print_exc() return False def stop_taint_cpp(): # if we get really unlucky, this might happen exactly when the emulation # is done and the signal is not being caught but the probability should # be very low proc.send_signal(signal.SIGINT) # mark that we timed out report_dict['timeout'] = True timer = threading.Timer(36 * 60 * 60, stop_taint_cpp) try: timer.start() proc.wait() finally: timer.cancel() with open(patches_path, 'r') as f: patches = json.load(f) # "address", "asm_string", "data_hex" patches = patches['patches'] # save number of detected checkers # (assuming each guard takes at most one patch since only cmovs/cjmps are patched) report_dict['checkers_patched'] = len(patches) # address, binary data, cmd_string patches_r2_format = [(entry['address'], binascii.unhexlify(entry['data_hex']), entry['asm_string']) for entry in patches] # cpp backend doesn't know how to apply patches print('[*] applying patches\n {} => {}'.format(input_file, output_file)) if not patch_program(input_file, output_file, patches_r2_format): print('[-] r2_apply_patches failed') return False return True
def window(self): try: app = QApplication(sys.argv) window = QWidget() window.setWindowTitle('COWIN Slot Finder') window.setMinimumWidth(1000) window.setMinimumHeight(800) layout = QGridLayout() timer = QTimer() timer.timeout.connect(self.tick) timer.start(100) self.states = QComboBox() for elem in self.stateDict['states']: itemStr = str(elem["state_id"]) + ":" + str(elem["state_name"]) self.states.addItem(itemStr) row = 1 labelState = QLabel("States") labelState.setFont(QFont("Times", weight=QFont.Bold)) labelDist = QLabel("Districts") labelDist.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelState, row, 1, 1, 2) layout.addWidget(labelDist, row, 4, 1, 2) row += 1 self.states.currentIndexChanged.connect(self.stateSelectionchange) layout.addWidget(self.states, row, 1, 1, 2) self.districts = QComboBox() self.districts.currentIndexChanged.connect(self.districtSelectionchange) layout.addWidget(self.districts, row, 4, 1, 2) row += 1 self.searchBox = QLineEdit() self.searchBox.setPlaceholderText("Search...") self.searchBox.textChanged.connect(self.textChanged) layout.addWidget(self.searchBox, row, 1, 1, 3) labelDose = QLabel("Select Dose:") # labelDose.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelDose, row, 4, 1, 1) radiobutton = QRadioButton("Dose 1") radiobutton.setChecked(True) radiobutton.dose = 1 radiobutton.toggled.connect(lambda: self.onSelectRadio(radiobutton)) layout.addWidget(radiobutton, row, 5, 1, 1) radiobutton2 = QRadioButton("Dose 2") radiobutton2.setChecked(False) radiobutton2.dose = 2 radiobutton2.toggled.connect(lambda: self.onSelectRadio(radiobutton2)) layout.addWidget(radiobutton2, row, 6, 1, 1) row += 1 labelCenter = QLabel("Available Centers") labelCenter.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelCenter, row, 1, 1, 3) labelSelect = QLabel("Selected Centers") labelSelect.setFont(QFont("Times", weight=QFont.Bold)) layout.addWidget(labelSelect, row, 4, 1, 3) row += 1 self.selectAllChk = QCheckBox("Select All") self.selectAllChk.stateChanged.connect(lambda: self.selectAll(self.selectAllChk)) layout.addWidget(self.selectAllChk, row, 1, 1, 3) row += 1 self.centreLayout = QVBoxLayout() self.checks = [] widget = QWidget() widget.setLayout(self.centreLayout) # Scroll Area Properties scroll = QScrollArea() # scroll.setFrameShape(frame) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(True) scroll.setWidget(widget) layout.addWidget(scroll, row, 1, 1, 3) self.selectedLayout = QVBoxLayout() widget2 = QWidget() widget2.setLayout(self.selectedLayout) # Scroll Area Properties scroll2 = QScrollArea() # scroll.setFrameShape(frame) scroll2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # scroll2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll2.setWidgetResizable(True) scroll2.setWidget(widget2) layout.addWidget(scroll2, row, 4, 1, 3) row += 1 self.button1 = QPushButton() self.button1.setText("Run Slot Notifier") self.button1.clicked.connect(self.runService) layout.addWidget(self.button1, row, 3, 1, 2) self.buttonClear = QPushButton() self.buttonClear.setText("Clear") self.buttonClear.clicked.connect(self.clearSelections) layout.addWidget(self.buttonClear, row, 6, 1, 1) row += 1 self.button2 = QPushButton() self.button2.setText("Stop Slot Notifier") self.button2.clicked.connect(self.stopService) layout.addWidget(self.button2, row, 3, 1, 2) row += 1 self.msgLayout = QVBoxLayout() widget3 = QWidget() widget3.setLayout(self.msgLayout) # Scroll Area Properties self.scroll3 = QScrollArea() # scroll.setFrameShape(frame) self.scroll3.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) # scroll3.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scroll3.setWidgetResizable(True) self.scroll3.setWidget(widget3) layout.addWidget(self.scroll3, row, 1, 1, 6) row += 1 app.aboutToQuit.connect(self.closeEvent) window.setLayout(layout) window.show() sys.exit(app.exec_()) except BaseException as e: raise