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 _send_breakpoint_condition_exception(self, thread, conditional_breakpoint_exception_tuple): """If conditional breakpoint raises an exception during evaluation send exception details to java """
thread_id = get_thread_id(thread) # conditional_breakpoint_exception_tuple - should contain 2 values (exception_type, stacktrace) if conditional_breakpoint_exception_tuple and len(conditional_breakpoint_exception_tuple) == 2: exc_type, stacktrace = conditional_breakpoint_exception_tuple int_cmd = InternalGetBreakpointException(thread_id, exc_type, stacktrace) self.post_internal_command(int_cmd, thread_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_caught_exception_stack_proceeded(self, thread): """Sends that some thread was resumed and is no longer showing an exception trace. """
thread_id = get_thread_id(thread) int_cmd = InternalSendCurrExceptionTraceProceeded(thread_id) self.post_internal_command(int_cmd, thread_id) self.process_internal_commands()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_process_created_message(self): """Sends a message that a new process has been created. """
cmd = self.cmd_factory.make_process_created_message() self.writer.add_command(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_wait_suspend(self, thread, frame, event, arg, is_unhandled_exception=False): # @UnusedVariable """ busy waits until the thread state changes to RUN it expects thread's state as attributes of the thread. Upon running, processes any outstanding Stepping commands. :param is_unhandled_exception: If True we should use the line of the exception instead of the current line in the frame as the paused location on the top-level frame (exception info must be passed on 'arg'). """
# print('do_wait_suspend %s %s %s %s' % (frame.f_lineno, frame.f_code.co_name, frame.f_code.co_filename, event)) self.process_internal_commands() thread_id = get_current_thread_id(thread) # Send the suspend message message = thread.additional_info.pydev_message suspend_type = thread.additional_info.trace_suspend_type thread.additional_info.trace_suspend_type = 'trace' # Reset to trace mode for next call. frame_id_to_lineno = {} stop_reason = thread.stop_reason if is_unhandled_exception: # arg must be the exception info (tuple(exc_type, exc, traceback)) tb = arg[2] while tb is not None: frame_id_to_lineno[id(tb.tb_frame)] = tb.tb_lineno tb = tb.tb_next with self.suspended_frames_manager.track_frames(self) as frames_tracker: frames_tracker.track(thread_id, frame, frame_id_to_lineno) cmd = frames_tracker.create_thread_suspend_command(thread_id, stop_reason, message, suspend_type) self.writer.add_command(cmd) with CustomFramesContainer.custom_frames_lock: # @UndefinedVariable from_this_thread = [] for frame_custom_thread_id, custom_frame in dict_iter_items(CustomFramesContainer.custom_frames): if custom_frame.thread_id == thread.ident: frames_tracker.track(thread_id, custom_frame.frame, frame_id_to_lineno, frame_custom_thread_id=frame_custom_thread_id) # print('Frame created as thread: %s' % (frame_custom_thread_id,)) self.writer.add_command(self.cmd_factory.make_custom_frame_created_message( frame_custom_thread_id, custom_frame.name)) self.writer.add_command( frames_tracker.create_thread_suspend_command(frame_custom_thread_id, CMD_THREAD_SUSPEND, "", suspend_type)) from_this_thread.append(frame_custom_thread_id) with self._threads_suspended_single_notification.notify_thread_suspended(thread_id, stop_reason): keep_suspended = self._do_wait_suspend(thread, frame, event, arg, suspend_type, from_this_thread, frames_tracker) if keep_suspended: # This means that we should pause again after a set next statement. self._threads_suspended_single_notification.increment_suspend_time() self.do_wait_suspend(thread, frame, event, arg, is_unhandled_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 _get_arch(): """ Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: - L{ARCH_I386} (C{"i386"}) for Intel 32-bit x86 processor or compatible. - L{ARCH_AMD64} (C{"amd64"}) for Intel 64-bit x86_64 processor or compatible. May also return one of the following values if you get both Python and - L{ARCH_MIPS} (C{"mips"}) for MIPS compatible processors. - L{ARCH_ALPHA} (C{"alpha"}) for Alpha processors. - L{ARCH_PPC} (C{"ppc"}) for PowerPC compatible processors. - L{ARCH_SHX} (C{"shx"}) for Hitachi SH processors. - L{ARCH_ARM} (C{"arm"}) for ARM compatible processors. - L{ARCH_IA64} (C{"ia64"}) for Intel Itanium processor or compatible. - L{ARCH_ALPHA64} (C{"alpha64"}) for Alpha64 processors. - L{ARCH_MSIL} (C{"msil"}) for the .NET virtual machine. - L{ARCH_SPARC} (C{"sparc"}) for Sun Sparc processors. Probably IronPython returns C{ARCH_MSIL} but I haven't tried it. Python on Windows CE and Windows Mobile should return C{ARCH_ARM}. Python on Solaris using Wine would return C{ARCH_SPARC}. Python in an Itanium machine should return C{ARCH_IA64} both on Wine and proper Windows. All other values should only be returned on Linux using Wine. """
try: si = GetNativeSystemInfo() except Exception: si = GetSystemInfo() try: return _arch_map[si.id.w.wProcessorArchitecture] except KeyError: return ARCH_UNKNOWN
<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_wow64(): """ Determines if the current process is running in Windows-On-Windows 64 bits. @rtype: bool @return: C{True} of the current process is a 32 bit program running in a 64 bit version of Windows, C{False} if it's either a 32 bit program in a 32 bit Windows or a 64 bit program in a 64 bit Windows. """
# Try to determine if the debugger itself is running on WOW64. # On error assume False. if bits == 64: wow64 = False else: try: wow64 = IsWow64Process( GetCurrentProcess() ) except Exception: wow64 = False 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 log_context(trace_level, stream): ''' To be used to temporarily change the logging settings. ''' original_trace_level = DebugInfoHolder.DEBUG_TRACE_LEVEL original_stream = DebugInfoHolder.DEBUG_STREAM DebugInfoHolder.DEBUG_TRACE_LEVEL = trace_level DebugInfoHolder.DEBUG_STREAM = stream try: yield finally: DebugInfoHolder.DEBUG_TRACE_LEVEL = original_trace_level DebugInfoHolder.DEBUG_STREAM = original_stream
<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_control_flow(self): """ Private method to tell if the instruction pointed to by the program counter is a control flow instruction. Currently only works for x86 and amd64 architectures. """
jump_instructions = ( 'jmp', 'jecxz', 'jcxz', 'ja', 'jnbe', 'jae', 'jnb', 'jb', 'jnae', 'jbe', 'jna', 'jc', 'je', 'jz', 'jnc', 'jne', 'jnz', 'jnp', 'jpo', 'jp', 'jpe', 'jg', 'jnle', 'jge', 'jnl', 'jl', 'jnge', 'jle', 'jng', 'jno', 'jns', 'jo', 'js' ) call_instructions = ( 'call', 'ret', 'retn' ) loop_instructions = ( 'loop', 'loopz', 'loopnz', 'loope', 'loopne' ) control_flow_instructions = call_instructions + loop_instructions + \ jump_instructions isControlFlow = False instruction = None if self.pc is not None and self.faultDisasm: for disasm in self.faultDisasm: if disasm[0] == self.pc: instruction = disasm[2].lower().strip() break if instruction: for x in control_flow_instructions: if x in instruction: isControlFlow = True break return isControlFlow
<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_block_data_move(self): """ Private method to tell if the instruction pointed to by the program counter is a block data move instruction. Currently only works for x86 and amd64 architectures. """
block_data_move_instructions = ('movs', 'stos', 'lods') isBlockDataMove = False instruction = None if self.pc is not None and self.faultDisasm: for disasm in self.faultDisasm: if disasm[0] == self.pc: instruction = disasm[2].lower().strip() break if instruction: for x in block_data_move_instructions: if x in instruction: isBlockDataMove = True break return isBlockDataMove
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def marshall_key(self, key): """ Marshalls a Crash key to be used in the database. @see: L{__init__} @type key: L{Crash} key. @param key: Key to convert. @rtype: str or buffer @return: Converted key. """
if key in self.__keys: return self.__keys[key] skey = pickle.dumps(key, protocol = 0) if self.compressKeys: skey = zlib.compress(skey, zlib.Z_BEST_COMPRESSION) if self.escapeKeys: skey = skey.encode('hex') if self.binaryKeys: skey = buffer(skey) self.__keys[key] = skey return skey
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unmarshall_key(self, key): """ Unmarshalls a Crash key read from the database. @type key: str or buffer @param key: Key to convert. @rtype: L{Crash} key. @return: Converted key. """
key = str(key) if self.escapeKeys: key = key.decode('hex') if self.compressKeys: key = zlib.decompress(key) key = pickle.loads(key) return key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unmarshall_value(self, value): """ Unmarshalls a Crash object read from the database. @type value: str @param value: Object to convert. @rtype: L{Crash} @return: Converted object. """
value = str(value) if self.escapeValues: value = value.decode('hex') if self.compressValues: value = zlib.decompress(value) value = pickle.loads(value) return value
<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(self, crash): """ Adds a new crash to the container. If the crash appears to be already known, it's ignored. @see: L{Crash.key} @type crash: L{Crash} @param crash: Crash object to add. """
if crash not in self: key = crash.key() skey = self.marshall_key(key) data = self.marshall_value(crash, storeMemoryMap = True) self.__db[skey] = 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 add(self, crash): """ Adds a new crash to the container. @note: When the C{allowRepeatedKeys} parameter of the constructor is set to C{False}, duplicated crashes are ignored. @see: L{Crash.key} @type crash: L{Crash} @param crash: Crash object to add. """
self.__keys.add( crash.signature ) self.__count += 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 _schedule_callback(prev, next): ''' Called when a context is stopped or a new context is made runnable. ''' try: if not prev and not next: return current_frame = sys._getframe() if next: register_tasklet_info(next) # Ok, making next runnable: set the tracing facility in it. debugger = get_global_debugger() if debugger is not None: next.trace_function = debugger.get_thread_local_trace_func() frame = next.frame if frame is current_frame: frame = frame.f_back if hasattr(frame, 'f_trace'): # Note: can be None (but hasattr should cover for that too). frame.f_trace = debugger.get_thread_local_trace_func() debugger = None if prev: register_tasklet_info(prev) try: for tasklet_ref, tasklet_info in dict_items(_weak_tasklet_registered_to_info): # Make sure it's a copy! tasklet = tasklet_ref() if tasklet is None or not tasklet.alive: # Garbage-collected already! try: del _weak_tasklet_registered_to_info[tasklet_ref] except KeyError: pass if tasklet_info.frame_id is not None: remove_custom_frame(tasklet_info.frame_id) else: is_running = stackless.get_thread_info(tasklet.thread_id)[1] is tasklet if tasklet is prev or (tasklet is not next and not is_running): # the tasklet won't run after this scheduler action: # - the tasklet is the previous tasklet # - it is not the next tasklet and it is not an already running tasklet frame = tasklet.frame if frame is current_frame: frame = frame.f_back if frame is not None: abs_real_path_and_base = get_abs_path_real_path_and_base_from_frame(frame) # print >>sys.stderr, "SchedCB: %r, %d, '%s', '%s'" % (tasklet, frame.f_lineno, _filename, base) if debugger.get_file_type(abs_real_path_and_base) is None: tasklet_info.update_name() if tasklet_info.frame_id is None: tasklet_info.frame_id = add_custom_frame(frame, tasklet_info.tasklet_name, tasklet.thread_id) else: update_custom_frame(tasklet_info.frame_id, frame, tasklet.thread_id, name=tasklet_info.tasklet_name) elif tasklet is next or is_running: if tasklet_info.frame_id is not None: # Remove info about stackless suspended when it starts to run. remove_custom_frame(tasklet_info.frame_id) tasklet_info.frame_id = None finally: tasklet = None tasklet_info = None frame = None except: pydev_log.exception() if _application_set_schedule_callback is not None: return _application_set_schedule_callback(prev, next)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def patch_stackless(): ''' This function should be called to patch the stackless module so that new tasklets are properly tracked in the debugger. ''' global _application_set_schedule_callback _application_set_schedule_callback = stackless.set_schedule_callback(_schedule_callback) def set_schedule_callback(callable): global _application_set_schedule_callback old = _application_set_schedule_callback _application_set_schedule_callback = callable return old def get_schedule_callback(): global _application_set_schedule_callback return _application_set_schedule_callback set_schedule_callback.__doc__ = stackless.set_schedule_callback.__doc__ if hasattr(stackless, "get_schedule_callback"): get_schedule_callback.__doc__ = stackless.get_schedule_callback.__doc__ stackless.set_schedule_callback = set_schedule_callback stackless.get_schedule_callback = get_schedule_callback if not hasattr(stackless.tasklet, "trace_function"): # Older versions of Stackless, released before 2014 __call__.__doc__ = stackless.tasklet.__call__.__doc__ stackless.tasklet.__call__ = __call__ setup.__doc__ = stackless.tasklet.setup.__doc__ stackless.tasklet.setup = setup run.__doc__ = stackless.run.__doc__ stackless.run = run
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach(self, dwProcessId): """ Attaches to an existing process for debugging. @see: L{detach}, L{execv}, L{execl} @type dwProcessId: int @param dwProcessId: Global ID of a process to attach to. @rtype: L{Process} @return: A new Process object. Normally you don't need to use it now, it's best to interact with the process from the event handler. @raise WindowsError: Raises an exception on error. Depending on the circumstances, the debugger may or may not have attached to the target process. """
# Get the Process object from the snapshot, # if missing create a new one. try: aProcess = self.system.get_process(dwProcessId) except KeyError: aProcess = Process(dwProcessId) # Warn when mixing 32 and 64 bits. # This also allows the user to stop attaching altogether, # depending on how the warnings are configured. if System.bits != aProcess.get_bits(): msg = "Mixture of 32 and 64 bits is considered experimental." \ " Use at your own risk!" warnings.warn(msg, MixedBitsWarning) # Attach to the process. win32.DebugActiveProcess(dwProcessId) # Add the new PID to the set of debugees. self.__attachedDebugees.add(dwProcessId) # Match the system kill-on-exit flag to our own. self.__setSystemKillOnExitMode() # If the Process object was not in the snapshot, add it now. if not self.system.has_process(dwProcessId): self.system._add_process(aProcess) # Scan the process threads and loaded modules. # This is prefered because the thread and library events do not # properly give some information, like the filename for each module. aProcess.scan_threads() aProcess.scan_modules() # Return the Process object, like the execv() and execl() methods. return aProcess
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __cleanup_process(self, dwProcessId, bIgnoreExceptions = False): """ Perform the necessary cleanup of a process about to be killed or detached from. This private method is called by L{kill} and L{detach}. @type dwProcessId: int @param dwProcessId: Global ID of a process to kill. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when killing the process. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
# If the process is being debugged... if self.is_debugee(dwProcessId): # Make sure a Process object exists or the following calls fail. if not self.system.has_process(dwProcessId): aProcess = Process(dwProcessId) try: aProcess.get_handle() except WindowsError: pass # fails later on with more specific reason self.system._add_process(aProcess) # Erase all breakpoints in the process. try: self.erase_process_breakpoints(dwProcessId) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Stop tracing all threads in the process. try: self.stop_tracing_process(dwProcessId) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # The process is no longer a debugee. try: if dwProcessId in self.__attachedDebugees: self.__attachedDebugees.remove(dwProcessId) if dwProcessId in self.__startedDebugees: self.__startedDebugees.remove(dwProcessId) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Clear and remove the process from the snapshot. # If the user wants to do something with it after detaching # a new Process instance should be created. try: if self.system.has_process(dwProcessId): try: self.system.get_process(dwProcessId).clear() finally: self.system._del_process(dwProcessId) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # If the last debugging event is related to this process, forget it. try: if self.lastEvent and self.lastEvent.get_pid() == dwProcessId: self.lastEvent = None except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), 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 kill(self, dwProcessId, bIgnoreExceptions = False): """ Kills a process currently being debugged. @see: L{detach} @type dwProcessId: int @param dwProcessId: Global ID of a process to kill. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when killing the process. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
# Keep a reference to the process. We'll need it later. try: aProcess = self.system.get_process(dwProcessId) except KeyError: aProcess = Process(dwProcessId) # Cleanup all data referring to the process. self.__cleanup_process(dwProcessId, bIgnoreExceptions = bIgnoreExceptions) # Kill the process. try: try: if self.is_debugee(dwProcessId): try: if aProcess.is_alive(): aProcess.suspend() finally: self.detach(dwProcessId, bIgnoreExceptions = bIgnoreExceptions) finally: aProcess.kill() except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Cleanup what remains of the process data. try: aProcess.clear() except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), 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 kill_all(self, bIgnoreExceptions = False): """ Kills from all processes currently being debugged. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when killing each process. C{False} to stop and raise an exception when encountering an error. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
for pid in self.get_debugee_pids(): self.kill(pid, bIgnoreExceptions = bIgnoreExceptions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detach(self, dwProcessId, bIgnoreExceptions = False): """ Detaches from a process currently being debugged. @note: On Windows 2000 and below the process is killed. @see: L{attach}, L{detach_from_all} @type dwProcessId: int @param dwProcessId: Global ID of a process to detach from. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when detaching. C{False} to stop and raise an exception when encountering an error. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
# Keep a reference to the process. We'll need it later. try: aProcess = self.system.get_process(dwProcessId) except KeyError: aProcess = Process(dwProcessId) # Determine if there is support for detaching. # This check should only fail on Windows 2000 and older. try: win32.DebugActiveProcessStop can_detach = True except AttributeError: can_detach = False # Continue the last event before detaching. # XXX not sure about this... try: if can_detach and self.lastEvent and \ self.lastEvent.get_pid() == dwProcessId: self.cont(self.lastEvent) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Cleanup all data referring to the process. self.__cleanup_process(dwProcessId, bIgnoreExceptions = bIgnoreExceptions) try: # Detach from the process. # On Windows 2000 and before, kill the process. if can_detach: try: win32.DebugActiveProcessStop(dwProcessId) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) else: try: aProcess.kill() except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) finally: # Cleanup what remains of the process data. aProcess.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 detach_from_all(self, bIgnoreExceptions = False): """ Detaches from all processes currently being debugged. @note: To better handle last debugging event, call L{stop} instead. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when detaching. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
for pid in self.get_debugee_pids(): self.detach(pid, bIgnoreExceptions = bIgnoreExceptions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, dwMilliseconds = None): """ Waits for the next debug event. @see: L{cont}, L{dispatch}, L{loop} @type dwMilliseconds: int @param dwMilliseconds: (Optional) Timeout in milliseconds. Use C{INFINITE} or C{None} for no timeout. @rtype: L{Event} @return: An event that occured in one of the debugees. @raise WindowsError: Raises an exception on error. If no target processes are left to debug, the error code is L{win32.ERROR_INVALID_HANDLE}. """
# Wait for the next debug event. raw = win32.WaitForDebugEvent(dwMilliseconds) event = EventFactory.get(self, raw) # Remember it. self.lastEvent = event # Return it. return event
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, event = None): """ Calls the debug event notify callbacks. @see: L{cont}, L{loop}, L{wait} @type event: L{Event} @param event: (Optional) Event object returned by L{wait}. @raise WindowsError: Raises an exception on error. """
# If no event object was given, use the last event. if event is None: event = self.lastEvent # Ignore dummy events. if not event: return # Determine the default behaviour for this event. # XXX HACK # Some undocumented flags are used, but as far as I know in those # versions of Windows that don't support them they should behave # like DGB_CONTINUE. code = event.get_event_code() if code == win32.EXCEPTION_DEBUG_EVENT: # At this point, by default some exception types are swallowed by # the debugger, because we don't know yet if it was caused by the # debugger itself or the debugged process. # # Later on (see breakpoint.py) if we determined the exception was # not caused directly by the debugger itself, we set the default # back to passing the exception to the debugee. # # The "invalid handle" exception is also swallowed by the debugger # because it's not normally generated by the debugee. But in # hostile mode we want to pass it to the debugee, as it may be the # result of an anti-debug trick. In that case it's best to disable # bad handles detection with Microsoft's gflags.exe utility. See: # http://msdn.microsoft.com/en-us/library/windows/hardware/ff549557(v=vs.85).aspx exc_code = event.get_exception_code() if exc_code in ( win32.EXCEPTION_BREAKPOINT, win32.EXCEPTION_WX86_BREAKPOINT, win32.EXCEPTION_SINGLE_STEP, win32.EXCEPTION_GUARD_PAGE, ): event.continueStatus = win32.DBG_CONTINUE elif exc_code == win32.EXCEPTION_INVALID_HANDLE: if self.__bHostileCode: event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED else: event.continueStatus = win32.DBG_CONTINUE else: event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED elif code == win32.RIP_EVENT and \ event.get_rip_type() == win32.SLE_ERROR: # RIP events that signal fatal events should kill the process. event.continueStatus = win32.DBG_TERMINATE_PROCESS else: # Other events need this continue code. # Sometimes other codes can be used and are ignored, sometimes not. # For example, when using the DBG_EXCEPTION_NOT_HANDLED code, # debug strings are sent twice (!) event.continueStatus = win32.DBG_CONTINUE # Dispatch the debug event. return EventDispatcher.dispatch(self, event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cont(self, event = None): """ Resumes execution after processing a debug event. @see: dispatch(), loop(), wait() @type event: L{Event} @param event: (Optional) Event object returned by L{wait}. @raise WindowsError: Raises an exception on error. """
# If no event object was given, use the last event. if event is None: event = self.lastEvent # Ignore dummy events. if not event: return # Get the event continue status information. dwProcessId = event.get_pid() dwThreadId = event.get_tid() dwContinueStatus = event.continueStatus # Check if the process is still being debugged. if self.is_debugee(dwProcessId): # Try to flush the instruction cache. try: if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.flush_instruction_cache() except WindowsError: pass # XXX TODO # # Try to execute the UnhandledExceptionFilter for second chance # exceptions, at least when in hostile mode (in normal mode it # would be breaking compatibility, as users may actually expect # second chance exceptions to be raised again). # # Reportedly in Windows 7 (maybe in Vista too) this seems to be # happening already. In XP and below the UnhandledExceptionFilter # was never called for processes being debugged. # Continue execution of the debugee. win32.ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus) # If the event is the last event, forget it. if event == self.lastEvent: self.lastEvent = 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 stop(self, bIgnoreExceptions = True): """ Stops debugging all processes. If the kill on exit mode is on, debugged processes are killed when the debugger is stopped. Otherwise when the debugger stops it detaches from all debugged processes and leaves them running (default). For more details see: L{__init__} @note: This method is better than L{detach_from_all} because it can gracefully handle the last debugging event before detaching. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when detaching. """
# Determine if we have a last debug event that we need to continue. try: event = self.lastEvent has_event = bool(event) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) has_event = False # If we do... if has_event: # Disable all breakpoints in the process before resuming execution. try: pid = event.get_pid() self.disable_process_breakpoints(pid) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Disable all breakpoints in the thread before resuming execution. try: tid = event.get_tid() self.disable_thread_breakpoints(tid) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Resume execution. try: event.continueDebugEvent = win32.DBG_CONTINUE self.cont(event) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Detach from or kill all debuggees. try: if self.__bKillOnExit: self.kill_all(bIgnoreExceptions) else: self.detach_from_all(bIgnoreExceptions) except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Cleanup the process snapshots. try: self.system.clear() except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) # Close all Win32 handles the Python garbage collector failed to close. self.force_garbage_collection(bIgnoreExceptions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ Handles the next debug event. @see: L{cont}, L{dispatch}, L{wait}, L{stop} @raise WindowsError: Raises an exception on error. If the wait operation causes an error, debugging is stopped (meaning all debugees are either killed or detached from). If the event dispatching causes an error, the event is still continued before returning. This may happen, for example, if the event handler raises an exception nobody catches. """
try: event = self.wait() except Exception: self.stop() raise try: self.dispatch() finally: self.cont()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interactive(self, bConfirmQuit = True, bShowBanner = True): """ Start an interactive debugging session. @type bConfirmQuit: bool @param bConfirmQuit: Set to C{True} to ask the user for confirmation before closing the session, C{False} otherwise. @type bShowBanner: bool @param bShowBanner: Set to C{True} to show a banner before entering the session and after leaving it, C{False} otherwise. @warn: This will temporarily disable the user-defined event handler! This method returns when the user closes the session. """
print('') print("-" * 79) print("Interactive debugging session started.") print("Use the \"help\" command to list all available commands.") print("Use the \"quit\" command to close this session.") print("-" * 79) if self.lastEvent is None: print('') console = ConsoleDebugger() console.confirm_quit = bConfirmQuit console.load_history() try: console.start_using_debugger(self) console.loop() finally: console.stop_using_debugger() console.save_history() print('') print("-" * 79) print("Interactive debugging session closed.") print("-" * 79) print('')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_garbage_collection(bIgnoreExceptions = True): """ Close all Win32 handles the Python garbage collector failed to close. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when detaching. """
try: import gc gc.collect() bRecollect = False for obj in list(gc.garbage): try: if isinstance(obj, win32.Handle): obj.close() elif isinstance(obj, Event): obj.debug = None elif isinstance(obj, Process): obj.clear() elif isinstance(obj, Thread): obj.set_process(None) obj.clear() elif isinstance(obj, Module): obj.set_process(None) elif isinstance(obj, Window): obj.set_process(None) else: continue gc.garbage.remove(obj) del obj bRecollect = True except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), RuntimeWarning) if bRecollect: gc.collect() except Exception: if not bIgnoreExceptions: raise e = sys.exc_info()[1] warnings.warn(str(e), 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 _notify_load_dll(self, event): """ Notify the load of a new module. @warning: This method is meant to be used internally by the debugger. @type event: L{LoadDLLEvent} @param event: Load DLL event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
# Pass the event to the breakpoint container. bCallHandler = _BreakpointContainer._notify_load_dll(self, event) # Get the process where the DLL was loaded. aProcess = event.get_process() # Pass the event to the process. bCallHandler = aProcess._notify_load_dll(event) and bCallHandler # Anti-anti-debugging tricks on ntdll.dll. if self.__bHostileCode: aModule = event.get_module() if aModule.match_name('ntdll.dll'): # Since we've overwritten the PEB to hide # ourselves, we no longer have the system # breakpoint when attaching to the process. # Set a breakpoint at ntdll!DbgUiRemoteBreakin # instead (that's where the debug API spawns # it's auxiliary threads). This also defeats # a simple anti-debugging trick: the hostile # process could have overwritten the int3 # instruction at the system breakpoint. self.break_at(aProcess.get_pid(), aProcess.resolve_label('ntdll!DbgUiRemoteBreakin')) return bCallHandler
<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 unload of a module. @warning: This method is meant to be used internally by the debugger. @type event: L{UnloadDLLEvent} @param event: Unload DLL event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
bCallHandler1 = _BreakpointContainer._notify_unload_dll(self, event) bCallHandler2 = event.get_process()._notify_unload_dll(event) return bCallHandler1 and bCallHandler2
<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_debug_control_c(self, event): """ Notify of a Debug Ctrl-C exception. @warning: This method is meant to be used internally by the debugger. @note: This exception is only raised when a debugger is attached, and applications are not supposed to handle it, so we need to handle it ourselves or the application may crash. @see: U{http://msdn.microsoft.com/en-us/library/aa363082(VS.85).aspx} @type event: L{ExceptionEvent} @param event: Debug Ctrl-C exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
if event.is_first_chance(): event.continueStatus = win32.DBG_EXCEPTION_HANDLED 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 _notify_ms_vc_exception(self, event): """ Notify of a Microsoft Visual C exception. @warning: This method is meant to be used internally by the debugger. @note: This allows the debugger to understand the Microsoft Visual C thread naming convention. @see: U{http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx} @type event: L{ExceptionEvent} @param event: Microsoft Visual C exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
dwType = event.get_exception_information(0) if dwType == 0x1000: pszName = event.get_exception_information(1) dwThreadId = event.get_exception_information(2) dwFlags = event.get_exception_information(3) aProcess = event.get_process() szName = aProcess.peek_string(pszName, fUnicode = False) if szName: if dwThreadId == -1: dwThreadId = event.get_tid() if aProcess.has_thread(dwThreadId): aThread = aProcess.get_thread(dwThreadId) else: aThread = Thread(dwThreadId) aProcess._add_thread(aThread) ## if aThread.get_name() is None: ## aThread.set_name(szName) aThread.set_name(szName) 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 _newer(a, b): """Inquire whether file a was written since file b."""
if not os.path.exists(a): return False if not os.path.exists(b): return True return os.path.getmtime(a) >= os.path.getmtime(b)
<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_tokens(self, tokens, debug=False): """Parse a series of tokens and return the syntax tree."""
# XXX Move the prefix computation into a wrapper around tokenize. p = parse.Parser(self.grammar, self.convert) p.setup() lineno = 1 column = 0 type = value = start = end = line_text = None prefix = u"" for quintuple in tokens: type, value, start, end, line_text = quintuple if start != (lineno, column): assert (lineno, column) <= start, ((lineno, column), start) s_lineno, s_column = start if lineno < s_lineno: prefix += "\n" * (s_lineno - lineno) lineno = s_lineno column = 0 if column < s_column: prefix += line_text[column:s_column] column = s_column if type in (tokenize.COMMENT, tokenize.NL): prefix += value lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 continue if type == token.OP: type = grammar.opmap[value] if debug: self.logger.debug("%s %r (prefix=%r)", token.tok_name[type], value, prefix) if p.addtoken(type, value, (prefix, start)): if debug: self.logger.debug("Stop.") break prefix = "" lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 else: # We never broke out -- EOF is too soon (how can this happen???) raise parse.ParseError("incomplete input", type, value, (prefix, start)) return p.rootnode
<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_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug)
<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_file(self, filename, encoding=None, debug=False): """Parse a file and return the syntax tree."""
stream = codecs.open(filename, "r", encoding) try: return self.parse_stream(stream, debug) finally: stream.close()
<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_string(self, text, debug=False): """Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(StringIO.StringIO(text).readline) return self.parse_tokens(tokens, debug)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dump_threads(stream=None): ''' Helper to dump thread info. ''' if stream is None: stream = sys.stderr thread_id_to_name = {} try: for t in threading.enumerate(): thread_id_to_name[t.ident] = '%s (daemon: %s, pydevd thread: %s)' % ( t.name, t.daemon, getattr(t, 'is_pydev_daemon_thread', False)) except: pass from _pydevd_bundle.pydevd_additional_thread_info_regular import _current_frames stream.write('===============================================================================\n') stream.write('Threads running\n') stream.write('================================= Thread Dump =================================\n') stream.flush() for thread_id, stack in _current_frames().items(): stream.write('\n-------------------------------------------------------------------------------\n') stream.write(" Thread %s" % thread_id_to_name.get(thread_id, thread_id)) stream.write('\n\n') for i, (filename, lineno, name, line) in enumerate(traceback.extract_stack(stack)): stream.write(' File "%s", line %d, in %s\n' % (filename, lineno, name)) if line: stream.write(" %s\n" % (line.strip())) if i == 0 and 'self' in stack.f_locals: stream.write(' self: ') try: stream.write(str(stack.f_locals['self'])) except: stream.write('Unable to get str of: %s' % (type(stack.f_locals['self']),)) stream.write('\n') stream.flush() stream.write('\n=============================== END Thread Dump ===============================') stream.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_debug_privileges(cls, bIgnoreExceptions = False): """ Requests debug privileges. This may be needed to debug processes running as SYSTEM (such as services) since Windows XP. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when requesting debug privileges. @rtype: bool @return: C{True} on success, C{False} on failure. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
try: cls.request_privileges(win32.SE_DEBUG_NAME) return True except Exception: if not bIgnoreExceptions: raise 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 drop_debug_privileges(cls, bIgnoreExceptions = False): """ Drops debug privileges. This may be needed to avoid being detected by certain anti-debug tricks. @type bIgnoreExceptions: bool @param bIgnoreExceptions: C{True} to ignore any exceptions that may be raised when dropping debug privileges. @rtype: bool @return: C{True} on success, C{False} on failure. @raise WindowsError: Raises an exception on error, unless C{bIgnoreExceptions} is C{True}. """
try: cls.drop_privileges(win32.SE_DEBUG_NAME) return True except Exception: if not bIgnoreExceptions: raise 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 adjust_privileges(state, privileges): """ Requests or drops privileges. @type state: bool @param state: C{True} to request, C{False} to drop. @type privileges: list(int) @param privileges: Privileges to request or drop. @raise WindowsError: Raises an exception on error. """
with win32.OpenProcessToken(win32.GetCurrentProcess(), win32.TOKEN_ADJUST_PRIVILEGES) as hToken: NewState = ( (priv, state) for priv in privileges ) win32.AdjustTokenPrivileges(hToken, NewState)
<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_file_version_info(cls, filename): """ Get the program version from an executable file, if available. @type filename: str @param filename: Pathname to the executable file to query. @rtype: tuple(str, str, bool, bool, str, str) @return: Tuple with version information extracted from the executable file metadata, containing the following: - File version number (C{"major.minor"}). - Product version number (C{"major.minor"}). - C{True} for debug builds, C{False} for production builds. - C{True} for legacy OS builds (DOS, OS/2, Win16), C{False} for modern OS builds. - Binary file type. May be one of the following values: - "application" - "dynamic link library" - "static link library" - "font" - "raster font" - "TrueType font" - "vector font" - "driver" - "communications driver" - "display driver" - "installable driver" - "keyboard driver" - "language driver" - "legacy driver" - "mouse driver" - "network driver" - "printer driver" - "sound driver" - "system driver" - "versioned printer driver" - Binary creation timestamp. Any of the fields may be C{None} if not available. @raise WindowsError: Raises an exception on error. """
# Get the file version info structure. pBlock = win32.GetFileVersionInfo(filename) pBuffer, dwLen = win32.VerQueryValue(pBlock, "\\") if dwLen != ctypes.sizeof(win32.VS_FIXEDFILEINFO): raise ctypes.WinError(win32.ERROR_BAD_LENGTH) pVersionInfo = ctypes.cast(pBuffer, ctypes.POINTER(win32.VS_FIXEDFILEINFO)) VersionInfo = pVersionInfo.contents if VersionInfo.dwSignature != 0xFEEF04BD: raise ctypes.WinError(win32.ERROR_BAD_ARGUMENTS) # File and product versions. FileVersion = "%d.%d" % (VersionInfo.dwFileVersionMS, VersionInfo.dwFileVersionLS) ProductVersion = "%d.%d" % (VersionInfo.dwProductVersionMS, VersionInfo.dwProductVersionLS) # Debug build? if VersionInfo.dwFileFlagsMask & win32.VS_FF_DEBUG: DebugBuild = (VersionInfo.dwFileFlags & win32.VS_FF_DEBUG) != 0 else: DebugBuild = None # Legacy OS build? LegacyBuild = (VersionInfo.dwFileOS != win32.VOS_NT_WINDOWS32) # File type. FileType = cls.__binary_types.get(VersionInfo.dwFileType) if VersionInfo.dwFileType == win32.VFT_DRV: FileType = cls.__driver_types.get(VersionInfo.dwFileSubtype) elif VersionInfo.dwFileType == win32.VFT_FONT: FileType = cls.__font_types.get(VersionInfo.dwFileSubtype) # Timestamp, ex: "Monday, July 7, 2013 (12:20:50.126)". # FIXME: how do we know the time zone? FileDate = (VersionInfo.dwFileDateMS << 32) + VersionInfo.dwFileDateLS if FileDate: CreationTime = win32.FileTimeToSystemTime(FileDate) CreationTimestamp = "%s, %s %d, %d (%d:%d:%d.%d)" % ( cls.__days_of_the_week[CreationTime.wDayOfWeek], cls.__months[CreationTime.wMonth], CreationTime.wDay, CreationTime.wYear, CreationTime.wHour, CreationTime.wMinute, CreationTime.wSecond, CreationTime.wMilliseconds, ) else: CreationTimestamp = None # Return the file version info. return ( FileVersion, ProductVersion, DebugBuild, LegacyBuild, FileType, CreationTimestamp, )
<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_kill_on_exit_mode(bKillOnExit = False): """ Defines the behavior of the debugged processes when the debugging thread dies. This method only affects the calling thread. Works on the following platforms: - Microsoft Windows XP and above. - Wine (Windows Emulator). Fails on the following platforms: - Microsoft Windows 2000 and below. - ReactOS. @type bKillOnExit: bool @param bKillOnExit: C{True} to automatically kill processes when the debugger thread dies. C{False} to automatically detach from processes when the debugger thread dies. @rtype: bool @return: C{True} on success, C{False} on error. @note: This call will fail if a debug port was not created. That is, if the debugger isn't attached to at least one process. For more info see: U{http://msdn.microsoft.com/en-us/library/ms679307.aspx} """
try: # won't work before calling CreateProcess or DebugActiveProcess win32.DebugSetProcessKillOnExit(bKillOnExit) except (AttributeError, WindowsError): return False 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 enable_step_on_branch_mode(cls): """ When tracing, call this on every single step event for step on branch mode. @raise WindowsError: Raises C{ERROR_DEBUGGER_INACTIVE} if the debugger is not attached to least one process. @raise NotImplementedError: Current architecture is not C{i386} or C{amd64}. @warning: This method uses the processor's machine specific registers (MSR). It could potentially brick your machine. It works on my machine, but your mileage may vary. @note: It doesn't seem to work in VMWare or VirtualBox machines. Maybe it fails in other virtualization/emulation environments, no extensive testing was made so far. """
cls.write_msr(DebugRegister.DebugCtlMSR, DebugRegister.BranchTrapFlag | DebugRegister.LastBranchRecord)
<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_last_branch_location(cls): """ Returns the source and destination addresses of the last taken branch. @rtype: tuple( int, int ) @return: Source and destination addresses of the last taken branch. @raise WindowsError: Raises an exception on error. @raise NotImplementedError: Current architecture is not C{i386} or C{amd64}. @warning: This method uses the processor's machine specific registers (MSR). It could potentially brick your machine. It works on my machine, but your mileage may vary. @note: It doesn't seem to work in VMWare or VirtualBox machines. Maybe it fails in other virtualization/emulation environments, no extensive testing was made so far. """
LastBranchFromIP = cls.read_msr(DebugRegister.LastBranchFromIP) LastBranchToIP = cls.read_msr(DebugRegister.LastBranchToIP) return ( LastBranchFromIP, LastBranchToIP )
<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_postmortem_debugger(cls, bits = None): """ Returns the postmortem debugging settings from the Registry. @see: L{set_postmortem_debugger} @type bits: int @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the 64 bits debugger. Set to {None} for the default (L{System.bits}. @rtype: tuple( str, bool, int ) @return: A tuple containing the command line string to the postmortem debugger, a boolean specifying if user interaction is allowed before attaching, and an integer specifying a user defined hotkey. Any member of the tuple may be C{None}. See L{set_postmortem_debugger} for more details. @raise WindowsError: Raises an exception on error. """
if bits is None: bits = cls.bits elif bits not in (32, 64): raise NotImplementedError("Unknown architecture (%r bits)" % bits) if bits == 32 and cls.bits == 64: keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' else: keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' key = cls.registry[keyname] debugger = key.get('Debugger') auto = key.get('Auto') hotkey = key.get('UserDebuggerHotkey') if auto is not None: auto = bool(auto) return (debugger, auto, hotkey)
<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_postmortem_exclusion_list(cls, bits = None): """ Returns the exclusion list for the postmortem debugger. @see: L{get_postmortem_debugger} @type bits: int @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the 64 bits debugger. Set to {None} for the default (L{System.bits}). @rtype: list( str ) @return: List of excluded application filenames. @raise WindowsError: Raises an exception on error. """
if bits is None: bits = cls.bits elif bits not in (32, 64): raise NotImplementedError("Unknown architecture (%r bits)" % bits) if bits == 32 and cls.bits == 64: keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' else: keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' try: key = cls.registry[keyname] except KeyError: return [] return [name for (name, enabled) in key.items() if enabled]
<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_postmortem_debugger(cls, cmdline, auto = None, hotkey = None, bits = None): """ Sets the postmortem debugging settings in the Registry. @warning: This method requires administrative rights. @see: L{get_postmortem_debugger} @type cmdline: str @param cmdline: Command line to the new postmortem debugger. When the debugger is invoked, the first "%ld" is replaced with the process ID and the second "%ld" is replaced with the event handle. Don't forget to enclose the program filename in double quotes if the path contains spaces. @type auto: bool @param auto: Set to C{True} if no user interaction is allowed, C{False} to prompt a confirmation dialog before attaching. Use C{None} to leave this value unchanged. @type hotkey: int @param hotkey: Virtual key scan code for the user defined hotkey. Use C{0} to disable the hotkey. Use C{None} to leave this value unchanged. @type bits: int @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the 64 bits debugger. Set to {None} for the default (L{System.bits}). @rtype: tuple( str, bool, int ) @return: Previously defined command line and auto flag. @raise WindowsError: Raises an exception on error. """
if bits is None: bits = cls.bits elif bits not in (32, 64): raise NotImplementedError("Unknown architecture (%r bits)" % bits) if bits == 32 and cls.bits == 64: keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' else: keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' key = cls.registry[keyname] if cmdline is not None: key['Debugger'] = cmdline if auto is not None: key['Auto'] = int(bool(auto)) if hotkey is not None: key['UserDebuggerHotkey'] = int(hotkey)
<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_to_postmortem_exclusion_list(cls, pathname, bits = None): """ Adds the given filename to the exclusion list for postmortem debugging. @warning: This method requires administrative rights. @see: L{get_postmortem_exclusion_list} @type pathname: str @param pathname: Application pathname to exclude from postmortem debugging. @type bits: int @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the 64 bits debugger. Set to {None} for the default (L{System.bits}). @raise WindowsError: Raises an exception on error. """
if bits is None: bits = cls.bits elif bits not in (32, 64): raise NotImplementedError("Unknown architecture (%r bits)" % bits) if bits == 32 and cls.bits == 64: keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' else: keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' try: key = cls.registry[keyname] except KeyError: key = cls.registry.create(keyname) key[pathname] = 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 remove_from_postmortem_exclusion_list(cls, pathname, bits = None): """ Removes the given filename to the exclusion list for postmortem debugging from the Registry. @warning: This method requires administrative rights. @warning: Don't ever delete entries you haven't created yourself! Some entries are set by default for your version of Windows. Deleting them might deadlock your system under some circumstances. For more details see: U{http://msdn.microsoft.com/en-us/library/bb204634(v=vs.85).aspx} @see: L{get_postmortem_exclusion_list} @type pathname: str @param pathname: Application pathname to remove from the postmortem debugging exclusion list. @type bits: int @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the 64 bits debugger. Set to {None} for the default (L{System.bits}). @raise WindowsError: Raises an exception on error. """
if bits is None: bits = cls.bits elif bits not in (32, 64): raise NotImplementedError("Unknown architecture (%r bits)" % bits) if bits == 32 and cls.bits == 64: keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' else: keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' try: key = cls.registry[keyname] except KeyError: return try: del key[pathname] except KeyError: 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 get_services(): """ Retrieve a list of all system services. @see: L{get_active_services}, L{start_service}, L{stop_service}, L{pause_service}, L{resume_service} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors. """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager: try: return win32.EnumServicesStatusEx(hSCManager) except AttributeError: return win32.EnumServicesStatus(hSCManager)
<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_active_services(): """ Retrieve a list of all active system services. @see: L{get_services}, L{start_service}, L{stop_service}, L{pause_service}, L{resume_service} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors. """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager: return [ entry for entry in win32.EnumServicesStatusEx(hSCManager, dwServiceType = win32.SERVICE_WIN32, dwServiceState = win32.SERVICE_ACTIVE) \ if entry.ProcessId ]
<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_service(name): """ Get the service descriptor for the given service name. @see: L{start_service}, L{stop_service}, L{pause_service}, L{resume_service} @type name: str @param name: Service unique name. You can get this value from the C{ServiceName} member of the service descriptors returned by L{get_services} or L{get_active_services}. @rtype: L{win32.ServiceStatusProcess} @return: Service status descriptor. """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager: with win32.OpenService(hSCManager, name, dwDesiredAccess = win32.SERVICE_QUERY_STATUS ) as hService: try: return win32.QueryServiceStatusEx(hService) except AttributeError: return win32.QueryServiceStatus(hService)
<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_service_display_name(name): """ Get the service display name for the given service name. @see: L{get_service} @type name: str @param name: Service unique name. You can get this value from the C{ServiceName} member of the service descriptors returned by L{get_services} or L{get_active_services}. @rtype: str @return: Service display name. """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager: return win32.GetServiceDisplayName(hSCManager, name)
<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_service_from_display_name(displayName): """ Get the service unique name given its display name. @see: L{get_service} @type displayName: str @param displayName: Service display name. You can get this value from the C{DisplayName} member of the service descriptors returned by L{get_services} or L{get_active_services}. @rtype: str @return: Service unique name. """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager: return win32.GetServiceKeyName(hSCManager, displayName)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_service(name, argv = None): """ Start the service given by name. @warn: This method requires UAC elevation in Windows Vista and above. @see: L{stop_service}, L{pause_service}, L{resume_service} @type name: str @param name: Service unique name. You can get this value from the C{ServiceName} member of the service descriptors returned by L{get_services} or L{get_active_services}. """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_CONNECT ) as hSCManager: with win32.OpenService(hSCManager, name, dwDesiredAccess = win32.SERVICE_START ) as hService: win32.StartService(hService)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_service(name): """ Stop the service given by name. @warn: This method requires UAC elevation in Windows Vista and above. @see: L{get_services}, L{get_active_services}, L{start_service}, L{pause_service}, L{resume_service} """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_CONNECT ) as hSCManager: with win32.OpenService(hSCManager, name, dwDesiredAccess = win32.SERVICE_STOP ) as hService: win32.ControlService(hService, win32.SERVICE_CONTROL_STOP)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause_service(name): """ Pause the service given by name. @warn: This method requires UAC elevation in Windows Vista and above. @note: Not all services support this. @see: L{get_services}, L{get_active_services}, L{start_service}, L{stop_service}, L{resume_service} """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_CONNECT ) as hSCManager: with win32.OpenService(hSCManager, name, dwDesiredAccess = win32.SERVICE_PAUSE_CONTINUE ) as hService: win32.ControlService(hService, win32.SERVICE_CONTROL_PAUSE)
<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_service(name): """ Resume the service given by name. @warn: This method requires UAC elevation in Windows Vista and above. @note: Not all services support this. @see: L{get_services}, L{get_active_services}, L{start_service}, L{stop_service}, L{pause_service} """
with win32.OpenSCManager( dwDesiredAccess = win32.SC_MANAGER_CONNECT ) as hSCManager: with win32.OpenService(hSCManager, name, dwDesiredAccess = win32.SERVICE_PAUSE_CONTINUE ) as hService: win32.ControlService(hService, win32.SERVICE_CONTROL_CONTINUE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ifconfig_getnode(): """Get the hardware address on Unix by running ifconfig."""
# This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes. for args in ('', '-a', '-av'): mac = _find_mac('ifconfig', args, ['hwaddr', 'ether'], lambda i: i+1) if mac: return mac import socket ip_addr = socket.gethostbyname(socket.gethostname()) # Try getting the MAC addr from arp based on our IP address (Solaris). mac = _find_mac('arp', '-an', [ip_addr], lambda i: -1) if mac: return mac # This might work on HP-UX. mac = _find_mac('lanscan', '-ai', ['lan0'], lambda i: 0) if mac: return mac 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 _ipconfig_getnode(): """Get the hardware address on Windows by running ipconfig.exe."""
import os, re dirs = ['', r'c:\windows\system32', r'c:\winnt\system32'] try: import ctypes buffer = ctypes.create_string_buffer(300) ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300) # @UndefinedVariable dirs.insert(0, buffer.value.decode('mbcs')) except: pass for dir in dirs: try: pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all') except IOError: continue for line in pipe: value = line.split(':')[-1].strip().lower() if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value): return int(value.replace('-', ''), 16)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getnode(): """Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with its eighth bit set to 1 as recommended in RFC 4122. """
global _node if _node is not None: return _node import sys if sys.platform == 'win32': getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode] else: getters = [_unixdll_getnode, _ifconfig_getnode] for getter in getters + [_random_getnode]: try: _node = getter() except: continue if _node is not None: return _node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uuid3(namespace, name): """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
import md5 hash = md5.md5(namespace.bytes + name).digest() return UUID(bytes=hash[:16], version=3)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def default_should_trace_hook(frame, filename): ''' Return True if this frame should be traced, False if tracing should be blocked. ''' # First, check whether this code object has a cached value ignored_lines = _filename_to_ignored_lines.get(filename) if ignored_lines is None: # Now, look up that line of code and check for a @DontTrace # preceding or on the same line as the method. # E.g.: # #@DontTrace # def test(): # pass # ... or ... # def test(): #@DontTrace # pass ignored_lines = {} lines = linecache.getlines(filename) for i_line, line in enumerate(lines): j = line.find('#') if j >= 0: comment = line[j:] if DONT_TRACE_TAG in comment: ignored_lines[i_line] = 1 #Note: when it's found in the comment, mark it up and down for the decorator lines found. k = i_line - 1 while k >= 0: if RE_DECORATOR.match(lines[k]): ignored_lines[k] = 1 k -= 1 else: break k = i_line + 1 while k <= len(lines): if RE_DECORATOR.match(lines[k]): ignored_lines[k] = 1 k += 1 else: break _filename_to_ignored_lines[filename] = ignored_lines func_line = frame.f_code.co_firstlineno - 1 # co_firstlineno is 1-based, so -1 is needed return not ( func_line - 1 in ignored_lines or #-1 to get line before method func_line in ignored_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 clear_trace_filter_cache(): ''' Clear the trace filter cache. Call this after reloading. ''' global should_trace_hook try: # Need to temporarily disable a hook because otherwise # _filename_to_ignored_lines.clear() will never complete. old_hook = should_trace_hook should_trace_hook = None # Clear the linecache linecache.clearcache() _filename_to_ignored_lines.clear() finally: should_trace_hook = old_hook
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def trace_filter(mode): ''' Set the trace filter mode. mode: Whether to enable the trace hook. True: Trace filtering on (skipping methods tagged @DontTrace) False: Trace filtering off (trace methods tagged @DontTrace) None/default: Toggle trace filtering. ''' global should_trace_hook if mode is None: mode = should_trace_hook is None if mode: should_trace_hook = default_should_trace_hook else: should_trace_hook = None return mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do(self, arg): ".symfix - Set the default Microsoft Symbol Store settings if missing" self.debug.system.fix_symbol_store_path(remote = True, force = 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 dump(self, filename): """Dump the grammar tables to a pickle file."""
f = open(filename, "wb") pickle.dump(self.__dict__, f, 2) f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, filename): """Load the grammar tables from a pickle file."""
f = open(filename, "rb") d = pickle.load(f) f.close() self.__dict__.update(d)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Copy the grammar. """
new = self.__class__() for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords", "tokens", "symbol2label"): setattr(new, dict_attr, getattr(self, dict_attr).copy()) new.labels = self.labels[:] new.states = self.states[:] new.start = self.start return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report(self): """Dump the grammar tables to standard output, for debugging."""
from pprint import pprint print "s2n" pprint(self.symbol2number) print "n2s" pprint(self.number2symbol) print "states" pprint(self.states) print "dfas" pprint(self.dfas) print "labels" pprint(self.labels) print "start", self.start
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dyld_image_suffix_search(iterator, env=None): """For a potential path iterator, add DYLD_IMAGE_SUFFIX semantics"""
suffix = dyld_image_suffix(env) if suffix is None: return iterator def _inject(iterator=iterator, suffix=suffix): for path in iterator: if path.endswith('.dylib'): yield path[:-len('.dylib')] + suffix + '.dylib' else: yield path + suffix yield path return _inject()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traverse_imports(names): """ Walks over all the names imported in a dotted_as_names node. """
pending = [names] while pending: node = pending.pop() if node.type == token.NAME: yield node.value elif node.type == syms.dotted_name: yield "".join([ch.value for ch in node.children]) elif node.type == syms.dotted_as_name: pending.append(node.children[0]) elif node.type == syms.dotted_as_names: pending.extend(node.children[::-2]) else: raise AssertionError("unkown node type")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unmodified_isinstance(*bases): """When called in the form MyOverrideClass(unmodified_isinstance(BuiltInClass)) it allows calls against passed in built in instances to pass even if there not a subclass """
class UnmodifiedIsInstance(type): if sys.version_info[0] == 2 and sys.version_info[1] <= 6: @classmethod def __instancecheck__(cls, instance): if cls.__name__ in (str(base.__name__) for base in bases): return isinstance(instance, bases) subclass = getattr(instance, '__class__', None) subtype = type(instance) instance_type = getattr(abc, '_InstanceType', None) if not instance_type: class test_object: pass instance_type = type(test_object) if subtype is instance_type: subtype = subclass if subtype is subclass or subclass is None: return cls.__subclasscheck__(subtype) return (cls.__subclasscheck__(subclass) or cls.__subclasscheck__(subtype)) else: @classmethod def __instancecheck__(cls, instance): if cls.__name__ in (str(base.__name__) for base in bases): return isinstance(instance, bases) return type.__instancecheck__(cls, instance) return with_metaclass(UnmodifiedIsInstance, *bases)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do(self, arg): ".exchain - Show the SEH chain" thread = self.get_thread_from_prefix() print "Exception handlers for thread %d" % thread.get_tid() print table = Table() table.addRow("Block", "Function") bits = thread.get_bits() for (seh, seh_func) in thread.get_seh_chain(): if seh is not None: seh = HexDump.address(seh, bits) if seh_func is not None: seh_func = HexDump.address(seh_func, bits) table.addRow(seh, seh_func) print table.getOutput()
<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_debug_options(opts): """Debug options are semicolon separated key=value pairs WAIT_ON_ABNORMAL_EXIT=True|False WAIT_ON_NORMAL_EXIT=True|False REDIRECT_OUTPUT=True|False VERSION=string INTERPRETER_OPTIONS=string WEB_BROWSER_URL=string url DJANGO_DEBUG=True|False CLIENT_OS_TYPE=WINDOWS|UNIX DEBUG_STDLIB=True|False """
options = {} if not opts: return options for opt in opts.split(';'): try: key, value = opt.split('=') except ValueError: continue try: options[key] = DEBUG_OPTIONS_PARSER[key](value) except KeyError: continue return options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_varchar_mysql(element, compiler, **kw): """MySQL hack to avoid the "VARCHAR requires a length" error."""
if not element.length or element.length == 'max': return "TEXT" else: return compiler.visit_VARCHAR(element, **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Transactional(fn, self, *argv, **argd): """ Decorator that wraps DAO methods to handle transactions automatically. It may only work with subclasses of L{BaseDAO}. """
return self._transactional(fn, *argv, **argd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(dbapi_connection, connection_record): """ Called once by SQLAlchemy for each new SQLite DB-API connection. Here is where we issue some PRAGMA statements to configure how we're going to access the SQLite database. @param dbapi_connection: A newly connected raw SQLite DB-API connection. @param connection_record: Unused by this method. """
try: cursor = dbapi_connection.cursor() try: cursor.execute("PRAGMA foreign_keys = ON;") cursor.execute("PRAGMA foreign_keys;") if cursor.fetchone()[0] != 1: raise Exception() finally: cursor.close() except Exception: dbapi_connection.close() raise sqlite3.Error()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transactional(self, method, *argv, **argd): """ Begins a transaction and calls the given DAO method. If the method executes successfully the transaction is commited. If the method fails, the transaction is rolled back. @type method: callable @param method: Bound method of this class or one of its subclasses. The first argument will always be C{self}. @return: The return value of the method call. @raise Exception: Any exception raised by the method. """
self._session.begin(subtransactions = True) try: result = method(self, *argv, **argd) self._session.commit() return result except: self._session.rollback() 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 add(self, crash, allow_duplicates = True): """ Add a new crash dump to the database, optionally filtering them by signature to avoid duplicates. @type crash: L{Crash} @param crash: Crash object. @type allow_duplicates: bool @param allow_duplicates: (Optional) C{True} to always add the new crash dump. C{False} to only add the crash dump if no other crash with the same signature is found in the database. Sometimes, your fuzzer turns out to be I{too} good. Then you find youself browsing through gigabytes of crash dumps, only to find a handful of actual bugs in them. This simple heuristic filter saves you the trouble by discarding crashes that seem to be similar to another one you've already found. """
# Filter out duplicated crashes, if requested. if not allow_duplicates: signature = pickle.dumps(crash.signature, protocol = 0) if self._session.query(CrashDTO.id) \ .filter_by(signature = signature) \ .count() > 0: return # Fill out a new row for the crashes table. crash_id = self.__add_crash(crash) # Fill out new rows for the memory dump. self.__add_memory(crash_id, crash.memoryMap) # On success set the row ID for the Crash object. # WARNING: In nested calls, make sure to delete # this property before a session rollback! crash._rowid = crash_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_example(self, crash, offset = None, limit = None): """ Find all crash dumps that have common properties with the crash dump provided. Results can be paged to avoid consuming too much memory if the database is large. @see: L{find} @type crash: L{Crash} @param crash: Crash object to compare with. Fields set to C{None} are ignored, all other fields but the signature are used in the comparison. To search for signature instead use the L{find} method. @type offset: int @param offset: (Optional) Skip the first I{offset} results. @type limit: int @param limit: (Optional) Return at most I{limit} results. @rtype: list(L{Crash}) @return: List of similar crash dumps found. """
# Validate the parameters. if limit is not None and not limit: warnings.warn("CrashDAO.find_by_example() was set a limit of 0" " results, returning without executing a query.") return [] # Build the query. query = self._session.query(CrashDTO) # Order by row ID to get consistent results. # Also some database engines require ordering when using offsets. query = query.asc(CrashDTO.id) # Build a CrashDTO from the Crash object. dto = CrashDTO(crash) # Filter all the fields in the crashes table that are present in the # CrashDTO object and not set to None, except for the row ID. for name, column in compat.iteritems(CrashDTO.__dict__): if not name.startswith('__') and name not in ('id', 'signature', 'data'): if isinstance(column, Column): value = getattr(dto, name, None) if value is not None: query = query.filter(column == value) # Page the query. if offset: query = query.offset(offset) if limit: query = query.limit(limit) # Execute the SQL query and convert the results. try: return [dto.toCrash() for dto in query.all()] except NoResultFound: 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 count(self, signature = None): """ Counts how many crash dumps have been stored in this database. Optionally filters the count by heuristic signature. @type signature: object @param signature: (Optional) Count only the crashes that match this signature. See L{Crash.signature} for more details. @rtype: int @return: Count of crash dumps stored in this database. """
query = self._session.query(CrashDTO.id) if signature: sig_pickled = pickle.dumps(signature, protocol = 0) query = query.filter_by(signature = sig_pickled) return query.count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, crash): """ Remove the given crash dump from the database. @type crash: L{Crash} @param crash: Crash dump to remove. """
query = self._session.query(CrashDTO).filter_by(id = crash._rowid) query.delete(synchronize_session = False) del crash._rowid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _repr(self, obj, level): '''Returns an iterable of the parts in the final repr string.''' try: obj_repr = type(obj).__repr__ except Exception: obj_repr = None def has_obj_repr(t): r = t.__repr__ try: return obj_repr == r except Exception: return obj_repr is r for t, prefix, suffix, comma in self.collection_types: if isinstance(obj, t) and has_obj_repr(t): return self._repr_iter(obj, level, prefix, suffix, comma) for t, prefix, suffix, item_prefix, item_sep, item_suffix in self.dict_types: # noqa if isinstance(obj, t) and has_obj_repr(t): return self._repr_dict(obj, level, prefix, suffix, item_prefix, item_sep, item_suffix) for t in self.string_types: if isinstance(obj, t) and has_obj_repr(t): return self._repr_str(obj, level) if self._is_long_iter(obj): return self._repr_long_iter(obj) return self._repr_other(obj, level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def leaf_to_root(self): """Internal method. Returns a characteristic path of the pattern tree. This method must be run for all leaves until the linear subpatterns are merged into a single"""
node = self subp = [] while node: if node.type == TYPE_ALTERNATIVES: node.alternatives.append(subp) if len(node.alternatives) == len(node.children): #last alternative subp = [tuple(node.alternatives)] node.alternatives = [] node = node.parent continue else: node = node.parent subp = None break if node.type == TYPE_GROUP: node.group.append(subp) #probably should check the number of leaves if len(node.group) == len(node.children): subp = get_characteristic_subpattern(node.group) node.group = [] node = node.parent continue else: node = node.parent subp = None break if node.type == token_labels.NAME and node.name: #in case of type=name, use the name instead subp.append(node.name) else: subp.append(node.type) node = node.parent return subp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def leaves(self): "Generator that returns the leaves of the tree" for child in self.children: for x in child.leaves(): yield x if not self.children: yield self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize_wrapper(input): """Tokenizes a string suppressing significant whitespace."""
skip = set((token.NEWLINE, token.INDENT, token.DEDENT)) tokens = tokenize.generate_tokens(StringIO.StringIO(input).readline) for quintuple in tokens: type, value, start, end, line_text = quintuple if type not in skip: yield quintuple
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pattern_convert(grammar, raw_node_info): """Converts raw node information to a Node or Leaf instance."""
type, value, context, children = raw_node_info if children or type in grammar.number2symbol: return pytree.Node(type, children, context=context) else: return pytree.Leaf(type, value, context=context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """
# XXX Optimize certain Wildcard-containing-Wildcard patterns # that can be merged if node.type == self.syms.Matcher: node = node.children[0] # Avoid unneeded recursion if node.type == self.syms.Alternatives: # Skip the odd children since they are just '|' tokens alts = [self.compile_node(ch) for ch in node.children[::2]] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if node.type == self.syms.Alternative: units = [self.compile_node(ch) for ch in node.children] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert node.type == self.syms.Unit name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] # Now we've reduced it to: STRING | NAME [Details] | (...) | [...] pattern = self.compile_basic(nodes, repeat) if repeat is not None: assert repeat.type == self.syms.Repeater children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: assert children[-1].type == token.RBRACE assert len(children) in (3, 5) min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) else: assert False if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize()
<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_WPARAM(wParam): """ Convert arguments to the WPARAM type. Used automatically by SendMessage, PostMessage, etc. You shouldn't need to call this function. """
wParam = ctypes.cast(wParam, LPVOID).value if wParam is None: wParam = 0 return wParam
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterchildren(self): """ Iterates the subkeys for this Registry key. @rtype: iter of L{RegistryKey} @return: Iterator of subkeys. """
handle = self.handle index = 0 while 1: subkey = win32.RegEnumKey(handle, index) if subkey is None: break yield self.child(subkey) index += 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 children(self): """ Returns a list of subkeys for this Registry key. @rtype: list(L{RegistryKey}) @return: List of subkeys. """
# return list(self.iterchildren()) # that can't be optimized by psyco handle = self.handle result = [] index = 0 while 1: subkey = win32.RegEnumKey(handle, index) if subkey is None: break result.append( self.child(subkey) ) index += 1 return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child(self, subkey): """ Retrieves a subkey for this Registry key, given its name. @type subkey: str @param subkey: Name of the subkey. @rtype: L{RegistryKey} @return: Subkey. """
path = self._path + '\\' + subkey handle = win32.RegOpenKey(self.handle, subkey) return RegistryKey(path, handle)
<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_path(self, path): """ Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the following integer constants: - L{win32.HKEY_CLASSES_ROOT} - L{win32.HKEY_CURRENT_USER} - L{win32.HKEY_LOCAL_MACHINE} - L{win32.HKEY_USERS} - L{win32.HKEY_PERFORMANCE_DATA} - L{win32.HKEY_CURRENT_CONFIG} """
if '\\' in path: p = path.find('\\') hive = path[:p] path = path[p+1:] else: hive = path path = None handle = self._hives_by_name[ hive.upper() ] return handle, path
<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_path(self, path): """ Parses a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. For a local Registry, the hive handle is an integer. For a remote Registry, the hive handle is a L{RegistryKeyHandle}. """
handle, path = self._split_path(path) if self._machine is not None: handle = self._connect_hive(handle) return handle, path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _join_path(self, hive, subkey): """ Joins the hive and key to make a Registry path. @type hive: int @param hive: Registry hive handle. The hive handle must be one of the following integer constants: - L{win32.HKEY_CLASSES_ROOT} - L{win32.HKEY_CURRENT_USER} - L{win32.HKEY_LOCAL_MACHINE} - L{win32.HKEY_USERS} - L{win32.HKEY_PERFORMANCE_DATA} - L{win32.HKEY_CURRENT_CONFIG} @type subkey: str @param subkey: Subkey path. @rtype: str @return: Registry path. """
path = self._hives_by_value[hive] if subkey: path = path + '\\' + subkey return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _connect_hive(self, hive): """ Connect to the specified hive of a remote Registry. @note: The connection will be cached, to close all connections and erase this cache call the L{close} method. @type hive: int @param hive: Hive to connect to. @rtype: L{win32.RegistryKeyHandle} @return: Open handle to the remote Registry hive. """
try: handle = self._remote_hives[hive] except KeyError: handle = win32.RegConnectRegistry(self._machine, hive) self._remote_hives[hive] = handle return handle
<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(self): """ Closes all open connections to the remote Registry. No exceptions are raised, even if an error occurs. This method has no effect when opening the local Registry. The remote Registry will still be accessible after calling this method (new connections will be opened automatically on access). """
while self._remote_hives: hive = self._remote_hives.popitem()[1] try: hive.close() except Exception: try: e = sys.exc_info()[1] msg = "Cannot close registry hive handle %s, reason: %s" msg %= (hive.value, str(e)) warnings.warn(msg) except Exception: pass