text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_glut(self): """Disable event loop integration with glut. This sets PyOS_InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future. """
import OpenGL.GLUT as glut # @UnresolvedImport from glut_support import glutMainLoopEvent # @UnresolvedImport glut.glutHideWindow() # This is an event to be processed below glutMainLoopEvent() self.clear_inputhook()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_pyglet(self, app=None): """Enable event loop integration with pyglet. Parameters app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the ``PyOS_InputHook`` for pyglet, which allows pyglet to integrate with terminal based applications like IPython. """
from pydev_ipython.inputhookpyglet import inputhook_pyglet self.set_inputhook(inputhook_pyglet) self._current_gui = GUI_PYGLET return app
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_mac(self, app=None): """ Enable event loop integration with MacOSX. We call function pyplot.pause, which updates and displays active figure during pause. It's not MacOSX-specific, but it enables to avoid inputhooks in native MacOSX backend. Also we shouldn't import pyplot, until user does it. Cause it's possible to choose backend before importing pyplot for the first time only. """
def inputhook_mac(app=None): if self.pyplot_imported: pyplot = sys.modules['matplotlib.pyplot'] try: pyplot.pause(0.01) except: pass else: if 'matplotlib.pyplot' in sys.modules: self.pyplot_imported = True self.set_inputhook(inputhook_mac) self._current_gui = GUI_OSX
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _thread_to_xml(self, thread): """ thread information as XML """
name = pydevd_xml.make_valid_xml_value(thread.getName()) cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread)) return cmdText
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_list_threads_message(self, py_db, seq): """ returns thread listing as XML """
try: threads = get_non_pydevd_threads() cmd_text = ["<xml>"] append = cmd_text.append for thread in threads: if is_thread_alive(thread): append(self._thread_to_xml(thread)) append("</xml>") return NetCommand(CMD_RETURN, seq, ''.join(cmd_text)) except: return self.make_error_message(seq, get_exception_traceback_str())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0): """ Returns thread stack as XML. :param must_be_suspended: If True and the thread is not suspended, returns None. """
try: # If frame is None, the return is an empty frame list. cmd_text = ['<xml><thread id="%s">' % (thread_id,)] if topmost_frame is not None: frame_id_to_lineno = {} try: # : :type suspended_frames_manager: SuspendedFramesManager suspended_frames_manager = py_db.suspended_frames_manager info = suspended_frames_manager.get_topmost_frame_and_frame_id_to_line(thread_id) if info is None: # Could not find stack of suspended frame... if must_be_suspended: return None else: # Note: we have to use the topmost frame where it was suspended (it may # be different if it was an exception). topmost_frame, frame_id_to_lineno = info cmd_text.append(self.make_thread_stack_str(topmost_frame, frame_id_to_lineno)) finally: topmost_frame = None cmd_text.append('</thread></xml>') return NetCommand(CMD_GET_THREAD_STACK, seq, ''.join(cmd_text)) except: return self.make_error_message(seq, get_exception_traceback_str())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_get_exception_details_message(self, seq, thread_id, topmost_frame): """Returns exception details as XML """
try: # If the debugger is not suspended, just return the thread and its id. cmd_text = ['<xml><thread id="%s" ' % (thread_id,)] if topmost_frame is not None: try: frame = topmost_frame topmost_frame = None while frame is not None: if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'): arg = frame.f_locals.get('arg', None) if arg is not None: exc_type, exc_desc, _thread_suspend_str, thread_stack_str = self._make_send_curr_exception_trace_str( thread_id, *arg) cmd_text.append('exc_type="%s" ' % (exc_type,)) cmd_text.append('exc_desc="%s" ' % (exc_desc,)) cmd_text.append('>') cmd_text.append(thread_stack_str) break frame = frame.f_back else: cmd_text.append('>') finally: frame = None cmd_text.append('</thread></xml>') return NetCommand(CMD_GET_EXCEPTION_DETAILS, seq, ''.join(cmd_text)) except: return self.make_error_message(seq, get_exception_traceback_str())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_process(self, process = None): """ Manually set the parent process. Use with care! @type process: L{Process} @param process: (Optional) Process object. Use C{None} for no process. """
if process is None: self.__process = None else: global Process # delayed import if Process is None: from winappdbg.process import Process if not isinstance(process, Process): msg = "Parent process must be a Process instance, " msg += "got %s instead" % type(process) raise TypeError(msg) self.__process = process
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __get_size_and_entry_point(self): "Get the size and entry point of the module using the Win32 API." process = self.get_process() if process: try: handle = process.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) base = self.get_base() mi = win32.GetModuleInformation(handle, base) self.SizeOfImage = mi.SizeOfImage self.EntryPoint = mi.EntryPoint except WindowsError: e = sys.exc_info()[1] warnings.warn( "Cannot get size and entry point of module %s, reason: %s"\ % (self.get_name(), e.strerror), RuntimeWarning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_handle(self): """ Opens a new handle to the module. The new handle is stored in the L{hFile} property. """
if not self.get_filename(): msg = "Cannot retrieve filename for module at %s" msg = msg % HexDump.address( self.get_base() ) raise Exception(msg) hFile = win32.CreateFile(self.get_filename(), dwShareMode = win32.FILE_SHARE_READ, dwCreationDisposition = win32.OPEN_EXISTING) # In case hFile was set to an actual handle value instead of a Handle # object. This shouldn't happen unless the user tinkered with hFile. if not hasattr(self.hFile, '__del__'): self.close_handle() self.hFile = hFile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_handle(self): """ Closes the handle to the module. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. So unless you've been tinkering with it, setting L{hFile} to C{None} should be enough. """
try: if hasattr(self.hFile, 'close'): self.hFile.close() elif self.hFile not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hFile) finally: self.hFile = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_label(self, function = None, offset = None): """ Retrieves the label for the given function of this module or the module base address if no function name is given. @type function: str @param function: (Optional) Exported function name. @type offset: int @param offset: (Optional) Offset from the module base address. @rtype: str @return: Label for the module base address, plus the offset if given. """
return _ModuleContainer.parse_label(self.get_name(), function, offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_here(self, address): """ Tries to determine if the given address belongs to this module. @type address: int @param address: Memory address. @rtype: bool or None @return: C{True} if the address belongs to the module, C{False} if it doesn't, and C{None} if it can't be determined. """
base = self.get_base() size = self.get_size() if base and size: return base <= address < (base + size) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(self, function): """ Resolves a function exported by this module. @type function: str or int @param function: str: Name of the function. int: Ordinal of the function. @rtype: int @return: Memory address of the exported function in the process. Returns None on error. """
# Unknown DLL filename, there's nothing we can do. filename = self.get_filename() if not filename: return None # If the DLL is already mapped locally, resolve the function. try: hlib = win32.GetModuleHandle(filename) address = win32.GetProcAddress(hlib, function) except WindowsError: # Load the DLL locally, resolve the function and unload it. try: hlib = win32.LoadLibraryEx(filename, win32.DONT_RESOLVE_DLL_REFERENCES) try: address = win32.GetProcAddress(hlib, function) finally: win32.FreeLibrary(hlib) except WindowsError: return None # A NULL pointer means the function was not found. if address in (None, 0): return None # Compensate for DLL base relocations locally and remotely. return address - hlib + self.lpBaseOfDll
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_label(self, label): """ Resolves a label for this module only. If the label refers to another module, an exception is raised. @type label: str @param label: Label to resolve. @rtype: int @return: Memory address pointed to by the label. @raise ValueError: The label is malformed or impossible to resolve. @raise RuntimeError: Cannot resolve the module or function. """
# Split the label into it's components. # Use the fuzzy mode whenever possible. aProcess = self.get_process() if aProcess is not None: (module, procedure, offset) = aProcess.split_label(label) else: (module, procedure, offset) = _ModuleContainer.split_label(label) # If a module name is given that doesn't match ours, # raise an exception. if module and not self.match_name(module): raise RuntimeError("Label does not belong to this module") # Resolve the procedure if given. if procedure: address = self.resolve(procedure) if address is None: # If it's a debug symbol, use the symbol. address = self.resolve_symbol(procedure) # If it's the keyword "start" use the entry point. if address is None and procedure == "start": address = self.get_entry_point() # The procedure was not found. if address is None: if not module: module = self.get_name() msg = "Can't find procedure %s in module %s" raise RuntimeError(msg % (procedure, module)) # If no procedure is given use the base address of the module. else: address = self.get_base() # Add the offset if given and return the resolved address. if offset: address = address + offset return address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_modules(self): """ Clears the modules snapshot. """
for aModule in compat.itervalues(self.__moduleDict): aModule.clear() self.__moduleDict = dict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_label(module = None, function = None, offset = None): """ Creates a label from a module and a function name, plus an offset. @warning: This method only creates the label, it doesn't make sure the label actually points to a valid memory location. @type module: None or str @param module: (Optional) Module name. @type function: None, str or int @param function: (Optional) Function name or ordinal. @type offset: None or int @param offset: (Optional) Offset value. If C{function} is specified, offset from the function. If C{function} is C{None}, offset from the module. @rtype: str @return: Label representing the given function in the given module. @raise ValueError: The module or function name contain invalid characters. """
# TODO # Invalid characters should be escaped or filtered. # Convert ordinals to strings. try: function = "#0x%x" % function except TypeError: pass # Validate the parameters. if module is not None and ('!' in module or '+' in module): raise ValueError("Invalid module name: %s" % module) if function is not None and ('!' in function or '+' in function): raise ValueError("Invalid function name: %s" % function) # Parse the label. if module: if function: if offset: label = "%s!%s+0x%x" % (module, function, offset) else: label = "%s!%s" % (module, function) else: if offset: ## label = "%s+0x%x!" % (module, offset) label = "%s!0x%x" % (module, offset) else: label = "%s!" % module else: if function: if offset: label = "!%s+0x%x" % (function, offset) else: label = "!%s" % function else: if offset: label = "0x%x" % offset else: label = "0x0" return label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_label_fuzzy(self, label): """ Splits a label entered as user input. It's more flexible in it's syntax parsing than the L{split_label_strict} method, as it allows the exclamation mark (B{C{!}}) to be omitted. The ambiguity is resolved by searching the modules in the snapshot to guess if a label refers to a module or a function. It also tries to rebuild labels when they contain hardcoded addresses. @warning: This method only parses the label, it doesn't make sure the label actually points to a valid memory location. @type label: str @param label: Label to split. @rtype: tuple( str or None, str or int or None, int or None ) @return: Tuple containing the C{module} name, the C{function} name or ordinal, and the C{offset} value. If the label doesn't specify a module, then C{module} is C{None}. If the label doesn't specify a function, then C{function} is C{None}. If the label doesn't specify an offset, then C{offset} is C{0}. @raise ValueError: The label is malformed. """
module = function = None offset = 0 # Special case: None if not label: label = compat.b("0x0") else: # Remove all blanks. label = label.replace(compat.b(' '), compat.b('')) label = label.replace(compat.b('\t'), compat.b('')) label = label.replace(compat.b('\r'), compat.b('')) label = label.replace(compat.b('\n'), compat.b('')) # Special case: empty label. if not label: label = compat.b("0x0") # If an exclamation sign is present, we know we can parse it strictly. if compat.b('!') in label: return self.split_label_strict(label) ## # Try to parse it strictly, on error do it the fuzzy way. ## try: ## return self.split_label(label) ## except ValueError: ## pass # * + offset if compat.b('+') in label: try: prefix, offset = label.split(compat.b('+')) except ValueError: raise ValueError("Malformed label: %s" % label) try: offset = HexInput.integer(offset) except ValueError: raise ValueError("Malformed label: %s" % label) label = prefix # This parses both filenames and base addresses. modobj = self.get_module_by_name(label) if modobj: # module # module + offset module = modobj.get_name() else: # TODO # If 0xAAAAAAAA + 0xBBBBBBBB is given, # A is interpreted as a module base address, # and B as an offset. # If that fails, it'd be good to add A+B and try to # use the nearest loaded module. # offset # base address + offset (when no module has that base address) try: address = HexInput.integer(label) if offset: # If 0xAAAAAAAA + 0xBBBBBBBB is given, # A is interpreted as a module base address, # and B as an offset. # If that fails, we get here, meaning no module was found # at A. Then add up A+B and work with that as a hardcoded # address. offset = address + offset else: # If the label is a hardcoded address, we get here. offset = address # If only a hardcoded address is given, # rebuild the label using get_label_at_address. # Then parse it again, but this time strictly, # both because there is no need for fuzzy syntax and # to prevent an infinite recursion if there's a bug here. try: new_label = self.get_label_at_address(offset) module, function, offset = \ self.split_label_strict(new_label) except ValueError: pass # function # function + offset except ValueError: function = label # Convert function ordinal strings into integers. if function and function.startswith(compat.b('#')): try: function = HexInput.integer(function[1:]) except ValueError: pass # Convert null offsets to None. if not offset: offset = None return (module, function, offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize_label(self, label): """ Converts a label taken from user input into a well-formed label. @type label: str @param label: Label taken from user input. @rtype: str @return: Sanitized label. """
(module, function, offset) = self.split_label_fuzzy(label) label = self.parse_label(module, function, offset) return label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_label(self, label): """ Resolve the memory address of the given label. @note: If multiple modules with the same name are loaded, the label may be resolved at any of them. For a more precise way to resolve functions use the base address to get the L{Module} object (see L{Process.get_module}) and then call L{Module.resolve}. If no module name is specified in the label, the function may be resolved in any loaded module. If you want to resolve all functions with that name in all processes, call L{Process.iter_modules} to iterate through all loaded modules, and then try to resolve the function in each one of them using L{Module.resolve}. @type label: str @param label: Label to resolve. @rtype: int @return: Memory address pointed to by the label. @raise ValueError: The label is malformed or impossible to resolve. @raise RuntimeError: Cannot resolve the module or function. """
# Split the label into module, function and offset components. module, function, offset = self.split_label_fuzzy(label) # Resolve the components into a memory address. address = self.resolve_label_components(module, function, offset) # Return the memory address. return address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_symbols(self): """ Returns the debugging symbols for all modules in this snapshot. The symbols are automatically loaded when needed. @rtype: list of tuple( str, int, int ) @return: List of symbols. Each symbol is represented by a tuple that contains: - Symbol name - Symbol memory address - Symbol size in bytes """
symbols = list() for aModule in self.iter_modules(): for symbol in aModule.iter_symbols(): symbols.append(symbol) return symbols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_symbol_at_address(self, address): """ Tries to find the closest matching symbol for the given address. @type address: int @param address: Memory address to query. @rtype: None or tuple( str, int, int ) @return: Returns a tuple consisting of: - Name - Address - Size (in bytes) Returns C{None} if no symbol could be matched. """
# Any module may have symbols pointing anywhere in memory, so there's # no easy way to optimize this. I guess we're stuck with brute force. found = None for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if SymbolAddress > address: continue if SymbolAddress == address: found = (SymbolName, SymbolAddress, SymbolSize) break if SymbolAddress < address: if found and (address - found[1]) < (address - SymbolAddress): continue else: found = (SymbolName, SymbolAddress, SymbolSize) return found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_module(self, aModule): """ Private method to add a module object to the snapshot. @type aModule: L{Module} @param aModule: Module object. """
## if not isinstance(aModule, Module): ## if hasattr(aModule, '__class__'): ## typename = aModule.__class__.__name__ ## else: ## typename = str(type(aModule)) ## msg = "Expected Module, got %s instead" % typename ## raise TypeError(msg) lpBaseOfDll = aModule.get_base() ## if lpBaseOfDll in self.__moduleDict: ## msg = "Module already exists: %d" % lpBaseOfDll ## raise KeyError(msg) aModule.set_process(self) self.__moduleDict[lpBaseOfDll] = aModule
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _del_module(self, lpBaseOfDll): """ Private method to remove a module object from the snapshot. @type lpBaseOfDll: int @param lpBaseOfDll: Module base address. """
try: aModule = self.__moduleDict[lpBaseOfDll] del self.__moduleDict[lpBaseOfDll] except KeyError: aModule = None msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll) warnings.warn(msg, RuntimeWarning) if aModule: aModule.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __add_loaded_module(self, event): """ Private method to automatically add new module objects from debug events. @type event: L{Event} @param event: Event object. """
lpBaseOfDll = event.get_module_base() hFile = event.get_file_handle() ## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan if lpBaseOfDll not in self.__moduleDict: fileName = event.get_filename() if not fileName: fileName = None if hasattr(event, 'get_start_address'): EntryPoint = event.get_start_address() else: EntryPoint = None aModule = Module(lpBaseOfDll, hFile, fileName = fileName, EntryPoint = EntryPoint, process = self) self._add_module(aModule) else: aModule = self.get_module(lpBaseOfDll) if not aModule.hFile and hFile not in (None, 0, win32.INVALID_HANDLE_VALUE): aModule.hFile = hFile if not aModule.process: aModule.process = self if aModule.EntryPoint is None and \ hasattr(event, 'get_start_address'): aModule.EntryPoint = event.get_start_address() if not aModule.fileName: fileName = event.get_filename() if fileName: aModule.fileName = fileName
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _notify_unload_dll(self, event): """ Notify the release of a loaded module. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{UnloadDLLEvent} @param event: Unload DLL event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
lpBaseOfDll = event.get_module_base() ## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan if lpBaseOfDll in self.__moduleDict: self._del_module(lpBaseOfDll) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def connectToDebugger(self, debuggerPort, debugger_options=None): ''' Used to show console with variables connection. Mainly, monkey-patches things in the debugger structure so that the debugger protocol works. ''' if debugger_options is None: debugger_options = {} env_key = "PYDEVD_EXTRA_ENVS" if env_key in debugger_options: for (env_name, value) in dict_iter_items(debugger_options[env_key]): existing_value = os.environ.get(env_name, None) if existing_value: os.environ[env_name] = "%s%c%s" % (existing_value, os.path.pathsep, value) else: os.environ[env_name] = value if env_name == "PYTHONPATH": sys.path.append(value) del debugger_options[env_key] def do_connect_to_debugger(): try: # Try to import the packages needed to attach the debugger import pydevd from _pydev_imps._pydev_saved_modules import threading except: # This happens on Jython embedded in host eclipse traceback.print_exc() sys.stderr.write('pydevd is not available, cannot connect\n', ) from _pydevd_bundle.pydevd_constants import set_thread_id from _pydev_bundle import pydev_localhost set_thread_id(threading.currentThread(), "console_main") VIRTUAL_FRAME_ID = "1" # matches PyStackFrameConsole.java VIRTUAL_CONSOLE_ID = "console_main" # matches PyThreadConsole.java f = FakeFrame() f.f_back = None f.f_globals = {} # As globals=locals here, let's simply let it empty (and save a bit of network traffic). f.f_locals = self.get_namespace() self.debugger = pydevd.PyDB() self.debugger.add_fake_frame(thread_id=VIRTUAL_CONSOLE_ID, frame_id=VIRTUAL_FRAME_ID, frame=f) try: pydevd.apply_debugger_options(debugger_options) self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort) self.debugger.prepare_to_run() self.debugger.disable_tracing() except: traceback.print_exc() sys.stderr.write('Failed to connect to target debugger.\n') # Register to process commands when idle self.debugrunning = False try: import pydevconsole pydevconsole.set_debug_hook(self.debugger.process_internal_commands) except: traceback.print_exc() sys.stderr.write('Version of Python does not support debuggable Interactive Console.\n') # Important: it has to be really enabled in the main thread, so, schedule # it to run in the main thread. self.exec_queue.put(do_connect_to_debugger) return ('connect complete',)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit_api(api): """Commit to a particular API, and trigger ImportErrors on subsequent dangerous imports"""
if api == QT_API_PYSIDE: ID.forbid('PyQt4') ID.forbid('PyQt5') else: ID.forbid('PySide')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loaded_api(): """Return which API is loaded, if any If this returns anything besides None, importing any other Qt binding is unsafe. Returns ------- None, 'pyside', 'pyqt', or 'pyqtv1' """
if 'PyQt4.QtCore' in sys.modules: if qtapi_version() == 2: return QT_API_PYQT else: return QT_API_PYQTv1 elif 'PySide.QtCore' in sys.modules: return QT_API_PYSIDE elif 'PyQt5.QtCore' in sys.modules: return QT_API_PYQT5 return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_binding(api): """Safely check for PyQt4 or PySide, without importing submodules Parameters api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault'] Which module to check for Returns ------- True if the relevant module appears to be importable """
# we can't import an incomplete pyside and pyqt4 # this will cause a crash in sip (#1431) # check for complete presence before importing module_name = {QT_API_PYSIDE: 'PySide', QT_API_PYQT: 'PyQt4', QT_API_PYQTv1: 'PyQt4', QT_API_PYQT_DEFAULT: 'PyQt4', QT_API_PYQT5: 'PyQt5', } module_name = module_name[api] import imp try: #importing top level PyQt4/PySide module is ok... mod = __import__(module_name) #...importing submodules is not imp.find_module('QtCore', mod.__path__) imp.find_module('QtGui', mod.__path__) imp.find_module('QtSvg', mod.__path__) #we can also safely check PySide version if api == QT_API_PYSIDE: return check_version(mod.__version__, '1.0.3') else: return True except ImportError: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_import(api): """Safely query whether an API is importable, without importing it"""
if not has_binding(api): return False current = loaded_api() if api == QT_API_PYQT_DEFAULT: return current in [QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT5, None] else: return current in [api, None]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extended_blank_lines(logical_line, blank_lines, blank_before, indent_level, previous_logical): """Check for missing blank lines after class declaration."""
if previous_logical.startswith('def '): if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line): yield (0, 'E303 too many blank lines ({0})'.format(blank_lines)) elif pycodestyle.DOCSTRING_REGEX.match(previous_logical): # Missing blank line between class docstring and method declaration. if ( indent_level and not blank_lines and not blank_before and logical_line.startswith(('def ')) and '(self' in logical_line ): yield (0, 'E301 expected 1 blank line, found 0')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_e265(source, aggressive=False): # pylint: disable=unused-argument """Format block comments."""
if '#' not in source: # Optimization. return source ignored_line_numbers = multiline_string_lines( source, include_docstrings=True) | set(commented_out_code_lines(source)) fixed_lines = [] sio = io.StringIO(source) for (line_number, line) in enumerate(sio.readlines(), start=1): if ( line.lstrip().startswith('#') and line_number not in ignored_line_numbers and not pycodestyle.noqa(line) ): indentation = _get_indentation(line) line = line.lstrip() # Normalize beginning if not a shebang. if len(line) > 1: pos = next((index for index, c in enumerate(line) if c != '#')) if ( # Leave multiple spaces like '# ' alone. (line[:pos].count('#') > 1 or line[1].isalnum()) and # Leave stylistic outlined blocks alone. not line.rstrip().endswith('#') ): line = '# ' + line.lstrip('# \t') fixed_lines.append(indentation + line) else: fixed_lines.append(line) return ''.join(fixed_lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refactor(source, fixer_names, ignore=None, filename=''): """Return refactored code using lib2to3. Skip if ignore string is produced in the refactored code. """
check_lib2to3() from lib2to3 import pgen2 try: new_text = refactor_with_2to3(source, fixer_names=fixer_names, filename=filename) except (pgen2.parse.ParseError, SyntaxError, UnicodeDecodeError, UnicodeEncodeError): return source if ignore: if ignore in new_text and ignore not in source: return source return new_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_indentation(line): """Return leading whitespace."""
if line.strip(): non_whitespace_index = len(line) - len(line.lstrip()) return line[:non_whitespace_index] else: return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _priority_key(pep8_result): """Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation. """
priority = [ # Fix multiline colon-based before semicolon based. 'e701', # Break multiline statements early. 'e702', # Things that make lines longer. 'e225', 'e231', # Remove extraneous whitespace before breaking lines. 'e201', # Shorten whitespace in comment before resorting to wrapping. 'e262' ] middle_index = 10000 lowest_priority = [ # We need to shorten lines last since the logical fixer can get in a # loop, which causes us to exit early. 'e501' ] key = pep8_result['id'].lower() try: return priority.index(key) except ValueError: try: return middle_index + lowest_priority.index(key) + 1 except ValueError: return middle_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_multiline(line): """Normalize multiline-related code that will cause syntax error. This is for purposes of checking syntax. """
if line.startswith('def ') and line.rstrip().endswith(':'): return line + ' pass' elif line.startswith('return '): return 'def _(): ' + line elif line.startswith('@'): return line + 'def _(): pass' elif line.startswith('class '): return line + ' pass' elif line.startswith(('if ', 'elif ', 'for ', 'while ')): return line + ' pass' else: return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_whitespace(line, offset, replacement): """Replace whitespace at offset and return fixed line."""
# Replace escaped newlines too left = line[:offset].rstrip('\n\r \t\\') right = line[offset:].lstrip('\n\r \t\\') if right.startswith('#'): return line else: return left + replacement + right
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_global_fixes(source, options, where='global', filename=''): """Run global fixes on source code. These are fixes that only need be done once (unlike those in FixPEP8, which are dependent on pycodestyle). """
if any(code_match(code, select=options.select, ignore=options.ignore) for code in ['E101', 'E111']): source = reindent(source, indent_size=options.indent_size) for (code, function) in global_fixes(): if code_match(code, select=options.select, ignore=options.ignore): if options.verbose: print('---> Applying {0} fix for {1}'.format(where, code.upper()), file=sys.stderr) source = function(source, aggressive=options.aggressive) source = fix_2to3(source, aggressive=options.aggressive, select=options.select, ignore=options.ignore, filename=filename) return source
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv=None, apply_config=True): """Command-line entry."""
if argv is None: argv = sys.argv try: # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: args = parse_args(argv[1:], apply_config=apply_config) if args.list_fixes: for code, description in sorted(supported_fixes()): print('{code} - {description}'.format( code=code, description=description)) return 0 if args.files == ['-']: assert not args.in_place encoding = sys.stdin.encoding or get_encoding() # LineEndingWrapper is unnecessary here due to the symmetry between # standard in and standard out. wrap_output(sys.stdout, encoding=encoding).write( fix_code(sys.stdin.read(), args, encoding=encoding)) else: if args.in_place or args.diff: args.files = list(set(args.files)) else: assert len(args.files) == 1 assert not args.recursive fix_multiple_files(args.files, args, sys.stdout) except KeyboardInterrupt: return 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_e722(self, result): """fix bare except"""
(line_index, _, target) = get_index_offset_contents(result, self.source) if BARE_EXCEPT_REGEX.search(target): self.source[line_index] = '{0}{1}'.format( target[:result['column'] - 1], "except Exception:")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_after_delimiter(self, item, indent_amt): """Split the line only after a delimiter."""
self._delete_whitespace() if self.fits_on_current_line(item.size): return last_space = None for item in reversed(self._lines): if ( last_space and (not isinstance(item, Atom) or not item.is_colon) ): break else: last_space = None if isinstance(item, self._Space): last_space = item if isinstance(item, (self._LineBreak, self._Indent)): return if not last_space: return self.add_line_break_at(self._lines.index(last_space), indent_amt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interact(banner=None, readfunc=None, local=None): """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() """
console = InteractiveConsole(local) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runsource(self, source, filename="<input>", symbol="single"): """Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens. 3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit). The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line. """
try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return False if code is None: # Case 2 return True # Case 3 self.runcode(code) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, line): """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()). """
self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_in_pager(self, strng, *args, **kwargs): """ Run a string through pager """
# On PyDev we just output the string, there are scroll bars in the console # to handle "paging". This is the same behaviour as when TERM==dump (see # page.py) # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng.get('text/plain', strng) print(strng)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matchers(self): """All active matcher routines for completion"""
# To remove python_matches we now have to override it as it's now a property in the superclass. return [ self.file_matches, self.magic_matches, self.python_func_kw_matches, self.dict_key_matches, ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_completer(self): """Initialize the completion machinery. This creates a completer that provides the completions that are IPython specific. We use this to supplement PyDev's core code completions. """
# PyDev uses its own completer and custom hooks so that it uses # most completions from PyDev's core completer which provides # extra information. # See getCompletions for where the two sets of results are merged if IPythonRelease._version_major >= 6: self.Completer = self._new_completer_600() elif IPythonRelease._version_major >= 5: self.Completer = self._new_completer_500() elif IPythonRelease._version_major >= 2: self.Completer = self._new_completer_234() elif IPythonRelease._version_major >= 1: self.Completer = self._new_completer_100() if hasattr(self.Completer, 'use_jedi'): self.Completer.use_jedi = False self.add_completer_hooks() if IPythonRelease._version_major <= 3: # Only configure readline if we truly are using readline. IPython can # do tab-completion over the network, in GUIs, etc, where readline # itself may be absent if self.has_readline: self.set_readline_completer()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): """ Opens a new handle to the process. The new handle is stored in the L{hProcess} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.PROCESS_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx} @raise WindowsError: It's not possible to open a handle to the process with the requested access rights. This tipically happens because the target process is a system process and the debugger is not runnning with administrative rights. """
hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId) try: self.close_handle() except Exception: warnings.warn( "Failed to close process handle: %s" % traceback.format_exc()) self.hProcess = hProcess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_handle(self): """ Closes the handle to the process. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. So unless you've been tinkering with it, setting L{hProcess} to C{None} should be enough. """
try: if hasattr(self.hProcess, 'close'): self.hProcess.close() elif self.hProcess not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hProcess) finally: self.hProcess = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self, dwExitCode = 0): """ Terminates the execution of the process. @raise WindowsError: On error an exception is raised. """
hProcess = self.get_handle(win32.PROCESS_TERMINATE) win32.TerminateProcess(hProcess, dwExitCode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suspend(self): """ Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised. """
self.scan_threads() # force refresh the snapshot suspended = list() try: for aThread in self.iter_threads(): aThread.suspend() suspended.append(aThread) except Exception: for aThread in suspended: try: aThread.resume() except Exception: pass raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume(self): """ Resumes execution on all threads of the process. @raise WindowsError: On error an exception is raised. """
if self.get_thread_count() == 0: self.scan_threads() # only refresh the snapshot if empty resumed = list() try: for aThread in self.iter_threads(): aThread.resume() resumed.append(aThread) except Exception: for aThread in resumed: try: aThread.suspend() except Exception: pass raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_debugged(self): """ Tries to determine if the process is being debugged by another process. It may detect other debuggers besides WinAppDbg. @rtype: bool @return: C{True} if the process has a debugger attached. @warning: May return inaccurate results when some anti-debug techniques are used by the target process. @note: To know if a process currently being debugged by a L{Debug} object, call L{Debug.is_debugee} instead. """
# FIXME the MSDN docs don't say what access rights are needed here! hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.CheckRemoteDebuggerPresent(hProcess)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __fixup_labels(self, disasm): """ Private method used when disassembling from process memory. It has no return value because the list is modified in place. On return all raw memory addresses are replaced by labels when possible. @type disasm: list of tuple(int, int, str, str) @param disasm: Output of one of the dissassembly functions. """
for index in compat.xrange(len(disasm)): (address, size, text, dump) = disasm[index] m = self.__hexa_parameter.search(text) while m: s, e = m.span() value = text[s:e] try: label = self.get_label_at_address( int(value, 0x10) ) except Exception: label = None if label: text = text[:s] + label + text[e:] e = s + len(value) m = self.__hexa_parameter.search(text, e) disasm[index] = (address, size, text, dump)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disassemble_current(self, dwThreadId): """ Disassemble the instruction at the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """
aThread = self.get_thread(dwThreadId) return self.disassemble_instruction(aThread.get_pc())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_wow64(self): """ Determines if the process is running under WOW64. @rtype: bool @return: C{True} if the process is running under WOW64. That is, a 32-bit application running in a 64-bit Windows. C{False} if the process is either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows. @raise WindowsError: On error an exception is raised. @see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} """
try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) try: wow64 = win32.IsWow64Process(hProcess) except AttributeError: wow64 = False self.__wow64 = wow64 return wow64
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_start_time(self): """ Determines when has this process started running. @rtype: win32.SYSTEMTIME @return: Process start time. """
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) CreationTime = win32.GetProcessTimes(hProcess)[0] return win32.FileTimeToSystemTime(CreationTime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_exit_time(self): """ Determines when has this process finished running. If the process is still alive, the current time is returned instead. @rtype: win32.SYSTEMTIME @return: Process exit time. """
if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) ExitTime = win32.GetProcessTimes(hProcess)[1] return win32.FileTimeToSystemTime(ExitTime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_running_time(self): """ Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds. """
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) (CreationTime, ExitTime, _, _) = win32.GetProcessTimes(hProcess) if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32) ExitTime = ExitTime.dwLowDateTime + ( ExitTime.dwHighDateTime << 32) RunningTime = ExitTime - CreationTime return RunningTime / 10000
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_services(self): """ Retrieves the list of system services that are currently running in this process. @see: L{System.get_services} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors. """
self.__load_System_class() pid = self.get_pid() return [d for d in System.get_active_services() if d.ProcessId == pid]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_peb_address(self): """ Returns a remote pointer to the PEB. @rtype: int @return: Remote pointer to the L{win32.PEB} structure. Returns C{None} on error. """
try: return self._peb_ptr except AttributeError: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) pbi = win32.NtQueryInformationProcess(hProcess, win32.ProcessBasicInformation) address = pbi.PebBaseAddress self._peb_ptr = address return address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command_line_block(self): """ Retrieves the command line block memory address and size. @rtype: tuple(int, int) @return: Tuple with the memory address of the command line block and it's maximum size in Unicode characters. @raise WindowsError: On error an exception is raised. """
peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.CommandLine return (s.Buffer, s.MaximumLength)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environment_block(self): """ Retrieves the environment block memory address for the process. @note: The size is always enough to contain the environment data, but it may not be an exact size. It's best to read the memory and scan for two null wide chars to find the actual size. @rtype: tuple(int, int) @return: Tuple with the memory address of the environment block and it's size. @raise WindowsError: On error an exception is raised. """
peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) Environment = pp.Environment try: EnvironmentSize = pp.EnvironmentSize except AttributeError: mbi = self.mquery(Environment) EnvironmentSize = mbi.RegionSize + mbi.BaseAddress - Environment return (Environment, EnvironmentSize)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command_line(self): """ Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised. """
(Buffer, MaximumLength) = self.get_command_line_block() CommandLine = self.peek_string(Buffer, dwMaxSize=MaximumLength, fUnicode=True) gst = win32.GuessStringType if gst.t_default == gst.t_ansi: CommandLine = CommandLine.encode('cp1252') return CommandLine
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environment_variables(self): """ Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised. """
# Note: the first bytes are garbage and must be skipped. Then the first # two environment entries are the current drive and directory as key # and value pairs, followed by the ExitCode variable (it's what batch # files know as "errorlevel"). After that, the real environment vars # are there in alphabetical order. In theory that's where it stops, # but I've always seen one more "variable" tucked at the end which # may be another environment block but in ANSI. I haven't examined it # yet, I'm just skipping it because if it's parsed as Unicode it just # renders garbage. # Read the environment block contents. data = self.peek( *self.get_environment_block() ) # Put them into a Unicode buffer. tmp = ctypes.create_string_buffer(data) buffer = ctypes.create_unicode_buffer(len(data)) ctypes.memmove(buffer, tmp, len(data)) del tmp # Skip until the first Unicode null char is found. pos = 0 while buffer[pos] != u'\0': pos += 1 pos += 1 # Loop for each environment variable... environment = [] while buffer[pos] != u'\0': # Until we find a null char... env_name_pos = pos env_name = u'' found_name = False while buffer[pos] != u'\0': # Get the current char. char = buffer[pos] # Is it an equal sign? if char == u'=': # Skip leading equal signs. if env_name_pos == pos: env_name_pos += 1 pos += 1 continue # Otherwise we found the separator equal sign. pos += 1 found_name = True break # Add the char to the variable name. env_name += char # Next char. pos += 1 # If the name was not parsed properly, stop. if not found_name: break # Read the variable value until we find a null char. env_value = u'' while buffer[pos] != u'\0': env_value += buffer[pos] pos += 1 # Skip the null char. pos += 1 # Add to the list of environment variables found. environment.append( (env_name, env_value) ) # Remove the last entry, it's garbage. if environment: environment.pop() # Return the environment variables. return environment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environment_data(self, fUnicode = None): """ Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: list of str @return: Environment keys and values separated by a (C{=}) character, as found in the process memory. @raise WindowsError: On error an exception is raised. """
# Issue a deprecation warning. warnings.warn( "Process.get_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Get the environment variables. block = [ key + u'=' + value for (key, value) \ in self.get_environment_variables() ] # Convert the data to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: block = [x.encode('cp1252') for x in block] # Return the environment data. return block
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_environment_data(block): """ Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. """
# Issue a deprecation warning. warnings.warn( "Process.parse_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Create an empty environment dictionary. environment = dict() # End here if the environment block is empty. if not block: return environment # Prepare the tokens (ANSI or Unicode). gst = win32.GuessStringType if type(block[0]) == gst.t_ansi: equals = '=' terminator = '\0' else: equals = u'=' terminator = u'\0' # Split the blocks into key/value pairs. for chunk in block: sep = chunk.find(equals, 1) if sep < 0: ## raise Exception() continue # corrupted environment block? key, value = chunk[:sep], chunk[sep+1:] # For duplicated keys, append the value. # Values are separated using null terminators. if key not in environment: environment[key] = value else: environment[key] += terminator + value # Return the environment dictionary. return environment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environment(self, fUnicode = None): """ Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_variables())} @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. @raise WindowsError: On error an exception is raised. """
# Get the environment variables. variables = self.get_environment_variables() # Convert the strings to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: variables = [ ( key.encode('cp1252'), value.encode('cp1252') ) \ for (key, value) in variables ] # Add the variables to a dictionary, concatenating duplicates. environment = dict() for key, value in variables: if key in environment: environment[key] = environment[key] + u'\0' + value else: environment[key] = value # Return the dictionary. return environment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_bytes(self, bytes, minAddr = None, maxAddr = None): """ Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of int @return: An iterator of memory addresses where the pattern was found. @raise WindowsError: An error occurred when querying or reading the process memory. """
pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None): """ Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The text that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """
pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1): """ Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """
pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_hexa(self, hexa, minAddr = None, maxAddr = None): """ Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The bytes that match the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """
pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, lpBaseAddress, nSize): """ Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: On error an exception is raised. """
hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not self.is_buffer(lpBaseAddress, nSize): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) data = win32.ReadProcessMemory(hProcess, lpBaseAddress, nSize) if len(data) != nSize: raise ctypes.WinError() return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """
return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_structure(self, lpBaseAddress, stype): """ Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return: Structure instance filled in with data read from the process memory. @raise WindowsError: On error an exception is raised. """
if type(lpBaseAddress) not in (type(0), type(long(0))): lpBaseAddress = ctypes.cast(lpBaseAddress, ctypes.c_void_p) data = self.read(lpBaseAddress, ctypes.sizeof(stype)) buff = ctypes.create_string_buffer(data) ptr = ctypes.cast(ctypes.pointer(buff), ctypes.POINTER(stype)) return ptr.contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_string(self, lpBaseAddress, nChars, fUnicode = False): """ Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember that Unicode strings have two byte characters. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @rtype: str, compat.unicode @return: String read from the process memory space. @raise WindowsError: On error an exception is raised. """
if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek(self, lpBaseAddress, nSize): """ Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Returns an empty string on error. """
# XXX TODO # + Maybe change page permissions before trying to read? # + Maybe use mquery instead of get_memory_map? # (less syscalls if we break out of the loop earlier) data = '' if nSize > 0: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) for mbi in self.get_memory_map(lpBaseAddress, lpBaseAddress + nSize): if not mbi.is_readable(): nSize = mbi.BaseAddress - lpBaseAddress break if nSize > 0: data = win32.ReadProcessMemory( hProcess, lpBaseAddress, nSize) except WindowsError: e = sys.exc_info()[1] msg = "Error reading process %d address %s: %s" msg %= (self.get_pid(), HexDump.address(lpBaseAddress), e.strerror) warnings.warn(msg) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_char(self, lpBaseAddress): """ Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error. """
char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000): """ Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @type dwMaxSize: int @param dwMaxSize: Maximum allowed string length to read, in bytes. @rtype: str, compat.unicode @return: String read from the process memory space. It B{doesn't} include the terminating null character. Returns an empty string on failure. """
# Validate the parameters. if not lpBaseAddress or dwMaxSize == 0: if fUnicode: return u'' return '' if not dwMaxSize: dwMaxSize = 0x1000 # Read the string. szString = self.peek(lpBaseAddress, dwMaxSize) # If the string is Unicode... if fUnicode: # Decode the string. szString = compat.unicode(szString, 'U16', 'replace') ## try: ## szString = compat.unicode(szString, 'U16') ## except UnicodeDecodeError: ## szString = struct.unpack('H' * (len(szString) / 2), szString) ## szString = [ unichr(c) for c in szString ] ## szString = u''.join(szString) # Truncate the string when the first null char is found. szString = szString[ : szString.find(u'\0') ] # If the string is ANSI... else: # Truncate the string when the first null char is found. szString = szString[ : szString.find('\0') ] # Return the decoded string. return szString
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def malloc(self, dwSize, lpAddress = None): """ Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. @rtype: int @return: Address of the newly allocated memory. @raise WindowsError: On error an exception is raised. """
hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mprotect(self, lpAddress, dwSize, flNewProtect): """ Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewProtect: int @param flNewProtect: New protect flags. @rtype: int @return: Old protect flags. @raise WindowsError: On error an exception is raised. """
hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free(self, lpAddress): """ Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an exception is raised. """
hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_pointer(self, address): """ Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code or data pointer. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.has_content()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_valid(self, address): """ Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_free(self, address): """ Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_free()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_reserved()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_commited(self, address): """ Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_commited()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_guard(self, address): """ Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_readable(self, address): """ Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and readable page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_readable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_writeable(self, address): """ Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and writeable page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_writeable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_copy_on_write(self, address): """ Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, copy-on-write page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_copy_on_write()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_executable(self, address): """ Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and executable page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_address_executable_and_writeable(self, address): """ Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, writeable and executable page. @raise WindowsError: An exception is raised on error. """
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable_and_writeable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is a valid code or data buffer, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """
if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.has_content(): return False size = size - mbi.RegionSize return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_memory_map(self, minAddr = None, maxAddr = None): """ Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """
minAddr, maxAddr = MemoryAddresses.align_address_range(minAddr,maxAddr) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr: try: mbi = self.mquery(currentAddr) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: break raise yield mbi prevAddr = currentAddr currentAddr = mbi.BaseAddress + mbi.RegionSize
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @return: Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible. """
hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not memoryMap: memoryMap = self.get_memory_map() mappedFilenames = dict() for mbi in memoryMap: if mbi.Type not in (win32.MEM_IMAGE, win32.MEM_MAPPED): continue baseAddress = mbi.BaseAddress fileName = "" try: fileName = win32.GetMappedFileName(hProcess, baseAddress) fileName = PathOperations.native_to_win32_pathname(fileName) except WindowsError: #e = sys.exc_info()[1] #try: # msg = "Can't get mapped file name at address %s in process " \ # "%d, reason: %s" % (HexDump.address(baseAddress), # self.get_pid(), # e.strerror) # warnings.warn(msg, Warning) #except Exception: pass mappedFilenames[baseAddress] = fileName return mappedFilenames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can only iterated once. To be able to iterate indefinitely call the L{generate_memory_snapshot} method instead. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: Iterator of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """
# One may feel tempted to include calls to self.suspend() and # self.resume() here, but that wouldn't work on a dead process. # It also wouldn't be needed when debugging since the process is # already suspended when the debug event arrives. So it's up to # the user to suspend the process if needed. # Get the memory map. memory = self.get_memory_map(minAddr, maxAddr) # Abort if the map couldn't be retrieved. if not memory: return # Get the mapped filenames. # Don't fail on access denied errors. try: filenames = self.get_mapped_filenames(memory) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise filenames = dict() # Trim the first memory information block if needed. if minAddr is not None: minAddr = MemoryAddresses.align_address_to_page_start(minAddr) mbi = memory[0] if mbi.BaseAddress < minAddr: mbi.RegionSize = mbi.BaseAddress + mbi.RegionSize - minAddr mbi.BaseAddress = minAddr # Trim the last memory information block if needed. if maxAddr is not None: if maxAddr != MemoryAddresses.align_address_to_page_start(maxAddr): maxAddr = MemoryAddresses.align_address_to_page_end(maxAddr) mbi = memory[-1] if mbi.BaseAddress + mbi.RegionSize > maxAddr: mbi.RegionSize = maxAddr - mbi.BaseAddress # Read the contents of each block and yield it. while memory: mbi = memory.pop(0) # so the garbage collector can take it mbi.filename = filenames.get(mbi.BaseAddress, None) if mbi.has_content(): mbi.content = self.read(mbi.BaseAddress, mbi.RegionSize) else: mbi.content = None yield mbi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False): """ Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). @type snapshot: list( L{win32.MemoryBasicInformation} ) @param snapshot: Memory snapshot returned by L{take_memory_snapshot}. Snapshots returned by L{generate_memory_snapshot} don't work here. @type bSkipMappedFiles: bool @param bSkipMappedFiles: C{True} to avoid restoring the contents of memory mapped files, C{False} otherwise. Use with care! Setting this to C{False} can cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don't change, so trying to restore their contents is usually a waste of time. @type bSkipOnError: bool @param bSkipOnError: C{True} to issue a warning when an error occurs during the restoration of the snapshot, C{False} to stop and raise an exception instead. Use with care! Setting this to C{True} will cause the debugger to falsely believe the memory snapshot has been correctly restored. @raise WindowsError: An error occured while restoring the snapshot. @raise RuntimeError: An error occured while restoring the snapshot. @raise TypeError: A snapshot of the wrong type was passed. """
if not snapshot or not isinstance(snapshot, list) \ or not isinstance(snapshot[0], win32.MemoryBasicInformation): raise TypeError( "Only snapshots returned by " \ "take_memory_snapshot() can be used here." ) # Get the process handle. hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_SUSPEND_RESUME | win32.PROCESS_QUERY_INFORMATION ) # Freeze the process. self.suspend() try: # For each memory region in the snapshot... for old_mbi in snapshot: # If the region matches, restore it directly. new_mbi = self.mquery(old_mbi.BaseAddress) if new_mbi.BaseAddress == old_mbi.BaseAddress and \ new_mbi.RegionSize == old_mbi.RegionSize: self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles) # If the region doesn't match, restore it page by page. else: # We need a copy so we don't corrupt the snapshot. old_mbi = win32.MemoryBasicInformation(old_mbi) # Get the overlapping range of pages. old_start = old_mbi.BaseAddress old_end = old_start + old_mbi.RegionSize new_start = new_mbi.BaseAddress new_end = new_start + new_mbi.RegionSize if old_start > new_start: start = old_start else: start = new_start if old_end < new_end: end = old_end else: end = new_end # Restore each page in the overlapping range. step = MemoryAddresses.pageSize old_mbi.RegionSize = step new_mbi.RegionSize = step address = start while address < end: old_mbi.BaseAddress = address new_mbi.BaseAddress = address self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError) address = address + step # Resume execution. finally: self.resume()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run in a new thread. @type lpParameter: int @param lpParameter: (Optional) Parameter to be pushed in the stack. @rtype: tuple( L{Thread}, int ) @return: The injected Thread object and the memory address where the code was written. @raise WindowsError: An exception is raised on error. """
# Uncomment for debugging... ## payload = '\xCC' + payload # Allocate the memory for the shellcode. lpStartAddress = self.malloc(len(payload)) # Catch exceptions so we can free the memory on error. try: # Write the shellcode to our memory location. self.write(lpStartAddress, payload) # Start a new thread for the shellcode to run. aThread = self.start_thread(lpStartAddress, lpParameter, bSuspended = False) # Remember the shellcode address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code, or have your shellcode clean up # after itself (recommended). aThread.pInjectedMemory = lpStartAddress # Free the memory on error. except Exception: self.free(lpStartAddress) raise # Return the Thread object and the shellcode address. return aThread, lpStartAddress