file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_console.py
'''An helper file for the pydev debugger (REPL) console ''' import sys import traceback from _pydevd_bundle.pydevconsole_code import InteractiveConsole, _EvalAwaitInNewEventLoop from _pydev_bundle import _pydev_completer from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn from _pydev_bundle.pydev_imports import Exec from _pydev_bundle.pydev_override import overrides from _pydevd_bundle import pydevd_save_locals from _pydevd_bundle.pydevd_io import IOBuf from pydevd_tracing import get_exception_traceback_str from _pydevd_bundle.pydevd_xml import make_valid_xml_value import inspect from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals CONSOLE_OUTPUT = "output" CONSOLE_ERROR = "error" #======================================================================================================================= # ConsoleMessage #======================================================================================================================= class ConsoleMessage: """Console Messages """ def __init__(self): self.more = False # List of tuple [('error', 'error_message'), ('message_list', 'output_message')] self.console_messages = [] def add_console_message(self, message_type, message): """add messages in the console_messages list """ for m in message.split("\n"): if m.strip(): self.console_messages.append((message_type, m)) def update_more(self, more): """more is set to true if further input is required from the user else more is set to false """ self.more = more def to_xml(self): """Create an XML for console message_list, error and more (true/false) <xml> <message_list>console message_list</message_list> <error>console error</error> <more>true/false</more> </xml> """ makeValid = make_valid_xml_value xml = '<xml><more>%s</more>' % (self.more) for message_type, message in self.console_messages: xml += '<%s message="%s"></%s>' % (message_type, makeValid(message), message_type) xml += '</xml>' return xml #======================================================================================================================= # _DebugConsoleStdIn #======================================================================================================================= class _DebugConsoleStdIn(BaseStdIn): @overrides(BaseStdIn.readline) def readline(self, *args, **kwargs): sys.stderr.write('Warning: Reading from stdin is still not supported in this console.\n') return '\n' #======================================================================================================================= # DebugConsole #======================================================================================================================= class DebugConsole(InteractiveConsole, BaseInterpreterInterface): """Wrapper around code.InteractiveConsole, in order to send errors and outputs to the debug console """ @overrides(BaseInterpreterInterface.create_std_in) def create_std_in(self, *args, **kwargs): try: if not self.__buffer_output: return sys.stdin except: pass return _DebugConsoleStdIn() # If buffered, raw_input is not supported in this console. @overrides(InteractiveConsole.push) def push(self, line, frame, buffer_output=True): """Change built-in stdout and stderr methods by the new custom StdMessage. execute the InteractiveConsole.push. Change the stdout and stderr back be the original built-ins :param buffer_output: if False won't redirect the output. Return boolean (True if more input is required else False), output_messages and input_messages """ self.__buffer_output = buffer_output more = False if buffer_output: original_stdout = sys.stdout original_stderr = sys.stderr try: try: self.frame = frame if buffer_output: out = sys.stdout = IOBuf() err = sys.stderr = IOBuf() more = self.add_exec(line) except Exception: exc = get_exception_traceback_str() if buffer_output: err.buflist.append("Internal Error: %s" % (exc,)) else: sys.stderr.write("Internal Error: %s\n" % (exc,)) finally: # Remove frame references. self.frame = None frame = None if buffer_output: sys.stdout = original_stdout sys.stderr = original_stderr if buffer_output: return more, out.buflist, err.buflist else: return more, [], [] @overrides(BaseInterpreterInterface.do_add_exec) def do_add_exec(self, line): return InteractiveConsole.push(self, line) @overrides(InteractiveConsole.runcode) def runcode(self, code): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: updated_globals = self.get_namespace() initial_globals = updated_globals.copy() updated_locals = None is_async = False if hasattr(inspect, 'CO_COROUTINE'): is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE if is_async: t = _EvalAwaitInNewEventLoop(code, updated_globals, updated_locals) t.start() t.join() update_globals_and_locals(updated_globals, initial_globals, self.frame) if t.exc: raise t.exc[1].with_traceback(t.exc[2]) else: try: exec(code, updated_globals, updated_locals) finally: update_globals_and_locals(updated_globals, initial_globals, self.frame) except SystemExit: raise except: # In case sys.excepthook called, use original excepthook #PyDev-877: Debug console freezes with Python 3.5+ # (showtraceback does it on python 3.5 onwards) sys.excepthook = sys.__excepthook__ try: self.showtraceback() finally: sys.__excepthook__ = sys.excepthook def get_namespace(self): dbg_namespace = {} dbg_namespace.update(self.frame.f_globals) dbg_namespace.update(self.frame.f_locals) # locals later because it has precedence over the actual globals return dbg_namespace #======================================================================================================================= # InteractiveConsoleCache #======================================================================================================================= class InteractiveConsoleCache: thread_id = None frame_id = None interactive_console_instance = None # Note: On Jython 2.1 we can't use classmethod or staticmethod, so, just make the functions below free-functions. def get_interactive_console(thread_id, frame_id, frame, console_message): """returns the global interactive console. interactive console should have been initialized by this time :rtype: DebugConsole """ if InteractiveConsoleCache.thread_id == thread_id and InteractiveConsoleCache.frame_id == frame_id: return InteractiveConsoleCache.interactive_console_instance InteractiveConsoleCache.interactive_console_instance = DebugConsole() InteractiveConsoleCache.thread_id = thread_id InteractiveConsoleCache.frame_id = frame_id console_stacktrace = traceback.extract_stack(frame, limit=1) if console_stacktrace: current_context = console_stacktrace[0] # top entry from stacktrace context_message = 'File "%s", line %s, in %s' % (current_context[0], current_context[1], current_context[2]) console_message.add_console_message(CONSOLE_OUTPUT, "[Current context]: %s" % (context_message,)) return InteractiveConsoleCache.interactive_console_instance def clear_interactive_console(): InteractiveConsoleCache.thread_id = None InteractiveConsoleCache.frame_id = None InteractiveConsoleCache.interactive_console_instance = None def execute_console_command(frame, thread_id, frame_id, line, buffer_output=True): """fetch an interactive console instance from the cache and push the received command to the console. create and return an instance of console_message """ console_message = ConsoleMessage() interpreter = get_interactive_console(thread_id, frame_id, frame, console_message) more, output_messages, error_messages = interpreter.push(line, frame, buffer_output) console_message.update_more(more) for message in output_messages: console_message.add_console_message(CONSOLE_OUTPUT, message) for message in error_messages: console_message.add_console_message(CONSOLE_ERROR, message) return console_message def get_description(frame, thread_id, frame_id, expression): console_message = ConsoleMessage() interpreter = get_interactive_console(thread_id, frame_id, frame, console_message) try: interpreter.frame = frame return interpreter.getDescription(expression) finally: interpreter.frame = None def get_completions(frame, act_tok): """ fetch all completions, create xml for the same return the completions xml """ return _pydev_completer.generate_completions_as_xml(frame, act_tok)
10,179
Python
36.564576
120
0.580411
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_constants.py
''' This module holds the constants used for specifying the states of the debugger. ''' from __future__ import nested_scopes import platform import weakref import struct import warnings import functools from contextlib import contextmanager STATE_RUN = 1 STATE_SUSPEND = 2 PYTHON_SUSPEND = 1 DJANGO_SUSPEND = 2 JINJA2_SUSPEND = 3 int_types = (int,) # types does not include a MethodWrapperType try: MethodWrapperType = type([].__str__) except: MethodWrapperType = None import sys # Note: the sys import must be here anyways (others depend on it) # Preload codecs to avoid imports to them later on which can potentially halt the debugger. import codecs as _codecs for _codec in ["ascii", "utf8", "utf-8", "latin1", "latin-1", "idna"]: _codecs.lookup(_codec) class DebugInfoHolder: # we have to put it here because it can be set through the command line (so, the # already imported references would not have it). # General information DEBUG_TRACE_LEVEL = 0 # 0 = critical, 1 = info, 2 = debug, 3 = verbose # Flags to debug specific points of the code. DEBUG_RECORD_SOCKET_READS = False DEBUG_TRACE_BREAKPOINTS = -1 PYDEVD_DEBUG_FILE = None # Any filename that starts with these strings is not traced nor shown to the user. # In Python 3.7 "<frozen ..." appears multiple times during import and should be ignored for the user. # In PyPy "<builtin> ..." can appear and should be ignored for the user. # <attrs is used internally by attrs # <__array_function__ is used by numpy IGNORE_BASENAMES_STARTING_WITH = ('<frozen ', '<builtin', '<attrs', '<__array_function__') # Note: <string> has special heuristics to know whether it should be traced or not (it's part of # user code when it's the <string> used in python -c and part of the library otherwise). # Any filename that starts with these strings is considered user (project) code. Note # that files for which we have a source mapping are also considered as a part of the project. USER_CODE_BASENAMES_STARTING_WITH = ('<ipython',) # Any filename that starts with these strings is considered library code (note: checked after USER_CODE_BASENAMES_STARTING_WITH). LIBRARY_CODE_BASENAMES_STARTING_WITH = ('<',) IS_CPYTHON = platform.python_implementation() == 'CPython' # Hold a reference to the original _getframe (because psyco will change that as soon as it's imported) IS_IRONPYTHON = sys.platform == 'cli' try: get_frame = sys._getframe if IS_IRONPYTHON: def get_frame(): try: return sys._getframe() except ValueError: pass except AttributeError: def get_frame(): raise AssertionError('sys._getframe not available (possible causes: enable -X:Frames on IronPython?)') # Used to determine the maximum size of each variable passed to eclipse -- having a big value here may make # the communication slower -- as the variables are being gathered lazily in the latest version of eclipse, # this value was raised from 200 to 1000. MAXIMUM_VARIABLE_REPRESENTATION_SIZE = 1000 # Prefix for saving functions return values in locals RETURN_VALUES_DICT = '__pydevd_ret_val_dict' GENERATED_LEN_ATTR_NAME = 'len()' import os from _pydevd_bundle import pydevd_vm_type # Constant detects when running on Jython/windows properly later on. IS_WINDOWS = sys.platform == 'win32' IS_LINUX = sys.platform in ('linux', 'linux2') IS_MAC = sys.platform == 'darwin' IS_64BIT_PROCESS = sys.maxsize > (2 ** 32) IS_JYTHON = pydevd_vm_type.get_vm_type() == pydevd_vm_type.PydevdVmType.JYTHON IS_PYPY = platform.python_implementation() == 'PyPy' if IS_JYTHON: import java.lang.System # @UnresolvedImport IS_WINDOWS = java.lang.System.getProperty("os.name").lower().startswith("windows") USE_CUSTOM_SYS_CURRENT_FRAMES = not hasattr(sys, '_current_frames') or IS_PYPY USE_CUSTOM_SYS_CURRENT_FRAMES_MAP = USE_CUSTOM_SYS_CURRENT_FRAMES and (IS_PYPY or IS_IRONPYTHON) if USE_CUSTOM_SYS_CURRENT_FRAMES: # Some versions of Jython don't have it (but we can provide a replacement) if IS_JYTHON: from java.lang import NoSuchFieldException from org.python.core import ThreadStateMapping try: cachedThreadState = ThreadStateMapping.getDeclaredField('globalThreadStates') # Dev version except NoSuchFieldException: cachedThreadState = ThreadStateMapping.getDeclaredField('cachedThreadState') # Release Jython 2.7.0 cachedThreadState.accessible = True thread_states = cachedThreadState.get(ThreadStateMapping) def _current_frames(): as_array = thread_states.entrySet().toArray() ret = {} for thread_to_state in as_array: thread = thread_to_state.getKey() if thread is None: continue thread_state = thread_to_state.getValue() if thread_state is None: continue frame = thread_state.frame if frame is None: continue ret[thread.getId()] = frame return ret elif USE_CUSTOM_SYS_CURRENT_FRAMES_MAP: constructed_tid_to_last_frame = {} # IronPython doesn't have it. Let's use our workaround... def _current_frames(): return constructed_tid_to_last_frame else: raise RuntimeError('Unable to proceed (sys._current_frames not available in this Python implementation).') else: _current_frames = sys._current_frames IS_PYTHON_STACKLESS = "stackless" in sys.version.lower() CYTHON_SUPPORTED = False python_implementation = platform.python_implementation() if python_implementation == 'CPython': # Only available for CPython! CYTHON_SUPPORTED = True #======================================================================================================================= # Python 3? #======================================================================================================================= IS_PY36_OR_GREATER = sys.version_info >= (3, 6) IS_PY37_OR_GREATER = sys.version_info >= (3, 7) IS_PY38_OR_GREATER = sys.version_info >= (3, 8) IS_PY39_OR_GREATER = sys.version_info >= (3, 9) IS_PY310_OR_GREATER = sys.version_info >= (3, 10) IS_PY311_OR_GREATER = sys.version_info >= (3, 11) def version_str(v): return '.'.join((str(x) for x in v[:3])) + ''.join((str(x) for x in v[3:])) PY_VERSION_STR = version_str(sys.version_info) try: PY_IMPL_VERSION_STR = version_str(sys.implementation.version) except AttributeError: PY_IMPL_VERSION_STR = '' try: PY_IMPL_NAME = sys.implementation.name except AttributeError: PY_IMPL_NAME = '' ENV_TRUE_LOWER_VALUES = ('yes', 'true', '1') ENV_FALSE_LOWER_VALUES = ('no', 'false', '0') def is_true_in_env(env_key): if isinstance(env_key, tuple): # If a tuple, return True if any of those ends up being true. for v in env_key: if is_true_in_env(v): return True return False else: return os.getenv(env_key, '').lower() in ENV_TRUE_LOWER_VALUES def as_float_in_env(env_key, default): value = os.getenv(env_key) if value is None: return default try: return float(value) except Exception: raise RuntimeError( 'Error: expected the env variable: %s to be set to a float value. Found: %s' % ( env_key, value)) def as_int_in_env(env_key, default): value = os.getenv(env_key) if value is None: return default try: return int(value) except Exception: raise RuntimeError( 'Error: expected the env variable: %s to be set to a int value. Found: %s' % ( env_key, value)) # If true in env, use gevent mode. SUPPORT_GEVENT = is_true_in_env('GEVENT_SUPPORT') # Opt-in support to show gevent paused greenlets. False by default because if too many greenlets are # paused the UI can slow-down (i.e.: if 1000 greenlets are paused, each one would be shown separate # as a different thread, but if the UI isn't optimized for that the experience is lacking...). GEVENT_SHOW_PAUSED_GREENLETS = is_true_in_env('GEVENT_SHOW_PAUSED_GREENLETS') DISABLE_FILE_VALIDATION = is_true_in_env('PYDEVD_DISABLE_FILE_VALIDATION') GEVENT_SUPPORT_NOT_SET_MSG = os.getenv( 'GEVENT_SUPPORT_NOT_SET_MSG', 'It seems that the gevent monkey-patching is being used.\n' 'Please set an environment variable with:\n' 'GEVENT_SUPPORT=True\n' 'to enable gevent support in the debugger.' ) USE_LIB_COPY = SUPPORT_GEVENT INTERACTIVE_MODE_AVAILABLE = sys.platform in ('darwin', 'win32') or os.getenv('DISPLAY') is not None # If true in env, forces cython to be used (raises error if not available). # If false in env, disables it. # If not specified, uses default heuristic to determine if it should be loaded. USE_CYTHON_FLAG = os.getenv('PYDEVD_USE_CYTHON') if USE_CYTHON_FLAG is not None: USE_CYTHON_FLAG = USE_CYTHON_FLAG.lower() if USE_CYTHON_FLAG not in ENV_TRUE_LOWER_VALUES and USE_CYTHON_FLAG not in ENV_FALSE_LOWER_VALUES: raise RuntimeError('Unexpected value for PYDEVD_USE_CYTHON: %s (enable with one of: %s, disable with one of: %s)' % ( USE_CYTHON_FLAG, ENV_TRUE_LOWER_VALUES, ENV_FALSE_LOWER_VALUES)) else: if not CYTHON_SUPPORTED: USE_CYTHON_FLAG = 'no' # If true in env, forces frame eval to be used (raises error if not available). # If false in env, disables it. # If not specified, uses default heuristic to determine if it should be loaded. PYDEVD_USE_FRAME_EVAL = os.getenv('PYDEVD_USE_FRAME_EVAL', '').lower() PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING = is_true_in_env('PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING') # If specified in PYDEVD_IPYTHON_CONTEXT it must be a string with the basename # and then the name of 2 methods in which the evaluate is done. PYDEVD_IPYTHON_CONTEXT = ('interactiveshell.py', 'run_code', 'run_ast_nodes') _ipython_ctx = os.getenv('PYDEVD_IPYTHON_CONTEXT') if _ipython_ctx: PYDEVD_IPYTHON_CONTEXT = tuple(x.strip() for x in _ipython_ctx.split(',')) assert len(PYDEVD_IPYTHON_CONTEXT) == 3, 'Invalid PYDEVD_IPYTHON_CONTEXT: %s' % (_ipython_ctx,) # Use to disable loading the lib to set tracing to all threads (default is using heuristics based on where we're running). LOAD_NATIVE_LIB_FLAG = os.getenv('PYDEVD_LOAD_NATIVE_LIB', '').lower() LOG_TIME = os.getenv('PYDEVD_LOG_TIME', 'true').lower() in ENV_TRUE_LOWER_VALUES SHOW_COMPILE_CYTHON_COMMAND_LINE = is_true_in_env('PYDEVD_SHOW_COMPILE_CYTHON_COMMAND_LINE') LOAD_VALUES_ASYNC = is_true_in_env('PYDEVD_LOAD_VALUES_ASYNC') DEFAULT_VALUE = "__pydevd_value_async" ASYNC_EVAL_TIMEOUT_SEC = 60 NEXT_VALUE_SEPARATOR = "__pydev_val__" BUILTINS_MODULE_NAME = 'builtins' SHOW_DEBUG_INFO_ENV = is_true_in_env(('PYCHARM_DEBUG', 'PYDEV_DEBUG', 'PYDEVD_DEBUG')) # Pandas customization. PANDAS_MAX_ROWS = as_int_in_env('PYDEVD_PANDAS_MAX_ROWS', 60) PANDAS_MAX_COLS = as_int_in_env('PYDEVD_PANDAS_MAX_COLS', 10) PANDAS_MAX_COLWIDTH = as_int_in_env('PYDEVD_PANDAS_MAX_COLWIDTH', 50) # If getting an attribute or computing some value is too slow, let the user know if the given timeout elapses. PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT = as_float_in_env('PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT', 0.15) # This timeout is used to track the time to send a message saying that the evaluation # is taking too long and possible mitigations. PYDEVD_WARN_EVALUATION_TIMEOUT = as_float_in_env('PYDEVD_WARN_EVALUATION_TIMEOUT', 3.) # If True in env shows a thread dump when the evaluation times out. PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT = is_true_in_env('PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT') # This timeout is used only when the mode that all threads are stopped/resumed at once is used # (i.e.: multi_threads_single_notification) # # In this mode, if some evaluation doesn't finish until this timeout, we notify the user # and then resume all threads until the evaluation finishes. # # A negative value will disable the timeout and a value of 0 will automatically run all threads # (without any notification) when the evaluation is started and pause all threads when the # evaluation is finished. A positive value will run run all threads after the timeout # elapses. PYDEVD_UNBLOCK_THREADS_TIMEOUT = as_float_in_env('PYDEVD_UNBLOCK_THREADS_TIMEOUT', -1.) # Timeout to interrupt a thread (so, if some evaluation doesn't finish until this # timeout, the thread doing the evaluation is interrupted). # A value <= 0 means this is disabled. # See: _pydevd_bundle.pydevd_timeout.create_interrupt_this_thread_callback for details # on how the thread interruption works (there are some caveats related to it). PYDEVD_INTERRUPT_THREAD_TIMEOUT = as_float_in_env('PYDEVD_INTERRUPT_THREAD_TIMEOUT', -1) # If PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS is set to False, the patching to hide pydevd threads won't be applied. PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS = os.getenv('PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS', 'true').lower() in ENV_TRUE_LOWER_VALUES EXCEPTION_TYPE_UNHANDLED = 'UNHANDLED' EXCEPTION_TYPE_USER_UNHANDLED = 'USER_UNHANDLED' EXCEPTION_TYPE_HANDLED = 'HANDLED' if SHOW_DEBUG_INFO_ENV: # show debug info before the debugger start DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 1 DebugInfoHolder.PYDEVD_DEBUG_FILE = os.getenv('PYDEVD_DEBUG_FILE') def protect_libraries_from_patching(): """ In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patching by external libraries (e.g. gevent). """ patched = ['threading', 'thread', '_thread', 'time', 'socket', 'queue', 'select', 'xmlrpclib', 'SimpleXMLRPCServer', 'BaseHTTPServer', 'SocketServer', 'xmlrpc.client', 'xmlrpc.server', 'http.server', 'socketserver'] for name in patched: try: __import__(name) except: pass patched_modules = dict([(k, v) for k, v in sys.modules.items() if k in patched]) for name in patched_modules: del sys.modules[name] # import for side effects import _pydev_bundle._pydev_saved_modules for name in patched_modules: sys.modules[name] = patched_modules[name] if USE_LIB_COPY: protect_libraries_from_patching() from _pydev_bundle._pydev_saved_modules import thread, threading _fork_safe_locks = [] if IS_JYTHON: def ForkSafeLock(rlock=False): if rlock: return threading.RLock() else: return threading.Lock() else: class ForkSafeLock(object): ''' A lock which is fork-safe (when a fork is done, `pydevd_constants.after_fork()` should be called to reset the locks in the new process to avoid deadlocks from a lock which was locked during the fork). Note: Unlike `threading.Lock` this class is not completely atomic, so, doing: lock = ForkSafeLock() with lock: ... is different than using `threading.Lock` directly because the tracing may find an additional function call on `__enter__` and on `__exit__`, so, it's not recommended to use this in all places, only where the forking may be important (so, for instance, the locks on PyDB should not be changed to this lock because of that -- and those should all be collected in the new process because PyDB itself should be completely cleared anyways). It's possible to overcome this limitation by using `ForkSafeLock.acquire` and `ForkSafeLock.release` instead of the context manager (as acquire/release are bound to the original implementation, whereas __enter__/__exit__ is not due to Python limitations). ''' def __init__(self, rlock=False): self._rlock = rlock self._init() _fork_safe_locks.append(weakref.ref(self)) def __enter__(self): return self._lock.__enter__() def __exit__(self, exc_type, exc_val, exc_tb): return self._lock.__exit__(exc_type, exc_val, exc_tb) def _init(self): if self._rlock: self._lock = threading.RLock() else: self._lock = thread.allocate_lock() self.acquire = self._lock.acquire self.release = self._lock.release _fork_safe_locks.append(weakref.ref(self)) def after_fork(): ''' Must be called after a fork operation (will reset the ForkSafeLock). ''' global _fork_safe_locks locks = _fork_safe_locks[:] _fork_safe_locks = [] for lock in locks: lock = lock() if lock is not None: lock._init() _thread_id_lock = ForkSafeLock() thread_get_ident = thread.get_ident def as_str(s): assert isinstance(s, str) return s @contextmanager def filter_all_warnings(): with warnings.catch_warnings(): warnings.filterwarnings("ignore") yield def silence_warnings_decorator(func): @functools.wraps(func) def new_func(*args, **kwargs): with filter_all_warnings(): return func(*args, **kwargs) return new_func def sorted_dict_repr(d): s = sorted(d.items(), key=lambda x:str(x[0])) return '{' + ', '.join(('%r: %r' % x) for x in s) + '}' def iter_chars(b): # In Python 2, we can iterate bytes or str with individual characters, but Python 3 onwards # changed that behavior so that when iterating bytes we actually get ints! if isinstance(b, bytes): # i.e.: do something as struct.unpack('3c', b) return iter(struct.unpack(str(len(b)) + 'c', b)) return iter(b) if IS_JYTHON: def NO_FTRACE(frame, event, arg): return None else: _curr_trace = sys.gettrace() # Set a temporary trace which does nothing for us to test (otherwise setting frame.f_trace has no # effect). def _temp_trace(frame, event, arg): return None sys.settrace(_temp_trace) def _check_ftrace_set_none(): ''' Will throw an error when executing a line event ''' sys._getframe().f_trace = None _line_event = 1 _line_event = 2 try: _check_ftrace_set_none() def NO_FTRACE(frame, event, arg): frame.f_trace = None return None except TypeError: def NO_FTRACE(frame, event, arg): # In Python <= 2.6 and <= 3.4, if we're tracing a method, frame.f_trace may not be set # to None, it must always be set to a tracing function. # See: tests_python.test_tracing_gotchas.test_tracing_gotchas # # Note: Python 2.7 sometimes works and sometimes it doesn't depending on the minor # version because of https://bugs.python.org/issue20041 (although bug reports didn't # include the minor version, so, mark for any Python 2.7 as I'm not completely sure # the fix in later 2.7 versions is the same one we're dealing with). return None sys.settrace(_curr_trace) #======================================================================================================================= # get_pid #======================================================================================================================= def get_pid(): try: return os.getpid() except AttributeError: try: # Jython does not have it! import java.lang.management.ManagementFactory # @UnresolvedImport -- just for jython pid = java.lang.management.ManagementFactory.getRuntimeMXBean().getName() return pid.replace('@', '_') except: # ok, no pid available (will be unable to debug multiple processes) return '000001' def clear_cached_thread_id(thread): with _thread_id_lock: try: if thread.__pydevd_id__ != 'console_main': # The console_main is a special thread id used in the console and its id should never be reset # (otherwise we may no longer be able to get its variables -- see: https://www.brainwy.com/tracker/PyDev/776). del thread.__pydevd_id__ except AttributeError: pass # Don't let threads be collected (so that id(thread) is guaranteed to be unique). _thread_id_to_thread_found = {} def _get_or_compute_thread_id_with_lock(thread, is_current_thread): with _thread_id_lock: # We do a new check with the lock in place just to be sure that nothing changed tid = getattr(thread, '__pydevd_id__', None) if tid is not None: return tid _thread_id_to_thread_found[id(thread)] = thread # Note: don't use thread.ident because a new thread may have the # same id from an old thread. pid = get_pid() tid = 'pid_%s_id_%s' % (pid, id(thread)) thread.__pydevd_id__ = tid return tid def get_current_thread_id(thread): ''' Note: the difference from get_current_thread_id to get_thread_id is that for the current thread we can get the thread id while the thread.ident is still not set in the Thread instance. ''' try: # Fast path without getting lock. tid = thread.__pydevd_id__ if tid is None: # Fix for https://www.brainwy.com/tracker/PyDev/645 # if __pydevd_id__ is None, recalculate it... also, use an heuristic # that gives us always the same id for the thread (using thread.ident or id(thread)). raise AttributeError() except AttributeError: tid = _get_or_compute_thread_id_with_lock(thread, is_current_thread=True) return tid def get_thread_id(thread): try: # Fast path without getting lock. tid = thread.__pydevd_id__ if tid is None: # Fix for https://www.brainwy.com/tracker/PyDev/645 # if __pydevd_id__ is None, recalculate it... also, use an heuristic # that gives us always the same id for the thread (using thread.ident or id(thread)). raise AttributeError() except AttributeError: tid = _get_or_compute_thread_id_with_lock(thread, is_current_thread=False) return tid def set_thread_id(thread, thread_id): with _thread_id_lock: thread.__pydevd_id__ = thread_id #======================================================================================================================= # Null #======================================================================================================================= class Null: """ Gotten from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 """ def __init__(self, *args, **kwargs): return None def __call__(self, *args, **kwargs): return self def __enter__(self, *args, **kwargs): return self def __exit__(self, *args, **kwargs): return self def __getattr__(self, mname): if len(mname) > 4 and mname[:2] == '__' and mname[-2:] == '__': # Don't pretend to implement special method names. raise AttributeError(mname) return self def __setattr__(self, name, value): return self def __delattr__(self, name): return self def __repr__(self): return "<Null>" def __str__(self): return "Null" def __len__(self): return 0 def __getitem__(self): return self def __setitem__(self, *args, **kwargs): pass def write(self, *args, **kwargs): pass def __nonzero__(self): return 0 def __iter__(self): return iter(()) # Default instance NULL = Null() class KeyifyList(object): def __init__(self, inner, key): self.inner = inner self.key = key def __len__(self): return len(self.inner) def __getitem__(self, k): return self.key(self.inner[k]) def call_only_once(func): ''' To be used as a decorator @call_only_once def func(): print 'Calling func only this time' Actually, in PyDev it must be called as: func = call_only_once(func) to support older versions of Python. ''' def new_func(*args, **kwargs): if not new_func._called: new_func._called = True return func(*args, **kwargs) new_func._called = False return new_func # Protocol where each line is a new message (text is quoted to prevent new lines). # payload is xml QUOTED_LINE_PROTOCOL = 'quoted-line' ARGUMENT_QUOTED_LINE_PROTOCOL = 'protocol-quoted-line' # Uses http protocol to provide a new message. # i.e.: Content-Length:xxx\r\n\r\npayload # payload is xml HTTP_PROTOCOL = 'http' ARGUMENT_HTTP_PROTOCOL = 'protocol-http' # Message is sent without any header. # payload is json JSON_PROTOCOL = 'json' ARGUMENT_JSON_PROTOCOL = 'json-dap' # Same header as the HTTP_PROTOCOL # payload is json HTTP_JSON_PROTOCOL = 'http_json' ARGUMENT_HTTP_JSON_PROTOCOL = 'json-dap-http' ARGUMENT_PPID = 'ppid' class _GlobalSettings: protocol = QUOTED_LINE_PROTOCOL def set_protocol(protocol): expected = (HTTP_PROTOCOL, QUOTED_LINE_PROTOCOL, JSON_PROTOCOL, HTTP_JSON_PROTOCOL) assert protocol in expected, 'Protocol (%s) should be one of: %s' % ( protocol, expected) _GlobalSettings.protocol = protocol def get_protocol(): return _GlobalSettings.protocol def is_json_protocol(): return _GlobalSettings.protocol in (JSON_PROTOCOL, HTTP_JSON_PROTOCOL) class GlobalDebuggerHolder: ''' Holder for the global debugger. ''' global_dbg = None # Note: don't rename (the name is used in our attach to process) def get_global_debugger(): return GlobalDebuggerHolder.global_dbg GetGlobalDebugger = get_global_debugger # Backward-compatibility def set_global_debugger(dbg): GlobalDebuggerHolder.global_dbg = dbg if __name__ == '__main__': if Null(): sys.stdout.write('here\n')
26,450
Python
32.355612
145
0.637883
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_extension_api.py
import abc # borrowed from from six def _with_metaclass(meta, *bases): """Create a base class with a metaclass.""" class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) # ======================================================================================================================= # AbstractResolver # ======================================================================================================================= class _AbstractResolver(_with_metaclass(abc.ABCMeta)): """ This class exists only for documentation purposes to explain how to create a resolver. Some examples on how to resolve things: - list: get_dictionary could return a dict with index->item and use the index to resolve it later - set: get_dictionary could return a dict with id(object)->object and reiterate in that array to resolve it later - arbitrary instance: get_dictionary could return dict with attr_name->attr and use getattr to resolve it later """ @abc.abstractmethod def resolve(self, var, attribute): """ In this method, we'll resolve some child item given the string representation of the item in the key representing the previously asked dictionary. @param var: this is the actual variable to be resolved. @param attribute: this is the string representation of a key previously returned in get_dictionary. """ raise NotImplementedError @abc.abstractmethod def get_dictionary(self, var): """ @param var: this is the variable that should have its children gotten. @return: a dictionary where each pair key, value should be shown to the user as children items in the variables view for the given var. """ raise NotImplementedError class _AbstractProvider(_with_metaclass(abc.ABCMeta)): @abc.abstractmethod def can_provide(self, type_object, type_name): raise NotImplementedError # ======================================================================================================================= # API CLASSES: # ======================================================================================================================= class TypeResolveProvider(_AbstractResolver, _AbstractProvider): """ Implement this in an extension to provide a custom resolver, see _AbstractResolver """ class StrPresentationProvider(_AbstractProvider): """ Implement this in an extension to provide a str presentation for a type """ @abc.abstractmethod def get_str(self, val): raise NotImplementedError class DebuggerEventHandler(_with_metaclass(abc.ABCMeta)): """ Implement this to receive lifecycle events from the debugger """ def on_debugger_modules_loaded(self, **kwargs): """ This method invoked after all debugger modules are loaded. Useful for importing and/or patching debugger modules at a safe time :param kwargs: This is intended to be flexible dict passed from the debugger. Currently passes the debugger version """
3,288
Python
36.375
121
0.575122
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_suspended_frames.py
from contextlib import contextmanager import sys from _pydevd_bundle.pydevd_constants import get_frame, RETURN_VALUES_DICT, \ ForkSafeLock, GENERATED_LEN_ATTR_NAME, silence_warnings_decorator from _pydevd_bundle.pydevd_xml import get_variable_details, get_type from _pydev_bundle.pydev_override import overrides from _pydevd_bundle.pydevd_resolver import sorted_attributes_key, TOO_LARGE_ATTR, get_var_scope from _pydevd_bundle.pydevd_safe_repr import SafeRepr from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_vars from _pydev_bundle.pydev_imports import Exec from _pydevd_bundle.pydevd_frame_utils import FramesList from _pydevd_bundle.pydevd_utils import ScopeRequest, DAPGrouper, Timer class _AbstractVariable(object): # Default attributes in class, set in instance. name = None value = None evaluate_name = None def __init__(self, py_db): assert py_db is not None self.py_db = py_db def get_name(self): return self.name def get_value(self): return self.value def get_variable_reference(self): return id(self.value) def get_var_data(self, fmt=None, **safe_repr_custom_attrs): ''' :param dict fmt: Format expected by the DAP (keys: 'hex': bool, 'rawString': bool) ''' timer = Timer() safe_repr = SafeRepr() if fmt is not None: safe_repr.convert_to_hex = fmt.get('hex', False) safe_repr.raw_value = fmt.get('rawString', False) for key, val in safe_repr_custom_attrs.items(): setattr(safe_repr, key, val) type_name, _type_qualifier, _is_exception_on_eval, resolver, value = get_variable_details( self.value, to_string=safe_repr) is_raw_string = type_name in ('str', 'bytes', 'bytearray') attributes = [] if is_raw_string: attributes.append('rawString') name = self.name if self._is_return_value: attributes.append('readOnly') name = '(return) %s' % (name,) elif name in (TOO_LARGE_ATTR, GENERATED_LEN_ATTR_NAME): attributes.append('readOnly') try: if self.value.__class__ == DAPGrouper: type_name = '' except: pass # Ignore errors accessing __class__. var_data = { 'name': name, 'value': value, 'type': type_name, } if self.evaluate_name is not None: var_data['evaluateName'] = self.evaluate_name if resolver is not None: # I.e.: it's a container var_data['variablesReference'] = self.get_variable_reference() else: var_data['variablesReference'] = 0 # It's mandatory (although if == 0 it doesn't have children). if len(attributes) > 0: var_data['presentationHint'] = {'attributes': attributes} timer.report_if_compute_repr_attr_slow('', name, type_name) return var_data def get_children_variables(self, fmt=None, scope=None): raise NotImplementedError() def get_child_variable_named(self, name, fmt=None, scope=None): for child_var in self.get_children_variables(fmt=fmt, scope=scope): if child_var.get_name() == name: return child_var return None def _group_entries(self, lst, handle_return_values): scope_to_grouper = {} group_entries = [] if isinstance(self.value, DAPGrouper): new_lst = lst else: new_lst = [] get_presentation = self.py_db.variable_presentation.get_presentation # Now that we have the contents, group items. for attr_name, attr_value, evaluate_name in lst: scope = get_var_scope(attr_name, attr_value, evaluate_name, handle_return_values) entry = (attr_name, attr_value, evaluate_name) if scope: presentation = get_presentation(scope) if presentation == 'hide': continue elif presentation == 'inline': new_lst.append(entry) else: # group if scope not in scope_to_grouper: grouper = DAPGrouper(scope) scope_to_grouper[scope] = grouper else: grouper = scope_to_grouper[scope] grouper.contents_debug_adapter_protocol.append(entry) else: new_lst.append(entry) for scope in DAPGrouper.SCOPES_SORTED: grouper = scope_to_grouper.get(scope) if grouper is not None: group_entries.append((scope, grouper, None)) return new_lst, group_entries class _ObjectVariable(_AbstractVariable): def __init__(self, py_db, name, value, register_variable, is_return_value=False, evaluate_name=None, frame=None): _AbstractVariable.__init__(self, py_db) self.frame = frame self.name = name self.value = value self._register_variable = register_variable self._register_variable(self) self._is_return_value = is_return_value self.evaluate_name = evaluate_name @silence_warnings_decorator @overrides(_AbstractVariable.get_children_variables) def get_children_variables(self, fmt=None, scope=None): _type, _type_name, resolver = get_type(self.value) children_variables = [] if resolver is not None: # i.e.: it's a container. if hasattr(resolver, 'get_contents_debug_adapter_protocol'): # The get_contents_debug_adapter_protocol needs to return sorted. lst = resolver.get_contents_debug_adapter_protocol(self.value, fmt=fmt) else: # If there's no special implementation, the default is sorting the keys. dct = resolver.get_dictionary(self.value) lst = sorted(dct.items(), key=lambda tup: sorted_attributes_key(tup[0])) # No evaluate name in this case. lst = [(key, value, None) for (key, value) in lst] lst, group_entries = self._group_entries(lst, handle_return_values=False) if group_entries: lst = group_entries + lst parent_evaluate_name = self.evaluate_name if parent_evaluate_name: for key, val, evaluate_name in lst: if evaluate_name is not None: if callable(evaluate_name): evaluate_name = evaluate_name(parent_evaluate_name) else: evaluate_name = parent_evaluate_name + evaluate_name variable = _ObjectVariable( self.py_db, key, val, self._register_variable, evaluate_name=evaluate_name, frame=self.frame) children_variables.append(variable) else: for key, val, evaluate_name in lst: # No evaluate name variable = _ObjectVariable(self.py_db, key, val, self._register_variable, frame=self.frame) children_variables.append(variable) return children_variables def change_variable(self, name, value, py_db, fmt=None): children_variable = self.get_child_variable_named(name) if children_variable is None: return None var_data = children_variable.get_var_data() evaluate_name = var_data.get('evaluateName') if not evaluate_name: # Note: right now we only pass control to the resolver in the cases where # there's no evaluate name (the idea being that if we can evaluate it, # we can use that evaluation to set the value too -- if in the future # a case where this isn't true is found this logic may need to be changed). _type, _type_name, container_resolver = get_type(self.value) if hasattr(container_resolver, 'change_var_from_name'): try: new_value = eval(value) except: return None new_key = container_resolver.change_var_from_name(self.value, name, new_value) if new_key is not None: return _ObjectVariable( self.py_db, new_key, new_value, self._register_variable, evaluate_name=None, frame=self.frame) return None else: return None frame = self.frame if frame is None: return None try: # This handles the simple cases (such as dict, list, object) Exec('%s=%s' % (evaluate_name, value), frame.f_globals, frame.f_locals) except: return None return self.get_child_variable_named(name, fmt=fmt) def sorted_variables_key(obj): return sorted_attributes_key(obj.name) class _FrameVariable(_AbstractVariable): def __init__(self, py_db, frame, register_variable): _AbstractVariable.__init__(self, py_db) self.frame = frame self.name = self.frame.f_code.co_name self.value = frame self._register_variable = register_variable self._register_variable(self) def change_variable(self, name, value, py_db, fmt=None): frame = self.frame pydevd_vars.change_attr_expression(frame, name, value, py_db) return self.get_child_variable_named(name, fmt=fmt) @silence_warnings_decorator @overrides(_AbstractVariable.get_children_variables) def get_children_variables(self, fmt=None, scope=None): children_variables = [] if scope is not None: assert isinstance(scope, ScopeRequest) scope = scope.scope if scope in ('locals', None): dct = self.frame.f_locals elif scope == 'globals': dct = self.frame.f_globals else: raise AssertionError('Unexpected scope: %s' % (scope,)) lst, group_entries = self._group_entries([(x[0], x[1], None) for x in list(dct.items()) if x[0] != '_pydev_stop_at_break'], handle_return_values=True) group_variables = [] for key, val, _ in group_entries: # Make sure that the contents in the group are also sorted. val.contents_debug_adapter_protocol.sort(key=lambda v:sorted_attributes_key(v[0])) variable = _ObjectVariable(self.py_db, key, val, self._register_variable, False, key, frame=self.frame) group_variables.append(variable) for key, val, _ in lst: is_return_value = key == RETURN_VALUES_DICT if is_return_value: for return_key, return_value in val.items(): variable = _ObjectVariable( self.py_db, return_key, return_value, self._register_variable, is_return_value, '%s[%r]' % (key, return_key), frame=self.frame) children_variables.append(variable) else: variable = _ObjectVariable(self.py_db, key, val, self._register_variable, is_return_value, key, frame=self.frame) children_variables.append(variable) # Frame variables always sorted. children_variables.sort(key=sorted_variables_key) if group_variables: # Groups have priority over other variables. children_variables = group_variables + children_variables return children_variables class _FramesTracker(object): ''' This is a helper class to be used to track frames when a thread becomes suspended. ''' def __init__(self, suspended_frames_manager, py_db): self._suspended_frames_manager = suspended_frames_manager self.py_db = py_db self._frame_id_to_frame = {} # Note that a given frame may appear in multiple threads when we have custom # frames added, but as those are coroutines, this map will point to the actual # main thread (which is the one that needs to be suspended for us to get the # variables). self._frame_id_to_main_thread_id = {} # A map of the suspended thread id -> list(frames ids) -- note that # frame ids are kept in order (the first one is the suspended frame). self._thread_id_to_frame_ids = {} self._thread_id_to_frames_list = {} # The main suspended thread (if this is a coroutine this isn't the id of the # coroutine thread, it's the id of the actual suspended thread). self._main_thread_id = None # Helper to know if it was already untracked. self._untracked = False # We need to be thread-safe! self._lock = ForkSafeLock() self._variable_reference_to_variable = {} def _register_variable(self, variable): variable_reference = variable.get_variable_reference() self._variable_reference_to_variable[variable_reference] = variable def obtain_as_variable(self, name, value, evaluate_name=None, frame=None): if evaluate_name is None: evaluate_name = name variable_reference = id(value) variable = self._variable_reference_to_variable.get(variable_reference) if variable is not None: return variable # Still not created, let's do it now. return _ObjectVariable( self.py_db, name, value, self._register_variable, is_return_value=False, evaluate_name=evaluate_name, frame=frame) def get_main_thread_id(self): return self._main_thread_id def get_variable(self, variable_reference): return self._variable_reference_to_variable[variable_reference] def track(self, thread_id, frames_list, frame_custom_thread_id=None): ''' :param thread_id: The thread id to be used for this frame. :param FramesList frames_list: A list of frames to be tracked (the first is the topmost frame which is suspended at the given thread). :param frame_custom_thread_id: If None this this is the id of the thread id for the custom frame (i.e.: coroutine). ''' assert frames_list.__class__ == FramesList with self._lock: coroutine_or_main_thread_id = frame_custom_thread_id or thread_id if coroutine_or_main_thread_id in self._suspended_frames_manager._thread_id_to_tracker: sys.stderr.write('pydevd: Something is wrong. Tracker being added twice to the same thread id.\n') self._suspended_frames_manager._thread_id_to_tracker[coroutine_or_main_thread_id] = self self._main_thread_id = thread_id frame_ids_from_thread = self._thread_id_to_frame_ids.setdefault( coroutine_or_main_thread_id, []) self._thread_id_to_frames_list[coroutine_or_main_thread_id] = frames_list for frame in frames_list: frame_id = id(frame) self._frame_id_to_frame[frame_id] = frame _FrameVariable(self.py_db, frame, self._register_variable) # Instancing is enough to register. self._suspended_frames_manager._variable_reference_to_frames_tracker[frame_id] = self frame_ids_from_thread.append(frame_id) self._frame_id_to_main_thread_id[frame_id] = thread_id frame = None def untrack_all(self): with self._lock: if self._untracked: # Calling multiple times is expected for the set next statement. return self._untracked = True for thread_id in self._thread_id_to_frame_ids: self._suspended_frames_manager._thread_id_to_tracker.pop(thread_id, None) for frame_id in self._frame_id_to_frame: del self._suspended_frames_manager._variable_reference_to_frames_tracker[frame_id] self._frame_id_to_frame.clear() self._frame_id_to_main_thread_id.clear() self._thread_id_to_frame_ids.clear() self._thread_id_to_frames_list.clear() self._main_thread_id = None self._suspended_frames_manager = None self._variable_reference_to_variable.clear() def get_frames_list(self, thread_id): with self._lock: return self._thread_id_to_frames_list.get(thread_id) def find_frame(self, thread_id, frame_id): with self._lock: return self._frame_id_to_frame.get(frame_id) def create_thread_suspend_command(self, thread_id, stop_reason, message, suspend_type): with self._lock: # First one is topmost frame suspended. frames_list = self._thread_id_to_frames_list[thread_id] cmd = self.py_db.cmd_factory.make_thread_suspend_message( self.py_db, thread_id, frames_list, stop_reason, message, suspend_type) frames_list = None return cmd class SuspendedFramesManager(object): def __init__(self): self._thread_id_to_fake_frames = {} self._thread_id_to_tracker = {} # Mappings self._variable_reference_to_frames_tracker = {} def _get_tracker_for_variable_reference(self, variable_reference): tracker = self._variable_reference_to_frames_tracker.get(variable_reference) if tracker is not None: return tracker for _thread_id, tracker in self._thread_id_to_tracker.items(): try: tracker.get_variable(variable_reference) except KeyError: pass else: return tracker return None def get_thread_id_for_variable_reference(self, variable_reference): ''' We can't evaluate variable references values on any thread, only in the suspended thread (the main reason for this is that in UI frameworks inspecting a UI object from a different thread can potentially crash the application). :param int variable_reference: The variable reference (can be either a frame id or a reference to a previously gotten variable). :return str: The thread id for the thread to be used to inspect the given variable reference or None if the thread was already resumed. ''' frames_tracker = self._get_tracker_for_variable_reference(variable_reference) if frames_tracker is not None: return frames_tracker.get_main_thread_id() return None def get_frame_tracker(self, thread_id): return self._thread_id_to_tracker.get(thread_id) def get_variable(self, variable_reference): ''' :raises KeyError ''' frames_tracker = self._get_tracker_for_variable_reference(variable_reference) if frames_tracker is None: raise KeyError() return frames_tracker.get_variable(variable_reference) def get_frames_list(self, thread_id): tracker = self._thread_id_to_tracker.get(thread_id) if tracker is None: return None return tracker.get_frames_list(thread_id) @contextmanager def track_frames(self, py_db): tracker = _FramesTracker(self, py_db) try: yield tracker finally: tracker.untrack_all() def add_fake_frame(self, thread_id, frame_id, frame): self._thread_id_to_fake_frames.setdefault(thread_id, {})[int(frame_id)] = frame def find_frame(self, thread_id, frame_id): try: if frame_id == "*": return get_frame() # any frame is specified with "*" frame_id = int(frame_id) fake_frames = self._thread_id_to_fake_frames.get(thread_id) if fake_frames is not None: frame = fake_frames.get(frame_id) if frame is not None: return frame frames_tracker = self._thread_id_to_tracker.get(thread_id) if frames_tracker is not None: frame = frames_tracker.find_frame(thread_id, frame_id) if frame is not None: return frame return None except: pydev_log.exception() return None
20,559
Python
37.501873
158
0.594776
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_cython_wrapper.py
import sys try: try: from _pydevd_bundle_ext import pydevd_cython as mod except ImportError: from _pydevd_bundle import pydevd_cython as mod except ImportError: import struct try: is_python_64bit = (struct.calcsize('P') == 8) except: # In Jython this call fails, but this is Ok, we don't support Jython for speedups anyways. raise ImportError plat = '32' if is_python_64bit: plat = '64' # We also accept things as: # # _pydevd_bundle.pydevd_cython_win32_27_32 # _pydevd_bundle.pydevd_cython_win32_34_64 # # to have multiple pre-compiled pyds distributed along the IDE # (generated by build_tools/build_binaries_windows.py). mod_name = 'pydevd_cython_%s_%s%s_%s' % (sys.platform, sys.version_info[0], sys.version_info[1], plat) check_name = '_pydevd_bundle.%s' % (mod_name,) mod = getattr(__import__(check_name), mod_name) # Regardless of how it was found, make sure it's later available as the # initial name so that the expected types from cython in frame eval # are valid. sys.modules['_pydevd_bundle.pydevd_cython'] = mod trace_dispatch = mod.trace_dispatch PyDBAdditionalThreadInfo = mod.PyDBAdditionalThreadInfo set_additional_thread_info = mod.set_additional_thread_info global_cache_skips = mod.global_cache_skips global_cache_frame_skips = mod.global_cache_frame_skips _set_additional_thread_info_lock = mod._set_additional_thread_info_lock fix_top_level_trace_and_get_trace_func = mod.fix_top_level_trace_and_get_trace_func version = getattr(mod, 'version', 0)
1,600
Python
29.207547
106
0.694375
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_stackless.py
from __future__ import nested_scopes import weakref import sys from _pydevd_bundle.pydevd_comm import get_global_debugger from _pydevd_bundle.pydevd_constants import call_only_once from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_custom_frames import update_custom_frame, remove_custom_frame, add_custom_frame import stackless # @UnresolvedImport from _pydev_bundle import pydev_log # Used so that we don't loose the id (because we'll remove when it's not alive and would generate a new id for the # same tasklet). class TaskletToLastId: ''' So, why not a WeakKeyDictionary? The problem is that removals from the WeakKeyDictionary will create a new tasklet (as it adds a callback to remove the key when it's garbage-collected), so, we can get into a recursion. ''' def __init__(self): self.tasklet_ref_to_last_id = {} self._i = 0 def get(self, tasklet): return self.tasklet_ref_to_last_id.get(weakref.ref(tasklet)) def __setitem__(self, tasklet, last_id): self.tasklet_ref_to_last_id[weakref.ref(tasklet)] = last_id self._i += 1 if self._i % 100 == 0: # Collect at each 100 additions to the dict (no need to rush). for tasklet_ref in list(self.tasklet_ref_to_last_id.keys()): if tasklet_ref() is None: del self.tasklet_ref_to_last_id[tasklet_ref] _tasklet_to_last_id = TaskletToLastId() #======================================================================================================================= # _TaskletInfo #======================================================================================================================= class _TaskletInfo: _last_id = 0 def __init__(self, tasklet_weakref, tasklet): self.frame_id = None self.tasklet_weakref = tasklet_weakref last_id = _tasklet_to_last_id.get(tasklet) if last_id is None: _TaskletInfo._last_id += 1 last_id = _TaskletInfo._last_id _tasklet_to_last_id[tasklet] = last_id self._tasklet_id = last_id self.update_name() def update_name(self): tasklet = self.tasklet_weakref() if tasklet: if tasklet.blocked: state = 'blocked' elif tasklet.paused: state = 'paused' elif tasklet.scheduled: state = 'scheduled' else: state = '<UNEXPECTED>' try: name = tasklet.name except AttributeError: if tasklet.is_main: name = 'MainTasklet' else: name = 'Tasklet-%s' % (self._tasklet_id,) thread_id = tasklet.thread_id if thread_id != -1: for thread in threading.enumerate(): if thread.ident == thread_id: if thread.name: thread_name = "of %s" % (thread.name,) else: thread_name = "of Thread-%s" % (thread.name or str(thread_id),) break else: # should not happen. thread_name = "of Thread-%s" % (str(thread_id),) thread = None else: # tasklet is no longer bound to a thread, because its thread ended thread_name = "without thread" tid = id(tasklet) tasklet = None else: state = 'dead' name = 'Tasklet-%s' % (self._tasklet_id,) thread_name = "" tid = '-' self.tasklet_name = '%s %s %s (%s)' % (state, name, thread_name, tid) if not hasattr(stackless.tasklet, "trace_function"): # bug https://bitbucket.org/stackless-dev/stackless/issue/42 # is not fixed. Stackless releases before 2014 def update_name(self): tasklet = self.tasklet_weakref() if tasklet: try: name = tasklet.name except AttributeError: if tasklet.is_main: name = 'MainTasklet' else: name = 'Tasklet-%s' % (self._tasklet_id,) thread_id = tasklet.thread_id for thread in threading.enumerate(): if thread.ident == thread_id: if thread.name: thread_name = "of %s" % (thread.name,) else: thread_name = "of Thread-%s" % (thread.name or str(thread_id),) break else: # should not happen. thread_name = "of Thread-%s" % (str(thread_id),) thread = None tid = id(tasklet) tasklet = None else: name = 'Tasklet-%s' % (self._tasklet_id,) thread_name = "" tid = '-' self.tasklet_name = '%s %s (%s)' % (name, thread_name, tid) _weak_tasklet_registered_to_info = {} #======================================================================================================================= # get_tasklet_info #======================================================================================================================= def get_tasklet_info(tasklet): return register_tasklet_info(tasklet) #======================================================================================================================= # register_tasklet_info #======================================================================================================================= def register_tasklet_info(tasklet): r = weakref.ref(tasklet) info = _weak_tasklet_registered_to_info.get(r) if info is None: info = _weak_tasklet_registered_to_info[r] = _TaskletInfo(r, tasklet) return info _application_set_schedule_callback = None #======================================================================================================================= # _schedule_callback #======================================================================================================================= 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 list(_weak_tasklet_registered_to_info.items()): # 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: # print >>sys.stderr, "SchedCB: %r, %d, '%s', '%s'" % (tasklet, frame.f_lineno, _filename, base) debugger = get_global_debugger() if debugger is not None and debugger.get_file_type(frame) 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) debugger = None 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) if not hasattr(stackless.tasklet, "trace_function"): # Older versions of Stackless, released before 2014 # This code does not work reliable! It is affected by several # stackless bugs: Stackless issues #44, #42, #40 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 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 and next.frame: if hasattr(next.frame, 'f_trace'): next.frame.f_trace = debugger.get_thread_local_trace_func() debugger = None if prev: register_tasklet_info(prev) try: for tasklet_ref, tasklet_info in list(_weak_tasklet_registered_to_info.items()): # 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: if tasklet.paused or tasklet.blocked or tasklet.scheduled: if tasklet.frame and tasklet.frame.f_back: f_back = tasklet.frame.f_back debugger = get_global_debugger() if debugger is not None and debugger.get_file_type(f_back) is None: if tasklet_info.frame_id is None: tasklet_info.frame_id = add_custom_frame(f_back, tasklet_info.tasklet_name, tasklet.thread_id) else: update_custom_frame(tasklet_info.frame_id, f_back, tasklet.thread_id) debugger = None elif tasklet.is_current: 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 f_back = None except: pydev_log.exception() if _application_set_schedule_callback is not None: return _application_set_schedule_callback(prev, next) _original_setup = stackless.tasklet.setup #======================================================================================================================= # setup #======================================================================================================================= def setup(self, *args, **kwargs): ''' Called to run a new tasklet: rebind the creation so that we can trace it. ''' f = self.tempval def new_f(old_f, args, kwargs): debugger = get_global_debugger() if debugger is not None: debugger.enable_tracing() debugger = None # Remove our own traces :) self.tempval = old_f register_tasklet_info(self) # Hover old_f to see the stackless being created and *args and **kwargs to see its parameters. return old_f(*args, **kwargs) # This is the way to tell stackless that the function it should execute is our function, not the original one. Note: # setting tempval is the same as calling bind(new_f), but it seems that there's no other way to get the currently # bound function, so, keeping on using tempval instead of calling bind (which is actually the same thing in a better # API). self.tempval = new_f return _original_setup(self, f, args, kwargs) #======================================================================================================================= # __call__ #======================================================================================================================= def __call__(self, *args, **kwargs): ''' Called to run a new tasklet: rebind the creation so that we can trace it. ''' return setup(self, *args, **kwargs) _original_run = stackless.run #======================================================================================================================= # run #======================================================================================================================= def run(*args, **kwargs): debugger = get_global_debugger() if debugger is not None: debugger.enable_tracing() debugger = None return _original_run(*args, **kwargs) #======================================================================================================================= # patch_stackless #======================================================================================================================= 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 patch_stackless = call_only_once(patch_stackless)
16,909
Python
39.551559
136
0.472411
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch_regular.py
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle.pydev_log import exception as pydev_log_exception from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_constants import (get_current_thread_id, NO_FTRACE, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, ForkSafeLock) from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER # IFDEF CYTHON # from cpython.object cimport PyObject # from cpython.ref cimport Py_INCREF, Py_XDECREF # ELSE from _pydevd_bundle.pydevd_frame import PyDBFrame, is_unhandled_exception # ENDIF # IFDEF CYTHON # cdef dict _global_notify_skipped_step_in # cython_inline_constant: CMD_STEP_INTO = 107 # cython_inline_constant: CMD_STEP_INTO_MY_CODE = 144 # cython_inline_constant: CMD_STEP_RETURN = 109 # cython_inline_constant: CMD_STEP_RETURN_MY_CODE = 160 # ELSE # Note: those are now inlined on cython. CMD_STEP_INTO = 107 CMD_STEP_INTO_MY_CODE = 144 CMD_STEP_RETURN = 109 CMD_STEP_RETURN_MY_CODE = 160 # ENDIF # Cache where we should keep that we completely skipped entering some context. # It needs to be invalidated when: # - Breakpoints are changed # It can be used when running regularly (without step over/step in/step return) global_cache_skips = {} global_cache_frame_skips = {} _global_notify_skipped_step_in = False _global_notify_skipped_step_in_lock = ForkSafeLock() def notify_skipped_step_in_because_of_filters(py_db, frame): global _global_notify_skipped_step_in with _global_notify_skipped_step_in_lock: if _global_notify_skipped_step_in: # Check with lock in place (callers should actually have checked # before without the lock in place due to performance). return _global_notify_skipped_step_in = True py_db.notify_skipped_step_in_because_of_filters(frame) # IFDEF CYTHON # cdef class SafeCallWrapper: # cdef method_object # def __init__(self, method_object): # self.method_object = method_object # def __call__(self, *args): # #Cannot use 'self' once inside the delegate call since we are borrowing the self reference f_trace field # #in the frame, and that reference might get destroyed by set trace on frame and parents # cdef PyObject* method_obj = <PyObject*> self.method_object # Py_INCREF(<object>method_obj) # ret = (<object>method_obj)(*args) # Py_XDECREF (method_obj) # return SafeCallWrapper(ret) if ret is not None else None # def get_method_object(self): # return self.method_object # ELSE # ENDIF def fix_top_level_trace_and_get_trace_func(py_db, frame): # IFDEF CYTHON # cdef str filename; # cdef str name; # cdef tuple args; # ENDIF # Note: this is always the first entry-point in the tracing for any thread. # After entering here we'll set a new tracing function for this thread # where more information is cached (and will also setup the tracing for # frames where we should deal with unhandled exceptions). thread = None # Cache the frame which should be traced to deal with unhandled exceptions. # (i.e.: thread entry-points). f_unhandled = frame # print('called at', f_unhandled.f_code.co_name, f_unhandled.f_code.co_filename, f_unhandled.f_code.co_firstlineno) force_only_unhandled_tracer = False while f_unhandled is not None: # name = splitext(basename(f_unhandled.f_code.co_filename))[0] name = f_unhandled.f_code.co_filename # basename i = name.rfind('/') j = name.rfind('\\') if j > i: i = j if i >= 0: name = name[i + 1:] # remove ext i = name.rfind('.') if i >= 0: name = name[:i] if name == 'threading': if f_unhandled.f_code.co_name in ('__bootstrap', '_bootstrap'): # We need __bootstrap_inner, not __bootstrap. return None, False elif f_unhandled.f_code.co_name in ('__bootstrap_inner', '_bootstrap_inner'): # Note: be careful not to use threading.currentThread to avoid creating a dummy thread. t = f_unhandled.f_locals.get('self') force_only_unhandled_tracer = True if t is not None and isinstance(t, threading.Thread): thread = t break elif name == 'pydev_monkey': if f_unhandled.f_code.co_name == '__call__': force_only_unhandled_tracer = True break elif name == 'pydevd': if f_unhandled.f_code.co_name in ('run', 'main'): # We need to get to _exec return None, False if f_unhandled.f_code.co_name == '_exec': force_only_unhandled_tracer = True break elif name == 'pydevd_tracing': return None, False elif f_unhandled.f_back is None: break f_unhandled = f_unhandled.f_back if thread is None: # Important: don't call threadingCurrentThread if we're in the threading module # to avoid creating dummy threads. if py_db.threading_get_ident is not None: thread = py_db.threading_active.get(py_db.threading_get_ident()) if thread is None: return None, False else: # Jython does not have threading.get_ident(). thread = py_db.threading_current_thread() if getattr(thread, 'pydev_do_not_trace', None): py_db.disable_tracing() return None, False try: additional_info = thread.additional_info if additional_info is None: raise AttributeError() except: additional_info = py_db.set_additional_thread_info(thread) # print('enter thread tracer', thread, get_current_thread_id(thread)) args = (py_db, thread, additional_info, global_cache_skips, global_cache_frame_skips) if f_unhandled is not None: if f_unhandled.f_back is None and not force_only_unhandled_tracer: # Happens when we attach to a running program (cannot reuse instance because it's mutable). top_level_thread_tracer = TopLevelThreadTracerNoBackFrame(ThreadTracer(args), args) additional_info.top_level_thread_tracer_no_back_frames.append(top_level_thread_tracer) # Hack for cython to keep it alive while the thread is alive (just the method in the SetTrace is not enough). else: top_level_thread_tracer = additional_info.top_level_thread_tracer_unhandled if top_level_thread_tracer is None: # Stop in some internal place to report about unhandled exceptions top_level_thread_tracer = TopLevelThreadTracerOnlyUnhandledExceptions(args) additional_info.top_level_thread_tracer_unhandled = top_level_thread_tracer # Hack for cython to keep it alive while the thread is alive (just the method in the SetTrace is not enough). # print(' --> found to trace unhandled', f_unhandled.f_code.co_name, f_unhandled.f_code.co_filename, f_unhandled.f_code.co_firstlineno) f_trace = top_level_thread_tracer.get_trace_dispatch_func() # IFDEF CYTHON # f_trace = SafeCallWrapper(f_trace) # ENDIF f_unhandled.f_trace = f_trace if frame is f_unhandled: return f_trace, False thread_tracer = additional_info.thread_tracer if thread_tracer is None or thread_tracer._args[0] is not py_db: thread_tracer = ThreadTracer(args) additional_info.thread_tracer = thread_tracer # IFDEF CYTHON # return SafeCallWrapper(thread_tracer), True # ELSE return thread_tracer, True # ENDIF def trace_dispatch(py_db, frame, event, arg): thread_trace_func, apply_to_settrace = py_db.fix_top_level_trace_and_get_trace_func(py_db, frame) if thread_trace_func is None: return None if event == 'call' else NO_FTRACE if apply_to_settrace: py_db.enable_tracing(thread_trace_func) return thread_trace_func(frame, event, arg) # IFDEF CYTHON # cdef class TopLevelThreadTracerOnlyUnhandledExceptions: # cdef public tuple _args; # def __init__(self, tuple args): # self._args = args # ELSE class TopLevelThreadTracerOnlyUnhandledExceptions(object): def __init__(self, args): self._args = args # ENDIF def trace_unhandled_exceptions(self, frame, event, arg): # Note that we ignore the frame as this tracing method should only be put in topmost frames already. # print('trace_unhandled_exceptions', event, frame.f_code.co_name, frame.f_code.co_filename, frame.f_code.co_firstlineno) if event == 'exception' and arg is not None: py_db, t, additional_info = self._args[0:3] if arg is not None: if not additional_info.suspended_at_unhandled: additional_info.suspended_at_unhandled = True py_db.stop_on_unhandled_exception(py_db, t, additional_info, arg) # No need to reset frame.f_trace to keep the same trace function. return self.trace_unhandled_exceptions def get_trace_dispatch_func(self): return self.trace_unhandled_exceptions # IFDEF CYTHON # cdef class TopLevelThreadTracerNoBackFrame: # # cdef public object _frame_trace_dispatch; # cdef public tuple _args; # cdef public object try_except_infos; # cdef public object _last_exc_arg; # cdef public set _raise_lines; # cdef public int _last_raise_line; # # def __init__(self, frame_trace_dispatch, tuple args): # self._frame_trace_dispatch = frame_trace_dispatch # self._args = args # self.try_except_infos = None # self._last_exc_arg = None # self._raise_lines = set() # self._last_raise_line = -1 # ELSE class TopLevelThreadTracerNoBackFrame(object): ''' This tracer is pretty special in that it's dealing with a frame without f_back (i.e.: top frame on remote attach or QThread). This means that we have to carefully inspect exceptions to discover whether the exception will be unhandled or not (if we're dealing with an unhandled exception we need to stop as unhandled, otherwise we need to use the regular tracer -- unfortunately the debugger has little info to work with in the tracing -- see: https://bugs.python.org/issue34099, so, we inspect bytecode to determine if some exception will be traced or not... note that if this is not available -- such as on Jython -- we consider any top-level exception to be unnhandled). ''' def __init__(self, frame_trace_dispatch, args): self._frame_trace_dispatch = frame_trace_dispatch self._args = args self.try_except_infos = None self._last_exc_arg = None self._raise_lines = set() self._last_raise_line = -1 # ENDIF def trace_dispatch_and_unhandled_exceptions(self, frame, event, arg): # DEBUG = 'code_to_debug' in frame.f_code.co_filename # if DEBUG: print('trace_dispatch_and_unhandled_exceptions: %s %s %s %s %s %s' % (event, frame.f_code.co_name, frame.f_code.co_filename, frame.f_code.co_firstlineno, self._frame_trace_dispatch, frame.f_lineno)) frame_trace_dispatch = self._frame_trace_dispatch if frame_trace_dispatch is not None: self._frame_trace_dispatch = frame_trace_dispatch(frame, event, arg) if event == 'exception': self._last_exc_arg = arg self._raise_lines.add(frame.f_lineno) self._last_raise_line = frame.f_lineno elif event == 'return' and self._last_exc_arg is not None: # For unhandled exceptions we actually track the return when at the topmost level. try: py_db, t, additional_info = self._args[0:3] if not additional_info.suspended_at_unhandled: # Note: only check it here, don't set. if is_unhandled_exception(self, py_db, frame, self._last_raise_line, self._raise_lines): py_db.stop_on_unhandled_exception(py_db, t, additional_info, self._last_exc_arg) finally: # Remove reference to exception after handling it. self._last_exc_arg = None ret = self.trace_dispatch_and_unhandled_exceptions # Need to reset (the call to _frame_trace_dispatch may have changed it). # IFDEF CYTHON # frame.f_trace = SafeCallWrapper(ret) # ELSE frame.f_trace = ret # ENDIF return ret def get_trace_dispatch_func(self): return self.trace_dispatch_and_unhandled_exceptions # IFDEF CYTHON # cdef class ThreadTracer: # cdef public tuple _args; # def __init__(self, tuple args): # self._args = args # ELSE class ThreadTracer(object): def __init__(self, args): self._args = args # ENDIF def __call__(self, frame, event, arg): ''' This is the callback used when we enter some context in the debugger. We also decorate the thread we are in with info about the debugging. The attributes added are: pydev_state pydev_step_stop pydev_step_cmd pydev_notify_kill :param PyDB py_db: This is the global debugger (this method should actually be added as a method to it). ''' # IFDEF CYTHON # cdef str filename; # cdef str base; # cdef int pydev_step_cmd; # cdef object frame_cache_key; # cdef dict cache_skips; # cdef bint is_stepping; # cdef tuple abs_path_canonical_path_and_base; # cdef PyDBAdditionalThreadInfo additional_info; # ENDIF # DEBUG = 'code_to_debug' in frame.f_code.co_filename # if DEBUG: print('ENTER: trace_dispatch: %s %s %s %s' % (frame.f_code.co_filename, frame.f_lineno, event, frame.f_code.co_name)) py_db, t, additional_info, cache_skips, frame_skips_cache = self._args if additional_info.is_tracing: return None if event == 'call' else NO_FTRACE # we don't wan't to trace code invoked from pydevd_frame.trace_dispatch additional_info.is_tracing += 1 try: pydev_step_cmd = additional_info.pydev_step_cmd is_stepping = pydev_step_cmd != -1 if py_db.pydb_disposed: return None if event == 'call' else NO_FTRACE # if thread is not alive, cancel trace_dispatch processing if not is_thread_alive(t): py_db.notify_thread_not_alive(get_current_thread_id(t)) return None if event == 'call' else NO_FTRACE # Note: it's important that the context name is also given because we may hit something once # in the global context and another in the local context. frame_cache_key = frame.f_code if frame_cache_key in cache_skips: if not is_stepping: # if DEBUG: print('skipped: trace_dispatch (cache hit)', frame_cache_key, frame.f_lineno, event, frame.f_code.co_name) return None if event == 'call' else NO_FTRACE else: # When stepping we can't take into account caching based on the breakpoints (only global filtering). if cache_skips.get(frame_cache_key) == 1: if additional_info.pydev_original_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE) and not _global_notify_skipped_step_in: notify_skipped_step_in_because_of_filters(py_db, frame) back_frame = frame.f_back if back_frame is not None and pydev_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE): back_frame_cache_key = back_frame.f_code if cache_skips.get(back_frame_cache_key) == 1: # if DEBUG: print('skipped: trace_dispatch (cache hit: 1)', frame_cache_key, frame.f_lineno, event, frame.f_code.co_name) return None if event == 'call' else NO_FTRACE else: # if DEBUG: print('skipped: trace_dispatch (cache hit: 2)', frame_cache_key, frame.f_lineno, event, frame.f_code.co_name) return None if event == 'call' else NO_FTRACE try: # Make fast path faster! abs_path_canonical_path_and_base = NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] except: abs_path_canonical_path_and_base = get_abs_path_real_path_and_base_from_frame(frame) file_type = py_db.get_file_type(frame, abs_path_canonical_path_and_base) # we don't want to debug threading or anything related to pydevd if file_type is not None: if file_type == 1: # inlining LIB_FILE = 1 if not py_db.in_project_scope(frame, abs_path_canonical_path_and_base[0]): # if DEBUG: print('skipped: trace_dispatch (not in scope)', abs_path_canonical_path_and_base[2], frame.f_lineno, event, frame.f_code.co_name, file_type) cache_skips[frame_cache_key] = 1 return None if event == 'call' else NO_FTRACE else: # if DEBUG: print('skipped: trace_dispatch', abs_path_canonical_path_and_base[2], frame.f_lineno, event, frame.f_code.co_name, file_type) cache_skips[frame_cache_key] = 1 return None if event == 'call' else NO_FTRACE if py_db.is_files_filter_enabled: if py_db.apply_files_filter(frame, abs_path_canonical_path_and_base[0], False): cache_skips[frame_cache_key] = 1 if is_stepping and additional_info.pydev_original_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE) and not _global_notify_skipped_step_in: notify_skipped_step_in_because_of_filters(py_db, frame) # A little gotcha, sometimes when we're stepping in we have to stop in a # return event showing the back frame as the current frame, so, we need # to check not only the current frame but the back frame too. back_frame = frame.f_back if back_frame is not None and pydev_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE): if py_db.apply_files_filter(back_frame, back_frame.f_code.co_filename, False): back_frame_cache_key = back_frame.f_code cache_skips[back_frame_cache_key] = 1 # if DEBUG: print('skipped: trace_dispatch (filtered out: 1)', frame_cache_key, frame.f_lineno, event, frame.f_code.co_name) return None if event == 'call' else NO_FTRACE else: # if DEBUG: print('skipped: trace_dispatch (filtered out: 2)', frame_cache_key, frame.f_lineno, event, frame.f_code.co_name) return None if event == 'call' else NO_FTRACE # if DEBUG: print('trace_dispatch', filename, frame.f_lineno, event, frame.f_code.co_name, file_type) # Just create PyDBFrame directly (removed support for Python versions < 2.5, which required keeping a weak # reference to the frame). ret = PyDBFrame( ( py_db, abs_path_canonical_path_and_base, additional_info, t, frame_skips_cache, frame_cache_key, ) ).trace_dispatch(frame, event, arg) if ret is None: # 1 means skipped because of filters. # 2 means skipped because no breakpoints were hit. cache_skips[frame_cache_key] = 2 return None if event == 'call' else NO_FTRACE # IFDEF CYTHON # frame.f_trace = SafeCallWrapper(ret) # Make sure we keep the returned tracer. # ELSE frame.f_trace = ret # Make sure we keep the returned tracer. # ENDIF return ret except SystemExit: return None if event == 'call' else NO_FTRACE except Exception: if py_db.pydb_disposed: return None if event == 'call' else NO_FTRACE # Don't log errors when we're shutting down. # Log it try: if pydev_log_exception is not None: # This can actually happen during the interpreter shutdown in Python 2.7 pydev_log_exception() except: # Error logging? We're really in the interpreter shutdown... # (https://github.com/fabioz/PyDev.Debugger/issues/8) pass return None if event == 'call' else NO_FTRACE finally: additional_info.is_tracing -= 1 if USE_CUSTOM_SYS_CURRENT_FRAMES_MAP: # This is far from ideal, as we'll leak frames (we'll always have the last created frame, not really # the last topmost frame saved -- this should be Ok for our usage, but it may leak frames and things # may live longer... as IronPython is garbage-collected, things should live longer anyways, so, it # shouldn't be an issue as big as it's in CPython -- it may still be annoying, but this should # be a reasonable workaround until IronPython itself is able to provide that functionality). # # See: https://github.com/IronLanguages/main/issues/1630 from _pydevd_bundle.pydevd_constants import constructed_tid_to_last_frame _original_call = ThreadTracer.__call__ def __call__(self, frame, event, arg): constructed_tid_to_last_frame[self._args[1].ident] = frame return _original_call(self, frame, event, arg) ThreadTracer.__call__ = __call__
22,202
Python
44.219959
218
0.616836
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_utils.py
from __future__ import nested_scopes import traceback import warnings from _pydev_bundle import pydev_log from _pydev_bundle._pydev_saved_modules import thread, threading from _pydev_bundle import _pydev_saved_modules import signal import os import ctypes from importlib import import_module from urllib.parse import quote # @UnresolvedImport import time import inspect import sys from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \ GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \ get_global_debugger def save_main_module(file, module_name): # patch provided by: Scott Schlesier - when script is run, it does not # use globals from pydevd: # This will prevent the pydevd script from contaminating the namespace for the script to be debugged # pretend pydevd is not the main module, and # convince the file to be debugged that it was loaded as main sys.modules[module_name] = sys.modules['__main__'] sys.modules[module_name].__name__ = module_name with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) warnings.simplefilter("ignore", category=PendingDeprecationWarning) from imp import new_module m = new_module('__main__') sys.modules['__main__'] = m if hasattr(sys.modules[module_name], '__loader__'): m.__loader__ = getattr(sys.modules[module_name], '__loader__') m.__file__ = file return m def is_current_thread_main_thread(): if hasattr(threading, 'main_thread'): return threading.current_thread() is threading.main_thread() else: return isinstance(threading.current_thread(), threading._MainThread) def get_main_thread(): if hasattr(threading, 'main_thread'): return threading.main_thread() else: for t in threading.enumerate(): if isinstance(t, threading._MainThread): return t return None def to_number(x): if is_string(x): try: n = float(x) return n except ValueError: pass l = x.find('(') if l != -1: y = x[0:l - 1] # print y try: n = float(y) return n except ValueError: pass return None def compare_object_attrs_key(x): if GENERATED_LEN_ATTR_NAME == x: as_number = to_number(x) if as_number is None: as_number = 99999999 # len() should appear after other attributes in a list. return (1, as_number) else: return (-1, to_string(x)) def is_string(x): return isinstance(x, str) def to_string(x): if isinstance(x, str): return x else: return str(x) def print_exc(): if traceback: traceback.print_exc() def quote_smart(s, safe='/'): return quote(s, safe) def get_clsname_for_code(code, frame): clsname = None if len(code.co_varnames) > 0: # We are checking the first argument of the function # (`self` or `cls` for methods). first_arg_name = code.co_varnames[0] if first_arg_name in frame.f_locals: first_arg_obj = frame.f_locals[first_arg_name] if inspect.isclass(first_arg_obj): # class method first_arg_class = first_arg_obj else: # instance method if hasattr(first_arg_obj, "__class__"): first_arg_class = first_arg_obj.__class__ else: # old style class, fall back on type first_arg_class = type(first_arg_obj) func_name = code.co_name if hasattr(first_arg_class, func_name): method = getattr(first_arg_class, func_name) func_code = None if hasattr(method, 'func_code'): # Python2 func_code = method.func_code elif hasattr(method, '__code__'): # Python3 func_code = method.__code__ if func_code and func_code == code: clsname = first_arg_class.__name__ return clsname def get_non_pydevd_threads(): threads = threading.enumerate() return [t for t in threads if t and not getattr(t, 'is_pydev_daemon_thread', False)] if USE_CUSTOM_SYS_CURRENT_FRAMES and IS_PYPY: # On PyPy we can use its fake_frames to get the traceback # (instead of the actual real frames that need the tracing to be correct). _tid_to_frame_for_dump_threads = sys._current_frames else: from _pydevd_bundle.pydevd_constants import _current_frames as _tid_to_frame_for_dump_threads def dump_threads(stream=None, show_pydevd_threads=True): ''' Helper to dump thread info. ''' if stream is None: stream = sys.stderr thread_id_to_name_and_is_pydevd_thread = {} try: threading_enumerate = _pydev_saved_modules.pydevd_saved_threading_enumerate if threading_enumerate is None: threading_enumerate = threading.enumerate for t in threading_enumerate(): is_pydevd_thread = getattr(t, 'is_pydev_daemon_thread', False) thread_id_to_name_and_is_pydevd_thread[t.ident] = ( '%s (daemon: %s, pydevd thread: %s)' % (t.name, t.daemon, is_pydevd_thread), is_pydevd_thread ) except: pass stream.write('===============================================================================\n') stream.write('Threads running\n') stream.write('================================= Thread Dump =================================\n') stream.flush() for thread_id, frame in _tid_to_frame_for_dump_threads().items(): name, is_pydevd_thread = thread_id_to_name_and_is_pydevd_thread.get(thread_id, (thread_id, False)) if not show_pydevd_threads and is_pydevd_thread: continue stream.write('\n-------------------------------------------------------------------------------\n') stream.write(" Thread %s" % (name,)) stream.write('\n\n') for i, (filename, lineno, name, line) in enumerate(traceback.extract_stack(frame)): 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 frame.f_locals: stream.write(' self: ') try: stream.write(str(frame.f_locals['self'])) except: stream.write('Unable to get str of: %s' % (type(frame.f_locals['self']),)) stream.write('\n') stream.flush() stream.write('\n=============================== END Thread Dump ===============================') stream.flush() def _extract_variable_nested_braces(char_iter): expression = [] level = 0 for c in char_iter: if c == '{': level += 1 if c == '}': level -= 1 if level == -1: return ''.join(expression).strip() expression.append(c) raise SyntaxError('Unbalanced braces in expression.') def _extract_expression_list(log_message): # Note: not using re because of nested braces. expression = [] expression_vars = [] char_iter = iter(log_message) for c in char_iter: if c == '{': expression_var = _extract_variable_nested_braces(char_iter) if expression_var: expression.append('%s') expression_vars.append(expression_var) else: expression.append(c) expression = ''.join(expression) return expression, expression_vars def convert_dap_log_message_to_expression(log_message): try: expression, expression_vars = _extract_expression_list(log_message) except SyntaxError: return repr('Unbalanced braces in: %s' % (log_message)) if not expression_vars: return repr(expression) # Note: use '%' to be compatible with Python 2.6. return repr(expression) + ' % (' + ', '.join(str(x) for x in expression_vars) + ',)' def notify_about_gevent_if_needed(stream=None): ''' When debugging with gevent check that the gevent flag is used if the user uses the gevent monkey-patching. :return bool: Returns True if a message had to be shown to the user and False otherwise. ''' stream = stream if stream is not None else sys.stderr if not SUPPORT_GEVENT: gevent_monkey = sys.modules.get('gevent.monkey') if gevent_monkey is not None: try: saved = gevent_monkey.saved except AttributeError: pydev_log.exception_once('Error checking for gevent monkey-patching.') return False if saved: # Note: print to stderr as it may deadlock the debugger. sys.stderr.write('%s\n' % (GEVENT_SUPPORT_NOT_SET_MSG,)) return True return False def hasattr_checked(obj, name): try: getattr(obj, name) except: # i.e.: Handle any exception, not only AttributeError. return False else: return True def getattr_checked(obj, name): try: return getattr(obj, name) except: # i.e.: Handle any exception, not only AttributeError. return None def dir_checked(obj): try: return dir(obj) except: return [] def isinstance_checked(obj, cls): try: return isinstance(obj, cls) except: return False class ScopeRequest(object): __slots__ = ['variable_reference', 'scope'] def __init__(self, variable_reference, scope): assert scope in ('globals', 'locals') self.variable_reference = variable_reference self.scope = scope def __eq__(self, o): if isinstance(o, ScopeRequest): return self.variable_reference == o.variable_reference and self.scope == o.scope return False def __ne__(self, o): return not self == o def __hash__(self): return hash((self.variable_reference, self.scope)) class DAPGrouper(object): ''' Note: this is a helper class to group variables on the debug adapter protocol (DAP). For the xml protocol the type is just added to each variable and the UI can group/hide it as needed. ''' SCOPE_SPECIAL_VARS = 'special variables' SCOPE_PROTECTED_VARS = 'protected variables' SCOPE_FUNCTION_VARS = 'function variables' SCOPE_CLASS_VARS = 'class variables' SCOPES_SORTED = [ SCOPE_SPECIAL_VARS, SCOPE_PROTECTED_VARS, SCOPE_FUNCTION_VARS, SCOPE_CLASS_VARS, ] __slots__ = ['variable_reference', 'scope', 'contents_debug_adapter_protocol'] def __init__(self, scope): self.variable_reference = id(self) self.scope = scope self.contents_debug_adapter_protocol = [] def get_contents_debug_adapter_protocol(self): return self.contents_debug_adapter_protocol[:] def __eq__(self, o): if isinstance(o, ScopeRequest): return self.variable_reference == o.variable_reference and self.scope == o.scope return False def __ne__(self, o): return not self == o def __hash__(self): return hash((self.variable_reference, self.scope)) def __repr__(self): return '' def __str__(self): return '' def interrupt_main_thread(main_thread): ''' Generates a KeyboardInterrupt in the main thread by sending a Ctrl+C or by calling thread.interrupt_main(). :param main_thread: Needed because Jython needs main_thread._thread.interrupt() to be called. Note: if unable to send a Ctrl+C, the KeyboardInterrupt will only be raised when the next Python instruction is about to be executed (so, it won't interrupt a sleep(1000)). ''' pydev_log.debug('Interrupt main thread.') called = False try: if os.name == 'posix': # On Linux we can't interrupt 0 as in Windows because it's # actually owned by a process -- on the good side, signals # work much better on Linux! os.kill(os.getpid(), signal.SIGINT) called = True elif os.name == 'nt': # This generates a Ctrl+C only for the current process and not # to the process group! # Note: there doesn't seem to be any public documentation for this # function (although it seems to be present from Windows Server 2003 SP1 onwards # according to: https://www.geoffchappell.com/studies/windows/win32/kernel32/api/index.htm) ctypes.windll.kernel32.CtrlRoutine(0) # The code below is deprecated because it actually sends a Ctrl+C # to the process group, so, if this was a process created without # passing `CREATE_NEW_PROCESS_GROUP` the signal may be sent to the # parent process and to sub-processes too (which is not ideal -- # for instance, when using pytest-xdist, it'll actually stop the # testing, even when called in the subprocess). # if hasattr_checked(signal, 'CTRL_C_EVENT'): # os.kill(0, signal.CTRL_C_EVENT) # else: # # Python 2.6 # ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, 0) called = True except: # If something went wrong, fallback to interrupting when the next # Python instruction is being called. pydev_log.exception('Error interrupting main thread (using fallback).') if not called: try: # In this case, we don't really interrupt a sleep() nor IO operations # (this makes the KeyboardInterrupt be sent only when the next Python # instruction is about to be executed). if hasattr(thread, 'interrupt_main'): thread.interrupt_main() else: main_thread._thread.interrupt() # Jython except: pydev_log.exception('Error on interrupt main thread fallback.') class Timer(object): def __init__(self, min_diff=PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT): self.min_diff = min_diff self._curr_time = time.time() def print_time(self, msg='Elapsed:'): old = self._curr_time new = self._curr_time = time.time() diff = new - old if diff >= self.min_diff: print('%s: %.2fs' % (msg, diff)) def _report_slow(self, compute_msg, *args): old = self._curr_time new = self._curr_time = time.time() diff = new - old if diff >= self.min_diff: py_db = get_global_debugger() if py_db is not None: msg = compute_msg(diff, *args) py_db.writer.add_command(py_db.cmd_factory.make_warning_message(msg)) def report_if_compute_repr_attr_slow(self, attrs_tab_separated, attr_name, attr_type): self._report_slow(self._compute_repr_slow, attrs_tab_separated, attr_name, attr_type) def _compute_repr_slow(self, diff, attrs_tab_separated, attr_name, attr_type): try: attr_type = attr_type.__name__ except: pass if attrs_tab_separated: return 'pydevd warning: Computing repr of %s.%s (%s) was slow (took %.2fs)\n' % ( attrs_tab_separated.replace('\t', '.'), attr_name, attr_type, diff) else: return 'pydevd warning: Computing repr of %s (%s) was slow (took %.2fs)\n' % ( attr_name, attr_type, diff) def report_if_getting_attr_slow(self, cls, attr_name): self._report_slow(self._compute_get_attr_slow, cls, attr_name) def _compute_get_attr_slow(self, diff, cls, attr_name): try: cls = cls.__name__ except: pass return 'pydevd warning: Getting attribute %s.%s was slow (took %.2fs)\n' % (cls, attr_name, diff) def import_attr_from_module(import_with_attr_access): if '.' not in import_with_attr_access: # We need at least one '.' (we don't support just the module import, we need the attribute access too). raise ImportError('Unable to import module with attr access: %s' % (import_with_attr_access,)) module_name, attr_name = import_with_attr_access.rsplit('.', 1) while True: try: mod = import_module(module_name) except ImportError: if '.' not in module_name: raise ImportError('Unable to import module with attr access: %s' % (import_with_attr_access,)) module_name, new_attr_part = module_name.rsplit('.', 1) attr_name = new_attr_part + '.' + attr_name else: # Ok, we got the base module, now, get the attribute we need. try: for attr in attr_name.split('.'): mod = getattr(mod, attr) return mod except: raise ImportError('Unable to import module with attr access: %s' % (import_with_attr_access,))
17,289
Python
32.769531
111
0.583955
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_vars.py
""" pydevd_vars deals with variables: resolution/conversion to XML. """ import pickle from _pydevd_bundle.pydevd_constants import get_frame, get_current_thread_id, \ iter_chars, silence_warnings_decorator, get_global_debugger from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate, get_type, var_to_xml from _pydev_bundle import pydev_log import functools from _pydevd_bundle.pydevd_thread_lifecycle import resume_threads, mark_thread_suspended, suspend_all_threads from _pydevd_bundle.pydevd_comm_constants import CMD_SET_BREAK import sys # @Reimport from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle import pydevd_save_locals, pydevd_timeout, pydevd_constants from _pydev_bundle.pydev_imports import Exec, execfile from _pydevd_bundle.pydevd_utils import to_string import inspect from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals from functools import lru_cache SENTINEL_VALUE = [] class VariableError(RuntimeError): pass def iter_frames(frame): while frame is not None: yield frame frame = frame.f_back frame = None def dump_frames(thread_id): sys.stdout.write('dumping frames\n') if thread_id != get_current_thread_id(threading.current_thread()): raise VariableError("find_frame: must execute on same thread") frame = get_frame() for frame in iter_frames(frame): sys.stdout.write('%s\n' % pickle.dumps(frame)) @silence_warnings_decorator def getVariable(dbg, thread_id, frame_id, scope, attrs): """ returns the value of a variable :scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME BY_ID means we'll traverse the list of all objects alive to get the object. :attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2) :note: when BY_ID is used, the frame_id is considered the id of the object to find and not the frame (as we don't care about the frame in this case). """ if scope == 'BY_ID': if thread_id != get_current_thread_id(threading.current_thread()): raise VariableError("getVariable: must execute on same thread") try: import gc objects = gc.get_objects() except: pass # Not all python variants have it. else: frame_id = int(frame_id) for var in objects: if id(var) == frame_id: if attrs is not None: attrList = attrs.split('\t') for k in attrList: _type, _type_name, resolver = get_type(var) var = resolver.resolve(var, k) return var # If it didn't return previously, we coudn't find it by id (i.e.: alrceady garbage collected). sys.stderr.write('Unable to find object with id: %s\n' % (frame_id,)) return None frame = dbg.find_frame(thread_id, frame_id) if frame is None: return {} if attrs is not None: attrList = attrs.split('\t') else: attrList = [] for attr in attrList: attr.replace("@_@TAB_CHAR@_@", '\t') if scope == 'EXPRESSION': for count in range(len(attrList)): if count == 0: # An Expression can be in any scope (globals/locals), therefore it needs to evaluated as an expression var = evaluate_expression(dbg, frame, attrList[count], False) else: _type, _type_name, resolver = get_type(var) var = resolver.resolve(var, attrList[count]) else: if scope == "GLOBAL": var = frame.f_globals del attrList[0] # globals are special, and they get a single dummy unused attribute else: # in a frame access both locals and globals as Python does var = {} var.update(frame.f_globals) var.update(frame.f_locals) for k in attrList: _type, _type_name, resolver = get_type(var) var = resolver.resolve(var, k) return var def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs): """ Resolve compound variable in debugger scopes by its name and attributes :param thread_id: id of the variable's thread :param frame_id: id of the variable's frame :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME :param attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields """ var = getVariable(dbg, thread_id, frame_id, scope, attrs) try: _type, type_name, resolver = get_type(var) return type_name, resolver.get_dictionary(var) except: pydev_log.exception('Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s.', thread_id, frame_id, scope, attrs) def resolve_var_object(var, attrs): """ Resolve variable's attribute :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a value of resolved variable's attribute """ if attrs is not None: attr_list = attrs.split('\t') else: attr_list = [] for k in attr_list: type, _type_name, resolver = get_type(var) var = resolver.resolve(var, k) return var def resolve_compound_var_object_fields(var, attrs): """ Resolve compound variable by its object and attributes :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields """ attr_list = attrs.split('\t') for k in attr_list: type, _type_name, resolver = get_type(var) var = resolver.resolve(var, k) try: type, _type_name, resolver = get_type(var) return resolver.get_dictionary(var) except: pydev_log.exception() def custom_operation(dbg, thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name): """ We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var. code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed. operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint) """ expressionValue = getVariable(dbg, thread_id, frame_id, scope, attrs) try: namespace = {'__name__': '<custom_operation>'} if style == "EXECFILE": namespace['__file__'] = code_or_file execfile(code_or_file, namespace, namespace) else: # style == EXEC namespace['__file__'] = '<customOperationCode>' Exec(code_or_file, namespace, namespace) return str(namespace[operation_fn_name](expressionValue)) except: pydev_log.exception() @lru_cache(3) def _expression_to_evaluate(expression): keepends = True lines = expression.splitlines(keepends) # find first non-empty line chars_to_strip = 0 for line in lines: if line.strip(): # i.e.: check first non-empty line for c in iter_chars(line): if c.isspace(): chars_to_strip += 1 else: break break if chars_to_strip: # I.e.: check that the chars we'll remove are really only whitespaces. proceed = True new_lines = [] for line in lines: if not proceed: break for c in iter_chars(line[:chars_to_strip]): if not c.isspace(): proceed = False break new_lines.append(line[chars_to_strip:]) if proceed: if isinstance(expression, bytes): expression = b''.join(new_lines) else: expression = u''.join(new_lines) return expression def eval_in_context(expression, global_vars, local_vars, py_db=None): result = None try: compiled = compile_as_eval(expression) is_async = inspect.CO_COROUTINE & compiled.co_flags == inspect.CO_COROUTINE if is_async: if py_db is None: py_db = get_global_debugger() if py_db is None: raise RuntimeError('Cannot evaluate async without py_db.') t = _EvalAwaitInNewEventLoop(py_db, compiled, global_vars, local_vars) t.start() t.join() if t.exc: raise t.exc[1].with_traceback(t.exc[2]) else: result = t.evaluated_value else: result = eval(compiled, global_vars, local_vars) except (Exception, KeyboardInterrupt): etype, result, tb = sys.exc_info() result = ExceptionOnEvaluate(result, etype, tb) # Ok, we have the initial error message, but let's see if we're dealing with a name mangling error... try: if '.__' in expression: # Try to handle '__' name mangling (for simple cases such as self.__variable.__another_var). split = expression.split('.') entry = split[0] if local_vars is None: local_vars = global_vars curr = local_vars[entry] # Note: we want the KeyError if it's not there. for entry in split[1:]: if entry.startswith('__') and not hasattr(curr, entry): entry = '_%s%s' % (curr.__class__.__name__, entry) curr = getattr(curr, entry) result = curr except: pass return result def _run_with_interrupt_thread(original_func, py_db, curr_thread, frame, expression, is_exec): on_interrupt_threads = None timeout_tracker = py_db.timeout_tracker # : :type timeout_tracker: TimeoutTracker interrupt_thread_timeout = pydevd_constants.PYDEVD_INTERRUPT_THREAD_TIMEOUT if interrupt_thread_timeout > 0: on_interrupt_threads = pydevd_timeout.create_interrupt_this_thread_callback() pydev_log.info('Doing evaluate with interrupt threads timeout: %s.', interrupt_thread_timeout) if on_interrupt_threads is None: return original_func(py_db, frame, expression, is_exec) else: with timeout_tracker.call_on_timeout(interrupt_thread_timeout, on_interrupt_threads): return original_func(py_db, frame, expression, is_exec) def _run_with_unblock_threads(original_func, py_db, curr_thread, frame, expression, is_exec): on_timeout_unblock_threads = None timeout_tracker = py_db.timeout_tracker # : :type timeout_tracker: TimeoutTracker if py_db.multi_threads_single_notification: unblock_threads_timeout = pydevd_constants.PYDEVD_UNBLOCK_THREADS_TIMEOUT else: unblock_threads_timeout = -1 # Don't use this if threads are managed individually. if unblock_threads_timeout >= 0: pydev_log.info('Doing evaluate with unblock threads timeout: %s.', unblock_threads_timeout) tid = get_current_thread_id(curr_thread) def on_timeout_unblock_threads(): on_timeout_unblock_threads.called = True pydev_log.info('Resuming threads after evaluate timeout.') resume_threads('*', except_thread=curr_thread) py_db.threads_suspended_single_notification.on_thread_resume(tid) on_timeout_unblock_threads.called = False try: if on_timeout_unblock_threads is None: return _run_with_interrupt_thread(original_func, py_db, curr_thread, frame, expression, is_exec) else: with timeout_tracker.call_on_timeout(unblock_threads_timeout, on_timeout_unblock_threads): return _run_with_interrupt_thread(original_func, py_db, curr_thread, frame, expression, is_exec) finally: if on_timeout_unblock_threads is not None and on_timeout_unblock_threads.called: mark_thread_suspended(curr_thread, CMD_SET_BREAK) py_db.threads_suspended_single_notification.increment_suspend_time() suspend_all_threads(py_db, except_thread=curr_thread) py_db.threads_suspended_single_notification.on_thread_suspend(tid, CMD_SET_BREAK) def _evaluate_with_timeouts(original_func): ''' Provides a decorator that wraps the original evaluate to deal with slow evaluates. If some evaluation is too slow, we may show a message, resume threads or interrupt them as needed (based on the related configurations). ''' @functools.wraps(original_func) def new_func(py_db, frame, expression, is_exec): if py_db is None: # Only for testing... pydev_log.critical('_evaluate_with_timeouts called without py_db!') return original_func(py_db, frame, expression, is_exec) warn_evaluation_timeout = pydevd_constants.PYDEVD_WARN_EVALUATION_TIMEOUT curr_thread = threading.current_thread() def on_warn_evaluation_timeout(): py_db.writer.add_command(py_db.cmd_factory.make_evaluation_timeout_msg( py_db, expression, curr_thread)) timeout_tracker = py_db.timeout_tracker # : :type timeout_tracker: TimeoutTracker with timeout_tracker.call_on_timeout(warn_evaluation_timeout, on_warn_evaluation_timeout): return _run_with_unblock_threads(original_func, py_db, curr_thread, frame, expression, is_exec) return new_func _ASYNC_COMPILE_FLAGS = None try: from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT _ASYNC_COMPILE_FLAGS = PyCF_ALLOW_TOP_LEVEL_AWAIT except: pass def compile_as_eval(expression): ''' :param expression: The expression to be _compiled. :return: code object :raises Exception if the expression cannot be evaluated. ''' expression_to_evaluate = _expression_to_evaluate(expression) if _ASYNC_COMPILE_FLAGS is not None: return compile(expression_to_evaluate, '<string>', 'eval', _ASYNC_COMPILE_FLAGS) else: return compile(expression_to_evaluate, '<string>', 'eval') def _compile_as_exec(expression): ''' :param expression: The expression to be _compiled. :return: code object :raises Exception if the expression cannot be evaluated. ''' expression_to_evaluate = _expression_to_evaluate(expression) if _ASYNC_COMPILE_FLAGS is not None: return compile(expression_to_evaluate, '<string>', 'exec', _ASYNC_COMPILE_FLAGS) else: return compile(expression_to_evaluate, '<string>', 'exec') class _EvalAwaitInNewEventLoop(PyDBDaemonThread): def __init__(self, py_db, compiled, updated_globals, updated_locals): PyDBDaemonThread.__init__(self, py_db) self._compiled = compiled self._updated_globals = updated_globals self._updated_locals = updated_locals # Output self.evaluated_value = None self.exc = None async def _async_func(self): return await eval(self._compiled, self._updated_locals, self._updated_globals) def _on_run(self): try: import asyncio loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.evaluated_value = asyncio.run(self._async_func()) except: self.exc = sys.exc_info() @_evaluate_with_timeouts def evaluate_expression(py_db, frame, expression, is_exec): ''' :param str expression: The expression to be evaluated. Note that if the expression is indented it's automatically dedented (based on the indentation found on the first non-empty line). i.e.: something as: ` def method(): a = 1 ` becomes: ` def method(): a = 1 ` Also, it's possible to evaluate calls with a top-level await (currently this is done by creating a new event loop in a new thread and making the evaluate at that thread -- note that this is still done synchronously so the evaluation has to finish before this function returns). :param is_exec: determines if we should do an exec or an eval. There are some changes in this function depending on whether it's an exec or an eval. When it's an exec (i.e.: is_exec==True): This function returns None. Any exception that happens during the evaluation is reraised. If the expression could actually be evaluated, the variable is printed to the console if not None. When it's an eval (i.e.: is_exec==False): This function returns the result from the evaluation. If some exception happens in this case, the exception is caught and a ExceptionOnEvaluate is returned. Also, in this case we try to resolve name-mangling (i.e.: to be able to add a self.__my_var watch). :param py_db: The debugger. Only needed if some top-level await is detected (for creating a PyDBDaemonThread). ''' if frame is None: return # This is very tricky. Some statements can change locals and use them in the same # call (see https://github.com/microsoft/debugpy/issues/815), also, if locals and globals are # passed separately, it's possible that one gets updated but apparently Python will still # try to load from the other, so, what's done is that we merge all in a single dict and # then go on and update the frame with the results afterwards. # -- see tests in test_evaluate_expression.py # This doesn't work because the variables aren't updated in the locals in case the # evaluation tries to set a variable and use it in the same expression. # updated_globals = frame.f_globals # updated_locals = frame.f_locals # This doesn't work because the variables aren't updated in the locals in case the # evaluation tries to set a variable and use it in the same expression. # updated_globals = {} # updated_globals.update(frame.f_globals) # updated_globals.update(frame.f_locals) # # updated_locals = frame.f_locals # This doesn't work either in the case where the evaluation tries to set a variable and use # it in the same expression (I really don't know why as it seems like this *should* work # in theory but doesn't in practice). # updated_globals = {} # updated_globals.update(frame.f_globals) # # updated_locals = {} # updated_globals.update(frame.f_locals) # This is the only case that worked consistently to run the tests in test_evaluate_expression.py # It's a bit unfortunate because although the exec works in this case, we have to manually # put the updates in the frame locals afterwards. updated_globals = {} updated_globals.update(frame.f_globals) updated_globals.update(frame.f_locals) initial_globals = updated_globals.copy() updated_locals = None try: expression = expression.replace('@LINE@', '\n') if is_exec: try: # Try to make it an eval (if it is an eval we can print it, otherwise we'll exec it and # it will have whatever the user actually did) compiled = compile_as_eval(expression) except Exception: compiled = None if compiled is None: try: compiled = _compile_as_exec(expression) is_async = inspect.CO_COROUTINE & compiled.co_flags == inspect.CO_COROUTINE if is_async: t = _EvalAwaitInNewEventLoop(py_db, compiled, updated_globals, updated_locals) t.start() t.join() if t.exc: raise t.exc[1].with_traceback(t.exc[2]) else: Exec(compiled, updated_globals, updated_locals) finally: # Update the globals even if it errored as it may have partially worked. update_globals_and_locals(updated_globals, initial_globals, frame) else: is_async = inspect.CO_COROUTINE & compiled.co_flags == inspect.CO_COROUTINE if is_async: t = _EvalAwaitInNewEventLoop(py_db, compiled, updated_globals, updated_locals) t.start() t.join() if t.exc: raise t.exc[1].with_traceback(t.exc[2]) else: result = t.evaluated_value else: result = eval(compiled, updated_globals, updated_locals) if result is not None: # Only print if it's not None (as python does) sys.stdout.write('%s\n' % (result,)) return else: ret = eval_in_context(expression, updated_globals, updated_locals, py_db) try: is_exception_returned = ret.__class__ == ExceptionOnEvaluate except: pass else: if not is_exception_returned: # i.e.: by using a walrus assignment (:=), expressions can change the locals, # so, make sure that we save the locals back to the frame. update_globals_and_locals(updated_globals, initial_globals, frame) return ret finally: # Should not be kept alive if an exception happens and this frame is kept in the stack. del updated_globals del updated_locals del initial_globals del frame def change_attr_expression(frame, attr, expression, dbg, value=SENTINEL_VALUE): '''Changes some attribute in a given frame. ''' if frame is None: return try: expression = expression.replace('@LINE@', '\n') if dbg.plugin and value is SENTINEL_VALUE: result = dbg.plugin.change_variable(frame, attr, expression) if result: return result if attr[:7] == "Globals": attr = attr[8:] if attr in frame.f_globals: if value is SENTINEL_VALUE: value = eval(expression, frame.f_globals, frame.f_locals) frame.f_globals[attr] = value return frame.f_globals[attr] else: if '.' not in attr: # i.e.: if we have a '.', we're changing some attribute of a local var. if pydevd_save_locals.is_save_locals_available(): if value is SENTINEL_VALUE: value = eval(expression, frame.f_globals, frame.f_locals) frame.f_locals[attr] = value pydevd_save_locals.save_locals(frame) return frame.f_locals[attr] # i.e.: case with '.' or save locals not available (just exec the assignment in the frame). if value is SENTINEL_VALUE: value = eval(expression, frame.f_globals, frame.f_locals) result = value Exec('%s=%s' % (attr, expression), frame.f_globals, frame.f_locals) return result except Exception: pydev_log.exception() MAXIMUM_ARRAY_SIZE = 100 MAX_SLICE_SIZE = 1000 def table_like_struct_to_xml(array, name, roffset, coffset, rows, cols, format): _, type_name, _ = get_type(array) if type_name == 'ndarray': array, metaxml, r, c, f = array_to_meta_xml(array, name, format) xml = metaxml format = '%' + f if rows == -1 and cols == -1: rows = r cols = c xml += array_to_xml(array, roffset, coffset, rows, cols, format) elif type_name == 'DataFrame': xml = dataframe_to_xml(array, name, roffset, coffset, rows, cols, format) else: raise VariableError("Do not know how to convert type %s to table" % (type_name)) return "<xml>%s</xml>" % xml def array_to_xml(array, roffset, coffset, rows, cols, format): xml = "" rows = min(rows, MAXIMUM_ARRAY_SIZE) cols = min(cols, MAXIMUM_ARRAY_SIZE) # there is no obvious rule for slicing (at least 5 choices) if len(array) == 1 and (rows > 1 or cols > 1): array = array[0] if array.size > len(array): array = array[roffset:, coffset:] rows = min(rows, len(array)) cols = min(cols, len(array[0])) if len(array) == 1: array = array[0] elif array.size == len(array): if roffset == 0 and rows == 1: array = array[coffset:] cols = min(cols, len(array)) elif coffset == 0 and cols == 1: array = array[roffset:] rows = min(rows, len(array)) xml += "<arraydata rows=\"%s\" cols=\"%s\"/>" % (rows, cols) for row in range(rows): xml += "<row index=\"%s\"/>" % to_string(row) for col in range(cols): value = array if rows == 1 or cols == 1: if rows == 1 and cols == 1: value = array[0] else: if rows == 1: dim = col else: dim = row value = array[dim] if "ndarray" in str(type(value)): value = value[0] else: value = array[row][col] value = format % value xml += var_to_xml(value, '') return xml def array_to_meta_xml(array, name, format): type = array.dtype.kind slice = name l = len(array.shape) # initial load, compute slice if format == '%': if l > 2: slice += '[0]' * (l - 2) for r in range(l - 2): array = array[0] if type == 'f': format = '.5f' elif type == 'i' or type == 'u': format = 'd' else: format = 's' else: format = format.replace('%', '') l = len(array.shape) reslice = "" if l > 2: raise Exception("%s has more than 2 dimensions." % slice) elif l == 1: # special case with 1D arrays arr[i, :] - row, but arr[:, i] - column with equal shape and ndim # http://stackoverflow.com/questions/16837946/numpy-a-2-rows-1-column-file-loadtxt-returns-1row-2-columns # explanation: http://stackoverflow.com/questions/15165170/how-do-i-maintain-row-column-orientation-of-vectors-in-numpy?rq=1 # we use kind of a hack - get information about memory from C_CONTIGUOUS is_row = array.flags['C_CONTIGUOUS'] if is_row: rows = 1 cols = min(len(array), MAX_SLICE_SIZE) if cols < len(array): reslice = '[0:%s]' % (cols) array = array[0:cols] else: cols = 1 rows = min(len(array), MAX_SLICE_SIZE) if rows < len(array): reslice = '[0:%s]' % (rows) array = array[0:rows] elif l == 2: rows = min(array.shape[-2], MAX_SLICE_SIZE) cols = min(array.shape[-1], MAX_SLICE_SIZE) if cols < array.shape[-1] or rows < array.shape[-2]: reslice = '[0:%s, 0:%s]' % (rows, cols) array = array[0:rows, 0:cols] # avoid slice duplication if not slice.endswith(reslice): slice += reslice bounds = (0, 0) if type in "biufc": bounds = (array.min(), array.max()) xml = '<array slice=\"%s\" rows=\"%s\" cols=\"%s\" format=\"%s\" type=\"%s\" max=\"%s\" min=\"%s\"/>' % \ (slice, rows, cols, format, type, bounds[1], bounds[0]) return array, xml, rows, cols, format def dataframe_to_xml(df, name, roffset, coffset, rows, cols, format): """ :type df: pandas.core.frame.DataFrame :type name: str :type coffset: int :type roffset: int :type rows: int :type cols: int :type format: str """ num_rows = min(df.shape[0], MAX_SLICE_SIZE) num_cols = min(df.shape[1], MAX_SLICE_SIZE) if (num_rows, num_cols) != df.shape: df = df.iloc[0:num_rows, 0: num_cols] slice = '.iloc[0:%s, 0:%s]' % (num_rows, num_cols) else: slice = '' slice = name + slice xml = '<array slice=\"%s\" rows=\"%s\" cols=\"%s\" format=\"\" type=\"\" max=\"0\" min=\"0\"/>\n' % \ (slice, num_rows, num_cols) if (rows, cols) == (-1, -1): rows, cols = num_rows, num_cols rows = min(rows, MAXIMUM_ARRAY_SIZE) cols = min(min(cols, MAXIMUM_ARRAY_SIZE), num_cols) # need to precompute column bounds here before slicing! col_bounds = [None] * cols for col in range(cols): dtype = df.dtypes.iloc[coffset + col].kind if dtype in "biufc": cvalues = df.iloc[:, coffset + col] bounds = (cvalues.min(), cvalues.max()) else: bounds = (0, 0) col_bounds[col] = bounds df = df.iloc[roffset: roffset + rows, coffset: coffset + cols] rows, cols = df.shape xml += "<headerdata rows=\"%s\" cols=\"%s\">\n" % (rows, cols) format = format.replace('%', '') col_formats = [] get_label = lambda label: str(label) if not isinstance(label, tuple) else '/'.join(map(str, label)) for col in range(cols): dtype = df.dtypes.iloc[col].kind if dtype == 'f' and format: fmt = format elif dtype == 'f': fmt = '.5f' elif dtype == 'i' or dtype == 'u': fmt = 'd' else: fmt = 's' col_formats.append('%' + fmt) bounds = col_bounds[col] xml += '<colheader index=\"%s\" label=\"%s\" type=\"%s\" format=\"%s\" max=\"%s\" min=\"%s\" />\n' % \ (str(col), get_label(df.axes[1].values[col]), dtype, fmt, bounds[1], bounds[0]) for row, label in enumerate(iter(df.axes[0])): xml += "<rowheader index=\"%s\" label = \"%s\"/>\n" % \ (str(row), get_label(label)) xml += "</headerdata>\n" xml += "<arraydata rows=\"%s\" cols=\"%s\"/>\n" % (rows, cols) for row in range(rows): xml += "<row index=\"%s\"/>\n" % str(row) for col in range(cols): value = df.iat[row, col] value = col_formats[col] % value xml += var_to_xml(value, '') return xml
30,786
Python
35.65119
132
0.5878
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_defaults.py
''' This module holds the customization settings for the debugger. ''' from _pydevd_bundle.pydevd_constants import QUOTED_LINE_PROTOCOL class PydevdCustomization(object): DEFAULT_PROTOCOL = QUOTED_LINE_PROTOCOL
217
Python
23.22222
64
0.788018
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_signature.py
from _pydev_bundle import pydev_log try: import trace except ImportError: pass else: trace._warn = lambda *args: None # workaround for http://bugs.python.org/issue17143 (PY-8706) import os from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand from _pydevd_bundle import pydevd_xml from _pydevd_bundle.pydevd_utils import get_clsname_for_code class Signature(object): def __init__(self, file, name): self.file = file self.name = name self.args = [] self.args_str = [] self.return_type = None def add_arg(self, name, type): self.args.append((name, type)) self.args_str.append("%s:%s" % (name, type)) def set_args(self, frame, recursive=False): self.args = [] code = frame.f_code locals = frame.f_locals for i in range(0, code.co_argcount): name = code.co_varnames[i] class_name = get_type_of_value(locals[name], recursive=recursive) self.add_arg(name, class_name) def __str__(self): return "%s %s(%s)" % (self.file, self.name, ", ".join(self.args_str)) def get_type_of_value(value, ignore_module_name=('__main__', '__builtin__', 'builtins'), recursive=False): tp = type(value) class_name = tp.__name__ if class_name == 'instance': # old-style classes tp = value.__class__ class_name = tp.__name__ if hasattr(tp, '__module__') and tp.__module__ and tp.__module__ not in ignore_module_name: class_name = "%s.%s" % (tp.__module__, class_name) if class_name == 'list': class_name = 'List' if len(value) > 0 and recursive: class_name += '[%s]' % get_type_of_value(value[0], recursive=recursive) return class_name if class_name == 'dict': class_name = 'Dict' if len(value) > 0 and recursive: for (k, v) in value.items(): class_name += '[%s, %s]' % (get_type_of_value(k, recursive=recursive), get_type_of_value(v, recursive=recursive)) break return class_name if class_name == 'tuple': class_name = 'Tuple' if len(value) > 0 and recursive: class_name += '[' class_name += ', '.join(get_type_of_value(v, recursive=recursive) for v in value) class_name += ']' return class_name def _modname(path): """Return a plausible module name for the path""" base = os.path.basename(path) filename, ext = os.path.splitext(base) return filename class SignatureFactory(object): def __init__(self): self._caller_cache = {} self.cache = CallSignatureCache() def create_signature(self, frame, filename, with_args=True): try: _, modulename, funcname = self.file_module_function_of(frame) signature = Signature(filename, funcname) if with_args: signature.set_args(frame, recursive=True) return signature except: pydev_log.exception() def file_module_function_of(self, frame): # this code is take from trace module and fixed to work with new-style classes code = frame.f_code filename = code.co_filename if filename: modulename = _modname(filename) else: modulename = None funcname = code.co_name clsname = None if code in self._caller_cache: if self._caller_cache[code] is not None: clsname = self._caller_cache[code] else: self._caller_cache[code] = None clsname = get_clsname_for_code(code, frame) if clsname is not None: # cache the result - assumption is that new.* is # not called later to disturb this relationship # _caller_cache could be flushed if functions in # the new module get called. self._caller_cache[code] = clsname if clsname is not None: funcname = "%s.%s" % (clsname, funcname) return filename, modulename, funcname def get_signature_info(signature): return signature.file, signature.name, ' '.join([arg[1] for arg in signature.args]) def get_frame_info(frame): co = frame.f_code return co.co_name, frame.f_lineno, co.co_filename class CallSignatureCache(object): def __init__(self): self.cache = {} def add(self, signature): filename, name, args_type = get_signature_info(signature) calls_from_file = self.cache.setdefault(filename, {}) name_calls = calls_from_file.setdefault(name, {}) name_calls[args_type] = None def is_in_cache(self, signature): filename, name, args_type = get_signature_info(signature) if args_type in self.cache.get(filename, {}).get(name, {}): return True return False def create_signature_message(signature): cmdTextList = ["<xml>"] cmdTextList.append('<call_signature file="%s" name="%s">' % (pydevd_xml.make_valid_xml_value(signature.file), pydevd_xml.make_valid_xml_value(signature.name))) for arg in signature.args: cmdTextList.append('<arg name="%s" type="%s"></arg>' % (pydevd_xml.make_valid_xml_value(arg[0]), pydevd_xml.make_valid_xml_value(arg[1]))) if signature.return_type is not None: cmdTextList.append('<return type="%s"></return>' % (pydevd_xml.make_valid_xml_value(signature.return_type))) cmdTextList.append("</call_signature></xml>") cmdText = ''.join(cmdTextList) return NetCommand(CMD_SIGNATURE_CALL_TRACE, 0, cmdText) def send_signature_call_trace(dbg, frame, filename): if dbg.signature_factory and dbg.in_project_scope(frame): signature = dbg.signature_factory.create_signature(frame, filename) if signature is not None: if dbg.signature_factory.cache is not None: if not dbg.signature_factory.cache.is_in_cache(signature): dbg.signature_factory.cache.add(signature) dbg.writer.add_command(create_signature_message(signature)) return True else: # we don't send signature if it is cached return False else: dbg.writer.add_command(create_signature_message(signature)) return True return False def send_signature_return_trace(dbg, frame, filename, return_value): if dbg.signature_factory and dbg.in_project_scope(frame): signature = dbg.signature_factory.create_signature(frame, filename, with_args=False) signature.return_type = get_type_of_value(return_value, recursive=True) dbg.writer.add_command(create_signature_message(signature)) return True return False
6,883
Python
33.079208
163
0.599593
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_timeout.py
from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread from _pydevd_bundle.pydevd_constants import thread_get_ident, IS_CPYTHON, NULL import ctypes import time from _pydev_bundle import pydev_log import weakref from _pydevd_bundle.pydevd_utils import is_current_thread_main_thread from _pydevd_bundle import pydevd_utils _DEBUG = False # Default should be False as this can be very verbose. class _TimeoutThread(PyDBDaemonThread): ''' The idea in this class is that it should be usually stopped waiting for the next event to be called (paused in a threading.Event.wait). When a new handle is added it sets the event so that it processes the handles and then keeps on waiting as needed again. This is done so that it's a bit more optimized than creating many Timer threads. ''' def __init__(self, py_db): PyDBDaemonThread.__init__(self, py_db) self._event = threading.Event() self._handles = [] # We could probably do things valid without this lock so that it's possible to add # handles while processing, but the implementation would also be harder to follow, # so, for now, we're either processing or adding handles, not both at the same time. self._lock = threading.Lock() def _on_run(self): wait_time = None while not self._kill_received: if _DEBUG: if wait_time is None: pydev_log.critical('pydevd_timeout: Wait until a new handle is added.') else: pydev_log.critical('pydevd_timeout: Next wait time: %s.', wait_time) self._event.wait(wait_time) if self._kill_received: self._handles = [] return wait_time = self.process_handles() def process_handles(self): ''' :return int: Returns the time we should be waiting for to process the next event properly. ''' with self._lock: if _DEBUG: pydev_log.critical('pydevd_timeout: Processing handles') self._event.clear() handles = self._handles new_handles = self._handles = [] # Do all the processing based on this time (we want to consider snapshots # of processing time -- anything not processed now may be processed at the # next snapshot). curtime = time.time() min_handle_timeout = None for handle in handles: if curtime < handle.abs_timeout and not handle.disposed: # It still didn't time out. if _DEBUG: pydev_log.critical('pydevd_timeout: Handle NOT processed: %s', handle) new_handles.append(handle) if min_handle_timeout is None: min_handle_timeout = handle.abs_timeout elif handle.abs_timeout < min_handle_timeout: min_handle_timeout = handle.abs_timeout else: if _DEBUG: pydev_log.critical('pydevd_timeout: Handle processed: %s', handle) # Timed out (or disposed), so, let's execute it (should be no-op if disposed). handle.exec_on_timeout() if min_handle_timeout is None: return None else: timeout = min_handle_timeout - curtime if timeout <= 0: pydev_log.critical('pydevd_timeout: Expected timeout to be > 0. Found: %s', timeout) return timeout def do_kill_pydev_thread(self): PyDBDaemonThread.do_kill_pydev_thread(self) with self._lock: self._event.set() def add_on_timeout_handle(self, handle): with self._lock: self._handles.append(handle) self._event.set() class _OnTimeoutHandle(object): def __init__(self, tracker, abs_timeout, on_timeout, kwargs): self._str = '_OnTimeoutHandle(%s)' % (on_timeout,) self._tracker = weakref.ref(tracker) self.abs_timeout = abs_timeout self.on_timeout = on_timeout if kwargs is None: kwargs = {} self.kwargs = kwargs self.disposed = False def exec_on_timeout(self): # Note: lock should already be obtained when executing this function. kwargs = self.kwargs on_timeout = self.on_timeout if not self.disposed: self.disposed = True self.kwargs = None self.on_timeout = None try: if _DEBUG: pydev_log.critical('pydevd_timeout: Calling on timeout: %s with kwargs: %s', on_timeout, kwargs) on_timeout(**kwargs) except Exception: pydev_log.exception('pydevd_timeout: Exception on callback timeout.') def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): tracker = self._tracker() if tracker is None: lock = NULL else: lock = tracker._lock with lock: self.disposed = True self.kwargs = None self.on_timeout = None def __str__(self): return self._str __repr__ = __str__ class TimeoutTracker(object): ''' This is a helper class to track the timeout of something. ''' def __init__(self, py_db): self._thread = None self._lock = threading.Lock() self._py_db = weakref.ref(py_db) def call_on_timeout(self, timeout, on_timeout, kwargs=None): ''' This can be called regularly to always execute the given function after a given timeout: call_on_timeout(py_db, 10, on_timeout) Or as a context manager to stop the method from being called if it finishes before the timeout elapses: with call_on_timeout(py_db, 10, on_timeout): ... Note: the callback will be called from a PyDBDaemonThread. ''' with self._lock: if self._thread is None: if _DEBUG: pydev_log.critical('pydevd_timeout: Created _TimeoutThread.') self._thread = _TimeoutThread(self._py_db()) self._thread.start() curtime = time.time() handle = _OnTimeoutHandle(self, curtime + timeout, on_timeout, kwargs) if _DEBUG: pydev_log.critical('pydevd_timeout: Added handle: %s.', handle) self._thread.add_on_timeout_handle(handle) return handle def create_interrupt_this_thread_callback(): ''' The idea here is returning a callback that when called will generate a KeyboardInterrupt in the thread that called this function. If this is the main thread, this means that it'll emulate a Ctrl+C (which may stop I/O and sleep operations). For other threads, this will call PyThreadState_SetAsyncExc to raise a KeyboardInterrupt before the next instruction (so, it won't really interrupt I/O or sleep operations). :return callable: Returns a callback that will interrupt the current thread (this may be called from an auxiliary thread). ''' tid = thread_get_ident() if is_current_thread_main_thread(): main_thread = threading.current_thread() def raise_on_this_thread(): pydev_log.debug('Callback to interrupt main thread.') pydevd_utils.interrupt_main_thread(main_thread) else: # Note: this works in the sense that it can stop some cpu-intensive slow operation, # but we can't really interrupt the thread out of some sleep or I/O operation # (this will only be raised when Python is about to execute the next instruction). def raise_on_this_thread(): if IS_CPYTHON: pydev_log.debug('Interrupt thread: %s', tid) ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(KeyboardInterrupt)) else: pydev_log.debug('It is only possible to interrupt non-main threads in CPython.') return raise_on_this_thread
8,366
Python
33.8625
116
0.590485
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_plugin_utils.py
import types from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_trace_api try: from pydevd_plugins import django_debug except: django_debug = None pydev_log.debug('Unable to load django_debug plugin') try: from pydevd_plugins import jinja2_debug except: jinja2_debug = None pydev_log.debug('Unable to load jinja2_debug plugin') def load_plugins(): plugins = [] if django_debug is not None: plugins.append(django_debug) if jinja2_debug is not None: plugins.append(jinja2_debug) return plugins def bind_func_to_method(func, obj, method_name): bound_method = types.MethodType(func, obj) setattr(obj, method_name, bound_method) return bound_method class PluginManager(object): def __init__(self, main_debugger): self.plugins = load_plugins() self.active_plugins = [] self.main_debugger = main_debugger self.rebind_methods() def add_breakpoint(self, func_name, *args, **kwargs): # add breakpoint for plugin and remember which plugin to use in tracing for plugin in self.plugins: if hasattr(plugin, func_name): func = getattr(plugin, func_name) result = func(self, *args, **kwargs) if result: self.activate(plugin) return result return None def activate(self, plugin): if plugin not in self.active_plugins: self.active_plugins.append(plugin) self.rebind_methods() def rebind_methods(self): if len(self.active_plugins) == 0: self.bind_functions(pydevd_trace_api, getattr, pydevd_trace_api) elif len(self.active_plugins) == 1: self.bind_functions(pydevd_trace_api, getattr, self.active_plugins[0]) else: self.bind_functions(pydevd_trace_api, create_dispatch, self.active_plugins) def bind_functions(self, interface, function_factory, arg): for name in dir(interface): func = function_factory(arg, name) if type(func) == types.FunctionType: bind_func_to_method(func, self, name) def create_dispatch(obj, name): def dispatch(self, *args, **kwargs): result = None for p in self.active_plugins: r = getattr(p, name)(self, *args, **kwargs) if not result: result = r return result return dispatch
2,484
Python
26.010869
87
0.615539
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_extension_utils.py
import pkgutil import sys from _pydev_bundle import pydev_log try: import pydevd_plugins.extensions as extensions except: pydev_log.exception() extensions = None class ExtensionManager(object): def __init__(self): self.loaded_extensions = None self.type_to_instance = {} def _load_modules(self): self.loaded_extensions = [] if extensions: for module_loader, name, ispkg in pkgutil.walk_packages(extensions.__path__, extensions.__name__ + '.'): mod_name = name.split('.')[-1] if not ispkg and mod_name.startswith('pydevd_plugin'): try: __import__(name) module = sys.modules[name] self.loaded_extensions.append(module) except ImportError: pydev_log.critical('Unable to load extension: %s', name) def _ensure_loaded(self): if self.loaded_extensions is None: self._load_modules() def _iter_attr(self): for extension in self.loaded_extensions: dunder_all = getattr(extension, '__all__', None) for attr_name in dir(extension): if not attr_name.startswith('_'): if dunder_all is None or attr_name in dunder_all: yield attr_name, getattr(extension, attr_name) def get_extension_classes(self, extension_type): self._ensure_loaded() if extension_type in self.type_to_instance: return self.type_to_instance[extension_type] handlers = self.type_to_instance.setdefault(extension_type, []) for attr_name, attr in self._iter_attr(): if isinstance(attr, type) and issubclass(attr, extension_type) and attr is not extension_type: try: handlers.append(attr()) except: pydev_log.exception('Unable to load extension class: %s', attr_name) return handlers EXTENSION_MANAGER_INSTANCE = ExtensionManager() def extensions_of_type(extension_type): """ :param T extension_type: The type of the extension hook :rtype: list[T] """ return EXTENSION_MANAGER_INSTANCE.get_extension_classes(extension_type)
2,369
Python
33.852941
106
0.56775
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_command_line_handling.py
import os class ArgHandlerWithParam: ''' Handler for some arguments which needs a value ''' def __init__(self, arg_name, convert_val=None, default_val=None): self.arg_name = arg_name self.arg_v_rep = '--%s' % (arg_name,) self.convert_val = convert_val self.default_val = default_val def to_argv(self, lst, setup): v = setup.get(self.arg_name) if v is not None and v != self.default_val: lst.append(self.arg_v_rep) lst.append('%s' % (v,)) def handle_argv(self, argv, i, setup): assert argv[i] == self.arg_v_rep del argv[i] val = argv[i] if self.convert_val: val = self.convert_val(val) setup[self.arg_name] = val del argv[i] class ArgHandlerBool: ''' If a given flag is received, mark it as 'True' in setup. ''' def __init__(self, arg_name, default_val=False): self.arg_name = arg_name self.arg_v_rep = '--%s' % (arg_name,) self.default_val = default_val def to_argv(self, lst, setup): v = setup.get(self.arg_name) if v: lst.append(self.arg_v_rep) def handle_argv(self, argv, i, setup): assert argv[i] == self.arg_v_rep del argv[i] setup[self.arg_name] = True def convert_ppid(ppid): ret = int(ppid) if ret != 0: if ret == os.getpid(): raise AssertionError( 'ppid passed is the same as the current process pid (%s)!' % (ret,)) return ret ACCEPTED_ARG_HANDLERS = [ ArgHandlerWithParam('port', int, 0), ArgHandlerWithParam('ppid', convert_ppid, 0), ArgHandlerWithParam('vm_type'), ArgHandlerWithParam('client'), ArgHandlerWithParam('access-token'), ArgHandlerWithParam('client-access-token'), ArgHandlerBool('server'), ArgHandlerBool('DEBUG_RECORD_SOCKET_READS'), ArgHandlerBool('multiproc'), # Used by PyCharm (reuses connection: ssh tunneling) ArgHandlerBool('multiprocess'), # Used by PyDev (creates new connection to ide) ArgHandlerBool('save-signatures'), ArgHandlerBool('save-threading'), ArgHandlerBool('save-asyncio'), ArgHandlerBool('print-in-debugger-startup'), ArgHandlerBool('cmd-line'), ArgHandlerBool('module'), ArgHandlerBool('skip-notify-stdin'), # The ones below should've been just one setting to specify the protocol, but for compatibility # reasons they're passed as a flag but are mutually exclusive. ArgHandlerBool('json-dap'), # Protocol used by ptvsd to communicate with pydevd (a single json message in each read) ArgHandlerBool('json-dap-http'), # Actual DAP (json messages over http protocol). ArgHandlerBool('protocol-quoted-line'), # Custom protocol with quoted lines. ArgHandlerBool('protocol-http'), # Custom protocol with http. ] ARGV_REP_TO_HANDLER = {} for handler in ACCEPTED_ARG_HANDLERS: ARGV_REP_TO_HANDLER[handler.arg_v_rep] = handler def get_pydevd_file(): import pydevd f = pydevd.__file__ if f.endswith('.pyc'): f = f[:-1] elif f.endswith('$py.class'): f = f[:-len('$py.class')] + '.py' return f def setup_to_argv(setup, skip_names=None): ''' :param dict setup: A dict previously gotten from process_command_line. :param set skip_names: The names in the setup which shouldn't be converted to argv. :note: does not handle --file nor --DEBUG. ''' if skip_names is None: skip_names = set() ret = [get_pydevd_file()] for handler in ACCEPTED_ARG_HANDLERS: if handler.arg_name in setup and handler.arg_name not in skip_names: handler.to_argv(ret, setup) return ret def process_command_line(argv): """ parses the arguments. removes our arguments from the command line """ setup = {} for handler in ACCEPTED_ARG_HANDLERS: setup[handler.arg_name] = handler.default_val setup['file'] = '' setup['qt-support'] = '' i = 0 del argv[0] while i < len(argv): handler = ARGV_REP_TO_HANDLER.get(argv[i]) if handler is not None: handler.handle_argv(argv, i, setup) elif argv[i].startswith('--qt-support'): # The --qt-support is special because we want to keep backward compatibility: # Previously, just passing '--qt-support' meant that we should use the auto-discovery mode # whereas now, if --qt-support is passed, it should be passed as --qt-support=<mode>, where # mode can be one of 'auto', 'none', 'pyqt5', 'pyqt4', 'pyside', 'pyside2'. if argv[i] == '--qt-support': setup['qt-support'] = 'auto' elif argv[i].startswith('--qt-support='): qt_support = argv[i][len('--qt-support='):] valid_modes = ('none', 'auto', 'pyqt5', 'pyqt4', 'pyside', 'pyside2') if qt_support not in valid_modes: raise ValueError("qt-support mode invalid: " + qt_support) if qt_support == 'none': # On none, actually set an empty string to evaluate to False. setup['qt-support'] = '' else: setup['qt-support'] = qt_support else: raise ValueError("Unexpected definition for qt-support flag: " + argv[i]) del argv[i] elif argv[i] == '--file': # --file is special because it's the last one (so, no handler for it). del argv[i] setup['file'] = argv[i] i = len(argv) # pop out, file is our last argument elif argv[i] == '--DEBUG': from pydevd import set_debug del argv[i] set_debug(setup) else: raise ValueError("Unexpected option: " + argv[i]) return setup
5,906
Python
32
121
0.586861
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_traceproperty.py
'''For debug purpose we are replacing actual builtin property by the debug property ''' from _pydevd_bundle.pydevd_comm import get_global_debugger from _pydev_bundle import pydev_log #======================================================================================================================= # replace_builtin_property #======================================================================================================================= def replace_builtin_property(new_property=None): if new_property is None: new_property = DebugProperty original = property try: import builtins builtins.__dict__['property'] = new_property except: pydev_log.exception() # @Reimport return original #======================================================================================================================= # DebugProperty #======================================================================================================================= class DebugProperty(object): """A custom property which allows python property to get controlled by the debugger and selectively disable/re-enable the tracing. """ def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self global_debugger = get_global_debugger() try: if global_debugger is not None and global_debugger.disable_property_getter_trace: global_debugger.disable_tracing() if self.fget is None: raise AttributeError("unreadable attribute") return self.fget(obj) finally: if global_debugger is not None: global_debugger.enable_tracing() def __set__(self, obj, value): global_debugger = get_global_debugger() try: if global_debugger is not None and global_debugger.disable_property_setter_trace: global_debugger.disable_tracing() if self.fset is None: raise AttributeError("can't set attribute") self.fset(obj, value) finally: if global_debugger is not None: global_debugger.enable_tracing() def __delete__(self, obj): global_debugger = get_global_debugger() try: if global_debugger is not None and global_debugger.disable_property_deleter_trace: global_debugger.disable_tracing() if self.fdel is None: raise AttributeError("can't delete attribute") self.fdel(obj) finally: if global_debugger is not None: global_debugger.enable_tracing() def getter(self, fget): """Overriding getter decorator for the property """ self.fget = fget return self def setter(self, fset): """Overriding setter decorator for the property """ self.fset = fset return self def deleter(self, fdel): """Overriding deleter decorator for the property """ self.fdel = fdel return self
3,279
Python
34.268817
120
0.511741
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command.py
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, \ get_global_debugger, GetGlobalDebugger, set_global_debugger # Keep for backward compatibility @UnusedImport from _pydevd_bundle.pydevd_utils import quote_smart as quote, to_string from _pydevd_bundle.pydevd_comm_constants import ID_TO_MEANING, CMD_EXIT from _pydevd_bundle.pydevd_constants import HTTP_PROTOCOL, HTTP_JSON_PROTOCOL, \ get_protocol, IS_JYTHON, ForkSafeLock import json from _pydev_bundle import pydev_log class _BaseNetCommand(object): # Command id. Should be set in instance. id = -1 # Dict representation of the command to be set in instance. Only set for json commands. as_dict = None def send(self, *args, **kwargs): pass def call_after_send(self, callback): pass class _NullNetCommand(_BaseNetCommand): pass class _NullExitCommand(_NullNetCommand): id = CMD_EXIT # Constant meant to be passed to the writer when the command is meant to be ignored. NULL_NET_COMMAND = _NullNetCommand() # Exit command -- only internal (we don't want/need to send this to the IDE). NULL_EXIT_COMMAND = _NullExitCommand() class NetCommand(_BaseNetCommand): """ Commands received/sent over the network. Command can represent command received from the debugger, or one to be sent by daemon. """ next_seq = 0 # sequence numbers _showing_debug_info = 0 _show_debug_info_lock = ForkSafeLock(rlock=True) _after_send = None def __init__(self, cmd_id, seq, text, is_json=False): """ If sequence is 0, new sequence will be generated (otherwise, this was the response to a command from the client). """ protocol = get_protocol() self.id = cmd_id if seq == 0: NetCommand.next_seq += 2 seq = NetCommand.next_seq self.seq = seq if is_json: if hasattr(text, 'to_dict'): as_dict = text.to_dict(update_ids_to_dap=True) else: assert isinstance(text, dict) as_dict = text as_dict['pydevd_cmd_id'] = cmd_id as_dict['seq'] = seq self.as_dict = as_dict text = json.dumps(as_dict) assert isinstance(text, str) if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: self._show_debug_info(cmd_id, seq, text) if is_json: msg = text else: if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL): encoded = quote(to_string(text), '/<>_=" \t') msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded) else: msg = '%s\t%s\t%s' % (cmd_id, seq, text) if isinstance(msg, str): msg = msg.encode('utf-8') assert isinstance(msg, bytes) as_bytes = msg self._as_bytes = as_bytes def send(self, sock): as_bytes = self._as_bytes try: if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL): sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii')) sock.sendall(as_bytes) if self._after_send: for method in self._after_send: method(sock) except: if IS_JYTHON: # Ignore errors in sock.sendall in Jython (seems to be common for Jython to # give spurious exceptions at interpreter shutdown here). pass else: raise def call_after_send(self, callback): if not self._after_send: self._after_send = [callback] else: self._after_send.append(callback) @classmethod def _show_debug_info(cls, cmd_id, seq, text): with cls._show_debug_info_lock: # Only one thread each time (rlock). if cls._showing_debug_info: # avoid recursing in the same thread (just printing could create # a new command when redirecting output). return cls._showing_debug_info += 1 try: out_message = 'sending cmd (%s) --> ' % (get_protocol(),) out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN') out_message += ' ' out_message += text.replace('\n', ' ') try: pydev_log.critical('%s\n', out_message) except: pass finally: cls._showing_debug_info -= 1
4,588
Python
30.217687
112
0.562772
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_exec2.py
def Exec(exp, global_vars, local_vars=None): if local_vars is not None: exec(exp, global_vars, local_vars) else: exec(exp, global_vars)
159
Python
30.999994
44
0.628931
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_xml.py
from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_extension_utils from _pydevd_bundle import pydevd_resolver import sys from _pydevd_bundle.pydevd_constants import BUILTINS_MODULE_NAME, MAXIMUM_VARIABLE_REPRESENTATION_SIZE, \ RETURN_VALUES_DICT, LOAD_VALUES_ASYNC, DEFAULT_VALUE from _pydev_bundle.pydev_imports import quote from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider from _pydevd_bundle.pydevd_utils import isinstance_checked, hasattr_checked, DAPGrouper from _pydevd_bundle.pydevd_resolver import get_var_scope try: import types frame_type = types.FrameType except: frame_type = None def make_valid_xml_value(s): # Same thing as xml.sax.saxutils.escape but also escaping double quotes. return s.replace("&", "&amp;").replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;') class ExceptionOnEvaluate: def __init__(self, result, etype, tb): self.result = result self.etype = etype self.tb = tb _IS_JYTHON = sys.platform.startswith("java") def _create_default_type_map(): default_type_map = [ # None means that it should not be treated as a compound variable # isintance does not accept a tuple on some versions of python, so, we must declare it expanded (type(None), None,), (int, None), (float, None), (complex, None), (str, None), (tuple, pydevd_resolver.tupleResolver), (list, pydevd_resolver.tupleResolver), (dict, pydevd_resolver.dictResolver), ] try: from collections import OrderedDict default_type_map.insert(0, (OrderedDict, pydevd_resolver.orderedDictResolver)) # we should put it before dict except: pass try: default_type_map.append((long, None)) # @UndefinedVariable except: pass # not available on all python versions default_type_map.append((DAPGrouper, pydevd_resolver.dapGrouperResolver)) try: default_type_map.append((set, pydevd_resolver.setResolver)) except: pass # not available on all python versions try: default_type_map.append((frozenset, pydevd_resolver.setResolver)) except: pass # not available on all python versions try: from django.utils.datastructures import MultiValueDict default_type_map.insert(0, (MultiValueDict, pydevd_resolver.multiValueDictResolver)) # we should put it before dict except: pass # django may not be installed try: from django.forms import BaseForm default_type_map.insert(0, (BaseForm, pydevd_resolver.djangoFormResolver)) # we should put it before instance resolver except: pass # django may not be installed try: from collections import deque default_type_map.append((deque, pydevd_resolver.dequeResolver)) except: pass if frame_type is not None: default_type_map.append((frame_type, pydevd_resolver.frameResolver)) if _IS_JYTHON: from org.python import core # @UnresolvedImport default_type_map.append((core.PyNone, None)) default_type_map.append((core.PyInteger, None)) default_type_map.append((core.PyLong, None)) default_type_map.append((core.PyFloat, None)) default_type_map.append((core.PyComplex, None)) default_type_map.append((core.PyString, None)) default_type_map.append((core.PyTuple, pydevd_resolver.tupleResolver)) default_type_map.append((core.PyList, pydevd_resolver.tupleResolver)) default_type_map.append((core.PyDictionary, pydevd_resolver.dictResolver)) default_type_map.append((core.PyStringMap, pydevd_resolver.dictResolver)) if hasattr(core, 'PyJavaInstance'): # Jython 2.5b3 removed it. default_type_map.append((core.PyJavaInstance, pydevd_resolver.instanceResolver)) return default_type_map class TypeResolveHandler(object): NO_PROVIDER = [] # Sentinel value (any mutable object to be used as a constant would be valid). def __init__(self): # Note: don't initialize with the types we already know about so that the extensions can override # the default resolvers that are already available if they want. self._type_to_resolver_cache = {} self._type_to_str_provider_cache = {} self._initialized = False def _initialize(self): self._default_type_map = _create_default_type_map() self._resolve_providers = pydevd_extension_utils.extensions_of_type(TypeResolveProvider) self._str_providers = pydevd_extension_utils.extensions_of_type(StrPresentationProvider) self._initialized = True def get_type(self, o): try: try: # Faster than type(o) as we don't need the function call. type_object = o.__class__ # could fail here type_name = type_object.__name__ return self._get_type(o, type_object, type_name) # could fail here except: # Not all objects have __class__ (i.e.: there are bad bindings around). type_object = type(o) type_name = type_object.__name__ try: return self._get_type(o, type_object, type_name) except: if isinstance(type_object, type): # If it's still something manageable, use the default resolver, otherwise # fallback to saying that it wasn't possible to get any info on it. return type_object, str(type_name), pydevd_resolver.defaultResolver return 'Unable to get Type', 'Unable to get Type', None except: # This happens for org.python.core.InitModule return 'Unable to get Type', 'Unable to get Type', None def _get_type(self, o, type_object, type_name): # Note: we could have an exception here if the type_object is not hashable... resolver = self._type_to_resolver_cache.get(type_object) if resolver is not None: return type_object, type_name, resolver if not self._initialized: self._initialize() try: for resolver in self._resolve_providers: if resolver.can_provide(type_object, type_name): # Cache it self._type_to_resolver_cache[type_object] = resolver return type_object, type_name, resolver for t in self._default_type_map: if isinstance_checked(o, t[0]): # Cache it resolver = t[1] self._type_to_resolver_cache[type_object] = resolver return (type_object, type_name, resolver) except: pydev_log.exception() # No match return default (and cache it). resolver = pydevd_resolver.defaultResolver self._type_to_resolver_cache[type_object] = resolver return type_object, type_name, resolver if _IS_JYTHON: _base_get_type = _get_type def _get_type(self, o, type_object, type_name): if type_name == 'org.python.core.PyJavaInstance': return type_object, type_name, pydevd_resolver.instanceResolver if type_name == 'org.python.core.PyArray': return type_object, type_name, pydevd_resolver.jyArrayResolver return self._base_get_type(o, type_object, type_name) def str_from_providers(self, o, type_object, type_name): provider = self._type_to_str_provider_cache.get(type_object) if provider is self.NO_PROVIDER: return None if provider is not None: return provider.get_str(o) if not self._initialized: self._initialize() for provider in self._str_providers: if provider.can_provide(type_object, type_name): self._type_to_str_provider_cache[type_object] = provider try: return provider.get_str(o) except: pydev_log.exception("Error when getting str with custom provider: %s." % (provider,)) self._type_to_str_provider_cache[type_object] = self.NO_PROVIDER return None _TYPE_RESOLVE_HANDLER = TypeResolveHandler() """ def get_type(o): Receives object and returns a triple (type_object, type_string, resolver). resolver != None means that variable is a container, and should be displayed as a hierarchy. Use the resolver to get its attributes. All container objects (i.e.: dict, list, tuple, object, etc) should have a resolver. """ get_type = _TYPE_RESOLVE_HANDLER.get_type _str_from_providers = _TYPE_RESOLVE_HANDLER.str_from_providers def is_builtin(x): return getattr(x, '__module__', None) == BUILTINS_MODULE_NAME def should_evaluate_full_value(val): return not LOAD_VALUES_ASYNC or (is_builtin(type(val)) and not isinstance_checked(val, (list, tuple, dict))) def return_values_from_dict_to_xml(return_dict): res = [] for name, val in return_dict.items(): res.append(var_to_xml(val, name, additional_in_xml=' isRetVal="True"')) return ''.join(res) def frame_vars_to_xml(frame_f_locals, hidden_ns=None): """ dumps frame variables to XML <var name="var_name" scope="local" type="type" value="value"/> """ xml = [] keys = sorted(frame_f_locals) return_values_xml = [] for k in keys: try: v = frame_f_locals[k] eval_full_val = should_evaluate_full_value(v) if k == '_pydev_stop_at_break': continue if k == RETURN_VALUES_DICT: for name, val in v.items(): return_values_xml.append(var_to_xml(val, name, additional_in_xml=' isRetVal="True"')) else: if hidden_ns is not None and k in hidden_ns: xml.append(var_to_xml(v, str(k), additional_in_xml=' isIPythonHidden="True"', evaluate_full_value=eval_full_val)) else: xml.append(var_to_xml(v, str(k), evaluate_full_value=eval_full_val)) except Exception: pydev_log.exception("Unexpected error, recovered safely.") # Show return values as the first entry. return_values_xml.extend(xml) return ''.join(return_values_xml) def get_variable_details(val, evaluate_full_value=True, to_string=None): try: # This should be faster than isinstance (but we have to protect against not having a '__class__' attribute). is_exception_on_eval = val.__class__ == ExceptionOnEvaluate except: is_exception_on_eval = False if is_exception_on_eval: v = val.result else: v = val _type, type_name, resolver = get_type(v) type_qualifier = getattr(_type, "__module__", "") if not evaluate_full_value: value = DEFAULT_VALUE else: try: str_from_provider = _str_from_providers(v, _type, type_name) if str_from_provider is not None: value = str_from_provider elif to_string is not None: value = to_string(v) elif hasattr_checked(v, '__class__'): if v.__class__ == frame_type: value = pydevd_resolver.frameResolver.get_frame_name(v) elif v.__class__ in (list, tuple): if len(v) > 300: value = '%s: %s' % (str(v.__class__), '<Too big to print. Len: %s>' % (len(v),)) else: value = '%s: %s' % (str(v.__class__), v) else: try: cName = str(v.__class__) if cName.find('.') != -1: cName = cName.split('.')[-1] elif cName.find("'") != -1: # does not have '.' (could be something like <type 'int'>) cName = cName[cName.index("'") + 1:] if cName.endswith("'>"): cName = cName[:-2] except: cName = str(v.__class__) value = '%s: %s' % (cName, v) else: value = str(v) except: try: value = repr(v) except: value = 'Unable to get repr for %s' % v.__class__ # fix to work with unicode values try: if value.__class__ == bytes: value = value.decode('utf-8', 'replace') except TypeError: pass return type_name, type_qualifier, is_exception_on_eval, resolver, value def var_to_xml(val, name, trim_if_too_big=True, additional_in_xml='', evaluate_full_value=True): """ single variable or dictionary to xml representation """ type_name, type_qualifier, is_exception_on_eval, resolver, value = get_variable_details( val, evaluate_full_value) scope = get_var_scope(name, val, '', True) try: name = quote(name, '/>_= ') # TODO: Fix PY-5834 without using quote except: pass xml = '<var name="%s" type="%s" ' % (make_valid_xml_value(name), make_valid_xml_value(type_name)) if type_qualifier: xml_qualifier = 'qualifier="%s"' % make_valid_xml_value(type_qualifier) else: xml_qualifier = '' if value: # cannot be too big... communication may not handle it. if len(value) > MAXIMUM_VARIABLE_REPRESENTATION_SIZE and trim_if_too_big: value = value[0:MAXIMUM_VARIABLE_REPRESENTATION_SIZE] value += '...' xml_value = ' value="%s"' % (make_valid_xml_value(quote(value, '/>_= '))) else: xml_value = '' if is_exception_on_eval: xml_container = ' isErrorOnEval="True"' else: if resolver is not None: xml_container = ' isContainer="True"' else: xml_container = '' if scope: return ''.join((xml, xml_qualifier, xml_value, xml_container, additional_in_xml, ' scope="', scope, '"', ' />\n')) else: return ''.join((xml, xml_qualifier, xml_value, xml_container, additional_in_xml, ' />\n'))
14,443
Python
35.11
122
0.589767
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py
""" Vendored copy of runpy from the standard library. It's vendored so that we can properly ignore it when used to start user code while still making it possible for the user to debug runpy itself. runpy.py - locating and running Python code using the module namespace Provides support for locating and running Python scripts using the Python module namespace instead of the native filesystem. This allows Python code to play nicely with non-filesystem based PEP 302 importers when locating support scripts as well as when importing modules. """ # Written by Nick Coghlan <ncoghlan at gmail.com> # to implement PEP 338 (Executing Modules as Scripts) import sys import importlib.machinery # importlib first so we can test #15386 via -m import importlib.util import io import types import os __all__ = [ "run_module", "run_path", ] # Note: fabioz: Don't use pkgutil (when handling caught exceptions we could end up # showing exceptions in pkgutil.get_imported (specifically the KeyError), so, # create a copy of the function we need to properly ignore this exception when # running the program. def pkgutil_get_importer(path_item): """Retrieve a finder for the given path item The returned finder is cached in sys.path_importer_cache if it was newly created by a path hook. The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) sys.path_importer_cache.setdefault(path_item, importer) break except ImportError: pass else: importer = None return importer class _TempModule(object): """Temporarily replace a module in sys.modules with an empty namespace""" def __init__(self, mod_name): self.mod_name = mod_name self.module = types.ModuleType(mod_name) self._saved_module = [] def __enter__(self): mod_name = self.mod_name try: self._saved_module.append(sys.modules[mod_name]) except KeyError: pass sys.modules[mod_name] = self.module return self def __exit__(self, *args): if self._saved_module: sys.modules[self.mod_name] = self._saved_module[0] else: del sys.modules[self.mod_name] self._saved_module = [] class _ModifiedArgv0(object): def __init__(self, value): self.value = value self._saved_value = self._sentinel = object() def __enter__(self): if self._saved_value is not self._sentinel: raise RuntimeError("Already preserving saved value") self._saved_value = sys.argv[0] sys.argv[0] = self.value def __exit__(self, *args): self.value = self._sentinel sys.argv[0] = self._saved_value # TODO: Replace these helpers with importlib._bootstrap_external functions. def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_spec=None, pkg_name=None, script_name=None): """Helper to run code in nominated namespace""" if init_globals is not None: run_globals.update(init_globals) if mod_spec is None: loader = None fname = script_name cached = None else: loader = mod_spec.loader fname = mod_spec.origin cached = mod_spec.cached if pkg_name is None: pkg_name = mod_spec.parent run_globals.update(__name__=mod_name, __file__=fname, __cached__=cached, __doc__=None, __loader__=loader, __package__=pkg_name, __spec__=mod_spec) exec(code, run_globals) return run_globals def _run_module_code(code, init_globals=None, mod_name=None, mod_spec=None, pkg_name=None, script_name=None): """Helper to run code in new namespace with sys modified""" fname = script_name if mod_spec is None else mod_spec.origin with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname): mod_globals = temp_module.module.__dict__ _run_code(code, mod_globals, init_globals, mod_name, mod_spec, pkg_name, script_name) # Copy the globals of the temporary module, as they # may be cleared when the temporary module goes away return mod_globals.copy() # Helper to get the full name, spec and code for a module def _get_module_details(mod_name, error=ImportError): if mod_name.startswith("."): raise error("Relative module names not supported") pkg_name, _, _ = mod_name.rpartition(".") if pkg_name: # Try importing the parent to avoid catching initialization errors try: __import__(pkg_name) except ImportError as e: # If the parent or higher ancestor package is missing, let the # error be raised by find_spec() below and then be caught. But do # not allow other errors to be caught. if e.name is None or (e.name != pkg_name and not pkg_name.startswith(e.name + ".")): raise # Warn if the module has already been imported under its normal name existing = sys.modules.get(mod_name) if existing is not None and not hasattr(existing, "__path__"): from warnings import warn msg = "{mod_name!r} found in sys.modules after import of " \ "package {pkg_name!r}, but prior to execution of " \ "{mod_name!r}; this may result in unpredictable " \ "behaviour".format(mod_name=mod_name, pkg_name=pkg_name) warn(RuntimeWarning(msg)) try: spec = importlib.util.find_spec(mod_name) except (ImportError, AttributeError, TypeError, ValueError) as ex: # This hack fixes an impedance mismatch between pkgutil and # importlib, where the latter raises other errors for cases where # pkgutil previously raised ImportError msg = "Error while finding module specification for {!r} ({}: {})" if mod_name.endswith(".py"): msg += (f". Try using '{mod_name[:-3]}' instead of " f"'{mod_name}' as the module name.") raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex if spec is None: raise error("No module named %s" % mod_name) if spec.submodule_search_locations is not None: if mod_name == "__main__" or mod_name.endswith(".__main__"): raise error("Cannot use package as __main__ module") try: pkg_main_name = mod_name + ".__main__" return _get_module_details(pkg_main_name, error) except error as e: if mod_name not in sys.modules: raise # No module loaded; being a package is irrelevant raise error(("%s; %r is a package and cannot " + "be directly executed") % (e, mod_name)) loader = spec.loader if loader is None: raise error("%r is a namespace package and cannot be executed" % mod_name) try: code = loader.get_code(mod_name) except ImportError as e: raise error(format(e)) from e if code is None: raise error("No code object available for %s" % mod_name) return mod_name, spec, code class _Error(Exception): """Error that _run_module_as_main() should report without a traceback""" # XXX ncoghlan: Should this be documented and made public? # (Current thoughts: don't repeat the mistake that lead to its # creation when run_module() no longer met the needs of # mainmodule.c, but couldn't be changed because it was public) def _run_module_as_main(mod_name, alter_argv=True): """Runs the designated module in the __main__ namespace Note that the executed module will have full access to the __main__ namespace. If this is not desirable, the run_module() function should be used to run the module code in a fresh namespace. At the very least, these variables in __main__ will be overwritten: __name__ __file__ __cached__ __loader__ __package__ """ try: if alter_argv or mod_name != "__main__": # i.e. -m switch mod_name, mod_spec, code = _get_module_details(mod_name, _Error) else: # i.e. directory or zipfile execution mod_name, mod_spec, code = _get_main_module_details(_Error) except _Error as exc: msg = "%s: %s" % (sys.executable, exc) sys.exit(msg) main_globals = sys.modules["__main__"].__dict__ if alter_argv: sys.argv[0] = mod_spec.origin return _run_code(code, main_globals, None, "__main__", mod_spec) def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): """Execute a module's code without importing it Returns the resulting top level namespace dictionary """ mod_name, mod_spec, code = _get_module_details(mod_name) if run_name is None: run_name = mod_name if alter_sys: return _run_module_code(code, init_globals, run_name, mod_spec) else: # Leave the sys module alone return _run_code(code, {}, init_globals, run_name, mod_spec) def _get_main_module_details(error=ImportError): # Helper that gives a nicer error message when attempting to # execute a zipfile or directory by invoking __main__.py # Also moves the standard __main__ out of the way so that the # preexisting __loader__ entry doesn't cause issues main_name = "__main__" saved_main = sys.modules[main_name] del sys.modules[main_name] try: return _get_module_details(main_name) except ImportError as exc: if main_name in str(exc): raise error("can't find %r module in %r" % (main_name, sys.path[0])) from exc raise finally: sys.modules[main_name] = saved_main try: io_open_code = io.open_code except AttributeError: # Compatibility with Python 3.6/3.7 import tokenize io_open_code = tokenize.open def _get_code_from_file(run_name, fname): # Check for a compiled file first from pkgutil import read_code decoded_path = os.path.abspath(os.fsdecode(fname)) with io_open_code(decoded_path) as f: code = read_code(f) if code is None: # That didn't work, so try it as normal source code with io_open_code(decoded_path) as f: code = compile(f.read(), fname, 'exec') return code, fname def run_path(path_name, init_globals=None, run_name=None): """Execute code located at the specified filesystem location Returns the resulting top level namespace dictionary The file path may refer directly to a Python script (i.e. one that could be directly executed with execfile) or else it may refer to a zipfile or directory containing a top level __main__.py script. """ if run_name is None: run_name = "<run_path>" pkg_name = run_name.rpartition(".")[0] importer = pkgutil_get_importer(path_name) # Trying to avoid importing imp so as to not consume the deprecation warning. is_NullImporter = False if type(importer).__module__ == 'imp': if type(importer).__name__ == 'NullImporter': is_NullImporter = True if isinstance(importer, type(None)) or is_NullImporter: # Not a valid sys.path entry, so run the code directly # execfile() doesn't help as we want to allow compiled files code, fname = _get_code_from_file(run_name, path_name) return _run_module_code(code, init_globals, run_name, pkg_name=pkg_name, script_name=fname) else: # Finder is defined for path, so add it to # the start of sys.path sys.path.insert(0, path_name) try: # Here's where things are a little different from the run_module # case. There, we only had to replace the module in sys while the # code was running and doing so was somewhat optional. Here, we # have no choice and we have to remove it even while we read the # code. If we don't do this, a __loader__ attribute in the # existing __main__ module may prevent location of the new module. mod_name, mod_spec, code = _get_main_module_details() with _TempModule(run_name) as temp_module, \ _ModifiedArgv0(path_name): mod_globals = temp_module.module.__dict__ return _run_code(code, mod_globals, init_globals, run_name, mod_spec, pkg_name).copy() finally: try: sys.path.remove(path_name) except ValueError: pass if __name__ == "__main__": # Run the module specified as the next command line argument if len(sys.argv) < 2: print("No module specified for execution", file=sys.stderr) else: del sys.argv[0] # Make the requested module sys.argv[0] _run_module_as_main(sys.argv[0])
13,521
Python
37.19774
82
0.607425
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_dont_trace_files.py
# Important: Autogenerated file. # DO NOT edit manually! # DO NOT edit manually! LIB_FILE = 1 PYDEV_FILE = 2 DONT_TRACE_DIRS = { '_pydev_bundle': PYDEV_FILE, '_pydev_runfiles': PYDEV_FILE, '_pydevd_bundle': PYDEV_FILE, '_pydevd_frame_eval': PYDEV_FILE, 'pydev_ipython': PYDEV_FILE, 'pydev_sitecustomize': PYDEV_FILE, 'pydevd_attach_to_process': PYDEV_FILE, 'pydevd_concurrency_analyser': PYDEV_FILE, 'pydevd_plugins': PYDEV_FILE, 'test_pydevd_reload': PYDEV_FILE, } DONT_TRACE = { # commonly used things from the stdlib that we don't want to trace 'Queue.py':LIB_FILE, 'queue.py':LIB_FILE, 'socket.py':LIB_FILE, 'weakref.py':LIB_FILE, '_weakrefset.py':LIB_FILE, 'linecache.py':LIB_FILE, 'threading.py':LIB_FILE, 'dis.py':LIB_FILE, # things from pydev that we don't want to trace '__main__pydevd_gen_debug_adapter_protocol.py': PYDEV_FILE, '_pydev_calltip_util.py': PYDEV_FILE, '_pydev_completer.py': PYDEV_FILE, '_pydev_execfile.py': PYDEV_FILE, '_pydev_filesystem_encoding.py': PYDEV_FILE, '_pydev_getopt.py': PYDEV_FILE, '_pydev_imports_tipper.py': PYDEV_FILE, '_pydev_jy_imports_tipper.py': PYDEV_FILE, '_pydev_log.py': PYDEV_FILE, '_pydev_saved_modules.py': PYDEV_FILE, '_pydev_sys_patch.py': PYDEV_FILE, '_pydev_tipper_common.py': PYDEV_FILE, 'django_debug.py': PYDEV_FILE, 'jinja2_debug.py': PYDEV_FILE, 'pycompletionserver.py': PYDEV_FILE, 'pydev_app_engine_debug_startup.py': PYDEV_FILE, 'pydev_console_utils.py': PYDEV_FILE, 'pydev_import_hook.py': PYDEV_FILE, 'pydev_imports.py': PYDEV_FILE, 'pydev_ipython_console.py': PYDEV_FILE, 'pydev_ipython_console_011.py': PYDEV_FILE, 'pydev_is_thread_alive.py': PYDEV_FILE, 'pydev_localhost.py': PYDEV_FILE, 'pydev_log.py': PYDEV_FILE, 'pydev_monkey.py': PYDEV_FILE, 'pydev_monkey_qt.py': PYDEV_FILE, 'pydev_override.py': PYDEV_FILE, 'pydev_run_in_console.py': PYDEV_FILE, 'pydev_runfiles.py': PYDEV_FILE, 'pydev_runfiles_coverage.py': PYDEV_FILE, 'pydev_runfiles_nose.py': PYDEV_FILE, 'pydev_runfiles_parallel.py': PYDEV_FILE, 'pydev_runfiles_parallel_client.py': PYDEV_FILE, 'pydev_runfiles_pytest2.py': PYDEV_FILE, 'pydev_runfiles_unittest.py': PYDEV_FILE, 'pydev_runfiles_xml_rpc.py': PYDEV_FILE, 'pydev_umd.py': PYDEV_FILE, 'pydev_versioncheck.py': PYDEV_FILE, 'pydevconsole.py': PYDEV_FILE, 'pydevconsole_code.py': PYDEV_FILE, 'pydevd.py': PYDEV_FILE, 'pydevd_additional_thread_info.py': PYDEV_FILE, 'pydevd_additional_thread_info_regular.py': PYDEV_FILE, 'pydevd_api.py': PYDEV_FILE, 'pydevd_base_schema.py': PYDEV_FILE, 'pydevd_breakpoints.py': PYDEV_FILE, 'pydevd_bytecode_utils.py': PYDEV_FILE, 'pydevd_code_to_source.py': PYDEV_FILE, 'pydevd_collect_bytecode_info.py': PYDEV_FILE, 'pydevd_comm.py': PYDEV_FILE, 'pydevd_comm_constants.py': PYDEV_FILE, 'pydevd_command_line_handling.py': PYDEV_FILE, 'pydevd_concurrency_logger.py': PYDEV_FILE, 'pydevd_console.py': PYDEV_FILE, 'pydevd_constants.py': PYDEV_FILE, 'pydevd_custom_frames.py': PYDEV_FILE, 'pydevd_cython_wrapper.py': PYDEV_FILE, 'pydevd_daemon_thread.py': PYDEV_FILE, 'pydevd_defaults.py': PYDEV_FILE, 'pydevd_dont_trace.py': PYDEV_FILE, 'pydevd_dont_trace_files.py': PYDEV_FILE, 'pydevd_exec2.py': PYDEV_FILE, 'pydevd_extension_api.py': PYDEV_FILE, 'pydevd_extension_utils.py': PYDEV_FILE, 'pydevd_file_utils.py': PYDEV_FILE, 'pydevd_filtering.py': PYDEV_FILE, 'pydevd_frame.py': PYDEV_FILE, 'pydevd_frame_eval_cython_wrapper.py': PYDEV_FILE, 'pydevd_frame_eval_main.py': PYDEV_FILE, 'pydevd_frame_tracing.py': PYDEV_FILE, 'pydevd_frame_utils.py': PYDEV_FILE, 'pydevd_gevent_integration.py': PYDEV_FILE, 'pydevd_helpers.py': PYDEV_FILE, 'pydevd_import_class.py': PYDEV_FILE, 'pydevd_io.py': PYDEV_FILE, 'pydevd_json_debug_options.py': PYDEV_FILE, 'pydevd_line_validation.py': PYDEV_FILE, 'pydevd_modify_bytecode.py': PYDEV_FILE, 'pydevd_net_command.py': PYDEV_FILE, 'pydevd_net_command_factory_json.py': PYDEV_FILE, 'pydevd_net_command_factory_xml.py': PYDEV_FILE, 'pydevd_plugin_numpy_types.py': PYDEV_FILE, 'pydevd_plugin_pandas_types.py': PYDEV_FILE, 'pydevd_plugin_utils.py': PYDEV_FILE, 'pydevd_plugins_django_form_str.py': PYDEV_FILE, 'pydevd_process_net_command.py': PYDEV_FILE, 'pydevd_process_net_command_json.py': PYDEV_FILE, 'pydevd_referrers.py': PYDEV_FILE, 'pydevd_reload.py': PYDEV_FILE, 'pydevd_resolver.py': PYDEV_FILE, 'pydevd_runpy.py': PYDEV_FILE, 'pydevd_safe_repr.py': PYDEV_FILE, 'pydevd_save_locals.py': PYDEV_FILE, 'pydevd_schema.py': PYDEV_FILE, 'pydevd_schema_log.py': PYDEV_FILE, 'pydevd_signature.py': PYDEV_FILE, 'pydevd_source_mapping.py': PYDEV_FILE, 'pydevd_stackless.py': PYDEV_FILE, 'pydevd_suspended_frames.py': PYDEV_FILE, 'pydevd_thread_lifecycle.py': PYDEV_FILE, 'pydevd_thread_wrappers.py': PYDEV_FILE, 'pydevd_timeout.py': PYDEV_FILE, 'pydevd_trace_api.py': PYDEV_FILE, 'pydevd_trace_dispatch.py': PYDEV_FILE, 'pydevd_trace_dispatch_regular.py': PYDEV_FILE, 'pydevd_traceproperty.py': PYDEV_FILE, 'pydevd_tracing.py': PYDEV_FILE, 'pydevd_utils.py': PYDEV_FILE, 'pydevd_vars.py': PYDEV_FILE, 'pydevd_vm_type.py': PYDEV_FILE, 'pydevd_xml.py': PYDEV_FILE, } # if we try to trace io.py it seems it can get halted (see http://bugs.python.org/issue4716) DONT_TRACE['io.py'] = LIB_FILE # Don't trace common encodings too DONT_TRACE['cp1252.py'] = LIB_FILE DONT_TRACE['utf_8.py'] = LIB_FILE DONT_TRACE['codecs.py'] = LIB_FILE
5,814
Python
36.75974
92
0.665807
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_referrers.py
import sys from _pydevd_bundle import pydevd_xml from os.path import basename from _pydev_bundle import pydev_log from urllib.parse import unquote_plus from _pydevd_bundle.pydevd_constants import IS_PY311_OR_GREATER #=================================================================================================== # print_var_node #=================================================================================================== def print_var_node(xml_node, stream): name = xml_node.getAttribute('name') value = xml_node.getAttribute('value') val_type = xml_node.getAttribute('type') found_as = xml_node.getAttribute('found_as') stream.write('Name: ') stream.write(unquote_plus(name)) stream.write(', Value: ') stream.write(unquote_plus(value)) stream.write(', Type: ') stream.write(unquote_plus(val_type)) if found_as: stream.write(', Found as: %s' % (unquote_plus(found_as),)) stream.write('\n') #=================================================================================================== # print_referrers #=================================================================================================== def print_referrers(obj, stream=None): if stream is None: stream = sys.stdout result = get_referrer_info(obj) from xml.dom.minidom import parseString dom = parseString(result) xml = dom.getElementsByTagName('xml')[0] for node in xml.childNodes: if node.nodeType == node.TEXT_NODE: continue if node.localName == 'for': stream.write('Searching references for: ') for child in node.childNodes: if child.nodeType == node.TEXT_NODE: continue print_var_node(child, stream) elif node.localName == 'var': stream.write('Referrer found: ') print_var_node(node, stream) else: sys.stderr.write('Unhandled node: %s\n' % (node,)) return result #=================================================================================================== # get_referrer_info #=================================================================================================== def get_referrer_info(searched_obj): DEBUG = 0 if DEBUG: sys.stderr.write('Getting referrers info.\n') try: try: if searched_obj is None: ret = ['<xml>\n'] ret.append('<for>\n') ret.append(pydevd_xml.var_to_xml( searched_obj, 'Skipping getting referrers for None', additional_in_xml=' id="%s"' % (id(searched_obj),))) ret.append('</for>\n') ret.append('</xml>') ret = ''.join(ret) return ret obj_id = id(searched_obj) try: if DEBUG: sys.stderr.write('Getting referrers...\n') import gc referrers = gc.get_referrers(searched_obj) except: pydev_log.exception() ret = ['<xml>\n'] ret.append('<for>\n') ret.append(pydevd_xml.var_to_xml( searched_obj, 'Exception raised while trying to get_referrers.', additional_in_xml=' id="%s"' % (id(searched_obj),))) ret.append('</for>\n') ret.append('</xml>') ret = ''.join(ret) return ret if DEBUG: sys.stderr.write('Found %s referrers.\n' % (len(referrers),)) curr_frame = sys._getframe() frame_type = type(curr_frame) # Ignore this frame and any caller frame of this frame ignore_frames = {} # Should be a set, but it's not available on all python versions. while curr_frame is not None: if basename(curr_frame.f_code.co_filename).startswith('pydev'): ignore_frames[curr_frame] = 1 curr_frame = curr_frame.f_back ret = ['<xml>\n'] ret.append('<for>\n') if DEBUG: sys.stderr.write('Searching Referrers of obj with id="%s"\n' % (obj_id,)) ret.append(pydevd_xml.var_to_xml( searched_obj, 'Referrers of obj with id="%s"' % (obj_id,))) ret.append('</for>\n') curr_frame = sys._getframe() all_objects = None for r in referrers: try: if r in ignore_frames: continue # Skip the references we may add ourselves except: pass # Ok: unhashable type checked... if r is referrers: continue if r is curr_frame.f_locals: continue r_type = type(r) r_id = str(id(r)) representation = str(r_type) found_as = '' if r_type == frame_type: if DEBUG: sys.stderr.write('Found frame referrer: %r\n' % (r,)) for key, val in r.f_locals.items(): if val is searched_obj: found_as = key break elif r_type == dict: if DEBUG: sys.stderr.write('Found dict referrer: %r\n' % (r,)) # Try to check if it's a value in the dict (and under which key it was found) for key, val in r.items(): if val is searched_obj: found_as = key if DEBUG: sys.stderr.write(' Found as %r in dict\n' % (found_as,)) break # Ok, there's one annoying thing: many times we find it in a dict from an instance, # but with this we don't directly have the class, only the dict, so, to workaround that # we iterate over all reachable objects ad check if one of those has the given dict. if all_objects is None: all_objects = gc.get_objects() for x in all_objects: try: if getattr(x, '__dict__', None) is r: r = x r_type = type(x) r_id = str(id(r)) representation = str(r_type) break except: pass # Just ignore any error here (i.e.: ReferenceError, etc.) elif r_type in (tuple, list): if DEBUG: sys.stderr.write('Found tuple referrer: %r\n' % (r,)) for i, x in enumerate(r): if x is searched_obj: found_as = '%s[%s]' % (r_type.__name__, i) if DEBUG: sys.stderr.write(' Found as %s in tuple: \n' % (found_as,)) break elif IS_PY311_OR_GREATER: # Up to Python 3.10, gc.get_referrers for an instance actually returned the # object.__dict__, but on Python 3.11 it returns the actual object, so, # handling is a bit easier (we don't need the workaround from the dict # case to find the actual instance, we just need to find the attribute name). if DEBUG: sys.stderr.write('Found dict referrer: %r\n' % (r,)) dct = getattr(r, '__dict__', None) if dct: # Try to check if it's a value in the dict (and under which key it was found) for key, val in dct.items(): if val is searched_obj: found_as = key if DEBUG: sys.stderr.write(' Found as %r in object instance\n' % (found_as,)) break if found_as: if not isinstance(found_as, str): found_as = str(found_as) found_as = ' found_as="%s"' % (pydevd_xml.make_valid_xml_value(found_as),) ret.append(pydevd_xml.var_to_xml( r, representation, additional_in_xml=' id="%s"%s' % (r_id, found_as))) finally: if DEBUG: sys.stderr.write('Done searching for references.\n') # If we have any exceptions, don't keep dangling references from this frame to any of our objects. all_objects = None referrers = None searched_obj = None r = None x = None key = None val = None curr_frame = None ignore_frames = None except: pydev_log.exception() ret = ['<xml>\n'] ret.append('<for>\n') ret.append(pydevd_xml.var_to_xml( searched_obj, 'Error getting referrers for:', additional_in_xml=' id="%s"' % (id(searched_obj),))) ret.append('</for>\n') ret.append('</xml>') ret = ''.join(ret) return ret ret.append('</xml>') ret = ''.join(ret) return ret
9,756
Python
36.817829
110
0.432554
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command_factory_json.py
from functools import partial import itertools import os import sys import socket as socket_module from _pydev_bundle._pydev_imports_tipper import TYPE_IMPORT, TYPE_CLASS, TYPE_FUNCTION, TYPE_ATTR, \ TYPE_BUILTIN, TYPE_PARAM from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle.pydev_override import overrides from _pydevd_bundle._debug_adapter import pydevd_schema from _pydevd_bundle._debug_adapter.pydevd_schema import ModuleEvent, ModuleEventBody, Module, \ OutputEventBody, OutputEvent, ContinuedEventBody, ExitedEventBody, \ ExitedEvent from _pydevd_bundle.pydevd_comm_constants import CMD_THREAD_CREATE, CMD_RETURN, CMD_MODULE_EVENT, \ CMD_WRITE_TO_CONSOLE, CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, \ CMD_STEP_RETURN, CMD_STEP_CAUGHT_EXCEPTION, CMD_ADD_EXCEPTION_BREAK, CMD_SET_BREAK, \ CMD_SET_NEXT_STATEMENT, CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION, \ CMD_THREAD_RESUME_SINGLE_NOTIFICATION, CMD_THREAD_KILL, CMD_STOP_ON_START, CMD_INPUT_REQUESTED, \ CMD_EXIT, CMD_STEP_INTO_COROUTINE, CMD_STEP_RETURN_MY_CODE, CMD_SMART_STEP_INTO, \ CMD_SET_FUNCTION_BREAK from _pydevd_bundle.pydevd_constants import get_thread_id, ForkSafeLock from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory from _pydevd_bundle.pydevd_utils import get_non_pydevd_threads import pydevd_file_utils from _pydevd_bundle.pydevd_comm import build_exception_info_response from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info from _pydevd_bundle import pydevd_frame_utils, pydevd_constants, pydevd_utils import linecache from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id from io import StringIO class ModulesManager(object): def __init__(self): self._lock = ForkSafeLock() self._modules = {} self._next_id = partial(next, itertools.count(0)) def track_module(self, filename_in_utf8, module_name, frame): ''' :return list(NetCommand): Returns a list with the module events to be sent. ''' if filename_in_utf8 in self._modules: return [] module_events = [] with self._lock: # Must check again after getting the lock. if filename_in_utf8 in self._modules: return try: version = str(frame.f_globals.get('__version__', '')) except: version = '<unknown>' try: package_name = str(frame.f_globals.get('__package__', '')) except: package_name = '<unknown>' module_id = self._next_id() module = Module(module_id, module_name, filename_in_utf8) if version: module.version = version if package_name: # Note: package doesn't appear in the docs but seems to be expected? module.kwargs['package'] = package_name module_event = ModuleEvent(ModuleEventBody('new', module)) module_events.append(NetCommand(CMD_MODULE_EVENT, 0, module_event, is_json=True)) self._modules[filename_in_utf8] = module.to_dict() return module_events def get_modules_info(self): ''' :return list(Module) ''' with self._lock: return list(self._modules.values()) class NetCommandFactoryJson(NetCommandFactory): ''' Factory for commands which will provide messages as json (they should be similar to the debug adapter where possible, although some differences are currently Ok). Note that it currently overrides the xml version so that messages can be done one at a time (any message not overridden will currently use the xml version) -- after having all messages handled, it should no longer use NetCommandFactory as the base class. ''' def __init__(self): NetCommandFactory.__init__(self) self.modules_manager = ModulesManager() @overrides(NetCommandFactory.make_version_message) def make_version_message(self, seq): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_protocol_set_message) def make_protocol_set_message(self, seq): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_thread_created_message) def make_thread_created_message(self, thread): # Note: the thread id for the debug adapter must be an int # (make the actual id from get_thread_id respect that later on). msg = pydevd_schema.ThreadEvent( pydevd_schema.ThreadEventBody('started', get_thread_id(thread)), ) return NetCommand(CMD_THREAD_CREATE, 0, msg, is_json=True) @overrides(NetCommandFactory.make_custom_frame_created_message) def make_custom_frame_created_message(self, frame_id, frame_description): self._additional_thread_id_to_thread_name[frame_id] = frame_description msg = pydevd_schema.ThreadEvent( pydevd_schema.ThreadEventBody('started', frame_id), ) return NetCommand(CMD_THREAD_CREATE, 0, msg, is_json=True) @overrides(NetCommandFactory.make_thread_killed_message) def make_thread_killed_message(self, tid): self._additional_thread_id_to_thread_name.pop(tid, None) msg = pydevd_schema.ThreadEvent( pydevd_schema.ThreadEventBody('exited', tid), ) return NetCommand(CMD_THREAD_KILL, 0, msg, is_json=True) @overrides(NetCommandFactory.make_list_threads_message) def make_list_threads_message(self, py_db, seq): threads = [] for thread in get_non_pydevd_threads(): if is_thread_alive(thread): thread_id = get_thread_id(thread) # Notify that it's created (no-op if we already notified before). py_db.notify_thread_created(thread_id, thread) thread_schema = pydevd_schema.Thread(id=thread_id, name=thread.name) threads.append(thread_schema.to_dict()) for thread_id, thread_name in list(self._additional_thread_id_to_thread_name.items()): thread_schema = pydevd_schema.Thread(id=thread_id, name=thread_name) threads.append(thread_schema.to_dict()) body = pydevd_schema.ThreadsResponseBody(threads) response = pydevd_schema.ThreadsResponse( request_seq=seq, success=True, command='threads', body=body) return NetCommand(CMD_RETURN, 0, response, is_json=True) @overrides(NetCommandFactory.make_get_completions_message) def make_get_completions_message(self, seq, completions, qualifier, start): COMPLETION_TYPE_LOOK_UP = { TYPE_IMPORT: pydevd_schema.CompletionItemType.MODULE, TYPE_CLASS: pydevd_schema.CompletionItemType.CLASS, TYPE_FUNCTION: pydevd_schema.CompletionItemType.FUNCTION, TYPE_ATTR: pydevd_schema.CompletionItemType.FIELD, TYPE_BUILTIN: pydevd_schema.CompletionItemType.KEYWORD, TYPE_PARAM: pydevd_schema.CompletionItemType.VARIABLE, } qualifier = qualifier.lower() qualifier_len = len(qualifier) targets = [] for completion in completions: label = completion[0] if label.lower().startswith(qualifier): completion = pydevd_schema.CompletionItem( label=label, type=COMPLETION_TYPE_LOOK_UP[completion[3]], start=start, length=qualifier_len) targets.append(completion.to_dict()) body = pydevd_schema.CompletionsResponseBody(targets) response = pydevd_schema.CompletionsResponse( request_seq=seq, success=True, command='completions', body=body) return NetCommand(CMD_RETURN, 0, response, is_json=True) def _format_frame_name(self, fmt, initial_name, module_name, line, path): if fmt is None: return initial_name frame_name = initial_name if fmt.get('module', False): if module_name: if initial_name == '<module>': frame_name = module_name else: frame_name = '%s.%s' % (module_name, initial_name) else: basename = os.path.basename(path) basename = basename[0:-3] if basename.lower().endswith('.py') else basename if initial_name == '<module>': frame_name = '%s in %s' % (initial_name, basename) else: frame_name = '%s.%s' % (basename, initial_name) if fmt.get('line', False): frame_name = '%s : %d' % (frame_name, line) return frame_name @overrides(NetCommandFactory.make_get_thread_stack_message) def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0): frames = [] module_events = [] try: # : :type suspended_frames_manager: SuspendedFramesManager suspended_frames_manager = py_db.suspended_frames_manager frames_list = suspended_frames_manager.get_frames_list(thread_id) if frames_list is None: # Could not find stack of suspended frame... if must_be_suspended: return None else: frames_list = pydevd_frame_utils.create_frames_list_from_frame(topmost_frame) for frame_id, frame, method_name, original_filename, filename_in_utf8, lineno, applied_mapping, show_as_current_frame in self._iter_visible_frames_info( py_db, frames_list ): try: module_name = str(frame.f_globals.get('__name__', '')) except: module_name = '<unknown>' module_events.extend(self.modules_manager.track_module(filename_in_utf8, module_name, frame)) presentation_hint = None if not getattr(frame, 'IS_PLUGIN_FRAME', False): # Never filter out plugin frames! if py_db.is_files_filter_enabled and py_db.apply_files_filter(frame, original_filename, False): continue if not py_db.in_project_scope(frame): presentation_hint = 'subtle' formatted_name = self._format_frame_name(fmt, method_name, module_name, lineno, filename_in_utf8) if show_as_current_frame: formatted_name += ' (Current frame)' source_reference = pydevd_file_utils.get_client_filename_source_reference(filename_in_utf8) if not source_reference and not applied_mapping and not os.path.exists(original_filename): if getattr(frame.f_code, 'co_lnotab', None): # Create a source-reference to be used where we provide the source by decompiling the code. # Note: When the time comes to retrieve the source reference in this case, we'll # check the linecache first (see: get_decompiled_source_from_frame_id). source_reference = pydevd_file_utils.create_source_reference_for_frame_id(frame_id, original_filename) else: # Check if someone added a source reference to the linecache (Python attrs does this). if linecache.getline(original_filename, 1): source_reference = pydevd_file_utils.create_source_reference_for_linecache( original_filename) frames.append(pydevd_schema.StackFrame( frame_id, formatted_name, lineno, column=1, source={ 'path': filename_in_utf8, 'sourceReference': source_reference, }, presentationHint=presentation_hint).to_dict()) finally: topmost_frame = None for module_event in module_events: py_db.writer.add_command(module_event) total_frames = len(frames) stack_frames = frames if bool(levels): start = start_frame end = min(start + levels, total_frames) stack_frames = frames[start:end] response = pydevd_schema.StackTraceResponse( request_seq=seq, success=True, command='stackTrace', body=pydevd_schema.StackTraceResponseBody(stackFrames=stack_frames, totalFrames=total_frames)) return NetCommand(CMD_RETURN, 0, response, is_json=True) @overrides(NetCommandFactory.make_warning_message) def make_warning_message(self, msg): category = 'important' body = OutputEventBody(msg, category) event = OutputEvent(body) return NetCommand(CMD_WRITE_TO_CONSOLE, 0, event, is_json=True) @overrides(NetCommandFactory.make_io_message) def make_io_message(self, msg, ctx): category = 'stdout' if int(ctx) == 1 else 'stderr' body = OutputEventBody(msg, category) event = OutputEvent(body) return NetCommand(CMD_WRITE_TO_CONSOLE, 0, event, is_json=True) _STEP_REASONS = set([ CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE, CMD_STEP_INTO_MY_CODE, CMD_STOP_ON_START, CMD_STEP_INTO_COROUTINE, CMD_SMART_STEP_INTO, ]) _EXCEPTION_REASONS = set([ CMD_STEP_CAUGHT_EXCEPTION, CMD_ADD_EXCEPTION_BREAK, ]) @overrides(NetCommandFactory.make_thread_suspend_single_notification) def make_thread_suspend_single_notification(self, py_db, thread_id, stop_reason): exc_desc = None exc_name = None thread = pydevd_find_thread_by_id(thread_id) info = set_additional_thread_info(thread) preserve_focus_hint = False if stop_reason in self._STEP_REASONS: if info.pydev_original_step_cmd == CMD_STOP_ON_START: # Just to make sure that's not set as the original reason anymore. info.pydev_original_step_cmd = -1 stop_reason = 'entry' else: stop_reason = 'step' elif stop_reason in self._EXCEPTION_REASONS: stop_reason = 'exception' elif stop_reason == CMD_SET_BREAK: stop_reason = 'breakpoint' elif stop_reason == CMD_SET_FUNCTION_BREAK: stop_reason = 'function breakpoint' elif stop_reason == CMD_SET_NEXT_STATEMENT: stop_reason = 'goto' else: stop_reason = 'pause' preserve_focus_hint = True if stop_reason == 'exception': exception_info_response = build_exception_info_response( py_db, thread_id, -1, set_additional_thread_info, self._iter_visible_frames_info, max_frames=-1) exception_info_response exc_name = exception_info_response.body.exceptionId exc_desc = exception_info_response.body.description body = pydevd_schema.StoppedEventBody( reason=stop_reason, description=exc_desc, threadId=thread_id, text=exc_name, allThreadsStopped=True, preserveFocusHint=preserve_focus_hint, ) event = pydevd_schema.StoppedEvent(body) return NetCommand(CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION, 0, event, is_json=True) @overrides(NetCommandFactory.make_thread_resume_single_notification) def make_thread_resume_single_notification(self, thread_id): body = ContinuedEventBody(threadId=thread_id, allThreadsContinued=True) event = pydevd_schema.ContinuedEvent(body) return NetCommand(CMD_THREAD_RESUME_SINGLE_NOTIFICATION, 0, event, is_json=True) @overrides(NetCommandFactory.make_set_next_stmnt_status_message) def make_set_next_stmnt_status_message(self, seq, is_success, exception_msg): response = pydevd_schema.GotoResponse( request_seq=int(seq), success=is_success, command='goto', body={}, message=(None if is_success else exception_msg)) return NetCommand(CMD_RETURN, 0, response, is_json=True) @overrides(NetCommandFactory.make_send_curr_exception_trace_message) def make_send_curr_exception_trace_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_send_curr_exception_trace_proceeded_message) def make_send_curr_exception_trace_proceeded_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_send_breakpoint_exception_message) def make_send_breakpoint_exception_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_process_created_message) def make_process_created_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_process_about_to_be_replaced_message) def make_process_about_to_be_replaced_message(self): event = ExitedEvent(ExitedEventBody(-1, pydevdReason="processReplaced")) cmd = NetCommand(CMD_RETURN, 0, event, is_json=True) def after_send(socket): socket.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_NODELAY, 1) cmd.call_after_send(after_send) return cmd @overrides(NetCommandFactory.make_thread_suspend_message) def make_thread_suspend_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_thread_run_message) def make_thread_run_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_reloaded_code_message) def make_reloaded_code_message(self, *args, **kwargs): return NULL_NET_COMMAND # Not a part of the debug adapter protocol @overrides(NetCommandFactory.make_input_requested_message) def make_input_requested_message(self, started): event = pydevd_schema.PydevdInputRequestedEvent(body={}) return NetCommand(CMD_INPUT_REQUESTED, 0, event, is_json=True) @overrides(NetCommandFactory.make_skipped_step_in_because_of_filters) def make_skipped_step_in_because_of_filters(self, py_db, frame): msg = 'Frame skipped from debugging during step-in.' if py_db.get_use_libraries_filter(): msg += ('\nNote: may have been skipped because of "justMyCode" option (default == true). ' 'Try setting \"justMyCode\": false in the debug configuration (e.g., launch.json).\n') return self.make_warning_message(msg) @overrides(NetCommandFactory.make_evaluation_timeout_msg) def make_evaluation_timeout_msg(self, py_db, expression, curr_thread): msg = '''Evaluating: %s did not finish after %.2f seconds. This may mean a number of things: - This evaluation is really slow and this is expected. In this case it's possible to silence this error by raising the timeout, setting the PYDEVD_WARN_EVALUATION_TIMEOUT environment variable to a bigger value. - The evaluation may need other threads running while it's running: In this case, it's possible to set the PYDEVD_UNBLOCK_THREADS_TIMEOUT environment variable so that if after a given timeout an evaluation doesn't finish, other threads are unblocked or you can manually resume all threads. Alternatively, it's also possible to skip breaking on a particular thread by setting a `pydev_do_not_trace = True` attribute in the related threading.Thread instance (if some thread should always be running and no breakpoints are expected to be hit in it). - The evaluation is deadlocked: In this case you may set the PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT environment variable to true so that a thread dump is shown along with this message and optionally, set the PYDEVD_INTERRUPT_THREAD_TIMEOUT to some value so that the debugger tries to interrupt the evaluation (if possible) when this happens. ''' % (expression, pydevd_constants.PYDEVD_WARN_EVALUATION_TIMEOUT) if pydevd_constants.PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT: stream = StringIO() pydevd_utils.dump_threads(stream, show_pydevd_threads=False) msg += '\n\n%s\n' % stream.getvalue() return self.make_warning_message(msg) @overrides(NetCommandFactory.make_exit_command) def make_exit_command(self, py_db): event = pydevd_schema.TerminatedEvent(pydevd_schema.TerminatedEventBody()) return NetCommand(CMD_EXIT, 0, event, is_json=True)
21,328
Python
43.903158
164
0.644599
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_api.py
import sys import bisect import types from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle import pydevd_utils, pydevd_source_mapping from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info from _pydevd_bundle.pydevd_comm import (InternalGetThreadStack, internal_get_completions, InternalSetNextStatementThread, internal_reload_code, InternalGetVariable, InternalGetArray, InternalLoadFullValue, internal_get_description, internal_get_frame, internal_evaluate_expression, InternalConsoleExec, internal_get_variable_json, internal_change_variable, internal_change_variable_json, internal_evaluate_expression_json, internal_set_expression_json, internal_get_exception_details_json, internal_step_in_thread, internal_smart_step_into) from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, file_system_encoding, CMD_STEP_INTO_MY_CODE, CMD_STOP_ON_START, CMD_SMART_STEP_INTO) from _pydevd_bundle.pydevd_constants import (get_current_thread_id, set_protocol, get_protocol, HTTP_JSON_PROTOCOL, JSON_PROTOCOL, DebugInfoHolder, IS_WINDOWS) from _pydevd_bundle.pydevd_net_command_factory_json import NetCommandFactoryJson from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory import pydevd_file_utils from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_breakpoints import LineBreakpoint from pydevd_tracing import get_exception_traceback_str import os import subprocess import ctypes from _pydevd_bundle.pydevd_collect_bytecode_info import code_to_bytecode_representation import itertools import linecache from _pydevd_bundle.pydevd_utils import DAPGrouper from _pydevd_bundle.pydevd_daemon_thread import run_as_pydevd_daemon_thread from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads import tokenize try: import dis except ImportError: def _get_code_lines(code): raise NotImplementedError else: def _get_code_lines(code): if not isinstance(code, types.CodeType): path = code with tokenize.open(path) as f: src = f.read() code = compile(src, path, 'exec', 0, dont_inherit=True) return _get_code_lines(code) def iterate(): # First, get all line starts for this code object. This does not include # bodies of nested class and function definitions, as they have their # own objects. for _, lineno in dis.findlinestarts(code): yield lineno # For nested class and function definitions, their respective code objects # are constants referenced by this object. for const in code.co_consts: if isinstance(const, types.CodeType) and const.co_filename == code.co_filename: for lineno in _get_code_lines(const): yield lineno return iterate() class PyDevdAPI(object): class VariablePresentation(object): def __init__(self, special='group', function='group', class_='group', protected='inline'): self._presentation = { DAPGrouper.SCOPE_SPECIAL_VARS: special, DAPGrouper.SCOPE_FUNCTION_VARS: function, DAPGrouper.SCOPE_CLASS_VARS: class_, DAPGrouper.SCOPE_PROTECTED_VARS: protected, } def get_presentation(self, scope): return self._presentation[scope] def run(self, py_db): py_db.ready_to_run = True def notify_initialize(self, py_db): py_db.on_initialize() def notify_configuration_done(self, py_db): py_db.on_configuration_done() def notify_disconnect(self, py_db): py_db.on_disconnect() def set_protocol(self, py_db, seq, protocol): set_protocol(protocol.strip()) if get_protocol() in (HTTP_JSON_PROTOCOL, JSON_PROTOCOL): cmd_factory_class = NetCommandFactoryJson else: cmd_factory_class = NetCommandFactory if not isinstance(py_db.cmd_factory, cmd_factory_class): py_db.cmd_factory = cmd_factory_class() return py_db.cmd_factory.make_protocol_set_message(seq) def set_ide_os_and_breakpoints_by(self, py_db, seq, ide_os, breakpoints_by): ''' :param ide_os: 'WINDOWS' or 'UNIX' :param breakpoints_by: 'ID' or 'LINE' ''' if breakpoints_by == 'ID': py_db._set_breakpoints_with_id = True else: py_db._set_breakpoints_with_id = False self.set_ide_os(ide_os) return py_db.cmd_factory.make_version_message(seq) def set_ide_os(self, ide_os): ''' :param ide_os: 'WINDOWS' or 'UNIX' ''' pydevd_file_utils.set_ide_os(ide_os) def set_gui_event_loop(self, py_db, gui_event_loop): py_db._gui_event_loop = gui_event_loop def send_error_message(self, py_db, msg): cmd = py_db.cmd_factory.make_warning_message('pydevd: %s\n' % (msg,)) py_db.writer.add_command(cmd) def set_show_return_values(self, py_db, show_return_values): if show_return_values: py_db.show_return_values = True else: if py_db.show_return_values: # We should remove saved return values py_db.remove_return_values_flag = True py_db.show_return_values = False pydev_log.debug("Show return values: %s", py_db.show_return_values) def list_threads(self, py_db, seq): # Response is the command with the list of threads to be added to the writer thread. return py_db.cmd_factory.make_list_threads_message(py_db, seq) def request_suspend_thread(self, py_db, thread_id='*'): # Yes, thread suspend is done at this point, not through an internal command. threads = [] suspend_all = thread_id.strip() == '*' if suspend_all: threads = pydevd_utils.get_non_pydevd_threads() elif thread_id.startswith('__frame__:'): sys.stderr.write("Can't suspend tasklet: %s\n" % (thread_id,)) else: threads = [pydevd_find_thread_by_id(thread_id)] for t in threads: if t is None: continue py_db.set_suspend( t, CMD_THREAD_SUSPEND, suspend_other_threads=suspend_all, is_pause=True, ) # Break here (even if it's suspend all) as py_db.set_suspend will # take care of suspending other threads. break def set_enable_thread_notifications(self, py_db, enable): ''' When disabled, no thread notifications (for creation/removal) will be issued until it's re-enabled. Note that when it's re-enabled, a creation notification will be sent for all existing threads even if it was previously sent (this is meant to be used on disconnect/reconnect). ''' py_db.set_enable_thread_notifications(enable) def request_disconnect(self, py_db, resume_threads): self.set_enable_thread_notifications(py_db, False) self.remove_all_breakpoints(py_db, '*') self.remove_all_exception_breakpoints(py_db) self.notify_disconnect(py_db) if resume_threads: self.request_resume_thread(thread_id='*') def request_resume_thread(self, thread_id): resume_threads(thread_id) def request_completions(self, py_db, seq, thread_id, frame_id, act_tok, line=-1, column=-1): py_db.post_method_as_internal_command( thread_id, internal_get_completions, seq, thread_id, frame_id, act_tok, line=line, column=column) def request_stack(self, py_db, seq, thread_id, fmt=None, timeout=.5, start_frame=0, levels=0): # If it's already suspended, get it right away. internal_get_thread_stack = InternalGetThreadStack( seq, thread_id, py_db, set_additional_thread_info, fmt=fmt, timeout=timeout, start_frame=start_frame, levels=levels) if internal_get_thread_stack.can_be_executed_by(get_current_thread_id(threading.current_thread())): internal_get_thread_stack.do_it(py_db) else: py_db.post_internal_command(internal_get_thread_stack, '*') def request_exception_info_json(self, py_db, request, thread_id, max_frames): py_db.post_method_as_internal_command( thread_id, internal_get_exception_details_json, request, thread_id, max_frames, set_additional_thread_info=set_additional_thread_info, iter_visible_frames_info=py_db.cmd_factory._iter_visible_frames_info, ) def request_step(self, py_db, thread_id, step_cmd_id): t = pydevd_find_thread_by_id(thread_id) if t: py_db.post_method_as_internal_command( thread_id, internal_step_in_thread, thread_id, step_cmd_id, set_additional_thread_info=set_additional_thread_info, ) elif thread_id.startswith('__frame__:'): sys.stderr.write("Can't make tasklet step command: %s\n" % (thread_id,)) def request_smart_step_into(self, py_db, seq, thread_id, offset, child_offset): t = pydevd_find_thread_by_id(thread_id) if t: py_db.post_method_as_internal_command( thread_id, internal_smart_step_into, thread_id, offset, child_offset, set_additional_thread_info=set_additional_thread_info) elif thread_id.startswith('__frame__:'): sys.stderr.write("Can't set next statement in tasklet: %s\n" % (thread_id,)) def request_smart_step_into_by_func_name(self, py_db, seq, thread_id, line, func_name): # Same thing as set next, just with a different cmd id. self.request_set_next(py_db, seq, thread_id, CMD_SMART_STEP_INTO, None, line, func_name) def request_set_next(self, py_db, seq, thread_id, set_next_cmd_id, original_filename, line, func_name): ''' set_next_cmd_id may actually be one of: CMD_RUN_TO_LINE CMD_SET_NEXT_STATEMENT CMD_SMART_STEP_INTO -- note: request_smart_step_into is preferred if it's possible to work with bytecode offset. :param Optional[str] original_filename: If available, the filename may be source translated, otherwise no translation will take place (the set next just needs the line afterwards as it executes locally, but for the Jupyter integration, the source mapping may change the actual lines and not only the filename). ''' t = pydevd_find_thread_by_id(thread_id) if t: if original_filename is not None: translated_filename = self.filename_to_server(original_filename) # Apply user path mapping. pydev_log.debug('Set next (after path translation) in: %s line: %s', translated_filename, line) func_name = self.to_str(func_name) assert translated_filename.__class__ == str # i.e.: bytes on py2 and str on py3 assert func_name.__class__ == str # i.e.: bytes on py2 and str on py3 # Apply source mapping (i.e.: ipython). _source_mapped_filename, new_line, multi_mapping_applied = py_db.source_mapping.map_to_server( translated_filename, line) if multi_mapping_applied: pydev_log.debug('Set next (after source mapping) in: %s line: %s', translated_filename, line) line = new_line int_cmd = InternalSetNextStatementThread(thread_id, set_next_cmd_id, line, func_name, seq=seq) py_db.post_internal_command(int_cmd, thread_id) elif thread_id.startswith('__frame__:'): sys.stderr.write("Can't set next statement in tasklet: %s\n" % (thread_id,)) def request_reload_code(self, py_db, seq, module_name, filename): ''' :param seq: if -1 no message will be sent back when the reload is done. Note: either module_name or filename may be None (but not both at the same time). ''' thread_id = '*' # Any thread # Note: not going for the main thread because in this case it'd only do the load # when we stopped on a breakpoint. py_db.post_method_as_internal_command( thread_id, internal_reload_code, seq, module_name, filename) def request_change_variable(self, py_db, seq, thread_id, frame_id, scope, attr, value): ''' :param scope: 'FRAME' or 'GLOBAL' ''' py_db.post_method_as_internal_command( thread_id, internal_change_variable, seq, thread_id, frame_id, scope, attr, value) def request_get_variable(self, py_db, seq, thread_id, frame_id, scope, attrs): ''' :param scope: 'FRAME' or 'GLOBAL' ''' int_cmd = InternalGetVariable(seq, thread_id, frame_id, scope, attrs) py_db.post_internal_command(int_cmd, thread_id) def request_get_array(self, py_db, seq, roffset, coffset, rows, cols, fmt, thread_id, frame_id, scope, attrs): int_cmd = InternalGetArray(seq, roffset, coffset, rows, cols, fmt, thread_id, frame_id, scope, attrs) py_db.post_internal_command(int_cmd, thread_id) def request_load_full_value(self, py_db, seq, thread_id, frame_id, vars): int_cmd = InternalLoadFullValue(seq, thread_id, frame_id, vars) py_db.post_internal_command(int_cmd, thread_id) def request_get_description(self, py_db, seq, thread_id, frame_id, expression): py_db.post_method_as_internal_command( thread_id, internal_get_description, seq, thread_id, frame_id, expression) def request_get_frame(self, py_db, seq, thread_id, frame_id): py_db.post_method_as_internal_command( thread_id, internal_get_frame, seq, thread_id, frame_id) def to_str(self, s): ''' -- in py3 raises an error if it's not str already. ''' if s.__class__ != str: raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (s, s.__class__)) return s def filename_to_str(self, filename): ''' -- in py3 raises an error if it's not str already. ''' if filename.__class__ != str: raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (filename, filename.__class__)) return filename def filename_to_server(self, filename): filename = self.filename_to_str(filename) filename = pydevd_file_utils.map_file_to_server(filename) return filename class _DummyFrame(object): ''' Dummy frame to be used with PyDB.apply_files_filter (as we don't really have the related frame as breakpoints are added before execution). ''' class _DummyCode(object): def __init__(self, filename): self.co_firstlineno = 1 self.co_filename = filename self.co_name = 'invalid func name ' def __init__(self, filename): self.f_code = self._DummyCode(filename) self.f_globals = {} ADD_BREAKPOINT_NO_ERROR = 0 ADD_BREAKPOINT_FILE_NOT_FOUND = 1 ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS = 2 # This means that the breakpoint couldn't be fully validated (more runtime # information may be needed). ADD_BREAKPOINT_LAZY_VALIDATION = 3 ADD_BREAKPOINT_INVALID_LINE = 4 class _AddBreakpointResult(object): # :see: ADD_BREAKPOINT_NO_ERROR = 0 # :see: ADD_BREAKPOINT_FILE_NOT_FOUND = 1 # :see: ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS = 2 # :see: ADD_BREAKPOINT_LAZY_VALIDATION = 3 # :see: ADD_BREAKPOINT_INVALID_LINE = 4 __slots__ = ['error_code', 'breakpoint_id', 'translated_filename', 'translated_line', 'original_line'] def __init__(self, breakpoint_id, translated_filename, translated_line, original_line): self.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR self.breakpoint_id = breakpoint_id self.translated_filename = translated_filename self.translated_line = translated_line self.original_line = original_line def add_breakpoint( self, py_db, original_filename, breakpoint_type, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint, adjust_line=False, on_changed_breakpoint_state=None): ''' :param str original_filename: Note: must be sent as it was received in the protocol. It may be translated in this function and its final value will be available in the returned _AddBreakpointResult. :param str breakpoint_type: One of: 'python-line', 'django-line', 'jinja2-line'. :param int breakpoint_id: :param int line: Note: it's possible that a new line was actually used. If that's the case its final value will be available in the returned _AddBreakpointResult. :param condition: Either None or the condition to activate the breakpoint. :param str func_name: If "None" (str), may hit in any context. Empty string will hit only top level. Any other value must match the scope of the method to be matched. :param str expression: None or the expression to be evaluated. :param suspend_policy: Either "NONE" (to suspend only the current thread when the breakpoint is hit) or "ALL" (to suspend all threads when a breakpoint is hit). :param str hit_condition: An expression where `@HIT@` will be replaced by the number of hits. i.e.: `@HIT@ == x` or `@HIT@ >= x` :param bool is_logpoint: If True and an expression is passed, pydevd will create an io message command with the result of the evaluation. :param bool adjust_line: If True, the breakpoint line should be adjusted if the current line doesn't really match an executable line (if possible). :param callable on_changed_breakpoint_state: This is called when something changed internally on the breakpoint after it was initially added (for instance, template file_to_line_to_breakpoints could be signaled as invalid initially and later when the related template is loaded, if the line is valid it could be marked as valid). The signature for the callback should be: on_changed_breakpoint_state(breakpoint_id: int, add_breakpoint_result: _AddBreakpointResult) Note that the add_breakpoint_result should not be modified by the callback (the implementation may internally reuse the same instance multiple times). :return _AddBreakpointResult: ''' assert original_filename.__class__ == str, 'Expected str, found: %s' % (original_filename.__class__,) # i.e.: bytes on py2 and str on py3 original_filename_normalized = pydevd_file_utils.normcase_from_client(original_filename) pydev_log.debug('Request for breakpoint in: %s line: %s', original_filename, line) original_line = line # Parameters to reapply breakpoint. api_add_breakpoint_params = (original_filename, breakpoint_type, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint) translated_filename = self.filename_to_server(original_filename) # Apply user path mapping. pydev_log.debug('Breakpoint (after path translation) in: %s line: %s', translated_filename, line) func_name = self.to_str(func_name) assert translated_filename.__class__ == str # i.e.: bytes on py2 and str on py3 assert func_name.__class__ == str # i.e.: bytes on py2 and str on py3 # Apply source mapping (i.e.: ipython). source_mapped_filename, new_line, multi_mapping_applied = py_db.source_mapping.map_to_server( translated_filename, line) if multi_mapping_applied: pydev_log.debug('Breakpoint (after source mapping) in: %s line: %s', source_mapped_filename, new_line) # Note that source mapping is internal and does not change the resulting filename nor line # (we want the outside world to see the line in the original file and not in the ipython # cell, otherwise the editor wouldn't be correct as the returned line is the line to # which the breakpoint will be moved in the editor). result = self._AddBreakpointResult(breakpoint_id, original_filename, line, original_line) # If a multi-mapping was applied, consider it the canonical / source mapped version (translated to ipython cell). translated_absolute_filename = source_mapped_filename canonical_normalized_filename = pydevd_file_utils.normcase(source_mapped_filename) line = new_line else: translated_absolute_filename = pydevd_file_utils.absolute_path(translated_filename) canonical_normalized_filename = pydevd_file_utils.canonical_normalized_path(translated_filename) if adjust_line and not translated_absolute_filename.startswith('<'): # Validate file_to_line_to_breakpoints and adjust their positions. try: lines = sorted(_get_code_lines(translated_absolute_filename)) except Exception: pass else: if line not in lines: # Adjust to the first preceding valid line. idx = bisect.bisect_left(lines, line) if idx > 0: line = lines[idx - 1] result = self._AddBreakpointResult(breakpoint_id, original_filename, line, original_line) py_db.api_received_breakpoints[(original_filename_normalized, breakpoint_id)] = (canonical_normalized_filename, api_add_breakpoint_params) if not translated_absolute_filename.startswith('<'): # Note: if a mapping pointed to a file starting with '<', don't validate. if not pydevd_file_utils.exists(translated_absolute_filename): result.error_code = self.ADD_BREAKPOINT_FILE_NOT_FOUND return result if ( py_db.is_files_filter_enabled and not py_db.get_require_module_for_filters() and py_db.apply_files_filter(self._DummyFrame(translated_absolute_filename), translated_absolute_filename, False) ): # Note that if `get_require_module_for_filters()` returns False, we don't do this check. # This is because we don't have the module name given a file at this point (in # runtime it's gotten from the frame.f_globals). # An option could be calculate it based on the filename and current sys.path, # but on some occasions that may be wrong (for instance with `__main__` or if # the user dynamically changes the PYTHONPATH). # Note: depending on the use-case, filters may be changed, so, keep on going and add the # breakpoint even with the error code. result.error_code = self.ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS if breakpoint_type == 'python-line': added_breakpoint = LineBreakpoint( breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition=hit_condition, is_logpoint=is_logpoint) file_to_line_to_breakpoints = py_db.breakpoints file_to_id_to_breakpoint = py_db.file_to_id_to_line_breakpoint supported_type = True else: add_plugin_breakpoint_result = None plugin = py_db.get_plugin_lazy_init() if plugin is not None: add_plugin_breakpoint_result = plugin.add_breakpoint( 'add_line_breakpoint', py_db, breakpoint_type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=hit_condition, is_logpoint=is_logpoint, add_breakpoint_result=result, on_changed_breakpoint_state=on_changed_breakpoint_state) if add_plugin_breakpoint_result is not None: supported_type = True added_breakpoint, file_to_line_to_breakpoints = add_plugin_breakpoint_result file_to_id_to_breakpoint = py_db.file_to_id_to_plugin_breakpoint else: supported_type = False if not supported_type: raise NameError(breakpoint_type) if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0: pydev_log.debug('Added breakpoint:%s - line:%s - func_name:%s\n', canonical_normalized_filename, line, func_name) if canonical_normalized_filename in file_to_id_to_breakpoint: id_to_pybreakpoint = file_to_id_to_breakpoint[canonical_normalized_filename] else: id_to_pybreakpoint = file_to_id_to_breakpoint[canonical_normalized_filename] = {} id_to_pybreakpoint[breakpoint_id] = added_breakpoint py_db.consolidate_breakpoints(canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints) if py_db.plugin is not None: py_db.has_plugin_line_breaks = py_db.plugin.has_line_breaks() py_db.plugin.after_breakpoints_consolidated(py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints) py_db.on_breakpoints_changed() return result def reapply_breakpoints(self, py_db): ''' Reapplies all the received breakpoints as they were received by the API (so, new translations are applied). ''' pydev_log.debug('Reapplying breakpoints.') values = list(py_db.api_received_breakpoints.values()) # Create a copy with items to reapply. self.remove_all_breakpoints(py_db, '*') for val in values: _new_filename, api_add_breakpoint_params = val self.add_breakpoint(py_db, *api_add_breakpoint_params) def remove_all_breakpoints(self, py_db, received_filename): ''' Removes all the breakpoints from a given file or from all files if received_filename == '*'. :param str received_filename: Note: must be sent as it was received in the protocol. It may be translated in this function. ''' assert received_filename.__class__ == str # i.e.: bytes on py2 and str on py3 changed = False lst = [ py_db.file_to_id_to_line_breakpoint, py_db.file_to_id_to_plugin_breakpoint, py_db.breakpoints ] if hasattr(py_db, 'django_breakpoints'): lst.append(py_db.django_breakpoints) if hasattr(py_db, 'jinja2_breakpoints'): lst.append(py_db.jinja2_breakpoints) if received_filename == '*': py_db.api_received_breakpoints.clear() for file_to_id_to_breakpoint in lst: if file_to_id_to_breakpoint: file_to_id_to_breakpoint.clear() changed = True else: received_filename_normalized = pydevd_file_utils.normcase_from_client(received_filename) items = list(py_db.api_received_breakpoints.items()) # Create a copy to remove items. translated_filenames = [] for key, val in items: original_filename_normalized, _breakpoint_id = key if original_filename_normalized == received_filename_normalized: canonical_normalized_filename, _api_add_breakpoint_params = val # Note: there can be actually 1:N mappings due to source mapping (i.e.: ipython). translated_filenames.append(canonical_normalized_filename) del py_db.api_received_breakpoints[key] for canonical_normalized_filename in translated_filenames: for file_to_id_to_breakpoint in lst: if canonical_normalized_filename in file_to_id_to_breakpoint: file_to_id_to_breakpoint.pop(canonical_normalized_filename, None) changed = True if changed: py_db.on_breakpoints_changed(removed=True) def remove_breakpoint(self, py_db, received_filename, breakpoint_type, breakpoint_id): ''' :param str received_filename: Note: must be sent as it was received in the protocol. It may be translated in this function. :param str breakpoint_type: One of: 'python-line', 'django-line', 'jinja2-line'. :param int breakpoint_id: ''' received_filename_normalized = pydevd_file_utils.normcase_from_client(received_filename) for key, val in list(py_db.api_received_breakpoints.items()): original_filename_normalized, existing_breakpoint_id = key _new_filename, _api_add_breakpoint_params = val if received_filename_normalized == original_filename_normalized and existing_breakpoint_id == breakpoint_id: del py_db.api_received_breakpoints[key] break else: pydev_log.info( 'Did not find breakpoint to remove: %s (breakpoint id: %s)', received_filename, breakpoint_id) file_to_id_to_breakpoint = None received_filename = self.filename_to_server(received_filename) canonical_normalized_filename = pydevd_file_utils.canonical_normalized_path(received_filename) if breakpoint_type == 'python-line': file_to_line_to_breakpoints = py_db.breakpoints file_to_id_to_breakpoint = py_db.file_to_id_to_line_breakpoint elif py_db.plugin is not None: result = py_db.plugin.get_breakpoints(py_db, breakpoint_type) if result is not None: file_to_id_to_breakpoint = py_db.file_to_id_to_plugin_breakpoint file_to_line_to_breakpoints = result if file_to_id_to_breakpoint is None: pydev_log.critical('Error removing breakpoint. Cannot handle breakpoint of type %s', breakpoint_type) else: try: id_to_pybreakpoint = file_to_id_to_breakpoint.get(canonical_normalized_filename, {}) if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0: existing = id_to_pybreakpoint[breakpoint_id] pydev_log.info('Removed breakpoint:%s - line:%s - func_name:%s (id: %s)\n' % ( canonical_normalized_filename, existing.line, existing.func_name.encode('utf-8'), breakpoint_id)) del id_to_pybreakpoint[breakpoint_id] py_db.consolidate_breakpoints(canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints) if py_db.plugin is not None: py_db.has_plugin_line_breaks = py_db.plugin.has_line_breaks() py_db.plugin.after_breakpoints_consolidated(py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints) except KeyError: pydev_log.info("Error removing breakpoint: Breakpoint id not found: %s id: %s. Available ids: %s\n", canonical_normalized_filename, breakpoint_id, list(id_to_pybreakpoint)) py_db.on_breakpoints_changed(removed=True) def set_function_breakpoints(self, py_db, function_breakpoints): function_breakpoint_name_to_breakpoint = {} for function_breakpoint in function_breakpoints: function_breakpoint_name_to_breakpoint[function_breakpoint.func_name] = function_breakpoint py_db.function_breakpoint_name_to_breakpoint = function_breakpoint_name_to_breakpoint py_db.on_breakpoints_changed() def request_exec_or_evaluate( self, py_db, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result): py_db.post_method_as_internal_command( thread_id, internal_evaluate_expression, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result) def request_exec_or_evaluate_json( self, py_db, request, thread_id): py_db.post_method_as_internal_command( thread_id, internal_evaluate_expression_json, request, thread_id) def request_set_expression_json(self, py_db, request, thread_id): py_db.post_method_as_internal_command( thread_id, internal_set_expression_json, request, thread_id) def request_console_exec(self, py_db, seq, thread_id, frame_id, expression): int_cmd = InternalConsoleExec(seq, thread_id, frame_id, expression) py_db.post_internal_command(int_cmd, thread_id) def request_load_source(self, py_db, seq, filename): ''' :param str filename: Note: must be sent as it was received in the protocol. It may be translated in this function. ''' try: filename = self.filename_to_server(filename) assert filename.__class__ == str # i.e.: bytes on py2 and str on py3 with tokenize.open(filename) as stream: source = stream.read() cmd = py_db.cmd_factory.make_load_source_message(seq, source) except: cmd = py_db.cmd_factory.make_error_message(seq, get_exception_traceback_str()) py_db.writer.add_command(cmd) def get_decompiled_source_from_frame_id(self, py_db, frame_id): ''' :param py_db: :param frame_id: :throws Exception: If unable to get the frame in the currently paused frames or if some error happened when decompiling. ''' variable = py_db.suspended_frames_manager.get_variable(int(frame_id)) frame = variable.value # Check if it's in the linecache first. lines = (linecache.getline(frame.f_code.co_filename, i) for i in itertools.count(1)) lines = itertools.takewhile(bool, lines) # empty lines are '\n', EOF is '' source = ''.join(lines) if not source: source = code_to_bytecode_representation(frame.f_code) return source def request_load_source_from_frame_id(self, py_db, seq, frame_id): try: source = self.get_decompiled_source_from_frame_id(py_db, frame_id) cmd = py_db.cmd_factory.make_load_source_from_frame_id_message(seq, source) except: cmd = py_db.cmd_factory.make_error_message(seq, get_exception_traceback_str()) py_db.writer.add_command(cmd) def add_python_exception_breakpoint( self, py_db, exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries, ): exception_breakpoint = py_db.add_break_on_exception( exception, condition=condition, expression=expression, notify_on_handled_exceptions=notify_on_handled_exceptions, notify_on_unhandled_exceptions=notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions=notify_on_user_unhandled_exceptions, notify_on_first_raise_only=notify_on_first_raise_only, ignore_libraries=ignore_libraries, ) if exception_breakpoint is not None: py_db.on_breakpoints_changed() def add_plugins_exception_breakpoint(self, py_db, breakpoint_type, exception): supported_type = False plugin = py_db.get_plugin_lazy_init() if plugin is not None: supported_type = plugin.add_breakpoint('add_exception_breakpoint', py_db, breakpoint_type, exception) if supported_type: py_db.has_plugin_exception_breaks = py_db.plugin.has_exception_breaks() py_db.on_breakpoints_changed() else: raise NameError(breakpoint_type) def remove_python_exception_breakpoint(self, py_db, exception): try: cp = py_db.break_on_uncaught_exceptions.copy() cp.pop(exception, None) py_db.break_on_uncaught_exceptions = cp cp = py_db.break_on_caught_exceptions.copy() cp.pop(exception, None) py_db.break_on_caught_exceptions = cp cp = py_db.break_on_user_uncaught_exceptions.copy() cp.pop(exception, None) py_db.break_on_user_uncaught_exceptions = cp except: pydev_log.exception("Error while removing exception %s", sys.exc_info()[0]) py_db.on_breakpoints_changed(removed=True) def remove_plugins_exception_breakpoint(self, py_db, exception_type, exception): # I.e.: no need to initialize lazy (if we didn't have it in the first place, we can't remove # anything from it anyways). plugin = py_db.plugin if plugin is None: return supported_type = plugin.remove_exception_breakpoint(py_db, exception_type, exception) if supported_type: py_db.has_plugin_exception_breaks = py_db.plugin.has_exception_breaks() else: pydev_log.info('No exception of type: %s was previously registered.', exception_type) py_db.on_breakpoints_changed(removed=True) def remove_all_exception_breakpoints(self, py_db): py_db.break_on_uncaught_exceptions = {} py_db.break_on_caught_exceptions = {} py_db.break_on_user_uncaught_exceptions = {} plugin = py_db.plugin if plugin is not None: plugin.remove_all_exception_breakpoints(py_db) py_db.on_breakpoints_changed(removed=True) def set_project_roots(self, py_db, project_roots): ''' :param str project_roots: ''' py_db.set_project_roots(project_roots) def set_stepping_resumes_all_threads(self, py_db, stepping_resumes_all_threads): py_db.stepping_resumes_all_threads = stepping_resumes_all_threads # Add it to the namespace so that it's available as PyDevdAPI.ExcludeFilter from _pydevd_bundle.pydevd_filtering import ExcludeFilter # noqa def set_exclude_filters(self, py_db, exclude_filters): ''' :param list(PyDevdAPI.ExcludeFilter) exclude_filters: ''' py_db.set_exclude_filters(exclude_filters) def set_use_libraries_filter(self, py_db, use_libraries_filter): py_db.set_use_libraries_filter(use_libraries_filter) def request_get_variable_json(self, py_db, request, thread_id): ''' :param VariablesRequest request: ''' py_db.post_method_as_internal_command( thread_id, internal_get_variable_json, request) def request_change_variable_json(self, py_db, request, thread_id): ''' :param SetVariableRequest request: ''' py_db.post_method_as_internal_command( thread_id, internal_change_variable_json, request) def set_dont_trace_start_end_patterns(self, py_db, start_patterns, end_patterns): # Note: start/end patterns normalized internally. start_patterns = tuple(pydevd_file_utils.normcase(x) for x in start_patterns) end_patterns = tuple(pydevd_file_utils.normcase(x) for x in end_patterns) # After it's set the first time, we can still change it, but we need to reset the # related caches. reset_caches = False dont_trace_start_end_patterns_previously_set = \ py_db.dont_trace_external_files.__name__ == 'custom_dont_trace_external_files' if not dont_trace_start_end_patterns_previously_set and not start_patterns and not end_patterns: # If it wasn't set previously and start and end patterns are empty we don't need to do anything. return if not py_db.is_cache_file_type_empty(): # i.e.: custom function set in set_dont_trace_start_end_patterns. if dont_trace_start_end_patterns_previously_set: reset_caches = py_db.dont_trace_external_files.start_patterns != start_patterns or \ py_db.dont_trace_external_files.end_patterns != end_patterns else: reset_caches = True def custom_dont_trace_external_files(abs_path): normalized_abs_path = pydevd_file_utils.normcase(abs_path) return normalized_abs_path.startswith(start_patterns) or normalized_abs_path.endswith(end_patterns) custom_dont_trace_external_files.start_patterns = start_patterns custom_dont_trace_external_files.end_patterns = end_patterns py_db.dont_trace_external_files = custom_dont_trace_external_files if reset_caches: py_db.clear_dont_trace_start_end_patterns_caches() def stop_on_entry(self): main_thread = pydevd_utils.get_main_thread() if main_thread is None: pydev_log.critical('Could not find main thread while setting Stop on Entry.') else: info = set_additional_thread_info(main_thread) info.pydev_original_step_cmd = CMD_STOP_ON_START info.pydev_step_cmd = CMD_STEP_INTO_MY_CODE def set_ignore_system_exit_codes(self, py_db, ignore_system_exit_codes): py_db.set_ignore_system_exit_codes(ignore_system_exit_codes) SourceMappingEntry = pydevd_source_mapping.SourceMappingEntry def set_source_mapping(self, py_db, source_filename, mapping): ''' :param str source_filename: The filename for the source mapping (bytes on py2 and str on py3). This filename will be made absolute in this function. :param list(SourceMappingEntry) mapping: A list with the source mapping entries to be applied to the given filename. :return str: An error message if it was not possible to set the mapping or an empty string if everything is ok. ''' source_filename = self.filename_to_server(source_filename) absolute_source_filename = pydevd_file_utils.absolute_path(source_filename) for map_entry in mapping: map_entry.source_filename = absolute_source_filename error_msg = py_db.source_mapping.set_source_mapping(absolute_source_filename, mapping) if error_msg: return error_msg self.reapply_breakpoints(py_db) return '' def set_variable_presentation(self, py_db, variable_presentation): assert isinstance(variable_presentation, self.VariablePresentation) py_db.variable_presentation = variable_presentation def get_ppid(self): ''' Provides the parent pid (even for older versions of Python on Windows). ''' ppid = None try: ppid = os.getppid() except AttributeError: pass if ppid is None and IS_WINDOWS: ppid = self._get_windows_ppid() return ppid def _get_windows_ppid(self): this_pid = os.getpid() for ppid, pid in _list_ppid_and_pid(): if pid == this_pid: return ppid return None def _terminate_child_processes_windows(self, dont_terminate_child_pids): this_pid = os.getpid() for _ in range(50): # Try this at most 50 times before giving up. # Note: we can't kill the process itself with taskkill, so, we # list immediate children, kill that tree and then exit this process. children_pids = [] for ppid, pid in _list_ppid_and_pid(): if ppid == this_pid: if pid not in dont_terminate_child_pids: children_pids.append(pid) if not children_pids: break else: for pid in children_pids: self._call( ['taskkill', '/F', '/PID', str(pid), '/T'], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) del children_pids[:] def _terminate_child_processes_linux_and_mac(self, dont_terminate_child_pids): this_pid = os.getpid() def list_children_and_stop_forking(initial_pid, stop=True): children_pids = [] if stop: # Ask to stop forking (shouldn't be called for this process, only subprocesses). self._call( ['kill', '-STOP', str(initial_pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) list_popen = self._popen( ['pgrep', '-P', str(initial_pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if list_popen is not None: stdout, _ = list_popen.communicate() for line in stdout.splitlines(): line = line.decode('ascii').strip() if line: pid = str(line) if pid in dont_terminate_child_pids: continue children_pids.append(pid) # Recursively get children. children_pids.extend(list_children_and_stop_forking(pid)) return children_pids previously_found = set() for _ in range(50): # Try this at most 50 times before giving up. children_pids = list_children_and_stop_forking(this_pid, stop=False) found_new = False for pid in children_pids: if pid not in previously_found: found_new = True previously_found.add(pid) self._call( ['kill', '-KILL', str(pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if not found_new: break def _popen(self, cmdline, **kwargs): try: return subprocess.Popen(cmdline, **kwargs) except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: pydev_log.exception('Error running: %s' % (' '.join(cmdline))) return None def _call(self, cmdline, **kwargs): try: subprocess.check_call(cmdline, **kwargs) except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: pydev_log.exception('Error running: %s' % (' '.join(cmdline))) def set_terminate_child_processes(self, py_db, terminate_child_processes): py_db.terminate_child_processes = terminate_child_processes def terminate_process(self, py_db): ''' Terminates the current process (and child processes if the option to also terminate child processes is enabled). ''' try: if py_db.terminate_child_processes: pydev_log.debug('Terminating child processes.') if IS_WINDOWS: self._terminate_child_processes_windows(py_db.dont_terminate_child_pids) else: self._terminate_child_processes_linux_and_mac(py_db.dont_terminate_child_pids) finally: pydev_log.debug('Exiting process (os._exit(0)).') os._exit(0) def _terminate_if_commands_processed(self, py_db): py_db.dispose_and_kill_all_pydevd_threads() self.terminate_process(py_db) def request_terminate_process(self, py_db): # We mark with a terminate_requested to avoid that paused threads start running # (we should terminate as is without letting any paused thread run). py_db.terminate_requested = True run_as_pydevd_daemon_thread(py_db, self._terminate_if_commands_processed, py_db) def setup_auto_reload_watcher(self, py_db, enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns): py_db.setup_auto_reload_watcher(enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns) def _list_ppid_and_pid(): _TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_uint32), ("cntUsage", ctypes.c_uint32), ("th32ProcessID", ctypes.c_uint32), ("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", ctypes.c_uint32), ("cntThreads", ctypes.c_uint32), ("th32ParentProcessID", ctypes.c_uint32), ("pcPriClassBase", ctypes.c_long), ("dwFlags", ctypes.c_uint32), ("szExeFile", ctypes.c_char * 260)] kernel32 = ctypes.windll.kernel32 snapshot = kernel32.CreateToolhelp32Snapshot(_TH32CS_SNAPPROCESS, 0) ppid_and_pids = [] try: process_entry = PROCESSENTRY32() process_entry.dwSize = ctypes.sizeof(PROCESSENTRY32) if not kernel32.Process32First(ctypes.c_void_p(snapshot), ctypes.byref(process_entry)): pydev_log.critical('Process32First failed (getting process from CreateToolhelp32Snapshot).') else: while True: ppid_and_pids.append((process_entry.th32ParentProcessID, process_entry.th32ProcessID)) if not kernel32.Process32Next(ctypes.c_void_p(snapshot), ctypes.byref(process_entry)): break finally: kernel32.CloseHandle(snapshot) return ppid_and_pids
50,385
Python
43.120841
150
0.617684
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_collect_bytecode_info.py
import dis import inspect import sys from collections import namedtuple from _pydev_bundle import pydev_log from opcode import (EXTENDED_ARG, HAVE_ARGUMENT, cmp_op, hascompare, hasconst, hasfree, hasjrel, haslocal, hasname, opname) from io import StringIO class TryExceptInfo(object): def __init__(self, try_line, ignore=False): ''' :param try_line: :param ignore: Usually we should ignore any block that's not a try..except (this can happen for finally blocks, with statements, etc, for which we create temporary entries). ''' self.try_line = try_line self.ignore = ignore self.except_line = -1 self.except_end_line = -1 self.raise_lines_in_except = [] # Note: these may not be available if generated from source instead of bytecode. self.except_bytecode_offset = -1 self.except_end_bytecode_offset = -1 def is_line_in_try_block(self, line): return self.try_line <= line < self.except_line def is_line_in_except_block(self, line): return self.except_line <= line <= self.except_end_line def __str__(self): lst = [ '{try:', str(self.try_line), ' except ', str(self.except_line), ' end block ', str(self.except_end_line), ] if self.raise_lines_in_except: lst.append(' raises: %s' % (', '.join(str(x) for x in self.raise_lines_in_except),)) lst.append('}') return ''.join(lst) __repr__ = __str__ class ReturnInfo(object): def __init__(self, return_line): self.return_line = return_line def __str__(self): return '{return: %s}' % (self.return_line,) __repr__ = __str__ def _get_line(op_offset_to_line, op_offset, firstlineno, search=False): op_offset_original = op_offset while op_offset >= 0: ret = op_offset_to_line.get(op_offset) if ret is not None: return ret - firstlineno if not search: return ret else: op_offset -= 1 raise AssertionError('Unable to find line for offset: %s.Info: %s' % ( op_offset_original, op_offset_to_line)) def debug(s): pass _Instruction = namedtuple('_Instruction', 'opname, opcode, starts_line, argval, is_jump_target, offset, argrepr') def _iter_as_bytecode_as_instructions_py2(co): code = co.co_code op_offset_to_line = dict(dis.findlinestarts(co)) labels = set(dis.findlabels(code)) bytecode_len = len(code) i = 0 extended_arg = 0 free = None op_to_name = opname while i < bytecode_len: c = code[i] op = ord(c) is_jump_target = i in labels curr_op_name = op_to_name[op] initial_bytecode_offset = i i = i + 1 if op < HAVE_ARGUMENT: yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), None, is_jump_target, initial_bytecode_offset, '') else: oparg = ord(code[i]) + ord(code[i + 1]) * 256 + extended_arg extended_arg = 0 i = i + 2 if op == EXTENDED_ARG: extended_arg = oparg * 65536 if op in hasconst: yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), co.co_consts[oparg], is_jump_target, initial_bytecode_offset, repr(co.co_consts[oparg])) elif op in hasname: yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), co.co_names[oparg], is_jump_target, initial_bytecode_offset, str(co.co_names[oparg])) elif op in hasjrel: argval = i + oparg yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), argval, is_jump_target, initial_bytecode_offset, "to " + repr(argval)) elif op in haslocal: yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), co.co_varnames[oparg], is_jump_target, initial_bytecode_offset, str(co.co_varnames[oparg])) elif op in hascompare: yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), cmp_op[oparg], is_jump_target, initial_bytecode_offset, cmp_op[oparg]) elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), free[oparg], is_jump_target, initial_bytecode_offset, str(free[oparg])) else: yield _Instruction(curr_op_name, op, _get_line(op_offset_to_line, initial_bytecode_offset, 0), oparg, is_jump_target, initial_bytecode_offset, str(oparg)) def iter_instructions(co): if sys.version_info[0] < 3: iter_in = _iter_as_bytecode_as_instructions_py2(co) else: iter_in = dis.Bytecode(co) iter_in = list(iter_in) bytecode_to_instruction = {} for instruction in iter_in: bytecode_to_instruction[instruction.offset] = instruction if iter_in: for instruction in iter_in: yield instruction def collect_return_info(co, use_func_first_line=False): if not hasattr(co, 'co_lnotab'): return [] if use_func_first_line: firstlineno = co.co_firstlineno else: firstlineno = 0 lst = [] op_offset_to_line = dict(dis.findlinestarts(co)) for instruction in iter_instructions(co): curr_op_name = instruction.opname if curr_op_name == 'RETURN_VALUE': lst.append(ReturnInfo(_get_line(op_offset_to_line, instruction.offset, firstlineno, search=True))) return lst if sys.version_info[:2] <= (3, 9): class _TargetInfo(object): def __init__(self, except_end_instruction, jump_if_not_exc_instruction=None): self.except_end_instruction = except_end_instruction self.jump_if_not_exc_instruction = jump_if_not_exc_instruction def __str__(self): msg = ['_TargetInfo('] msg.append(self.except_end_instruction.opname) if self.jump_if_not_exc_instruction: msg.append(' - ') msg.append(self.jump_if_not_exc_instruction.opname) msg.append('(') msg.append(str(self.jump_if_not_exc_instruction.argval)) msg.append(')') msg.append(')') return ''.join(msg) def _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx): next_3 = [j_instruction.opname for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]] # print('next_3:', [(j_instruction.opname, j_instruction.argval) for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]]) if next_3 == ['POP_TOP', 'POP_TOP', 'POP_TOP']: # try..except without checking exception. try: jump_instruction = instructions[exception_end_instruction_index - 1] if jump_instruction.opname not in ('JUMP_FORWARD', 'JUMP_ABSOLUTE'): return None except IndexError: pass if jump_instruction.opname == 'JUMP_ABSOLUTE': # On latest versions of Python 3 the interpreter has a go-backwards step, # used to show the initial line of a for/while, etc (which is this # JUMP_ABSOLUTE)... we're not really interested in it, but rather on where # it points to. except_end_instruction = instructions[offset_to_instruction_idx[jump_instruction.argval]] idx = offset_to_instruction_idx[except_end_instruction.argval] # Search for the POP_EXCEPT which should be at the end of the block. for pop_except_instruction in reversed(instructions[:idx]): if pop_except_instruction.opname == 'POP_EXCEPT': except_end_instruction = pop_except_instruction return _TargetInfo(except_end_instruction) else: return None # i.e.: Continue outer loop else: # JUMP_FORWARD i = offset_to_instruction_idx[jump_instruction.argval] try: # i.e.: the jump is to the instruction after the block finishes (so, we need to # get the previous instruction as that should be the place where the exception # block finishes). except_end_instruction = instructions[i - 1] except: pydev_log.critical('Error when computing try..except block end.') return None return _TargetInfo(except_end_instruction) elif next_3 and next_3[0] == 'DUP_TOP': # try..except AssertionError. iter_in = instructions[exception_end_instruction_index + 1:] for j, jump_if_not_exc_instruction in enumerate(iter_in): if jump_if_not_exc_instruction.opname == 'JUMP_IF_NOT_EXC_MATCH': # Python 3.9 except_end_instruction = instructions[offset_to_instruction_idx[jump_if_not_exc_instruction.argval]] return _TargetInfo(except_end_instruction, jump_if_not_exc_instruction) elif jump_if_not_exc_instruction.opname == 'COMPARE_OP' and jump_if_not_exc_instruction.argval == 'exception match': # Python 3.8 and before try: next_instruction = iter_in[j + 1] except: continue if next_instruction.opname == 'POP_JUMP_IF_FALSE': except_end_instruction = instructions[offset_to_instruction_idx[next_instruction.argval]] return _TargetInfo(except_end_instruction, next_instruction) else: return None # i.e.: Continue outer loop else: # i.e.: we're not interested in try..finally statements, only try..except. return None def collect_try_except_info(co, use_func_first_line=False): # We no longer have 'END_FINALLY', so, we need to do things differently in Python 3.9 if not hasattr(co, 'co_lnotab'): return [] if use_func_first_line: firstlineno = co.co_firstlineno else: firstlineno = 0 try_except_info_lst = [] op_offset_to_line = dict(dis.findlinestarts(co)) offset_to_instruction_idx = {} instructions = list(iter_instructions(co)) for i, instruction in enumerate(instructions): offset_to_instruction_idx[instruction.offset] = i for i, instruction in enumerate(instructions): curr_op_name = instruction.opname if curr_op_name in ('SETUP_FINALLY', 'SETUP_EXCEPT'): # SETUP_EXCEPT before Python 3.8, SETUP_FINALLY Python 3.8 onwards. exception_end_instruction_index = offset_to_instruction_idx[instruction.argval] jump_instruction = instructions[exception_end_instruction_index - 1] if jump_instruction.opname not in ('JUMP_FORWARD', 'JUMP_ABSOLUTE'): continue except_end_instruction = None indexes_checked = set() indexes_checked.add(exception_end_instruction_index) target_info = _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx) while target_info is not None: # Handle a try..except..except..except. jump_instruction = target_info.jump_if_not_exc_instruction except_end_instruction = target_info.except_end_instruction if jump_instruction is not None: check_index = offset_to_instruction_idx[jump_instruction.argval] if check_index in indexes_checked: break indexes_checked.add(check_index) target_info = _get_except_target_info(instructions, check_index, offset_to_instruction_idx) else: break if except_end_instruction is not None: try_except_info = TryExceptInfo( _get_line(op_offset_to_line, instruction.offset, firstlineno, search=True), ignore=False ) try_except_info.except_bytecode_offset = instruction.argval try_except_info.except_line = _get_line( op_offset_to_line, try_except_info.except_bytecode_offset, firstlineno, search=True ) try_except_info.except_end_bytecode_offset = except_end_instruction.offset try_except_info.except_end_line = _get_line(op_offset_to_line, except_end_instruction.offset, firstlineno, search=True) try_except_info_lst.append(try_except_info) for raise_instruction in instructions[i:offset_to_instruction_idx[try_except_info.except_end_bytecode_offset]]: if raise_instruction.opname == 'RAISE_VARARGS': if raise_instruction.argval == 0: try_except_info.raise_lines_in_except.append( _get_line(op_offset_to_line, raise_instruction.offset, firstlineno, search=True)) return try_except_info_lst elif sys.version_info[:2] == (3, 10): class _TargetInfo(object): def __init__(self, except_end_instruction, jump_if_not_exc_instruction=None): self.except_end_instruction = except_end_instruction self.jump_if_not_exc_instruction = jump_if_not_exc_instruction def __str__(self): msg = ['_TargetInfo('] msg.append(self.except_end_instruction.opname) if self.jump_if_not_exc_instruction: msg.append(' - ') msg.append(self.jump_if_not_exc_instruction.opname) msg.append('(') msg.append(str(self.jump_if_not_exc_instruction.argval)) msg.append(')') msg.append(')') return ''.join(msg) def _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx): next_3 = [j_instruction.opname for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]] # print('next_3:', [(j_instruction.opname, j_instruction.argval) for j_instruction in instructions[exception_end_instruction_index:exception_end_instruction_index + 3]]) if next_3 == ['POP_TOP', 'POP_TOP', 'POP_TOP']: # try..except without checking exception. # Previously there was a jump which was able to point where the exception would end. This # is no longer true, now a bare except doesn't really have any indication in the bytecode # where the end would be expected if the exception wasn't raised, so, we just blindly # search for a POP_EXCEPT from the current position. for pop_except_instruction in instructions[exception_end_instruction_index + 3:]: if pop_except_instruction.opname == 'POP_EXCEPT': except_end_instruction = pop_except_instruction return _TargetInfo(except_end_instruction) elif next_3 and next_3[0] == 'DUP_TOP': # try..except AssertionError. iter_in = instructions[exception_end_instruction_index + 1:] for jump_if_not_exc_instruction in iter_in: if jump_if_not_exc_instruction.opname == 'JUMP_IF_NOT_EXC_MATCH': # Python 3.9 except_end_instruction = instructions[offset_to_instruction_idx[jump_if_not_exc_instruction.argval]] return _TargetInfo(except_end_instruction, jump_if_not_exc_instruction) else: return None # i.e.: Continue outer loop else: # i.e.: we're not interested in try..finally statements, only try..except. return None def collect_try_except_info(co, use_func_first_line=False): # We no longer have 'END_FINALLY', so, we need to do things differently in Python 3.9 if not hasattr(co, 'co_lnotab'): return [] if use_func_first_line: firstlineno = co.co_firstlineno else: firstlineno = 0 try_except_info_lst = [] op_offset_to_line = dict(dis.findlinestarts(co)) offset_to_instruction_idx = {} instructions = list(iter_instructions(co)) for i, instruction in enumerate(instructions): offset_to_instruction_idx[instruction.offset] = i for i, instruction in enumerate(instructions): curr_op_name = instruction.opname if curr_op_name == 'SETUP_FINALLY': exception_end_instruction_index = offset_to_instruction_idx[instruction.argval] jump_instruction = instructions[exception_end_instruction_index] if jump_instruction.opname != 'DUP_TOP': continue except_end_instruction = None indexes_checked = set() indexes_checked.add(exception_end_instruction_index) target_info = _get_except_target_info(instructions, exception_end_instruction_index, offset_to_instruction_idx) while target_info is not None: # Handle a try..except..except..except. jump_instruction = target_info.jump_if_not_exc_instruction except_end_instruction = target_info.except_end_instruction if jump_instruction is not None: check_index = offset_to_instruction_idx[jump_instruction.argval] if check_index in indexes_checked: break indexes_checked.add(check_index) target_info = _get_except_target_info(instructions, check_index, offset_to_instruction_idx) else: break if except_end_instruction is not None: try_except_info = TryExceptInfo( _get_line(op_offset_to_line, instruction.offset, firstlineno, search=True), ignore=False ) try_except_info.except_bytecode_offset = instruction.argval try_except_info.except_line = _get_line( op_offset_to_line, try_except_info.except_bytecode_offset, firstlineno, search=True ) try_except_info.except_end_bytecode_offset = except_end_instruction.offset # On Python 3.10 the final line of the except end isn't really correct, rather, # it's engineered to be the same line of the except and not the end line of the # block, so, the approach taken is to search for the biggest line between the # except and the end instruction except_end_line = -1 start_i = offset_to_instruction_idx[try_except_info.except_bytecode_offset] end_i = offset_to_instruction_idx[except_end_instruction.offset] for instruction in instructions[start_i: end_i + 1]: found_at_line = op_offset_to_line.get(instruction.offset) if found_at_line is not None and found_at_line > except_end_line: except_end_line = found_at_line try_except_info.except_end_line = except_end_line - firstlineno try_except_info_lst.append(try_except_info) for raise_instruction in instructions[i:offset_to_instruction_idx[try_except_info.except_end_bytecode_offset]]: if raise_instruction.opname == 'RAISE_VARARGS': if raise_instruction.argval == 0: try_except_info.raise_lines_in_except.append( _get_line(op_offset_to_line, raise_instruction.offset, firstlineno, search=True)) return try_except_info_lst elif sys.version_info[:2] >= (3, 11): def collect_try_except_info(co, use_func_first_line=False): ''' Note: if the filename is available and we can get the source, `collect_try_except_info_from_source` is preferred (this is kept as a fallback for cases where sources aren't available). ''' return [] import ast as ast_module class _Visitor(ast_module.NodeVisitor): def __init__(self): self.try_except_infos = [] self._stack = [] self._in_except_stack = [] self.max_line = -1 def generic_visit(self, node): if hasattr(node, 'lineno'): if node.lineno > self.max_line: self.max_line = node.lineno return ast_module.NodeVisitor.generic_visit(self, node) def visit_Try(self, node): info = TryExceptInfo(node.lineno, ignore=True) self._stack.append(info) self.generic_visit(node) assert info is self._stack.pop() if not info.ignore: self.try_except_infos.insert(0, info) if sys.version_info[0] < 3: visit_TryExcept = visit_Try def visit_ExceptHandler(self, node): info = self._stack[-1] info.ignore = False if info.except_line == -1: info.except_line = node.lineno self._in_except_stack.append(info) self.generic_visit(node) if hasattr(node, 'end_lineno'): info.except_end_line = node.end_lineno else: info.except_end_line = self.max_line self._in_except_stack.pop() if sys.version_info[0] >= 3: def visit_Raise(self, node): for info in self._in_except_stack: if node.exc is None: info.raise_lines_in_except.append(node.lineno) self.generic_visit(node) else: def visit_Raise(self, node): for info in self._in_except_stack: if node.type is None and node.tback is None: info.raise_lines_in_except.append(node.lineno) self.generic_visit(node) def collect_try_except_info_from_source(filename): with open(filename, 'rb') as stream: contents = stream.read() return collect_try_except_info_from_contents(contents, filename) def collect_try_except_info_from_contents(contents, filename='<unknown>'): ast = ast_module.parse(contents, filename) visitor = _Visitor() visitor.visit(ast) return visitor.try_except_infos RESTART_FROM_LOOKAHEAD = object() SEPARATOR = object() class _MsgPart(object): def __init__(self, line, tok): assert line >= 0 self.line = line self.tok = tok @classmethod def add_to_line_to_contents(cls, obj, line_to_contents, line=None): if isinstance(obj, (list, tuple)): for o in obj: cls.add_to_line_to_contents(o, line_to_contents, line=line) return if isinstance(obj, str): assert line is not None line = int(line) lst = line_to_contents.setdefault(line, []) lst.append(obj) return if isinstance(obj, _MsgPart): if isinstance(obj.tok, (list, tuple)): cls.add_to_line_to_contents(obj.tok, line_to_contents, line=obj.line) return if isinstance(obj.tok, str): lst = line_to_contents.setdefault(obj.line, []) lst.append(obj.tok) return raise AssertionError("Unhandled: %" % (obj,)) class _Disassembler(object): def __init__(self, co, firstlineno, level=0): self.co = co self.firstlineno = firstlineno self.level = level self.instructions = list(iter_instructions(co)) op_offset_to_line = self.op_offset_to_line = dict(dis.findlinestarts(co)) # Update offsets so that all offsets have the line index (and update it based on # the passed firstlineno). line_index = co.co_firstlineno - firstlineno for instruction in self.instructions: new_line_index = op_offset_to_line.get(instruction.offset) if new_line_index is not None: line_index = new_line_index - firstlineno op_offset_to_line[instruction.offset] = line_index else: op_offset_to_line[instruction.offset] = line_index BIG_LINE_INT = 9999999 SMALL_LINE_INT = -1 def min_line(self, *args): m = self.BIG_LINE_INT for arg in args: if isinstance(arg, (list, tuple)): m = min(m, self.min_line(*arg)) elif isinstance(arg, _MsgPart): m = min(m, arg.line) elif hasattr(arg, 'offset'): m = min(m, self.op_offset_to_line[arg.offset]) return m def max_line(self, *args): m = self.SMALL_LINE_INT for arg in args: if isinstance(arg, (list, tuple)): m = max(m, self.max_line(*arg)) elif isinstance(arg, _MsgPart): m = max(m, arg.line) elif hasattr(arg, 'offset'): m = max(m, self.op_offset_to_line[arg.offset]) return m def _lookahead(self): ''' This handles and converts some common constructs from bytecode to actual source code. It may change the list of instructions. ''' msg = self._create_msg_part found = [] fullrepr = None # Collect all the load instructions for next_instruction in self.instructions: if next_instruction.opname in ('LOAD_GLOBAL', 'LOAD_FAST', 'LOAD_CONST', 'LOAD_NAME'): found.append(next_instruction) else: break if not found: return None if next_instruction.opname == 'LOAD_ATTR': prev_instruction = found[-1] # Remove the current LOAD_ATTR assert self.instructions.pop(len(found)) is next_instruction # Add the LOAD_ATTR to the previous LOAD self.instructions[len(found) - 1] = _Instruction( prev_instruction.opname, prev_instruction.opcode, prev_instruction.starts_line, prev_instruction.argval, False, # prev_instruction.is_jump_target, prev_instruction.offset, ( msg(prev_instruction), msg(prev_instruction, '.'), msg(next_instruction) ), ) return RESTART_FROM_LOOKAHEAD if next_instruction.opname in ('CALL_FUNCTION', 'PRECALL'): if len(found) == next_instruction.argval + 1: force_restart = False delta = 0 else: force_restart = True if len(found) > next_instruction.argval + 1: delta = len(found) - (next_instruction.argval + 1) else: return None # This is odd del_upto = delta + next_instruction.argval + 2 # +2 = NAME / CALL_FUNCTION if next_instruction.opname == 'PRECALL': del_upto += 1 # Also remove the CALL right after the PRECALL. del self.instructions[delta:del_upto] found = iter(found[delta:]) call_func = next(found) args = list(found) fullrepr = [ msg(call_func), msg(call_func, '('), ] prev = call_func for i, arg in enumerate(args): if i > 0: fullrepr.append(msg(prev, ', ')) prev = arg fullrepr.append(msg(arg)) fullrepr.append(msg(prev, ')')) if force_restart: self.instructions.insert(delta, _Instruction( call_func.opname, call_func.opcode, call_func.starts_line, call_func.argval, False, # call_func.is_jump_target, call_func.offset, tuple(fullrepr), )) return RESTART_FROM_LOOKAHEAD elif next_instruction.opname == 'BUILD_TUPLE': if len(found) == next_instruction.argval: force_restart = False delta = 0 else: force_restart = True if len(found) > next_instruction.argval: delta = len(found) - (next_instruction.argval) else: return None # This is odd del self.instructions[delta:delta + next_instruction.argval + 1] # +1 = BUILD_TUPLE found = iter(found[delta:]) args = [instruction for instruction in found] if args: first_instruction = args[0] else: first_instruction = next_instruction prev = first_instruction fullrepr = [] fullrepr.append(msg(prev, '(')) for i, arg in enumerate(args): if i > 0: fullrepr.append(msg(prev, ', ')) prev = arg fullrepr.append(msg(arg)) fullrepr.append(msg(prev, ')')) if force_restart: self.instructions.insert(delta, _Instruction( first_instruction.opname, first_instruction.opcode, first_instruction.starts_line, first_instruction.argval, False, # first_instruction.is_jump_target, first_instruction.offset, tuple(fullrepr), )) return RESTART_FROM_LOOKAHEAD if fullrepr is not None and self.instructions: if self.instructions[0].opname == 'POP_TOP': self.instructions.pop(0) if self.instructions[0].opname in ('STORE_FAST', 'STORE_NAME'): next_instruction = self.instructions.pop(0) return msg(next_instruction), msg(next_instruction, ' = '), fullrepr if self.instructions[0].opname == 'RETURN_VALUE': next_instruction = self.instructions.pop(0) return msg(next_instruction, 'return ', line=self.min_line(next_instruction, fullrepr)), fullrepr return fullrepr def _decorate_jump_target(self, instruction, instruction_repr): if instruction.is_jump_target: return ('|', str(instruction.offset), '|', instruction_repr) return instruction_repr def _create_msg_part(self, instruction, tok=None, line=None): dec = self._decorate_jump_target if line is None or line in (self.BIG_LINE_INT, self.SMALL_LINE_INT): line = self.op_offset_to_line[instruction.offset] argrepr = instruction.argrepr if isinstance(argrepr, str) and argrepr.startswith('NULL + '): argrepr = argrepr[7:] return _MsgPart( line, tok if tok is not None else dec(instruction, argrepr)) def _next_instruction_to_str(self, line_to_contents): # indent = '' # if self.level > 0: # indent += ' ' * self.level # print(indent, 'handle', self.instructions[0]) if self.instructions: ret = self._lookahead() if ret: return ret msg = self._create_msg_part instruction = self.instructions.pop(0) if instruction.opname in 'RESUME': return None if instruction.opname in ('LOAD_GLOBAL', 'LOAD_FAST', 'LOAD_CONST', 'LOAD_NAME'): next_instruction = self.instructions[0] if next_instruction.opname in ('STORE_FAST', 'STORE_NAME'): self.instructions.pop(0) return ( msg(next_instruction), msg(next_instruction, ' = '), msg(instruction)) if next_instruction.opname == 'RETURN_VALUE': self.instructions.pop(0) return (msg(instruction, 'return ', line=self.min_line(instruction)), msg(instruction)) if next_instruction.opname == 'RAISE_VARARGS' and next_instruction.argval == 1: self.instructions.pop(0) return (msg(instruction, 'raise ', line=self.min_line(instruction)), msg(instruction)) if instruction.opname == 'LOAD_CONST': if inspect.iscode(instruction.argval): code_line_to_contents = _Disassembler( instruction.argval, self.firstlineno, self.level + 1 ).build_line_to_contents() for contents in code_line_to_contents.values(): contents.insert(0, ' ') for line, contents in code_line_to_contents.items(): line_to_contents.setdefault(line, []).extend(contents) return msg(instruction, 'LOAD_CONST(code)') if instruction.opname == 'RAISE_VARARGS': if instruction.argval == 0: return msg(instruction, 'raise') if instruction.opname == 'SETUP_FINALLY': return msg(instruction, ('try(', instruction.argrepr, '):')) if instruction.argrepr: return msg(instruction, (instruction.opname, '(', instruction.argrepr, ')')) if instruction.argval: return msg(instruction, '%s{%s}' % (instruction.opname, instruction.argval,)) return msg(instruction, instruction.opname) def build_line_to_contents(self): # print('----') # for instruction in self.instructions: # print(instruction) # print('----\n\n') line_to_contents = {} instructions = self.instructions while instructions: s = self._next_instruction_to_str(line_to_contents) if s is RESTART_FROM_LOOKAHEAD: continue if s is None: continue _MsgPart.add_to_line_to_contents(s, line_to_contents) m = self.max_line(s) if m != self.SMALL_LINE_INT: line_to_contents.setdefault(m, []).append(SEPARATOR) return line_to_contents def disassemble(self): line_to_contents = self.build_line_to_contents() stream = StringIO() last_line = 0 show_lines = False for line, contents in sorted(line_to_contents.items()): while last_line < line - 1: if show_lines: stream.write('%s.\n' % (last_line + 1,)) else: stream.write('\n') last_line += 1 if show_lines: stream.write('%s. ' % (line,)) for i, content in enumerate(contents): if content == SEPARATOR: if i != len(contents) - 1: stream.write(', ') else: stream.write(content) stream.write('\n') last_line = line return stream.getvalue() def code_to_bytecode_representation(co, use_func_first_line=False): ''' A simple disassemble of bytecode. It does not attempt to provide the full Python source code, rather, it provides a low-level representation of the bytecode, respecting the lines (so, its target is making the bytecode easier to grasp and not providing the original source code). Note that it does show jump locations/targets and converts some common bytecode constructs to Python code to make it a bit easier to understand. ''' # Reference for bytecodes: # https://docs.python.org/3/library/dis.html if use_func_first_line: firstlineno = co.co_firstlineno else: firstlineno = 0 return _Disassembler(co, firstlineno).disassemble()
37,141
Python
39.110151
202
0.562532
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_frame_utils.py
from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED from _pydev_bundle import pydev_log class Frame(object): def __init__( self, f_back, f_fileno, f_code, f_locals, f_globals=None, f_trace=None): self.f_back = f_back self.f_lineno = f_fileno self.f_code = f_code self.f_locals = f_locals self.f_globals = f_globals self.f_trace = f_trace if self.f_globals is None: self.f_globals = {} class FCode(object): def __init__(self, name, filename): self.co_name = name self.co_filename = filename self.co_firstlineno = 1 self.co_flags = 0 def add_exception_to_frame(frame, exception_info): frame.f_locals['__exception__'] = exception_info def remove_exception_from_frame(frame): frame.f_locals.pop('__exception__', None) FILES_WITH_IMPORT_HOOKS = ['pydev_monkey_qt.py', 'pydev_import_hook.py'] def just_raised(trace): if trace is None: return False return trace.tb_next is None def ignore_exception_trace(trace): while trace is not None: filename = trace.tb_frame.f_code.co_filename if filename in ( '<frozen importlib._bootstrap>', '<frozen importlib._bootstrap_external>'): # Do not stop on inner exceptions in py3 while importing return True # ImportError should appear in a user's code, not inside debugger for file in FILES_WITH_IMPORT_HOOKS: if filename.endswith(file): return True trace = trace.tb_next return False def cached_call(obj, func, *args): cached_name = '_cached_' + func.__name__ if not hasattr(obj, cached_name): setattr(obj, cached_name, func(*args)) return getattr(obj, cached_name) class FramesList(object): def __init__(self): self._frames = [] # If available, the line number for the frame will be gotten from this dict, # otherwise frame.f_lineno will be used (needed for unhandled exceptions as # the place where we report may be different from the place where it's raised). self.frame_id_to_lineno = {} self.exc_type = None self.exc_desc = None self.trace_obj = None # This may be set to set the current frame (for the case where we have # an unhandled exception where we want to show the root bu we have a different # executing frame). self.current_frame = None # This is to know whether an exception was extracted from a __cause__ or __context__. self.exc_context_msg = '' def append(self, frame): self._frames.append(frame) def last_frame(self): return self._frames[-1] def __len__(self): return len(self._frames) def __iter__(self): return iter(self._frames) def __repr__(self): lst = ['FramesList('] lst.append('\n exc_type: ') lst.append(str(self.exc_type)) lst.append('\n exc_desc: ') lst.append(str(self.exc_desc)) lst.append('\n trace_obj: ') lst.append(str(self.trace_obj)) lst.append('\n current_frame: ') lst.append(str(self.current_frame)) for frame in self._frames: lst.append('\n ') lst.append(repr(frame)) lst.append(',') lst.append('\n)') return ''.join(lst) __str__ = __repr__ class _DummyFrameWrapper(object): def __init__(self, frame, f_lineno, f_back): self._base_frame = frame self.f_lineno = f_lineno self.f_back = f_back self.f_trace = None original_code = frame.f_code self.f_code = FCode(original_code.co_name , original_code.co_filename) @property def f_locals(self): return self._base_frame.f_locals @property def f_globals(self): return self._base_frame.f_globals _cause_message = ( "\nThe above exception was the direct cause " "of the following exception:\n\n") _context_message = ( "\nDuring handling of the above exception, " "another exception occurred:\n\n") def create_frames_list_from_exception_cause(trace_obj, frame, exc_type, exc_desc, memo): lst = [] msg = '<Unknown context>' try: exc_cause = getattr(exc_desc, '__cause__', None) msg = _cause_message except Exception: exc_cause = None if exc_cause is None: try: exc_cause = getattr(exc_desc, '__context__', None) msg = _context_message except Exception: exc_cause = None if exc_cause is None or id(exc_cause) in memo: return None # The traceback module does this, so, let's play safe here too... memo.add(id(exc_cause)) tb = exc_cause.__traceback__ frames_list = FramesList() frames_list.exc_type = type(exc_cause) frames_list.exc_desc = exc_cause frames_list.trace_obj = tb frames_list.exc_context_msg = msg while tb is not None: # Note: we don't use the actual tb.tb_frame because if the cause of the exception # uses the same frame object, the id(frame) would be the same and the frame_id_to_lineno # would be wrong as the same frame needs to appear with 2 different lines. lst.append((_DummyFrameWrapper(tb.tb_frame, tb.tb_lineno, None), tb.tb_lineno)) tb = tb.tb_next for tb_frame, tb_lineno in lst: frames_list.append(tb_frame) frames_list.frame_id_to_lineno[id(tb_frame)] = tb_lineno return frames_list def create_frames_list_from_traceback(trace_obj, frame, exc_type, exc_desc, exception_type=None): ''' :param trace_obj: This is the traceback from which the list should be created. :param frame: This is the first frame to be considered (i.e.: topmost frame). If None is passed, all the frames from the traceback are shown (so, None should be passed for unhandled exceptions). :param exception_type: If this is an unhandled exception or user unhandled exception, we'll not trim the stack to create from the passed frame, rather, we'll just mark the frame in the frames list. ''' lst = [] tb = trace_obj if tb is not None and tb.tb_frame is not None: f = tb.tb_frame.f_back while f is not None: lst.insert(0, (f, f.f_lineno)) f = f.f_back while tb is not None: lst.append((tb.tb_frame, tb.tb_lineno)) tb = tb.tb_next curr = exc_desc memo = set() while True: initial = curr try: curr = getattr(initial, '__cause__', None) except Exception: curr = None if curr is None: try: curr = getattr(initial, '__context__', None) except Exception: curr = None if curr is None or id(curr) in memo: break # The traceback module does this, so, let's play safe here too... memo.add(id(curr)) tb = getattr(curr, '__traceback__', None) while tb is not None: # Note: we don't use the actual tb.tb_frame because if the cause of the exception # uses the same frame object, the id(frame) would be the same and the frame_id_to_lineno # would be wrong as the same frame needs to appear with 2 different lines. lst.append((_DummyFrameWrapper(tb.tb_frame, tb.tb_lineno, None), tb.tb_lineno)) tb = tb.tb_next frames_list = None for tb_frame, tb_lineno in reversed(lst): if frames_list is None and ( (frame is tb_frame) or (frame is None) or (exception_type == EXCEPTION_TYPE_USER_UNHANDLED) ): frames_list = FramesList() if frames_list is not None: frames_list.append(tb_frame) frames_list.frame_id_to_lineno[id(tb_frame)] = tb_lineno if frames_list is None and frame is not None: # Fallback (shouldn't happen in practice). pydev_log.info('create_frames_list_from_traceback did not find topmost frame in list.') frames_list = create_frames_list_from_frame(frame) frames_list.exc_type = exc_type frames_list.exc_desc = exc_desc frames_list.trace_obj = trace_obj if exception_type == EXCEPTION_TYPE_USER_UNHANDLED: frames_list.current_frame = frame elif exception_type == EXCEPTION_TYPE_UNHANDLED: if len(frames_list) > 0: frames_list.current_frame = frames_list.last_frame() return frames_list def create_frames_list_from_frame(frame): lst = FramesList() while frame is not None: lst.append(frame) frame = frame.f_back return lst
8,923
Python
28.452145
121
0.596212
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_code_to_source.py
""" Decompiler that can be used with the debugger (where statements correctly represent the line numbers). Note: this is a work in progress / proof of concept / not ready to be used. """ import dis from _pydevd_bundle.pydevd_collect_bytecode_info import iter_instructions from _pydev_bundle import pydev_log import sys import inspect from io import StringIO class _Stack(object): def __init__(self): self._contents = [] def push(self, obj): # print('push', obj) self._contents.append(obj) def pop(self): return self._contents.pop(-1) INDENT_MARKER = object() DEDENT_MARKER = object() _SENTINEL = object() DEBUG = False class _Token(object): def __init__(self, i_line, instruction=None, tok=_SENTINEL, priority=0, after=None, end_of_line=False): ''' :param i_line: :param instruction: :param tok: :param priority: :param after: :param end_of_line: Marker to signal only after all the other tokens have been written. ''' self.i_line = i_line if tok is not _SENTINEL: self.tok = tok else: if instruction is not None: if inspect.iscode(instruction.argval): self.tok = '' else: self.tok = str(instruction.argval) else: raise AssertionError('Either the tok or the instruction is needed.') self.instruction = instruction self.priority = priority self.end_of_line = end_of_line self._after_tokens = set() self._after_handler_tokens = set() if after: self.mark_after(after) def mark_after(self, v): if isinstance(v, _Token): self._after_tokens.add(v) elif isinstance(v, _BaseHandler): self._after_handler_tokens.add(v) else: raise AssertionError('Unhandled: %s' % (v,)) def get_after_tokens(self): ret = self._after_tokens.copy() for handler in self._after_handler_tokens: ret.update(handler.tokens) return ret def __repr__(self): return 'Token(%s, after: %s)' % (self.tok, self.get_after_tokens()) __str__ = __repr__ class _Writer(object): def __init__(self): self.line_to_contents = {} self.all_tokens = set() def get_line(self, line): lst = self.line_to_contents.get(line) if lst is None: lst = self.line_to_contents[line] = [] return lst def indent(self, line): self.get_line(line).append(INDENT_MARKER) def dedent(self, line): self.get_line(line).append(DEDENT_MARKER) def write(self, line, token): if token in self.all_tokens: return self.all_tokens.add(token) assert isinstance(token, _Token) lst = self.get_line(line) lst.append(token) class _BaseHandler(object): def __init__(self, i_line, instruction, stack, writer, disassembler): self.i_line = i_line self.instruction = instruction self.stack = stack self.writer = writer self.disassembler = disassembler self.tokens = [] self._handle() def _write_tokens(self): for token in self.tokens: self.writer.write(token.i_line, token) def _handle(self): raise NotImplementedError(self) def __repr__(self, *args, **kwargs): try: return "%s line:%s" % (self.instruction, self.i_line) except: return object.__repr__(self) __str__ = __repr__ _op_name_to_handler = {} def _register(cls): _op_name_to_handler[cls.opname] = cls return cls class _BasePushHandler(_BaseHandler): def _handle(self): self.stack.push(self) class _BaseLoadHandler(_BasePushHandler): def _handle(self): _BasePushHandler._handle(self) self.tokens = [_Token(self.i_line, self.instruction)] @_register class _LoadBuildClass(_BasePushHandler): opname = "LOAD_BUILD_CLASS" @_register class _LoadConst(_BaseLoadHandler): opname = "LOAD_CONST" @_register class _LoadName(_BaseLoadHandler): opname = "LOAD_NAME" @_register class _LoadGlobal(_BaseLoadHandler): opname = "LOAD_GLOBAL" @_register class _LoadFast(_BaseLoadHandler): opname = "LOAD_FAST" @_register class _GetIter(_BaseHandler): ''' Implements TOS = iter(TOS). ''' opname = "GET_ITER" iter_target = None def _handle(self): self.iter_target = self.stack.pop() self.tokens.extend(self.iter_target.tokens) self.stack.push(self) @_register class _ForIter(_BaseHandler): ''' TOS is an iterator. Call its __next__() method. If this yields a new value, push it on the stack (leaving the iterator below it). If the iterator indicates it is exhausted TOS is popped, and the byte code counter is incremented by delta. ''' opname = "FOR_ITER" iter_in = None def _handle(self): self.iter_in = self.stack.pop() self.stack.push(self) def store_in_name(self, store_name): for_token = _Token(self.i_line, None, 'for ') self.tokens.append(for_token) prev = for_token t_name = _Token(store_name.i_line, store_name.instruction, after=prev) self.tokens.append(t_name) prev = t_name in_token = _Token(store_name.i_line, None, ' in ', after=prev) self.tokens.append(in_token) prev = in_token max_line = store_name.i_line if self.iter_in: for t in self.iter_in.tokens: t.mark_after(prev) max_line = max(max_line, t.i_line) prev = t self.tokens.extend(self.iter_in.tokens) colon_token = _Token(self.i_line, None, ':', after=prev) self.tokens.append(colon_token) prev = for_token self._write_tokens() @_register class _StoreName(_BaseHandler): ''' Implements name = TOS. namei is the index of name in the attribute co_names of the code object. The compiler tries to use STORE_FAST or STORE_GLOBAL if possible. ''' opname = "STORE_NAME" def _handle(self): v = self.stack.pop() if isinstance(v, _ForIter): v.store_in_name(self) else: if not isinstance(v, _MakeFunction) or v.is_lambda: line = self.i_line for t in v.tokens: line = min(line, t.i_line) t_name = _Token(line, self.instruction) t_equal = _Token(line, None, '=', after=t_name) self.tokens.append(t_name) self.tokens.append(t_equal) for t in v.tokens: t.mark_after(t_equal) self.tokens.extend(v.tokens) self._write_tokens() @_register class _ReturnValue(_BaseHandler): """ Returns with TOS to the caller of the function. """ opname = "RETURN_VALUE" def _handle(self): v = self.stack.pop() return_token = _Token(self.i_line, None, 'return ', end_of_line=True) self.tokens.append(return_token) for token in v.tokens: token.mark_after(return_token) self.tokens.extend(v.tokens) self._write_tokens() @_register class _CallFunction(_BaseHandler): """ CALL_FUNCTION(argc) Calls a callable object with positional arguments. argc indicates the number of positional arguments. The top of the stack contains positional arguments, with the right-most argument on top. Below the arguments is a callable object to call. CALL_FUNCTION pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object. Changed in version 3.6: This opcode is used only for calls with positional arguments. """ opname = "CALL_FUNCTION" def _handle(self): args = [] for _i in range(self.instruction.argval + 1): arg = self.stack.pop() args.append(arg) it = reversed(args) name = next(it) max_line = name.i_line for t in name.tokens: self.tokens.append(t) tok_open_parens = _Token(name.i_line, None, '(', after=name) self.tokens.append(tok_open_parens) prev = tok_open_parens for i, arg in enumerate(it): for t in arg.tokens: t.mark_after(name) t.mark_after(prev) max_line = max(max_line, t.i_line) self.tokens.append(t) prev = arg if i > 0: comma_token = _Token(prev.i_line, None, ',', after=prev) self.tokens.append(comma_token) prev = comma_token tok_close_parens = _Token(max_line, None, ')', after=prev) self.tokens.append(tok_close_parens) self._write_tokens() self.stack.push(self) @_register class _MakeFunctionPy3(_BaseHandler): """ Pushes a new function object on the stack. From bottom to top, the consumed stack must consist of values if the argument carries a specified flag value 0x01 a tuple of default values for positional-only and positional-or-keyword parameters in positional order 0x02 a dictionary of keyword-only parameters' default values 0x04 an annotation dictionary 0x08 a tuple containing cells for free variables, making a closure the code associated with the function (at TOS1) the qualified name of the function (at TOS) """ opname = "MAKE_FUNCTION" is_lambda = False def _handle(self): stack = self.stack self.qualified_name = stack.pop() self.code = stack.pop() default_node = None if self.instruction.argval & 0x01: default_node = stack.pop() is_lambda = self.is_lambda = '<lambda>' in [x.tok for x in self.qualified_name.tokens] if not is_lambda: def_token = _Token(self.i_line, None, 'def ') self.tokens.append(def_token) for token in self.qualified_name.tokens: self.tokens.append(token) if not is_lambda: token.mark_after(def_token) prev = token open_parens_token = _Token(self.i_line, None, '(', after=prev) self.tokens.append(open_parens_token) prev = open_parens_token code = self.code.instruction.argval if default_node: defaults = ([_SENTINEL] * (len(code.co_varnames) - len(default_node.instruction.argval))) + list(default_node.instruction.argval) else: defaults = [_SENTINEL] * len(code.co_varnames) for i, arg in enumerate(code.co_varnames): if i > 0: comma_token = _Token(prev.i_line, None, ', ', after=prev) self.tokens.append(comma_token) prev = comma_token arg_token = _Token(self.i_line, None, arg, after=prev) self.tokens.append(arg_token) default = defaults[i] if default is not _SENTINEL: eq_token = _Token(default_node.i_line, None, '=', after=prev) self.tokens.append(eq_token) prev = eq_token default_token = _Token(default_node.i_line, None, str(default), after=prev) self.tokens.append(default_token) prev = default_token tok_close_parens = _Token(prev.i_line, None, '):', after=prev) self.tokens.append(tok_close_parens) self._write_tokens() stack.push(self) self.writer.indent(prev.i_line + 1) self.writer.dedent(max(self.disassembler.merge_code(code))) _MakeFunction = _MakeFunctionPy3 def _print_after_info(line_contents, stream=None): if stream is None: stream = sys.stdout for token in line_contents: after_tokens = token.get_after_tokens() if after_tokens: s = '%s after: %s\n' % ( repr(token.tok), ('"' + '", "'.join(t.tok for t in token.get_after_tokens()) + '"')) stream.write(s) else: stream.write('%s (NO REQUISITES)' % repr(token.tok)) def _compose_line_contents(line_contents, previous_line_tokens): lst = [] handled = set() add_to_end_of_line = [] delete_indexes = [] for i, token in enumerate(line_contents): if token.end_of_line: add_to_end_of_line.append(token) delete_indexes.append(i) for i in reversed(delete_indexes): del line_contents[i] del delete_indexes while line_contents: added = False delete_indexes = [] for i, token in enumerate(line_contents): after_tokens = token.get_after_tokens() for after in after_tokens: if after not in handled and after not in previous_line_tokens: break else: added = True previous_line_tokens.add(token) handled.add(token) lst.append(token.tok) delete_indexes.append(i) for i in reversed(delete_indexes): del line_contents[i] if not added: if add_to_end_of_line: line_contents.extend(add_to_end_of_line) del add_to_end_of_line[:] continue # Something is off, let's just add as is. for token in line_contents: if token not in handled: lst.append(token.tok) stream = StringIO() _print_after_info(line_contents, stream) pydev_log.critical('Error. After markers are not correct:\n%s', stream.getvalue()) break return ''.join(lst) class _PyCodeToSource(object): def __init__(self, co, memo=None): if memo is None: memo = {} self.memo = memo self.co = co self.instructions = list(iter_instructions(co)) self.stack = _Stack() self.writer = _Writer() def _process_next(self, i_line): instruction = self.instructions.pop(0) handler_class = _op_name_to_handler.get(instruction.opname) if handler_class is not None: s = handler_class(i_line, instruction, self.stack, self.writer, self) if DEBUG: print(s) else: if DEBUG: print("UNHANDLED", instruction) def build_line_to_contents(self): co = self.co op_offset_to_line = dict(dis.findlinestarts(co)) curr_line_index = 0 instructions = self.instructions while instructions: instruction = instructions[0] new_line_index = op_offset_to_line.get(instruction.offset) if new_line_index is not None: if new_line_index is not None: curr_line_index = new_line_index self._process_next(curr_line_index) return self.writer.line_to_contents def merge_code(self, code): if DEBUG: print('merge code ----') # for d in dir(code): # if not d.startswith('_'): # print(d, getattr(code, d)) line_to_contents = _PyCodeToSource(code, self.memo).build_line_to_contents() lines = [] for line, contents in sorted(line_to_contents.items()): lines.append(line) self.writer.get_line(line).extend(contents) if DEBUG: print('end merge code ----') return lines def disassemble(self): show_lines = False line_to_contents = self.build_line_to_contents() stream = StringIO() last_line = 0 indent = '' previous_line_tokens = set() for i_line, contents in sorted(line_to_contents.items()): while last_line < i_line - 1: if show_lines: stream.write(u"%s.\n" % (last_line + 1,)) else: stream.write(u"\n") last_line += 1 line_contents = [] dedents_found = 0 for part in contents: if part is INDENT_MARKER: if DEBUG: print('found indent', i_line) indent += ' ' continue if part is DEDENT_MARKER: if DEBUG: print('found dedent', i_line) dedents_found += 1 continue line_contents.append(part) s = indent + _compose_line_contents(line_contents, previous_line_tokens) if show_lines: stream.write(u"%s. %s\n" % (i_line, s)) else: stream.write(u"%s\n" % s) if dedents_found: indent = indent[:-(4 * dedents_found)] last_line = i_line return stream.getvalue() def code_obj_to_source(co): """ Converts a code object to source code to provide a suitable representation for the compiler when the actual source code is not found. This is a work in progress / proof of concept / not ready to be used. """ ret = _PyCodeToSource(co).disassemble() if DEBUG: print(ret) return ret
17,622
Python
27.795752
141
0.563046
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_save_locals.py
""" Utility for saving locals. """ import sys try: import types frame_type = types.FrameType except: frame_type = type(sys._getframe()) def is_save_locals_available(): return save_locals_impl is not None def save_locals(frame): """ Copy values from locals_dict into the fast stack slots in the given frame. Note: the 'save_locals' branch had a different approach wrapping the frame (much more code, but it gives ideas on how to save things partially, not the 'whole' locals). """ if not isinstance(frame, frame_type): # Fix exception when changing Django variable (receiving DjangoTemplateFrame) return if save_locals_impl is not None: try: save_locals_impl(frame) except: pass def make_save_locals_impl(): """ Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger lock being taken in different order in different threads. """ try: if '__pypy__' in sys.builtin_module_names: import __pypy__ # @UnresolvedImport save_locals = __pypy__.locals_to_fast except: pass else: if '__pypy__' in sys.builtin_module_names: def save_locals_pypy_impl(frame): save_locals(frame) return save_locals_pypy_impl try: import ctypes locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast except: pass else: def save_locals_ctypes_impl(frame): locals_to_fast(ctypes.py_object(frame), ctypes.c_int(0)) return save_locals_ctypes_impl return None save_locals_impl = make_save_locals_impl() def update_globals_and_locals(updated_globals, initial_globals, frame): # We don't have the locals and passed all in globals, so, we have to # manually choose how to update the variables. # # Note that the current implementation is a bit tricky: it does work in general # but if we do something as 'some_var = 10' and 'some_var' is already defined to have # the value '10' in the globals, we won't actually put that value in the locals # (which means that the frame locals won't be updated). # Still, the approach to have a single namespace was chosen because it was the only # one that enabled creating and using variables during the same evaluation. assert updated_globals is not None f_locals = None for key, val in updated_globals.items(): if initial_globals.get(key) is not val: if f_locals is None: # Note: we call f_locals only once because each time # we call it the values may be reset. f_locals = frame.f_locals f_locals[key] = val if f_locals is not None: save_locals(frame)
3,020
Python
30.14433
140
0.647682
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_custom_frames.py
from _pydevd_bundle.pydevd_constants import get_current_thread_id, Null, ForkSafeLock from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame from _pydev_bundle._pydev_saved_modules import thread, threading import sys from _pydev_bundle import pydev_log DEBUG = False class CustomFramesContainer: # Actual Values initialized later on. custom_frames_lock = None # : :type custom_frames_lock: threading.Lock custom_frames = None _next_frame_id = None _py_db_command_thread_event = None def custom_frames_container_init(): # Note: no staticmethod on jython 2.1 (so, use free-function) CustomFramesContainer.custom_frames_lock = ForkSafeLock() # custom_frames can only be accessed if properly locked with custom_frames_lock! # Key is a string identifying the frame (as well as the thread it belongs to). # Value is a CustomFrame. # CustomFramesContainer.custom_frames = {} # Only to be used in this module CustomFramesContainer._next_frame_id = 0 # This is the event we must set to release an internal process events. It's later set by the actual debugger # when we do create the debugger. CustomFramesContainer._py_db_command_thread_event = Null() # Initialize it the first time (it may be reinitialized later on when dealing with a fork). custom_frames_container_init() class CustomFrame: def __init__(self, name, frame, thread_id): # 0 = string with the representation of that frame self.name = name # 1 = the frame to show self.frame = frame # 2 = an integer identifying the last time the frame was changed. self.mod_time = 0 # 3 = the thread id of the given frame self.thread_id = thread_id def add_custom_frame(frame, name, thread_id): ''' It's possible to show paused frames by adding a custom frame through this API (it's intended to be used for coroutines, but could potentially be used for generators too). :param frame: The topmost frame to be shown paused when a thread with thread.ident == thread_id is paused. :param name: The name to be shown for the custom thread in the UI. :param thread_id: The thread id to which this frame is related (must match thread.ident). :return: str Returns the custom thread id which will be used to show the given frame paused. ''' with CustomFramesContainer.custom_frames_lock: curr_thread_id = get_current_thread_id(threading.current_thread()) next_id = CustomFramesContainer._next_frame_id = CustomFramesContainer._next_frame_id + 1 # Note: the frame id kept contains an id and thread information on the thread where the frame was added # so that later on we can check if the frame is from the current thread by doing frame_id.endswith('|'+thread_id). frame_custom_thread_id = '__frame__:%s|%s' % (next_id, curr_thread_id) if DEBUG: sys.stderr.write('add_custom_frame: %s (%s) %s %s\n' % ( frame_custom_thread_id, get_abs_path_real_path_and_base_from_frame(frame)[-1], frame.f_lineno, frame.f_code.co_name)) CustomFramesContainer.custom_frames[frame_custom_thread_id] = CustomFrame(name, frame, thread_id) CustomFramesContainer._py_db_command_thread_event.set() return frame_custom_thread_id def update_custom_frame(frame_custom_thread_id, frame, thread_id, name=None): with CustomFramesContainer.custom_frames_lock: if DEBUG: sys.stderr.write('update_custom_frame: %s\n' % frame_custom_thread_id) try: old = CustomFramesContainer.custom_frames[frame_custom_thread_id] if name is not None: old.name = name old.mod_time += 1 old.thread_id = thread_id except: sys.stderr.write('Unable to get frame to replace: %s\n' % (frame_custom_thread_id,)) pydev_log.exception() CustomFramesContainer._py_db_command_thread_event.set() def remove_custom_frame(frame_custom_thread_id): with CustomFramesContainer.custom_frames_lock: if DEBUG: sys.stderr.write('remove_custom_frame: %s\n' % frame_custom_thread_id) CustomFramesContainer.custom_frames.pop(frame_custom_thread_id, None) CustomFramesContainer._py_db_command_thread_event.set()
4,399
Python
36.606837
133
0.677881
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_safe_repr.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. # Gotten from ptvsd for supporting the format expected there. import sys from _pydevd_bundle.pydevd_constants import IS_PY36_OR_GREATER import locale from _pydev_bundle import pydev_log class SafeRepr(object): # Can be used to override the encoding from locale.getpreferredencoding() locale_preferred_encoding = None # Can be used to override the encoding used for sys.stdout.encoding sys_stdout_encoding = None # String types are truncated to maxstring_outer when at the outer- # most level, and truncated to maxstring_inner characters inside # collections. maxstring_outer = 2 ** 16 maxstring_inner = 30 string_types = (str, bytes) bytes = bytes set_info = (set, '{', '}', False) frozenset_info = (frozenset, 'frozenset({', '})', False) int_types = (int,) long_iter_types = (list, tuple, bytearray, range, dict, set, frozenset) # Collection types are recursively iterated for each limit in # maxcollection. maxcollection = (15, 10) # Specifies type, prefix string, suffix string, and whether to include a # comma if there is only one element. (Using a sequence rather than a # mapping because we use isinstance() to determine the matching type.) collection_types = [ (tuple, '(', ')', True), (list, '[', ']', False), frozenset_info, set_info, ] try: from collections import deque collection_types.append((deque, 'deque([', '])', False)) except Exception: pass # type, prefix string, suffix string, item prefix string, # item key/value separator, item suffix string dict_types = [(dict, '{', '}', '', ': ', '')] try: from collections import OrderedDict dict_types.append((OrderedDict, 'OrderedDict([', '])', '(', ', ', ')')) except Exception: pass # All other types are treated identically to strings, but using # different limits. maxother_outer = 2 ** 16 maxother_inner = 30 convert_to_hex = False raw_value = False def __call__(self, obj): ''' :param object obj: The object for which we want a representation. :return str: Returns bytes encoded as utf-8 on py2 and str on py3. ''' try: return ''.join(self._repr(obj, 0)) except Exception: try: return 'An exception was raised: %r' % sys.exc_info()[1] except Exception: return 'An exception was raised' 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) # Determines whether an iterable exceeds the limits set in # maxlimits, and is therefore unsafe to repr(). def _is_long_iter(self, obj, level=0): try: # Strings have their own limits (and do not nest). Because # they don't have __iter__ in 2.x, this check goes before # the next one. if isinstance(obj, self.string_types): return len(obj) > self.maxstring_inner # If it's not an iterable (and not a string), it's fine. if not hasattr(obj, '__iter__'): return False # If it's not an instance of these collection types then it # is fine. Note: this is a fix for # https://github.com/Microsoft/ptvsd/issues/406 if not isinstance(obj, self.long_iter_types): return False # Iterable is its own iterator - this is a one-off iterable # like generator or enumerate(). We can't really count that, # but repr() for these should not include any elements anyway, # so we can treat it the same as non-iterables. if obj is iter(obj): return False # range reprs fine regardless of length. if isinstance(obj, range): return False # numpy and scipy collections (ndarray etc) have # self-truncating repr, so they're always safe. try: module = type(obj).__module__.partition('.')[0] if module in ('numpy', 'scipy'): return False except Exception: pass # Iterables that nest too deep are considered long. if level >= len(self.maxcollection): return True # It is too long if the length exceeds the limit, or any # of its elements are long iterables. if hasattr(obj, '__len__'): try: size = len(obj) except Exception: size = None if size is not None and size > self.maxcollection[level]: return True return any((self._is_long_iter(item, level + 1) for item in obj)) # noqa return any(i > self.maxcollection[level] or self._is_long_iter(item, level + 1) for i, item in enumerate(obj)) # noqa except Exception: # If anything breaks, assume the worst case. return True def _repr_iter(self, obj, level, prefix, suffix, comma_after_single_element=False): yield prefix if level >= len(self.maxcollection): yield '...' else: count = self.maxcollection[level] yield_comma = False for item in obj: if yield_comma: yield ', ' yield_comma = True count -= 1 if count <= 0: yield '...' break for p in self._repr(item, 100 if item is obj else level + 1): yield p else: if comma_after_single_element: if count == self.maxcollection[level] - 1: yield ',' yield suffix def _repr_long_iter(self, obj): try: length = hex(len(obj)) if self.convert_to_hex else len(obj) obj_repr = '<%s, len() = %s>' % (type(obj).__name__, length) except Exception: try: obj_repr = '<' + type(obj).__name__ + '>' except Exception: obj_repr = '<no repr available for object>' yield obj_repr def _repr_dict(self, obj, level, prefix, suffix, item_prefix, item_sep, item_suffix): if not obj: yield prefix + suffix return if level >= len(self.maxcollection): yield prefix + '...' + suffix return yield prefix count = self.maxcollection[level] yield_comma = False if IS_PY36_OR_GREATER: # On Python 3.6 (onwards) dictionaries now keep # insertion order. sorted_keys = list(obj) else: try: sorted_keys = sorted(obj) except Exception: sorted_keys = list(obj) for key in sorted_keys: if yield_comma: yield ', ' yield_comma = True count -= 1 if count <= 0: yield '...' break yield item_prefix for p in self._repr(key, level + 1): yield p yield item_sep try: item = obj[key] except Exception: yield '<?>' else: for p in self._repr(item, 100 if item is obj else level + 1): yield p yield item_suffix yield suffix def _repr_str(self, obj, level): try: if self.raw_value: # For raw value retrieval, ignore all limits. if isinstance(obj, bytes): yield obj.decode('latin-1') else: yield obj return limit_inner = self.maxother_inner limit_outer = self.maxother_outer limit = limit_inner if level > 0 else limit_outer if len(obj) <= limit: # Note that we check the limit before doing the repr (so, the final string # may actually be considerably bigger on some cases, as besides # the additional u, b, ' chars, some chars may be escaped in repr, so # even a single char such as \U0010ffff may end up adding more # chars than expected). yield self._convert_to_unicode_or_bytes_repr(repr(obj)) return # Slightly imprecise calculations - we may end up with a string that is # up to 6 characters longer than limit. If you need precise formatting, # you are using the wrong class. left_count, right_count = max(1, int(2 * limit / 3)), max(1, int(limit / 3)) # noqa # Important: only do repr after slicing to avoid duplicating a byte array that could be # huge. # Note: we don't deal with high surrogates here because we're not dealing with the # repr() of a random object. # i.e.: A high surrogate unicode char may be splitted on Py2, but as we do a `repr` # afterwards, that's ok. # Also, we just show the unicode/string/bytes repr() directly to make clear what the # input type was (so, on py2 a unicode would start with u' and on py3 a bytes would # start with b'). part1 = obj[:left_count] part1 = repr(part1) part1 = part1[:part1.rindex("'")] # Remove the last ' part2 = obj[-right_count:] part2 = repr(part2) part2 = part2[part2.index("'") + 1:] # Remove the first ' (and possibly u or b). yield part1 yield '...' yield part2 except: # This shouldn't really happen, but let's play it safe. pydev_log.exception('Error getting string representation to show.') for part in self._repr_obj(obj, level, self.maxother_inner, self.maxother_outer): yield part def _repr_other(self, obj, level): return self._repr_obj(obj, level, self.maxother_inner, self.maxother_outer) def _repr_obj(self, obj, level, limit_inner, limit_outer): try: if self.raw_value: # For raw value retrieval, ignore all limits. if isinstance(obj, bytes): yield obj.decode('latin-1') return try: mv = memoryview(obj) except Exception: yield self._convert_to_unicode_or_bytes_repr(repr(obj)) return else: # Map bytes to Unicode codepoints with same values. yield mv.tobytes().decode('latin-1') return elif self.convert_to_hex and isinstance(obj, self.int_types): obj_repr = hex(obj) else: obj_repr = repr(obj) except Exception: try: obj_repr = object.__repr__(obj) except Exception: try: obj_repr = '<no repr available for ' + type(obj).__name__ + '>' # noqa except Exception: obj_repr = '<no repr available for object>' limit = limit_inner if level > 0 else limit_outer if limit >= len(obj_repr): yield self._convert_to_unicode_or_bytes_repr(obj_repr) return # Slightly imprecise calculations - we may end up with a string that is # up to 3 characters longer than limit. If you need precise formatting, # you are using the wrong class. left_count, right_count = max(1, int(2 * limit / 3)), max(1, int(limit / 3)) # noqa yield obj_repr[:left_count] yield '...' yield obj_repr[-right_count:] def _convert_to_unicode_or_bytes_repr(self, obj_repr): return obj_repr def _bytes_as_unicode_if_possible(self, obj_repr): # We try to decode with 3 possible encoding (sys.stdout.encoding, # locale.getpreferredencoding() and 'utf-8). If no encoding can decode # the input, we return the original bytes. try_encodings = [] encoding = self.sys_stdout_encoding or getattr(sys.stdout, 'encoding', '') if encoding: try_encodings.append(encoding.lower()) preferred_encoding = self.locale_preferred_encoding or locale.getpreferredencoding() if preferred_encoding: preferred_encoding = preferred_encoding.lower() if preferred_encoding not in try_encodings: try_encodings.append(preferred_encoding) if 'utf-8' not in try_encodings: try_encodings.append('utf-8') for encoding in try_encodings: try: return obj_repr.decode(encoding) except UnicodeDecodeError: pass return obj_repr # Return the original version (in bytes)
14,554
Python
35.3875
130
0.535592
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_dont_trace.py
''' Support for a tag that allows skipping over functions while debugging. ''' import linecache import re # To suppress tracing a method, add the tag @DontTrace # to a comment either preceding or on the same line as # the method definition # # E.g.: # #@DontTrace # def test1(): # pass # # ... or ... # # def test2(): #@DontTrace # pass DONT_TRACE_TAG = '@DontTrace' # Regular expression to match a decorator (at the beginning # of a line). RE_DECORATOR = re.compile(r'^\s*@') # Mapping from code object to bool. # If the key exists, the value is the cached result of should_trace_hook _filename_to_ignored_lines = {} def default_should_trace_hook(frame, absolute_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(absolute_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(absolute_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[absolute_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) # method line should_trace_hook = None 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 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
3,567
Python
27.774193
110
0.561256
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_reload.py
""" Based on the python xreload. Changes ====================== 1. we don't recreate the old namespace from new classes. Rather, we keep the existing namespace, load a new version of it and update only some of the things we can inplace. That way, we don't break things such as singletons or end up with a second representation of the same class in memory. 2. If we find it to be a __metaclass__, we try to update it as a regular class. 3. We don't remove old attributes (and leave them lying around even if they're no longer used). 4. Reload hooks were changed These changes make it more stable, especially in the common case (where in a debug session only the contents of a function are changed), besides providing flexibility for users that want to extend on it. Hooks ====================== Classes/modules can be specially crafted to work with the reload (so that it can, for instance, update some constant which was changed). 1. To participate in the change of some attribute: In a module: __xreload_old_new__(namespace, name, old, new) in a class: @classmethod __xreload_old_new__(cls, name, old, new) A class or module may include a method called '__xreload_old_new__' which is called when we're unable to reload a given attribute. 2. To do something after the whole reload is finished: In a module: __xreload_after_reload_update__(namespace): In a class: @classmethod __xreload_after_reload_update__(cls): A class or module may include a method called '__xreload_after_reload_update__' which is called after the reload finishes. Important: when providing a hook, always use the namespace or cls provided and not anything in the global namespace, as the global namespace are only temporarily created during the reload and may not reflect the actual application state (while the cls and namespace passed are). Current limitations ====================== - Attributes/constants are added, but not changed (so singletons and the application state is not broken -- use provided hooks to workaround it). - Code using metaclasses may not always work. - Functions and methods using decorators (other than classmethod and staticmethod) are not handled correctly. - Renamings are not handled correctly. - Dependent modules are not reloaded. - New __slots__ can't be added to existing classes. Info ====================== Original: http://svn.python.org/projects/sandbox/trunk/xreload/xreload.py Note: it seems https://github.com/plone/plone.reload/blob/master/plone/reload/xreload.py enhances it (to check later) Interesting alternative: https://code.google.com/p/reimport/ Alternative to reload(). This works by executing the module in a scratch namespace, and then patching classes, methods and functions in place. This avoids the need to patch instances. New objects are copied into the target namespace. """ from _pydev_bundle.pydev_imports import execfile from _pydevd_bundle import pydevd_dont_trace import types from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import get_global_debugger NO_DEBUG = 0 LEVEL1 = 1 LEVEL2 = 2 DEBUG = NO_DEBUG def write_err(*args): py_db = get_global_debugger() if py_db is not None: new_lst = [] for a in args: new_lst.append(str(a)) msg = ' '.join(new_lst) s = 'code reload: %s\n' % (msg,) cmd = py_db.cmd_factory.make_io_message(s, 2) if py_db.writer is not None: py_db.writer.add_command(cmd) def notify_info0(*args): write_err(*args) def notify_info(*args): if DEBUG >= LEVEL1: write_err(*args) def notify_info2(*args): if DEBUG >= LEVEL2: write_err(*args) def notify_error(*args): write_err(*args) #======================================================================================================================= # code_objects_equal #======================================================================================================================= def code_objects_equal(code0, code1): for d in dir(code0): if d.startswith('_') or 'line' in d or d in ('replace', 'co_positions', 'co_qualname'): continue if getattr(code0, d) != getattr(code1, d): return False return True #======================================================================================================================= # xreload #======================================================================================================================= def xreload(mod): """Reload a module in place, updating classes, methods and functions. mod: a module object Returns a boolean indicating whether a change was done. """ r = Reload(mod) r.apply() found_change = r.found_change r = None pydevd_dont_trace.clear_trace_filter_cache() return found_change # This isn't actually used... Initially I planned to reload variables which are immutable on the # namespace, but this can destroy places where we're saving state, which may not be what we want, # so, we're being conservative and giving the user hooks if he wants to do a reload. # # immutable_types = [int, str, float, tuple] #That should be common to all Python versions # # for name in 'long basestr unicode frozenset'.split(): # try: # immutable_types.append(__builtins__[name]) # except: # pass #Just ignore: not all python versions are created equal. # immutable_types = tuple(immutable_types) #======================================================================================================================= # Reload #======================================================================================================================= class Reload: def __init__(self, mod, mod_name=None, mod_filename=None): self.mod = mod if mod_name: self.mod_name = mod_name else: self.mod_name = mod.__name__ if mod is not None else None if mod_filename: self.mod_filename = mod_filename else: self.mod_filename = mod.__file__ if mod is not None else None self.found_change = False def apply(self): mod = self.mod self._on_finish_callbacks = [] try: # Get the module namespace (dict) early; this is part of the type check modns = mod.__dict__ # Execute the code. We copy the module dict to a temporary; then # clear the module dict; then execute the new code in the module # dict; then swap things back and around. This trick (due to # Glyph Lefkowitz) ensures that the (readonly) __globals__ # attribute of methods and functions is set to the correct dict # object. new_namespace = modns.copy() new_namespace.clear() if self.mod_filename: new_namespace["__file__"] = self.mod_filename try: new_namespace["__builtins__"] = __builtins__ except NameError: raise # Ok if not there. if self.mod_name: new_namespace["__name__"] = self.mod_name if new_namespace["__name__"] == '__main__': # We do this because usually the __main__ starts-up the program, guarded by # the if __name__ == '__main__', but we don't want to start the program again # on a reload. new_namespace["__name__"] = '__main_reloaded__' execfile(self.mod_filename, new_namespace, new_namespace) # Now we get to the hard part oldnames = set(modns) newnames = set(new_namespace) # Create new tokens (note: not deleting existing) for name in newnames - oldnames: notify_info0('Added:', name, 'to namespace') self.found_change = True modns[name] = new_namespace[name] # Update in-place what we can for name in oldnames & newnames: self._update(modns, name, modns[name], new_namespace[name]) self._handle_namespace(modns) for c in self._on_finish_callbacks: c() del self._on_finish_callbacks[:] except: pydev_log.exception() def _handle_namespace(self, namespace, is_class_namespace=False): on_finish = None if is_class_namespace: xreload_after_update = getattr(namespace, '__xreload_after_reload_update__', None) if xreload_after_update is not None: self.found_change = True on_finish = lambda: xreload_after_update() elif '__xreload_after_reload_update__' in namespace: xreload_after_update = namespace['__xreload_after_reload_update__'] self.found_change = True on_finish = lambda: xreload_after_update(namespace) if on_finish is not None: # If a client wants to know about it, give him a chance. self._on_finish_callbacks.append(on_finish) def _update(self, namespace, name, oldobj, newobj, is_class_namespace=False): """Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update """ try: notify_info2('Updating: ', oldobj) if oldobj is newobj: # Probably something imported return if type(oldobj) is not type(newobj): # Cop-out: if the type changed, give up if name not in ('__builtins__',): notify_error('Type of: %s (old: %s != new: %s) changed... Skipping.' % (name, type(oldobj), type(newobj))) return if isinstance(newobj, types.FunctionType): self._update_function(oldobj, newobj) return if isinstance(newobj, types.MethodType): self._update_method(oldobj, newobj) return if isinstance(newobj, classmethod): self._update_classmethod(oldobj, newobj) return if isinstance(newobj, staticmethod): self._update_staticmethod(oldobj, newobj) return if hasattr(types, 'ClassType'): classtype = (types.ClassType, type) # object is not instance of types.ClassType. else: classtype = type if isinstance(newobj, classtype): self._update_class(oldobj, newobj) return # New: dealing with metaclasses. if hasattr(newobj, '__metaclass__') and hasattr(newobj, '__class__') and newobj.__metaclass__ == newobj.__class__: self._update_class(oldobj, newobj) return if namespace is not None: # Check for the `__xreload_old_new__` protocol (don't even compare things # as even doing a comparison may break things -- see: https://github.com/microsoft/debugpy/issues/615). xreload_old_new = None if is_class_namespace: xreload_old_new = getattr(namespace, '__xreload_old_new__', None) if xreload_old_new is not None: self.found_change = True xreload_old_new(name, oldobj, newobj) elif '__xreload_old_new__' in namespace: xreload_old_new = namespace['__xreload_old_new__'] xreload_old_new(namespace, name, oldobj, newobj) self.found_change = True # Too much information to the user... # else: # notify_info0('%s NOT updated. Create __xreload_old_new__(name, old, new) for custom reload' % (name,)) except: notify_error('Exception found when updating %s. Proceeding for other items.' % (name,)) pydev_log.exception() # All of the following functions have the same signature as _update() def _update_function(self, oldfunc, newfunc): """Update a function object.""" oldfunc.__doc__ = newfunc.__doc__ oldfunc.__dict__.update(newfunc.__dict__) try: newfunc.__code__ attr_name = '__code__' except AttributeError: newfunc.func_code attr_name = 'func_code' old_code = getattr(oldfunc, attr_name) new_code = getattr(newfunc, attr_name) if not code_objects_equal(old_code, new_code): notify_info0('Updated function code:', oldfunc) setattr(oldfunc, attr_name, new_code) self.found_change = True try: oldfunc.__defaults__ = newfunc.__defaults__ except AttributeError: oldfunc.func_defaults = newfunc.func_defaults return oldfunc def _update_method(self, oldmeth, newmeth): """Update a method object.""" # XXX What if im_func is not a function? if hasattr(oldmeth, 'im_func') and hasattr(newmeth, 'im_func'): self._update(None, None, oldmeth.im_func, newmeth.im_func) elif hasattr(oldmeth, '__func__') and hasattr(newmeth, '__func__'): self._update(None, None, oldmeth.__func__, newmeth.__func__) return oldmeth def _update_class(self, oldclass, newclass): """Update a class object.""" olddict = oldclass.__dict__ newdict = newclass.__dict__ oldnames = set(olddict) newnames = set(newdict) for name in newnames - oldnames: setattr(oldclass, name, newdict[name]) notify_info0('Added:', name, 'to', oldclass) self.found_change = True # Note: not removing old things... # for name in oldnames - newnames: # notify_info('Removed:', name, 'from', oldclass) # delattr(oldclass, name) for name in (oldnames & newnames) - set(['__dict__', '__doc__']): self._update(oldclass, name, olddict[name], newdict[name], is_class_namespace=True) old_bases = getattr(oldclass, '__bases__', None) new_bases = getattr(newclass, '__bases__', None) if str(old_bases) != str(new_bases): notify_error('Changing the hierarchy of a class is not supported. %s may be inconsistent.' % (oldclass,)) self._handle_namespace(oldclass, is_class_namespace=True) def _update_classmethod(self, oldcm, newcm): """Update a classmethod update.""" # While we can't modify the classmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns a method object) and update # it in-place. We don't have the class available to pass to # __get__() but any object except None will do. self._update(None, None, oldcm.__get__(0), newcm.__get__(0)) def _update_staticmethod(self, oldsm, newsm): """Update a staticmethod update.""" # While we can't modify the staticmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns it) and update it in-place. # We don't have the class available to pass to __get__() but any # object except None will do. self._update(None, None, oldsm.__get__(0), newsm.__get__(0))
15,773
Python
35.345622
126
0.572561
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_daemon_thread.py
from _pydev_bundle._pydev_saved_modules import threading from _pydev_bundle import _pydev_saved_modules from _pydevd_bundle.pydevd_utils import notify_about_gevent_if_needed import weakref from _pydevd_bundle.pydevd_constants import IS_JYTHON, IS_IRONPYTHON, \ PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS from _pydev_bundle.pydev_log import exception as pydev_log_exception import sys from _pydev_bundle import pydev_log import pydevd_tracing from _pydevd_bundle.pydevd_collect_bytecode_info import iter_instructions if IS_JYTHON: import org.python.core as JyCore # @UnresolvedImport class PyDBDaemonThread(threading.Thread): def __init__(self, py_db, target_and_args=None): ''' :param target_and_args: tuple(func, args, kwargs) if this should be a function and args to run. -- Note: use through run_as_pydevd_daemon_thread(). ''' threading.Thread.__init__(self) notify_about_gevent_if_needed() self._py_db = weakref.ref(py_db) self._kill_received = False mark_as_pydevd_daemon_thread(self) self._target_and_args = target_and_args @property def py_db(self): return self._py_db() def run(self): created_pydb_daemon = self.py_db.created_pydb_daemon_threads created_pydb_daemon[self] = 1 try: try: if IS_JYTHON and not isinstance(threading.current_thread(), threading._MainThread): # we shouldn't update sys.modules for the main thread, cause it leads to the second importing 'threading' # module, and the new instance of main thread is created ss = JyCore.PySystemState() # Note: Py.setSystemState() affects only the current thread. JyCore.Py.setSystemState(ss) self._stop_trace() self._on_run() except: if sys is not None and pydev_log_exception is not None: pydev_log_exception() finally: del created_pydb_daemon[self] def _on_run(self): if self._target_and_args is not None: target, args, kwargs = self._target_and_args target(*args, **kwargs) else: raise NotImplementedError('Should be reimplemented by: %s' % self.__class__) def do_kill_pydev_thread(self): if not self._kill_received: pydev_log.debug('%s received kill signal', self.name) self._kill_received = True def _stop_trace(self): if self.pydev_do_not_trace: pydevd_tracing.SetTrace(None) # no debugging on this thread def _collect_load_names(func): found_load_names = set() for instruction in iter_instructions(func.__code__): if instruction.opname in ('LOAD_GLOBAL', 'LOAD_ATTR', 'LOAD_METHOD'): found_load_names.add(instruction.argrepr) return found_load_names def _patch_threading_to_hide_pydevd_threads(): ''' Patches the needed functions on the `threading` module so that the pydevd threads are hidden. Note that we patch the functions __code__ to avoid issues if some code had already imported those variables prior to the patching. ''' found_load_names = _collect_load_names(threading.enumerate) # i.e.: we'll only apply the patching if the function seems to be what we expect. new_threading_enumerate = None if found_load_names in ( {'_active_limbo_lock', '_limbo', '_active', 'values', 'list'}, {'_active_limbo_lock', '_limbo', '_active', 'values', 'NULL + list'} ): pydev_log.debug('Applying patching to hide pydevd threads (Py3 version).') def new_threading_enumerate(): with _active_limbo_lock: ret = list(_active.values()) + list(_limbo.values()) return [t for t in ret if not getattr(t, 'is_pydev_daemon_thread', False)] elif found_load_names == set(('_active_limbo_lock', '_limbo', '_active', 'values')): pydev_log.debug('Applying patching to hide pydevd threads (Py2 version).') def new_threading_enumerate(): with _active_limbo_lock: ret = _active.values() + _limbo.values() return [t for t in ret if not getattr(t, 'is_pydev_daemon_thread', False)] else: pydev_log.info('Unable to hide pydevd threads. Found names in threading.enumerate: %s', found_load_names) if new_threading_enumerate is not None: def pydevd_saved_threading_enumerate(): with threading._active_limbo_lock: return list(threading._active.values()) + list(threading._limbo.values()) _pydev_saved_modules.pydevd_saved_threading_enumerate = pydevd_saved_threading_enumerate threading.enumerate.__code__ = new_threading_enumerate.__code__ # We also need to patch the active count (to match what we have in the enumerate). def new_active_count(): # Note: as this will be executed in the `threading` module, `enumerate` will # actually be threading.enumerate. return len(enumerate()) threading.active_count.__code__ = new_active_count.__code__ # When shutting down, Python (on some versions) may do something as: # # def _pickSomeNonDaemonThread(): # for t in enumerate(): # if not t.daemon and t.is_alive(): # return t # return None # # But in this particular case, we do want threads with `is_pydev_daemon_thread` to appear # explicitly due to the pydevd `CheckAliveThread` (because we want the shutdown to wait on it). # So, it can't rely on the `enumerate` for that anymore as it's patched to not return pydevd threads. if hasattr(threading, '_pickSomeNonDaemonThread'): def new_pick_some_non_daemon_thread(): with _active_limbo_lock: # Ok for py2 and py3. threads = list(_active.values()) + list(_limbo.values()) for t in threads: if not t.daemon and t.is_alive(): return t return None threading._pickSomeNonDaemonThread.__code__ = new_pick_some_non_daemon_thread.__code__ _patched_threading_to_hide_pydevd_threads = False def mark_as_pydevd_daemon_thread(thread): if not IS_JYTHON and not IS_IRONPYTHON and PYDEVD_APPLY_PATCHING_TO_HIDE_PYDEVD_THREADS: global _patched_threading_to_hide_pydevd_threads if not _patched_threading_to_hide_pydevd_threads: # When we mark the first thread as a pydevd daemon thread, we also change the threading # functions to hide pydevd threads. # Note: we don't just "hide" the pydevd threads from the threading module by not using it # (i.e.: just using the `thread.start_new_thread` instead of `threading.Thread`) # because there's 1 thread (the `CheckAliveThread`) which is a pydevd thread but # isn't really a daemon thread (so, we need CPython to wait on it for shutdown, # in which case it needs to be in `threading` and the patching would be needed anyways). _patched_threading_to_hide_pydevd_threads = True try: _patch_threading_to_hide_pydevd_threads() except: pydev_log.exception('Error applying patching to hide pydevd threads.') thread.pydev_do_not_trace = True thread.is_pydev_daemon_thread = True thread.daemon = True def run_as_pydevd_daemon_thread(py_db, func, *args, **kwargs): ''' Runs a function as a pydevd daemon thread (without any tracing in place). ''' t = PyDBDaemonThread(py_db, target_and_args=(func, args, kwargs)) t.name = '%s (pydevd daemon thread)' % (func.__name__,) t.start() return t
7,964
Python
40.056701
125
0.621673
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_filtering.py
import fnmatch import glob import os.path import sys from _pydev_bundle import pydev_log import pydevd_file_utils import json from collections import namedtuple from _pydev_bundle._pydev_saved_modules import threading from pydevd_file_utils import normcase from _pydevd_bundle.pydevd_constants import USER_CODE_BASENAMES_STARTING_WITH, \ LIBRARY_CODE_BASENAMES_STARTING_WITH, IS_PYPY, IS_WINDOWS from _pydevd_bundle import pydevd_constants ExcludeFilter = namedtuple('ExcludeFilter', 'name, exclude, is_path') def _convert_to_str_and_clear_empty(roots): new_roots = [] for root in roots: assert isinstance(root, str), '%s not str (found: %s)' % (root, type(root)) if root: new_roots.append(root) return new_roots def _check_matches(patterns, paths): if not patterns and not paths: # Matched to the end. return True if (not patterns and paths) or (patterns and not paths): return False pattern = normcase(patterns[0]) path = normcase(paths[0]) if not glob.has_magic(pattern): if pattern != path: return False elif pattern == '**': if len(patterns) == 1: return True # if ** is the last one it matches anything to the right. for i in range(len(paths)): # Recursively check the remaining patterns as the # current pattern could match any number of paths. if _check_matches(patterns[1:], paths[i:]): return True elif not fnmatch.fnmatch(path, pattern): # Current part doesn't match. return False return _check_matches(patterns[1:], paths[1:]) def glob_matches_path(path, pattern, sep=os.sep, altsep=os.altsep): if altsep: pattern = pattern.replace(altsep, sep) path = path.replace(altsep, sep) drive = '' if len(path) > 1 and path[1] == ':': drive, path = path[0], path[2:] if drive and len(pattern) > 1: if pattern[1] == ':': if drive.lower() != pattern[0].lower(): return False pattern = pattern[2:] patterns = pattern.split(sep) paths = path.split(sep) if paths: if paths[0] == '': paths = paths[1:] if patterns: if patterns[0] == '': patterns = patterns[1:] return _check_matches(patterns, paths) class FilesFiltering(object): ''' Note: calls at FilesFiltering are uncached. The actual API used should be through PyDB. ''' def __init__(self): self._exclude_filters = [] self._project_roots = [] self._library_roots = [] # Filter out libraries? self._use_libraries_filter = False self.require_module = False # True if some exclude filter filters by the module. self.set_use_libraries_filter(os.getenv('PYDEVD_FILTER_LIBRARIES') is not None) project_roots = os.getenv('IDE_PROJECT_ROOTS', None) if project_roots is not None: project_roots = project_roots.split(os.pathsep) else: project_roots = [] self.set_project_roots(project_roots) library_roots = os.getenv('LIBRARY_ROOTS', None) if library_roots is not None: library_roots = library_roots.split(os.pathsep) else: library_roots = self._get_default_library_roots() self.set_library_roots(library_roots) # Stepping filters. pydevd_filters = os.getenv('PYDEVD_FILTERS', '') # To filter out it's something as: {'**/not_my_code/**': True} if pydevd_filters: pydev_log.debug("PYDEVD_FILTERS %s", (pydevd_filters,)) if pydevd_filters.startswith('{'): # dict(glob_pattern (str) -> exclude(True or False)) exclude_filters = [] for key, val in json.loads(pydevd_filters).items(): exclude_filters.append(ExcludeFilter(key, val, True)) self._exclude_filters = exclude_filters else: # A ';' separated list of strings with globs for the # list of excludes. filters = pydevd_filters.split(';') new_filters = [] for new_filter in filters: if new_filter.strip(): new_filters.append(ExcludeFilter(new_filter.strip(), True, True)) self._exclude_filters = new_filters @classmethod def _get_default_library_roots(cls): pydev_log.debug("Collecting default library roots.") # Provide sensible defaults if not in env vars. import site roots = [] try: import sysconfig # Python 2.7 onwards only. except ImportError: pass else: for path_name in set(('stdlib', 'platstdlib', 'purelib', 'platlib')) & set(sysconfig.get_path_names()): roots.append(sysconfig.get_path(path_name)) # Make sure we always get at least the standard library location (based on the `os` and # `threading` modules -- it's a bit weird that it may be different on the ci, but it happens). roots.append(os.path.dirname(os.__file__)) roots.append(os.path.dirname(threading.__file__)) if IS_PYPY: # On PyPy 3.6 (7.3.1) it wrongly says that sysconfig.get_path('stdlib') is # <install>/lib-pypy when the installed version is <install>/lib_pypy. try: import _pypy_wait except ImportError: pydev_log.debug("Unable to import _pypy_wait on PyPy when collecting default library roots.") else: pypy_lib_dir = os.path.dirname(_pypy_wait.__file__) pydev_log.debug("Adding %s to default library roots.", pypy_lib_dir) roots.append(pypy_lib_dir) if hasattr(site, 'getusersitepackages'): site_paths = site.getusersitepackages() if isinstance(site_paths, (list, tuple)): for site_path in site_paths: roots.append(site_path) else: roots.append(site_paths) if hasattr(site, 'getsitepackages'): site_paths = site.getsitepackages() if isinstance(site_paths, (list, tuple)): for site_path in site_paths: roots.append(site_path) else: roots.append(site_paths) for path in sys.path: if os.path.exists(path) and os.path.basename(path) in ('site-packages', 'pip-global'): roots.append(path) roots.extend([os.path.realpath(path) for path in roots]) return sorted(set(roots)) def _fix_roots(self, roots): roots = _convert_to_str_and_clear_empty(roots) new_roots = [] for root in roots: path = self._absolute_normalized_path(root) if pydevd_constants.IS_WINDOWS: new_roots.append(path + '\\') else: new_roots.append(path + '/') return new_roots def _absolute_normalized_path(self, filename): ''' Provides a version of the filename that's absolute and normalized. ''' return normcase(pydevd_file_utils.absolute_path(filename)) def set_project_roots(self, project_roots): self._project_roots = self._fix_roots(project_roots) pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % project_roots) def _get_project_roots(self): return self._project_roots def set_library_roots(self, roots): self._library_roots = self._fix_roots(roots) pydev_log.debug("LIBRARY_ROOTS %s\n" % roots) def _get_library_roots(self): return self._library_roots def in_project_roots(self, received_filename): ''' Note: don't call directly. Use PyDb.in_project_scope (there's no caching here and it doesn't handle all possibilities for knowing whether a project is actually in the scope, it just handles the heuristics based on the absolute_normalized_filename without the actual frame). ''' DEBUG = False if received_filename.startswith(USER_CODE_BASENAMES_STARTING_WITH): if DEBUG: pydev_log.debug('In in_project_roots - user basenames - starts with %s (%s)', received_filename, USER_CODE_BASENAMES_STARTING_WITH) return True if received_filename.startswith(LIBRARY_CODE_BASENAMES_STARTING_WITH): if DEBUG: pydev_log.debug('Not in in_project_roots - library basenames - starts with %s (%s)', received_filename, LIBRARY_CODE_BASENAMES_STARTING_WITH) return False project_roots = self._get_project_roots() # roots are absolute/normalized. absolute_normalized_filename = self._absolute_normalized_path(received_filename) absolute_normalized_filename_as_dir = absolute_normalized_filename + ('\\' if IS_WINDOWS else '/') found_in_project = [] for root in project_roots: if root and (absolute_normalized_filename.startswith(root) or root == absolute_normalized_filename_as_dir): if DEBUG: pydev_log.debug('In project: %s (%s)', absolute_normalized_filename, root) found_in_project.append(root) found_in_library = [] library_roots = self._get_library_roots() for root in library_roots: if root and (absolute_normalized_filename.startswith(root) or root == absolute_normalized_filename_as_dir): found_in_library.append(root) if DEBUG: pydev_log.debug('In library: %s (%s)', absolute_normalized_filename, root) else: if DEBUG: pydev_log.debug('Not in library: %s (%s)', absolute_normalized_filename, root) if not project_roots: # If we have no project roots configured, consider it being in the project # roots if it's not found in site-packages (because we have defaults for those # and not the other way around). in_project = not found_in_library if DEBUG: pydev_log.debug('Final in project (no project roots): %s (%s)', absolute_normalized_filename, in_project) else: in_project = False if found_in_project: if not found_in_library: if DEBUG: pydev_log.debug('Final in project (in_project and not found_in_library): %s (True)', absolute_normalized_filename) in_project = True else: # Found in both, let's see which one has the bigger path matched. if max(len(x) for x in found_in_project) > max(len(x) for x in found_in_library): in_project = True if DEBUG: pydev_log.debug('Final in project (found in both): %s (%s)', absolute_normalized_filename, in_project) return in_project def use_libraries_filter(self): ''' Should we debug only what's inside project folders? ''' return self._use_libraries_filter def set_use_libraries_filter(self, use): pydev_log.debug("pydevd: Use libraries filter: %s\n" % use) self._use_libraries_filter = use def use_exclude_filters(self): # Enabled if we have any filters registered. return len(self._exclude_filters) > 0 def exclude_by_filter(self, absolute_filename, module_name): ''' :return: True if it should be excluded, False if it should be included and None if no rule matched the given file. ''' for exclude_filter in self._exclude_filters: # : :type exclude_filter: ExcludeFilter if exclude_filter.is_path: if glob_matches_path(absolute_filename, exclude_filter.name): return exclude_filter.exclude else: # Module filter. if exclude_filter.name == module_name or module_name.startswith(exclude_filter.name + '.'): return exclude_filter.exclude return None def set_exclude_filters(self, exclude_filters): ''' :param list(ExcludeFilter) exclude_filters: ''' self._exclude_filters = exclude_filters self.require_module = False for exclude_filter in exclude_filters: if not exclude_filter.is_path: self.require_module = True break
12,701
Python
37.259036
157
0.587985
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_process_net_command.py
import json import os import sys import traceback from _pydev_bundle import pydev_log from _pydev_bundle.pydev_log import exception as pydev_log_exception from _pydevd_bundle import pydevd_traceproperty, pydevd_dont_trace, pydevd_utils from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info from _pydevd_bundle.pydevd_breakpoints import get_exception_class from _pydevd_bundle.pydevd_comm import ( InternalEvaluateConsoleExpression, InternalConsoleGetCompletions, InternalRunCustomOperation, internal_get_next_statement_targets, internal_get_smart_step_into_variants) from _pydevd_bundle.pydevd_constants import NEXT_VALUE_SEPARATOR, IS_WINDOWS, NULL from _pydevd_bundle.pydevd_comm_constants import ID_TO_MEANING, CMD_EXEC_EXPRESSION, CMD_AUTHENTICATE from _pydevd_bundle.pydevd_api import PyDevdAPI from io import StringIO from _pydevd_bundle.pydevd_net_command import NetCommand from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id import pydevd_file_utils class _PyDevCommandProcessor(object): def __init__(self): self.api = PyDevdAPI() def process_net_command(self, py_db, cmd_id, seq, text): '''Processes a command received from the Java side @param cmd_id: the id of the command @param seq: the sequence of the command @param text: the text received in the command ''' # We can only proceed if the client is already authenticated or if it's the # command to authenticate. if cmd_id != CMD_AUTHENTICATE and not py_db.authentication.is_authenticated(): cmd = py_db.cmd_factory.make_error_message(seq, 'Client not authenticated.') py_db.writer.add_command(cmd) return meaning = ID_TO_MEANING[str(cmd_id)] # print('Handling %s (%s)' % (meaning, text)) method_name = meaning.lower() on_command = getattr(self, method_name.lower(), None) if on_command is None: # I have no idea what this is all about cmd = py_db.cmd_factory.make_error_message(seq, "unexpected command " + str(cmd_id)) py_db.writer.add_command(cmd) return lock = py_db._main_lock if method_name == 'cmd_thread_dump_to_stderr': # We can skip the main debugger locks for cases where we know it's not needed. lock = NULL with lock: try: cmd = on_command(py_db, cmd_id, seq, text) if cmd is not None: py_db.writer.add_command(cmd) except: if traceback is not None and sys is not None and pydev_log_exception is not None: pydev_log_exception() stream = StringIO() traceback.print_exc(file=stream) cmd = py_db.cmd_factory.make_error_message( seq, "Unexpected exception in process_net_command.\nInitial params: %s. Exception: %s" % ( ((cmd_id, seq, text), stream.getvalue()) ) ) if cmd is not None: py_db.writer.add_command(cmd) def cmd_authenticate(self, py_db, cmd_id, seq, text): access_token = text py_db.authentication.login(access_token) if py_db.authentication.is_authenticated(): return NetCommand(cmd_id, seq, py_db.authentication.client_access_token) return py_db.cmd_factory.make_error_message(seq, 'Client not authenticated.') def cmd_run(self, py_db, cmd_id, seq, text): return self.api.run(py_db) def cmd_list_threads(self, py_db, cmd_id, seq, text): return self.api.list_threads(py_db, seq) def cmd_get_completions(self, py_db, cmd_id, seq, text): # we received some command to get a variable # the text is: thread_id\tframe_id\tactivation token thread_id, frame_id, _scope, act_tok = text.split('\t', 3) return self.api.request_completions(py_db, seq, thread_id, frame_id, act_tok) def cmd_get_thread_stack(self, py_db, cmd_id, seq, text): # Receives a thread_id and a given timeout, which is the time we should # wait to the provide the stack if a given thread is still not suspended. if '\t' in text: thread_id, timeout = text.split('\t') timeout = float(timeout) else: thread_id = text timeout = .5 # Default timeout is .5 seconds return self.api.request_stack(py_db, seq, thread_id, fmt={}, timeout=timeout) def cmd_set_protocol(self, py_db, cmd_id, seq, text): return self.api.set_protocol(py_db, seq, text.strip()) def cmd_thread_suspend(self, py_db, cmd_id, seq, text): return self.api.request_suspend_thread(py_db, text.strip()) def cmd_version(self, py_db, cmd_id, seq, text): # Default based on server process (although ideally the IDE should # provide it). if IS_WINDOWS: ide_os = 'WINDOWS' else: ide_os = 'UNIX' # Breakpoints can be grouped by 'LINE' or by 'ID'. breakpoints_by = 'LINE' splitted = text.split('\t') if len(splitted) == 1: _local_version = splitted elif len(splitted) == 2: _local_version, ide_os = splitted elif len(splitted) == 3: _local_version, ide_os, breakpoints_by = splitted version_msg = self.api.set_ide_os_and_breakpoints_by(py_db, seq, ide_os, breakpoints_by) # Enable thread notifications after the version command is completed. self.api.set_enable_thread_notifications(py_db, True) return version_msg def cmd_thread_run(self, py_db, cmd_id, seq, text): return self.api.request_resume_thread(text.strip()) def _cmd_step(self, py_db, cmd_id, seq, text): return self.api.request_step(py_db, text.strip(), cmd_id) cmd_step_into = _cmd_step cmd_step_into_my_code = _cmd_step cmd_step_over = _cmd_step cmd_step_over_my_code = _cmd_step cmd_step_return = _cmd_step cmd_step_return_my_code = _cmd_step def _cmd_set_next(self, py_db, cmd_id, seq, text): thread_id, line, func_name = text.split('\t', 2) return self.api.request_set_next(py_db, seq, thread_id, cmd_id, None, line, func_name) cmd_run_to_line = _cmd_set_next cmd_set_next_statement = _cmd_set_next def cmd_smart_step_into(self, py_db, cmd_id, seq, text): thread_id, line_or_bytecode_offset, func_name = text.split('\t', 2) if line_or_bytecode_offset.startswith('offset='): # In this case we request the smart step into to stop given the parent frame # and the location of the parent frame bytecode offset and not just the func_name # (this implies that `CMD_GET_SMART_STEP_INTO_VARIANTS` was previously used # to know what are the valid stop points). temp = line_or_bytecode_offset[len('offset='):] if ';' in temp: offset, child_offset = temp.split(';') offset = int(offset) child_offset = int(child_offset) else: child_offset = -1 offset = int(temp) return self.api.request_smart_step_into(py_db, seq, thread_id, offset, child_offset) else: # If the offset wasn't passed, just use the line/func_name to do the stop. return self.api.request_smart_step_into_by_func_name(py_db, seq, thread_id, line_or_bytecode_offset, func_name) def cmd_reload_code(self, py_db, cmd_id, seq, text): text = text.strip() if '\t' not in text: module_name = text.strip() filename = None else: module_name, filename = text.split('\t', 1) self.api.request_reload_code(py_db, seq, module_name, filename) def cmd_change_variable(self, py_db, cmd_id, seq, text): # the text is: thread\tstackframe\tFRAME|GLOBAL\tattribute_to_change\tvalue_to_change thread_id, frame_id, scope, attr_and_value = text.split('\t', 3) tab_index = attr_and_value.rindex('\t') attr = attr_and_value[0:tab_index].replace('\t', '.') value = attr_and_value[tab_index + 1:] self.api.request_change_variable(py_db, seq, thread_id, frame_id, scope, attr, value) def cmd_get_variable(self, py_db, cmd_id, seq, text): # we received some command to get a variable # the text is: thread_id\tframe_id\tFRAME|GLOBAL\tattributes* thread_id, frame_id, scopeattrs = text.split('\t', 2) if scopeattrs.find('\t') != -1: # there are attributes beyond scope scope, attrs = scopeattrs.split('\t', 1) else: scope, attrs = (scopeattrs, None) self.api.request_get_variable(py_db, seq, thread_id, frame_id, scope, attrs) def cmd_get_array(self, py_db, cmd_id, seq, text): # Note: untested and unused in pydev # we received some command to get an array variable # the text is: thread_id\tframe_id\tFRAME|GLOBAL\tname\ttemp\troffs\tcoffs\trows\tcols\tformat roffset, coffset, rows, cols, format, thread_id, frame_id, scopeattrs = text.split('\t', 7) if scopeattrs.find('\t') != -1: # there are attributes beyond scope scope, attrs = scopeattrs.split('\t', 1) else: scope, attrs = (scopeattrs, None) self.api.request_get_array(py_db, seq, roffset, coffset, rows, cols, format, thread_id, frame_id, scope, attrs) def cmd_show_return_values(self, py_db, cmd_id, seq, text): show_return_values = text.split('\t')[1] self.api.set_show_return_values(py_db, int(show_return_values) == 1) def cmd_load_full_value(self, py_db, cmd_id, seq, text): # Note: untested and unused in pydev thread_id, frame_id, scopeattrs = text.split('\t', 2) vars = scopeattrs.split(NEXT_VALUE_SEPARATOR) self.api.request_load_full_value(py_db, seq, thread_id, frame_id, vars) def cmd_get_description(self, py_db, cmd_id, seq, text): # Note: untested and unused in pydev thread_id, frame_id, expression = text.split('\t', 2) self.api.request_get_description(py_db, seq, thread_id, frame_id, expression) def cmd_get_frame(self, py_db, cmd_id, seq, text): thread_id, frame_id, scope = text.split('\t', 2) self.api.request_get_frame(py_db, seq, thread_id, frame_id) def cmd_set_break(self, py_db, cmd_id, seq, text): # func name: 'None': match anything. Empty: match global, specified: only method context. # command to add some breakpoint. # text is filename\tline. Add to breakpoints dictionary suspend_policy = u"NONE" # Can be 'NONE' or 'ALL' is_logpoint = False hit_condition = None if py_db._set_breakpoints_with_id: try: try: breakpoint_id, btype, filename, line, func_name, condition, expression, hit_condition, is_logpoint, suspend_policy = text.split(u'\t', 9) except ValueError: # not enough values to unpack # No suspend_policy passed (use default). breakpoint_id, btype, filename, line, func_name, condition, expression, hit_condition, is_logpoint = text.split(u'\t', 8) is_logpoint = is_logpoint == u'True' except ValueError: # not enough values to unpack breakpoint_id, btype, filename, line, func_name, condition, expression = text.split(u'\t', 6) breakpoint_id = int(breakpoint_id) line = int(line) # We must restore new lines and tabs as done in # AbstractDebugTarget.breakpointAdded condition = condition.replace(u"@_@NEW_LINE_CHAR@_@", u'\n').\ replace(u"@_@TAB_CHAR@_@", u'\t').strip() expression = expression.replace(u"@_@NEW_LINE_CHAR@_@", u'\n').\ replace(u"@_@TAB_CHAR@_@", u'\t').strip() else: # Note: this else should be removed after PyCharm migrates to setting # breakpoints by id (and ideally also provides func_name). btype, filename, line, func_name, suspend_policy, condition, expression = text.split(u'\t', 6) # If we don't have an id given for each breakpoint, consider # the id to be the line. breakpoint_id = line = int(line) condition = condition.replace(u"@_@NEW_LINE_CHAR@_@", u'\n'). \ replace(u"@_@TAB_CHAR@_@", u'\t').strip() expression = expression.replace(u"@_@NEW_LINE_CHAR@_@", u'\n'). \ replace(u"@_@TAB_CHAR@_@", u'\t').strip() if condition is not None and (len(condition) <= 0 or condition == u"None"): condition = None if expression is not None and (len(expression) <= 0 or expression == u"None"): expression = None if hit_condition is not None and (len(hit_condition) <= 0 or hit_condition == u"None"): hit_condition = None def on_changed_breakpoint_state(breakpoint_id, add_breakpoint_result): error_code = add_breakpoint_result.error_code translated_line = add_breakpoint_result.translated_line translated_filename = add_breakpoint_result.translated_filename msg = '' if error_code: if error_code == self.api.ADD_BREAKPOINT_FILE_NOT_FOUND: msg = 'pydev debugger: Trying to add breakpoint to file that does not exist: %s (will have no effect).\n' % (translated_filename,) elif error_code == self.api.ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS: msg = 'pydev debugger: Trying to add breakpoint to file that is excluded by filters: %s (will have no effect).\n' % (translated_filename,) elif error_code == self.api.ADD_BREAKPOINT_LAZY_VALIDATION: msg = '' # Ignore this here (if/when loaded, it'll call on_changed_breakpoint_state again accordingly). elif error_code == self.api.ADD_BREAKPOINT_INVALID_LINE: msg = 'pydev debugger: Trying to add breakpoint to line (%s) that is not valid in: %s.\n' % (translated_line, translated_filename,) else: # Shouldn't get here. msg = 'pydev debugger: Breakpoint not validated (reason unknown -- please report as error): %s (%s).\n' % (translated_filename, translated_line) else: if add_breakpoint_result.original_line != translated_line: msg = 'pydev debugger (info): Breakpoint in line: %s moved to line: %s (in %s).\n' % (add_breakpoint_result.original_line, translated_line, translated_filename) if msg: py_db.writer.add_command(py_db.cmd_factory.make_warning_message(msg)) result = self.api.add_breakpoint( py_db, self.api.filename_to_str(filename), btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint, on_changed_breakpoint_state=on_changed_breakpoint_state) on_changed_breakpoint_state(breakpoint_id, result) def cmd_remove_break(self, py_db, cmd_id, seq, text): # command to remove some breakpoint # text is type\file\tid. Remove from breakpoints dictionary breakpoint_type, filename, breakpoint_id = text.split('\t', 2) filename = self.api.filename_to_str(filename) try: breakpoint_id = int(breakpoint_id) except ValueError: pydev_log.critical('Error removing breakpoint. Expected breakpoint_id to be an int. Found: %s', breakpoint_id) else: self.api.remove_breakpoint(py_db, filename, breakpoint_type, breakpoint_id) def _cmd_exec_or_evaluate_expression(self, py_db, cmd_id, seq, text): # command to evaluate the given expression # text is: thread\tstackframe\tLOCAL\texpression attr_to_set_result = "" try: thread_id, frame_id, scope, expression, trim, attr_to_set_result = text.split('\t', 5) except ValueError: thread_id, frame_id, scope, expression, trim = text.split('\t', 4) is_exec = cmd_id == CMD_EXEC_EXPRESSION trim_if_too_big = int(trim) == 1 self.api.request_exec_or_evaluate( py_db, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result) cmd_evaluate_expression = _cmd_exec_or_evaluate_expression cmd_exec_expression = _cmd_exec_or_evaluate_expression def cmd_console_exec(self, py_db, cmd_id, seq, text): # command to exec expression in console, in case expression is only partially valid 'False' is returned # text is: thread\tstackframe\tLOCAL\texpression thread_id, frame_id, scope, expression = text.split('\t', 3) self.api.request_console_exec(py_db, seq, thread_id, frame_id, expression) def cmd_set_path_mapping_json(self, py_db, cmd_id, seq, text): ''' :param text: Json text. Something as: { "pathMappings": [ { "localRoot": "c:/temp", "remoteRoot": "/usr/temp" } ], "debug": true, "force": false } ''' as_json = json.loads(text) force = as_json.get('force', False) path_mappings = [] for pathMapping in as_json.get('pathMappings', []): localRoot = pathMapping.get('localRoot', '') remoteRoot = pathMapping.get('remoteRoot', '') if (localRoot != '') and (remoteRoot != ''): path_mappings.append((localRoot, remoteRoot)) if bool(path_mappings) or force: pydevd_file_utils.setup_client_server_paths(path_mappings) debug = as_json.get('debug', False) if debug or force: pydevd_file_utils.DEBUG_CLIENT_SERVER_TRANSLATION = debug def cmd_set_py_exception_json(self, py_db, cmd_id, seq, text): # This API is optional and works 'in bulk' -- it's possible # to get finer-grained control with CMD_ADD_EXCEPTION_BREAK/CMD_REMOVE_EXCEPTION_BREAK # which allows setting caught/uncaught per exception, although global settings such as: # - skip_on_exceptions_thrown_in_same_context # - ignore_exceptions_thrown_in_lines_with_ignore_exception # must still be set through this API (before anything else as this clears all existing # exception breakpoints). try: py_db.break_on_uncaught_exceptions = {} py_db.break_on_caught_exceptions = {} py_db.break_on_user_uncaught_exceptions = {} as_json = json.loads(text) break_on_uncaught = as_json.get('break_on_uncaught', False) break_on_caught = as_json.get('break_on_caught', False) break_on_user_caught = as_json.get('break_on_user_caught', False) py_db.skip_on_exceptions_thrown_in_same_context = as_json.get('skip_on_exceptions_thrown_in_same_context', False) py_db.ignore_exceptions_thrown_in_lines_with_ignore_exception = as_json.get('ignore_exceptions_thrown_in_lines_with_ignore_exception', False) ignore_libraries = as_json.get('ignore_libraries', False) exception_types = as_json.get('exception_types', []) for exception_type in exception_types: if not exception_type: continue py_db.add_break_on_exception( exception_type, condition=None, expression=None, notify_on_handled_exceptions=break_on_caught, notify_on_unhandled_exceptions=break_on_uncaught, notify_on_user_unhandled_exceptions=break_on_user_caught, notify_on_first_raise_only=True, ignore_libraries=ignore_libraries, ) py_db.on_breakpoints_changed() except: pydev_log.exception("Error when setting exception list. Received: %s", text) def cmd_set_py_exception(self, py_db, cmd_id, seq, text): # DEPRECATED. Use cmd_set_py_exception_json instead. try: splitted = text.split(';') py_db.break_on_uncaught_exceptions = {} py_db.break_on_caught_exceptions = {} py_db.break_on_user_uncaught_exceptions = {} if len(splitted) >= 5: if splitted[0] == 'true': break_on_uncaught = True else: break_on_uncaught = False if splitted[1] == 'true': break_on_caught = True else: break_on_caught = False if splitted[2] == 'true': py_db.skip_on_exceptions_thrown_in_same_context = True else: py_db.skip_on_exceptions_thrown_in_same_context = False if splitted[3] == 'true': py_db.ignore_exceptions_thrown_in_lines_with_ignore_exception = True else: py_db.ignore_exceptions_thrown_in_lines_with_ignore_exception = False if splitted[4] == 'true': ignore_libraries = True else: ignore_libraries = False for exception_type in splitted[5:]: exception_type = exception_type.strip() if not exception_type: continue py_db.add_break_on_exception( exception_type, condition=None, expression=None, notify_on_handled_exceptions=break_on_caught, notify_on_unhandled_exceptions=break_on_uncaught, notify_on_user_unhandled_exceptions=False, # TODO (not currently supported in this API). notify_on_first_raise_only=True, ignore_libraries=ignore_libraries, ) else: pydev_log.exception("Expected to have at least 5 ';' separated items. Received: %s", text) except: pydev_log.exception("Error when setting exception list. Received: %s", text) def _load_source(self, py_db, cmd_id, seq, text): filename = text filename = self.api.filename_to_str(filename) self.api.request_load_source(py_db, seq, filename) cmd_load_source = _load_source cmd_get_file_contents = _load_source def cmd_load_source_from_frame_id(self, py_db, cmd_id, seq, text): frame_id = text self.api.request_load_source_from_frame_id(py_db, seq, frame_id) def cmd_set_property_trace(self, py_db, cmd_id, seq, text): # Command which receives whether to trace property getter/setter/deleter # text is feature_state(true/false);disable_getter/disable_setter/disable_deleter if text: splitted = text.split(';') if len(splitted) >= 3: if not py_db.disable_property_trace and splitted[0] == 'true': # Replacing property by custom property only when the debugger starts pydevd_traceproperty.replace_builtin_property() py_db.disable_property_trace = True # Enable/Disable tracing of the property getter if splitted[1] == 'true': py_db.disable_property_getter_trace = True else: py_db.disable_property_getter_trace = False # Enable/Disable tracing of the property setter if splitted[2] == 'true': py_db.disable_property_setter_trace = True else: py_db.disable_property_setter_trace = False # Enable/Disable tracing of the property deleter if splitted[3] == 'true': py_db.disable_property_deleter_trace = True else: py_db.disable_property_deleter_trace = False def cmd_add_exception_break(self, py_db, cmd_id, seq, text): # Note that this message has some idiosyncrasies... # # notify_on_handled_exceptions can be 0, 1 or 2 # 0 means we should not stop on handled exceptions. # 1 means we should stop on handled exceptions showing it on all frames where the exception passes. # 2 means we should stop on handled exceptions but we should only notify about it once. # # To ignore_libraries properly, besides setting ignore_libraries to 1, the IDE_PROJECT_ROOTS environment # variable must be set (so, we'll ignore anything not below IDE_PROJECT_ROOTS) -- this is not ideal as # the environment variable may not be properly set if it didn't start from the debugger (we should # create a custom message for that). # # There are 2 global settings which can only be set in CMD_SET_PY_EXCEPTION. Namely: # # py_db.skip_on_exceptions_thrown_in_same_context # - If True, we should only show the exception in a caller, not where it was first raised. # # py_db.ignore_exceptions_thrown_in_lines_with_ignore_exception # - If True exceptions thrown in lines with '@IgnoreException' will not be shown. condition = "" expression = "" if text.find('\t') != -1: try: exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, ignore_libraries = text.split('\t', 5) except: exception, notify_on_handled_exceptions, notify_on_unhandled_exceptions, ignore_libraries = text.split('\t', 3) else: exception, notify_on_handled_exceptions, notify_on_unhandled_exceptions, ignore_libraries = text, 0, 0, 0 condition = condition.replace("@_@NEW_LINE_CHAR@_@", '\n').replace("@_@TAB_CHAR@_@", '\t').strip() if condition is not None and (len(condition) == 0 or condition == "None"): condition = None expression = expression.replace("@_@NEW_LINE_CHAR@_@", '\n').replace("@_@TAB_CHAR@_@", '\t').strip() if expression is not None and (len(expression) == 0 or expression == "None"): expression = None if exception.find('-') != -1: breakpoint_type, exception = exception.split('-') else: breakpoint_type = 'python' if breakpoint_type == 'python': self.api.add_python_exception_breakpoint( py_db, exception, condition, expression, notify_on_handled_exceptions=int(notify_on_handled_exceptions) > 0, notify_on_unhandled_exceptions=int(notify_on_unhandled_exceptions) == 1, notify_on_user_unhandled_exceptions=0, # TODO (not currently supported in this API). notify_on_first_raise_only=int(notify_on_handled_exceptions) == 2, ignore_libraries=int(ignore_libraries) > 0, ) else: self.api.add_plugins_exception_breakpoint(py_db, breakpoint_type, exception) def cmd_remove_exception_break(self, py_db, cmd_id, seq, text): exception = text if exception.find('-') != -1: exception_type, exception = exception.split('-') else: exception_type = 'python' if exception_type == 'python': self.api.remove_python_exception_breakpoint(py_db, exception) else: self.api.remove_plugins_exception_breakpoint(py_db, exception_type, exception) def cmd_add_django_exception_break(self, py_db, cmd_id, seq, text): self.api.add_plugins_exception_breakpoint(py_db, breakpoint_type='django', exception=text) def cmd_remove_django_exception_break(self, py_db, cmd_id, seq, text): self.api.remove_plugins_exception_breakpoint(py_db, exception_type='django', exception=text) def cmd_evaluate_console_expression(self, py_db, cmd_id, seq, text): # Command which takes care for the debug console communication if text != "": thread_id, frame_id, console_command = text.split('\t', 2) console_command, line = console_command.split('\t') if console_command == 'EVALUATE': int_cmd = InternalEvaluateConsoleExpression( seq, thread_id, frame_id, line, buffer_output=True) elif console_command == 'EVALUATE_UNBUFFERED': int_cmd = InternalEvaluateConsoleExpression( seq, thread_id, frame_id, line, buffer_output=False) elif console_command == 'GET_COMPLETIONS': int_cmd = InternalConsoleGetCompletions(seq, thread_id, frame_id, line) else: raise ValueError('Unrecognized command: %s' % (console_command,)) py_db.post_internal_command(int_cmd, thread_id) def cmd_run_custom_operation(self, py_db, cmd_id, seq, text): # Command which runs a custom operation if text != "": try: location, custom = text.split('||', 1) except: sys.stderr.write('Custom operation now needs a || separator. Found: %s\n' % (text,)) raise thread_id, frame_id, scopeattrs = location.split('\t', 2) if scopeattrs.find('\t') != -1: # there are attributes beyond scope scope, attrs = scopeattrs.split('\t', 1) else: scope, attrs = (scopeattrs, None) # : style: EXECFILE or EXEC # : encoded_code_or_file: file to execute or code # : fname: name of function to be executed in the resulting namespace style, encoded_code_or_file, fnname = custom.split('\t', 3) int_cmd = InternalRunCustomOperation(seq, thread_id, frame_id, scope, attrs, style, encoded_code_or_file, fnname) py_db.post_internal_command(int_cmd, thread_id) def cmd_ignore_thrown_exception_at(self, py_db, cmd_id, seq, text): if text: replace = 'REPLACE:' # Not all 3.x versions support u'REPLACE:', so, doing workaround. if text.startswith(replace): text = text[8:] py_db.filename_to_lines_where_exceptions_are_ignored.clear() if text: for line in text.split('||'): # Can be bulk-created (one in each line) original_filename, line_number = line.split('|') original_filename = self.api.filename_to_server(original_filename) canonical_normalized_filename = pydevd_file_utils.canonical_normalized_path(original_filename) absolute_filename = pydevd_file_utils.absolute_path(original_filename) if os.path.exists(absolute_filename): lines_ignored = py_db.filename_to_lines_where_exceptions_are_ignored.get(canonical_normalized_filename) if lines_ignored is None: lines_ignored = py_db.filename_to_lines_where_exceptions_are_ignored[canonical_normalized_filename] = {} lines_ignored[int(line_number)] = 1 else: sys.stderr.write('pydev debugger: warning: trying to ignore exception thrown'\ ' on file that does not exist: %s (will have no effect)\n' % (absolute_filename,)) def cmd_enable_dont_trace(self, py_db, cmd_id, seq, text): if text: true_str = 'true' # Not all 3.x versions support u'str', so, doing workaround. mode = text.strip() == true_str pydevd_dont_trace.trace_filter(mode) def cmd_redirect_output(self, py_db, cmd_id, seq, text): if text: py_db.enable_output_redirection('STDOUT' in text, 'STDERR' in text) def cmd_get_next_statement_targets(self, py_db, cmd_id, seq, text): thread_id, frame_id = text.split('\t', 1) py_db.post_method_as_internal_command( thread_id, internal_get_next_statement_targets, seq, thread_id, frame_id) def cmd_get_smart_step_into_variants(self, py_db, cmd_id, seq, text): thread_id, frame_id, start_line, end_line = text.split('\t', 3) py_db.post_method_as_internal_command( thread_id, internal_get_smart_step_into_variants, seq, thread_id, frame_id, start_line, end_line, set_additional_thread_info=set_additional_thread_info) def cmd_set_project_roots(self, py_db, cmd_id, seq, text): self.api.set_project_roots(py_db, text.split(u'\t')) def cmd_thread_dump_to_stderr(self, py_db, cmd_id, seq, text): pydevd_utils.dump_threads() def cmd_stop_on_start(self, py_db, cmd_id, seq, text): if text.strip() in ('True', 'true', '1'): self.api.stop_on_entry() def cmd_pydevd_json_config(self, py_db, cmd_id, seq, text): # Expected to receive a json string as: # { # 'skip_suspend_on_breakpoint_exception': [<exception names where we should suspend>], # 'skip_print_breakpoint_exception': [<exception names where we should print>], # 'multi_threads_single_notification': bool, # } msg = json.loads(text.strip()) if 'skip_suspend_on_breakpoint_exception' in msg: py_db.skip_suspend_on_breakpoint_exception = tuple( get_exception_class(x) for x in msg['skip_suspend_on_breakpoint_exception']) if 'skip_print_breakpoint_exception' in msg: py_db.skip_print_breakpoint_exception = tuple( get_exception_class(x) for x in msg['skip_print_breakpoint_exception']) if 'multi_threads_single_notification' in msg: py_db.multi_threads_single_notification = msg['multi_threads_single_notification'] def cmd_get_exception_details(self, py_db, cmd_id, seq, text): thread_id = text t = pydevd_find_thread_by_id(thread_id) frame = None if t and not getattr(t, 'pydev_do_not_trace', None): additional_info = set_additional_thread_info(t) frame = additional_info.get_topmost_frame(t) try: return py_db.cmd_factory.make_get_exception_details_message(py_db, seq, thread_id, frame) finally: frame = None t = None process_net_command = _PyDevCommandProcessor().process_net_command
35,106
Python
45.315303
180
0.59326
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_net_command_factory_xml.py
import json from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle._pydev_saved_modules import thread from _pydevd_bundle import pydevd_xml, pydevd_frame_utils, pydevd_constants, pydevd_utils from _pydevd_bundle.pydevd_comm_constants import ( CMD_THREAD_CREATE, CMD_THREAD_KILL, CMD_THREAD_SUSPEND, CMD_THREAD_RUN, CMD_GET_VARIABLE, CMD_EVALUATE_EXPRESSION, CMD_GET_FRAME, CMD_WRITE_TO_CONSOLE, CMD_GET_COMPLETIONS, CMD_LOAD_SOURCE, CMD_SET_NEXT_STATEMENT, CMD_EXIT, CMD_GET_FILE_CONTENTS, CMD_EVALUATE_CONSOLE_EXPRESSION, CMD_RUN_CUSTOM_OPERATION, CMD_GET_BREAKPOINT_EXCEPTION, CMD_SEND_CURR_EXCEPTION_TRACE, CMD_SEND_CURR_EXCEPTION_TRACE_PROCEEDED, CMD_SHOW_CONSOLE, CMD_GET_ARRAY, CMD_INPUT_REQUESTED, CMD_GET_DESCRIPTION, CMD_PROCESS_CREATED, CMD_SHOW_CYTHON_WARNING, CMD_LOAD_FULL_VALUE, CMD_GET_THREAD_STACK, CMD_GET_EXCEPTION_DETAILS, CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION, CMD_THREAD_RESUME_SINGLE_NOTIFICATION, CMD_GET_NEXT_STATEMENT_TARGETS, CMD_VERSION, CMD_RETURN, CMD_SET_PROTOCOL, CMD_ERROR, MAX_IO_MSG_SIZE, VERSION_STRING, CMD_RELOAD_CODE, CMD_LOAD_SOURCE_FROM_FRAME_ID) from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, get_thread_id, get_global_debugger, GetGlobalDebugger, set_global_debugger) # Keep for backward compatibility @UnusedImport from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND, NULL_EXIT_COMMAND from _pydevd_bundle.pydevd_utils import quote_smart as quote, get_non_pydevd_threads from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame import pydevd_file_utils from pydevd_tracing import get_exception_traceback_str from _pydev_bundle._pydev_completer import completions_to_xml from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_frame_utils import FramesList from io import StringIO #======================================================================================================================= # NetCommandFactory #======================================================================================================================= class NetCommandFactory(object): def __init__(self): self._additional_thread_id_to_thread_name = {} def _thread_to_xml(self, thread): """ thread information as XML """ name = pydevd_xml.make_valid_xml_value(thread.name) cmd_text = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread)) return cmd_text def make_error_message(self, seq, text): cmd = NetCommand(CMD_ERROR, seq, text) if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2: pydev_log.error("Error: %s" % (text,)) return cmd def make_protocol_set_message(self, seq): return NetCommand(CMD_SET_PROTOCOL, seq, '') def make_thread_created_message(self, thread): cmdText = "<xml>" + self._thread_to_xml(thread) + "</xml>" return NetCommand(CMD_THREAD_CREATE, 0, cmdText) def make_process_created_message(self): cmdText = '<process/>' return NetCommand(CMD_PROCESS_CREATED, 0, cmdText) def make_process_about_to_be_replaced_message(self): return NULL_NET_COMMAND def make_show_cython_warning_message(self): try: return NetCommand(CMD_SHOW_CYTHON_WARNING, 0, '') except: return self.make_error_message(0, get_exception_traceback_str()) def make_custom_frame_created_message(self, frame_id, frame_description): self._additional_thread_id_to_thread_name[frame_id] = frame_description frame_description = pydevd_xml.make_valid_xml_value(frame_description) return NetCommand(CMD_THREAD_CREATE, 0, '<xml><thread name="%s" id="%s"/></xml>' % (frame_description, frame_id)) def make_list_threads_message(self, py_db, seq): """ returns thread listing as XML """ try: threads = get_non_pydevd_threads() cmd_text = ["<xml>"] append = cmd_text.append for thread in threads: if is_thread_alive(thread): append(self._thread_to_xml(thread)) for thread_id, thread_name in list(self._additional_thread_id_to_thread_name.items()): name = pydevd_xml.make_valid_xml_value(thread_name) append('<thread name="%s" id="%s" />' % (quote(name), thread_id)) append("</xml>") return NetCommand(CMD_RETURN, seq, ''.join(cmd_text)) except: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0): """ Returns thread stack as XML. :param must_be_suspended: If True and the thread is not suspended, returns None. """ try: # If frame is None, the return is an empty frame list. cmd_text = ['<xml><thread id="%s">' % (thread_id,)] if topmost_frame is not None: try: # : :type suspended_frames_manager: SuspendedFramesManager suspended_frames_manager = py_db.suspended_frames_manager frames_list = suspended_frames_manager.get_frames_list(thread_id) if frames_list is None: # Could not find stack of suspended frame... if must_be_suspended: return None else: frames_list = pydevd_frame_utils.create_frames_list_from_frame(topmost_frame) cmd_text.append(self.make_thread_stack_str(py_db, frames_list)) finally: topmost_frame = None cmd_text.append('</thread></xml>') return NetCommand(CMD_GET_THREAD_STACK, seq, ''.join(cmd_text)) except: return self.make_error_message(seq, get_exception_traceback_str()) def make_variable_changed_message(self, seq, payload): # notify debugger that value was changed successfully return NetCommand(CMD_RETURN, seq, payload) def make_warning_message(self, msg): return self.make_io_message(msg, 2) def make_io_message(self, msg, ctx): ''' @param msg: the message to pass to the debug server @param ctx: 1 for stdio 2 for stderr ''' try: msg = pydevd_constants.as_str(msg) if len(msg) > MAX_IO_MSG_SIZE: msg = msg[0:MAX_IO_MSG_SIZE] msg += '...' msg = pydevd_xml.make_valid_xml_value(quote(msg, '/>_= ')) return NetCommand(str(CMD_WRITE_TO_CONSOLE), 0, '<xml><io s="%s" ctx="%s"/></xml>' % (msg, ctx)) except: return self.make_error_message(0, get_exception_traceback_str()) def make_version_message(self, seq): try: return NetCommand(CMD_VERSION, seq, VERSION_STRING) except: return self.make_error_message(seq, get_exception_traceback_str()) def make_thread_killed_message(self, tid): self._additional_thread_id_to_thread_name.pop(tid, None) try: return NetCommand(CMD_THREAD_KILL, 0, str(tid)) except: return self.make_error_message(0, get_exception_traceback_str()) def _iter_visible_frames_info(self, py_db, frames_list): assert frames_list.__class__ == FramesList for frame in frames_list: show_as_current_frame = frame is frames_list.current_frame if frame.f_code is None: pydev_log.info('Frame without f_code: %s', frame) continue # IronPython sometimes does not have it! method_name = frame.f_code.co_name # method name (if in method) or ? if global if method_name is None: pydev_log.info('Frame without co_name: %s', frame) continue # IronPython sometimes does not have it! abs_path_real_path_and_base = get_abs_path_real_path_and_base_from_frame(frame) if py_db.get_file_type(frame, abs_path_real_path_and_base) == py_db.PYDEV_FILE: # Skip pydevd files. frame = frame.f_back continue frame_id = id(frame) lineno = frames_list.frame_id_to_lineno.get(frame_id, frame.f_lineno) filename_in_utf8, lineno, changed = py_db.source_mapping.map_to_client(abs_path_real_path_and_base[0], lineno) new_filename_in_utf8, applied_mapping = pydevd_file_utils.map_file_to_client(filename_in_utf8) applied_mapping = applied_mapping or changed yield frame_id, frame, method_name, abs_path_real_path_and_base[0], new_filename_in_utf8, lineno, applied_mapping, show_as_current_frame def make_thread_stack_str(self, py_db, frames_list): assert frames_list.__class__ == FramesList make_valid_xml_value = pydevd_xml.make_valid_xml_value cmd_text_list = [] append = cmd_text_list.append try: for frame_id, frame, method_name, _original_filename, filename_in_utf8, lineno, _applied_mapping, _show_as_current_frame in self._iter_visible_frames_info( py_db, frames_list ): # print("file is ", filename_in_utf8) # print("line is ", lineno) # Note: variables are all gotten 'on-demand'. append('<frame id="%s" name="%s" ' % (frame_id , make_valid_xml_value(method_name))) append('file="%s" line="%s">' % (quote(make_valid_xml_value(filename_in_utf8), '/>_= \t'), lineno)) append("</frame>") except: pydev_log.exception() return ''.join(cmd_text_list) def make_thread_suspend_str( self, py_db, thread_id, frames_list, stop_reason=None, message=None, suspend_type="trace", ): """ :return tuple(str,str): Returns tuple(thread_suspended_str, thread_stack_str). i.e.: ( ''' <xml> <thread id="id" stop_reason="reason"> <frame id="id" name="functionName " file="file" line="line"> </frame> </thread> </xml> ''' , ''' <frame id="id" name="functionName " file="file" line="line"> </frame> ''' ) """ assert frames_list.__class__ == FramesList make_valid_xml_value = pydevd_xml.make_valid_xml_value cmd_text_list = [] append = cmd_text_list.append cmd_text_list.append('<xml>') if message: message = make_valid_xml_value(message) append('<thread id="%s"' % (thread_id,)) if stop_reason is not None: append(' stop_reason="%s"' % (stop_reason,)) if message is not None: append(' message="%s"' % (message,)) if suspend_type is not None: append(' suspend_type="%s"' % (suspend_type,)) append('>') thread_stack_str = self.make_thread_stack_str(py_db, frames_list) append(thread_stack_str) append("</thread></xml>") return ''.join(cmd_text_list), thread_stack_str def make_thread_suspend_message(self, py_db, thread_id, frames_list, stop_reason, message, suspend_type): try: thread_suspend_str, thread_stack_str = self.make_thread_suspend_str( py_db, thread_id, frames_list, stop_reason, message, suspend_type) cmd = NetCommand(CMD_THREAD_SUSPEND, 0, thread_suspend_str) cmd.thread_stack_str = thread_stack_str cmd.thread_suspend_str = thread_suspend_str return cmd except: return self.make_error_message(0, get_exception_traceback_str()) def make_thread_suspend_single_notification(self, py_db, thread_id, stop_reason): try: return NetCommand(CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION, 0, json.dumps( {'thread_id': thread_id, 'stop_reason':stop_reason})) except: return self.make_error_message(0, get_exception_traceback_str()) def make_thread_resume_single_notification(self, thread_id): try: return NetCommand(CMD_THREAD_RESUME_SINGLE_NOTIFICATION, 0, json.dumps( {'thread_id': thread_id})) except: return self.make_error_message(0, get_exception_traceback_str()) def make_thread_run_message(self, thread_id, reason): try: return NetCommand(CMD_THREAD_RUN, 0, "%s\t%s" % (thread_id, reason)) except: return self.make_error_message(0, get_exception_traceback_str()) def make_get_variable_message(self, seq, payload): try: return NetCommand(CMD_GET_VARIABLE, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_array_message(self, seq, payload): try: return NetCommand(CMD_GET_ARRAY, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_description_message(self, seq, payload): try: return NetCommand(CMD_GET_DESCRIPTION, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_frame_message(self, seq, payload): try: return NetCommand(CMD_GET_FRAME, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_evaluate_expression_message(self, seq, payload): try: return NetCommand(CMD_EVALUATE_EXPRESSION, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_completions_message(self, seq, completions, qualifier, start): try: payload = completions_to_xml(completions) return NetCommand(CMD_GET_COMPLETIONS, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_file_contents(self, seq, payload): try: return NetCommand(CMD_GET_FILE_CONTENTS, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_reloaded_code_message(self, seq, reloaded_ok): try: return NetCommand(CMD_RELOAD_CODE, seq, '<xml><reloaded ok="%s"></reloaded></xml>' % reloaded_ok) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_send_breakpoint_exception_message(self, seq, payload): try: return NetCommand(CMD_GET_BREAKPOINT_EXCEPTION, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def _make_send_curr_exception_trace_str(self, py_db, thread_id, exc_type, exc_desc, trace_obj): frames_list = pydevd_frame_utils.create_frames_list_from_traceback(trace_obj, None, exc_type, exc_desc) exc_type = pydevd_xml.make_valid_xml_value(str(exc_type)).replace('\t', ' ') or 'exception: type unknown' exc_desc = pydevd_xml.make_valid_xml_value(str(exc_desc)).replace('\t', ' ') or 'exception: no description' thread_suspend_str, thread_stack_str = self.make_thread_suspend_str( py_db, thread_id, frames_list, CMD_SEND_CURR_EXCEPTION_TRACE, '') return exc_type, exc_desc, thread_suspend_str, thread_stack_str def make_send_curr_exception_trace_message(self, py_db, seq, thread_id, curr_frame_id, exc_type, exc_desc, trace_obj): try: exc_type, exc_desc, thread_suspend_str, _thread_stack_str = self._make_send_curr_exception_trace_str( py_db, thread_id, exc_type, exc_desc, trace_obj) payload = str(curr_frame_id) + '\t' + exc_type + "\t" + exc_desc + "\t" + thread_suspend_str return NetCommand(CMD_SEND_CURR_EXCEPTION_TRACE, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_exception_details_message(self, py_db, seq, thread_id, topmost_frame): """Returns exception details as XML """ try: # If the debugger is not suspended, just return the thread and its id. cmd_text = ['<xml><thread id="%s" ' % (thread_id,)] if topmost_frame is not None: try: frame = topmost_frame topmost_frame = None while frame is not None: if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'): arg = frame.f_locals.get('arg', None) if arg is not None: exc_type, exc_desc, _thread_suspend_str, thread_stack_str = self._make_send_curr_exception_trace_str( py_db, thread_id, *arg) cmd_text.append('exc_type="%s" ' % (exc_type,)) cmd_text.append('exc_desc="%s" ' % (exc_desc,)) cmd_text.append('>') cmd_text.append(thread_stack_str) break frame = frame.f_back else: cmd_text.append('>') finally: frame = None cmd_text.append('</thread></xml>') return NetCommand(CMD_GET_EXCEPTION_DETAILS, seq, ''.join(cmd_text)) except: return self.make_error_message(seq, get_exception_traceback_str()) def make_send_curr_exception_trace_proceeded_message(self, seq, thread_id): try: return NetCommand(CMD_SEND_CURR_EXCEPTION_TRACE_PROCEEDED, 0, str(thread_id)) except: return self.make_error_message(0, get_exception_traceback_str()) def make_send_console_message(self, seq, payload): try: return NetCommand(CMD_EVALUATE_CONSOLE_EXPRESSION, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_custom_operation_message(self, seq, payload): try: return NetCommand(CMD_RUN_CUSTOM_OPERATION, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_load_source_message(self, seq, source): return NetCommand(CMD_LOAD_SOURCE, seq, source) def make_load_source_from_frame_id_message(self, seq, source): return NetCommand(CMD_LOAD_SOURCE_FROM_FRAME_ID, seq, source) def make_show_console_message(self, py_db, thread_id, frame): try: frames_list = pydevd_frame_utils.create_frames_list_from_frame(frame) thread_suspended_str, _thread_stack_str = self.make_thread_suspend_str( py_db, thread_id, frames_list, CMD_SHOW_CONSOLE, '') return NetCommand(CMD_SHOW_CONSOLE, 0, thread_suspended_str) except: return self.make_error_message(0, get_exception_traceback_str()) def make_input_requested_message(self, started): try: return NetCommand(CMD_INPUT_REQUESTED, 0, str(started)) except: return self.make_error_message(0, get_exception_traceback_str()) def make_set_next_stmnt_status_message(self, seq, is_success, exception_msg): try: message = str(is_success) + '\t' + exception_msg return NetCommand(CMD_SET_NEXT_STATEMENT, int(seq), message) except: return self.make_error_message(0, get_exception_traceback_str()) def make_load_full_value_message(self, seq, payload): try: return NetCommand(CMD_LOAD_FULL_VALUE, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_get_next_statement_targets_message(self, seq, payload): try: return NetCommand(CMD_GET_NEXT_STATEMENT_TARGETS, seq, payload) except Exception: return self.make_error_message(seq, get_exception_traceback_str()) def make_skipped_step_in_because_of_filters(self, py_db, frame): return NULL_NET_COMMAND # Not a part of the xml protocol def make_evaluation_timeout_msg(self, py_db, expression, thread): msg = '''pydevd: Evaluating: %s did not finish after %.2f seconds. This may mean a number of things: - This evaluation is really slow and this is expected. In this case it's possible to silence this error by raising the timeout, setting the PYDEVD_WARN_EVALUATION_TIMEOUT environment variable to a bigger value. - The evaluation may need other threads running while it's running: In this case, you may need to manually let other paused threads continue. Alternatively, it's also possible to skip breaking on a particular thread by setting a `pydev_do_not_trace = True` attribute in the related threading.Thread instance (if some thread should always be running and no breakpoints are expected to be hit in it). - The evaluation is deadlocked: In this case you may set the PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT environment variable to true so that a thread dump is shown along with this message and optionally, set the PYDEVD_INTERRUPT_THREAD_TIMEOUT to some value so that the debugger tries to interrupt the evaluation (if possible) when this happens. ''' % (expression, pydevd_constants.PYDEVD_WARN_EVALUATION_TIMEOUT) if pydevd_constants.PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT: stream = StringIO() pydevd_utils.dump_threads(stream, show_pydevd_threads=False) msg += '\n\n%s\n' % stream.getvalue() return self.make_warning_message(msg) def make_exit_command(self, py_db): return NULL_EXIT_COMMAND
22,531
Python
44.611336
167
0.602503
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_comm_constants.py
CMD_RUN = 101 CMD_LIST_THREADS = 102 CMD_THREAD_CREATE = 103 CMD_THREAD_KILL = 104 CMD_THREAD_SUSPEND = 105 CMD_THREAD_RUN = 106 CMD_STEP_INTO = 107 CMD_STEP_OVER = 108 CMD_STEP_RETURN = 109 CMD_GET_VARIABLE = 110 CMD_SET_BREAK = 111 CMD_REMOVE_BREAK = 112 CMD_EVALUATE_EXPRESSION = 113 CMD_GET_FRAME = 114 CMD_EXEC_EXPRESSION = 115 CMD_WRITE_TO_CONSOLE = 116 CMD_CHANGE_VARIABLE = 117 CMD_RUN_TO_LINE = 118 CMD_RELOAD_CODE = 119 CMD_GET_COMPLETIONS = 120 # Note: renumbered (conflicted on merge) CMD_CONSOLE_EXEC = 121 CMD_ADD_EXCEPTION_BREAK = 122 CMD_REMOVE_EXCEPTION_BREAK = 123 CMD_LOAD_SOURCE = 124 CMD_ADD_DJANGO_EXCEPTION_BREAK = 125 CMD_REMOVE_DJANGO_EXCEPTION_BREAK = 126 CMD_SET_NEXT_STATEMENT = 127 CMD_SMART_STEP_INTO = 128 CMD_EXIT = 129 CMD_SIGNATURE_CALL_TRACE = 130 CMD_SET_PY_EXCEPTION = 131 CMD_GET_FILE_CONTENTS = 132 CMD_SET_PROPERTY_TRACE = 133 # Pydev debug console commands CMD_EVALUATE_CONSOLE_EXPRESSION = 134 CMD_RUN_CUSTOM_OPERATION = 135 CMD_GET_BREAKPOINT_EXCEPTION = 136 CMD_STEP_CAUGHT_EXCEPTION = 137 CMD_SEND_CURR_EXCEPTION_TRACE = 138 CMD_SEND_CURR_EXCEPTION_TRACE_PROCEEDED = 139 CMD_IGNORE_THROWN_EXCEPTION_AT = 140 CMD_ENABLE_DONT_TRACE = 141 CMD_SHOW_CONSOLE = 142 CMD_GET_ARRAY = 143 CMD_STEP_INTO_MY_CODE = 144 CMD_GET_CONCURRENCY_EVENT = 145 CMD_SHOW_RETURN_VALUES = 146 CMD_INPUT_REQUESTED = 147 CMD_GET_DESCRIPTION = 148 CMD_PROCESS_CREATED = 149 CMD_SHOW_CYTHON_WARNING = 150 CMD_LOAD_FULL_VALUE = 151 CMD_GET_THREAD_STACK = 152 # This is mostly for unit-tests to diagnose errors on ci. CMD_THREAD_DUMP_TO_STDERR = 153 # Sent from the client to signal that we should stop when we start executing user code. CMD_STOP_ON_START = 154 # When the debugger is stopped in an exception, this command will provide the details of the current exception (in the current thread). CMD_GET_EXCEPTION_DETAILS = 155 # Allows configuring pydevd settings (can be called multiple times and only keys # available in the json will be configured -- keys not passed will not change the # previous configuration). CMD_PYDEVD_JSON_CONFIG = 156 CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION = 157 CMD_THREAD_RESUME_SINGLE_NOTIFICATION = 158 CMD_STEP_OVER_MY_CODE = 159 CMD_STEP_RETURN_MY_CODE = 160 CMD_SET_PY_EXCEPTION_JSON = 161 CMD_SET_PATH_MAPPING_JSON = 162 CMD_GET_SMART_STEP_INTO_VARIANTS = 163 # XXX: PyCharm has 160 for this (we're currently incompatible anyways). CMD_REDIRECT_OUTPUT = 200 CMD_GET_NEXT_STATEMENT_TARGETS = 201 CMD_SET_PROJECT_ROOTS = 202 CMD_MODULE_EVENT = 203 CMD_PROCESS_EVENT = 204 CMD_AUTHENTICATE = 205 CMD_STEP_INTO_COROUTINE = 206 CMD_LOAD_SOURCE_FROM_FRAME_ID = 207 CMD_SET_FUNCTION_BREAK = 208 CMD_VERSION = 501 CMD_RETURN = 502 CMD_SET_PROTOCOL = 503 CMD_ERROR = 901 # this number can be changed if there's need to do so # if the io is too big, we'll not send all (could make the debugger too non-responsive) MAX_IO_MSG_SIZE = 10000 VERSION_STRING = "@@BUILD_NUMBER@@" from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding file_system_encoding = getfilesystemencoding() filesystem_encoding_is_utf8 = file_system_encoding.lower() in ('utf-8', 'utf_8', 'utf8') ID_TO_MEANING = { '101': 'CMD_RUN', '102': 'CMD_LIST_THREADS', '103': 'CMD_THREAD_CREATE', '104': 'CMD_THREAD_KILL', '105': 'CMD_THREAD_SUSPEND', '106': 'CMD_THREAD_RUN', '107': 'CMD_STEP_INTO', '108': 'CMD_STEP_OVER', '109': 'CMD_STEP_RETURN', '110': 'CMD_GET_VARIABLE', '111': 'CMD_SET_BREAK', '112': 'CMD_REMOVE_BREAK', '113': 'CMD_EVALUATE_EXPRESSION', '114': 'CMD_GET_FRAME', '115': 'CMD_EXEC_EXPRESSION', '116': 'CMD_WRITE_TO_CONSOLE', '117': 'CMD_CHANGE_VARIABLE', '118': 'CMD_RUN_TO_LINE', '119': 'CMD_RELOAD_CODE', '120': 'CMD_GET_COMPLETIONS', '121': 'CMD_CONSOLE_EXEC', '122': 'CMD_ADD_EXCEPTION_BREAK', '123': 'CMD_REMOVE_EXCEPTION_BREAK', '124': 'CMD_LOAD_SOURCE', '125': 'CMD_ADD_DJANGO_EXCEPTION_BREAK', '126': 'CMD_REMOVE_DJANGO_EXCEPTION_BREAK', '127': 'CMD_SET_NEXT_STATEMENT', '128': 'CMD_SMART_STEP_INTO', '129': 'CMD_EXIT', '130': 'CMD_SIGNATURE_CALL_TRACE', '131': 'CMD_SET_PY_EXCEPTION', '132': 'CMD_GET_FILE_CONTENTS', '133': 'CMD_SET_PROPERTY_TRACE', '134': 'CMD_EVALUATE_CONSOLE_EXPRESSION', '135': 'CMD_RUN_CUSTOM_OPERATION', '136': 'CMD_GET_BREAKPOINT_EXCEPTION', '137': 'CMD_STEP_CAUGHT_EXCEPTION', '138': 'CMD_SEND_CURR_EXCEPTION_TRACE', '139': 'CMD_SEND_CURR_EXCEPTION_TRACE_PROCEEDED', '140': 'CMD_IGNORE_THROWN_EXCEPTION_AT', '141': 'CMD_ENABLE_DONT_TRACE', '142': 'CMD_SHOW_CONSOLE', '143': 'CMD_GET_ARRAY', '144': 'CMD_STEP_INTO_MY_CODE', '145': 'CMD_GET_CONCURRENCY_EVENT', '146': 'CMD_SHOW_RETURN_VALUES', '147': 'CMD_INPUT_REQUESTED', '148': 'CMD_GET_DESCRIPTION', '149': 'CMD_PROCESS_CREATED', # Note: this is actually a notification of a sub-process created. '150': 'CMD_SHOW_CYTHON_WARNING', '151': 'CMD_LOAD_FULL_VALUE', '152': 'CMD_GET_THREAD_STACK', '153': 'CMD_THREAD_DUMP_TO_STDERR', '154': 'CMD_STOP_ON_START', '155': 'CMD_GET_EXCEPTION_DETAILS', '156': 'CMD_PYDEVD_JSON_CONFIG', '157': 'CMD_THREAD_SUSPEND_SINGLE_NOTIFICATION', '158': 'CMD_THREAD_RESUME_SINGLE_NOTIFICATION', '159': 'CMD_STEP_OVER_MY_CODE', '160': 'CMD_STEP_RETURN_MY_CODE', '161': 'CMD_SET_PY_EXCEPTION_JSON', '162': 'CMD_SET_PATH_MAPPING_JSON', '163': 'CMD_GET_SMART_STEP_INTO_VARIANTS', '200': 'CMD_REDIRECT_OUTPUT', '201': 'CMD_GET_NEXT_STATEMENT_TARGETS', '202': 'CMD_SET_PROJECT_ROOTS', '203': 'CMD_MODULE_EVENT', '204': 'CMD_PROCESS_EVENT', # DAP process event. '205': 'CMD_AUTHENTICATE', '206': 'CMD_STEP_INTO_COROUTINE', '207': 'CMD_LOAD_SOURCE_FROM_FRAME_ID', '501': 'CMD_VERSION', '502': 'CMD_RETURN', '503': 'CMD_SET_PROTOCOL', '901': 'CMD_ERROR', } def constant_to_str(constant): s = ID_TO_MEANING.get(str(constant)) if not s: s = '<Unknown: %s>' % (constant,) return s
6,084
Python
28.114832
135
0.674556
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_bytecode_utils.py
""" Bytecode analysing utils. Originally added for using in smart step into. Note: not importable from Python 2. """ from _pydev_bundle import pydev_log from types import CodeType from _pydevd_frame_eval.vendored.bytecode.instr import _Variable from _pydevd_frame_eval.vendored import bytecode from _pydevd_frame_eval.vendored.bytecode import cfg as bytecode_cfg import dis import opcode as _opcode from _pydevd_bundle.pydevd_constants import KeyifyList, DebugInfoHolder, IS_PY311_OR_GREATER from bisect import bisect from collections import deque # When True, throws errors on unknown bytecodes, when False, ignore those as if they didn't change the stack. STRICT_MODE = False DEBUG = False _BINARY_OPS = set([opname for opname in dis.opname if opname.startswith('BINARY_')]) _BINARY_OP_MAP = { 'BINARY_POWER': '__pow__', 'BINARY_MULTIPLY': '__mul__', 'BINARY_MATRIX_MULTIPLY': '__matmul__', 'BINARY_FLOOR_DIVIDE': '__floordiv__', 'BINARY_TRUE_DIVIDE': '__div__', 'BINARY_MODULO': '__mod__', 'BINARY_ADD': '__add__', 'BINARY_SUBTRACT': '__sub__', 'BINARY_LSHIFT': '__lshift__', 'BINARY_RSHIFT': '__rshift__', 'BINARY_AND': '__and__', 'BINARY_OR': '__or__', 'BINARY_XOR': '__xor__', 'BINARY_SUBSCR': '__getitem__', 'BINARY_DIVIDE': '__div__' } _COMP_OP_MAP = { '<': '__lt__', '<=': '__le__', '==': '__eq__', '!=': '__ne__', '>': '__gt__', '>=': '__ge__', 'in': '__contains__', 'not in': '__contains__', } class Target(object): __slots__ = ['arg', 'lineno', 'offset', 'children_targets'] def __init__(self, arg, lineno, offset, children_targets=()): self.arg = arg self.lineno = lineno self.offset = offset self.children_targets = children_targets def __repr__(self): ret = [] for s in self.__slots__: ret.append('%s: %s' % (s, getattr(self, s))) return 'Target(%s)' % ', '.join(ret) __str__ = __repr__ class _TargetIdHashable(object): def __init__(self, target): self.target = target def __eq__(self, other): if not hasattr(other, 'target'): return return other.target is self.target def __ne__(self, other): return not self == other def __hash__(self): return id(self.target) class _StackInterpreter(object): ''' Good reference: https://github.com/python/cpython/blob/fcb55c0037baab6f98f91ee38ce84b6f874f034a/Python/ceval.c ''' def __init__(self, bytecode): self.bytecode = bytecode self._stack = deque() self.function_calls = [] self.load_attrs = {} self.func = set() self.func_name_id_to_code_object = {} def __str__(self): return 'Stack:\nFunction calls:\n%s\nLoad attrs:\n%s\n' % (self.function_calls, list(self.load_attrs.values())) def _getname(self, instr): if instr.opcode in _opcode.hascompare: cmp_op = dis.cmp_op[instr.arg] if cmp_op not in ('exception match', 'BAD'): return _COMP_OP_MAP.get(cmp_op, cmp_op) return instr.arg def _getcallname(self, instr): if instr.name == 'BINARY_SUBSCR': return '__getitem__().__call__' if instr.name == 'CALL_FUNCTION': # Note: previously a '__call__().__call__' was returned, but this was a bit weird # and on Python 3.9 this construct could appear for some internal things where # it wouldn't be expected. # Note: it'd be what we had in func()(). return None if instr.name == 'MAKE_FUNCTION': return '__func__().__call__' if instr.name == 'LOAD_ASSERTION_ERROR': return 'AssertionError' name = self._getname(instr) if isinstance(name, CodeType): name = name.co_qualname # Note: only available for Python 3.11 if isinstance(name, _Variable): name = name.name if not isinstance(name, str): return None if name.endswith('>'): # xxx.<listcomp>, xxx.<lambda>, ... return name.split('.')[-1] return name def _no_stack_change(self, instr): pass # Can be aliased when the instruction does nothing. def on_LOAD_GLOBAL(self, instr): self._stack.append(instr) def on_POP_TOP(self, instr): try: self._stack.pop() except IndexError: pass # Ok (in the end of blocks) def on_LOAD_ATTR(self, instr): self.on_POP_TOP(instr) # replaces the current top self._stack.append(instr) self.load_attrs[_TargetIdHashable(instr)] = Target(self._getname(instr), instr.lineno, instr.offset) on_LOOKUP_METHOD = on_LOAD_ATTR # Improvement in PyPy def on_LOAD_CONST(self, instr): self._stack.append(instr) on_LOAD_DEREF = on_LOAD_CONST on_LOAD_NAME = on_LOAD_CONST on_LOAD_CLOSURE = on_LOAD_CONST on_LOAD_CLASSDEREF = on_LOAD_CONST # Although it actually changes the stack, it's inconsequential for us as a function call can't # really be found there. on_IMPORT_NAME = _no_stack_change on_IMPORT_FROM = _no_stack_change on_IMPORT_STAR = _no_stack_change on_SETUP_ANNOTATIONS = _no_stack_change def on_STORE_FAST(self, instr): try: self._stack.pop() except IndexError: pass # Ok, we may have a block just with the store # Note: it stores in the locals and doesn't put anything in the stack. on_STORE_GLOBAL = on_STORE_FAST on_STORE_DEREF = on_STORE_FAST on_STORE_ATTR = on_STORE_FAST on_STORE_NAME = on_STORE_FAST on_DELETE_NAME = on_POP_TOP on_DELETE_ATTR = on_POP_TOP on_DELETE_GLOBAL = on_POP_TOP on_DELETE_FAST = on_POP_TOP on_DELETE_DEREF = on_POP_TOP on_DICT_UPDATE = on_POP_TOP on_SET_UPDATE = on_POP_TOP on_GEN_START = on_POP_TOP def on_NOP(self, instr): pass def _handle_call_from_instr(self, func_name_instr, func_call_instr): self.load_attrs.pop(_TargetIdHashable(func_name_instr), None) call_name = self._getcallname(func_name_instr) target = None if not call_name: pass # Ignore if we can't identify a name elif call_name in ('<listcomp>', '<genexpr>', '<setcomp>', '<dictcomp>'): code_obj = self.func_name_id_to_code_object[_TargetIdHashable(func_name_instr)] if code_obj is not None: children_targets = _get_smart_step_into_targets(code_obj) if children_targets: # i.e.: we have targets inside of a <listcomp> or <genexpr>. # Note that to actually match this in the debugger we need to do matches on 2 frames, # the one with the <listcomp> and then the actual target inside the <listcomp>. target = Target(call_name, func_name_instr.lineno, func_call_instr.offset, children_targets) self.function_calls.append( target) else: # Ok, regular call target = Target(call_name, func_name_instr.lineno, func_call_instr.offset) self.function_calls.append(target) if DEBUG and target is not None: print('Created target', target) self._stack.append(func_call_instr) # Keep the func call as the result def on_COMPARE_OP(self, instr): try: _right = self._stack.pop() except IndexError: return try: _left = self._stack.pop() except IndexError: return cmp_op = dis.cmp_op[instr.arg] if cmp_op not in ('exception match', 'BAD'): self.function_calls.append(Target(self._getname(instr), instr.lineno, instr.offset)) self._stack.append(instr) def on_IS_OP(self, instr): try: self._stack.pop() except IndexError: return try: self._stack.pop() except IndexError: return def on_BINARY_SUBSCR(self, instr): try: _sub = self._stack.pop() except IndexError: return try: _container = self._stack.pop() except IndexError: return self.function_calls.append(Target(_BINARY_OP_MAP[instr.name], instr.lineno, instr.offset)) self._stack.append(instr) on_BINARY_MATRIX_MULTIPLY = on_BINARY_SUBSCR on_BINARY_POWER = on_BINARY_SUBSCR on_BINARY_MULTIPLY = on_BINARY_SUBSCR on_BINARY_FLOOR_DIVIDE = on_BINARY_SUBSCR on_BINARY_TRUE_DIVIDE = on_BINARY_SUBSCR on_BINARY_MODULO = on_BINARY_SUBSCR on_BINARY_ADD = on_BINARY_SUBSCR on_BINARY_SUBTRACT = on_BINARY_SUBSCR on_BINARY_LSHIFT = on_BINARY_SUBSCR on_BINARY_RSHIFT = on_BINARY_SUBSCR on_BINARY_AND = on_BINARY_SUBSCR on_BINARY_OR = on_BINARY_SUBSCR on_BINARY_XOR = on_BINARY_SUBSCR def on_LOAD_METHOD(self, instr): self.on_POP_TOP(instr) # Remove the previous as we're loading something from it. self._stack.append(instr) def on_MAKE_FUNCTION(self, instr): if not IS_PY311_OR_GREATER: # The qualifier name is no longer put in the stack. qualname = self._stack.pop() code_obj_instr = self._stack.pop() else: # In 3.11 the code object has a co_qualname which we can use. qualname = code_obj_instr = self._stack.pop() arg = instr.arg if arg & 0x08: _func_closure = self._stack.pop() if arg & 0x04: _func_annotations = self._stack.pop() if arg & 0x02: _func_kwdefaults = self._stack.pop() if arg & 0x01: _func_defaults = self._stack.pop() call_name = self._getcallname(qualname) if call_name in ('<genexpr>', '<listcomp>', '<setcomp>', '<dictcomp>'): if isinstance(code_obj_instr.arg, CodeType): self.func_name_id_to_code_object[_TargetIdHashable(qualname)] = code_obj_instr.arg self._stack.append(qualname) def on_LOAD_FAST(self, instr): self._stack.append(instr) def on_LOAD_ASSERTION_ERROR(self, instr): self._stack.append(instr) on_LOAD_BUILD_CLASS = on_LOAD_FAST def on_CALL_METHOD(self, instr): # pop the actual args for _ in range(instr.arg): self._stack.pop() func_name_instr = self._stack.pop() self._handle_call_from_instr(func_name_instr, instr) def on_PUSH_NULL(self, instr): self._stack.append(instr) def on_CALL_FUNCTION(self, instr): arg = instr.arg argc = arg & 0xff # positional args argc += ((arg >> 8) * 2) # keyword args # pop the actual args for _ in range(argc): try: self._stack.pop() except IndexError: return try: func_name_instr = self._stack.pop() except IndexError: return self._handle_call_from_instr(func_name_instr, instr) def on_CALL_FUNCTION_KW(self, instr): # names of kw args _names_of_kw_args = self._stack.pop() # pop the actual args arg = instr.arg argc = arg & 0xff # positional args argc += ((arg >> 8) * 2) # keyword args for _ in range(argc): self._stack.pop() func_name_instr = self._stack.pop() self._handle_call_from_instr(func_name_instr, instr) def on_CALL_FUNCTION_VAR(self, instr): # var name _var_arg = self._stack.pop() # pop the actual args arg = instr.arg argc = arg & 0xff # positional args argc += ((arg >> 8) * 2) # keyword args for _ in range(argc): self._stack.pop() func_name_instr = self._stack.pop() self._handle_call_from_instr(func_name_instr, instr) def on_CALL_FUNCTION_VAR_KW(self, instr): # names of kw args _names_of_kw_args = self._stack.pop() arg = instr.arg argc = arg & 0xff # positional args argc += ((arg >> 8) * 2) # keyword args # also pop **kwargs self._stack.pop() # pop the actual args for _ in range(argc): self._stack.pop() func_name_instr = self._stack.pop() self._handle_call_from_instr(func_name_instr, instr) def on_CALL_FUNCTION_EX(self, instr): if instr.arg & 0x01: _kwargs = self._stack.pop() _callargs = self._stack.pop() func_name_instr = self._stack.pop() self._handle_call_from_instr(func_name_instr, instr) on_YIELD_VALUE = _no_stack_change on_GET_AITER = _no_stack_change on_GET_ANEXT = _no_stack_change on_END_ASYNC_FOR = _no_stack_change on_BEFORE_ASYNC_WITH = _no_stack_change on_SETUP_ASYNC_WITH = _no_stack_change on_YIELD_FROM = _no_stack_change on_SETUP_LOOP = _no_stack_change on_FOR_ITER = _no_stack_change on_BREAK_LOOP = _no_stack_change on_JUMP_ABSOLUTE = _no_stack_change on_RERAISE = _no_stack_change on_LIST_TO_TUPLE = _no_stack_change on_CALL_FINALLY = _no_stack_change on_POP_FINALLY = _no_stack_change def on_JUMP_IF_FALSE_OR_POP(self, instr): try: self._stack.pop() except IndexError: return on_JUMP_IF_TRUE_OR_POP = on_JUMP_IF_FALSE_OR_POP def on_JUMP_IF_NOT_EXC_MATCH(self, instr): try: self._stack.pop() except IndexError: return try: self._stack.pop() except IndexError: return def on_ROT_TWO(self, instr): try: p0 = self._stack.pop() except IndexError: return try: p1 = self._stack.pop() except: self._stack.append(p0) return self._stack.append(p0) self._stack.append(p1) def on_ROT_THREE(self, instr): try: p0 = self._stack.pop() except IndexError: return try: p1 = self._stack.pop() except: self._stack.append(p0) return try: p2 = self._stack.pop() except: self._stack.append(p0) self._stack.append(p1) return self._stack.append(p0) self._stack.append(p1) self._stack.append(p2) def on_ROT_FOUR(self, instr): try: p0 = self._stack.pop() except IndexError: return try: p1 = self._stack.pop() except: self._stack.append(p0) return try: p2 = self._stack.pop() except: self._stack.append(p0) self._stack.append(p1) return try: p3 = self._stack.pop() except: self._stack.append(p0) self._stack.append(p1) self._stack.append(p2) return self._stack.append(p0) self._stack.append(p1) self._stack.append(p2) self._stack.append(p3) def on_BUILD_LIST_FROM_ARG(self, instr): self._stack.append(instr) def on_BUILD_MAP(self, instr): for _i in range(instr.arg): self._stack.pop() self._stack.pop() self._stack.append(instr) def on_BUILD_CONST_KEY_MAP(self, instr): self.on_POP_TOP(instr) # keys for _i in range(instr.arg): self.on_POP_TOP(instr) # value self._stack.append(instr) on_RETURN_VALUE = on_POP_TOP on_POP_JUMP_IF_FALSE = on_POP_TOP on_POP_JUMP_IF_TRUE = on_POP_TOP on_DICT_MERGE = on_POP_TOP on_LIST_APPEND = on_POP_TOP on_SET_ADD = on_POP_TOP on_LIST_EXTEND = on_POP_TOP on_UNPACK_EX = on_POP_TOP # ok: doesn't change the stack (converts top to getiter(top)) on_GET_ITER = _no_stack_change on_GET_AWAITABLE = _no_stack_change on_GET_YIELD_FROM_ITER = _no_stack_change def on_RETURN_GENERATOR(self, instr): self._stack.append(instr) on_RETURN_GENERATOR = _no_stack_change on_RESUME = _no_stack_change def on_MAP_ADD(self, instr): self.on_POP_TOP(instr) self.on_POP_TOP(instr) def on_UNPACK_SEQUENCE(self, instr): self._stack.pop() for _i in range(instr.arg): self._stack.append(instr) def on_BUILD_LIST(self, instr): for _i in range(instr.arg): self.on_POP_TOP(instr) self._stack.append(instr) on_BUILD_TUPLE = on_BUILD_LIST on_BUILD_STRING = on_BUILD_LIST on_BUILD_TUPLE_UNPACK_WITH_CALL = on_BUILD_LIST on_BUILD_TUPLE_UNPACK = on_BUILD_LIST on_BUILD_LIST_UNPACK = on_BUILD_LIST on_BUILD_MAP_UNPACK_WITH_CALL = on_BUILD_LIST on_BUILD_MAP_UNPACK = on_BUILD_LIST on_BUILD_SET = on_BUILD_LIST on_BUILD_SET_UNPACK = on_BUILD_LIST on_SETUP_FINALLY = _no_stack_change on_POP_FINALLY = _no_stack_change on_BEGIN_FINALLY = _no_stack_change on_END_FINALLY = _no_stack_change def on_RAISE_VARARGS(self, instr): for _i in range(instr.arg): self.on_POP_TOP(instr) on_POP_BLOCK = _no_stack_change on_JUMP_FORWARD = _no_stack_change on_POP_EXCEPT = _no_stack_change on_SETUP_EXCEPT = _no_stack_change on_WITH_EXCEPT_START = _no_stack_change on_END_FINALLY = _no_stack_change on_BEGIN_FINALLY = _no_stack_change on_SETUP_WITH = _no_stack_change on_WITH_CLEANUP_START = _no_stack_change on_WITH_CLEANUP_FINISH = _no_stack_change on_FORMAT_VALUE = _no_stack_change on_EXTENDED_ARG = _no_stack_change def on_INPLACE_ADD(self, instr): # This would actually pop 2 and leave the value in the stack. # In a += 1 it pop `a` and `1` and leave the resulting value # for a load. In our case, let's just pop the `1` and leave the `a` # instead of leaving the INPLACE_ADD bytecode. try: self._stack.pop() except IndexError: pass on_INPLACE_POWER = on_INPLACE_ADD on_INPLACE_MULTIPLY = on_INPLACE_ADD on_INPLACE_MATRIX_MULTIPLY = on_INPLACE_ADD on_INPLACE_TRUE_DIVIDE = on_INPLACE_ADD on_INPLACE_FLOOR_DIVIDE = on_INPLACE_ADD on_INPLACE_MODULO = on_INPLACE_ADD on_INPLACE_SUBTRACT = on_INPLACE_ADD on_INPLACE_RSHIFT = on_INPLACE_ADD on_INPLACE_LSHIFT = on_INPLACE_ADD on_INPLACE_AND = on_INPLACE_ADD on_INPLACE_OR = on_INPLACE_ADD on_INPLACE_XOR = on_INPLACE_ADD def on_DUP_TOP(self, instr): try: i = self._stack[-1] except IndexError: # ok (in the start of block) self._stack.append(instr) else: self._stack.append(i) def on_DUP_TOP_TWO(self, instr): if len(self._stack) == 0: self._stack.append(instr) return if len(self._stack) == 1: i = self._stack[-1] self._stack.append(i) self._stack.append(instr) return i = self._stack[-1] j = self._stack[-2] self._stack.append(j) self._stack.append(i) def on_BUILD_SLICE(self, instr): for _ in range(instr.arg): try: self._stack.pop() except IndexError: pass self._stack.append(instr) def on_STORE_SUBSCR(self, instr): try: self._stack.pop() self._stack.pop() self._stack.pop() except IndexError: pass def on_DELETE_SUBSCR(self, instr): try: self._stack.pop() self._stack.pop() except IndexError: pass # Note: on Python 3 this is only found on interactive mode to print the results of # some evaluation. on_PRINT_EXPR = on_POP_TOP on_UNARY_POSITIVE = _no_stack_change on_UNARY_NEGATIVE = _no_stack_change on_UNARY_NOT = _no_stack_change on_UNARY_INVERT = _no_stack_change on_CACHE = _no_stack_change on_PRECALL = _no_stack_change def _get_smart_step_into_targets(code): ''' :return list(Target) ''' b = bytecode.Bytecode.from_code(code) cfg = bytecode_cfg.ControlFlowGraph.from_bytecode(b) ret = [] for block in cfg: if DEBUG: print('\nStart block----') stack = _StackInterpreter(block) for instr in block: try: func_name = 'on_%s' % (instr.name,) func = getattr(stack, func_name, None) if DEBUG: if instr.name != 'CACHE': # Filter the ones we don't want to see. print('\nWill handle: ', instr, '>>', stack._getname(instr), '<<') print('Current stack:') for entry in stack._stack: print(' arg:', stack._getname(entry), '(', entry, ')') if func is None: if STRICT_MODE: raise AssertionError('%s not found.' % (func_name,)) else: continue func(instr) except: if STRICT_MODE: raise # Error in strict mode. else: # In non-strict mode, log it (if in verbose mode) and keep on going. if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2: pydev_log.exception('Exception computing step into targets (handled).') ret.extend(stack.function_calls) # No longer considering attr loads as calls (while in theory sometimes it's possible # that something as `some.attr` can turn out to be a property which could be stepped # in, it's not that common in practice and can be surprising for users, so, disabling # step into from stepping into properties). # ret.extend(stack.load_attrs.values()) return ret # Note that the offset is unique within the frame (so, we can use it as the target id). # Also, as the offset is the instruction offset within the frame, it's possible to # to inspect the parent frame for frame.f_lasti to know where we actually are (as the # caller name may not always match the new frame name). class Variant(object): __slots__ = ['name', 'is_visited', 'line', 'offset', 'call_order', 'children_variants', 'parent'] def __init__(self, name, is_visited, line, offset, call_order, children_variants=None): self.name = name self.is_visited = is_visited self.line = line self.offset = offset self.call_order = call_order self.children_variants = children_variants self.parent = None if children_variants: for variant in children_variants: variant.parent = self def __repr__(self): ret = [] for s in self.__slots__: if s == 'parent': try: parent = self.parent except AttributeError: ret.append('%s: <not set>' % (s,)) else: if parent is None: ret.append('parent: None') else: ret.append('parent: %s (%s)' % (parent.name, parent.offset)) continue if s == 'children_variants': ret.append('children_variants: %s' % (len(self.children_variants) if self.children_variants else 0)) continue try: ret.append('%s: %s' % (s, getattr(self, s))) except AttributeError: ret.append('%s: <not set>' % (s,)) return 'Variant(%s)' % ', '.join(ret) __str__ = __repr__ def _convert_target_to_variant(target, start_line, end_line, call_order_cache, lasti, base): name = target.arg if not isinstance(name, str): return if target.lineno > end_line: return if target.lineno < start_line: return call_order = call_order_cache.get(name, 0) + 1 call_order_cache[name] = call_order is_visited = target.offset <= lasti children_targets = target.children_targets children_variants = None if children_targets: children_variants = [ _convert_target_to_variant(child, start_line, end_line, call_order_cache, lasti, base) for child in target.children_targets] return Variant(name, is_visited, target.lineno - base, target.offset, call_order, children_variants) def calculate_smart_step_into_variants(frame, start_line, end_line, base=0): """ Calculate smart step into variants for the given line range. :param frame: :type frame: :py:class:`types.FrameType` :param start_line: :param end_line: :return: A list of call names from the first to the last. :note: it's guaranteed that the offsets appear in order. :raise: :py:class:`RuntimeError` if failed to parse the bytecode or if dis cannot be used. """ variants = [] code = frame.f_code lasti = frame.f_lasti call_order_cache = {} if DEBUG: print('dis.dis:') if IS_PY311_OR_GREATER: dis.dis(code, show_caches=False) else: dis.dis(code) for target in _get_smart_step_into_targets(code): variant = _convert_target_to_variant(target, start_line, end_line, call_order_cache, lasti, base) if variant is None: continue variants.append(variant) return variants def get_smart_step_into_variant_from_frame_offset(frame_f_lasti, variants): """ Given the frame.f_lasti, return the related `Variant`. :note: if the offset is found before any variant available or no variants are available, None is returned. :rtype: Variant|NoneType """ if not variants: return None i = bisect(KeyifyList(variants, lambda entry:entry.offset), frame_f_lasti) if i == 0: return None else: return variants[i - 1]
26,277
Python
30.135071
119
0.568101
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_io.py
from _pydevd_bundle.pydevd_constants import ForkSafeLock, get_global_debugger import os import sys from contextlib import contextmanager class IORedirector: ''' This class works to wrap a stream (stdout/stderr) with an additional redirect. ''' def __init__(self, original, new_redirect, wrap_buffer=False): ''' :param stream original: The stream to be wrapped (usually stdout/stderr, but could be None). :param stream new_redirect: Usually IOBuf (below). :param bool wrap_buffer: Whether to create a buffer attribute (needed to mimick python 3 s tdout/stderr which has a buffer to write binary data). ''' self._lock = ForkSafeLock(rlock=True) self._writing = False self._redirect_to = (original, new_redirect) if wrap_buffer and hasattr(original, 'buffer'): self.buffer = IORedirector(original.buffer, new_redirect.buffer, False) def write(self, s): # Note that writing to the original stream may fail for some reasons # (such as trying to write something that's not a string or having it closed). with self._lock: if self._writing: return self._writing = True try: for r in self._redirect_to: if hasattr(r, 'write'): r.write(s) finally: self._writing = False def isatty(self): for r in self._redirect_to: if hasattr(r, 'isatty'): return r.isatty() return False def flush(self): for r in self._redirect_to: if hasattr(r, 'flush'): r.flush() def __getattr__(self, name): for r in self._redirect_to: if hasattr(r, name): return getattr(r, name) raise AttributeError(name) class RedirectToPyDBIoMessages(object): def __init__(self, out_ctx, wrap_stream, wrap_buffer, on_write=None): ''' :param out_ctx: 1=stdout and 2=stderr :param wrap_stream: Either sys.stdout or sys.stderr. :param bool wrap_buffer: If True the buffer attribute (which wraps writing bytes) should be wrapped. :param callable(str) on_write: May be a custom callable to be called when to write something. If not passed the default implementation will create an io message and send it through the debugger. ''' encoding = getattr(wrap_stream, 'encoding', None) if not encoding: encoding = os.environ.get('PYTHONIOENCODING', 'utf-8') self.encoding = encoding self._out_ctx = out_ctx if wrap_buffer: self.buffer = RedirectToPyDBIoMessages(out_ctx, wrap_stream, wrap_buffer=False, on_write=on_write) self._on_write = on_write def get_pydb(self): # Note: separate method for mocking on tests. return get_global_debugger() def flush(self): pass # no-op here def write(self, s): if self._on_write is not None: self._on_write(s) return if s: # Need s in str if isinstance(s, bytes): s = s.decode(self.encoding, errors='replace') py_db = self.get_pydb() if py_db is not None: # Note that the actual message contents will be a xml with utf-8, although # the entry is str on py3 and bytes on py2. cmd = py_db.cmd_factory.make_io_message(s, self._out_ctx) if py_db.writer is not None: py_db.writer.add_command(cmd) class IOBuf: '''This class works as a replacement for stdio and stderr. It is a buffer and when its contents are requested, it will erase what it has so far so that the next return will not return the same contents again. ''' def __init__(self): self.buflist = [] import os self.encoding = os.environ.get('PYTHONIOENCODING', 'utf-8') def getvalue(self): b = self.buflist self.buflist = [] # clear it return ''.join(b) # bytes on py2, str on py3. def write(self, s): if isinstance(s, bytes): s = s.decode(self.encoding, errors='replace') self.buflist.append(s) def isatty(self): return False def flush(self): pass def empty(self): return len(self.buflist) == 0 class _RedirectInfo(object): def __init__(self, original, redirect_to): self.original = original self.redirect_to = redirect_to class _RedirectionsHolder: _lock = ForkSafeLock(rlock=True) _stack_stdout = [] _stack_stderr = [] _pydevd_stdout_redirect_ = None _pydevd_stderr_redirect_ = None def start_redirect(keep_original_redirection=False, std='stdout', redirect_to=None): ''' @param std: 'stdout', 'stderr', or 'both' ''' with _RedirectionsHolder._lock: if redirect_to is None: redirect_to = IOBuf() if std == 'both': config_stds = ['stdout', 'stderr'] else: config_stds = [std] for std in config_stds: original = getattr(sys, std) stack = getattr(_RedirectionsHolder, '_stack_%s' % std) if keep_original_redirection: wrap_buffer = True if hasattr(redirect_to, 'buffer') else False new_std_instance = IORedirector(getattr(sys, std), redirect_to, wrap_buffer=wrap_buffer) setattr(sys, std, new_std_instance) else: new_std_instance = redirect_to setattr(sys, std, redirect_to) stack.append(_RedirectInfo(original, new_std_instance)) return redirect_to def end_redirect(std='stdout'): with _RedirectionsHolder._lock: if std == 'both': config_stds = ['stdout', 'stderr'] else: config_stds = [std] for std in config_stds: stack = getattr(_RedirectionsHolder, '_stack_%s' % std) redirect_info = stack.pop() setattr(sys, std, redirect_info.original) def redirect_stream_to_pydb_io_messages(std): ''' :param std: 'stdout' or 'stderr' ''' with _RedirectionsHolder._lock: redirect_to_name = '_pydevd_%s_redirect_' % (std,) if getattr(_RedirectionsHolder, redirect_to_name) is None: wrap_buffer = True original = getattr(sys, std) redirect_to = RedirectToPyDBIoMessages(1 if std == 'stdout' else 2, original, wrap_buffer) start_redirect(keep_original_redirection=True, std=std, redirect_to=redirect_to) stack = getattr(_RedirectionsHolder, '_stack_%s' % std) setattr(_RedirectionsHolder, redirect_to_name, stack[-1]) return True return False def stop_redirect_stream_to_pydb_io_messages(std): ''' :param std: 'stdout' or 'stderr' ''' with _RedirectionsHolder._lock: redirect_to_name = '_pydevd_%s_redirect_' % (std,) redirect_info = getattr(_RedirectionsHolder, redirect_to_name) if redirect_info is not None: # :type redirect_info: _RedirectInfo setattr(_RedirectionsHolder, redirect_to_name, None) stack = getattr(_RedirectionsHolder, '_stack_%s' % std) prev_info = stack.pop() curr = getattr(sys, std) if curr is redirect_info.redirect_to: setattr(sys, std, redirect_info.original) @contextmanager def redirect_stream_to_pydb_io_messages_context(): with _RedirectionsHolder._lock: redirecting = [] for std in ('stdout', 'stderr'): if redirect_stream_to_pydb_io_messages(std): redirecting.append(std) try: yield finally: for std in redirecting: stop_redirect_stream_to_pydb_io_messages(std)
8,117
Python
30.343629
110
0.575459
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_gevent_integration.py
import pydevd_tracing import greenlet import gevent from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_custom_frames import add_custom_frame, update_custom_frame, remove_custom_frame from _pydevd_bundle.pydevd_constants import GEVENT_SHOW_PAUSED_GREENLETS, get_global_debugger, \ thread_get_ident from _pydev_bundle import pydev_log from pydevd_file_utils import basename _saved_greenlets_to_custom_frame_thread_id = {} if GEVENT_SHOW_PAUSED_GREENLETS: def _get_paused_name(py_db, g): frame = g.gr_frame use_frame = frame # i.e.: Show in the description of the greenlet the last user-code found. while use_frame is not None: if py_db.apply_files_filter(use_frame, use_frame.f_code.co_filename, True): frame = use_frame use_frame = use_frame.f_back else: break if use_frame is None: use_frame = frame return '%s: %s - %s' % (type(g).__name__, use_frame.f_code.co_name, basename(use_frame.f_code.co_filename)) def greenlet_events(event, args): if event in ('switch', 'throw'): py_db = get_global_debugger() origin, target = args if not origin.dead and origin.gr_frame is not None: frame_custom_thread_id = _saved_greenlets_to_custom_frame_thread_id.get(origin) if frame_custom_thread_id is None: _saved_greenlets_to_custom_frame_thread_id[origin] = add_custom_frame( origin.gr_frame, _get_paused_name(py_db, origin), thread_get_ident()) else: update_custom_frame( frame_custom_thread_id, origin.gr_frame, _get_paused_name(py_db, origin), thread_get_ident()) else: frame_custom_thread_id = _saved_greenlets_to_custom_frame_thread_id.pop(origin, None) if frame_custom_thread_id is not None: remove_custom_frame(frame_custom_thread_id) # This one will be resumed, so, remove custom frame from it. frame_custom_thread_id = _saved_greenlets_to_custom_frame_thread_id.pop(target, None) if frame_custom_thread_id is not None: remove_custom_frame(frame_custom_thread_id) # The tracing needs to be reapplied for each greenlet as gevent # clears the tracing set through sys.settrace for each greenlet. pydevd_tracing.reapply_settrace() else: # i.e.: no logic related to showing paused greenlets is needed. def greenlet_events(event, args): pydevd_tracing.reapply_settrace() def enable_gevent_integration(): # References: # https://greenlet.readthedocs.io/en/latest/api.html#greenlet.settrace # https://greenlet.readthedocs.io/en/latest/tracing.html # Note: gevent.version_info is WRONG (gevent.__version__ must be used). try: if tuple(int(x) for x in gevent.__version__.split('.')[:2]) <= (20, 0): if not GEVENT_SHOW_PAUSED_GREENLETS: return if not hasattr(greenlet, 'settrace'): # In older versions it was optional. # We still try to use if available though (because without it pydev_log.debug('greenlet.settrace not available. GEVENT_SHOW_PAUSED_GREENLETS will have no effect.') return try: greenlet.settrace(greenlet_events) except: pydev_log.exception('Error with greenlet.settrace.') except: pydev_log.exception('Error setting up gevent %s.', gevent.__version__) def log_gevent_debug_info(): pydev_log.debug('Greenlet version: %s', greenlet.__version__) pydev_log.debug('Gevent version: %s', gevent.__version__) pydev_log.debug('Gevent install location: %s', gevent.__file__)
3,896
Python
40.457446
117
0.622433
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_process_net_command_json.py
import itertools import json import linecache import os import platform import sys from functools import partial import pydevd_file_utils from _pydev_bundle import pydev_log from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema from _pydevd_bundle._debug_adapter.pydevd_schema import ( CompletionsResponseBody, EvaluateResponseBody, ExceptionOptions, GotoTargetsResponseBody, ModulesResponseBody, ProcessEventBody, ProcessEvent, Scope, ScopesResponseBody, SetExpressionResponseBody, SetVariableResponseBody, SourceBreakpoint, SourceResponseBody, VariablesResponseBody, SetBreakpointsResponseBody, Response, Capabilities, PydevdAuthorizeRequest, Request, StepInTargetsResponseBody, SetFunctionBreakpointsResponseBody, BreakpointEvent, BreakpointEventBody) from _pydevd_bundle.pydevd_api import PyDevdAPI from _pydevd_bundle.pydevd_breakpoints import get_exception_class, FunctionBreakpoint from _pydevd_bundle.pydevd_comm_constants import ( CMD_PROCESS_EVENT, CMD_RETURN, CMD_SET_NEXT_STATEMENT, CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, file_system_encoding, CMD_STEP_RETURN_MY_CODE, CMD_STEP_RETURN) from _pydevd_bundle.pydevd_filtering import ExcludeFilter from _pydevd_bundle.pydevd_json_debug_options import _extract_debug_options, DebugOptions from _pydevd_bundle.pydevd_net_command import NetCommand from _pydevd_bundle.pydevd_utils import convert_dap_log_message_to_expression, ScopeRequest from _pydevd_bundle.pydevd_constants import (PY_IMPL_NAME, DebugInfoHolder, PY_VERSION_STR, PY_IMPL_VERSION_STR, IS_64BIT_PROCESS) from _pydevd_bundle.pydevd_trace_dispatch import USING_CYTHON from _pydevd_frame_eval.pydevd_frame_eval_main import USING_FRAME_EVAL from _pydevd_bundle.pydevd_comm import internal_get_step_in_targets_json from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id def _convert_rules_to_exclude_filters(rules, on_error): exclude_filters = [] if not isinstance(rules, list): on_error('Invalid "rules" (expected list of dicts). Found: %s' % (rules,)) else: directory_exclude_filters = [] module_exclude_filters = [] glob_exclude_filters = [] for rule in rules: if not isinstance(rule, dict): on_error('Invalid "rules" (expected list of dicts). Found: %s' % (rules,)) continue include = rule.get('include') if include is None: on_error('Invalid "rule" (expected dict with "include"). Found: %s' % (rule,)) continue path = rule.get('path') module = rule.get('module') if path is None and module is None: on_error('Invalid "rule" (expected dict with "path" or "module"). Found: %s' % (rule,)) continue if path is not None: glob_pattern = path if '*' not in path and '?' not in path: if os.path.isdir(glob_pattern): # If a directory was specified, add a '/**' # to be consistent with the glob pattern required # by pydevd. if not glob_pattern.endswith('/') and not glob_pattern.endswith('\\'): glob_pattern += '/' glob_pattern += '**' directory_exclude_filters.append(ExcludeFilter(glob_pattern, not include, True)) else: glob_exclude_filters.append(ExcludeFilter(glob_pattern, not include, True)) elif module is not None: module_exclude_filters.append(ExcludeFilter(module, not include, False)) else: on_error('Internal error: expected path or module to be specified.') # Note that we have to sort the directory/module exclude filters so that the biggest # paths match first. # i.e.: if we have: # /sub1/sub2/sub3 # a rule with /sub1/sub2 would match before a rule only with /sub1. directory_exclude_filters = sorted(directory_exclude_filters, key=lambda exclude_filter:-len(exclude_filter.name)) module_exclude_filters = sorted(module_exclude_filters, key=lambda exclude_filter:-len(exclude_filter.name)) exclude_filters = directory_exclude_filters + glob_exclude_filters + module_exclude_filters return exclude_filters class IDMap(object): def __init__(self): self._value_to_key = {} self._key_to_value = {} self._next_id = partial(next, itertools.count(0)) def obtain_value(self, key): return self._key_to_value[key] def obtain_key(self, value): try: key = self._value_to_key[value] except KeyError: key = self._next_id() self._key_to_value[key] = value self._value_to_key[value] = key return key class PyDevJsonCommandProcessor(object): def __init__(self, from_json): self.from_json = from_json self.api = PyDevdAPI() self._options = DebugOptions() self._next_breakpoint_id = partial(next, itertools.count(0)) self._goto_targets_map = IDMap() self._launch_or_attach_request_done = False def process_net_command_json(self, py_db, json_contents, send_response=True): ''' Processes a debug adapter protocol json command. ''' DEBUG = False try: if isinstance(json_contents, bytes): json_contents = json_contents.decode('utf-8') request = self.from_json(json_contents, update_ids_from_dap=True) except Exception as e: try: loaded_json = json.loads(json_contents) request = Request(loaded_json.get('command', '<unknown>'), loaded_json['seq']) except: # There's not much we can do in this case... pydev_log.exception('Error loading json: %s', json_contents) return error_msg = str(e) if error_msg.startswith("'") and error_msg.endswith("'"): error_msg = error_msg[1:-1] # This means a failure processing the request (but we were able to load the seq, # so, answer with a failure response). def on_request(py_db, request): error_response = { 'type': 'response', 'request_seq': request.seq, 'success': False, 'command': request.command, 'message': error_msg, } return NetCommand(CMD_RETURN, 0, error_response, is_json=True) else: if DebugInfoHolder.DEBUG_RECORD_SOCKET_READS and DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: pydev_log.info('Process %s: %s\n' % ( request.__class__.__name__, json.dumps(request.to_dict(update_ids_to_dap=True), indent=4, sort_keys=True),)) assert request.type == 'request' method_name = 'on_%s_request' % (request.command.lower(),) on_request = getattr(self, method_name, None) if on_request is None: print('Unhandled: %s not available in PyDevJsonCommandProcessor.\n' % (method_name,)) return if DEBUG: print('Handled in pydevd: %s (in PyDevJsonCommandProcessor).\n' % (method_name,)) with py_db._main_lock: if request.__class__ == PydevdAuthorizeRequest: authorize_request = request # : :type authorize_request: PydevdAuthorizeRequest access_token = authorize_request.arguments.debugServerAccessToken py_db.authentication.login(access_token) if not py_db.authentication.is_authenticated(): response = Response( request.seq, success=False, command=request.command, message='Client not authenticated.', body={}) cmd = NetCommand(CMD_RETURN, 0, response, is_json=True) py_db.writer.add_command(cmd) return cmd = on_request(py_db, request) if cmd is not None and send_response: py_db.writer.add_command(cmd) def on_pydevdauthorize_request(self, py_db, request): client_access_token = py_db.authentication.client_access_token body = {'clientAccessToken': None} if client_access_token: body['clientAccessToken'] = client_access_token response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_initialize_request(self, py_db, request): body = Capabilities( # Supported. supportsConfigurationDoneRequest=True, supportsConditionalBreakpoints=True, supportsHitConditionalBreakpoints=True, supportsEvaluateForHovers=True, supportsSetVariable=True, supportsGotoTargetsRequest=True, supportsCompletionsRequest=True, supportsModulesRequest=True, supportsExceptionOptions=True, supportsValueFormattingOptions=True, supportsExceptionInfoRequest=True, supportTerminateDebuggee=True, supportsDelayedStackTraceLoading=True, supportsLogPoints=True, supportsSetExpression=True, supportsTerminateRequest=True, supportsClipboardContext=True, supportsFunctionBreakpoints=True, exceptionBreakpointFilters=[ {'filter': 'raised', 'label': 'Raised Exceptions', 'default': False}, {'filter': 'uncaught', 'label': 'Uncaught Exceptions', 'default': True}, {"filter": "userUnhandled", "label": "User Uncaught Exceptions", "default": False}, ], # Not supported. supportsStepBack=False, supportsRestartFrame=False, supportsStepInTargetsRequest=True, supportsRestartRequest=False, supportsLoadedSourcesRequest=False, supportsTerminateThreadsRequest=False, supportsDataBreakpoints=False, supportsReadMemoryRequest=False, supportsDisassembleRequest=False, additionalModuleColumns=[], completionTriggerCharacters=[], supportedChecksumAlgorithms=[], ).to_dict() # Non-standard capabilities/info below. body['supportsDebuggerProperties'] = True body['pydevd'] = pydevd_info = {} pydevd_info['processId'] = os.getpid() self.api.notify_initialize(py_db) response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' if not self._launch_or_attach_request_done: pydev_log.critical('Missing launch request or attach request before configuration done request.') self.api.run(py_db) self.api.notify_configuration_done(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True) def on_threads_request(self, py_db, request): ''' :param ThreadsRequest request: ''' return self.api.list_threads(py_db, request.seq) def on_terminate_request(self, py_db, request): ''' :param TerminateRequest request: ''' self._request_terminate_process(py_db) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def _request_terminate_process(self, py_db): self.api.request_terminate_process(py_db) def on_completions_request(self, py_db, request): ''' :param CompletionsRequest request: ''' arguments = request.arguments # : :type arguments: CompletionsArguments seq = request.seq text = arguments.text frame_id = arguments.frameId thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( frame_id) if thread_id is None: body = CompletionsResponseBody([]) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Thread to get completions seems to have resumed already.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) # Note: line and column are 1-based (convert to 0-based for pydevd). column = arguments.column - 1 if arguments.line is None: # line is optional line = -1 else: line = arguments.line - 1 self.api.request_completions(py_db, seq, thread_id, frame_id, text, line=line, column=column) def _resolve_remote_root(self, local_root, remote_root): if remote_root == '.': cwd = os.getcwd() append_pathsep = local_root.endswith('\\') or local_root.endswith('/') return cwd + (os.path.sep if append_pathsep else '') return remote_root def _set_debug_options(self, py_db, args, start_reason): rules = args.get('rules') stepping_resumes_all_threads = args.get('steppingResumesAllThreads', True) self.api.set_stepping_resumes_all_threads(py_db, stepping_resumes_all_threads) terminate_child_processes = args.get('terminateChildProcesses', True) self.api.set_terminate_child_processes(py_db, terminate_child_processes) variable_presentation = args.get('variablePresentation', None) if isinstance(variable_presentation, dict): def get_variable_presentation(setting, default): value = variable_presentation.get(setting, default) if value not in ('group', 'inline', 'hide'): pydev_log.info( 'The value set for "%s" (%s) in the variablePresentation is not valid. Valid values are: "group", "inline", "hide"' % ( setting, value,)) value = default return value default = get_variable_presentation('all', 'group') special_presentation = get_variable_presentation('special', default) function_presentation = get_variable_presentation('function', default) class_presentation = get_variable_presentation('class', default) protected_presentation = get_variable_presentation('protected', default) self.api.set_variable_presentation(py_db, self.api.VariablePresentation( special_presentation, function_presentation, class_presentation, protected_presentation )) exclude_filters = [] if rules is not None: exclude_filters = _convert_rules_to_exclude_filters( rules, lambda msg: self.api.send_error_message(py_db, msg)) self.api.set_exclude_filters(py_db, exclude_filters) debug_options = _extract_debug_options( args.get('options'), args.get('debugOptions'), ) self._options.update_fom_debug_options(debug_options) self._options.update_from_args(args) self.api.set_use_libraries_filter(py_db, self._options.just_my_code) path_mappings = [] for pathMapping in args.get('pathMappings', []): localRoot = pathMapping.get('localRoot', '') remoteRoot = pathMapping.get('remoteRoot', '') remoteRoot = self._resolve_remote_root(localRoot, remoteRoot) if (localRoot != '') and (remoteRoot != ''): path_mappings.append((localRoot, remoteRoot)) if bool(path_mappings): pydevd_file_utils.setup_client_server_paths(path_mappings) resolve_symlinks = args.get('resolveSymlinks', None) if resolve_symlinks is not None: pydevd_file_utils.set_resolve_symlinks(resolve_symlinks) redirecting = args.get("isOutputRedirected") if self._options.redirect_output: py_db.enable_output_redirection(True, True) redirecting = True else: py_db.enable_output_redirection(False, False) py_db.is_output_redirected = redirecting self.api.set_show_return_values(py_db, self._options.show_return_value) if not self._options.break_system_exit_zero: ignore_system_exit_codes = [0, None] if self._options.django_debug or self._options.flask_debug: ignore_system_exit_codes += [3] self.api.set_ignore_system_exit_codes(py_db, ignore_system_exit_codes) auto_reload = args.get('autoReload', {}) if not isinstance(auto_reload, dict): pydev_log.info('Expected autoReload to be a dict. Received: %s' % (auto_reload,)) auto_reload = {} enable_auto_reload = auto_reload.get('enable', False) watch_dirs = auto_reload.get('watchDirectories') if not watch_dirs: watch_dirs = [] # Note: by default this is no longer done because on some cases there are entries in the PYTHONPATH # such as the home directory or /python/x64, where the site packages are in /python/x64/libs, so, # we only watch the current working directory as well as executed script. # check = getattr(sys, 'path', [])[:] # # By default only watch directories that are in the project roots / # # program dir (if available), sys.argv[0], as well as the current dir (we don't want to # # listen to the whole site-packages by default as it can be huge). # watch_dirs = [pydevd_file_utils.absolute_path(w) for w in check] # watch_dirs = [w for w in watch_dirs if py_db.in_project_roots_filename_uncached(w) and os.path.isdir(w)] program = args.get('program') if program: if os.path.isdir(program): watch_dirs.append(program) else: watch_dirs.append(os.path.dirname(program)) watch_dirs.append(os.path.abspath('.')) argv = getattr(sys, 'argv', []) if argv: f = argv[0] if f: # argv[0] could be None (https://github.com/microsoft/debugpy/issues/987) if os.path.isdir(f): watch_dirs.append(f) else: watch_dirs.append(os.path.dirname(f)) if not isinstance(watch_dirs, (list, set, tuple)): watch_dirs = (watch_dirs,) new_watch_dirs = set() for w in watch_dirs: try: new_watch_dirs.add(pydevd_file_utils.get_path_with_real_case(pydevd_file_utils.absolute_path(w))) except Exception: pydev_log.exception('Error adding watch dir: %s', w) watch_dirs = new_watch_dirs poll_target_time = auto_reload.get('pollingInterval', 1) exclude_patterns = auto_reload.get('exclude', ('**/.git/**', '**/__pycache__/**', '**/node_modules/**', '**/.metadata/**', '**/site-packages/**')) include_patterns = auto_reload.get('include', ('**/*.py', '**/*.pyw')) self.api.setup_auto_reload_watcher( py_db, enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns) if self._options.stop_on_entry and start_reason == 'launch': self.api.stop_on_entry() self.api.set_gui_event_loop(py_db, self._options.gui_event_loop) def _send_process_event(self, py_db, start_method): argv = getattr(sys, 'argv', []) if len(argv) > 0: name = argv[0] else: name = '' if isinstance(name, bytes): name = name.decode(file_system_encoding, 'replace') name = name.encode('utf-8') body = ProcessEventBody( name=name, systemProcessId=os.getpid(), isLocalProcess=True, startMethod=start_method, ) event = ProcessEvent(body) py_db.writer.add_command(NetCommand(CMD_PROCESS_EVENT, 0, event, is_json=True)) def _handle_launch_or_attach_request(self, py_db, request, start_reason): self._send_process_event(py_db, start_reason) self._launch_or_attach_request_done = True self.api.set_enable_thread_notifications(py_db, True) self._set_debug_options(py_db, request.arguments.kwargs, start_reason=start_reason) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_launch_request(self, py_db, request): ''' :param LaunchRequest request: ''' return self._handle_launch_or_attach_request(py_db, request, start_reason='launch') def on_attach_request(self, py_db, request): ''' :param AttachRequest request: ''' return self._handle_launch_or_attach_request(py_db, request, start_reason='attach') def on_pause_request(self, py_db, request): ''' :param PauseRequest request: ''' arguments = request.arguments # : :type arguments: PauseArguments thread_id = arguments.threadId self.api.request_suspend_thread(py_db, thread_id=thread_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_continue_request(self, py_db, request): ''' :param ContinueRequest request: ''' arguments = request.arguments # : :type arguments: ContinueArguments thread_id = arguments.threadId def on_resumed(): body = {'allThreadsContinued': thread_id == '*'} response = pydevd_base_schema.build_response(request, kwargs={'body': body}) cmd = NetCommand(CMD_RETURN, 0, response, is_json=True) py_db.writer.add_command(cmd) # Only send resumed notification when it has actually resumed! # (otherwise the user could send a continue, receive the notification and then # request a new pause which would be paused without sending any notification as # it didn't really run in the first place). py_db.threads_suspended_single_notification.add_on_resumed_callback(on_resumed) self.api.request_resume_thread(thread_id) def on_next_request(self, py_db, request): ''' :param NextRequest request: ''' arguments = request.arguments # : :type arguments: NextArguments thread_id = arguments.threadId if py_db.get_use_libraries_filter(): step_cmd_id = CMD_STEP_OVER_MY_CODE else: step_cmd_id = CMD_STEP_OVER self.api.request_step(py_db, thread_id, step_cmd_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_stepin_request(self, py_db, request): ''' :param StepInRequest request: ''' arguments = request.arguments # : :type arguments: StepInArguments thread_id = arguments.threadId target_id = arguments.targetId if target_id is not None: thread = pydevd_find_thread_by_id(thread_id) info = set_additional_thread_info(thread) target_id_to_smart_step_into_variant = info.target_id_to_smart_step_into_variant if not target_id_to_smart_step_into_variant: variables_response = pydevd_base_schema.build_response( request, kwargs={ 'success': False, 'message': 'Unable to step into target (no targets are saved in the thread info).' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) variant = target_id_to_smart_step_into_variant.get(target_id) if variant is not None: parent = variant.parent if parent is not None: self.api.request_smart_step_into(py_db, request.seq, thread_id, parent.offset, variant.offset) else: self.api.request_smart_step_into(py_db, request.seq, thread_id, variant.offset, -1) else: variables_response = pydevd_base_schema.build_response( request, kwargs={ 'success': False, 'message': 'Unable to find step into target %s. Available targets: %s' % ( target_id, target_id_to_smart_step_into_variant) }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) else: if py_db.get_use_libraries_filter(): step_cmd_id = CMD_STEP_INTO_MY_CODE else: step_cmd_id = CMD_STEP_INTO self.api.request_step(py_db, thread_id, step_cmd_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_stepintargets_request(self, py_db, request): ''' :param StepInTargetsRequest request: ''' frame_id = request.arguments.frameId thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( frame_id) if thread_id is None: body = StepInTargetsResponseBody([]) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to get thread_id from frame_id (thread to get step in targets seems to have resumed already).' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) py_db.post_method_as_internal_command( thread_id, internal_get_step_in_targets_json, request.seq, thread_id, frame_id, request, set_additional_thread_info) def on_stepout_request(self, py_db, request): ''' :param StepOutRequest request: ''' arguments = request.arguments # : :type arguments: StepOutArguments thread_id = arguments.threadId if py_db.get_use_libraries_filter(): step_cmd_id = CMD_STEP_RETURN_MY_CODE else: step_cmd_id = CMD_STEP_RETURN self.api.request_step(py_db, thread_id, step_cmd_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def _get_hit_condition_expression(self, hit_condition): '''Following hit condition values are supported * x or == x when breakpoint is hit x times * >= x when breakpoint is hit more than or equal to x times * % x when breakpoint is hit multiple of x times Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits ''' if not hit_condition: return None expr = hit_condition.strip() try: int(expr) return '@HIT@ == {}'.format(expr) except ValueError: pass if expr.startswith('%'): return '@HIT@ {} == 0'.format(expr) if expr.startswith('==') or \ expr.startswith('>') or \ expr.startswith('<'): return '@HIT@ {}'.format(expr) return hit_condition def on_disconnect_request(self, py_db, request): ''' :param DisconnectRequest request: ''' if request.arguments.terminateDebuggee: self._request_terminate_process(py_db) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) self._launch_or_attach_request_done = False py_db.enable_output_redirection(False, False) self.api.request_disconnect(py_db, resume_threads=True) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True) def _verify_launch_or_attach_done(self, request): if not self._launch_or_attach_request_done: # Note that to validate the breakpoints we need the launch request to be done already # (otherwise the filters wouldn't be set for the breakpoint validation). if request.command == 'setFunctionBreakpoints': body = SetFunctionBreakpointsResponseBody([]) else: body = SetBreakpointsResponseBody([]) response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Breakpoints may only be set after the launch request is received.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_setfunctionbreakpoints_request(self, py_db, request): ''' :param SetFunctionBreakpointsRequest request: ''' response = self._verify_launch_or_attach_done(request) if response is not None: return response arguments = request.arguments # : :type arguments: SetFunctionBreakpointsArguments function_breakpoints = [] suspend_policy = 'ALL' # Not currently covered by the DAP. is_logpoint = False expression = None breakpoints_set = [] for bp in arguments.breakpoints: hit_condition = self._get_hit_condition_expression(bp.get('hitCondition')) condition = bp.get('condition') function_breakpoints.append( FunctionBreakpoint(bp['name'], condition, expression, suspend_policy, hit_condition, is_logpoint)) # Note: always succeeds. breakpoints_set.append(pydevd_schema.Breakpoint( verified=True, id=self._next_breakpoint_id()).to_dict()) self.api.set_function_breakpoints(py_db, function_breakpoints) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True) def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' response = self._verify_launch_or_attach_done(request) if response is not None: return response arguments = request.arguments # : :type arguments: SetBreakpointsArguments # TODO: Path is optional here it could be source reference. filename = self.api.filename_to_str(arguments.source.path) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith('.py'): # Note: check based on original file, not mapping. if self._options.django_debug: btype = 'django-line' elif self._options.flask_debug: btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = self._next_breakpoint_id() hit_condition = self._get_hit_condition_expression(source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expression = convert_dap_log_message_to_expression(log_message) on_changed_breakpoint_state = partial(self._on_changed_breakpoint_state, py_db, arguments.source) result = self.api.add_breakpoint( py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint, adjust_line=True, on_changed_breakpoint_state=on_changed_breakpoint_state) bp = self._create_breakpoint_from_add_breakpoint_result(py_db, arguments.source, breakpoint_id, result) breakpoints_set.append(bp) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True) def _on_changed_breakpoint_state(self, py_db, source, breakpoint_id, result): bp = self._create_breakpoint_from_add_breakpoint_result(py_db, source, breakpoint_id, result) body = BreakpointEventBody( reason='changed', breakpoint=bp, ) event = BreakpointEvent(body) event_id = 0 # Actually ignored in this case py_db.writer.add_command(NetCommand(event_id, 0, event, is_json=True)) def _create_breakpoint_from_add_breakpoint_result(self, py_db, source, breakpoint_id, result): error_code = result.error_code if error_code: if error_code == self.api.ADD_BREAKPOINT_FILE_NOT_FOUND: error_msg = 'Breakpoint in file that does not exist.' elif error_code == self.api.ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS: error_msg = 'Breakpoint in file excluded by filters.' if py_db.get_use_libraries_filter(): error_msg += ('\nNote: may be excluded because of "justMyCode" option (default == true).' 'Try setting \"justMyCode\": false in the debug configuration (e.g., launch.json).\n') elif error_code == self.api.ADD_BREAKPOINT_LAZY_VALIDATION: error_msg = 'Waiting for code to be loaded to verify breakpoint.' elif error_code == self.api.ADD_BREAKPOINT_INVALID_LINE: error_msg = 'Breakpoint added to invalid line.' else: # Shouldn't get here. error_msg = 'Breakpoint not validated (reason unknown -- please report as bug).' return pydevd_schema.Breakpoint( verified=False, id=breakpoint_id, line=result.translated_line, message=error_msg, source=source).to_dict() else: return pydevd_schema.Breakpoint( verified=True, id=breakpoint_id, line=result.translated_line, source=source).to_dict() def on_setexceptionbreakpoints_request(self, py_db, request): ''' :param SetExceptionBreakpointsRequest request: ''' # : :type arguments: SetExceptionBreakpointsArguments arguments = request.arguments filters = arguments.filters exception_options = arguments.exceptionOptions self.api.remove_all_exception_breakpoints(py_db) # Can't set these in the DAP. condition = None expression = None notify_on_first_raise_only = False ignore_libraries = 1 if py_db.get_use_libraries_filter() else 0 if exception_options: break_raised = False break_uncaught = False for option in exception_options: option = ExceptionOptions(**option) if not option.path: continue # never: never breaks # # always: always breaks # # unhandled: breaks when exception unhandled # # userUnhandled: breaks if the exception is not handled by user code notify_on_handled_exceptions = 1 if option.breakMode == 'always' else 0 notify_on_unhandled_exceptions = 1 if option.breakMode == 'unhandled' else 0 notify_on_user_unhandled_exceptions = 1 if option.breakMode == 'userUnhandled' else 0 exception_paths = option.path break_raised |= notify_on_handled_exceptions break_uncaught |= notify_on_unhandled_exceptions exception_names = [] if len(exception_paths) == 0: continue elif len(exception_paths) == 1: if 'Python Exceptions' in exception_paths[0]['names']: exception_names = ['BaseException'] else: path_iterator = iter(exception_paths) if 'Python Exceptions' in next(path_iterator)['names']: for path in path_iterator: for ex_name in path['names']: exception_names.append(ex_name) for exception_name in exception_names: self.api.add_python_exception_breakpoint( py_db, exception_name, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries ) else: break_raised = 'raised' in filters break_uncaught = 'uncaught' in filters break_user = 'userUnhandled' in filters if break_raised or break_uncaught or break_user: notify_on_handled_exceptions = 1 if break_raised else 0 notify_on_unhandled_exceptions = 1 if break_uncaught else 0 notify_on_user_unhandled_exceptions = 1 if break_user else 0 exception = 'BaseException' self.api.add_python_exception_breakpoint( py_db, exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries ) if break_raised: btype = None if self._options.django_debug: btype = 'django' elif self._options.flask_debug: btype = 'jinja2' if btype: self.api.add_plugins_exception_breakpoint( py_db, btype, 'BaseException') # Note: Exception name could be anything here. # Note: no body required on success. set_breakpoints_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True) def on_stacktrace_request(self, py_db, request): ''' :param StackTraceRequest request: ''' # : :type stack_trace_arguments: StackTraceArguments stack_trace_arguments = request.arguments thread_id = stack_trace_arguments.threadId if stack_trace_arguments.startFrame: start_frame = int(stack_trace_arguments.startFrame) else: start_frame = 0 if stack_trace_arguments.levels: levels = int(stack_trace_arguments.levels) else: levels = 0 fmt = stack_trace_arguments.format if hasattr(fmt, 'to_dict'): fmt = fmt.to_dict() self.api.request_stack(py_db, request.seq, thread_id, fmt=fmt, start_frame=start_frame, levels=levels) def on_exceptioninfo_request(self, py_db, request): ''' :param ExceptionInfoRequest request: ''' # : :type exception_into_arguments: ExceptionInfoArguments exception_into_arguments = request.arguments thread_id = exception_into_arguments.threadId max_frames = self._options.max_exception_stack_frames self.api.request_exception_info_json(py_db, request, thread_id, max_frames) def on_scopes_request(self, py_db, request): ''' Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request: ''' frame_id = request.arguments.frameId variables_reference = frame_id scopes = [ Scope('Locals', ScopeRequest(int(variables_reference), 'locals'), False, presentationHint='locals'), Scope('Globals', ScopeRequest(int(variables_reference), 'globals'), False), ] body = ScopesResponseBody(scopes) scopes_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, scopes_response, is_json=True) def on_evaluate_request(self, py_db, request): ''' :param EvaluateRequest request: ''' # : :type arguments: EvaluateArguments arguments = request.arguments if arguments.frameId is None: self.api.request_exec_or_evaluate_json(py_db, request, thread_id='*') else: thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) if thread_id is not None: self.api.request_exec_or_evaluate_json( py_db, request, thread_id) else: body = EvaluateResponseBody('', 0) response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread for evaluation.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_setexpression_request(self, py_db, request): # : :type arguments: SetExpressionArguments arguments = request.arguments thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) if thread_id is not None: self.api.request_set_expression_json(py_db, request, thread_id) else: body = SetExpressionResponseBody('') response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to set expression.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_variables_request(self, py_db, request): ''' Variables can be asked whenever some place returned a variables reference (so, it can be a scope gotten from on_scopes_request, the result of some evaluation, etc.). Note that in the DAP the variables reference requires a unique int... the way this works for pydevd is that an instance is generated for that specific variable reference and we use its id(instance) to identify it to make sure all items are unique (and the actual {id->instance} is added to a dict which is only valid while the thread is suspended and later cleared when the related thread resumes execution). see: SuspendedFramesManager :param VariablesRequest request: ''' arguments = request.arguments # : :type arguments: VariablesArguments variables_reference = arguments.variablesReference if isinstance(variables_reference, ScopeRequest): variables_reference = variables_reference.variable_reference thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( variables_reference) if thread_id is not None: self.api.request_get_variable_json(py_db, request, thread_id) else: variables = [] body = VariablesResponseBody(variables) variables_response = pydevd_base_schema.build_response(request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) def on_setvariable_request(self, py_db, request): arguments = request.arguments # : :type arguments: SetVariableArguments variables_reference = arguments.variablesReference if isinstance(variables_reference, ScopeRequest): variables_reference = variables_reference.variable_reference if arguments.name.startswith('(return) '): response = pydevd_base_schema.build_response( request, kwargs={ 'body': SetVariableResponseBody(''), 'success': False, 'message': 'Cannot change return value' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( variables_reference) if thread_id is not None: self.api.request_change_variable_json(py_db, request, thread_id) else: response = pydevd_base_schema.build_response( request, kwargs={ 'body': SetVariableResponseBody(''), 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_modules_request(self, py_db, request): modules_manager = py_db.cmd_factory.modules_manager # : :type modules_manager: ModulesManager modules_info = modules_manager.get_modules_info() body = ModulesResponseBody(modules_info) variables_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) def on_source_request(self, py_db, request): ''' :param SourceRequest request: ''' source_reference = request.arguments.sourceReference server_filename = None content = None if source_reference != 0: server_filename = pydevd_file_utils.get_server_filename_from_source_reference(source_reference) if not server_filename: server_filename = pydevd_file_utils.get_source_reference_filename_from_linecache(source_reference) if server_filename: # Try direct file access first - it's much faster when available. try: with open(server_filename, 'r') as stream: content = stream.read() except: pass if content is None: # File might not exist at all, or we might not have a permission to read it, # but it might also be inside a zipfile, or an IPython cell. In this case, # linecache might still be able to retrieve the source. lines = (linecache.getline(server_filename, i) for i in itertools.count(1)) lines = itertools.takewhile(bool, lines) # empty lines are '\n', EOF is '' # If we didn't get at least one line back, reset it to None so that it's # reported as error below, and not as an empty file. content = ''.join(lines) or None if content is None: frame_id = pydevd_file_utils.get_frame_id_from_source_reference(source_reference) pydev_log.debug('Found frame id: %s for source reference: %s', frame_id, source_reference) if frame_id is not None: try: content = self.api.get_decompiled_source_from_frame_id(py_db, frame_id) except Exception: pydev_log.exception('Error getting source for frame id: %s', frame_id) content = None body = SourceResponseBody(content or '') response_args = {'body': body} if content is None: if source_reference == 0: message = 'Source unavailable' elif server_filename: message = 'Unable to retrieve source for %s' % (server_filename,) else: message = 'Invalid sourceReference %d' % (source_reference,) response_args.update({'success': False, 'message': message}) response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_gototargets_request(self, py_db, request): path = request.arguments.source.path line = request.arguments.line target_id = self._goto_targets_map.obtain_key((path, line)) target = { 'id': target_id, 'label': '%s:%s' % (path, line), 'line': line } body = GotoTargetsResponseBody(targets=[target]) response_args = {'body': body} response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_goto_request(self, py_db, request): target_id = int(request.arguments.targetId) thread_id = request.arguments.threadId try: path, line = self._goto_targets_map.obtain_value(target_id) except KeyError: response = pydevd_base_schema.build_response( request, kwargs={ 'body': {}, 'success': False, 'message': 'Unknown goto target id: %d' % (target_id,), }) return NetCommand(CMD_RETURN, 0, response, is_json=True) self.api.request_set_next(py_db, request.seq, thread_id, CMD_SET_NEXT_STATEMENT, path, line, '*') # See 'NetCommandFactoryJson.make_set_next_stmnt_status_message' for response return None def on_setdebuggerproperty_request(self, py_db, request): args = request.arguments # : :type args: SetDebuggerPropertyArguments if args.ideOS is not None: self.api.set_ide_os(args.ideOS) if args.dontTraceStartPatterns is not None and args.dontTraceEndPatterns is not None: start_patterns = tuple(args.dontTraceStartPatterns) end_patterns = tuple(args.dontTraceEndPatterns) self.api.set_dont_trace_start_end_patterns(py_db, start_patterns, end_patterns) if args.skipSuspendOnBreakpointException is not None: py_db.skip_suspend_on_breakpoint_exception = tuple( get_exception_class(x) for x in args.skipSuspendOnBreakpointException) if args.skipPrintBreakpointException is not None: py_db.skip_print_breakpoint_exception = tuple( get_exception_class(x) for x in args.skipPrintBreakpointException) if args.multiThreadsSingleNotification is not None: py_db.multi_threads_single_notification = args.multiThreadsSingleNotification # TODO: Support other common settings. Note that not all of these might be relevant to python. # JustMyCodeStepping: 0 or 1 # AllowOutOfProcessSymbols: 0 or 1 # DisableJITOptimization: 0 or 1 # InterpreterOptions: 0 or 1 # StopOnExceptionCrossingManagedBoundary: 0 or 1 # WarnIfNoUserCodeOnLaunch: 0 or 1 # EnableStepFiltering: true of false response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_pydevdsysteminfo_request(self, py_db, request): try: pid = os.getpid() except AttributeError: pid = None # It's possible to have the ppid reported from args. In this case, use that instead of the # real ppid (athough we're using `ppid`, what we want in meaning is the `launcher_pid` -- # so, if a python process is launched from another python process, consider that process the # parent and not any intermediary stubs). ppid = py_db.get_arg_ppid() or self.api.get_ppid() try: impl_desc = platform.python_implementation() except AttributeError: impl_desc = PY_IMPL_NAME py_info = pydevd_schema.PydevdPythonInfo( version=PY_VERSION_STR, implementation=pydevd_schema.PydevdPythonImplementationInfo( name=PY_IMPL_NAME, version=PY_IMPL_VERSION_STR, description=impl_desc, ) ) platform_info = pydevd_schema.PydevdPlatformInfo(name=sys.platform) process_info = pydevd_schema.PydevdProcessInfo( pid=pid, ppid=ppid, executable=sys.executable, bitness=64 if IS_64BIT_PROCESS else 32, ) pydevd_info = pydevd_schema.PydevdInfo( usingCython=USING_CYTHON, usingFrameEval=USING_FRAME_EVAL, ) body = { 'python': py_info, 'platform': platform_info, 'process': process_info, 'pydevd': pydevd_info, } response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True) def on_setpydevdsourcemap_request(self, py_db, request): args = request.arguments # : :type args: SetPydevdSourceMapArguments SourceMappingEntry = self.api.SourceMappingEntry path = args.source.path source_maps = args.pydevdSourceMaps # : :type source_map: PydevdSourceMap new_mappings = [ SourceMappingEntry( source_map['line'], source_map['endLine'], source_map['runtimeLine'], self.api.filename_to_str(source_map['runtimeSource']['path']) ) for source_map in source_maps ] error_msg = self.api.set_source_mapping(py_db, path, new_mappings) if error_msg: response = pydevd_base_schema.build_response( request, kwargs={ 'body': {}, 'success': False, 'message': error_msg, }) return NetCommand(CMD_RETURN, 0, response, is_json=True) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
55,820
Python
41.546494
154
0.593945
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_json_debug_options.py
import json import urllib.parse as urllib_parse class DebugOptions(object): __slots__ = [ 'just_my_code', 'redirect_output', 'show_return_value', 'break_system_exit_zero', 'django_debug', 'flask_debug', 'stop_on_entry', 'max_exception_stack_frames', 'gui_event_loop', ] def __init__(self): self.just_my_code = True self.redirect_output = False self.show_return_value = False self.break_system_exit_zero = False self.django_debug = False self.flask_debug = False self.stop_on_entry = False self.max_exception_stack_frames = 0 self.gui_event_loop = 'matplotlib' def to_json(self): dct = {} for s in self.__slots__: dct[s] = getattr(self, s) return json.dumps(dct) def update_fom_debug_options(self, debug_options): if 'DEBUG_STDLIB' in debug_options: self.just_my_code = not debug_options.get('DEBUG_STDLIB') if 'REDIRECT_OUTPUT' in debug_options: self.redirect_output = debug_options.get('REDIRECT_OUTPUT') if 'SHOW_RETURN_VALUE' in debug_options: self.show_return_value = debug_options.get('SHOW_RETURN_VALUE') if 'BREAK_SYSTEMEXIT_ZERO' in debug_options: self.break_system_exit_zero = debug_options.get('BREAK_SYSTEMEXIT_ZERO') if 'DJANGO_DEBUG' in debug_options: self.django_debug = debug_options.get('DJANGO_DEBUG') if 'FLASK_DEBUG' in debug_options: self.flask_debug = debug_options.get('FLASK_DEBUG') if 'STOP_ON_ENTRY' in debug_options: self.stop_on_entry = debug_options.get('STOP_ON_ENTRY') # Note: _max_exception_stack_frames cannot be set by debug options. def update_from_args(self, args): if 'justMyCode' in args: self.just_my_code = bool_parser(args['justMyCode']) else: # i.e.: if justMyCode is provided, don't check the deprecated value if 'debugStdLib' in args: self.just_my_code = not bool_parser(args['debugStdLib']) if 'redirectOutput' in args: self.redirect_output = bool_parser(args['redirectOutput']) if 'showReturnValue' in args: self.show_return_value = bool_parser(args['showReturnValue']) if 'breakOnSystemExitZero' in args: self.break_system_exit_zero = bool_parser(args['breakOnSystemExitZero']) if 'django' in args: self.django_debug = bool_parser(args['django']) if 'flask' in args: self.flask_debug = bool_parser(args['flask']) if 'jinja' in args: self.flask_debug = bool_parser(args['jinja']) if 'stopOnEntry' in args: self.stop_on_entry = bool_parser(args['stopOnEntry']) self.max_exception_stack_frames = int_parser(args.get('maxExceptionStackFrames', 0)) if 'guiEventLoop' in args: self.gui_event_loop = str(args['guiEventLoop']) def int_parser(s, default_value=0): try: return int(s) except Exception: return default_value def bool_parser(s): return s in ("True", "true", "1", True, 1) def unquote(s): return None if s is None else urllib_parse.unquote(s) DEBUG_OPTIONS_PARSER = { 'WAIT_ON_ABNORMAL_EXIT': bool_parser, 'WAIT_ON_NORMAL_EXIT': bool_parser, 'BREAK_SYSTEMEXIT_ZERO': bool_parser, 'REDIRECT_OUTPUT': bool_parser, 'DJANGO_DEBUG': bool_parser, 'FLASK_DEBUG': bool_parser, 'FIX_FILE_PATH_CASE': bool_parser, 'CLIENT_OS_TYPE': unquote, 'DEBUG_STDLIB': bool_parser, 'STOP_ON_ENTRY': bool_parser, 'SHOW_RETURN_VALUE': bool_parser, 'MULTIPROCESS': bool_parser, } DEBUG_OPTIONS_BY_FLAG = { 'RedirectOutput': 'REDIRECT_OUTPUT=True', 'WaitOnNormalExit': 'WAIT_ON_NORMAL_EXIT=True', 'WaitOnAbnormalExit': 'WAIT_ON_ABNORMAL_EXIT=True', 'BreakOnSystemExitZero': 'BREAK_SYSTEMEXIT_ZERO=True', 'Django': 'DJANGO_DEBUG=True', 'Flask': 'FLASK_DEBUG=True', 'Jinja': 'FLASK_DEBUG=True', 'FixFilePathCase': 'FIX_FILE_PATH_CASE=True', 'DebugStdLib': 'DEBUG_STDLIB=True', 'WindowsClient': 'CLIENT_OS_TYPE=WINDOWS', 'UnixClient': 'CLIENT_OS_TYPE=UNIX', 'StopOnEntry': 'STOP_ON_ENTRY=True', 'ShowReturnValue': 'SHOW_RETURN_VALUE=True', 'Multiprocess': 'MULTIPROCESS=True', } def _build_debug_options(flags): """Build string representation of debug options from the launch config.""" return ';'.join(DEBUG_OPTIONS_BY_FLAG[flag] for flag in flags or [] if flag in DEBUG_OPTIONS_BY_FLAG) def _parse_debug_options(opts): """Debug options are semicolon separated key=value pairs """ 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 def _extract_debug_options(opts, flags=None): """Return the debug options encoded in the given value. "opts" is a semicolon-separated string of "key=value" pairs. "flags" is a list of strings. If flags is provided then it is used as a fallback. The values come from the launch config: { type:'python', request:'launch'|'attach', name:'friendly name for debug config', debugOptions:[ 'RedirectOutput', 'Django' ], options:'REDIRECT_OUTPUT=True;DJANGO_DEBUG=True' } Further information can be found here: https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes """ if not opts: opts = _build_debug_options(flags) return _parse_debug_options(opts)
5,945
Python
29.182741
92
0.60942
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_additional_thread_info_regular.py
from _pydevd_bundle.pydevd_constants import (STATE_RUN, PYTHON_SUSPEND, SUPPORT_GEVENT, ForkSafeLock, _current_frames) from _pydev_bundle import pydev_log # IFDEF CYTHON # pydev_log.debug("Using Cython speedups") # ELSE from _pydevd_bundle.pydevd_frame import PyDBFrame # ENDIF version = 11 #======================================================================================================================= # PyDBAdditionalThreadInfo #======================================================================================================================= # IFDEF CYTHON # cdef class PyDBAdditionalThreadInfo: # ELSE class PyDBAdditionalThreadInfo(object): # ENDIF # Note: the params in cython are declared in pydevd_cython.pxd. # IFDEF CYTHON # ELSE __slots__ = [ 'pydev_state', 'pydev_step_stop', 'pydev_original_step_cmd', 'pydev_step_cmd', 'pydev_notify_kill', 'pydev_django_resolve_frame', 'pydev_call_from_jinja2', 'pydev_call_inside_jinja2', 'is_tracing', 'conditional_breakpoint_exception', 'pydev_message', 'suspend_type', 'pydev_next_line', 'pydev_func_name', 'suspended_at_unhandled', 'trace_suspend_type', 'top_level_thread_tracer_no_back_frames', 'top_level_thread_tracer_unhandled', 'thread_tracer', 'step_in_initial_location', # Used for CMD_SMART_STEP_INTO (to know which smart step into variant to use) 'pydev_smart_parent_offset', 'pydev_smart_child_offset', # Used for CMD_SMART_STEP_INTO (list[_pydevd_bundle.pydevd_bytecode_utils.Variant]) # Filled when the cmd_get_smart_step_into_variants is requested (so, this is a copy # of the last request for a given thread and pydev_smart_parent_offset/pydev_smart_child_offset relies on it). 'pydev_smart_step_into_variants', 'target_id_to_smart_step_into_variant', 'pydev_use_scoped_step_frame', ] # ENDIF def __init__(self): self.pydev_state = STATE_RUN # STATE_RUN or STATE_SUSPEND self.pydev_step_stop = None # Note: we have `pydev_original_step_cmd` and `pydev_step_cmd` because the original is to # say the action that started it and the other is to say what's the current tracing behavior # (because it's possible that we start with a step over but may have to switch to a # different step strategy -- for instance, if a step over is done and we return the current # method the strategy is changed to a step in). self.pydev_original_step_cmd = -1 # Something as CMD_STEP_INTO, CMD_STEP_OVER, etc. self.pydev_step_cmd = -1 # Something as CMD_STEP_INTO, CMD_STEP_OVER, etc. self.pydev_notify_kill = False self.pydev_django_resolve_frame = False self.pydev_call_from_jinja2 = None self.pydev_call_inside_jinja2 = None self.is_tracing = 0 self.conditional_breakpoint_exception = None self.pydev_message = '' self.suspend_type = PYTHON_SUSPEND self.pydev_next_line = -1 self.pydev_func_name = '.invalid.' # Must match the type in cython self.suspended_at_unhandled = False self.trace_suspend_type = 'trace' # 'trace' or 'frame_eval' self.top_level_thread_tracer_no_back_frames = [] self.top_level_thread_tracer_unhandled = None self.thread_tracer = None self.step_in_initial_location = None self.pydev_smart_parent_offset = -1 self.pydev_smart_child_offset = -1 self.pydev_smart_step_into_variants = () self.target_id_to_smart_step_into_variant = {} # Flag to indicate ipython use-case where each line will be executed as a call/line/return # in a new new frame but in practice we want to consider each new frame as if it was all # part of the same frame. # # In practice this means that a step over shouldn't revert to a step in and we need some # special logic to know when we should stop in a step over as we need to consider 2 # different frames as being equal if they're logically the continuation of a frame # being executed by ipython line by line. # # See: https://github.com/microsoft/debugpy/issues/869#issuecomment-1132141003 self.pydev_use_scoped_step_frame = False def get_topmost_frame(self, thread): ''' Gets the topmost frame for the given thread. Note that it may be None and callers should remove the reference to the frame as soon as possible to avoid disturbing user code. ''' # sys._current_frames(): dictionary with thread id -> topmost frame current_frames = _current_frames() topmost_frame = current_frames.get(thread.ident) if topmost_frame is None: # Note: this is expected for dummy threads (so, getting the topmost frame should be # treated as optional). pydev_log.info( 'Unable to get topmost frame for thread: %s, thread.ident: %s, id(thread): %s\nCurrent frames: %s.\n' 'GEVENT_SUPPORT: %s', thread, thread.ident, id(thread), current_frames, SUPPORT_GEVENT, ) return topmost_frame def __str__(self): return 'State:%s Stop:%s Cmd: %s Kill:%s' % ( self.pydev_state, self.pydev_step_stop, self.pydev_step_cmd, self.pydev_notify_kill) _set_additional_thread_info_lock = ForkSafeLock() def set_additional_thread_info(thread): try: additional_info = thread.additional_info if additional_info is None: raise AttributeError() except: with _set_additional_thread_info_lock: # If it's not there, set it within a lock to avoid any racing # conditions. additional_info = getattr(thread, 'additional_info', None) if additional_info is None: additional_info = PyDBAdditionalThreadInfo() thread.additional_info = additional_info return additional_info
6,239
Python
39.51948
120
0.605706
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_additional_thread_info.py
# Defines which version of the PyDBAdditionalThreadInfo we'll use. from _pydevd_bundle.pydevd_constants import ENV_FALSE_LOWER_VALUES, USE_CYTHON_FLAG, \ ENV_TRUE_LOWER_VALUES if USE_CYTHON_FLAG in ENV_TRUE_LOWER_VALUES: # We must import the cython version if forcing cython from _pydevd_bundle.pydevd_cython_wrapper import PyDBAdditionalThreadInfo, set_additional_thread_info, _set_additional_thread_info_lock # @UnusedImport elif USE_CYTHON_FLAG in ENV_FALSE_LOWER_VALUES: # Use the regular version if not forcing cython from _pydevd_bundle.pydevd_additional_thread_info_regular import PyDBAdditionalThreadInfo, set_additional_thread_info, _set_additional_thread_info_lock # @UnusedImport @Reimport else: # Regular: use fallback if not found (message is already given elsewhere). try: from _pydevd_bundle.pydevd_cython_wrapper import PyDBAdditionalThreadInfo, set_additional_thread_info, _set_additional_thread_info_lock except ImportError: from _pydevd_bundle.pydevd_additional_thread_info_regular import PyDBAdditionalThreadInfo, set_additional_thread_info, _set_additional_thread_info_lock # @UnusedImport
1,166
Python
57.349997
182
0.780446
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_frame.py
import linecache import os.path import re from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_dont_trace from _pydevd_bundle.pydevd_constants import (RETURN_VALUES_DICT, NO_FTRACE, EXCEPTION_TYPE_HANDLED, EXCEPTION_TYPE_USER_UNHANDLED, PYDEVD_IPYTHON_CONTEXT) from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, just_raised, remove_exception_from_frame, ignore_exception_trace from _pydevd_bundle.pydevd_utils import get_clsname_for_code from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame from _pydevd_bundle.pydevd_comm_constants import constant_to_str, CMD_SET_FUNCTION_BREAK try: from _pydevd_bundle.pydevd_bytecode_utils import get_smart_step_into_variant_from_frame_offset except ImportError: def get_smart_step_into_variant_from_frame_offset(*args, **kwargs): return None # IFDEF CYTHON # cython_inline_constant: CMD_STEP_INTO = 107 # cython_inline_constant: CMD_STEP_INTO_MY_CODE = 144 # cython_inline_constant: CMD_STEP_RETURN = 109 # cython_inline_constant: CMD_STEP_RETURN_MY_CODE = 160 # cython_inline_constant: CMD_STEP_OVER = 108 # cython_inline_constant: CMD_STEP_OVER_MY_CODE = 159 # cython_inline_constant: CMD_STEP_CAUGHT_EXCEPTION = 137 # cython_inline_constant: CMD_SET_BREAK = 111 # cython_inline_constant: CMD_SMART_STEP_INTO = 128 # cython_inline_constant: CMD_STEP_INTO_COROUTINE = 206 # cython_inline_constant: STATE_RUN = 1 # cython_inline_constant: STATE_SUSPEND = 2 # ELSE # Note: those are now inlined on cython. CMD_STEP_INTO = 107 CMD_STEP_INTO_MY_CODE = 144 CMD_STEP_RETURN = 109 CMD_STEP_RETURN_MY_CODE = 160 CMD_STEP_OVER = 108 CMD_STEP_OVER_MY_CODE = 159 CMD_STEP_CAUGHT_EXCEPTION = 137 CMD_SET_BREAK = 111 CMD_SMART_STEP_INTO = 128 CMD_STEP_INTO_COROUTINE = 206 STATE_RUN = 1 STATE_SUSPEND = 2 # ENDIF basename = os.path.basename IGNORE_EXCEPTION_TAG = re.compile('[^#]*#.*@IgnoreException') DEBUG_START = ('pydevd.py', 'run') DEBUG_START_PY3K = ('_pydev_execfile.py', 'execfile') TRACE_PROPERTY = 'pydevd_traceproperty.py' import dis try: StopAsyncIteration except NameError: StopAsyncIteration = StopIteration # IFDEF CYTHON # cdef is_unhandled_exception(container_obj, py_db, frame, int last_raise_line, set raise_lines): # ELSE def is_unhandled_exception(container_obj, py_db, frame, last_raise_line, raise_lines): # ENDIF if frame.f_lineno in raise_lines: return True else: try_except_infos = container_obj.try_except_infos if try_except_infos is None: container_obj.try_except_infos = try_except_infos = py_db.collect_try_except_info(frame.f_code) if not try_except_infos: # Consider the last exception as unhandled because there's no try..except in it. return True else: # Now, consider only the try..except for the raise valid_try_except_infos = [] for try_except_info in try_except_infos: if try_except_info.is_line_in_try_block(last_raise_line): valid_try_except_infos.append(try_except_info) if not valid_try_except_infos: return True else: # Note: check all, not only the "valid" ones to cover the case # in "tests_python.test_tracing_on_top_level.raise_unhandled10" # where one try..except is inside the other with only a raise # and it's gotten in the except line. for try_except_info in try_except_infos: if try_except_info.is_line_in_except_block(frame.f_lineno): if ( frame.f_lineno == try_except_info.except_line or frame.f_lineno in try_except_info.raise_lines_in_except ): # In a raise inside a try..except block or some except which doesn't # match the raised exception. return True return False # IFDEF CYTHON # cdef class _TryExceptContainerObj: # cdef public list try_except_infos; # def __init__(self): # self.try_except_infos = None # ELSE class _TryExceptContainerObj(object): ''' A dumb container object just to containe the try..except info when needed. Meant to be persisent among multiple PyDBFrames to the same code object. ''' try_except_infos = None # ENDIF #======================================================================================================================= # PyDBFrame #======================================================================================================================= # IFDEF CYTHON # cdef class PyDBFrame: # ELSE class PyDBFrame: '''This makes the tracing for a given frame, so, the trace_dispatch is used initially when we enter into a new context ('call') and then is reused for the entire context. ''' # ENDIF # Note: class (and not instance) attributes. # Same thing in the main debugger but only considering the file contents, while the one in the main debugger # considers the user input (so, the actual result must be a join of both). filename_to_lines_where_exceptions_are_ignored = {} filename_to_stat_info = {} # IFDEF CYTHON # cdef tuple _args # cdef int should_skip # cdef object exc_info # def __init__(self, tuple args): # self._args = args # In the cython version we don't need to pass the frame # self.should_skip = -1 # On cythonized version, put in instance. # self.exc_info = () # ELSE should_skip = -1 # Default value in class (put in instance on set). exc_info = () # Default value in class (put in instance on set). def __init__(self, args): # args = main_debugger, abs_path_canonical_path_and_base, base, info, t, frame # yeap, much faster than putting in self and then getting it from self later on self._args = args # ENDIF def set_suspend(self, *args, **kwargs): self._args[0].set_suspend(*args, **kwargs) def do_wait_suspend(self, *args, **kwargs): self._args[0].do_wait_suspend(*args, **kwargs) # IFDEF CYTHON # def trace_exception(self, frame, str event, arg): # cdef bint should_stop; # cdef tuple exc_info; # ELSE def trace_exception(self, frame, event, arg): # ENDIF if event == 'exception': should_stop, frame = self._should_stop_on_exception(frame, event, arg) if should_stop: if self._handle_exception(frame, event, arg, EXCEPTION_TYPE_HANDLED): return self.trace_dispatch elif event == 'return': exc_info = self.exc_info if exc_info and arg is None: frame_skips_cache, frame_cache_key = self._args[4], self._args[5] custom_key = (frame_cache_key, 'try_exc_info') container_obj = frame_skips_cache.get(custom_key) if container_obj is None: container_obj = frame_skips_cache[custom_key] = _TryExceptContainerObj() if is_unhandled_exception(container_obj, self._args[0], frame, exc_info[1], exc_info[2]) and \ self.handle_user_exception(frame): return self.trace_dispatch return self.trace_exception # IFDEF CYTHON # cdef _should_stop_on_exception(self, frame, str event, arg): # cdef PyDBAdditionalThreadInfo info; # cdef bint should_stop; # cdef bint was_just_raised; # cdef list check_excs; # ELSE def _should_stop_on_exception(self, frame, event, arg): # ENDIF # main_debugger, _filename, info, _thread = self._args main_debugger = self._args[0] info = self._args[2] should_stop = False # STATE_SUSPEND = 2 if info.pydev_state != 2: # and breakpoint is not None: exception, value, trace = arg if trace is not None and hasattr(trace, 'tb_next'): # on jython trace is None on the first event and it may not have a tb_next. should_stop = False exception_breakpoint = None try: if main_debugger.plugin is not None: result = main_debugger.plugin.exception_break(main_debugger, self, frame, self._args, arg) if result: should_stop, frame = result except: pydev_log.exception() if not should_stop: # Apply checks that don't need the exception breakpoint (where we shouldn't ever stop). if exception == SystemExit and main_debugger.ignore_system_exit_code(value): pass elif exception in (GeneratorExit, StopIteration, StopAsyncIteration): # These exceptions are control-flow related (they work as a generator # pause), so, we shouldn't stop on them. pass elif ignore_exception_trace(trace): pass else: was_just_raised = trace.tb_next is None # It was not handled by any plugin, lets check exception breakpoints. check_excs = [] # Note: check user unhandled before regular exceptions. exc_break_user = main_debugger.get_exception_breakpoint( exception, main_debugger.break_on_user_uncaught_exceptions) if exc_break_user is not None: check_excs.append((exc_break_user, True)) exc_break_caught = main_debugger.get_exception_breakpoint( exception, main_debugger.break_on_caught_exceptions) if exc_break_caught is not None: check_excs.append((exc_break_caught, False)) for exc_break, is_user_uncaught in check_excs: # Initially mark that it should stop and then go into exclusions. should_stop = True if main_debugger.exclude_exception_by_filter(exc_break, trace): pydev_log.debug("Ignore exception %s in library %s -- (%s)" % (exception, frame.f_code.co_filename, frame.f_code.co_name)) should_stop = False elif exc_break.condition is not None and \ not main_debugger.handle_breakpoint_condition(info, exc_break, frame): should_stop = False elif is_user_uncaught: # Note: we don't stop here, we just collect the exc_info to use later on... should_stop = False if not main_debugger.apply_files_filter(frame, frame.f_code.co_filename, True) \ and (frame.f_back is None or main_debugger.apply_files_filter(frame.f_back, frame.f_back.f_code.co_filename, True)): # User uncaught means that we're currently in user code but the code # up the stack is library code. exc_info = self.exc_info if not exc_info: exc_info = (arg, frame.f_lineno, set([frame.f_lineno])) else: lines = exc_info[2] lines.add(frame.f_lineno) exc_info = (arg, frame.f_lineno, lines) self.exc_info = exc_info else: # I.e.: these are only checked if we're not dealing with user uncaught exceptions. if exc_break.notify_on_first_raise_only and main_debugger.skip_on_exceptions_thrown_in_same_context \ and not was_just_raised and not just_raised(trace.tb_next): # In this case we never stop if it was just raised, so, to know if it was the first we # need to check if we're in the 2nd method. should_stop = False # I.e.: we stop only when we're at the caller of a method that throws an exception elif exc_break.notify_on_first_raise_only and not main_debugger.skip_on_exceptions_thrown_in_same_context \ and not was_just_raised: should_stop = False # I.e.: we stop only when it was just raised elif was_just_raised and main_debugger.skip_on_exceptions_thrown_in_same_context: # Option: Don't break if an exception is caught in the same function from which it is thrown should_stop = False if should_stop: exception_breakpoint = exc_break try: info.pydev_message = exc_break.qname except: info.pydev_message = exc_break.qname.encode('utf-8') break if should_stop: # Always add exception to frame (must remove later after we proceed). add_exception_to_frame(frame, (exception, value, trace)) if exception_breakpoint is not None and exception_breakpoint.expression is not None: main_debugger.handle_breakpoint_expression(exception_breakpoint, info, frame) return should_stop, frame def handle_user_exception(self, frame): exc_info = self.exc_info if exc_info: return self._handle_exception(frame, 'exception', exc_info[0], EXCEPTION_TYPE_USER_UNHANDLED) return False # IFDEF CYTHON # cdef _handle_exception(self, frame, str event, arg, str exception_type): # cdef bint stopped; # cdef tuple abs_real_path_and_base; # cdef str absolute_filename; # cdef str canonical_normalized_filename; # cdef dict filename_to_lines_where_exceptions_are_ignored; # cdef dict lines_ignored; # cdef dict frame_id_to_frame; # cdef dict merged; # cdef object trace_obj; # cdef object main_debugger; # ELSE def _handle_exception(self, frame, event, arg, exception_type): # ENDIF stopped = False try: # print('_handle_exception', frame.f_lineno, frame.f_code.co_name) # We have 3 things in arg: exception type, description, traceback object trace_obj = arg[2] main_debugger = self._args[0] initial_trace_obj = trace_obj if trace_obj.tb_next is None and trace_obj.tb_frame is frame: # I.e.: tb_next should be only None in the context it was thrown (trace_obj.tb_frame is frame is just a double check). pass else: # Get the trace_obj from where the exception was raised... while trace_obj.tb_next is not None: trace_obj = trace_obj.tb_next if main_debugger.ignore_exceptions_thrown_in_lines_with_ignore_exception: for check_trace_obj in (initial_trace_obj, trace_obj): abs_real_path_and_base = get_abs_path_real_path_and_base_from_frame(check_trace_obj.tb_frame) absolute_filename = abs_real_path_and_base[0] canonical_normalized_filename = abs_real_path_and_base[1] filename_to_lines_where_exceptions_are_ignored = self.filename_to_lines_where_exceptions_are_ignored lines_ignored = filename_to_lines_where_exceptions_are_ignored.get(canonical_normalized_filename) if lines_ignored is None: lines_ignored = filename_to_lines_where_exceptions_are_ignored[canonical_normalized_filename] = {} try: curr_stat = os.stat(absolute_filename) curr_stat = (curr_stat.st_size, curr_stat.st_mtime) except: curr_stat = None last_stat = self.filename_to_stat_info.get(absolute_filename) if last_stat != curr_stat: self.filename_to_stat_info[absolute_filename] = curr_stat lines_ignored.clear() try: linecache.checkcache(absolute_filename) except: pydev_log.exception('Error in linecache.checkcache(%r)', absolute_filename) from_user_input = main_debugger.filename_to_lines_where_exceptions_are_ignored.get(canonical_normalized_filename) if from_user_input: merged = {} merged.update(lines_ignored) # Override what we have with the related entries that the user entered merged.update(from_user_input) else: merged = lines_ignored exc_lineno = check_trace_obj.tb_lineno # print ('lines ignored', lines_ignored) # print ('user input', from_user_input) # print ('merged', merged, 'curr', exc_lineno) if exc_lineno not in merged: # Note: check on merged but update lines_ignored. try: line = linecache.getline(absolute_filename, exc_lineno, check_trace_obj.tb_frame.f_globals) except: pydev_log.exception('Error in linecache.getline(%r, %s, f_globals)', absolute_filename, exc_lineno) line = '' if IGNORE_EXCEPTION_TAG.match(line) is not None: lines_ignored[exc_lineno] = 1 return False else: # Put in the cache saying not to ignore lines_ignored[exc_lineno] = 0 else: # Ok, dict has it already cached, so, let's check it... if merged.get(exc_lineno, 0): return False thread = self._args[3] try: frame_id_to_frame = {} frame_id_to_frame[id(frame)] = frame f = trace_obj.tb_frame while f is not None: frame_id_to_frame[id(f)] = f f = f.f_back f = None stopped = True main_debugger.send_caught_exception_stack(thread, arg, id(frame)) try: self.set_suspend(thread, CMD_STEP_CAUGHT_EXCEPTION) self.do_wait_suspend(thread, frame, event, arg, exception_type=exception_type) finally: main_debugger.send_caught_exception_stack_proceeded(thread) except: pydev_log.exception() main_debugger.set_trace_for_frame_and_parents(frame) finally: # Make sure the user cannot see the '__exception__' we added after we leave the suspend state. remove_exception_from_frame(frame) # Clear some local variables... frame = None trace_obj = None initial_trace_obj = None check_trace_obj = None f = None frame_id_to_frame = None main_debugger = None thread = None return stopped # IFDEF CYTHON # cdef get_func_name(self, frame): # cdef str func_name # ELSE def get_func_name(self, frame): # ENDIF code_obj = frame.f_code func_name = code_obj.co_name try: cls_name = get_clsname_for_code(code_obj, frame) if cls_name is not None: return "%s.%s" % (cls_name, func_name) else: return func_name except: pydev_log.exception() return func_name # IFDEF CYTHON # cdef _show_return_values(self, frame, arg): # ELSE def _show_return_values(self, frame, arg): # ENDIF try: try: f_locals_back = getattr(frame.f_back, "f_locals", None) if f_locals_back is not None: return_values_dict = f_locals_back.get(RETURN_VALUES_DICT, None) if return_values_dict is None: return_values_dict = {} f_locals_back[RETURN_VALUES_DICT] = return_values_dict name = self.get_func_name(frame) return_values_dict[name] = arg except: pydev_log.exception() finally: f_locals_back = None # IFDEF CYTHON # cdef _remove_return_values(self, main_debugger, frame): # ELSE def _remove_return_values(self, main_debugger, frame): # ENDIF try: try: # Showing return values was turned off, we should remove them from locals dict. # The values can be in the current frame or in the back one frame.f_locals.pop(RETURN_VALUES_DICT, None) f_locals_back = getattr(frame.f_back, "f_locals", None) if f_locals_back is not None: f_locals_back.pop(RETURN_VALUES_DICT, None) except: pydev_log.exception() finally: f_locals_back = None # IFDEF CYTHON # cdef _get_unfiltered_back_frame(self, main_debugger, frame): # ELSE def _get_unfiltered_back_frame(self, main_debugger, frame): # ENDIF f = frame.f_back while f is not None: if not main_debugger.is_files_filter_enabled: return f else: if main_debugger.apply_files_filter(f, f.f_code.co_filename, False): f = f.f_back else: return f return f # IFDEF CYTHON # cdef _is_same_frame(self, target_frame, current_frame): # cdef PyDBAdditionalThreadInfo info; # ELSE def _is_same_frame(self, target_frame, current_frame): # ENDIF if target_frame is current_frame: return True info = self._args[2] if info.pydev_use_scoped_step_frame: # If using scoped step we don't check the target, we just need to check # if the current matches the same heuristic where the target was defined. if target_frame is not None and current_frame is not None: if target_frame.f_code.co_filename == current_frame.f_code.co_filename: # The co_name may be different (it may include the line number), but # the filename must still be the same. f = current_frame.f_back if f is not None and f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[1]: f = f.f_back if f is not None and f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[2]: return True return False # IFDEF CYTHON # cpdef trace_dispatch(self, frame, str event, arg): # cdef tuple abs_path_canonical_path_and_base; # cdef bint is_exception_event; # cdef bint has_exception_breakpoints; # cdef bint can_skip; # cdef bint stop; # cdef PyDBAdditionalThreadInfo info; # cdef int step_cmd; # cdef int line; # cdef bint is_line; # cdef bint is_call; # cdef bint is_return; # cdef bint should_stop; # cdef dict breakpoints_for_file; # cdef dict stop_info; # cdef str curr_func_name; # cdef bint exist_result; # cdef dict frame_skips_cache; # cdef object frame_cache_key; # cdef tuple line_cache_key; # cdef int breakpoints_in_line_cache; # cdef int breakpoints_in_frame_cache; # cdef bint has_breakpoint_in_frame; # cdef bint is_coroutine_or_generator; # cdef int bp_line; # cdef object bp; # cdef int pydev_smart_parent_offset # cdef int pydev_smart_child_offset # cdef tuple pydev_smart_step_into_variants # ELSE def trace_dispatch(self, frame, event, arg): # ENDIF # Note: this is a big function because most of the logic related to hitting a breakpoint and # stepping is contained in it. Ideally this could be split among multiple functions, but the # problem in this case is that in pure-python function calls are expensive and even more so # when tracing is on (because each function call will get an additional tracing call). We # try to address this by using the info.is_tracing for the fastest possible return, but the # cost is still high (maybe we could use code-generation in the future and make the code # generation be better split among what each part does). # DEBUG = '_debugger_case_generator.py' in frame.f_code.co_filename main_debugger, abs_path_canonical_path_and_base, info, thread, frame_skips_cache, frame_cache_key = self._args # if DEBUG: print('frame trace_dispatch %s %s %s %s %s %s, stop: %s' % (frame.f_lineno, frame.f_code.co_name, frame.f_code.co_filename, event, constant_to_str(info.pydev_step_cmd), arg, info.pydev_step_stop)) try: info.is_tracing += 1 # TODO: This shouldn't be needed. The fact that frame.f_lineno # is None seems like a bug in Python 3.11. # Reported in: https://github.com/python/cpython/issues/94485 line = frame.f_lineno or 0 # Workaround or case where frame.f_lineno is None line_cache_key = (frame_cache_key, line) if main_debugger.pydb_disposed: return None if event == 'call' else NO_FTRACE plugin_manager = main_debugger.plugin has_exception_breakpoints = ( main_debugger.break_on_caught_exceptions or main_debugger.break_on_user_uncaught_exceptions or main_debugger.has_plugin_exception_breaks) stop_frame = info.pydev_step_stop step_cmd = info.pydev_step_cmd function_breakpoint_on_call_event = None if frame.f_code.co_flags & 0xa0: # 0xa0 == CO_GENERATOR = 0x20 | CO_COROUTINE = 0x80 # Dealing with coroutines and generators: # When in a coroutine we change the perceived event to the debugger because # a call, StopIteration exception and return are usually just pausing/unpausing it. if event == 'line': is_line = True is_call = False is_return = False is_exception_event = False elif event == 'return': is_line = False is_call = False is_return = True is_exception_event = False returns_cache_key = (frame_cache_key, 'returns') return_lines = frame_skips_cache.get(returns_cache_key) if return_lines is None: # Note: we're collecting the return lines by inspecting the bytecode as # there are multiple returns and multiple stop iterations when awaiting and # it doesn't give any clear indication when a coroutine or generator is # finishing or just pausing. return_lines = set() for x in main_debugger.collect_return_info(frame.f_code): # Note: cython does not support closures in cpdefs (so we can't use # a list comprehension). return_lines.add(x.return_line) frame_skips_cache[returns_cache_key] = return_lines if line not in return_lines: # Not really a return (coroutine/generator paused). return self.trace_dispatch else: if self.exc_info: self.handle_user_exception(frame) return self.trace_dispatch # Tricky handling: usually when we're on a frame which is about to exit # we set the step mode to step into, but in this case we'd end up in the # asyncio internal machinery, which is not what we want, so, we just # ask the stop frame to be a level up. # # Note that there's an issue here which we may want to fix in the future: if # the back frame is a frame which is filtered, we won't stop properly. # Solving this may not be trivial as we'd need to put a scope in the step # in, but we may have to do it anyways to have a step in which doesn't end # up in asyncio). # # Note2: we don't revert to a step in if we're doing scoped stepping # (because on scoped stepping we're always receiving a call/line/return # event for each line in ipython, so, we can't revert to step in on return # as the return shouldn't mean that we've actually completed executing a # frame in this case). if stop_frame is frame and not info.pydev_use_scoped_step_frame: if step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE): f = self._get_unfiltered_back_frame(main_debugger, frame) if f is not None: info.pydev_step_cmd = CMD_STEP_INTO_COROUTINE info.pydev_step_stop = f else: if step_cmd == CMD_STEP_OVER: info.pydev_step_cmd = CMD_STEP_INTO info.pydev_step_stop = None elif step_cmd == CMD_STEP_OVER_MY_CODE: info.pydev_step_cmd = CMD_STEP_INTO_MY_CODE info.pydev_step_stop = None elif step_cmd == CMD_STEP_INTO_COROUTINE: # We're exiting this one, so, mark the new coroutine context. f = self._get_unfiltered_back_frame(main_debugger, frame) if f is not None: info.pydev_step_stop = f else: info.pydev_step_cmd = CMD_STEP_INTO info.pydev_step_stop = None elif event == 'exception': breakpoints_for_file = None if has_exception_breakpoints: should_stop, frame = self._should_stop_on_exception(frame, event, arg) if should_stop: if self._handle_exception(frame, event, arg, EXCEPTION_TYPE_HANDLED): return self.trace_dispatch return self.trace_dispatch else: # event == 'call' or event == 'c_XXX' return self.trace_dispatch else: # Not coroutine nor generator if event == 'line': is_line = True is_call = False is_return = False is_exception_event = False elif event == 'return': is_line = False is_return = True is_call = False is_exception_event = False # If we are in single step mode and something causes us to exit the current frame, we need to make sure we break # eventually. Force the step mode to step into and the step stop frame to None. # I.e.: F6 in the end of a function should stop in the next possible position (instead of forcing the user # to make a step in or step over at that location). # Note: this is especially troublesome when we're skipping code with the # @DontTrace comment. if ( stop_frame is frame and not info.pydev_use_scoped_step_frame and is_return and step_cmd in (CMD_STEP_OVER, CMD_STEP_RETURN, CMD_STEP_OVER_MY_CODE, CMD_STEP_RETURN_MY_CODE, CMD_SMART_STEP_INTO) ): if step_cmd in (CMD_STEP_OVER, CMD_STEP_RETURN, CMD_SMART_STEP_INTO): info.pydev_step_cmd = CMD_STEP_INTO else: info.pydev_step_cmd = CMD_STEP_INTO_MY_CODE info.pydev_step_stop = None if self.exc_info: if self.handle_user_exception(frame): return self.trace_dispatch elif event == 'call': is_line = False is_call = True is_return = False is_exception_event = False if frame.f_code.co_firstlineno == frame.f_lineno: # Check line to deal with async/await. function_breakpoint_on_call_event = main_debugger.function_breakpoint_name_to_breakpoint.get(frame.f_code.co_name) elif event == 'exception': is_exception_event = True breakpoints_for_file = None if has_exception_breakpoints: should_stop, frame = self._should_stop_on_exception(frame, event, arg) if should_stop: if self._handle_exception(frame, event, arg, EXCEPTION_TYPE_HANDLED): return self.trace_dispatch is_line = False is_return = False is_call = False else: # Unexpected: just keep the same trace func (i.e.: event == 'c_XXX'). return self.trace_dispatch if not is_exception_event: breakpoints_for_file = main_debugger.breakpoints.get(abs_path_canonical_path_and_base[1]) can_skip = False if info.pydev_state == 1: # STATE_RUN = 1 # we can skip if: # - we have no stop marked # - we should make a step return/step over and we're not in the current frame # - we're stepping into a coroutine context and we're not in that context if step_cmd == -1: can_skip = True elif step_cmd in (CMD_STEP_OVER, CMD_STEP_RETURN, CMD_STEP_OVER_MY_CODE, CMD_STEP_RETURN_MY_CODE) and not self._is_same_frame(stop_frame, frame): can_skip = True elif step_cmd == CMD_SMART_STEP_INTO and ( stop_frame is not None and stop_frame is not frame and stop_frame is not frame.f_back and (frame.f_back is None or stop_frame is not frame.f_back.f_back)): can_skip = True elif step_cmd == CMD_STEP_INTO_MY_CODE: if ( main_debugger.apply_files_filter(frame, frame.f_code.co_filename, True) and (frame.f_back is None or main_debugger.apply_files_filter(frame.f_back, frame.f_back.f_code.co_filename, True)) ): can_skip = True elif step_cmd == CMD_STEP_INTO_COROUTINE: f = frame while f is not None: if self._is_same_frame(stop_frame, f): break f = f.f_back else: can_skip = True if can_skip: if plugin_manager is not None and ( main_debugger.has_plugin_line_breaks or main_debugger.has_plugin_exception_breaks): can_skip = plugin_manager.can_skip(main_debugger, frame) if can_skip and main_debugger.show_return_values and info.pydev_step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE) and self._is_same_frame(stop_frame, frame.f_back): # trace function for showing return values after step over can_skip = False # Let's check to see if we are in a function that has a breakpoint. If we don't have a breakpoint, # we will return nothing for the next trace # also, after we hit a breakpoint and go to some other debugging state, we have to force the set trace anyway, # so, that's why the additional checks are there. if function_breakpoint_on_call_event: pass # Do nothing here (just keep on going as we can't skip it). elif not breakpoints_for_file: if can_skip: if has_exception_breakpoints: return self.trace_exception else: return None if is_call else NO_FTRACE else: # When cached, 0 means we don't have a breakpoint and 1 means we have. if can_skip: breakpoints_in_line_cache = frame_skips_cache.get(line_cache_key, -1) if breakpoints_in_line_cache == 0: return self.trace_dispatch breakpoints_in_frame_cache = frame_skips_cache.get(frame_cache_key, -1) if breakpoints_in_frame_cache != -1: # Gotten from cache. has_breakpoint_in_frame = breakpoints_in_frame_cache == 1 else: has_breakpoint_in_frame = False try: func_lines = set() for offset_and_lineno in dis.findlinestarts(frame.f_code): func_lines.add(offset_and_lineno[1]) except: # This is a fallback for implementations where we can't get the function # lines -- i.e.: jython (in this case clients need to provide the function # name to decide on the skip or we won't be able to skip the function # completely). # Checks the breakpoint to see if there is a context match in some function. curr_func_name = frame.f_code.co_name # global context is set with an empty name if curr_func_name in ('?', '<module>', '<lambda>'): curr_func_name = '' for bp in breakpoints_for_file.values(): # will match either global or some function if bp.func_name in ('None', curr_func_name): has_breakpoint_in_frame = True break else: for bp_line in breakpoints_for_file: # iterate on keys if bp_line in func_lines: has_breakpoint_in_frame = True break # Cache the value (1 or 0 or -1 for default because of cython). if has_breakpoint_in_frame: frame_skips_cache[frame_cache_key] = 1 else: frame_skips_cache[frame_cache_key] = 0 if can_skip and not has_breakpoint_in_frame: if has_exception_breakpoints: return self.trace_exception else: return None if is_call else NO_FTRACE # We may have hit a breakpoint or we are already in step mode. Either way, let's check what we should do in this frame # if DEBUG: print('NOT skipped: %s %s %s %s' % (frame.f_lineno, frame.f_code.co_name, event, frame.__class__.__name__)) try: flag = False # return is not taken into account for breakpoint hit because we'd have a double-hit in this case # (one for the line and the other for the return). stop_info = {} breakpoint = None exist_result = False stop = False stop_reason = CMD_SET_BREAK bp_type = None if function_breakpoint_on_call_event: breakpoint = function_breakpoint_on_call_event stop = True new_frame = frame stop_reason = CMD_SET_FUNCTION_BREAK elif is_line and info.pydev_state != STATE_SUSPEND and breakpoints_for_file is not None and line in breakpoints_for_file: breakpoint = breakpoints_for_file[line] new_frame = frame stop = True if step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE) and (self._is_same_frame(stop_frame, frame) and is_line): stop = False # we don't stop on breakpoint if we have to stop by step-over (it will be processed later) elif plugin_manager is not None and main_debugger.has_plugin_line_breaks: result = plugin_manager.get_breakpoint(main_debugger, self, frame, event, self._args) if result: exist_result = True flag, breakpoint, new_frame, bp_type = result if breakpoint: # ok, hit breakpoint, now, we have to discover if it is a conditional breakpoint # lets do the conditional stuff here if breakpoint.expression is not None: main_debugger.handle_breakpoint_expression(breakpoint, info, new_frame) if breakpoint.is_logpoint and info.pydev_message is not None and len(info.pydev_message) > 0: cmd = main_debugger.cmd_factory.make_io_message(info.pydev_message + os.linesep, '1') main_debugger.writer.add_command(cmd) if stop or exist_result: eval_result = False if breakpoint.has_condition: eval_result = main_debugger.handle_breakpoint_condition(info, breakpoint, new_frame) if breakpoint.has_condition: if not eval_result: stop = False elif breakpoint.is_logpoint: stop = False if is_call and (frame.f_code.co_name in ('<lambda>', '<module>') or (line == 1 and frame.f_code.co_name.startswith('<cell'))): # If we find a call for a module, it means that the module is being imported/executed for the # first time. In this case we have to ignore this hit as it may later duplicated by a # line event at the same place (so, if there's a module with a print() in the first line # the user will hit that line twice, which is not what we want). # # For lambda, as it only has a single statement, it's not interesting to trace # its call and later its line event as they're usually in the same line. # # For ipython, <cell xxx> may be executed having each line compiled as a new # module, so it's the same case as <module>. return self.trace_dispatch if main_debugger.show_return_values: if is_return and ( (info.pydev_step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_SMART_STEP_INTO) and (self._is_same_frame(stop_frame, frame.f_back))) or (info.pydev_step_cmd in (CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE) and (self._is_same_frame(stop_frame, frame))) or (info.pydev_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_COROUTINE)) or ( info.pydev_step_cmd == CMD_STEP_INTO_MY_CODE and frame.f_back is not None and not main_debugger.apply_files_filter(frame.f_back, frame.f_back.f_code.co_filename, True) ) ): self._show_return_values(frame, arg) elif main_debugger.remove_return_values_flag: try: self._remove_return_values(main_debugger, frame) finally: main_debugger.remove_return_values_flag = False if stop: self.set_suspend( thread, stop_reason, suspend_other_threads=breakpoint and breakpoint.suspend_policy == "ALL", ) elif flag and plugin_manager is not None: result = plugin_manager.suspend(main_debugger, thread, frame, bp_type) if result: frame = result # if thread has a suspend flag, we suspend with a busy wait if info.pydev_state == STATE_SUSPEND: self.do_wait_suspend(thread, frame, event, arg) return self.trace_dispatch else: if not breakpoint and is_line: # No stop from anyone and no breakpoint found in line (cache that). frame_skips_cache[line_cache_key] = 0 except: pydev_log.exception() raise # step handling. We stop when we hit the right frame try: should_skip = 0 if pydevd_dont_trace.should_trace_hook is not None: if self.should_skip == -1: # I.e.: cache the result on self.should_skip (no need to evaluate the same frame multiple times). # Note that on a code reload, we won't re-evaluate this because in practice, the frame.f_code # Which will be handled by this frame is read-only, so, we can cache it safely. if not pydevd_dont_trace.should_trace_hook(frame, abs_path_canonical_path_and_base[0]): # -1, 0, 1 to be Cython-friendly should_skip = self.should_skip = 1 else: should_skip = self.should_skip = 0 else: should_skip = self.should_skip plugin_stop = False if should_skip: stop = False elif step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_INTO_COROUTINE): force_check_project_scope = step_cmd == CMD_STEP_INTO_MY_CODE if is_line: if not info.pydev_use_scoped_step_frame: if force_check_project_scope or main_debugger.is_files_filter_enabled: stop = not main_debugger.apply_files_filter(frame, frame.f_code.co_filename, force_check_project_scope) else: stop = True else: # We can only stop inside the ipython call. filename = frame.f_code.co_filename if filename.endswith('.pyc'): filename = filename[:-1] if not filename.endswith(PYDEVD_IPYTHON_CONTEXT[0]): f = frame.f_back while f is not None: if f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[1]: f2 = f.f_back if f2 is not None and f2.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[2]: pydev_log.debug('Stop inside ipython call') stop = True break f = f.f_back del f if not stop: # In scoped mode if step in didn't work in this context it won't work # afterwards anyways. return None if is_call else NO_FTRACE elif is_return and frame.f_back is not None and not info.pydev_use_scoped_step_frame: if main_debugger.get_file_type(frame.f_back) == main_debugger.PYDEV_FILE: stop = False else: if force_check_project_scope or main_debugger.is_files_filter_enabled: stop = not main_debugger.apply_files_filter(frame.f_back, frame.f_back.f_code.co_filename, force_check_project_scope) if stop: # Prevent stopping in a return to the same location we were initially # (i.e.: double-stop at the same place due to some filtering). if info.step_in_initial_location == (frame.f_back, frame.f_back.f_lineno): stop = False else: stop = True else: stop = False if stop: if step_cmd == CMD_STEP_INTO_COROUTINE: # i.e.: Check if we're stepping into the proper context. f = frame while f is not None: if self._is_same_frame(stop_frame, f): break f = f.f_back else: stop = False if plugin_manager is not None: result = plugin_manager.cmd_step_into(main_debugger, frame, event, self._args, stop_info, stop) if result: stop, plugin_stop = result elif step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE): # Note: when dealing with a step over my code it's the same as a step over (the # difference is that when we return from a frame in one we go to regular step # into and in the other we go to a step into my code). stop = self._is_same_frame(stop_frame, frame) and is_line # Note: don't stop on a return for step over, only for line events # i.e.: don't stop in: (stop_frame is frame.f_back and is_return) as we'd stop twice in that line. if plugin_manager is not None: result = plugin_manager.cmd_step_over(main_debugger, frame, event, self._args, stop_info, stop) if result: stop, plugin_stop = result elif step_cmd == CMD_SMART_STEP_INTO: stop = False back = frame.f_back if self._is_same_frame(stop_frame, frame) and is_return: # We're exiting the smart step into initial frame (so, we probably didn't find our target). stop = True elif self._is_same_frame(stop_frame, back) and is_line: if info.pydev_smart_child_offset != -1: # i.e.: in this case, we're not interested in the pause in the parent, rather # we're interested in the pause in the child (when the parent is at the proper place). stop = False else: pydev_smart_parent_offset = info.pydev_smart_parent_offset pydev_smart_step_into_variants = info.pydev_smart_step_into_variants if pydev_smart_parent_offset >= 0 and pydev_smart_step_into_variants: # Preferred mode (when the smart step into variants are available # and the offset is set). stop = get_smart_step_into_variant_from_frame_offset(back.f_lasti, pydev_smart_step_into_variants) is \ get_smart_step_into_variant_from_frame_offset(pydev_smart_parent_offset, pydev_smart_step_into_variants) else: # Only the name/line is available, so, check that. curr_func_name = frame.f_code.co_name # global context is set with an empty name if curr_func_name in ('?', '<module>') or curr_func_name is None: curr_func_name = '' if curr_func_name == info.pydev_func_name and stop_frame.f_lineno == info.pydev_next_line: stop = True if not stop: # In smart step into, if we didn't hit it in this frame once, that'll # not be the case next time either, so, disable tracing for this frame. return None if is_call else NO_FTRACE elif back is not None and self._is_same_frame(stop_frame, back.f_back) and is_line: # Ok, we have to track 2 stops at this point, the parent and the child offset. # This happens when handling a step into which targets a function inside a list comprehension # or generator (in which case an intermediary frame is created due to an internal function call). pydev_smart_parent_offset = info.pydev_smart_parent_offset pydev_smart_child_offset = info.pydev_smart_child_offset # print('matched back frame', pydev_smart_parent_offset, pydev_smart_child_offset) # print('parent f_lasti', back.f_back.f_lasti) # print('child f_lasti', back.f_lasti) stop = False if pydev_smart_child_offset >= 0 and pydev_smart_child_offset >= 0: pydev_smart_step_into_variants = info.pydev_smart_step_into_variants if pydev_smart_parent_offset >= 0 and pydev_smart_step_into_variants: # Note that we don't really check the parent offset, only the offset of # the child (because this is a generator, the parent may have moved forward # already -- and that's ok, so, we just check that the parent frame # matches in this case). smart_step_into_variant = get_smart_step_into_variant_from_frame_offset(pydev_smart_parent_offset, pydev_smart_step_into_variants) # print('matched parent offset', pydev_smart_parent_offset) # Ok, now, check the child variant children_variants = smart_step_into_variant.children_variants stop = children_variants and ( get_smart_step_into_variant_from_frame_offset(back.f_lasti, children_variants) is \ get_smart_step_into_variant_from_frame_offset(pydev_smart_child_offset, children_variants) ) # print('stop at child', stop) if not stop: # In smart step into, if we didn't hit it in this frame once, that'll # not be the case next time either, so, disable tracing for this frame. return None if is_call else NO_FTRACE elif step_cmd in (CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE): stop = is_return and self._is_same_frame(stop_frame, frame) else: stop = False if stop and step_cmd != -1 and is_return and hasattr(frame, "f_back"): f_code = getattr(frame.f_back, 'f_code', None) if f_code is not None: if main_debugger.get_file_type(frame.f_back) == main_debugger.PYDEV_FILE: stop = False if plugin_stop: stopped_on_plugin = plugin_manager.stop(main_debugger, frame, event, self._args, stop_info, arg, step_cmd) elif stop: if is_line: self.set_suspend(thread, step_cmd, original_step_cmd=info.pydev_original_step_cmd) self.do_wait_suspend(thread, frame, event, arg) elif is_return: # return event back = frame.f_back if back is not None: # When we get to the pydevd run function, the debugging has actually finished for the main thread # (note that it can still go on for other threads, but for this one, we just make it finish) # So, just setting it to None should be OK back_absolute_filename, _, base = get_abs_path_real_path_and_base_from_frame(back) if (base, back.f_code.co_name) in (DEBUG_START, DEBUG_START_PY3K): back = None elif base == TRACE_PROPERTY: # We dont want to trace the return event of pydevd_traceproperty (custom property for debugging) # if we're in a return, we want it to appear to the user in the previous frame! return None if is_call else NO_FTRACE elif pydevd_dont_trace.should_trace_hook is not None: if not pydevd_dont_trace.should_trace_hook(back, back_absolute_filename): # In this case, we'll have to skip the previous one because it shouldn't be traced. # Also, we have to reset the tracing, because if the parent's parent (or some # other parent) has to be traced and it's not currently, we wouldn't stop where # we should anymore (so, a step in/over/return may not stop anywhere if no parent is traced). # Related test: _debugger_case17a.py main_debugger.set_trace_for_frame_and_parents(back) return None if is_call else NO_FTRACE if back is not None: # if we're in a return, we want it to appear to the user in the previous frame! self.set_suspend(thread, step_cmd, original_step_cmd=info.pydev_original_step_cmd) self.do_wait_suspend(thread, back, event, arg) else: # in jython we may not have a back frame info.pydev_step_stop = None info.pydev_original_step_cmd = -1 info.pydev_step_cmd = -1 info.pydev_state = STATE_RUN except KeyboardInterrupt: raise except: try: pydev_log.exception() info.pydev_original_step_cmd = -1 info.pydev_step_cmd = -1 info.pydev_step_stop = None except: return None if is_call else NO_FTRACE # if we are quitting, let's stop the tracing if main_debugger.quitting: return None if is_call else NO_FTRACE return self.trace_dispatch finally: info.is_tracing -= 1 # end trace_dispatch
63,187
Python
49.958064
216
0.507051
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_thread_lifecycle.py
from _pydevd_bundle import pydevd_utils from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info from _pydevd_bundle.pydevd_comm_constants import CMD_STEP_INTO, CMD_THREAD_SUSPEND from _pydevd_bundle.pydevd_constants import PYTHON_SUSPEND, STATE_SUSPEND, get_thread_id, STATE_RUN from _pydev_bundle._pydev_saved_modules import threading from _pydev_bundle import pydev_log def pydevd_find_thread_by_id(thread_id): try: threads = threading.enumerate() for i in threads: tid = get_thread_id(i) if thread_id == tid or thread_id.endswith('|' + tid): return i # This can happen when a request comes for a thread which was previously removed. pydev_log.info("Could not find thread %s.", thread_id) pydev_log.info("Available: %s.", ([get_thread_id(t) for t in threads],)) except: pydev_log.exception() return None def mark_thread_suspended(thread, stop_reason, original_step_cmd=-1): info = set_additional_thread_info(thread) info.suspend_type = PYTHON_SUSPEND if original_step_cmd != -1: stop_reason = original_step_cmd thread.stop_reason = stop_reason # Note: don't set the 'pydev_original_step_cmd' here if unset. if info.pydev_step_cmd == -1: # If the step command is not specified, set it to step into # to make sure it'll break as soon as possible. info.pydev_step_cmd = CMD_STEP_INTO info.pydev_step_stop = None # Mark as suspended as the last thing. info.pydev_state = STATE_SUSPEND return info def internal_run_thread(thread, set_additional_thread_info): info = set_additional_thread_info(thread) info.pydev_original_step_cmd = -1 info.pydev_step_cmd = -1 info.pydev_step_stop = None info.pydev_state = STATE_RUN def resume_threads(thread_id, except_thread=None): pydev_log.info('Resuming threads: %s (except thread: %s)', thread_id, except_thread) threads = [] if thread_id == '*': threads = pydevd_utils.get_non_pydevd_threads() elif thread_id.startswith('__frame__:'): pydev_log.critical("Can't make tasklet run: %s", thread_id) else: threads = [pydevd_find_thread_by_id(thread_id)] for t in threads: if t is None or t is except_thread: pydev_log.info('Skipped resuming thread: %s', t) continue internal_run_thread(t, set_additional_thread_info=set_additional_thread_info) def suspend_all_threads(py_db, except_thread): ''' Suspend all except the one passed as a parameter. :param except_thread: ''' pydev_log.info('Suspending all threads except: %s', except_thread) all_threads = pydevd_utils.get_non_pydevd_threads() for t in all_threads: if getattr(t, 'pydev_do_not_trace', None): pass # skip some other threads, i.e. ipython history saving thread from debug console else: if t is except_thread: continue info = mark_thread_suspended(t, CMD_THREAD_SUSPEND) frame = info.get_topmost_frame(t) # Reset the tracing as in this case as it could've set scopes to be untraced. if frame is not None: try: py_db.set_trace_for_frame_and_parents(frame) finally: frame = None
3,408
Python
34.14433
99
0.639378
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_breakpoints.py
from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_import_class from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame from _pydev_bundle._pydev_saved_modules import threading class ExceptionBreakpoint(object): def __init__( self, qname, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries ): exctype = get_exception_class(qname) self.qname = qname if exctype is not None: self.name = exctype.__name__ else: self.name = None self.condition = condition self.expression = expression self.notify_on_unhandled_exceptions = notify_on_unhandled_exceptions self.notify_on_handled_exceptions = notify_on_handled_exceptions self.notify_on_first_raise_only = notify_on_first_raise_only self.notify_on_user_unhandled_exceptions = notify_on_user_unhandled_exceptions self.ignore_libraries = ignore_libraries self.type = exctype def __str__(self): return self.qname @property def has_condition(self): return self.condition is not None def handle_hit_condition(self, frame): return False class LineBreakpoint(object): def __init__(self, breakpoint_id, line, condition, func_name, expression, suspend_policy="NONE", hit_condition=None, is_logpoint=False): self.breakpoint_id = breakpoint_id self.line = line self.condition = condition self.func_name = func_name self.expression = expression self.suspend_policy = suspend_policy self.hit_condition = hit_condition self._hit_count = 0 self._hit_condition_lock = threading.Lock() self.is_logpoint = is_logpoint @property def has_condition(self): return bool(self.condition) or bool(self.hit_condition) def handle_hit_condition(self, frame): if not self.hit_condition: return False ret = False with self._hit_condition_lock: self._hit_count += 1 expr = self.hit_condition.replace('@HIT@', str(self._hit_count)) try: ret = bool(eval(expr, frame.f_globals, frame.f_locals)) except Exception: ret = False return ret class FunctionBreakpoint(object): def __init__(self, func_name, condition, expression, suspend_policy="NONE", hit_condition=None, is_logpoint=False): self.condition = condition self.func_name = func_name self.expression = expression self.suspend_policy = suspend_policy self.hit_condition = hit_condition self._hit_count = 0 self._hit_condition_lock = threading.Lock() self.is_logpoint = is_logpoint @property def has_condition(self): return bool(self.condition) or bool(self.hit_condition) def handle_hit_condition(self, frame): if not self.hit_condition: return False ret = False with self._hit_condition_lock: self._hit_count += 1 expr = self.hit_condition.replace('@HIT@', str(self._hit_count)) try: ret = bool(eval(expr, frame.f_globals, frame.f_locals)) except Exception: ret = False return ret def get_exception_breakpoint(exctype, exceptions): if not exctype: exception_full_qname = None else: exception_full_qname = str(exctype.__module__) + '.' + exctype.__name__ exc = None if exceptions is not None: try: return exceptions[exception_full_qname] except KeyError: for exception_breakpoint in exceptions.values(): if exception_breakpoint.type is not None and issubclass(exctype, exception_breakpoint.type): if exc is None or issubclass(exception_breakpoint.type, exc.type): exc = exception_breakpoint return exc def stop_on_unhandled_exception(py_db, thread, additional_info, arg): exctype, value, tb = arg break_on_uncaught_exceptions = py_db.break_on_uncaught_exceptions if break_on_uncaught_exceptions: exception_breakpoint = py_db.get_exception_breakpoint(exctype, break_on_uncaught_exceptions) else: exception_breakpoint = None if not exception_breakpoint: return if tb is None: # sometimes it can be None, e.g. with GTK return if exctype is KeyboardInterrupt: return if exctype is SystemExit and py_db.ignore_system_exit_code(value): return frames = [] user_frame = None while tb is not None: if not py_db.exclude_exception_by_filter(exception_breakpoint, tb): user_frame = tb.tb_frame frames.append(tb.tb_frame) tb = tb.tb_next if user_frame is None: return frames_byid = dict([(id(frame), frame) for frame in frames]) add_exception_to_frame(user_frame, arg) if exception_breakpoint.condition is not None: eval_result = py_db.handle_breakpoint_condition(additional_info, exception_breakpoint, user_frame) if not eval_result: return if exception_breakpoint.expression is not None: py_db.handle_breakpoint_expression(exception_breakpoint, additional_info, user_frame) try: additional_info.pydev_message = exception_breakpoint.qname except: additional_info.pydev_message = exception_breakpoint.qname.encode('utf-8') pydev_log.debug('Handling post-mortem stop on exception breakpoint %s' % (exception_breakpoint.qname,)) py_db.do_stop_on_unhandled_exception(thread, user_frame, frames_byid, arg) def get_exception_class(kls): try: return eval(kls) except: return pydevd_import_class.import_name(kls)
6,010
Python
31.491892
140
0.635275
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_dispatch.py
# Defines which version of the trace_dispatch we'll use. # Should give warning only here if cython is not available but supported. import os from _pydevd_bundle.pydevd_constants import USE_CYTHON_FLAG, ENV_TRUE_LOWER_VALUES, \ ENV_FALSE_LOWER_VALUES from _pydev_bundle import pydev_log dirname = os.path.dirname(os.path.dirname(__file__)) USING_CYTHON = False def delete_old_compiled_extensions(): import _pydevd_bundle cython_extensions_dir = os.path.dirname(os.path.dirname(_pydevd_bundle.__file__)) _pydevd_bundle_ext_dir = os.path.dirname(_pydevd_bundle.__file__) _pydevd_frame_eval_ext_dir = os.path.join(cython_extensions_dir, '_pydevd_frame_eval_ext') try: import shutil for file in os.listdir(_pydevd_bundle_ext_dir): if file.startswith("pydevd") and file.endswith(".so"): os.remove(os.path.join(_pydevd_bundle_ext_dir, file)) for file in os.listdir(_pydevd_frame_eval_ext_dir): if file.startswith("pydevd") and file.endswith(".so"): os.remove(os.path.join(_pydevd_frame_eval_ext_dir, file)) build_dir = os.path.join(cython_extensions_dir, "build") if os.path.exists(build_dir): shutil.rmtree(os.path.join(cython_extensions_dir, "build")) except OSError: pydev_log.error_once("warning: failed to delete old cython speedups. Please delete all *.so files from the directories " "\"%s\" and \"%s\"" % (_pydevd_bundle_ext_dir, _pydevd_frame_eval_ext_dir)) if USE_CYTHON_FLAG in ENV_TRUE_LOWER_VALUES: # We must import the cython version if forcing cython from _pydevd_bundle.pydevd_cython_wrapper import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func USING_CYTHON = True elif USE_CYTHON_FLAG in ENV_FALSE_LOWER_VALUES: # Use the regular version if not forcing cython from _pydevd_bundle.pydevd_trace_dispatch_regular import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func # @UnusedImport else: # Regular: use fallback if not found and give message to user try: from _pydevd_bundle.pydevd_cython_wrapper import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func # This version number is always available from _pydevd_bundle.pydevd_additional_thread_info_regular import version as regular_version # This version number from the already compiled cython extension from _pydevd_bundle.pydevd_cython_wrapper import version as cython_version if cython_version != regular_version: # delete_old_compiled_extensions() -- would be ok in dev mode but we don't want to erase # files from other python versions on release, so, just raise import error here. raise ImportError('Cython version of speedups does not match.') else: USING_CYTHON = True except ImportError: from _pydevd_bundle.pydevd_trace_dispatch_regular import trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func # @UnusedImport pydev_log.show_compile_cython_command_line()
3,265
Python
50.841269
182
0.69709
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_import_class.py
#Note: code gotten from _pydev_imports_tipper. import sys def _imp(name, log=None): try: return __import__(name) except: if '.' in name: sub = name[0:name.rfind('.')] if log is not None: log.add_content('Unable to import', name, 'trying with', sub) log.add_exception() return _imp(sub, log) else: s = 'Unable to import module: %s - sys.path: %s' % (str(name), sys.path) if log is not None: log.add_content(s) log.add_exception() raise ImportError(s) IS_IPY = False if sys.platform == 'cli': IS_IPY = True _old_imp = _imp def _imp(name, log=None): #We must add a reference in clr for .Net import clr #@UnresolvedImport initial_name = name while '.' in name: try: clr.AddReference(name) break #If it worked, that's OK. except: name = name[0:name.rfind('.')] else: try: clr.AddReference(name) except: pass #That's OK (not dot net module). return _old_imp(initial_name, log) def import_name(name, log=None): mod = _imp(name, log) components = name.split('.') old_comp = None for comp in components[1:]: try: #this happens in the following case: #we have mx.DateTime.mxDateTime.mxDateTime.pyd #but after importing it, mx.DateTime.mxDateTime shadows access to mxDateTime.pyd mod = getattr(mod, comp) except AttributeError: if old_comp != comp: raise old_comp = comp return mod
1,838
Python
25.652174
92
0.490751
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_trace_api.py
def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None): return None def after_breakpoints_consolidated(py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints): return None def add_exception_breakpoint(plugin, pydb, type, exception): return False def remove_exception_breakpoint(plugin, pydb, type, exception): return False def remove_all_exception_breakpoints(plugin, pydb): return False def get_breakpoints(plugin, pydb): return None def can_skip(plugin, pydb, frame): return True def has_exception_breaks(plugin): return False def has_line_breaks(plugin): return False def cmd_step_into(plugin, pydb, frame, event, args, stop_info, stop): return False def cmd_step_over(plugin, pydb, frame, event, args, stop_info, stop): return False def stop(plugin, pydb, frame, event, args, stop_info, arg, step_cmd): return False def get_breakpoint(plugin, pydb, pydb_frame, frame, event, args): return None def suspend(plugin, pydb, thread, frame): return None def exception_break(plugin, pydb, pydb_frame, frame, args, arg): return None def change_variable(plugin, frame, attr, expression): return False
1,397
Python
21.190476
231
0.727989
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_comm.py
''' pydevd - a debugging daemon This is the daemon you launch for python remote debugging. Protocol: each command has a format: id\tsequence-num\ttext id: protocol command number sequence-num: each request has a sequence number. Sequence numbers originating at the debugger are odd, sequence numbers originating at the daemon are even. Every response uses the same sequence number as the request. payload: it is protocol dependent. When response is a complex structure, it is returned as XML. Each attribute value is urlencoded, and then the whole payload is urlencoded again to prevent stray characters corrupting protocol/xml encodings Commands: NUMBER NAME FROM* ARGUMENTS RESPONSE NOTE 100 series: program execution 101 RUN JAVA - - 102 LIST_THREADS JAVA RETURN with XML listing of all threads 103 THREAD_CREATE PYDB - XML with thread information 104 THREAD_KILL JAVA id (or * to exit) kills the thread PYDB id nofies JAVA that thread was killed 105 THREAD_SUSPEND JAVA XML of the stack, suspends the thread reason for suspension PYDB id notifies JAVA that thread was suspended 106 CMD_THREAD_RUN JAVA id resume the thread PYDB id \t reason notifies JAVA that thread was resumed 107 STEP_INTO JAVA thread_id 108 STEP_OVER JAVA thread_id 109 STEP_RETURN JAVA thread_id 110 GET_VARIABLE JAVA thread_id \t frame_id \t GET_VARIABLE with XML of var content FRAME|GLOBAL \t attributes* 111 SET_BREAK JAVA file/line of the breakpoint 112 REMOVE_BREAK JAVA file/line of the return 113 CMD_EVALUATE_EXPRESSION JAVA expression result of evaluating the expression 114 CMD_GET_FRAME JAVA request for frame contents 115 CMD_EXEC_EXPRESSION JAVA 116 CMD_WRITE_TO_CONSOLE PYDB 117 CMD_CHANGE_VARIABLE 118 CMD_RUN_TO_LINE 119 CMD_RELOAD_CODE 120 CMD_GET_COMPLETIONS JAVA 200 CMD_REDIRECT_OUTPUT JAVA streams to redirect as string - 'STDOUT' (redirect only STDOUT) 'STDERR' (redirect only STDERR) 'STDOUT STDERR' (redirect both streams) 500 series diagnostics/ok 501 VERSION either Version string (1.0) Currently just used at startup 502 RETURN either Depends on caller - 900 series: errors 901 ERROR either - This is reserved for unexpected errors. * JAVA - remote debugger, the java end * PYDB - pydevd, the python end ''' import linecache import os from _pydev_bundle.pydev_imports import _queue from _pydev_bundle._pydev_saved_modules import time from _pydev_bundle._pydev_saved_modules import threading from _pydev_bundle._pydev_saved_modules import socket as socket_module from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC, get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport silence_warnings_decorator, filter_all_warnings) from _pydev_bundle.pydev_override import overrides import weakref from _pydev_bundle._pydev_completer import extract_token_and_qualifier from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \ SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema from _pydevd_bundle.pydevd_net_command import NetCommand from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE import dis from _pydevd_bundle.pydevd_frame_utils import create_frames_list_from_exception_cause import pydevd_file_utils import itertools from urllib.parse import quote_plus, unquote_plus import pydevconsole from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload from _pydevd_bundle import pydevd_bytecode_utils from _pydevd_bundle import pydevd_xml from _pydevd_bundle import pydevd_vm_type import sys import traceback from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \ notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer from _pydev_bundle import pydev_log, fsnotify from _pydev_bundle.pydev_log import exception as pydev_log_exception from _pydev_bundle import _pydev_completer from pydevd_tracing import get_exception_traceback_str from _pydevd_bundle import pydevd_console from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules from io import StringIO # CMD_XXX constants imported for backward compatibility from _pydevd_bundle.pydevd_comm_constants import * # @UnusedWildImport # Socket import aliases: AF_INET, SOCK_STREAM, SHUT_WR, SOL_SOCKET, SO_REUSEADDR, IPPROTO_TCP, socket = ( socket_module.AF_INET, socket_module.SOCK_STREAM, socket_module.SHUT_WR, socket_module.SOL_SOCKET, socket_module.SO_REUSEADDR, socket_module.IPPROTO_TCP, socket_module.socket, ) if IS_WINDOWS and not IS_JYTHON: SO_EXCLUSIVEADDRUSE = socket_module.SO_EXCLUSIVEADDRUSE class ReaderThread(PyDBDaemonThread): ''' reader thread reads and dispatches commands in an infinite loop ''' def __init__(self, sock, py_db, PyDevJsonCommandProcessor, process_net_command, terminate_on_socket_close=True): assert sock is not None PyDBDaemonThread.__init__(self, py_db) self.__terminate_on_socket_close = terminate_on_socket_close self.sock = sock self._buffer = b'' self.name = "pydevd.Reader" self.process_net_command = process_net_command self.process_net_command_json = PyDevJsonCommandProcessor(self._from_json).process_net_command_json def _from_json(self, json_msg, update_ids_from_dap=False): return pydevd_base_schema.from_json(json_msg, update_ids_from_dap, on_dict_loaded=self._on_dict_loaded) def _on_dict_loaded(self, dct): for listener in self.py_db.dap_messages_listeners: listener.after_receive(dct) @overrides(PyDBDaemonThread.do_kill_pydev_thread) def do_kill_pydev_thread(self): PyDBDaemonThread.do_kill_pydev_thread(self) # Note that we no longer shutdown the reader, just the writer. The idea is that we shutdown # the writer to send that the communication has finished, then, the client will shutdown its # own writer when it receives an empty read, at which point this reader will also shutdown. # That way, we can *almost* guarantee that all messages have been properly sent -- it's not # completely guaranteed because it's possible that the process exits before the whole # message was sent as having this thread alive won't stop the process from exiting -- we # have a timeout when exiting the process waiting for this thread to finish -- see: # PyDB.dispose_and_kill_all_pydevd_threads()). # try: # self.sock.shutdown(SHUT_RD) # except: # pass # try: # self.sock.close() # except: # pass def _read(self, size): while True: buffer_len = len(self._buffer) if buffer_len == size: ret = self._buffer self._buffer = b'' return ret if buffer_len > size: ret = self._buffer[:size] self._buffer = self._buffer[size:] return ret try: r = self.sock.recv(max(size - buffer_len, 1024)) except OSError: return b'' if not r: return b'' self._buffer += r def _read_line(self): while True: i = self._buffer.find(b'\n') if i != -1: i += 1 # Add the newline to the return ret = self._buffer[:i] self._buffer = self._buffer[i:] return ret else: try: r = self.sock.recv(1024) except OSError: return b'' if not r: return b'' self._buffer += r @overrides(PyDBDaemonThread._on_run) def _on_run(self): try: content_len = -1 while True: # i.e.: even if we received a kill, we should only exit the ReaderThread when the # client itself closes the connection (although on kill received we stop actually # processing anything read). try: notify_about_gevent_if_needed() line = self._read_line() if len(line) == 0: pydev_log.debug('ReaderThread: empty contents received (len(line) == 0).') self._terminate_on_socket_close() return # Finished communication. if self._kill_received: continue if line.startswith(b'Content-Length:'): content_len = int(line.strip().split(b':', 1)[1]) continue if content_len != -1: # If we previously received a content length, read until a '\r\n'. if line == b'\r\n': json_contents = self._read(content_len) content_len = -1 if len(json_contents) == 0: pydev_log.debug('ReaderThread: empty contents received (len(json_contents) == 0).') self._terminate_on_socket_close() return # Finished communication. if self._kill_received: continue # We just received a json message, let's process it. self.process_net_command_json(self.py_db, json_contents) continue else: # No content len, regular line-based protocol message (remove trailing new-line). if line.endswith(b'\n\n'): line = line[:-2] elif line.endswith(b'\n'): line = line[:-1] elif line.endswith(b'\r'): line = line[:-1] except: if not self._kill_received: pydev_log_exception() self._terminate_on_socket_close() return # Finished communication. # Note: the java backend is always expected to pass utf-8 encoded strings. We now work with str # internally and thus, we may need to convert to the actual encoding where needed (i.e.: filenames # on python 2 may need to be converted to the filesystem encoding). if hasattr(line, 'decode'): line = line.decode('utf-8') if DebugInfoHolder.DEBUG_RECORD_SOCKET_READS: pydev_log.critical(u'debugger: received >>%s<<\n' % (line,)) args = line.split(u'\t', 2) try: cmd_id = int(args[0]) pydev_log.debug('Received command: %s %s\n' % (ID_TO_MEANING.get(str(cmd_id), '???'), line,)) self.process_command(cmd_id, int(args[1]), args[2]) except: if sys is not None and pydev_log_exception is not None: # Could happen at interpreter shutdown pydev_log_exception("Can't process net command: %s.", line) except: if not self._kill_received: if sys is not None and pydev_log_exception is not None: # Could happen at interpreter shutdown pydev_log_exception() self._terminate_on_socket_close() finally: pydev_log.debug('ReaderThread: exit') def _terminate_on_socket_close(self): if self.__terminate_on_socket_close: self.py_db.dispose_and_kill_all_pydevd_threads() def process_command(self, cmd_id, seq, text): self.process_net_command(self.py_db, cmd_id, seq, text) class FSNotifyThread(PyDBDaemonThread): def __init__(self, py_db, api, watch_dirs): PyDBDaemonThread.__init__(self, py_db) self.api = api self.name = "pydevd.FSNotifyThread" self.watcher = fsnotify.Watcher() self.watch_dirs = watch_dirs @overrides(PyDBDaemonThread._on_run) def _on_run(self): try: pydev_log.info('Watching directories for code reload:\n---\n%s\n---' % ('\n'.join(sorted(self.watch_dirs)))) # i.e.: The first call to set_tracked_paths will do a full scan, so, do it in the thread # too (after everything is configured). self.watcher.set_tracked_paths(self.watch_dirs) while not self._kill_received: for change_enum, change_path in self.watcher.iter_changes(): # We're only interested in modified events if change_enum == fsnotify.Change.modified: pydev_log.info('Modified: %s', change_path) self.api.request_reload_code(self.py_db, -1, None, change_path) else: pydev_log.info('Ignored (add or remove) change in: %s', change_path) except: pydev_log.exception('Error when waiting for filesystem changes in FSNotifyThread.') @overrides(PyDBDaemonThread.do_kill_pydev_thread) def do_kill_pydev_thread(self): self.watcher.dispose() PyDBDaemonThread.do_kill_pydev_thread(self) class WriterThread(PyDBDaemonThread): ''' writer thread writes out the commands in an infinite loop ''' def __init__(self, sock, py_db, terminate_on_socket_close=True): PyDBDaemonThread.__init__(self, py_db) self.sock = sock self.__terminate_on_socket_close = terminate_on_socket_close self.name = "pydevd.Writer" self._cmd_queue = _queue.Queue() if pydevd_vm_type.get_vm_type() == 'python': self.timeout = 0 else: self.timeout = 0.1 def add_command(self, cmd): ''' cmd is NetCommand ''' if not self._kill_received: # we don't take new data after everybody die self._cmd_queue.put(cmd, False) @overrides(PyDBDaemonThread._on_run) def _on_run(self): ''' just loop and write responses ''' try: while True: try: try: cmd = self._cmd_queue.get(True, 0.1) except _queue.Empty: if self._kill_received: pydev_log.debug('WriterThread: kill_received (sock.shutdown(SHUT_WR))') try: self.sock.shutdown(SHUT_WR) except: pass # Note: don't close the socket, just send the shutdown, # then, when no data is received on the reader, it can close # the socket. # See: https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable # try: # self.sock.close() # except: # pass return # break if queue is empty and _kill_received else: continue except: # pydev_log.info('Finishing debug communication...(1)') # when liberating the thread here, we could have errors because we were shutting down # but the thread was still not liberated return if cmd.as_dict is not None: for listener in self.py_db.dap_messages_listeners: listener.before_send(cmd.as_dict) notify_about_gevent_if_needed() cmd.send(self.sock) if cmd.id == CMD_EXIT: pydev_log.debug('WriterThread: CMD_EXIT received') break if time is None: break # interpreter shutdown time.sleep(self.timeout) except Exception: if self.__terminate_on_socket_close: self.py_db.dispose_and_kill_all_pydevd_threads() if DebugInfoHolder.DEBUG_TRACE_LEVEL > 0: pydev_log_exception() finally: pydev_log.debug('WriterThread: exit') def empty(self): return self._cmd_queue.empty() @overrides(PyDBDaemonThread.do_kill_pydev_thread) def do_kill_pydev_thread(self): if not self._kill_received: # Add command before setting the kill flag (otherwise the command may not be added). exit_cmd = self.py_db.cmd_factory.make_exit_command(self.py_db) self.add_command(exit_cmd) PyDBDaemonThread.do_kill_pydev_thread(self) def create_server_socket(host, port): try: server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) if IS_WINDOWS and not IS_JYTHON: server.setsockopt(SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1) else: server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) server.bind((host, port)) server.settimeout(None) except Exception: server.close() raise return server def start_server(port): ''' binds to a port, waits for the debugger to connect ''' s = create_server_socket(host='', port=port) try: s.listen(1) new_socket, _addr = s.accept() pydev_log.info("Connection accepted") # closing server socket is not necessary but we don't need it s.close() return new_socket except: pydev_log.exception("Could not bind to port: %s\n", port) raise def start_client(host, port): ''' connects to a host/port ''' pydev_log.info("Connecting to %s:%s", host, port) s = socket(AF_INET, SOCK_STREAM) # Set TCP keepalive on an open socket. # It activates after 1 second (TCP_KEEPIDLE,) of idleness, # then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL), # and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds try: s.setsockopt(SOL_SOCKET, socket_module.SO_KEEPALIVE, 1) except (AttributeError, OSError): pass # May not be available everywhere. try: s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPIDLE, 1) except (AttributeError, OSError): pass # May not be available everywhere. try: s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPINTVL, 3) except (AttributeError, OSError): pass # May not be available everywhere. try: s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPCNT, 5) except (AttributeError, OSError): pass # May not be available everywhere. try: # 10 seconds default timeout timeout = int(os.environ.get('PYDEVD_CONNECT_TIMEOUT', 10)) s.settimeout(timeout) s.connect((host, port)) s.settimeout(None) # no timeout after connected pydev_log.info("Connected.") return s except: pydev_log.exception("Could not connect to %s: %s", host, port) raise INTERNAL_TERMINATE_THREAD = 1 INTERNAL_SUSPEND_THREAD = 2 class InternalThreadCommand(object): ''' internal commands are generated/executed by the debugger. The reason for their existence is that some commands have to be executed on specific threads. These are the InternalThreadCommands that get get posted to PyDB. ''' def __init__(self, thread_id, method=None, *args, **kwargs): self.thread_id = thread_id self.method = method self.args = args self.kwargs = kwargs def can_be_executed_by(self, thread_id): '''By default, it must be in the same thread to be executed ''' return self.thread_id == thread_id or self.thread_id.endswith('|' + thread_id) def do_it(self, dbg): try: if self.method is not None: self.method(dbg, *self.args, **self.kwargs) else: raise NotImplementedError("you have to override do_it") finally: self.args = None self.kwargs = None def __str__(self): return 'InternalThreadCommands(%s, %s, %s)' % (self.method, self.args, self.kwargs) __repr__ = __str__ class InternalThreadCommandForAnyThread(InternalThreadCommand): def __init__(self, thread_id, method=None, *args, **kwargs): assert thread_id == '*' InternalThreadCommand.__init__(self, thread_id, method, *args, **kwargs) self.executed = False self.lock = ForkSafeLock() def can_be_executed_by(self, thread_id): return True # Can be executed by any thread. def do_it(self, dbg): with self.lock: if self.executed: return self.executed = True InternalThreadCommand.do_it(self, dbg) def _send_io_message(py_db, s): cmd = py_db.cmd_factory.make_io_message(s, 2) if py_db.writer is not None: py_db.writer.add_command(cmd) def internal_reload_code(dbg, seq, module_name, filename): try: found_module_to_reload = False if module_name is not None: module_name = module_name if module_name not in sys.modules: if '.' in module_name: new_module_name = module_name.split('.')[-1] if new_module_name in sys.modules: module_name = new_module_name modules_to_reload = {} module = sys.modules.get(module_name) if module is not None: modules_to_reload[id(module)] = (module, module_name) if filename: filename = pydevd_file_utils.normcase(filename) for module_name, module in sys.modules.copy().items(): f = getattr_checked(module, '__file__') if f is not None: if f.endswith(('.pyc', '.pyo')): f = f[:-1] if pydevd_file_utils.normcase(f) == filename: modules_to_reload[id(module)] = (module, module_name) if not modules_to_reload: if filename and module_name: _send_io_message(dbg, 'code reload: Unable to find module %s to reload for path: %s\n' % (module_name, filename)) elif filename: _send_io_message(dbg, 'code reload: Unable to find module to reload for path: %s\n' % (filename,)) elif module_name: _send_io_message(dbg, 'code reload: Unable to find module to reload: %s\n' % (module_name,)) else: # Too much info... # _send_io_message(dbg, 'code reload: This usually means you are trying to reload the __main__ module (which cannot be reloaded).\n') for module, module_name in modules_to_reload.values(): _send_io_message(dbg, 'code reload: Start reloading module: "' + module_name + '" ... \n') found_module_to_reload = True if pydevd_reload.xreload(module): _send_io_message(dbg, 'code reload: reload finished\n') else: _send_io_message(dbg, 'code reload: reload finished without applying any change\n') cmd = dbg.cmd_factory.make_reloaded_code_message(seq, found_module_to_reload) dbg.writer.add_command(cmd) except: pydev_log.exception('Error reloading code') class InternalGetThreadStack(InternalThreadCommand): ''' This command will either wait for a given thread to be paused to get its stack or will provide it anyways after a timeout (in which case the stack will be gotten but local variables won't be available and it'll not be possible to interact with the frame as it's not actually stopped in a breakpoint). ''' def __init__(self, seq, thread_id, py_db, set_additional_thread_info, fmt, timeout=.5, start_frame=0, levels=0): InternalThreadCommand.__init__(self, thread_id) self._py_db = weakref.ref(py_db) self._timeout = time.time() + timeout self.seq = seq self._cmd = None self._fmt = fmt self._start_frame = start_frame self._levels = levels # Note: receives set_additional_thread_info to avoid a circular import # in this module. self._set_additional_thread_info = set_additional_thread_info @overrides(InternalThreadCommand.can_be_executed_by) def can_be_executed_by(self, _thread_id): timed_out = time.time() >= self._timeout py_db = self._py_db() t = pydevd_find_thread_by_id(self.thread_id) frame = None if t and not getattr(t, 'pydev_do_not_trace', None): additional_info = self._set_additional_thread_info(t) frame = additional_info.get_topmost_frame(t) try: self._cmd = py_db.cmd_factory.make_get_thread_stack_message( py_db, self.seq, self.thread_id, frame, self._fmt, must_be_suspended=not timed_out, start_frame=self._start_frame, levels=self._levels) finally: frame = None t = None return self._cmd is not None or timed_out @overrides(InternalThreadCommand.do_it) def do_it(self, dbg): if self._cmd is not None: dbg.writer.add_command(self._cmd) self._cmd = None def internal_step_in_thread(py_db, thread_id, cmd_id, set_additional_thread_info): thread_to_step = pydevd_find_thread_by_id(thread_id) if thread_to_step: info = set_additional_thread_info(thread_to_step) info.pydev_original_step_cmd = cmd_id info.pydev_step_cmd = cmd_id info.pydev_step_stop = None info.pydev_state = STATE_RUN if py_db.stepping_resumes_all_threads: resume_threads('*', except_thread=thread_to_step) def internal_smart_step_into(py_db, thread_id, offset, child_offset, set_additional_thread_info): thread_to_step = pydevd_find_thread_by_id(thread_id) if thread_to_step: info = set_additional_thread_info(thread_to_step) info.pydev_original_step_cmd = CMD_SMART_STEP_INTO info.pydev_step_cmd = CMD_SMART_STEP_INTO info.pydev_step_stop = None info.pydev_smart_parent_offset = int(offset) info.pydev_smart_child_offset = int(child_offset) info.pydev_state = STATE_RUN if py_db.stepping_resumes_all_threads: resume_threads('*', except_thread=thread_to_step) class InternalSetNextStatementThread(InternalThreadCommand): def __init__(self, thread_id, cmd_id, line, func_name, seq=0): ''' cmd_id may actually be one of: CMD_RUN_TO_LINE CMD_SET_NEXT_STATEMENT CMD_SMART_STEP_INTO ''' self.thread_id = thread_id self.cmd_id = cmd_id self.line = line self.seq = seq self.func_name = func_name def do_it(self, dbg): t = pydevd_find_thread_by_id(self.thread_id) if t: info = t.additional_info info.pydev_original_step_cmd = self.cmd_id info.pydev_step_cmd = self.cmd_id info.pydev_step_stop = None info.pydev_next_line = int(self.line) info.pydev_func_name = self.func_name info.pydev_message = str(self.seq) info.pydev_smart_parent_offset = -1 info.pydev_smart_child_offset = -1 info.pydev_state = STATE_RUN @silence_warnings_decorator def internal_get_variable_json(py_db, request): ''' :param VariablesRequest request: ''' arguments = request.arguments # : :type arguments: VariablesArguments variables_reference = arguments.variablesReference scope = None if isinstance_checked(variables_reference, ScopeRequest): scope = variables_reference variables_reference = variables_reference.variable_reference fmt = arguments.format if hasattr(fmt, 'to_dict'): fmt = fmt.to_dict() variables = [] try: try: variable = py_db.suspended_frames_manager.get_variable(variables_reference) except KeyError: pass else: for child_var in variable.get_children_variables(fmt=fmt, scope=scope): variables.append(child_var.get_var_data(fmt=fmt)) except: try: exc, exc_type, tb = sys.exc_info() err = ''.join(traceback.format_exception(exc, exc_type, tb)) variables = [{ 'name': '<error>', 'value': err, 'type': '<error>', 'variablesReference': 0 }] except: err = '<Internal error - unable to get traceback when getting variables>' pydev_log.exception(err) variables = [] body = VariablesResponseBody(variables) variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) class InternalGetVariable(InternalThreadCommand): ''' gets the value of a variable ''' def __init__(self, seq, thread_id, frame_id, scope, attrs): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.scope = scope self.attributes = attrs @silence_warnings_decorator def do_it(self, dbg): ''' Converts request into python variable ''' try: xml = StringIO() xml.write("<xml>") type_name, val_dict = pydevd_vars.resolve_compound_variable_fields( dbg, self.thread_id, self.frame_id, self.scope, self.attributes) if val_dict is None: val_dict = {} # assume properly ordered if resolver returns 'OrderedDict' # check type as string to support OrderedDict backport for older Python keys = list(val_dict) if not (type_name == "OrderedDict" or val_dict.__class__.__name__ == "OrderedDict" or IS_PY36_OR_GREATER): keys = sorted(keys, key=compare_object_attrs_key) timer = Timer() for k in keys: val = val_dict[k] evaluate_full_value = pydevd_xml.should_evaluate_full_value(val) xml.write(pydevd_xml.var_to_xml(val, k, evaluate_full_value=evaluate_full_value)) timer.report_if_compute_repr_attr_slow(self.attributes, k, type(val)) xml.write("</xml>") cmd = dbg.cmd_factory.make_get_variable_message(self.sequence, xml.getvalue()) xml.close() dbg.writer.add_command(cmd) except Exception: cmd = dbg.cmd_factory.make_error_message( self.sequence, "Error resolving variables %s" % (get_exception_traceback_str(),)) dbg.writer.add_command(cmd) class InternalGetArray(InternalThreadCommand): def __init__(self, seq, roffset, coffset, rows, cols, format, thread_id, frame_id, scope, attrs): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.scope = scope self.name = attrs.split("\t")[-1] self.attrs = attrs self.roffset = int(roffset) self.coffset = int(coffset) self.rows = int(rows) self.cols = int(cols) self.format = format def do_it(self, dbg): try: frame = dbg.find_frame(self.thread_id, self.frame_id) var = pydevd_vars.eval_in_context(self.name, frame.f_globals, frame.f_locals, py_db=dbg) xml = pydevd_vars.table_like_struct_to_xml(var, self.name, self.roffset, self.coffset, self.rows, self.cols, self.format) cmd = dbg.cmd_factory.make_get_array_message(self.sequence, xml) dbg.writer.add_command(cmd) except: cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error resolving array: " + get_exception_traceback_str()) dbg.writer.add_command(cmd) def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value): ''' Changes the value of a variable ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame is not None: result = pydevd_vars.change_attr_expression(frame, attr, value, dbg) else: result = None xml = "<xml>" xml += pydevd_xml.var_to_xml(result, "") xml += "</xml>" cmd = dbg.cmd_factory.make_variable_changed_message(seq, xml) dbg.writer.add_command(cmd) except Exception: cmd = dbg.cmd_factory.make_error_message(seq, "Error changing variable attr:%s expression:%s traceback:%s" % (attr, value, get_exception_traceback_str())) dbg.writer.add_command(cmd) def internal_change_variable_json(py_db, request): ''' The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only deal with changing at a frame level, so, currently changing the contents of something in a different scope is currently not supported. :param SetVariableRequest request: ''' # : :type arguments: SetVariableArguments arguments = request.arguments variables_reference = arguments.variablesReference scope = None if isinstance_checked(variables_reference, ScopeRequest): scope = variables_reference variables_reference = variables_reference.variable_reference fmt = arguments.format if hasattr(fmt, 'to_dict'): fmt = fmt.to_dict() try: variable = py_db.suspended_frames_manager.get_variable(variables_reference) except KeyError: variable = None if variable is None: _write_variable_response( py_db, request, value='', success=False, message='Unable to find variable container to change: %s.' % (variables_reference,)) return child_var = variable.change_variable(arguments.name, arguments.value, py_db, fmt=fmt) if child_var is None: _write_variable_response( py_db, request, value='', success=False, message='Unable to change: %s.' % (arguments.name,)) return var_data = child_var.get_var_data(fmt=fmt) body = SetVariableResponseBody( value=var_data['value'], type=var_data['type'], variablesReference=var_data.get('variablesReference'), namedVariables=var_data.get('namedVariables'), indexedVariables=var_data.get('indexedVariables'), ) variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) def _write_variable_response(py_db, request, value, success, message): body = SetVariableResponseBody('') variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body':body, 'success': False, 'message': message }) cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True) py_db.writer.add_command(cmd) @silence_warnings_decorator def internal_get_frame(dbg, seq, thread_id, frame_id): ''' Converts request into python variable ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame is not None: hidden_ns = pydevconsole.get_ipython_hidden_vars() xml = "<xml>" xml += pydevd_xml.frame_vars_to_xml(frame.f_locals, hidden_ns) del frame xml += "</xml>" cmd = dbg.cmd_factory.make_get_frame_message(seq, xml) dbg.writer.add_command(cmd) else: # pydevd_vars.dump_frames(thread_id) # don't print this error: frame not found: means that the client is not synchronized (but that's ok) cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) except: cmd = dbg.cmd_factory.make_error_message(seq, "Error resolving frame: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) def internal_get_smart_step_into_variants(dbg, seq, thread_id, frame_id, start_line, end_line, set_additional_thread_info): try: thread = pydevd_find_thread_by_id(thread_id) frame = dbg.find_frame(thread_id, frame_id) if thread is None or frame is None: cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) return if pydevd_bytecode_utils is None: variants = [] else: variants = pydevd_bytecode_utils.calculate_smart_step_into_variants(frame, int(start_line), int(end_line)) info = set_additional_thread_info(thread) # Store the last request (may be used afterwards when stepping). info.pydev_smart_step_into_variants = tuple(variants) xml = "<xml>" for variant in variants: if variant.children_variants: for child_variant in variant.children_variants: # If there are child variants, the current one is just an intermediary, so, # just create variants for the child (notifying properly about the parent too). xml += '<variant name="%s" isVisited="%s" line="%s" offset="%s" childOffset="%s" callOrder="%s"/>' % ( quote(child_variant.name), str(child_variant.is_visited).lower(), child_variant.line, variant.offset, child_variant.offset, child_variant.call_order, ) else: xml += '<variant name="%s" isVisited="%s" line="%s" offset="%s" childOffset="-1" callOrder="%s"/>' % ( quote(variant.name), str(variant.is_visited).lower(), variant.line, variant.offset, variant.call_order, ) xml += "</xml>" cmd = NetCommand(CMD_GET_SMART_STEP_INTO_VARIANTS, seq, xml) dbg.writer.add_command(cmd) except: # Error is expected (if `dis` module cannot be used -- i.e.: Jython). pydev_log.exception('Error calculating Smart Step Into Variants.') cmd = dbg.cmd_factory.make_error_message( seq, "Error getting smart step into variants for frame: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) def internal_get_step_in_targets_json(dbg, seq, thread_id, frame_id, request, set_additional_thread_info): try: thread = pydevd_find_thread_by_id(thread_id) frame = dbg.find_frame(thread_id, frame_id) if thread is None or frame is None: body = StepInTargetsResponseBody([]) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Thread to get step in targets seems to have resumed already.' }) cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True) dbg.writer.add_command(cmd) return start_line = 0 end_line = 99999999 if pydevd_bytecode_utils is None: variants = [] else: variants = pydevd_bytecode_utils.calculate_smart_step_into_variants(frame, start_line, end_line) info = set_additional_thread_info(thread) targets = [] counter = itertools.count(0) target_id_to_variant = {} for variant in variants: if not variant.is_visited: if variant.children_variants: for child_variant in variant.children_variants: target_id = next(counter) if child_variant.call_order > 1: targets.append(StepInTarget(id=target_id, label='%s (call %s)' % (child_variant.name, child_variant.call_order),)) else: targets.append(StepInTarget(id=target_id, label=child_variant.name)) target_id_to_variant[target_id] = child_variant if len(targets) >= 15: # Show at most 15 targets. break else: target_id = next(counter) if variant.call_order > 1: targets.append(StepInTarget(id=target_id, label='%s (call %s)' % (variant.name, variant.call_order),)) else: targets.append(StepInTarget(id=target_id, label=variant.name)) target_id_to_variant[target_id] = variant if len(targets) >= 15: # Show at most 15 targets. break # Store the last request (may be used afterwards when stepping). info.pydev_smart_step_into_variants = tuple(variants) info.target_id_to_smart_step_into_variant = target_id_to_variant body = StepInTargetsResponseBody(targets=targets) response = pydevd_base_schema.build_response(request, kwargs={'body': body}) cmd = NetCommand(CMD_RETURN, 0, response, is_json=True) dbg.writer.add_command(cmd) except Exception as e: # Error is expected (if `dis` module cannot be used -- i.e.: Jython). pydev_log.exception('Error calculating Smart Step Into Variants.') body = StepInTargetsResponseBody([]) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': str(e) }) cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True) dbg.writer.add_command(cmd) def internal_get_next_statement_targets(dbg, seq, thread_id, frame_id): ''' gets the valid line numbers for use with set next statement ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame is not None: code = frame.f_code xml = "<xml>" try: linestarts = dis.findlinestarts(code) except: # i.e.: jython doesn't provide co_lnotab, so, we can only keep at the current line. xml += "<line>%d</line>" % (frame.f_lineno,) else: for _, line in linestarts: xml += "<line>%d</line>" % (line,) del frame xml += "</xml>" cmd = dbg.cmd_factory.make_get_next_statement_targets_message(seq, xml) dbg.writer.add_command(cmd) else: cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) except: cmd = dbg.cmd_factory.make_error_message(seq, "Error resolving frame: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) def _evaluate_response(py_db, request, result, error_message=''): is_error = isinstance(result, ExceptionOnEvaluate) if is_error: result = result.result if not error_message: body = pydevd_schema.EvaluateResponseBody(result=result, variablesReference=0) variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) else: body = pydevd_schema.EvaluateResponseBody(result=result, variablesReference=0) variables_response = pydevd_base_schema.build_response(request, kwargs={ 'body':body, 'success':False, 'message': error_message}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) _global_frame = None def internal_evaluate_expression_json(py_db, request, thread_id): ''' :param EvaluateRequest request: ''' global _global_frame # : :type arguments: EvaluateArguments arguments = request.arguments expression = arguments.expression frame_id = arguments.frameId context = arguments.context fmt = arguments.format if hasattr(fmt, 'to_dict'): fmt = fmt.to_dict() ctx = NULL if context == 'repl': if not py_db.is_output_redirected: ctx = pydevd_io.redirect_stream_to_pydb_io_messages_context() else: # If we're not in a repl (watch, hover, ...) don't show warnings. ctx = filter_all_warnings() with ctx: try_exec = False if frame_id is None: if _global_frame is None: # Lazily create a frame to be used for evaluation with no frame id. def __create_frame(): yield sys._getframe() _global_frame = next(__create_frame()) frame = _global_frame try_exec = True # Always exec in this case eval_result = None else: frame = py_db.find_frame(thread_id, frame_id) eval_result = pydevd_vars.evaluate_expression(py_db, frame, expression, is_exec=False) is_error = isinstance_checked(eval_result, ExceptionOnEvaluate) if is_error: if context == 'hover': # In a hover it doesn't make sense to do an exec. _evaluate_response(py_db, request, result='', error_message='Exception occurred during evaluation.') return elif context == 'watch': # If it's a watch, don't show it as an exception object, rather, format # it and show it as a string (with success=False). msg = '%s: %s' % ( eval_result.result.__class__.__name__, eval_result.result,) _evaluate_response(py_db, request, result=msg, error_message=msg) return else: # We only try the exec if the failure we had was due to not being able # to evaluate the expression. try: pydevd_vars.compile_as_eval(expression) except Exception: try_exec = context == 'repl' else: try_exec = False if context == 'repl': # In the repl we should show the exception to the user. _evaluate_response_return_exception(py_db, request, eval_result.etype, eval_result.result, eval_result.tb) return if try_exec: try: pydevd_vars.evaluate_expression(py_db, frame, expression, is_exec=True) except (Exception, KeyboardInterrupt): _evaluate_response_return_exception(py_db, request, *sys.exc_info()) return # No result on exec. _evaluate_response(py_db, request, result='') return # Ok, we have the result (could be an error), let's put it into the saved variables. frame_tracker = py_db.suspended_frames_manager.get_frame_tracker(thread_id) if frame_tracker is None: # This is not really expected. _evaluate_response(py_db, request, result='', error_message='Thread id: %s is not current thread id.' % (thread_id,)) return safe_repr_custom_attrs = {} if context == 'clipboard': safe_repr_custom_attrs = dict( maxstring_outer=2 ** 64, maxstring_inner=2 ** 64, maxother_outer=2 ** 64, maxother_inner=2 ** 64, ) if context == 'repl' and eval_result is None: # We don't want "None" to appear when typing in the repl. body = pydevd_schema.EvaluateResponseBody( result=None, variablesReference=0, ) else: variable = frame_tracker.obtain_as_variable(expression, eval_result, frame=frame) var_data = variable.get_var_data(fmt=fmt, **safe_repr_custom_attrs) body = pydevd_schema.EvaluateResponseBody( result=var_data['value'], variablesReference=var_data.get('variablesReference', 0), type=var_data.get('type'), presentationHint=var_data.get('presentationHint'), namedVariables=var_data.get('namedVariables'), indexedVariables=var_data.get('indexedVariables'), ) variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) def _evaluate_response_return_exception(py_db, request, exc_type, exc, initial_tb): try: tb = initial_tb # Show the traceback without pydevd frames. temp_tb = tb while temp_tb: if py_db.get_file_type(temp_tb.tb_frame) == PYDEV_FILE: tb = temp_tb.tb_next temp_tb = temp_tb.tb_next if tb is None: tb = initial_tb err = ''.join(traceback.format_exception(exc_type, exc, tb)) # Make sure we don't keep references to them. exc = None exc_type = None tb = None temp_tb = None initial_tb = None except: err = '<Internal error - unable to get traceback when evaluating expression>' pydev_log.exception(err) # Currently there is an issue in VSC where returning success=false for an # eval request, in repl context, VSC does not show the error response in # the debug console. So return the error message in result as well. _evaluate_response(py_db, request, result=err, error_message=err) @silence_warnings_decorator def internal_evaluate_expression(dbg, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result): ''' gets the value of a variable ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame is not None: result = pydevd_vars.evaluate_expression(dbg, frame, expression, is_exec) if attr_to_set_result != "": pydevd_vars.change_attr_expression(frame, attr_to_set_result, expression, dbg, result) else: result = None xml = "<xml>" xml += pydevd_xml.var_to_xml(result, expression, trim_if_too_big) xml += "</xml>" cmd = dbg.cmd_factory.make_evaluate_expression_message(seq, xml) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() cmd = dbg.cmd_factory.make_error_message(seq, "Error evaluating expression " + exc) dbg.writer.add_command(cmd) def _set_expression_response(py_db, request, result, error_message): body = pydevd_schema.SetExpressionResponseBody(result='', variablesReference=0) variables_response = pydevd_base_schema.build_response(request, kwargs={ 'body':body, 'success':False, 'message': error_message}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) def internal_set_expression_json(py_db, request, thread_id): # : :type arguments: SetExpressionArguments arguments = request.arguments expression = arguments.expression frame_id = arguments.frameId value = arguments.value fmt = arguments.format if hasattr(fmt, 'to_dict'): fmt = fmt.to_dict() frame = py_db.find_frame(thread_id, frame_id) exec_code = '%s = (%s)' % (expression, value) result = pydevd_vars.evaluate_expression(py_db, frame, exec_code, is_exec=True) is_error = isinstance(result, ExceptionOnEvaluate) if is_error: _set_expression_response(py_db, request, result, error_message='Error executing: %s' % (exec_code,)) return # Ok, we have the result (could be an error), let's put it into the saved variables. frame_tracker = py_db.suspended_frames_manager.get_frame_tracker(thread_id) if frame_tracker is None: # This is not really expected. _set_expression_response(py_db, request, result, error_message='Thread id: %s is not current thread id.' % (thread_id,)) return # Now that the exec is done, get the actual value changed to return. result = pydevd_vars.evaluate_expression(py_db, frame, expression, is_exec=False) variable = frame_tracker.obtain_as_variable(expression, result, frame=frame) var_data = variable.get_var_data(fmt=fmt) body = pydevd_schema.SetExpressionResponseBody( value=var_data['value'], variablesReference=var_data.get('variablesReference', 0), type=var_data.get('type'), presentationHint=var_data.get('presentationHint'), namedVariables=var_data.get('namedVariables'), indexedVariables=var_data.get('indexedVariables'), ) variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) def internal_get_completions(dbg, seq, thread_id, frame_id, act_tok, line=-1, column=-1): ''' Note that if the column is >= 0, the act_tok is considered text and the actual activation token/qualifier is computed in this command. ''' try: remove_path = None try: qualifier = u'' if column >= 0: token_and_qualifier = extract_token_and_qualifier(act_tok, line, column) act_tok = token_and_qualifier[0] if act_tok: act_tok += u'.' qualifier = token_and_qualifier[1] frame = dbg.find_frame(thread_id, frame_id) if frame is not None: completions = _pydev_completer.generate_completions(frame, act_tok) # Note that qualifier and start are only actually valid for the # Debug Adapter Protocol (for the line-based protocol, the IDE # is required to filter the completions returned). cmd = dbg.cmd_factory.make_get_completions_message( seq, completions, qualifier, start=column - len(qualifier)) dbg.writer.add_command(cmd) else: cmd = dbg.cmd_factory.make_error_message(seq, "internal_get_completions: Frame not found: %s from thread: %s" % (frame_id, thread_id)) dbg.writer.add_command(cmd) finally: if remove_path is not None: sys.path.remove(remove_path) except: exc = get_exception_traceback_str() sys.stderr.write('%s\n' % (exc,)) cmd = dbg.cmd_factory.make_error_message(seq, "Error evaluating expression " + exc) dbg.writer.add_command(cmd) def internal_get_description(dbg, seq, thread_id, frame_id, expression): ''' Fetch the variable description stub from the debug console ''' try: frame = dbg.find_frame(thread_id, frame_id) description = pydevd_console.get_description(frame, thread_id, frame_id, expression) description = pydevd_xml.make_valid_xml_value(quote(description, '/>_= \t')) description_xml = '<xml><var name="" type="" value="%s"/></xml>' % description cmd = dbg.cmd_factory.make_get_description_message(seq, description_xml) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() cmd = dbg.cmd_factory.make_error_message(seq, "Error in fetching description" + exc) dbg.writer.add_command(cmd) def build_exception_info_response(dbg, thread_id, request_seq, set_additional_thread_info, iter_visible_frames_info, max_frames): ''' :return ExceptionInfoResponse ''' thread = pydevd_find_thread_by_id(thread_id) additional_info = set_additional_thread_info(thread) topmost_frame = additional_info.get_topmost_frame(thread) current_paused_frame_name = '' source_path = '' # This is an extra bit of data used by Visual Studio stack_str_lst = [] name = None description = None if topmost_frame is not None: try: try: frames_list = dbg.suspended_frames_manager.get_frames_list(thread_id) memo = set() while frames_list is not None and len(frames_list): frames = [] frame = None if not name: exc_type = frames_list.exc_type if exc_type is not None: try: name = exc_type.__qualname__ except: try: name = exc_type.__name__ except: try: name = str(exc_type) except: pass if not description: exc_desc = frames_list.exc_desc if exc_desc is not None: try: description = str(exc_desc) except: pass for frame_id, frame, method_name, original_filename, filename_in_utf8, lineno, _applied_mapping, show_as_current_frame in \ iter_visible_frames_info(dbg, frames_list): line_text = linecache.getline(original_filename, lineno) # Never filter out plugin frames! if not getattr(frame, 'IS_PLUGIN_FRAME', False): if dbg.is_files_filter_enabled and dbg.apply_files_filter(frame, original_filename, False): continue if show_as_current_frame: current_paused_frame_name = method_name method_name += ' (Current frame)' frames.append((filename_in_utf8, lineno, method_name, line_text)) if not source_path and frames: source_path = frames[0][0] stack_str = ''.join(traceback.format_list(frames[-max_frames:])) stack_str += frames_list.exc_context_msg stack_str_lst.append(stack_str) frames_list = create_frames_list_from_exception_cause( frames_list.trace_obj, None, frames_list.exc_type, frames_list.exc_desc, memo) if frames_list is None or not frames_list: break except: pydev_log.exception('Error on build_exception_info_response.') finally: topmost_frame = None full_stack_str = ''.join(reversed(stack_str_lst)) if not name: name = 'exception: type unknown' if not description: description = 'exception: no description' if current_paused_frame_name: name += ' (note: full exception trace is shown but execution is paused at: %s)' % (current_paused_frame_name,) if thread.stop_reason == CMD_STEP_CAUGHT_EXCEPTION: break_mode = pydevd_schema.ExceptionBreakMode.ALWAYS else: break_mode = pydevd_schema.ExceptionBreakMode.UNHANDLED response = pydevd_schema.ExceptionInfoResponse( request_seq=request_seq, success=True, command='exceptionInfo', body=pydevd_schema.ExceptionInfoResponseBody( exceptionId=name, description=description, breakMode=break_mode, details=pydevd_schema.ExceptionDetails( message=description, typeName=name, stackTrace=full_stack_str, source=source_path, # Note: ExceptionDetails actually accepts an 'innerException', but # when passing it, VSCode is not showing the stack trace at all. ) ) ) return response def internal_get_exception_details_json(dbg, request, thread_id, max_frames, set_additional_thread_info=None, iter_visible_frames_info=None): ''' Fetch exception details ''' try: response = build_exception_info_response(dbg, thread_id, request.seq, set_additional_thread_info, iter_visible_frames_info, max_frames) except: exc = get_exception_traceback_str() response = pydevd_base_schema.build_response(request, kwargs={ 'success': False, 'message': exc, 'body':{} }) dbg.writer.add_command(NetCommand(CMD_RETURN, 0, response, is_json=True)) class InternalGetBreakpointException(InternalThreadCommand): ''' Send details of exception raised while evaluating conditional breakpoint ''' def __init__(self, thread_id, exc_type, stacktrace): self.sequence = 0 self.thread_id = thread_id self.stacktrace = stacktrace self.exc_type = exc_type def do_it(self, dbg): try: callstack = "<xml>" makeValid = pydevd_xml.make_valid_xml_value for filename, line, methodname, methodobj in self.stacktrace: if not filesystem_encoding_is_utf8 and hasattr(filename, "decode"): # filename is a byte string encoded using the file system encoding # convert it to utf8 filename = filename.decode(file_system_encoding).encode("utf-8") callstack += '<frame thread_id = "%s" file="%s" line="%s" name="%s" obj="%s" />' \ % (self.thread_id, makeValid(filename), line, makeValid(methodname), makeValid(methodobj)) callstack += "</xml>" cmd = dbg.cmd_factory.make_send_breakpoint_exception_message(self.sequence, self.exc_type + "\t" + callstack) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() sys.stderr.write('%s\n' % (exc,)) cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error Sending Exception: " + exc) dbg.writer.add_command(cmd) class InternalSendCurrExceptionTrace(InternalThreadCommand): ''' Send details of the exception that was caught and where we've broken in. ''' def __init__(self, thread_id, arg, curr_frame_id): ''' :param arg: exception type, description, traceback object ''' self.sequence = 0 self.thread_id = thread_id self.curr_frame_id = curr_frame_id self.arg = arg def do_it(self, dbg): try: cmd = dbg.cmd_factory.make_send_curr_exception_trace_message(dbg, self.sequence, self.thread_id, self.curr_frame_id, *self.arg) del self.arg dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() sys.stderr.write('%s\n' % (exc,)) cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error Sending Current Exception Trace: " + exc) dbg.writer.add_command(cmd) class InternalSendCurrExceptionTraceProceeded(InternalThreadCommand): ''' Send details of the exception that was caught and where we've broken in. ''' def __init__(self, thread_id): self.sequence = 0 self.thread_id = thread_id def do_it(self, dbg): try: cmd = dbg.cmd_factory.make_send_curr_exception_trace_proceeded_message(self.sequence, self.thread_id) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() sys.stderr.write('%s\n' % (exc,)) cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error Sending Current Exception Trace Proceeded: " + exc) dbg.writer.add_command(cmd) class InternalEvaluateConsoleExpression(InternalThreadCommand): ''' Execute the given command in the debug console ''' def __init__(self, seq, thread_id, frame_id, line, buffer_output=True): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.line = line self.buffer_output = buffer_output def do_it(self, dbg): ''' Create an XML for console output, error and more (true/false) <xml> <output message=output_message></output> <error message=error_message></error> <more>true/false</more> </xml> ''' try: frame = dbg.find_frame(self.thread_id, self.frame_id) if frame is not None: console_message = pydevd_console.execute_console_command( frame, self.thread_id, self.frame_id, self.line, self.buffer_output) cmd = dbg.cmd_factory.make_send_console_message(self.sequence, console_message.to_xml()) else: from _pydevd_bundle.pydevd_console import ConsoleMessage console_message = ConsoleMessage() console_message.add_console_message( pydevd_console.CONSOLE_ERROR, "Select the valid frame in the debug view (thread: %s, frame: %s invalid)" % (self.thread_id, self.frame_id), ) cmd = dbg.cmd_factory.make_error_message(self.sequence, console_message.to_xml()) except: exc = get_exception_traceback_str() cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error evaluating expression " + exc) dbg.writer.add_command(cmd) class InternalRunCustomOperation(InternalThreadCommand): ''' Run a custom command on an expression ''' def __init__(self, seq, thread_id, frame_id, scope, attrs, style, encoded_code_or_file, fnname): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.scope = scope self.attrs = attrs self.style = style self.code_or_file = unquote_plus(encoded_code_or_file) self.fnname = fnname def do_it(self, dbg): try: res = pydevd_vars.custom_operation(dbg, self.thread_id, self.frame_id, self.scope, self.attrs, self.style, self.code_or_file, self.fnname) resEncoded = quote_plus(res) cmd = dbg.cmd_factory.make_custom_operation_message(self.sequence, resEncoded) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error in running custom operation" + exc) dbg.writer.add_command(cmd) class InternalConsoleGetCompletions(InternalThreadCommand): ''' Fetch the completions in the debug console ''' def __init__(self, seq, thread_id, frame_id, act_tok): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.act_tok = act_tok def do_it(self, dbg): ''' Get completions and write back to the client ''' try: frame = dbg.find_frame(self.thread_id, self.frame_id) completions_xml = pydevd_console.get_completions(frame, self.act_tok) cmd = dbg.cmd_factory.make_send_console_message(self.sequence, completions_xml) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error in fetching completions" + exc) dbg.writer.add_command(cmd) class InternalConsoleExec(InternalThreadCommand): ''' gets the value of a variable ''' def __init__(self, seq, thread_id, frame_id, expression): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.expression = expression def do_it(self, dbg): ''' Converts request into python variable ''' try: try: # don't trace new threads created by console command disable_trace_thread_modules() result = pydevconsole.console_exec(self.thread_id, self.frame_id, self.expression, dbg) xml = "<xml>" xml += pydevd_xml.var_to_xml(result, "") xml += "</xml>" cmd = dbg.cmd_factory.make_evaluate_expression_message(self.sequence, xml) dbg.writer.add_command(cmd) except: exc = get_exception_traceback_str() sys.stderr.write('%s\n' % (exc,)) cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error evaluating console expression " + exc) dbg.writer.add_command(cmd) finally: enable_trace_thread_modules() sys.stderr.flush() sys.stdout.flush() class InternalLoadFullValue(InternalThreadCommand): ''' Loads values asynchronously ''' def __init__(self, seq, thread_id, frame_id, vars): self.sequence = seq self.thread_id = thread_id self.frame_id = frame_id self.vars = vars @silence_warnings_decorator def do_it(self, dbg): '''Starts a thread that will load values asynchronously''' try: var_objects = [] for variable in self.vars: variable = variable.strip() if len(variable) > 0: if '\t' in variable: # there are attributes beyond scope scope, attrs = variable.split('\t', 1) name = attrs[0] else: scope, attrs = (variable, None) name = scope var_obj = pydevd_vars.getVariable(dbg, self.thread_id, self.frame_id, scope, attrs) var_objects.append((var_obj, name)) t = GetValueAsyncThreadDebug(dbg, dbg, self.sequence, var_objects) t.start() except: exc = get_exception_traceback_str() sys.stderr.write('%s\n' % (exc,)) cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error evaluating variable %s " % exc) dbg.writer.add_command(cmd) class AbstractGetValueAsyncThread(PyDBDaemonThread): ''' Abstract class for a thread, which evaluates values for async variables ''' def __init__(self, py_db, frame_accessor, seq, var_objects): PyDBDaemonThread.__init__(self, py_db) self.frame_accessor = frame_accessor self.seq = seq self.var_objs = var_objects self.cancel_event = threading.Event() def send_result(self, xml): raise NotImplementedError() @overrides(PyDBDaemonThread._on_run) def _on_run(self): start = time.time() xml = StringIO() xml.write("<xml>") for (var_obj, name) in self.var_objs: current_time = time.time() if current_time - start > ASYNC_EVAL_TIMEOUT_SEC or self.cancel_event.is_set(): break xml.write(pydevd_xml.var_to_xml(var_obj, name, evaluate_full_value=True)) xml.write("</xml>") self.send_result(xml) xml.close() class GetValueAsyncThreadDebug(AbstractGetValueAsyncThread): ''' A thread for evaluation async values, which returns result for debugger Create message and send it via writer thread ''' def send_result(self, xml): if self.frame_accessor is not None: cmd = self.frame_accessor.cmd_factory.make_load_full_value_message(self.seq, xml.getvalue()) self.frame_accessor.writer.add_command(cmd) class GetValueAsyncThreadConsole(AbstractGetValueAsyncThread): ''' A thread for evaluation async values, which returns result for Console Send result directly to Console's server ''' def send_result(self, xml): if self.frame_accessor is not None: self.frame_accessor.ReturnFullValue(self.seq, xml.getvalue())
74,656
Python
39.952825
162
0.580208
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_source_mapping.py
import bisect from _pydevd_bundle.pydevd_constants import NULL, KeyifyList import pydevd_file_utils class SourceMappingEntry(object): __slots__ = ['source_filename', 'line', 'end_line', 'runtime_line', 'runtime_source'] def __init__(self, line, end_line, runtime_line, runtime_source): assert isinstance(runtime_source, str) self.line = int(line) self.end_line = int(end_line) self.runtime_line = int(runtime_line) self.runtime_source = runtime_source # Something as <ipython-cell-xxx> # Should be set after translated to server (absolute_source_filename). # This is what's sent to the client afterwards (so, its case should not be normalized). self.source_filename = None def contains_line(self, i): return self.line <= i <= self.end_line def contains_runtime_line(self, i): line_count = self.end_line + self.line runtime_end_line = self.runtime_line + line_count return self.runtime_line <= i <= runtime_end_line def __str__(self): return 'SourceMappingEntry(%s)' % ( ', '.join('%s=%r' % (attr, getattr(self, attr)) for attr in self.__slots__)) __repr__ = __str__ class SourceMapping(object): def __init__(self, on_source_mapping_changed=NULL): self._mappings_to_server = {} # dict(normalized(file.py) to [SourceMappingEntry]) self._mappings_to_client = {} # dict(<cell> to File.py) self._cache = {} self._on_source_mapping_changed = on_source_mapping_changed def set_source_mapping(self, absolute_filename, mapping): ''' :param str absolute_filename: The filename for the source mapping (bytes on py2 and str on py3). :param list(SourceMappingEntry) mapping: A list with the source mapping entries to be applied to the given filename. :return str: An error message if it was not possible to set the mapping or an empty string if everything is ok. ''' # Let's first validate if it's ok to apply that mapping. # File mappings must be 1:N, not M:N (i.e.: if there's a mapping from file1.py to <cell1>, # there can be no other mapping from any other file to <cell1>). # This is a limitation to make it easier to remove existing breakpoints when new breakpoints are # set to a file (so, any file matching that breakpoint can be removed instead of needing to check # which lines are corresponding to that file). for map_entry in mapping: existing_source_filename = self._mappings_to_client.get(map_entry.runtime_source) if existing_source_filename and existing_source_filename != absolute_filename: return 'Cannot apply mapping from %s to %s (it conflicts with mapping: %s to %s)' % ( absolute_filename, map_entry.runtime_source, existing_source_filename, map_entry.runtime_source) try: absolute_normalized_filename = pydevd_file_utils.normcase(absolute_filename) current_mapping = self._mappings_to_server.get(absolute_normalized_filename, []) for map_entry in current_mapping: del self._mappings_to_client[map_entry.runtime_source] self._mappings_to_server[absolute_normalized_filename] = sorted(mapping, key=lambda entry:entry.line) for map_entry in mapping: self._mappings_to_client[map_entry.runtime_source] = absolute_filename finally: self._cache.clear() self._on_source_mapping_changed() return '' def map_to_client(self, runtime_source_filename, lineno): key = (lineno, 'client', runtime_source_filename) try: return self._cache[key] except KeyError: for _, mapping in list(self._mappings_to_server.items()): for map_entry in mapping: if map_entry.runtime_source == runtime_source_filename: # <cell1> if map_entry.contains_runtime_line(lineno): # matches line range self._cache[key] = (map_entry.source_filename, map_entry.line + (lineno - map_entry.runtime_line), True) return self._cache[key] self._cache[key] = (runtime_source_filename, lineno, False) # Mark that no translation happened in the cache. return self._cache[key] def has_mapping_entry(self, runtime_source_filename): ''' :param runtime_source_filename: Something as <ipython-cell-xxx> ''' # Note that we're not interested in the line here, just on knowing if a given filename # (from the server) has a mapping for it. key = ('has_entry', runtime_source_filename) try: return self._cache[key] except KeyError: for _absolute_normalized_filename, mapping in list(self._mappings_to_server.items()): for map_entry in mapping: if map_entry.runtime_source == runtime_source_filename: self._cache[key] = True return self._cache[key] self._cache[key] = False return self._cache[key] def map_to_server(self, absolute_filename, lineno): ''' Convert something as 'file1.py' at line 10 to '<ipython-cell-xxx>' at line 2. Note that the name should be already normalized at this point. ''' absolute_normalized_filename = pydevd_file_utils.normcase(absolute_filename) changed = False mappings = self._mappings_to_server.get(absolute_normalized_filename) if mappings: i = bisect.bisect(KeyifyList(mappings, lambda entry:entry.line), lineno) if i >= len(mappings): i -= 1 if i == 0: entry = mappings[i] else: entry = mappings[i - 1] if not entry.contains_line(lineno): entry = mappings[i] if not entry.contains_line(lineno): entry = None if entry is not None: lineno = entry.runtime_line + (lineno - entry.line) absolute_filename = entry.runtime_source changed = True return absolute_filename, lineno, changed
6,428
Python
40.746753
132
0.602209
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevconsole_code.py
""" A copy of the code module in the standard library with some changes to work with async evaluation. Utilities needed to emulate Python's interactive interpreter. """ # Inspired by similar code by Jeff Epler and Fredrik Lundh. import sys import traceback import inspect # START --------------------------- from codeop import CommandCompiler, compile_command # START --------------------------- from codeop import CommandCompiler, compile_command # START --------------------------- from codeop import CommandCompiler, compile_command # START --------------------------- from codeop import CommandCompiler, compile_command # START --------------------------- from codeop import CommandCompiler, compile_command r"""Utilities to compile possibly incomplete Python source code. This module provides two interfaces, broadly similar to the builtin function compile(), which take program text, a filename and a 'mode' and: - Return code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals). Approach: First, check if the source consists entirely of blank lines and comments; if so, replace it with 'pass', because the built-in parser doesn't always do the right thing for these. Compile three times: as is, with \n, and with \n\n appended. If it compiles as is, it's complete. If it compiles with one \n appended, we expect more. If it doesn't compile either way, we compare the error we get when compiling with \n or \n\n appended. If the errors are the same, the code is broken. But if the errors are different, we expect more. Not intuitive; not even guaranteed to hold in future releases; but this matches the compiler's behavior from Python 1.4 through 2.2, at least. Caveat: It is possible (but not likely) that the parser stops parsing with a successful outcome before reaching the end of the source; in this case, trailing symbols may be ignored instead of causing an error. For example, a backslash followed by two newlines may be followed by arbitrary garbage. This will be fixed once the API for the parser is better. The two interfaces are: compile_command(source, filename, symbol): Compiles a single command in the manner described above. CommandCompiler(): Instances of this class have __call__ methods identical in signature to compile_command; the difference is that if the instance compiles program text containing a __future__ statement, the instance 'remembers' and compiles all subsequent program texts with the statement in force. The module also provides another class: Compile(): Instances of this class act like the built-in function compile, but with 'memory' in the sense described above. """ import __future__ _features = [getattr(__future__, fname) for fname in __future__.all_feature_names] __all__ = ["compile_command", "Compile", "CommandCompiler"] PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h def _maybe_compile(compiler, source, filename, symbol): # Check for source consisting of only blank lines and comments for line in source.split("\n"): line = line.strip() if line and line[0] != '#': break # Leave it alone else: if symbol != "eval": source = "pass" # Replace it with a 'pass' statement err = err1 = err2 = None code = code1 = code2 = None try: code = compiler(source, filename, symbol) except SyntaxError as err: pass try: code1 = compiler(source + "\n", filename, symbol) except SyntaxError as e: err1 = e try: code2 = compiler(source + "\n\n", filename, symbol) except SyntaxError as e: err2 = e try: if code: return code if not code1 and repr(err1) == repr(err2): raise err1 finally: err1 = err2 = None def _compile(source, filename, symbol): return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) def compile_command(source, filename="<input>", symbol="single"): r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exceptions raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals). """ return _maybe_compile(_compile, source, filename, symbol) class Compile: """Instances of this class behave much like the built-in compile function, but if one is used to compile text containing a future statement, it "remembers" and compiles all subsequent program texts with the statement in force.""" def __init__(self): self.flags = PyCF_DONT_IMPLY_DEDENT try: from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT self.flags |= PyCF_ALLOW_TOP_LEVEL_AWAIT except: pass def __call__(self, source, filename, symbol): codeob = compile(source, filename, symbol, self.flags, 1) for feature in _features: if codeob.co_flags & feature.compiler_flag: self.flags |= feature.compiler_flag return codeob class CommandCompiler: """Instances of this class have __call__ methods identical in signature to compile_command; the difference is that if the instance compiles program text containing a __future__ statement, the instance 'remembers' and compiles all subsequent program texts with the statement in force.""" def __init__(self,): self.compiler = Compile() def __call__(self, source, filename="<input>", symbol="single"): r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default) or "eval" Return value / exceptions raised: - Return a code object if the command is complete and valid - Return None if the command is incomplete - Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals). """ return _maybe_compile(self.compiler, source, filename, symbol) # END --------------------------- from codeop import CommandCompiler, compile_command # END --------------------------- from codeop import CommandCompiler, compile_command # END --------------------------- from codeop import CommandCompiler, compile_command # END --------------------------- from codeop import CommandCompiler, compile_command # END --------------------------- from codeop import CommandCompiler, compile_command __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] from _pydev_bundle._pydev_saved_modules import threading class _EvalAwaitInNewEventLoop(threading.Thread): def __init__(self, compiled, updated_globals, updated_locals): threading.Thread.__init__(self) self.daemon = True self._compiled = compiled self._updated_globals = updated_globals self._updated_locals = updated_locals # Output self.evaluated_value = None self.exc = None async def _async_func(self): return await eval(self._compiled, self._updated_locals, self._updated_globals) def run(self): try: import asyncio loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.evaluated_value = asyncio.run(self._async_func()) except: self.exc = sys.exc_info() class InteractiveInterpreter: """Base class for InteractiveConsole. This class deals with parsing and interpreter state (the user's namespace); it doesn't deal with input buffering or prompting or input file naming (the filename is always passed in explicitly). """ def __init__(self, locals=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. """ if locals is None: locals = {"__name__": "__console__", "__doc__": None} self.locals = locals self.compile = CommandCompiler() def runsource(self, source, filename="<input>", symbol="single"): """Compile and run some source in the interpreter. Arguments are as for compile_command(). One of several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens. 3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit). The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line. """ try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return False if code is None: # Case 2 return True # Case 3 self.runcode(code) return False def runcode(self, code): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: is_async = False if hasattr(inspect, 'CO_COROUTINE'): is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE if is_async: t = _EvalAwaitInNewEventLoop(code, self.locals, None) t.start() t.join() if t.exc: raise t.exc[1].with_traceback(t.exc[2]) else: exec(code, self.locals) except SystemExit: raise except: self.showtraceback() def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below. """ type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value if sys.excepthook is sys.__excepthook__: lines = traceback.format_exception_only(type, value) self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(type, value, tb) def showtraceback(self): """Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below. """ sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() sys.last_traceback = last_tb try: lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) if sys.excepthook is sys.__excepthook__: self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(ei[0], ei[1], last_tb) finally: last_tb = ei = None def write(self, data): """Write a string. The base implementation writes to sys.stderr; a subclass may replace this with a different implementation. """ sys.stderr.write(data) class InteractiveConsole(InteractiveInterpreter): """Closely emulate the behavior of the interactive Python interpreter. This class builds on InteractiveInterpreter and adds prompting using the familiar sys.ps1 and sys.ps2, and input buffering. """ def __init__(self, locals=None, filename="<console>"): """Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. The optional filename argument should specify the (file)name of the input stream; it will show up in tracebacks. """ InteractiveInterpreter.__init__(self, locals) self.filename = filename self.resetbuffer() def resetbuffer(self): """Reset the input buffer.""" self.buffer = [] def interact(self, banner=None, exitmsg=None): """Closely emulate the interactive Python console. The optional banner argument specifies the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!). The optional exitmsg argument specifies the exit message printed when exiting. Pass the empty string to suppress printing an exit message. If exitmsg is not given or None, a default message is printed. """ try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) elif banner: self.write("%s\n" % str(banner)) more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = self.raw_input(prompt) except EOFError: self.write("\n") break else: more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0 if exitmsg is None: self.write('now exiting %s...\n' % self.__class__.__name__) elif exitmsg != '': self.write('%s\n' % exitmsg) def push(self, line): """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()). """ self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more def raw_input(self, prompt=""): """Write a prompt and read a line. The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. The base implementation uses the built-in function input(); a subclass may replace this with a different implementation. """ return input(prompt) def interact(banner=None, readfunc=None, local=None, exitmsg=None): """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() exitmsg -- passed to InteractiveConsole.interact() """ console = InteractiveConsole(local) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner, exitmsg) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('-q', action='store_true', help="don't print version and copyright messages") args = parser.parse_args() if args.q or sys.flags.quiet: banner = '' else: banner = None interact(banner)
19,014
Python
33.261261
87
0.622068
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_concurrency_logger.py
import time from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle import pydevd_xml from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder from _pydevd_bundle.pydevd_constants import get_thread_id from _pydevd_bundle.pydevd_net_command import NetCommand from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import ObjectWrapper, wrap_attr import pydevd_file_utils from _pydev_bundle import pydev_log import sys file_system_encoding = getfilesystemencoding() from urllib.parse import quote threadingCurrentThread = threading.current_thread DONT_TRACE_THREADING = ['threading.py', 'pydevd.py'] INNER_METHODS = ['_stop'] INNER_FILES = ['threading.py'] THREAD_METHODS = ['start', '_stop', 'join'] LOCK_METHODS = ['__init__', 'acquire', 'release', '__enter__', '__exit__'] QUEUE_METHODS = ['put', 'get'] # return time since epoch in milliseconds cur_time = lambda: int(round(time.time() * 1000000)) def get_text_list_for_frame(frame): # partial copy-paste from make_thread_suspend_str curFrame = frame cmdTextList = [] try: while curFrame: # print cmdText myId = str(id(curFrame)) # print "id is ", myId if curFrame.f_code is None: break # Iron Python sometimes does not have it! myName = curFrame.f_code.co_name # method name (if in method) or ? if global if myName is None: break # Iron Python sometimes does not have it! # print "name is ", myName absolute_filename = pydevd_file_utils.get_abs_path_real_path_and_base_from_frame(curFrame)[0] my_file, _applied_mapping = pydevd_file_utils.map_file_to_client(absolute_filename) # print "file is ", my_file # my_file = inspect.getsourcefile(curFrame) or inspect.getfile(frame) myLine = str(curFrame.f_lineno) # print "line is ", myLine # the variables are all gotten 'on-demand' # variables = pydevd_xml.frame_vars_to_xml(curFrame.f_locals) variables = '' cmdTextList.append('<frame id="%s" name="%s" ' % (myId , pydevd_xml.make_valid_xml_value(myName))) cmdTextList.append('file="%s" line="%s">' % (quote(my_file, '/>_= \t'), myLine)) cmdTextList.append(variables) cmdTextList.append("</frame>") curFrame = curFrame.f_back except: pydev_log.exception() return cmdTextList def send_concurrency_message(event_class, time, name, thread_id, type, event, file, line, frame, lock_id=0, parent=None): dbg = GlobalDebuggerHolder.global_dbg if dbg is None: return cmdTextList = ['<xml>'] cmdTextList.append('<' + event_class) cmdTextList.append(' time="%s"' % pydevd_xml.make_valid_xml_value(str(time))) cmdTextList.append(' name="%s"' % pydevd_xml.make_valid_xml_value(name)) cmdTextList.append(' thread_id="%s"' % pydevd_xml.make_valid_xml_value(thread_id)) cmdTextList.append(' type="%s"' % pydevd_xml.make_valid_xml_value(type)) if type == "lock": cmdTextList.append(' lock_id="%s"' % pydevd_xml.make_valid_xml_value(str(lock_id))) if parent is not None: cmdTextList.append(' parent="%s"' % pydevd_xml.make_valid_xml_value(parent)) cmdTextList.append(' event="%s"' % pydevd_xml.make_valid_xml_value(event)) cmdTextList.append(' file="%s"' % pydevd_xml.make_valid_xml_value(file)) cmdTextList.append(' line="%s"' % pydevd_xml.make_valid_xml_value(str(line))) cmdTextList.append('></' + event_class + '>') cmdTextList += get_text_list_for_frame(frame) cmdTextList.append('</xml>') text = ''.join(cmdTextList) if dbg.writer is not None: dbg.writer.add_command(NetCommand(145, 0, text)) def log_new_thread(global_debugger, t): event_time = cur_time() - global_debugger.thread_analyser.start_time send_concurrency_message("threading_event", event_time, t.name, get_thread_id(t), "thread", "start", "code_name", 0, None, parent=get_thread_id(t)) class ThreadingLogger: def __init__(self): self.start_time = cur_time() def set_start_time(self, time): self.start_time = time def log_event(self, frame): write_log = False self_obj = None if "self" in frame.f_locals: self_obj = frame.f_locals["self"] if isinstance(self_obj, threading.Thread) or self_obj.__class__ == ObjectWrapper: write_log = True if hasattr(frame, "f_back") and frame.f_back is not None: back = frame.f_back if hasattr(back, "f_back") and back.f_back is not None: back = back.f_back if "self" in back.f_locals: if isinstance(back.f_locals["self"], threading.Thread): write_log = True try: if write_log: t = threadingCurrentThread() back = frame.f_back if not back: return name, _, back_base = pydevd_file_utils.get_abs_path_real_path_and_base_from_frame(back) event_time = cur_time() - self.start_time method_name = frame.f_code.co_name if isinstance(self_obj, threading.Thread): if not hasattr(self_obj, "_pydev_run_patched"): wrap_attr(self_obj, "run") if (method_name in THREAD_METHODS) and (back_base not in DONT_TRACE_THREADING or \ (method_name in INNER_METHODS and back_base in INNER_FILES)): thread_id = get_thread_id(self_obj) name = self_obj.getName() real_method = frame.f_code.co_name parent = None if real_method == "_stop": if back_base in INNER_FILES and \ back.f_code.co_name == "_wait_for_tstate_lock": back = back.f_back.f_back real_method = "stop" if hasattr(self_obj, "_pydev_join_called"): parent = get_thread_id(t) elif real_method == "join": # join called in the current thread, not in self object if not self_obj.is_alive(): return thread_id = get_thread_id(t) name = t.name self_obj._pydev_join_called = True if real_method == "start": parent = get_thread_id(t) send_concurrency_message("threading_event", event_time, name, thread_id, "thread", real_method, back.f_code.co_filename, back.f_lineno, back, parent=parent) # print(event_time, self_obj.getName(), thread_id, "thread", # real_method, back.f_code.co_filename, back.f_lineno) if method_name == "pydev_after_run_call": if hasattr(frame, "f_back") and frame.f_back is not None: back = frame.f_back if hasattr(back, "f_back") and back.f_back is not None: back = back.f_back if "self" in back.f_locals: if isinstance(back.f_locals["self"], threading.Thread): my_self_obj = frame.f_back.f_back.f_locals["self"] my_back = frame.f_back.f_back my_thread_id = get_thread_id(my_self_obj) send_massage = True if hasattr(my_self_obj, "_pydev_join_called"): send_massage = False # we can't detect stop after join in Python 2 yet if send_massage: send_concurrency_message("threading_event", event_time, "Thread", my_thread_id, "thread", "stop", my_back.f_code.co_filename, my_back.f_lineno, my_back, parent=None) if self_obj.__class__ == ObjectWrapper: if back_base in DONT_TRACE_THREADING: # do not trace methods called from threading return back_back_base = pydevd_file_utils.get_abs_path_real_path_and_base_from_frame(back.f_back)[2] back = back.f_back if back_back_base in DONT_TRACE_THREADING: # back_back_base is the file, where the method was called froms return if method_name == "__init__": send_concurrency_message("threading_event", event_time, t.name, get_thread_id(t), "lock", method_name, back.f_code.co_filename, back.f_lineno, back, lock_id=str(id(frame.f_locals["self"]))) if "attr" in frame.f_locals and \ (frame.f_locals["attr"] in LOCK_METHODS or frame.f_locals["attr"] in QUEUE_METHODS): real_method = frame.f_locals["attr"] if method_name == "call_begin": real_method += "_begin" elif method_name == "call_end": real_method += "_end" else: return if real_method == "release_end": # do not log release end. Maybe use it later return send_concurrency_message("threading_event", event_time, t.name, get_thread_id(t), "lock", real_method, back.f_code.co_filename, back.f_lineno, back, lock_id=str(id(self_obj))) if real_method in ("put_end", "get_end"): # fake release for queue, cause we don't call it directly send_concurrency_message("threading_event", event_time, t.name, get_thread_id(t), "lock", "release", back.f_code.co_filename, back.f_lineno, back, lock_id=str(id(self_obj))) # print(event_time, t.name, get_thread_id(t), "lock", # real_method, back.f_code.co_filename, back.f_lineno) except Exception: pydev_log.exception() class NameManager: def __init__(self, name_prefix): self.tasks = {} self.last = 0 self.prefix = name_prefix def get(self, id): if id not in self.tasks: self.last += 1 self.tasks[id] = self.prefix + "-" + str(self.last) return self.tasks[id] class AsyncioLogger: def __init__(self): self.task_mgr = NameManager("Task") self.coro_mgr = NameManager("Coro") self.start_time = cur_time() def get_task_id(self, frame): asyncio = sys.modules.get('asyncio') if asyncio is None: # If asyncio was not imported, there's nothing to be done # (also fixes issue where multiprocessing is imported due # to asyncio). return None while frame is not None: if "self" in frame.f_locals: self_obj = frame.f_locals["self"] if isinstance(self_obj, asyncio.Task): method_name = frame.f_code.co_name if method_name == "_step": return id(self_obj) frame = frame.f_back return None def log_event(self, frame): event_time = cur_time() - self.start_time # Debug loop iterations # if isinstance(self_obj, asyncio.base_events.BaseEventLoop): # if method_name == "_run_once": # print("Loop iteration") if not hasattr(frame, "f_back") or frame.f_back is None: return asyncio = sys.modules.get('asyncio') if asyncio is None: # If asyncio was not imported, there's nothing to be done # (also fixes issue where multiprocessing is imported due # to asyncio). return back = frame.f_back if "self" in frame.f_locals: self_obj = frame.f_locals["self"] if isinstance(self_obj, asyncio.Task): method_name = frame.f_code.co_name if method_name == "set_result": task_id = id(self_obj) task_name = self.task_mgr.get(str(task_id)) send_concurrency_message("asyncio_event", event_time, task_name, task_name, "thread", "stop", frame.f_code.co_filename, frame.f_lineno, frame) method_name = back.f_code.co_name if method_name == "__init__": task_id = id(self_obj) task_name = self.task_mgr.get(str(task_id)) send_concurrency_message("asyncio_event", event_time, task_name, task_name, "thread", "start", frame.f_code.co_filename, frame.f_lineno, frame) method_name = frame.f_code.co_name if isinstance(self_obj, asyncio.Lock): if method_name in ("acquire", "release"): task_id = self.get_task_id(frame) task_name = self.task_mgr.get(str(task_id)) if method_name == "acquire": if not self_obj._waiters and not self_obj.locked(): send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", method_name + "_begin", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) if self_obj.locked(): method_name += "_begin" else: method_name += "_end" elif method_name == "release": method_name += "_end" send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", method_name, frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) if isinstance(self_obj, asyncio.Queue): if method_name in ("put", "get", "_put", "_get"): task_id = self.get_task_id(frame) task_name = self.task_mgr.get(str(task_id)) if method_name == "put": send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", "acquire_begin", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) elif method_name == "_put": send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", "acquire_end", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", "release", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) elif method_name == "get": back = frame.f_back if back.f_code.co_name != "send": send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", "acquire_begin", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) else: send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", "acquire_end", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj))) send_concurrency_message("asyncio_event", event_time, task_name, task_name, "lock", "release", frame.f_code.co_filename, frame.f_lineno, frame, lock_id=str(id(self_obj)))
16,764
Python
47.314121
140
0.519924
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_concurrency_analyser/pydevd_thread_wrappers.py
from _pydev_bundle._pydev_saved_modules import threading def wrapper(fun): def pydev_after_run_call(): pass def inner(*args, **kwargs): fun(*args, **kwargs) pydev_after_run_call() return inner def wrap_attr(obj, attr): t_save_start = getattr(obj, attr) setattr(obj, attr, wrapper(t_save_start)) obj._pydev_run_patched = True class ObjectWrapper(object): def __init__(self, obj): self.wrapped_object = obj try: import functools functools.update_wrapper(self, obj) except: pass def __getattr__(self, attr): orig_attr = getattr(self.wrapped_object, attr) # .__getattribute__(attr) if callable(orig_attr): def patched_attr(*args, **kwargs): self.call_begin(attr) result = orig_attr(*args, **kwargs) self.call_end(attr) if result == self.wrapped_object: return self return result return patched_attr else: return orig_attr def call_begin(self, attr): pass def call_end(self, attr): pass def __enter__(self): self.call_begin("__enter__") self.wrapped_object.__enter__() self.call_end("__enter__") def __exit__(self, exc_type, exc_val, exc_tb): self.call_begin("__exit__") self.wrapped_object.__exit__(exc_type, exc_val, exc_tb) def factory_wrapper(fun): def inner(*args, **kwargs): obj = fun(*args, **kwargs) return ObjectWrapper(obj) return inner def wrap_threads(): # TODO: add wrappers for thread and _thread # import _thread as mod # print("Thread imported") # mod.start_new_thread = wrapper(mod.start_new_thread) threading.Lock = factory_wrapper(threading.Lock) threading.RLock = factory_wrapper(threading.RLock) # queue patching import queue # @UnresolvedImport queue.Queue = factory_wrapper(queue.Queue)
2,039
Python
23.285714
81
0.57332
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/_debug_adapter/__main__pydevd_gen_debug_adapter_protocol.py
''' Run this module to regenerate the `pydevd_schema.py` file. Note that it'll generate it based on the current debugProtocol.json. Erase it and rerun to download the latest version. ''' def is_variable_to_translate(cls_name, var_name): if var_name in ('variablesReference', 'frameId', 'threadId'): return True if cls_name == 'StackFrame' and var_name == 'id': # It's frameId everywhere except on StackFrame. return True if cls_name == 'Thread' and var_name == 'id': # It's threadId everywhere except on Thread. return True return False def _get_noqa_for_var(prop_name): return ' # noqa (assign to builtin)' if prop_name in ('type', 'format', 'id', 'hex', 'breakpoint', 'filter') else '' class _OrderedSet(object): # Not a good ordered set (just something to be small without adding any deps) def __init__(self, initial_contents=None): self._contents = [] self._contents_as_set = set() if initial_contents is not None: for x in initial_contents: self.add(x) def add(self, x): if x not in self._contents_as_set: self._contents_as_set.add(x) self._contents.append(x) def discard(self, x): if x in self._contents_as_set: self._contents_as_set.remove(x) self._contents.remove(x) def copy(self): return _OrderedSet(self._contents) def update(self, contents): for x in contents: self.add(x) def __iter__(self): return iter(self._contents) def __contains__(self, item): return item in self._contents_as_set def __len__(self): return len(self._contents) def set_repr(self): if len(self) == 0: return 'set()' lst = [repr(x) for x in self] return 'set([' + ', '.join(lst) + '])' class Ref(object): def __init__(self, ref, ref_data): self.ref = ref self.ref_data = ref_data def __str__(self): return self.ref def load_schema_data(): import os.path import json json_file = os.path.join(os.path.dirname(__file__), 'debugProtocol.json') if not os.path.exists(json_file): import requests req = requests.get('https://raw.githubusercontent.com/microsoft/debug-adapter-protocol/gh-pages/debugAdapterProtocol.json') assert req.status_code == 200 with open(json_file, 'wb') as stream: stream.write(req.content) with open(json_file, 'rb') as json_contents: json_schema_data = json.loads(json_contents.read()) return json_schema_data def load_custom_schema_data(): import os.path import json json_file = os.path.join(os.path.dirname(__file__), 'debugProtocolCustom.json') with open(json_file, 'rb') as json_contents: json_schema_data = json.loads(json_contents.read()) return json_schema_data def create_classes_to_generate_structure(json_schema_data): definitions = json_schema_data['definitions'] class_to_generatees = {} for name, definition in definitions.items(): all_of = definition.get('allOf') description = definition.get('description') is_enum = definition.get('type') == 'string' and 'enum' in definition enum_values = None if is_enum: enum_values = definition['enum'] properties = {} properties.update(definition.get('properties', {})) required = _OrderedSet(definition.get('required', _OrderedSet())) base_definitions = [] if all_of is not None: for definition in all_of: ref = definition.get('$ref') if ref is not None: assert ref.startswith('#/definitions/') ref = ref[len('#/definitions/'):] base_definitions.append(ref) else: if not description: description = definition.get('description') properties.update(definition.get('properties', {})) required.update(_OrderedSet(definition.get('required', _OrderedSet()))) if isinstance(description, (list, tuple)): description = '\n'.join(description) if name == 'ModulesRequest': # Hack to accept modules request without arguments (ptvsd: 2050). required.discard('arguments') class_to_generatees[name] = dict( name=name, properties=properties, base_definitions=base_definitions, description=description, required=required, is_enum=is_enum, enum_values=enum_values ) return class_to_generatees def collect_bases(curr_class, classes_to_generate, memo=None): ret = [] if memo is None: memo = {} base_definitions = curr_class['base_definitions'] for base_definition in base_definitions: if base_definition not in memo: ret.append(base_definition) ret.extend(collect_bases(classes_to_generate[base_definition], classes_to_generate, memo)) return ret def fill_properties_and_required_from_base(classes_to_generate): # Now, resolve properties based on refs for class_to_generate in classes_to_generate.values(): dct = {} s = _OrderedSet() for base_definition in reversed(collect_bases(class_to_generate, classes_to_generate)): # Note: go from base to current so that the initial order of the properties has that # same order. dct.update(classes_to_generate[base_definition].get('properties', {})) s.update(classes_to_generate[base_definition].get('required', _OrderedSet())) dct.update(class_to_generate['properties']) class_to_generate['properties'] = dct s.update(class_to_generate['required']) class_to_generate['required'] = s return class_to_generate def update_class_to_generate_description(class_to_generate): import textwrap description = class_to_generate['description'] lines = [] for line in description.splitlines(): wrapped = textwrap.wrap(line.strip(), 100) lines.extend(wrapped) lines.append('') while lines and lines[-1] == '': lines = lines[:-1] class_to_generate['description'] = ' ' + ('\n '.join(lines)) def update_class_to_generate_type(classes_to_generate, class_to_generate): properties = class_to_generate.get('properties') for _prop_name, prop_val in properties.items(): prop_type = prop_val.get('type', '') if not prop_type: prop_type = prop_val.pop('$ref', '') if prop_type: assert prop_type.startswith('#/definitions/') prop_type = prop_type[len('#/definitions/'):] prop_val['type'] = Ref(prop_type, classes_to_generate[prop_type]) def update_class_to_generate_register_dec(classes_to_generate, class_to_generate): # Default class_to_generate['register_request'] = '' class_to_generate['register_dec'] = '@register' properties = class_to_generate.get('properties') enum_type = properties.get('type', {}).get('enum') command = None event = None if enum_type and len(enum_type) == 1 and next(iter(enum_type)) in ("request", "response", "event"): msg_type = next(iter(enum_type)) if msg_type == 'response': # The actual command is typed in the request response_name = class_to_generate['name'] request_name = response_name[:-len('Response')] + 'Request' if request_name in classes_to_generate: command = classes_to_generate[request_name]['properties'].get('command') else: if response_name == 'ErrorResponse': command = {'enum': ['error']} else: raise AssertionError('Unhandled: %s' % (response_name,)) elif msg_type == 'request': command = properties.get('command') elif msg_type == 'event': command = properties.get('event') else: raise AssertionError('Unexpected condition.') if command: enum = command.get('enum') if enum and len(enum) == 1: class_to_generate['register_request'] = '@register_%s(%r)\n' % (msg_type, enum[0]) def extract_prop_name_and_prop(class_to_generate): properties = class_to_generate.get('properties') required = _OrderedSet(class_to_generate.get('required', _OrderedSet())) # Sort so that required come first prop_name_and_prop = list(properties.items()) def compute_sort_key(x): key = x[0] if key in required: if key == 'seq': return 0.5 # seq when required is after the other required keys (to have a default of -1). return 0 return 1 prop_name_and_prop.sort(key=compute_sort_key) return prop_name_and_prop def update_class_to_generate_to_json(class_to_generate): required = _OrderedSet(class_to_generate.get('required', _OrderedSet())) prop_name_and_prop = extract_prop_name_and_prop(class_to_generate) to_dict_body = ['def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused)'] translate_prop_names = [] for prop_name, prop in prop_name_and_prop: if is_variable_to_translate(class_to_generate['name'], prop_name): translate_prop_names.append(prop_name) for prop_name, prop in prop_name_and_prop: namespace = dict(prop_name=prop_name, noqa=_get_noqa_for_var(prop_name)) to_dict_body.append(' %(prop_name)s = self.%(prop_name)s%(noqa)s' % namespace) if prop.get('type') == 'array': to_dict_body.append(' if %(prop_name)s and hasattr(%(prop_name)s[0], "to_dict"):' % namespace) to_dict_body.append(' %(prop_name)s = [x.to_dict() for x in %(prop_name)s]' % namespace) if translate_prop_names: to_dict_body.append(' if update_ids_to_dap:') for prop_name in translate_prop_names: namespace = dict(prop_name=prop_name, noqa=_get_noqa_for_var(prop_name)) to_dict_body.append(' if %(prop_name)s is not None:' % namespace) to_dict_body.append(' %(prop_name)s = self._translate_id_to_dap(%(prop_name)s)%(noqa)s' % namespace) if not translate_prop_names: update_dict_ids_from_dap_body = [] else: update_dict_ids_from_dap_body = ['', '', '@classmethod', 'def update_dict_ids_from_dap(cls, dct):'] for prop_name in translate_prop_names: namespace = dict(prop_name=prop_name) update_dict_ids_from_dap_body.append(' if %(prop_name)r in dct:' % namespace) update_dict_ids_from_dap_body.append(' dct[%(prop_name)r] = cls._translate_id_from_dap(dct[%(prop_name)r])' % namespace) update_dict_ids_from_dap_body.append(' return dct') class_to_generate['update_dict_ids_from_dap'] = _indent_lines('\n'.join(update_dict_ids_from_dap_body)) to_dict_body.append(' dct = {') first_not_required = False for prop_name, prop in prop_name_and_prop: use_to_dict = prop['type'].__class__ == Ref and not prop['type'].ref_data.get('is_enum', False) is_array = prop['type'] == 'array' ref_array_cls_name = '' if is_array: ref = prop['items'].get('$ref') if ref is not None: ref_array_cls_name = ref.split('/')[-1] namespace = dict(prop_name=prop_name, ref_array_cls_name=ref_array_cls_name) if prop_name in required: if use_to_dict: to_dict_body.append(' %(prop_name)r: %(prop_name)s.to_dict(update_ids_to_dap=update_ids_to_dap),' % namespace) else: if ref_array_cls_name: to_dict_body.append(' %(prop_name)r: [%(ref_array_cls_name)s.update_dict_ids_to_dap(o) for o in %(prop_name)s] if (update_ids_to_dap and %(prop_name)s) else %(prop_name)s,' % namespace) else: to_dict_body.append(' %(prop_name)r: %(prop_name)s,' % namespace) else: if not first_not_required: first_not_required = True to_dict_body.append(' }') to_dict_body.append(' if %(prop_name)s is not None:' % namespace) if use_to_dict: to_dict_body.append(' dct[%(prop_name)r] = %(prop_name)s.to_dict(update_ids_to_dap=update_ids_to_dap)' % namespace) else: if ref_array_cls_name: to_dict_body.append(' dct[%(prop_name)r] = [%(ref_array_cls_name)s.update_dict_ids_to_dap(o) for o in %(prop_name)s] if (update_ids_to_dap and %(prop_name)s) else %(prop_name)s' % namespace) else: to_dict_body.append(' dct[%(prop_name)r] = %(prop_name)s' % namespace) if not first_not_required: first_not_required = True to_dict_body.append(' }') to_dict_body.append(' dct.update(self.kwargs)') to_dict_body.append(' return dct') class_to_generate['to_dict'] = _indent_lines('\n'.join(to_dict_body)) if not translate_prop_names: update_dict_ids_to_dap_body = [] else: update_dict_ids_to_dap_body = ['', '', '@classmethod', 'def update_dict_ids_to_dap(cls, dct):'] for prop_name in translate_prop_names: namespace = dict(prop_name=prop_name) update_dict_ids_to_dap_body.append(' if %(prop_name)r in dct:' % namespace) update_dict_ids_to_dap_body.append(' dct[%(prop_name)r] = cls._translate_id_to_dap(dct[%(prop_name)r])' % namespace) update_dict_ids_to_dap_body.append(' return dct') class_to_generate['update_dict_ids_to_dap'] = _indent_lines('\n'.join(update_dict_ids_to_dap_body)) def update_class_to_generate_init(class_to_generate): args = [] init_body = [] docstring = [] required = _OrderedSet(class_to_generate.get('required', _OrderedSet())) prop_name_and_prop = extract_prop_name_and_prop(class_to_generate) translate_prop_names = [] for prop_name, prop in prop_name_and_prop: if is_variable_to_translate(class_to_generate['name'], prop_name): translate_prop_names.append(prop_name) enum = prop.get('enum') if enum and len(enum) == 1: init_body.append(' self.%(prop_name)s = %(enum)r' % dict(prop_name=prop_name, enum=next(iter(enum)))) else: if prop_name in required: if prop_name == 'seq': args.append(prop_name + '=-1') else: args.append(prop_name) else: args.append(prop_name + '=None') if prop['type'].__class__ == Ref: ref = prop['type'] ref_data = ref.ref_data if ref_data.get('is_enum', False): init_body.append(' if %s is not None:' % (prop_name,)) init_body.append(' assert %s in %s.VALID_VALUES' % (prop_name, str(ref))) init_body.append(' self.%(prop_name)s = %(prop_name)s' % dict( prop_name=prop_name)) else: namespace = dict( prop_name=prop_name, ref_name=str(ref) ) init_body.append(' if %(prop_name)s is None:' % namespace) init_body.append(' self.%(prop_name)s = %(ref_name)s()' % namespace) init_body.append(' else:') init_body.append(' self.%(prop_name)s = %(ref_name)s(update_ids_from_dap=update_ids_from_dap, **%(prop_name)s) if %(prop_name)s.__class__ != %(ref_name)s else %(prop_name)s' % namespace ) else: init_body.append(' self.%(prop_name)s = %(prop_name)s' % dict(prop_name=prop_name)) if prop['type'] == 'array': ref = prop['items'].get('$ref') if ref is not None: ref_array_cls_name = ref.split('/')[-1] init_body.append(' if update_ids_from_dap and self.%(prop_name)s:' % dict(prop_name=prop_name)) init_body.append(' for o in self.%(prop_name)s:' % dict(prop_name=prop_name)) init_body.append(' %(ref_array_cls_name)s.update_dict_ids_from_dap(o)' % dict(ref_array_cls_name=ref_array_cls_name)) prop_type = prop['type'] prop_description = prop.get('description', '') if isinstance(prop_description, (list, tuple)): prop_description = '\n '.join(prop_description) docstring.append(':param %(prop_type)s %(prop_name)s: %(prop_description)s' % dict( prop_type=prop_type, prop_name=prop_name, prop_description=prop_description)) if translate_prop_names: init_body.append(' if update_ids_from_dap:') for prop_name in translate_prop_names: init_body.append(' self.%(prop_name)s = self._translate_id_from_dap(self.%(prop_name)s)' % dict(prop_name=prop_name)) docstring = _indent_lines('\n'.join(docstring)) init_body = '\n'.join(init_body) # Actually bundle the whole __init__ from the parts. args = ', '.join(args) if args: args = ', ' + args # Note: added kwargs because some messages are expected to be extended by the user (so, we'll actually # make all extendable so that we don't have to worry about which ones -- we loose a little on typing, # but may be better than doing a allow list based on something only pointed out in the documentation). class_to_generate['init'] = '''def __init__(self%(args)s, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused) """ %(docstring)s """ %(init_body)s self.kwargs = kwargs ''' % dict(args=args, init_body=init_body, docstring=docstring) class_to_generate['init'] = _indent_lines(class_to_generate['init']) def update_class_to_generate_props(class_to_generate): import json def default(o): if isinstance(o, Ref): return o.ref raise AssertionError('Unhandled: %s' % (o,)) properties = class_to_generate['properties'] class_to_generate['props'] = ' __props__ = %s' % _indent_lines( json.dumps(properties, indent=4, default=default)).strip() def update_class_to_generate_refs(class_to_generate): properties = class_to_generate['properties'] class_to_generate['refs'] = ' __refs__ = %s' % _OrderedSet( key for (key, val) in properties.items() if val['type'].__class__ == Ref).set_repr() def update_class_to_generate_enums(class_to_generate): class_to_generate['enums'] = '' if class_to_generate.get('is_enum', False): enums = '' for enum in class_to_generate['enum_values']: enums += ' %s = %r\n' % (enum.upper(), enum) enums += '\n' enums += ' VALID_VALUES = %s\n\n' % _OrderedSet(class_to_generate['enum_values']).set_repr() class_to_generate['enums'] = enums def update_class_to_generate_objects(classes_to_generate, class_to_generate): properties = class_to_generate['properties'] for key, val in properties.items(): if 'type' not in val: val['type'] = 'TypeNA' continue if val['type'] == 'object': create_new = val.copy() create_new.update({ 'name': '%s%s' % (class_to_generate['name'], key.title()), 'description': ' "%s" of %s' % (key, class_to_generate['name']) }) if 'properties' not in create_new: create_new['properties'] = {} assert create_new['name'] not in classes_to_generate classes_to_generate[create_new['name']] = create_new update_class_to_generate_type(classes_to_generate, create_new) update_class_to_generate_props(create_new) # Update nested object types update_class_to_generate_objects(classes_to_generate, create_new) val['type'] = Ref(create_new['name'], classes_to_generate[create_new['name']]) val.pop('properties', None) def gen_debugger_protocol(): import os.path import sys if sys.version_info[:2] < (3, 6): raise AssertionError('Must be run with Python 3.6 onwards (to keep dict order).') classes_to_generate = create_classes_to_generate_structure(load_schema_data()) classes_to_generate.update(create_classes_to_generate_structure(load_custom_schema_data())) class_to_generate = fill_properties_and_required_from_base(classes_to_generate) for class_to_generate in list(classes_to_generate.values()): update_class_to_generate_description(class_to_generate) update_class_to_generate_type(classes_to_generate, class_to_generate) update_class_to_generate_props(class_to_generate) update_class_to_generate_objects(classes_to_generate, class_to_generate) for class_to_generate in classes_to_generate.values(): update_class_to_generate_refs(class_to_generate) update_class_to_generate_init(class_to_generate) update_class_to_generate_enums(class_to_generate) update_class_to_generate_to_json(class_to_generate) update_class_to_generate_register_dec(classes_to_generate, class_to_generate) class_template = ''' %(register_request)s%(register_dec)s class %(name)s(BaseSchema): """ %(description)s Note: automatically generated code. Do not edit manually. """ %(enums)s%(props)s %(refs)s __slots__ = list(__props__.keys()) + ['kwargs'] %(init)s%(update_dict_ids_from_dap)s %(to_dict)s%(update_dict_ids_to_dap)s ''' contents = [] contents.append('# coding: utf-8') contents.append('# Automatically generated code.') contents.append('# Do not edit manually.') contents.append('# Generated by running: %s' % os.path.basename(__file__)) contents.append('from .pydevd_base_schema import BaseSchema, register, register_request, register_response, register_event') contents.append('') for class_to_generate in classes_to_generate.values(): contents.append(class_template % class_to_generate) parent_dir = os.path.dirname(__file__) schema = os.path.join(parent_dir, 'pydevd_schema.py') with open(schema, 'w', encoding='utf-8') as stream: stream.write('\n'.join(contents)) def _indent_lines(lines, indent=' '): out_lines = [] for line in lines.splitlines(keepends=True): out_lines.append(indent + line) return ''.join(out_lines) if __name__ == '__main__': gen_debugger_protocol()
23,085
Python
37.93086
217
0.586788
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/_debug_adapter/pydevd_base_schema.py
from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception import json import itertools from functools import partial class BaseSchema(object): @staticmethod def initialize_ids_translation(): BaseSchema._dap_id_to_obj_id = {0:0, None:None} BaseSchema._obj_id_to_dap_id = {0:0, None:None} BaseSchema._next_dap_id = partial(next, itertools.count(1)) def to_json(self): return json.dumps(self.to_dict()) @staticmethod def _translate_id_to_dap(obj_id): if obj_id == '*': return '*' # Note: we don't invalidate ids, so, if some object starts using the same id # of another object, the same id will be used. dap_id = BaseSchema._obj_id_to_dap_id.get(obj_id) if dap_id is None: dap_id = BaseSchema._obj_id_to_dap_id[obj_id] = BaseSchema._next_dap_id() BaseSchema._dap_id_to_obj_id[dap_id] = obj_id return dap_id @staticmethod def _translate_id_from_dap(dap_id): if dap_id == '*': return '*' try: return BaseSchema._dap_id_to_obj_id[dap_id] except: raise KeyError('Wrong ID sent from the client: %s' % (dap_id,)) @staticmethod def update_dict_ids_to_dap(dct): return dct @staticmethod def update_dict_ids_from_dap(dct): return dct BaseSchema.initialize_ids_translation() _requests_to_types = {} _responses_to_types = {} _event_to_types = {} _all_messages = {} def register(cls): _all_messages[cls.__name__] = cls return cls def register_request(command): def do_register(cls): _requests_to_types[command] = cls return cls return do_register def register_response(command): def do_register(cls): _responses_to_types[command] = cls return cls return do_register def register_event(event): def do_register(cls): _event_to_types[event] = cls return cls return do_register def from_dict(dct, update_ids_from_dap=False): msg_type = dct.get('type') if msg_type is None: raise ValueError('Unable to make sense of message: %s' % (dct,)) if msg_type == 'request': to_type = _requests_to_types use = dct['command'] elif msg_type == 'response': to_type = _responses_to_types use = dct['command'] else: to_type = _event_to_types use = dct['event'] cls = to_type.get(use) if cls is None: raise ValueError('Unable to create message from dict: %s. %s not in %s' % (dct, use, sorted(to_type.keys()))) try: return cls(update_ids_from_dap=update_ids_from_dap, **dct) except: msg = 'Error creating %s from %s' % (cls, dct) debug_exception(msg) raise def from_json(json_msg, update_ids_from_dap=False, on_dict_loaded=lambda dct:None): if isinstance(json_msg, bytes): json_msg = json_msg.decode('utf-8') as_dict = json.loads(json_msg) on_dict_loaded(as_dict) try: return from_dict(as_dict, update_ids_from_dap=update_ids_from_dap) except: if as_dict.get('type') == 'response' and not as_dict.get('success'): # Error messages may not have required body (return as a generic Response). Response = _all_messages['Response'] return Response(**as_dict) else: raise def get_response_class(request): if request.__class__ == dict: return _responses_to_types[request['command']] return _responses_to_types[request.command] def build_response(request, kwargs=None): if kwargs is None: kwargs = {'success':True} else: if 'success' not in kwargs: kwargs['success'] = True response_class = _responses_to_types[request.command] kwargs.setdefault('seq', -1) # To be overwritten before sending return response_class(command=request.command, request_seq=request.seq, **kwargs)
3,998
Python
26.02027
117
0.608304
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydevd_bundle/_debug_adapter/pydevd_schema_log.py
import os import traceback from _pydevd_bundle.pydevd_constants import ForkSafeLock _pid = os.getpid() _pid_msg = '%s: ' % (_pid,) _debug_lock = ForkSafeLock() DEBUG = False DEBUG_FILE = os.path.join(os.path.dirname(__file__), '__debug_output__.txt') def debug(msg): if DEBUG: with _debug_lock: _pid_prefix = _pid_msg if isinstance(msg, bytes): _pid_prefix = _pid_prefix.encode('utf-8') if not msg.endswith(b'\r') and not msg.endswith(b'\n'): msg += b'\n' mode = 'a+b' else: if not msg.endswith('\r') and not msg.endswith('\n'): msg += '\n' mode = 'a+' with open(DEBUG_FILE, mode) as stream: stream.write(_pid_prefix) stream.write(msg) def debug_exception(msg=None): if DEBUG: if msg: debug(msg) with _debug_lock: with open(DEBUG_FILE, 'a+') as stream: _pid_prefix = _pid_msg if isinstance(msg, bytes): _pid_prefix = _pid_prefix.encode('utf-8') stream.write(_pid_prefix) traceback.print_exc(file=stream)
1,255
Python
25.723404
76
0.494024
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_sitecustomize/sitecustomize.py
''' This module will: - change the input() and raw_input() commands to change \r\n or \r into \n - execute the user site customize -- if available - change raw_input() and input() to also remove any trailing \r Up to PyDev 3.4 it also was setting the default encoding, but it was removed because of differences when running from a shell (i.e.: now we just set the PYTHONIOENCODING related to that -- which is properly treated on Py 2.7 onwards). ''' DEBUG = 0 #0 or 1 because of jython import sys encoding = None IS_PYTHON_3_ONWARDS = 0 try: IS_PYTHON_3_ONWARDS = sys.version_info[0] >= 3 except: #That's OK, not all versions of python have sys.version_info if DEBUG: import traceback;traceback.print_exc() #@Reimport #----------------------------------------------------------------------------------------------------------------------- #Line buffering if IS_PYTHON_3_ONWARDS: #Python 3 has a bug (http://bugs.python.org/issue4705) in which -u doesn't properly make output/input unbuffered #so, we need to enable that ourselves here. try: sys.stdout._line_buffering = True except: pass try: sys.stderr._line_buffering = True except: pass try: sys.stdin._line_buffering = True except: pass try: import org.python.core.PyDictionary #@UnresolvedImport @UnusedImport -- just to check if it could be valid def dict_contains(d, key): return d.has_key(key) except: try: #Py3k does not have has_key anymore, and older versions don't have __contains__ dict_contains = dict.__contains__ except: try: dict_contains = dict.has_key except NameError: def dict_contains(d, key): return d.has_key(key) def install_breakpointhook(): def custom_sitecustomize_breakpointhook(*args, **kwargs): import os hookname = os.getenv('PYTHONBREAKPOINT') if ( hookname is not None and len(hookname) > 0 and hasattr(sys, '__breakpointhook__') and sys.__breakpointhook__ != custom_sitecustomize_breakpointhook ): sys.__breakpointhook__(*args, **kwargs) else: sys.path.append(os.path.dirname(os.path.dirname(__file__))) import pydevd kwargs.setdefault('stop_at_frame', sys._getframe().f_back) pydevd.settrace(*args, **kwargs) if sys.version_info[0:2] >= (3, 7): # There are some choices on how to provide the breakpoint hook. Namely, we can provide a # PYTHONBREAKPOINT which provides the import path for a method to be executed or we # can override sys.breakpointhook. # pydevd overrides sys.breakpointhook instead of providing an environment variable because # it's possible that the debugger starts the user program but is not available in the # PYTHONPATH (and would thus fail to be imported if PYTHONBREAKPOINT was set to pydevd.settrace). # Note that the implementation still takes PYTHONBREAKPOINT in account (so, if it was provided # by someone else, it'd still work). sys.breakpointhook = custom_sitecustomize_breakpointhook else: if sys.version_info[0] >= 3: import builtins as __builtin__ # Py3 else: import __builtin__ # In older versions, breakpoint() isn't really available, so, install the hook directly # in the builtins. __builtin__.breakpoint = custom_sitecustomize_breakpointhook sys.__breakpointhook__ = custom_sitecustomize_breakpointhook # Install the breakpoint hook at import time. install_breakpointhook() #----------------------------------------------------------------------------------------------------------------------- #now that we've finished the needed pydev sitecustomize, let's run the default one (if available) #Ok, some weirdness going on in Python 3k: when removing this module from the sys.module to import the 'real' #sitecustomize, all the variables in this scope become None (as if it was garbage-collected), so, the the reference #below is now being kept to create a cyclic reference so that it neven dies) __pydev_sitecustomize_module__ = sys.modules.get('sitecustomize') #A ref to this module #remove the pydev site customize (and the pythonpath for it) paths_removed = [] try: for c in sys.path[:]: #Pydev controls the whole classpath in Jython already, so, we don't want a a duplicate for #what we've already added there (this is needed to support Jython 2.5b1 onwards -- otherwise, as #we added the sitecustomize to the pythonpath and to the classpath, we'd have to remove it from the #classpath too -- and I don't think there's a way to do that... or not?) if c.find('pydev_sitecustomize') != -1 or c == '__classpath__' or c == '__pyclasspath__' or \ c == '__classpath__/' or c == '__pyclasspath__/' or c == '__classpath__\\' or c == '__pyclasspath__\\': sys.path.remove(c) if c.find('pydev_sitecustomize') == -1: #We'll re-add any paths removed but the pydev_sitecustomize we added from pydev. paths_removed.append(c) if dict_contains(sys.modules, 'sitecustomize'): del sys.modules['sitecustomize'] #this module except: #print the error... should never happen (so, always show, and not only on debug)! import traceback;traceback.print_exc() #@Reimport else: #Now, execute the default sitecustomize try: import sitecustomize #@UnusedImport sitecustomize.__pydev_sitecustomize_module__ = __pydev_sitecustomize_module__ except: pass if not dict_contains(sys.modules, 'sitecustomize'): #If there was no sitecustomize, re-add the pydev sitecustomize (pypy gives a KeyError if it's not there) sys.modules['sitecustomize'] = __pydev_sitecustomize_module__ try: if paths_removed: if sys is None: import sys if sys is not None: #And after executing the default sitecustomize, restore the paths (if we didn't remove it before, #the import sitecustomize would recurse). sys.path.extend(paths_removed) except: #print the error... should never happen (so, always show, and not only on debug)! import traceback;traceback.print_exc() #@Reimport if sys.version_info[0] < 3: try: #Redefine input and raw_input only after the original sitecustomize was executed #(because otherwise, the original raw_input and input would still not be defined) import __builtin__ original_raw_input = __builtin__.raw_input original_input = __builtin__.input def raw_input(prompt=''): #the original raw_input would only remove a trailing \n, so, at #this point if we had a \r\n the \r would remain (which is valid for eclipse) #so, let's remove the remaining \r which python didn't expect. ret = original_raw_input(prompt) if ret.endswith('\r'): return ret[:-1] return ret raw_input.__doc__ = original_raw_input.__doc__ def input(prompt=''): #input must also be rebinded for using the new raw_input defined return eval(raw_input(prompt)) input.__doc__ = original_input.__doc__ __builtin__.raw_input = raw_input __builtin__.input = input except: #Don't report errors at this stage if DEBUG: import traceback;traceback.print_exc() #@Reimport else: try: import builtins #Python 3.0 does not have the __builtin__ module @UnresolvedImport original_input = builtins.input def input(prompt=''): #the original input would only remove a trailing \n, so, at #this point if we had a \r\n the \r would remain (which is valid for eclipse) #so, let's remove the remaining \r which python didn't expect. ret = original_input(prompt) if ret.endswith('\r'): return ret[:-1] return ret input.__doc__ = original_input.__doc__ builtins.input = input except: #Don't report errors at this stage if DEBUG: import traceback;traceback.print_exc() #@Reimport try: #The original getpass doesn't work from the eclipse console, so, let's put a replacement #here (note that it'll not go into echo mode in the console, so, what' the user writes #will actually be seen) #Note: same thing from the fix_getpass module -- but we don't want to import it in this #custom sitecustomize. def fix_get_pass(): try: import getpass except ImportError: return #If we can't import it, we can't fix it import warnings fallback = getattr(getpass, 'fallback_getpass', None) # >= 2.6 if not fallback: fallback = getpass.default_getpass # <= 2.5 getpass.getpass = fallback if hasattr(getpass, 'GetPassWarning'): warnings.simplefilter("ignore", category=getpass.GetPassWarning) fix_get_pass() except: #Don't report errors at this stage if DEBUG: import traceback;traceback.print_exc() #@Reimport
9,473
Python
38.806723
120
0.616172
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookgtk3.py
# encoding: utf-8 """ Enable Gtk3 to be used interacive by IPython. Authors: Thomi Richards """ #----------------------------------------------------------------------------- # Copyright (c) 2012, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from gi.repository import Gtk, GLib # @UnresolvedImport #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def _main_quit(*args, **kwargs): Gtk.main_quit() return False def create_inputhook_gtk3(stdin_file): def inputhook_gtk3(): GLib.io_add_watch(stdin_file, GLib.IO_IN, _main_quit) Gtk.main() return 0 return inputhook_gtk3
1,104
Python
29.694444
78
0.394022
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookgtk.py
# encoding: utf-8 """ Enable pygtk to be used interacive by setting PyOS_InputHook. Authors: Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import gtk, gobject # @UnresolvedImport #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def _main_quit(*args, **kwargs): gtk.main_quit() return False def create_inputhook_gtk(stdin_file): def inputhook_gtk(): gobject.io_add_watch(stdin_file, gobject.IO_IN, _main_quit) gtk.main() return 0 return inputhook_gtk
1,107
Python
28.945945
78
0.392954
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhooktk.py
# encoding: utf-8 # Unlike what IPython does, we need to have an explicit inputhook because tkinter handles # input hook in the C Source code #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from pydev_ipython.inputhook import stdin_ready #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- TCL_DONT_WAIT = 1 << 1 def create_inputhook_tk(app): def inputhook_tk(): while app.dooneevent(TCL_DONT_WAIT) == 1: if stdin_ready(): break return 0 return inputhook_tk
748
Python
30.208332
89
0.378342
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookqt4.py
# -*- coding: utf-8 -*- """ Qt4's inputhook support function Author: Christian Boos """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import os import signal import threading from pydev_ipython.qt_for_kernel import QtCore, QtGui from pydev_ipython.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready # To minimise future merging complexity, rather than edit the entire code base below # we fake InteractiveShell here class InteractiveShell: _instance = None @classmethod def instance(cls): if cls._instance is None: cls._instance = cls() return cls._instance def set_hook(self, *args, **kwargs): # We don't consider the pre_prompt_hook because we don't have # KeyboardInterrupts to consider since we are running under PyDev pass #----------------------------------------------------------------------------- # Module Globals #----------------------------------------------------------------------------- got_kbdint = False sigint_timer = None #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def create_inputhook_qt4(mgr, app=None): """Create an input hook for running the Qt4 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Returns ------- A pair consisting of a Qt Application (either the one given or the one found or created) and a inputhook. Notes ----- We use a custom input hook instead of PyQt4's default one, as it interacts better with the readline packages (issue #481). The inputhook function works in tandem with a 'pre_prompt_hook' which automatically restores the hook as an inputhook in case the latter has been temporarily disabled after having intercepted a KeyboardInterrupt. """ if app is None: app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([" "]) # Re-use previously created inputhook if any ip = InteractiveShell.instance() if hasattr(ip, '_inputhook_qt4'): return app, ip._inputhook_qt4 # Otherwise create the inputhook_qt4/preprompthook_qt4 pair of # hooks (they both share the got_kbdint flag) def inputhook_qt4(): """PyOS_InputHook python hook for Qt4. Process pending Qt events and if there's no pending keyboard input, spend a short slice of time (50ms) running the Qt event loop. As a Python ctypes callback can't raise an exception, we catch the KeyboardInterrupt and temporarily deactivate the hook, which will let a *second* CTRL+C be processed normally and go back to a clean prompt line. """ try: allow_CTRL_C() app = QtCore.QCoreApplication.instance() if not app: # shouldn't happen, but safer if it happens anyway... return 0 app.processEvents(QtCore.QEventLoop.AllEvents, 300) if not stdin_ready(): # Generally a program would run QCoreApplication::exec() # from main() to enter and process the Qt event loop until # quit() or exit() is called and the program terminates. # # For our input hook integration, we need to repeatedly # enter and process the Qt event loop for only a short # amount of time (say 50ms) to ensure that Python stays # responsive to other user inputs. # # A naive approach would be to repeatedly call # QCoreApplication::exec(), using a timer to quit after a # short amount of time. Unfortunately, QCoreApplication # emits an aboutToQuit signal before stopping, which has # the undesirable effect of closing all modal windows. # # To work around this problem, we instead create a # QEventLoop and call QEventLoop::exec(). Other than # setting some state variables which do not seem to be # used anywhere, the only thing QCoreApplication adds is # the aboutToQuit signal which is precisely what we are # trying to avoid. timer = QtCore.QTimer() event_loop = QtCore.QEventLoop() timer.timeout.connect(event_loop.quit) while not stdin_ready(): timer.start(50) event_loop.exec_() timer.stop() except KeyboardInterrupt: global got_kbdint, sigint_timer ignore_CTRL_C() got_kbdint = True mgr.clear_inputhook() # This generates a second SIGINT so the user doesn't have to # press CTRL+C twice to get a clean prompt. # # Since we can't catch the resulting KeyboardInterrupt here # (because this is a ctypes callback), we use a timer to # generate the SIGINT after we leave this callback. # # Unfortunately this doesn't work on Windows (SIGINT kills # Python and CTRL_C_EVENT doesn't work). if(os.name == 'posix'): pid = os.getpid() if(not sigint_timer): sigint_timer = threading.Timer(.01, os.kill, args=[pid, signal.SIGINT] ) sigint_timer.start() else: print("\nKeyboardInterrupt - Ctrl-C again for new prompt") except: # NO exceptions are allowed to escape from a ctypes callback ignore_CTRL_C() from traceback import print_exc print_exc() print("Got exception from inputhook_qt4, unregistering.") mgr.clear_inputhook() finally: allow_CTRL_C() return 0 def preprompthook_qt4(ishell): """'pre_prompt_hook' used to restore the Qt4 input hook (in case the latter was temporarily deactivated after a CTRL+C) """ global got_kbdint, sigint_timer if(sigint_timer): sigint_timer.cancel() sigint_timer = None if got_kbdint: mgr.set_inputhook(inputhook_qt4) got_kbdint = False ip._inputhook_qt4 = inputhook_qt4 ip.set_hook('pre_prompt_hook', preprompthook_qt4) return app, inputhook_qt4
7,242
Python
35.766497
84
0.549296
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhook.py
# coding: utf-8 """ Inputhook management for GUI event loop integration. """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import sys import select #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Constants for identifying the GUI toolkits. GUI_WX = 'wx' GUI_QT = 'qt' GUI_QT4 = 'qt4' GUI_QT5 = 'qt5' GUI_GTK = 'gtk' GUI_TK = 'tk' GUI_OSX = 'osx' GUI_GLUT = 'glut' GUI_PYGLET = 'pyglet' GUI_GTK3 = 'gtk3' GUI_NONE = 'none' # i.e. disable #----------------------------------------------------------------------------- # Utilities #----------------------------------------------------------------------------- def ignore_CTRL_C(): """Ignore CTRL+C (not implemented).""" pass def allow_CTRL_C(): """Take CTRL+C into account (not implemented).""" pass #----------------------------------------------------------------------------- # Main InputHookManager class #----------------------------------------------------------------------------- class InputHookManager(object): """Manage PyOS_InputHook for different GUI toolkits. This class installs various hooks under ``PyOSInputHook`` to handle GUI event loop integration. """ def __init__(self): self._return_control_callback = None self._apps = {} self._reset() self.pyplot_imported = False def _reset(self): self._callback_pyfunctype = None self._callback = None self._current_gui = None def set_return_control_callback(self, return_control_callback): self._return_control_callback = return_control_callback def get_return_control_callback(self): return self._return_control_callback def return_control(self): return self._return_control_callback() def get_inputhook(self): return self._callback def set_inputhook(self, callback): """Set inputhook to callback.""" # We don't (in the context of PyDev console) actually set PyOS_InputHook, but rather # while waiting for input on xmlrpc we run this code self._callback = callback def clear_inputhook(self, app=None): """Clear input hook. Parameters ---------- app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` methods. But the actual value of the parameter is ignored. This uniform interface makes it easier to have user-level entry points in the main IPython app like :meth:`enable_gui`.""" self._reset() def clear_app_refs(self, gui=None): """Clear IPython's internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn't hold a reference themselves. This method is provided to clear the references we are holding. Parameters ---------- gui : None or str If None, clear all app references. If ('wx', 'qt4') clear the app for that toolkit. References are not held for gtk or tk as those toolkits don't have the notion of an app. """ if gui is None: self._apps = {} elif gui in self._apps: del self._apps[gui] def enable_wx(self, app=None): """Enable event loop integration with wxPython. Parameters ---------- app : WX Application, optional. Running application to use. If not given, we probe WX for an existing application object, and create a new one if none is found. Notes ----- This methods sets the ``PyOS_InputHook`` for wxPython, which allows the wxPython to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`wx.App` as follows:: import wx app = wx.App(redirect=False, clearSigInt=False) """ import wx from distutils.version import LooseVersion as V wx_version = V(wx.__version__).version # @UndefinedVariable if wx_version < [2, 8]: raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__) # @UndefinedVariable from pydev_ipython.inputhookwx import inputhook_wx self.set_inputhook(inputhook_wx) self._current_gui = GUI_WX if app is None: app = wx.GetApp() # @UndefinedVariable if app is None: app = wx.App(redirect=False, clearSigInt=False) # @UndefinedVariable app._in_event_loop = True self._apps[GUI_WX] = app return app def disable_wx(self): """Disable event loop integration with wxPython. This merely sets PyOS_InputHook to NULL. """ if GUI_WX in self._apps: self._apps[GUI_WX]._in_event_loop = False self.clear_inputhook() def enable_qt(self, app=None): from pydev_ipython.qt_for_kernel import QT_API, QT_API_PYQT5 if QT_API == QT_API_PYQT5: self.enable_qt5(app) else: self.enable_qt4(app) def enable_qt4(self, app=None): """Enable event loop integration with PyQt4. Parameters ---------- app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Notes ----- This methods sets the PyOS_InputHook for PyQt4, which allows the PyQt4 to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`QApplication` as follows:: from PyQt4 import QtCore app = QtGui.QApplication(sys.argv) """ from pydev_ipython.inputhookqt4 import create_inputhook_qt4 app, inputhook_qt4 = create_inputhook_qt4(self, app) self.set_inputhook(inputhook_qt4) self._current_gui = GUI_QT4 app._in_event_loop = True self._apps[GUI_QT4] = app return app def disable_qt4(self): """Disable event loop integration with PyQt4. This merely sets PyOS_InputHook to NULL. """ if GUI_QT4 in self._apps: self._apps[GUI_QT4]._in_event_loop = False self.clear_inputhook() def enable_qt5(self, app=None): from pydev_ipython.inputhookqt5 import create_inputhook_qt5 app, inputhook_qt5 = create_inputhook_qt5(self, app) self.set_inputhook(inputhook_qt5) self._current_gui = GUI_QT5 app._in_event_loop = True self._apps[GUI_QT5] = app return app def disable_qt5(self): if GUI_QT5 in self._apps: self._apps[GUI_QT5]._in_event_loop = False self.clear_inputhook() def enable_gtk(self, app=None): """Enable event loop integration with PyGTK. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for PyGTK, which allows the PyGTK to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk import create_inputhook_gtk self.set_inputhook(create_inputhook_gtk(self._stdin_file)) self._current_gui = GUI_GTK def disable_gtk(self): """Disable event loop integration with PyGTK. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_tk(self, app=None): """Enable event loop integration with Tk. Parameters ---------- app : toplevel :class:`Tkinter.Tk` widget, optional. Running toplevel widget to use. If not given, we probe Tk for an existing one, and create a new one if none is found. Notes ----- If you have already created a :class:`Tkinter.Tk` object, the only thing done by this method is to register with the :class:`InputHookManager`, since creating that object automatically sets ``PyOS_InputHook``. """ self._current_gui = GUI_TK if app is None: try: import Tkinter as _TK except: # Python 3 import tkinter as _TK # @UnresolvedImport app = _TK.Tk() app.withdraw() self._apps[GUI_TK] = app from pydev_ipython.inputhooktk import create_inputhook_tk self.set_inputhook(create_inputhook_tk(app)) return app def disable_tk(self): """Disable event loop integration with Tkinter. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_glut(self, app=None): """ Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """ import OpenGL.GLUT as glut # @UnresolvedImport from pydev_ipython.inputhookglut import glut_display_mode, \ glut_close, glut_display, \ glut_idle, inputhook_glut if GUI_GLUT not in self._apps: argv = getattr(sys, 'argv', []) glut.glutInit(argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(argv[0] if len(argv) > 0 else '') glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.set_inputhook(inputhook_glut) self._current_gui = GUI_GLUT self._apps[GUI_GLUT] = True def disable_glut(self): """Disable event loop integration with glut. This sets PyOS_InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future. """ import OpenGL.GLUT as glut # @UnresolvedImport from glut_support import glutMainLoopEvent # @UnresolvedImport glut.glutHideWindow() # This is an event to be processed below glutMainLoopEvent() self.clear_inputhook() def enable_pyglet(self, app=None): """Enable event loop integration with pyglet. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the ``PyOS_InputHook`` for pyglet, which allows pyglet to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookpyglet import inputhook_pyglet self.set_inputhook(inputhook_pyglet) self._current_gui = GUI_PYGLET return app def disable_pyglet(self): """Disable event loop integration with pyglet. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for Gtk3, which allows the Gtk3 to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3 self.set_inputhook(create_inputhook_gtk3(self._stdin_file)) self._current_gui = GUI_GTK def disable_gtk3(self): """Disable event loop integration with PyGTK. This merely sets PyOS_InputHook to NULL. """ self.clear_inputhook() def enable_mac(self, app=None): """ Enable event loop integration with MacOSX. We call function pyplot.pause, which updates and displays active figure during pause. It's not MacOSX-specific, but it enables to avoid inputhooks in native MacOSX backend. Also we shouldn't import pyplot, until user does it. Cause it's possible to choose backend before importing pyplot for the first time only. """ def inputhook_mac(app=None): if self.pyplot_imported: pyplot = sys.modules['matplotlib.pyplot'] try: pyplot.pause(0.01) except: pass else: if 'matplotlib.pyplot' in sys.modules: self.pyplot_imported = True self.set_inputhook(inputhook_mac) self._current_gui = GUI_OSX def disable_mac(self): self.clear_inputhook() def current_gui(self): """Return a string indicating the currently active GUI or None.""" return self._current_gui inputhook_manager = InputHookManager() enable_wx = inputhook_manager.enable_wx disable_wx = inputhook_manager.disable_wx enable_qt = inputhook_manager.enable_qt enable_qt4 = inputhook_manager.enable_qt4 disable_qt4 = inputhook_manager.disable_qt4 enable_qt5 = inputhook_manager.enable_qt5 disable_qt5 = inputhook_manager.disable_qt5 enable_gtk = inputhook_manager.enable_gtk disable_gtk = inputhook_manager.disable_gtk enable_tk = inputhook_manager.enable_tk disable_tk = inputhook_manager.disable_tk enable_glut = inputhook_manager.enable_glut disable_glut = inputhook_manager.disable_glut enable_pyglet = inputhook_manager.enable_pyglet disable_pyglet = inputhook_manager.disable_pyglet enable_gtk3 = inputhook_manager.enable_gtk3 disable_gtk3 = inputhook_manager.disable_gtk3 enable_mac = inputhook_manager.enable_mac disable_mac = inputhook_manager.disable_mac clear_inputhook = inputhook_manager.clear_inputhook set_inputhook = inputhook_manager.set_inputhook current_gui = inputhook_manager.current_gui clear_app_refs = inputhook_manager.clear_app_refs # We maintain this as stdin_ready so that the individual inputhooks # can diverge as little as possible from their IPython sources stdin_ready = inputhook_manager.return_control set_return_control_callback = inputhook_manager.set_return_control_callback get_return_control_callback = inputhook_manager.get_return_control_callback get_inputhook = inputhook_manager.get_inputhook # Convenience function to switch amongst them def enable_gui(gui=None, app=None): """Switch amongst GUI input hooks by name. This is just a utility wrapper around the methods of the InputHookManager object. Parameters ---------- gui : optional, string or None If None (or 'none'), clears input hook, otherwise it must be one of the recognized GUI names (see ``GUI_*`` constants in module). app : optional, existing application object. For toolkits that have the concept of a global app, you can supply an existing one. If not given, the toolkit will be probed for one, and if none is found, a new one will be created. Note that GTK does not have this concept, and passing an app if ``gui=="GTK"`` will raise an error. Returns ------- The output of the underlying gui switch routine, typically the actual PyOS_InputHook wrapper object or the GUI toolkit app created, if there was one. """ if get_return_control_callback() is None: raise ValueError("A return_control_callback must be supplied as a reference before a gui can be enabled") guis = {GUI_NONE: clear_inputhook, GUI_OSX: enable_mac, GUI_TK: enable_tk, GUI_GTK: enable_gtk, GUI_WX: enable_wx, GUI_QT: enable_qt, GUI_QT4: enable_qt4, GUI_QT5: enable_qt5, GUI_GLUT: enable_glut, GUI_PYGLET: enable_pyglet, GUI_GTK3: enable_gtk3, } try: gui_hook = guis[gui] except KeyError: if gui is None or gui == '': gui_hook = clear_inputhook else: e = "Invalid GUI request %r, valid ones are:%s" % (gui, list(guis.keys())) raise ValueError(e) return gui_hook(app) __all__ = [ "GUI_WX", "GUI_QT", "GUI_QT4", "GUI_QT5", "GUI_GTK", "GUI_TK", "GUI_OSX", "GUI_GLUT", "GUI_PYGLET", "GUI_GTK3", "GUI_NONE", "ignore_CTRL_C", "allow_CTRL_C", "InputHookManager", "inputhook_manager", "enable_wx", "disable_wx", "enable_qt", "enable_qt4", "disable_qt4", "enable_qt5", "disable_qt5", "enable_gtk", "disable_gtk", "enable_tk", "disable_tk", "enable_glut", "disable_glut", "enable_pyglet", "disable_pyglet", "enable_gtk3", "disable_gtk3", "enable_mac", "disable_mac", "clear_inputhook", "set_inputhook", "current_gui", "clear_app_refs", "stdin_ready", "set_return_control_callback", "get_return_control_callback", "get_inputhook", "enable_gui"]
19,554
Python
31.976391
113
0.591388
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookpyglet.py
# encoding: utf-8 """ Enable pyglet to be used interacive by setting PyOS_InputHook. Authors ------- * Nicolas P. Rougier * Fernando Perez """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import os import sys from _pydev_bundle._pydev_saved_modules import time from timeit import default_timer as clock import pyglet # @UnresolvedImport from pydev_ipython.inputhook import stdin_ready # On linux only, window.flip() has a bug that causes an AttributeError on # window close. For details, see: # http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e if sys.platform.startswith('linux'): def flip(window): try: window.flip() except AttributeError: pass else: def flip(window): window.flip() #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def inputhook_pyglet(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: t = clock() while not stdin_ready(): pyglet.clock.tick() for window in pyglet.app.windows: window.switch_to() window.dispatch_events() window.dispatch_event('on_draw') flip(window) # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
3,255
Python
34.010752
118
0.519201
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/version.py
# encoding: utf-8 """ Utilities for version comparison It is a bit ridiculous that we need these. """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from distutils.version import LooseVersion #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def check_version(v, check): """check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. """ try: return LooseVersion(v) >= LooseVersion(check) except TypeError: return True
1,227
Python
32.189188
84
0.439283
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookglut.py
# coding: utf-8 """ GLUT Inputhook support functions """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- # GLUT is quite an old library and it is difficult to ensure proper # integration within IPython since original GLUT does not allow to handle # events one by one. Instead, it requires for the mainloop to be entered # and never returned (there is not even a function to exit he # mainloop). Fortunately, there are alternatives such as freeglut # (available for linux and windows) and the OSX implementation gives # access to a glutCheckLoop() function that blocks itself until a new # event is received. This means we have to setup the idle callback to # ensure we got at least one event that will unblock the function. # # Furthermore, it is not possible to install these handlers without a window # being first created. We choose to make this window invisible. This means that # display mode options are set at this level and user won't be able to change # them later without modifying the code. This should probably be made available # via IPython options system. #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import os import sys from _pydev_bundle._pydev_saved_modules import time import signal import OpenGL.GLUT as glut # @UnresolvedImport import OpenGL.platform as platform # @UnresolvedImport from timeit import default_timer as clock from pydev_ipython.inputhook import stdin_ready #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Frame per second : 60 # Should probably be an IPython option glut_fps = 60 # Display mode : double buffeed + rgba + depth # Should probably be an IPython option glut_display_mode = (glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH) glutMainLoopEvent = None if sys.platform == 'darwin': try: glutCheckLoop = platform.createBaseFunction( 'glutCheckLoop', dll=platform.GLUT, resultType=None, argTypes=[], doc='glutCheckLoop( ) -> None', argNames=(), ) except AttributeError: raise RuntimeError( '''Your glut implementation does not allow interactive sessions''' '''Consider installing freeglut.''') glutMainLoopEvent = glutCheckLoop elif glut.HAVE_FREEGLUT: glutMainLoopEvent = glut.glutMainLoopEvent else: raise RuntimeError( '''Your glut implementation does not allow interactive sessions. ''' '''Consider installing freeglut.''') #----------------------------------------------------------------------------- # Callback functions #----------------------------------------------------------------------------- def glut_display(): # Dummy display function pass def glut_idle(): # Dummy idle function pass def glut_close(): # Close function only hides the current window glut.glutHideWindow() glutMainLoopEvent() def glut_int_handler(signum, frame): # Catch sigint and print the defautl message signal.signal(signal.SIGINT, signal.default_int_handler) print('\nKeyboardInterrupt') # Need to reprint the prompt at this stage #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def inputhook_glut(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow(1) glutMainLoopEvent() return 0 while not stdin_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
5,675
Python
35.619355
79
0.56652
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookwx.py
# encoding: utf-8 """ Enable wxPython to be used interacive by setting PyOS_InputHook. Authors: Robin Dunn, Brian Granger, Ondrej Certik """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import sys import signal from _pydev_bundle._pydev_saved_modules import time from timeit import default_timer as clock import wx from pydev_ipython.inputhook import stdin_ready #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def inputhook_wx1(): """Run the wx event loop by processing pending events only. This approach seems to work, but its performance is not great as it relies on having PyOS_InputHook called regularly. """ try: app = wx.GetApp() # @UndefinedVariable if app is not None: assert wx.Thread_IsMain() # @UndefinedVariable # Make a temporary event loop and process system events until # there are no more waiting, then allow idle events (which # will also deal with pending or posted wx events.) evtloop = wx.EventLoop() # @UndefinedVariable ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable while evtloop.Pending(): evtloop.Dispatch() app.ProcessIdle() del ea except KeyboardInterrupt: pass return 0 class EventLoopTimer(wx.Timer): # @UndefinedVariable def __init__(self, func): self.func = func wx.Timer.__init__(self) # @UndefinedVariable def Notify(self): self.func() class EventLoopRunner(object): def Run(self, time): self.evtloop = wx.EventLoop() # @UndefinedVariable self.timer = EventLoopTimer(self.check_stdin) self.timer.Start(time) self.evtloop.Run() def check_stdin(self): if stdin_ready(): self.timer.Stop() self.evtloop.Exit() def inputhook_wx2(): """Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often. """ try: app = wx.GetApp() # @UndefinedVariable if app is not None: assert wx.Thread_IsMain() # @UndefinedVariable elr = EventLoopRunner() # As this time is made shorter, keyboard response improves, but idle # CPU load goes up. 10 ms seems like a good compromise. elr.Run(time=10) # CHANGE time here to control polling interval except KeyboardInterrupt: pass return 0 def inputhook_wx3(): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: app = wx.GetApp() # @UndefinedVariable if app is not None: if hasattr(wx, 'IsMainThread'): assert wx.IsMainThread() # @UndefinedVariable else: assert wx.Thread_IsMain() # @UndefinedVariable # The import of wx on Linux sets the handler for signal.SIGINT # to 0. This is a bug in wx or gtk. We fix by just setting it # back to the Python default. if not callable(signal.getsignal(signal.SIGINT)): signal.signal(signal.SIGINT, signal.default_int_handler) evtloop = wx.EventLoop() # @UndefinedVariable ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable t = clock() while not stdin_ready(): while evtloop.Pending(): t = clock() evtloop.Dispatch() app.ProcessIdle() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) del ea except KeyboardInterrupt: pass return 0 if sys.platform == 'darwin': # On OSX, evtloop.Pending() always returns True, regardless of there being # any events pending. As such we can't use implementations 1 or 3 of the # inputhook as those depend on a pending/dispatch loop. inputhook_wx = inputhook_wx2 else: # This is our default implementation inputhook_wx = inputhook_wx3
6,517
Python
37.341176
81
0.565444
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/qt_loaders.py
""" This module contains factory functions that attempt to return Qt submodules from the various python Qt bindings. It also protects against double-importing Qt with different bindings, which is unstable and likely to crash This is used primarily by qt and qt_for_kernel, and shouldn't be accessed directly from the outside """ import sys from functools import partial from pydev_ipython.version import check_version # Available APIs. QT_API_PYQT = 'pyqt' QT_API_PYQTv1 = 'pyqtv1' QT_API_PYQT_DEFAULT = 'pyqtdefault' # don't set SIP explicitly QT_API_PYSIDE = 'pyside' QT_API_PYSIDE2 = 'pyside2' QT_API_PYQT5 = 'pyqt5' class ImportDenier(object): """Import Hook that will guard against bad Qt imports once IPython commits to a specific binding """ def __init__(self): self.__forbidden = set() def forbid(self, module_name): sys.modules.pop(module_name, None) self.__forbidden.add(module_name) def find_module(self, fullname, path=None): if path: return if fullname in self.__forbidden: return self def load_module(self, fullname): raise ImportError(""" Importing %s disabled by IPython, which has already imported an Incompatible QT Binding: %s """ % (fullname, loaded_api())) ID = ImportDenier() sys.meta_path.append(ID) def commit_api(api): """Commit to a particular API, and trigger ImportErrors on subsequent dangerous imports""" if api == QT_API_PYSIDE: ID.forbid('PyQt4') ID.forbid('PyQt5') else: ID.forbid('PySide') ID.forbid('PySide2') def loaded_api(): """Return which API is loaded, if any If this returns anything besides None, importing any other Qt binding is unsafe. Returns ------- None, 'pyside', 'pyside2', 'pyqt', or 'pyqtv1' """ if 'PyQt4.QtCore' in sys.modules: if qtapi_version() == 2: return QT_API_PYQT else: return QT_API_PYQTv1 elif 'PySide.QtCore' in sys.modules: return QT_API_PYSIDE elif 'PySide2.QtCore' in sys.modules: return QT_API_PYSIDE2 elif 'PyQt5.QtCore' in sys.modules: return QT_API_PYQT5 return None def has_binding(api): """Safely check for PyQt4 or PySide, without importing submodules Parameters ---------- api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault'] Which module to check for Returns ------- True if the relevant module appears to be importable """ # we can't import an incomplete pyside and pyqt4 # this will cause a crash in sip (#1431) # check for complete presence before importing module_name = {QT_API_PYSIDE: 'PySide', QT_API_PYSIDE2: 'PySide2', QT_API_PYQT: 'PyQt4', QT_API_PYQTv1: 'PyQt4', QT_API_PYQT_DEFAULT: 'PyQt4', QT_API_PYQT5: 'PyQt5', } module_name = module_name[api] import imp try: # importing top level PyQt4/PySide module is ok... mod = __import__(module_name) # ...importing submodules is not imp.find_module('QtCore', mod.__path__) imp.find_module('QtGui', mod.__path__) imp.find_module('QtSvg', mod.__path__) # we can also safely check PySide version if api == QT_API_PYSIDE: return check_version(mod.__version__, '1.0.3') else: return True except ImportError: return False def qtapi_version(): """Return which QString API has been set, if any Returns ------- The QString API version (1 or 2), or None if not set """ try: import sip except ImportError: return try: return sip.getapi('QString') except ValueError: return def can_import(api): """Safely query whether an API is importable, without importing it""" if not has_binding(api): return False current = loaded_api() if api == QT_API_PYQT_DEFAULT: return current in [QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT5, None] else: return current in [api, None] def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors raised within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if not check_version(QtCore.PYQT_VERSION_STR, '4.7'): raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api def import_pyqt5(): """ Import PyQt5 ImportErrors raised within this function are non-recoverable """ from PyQt5 import QtGui, QtCore, QtSvg # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot return QtCore, QtGui, QtSvg, QT_API_PYQT5 def import_pyside(): """ Import PySide ImportErrors raised within this function are non-recoverable """ from PySide import QtGui, QtCore, QtSvg # @UnresolvedImport return QtCore, QtGui, QtSvg, QT_API_PYSIDE def import_pyside2(): """ Import PySide2 ImportErrors raised within this function are non-recoverable """ from PySide2 import QtGui, QtCore, QtSvg # @UnresolvedImport return QtCore, QtGui, QtSvg, QT_API_PYSIDE def load_qt(api_options): """ Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options: List of strings The order of APIs to try. Valid items are 'pyside', 'pyqt', and 'pyqtv1' Returns ------- A tuple of QtCore, QtGui, QtSvg, QT_API The first three are the Qt modules. The last is the string indicating which module was loaded. Raises ------ ImportError, if it isn't possible to import any requested bindings (either becaues they aren't installed, or because an incompatible library has already been installed) """ loaders = {QT_API_PYSIDE: import_pyside, QT_API_PYSIDE2: import_pyside2, QT_API_PYQT: import_pyqt4, QT_API_PYQTv1: partial(import_pyqt4, version=1), QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None), QT_API_PYQT5: import_pyqt5, } for api in api_options: if api not in loaders: raise RuntimeError( "Invalid Qt API %r, valid values are: %r, %r, %r, %r, %r, %r" % (api, QT_API_PYSIDE, QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT_DEFAULT, QT_API_PYQT5)) if not can_import(api): continue # cannot safely recover from an ImportError during this result = loaders[api]() api = result[-1] # changed if api = QT_API_PYQT_DEFAULT commit_api(api) return result else: raise ImportError(""" Could not load requested Qt binding. Please ensure that PyQt4 >= 4.7 or PySide >= 1.0.3 is available, and only one is imported per session. Currently-imported Qt library: %r PyQt4 installed: %s PyQt5 installed: %s PySide >= 1.0.3 installed: %s PySide2 installed: %s Tried to load: %r """ % (loaded_api(), has_binding(QT_API_PYQT), has_binding(QT_API_PYQT5), has_binding(QT_API_PYSIDE), has_binding(QT_API_PYSIDE2), api_options))
8,413
Python
26.860927
79
0.609771
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/qt_for_kernel.py
""" Import Qt in a manner suitable for an IPython kernel. This is the import used for the `gui=qt` or `matplotlib=qt` initialization. Import Priority: if Qt4 has been imported anywhere else: use that if matplotlib has been imported and doesn't support v2 (<= 1.0.1): use PyQt4 @v1 Next, ask ETS' QT_API env variable if QT_API not set: ask matplotlib via rcParams['backend.qt4'] if it said PyQt: use PyQt4 @v1 elif it said PySide: use PySide else: (matplotlib said nothing) # this is the default path - nobody told us anything try: PyQt @v1 except: fallback on PySide else: use PyQt @v2 or PySide, depending on QT_API because ETS doesn't work with PyQt @v1. """ import os import sys from pydev_ipython.version import check_version from pydev_ipython.qt_loaders import (load_qt, QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT_DEFAULT, loaded_api, QT_API_PYQT5) # Constraints placed on an imported matplotlib def matplotlib_options(mpl): if mpl is None: return # #PyDev-779: In pysrc/pydev_ipython/qt_for_kernel.py, matplotlib_options should be replaced with latest from ipython # (i.e.: properly check backend to decide upon qt4/qt5). backend = mpl.rcParams.get('backend', None) if backend == 'Qt4Agg': mpqt = mpl.rcParams.get('backend.qt4', None) if mpqt is None: return None if mpqt.lower() == 'pyside': return [QT_API_PYSIDE] elif mpqt.lower() == 'pyqt4': return [QT_API_PYQT_DEFAULT] elif mpqt.lower() == 'pyqt4v2': return [QT_API_PYQT] raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" % mpqt) elif backend == 'Qt5Agg': mpqt = mpl.rcParams.get('backend.qt5', None) if mpqt is None: return None if mpqt.lower() == 'pyqt5': return [QT_API_PYQT5] raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" % mpqt) # Fallback without checking backend (previous code) mpqt = mpl.rcParams.get('backend.qt4', None) if mpqt is None: mpqt = mpl.rcParams.get('backend.qt5', None) if mpqt is None: return None if mpqt.lower() == 'pyside': return [QT_API_PYSIDE] elif mpqt.lower() == 'pyqt4': return [QT_API_PYQT_DEFAULT] elif mpqt.lower() == 'pyqt5': return [QT_API_PYQT5] raise ImportError("unhandled value for qt backend from matplotlib: %r" % mpqt) def get_options(): """Return a list of acceptable QT APIs, in decreasing order of preference """ # already imported Qt somewhere. Use that loaded = loaded_api() if loaded is not None: return [loaded] mpl = sys.modules.get('matplotlib', None) if mpl is not None and not check_version(mpl.__version__, '1.0.2'): # 1.0.1 only supports PyQt4 v1 return [QT_API_PYQT_DEFAULT] if os.environ.get('QT_API', None) is None: # no ETS variable. Ask mpl, then use either return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT5] # ETS variable present. Will fallback to external.qt return None api_opts = get_options() if api_opts is not None: QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts) else: # use ETS variable from pydev_ipython.qt import QtCore, QtGui, QtSvg, QT_API
3,619
Python
29.166666
121
0.609284
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/matplotlibtools.py
import sys from _pydev_bundle import pydev_log backends = {'tk': 'TkAgg', 'gtk': 'GTKAgg', 'wx': 'WXAgg', 'qt': 'QtAgg', # Auto-choose qt4/5 'qt4': 'Qt4Agg', 'qt5': 'Qt5Agg', 'osx': 'MacOSX'} # We also need a reverse backends2guis mapping that will properly choose which # GUI support to activate based on the desired matplotlib backend. For the # most part it's just a reverse of the above dict, but we also need to add a # few others that map to the same GUI manually: backend2gui = dict(zip(backends.values(), backends.keys())) # In the reverse mapping, there are a few extra valid matplotlib backends that # map to the same GUI support backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk' backend2gui['WX'] = 'wx' backend2gui['CocoaAgg'] = 'osx' def do_enable_gui(guiname): from _pydev_bundle.pydev_versioncheck import versionok_for_gui if versionok_for_gui(): try: from pydev_ipython.inputhook import enable_gui enable_gui(guiname) except: sys.stderr.write("Failed to enable GUI event loop integration for '%s'\n" % guiname) pydev_log.exception() elif guiname not in ['none', '', None]: # Only print a warning if the guiname was going to do something sys.stderr.write("Debug console: Python version does not support GUI event loop integration for '%s'\n" % guiname) # Return value does not matter, so return back what was sent return guiname def find_gui_and_backend(): """Return the gui and mpl backend.""" matplotlib = sys.modules['matplotlib'] # WARNING: this assumes matplotlib 1.1 or newer!! backend = matplotlib.rcParams['backend'] # In this case, we need to find what the appropriate gui selection call # should be for IPython, so we can activate inputhook accordingly gui = backend2gui.get(backend, None) return gui, backend def is_interactive_backend(backend): """ Check if backend is interactive """ matplotlib = sys.modules['matplotlib'] from matplotlib.rcsetup import interactive_bk, non_interactive_bk # @UnresolvedImport if backend in interactive_bk: return True elif backend in non_interactive_bk: return False else: return matplotlib.is_interactive() def patch_use(enable_gui_function): """ Patch matplotlib function 'use' """ matplotlib = sys.modules['matplotlib'] def patched_use(*args, **kwargs): matplotlib.real_use(*args, **kwargs) gui, backend = find_gui_and_backend() enable_gui_function(gui) matplotlib.real_use = matplotlib.use matplotlib.use = patched_use def patch_is_interactive(): """ Patch matplotlib function 'use' """ matplotlib = sys.modules['matplotlib'] def patched_is_interactive(): return matplotlib.rcParams['interactive'] matplotlib.real_is_interactive = matplotlib.is_interactive matplotlib.is_interactive = patched_is_interactive def activate_matplotlib(enable_gui_function): """Set interactive to True for interactive backends. enable_gui_function - Function which enables gui, should be run in the main thread. """ matplotlib = sys.modules['matplotlib'] gui, backend = find_gui_and_backend() is_interactive = is_interactive_backend(backend) if is_interactive: enable_gui_function(gui) if not matplotlib.is_interactive(): sys.stdout.write("Backend %s is interactive backend. Turning interactive mode on.\n" % backend) matplotlib.interactive(True) else: if matplotlib.is_interactive(): sys.stdout.write("Backend %s is non-interactive backend. Turning interactive mode off.\n" % backend) matplotlib.interactive(False) patch_use(enable_gui_function) patch_is_interactive() def flag_calls(func): """Wrap a function to detect and flag when it gets called. This is a decorator which takes a function and wraps it in a function with a 'called' attribute. wrapper.called is initialized to False. The wrapper.called attribute is set to False right before each call to the wrapped function, so if the call fails it remains False. After the call completes, wrapper.called is set to True and the output is returned. Testing for truth in wrapper.called allows you to determine if a call to func() was attempted and succeeded.""" # don't wrap twice if hasattr(func, 'called'): return func def wrapper(*args, **kw): wrapper.called = False out = func(*args, **kw) wrapper.called = True return out wrapper.called = False wrapper.__doc__ = func.__doc__ return wrapper def activate_pylab(): pylab = sys.modules['pylab'] pylab.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) def activate_pyplot(): pyplot = sys.modules['matplotlib.pyplot'] pyplot.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. pyplot.draw_if_interactive = flag_calls(pyplot.draw_if_interactive)
5,378
Python
34.86
122
0.674972
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/qt.py
""" A Qt API selector that can be used to switch between PyQt and PySide. This uses the ETS 4.0 selection pattern of: PySide first, PyQt with API v2. second. Do not use this if you need PyQt with the old QString/QVariant API. """ import os from pydev_ipython.qt_loaders import (load_qt, QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5) QT_API = os.environ.get('QT_API', None) if QT_API not in [QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5, None]: raise RuntimeError("Invalid Qt API %r, valid values are: %r, %r" % (QT_API, QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5)) if QT_API is None: api_opts = [QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5] else: api_opts = [QT_API] QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
785
Python
31.749999
74
0.636943
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/__init__.py
import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)
294
Python
31.777774
66
0.656463
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/django_debug.py
import inspect from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \ DebugInfoHolder from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace from pydevd_file_utils import canonical_normalized_path, absolute_path from _pydevd_bundle.pydevd_api import PyDevdAPI from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo from _pydev_bundle.pydev_override import overrides IS_DJANGO18 = False IS_DJANGO19 = False IS_DJANGO19_OR_HIGHER = False try: import django version = django.VERSION IS_DJANGO18 = version[0] == 1 and version[1] == 8 IS_DJANGO19 = version[0] == 1 and version[1] == 9 IS_DJANGO19_OR_HIGHER = ((version[0] == 1 and version[1] >= 9) or version[0] > 1) except: pass class DjangoLineBreakpoint(LineBreakpointWithLazyValidation): def __init__(self, canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=None, is_logpoint=False): self.canonical_normalized_filename = canonical_normalized_filename LineBreakpointWithLazyValidation.__init__(self, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint) def __str__(self): return "DjangoLineBreakpoint: %s-%d" % (self.canonical_normalized_filename, self.line) class _DjangoValidationInfo(ValidationInfo): @overrides(ValidationInfo._collect_valid_lines_in_template_uncached) def _collect_valid_lines_in_template_uncached(self, template): lines = set() for node in self._iternodes(template.nodelist): if node.__class__.__name__ in _IGNORE_RENDER_OF_CLASSES: continue lineno = self._get_lineno(node) if lineno is not None: lines.add(lineno) return lines def _get_lineno(self, node): if hasattr(node, 'token') and hasattr(node.token, 'lineno'): return node.token.lineno return None def _iternodes(self, nodelist): for node in nodelist: yield node try: children = node.child_nodelists except: pass else: for attr in children: nodelist = getattr(node, attr, None) if nodelist: # i.e.: yield from _iternodes(nodelist) for node in self._iternodes(nodelist): yield node def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None): if type == 'django-line': django_line_breakpoint = DjangoLineBreakpoint(canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint) if not hasattr(pydb, 'django_breakpoints'): _init_plugin_breaks(pydb) if IS_DJANGO19_OR_HIGHER: add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_LAZY_VALIDATION django_line_breakpoint.add_breakpoint_result = add_breakpoint_result django_line_breakpoint.on_changed_breakpoint_state = on_changed_breakpoint_state else: add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR return django_line_breakpoint, pydb.django_breakpoints return None def after_breakpoints_consolidated(plugin, py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints): if IS_DJANGO19_OR_HIGHER: django_breakpoints_for_file = file_to_line_to_breakpoints.get(canonical_normalized_filename) if not django_breakpoints_for_file: return if not hasattr(py_db, 'django_validation_info'): _init_plugin_breaks(py_db) # In general we validate the breakpoints only when the template is loaded, but if the template # was already loaded, we can validate the breakpoints based on the last loaded value. py_db.django_validation_info.verify_breakpoints_from_template_cached_lines( py_db, canonical_normalized_filename, django_breakpoints_for_file) def add_exception_breakpoint(plugin, pydb, type, exception): if type == 'django': if not hasattr(pydb, 'django_exception_break'): _init_plugin_breaks(pydb) pydb.django_exception_break[exception] = True return True return False def _init_plugin_breaks(pydb): pydb.django_exception_break = {} pydb.django_breakpoints = {} pydb.django_validation_info = _DjangoValidationInfo() def remove_exception_breakpoint(plugin, pydb, type, exception): if type == 'django': try: del pydb.django_exception_break[exception] return True except: pass return False def remove_all_exception_breakpoints(plugin, pydb): if hasattr(pydb, 'django_exception_break'): pydb.django_exception_break = {} return True return False def get_breakpoints(plugin, pydb, type): if type == 'django-line': return pydb.django_breakpoints return None def _inherits(cls, *names): if cls.__name__ in names: return True inherits_node = False for base in inspect.getmro(cls): if base.__name__ in names: inherits_node = True break return inherits_node _IGNORE_RENDER_OF_CLASSES = ('TextNode', 'NodeList') def _is_django_render_call(frame, debug=False): try: name = frame.f_code.co_name if name != 'render': return False if 'self' not in frame.f_locals: return False cls = frame.f_locals['self'].__class__ inherits_node = _inherits(cls, 'Node') if not inherits_node: return False clsname = cls.__name__ if IS_DJANGO19: # in Django 1.9 we need to save the flag that there is included template if clsname == 'IncludeNode': if 'context' in frame.f_locals: context = frame.f_locals['context'] context._has_included_template = True return clsname not in _IGNORE_RENDER_OF_CLASSES except: pydev_log.exception() return False def _is_django_context_get_call(frame): try: if 'self' not in frame.f_locals: return False cls = frame.f_locals['self'].__class__ return _inherits(cls, 'BaseContext') except: pydev_log.exception() return False def _is_django_resolve_call(frame): try: name = frame.f_code.co_name if name != '_resolve_lookup': return False if 'self' not in frame.f_locals: return False cls = frame.f_locals['self'].__class__ clsname = cls.__name__ return clsname == 'Variable' except: pydev_log.exception() return False def _is_django_suspended(thread): return thread.additional_info.suspend_type == DJANGO_SUSPEND def suspend_django(main_debugger, thread, frame, cmd=CMD_SET_BREAK): if frame.f_lineno is None: return None main_debugger.set_suspend(thread, cmd) thread.additional_info.suspend_type = DJANGO_SUSPEND return frame def _find_django_render_frame(frame): while frame is not None and not _is_django_render_call(frame): frame = frame.f_back return frame #======================================================================================================================= # Django Frame #======================================================================================================================= def _read_file(filename): # type: (str) -> str f = open(filename, 'r', encoding='utf-8', errors='replace') s = f.read() f.close() return s def _offset_to_line_number(text, offset): curLine = 1 curOffset = 0 while curOffset < offset: if curOffset == len(text): return -1 c = text[curOffset] if c == '\n': curLine += 1 elif c == '\r': curLine += 1 if curOffset < len(text) and text[curOffset + 1] == '\n': curOffset += 1 curOffset += 1 return curLine def _get_source_django_18_or_lower(frame): # This method is usable only for the Django <= 1.8 try: node = frame.f_locals['self'] if hasattr(node, 'source'): return node.source else: if IS_DJANGO18: # The debug setting was changed since Django 1.8 pydev_log.error_once("WARNING: Template path is not available. Set the 'debug' option in the OPTIONS of a DjangoTemplates " "backend.") else: # The debug setting for Django < 1.8 pydev_log.error_once("WARNING: Template path is not available. Please set TEMPLATE_DEBUG=True in your settings.py to make " "django template breakpoints working") return None except: pydev_log.exception() return None def _convert_to_str(s): return s def _get_template_original_file_name_from_frame(frame): try: if IS_DJANGO19: # The Node source was removed since Django 1.9 if 'context' in frame.f_locals: context = frame.f_locals['context'] if hasattr(context, '_has_included_template'): # if there was included template we need to inspect the previous frames and find its name back = frame.f_back while back is not None and frame.f_code.co_name in ('render', '_render'): locals = back.f_locals if 'self' in locals: self = locals['self'] if self.__class__.__name__ == 'Template' and hasattr(self, 'origin') and \ hasattr(self.origin, 'name'): return _convert_to_str(self.origin.name) back = back.f_back else: if hasattr(context, 'template') and hasattr(context.template, 'origin') and \ hasattr(context.template.origin, 'name'): return _convert_to_str(context.template.origin.name) return None elif IS_DJANGO19_OR_HIGHER: # For Django 1.10 and later there is much simpler way to get template name if 'self' in frame.f_locals: self = frame.f_locals['self'] if hasattr(self, 'origin') and hasattr(self.origin, 'name'): return _convert_to_str(self.origin.name) return None source = _get_source_django_18_or_lower(frame) if source is None: pydev_log.debug("Source is None\n") return None fname = _convert_to_str(source[0].name) if fname == '<unknown source>': pydev_log.debug("Source name is %s\n" % fname) return None else: return fname except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2: pydev_log.exception('Error getting django template filename.') return None def _get_template_line(frame): if IS_DJANGO19_OR_HIGHER: node = frame.f_locals['self'] if hasattr(node, 'token') and hasattr(node.token, 'lineno'): return node.token.lineno else: return None source = _get_source_django_18_or_lower(frame) original_filename = _get_template_original_file_name_from_frame(frame) if original_filename is not None: try: absolute_filename = absolute_path(original_filename) return _offset_to_line_number(_read_file(absolute_filename), source[1][0]) except: return None return None class DjangoTemplateFrame(object): IS_PLUGIN_FRAME = True def __init__(self, frame): original_filename = _get_template_original_file_name_from_frame(frame) self._back_context = frame.f_locals['context'] self.f_code = FCode('Django Template', original_filename) self.f_lineno = _get_template_line(frame) self.f_back = frame self.f_globals = {} self.f_locals = self._collect_context(self._back_context) self.f_trace = None def _collect_context(self, context): res = {} try: for d in context.dicts: for k, v in d.items(): res[k] = v except AttributeError: pass return res def _change_variable(self, name, value): for d in self._back_context.dicts: for k, v in d.items(): if k == name: d[k] = value class DjangoTemplateSyntaxErrorFrame(object): IS_PLUGIN_FRAME = True def __init__(self, frame, original_filename, lineno, f_locals): self.f_code = FCode('Django TemplateSyntaxError', original_filename) self.f_lineno = lineno self.f_back = frame self.f_globals = {} self.f_locals = f_locals self.f_trace = None def change_variable(plugin, frame, attr, expression): if isinstance(frame, DjangoTemplateFrame): result = eval(expression, frame.f_globals, frame.f_locals) frame._change_variable(attr, result) return result return False def _is_django_variable_does_not_exist_exception_break_context(frame): try: name = frame.f_code.co_name except: name = None return name in ('_resolve_lookup', 'find_template') def _is_ignoring_failures(frame): while frame is not None: if frame.f_code.co_name == 'resolve': ignore_failures = frame.f_locals.get('ignore_failures') if ignore_failures: return True frame = frame.f_back return False #======================================================================================================================= # Django Step Commands #======================================================================================================================= def can_skip(plugin, main_debugger, frame): if main_debugger.django_breakpoints: if _is_django_render_call(frame): return False if main_debugger.django_exception_break: module_name = frame.f_globals.get('__name__', '') if module_name == 'django.template.base': # Exceptions raised at django.template.base must be checked. return False return True def has_exception_breaks(plugin): if len(plugin.main_debugger.django_exception_break) > 0: return True return False def has_line_breaks(plugin): for _canonical_normalized_filename, breakpoints in plugin.main_debugger.django_breakpoints.items(): if len(breakpoints) > 0: return True return False def cmd_step_into(plugin, main_debugger, frame, event, args, stop_info, stop): info = args[2] thread = args[3] plugin_stop = False if _is_django_suspended(thread): stop_info['django_stop'] = event == 'call' and _is_django_render_call(frame) plugin_stop = stop_info['django_stop'] stop = stop and _is_django_resolve_call(frame.f_back) and not _is_django_context_get_call(frame) if stop: info.pydev_django_resolve_frame = True # we remember that we've go into python code from django rendering frame return stop, plugin_stop def cmd_step_over(plugin, main_debugger, frame, event, args, stop_info, stop): info = args[2] thread = args[3] plugin_stop = False if _is_django_suspended(thread): stop_info['django_stop'] = event == 'call' and _is_django_render_call(frame) plugin_stop = stop_info['django_stop'] stop = False return stop, plugin_stop else: if event == 'return' and info.pydev_django_resolve_frame and _is_django_resolve_call(frame.f_back): # we return to Django suspend mode and should not stop before django rendering frame info.pydev_step_stop = frame.f_back info.pydev_django_resolve_frame = False thread.additional_info.suspend_type = DJANGO_SUSPEND stop = info.pydev_step_stop is frame and event in ('line', 'return') return stop, plugin_stop def stop(plugin, main_debugger, frame, event, args, stop_info, arg, step_cmd): main_debugger = args[0] thread = args[3] if 'django_stop' in stop_info and stop_info['django_stop']: frame = suspend_django(main_debugger, thread, DjangoTemplateFrame(frame), step_cmd) if frame: main_debugger.do_wait_suspend(thread, frame, event, arg) return True return False def get_breakpoint(plugin, py_db, pydb_frame, frame, event, args): py_db = args[0] _filename = args[1] info = args[2] breakpoint_type = 'django' if event == 'call' and info.pydev_state != STATE_SUSPEND and py_db.django_breakpoints and _is_django_render_call(frame): original_filename = _get_template_original_file_name_from_frame(frame) pydev_log.debug("Django is rendering a template: %s", original_filename) canonical_normalized_filename = canonical_normalized_path(original_filename) django_breakpoints_for_file = py_db.django_breakpoints.get(canonical_normalized_filename) if django_breakpoints_for_file: # At this point, let's validate whether template lines are correct. if IS_DJANGO19_OR_HIGHER: django_validation_info = py_db.django_validation_info context = frame.f_locals['context'] django_template = context.template django_validation_info.verify_breakpoints(py_db, canonical_normalized_filename, django_breakpoints_for_file, django_template) pydev_log.debug("Breakpoints for that file: %s", django_breakpoints_for_file) template_line = _get_template_line(frame) pydev_log.debug("Tracing template line: %s", template_line) if template_line in django_breakpoints_for_file: django_breakpoint = django_breakpoints_for_file[template_line] new_frame = DjangoTemplateFrame(frame) return True, django_breakpoint, new_frame, breakpoint_type return False, None, None, breakpoint_type def suspend(plugin, main_debugger, thread, frame, bp_type): if bp_type == 'django': return suspend_django(main_debugger, thread, DjangoTemplateFrame(frame)) return None def _get_original_filename_from_origin_in_parent_frame_locals(frame, parent_frame_name): filename = None parent_frame = frame while parent_frame.f_code.co_name != parent_frame_name: parent_frame = parent_frame.f_back origin = None if parent_frame is not None: origin = parent_frame.f_locals.get('origin') if hasattr(origin, 'name') and origin.name is not None: filename = _convert_to_str(origin.name) return filename def exception_break(plugin, main_debugger, pydb_frame, frame, args, arg): main_debugger = args[0] thread = args[3] exception, value, trace = arg if main_debugger.django_exception_break and exception is not None: if exception.__name__ in ['VariableDoesNotExist', 'TemplateDoesNotExist', 'TemplateSyntaxError'] and \ just_raised(trace) and not ignore_exception_trace(trace): if exception.__name__ == 'TemplateSyntaxError': # In this case we don't actually have a regular render frame with the context # (we didn't really get to that point). token = getattr(value, 'token', None) if token is None: # Django 1.7 does not have token in exception. Try to get it from locals. token = frame.f_locals.get('token') lineno = getattr(token, 'lineno', None) original_filename = None if lineno is not None: original_filename = _get_original_filename_from_origin_in_parent_frame_locals(frame, 'get_template') if original_filename is None: # Django 1.7 does not have origin in get_template. Try to get it from # load_template. original_filename = _get_original_filename_from_origin_in_parent_frame_locals(frame, 'load_template') if original_filename is not None and lineno is not None: syntax_error_frame = DjangoTemplateSyntaxErrorFrame( frame, original_filename, lineno, {'token': token, 'exception': exception}) suspend_frame = suspend_django( main_debugger, thread, syntax_error_frame, CMD_ADD_EXCEPTION_BREAK) return True, suspend_frame elif exception.__name__ == 'VariableDoesNotExist': if _is_django_variable_does_not_exist_exception_break_context(frame): if not getattr(exception, 'silent_variable_failure', False) and not _is_ignoring_failures(frame): render_frame = _find_django_render_frame(frame) if render_frame: suspend_frame = suspend_django( main_debugger, thread, DjangoTemplateFrame(render_frame), CMD_ADD_EXCEPTION_BREAK) if suspend_frame: add_exception_to_frame(suspend_frame, (exception, value, trace)) thread.additional_info.pydev_message = 'VariableDoesNotExist' suspend_frame.f_back = frame frame = suspend_frame return True, frame return None
22,430
Python
35.532573
231
0.595988
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/pydevd_line_validation.py
from _pydevd_bundle.pydevd_breakpoints import LineBreakpoint from _pydevd_bundle.pydevd_api import PyDevdAPI import bisect from _pydev_bundle import pydev_log class LineBreakpointWithLazyValidation(LineBreakpoint): def __init__(self, *args, **kwargs): LineBreakpoint.__init__(self, *args, **kwargs) # This is the _AddBreakpointResult that'll be modified (and then re-sent on the # on_changed_breakpoint_state). self.add_breakpoint_result = None # The signature for the callback should be: # on_changed_breakpoint_state(breakpoint_id: int, add_breakpoint_result: _AddBreakpointResult) self.on_changed_breakpoint_state = None # When its state is checked (in which case it'd call on_changed_breakpoint_state if the # state changed), we store a cache key in 'verified_cache_key' -- in case it changes # we'd need to re-verify it (for instance, the template could have changed on disk). self.verified_cache_key = None class ValidationInfo(object): def __init__(self): self._canonical_normalized_filename_to_last_template_lines = {} def _collect_valid_lines_in_template(self, template): # We cache the lines in the template itself. Note that among requests the # template may be a different instance (because the template contents could be # changed on disk), but this may still be called multiple times during the # same render session, so, caching is interesting. lines_cache = getattr(template, '__pydevd_lines_cache__', None) if lines_cache is not None: lines, sorted_lines = lines_cache return lines, sorted_lines lines = self._collect_valid_lines_in_template_uncached(template) lines = frozenset(lines) sorted_lines = tuple(sorted(lines)) template.__pydevd_lines_cache__ = lines, sorted_lines return lines, sorted_lines def _collect_valid_lines_in_template_uncached(self, template): raise NotImplementedError() def verify_breakpoints(self, py_db, canonical_normalized_filename, template_breakpoints_for_file, template): ''' This function should be called whenever a rendering is detected. :param str canonical_normalized_filename: :param dict[int:LineBreakpointWithLazyValidation] template_breakpoints_for_file: ''' valid_lines_frozenset, sorted_lines = self._collect_valid_lines_in_template(template) self._canonical_normalized_filename_to_last_template_lines[canonical_normalized_filename] = valid_lines_frozenset, sorted_lines self._verify_breakpoints_with_lines_collected(py_db, canonical_normalized_filename, template_breakpoints_for_file, valid_lines_frozenset, sorted_lines) def verify_breakpoints_from_template_cached_lines(self, py_db, canonical_normalized_filename, template_breakpoints_for_file): ''' This is used when the lines are already available (if just the template is available, `verify_breakpoints` should be used instead). ''' cached = self._canonical_normalized_filename_to_last_template_lines.get(canonical_normalized_filename) if cached is not None: valid_lines_frozenset, sorted_lines = cached self._verify_breakpoints_with_lines_collected(py_db, canonical_normalized_filename, template_breakpoints_for_file, valid_lines_frozenset, sorted_lines) def _verify_breakpoints_with_lines_collected(self, py_db, canonical_normalized_filename, template_breakpoints_for_file, valid_lines_frozenset, sorted_lines): for line, template_bp in list(template_breakpoints_for_file.items()): # Note: iterate in a copy (we may mutate it). if template_bp.verified_cache_key != valid_lines_frozenset: template_bp.verified_cache_key = valid_lines_frozenset valid = line in valid_lines_frozenset if not valid: new_line = -1 if sorted_lines: # Adjust to the first preceding valid line. idx = bisect.bisect_left(sorted_lines, line) if idx > 0: new_line = sorted_lines[idx - 1] if new_line >= 0 and new_line not in template_breakpoints_for_file: # We just add it if found and if there's no existing breakpoint at that # location. if template_bp.add_breakpoint_result.error_code != PyDevdAPI.ADD_BREAKPOINT_NO_ERROR and template_bp.add_breakpoint_result.translated_line != new_line: pydev_log.debug('Template breakpoint in %s in line: %s moved to line: %s', canonical_normalized_filename, line, new_line) template_bp.add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR template_bp.add_breakpoint_result.translated_line = new_line # Add it to a new line. template_breakpoints_for_file.pop(line, None) template_breakpoints_for_file[new_line] = template_bp template_bp.on_changed_breakpoint_state(template_bp.breakpoint_id, template_bp.add_breakpoint_result) else: if template_bp.add_breakpoint_result.error_code != PyDevdAPI.ADD_BREAKPOINT_INVALID_LINE: pydev_log.debug('Template breakpoint in %s in line: %s invalid (valid lines: %s)', canonical_normalized_filename, line, valid_lines_frozenset) template_bp.add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_INVALID_LINE template_bp.on_changed_breakpoint_state(template_bp.breakpoint_id, template_bp.add_breakpoint_result) else: if template_bp.add_breakpoint_result.error_code != PyDevdAPI.ADD_BREAKPOINT_NO_ERROR: template_bp.add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR template_bp.on_changed_breakpoint_state(template_bp.breakpoint_id, template_bp.add_breakpoint_result)
6,286
Python
57.212962
175
0.649539
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/jinja2_debug.py
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK from pydevd_file_utils import canonical_normalized_path from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode from _pydev_bundle import pydev_log from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo from _pydev_bundle.pydev_override import overrides from _pydevd_bundle.pydevd_api import PyDevdAPI class Jinja2LineBreakpoint(LineBreakpointWithLazyValidation): def __init__(self, canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=None, is_logpoint=False): self.canonical_normalized_filename = canonical_normalized_filename LineBreakpointWithLazyValidation.__init__(self, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint) def __str__(self): return "Jinja2LineBreakpoint: %s-%d" % (self.canonical_normalized_filename, self.line) class _Jinja2ValidationInfo(ValidationInfo): @overrides(ValidationInfo._collect_valid_lines_in_template_uncached) def _collect_valid_lines_in_template_uncached(self, template): lineno_mapping = _get_frame_lineno_mapping(template) if not lineno_mapping: return set() return set(x[0] for x in lineno_mapping) def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None): if type == 'jinja2-line': jinja2_line_breakpoint = Jinja2LineBreakpoint(canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint) if not hasattr(pydb, 'jinja2_breakpoints'): _init_plugin_breaks(pydb) add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_LAZY_VALIDATION jinja2_line_breakpoint.add_breakpoint_result = add_breakpoint_result jinja2_line_breakpoint.on_changed_breakpoint_state = on_changed_breakpoint_state return jinja2_line_breakpoint, pydb.jinja2_breakpoints return None def after_breakpoints_consolidated(plugin, py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints): jinja2_breakpoints_for_file = file_to_line_to_breakpoints.get(canonical_normalized_filename) if not jinja2_breakpoints_for_file: return if not hasattr(py_db, 'jinja2_validation_info'): _init_plugin_breaks(py_db) # In general we validate the breakpoints only when the template is loaded, but if the template # was already loaded, we can validate the breakpoints based on the last loaded value. py_db.jinja2_validation_info.verify_breakpoints_from_template_cached_lines( py_db, canonical_normalized_filename, jinja2_breakpoints_for_file) def add_exception_breakpoint(plugin, pydb, type, exception): if type == 'jinja2': if not hasattr(pydb, 'jinja2_exception_break'): _init_plugin_breaks(pydb) pydb.jinja2_exception_break[exception] = True return True return False def _init_plugin_breaks(pydb): pydb.jinja2_exception_break = {} pydb.jinja2_breakpoints = {} pydb.jinja2_validation_info = _Jinja2ValidationInfo() def remove_all_exception_breakpoints(plugin, pydb): if hasattr(pydb, 'jinja2_exception_break'): pydb.jinja2_exception_break = {} return True return False def remove_exception_breakpoint(plugin, pydb, type, exception): if type == 'jinja2': try: del pydb.jinja2_exception_break[exception] return True except: pass return False def get_breakpoints(plugin, pydb, type): if type == 'jinja2-line': return pydb.jinja2_breakpoints return None def _is_jinja2_render_call(frame): try: name = frame.f_code.co_name if "__jinja_template__" in frame.f_globals and name in ("root", "loop", "macro") or name.startswith("block_"): return True return False except: pydev_log.exception() return False def _suspend_jinja2(pydb, thread, frame, cmd=CMD_SET_BREAK, message=None): frame = Jinja2TemplateFrame(frame) if frame.f_lineno is None: return None pydb.set_suspend(thread, cmd) thread.additional_info.suspend_type = JINJA2_SUSPEND if cmd == CMD_ADD_EXCEPTION_BREAK: # send exception name as message if message: message = str(message) thread.additional_info.pydev_message = message return frame def _is_jinja2_suspended(thread): return thread.additional_info.suspend_type == JINJA2_SUSPEND def _is_jinja2_context_call(frame): return "_Context__obj" in frame.f_locals def _is_jinja2_internal_function(frame): return 'self' in frame.f_locals and frame.f_locals['self'].__class__.__name__ in \ ('LoopContext', 'TemplateReference', 'Macro', 'BlockReference') def _find_jinja2_render_frame(frame): while frame is not None and not _is_jinja2_render_call(frame): frame = frame.f_back return frame #======================================================================================================================= # Jinja2 Frame #======================================================================================================================= class Jinja2TemplateFrame(object): IS_PLUGIN_FRAME = True def __init__(self, frame, original_filename=None, template_lineno=None): if original_filename is None: original_filename = _get_jinja2_template_original_filename(frame) if template_lineno is None: template_lineno = _get_jinja2_template_line(frame) self.back_context = None if 'context' in frame.f_locals: # sometimes we don't have 'context', e.g. in macros self.back_context = frame.f_locals['context'] self.f_code = FCode('template', original_filename) self.f_lineno = template_lineno self.f_back = frame self.f_globals = {} self.f_locals = self.collect_context(frame) self.f_trace = None def _get_real_var_name(self, orig_name): # replace leading number for local variables parts = orig_name.split('_') if len(parts) > 1 and parts[0].isdigit(): return parts[1] return orig_name def collect_context(self, frame): res = {} for k, v in frame.f_locals.items(): if not k.startswith('l_'): res[k] = v elif v and not _is_missing(v): res[self._get_real_var_name(k[2:])] = v if self.back_context is not None: for k, v in self.back_context.items(): res[k] = v return res def _change_variable(self, frame, name, value): in_vars_or_parents = False if 'context' in frame.f_locals: if name in frame.f_locals['context'].parent: self.back_context.parent[name] = value in_vars_or_parents = True if name in frame.f_locals['context'].vars: self.back_context.vars[name] = value in_vars_or_parents = True l_name = 'l_' + name if l_name in frame.f_locals: if in_vars_or_parents: frame.f_locals[l_name] = self.back_context.resolve(name) else: frame.f_locals[l_name] = value class Jinja2TemplateSyntaxErrorFrame(object): IS_PLUGIN_FRAME = True def __init__(self, frame, exception_cls_name, filename, lineno, f_locals): self.f_code = FCode('Jinja2 %s' % (exception_cls_name,), filename) self.f_lineno = lineno self.f_back = frame self.f_globals = {} self.f_locals = f_locals self.f_trace = None def change_variable(plugin, frame, attr, expression): if isinstance(frame, Jinja2TemplateFrame): result = eval(expression, frame.f_globals, frame.f_locals) frame._change_variable(frame.f_back, attr, result) return result return False def _is_missing(item): if item.__class__.__name__ == 'MissingType': return True return False def _find_render_function_frame(frame): # in order to hide internal rendering functions old_frame = frame try: while not ('self' in frame.f_locals and frame.f_locals['self'].__class__.__name__ == 'Template' and \ frame.f_code.co_name == 'render'): frame = frame.f_back if frame is None: return old_frame return frame except: return old_frame def _get_jinja2_template_debug_info(frame): frame_globals = frame.f_globals jinja_template = frame_globals.get('__jinja_template__') if jinja_template is None: return None return _get_frame_lineno_mapping(jinja_template) def _get_frame_lineno_mapping(jinja_template): ''' :rtype: list(tuple(int,int)) :return: list((original_line, line_in_frame)) ''' # _debug_info is a string with the mapping from frame line to actual line # i.e.: "5=13&8=14" _debug_info = jinja_template._debug_info if not _debug_info: # Sometimes template contains only plain text. return None # debug_info is a list with the mapping from frame line to actual line # i.e.: [(5, 13), (8, 14)] return jinja_template.debug_info def _get_jinja2_template_line(frame): debug_info = _get_jinja2_template_debug_info(frame) if debug_info is None: return None lineno = frame.f_lineno for pair in debug_info: if pair[1] == lineno: return pair[0] return None def _convert_to_str(s): return s def _get_jinja2_template_original_filename(frame): if '__jinja_template__' in frame.f_globals: return _convert_to_str(frame.f_globals['__jinja_template__'].filename) return None #======================================================================================================================= # Jinja2 Step Commands #======================================================================================================================= def has_exception_breaks(plugin): if len(plugin.main_debugger.jinja2_exception_break) > 0: return True return False def has_line_breaks(plugin): for _canonical_normalized_filename, breakpoints in plugin.main_debugger.jinja2_breakpoints.items(): if len(breakpoints) > 0: return True return False def can_skip(plugin, pydb, frame): if pydb.jinja2_breakpoints and _is_jinja2_render_call(frame): filename = _get_jinja2_template_original_filename(frame) if filename is not None: canonical_normalized_filename = canonical_normalized_path(filename) jinja2_breakpoints_for_file = pydb.jinja2_breakpoints.get(canonical_normalized_filename) if jinja2_breakpoints_for_file: return False if pydb.jinja2_exception_break: name = frame.f_code.co_name # errors in compile time if name in ('template', 'top-level template code', '<module>') or name.startswith('block '): f_back = frame.f_back module_name = '' if f_back is not None: module_name = f_back.f_globals.get('__name__', '') if module_name.startswith('jinja2.'): return False return True def cmd_step_into(plugin, pydb, frame, event, args, stop_info, stop): info = args[2] thread = args[3] plugin_stop = False stop_info['jinja2_stop'] = False if _is_jinja2_suspended(thread): stop_info['jinja2_stop'] = event in ('call', 'line') and _is_jinja2_render_call(frame) plugin_stop = stop_info['jinja2_stop'] stop = False if info.pydev_call_from_jinja2 is not None: if _is_jinja2_internal_function(frame): # if internal Jinja2 function was called, we sould continue debugging inside template info.pydev_call_from_jinja2 = None else: # we go into python code from Jinja2 rendering frame stop = True if event == 'call' and _is_jinja2_context_call(frame.f_back): # we called function from context, the next step will be in function info.pydev_call_from_jinja2 = 1 if event == 'return' and _is_jinja2_context_call(frame.f_back): # we return from python code to Jinja2 rendering frame info.pydev_step_stop = info.pydev_call_from_jinja2 info.pydev_call_from_jinja2 = None thread.additional_info.suspend_type = JINJA2_SUSPEND stop = False # print "info.pydev_call_from_jinja2", info.pydev_call_from_jinja2, "stop_info", stop_info, \ # "thread.additional_info.suspend_type", thread.additional_info.suspend_type # print "event", event, "farme.locals", frame.f_locals return stop, plugin_stop def cmd_step_over(plugin, pydb, frame, event, args, stop_info, stop): info = args[2] thread = args[3] plugin_stop = False stop_info['jinja2_stop'] = False if _is_jinja2_suspended(thread): stop = False if info.pydev_call_inside_jinja2 is None: if _is_jinja2_render_call(frame): if event == 'call': info.pydev_call_inside_jinja2 = frame.f_back if event in ('line', 'return'): info.pydev_call_inside_jinja2 = frame else: if event == 'line': if _is_jinja2_render_call(frame) and info.pydev_call_inside_jinja2 is frame: stop_info['jinja2_stop'] = True plugin_stop = stop_info['jinja2_stop'] if event == 'return': if frame is info.pydev_call_inside_jinja2 and 'event' not in frame.f_back.f_locals: info.pydev_call_inside_jinja2 = _find_jinja2_render_frame(frame.f_back) return stop, plugin_stop else: if event == 'return' and _is_jinja2_context_call(frame.f_back): # we return from python code to Jinja2 rendering frame info.pydev_call_from_jinja2 = None info.pydev_call_inside_jinja2 = _find_jinja2_render_frame(frame) thread.additional_info.suspend_type = JINJA2_SUSPEND stop = False return stop, plugin_stop # print "info.pydev_call_from_jinja2", info.pydev_call_from_jinja2, "stop", stop, "jinja_stop", jinja2_stop, \ # "thread.additional_info.suspend_type", thread.additional_info.suspend_type # print "event", event, "info.pydev_call_inside_jinja2", info.pydev_call_inside_jinja2 # print "frame", frame, "frame.f_back", frame.f_back, "step_stop", info.pydev_step_stop # print "is_context_call", _is_jinja2_context_call(frame) # print "render", _is_jinja2_render_call(frame) # print "-------------" return stop, plugin_stop def stop(plugin, pydb, frame, event, args, stop_info, arg, step_cmd): pydb = args[0] thread = args[3] if 'jinja2_stop' in stop_info and stop_info['jinja2_stop']: frame = _suspend_jinja2(pydb, thread, frame, step_cmd) if frame: pydb.do_wait_suspend(thread, frame, event, arg) return True return False def get_breakpoint(plugin, py_db, pydb_frame, frame, event, args): py_db = args[0] _filename = args[1] info = args[2] break_type = 'jinja2' if event == 'line' and info.pydev_state != STATE_SUSPEND and py_db.jinja2_breakpoints and _is_jinja2_render_call(frame): jinja_template = frame.f_globals.get('__jinja_template__') if jinja_template is None: return False, None, None, break_type original_filename = _get_jinja2_template_original_filename(frame) if original_filename is not None: pydev_log.debug("Jinja2 is rendering a template: %s", original_filename) canonical_normalized_filename = canonical_normalized_path(original_filename) jinja2_breakpoints_for_file = py_db.jinja2_breakpoints.get(canonical_normalized_filename) if jinja2_breakpoints_for_file: jinja2_validation_info = py_db.jinja2_validation_info jinja2_validation_info.verify_breakpoints(py_db, canonical_normalized_filename, jinja2_breakpoints_for_file, jinja_template) template_lineno = _get_jinja2_template_line(frame) if template_lineno is not None: jinja2_breakpoint = jinja2_breakpoints_for_file.get(template_lineno) if jinja2_breakpoint is not None: new_frame = Jinja2TemplateFrame(frame, original_filename, template_lineno) return True, jinja2_breakpoint, new_frame, break_type return False, None, None, break_type def suspend(plugin, pydb, thread, frame, bp_type): if bp_type == 'jinja2': return _suspend_jinja2(pydb, thread, frame) return None def exception_break(plugin, pydb, pydb_frame, frame, args, arg): pydb = args[0] thread = args[3] exception, value, trace = arg if pydb.jinja2_exception_break and exception is not None: exception_type = list(pydb.jinja2_exception_break.keys())[0] if exception.__name__ in ('UndefinedError', 'TemplateNotFound', 'TemplatesNotFound'): # errors in rendering render_frame = _find_jinja2_render_frame(frame) if render_frame: suspend_frame = _suspend_jinja2(pydb, thread, render_frame, CMD_ADD_EXCEPTION_BREAK, message=exception_type) if suspend_frame: add_exception_to_frame(suspend_frame, (exception, value, trace)) suspend_frame.f_back = frame frame = suspend_frame return True, frame elif exception.__name__ in ('TemplateSyntaxError', 'TemplateAssertionError'): name = frame.f_code.co_name # errors in compile time if name in ('template', 'top-level template code', '<module>') or name.startswith('block '): f_back = frame.f_back if f_back is not None: module_name = f_back.f_globals.get('__name__', '') if module_name.startswith('jinja2.'): # Jinja2 translates exception info and creates fake frame on his own pydb_frame.set_suspend(thread, CMD_ADD_EXCEPTION_BREAK) add_exception_to_frame(frame, (exception, value, trace)) thread.additional_info.suspend_type = JINJA2_SUSPEND thread.additional_info.pydev_message = str(exception_type) return True, frame return None
19,141
Python
36.755424
231
0.618045
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/README.md
Extensions allow extending the debugger without modifying the debugger code. This is implemented with explicit namespace packages. To implement your own extension: 1. Ensure that the root folder of your extension is in sys.path (add it to PYTHONPATH) 2. Ensure that your module follows the directory structure below 3. The ``__init__.py`` files inside the pydevd_plugin and extension folder must contain the preamble below, and nothing else. Preamble: ```python try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__) ``` 4. Your plugin name inside the extensions folder must start with `"pydevd_plugin"` 5. Implement one or more of the abstract base classes defined in `_pydevd_bundle.pydevd_extension_api`. This can be done by either inheriting from them or registering with the abstract base class. * Directory structure: ``` |-- root_directory-> must be on python path | |-- pydevd_plugins | | |-- __init__.py -> must contain preamble | | |-- extensions | | | |-- __init__.py -> must contain preamble | | | |-- pydevd_plugin_plugin_name.py ```
1,183
Markdown
38.466665
120
0.708369
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_plugins_django_form_str.py
from _pydevd_bundle.pydevd_extension_api import StrPresentationProvider from .pydevd_helpers import find_mod_attr, find_class_name class DjangoFormStr(object): def can_provide(self, type_object, type_name): form_class = find_mod_attr('django.forms', 'Form') return form_class is not None and issubclass(type_object, form_class) def get_str(self, val): return '%s: %r' % (find_class_name(val), val) import sys if not sys.platform.startswith("java"): StrPresentationProvider.register(DjangoFormStr)
538
Python
30.705881
77
0.717472
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_plugin_pandas_types.py
import sys from _pydevd_bundle.pydevd_constants import PANDAS_MAX_ROWS, PANDAS_MAX_COLS, PANDAS_MAX_COLWIDTH from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider from _pydevd_bundle.pydevd_resolver import inspect, MethodWrapperType from _pydevd_bundle.pydevd_utils import Timer from .pydevd_helpers import find_mod_attr from contextlib import contextmanager def _get_dictionary(obj, replacements): ret = dict() cls = obj.__class__ for attr_name in dir(obj): # This is interesting but it actually hides too much info from the dataframe. # attr_type_in_cls = type(getattr(cls, attr_name, None)) # if attr_type_in_cls == property: # ret[attr_name] = '<property (not computed)>' # continue timer = Timer() try: replacement = replacements.get(attr_name) if replacement is not None: ret[attr_name] = replacement continue attr_value = getattr(obj, attr_name, '<unable to get>') if inspect.isroutine(attr_value) or isinstance(attr_value, MethodWrapperType): continue ret[attr_name] = attr_value except Exception as e: ret[attr_name] = '<error getting: %s>' % (e,) finally: timer.report_if_getting_attr_slow(cls, attr_name) return ret @contextmanager def customize_pandas_options(): # The default repr depends on the settings of: # # pandas.set_option('display.max_columns', None) # pandas.set_option('display.max_rows', None) # # which can make the repr **very** slow on some cases, so, we customize pandas to have # smaller values if the current values are too big. custom_options = [] from pandas import get_option max_rows = get_option("display.max_rows") max_cols = get_option("display.max_columns") max_colwidth = get_option("display.max_colwidth") if max_rows is None or max_rows > PANDAS_MAX_ROWS: custom_options.append("display.max_rows") custom_options.append(PANDAS_MAX_ROWS) if max_cols is None or max_cols > PANDAS_MAX_COLS: custom_options.append("display.max_columns") custom_options.append(PANDAS_MAX_COLS) if max_colwidth is None or max_colwidth > PANDAS_MAX_COLWIDTH: custom_options.append("display.max_colwidth") custom_options.append(PANDAS_MAX_COLWIDTH) if custom_options: from pandas import option_context with option_context(*custom_options): yield else: yield class PandasDataFrameTypeResolveProvider(object): def can_provide(self, type_object, type_name): data_frame_class = find_mod_attr('pandas.core.frame', 'DataFrame') return data_frame_class is not None and issubclass(type_object, data_frame_class) def resolve(self, obj, attribute): return getattr(obj, attribute) def get_dictionary(self, obj): replacements = { # This actually calls: DataFrame.transpose(), which can be expensive, so, # let's just add some string representation for it. 'T': '<transposed dataframe -- debugger:skipped eval>', # This creates a whole new dict{index: Series) for each column. Doing a # subsequent repr() from this dict can be very slow, so, don't return it. '_series': '<dict[index:Series] -- debugger:skipped eval>', 'style': '<pandas.io.formats.style.Styler -- debugger: skipped eval>', } return _get_dictionary(obj, replacements) def get_str(self, df): with customize_pandas_options(): return repr(df) class PandasSeriesTypeResolveProvider(object): def can_provide(self, type_object, type_name): series_class = find_mod_attr('pandas.core.series', 'Series') return series_class is not None and issubclass(type_object, series_class) def resolve(self, obj, attribute): return getattr(obj, attribute) def get_dictionary(self, obj): replacements = { # This actually calls: DataFrame.transpose(), which can be expensive, so, # let's just add some string representation for it. 'T': '<transposed dataframe -- debugger:skipped eval>', # This creates a whole new dict{index: Series) for each column. Doing a # subsequent repr() from this dict can be very slow, so, don't return it. '_series': '<dict[index:Series] -- debugger:skipped eval>', 'style': '<pandas.io.formats.style.Styler -- debugger: skipped eval>', } return _get_dictionary(obj, replacements) def get_str(self, series): with customize_pandas_options(): return repr(series) class PandasStylerTypeResolveProvider(object): def can_provide(self, type_object, type_name): series_class = find_mod_attr('pandas.io.formats.style', 'Styler') return series_class is not None and issubclass(type_object, series_class) def resolve(self, obj, attribute): return getattr(obj, attribute) def get_dictionary(self, obj): replacements = { 'data': '<Styler data -- debugger:skipped eval>', '__dict__': '<dict -- debugger: skipped eval>', } return _get_dictionary(obj, replacements) if not sys.platform.startswith("java"): TypeResolveProvider.register(PandasDataFrameTypeResolveProvider) StrPresentationProvider.register(PandasDataFrameTypeResolveProvider) TypeResolveProvider.register(PandasSeriesTypeResolveProvider) StrPresentationProvider.register(PandasSeriesTypeResolveProvider) TypeResolveProvider.register(PandasStylerTypeResolveProvider)
5,791
Python
34.975155
97
0.654637
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_plugin_numpy_types.py
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider from _pydevd_bundle.pydevd_resolver import defaultResolver, MAX_ITEMS_TO_HANDLE, TOO_LARGE_ATTR, TOO_LARGE_MSG from .pydevd_helpers import find_mod_attr class NdArrayItemsContainer(object): pass class NDArrayTypeResolveProvider(object): ''' This resolves a numpy ndarray returning some metadata about the NDArray ''' def can_provide(self, type_object, type_name): nd_array = find_mod_attr('numpy', 'ndarray') return nd_array is not None and issubclass(type_object, nd_array) def is_numeric(self, obj): if not hasattr(obj, 'dtype'): return False return obj.dtype.kind in 'biufc' def resolve(self, obj, attribute): if attribute == '__internals__': return defaultResolver.get_dictionary(obj) if attribute == 'min': if self.is_numeric(obj) and obj.size > 0: return obj.min() else: return None if attribute == 'max': if self.is_numeric(obj) and obj.size > 0: return obj.max() else: return None if attribute == 'shape': return obj.shape if attribute == 'dtype': return obj.dtype if attribute == 'size': return obj.size if attribute.startswith('['): container = NdArrayItemsContainer() i = 0 format_str = '%0' + str(int(len(str(len(obj))))) + 'd' for item in obj: setattr(container, format_str % i, item) i += 1 if i > MAX_ITEMS_TO_HANDLE: setattr(container, TOO_LARGE_ATTR, TOO_LARGE_MSG) break return container return None def get_dictionary(self, obj): ret = dict() ret['__internals__'] = defaultResolver.get_dictionary(obj) if obj.size > 1024 * 1024: ret['min'] = 'ndarray too big, calculating min would slow down debugging' ret['max'] = 'ndarray too big, calculating max would slow down debugging' elif obj.size == 0: ret['min'] = 'array is empty' ret['max'] = 'array is empty' else: if self.is_numeric(obj): ret['min'] = obj.min() ret['max'] = obj.max() else: ret['min'] = 'not a numeric object' ret['max'] = 'not a numeric object' ret['shape'] = obj.shape ret['dtype'] = obj.dtype ret['size'] = obj.size try: ret['[0:%s] ' % (len(obj))] = list(obj[0:MAX_ITEMS_TO_HANDLE]) except: # This may not work depending on the array shape. pass return ret import sys if not sys.platform.startswith("java"): TypeResolveProvider.register(NDArrayTypeResolveProvider)
2,945
Python
32.862069
110
0.54635
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_helpers.py
import sys def find_cached_module(mod_name): return sys.modules.get(mod_name, None) def find_mod_attr(mod_name, attr): mod = find_cached_module(mod_name) if mod is None: return None return getattr(mod, attr, None) def find_class_name(val): class_name = str(val.__class__) if class_name.find('.') != -1: class_name = class_name.split('.')[-1] elif class_name.find("'") != -1: #does not have '.' (could be something like <type 'int'>) class_name = class_name[class_name.index("'") + 1:] if class_name.endswith("'>"): class_name = class_name[:-2] return class_name
639
Python
22.703703
94
0.597809
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_script.py
def get_main_thread_instance(threading): if hasattr(threading, 'main_thread'): return threading.main_thread() else: # On Python 2 we don't really have an API to get the main thread, # so, we just get it from the 'shutdown' bound method. return threading._shutdown.im_self def get_main_thread_id(unlikely_thread_id=None): ''' :param unlikely_thread_id: Pass to mark some thread id as not likely the main thread. :return tuple(thread_id, critical_warning) ''' import sys import os current_frames = sys._current_frames() possible_thread_ids = [] for thread_ident, frame in current_frames.items(): while frame.f_back is not None: frame = frame.f_back basename = os.path.basename(frame.f_code.co_filename) if basename.endswith(('.pyc', '.pyo')): basename = basename[:-1] if (frame.f_code.co_name, basename) in [ ('_run_module_as_main', 'runpy.py'), ('_run_module_as_main', '<frozen runpy>'), ('run_module_as_main', 'runpy.py'), ('run_module', 'runpy.py'), ('run_path', 'runpy.py'), ]: # This is the case for python -m <module name> (this is an ideal match, so, # let's return it). return thread_ident, '' if frame.f_code.co_name == '<module>': if frame.f_globals.get('__name__') == '__main__': possible_thread_ids.insert(0, thread_ident) # Add with higher priority continue # Usually the main thread will be started in the <module>, whereas others would # be started in another place (but when Python is embedded, this may not be # correct, so, just add to the available possibilities as we'll have to choose # one if there are multiple). possible_thread_ids.append(thread_ident) if len(possible_thread_ids) > 0: if len(possible_thread_ids) == 1: return possible_thread_ids[0], '' # Ideal: only one match while unlikely_thread_id in possible_thread_ids: possible_thread_ids.remove(unlikely_thread_id) if len(possible_thread_ids) == 1: return possible_thread_ids[0], '' # Ideal: only one match elif len(possible_thread_ids) > 1: # Bad: we can't really be certain of anything at this point. return possible_thread_ids[0], \ 'Multiple thread ids found (%s). Choosing main thread id randomly (%s).' % ( possible_thread_ids, possible_thread_ids[0]) # If we got here we couldn't discover the main thread id. return None, 'Unable to discover main thread id.' def fix_main_thread_id(on_warn=lambda msg:None, on_exception=lambda msg:None, on_critical=lambda msg:None): # This means that we weren't able to import threading in the main thread (which most # likely means that the main thread is paused or in some very long operation). # In this case we'll import threading here and hotfix what may be wrong in the threading # module (if we're on Windows where we create a thread to do the attach and on Linux # we are not certain on which thread we're executing this code). # # The code below is a workaround for https://bugs.python.org/issue37416 import sys import threading try: with threading._active_limbo_lock: main_thread_instance = get_main_thread_instance(threading) if sys.platform == 'win32': # On windows this code would be called in a secondary thread, so, # the current thread is unlikely to be the main thread. if hasattr(threading, '_get_ident'): unlikely_thread_id = threading._get_ident() # py2 else: unlikely_thread_id = threading.get_ident() # py3 else: unlikely_thread_id = None main_thread_id, critical_warning = get_main_thread_id(unlikely_thread_id) if main_thread_id is not None: main_thread_id_attr = '_ident' if not hasattr(main_thread_instance, main_thread_id_attr): main_thread_id_attr = '_Thread__ident' assert hasattr(main_thread_instance, main_thread_id_attr) if main_thread_id != getattr(main_thread_instance, main_thread_id_attr): # Note that we also have to reset the '_tstack_lock' for a regular lock. # This is needed to avoid an error on shutdown because this lock is bound # to the thread state and will be released when the secondary thread # that initialized the lock is finished -- making an assert fail during # process shutdown. main_thread_instance._tstate_lock = threading._allocate_lock() main_thread_instance._tstate_lock.acquire() # Actually patch the thread ident as well as the threading._active dict # (we should have the _active_limbo_lock to do that). threading._active.pop(getattr(main_thread_instance, main_thread_id_attr), None) setattr(main_thread_instance, main_thread_id_attr, main_thread_id) threading._active[getattr(main_thread_instance, main_thread_id_attr)] = main_thread_instance # Note: only import from pydevd after the patching is done (we want to do the minimum # possible when doing that patching). on_warn('The threading module was not imported by user code in the main thread. The debugger will attempt to work around https://bugs.python.org/issue37416.') if critical_warning: on_critical('Issue found when debugger was trying to work around https://bugs.python.org/issue37416:\n%s' % (critical_warning,)) except: on_exception('Error patching main thread id.') def attach(port, host, protocol=''): try: import sys fix_main_thread = 'threading' not in sys.modules if fix_main_thread: def on_warn(msg): from _pydev_bundle import pydev_log pydev_log.warn(msg) def on_exception(msg): from _pydev_bundle import pydev_log pydev_log.exception(msg) def on_critical(msg): from _pydev_bundle import pydev_log pydev_log.critical(msg) fix_main_thread_id(on_warn=on_warn, on_exception=on_exception, on_critical=on_critical) else: from _pydev_bundle import pydev_log # @Reimport pydev_log.debug('The threading module is already imported by user code.') if protocol: from _pydevd_bundle import pydevd_defaults pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = protocol import pydevd # I.e.: disconnect/reset if already connected. pydevd.SetupHolder.setup = None py_db = pydevd.get_global_debugger() if py_db is not None: py_db.dispose_and_kill_all_pydevd_threads(wait=False) # pydevd.DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True # pydevd.DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3 # pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 pydevd.settrace( port=port, host=host, stdoutToServer=True, stderrToServer=True, overwrite_prev_trace=True, suspend=False, trace_only_current_thread=False, patch_multiprocessing=False, ) except: import traceback traceback.print_exc()
7,834
Python
40.898396
166
0.5988
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_test_attach_to_process.py
import subprocess import sys print(sys.executable) if __name__ == '__main__': p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py']) import attach_pydevd attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid), '--protocol', 'http'])) p.wait()
297
Python
28.799997
103
0.649832
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py
import add_code_to_python_process print(add_code_to_python_process.run_python_code(3736, "print(20)", connect_debugger_tracing=False))
135
Python
44.333319
100
0.785185
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/add_code_to_python_process.py
r''' Copyright: Brainwy Software Ltda. License: EPL. ============= Works for Windows by using an executable that'll inject a dll to a process and call a function. Note: https://github.com/fabioz/winappdbg is used just to determine if the target process is 32 or 64 bits. Works for Linux relying on gdb. Limitations: ============ Linux: ------ 1. It possible that ptrace is disabled: /etc/sysctl.d/10-ptrace.conf Note that even enabling it in /etc/sysctl.d/10-ptrace.conf (i.e.: making the ptrace_scope=0), it's possible that we need to run the application that'll use ptrace (or gdb in this case) as root (so, we must sudo the python which'll run this module). 2. It currently doesn't work in debug builds (i.e.: python_d) Other implementations: - pyrasite.com: GPL Windows/linux (in Linux it also uses gdb to connect -- although specifics are different as we use a dll to execute code with other threads stopped). It's Windows approach is more limited because it doesn't seem to deal properly with Python 3 if threading is disabled. - https://github.com/google/pyringe: Apache v2. Only linux/Python 2. - http://pytools.codeplex.com: Apache V2 Windows Only (but supports mixed mode debugging) Our own code relies heavily on a part of it: http://pytools.codeplex.com/SourceControl/latest#Python/Product/PyDebugAttach/PyDebugAttach.cpp to overcome some limitations of attaching and running code in the target python executable on Python 3. See: attach.cpp Linux: References if we wanted to use a pure-python debugger: https://bitbucket.org/haypo/python-ptrace/ http://stackoverflow.com/questions/7841573/how-to-get-an-error-message-for-errno-value-in-python Jugaad: https://www.defcon.org/images/defcon-19/dc-19-presentations/Jakhar/DEFCON-19-Jakhar-Jugaad-Linux-Thread-Injection.pdf https://github.com/aseemjakhar/jugaad Something else (general and not Python related): - http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces Other references: - https://github.com/haypo/faulthandler - http://nedbatchelder.com/text/trace-function.html - https://github.com/python-git/python/blob/master/Python/sysmodule.c (sys_settrace) - https://github.com/python-git/python/blob/master/Python/ceval.c (PyEval_SetTrace) - https://github.com/python-git/python/blob/master/Python/thread.c (PyThread_get_key_value) To build the dlls needed on windows, visual studio express 13 was used (see compile_dll.bat) See: attach_pydevd.py to attach the pydev debugger to a running python process. ''' # Note: to work with nasm compiling asm to code and decompiling to see asm with shellcode: # x:\nasm\nasm-2.07-win32\nasm-2.07\nasm.exe # nasm.asm&x:\nasm\nasm-2.07-win32\nasm-2.07\ndisasm.exe -b arch nasm import ctypes import os import struct import subprocess import sys import time from contextlib import contextmanager import platform import traceback try: TimeoutError = TimeoutError # @ReservedAssignment except NameError: class TimeoutError(RuntimeError): # @ReservedAssignment pass @contextmanager def _create_win_event(name): from winappdbg.win32.kernel32 import CreateEventA, WaitForSingleObject, CloseHandle manual_reset = False # i.e.: after someone waits it, automatically set to False. initial_state = False if not isinstance(name, bytes): name = name.encode('utf-8') event = CreateEventA(None, manual_reset, initial_state, name) if not event: raise ctypes.WinError() class _WinEvent(object): def wait_for_event_set(self, timeout=None): ''' :param timeout: in seconds ''' if timeout is None: timeout = 0xFFFFFFFF else: timeout = int(timeout * 1000) ret = WaitForSingleObject(event, timeout) if ret in (0, 0x80): return True elif ret == 0x102: # Timed out return False else: raise ctypes.WinError() try: yield _WinEvent() finally: CloseHandle(event) IS_WINDOWS = sys.platform == 'win32' IS_LINUX = sys.platform in ('linux', 'linux2') IS_MAC = sys.platform == 'darwin' def is_python_64bit(): return (struct.calcsize('P') == 8) def get_target_filename(is_target_process_64=None, prefix=None, extension=None): # Note: we have an independent (and similar -- but not equal) version of this method in # `pydevd_tracing.py` which should be kept synchronized with this one (we do a copy # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the # debugger -- the only situation where it's imported is if the user actually does an attach to # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly # and not from the debugger). libdir = os.path.dirname(__file__) if is_target_process_64 is None: if IS_WINDOWS: # i.e.: On windows the target process could have a different bitness (32bit is emulated on 64bit). raise AssertionError("On windows it's expected that the target bitness is specified.") # For other platforms, just use the the same bitness of the process we're running in. is_target_process_64 = is_python_64bit() arch = '' if IS_WINDOWS: # prefer not using platform.machine() when possible (it's a bit heavyweight as it may # spawn a subprocess). arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_ARCHITECTURE', '')) if not arch: arch = platform.machine() if not arch: print('platform.machine() did not return valid value.') # This shouldn't happen... return None if IS_WINDOWS: if not extension: extension = '.dll' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_LINUX: if not extension: extension = '.so' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_MAC: if not extension: extension = '.dylib' suffix_64 = 'x86_64' suffix_32 = 'x86' else: print('Unable to attach to process in platform: %s', sys.platform) return None if arch.lower() not in ('amd64', 'x86', 'x86_64', 'i386', 'x86'): # We don't support this processor by default. Still, let's support the case where the # user manually compiled it himself with some heuristics. # # Ideally the user would provide a library in the format: "attach_<arch>.<extension>" # based on the way it's currently compiled -- see: # - windows/compile_windows.bat # - linux_and_mac/compile_linux.sh # - linux_and_mac/compile_mac.sh try: found = [name for name in os.listdir(libdir) if name.startswith('attach_') and name.endswith(extension)] except: print('Error listing dir: %s' % (libdir,)) traceback.print_exc() return None if prefix: expected_name = prefix + arch + extension expected_name_linux = prefix + 'linux_' + arch + extension else: # Default is looking for the attach_ / attach_linux expected_name = 'attach_' + arch + extension expected_name_linux = 'attach_linux_' + arch + extension filename = None if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>" filename = os.path.join(libdir, expected_name) elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>" filename = os.path.join(libdir, expected_name_linux) elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib. filename = os.path.join(libdir, found[0]) else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one. filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))] if len(filtered) == 1: # If more than one is available we can't be sure... filename = os.path.join(libdir, found[0]) if filename is None: print( 'Unable to attach to process in arch: %s (did not find %s in %s).' % ( arch, expected_name, libdir ) ) return None print('Using %s in arch: %s.' % (filename, arch)) else: if is_target_process_64: suffix = suffix_64 else: suffix = suffix_32 if not prefix: # Default is looking for the attach_ / attach_linux if IS_WINDOWS or IS_MAC: # just the extension changes prefix = 'attach_' elif IS_LINUX: prefix = 'attach_linux_' # historically it has a different name else: print('Unable to attach to process in platform: %s' % (sys.platform,)) return None filename = os.path.join(libdir, '%s%s%s' % (prefix, suffix, extension)) if not os.path.exists(filename): print('Expected: %s to exist.' % (filename,)) return None return filename def run_python_code_windows(pid, python_code, connect_debugger_tracing=False, show_debug_info=0): assert '\'' not in python_code, 'Having a single quote messes with our command.' from winappdbg.process import Process if not isinstance(python_code, bytes): python_code = python_code.encode('utf-8') process = Process(pid) bits = process.get_bits() is_target_process_64 = bits == 64 # Note: this restriction no longer applies (we create a process with the proper bitness from # this process so that the attach works). # if is_target_process_64 != is_python_64bit(): # raise RuntimeError("The architecture of the Python used to connect doesn't match the architecture of the target.\n" # "Target 64 bits: %s\n" # "Current Python 64 bits: %s" % (is_target_process_64, is_python_64bit())) with _acquire_mutex('_pydevd_pid_attach_mutex_%s' % (pid,), 10): print('--- Connecting to %s bits target (current process is: %s) ---' % (bits, 64 if is_python_64bit() else 32)) with _win_write_to_shared_named_memory(python_code, pid): target_executable = get_target_filename(is_target_process_64, 'inject_dll_', '.exe') if not target_executable: raise RuntimeError('Could not find expected .exe file to inject dll in attach to process.') target_dll = get_target_filename(is_target_process_64) if not target_dll: raise RuntimeError('Could not find expected .dll file in attach to process.') print('\n--- Injecting attach dll: %s into pid: %s ---' % (os.path.basename(target_dll), pid)) args = [target_executable, str(pid), target_dll] subprocess.check_call(args) # Now, if the first injection worked, go on to the second which will actually # run the code. target_dll_run_on_dllmain = get_target_filename(is_target_process_64, 'run_code_on_dllmain_', '.dll') if not target_dll_run_on_dllmain: raise RuntimeError('Could not find expected .dll in attach to process.') with _create_win_event('_pydevd_pid_event_%s' % (pid,)) as event: print('\n--- Injecting run code dll: %s into pid: %s ---' % (os.path.basename(target_dll_run_on_dllmain), pid)) args = [target_executable, str(pid), target_dll_run_on_dllmain] subprocess.check_call(args) if not event.wait_for_event_set(10): print('Timeout error: the attach may not have completed.') print('--- Finished dll injection ---\n') return 0 @contextmanager def _acquire_mutex(mutex_name, timeout): ''' Only one process may be attaching to a pid, so, create a system mutex to make sure this holds in practice. ''' from winappdbg.win32.kernel32 import CreateMutex, GetLastError, CloseHandle from winappdbg.win32.defines import ERROR_ALREADY_EXISTS initial_time = time.time() while True: mutex = CreateMutex(None, True, mutex_name) acquired = GetLastError() != ERROR_ALREADY_EXISTS if acquired: break if time.time() - initial_time > timeout: raise TimeoutError('Unable to acquire mutex to make attach before timeout.') time.sleep(.2) try: yield finally: CloseHandle(mutex) @contextmanager def _win_write_to_shared_named_memory(python_code, pid): # Use the definitions from winappdbg when possible. from winappdbg.win32 import defines from winappdbg.win32.kernel32 import ( CreateFileMapping, MapViewOfFile, CloseHandle, UnmapViewOfFile, ) memmove = ctypes.cdll.msvcrt.memmove memmove.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, defines.SIZE_T, ] memmove.restype = ctypes.c_void_p # Note: BUFSIZE must be the same from run_code_in_memory.hpp BUFSIZE = 2048 assert isinstance(python_code, bytes) assert len(python_code) > 0, 'Python code must not be empty.' # Note: -1 so that we're sure we'll add a \0 to the end. assert len(python_code) < BUFSIZE - 1, 'Python code must have at most %s bytes (found: %s)' % (BUFSIZE - 1, len(python_code)) python_code += b'\0' * (BUFSIZE - len(python_code)) assert python_code.endswith(b'\0') INVALID_HANDLE_VALUE = -1 PAGE_READWRITE = 0x4 FILE_MAP_WRITE = 0x2 filemap = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, BUFSIZE, u"__pydevd_pid_code_to_run__%s" % (pid,)) if filemap == INVALID_HANDLE_VALUE or filemap is None: raise Exception("Failed to create named file mapping (ctypes: CreateFileMapping): %s" % (filemap,)) try: view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0) if not view: raise Exception("Failed to create view of named file mapping (ctypes: MapViewOfFile).") try: memmove(view, python_code, BUFSIZE) yield finally: UnmapViewOfFile(view) finally: CloseHandle(filemap) def run_python_code_linux(pid, python_code, connect_debugger_tracing=False, show_debug_info=0): assert '\'' not in python_code, 'Having a single quote messes with our command.' target_dll = get_target_filename() if not target_dll: raise RuntimeError('Could not find .so for attach to process.') target_dll_name = os.path.splitext(os.path.basename(target_dll))[0] # Note: we currently don't support debug builds is_debug = 0 # Note that the space in the beginning of each line in the multi-line is important! cmd = [ 'gdb', '--nw', # no gui interface '--nh', # no ~/.gdbinit '--nx', # no .gdbinit # '--quiet', # no version number on startup '--pid', str(pid), '--batch', # '--batch-silent', ] # PYDEVD_GDB_SCAN_SHARED_LIBRARIES can be a list of strings with the shared libraries # which should be scanned by default to make the attach to process (i.e.: libdl, libltdl, libc, libfreebl3). # # The default is scanning all shared libraries, but on some cases this can be in the 20-30 # seconds range for some corner cases. # See: https://github.com/JetBrains/intellij-community/pull/1608 # # By setting PYDEVD_GDB_SCAN_SHARED_LIBRARIES (to a comma-separated string), it's possible to # specify just a few libraries to be loaded (not many are needed for the attach, # but it can be tricky to pre-specify for all Linux versions as this may change # across different versions). # # See: https://github.com/microsoft/debugpy/issues/762#issuecomment-947103844 # for a comment that explains the basic steps on how to discover what should be available # in each case (mostly trying different versions based on the output of gdb). # # The upside is that for cases when too many libraries are loaded the attach could be slower # and just specifying the one that is actually needed for the attach can make it much faster. # # The downside is that it may be dependent on the Linux version being attached to (which is the # reason why this is no longer done by default -- see: https://github.com/microsoft/debugpy/issues/882). gdb_load_shared_libraries = os.environ.get('PYDEVD_GDB_SCAN_SHARED_LIBRARIES', '').strip() if gdb_load_shared_libraries: cmd.extend(["--init-eval-command='set auto-solib-add off'"]) # Don't scan all libraries. for lib in gdb_load_shared_libraries.split(','): lib = lib.strip() cmd.extend(["--eval-command='sharedlibrary %s'" % (lib,)]) # Scan the specified library cmd.extend(["--eval-command='set scheduler-locking off'"]) # If on we'll deadlock. # Leave auto by default (it should do the right thing as we're attaching to a process in the # current host). cmd.extend(["--eval-command='set architecture auto'"]) cmd.extend([ "--eval-command='call (void*)dlopen(\"%s\", 2)'" % target_dll, "--eval-command='sharedlibrary %s'" % target_dll_name, "--eval-command='call (int)DoAttach(%s, \"%s\", %s)'" % ( is_debug, python_code, show_debug_info) ]) # print ' '.join(cmd) env = os.environ.copy() # Remove the PYTHONPATH (if gdb has a builtin Python it could fail if we # have the PYTHONPATH for a different python version or some forced encoding). env.pop('PYTHONIOENCODING', None) env.pop('PYTHONPATH', None) print('Running: %s' % (' '.join(cmd))) p = subprocess.Popen( ' '.join(cmd), shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) print('Running gdb in target process.') out, err = p.communicate() print('stdout: %s' % (out,)) print('stderr: %s' % (err,)) return out, err def find_helper_script(filedir, script_name): target_filename = os.path.join(filedir, 'linux_and_mac', script_name) target_filename = os.path.normpath(target_filename) if not os.path.exists(target_filename): raise RuntimeError('Could not find helper script: %s' % target_filename) return target_filename def run_python_code_mac(pid, python_code, connect_debugger_tracing=False, show_debug_info=0): assert '\'' not in python_code, 'Having a single quote messes with our command.' target_dll = get_target_filename() if not target_dll: raise RuntimeError('Could not find .dylib for attach to process.') libdir = os.path.dirname(__file__) lldb_prepare_file = find_helper_script(libdir, 'lldb_prepare.py') # Note: we currently don't support debug builds is_debug = 0 # Note that the space in the beginning of each line in the multi-line is important! cmd = [ 'lldb', '--no-lldbinit', # Do not automatically parse any '.lldbinit' files. # '--attach-pid', # str(pid), # '--arch', # arch, '--script-language', 'Python' # '--batch-silent', ] cmd.extend([ "-o 'process attach --pid %d'" % pid, "-o 'command script import \"%s\"'" % (lldb_prepare_file,), "-o 'load_lib_and_attach \"%s\" %s \"%s\" %s'" % (target_dll, is_debug, python_code, show_debug_info), ]) cmd.extend([ "-o 'process detach'", "-o 'script import os; os._exit(1)'", ]) # print ' '.join(cmd) env = os.environ.copy() # Remove the PYTHONPATH (if gdb has a builtin Python it could fail if we # have the PYTHONPATH for a different python version or some forced encoding). env.pop('PYTHONIOENCODING', None) env.pop('PYTHONPATH', None) print('Running: %s' % (' '.join(cmd))) p = subprocess.Popen( ' '.join(cmd), shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) print('Running lldb in target process.') out, err = p.communicate() print('stdout: %s' % (out,)) print('stderr: %s' % (err,)) return out, err if IS_WINDOWS: run_python_code = run_python_code_windows elif IS_MAC: run_python_code = run_python_code_mac elif IS_LINUX: run_python_code = run_python_code_linux else: def run_python_code(*args, **kwargs): print('Unable to attach to process in platform: %s', sys.platform) def test(): print('Running with: %s' % (sys.executable,)) code = ''' import os, time, sys print(os.getpid()) #from threading import Thread #Thread(target=str).start() if __name__ == '__main__': while True: time.sleep(.5) sys.stdout.write('.\\n') sys.stdout.flush() ''' p = subprocess.Popen([sys.executable, '-u', '-c', code]) try: code = 'print("It worked!")\n' # Real code will be something as: # code = '''import sys;sys.path.append(r'X:\winappdbg-code\examples'); import imported;''' run_python_code(p.pid, python_code=code) print('\nRun a 2nd time...\n') run_python_code(p.pid, python_code=code) time.sleep(3) finally: p.kill() def main(args): # Otherwise, assume the first parameter is the pid and anything else is code to be executed # in the target process. pid = int(args[0]) del args[0] python_code = ';'.join(args) # Note: on Linux the python code may not have a single quote char: ' run_python_code(pid, python_code) if __name__ == '__main__': args = sys.argv[1:] if not args: print('Expected pid and Python code to execute in target process.') else: if '--test' == args[0]: test() else: main(args)
22,296
Python
35.733114
144
0.628095
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_test_attach_to_process_linux.py
''' This module is just for testing concepts. It should be erased later on. Experiments: // gdb -p 4957 // call dlopen("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 2) // call dlsym($1, "hello") // call hello() // call open("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 2) // call mmap(0, 6672, 1 | 2 | 4, 1, 3 , 0) // add-symbol-file // cat /proc/pid/maps // call dlopen("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 1|8) // call dlsym($1, "hello") // call hello() ''' import subprocess import sys import os import time if __name__ == '__main__': linux_dir = os.path.join(os.path.dirname(__file__), 'linux') os.chdir(linux_dir) so_location = os.path.join(linux_dir, 'attach_linux.so') try: os.remove(so_location) except: pass subprocess.call('g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c'.split()) print('Finished compiling') assert os.path.exists('/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so') os.chdir(os.path.dirname(linux_dir)) # import attach_pydevd # attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid)])) p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py']) print('Size of file: %s' % (os.stat(so_location).st_size)) # (gdb) set architecture # Requires an argument. Valid arguments are i386, i386:x86-64, i386:x64-32, i8086, i386:intel, i386:x86-64:intel, i386:x64-32:intel, i386:nacl, i386:x86-64:nacl, i386:x64-32:nacl, auto. cmd = [ 'gdb', '--pid', str(p.pid), '--batch', ] arch = 'i386:x86-64' if arch: cmd.extend(["--eval-command='set architecture %s'" % arch]) cmd.extend([ "--eval-command='call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)'", "--eval-command='call (int)DoAttach(1, \"print(\\\"check11111check\\\")\", 0)'", # "--eval-command='call (int)SetSysTraceFunc(1, 0)'", -- never call this way, always use "--command='...gdb_threads_settrace.py'", # So that threads are all stopped! ]) print(' '.join(cmd)) time.sleep(.5) env = os.environ.copy() env.pop('PYTHONIOENCODING', None) env.pop('PYTHONPATH', None) p2 = subprocess.call(' '.join(cmd), env=env, shell=True) time.sleep(1) p.kill()
2,523
Python
32.653333
189
0.635355
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_pydevd.py
import sys import os def process_command_line(argv): setup = {} setup['port'] = 5678 # Default port for PyDev remote debugger setup['pid'] = 0 setup['host'] = '127.0.0.1' setup['protocol'] = '' i = 0 while i < len(argv): if argv[i] == '--port': del argv[i] setup['port'] = int(argv[i]) del argv[i] elif argv[i] == '--pid': del argv[i] setup['pid'] = int(argv[i]) del argv[i] elif argv[i] == '--host': del argv[i] setup['host'] = argv[i] del argv[i] elif argv[i] == '--protocol': del argv[i] setup['protocol'] = argv[i] del argv[i] if not setup['pid']: sys.stderr.write('Expected --pid to be passed.\n') sys.exit(1) return setup def main(setup): sys.path.append(os.path.dirname(__file__)) import add_code_to_python_process show_debug_info_on_target_process = 0 pydevd_dirname = os.path.dirname(os.path.dirname(__file__)) if sys.platform == 'win32': setup['pythonpath'] = pydevd_dirname.replace('\\', '/') setup['pythonpath2'] = os.path.dirname(__file__).replace('\\', '/') python_code = '''import sys; sys.path.append("%(pythonpath)s"); sys.path.append("%(pythonpath2)s"); import attach_script; attach_script.attach(port=%(port)s, host="%(host)s", protocol="%(protocol)s"); '''.replace('\r\n', '').replace('\r', '').replace('\n', '') else: setup['pythonpath'] = pydevd_dirname setup['pythonpath2'] = os.path.dirname(__file__) # We have to pass it a bit differently for gdb python_code = '''import sys; sys.path.append(\\\"%(pythonpath)s\\\"); sys.path.append(\\\"%(pythonpath2)s\\\"); import attach_script; attach_script.attach(port=%(port)s, host=\\\"%(host)s\\\", protocol=\\\"%(protocol)s\\\"); '''.replace('\r\n', '').replace('\r', '').replace('\n', '') python_code = python_code % setup add_code_to_python_process.run_python_code( setup['pid'], python_code, connect_debugger_tracing=True, show_debug_info=show_debug_info_on_target_process) if __name__ == '__main__': main(process_command_line(sys.argv[1:]))
2,255
Python
29.486486
116
0.55122
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_always_live_program.py
import sys import struct print('Executable: %s' % sys.executable) import os def loop_in_thread(): while True: import time time.sleep(.5) sys.stdout.write('#') sys.stdout.flush() import threading threading.Thread(target=loop_in_thread).start() def is_python_64bit(): return (struct.calcsize('P') == 8) print('Is 64: %s' % is_python_64bit()) if __name__ == '__main__': print('pid:%s' % (os.getpid())) i = 0 while True: i += 1 import time time.sleep(.5) sys.stdout.write('.') sys.stdout.flush() if i % 40 == 0: sys.stdout.write('\n') sys.stdout.flush()
679
Python
19.60606
47
0.540501
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Miscellaneous utility classes and functions. @group Helpers: PathOperations, MemoryAddresses, CustomAddressIterator, DataAddressIterator, ImageAddressIterator, MappedAddressIterator, ExecutableAddressIterator, ReadableAddressIterator, WriteableAddressIterator, ExecutableAndWriteableAddressIterator, DebugRegister, Regenerator, BannerHelpFormatter, StaticClass, classproperty """ __revision__ = "$Id$" __all__ = [ # Filename and pathname manipulation 'PathOperations', # Memory address operations 'MemoryAddresses', 'CustomAddressIterator', 'DataAddressIterator', 'ImageAddressIterator', 'MappedAddressIterator', 'ExecutableAddressIterator', 'ReadableAddressIterator', 'WriteableAddressIterator', 'ExecutableAndWriteableAddressIterator', # Debug registers manipulation 'DebugRegister', # Miscellaneous 'Regenerator', ] import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat #============================================================================== class classproperty(property): """ Class property method. Only works for getting properties, if you set them the symbol gets overwritten in the class namespace. Inspired on: U{http://stackoverflow.com/a/7864317/426293} """ def __init__(self, fget=None, fset=None, fdel=None, doc=""): if fset is not None or fdel is not None: raise NotImplementedError() super(classproperty, self).__init__(fget=classmethod(fget), doc=doc) def __get__(self, cls, owner): return self.fget.__get__(None, owner)() class BannerHelpFormatter(optparse.IndentedHelpFormatter): "Just a small tweak to optparse to be able to print a banner." def __init__(self, banner, *argv, **argd): self.banner = banner optparse.IndentedHelpFormatter.__init__(self, *argv, **argd) def format_usage(self, usage): msg = optparse.IndentedHelpFormatter.format_usage(self, usage) return '%s\n%s' % (self.banner, msg) # See Process.generate_memory_snapshot() class Regenerator(object): """ Calls a generator and iterates it. When it's finished iterating, the generator is called again. This allows you to iterate a generator more than once (well, sort of). """ def __init__(self, g_function, *v_args, **d_args): """ @type g_function: function @param g_function: Function that when called returns a generator. @type v_args: tuple @param v_args: Variable arguments to pass to the generator function. @type d_args: dict @param d_args: Variable arguments to pass to the generator function. """ self.__g_function = g_function self.__v_args = v_args self.__d_args = d_args self.__g_object = None def __iter__(self): 'x.__iter__() <==> iter(x)' return self def next(self): 'x.next() -> the next value, or raise StopIteration' if self.__g_object is None: self.__g_object = self.__g_function( *self.__v_args, **self.__d_args ) try: return self.__g_object.next() except StopIteration: self.__g_object = None raise class StaticClass (object): def __new__(cls, *argv, **argd): "Don't try to instance this class, just use the static methods." raise NotImplementedError( "Cannot instance static class %s" % cls.__name__) #============================================================================== class PathOperations (StaticClass): """ Static methods for filename and pathname manipulation. """ @staticmethod def path_is_relative(path): """ @see: L{path_is_absolute} @type path: str @param path: Absolute or relative path. @rtype: bool @return: C{True} if the path is relative, C{False} if it's absolute. """ return win32.PathIsRelative(path) @staticmethod def path_is_absolute(path): """ @see: L{path_is_relative} @type path: str @param path: Absolute or relative path. @rtype: bool @return: C{True} if the path is absolute, C{False} if it's relative. """ return not win32.PathIsRelative(path) @staticmethod def make_relative(path, current = None): """ @type path: str @param path: Absolute path. @type current: str @param current: (Optional) Path to the current directory. @rtype: str @return: Relative path. @raise WindowsError: It's impossible to make the path relative. This happens when the path and the current path are not on the same disk drive or network share. """ return win32.PathRelativePathTo(pszFrom = current, pszTo = path) @staticmethod def make_absolute(path): """ @type path: str @param path: Relative path. @rtype: str @return: Absolute path. """ return win32.GetFullPathName(path)[0] @staticmethod def split_extension(pathname): """ @type pathname: str @param pathname: Absolute path. @rtype: tuple( str, str ) @return: Tuple containing the file and extension components of the filename. """ filepart = win32.PathRemoveExtension(pathname) extpart = win32.PathFindExtension(pathname) return (filepart, extpart) @staticmethod def split_filename(pathname): """ @type pathname: str @param pathname: Absolute path. @rtype: tuple( str, str ) @return: Tuple containing the path to the file and the base filename. """ filepart = win32.PathFindFileName(pathname) pathpart = win32.PathRemoveFileSpec(pathname) return (pathpart, filepart) @staticmethod def split_path(path): """ @see: L{join_path} @type path: str @param path: Absolute or relative path. @rtype: list( str... ) @return: List of path components. """ components = list() while path: next = win32.PathFindNextComponent(path) if next: prev = path[ : -len(next) ] components.append(prev) path = next return components @staticmethod def join_path(*components): """ @see: L{split_path} @type components: tuple( str... ) @param components: Path components. @rtype: str @return: Absolute or relative path. """ if components: path = components[0] for next in components[1:]: path = win32.PathAppend(path, next) else: path = "" return path @staticmethod def native_to_win32_pathname(name): """ @type name: str @param name: Native (NT) absolute pathname. @rtype: str @return: Win32 absolute pathname. """ # XXX TODO # There are probably some native paths that # won't be converted by this naive approach. if name.startswith(compat.b("\\")): if name.startswith(compat.b("\\??\\")): name = name[4:] elif name.startswith(compat.b("\\SystemRoot\\")): system_root_path = os.environ['SYSTEMROOT'] if system_root_path.endswith('\\'): system_root_path = system_root_path[:-1] name = system_root_path + name[11:] else: for drive_number in compat.xrange(ord('A'), ord('Z') + 1): drive_letter = '%c:' % drive_number try: device_native_path = win32.QueryDosDevice(drive_letter) except WindowsError: e = sys.exc_info()[1] if e.winerror in (win32.ERROR_FILE_NOT_FOUND, \ win32.ERROR_PATH_NOT_FOUND): continue raise if not device_native_path.endswith(compat.b('\\')): device_native_path += compat.b('\\') if name.startswith(device_native_path): name = drive_letter + compat.b('\\') + \ name[ len(device_native_path) : ] break return name @staticmethod def pathname_to_filename(pathname): """ Equivalent to: C{PathOperations.split_filename(pathname)[0]} @note: This function is preserved for backwards compatibility with WinAppDbg 1.4 and earlier. It may be removed in future versions. @type pathname: str @param pathname: Absolute path to a file. @rtype: str @return: Filename component of the path. """ return win32.PathFindFileName(pathname) #============================================================================== class MemoryAddresses (StaticClass): """ Class to manipulate memory addresses. @type pageSize: int @cvar pageSize: Page size in bytes. Defaults to 0x1000 but it's automatically updated on runtime when importing the module. """ @classproperty def pageSize(cls): """ Try to get the pageSize value on runtime. """ try: try: pageSize = win32.GetSystemInfo().dwPageSize except WindowsError: pageSize = 0x1000 except NameError: pageSize = 0x1000 cls.pageSize = pageSize # now this function won't be called again return pageSize @classmethod def align_address_to_page_start(cls, address): """ Align the given address to the start of the page it occupies. @type address: int @param address: Memory address. @rtype: int @return: Aligned memory address. """ return address - ( address % cls.pageSize ) @classmethod def align_address_to_page_end(cls, address): """ Align the given address to the end of the page it occupies. That is, to point to the start of the next page. @type address: int @param address: Memory address. @rtype: int @return: Aligned memory address. """ return address + cls.pageSize - ( address % cls.pageSize ) @classmethod def align_address_range(cls, begin, end): """ Align the given address range to the start and end of the page(s) it occupies. @type begin: int @param begin: Memory address of the beginning of the buffer. Use C{None} for the first legal address in the address space. @type end: int @param end: Memory address of the end of the buffer. Use C{None} for the last legal address in the address space. @rtype: tuple( int, int ) @return: Aligned memory addresses. """ if begin is None: begin = 0 if end is None: end = win32.LPVOID(-1).value # XXX HACK if end < begin: begin, end = end, begin begin = cls.align_address_to_page_start(begin) if end != cls.align_address_to_page_start(end): end = cls.align_address_to_page_end(end) return (begin, end) @classmethod def get_buffer_size_in_pages(cls, address, size): """ Get the number of pages in use by the given buffer. @type address: int @param address: Aligned memory address. @type size: int @param size: Buffer size. @rtype: int @return: Buffer size in number of pages. """ if size < 0: size = -size address = address - size begin, end = cls.align_address_range(address, address + size) # XXX FIXME # I think this rounding fails at least for address 0xFFFFFFFF size 1 return int(float(end - begin) / float(cls.pageSize)) @staticmethod def do_ranges_intersect(begin, end, old_begin, old_end): """ Determine if the two given memory address ranges intersect. @type begin: int @param begin: Start address of the first range. @type end: int @param end: End address of the first range. @type old_begin: int @param old_begin: Start address of the second range. @type old_end: int @param old_end: End address of the second range. @rtype: bool @return: C{True} if the two ranges intersect, C{False} otherwise. """ return (old_begin <= begin < old_end) or \ (old_begin < end <= old_end) or \ (begin <= old_begin < end) or \ (begin < old_end <= end) #============================================================================== def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @type condition: function @param condition: Callback function that returns C{True} if the memory block should be returned, or C{False} if it should be filtered. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 def DataAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that contain data. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.has_content) def ImageAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that belong to executable images. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_image) def MappedAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that belong to memory mapped files. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_mapped) def ReadableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are readable. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_readable) def WriteableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are writeable. @note: Writeable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_writeable) def ExecutableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are executable. @note: Executable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_executable) def ExecutableAndWriteableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are executable and writeable. @note: The presence of such pages make memory corruption vulnerabilities much easier to exploit. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_executable_and_writeable) #============================================================================== try: _registerMask = win32.SIZE_T(-1).value except TypeError: if win32.SIZEOF(win32.SIZE_T) == 4: _registerMask = 0xFFFFFFFF elif win32.SIZEOF(win32.SIZE_T) == 8: _registerMask = 0xFFFFFFFFFFFFFFFF else: raise class DebugRegister (StaticClass): """ Class to manipulate debug registers. Used by L{HardwareBreakpoint}. @group Trigger flags used by HardwareBreakpoint: BREAK_ON_EXECUTION, BREAK_ON_WRITE, BREAK_ON_ACCESS, BREAK_ON_IO_ACCESS @group Size flags used by HardwareBreakpoint: WATCH_BYTE, WATCH_WORD, WATCH_DWORD, WATCH_QWORD @group Bitwise masks for Dr7: enableMask, disableMask, triggerMask, watchMask, clearMask, generalDetectMask @group Bitwise masks for Dr6: hitMask, hitMaskAll, debugAccessMask, singleStepMask, taskSwitchMask, clearDr6Mask, clearHitMask @group Debug control MSR definitions: DebugCtlMSR, LastBranchRecord, BranchTrapFlag, PinControl, LastBranchToIP, LastBranchFromIP, LastExceptionToIP, LastExceptionFromIP @type BREAK_ON_EXECUTION: int @cvar BREAK_ON_EXECUTION: Break on execution. @type BREAK_ON_WRITE: int @cvar BREAK_ON_WRITE: Break on write. @type BREAK_ON_ACCESS: int @cvar BREAK_ON_ACCESS: Break on read or write. @type BREAK_ON_IO_ACCESS: int @cvar BREAK_ON_IO_ACCESS: Break on I/O port access. Not supported by any hardware. @type WATCH_BYTE: int @cvar WATCH_BYTE: Watch a byte. @type WATCH_WORD: int @cvar WATCH_WORD: Watch a word. @type WATCH_DWORD: int @cvar WATCH_DWORD: Watch a double word. @type WATCH_QWORD: int @cvar WATCH_QWORD: Watch one quad word. @type enableMask: 4-tuple of integers @cvar enableMask: Enable bit on C{Dr7} for each slot. Works as a bitwise-OR mask. @type disableMask: 4-tuple of integers @cvar disableMask: Mask of the enable bit on C{Dr7} for each slot. Works as a bitwise-AND mask. @type triggerMask: 4-tuple of 2-tuples of integers @cvar triggerMask: Trigger bits on C{Dr7} for each trigger flag value. Each 2-tuple has the bitwise-OR mask and the bitwise-AND mask. @type watchMask: 4-tuple of 2-tuples of integers @cvar watchMask: Watch bits on C{Dr7} for each watch flag value. Each 2-tuple has the bitwise-OR mask and the bitwise-AND mask. @type clearMask: 4-tuple of integers @cvar clearMask: Mask of all important bits on C{Dr7} for each slot. Works as a bitwise-AND mask. @type generalDetectMask: integer @cvar generalDetectMask: General detect mode bit. It enables the processor to notify the debugger when the debugee is trying to access one of the debug registers. @type hitMask: 4-tuple of integers @cvar hitMask: Hit bit on C{Dr6} for each slot. Works as a bitwise-AND mask. @type hitMaskAll: integer @cvar hitMaskAll: Bitmask for all hit bits in C{Dr6}. Useful to know if at least one hardware breakpoint was hit, or to clear the hit bits only. @type clearHitMask: integer @cvar clearHitMask: Bitmask to clear all the hit bits in C{Dr6}. @type debugAccessMask: integer @cvar debugAccessMask: The debugee tried to access a debug register. Needs bit L{generalDetectMask} enabled in C{Dr7}. @type singleStepMask: integer @cvar singleStepMask: A single step exception was raised. Needs the trap flag enabled. @type taskSwitchMask: integer @cvar taskSwitchMask: A task switch has occurred. Needs the TSS T-bit set to 1. @type clearDr6Mask: integer @cvar clearDr6Mask: Bitmask to clear all meaningful bits in C{Dr6}. """ BREAK_ON_EXECUTION = 0 BREAK_ON_WRITE = 1 BREAK_ON_ACCESS = 3 BREAK_ON_IO_ACCESS = 2 WATCH_BYTE = 0 WATCH_WORD = 1 WATCH_DWORD = 3 WATCH_QWORD = 2 registerMask = _registerMask #------------------------------------------------------------------------------ ########################################################################### # http://en.wikipedia.org/wiki/Debug_register # # DR7 - Debug control # # The low-order eight bits of DR7 (0,2,4,6 and 1,3,5,7) selectively enable # the four address breakpoint conditions. There are two levels of enabling: # the local (0,2,4,6) and global (1,3,5,7) levels. The local enable bits # are automatically reset by the processor at every task switch to avoid # unwanted breakpoint conditions in the new task. The global enable bits # are not reset by a task switch; therefore, they can be used for # conditions that are global to all tasks. # # Bits 16-17 (DR0), 20-21 (DR1), 24-25 (DR2), 28-29 (DR3), define when # breakpoints trigger. Each breakpoint has a two-bit entry that specifies # whether they break on execution (00b), data write (01b), data read or # write (11b). 10b is defined to mean break on IO read or write but no # hardware supports it. Bits 18-19 (DR0), 22-23 (DR1), 26-27 (DR2), 30-31 # (DR3), define how large area of memory is watched by breakpoints. Again # each breakpoint has a two-bit entry that specifies whether they watch # one (00b), two (01b), eight (10b) or four (11b) bytes. ########################################################################### # Dr7 |= enableMask[register] enableMask = ( 1 << 0, # Dr0 (bit 0) 1 << 2, # Dr1 (bit 2) 1 << 4, # Dr2 (bit 4) 1 << 6, # Dr3 (bit 6) ) # Dr7 &= disableMask[register] disableMask = tuple( [_registerMask ^ x for x in enableMask] ) # The registerMask from the class is not there in py3 try: del x # It's not there in py3 except: pass # orMask, andMask = triggerMask[register][trigger] # Dr7 = (Dr7 & andMask) | orMask # to set # Dr7 = Dr7 & andMask # to remove triggerMask = ( # Dr0 (bits 16-17) ( ((0 << 16), (3 << 16) ^ registerMask), # execute ((1 << 16), (3 << 16) ^ registerMask), # write ((2 << 16), (3 << 16) ^ registerMask), # io read ((3 << 16), (3 << 16) ^ registerMask), # access ), # Dr1 (bits 20-21) ( ((0 << 20), (3 << 20) ^ registerMask), # execute ((1 << 20), (3 << 20) ^ registerMask), # write ((2 << 20), (3 << 20) ^ registerMask), # io read ((3 << 20), (3 << 20) ^ registerMask), # access ), # Dr2 (bits 24-25) ( ((0 << 24), (3 << 24) ^ registerMask), # execute ((1 << 24), (3 << 24) ^ registerMask), # write ((2 << 24), (3 << 24) ^ registerMask), # io read ((3 << 24), (3 << 24) ^ registerMask), # access ), # Dr3 (bits 28-29) ( ((0 << 28), (3 << 28) ^ registerMask), # execute ((1 << 28), (3 << 28) ^ registerMask), # write ((2 << 28), (3 << 28) ^ registerMask), # io read ((3 << 28), (3 << 28) ^ registerMask), # access ), ) # orMask, andMask = watchMask[register][watch] # Dr7 = (Dr7 & andMask) | orMask # to set # Dr7 = Dr7 & andMask # to remove watchMask = ( # Dr0 (bits 18-19) ( ((0 << 18), (3 << 18) ^ registerMask), # byte ((1 << 18), (3 << 18) ^ registerMask), # word ((2 << 18), (3 << 18) ^ registerMask), # qword ((3 << 18), (3 << 18) ^ registerMask), # dword ), # Dr1 (bits 22-23) ( ((0 << 23), (3 << 23) ^ registerMask), # byte ((1 << 23), (3 << 23) ^ registerMask), # word ((2 << 23), (3 << 23) ^ registerMask), # qword ((3 << 23), (3 << 23) ^ registerMask), # dword ), # Dr2 (bits 26-27) ( ((0 << 26), (3 << 26) ^ registerMask), # byte ((1 << 26), (3 << 26) ^ registerMask), # word ((2 << 26), (3 << 26) ^ registerMask), # qword ((3 << 26), (3 << 26) ^ registerMask), # dword ), # Dr3 (bits 30-31) ( ((0 << 30), (3 << 31) ^ registerMask), # byte ((1 << 30), (3 << 31) ^ registerMask), # word ((2 << 30), (3 << 31) ^ registerMask), # qword ((3 << 30), (3 << 31) ^ registerMask), # dword ), ) # Dr7 = Dr7 & clearMask[register] clearMask = ( registerMask ^ ( (1 << 0) + (3 << 16) + (3 << 18) ), # Dr0 registerMask ^ ( (1 << 2) + (3 << 20) + (3 << 22) ), # Dr1 registerMask ^ ( (1 << 4) + (3 << 24) + (3 << 26) ), # Dr2 registerMask ^ ( (1 << 6) + (3 << 28) + (3 << 30) ), # Dr3 ) # Dr7 = Dr7 | generalDetectMask generalDetectMask = (1 << 13) ########################################################################### # http://en.wikipedia.org/wiki/Debug_register # # DR6 - Debug status # # The debug status register permits the debugger to determine which debug # conditions have occurred. When the processor detects an enabled debug # exception, it sets the low-order bits of this register (0,1,2,3) before # entering the debug exception handler. # # Note that the bits of DR6 are never cleared by the processor. To avoid # any confusion in identifying the next debug exception, the debug handler # should move zeros to DR6 immediately before returning. ########################################################################### # bool(Dr6 & hitMask[register]) hitMask = ( (1 << 0), # Dr0 (1 << 1), # Dr1 (1 << 2), # Dr2 (1 << 3), # Dr3 ) # bool(Dr6 & anyHitMask) hitMaskAll = hitMask[0] | hitMask[1] | hitMask[2] | hitMask[3] # Dr6 = Dr6 & clearHitMask clearHitMask = registerMask ^ hitMaskAll # bool(Dr6 & debugAccessMask) debugAccessMask = (1 << 13) # bool(Dr6 & singleStepMask) singleStepMask = (1 << 14) # bool(Dr6 & taskSwitchMask) taskSwitchMask = (1 << 15) # Dr6 = Dr6 & clearDr6Mask clearDr6Mask = registerMask ^ (hitMaskAll | \ debugAccessMask | singleStepMask | taskSwitchMask) #------------------------------------------------------------------------------ ############################################################################### # # (from the AMD64 manuals) # # The fields within the DebugCtlMSR register are: # # Last-Branch Record (LBR) - Bit 0, read/write. Software sets this bit to 1 # to cause the processor to record the source and target addresses of the # last control transfer taken before a debug exception occurs. The recorded # control transfers include branch instructions, interrupts, and exceptions. # # Branch Single Step (BTF) - Bit 1, read/write. Software uses this bit to # change the behavior of the rFLAGS.TF bit. When this bit is cleared to 0, # the rFLAGS.TF bit controls instruction single stepping, (normal behavior). # When this bit is set to 1, the rFLAGS.TF bit controls single stepping on # control transfers. The single-stepped control transfers include branch # instructions, interrupts, and exceptions. Control-transfer single stepping # requires both BTF=1 and rFLAGS.TF=1. # # Performance-Monitoring/Breakpoint Pin-Control (PBi) - Bits 5-2, read/write. # Software uses these bits to control the type of information reported by # the four external performance-monitoring/breakpoint pins on the processor. # When a PBi bit is cleared to 0, the corresponding external pin (BPi) # reports performance-monitor information. When a PBi bit is set to 1, the # corresponding external pin (BPi) reports breakpoint information. # # All remaining bits in the DebugCtlMSR register are reserved. # # Software can enable control-transfer single stepping by setting # DebugCtlMSR.BTF to 1 and rFLAGS.TF to 1. The processor automatically # disables control-transfer single stepping when a debug exception (#DB) # occurs by clearing DebugCtlMSR.BTF to 0. rFLAGS.TF is also cleared when a # #DB exception occurs. Before exiting the debug-exception handler, software # must set both DebugCtlMSR.BTF and rFLAGS.TF to 1 to restart single # stepping. # ############################################################################### DebugCtlMSR = 0x1D9 LastBranchRecord = (1 << 0) BranchTrapFlag = (1 << 1) PinControl = ( (1 << 2), # PB1 (1 << 3), # PB2 (1 << 4), # PB3 (1 << 5), # PB4 ) ############################################################################### # # (from the AMD64 manuals) # # Control-transfer recording MSRs: LastBranchToIP, LastBranchFromIP, # LastExceptionToIP, and LastExceptionFromIP. These registers are loaded # automatically by the processor when the DebugCtlMSR.LBR bit is set to 1. # These MSRs are read-only. # # The processor automatically disables control-transfer recording when a # debug exception (#DB) occurs by clearing DebugCtlMSR.LBR to 0. The # contents of the control-transfer recording MSRs are not altered by the # processor when the #DB occurs. Before exiting the debug-exception handler, # software can set DebugCtlMSR.LBR to 1 to re-enable the recording mechanism. # ############################################################################### LastBranchToIP = 0x1DC LastBranchFromIP = 0x1DB LastExceptionToIP = 0x1DE LastExceptionFromIP = 0x1DD #------------------------------------------------------------------------------ @classmethod def clear_bp(cls, ctx, register): """ Clears a hardware breakpoint. @see: find_slot, set_bp @type ctx: dict( str S{->} int ) @param ctx: Thread context dictionary. @type register: int @param register: Slot (debug register) for hardware breakpoint. """ ctx['Dr7'] &= cls.clearMask[register] ctx['Dr%d' % register] = 0 @classmethod def set_bp(cls, ctx, register, address, trigger, watch): """ Sets a hardware breakpoint. @see: clear_bp, find_slot @type ctx: dict( str S{->} int ) @param ctx: Thread context dictionary. @type register: int @param register: Slot (debug register). @type address: int @param address: Memory address. @type trigger: int @param trigger: Trigger flag. See L{HardwareBreakpoint.validTriggers}. @type watch: int @param watch: Watch flag. See L{HardwareBreakpoint.validWatchSizes}. """ Dr7 = ctx['Dr7'] Dr7 |= cls.enableMask[register] orMask, andMask = cls.triggerMask[register][trigger] Dr7 &= andMask Dr7 |= orMask orMask, andMask = cls.watchMask[register][watch] Dr7 &= andMask Dr7 |= orMask ctx['Dr7'] = Dr7 ctx['Dr%d' % register] = address @classmethod def find_slot(cls, ctx): """ Finds an empty slot to set a hardware breakpoint. @see: clear_bp, set_bp @type ctx: dict( str S{->} int ) @param ctx: Thread context dictionary. @rtype: int @return: Slot (debug register) for hardware breakpoint. """ Dr7 = ctx['Dr7'] slot = 0 for m in cls.enableMask: if (Dr7 & m) == 0: return slot slot += 1 return None
36,223
Python
33.864293
120
0.585208
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/module.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Module instrumentation. @group Instrumentation: Module @group Warnings: DebugSymbolsWarning """ from __future__ import with_statement __revision__ = "$Id$" __all__ = ['Module', 'DebugSymbolsWarning'] import sys from winappdbg import win32 from winappdbg import compat from winappdbg.textio import HexInput, HexDump from winappdbg.util import PathOperations # delayed imports Process = None import os import warnings import traceback #============================================================================== class DebugSymbolsWarning (UserWarning): """ This warning is issued if the support for debug symbols isn't working properly. """ #============================================================================== class Module (object): """ Interface to a DLL library loaded in the context of another process. @group Properties: get_base, get_filename, get_name, get_size, get_entry_point, get_process, set_process, get_pid, get_handle, set_handle, open_handle, close_handle @group Labels: get_label, get_label_at_address, is_address_here, resolve, resolve_label, match_name @group Symbols: load_symbols, unload_symbols, get_symbols, iter_symbols, resolve_symbol, get_symbol_at_address @group Modules snapshot: clear @type unknown: str @cvar unknown: Suggested tag for unknown modules. @type lpBaseOfDll: int @ivar lpBaseOfDll: Base of DLL module. Use L{get_base} instead. @type hFile: L{FileHandle} @ivar hFile: Handle to the module file. Use L{get_handle} instead. @type fileName: str @ivar fileName: Module filename. Use L{get_filename} instead. @type SizeOfImage: int @ivar SizeOfImage: Size of the module. Use L{get_size} instead. @type EntryPoint: int @ivar EntryPoint: Entry point of the module. Use L{get_entry_point} instead. @type process: L{Process} @ivar process: Process where the module is loaded. Use the L{get_process} method instead. """ unknown = '<unknown>' class _SymbolEnumerator (object): """ Internally used by L{Module} to enumerate symbols in a module. """ def __init__(self, undecorate = False): self.symbols = list() self.undecorate = undecorate def __call__(self, SymbolName, SymbolAddress, SymbolSize, UserContext): """ Callback that receives symbols and stores them in a Python list. """ if self.undecorate: try: SymbolName = win32.UnDecorateSymbolName(SymbolName) except Exception: pass # not all symbols are decorated! self.symbols.append( (SymbolName, SymbolAddress, SymbolSize) ) return win32.TRUE def __init__(self, lpBaseOfDll, hFile = None, fileName = None, SizeOfImage = None, EntryPoint = None, process = None): """ @type lpBaseOfDll: str @param lpBaseOfDll: Base address of the module. @type hFile: L{FileHandle} @param hFile: (Optional) Handle to the module file. @type fileName: str @param fileName: (Optional) Module filename. @type SizeOfImage: int @param SizeOfImage: (Optional) Size of the module. @type EntryPoint: int @param EntryPoint: (Optional) Entry point of the module. @type process: L{Process} @param process: (Optional) Process where the module is loaded. """ self.lpBaseOfDll = lpBaseOfDll self.fileName = fileName self.SizeOfImage = SizeOfImage self.EntryPoint = EntryPoint self.__symbols = list() self.set_handle(hFile) self.set_process(process) # Not really sure if it's a good idea... ## def __eq__(self, aModule): ## """ ## Compare two Module objects. The comparison is made using the process ## IDs and the module bases. ## ## @type aModule: L{Module} ## @param aModule: Another Module object. ## ## @rtype: bool ## @return: C{True} if the two process IDs and module bases are equal, ## C{False} otherwise. ## """ ## return isinstance(aModule, Module) and \ ## self.get_pid() == aModule.get_pid() and \ ## self.get_base() == aModule.get_base() def get_handle(self): """ @rtype: L{Handle} @return: File handle. Returns C{None} if unknown. """ # no way to guess! return self.__hFile def set_handle(self, hFile): """ @type hFile: L{Handle} @param hFile: File handle. Use C{None} to clear. """ if hFile == win32.INVALID_HANDLE_VALUE: hFile = None self.__hFile = hFile hFile = property(get_handle, set_handle, doc="") def get_process(self): """ @rtype: L{Process} @return: Parent Process object. Returns C{None} if unknown. """ # no way to guess! return self.__process def set_process(self, process = None): """ Manually set the parent process. Use with care! @type process: L{Process} @param process: (Optional) Process object. Use C{None} for no process. """ if process is None: self.__process = None else: global Process # delayed import if Process is None: from winappdbg.process import Process if not isinstance(process, Process): msg = "Parent process must be a Process instance, " msg += "got %s instead" % type(process) raise TypeError(msg) self.__process = process process = property(get_process, set_process, doc="") def get_pid(self): """ @rtype: int or None @return: Parent process global ID. Returns C{None} on error. """ process = self.get_process() if process is not None: return process.get_pid() def get_base(self): """ @rtype: int or None @return: Base address of the module. Returns C{None} if unknown. """ return self.lpBaseOfDll def get_size(self): """ @rtype: int or None @return: Base size of the module. Returns C{None} if unknown. """ if not self.SizeOfImage: self.__get_size_and_entry_point() return self.SizeOfImage def get_entry_point(self): """ @rtype: int or None @return: Entry point of the module. Returns C{None} if unknown. """ if not self.EntryPoint: self.__get_size_and_entry_point() return self.EntryPoint def __get_size_and_entry_point(self): "Get the size and entry point of the module using the Win32 API." process = self.get_process() if process: try: handle = process.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) base = self.get_base() mi = win32.GetModuleInformation(handle, base) self.SizeOfImage = mi.SizeOfImage self.EntryPoint = mi.EntryPoint except WindowsError: e = sys.exc_info()[1] warnings.warn( "Cannot get size and entry point of module %s, reason: %s"\ % (self.get_name(), e.strerror), RuntimeWarning) def get_filename(self): """ @rtype: str or None @return: Module filename. Returns C{None} if unknown. """ if self.fileName is None: if self.hFile not in (None, win32.INVALID_HANDLE_VALUE): fileName = self.hFile.get_filename() if fileName: fileName = PathOperations.native_to_win32_pathname(fileName) self.fileName = fileName return self.fileName def __filename_to_modname(self, pathname): """ @type pathname: str @param pathname: Pathname to a module. @rtype: str @return: Module name. """ filename = PathOperations.pathname_to_filename(pathname) if filename: filename = filename.lower() filepart, extpart = PathOperations.split_extension(filename) if filepart and extpart: modName = filepart else: modName = filename else: modName = pathname return modName def get_name(self): """ @rtype: str @return: Module name, as used in labels. @warning: Names are B{NOT} guaranteed to be unique. If you need unique identification for a loaded module, use the base address instead. @see: L{get_label} """ pathname = self.get_filename() if pathname: modName = self.__filename_to_modname(pathname) if isinstance(modName, compat.unicode): try: modName = modName.encode('cp1252') except UnicodeEncodeError: e = sys.exc_info()[1] warnings.warn(str(e)) else: modName = "0x%x" % self.get_base() return modName def match_name(self, name): """ @rtype: bool @return: C{True} if the given name could refer to this module. It may not be exactly the same returned by L{get_name}. """ # If the given name is exactly our name, return True. # Comparison is case insensitive. my_name = self.get_name().lower() if name.lower() == my_name: return True # If the given name is a base address, compare it with ours. try: base = HexInput.integer(name) except ValueError: base = None if base is not None and base == self.get_base(): return True # If the given name is a filename, convert it to a module name. # Then compare it with ours, case insensitive. modName = self.__filename_to_modname(name) if modName.lower() == my_name: return True # No match. return False #------------------------------------------------------------------------------ def open_handle(self): """ Opens a new handle to the module. The new handle is stored in the L{hFile} property. """ if not self.get_filename(): msg = "Cannot retrieve filename for module at %s" msg = msg % HexDump.address( self.get_base() ) raise Exception(msg) hFile = win32.CreateFile(self.get_filename(), dwShareMode = win32.FILE_SHARE_READ, dwCreationDisposition = win32.OPEN_EXISTING) # In case hFile was set to an actual handle value instead of a Handle # object. This shouldn't happen unless the user tinkered with hFile. if not hasattr(self.hFile, '__del__'): self.close_handle() self.hFile = hFile def close_handle(self): """ Closes the handle to the module. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. So unless you've been tinkering with it, setting L{hFile} to C{None} should be enough. """ try: if hasattr(self.hFile, 'close'): self.hFile.close() elif self.hFile not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hFile) finally: self.hFile = None def get_handle(self): """ @rtype: L{FileHandle} @return: Handle to the module file. """ if self.hFile in (None, win32.INVALID_HANDLE_VALUE): self.open_handle() return self.hFile def clear(self): """ Clears the resources held by this object. """ try: self.set_process(None) finally: self.close_handle() #------------------------------------------------------------------------------ # XXX FIXME # I've been told sometimes the debugging symbols APIs don't correctly # handle redirected exports (for example ws2_32!recv). # I haven't been able to reproduce the bug yet. def load_symbols(self): """ Loads the debugging symbols for a module. Automatically called by L{get_symbols}. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_process().get_handle(dwAccess) hFile = self.hFile BaseOfDll = self.get_base() SizeOfDll = self.get_size() Enumerator = self._SymbolEnumerator() try: win32.SymInitialize(hProcess) SymOptions = win32.SymGetOptions() SymOptions |= ( win32.SYMOPT_ALLOW_ZERO_ADDRESS | win32.SYMOPT_CASE_INSENSITIVE | win32.SYMOPT_FAVOR_COMPRESSED | win32.SYMOPT_INCLUDE_32BIT_MODULES | win32.SYMOPT_UNDNAME ) SymOptions &= ~( win32.SYMOPT_LOAD_LINES | win32.SYMOPT_NO_IMAGE_SEARCH | win32.SYMOPT_NO_CPP | win32.SYMOPT_IGNORE_NT_SYMPATH ) win32.SymSetOptions(SymOptions) try: win32.SymSetOptions( SymOptions | win32.SYMOPT_ALLOW_ABSOLUTE_SYMBOLS) except WindowsError: pass try: try: success = win32.SymLoadModule64( hProcess, hFile, None, None, BaseOfDll, SizeOfDll) except WindowsError: success = 0 if not success: ImageName = self.get_filename() success = win32.SymLoadModule64( hProcess, None, ImageName, None, BaseOfDll, SizeOfDll) if success: try: win32.SymEnumerateSymbols64( hProcess, BaseOfDll, Enumerator) finally: win32.SymUnloadModule64(hProcess, BaseOfDll) finally: win32.SymCleanup(hProcess) except WindowsError: e = sys.exc_info()[1] msg = "Cannot load debug symbols for process ID %d, reason:\n%s" msg = msg % (self.get_pid(), traceback.format_exc(e)) warnings.warn(msg, DebugSymbolsWarning) self.__symbols = Enumerator.symbols def unload_symbols(self): """ Unloads the debugging symbols for a module. """ self.__symbols = list() def get_symbols(self): """ Returns the debugging symbols for a module. The symbols are automatically loaded when needed. @rtype: list of tuple( str, int, int ) @return: List of symbols. Each symbol is represented by a tuple that contains: - Symbol name - Symbol memory address - Symbol size in bytes """ if not self.__symbols: self.load_symbols() return list(self.__symbols) def iter_symbols(self): """ Returns an iterator for the debugging symbols in a module, in no particular order. The symbols are automatically loaded when needed. @rtype: iterator of tuple( str, int, int ) @return: Iterator of symbols. Each symbol is represented by a tuple that contains: - Symbol name - Symbol memory address - Symbol size in bytes """ if not self.__symbols: self.load_symbols() return self.__symbols.__iter__() def resolve_symbol(self, symbol, bCaseSensitive = False): """ Resolves a debugging symbol's address. @type symbol: str @param symbol: Name of the symbol to resolve. @type bCaseSensitive: bool @param bCaseSensitive: C{True} for case sensitive matches, C{False} for case insensitive. @rtype: int or None @return: Memory address of symbol. C{None} if not found. """ if bCaseSensitive: for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if symbol == SymbolName: return SymbolAddress for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): try: SymbolName = win32.UnDecorateSymbolName(SymbolName) except Exception: continue if symbol == SymbolName: return SymbolAddress else: symbol = symbol.lower() for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if symbol == SymbolName.lower(): return SymbolAddress for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): try: SymbolName = win32.UnDecorateSymbolName(SymbolName) except Exception: continue if symbol == SymbolName.lower(): return SymbolAddress def get_symbol_at_address(self, address): """ Tries to find the closest matching symbol for the given address. @type address: int @param address: Memory address to query. @rtype: None or tuple( str, int, int ) @return: Returns a tuple consisting of: - Name - Address - Size (in bytes) Returns C{None} if no symbol could be matched. """ found = None for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if SymbolAddress > address: continue if SymbolAddress + SymbolSize > address: if not found or found[1] < SymbolAddress: found = (SymbolName, SymbolAddress, SymbolSize) return found #------------------------------------------------------------------------------ def get_label(self, function = None, offset = None): """ Retrieves the label for the given function of this module or the module base address if no function name is given. @type function: str @param function: (Optional) Exported function name. @type offset: int @param offset: (Optional) Offset from the module base address. @rtype: str @return: Label for the module base address, plus the offset if given. """ return _ModuleContainer.parse_label(self.get_name(), function, offset) def get_label_at_address(self, address, offset = None): """ Creates a label from the given memory address. If the address belongs to the module, the label is made relative to it's base address. @type address: int @param address: Memory address. @type offset: None or int @param offset: (Optional) Offset value. @rtype: str @return: Label pointing to the given address. """ # Add the offset to the address. if offset: address = address + offset # Make the label relative to the base address if no match is found. module = self.get_name() function = None offset = address - self.get_base() # Make the label relative to the entrypoint if no other match is found. # Skip if the entry point is unknown. start = self.get_entry_point() if start and start <= address: function = "start" offset = address - start # Enumerate exported functions and debug symbols, # then find the closest match, if possible. try: symbol = self.get_symbol_at_address(address) if symbol: (SymbolName, SymbolAddress, SymbolSize) = symbol new_offset = address - SymbolAddress if new_offset <= offset: function = SymbolName offset = new_offset except WindowsError: pass # Parse the label and return it. return _ModuleContainer.parse_label(module, function, offset) def is_address_here(self, address): """ Tries to determine if the given address belongs to this module. @type address: int @param address: Memory address. @rtype: bool or None @return: C{True} if the address belongs to the module, C{False} if it doesn't, and C{None} if it can't be determined. """ base = self.get_base() size = self.get_size() if base and size: return base <= address < (base + size) return None def resolve(self, function): """ Resolves a function exported by this module. @type function: str or int @param function: str: Name of the function. int: Ordinal of the function. @rtype: int @return: Memory address of the exported function in the process. Returns None on error. """ # Unknown DLL filename, there's nothing we can do. filename = self.get_filename() if not filename: return None # If the DLL is already mapped locally, resolve the function. try: hlib = win32.GetModuleHandle(filename) address = win32.GetProcAddress(hlib, function) except WindowsError: # Load the DLL locally, resolve the function and unload it. try: hlib = win32.LoadLibraryEx(filename, win32.DONT_RESOLVE_DLL_REFERENCES) try: address = win32.GetProcAddress(hlib, function) finally: win32.FreeLibrary(hlib) except WindowsError: return None # A NULL pointer means the function was not found. if address in (None, 0): return None # Compensate for DLL base relocations locally and remotely. return address - hlib + self.lpBaseOfDll def resolve_label(self, label): """ Resolves a label for this module only. If the label refers to another module, an exception is raised. @type label: str @param label: Label to resolve. @rtype: int @return: Memory address pointed to by the label. @raise ValueError: The label is malformed or impossible to resolve. @raise RuntimeError: Cannot resolve the module or function. """ # Split the label into it's components. # Use the fuzzy mode whenever possible. aProcess = self.get_process() if aProcess is not None: (module, procedure, offset) = aProcess.split_label(label) else: (module, procedure, offset) = _ModuleContainer.split_label(label) # If a module name is given that doesn't match ours, # raise an exception. if module and not self.match_name(module): raise RuntimeError("Label does not belong to this module") # Resolve the procedure if given. if procedure: address = self.resolve(procedure) if address is None: # If it's a debug symbol, use the symbol. address = self.resolve_symbol(procedure) # If it's the keyword "start" use the entry point. if address is None and procedure == "start": address = self.get_entry_point() # The procedure was not found. if address is None: if not module: module = self.get_name() msg = "Can't find procedure %s in module %s" raise RuntimeError(msg % (procedure, module)) # If no procedure is given use the base address of the module. else: address = self.get_base() # Add the offset if given and return the resolved address. if offset: address = address + offset return address #============================================================================== # TODO # An alternative approach to the toolhelp32 snapshots: parsing the PEB and # fetching the list of loaded modules from there. That would solve the problem # of toolhelp32 not working when the process hasn't finished initializing. # See: http://pferrie.host22.com/misc/lowlevel3.htm class _ModuleContainer (object): """ Encapsulates the capability to contain Module objects. @note: Labels are an approximated way of referencing memory locations across different executions of the same process, or different processes with common modules. They are not meant to be perfectly unique, and some errors may occur when multiple modules with the same name are loaded, or when module filenames can't be retrieved. @group Modules snapshot: scan_modules, get_module, get_module_bases, get_module_count, get_module_at_address, get_module_by_name, has_module, iter_modules, iter_module_addresses, clear_modules @group Labels: parse_label, split_label, sanitize_label, resolve_label, resolve_label_components, get_label_at_address, split_label_strict, split_label_fuzzy @group Symbols: load_symbols, unload_symbols, get_symbols, iter_symbols, resolve_symbol, get_symbol_at_address @group Debugging: is_system_defined_breakpoint, get_system_breakpoint, get_user_breakpoint, get_breakin_breakpoint, get_wow64_system_breakpoint, get_wow64_user_breakpoint, get_wow64_breakin_breakpoint, get_break_on_error_ptr """ def __init__(self): self.__moduleDict = dict() self.__system_breakpoints = dict() # Replace split_label with the fuzzy version on object instances. self.split_label = self.__use_fuzzy_mode def __initialize_snapshot(self): """ Private method to automatically initialize the snapshot when you try to use it without calling any of the scan_* methods first. You don't need to call this yourself. """ if not self.__moduleDict: try: self.scan_modules() except WindowsError: pass def __contains__(self, anObject): """ @type anObject: L{Module}, int @param anObject: - C{Module}: Module object to look for. - C{int}: Base address of the DLL to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Module} object with the same base address. """ if isinstance(anObject, Module): anObject = anObject.lpBaseOfDll return self.has_module(anObject) def __iter__(self): """ @see: L{iter_modules} @rtype: dictionary-valueiterator @return: Iterator of L{Module} objects in this snapshot. """ return self.iter_modules() def __len__(self): """ @see: L{get_module_count} @rtype: int @return: Count of L{Module} objects in this snapshot. """ return self.get_module_count() def has_module(self, lpBaseOfDll): """ @type lpBaseOfDll: int @param lpBaseOfDll: Base address of the DLL to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Module} object with the given base address. """ self.__initialize_snapshot() return lpBaseOfDll in self.__moduleDict def get_module(self, lpBaseOfDll): """ @type lpBaseOfDll: int @param lpBaseOfDll: Base address of the DLL to look for. @rtype: L{Module} @return: Module object with the given base address. """ self.__initialize_snapshot() if lpBaseOfDll not in self.__moduleDict: msg = "Unknown DLL base address %s" msg = msg % HexDump.address(lpBaseOfDll) raise KeyError(msg) return self.__moduleDict[lpBaseOfDll] def iter_module_addresses(self): """ @see: L{iter_modules} @rtype: dictionary-keyiterator @return: Iterator of DLL base addresses in this snapshot. """ self.__initialize_snapshot() return compat.iterkeys(self.__moduleDict) def iter_modules(self): """ @see: L{iter_module_addresses} @rtype: dictionary-valueiterator @return: Iterator of L{Module} objects in this snapshot. """ self.__initialize_snapshot() return compat.itervalues(self.__moduleDict) def get_module_bases(self): """ @see: L{iter_module_addresses} @rtype: list( int... ) @return: List of DLL base addresses in this snapshot. """ self.__initialize_snapshot() return compat.keys(self.__moduleDict) def get_module_count(self): """ @rtype: int @return: Count of L{Module} objects in this snapshot. """ self.__initialize_snapshot() return len(self.__moduleDict) #------------------------------------------------------------------------------ def get_module_by_name(self, modName): """ @type modName: int @param modName: Name of the module to look for, as returned by L{Module.get_name}. If two or more modules with the same name are loaded, only one of the matching modules is returned. You can also pass a full pathname to the DLL file. This works correctly even if two modules with the same name are loaded from different paths. @rtype: L{Module} @return: C{Module} object that best matches the given name. Returns C{None} if no C{Module} can be found. """ # Convert modName to lowercase. # This helps make case insensitive string comparisons. modName = modName.lower() # modName is an absolute pathname. if PathOperations.path_is_absolute(modName): for lib in self.iter_modules(): if modName == lib.get_filename().lower(): return lib return None # Stop trying to match the name. # Get all the module names. # This prevents having to iterate through the module list # more than once. modDict = [ ( lib.get_name(), lib ) for lib in self.iter_modules() ] modDict = dict(modDict) # modName is a base filename. if modName in modDict: return modDict[modName] # modName is a base filename without extension. filepart, extpart = PathOperations.split_extension(modName) if filepart and extpart: if filepart in modDict: return modDict[filepart] # modName is a base address. try: baseAddress = HexInput.integer(modName) except ValueError: return None if self.has_module(baseAddress): return self.get_module(baseAddress) # Module not found. return None def get_module_at_address(self, address): """ @type address: int @param address: Memory address to query. @rtype: L{Module} @return: C{Module} object that best matches the given address. Returns C{None} if no C{Module} can be found. """ bases = self.get_module_bases() bases.sort() bases.append(long(0x10000000000000000)) # max. 64 bit address + 1 if address >= bases[0]: i = 0 max_i = len(bases) - 1 while i < max_i: begin, end = bases[i:i+2] if begin <= address < end: module = self.get_module(begin) here = module.is_address_here(address) if here is False: break else: # True or None return module i = i + 1 return None # XXX this method musn't end up calling __initialize_snapshot by accident! def scan_modules(self): """ Populates the snapshot with loaded modules. """ # The module filenames may be spoofed by malware, # since this information resides in usermode space. # See: http://www.ragestorm.net/blogs/?p=163 # Ignore special process IDs. # PID 0: System Idle Process. Also has a special meaning to the # toolhelp APIs (current process). # PID 4: System Integrity Group. See this forum post for more info: # http://tinyurl.com/ycza8jo # (points to social.technet.microsoft.com) # Only on XP and above # PID 8: System (?) only in Windows 2000 and below AFAIK. # It's probably the same as PID 4 in XP and above. dwProcessId = self.get_pid() if dwProcessId in (0, 4, 8): return # It would seem easier to clear the snapshot first. # But then all open handles would be closed. found_bases = set() with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPMODULE, dwProcessId) as hSnapshot: me = win32.Module32First(hSnapshot) while me is not None: lpBaseAddress = me.modBaseAddr fileName = me.szExePath # full pathname if not fileName: fileName = me.szModule # filename only if not fileName: fileName = None else: fileName = PathOperations.native_to_win32_pathname(fileName) found_bases.add(lpBaseAddress) ## if not self.has_module(lpBaseAddress): # XXX triggers a scan if lpBaseAddress not in self.__moduleDict: aModule = Module(lpBaseAddress, fileName = fileName, SizeOfImage = me.modBaseSize, process = self) self._add_module(aModule) else: aModule = self.get_module(lpBaseAddress) if not aModule.fileName: aModule.fileName = fileName if not aModule.SizeOfImage: aModule.SizeOfImage = me.modBaseSize if not aModule.process: aModule.process = self me = win32.Module32Next(hSnapshot) ## for base in self.get_module_bases(): # XXX triggers a scan for base in compat.keys(self.__moduleDict): if base not in found_bases: self._del_module(base) def clear_modules(self): """ Clears the modules snapshot. """ for aModule in compat.itervalues(self.__moduleDict): aModule.clear() self.__moduleDict = dict() #------------------------------------------------------------------------------ @staticmethod def parse_label(module = None, function = None, offset = None): """ Creates a label from a module and a function name, plus an offset. @warning: This method only creates the label, it doesn't make sure the label actually points to a valid memory location. @type module: None or str @param module: (Optional) Module name. @type function: None, str or int @param function: (Optional) Function name or ordinal. @type offset: None or int @param offset: (Optional) Offset value. If C{function} is specified, offset from the function. If C{function} is C{None}, offset from the module. @rtype: str @return: Label representing the given function in the given module. @raise ValueError: The module or function name contain invalid characters. """ # TODO # Invalid characters should be escaped or filtered. # Convert ordinals to strings. try: function = "#0x%x" % function except TypeError: pass # Validate the parameters. if module is not None and ('!' in module or '+' in module): raise ValueError("Invalid module name: %s" % module) if function is not None and ('!' in function or '+' in function): raise ValueError("Invalid function name: %s" % function) # Parse the label. if module: if function: if offset: label = "%s!%s+0x%x" % (module, function, offset) else: label = "%s!%s" % (module, function) else: if offset: ## label = "%s+0x%x!" % (module, offset) label = "%s!0x%x" % (module, offset) else: label = "%s!" % module else: if function: if offset: label = "!%s+0x%x" % (function, offset) else: label = "!%s" % function else: if offset: label = "0x%x" % offset else: label = "0x0" return label @staticmethod def split_label_strict(label): """ Splits a label created with L{parse_label}. To parse labels with a less strict syntax, use the L{split_label_fuzzy} method instead. @warning: This method only parses the label, it doesn't make sure the label actually points to a valid memory location. @type label: str @param label: Label to split. @rtype: tuple( str or None, str or int or None, int or None ) @return: Tuple containing the C{module} name, the C{function} name or ordinal, and the C{offset} value. If the label doesn't specify a module, then C{module} is C{None}. If the label doesn't specify a function, then C{function} is C{None}. If the label doesn't specify an offset, then C{offset} is C{0}. @raise ValueError: The label is malformed. """ module = function = None offset = 0 # Special case: None if not label: label = "0x0" else: # Remove all blanks. label = label.replace(' ', '') label = label.replace('\t', '') label = label.replace('\r', '') label = label.replace('\n', '') # Special case: empty label. if not label: label = "0x0" # * ! * if '!' in label: try: module, function = label.split('!') except ValueError: raise ValueError("Malformed label: %s" % label) # module ! function if function: if '+' in module: raise ValueError("Malformed label: %s" % label) # module ! function + offset if '+' in function: try: function, offset = function.split('+') except ValueError: raise ValueError("Malformed label: %s" % label) try: offset = HexInput.integer(offset) except ValueError: raise ValueError("Malformed label: %s" % label) else: # module ! offset try: offset = HexInput.integer(function) function = None except ValueError: pass else: # module + offset ! if '+' in module: try: module, offset = module.split('+') except ValueError: raise ValueError("Malformed label: %s" % label) try: offset = HexInput.integer(offset) except ValueError: raise ValueError("Malformed label: %s" % label) else: # module ! try: offset = HexInput.integer(module) module = None # offset ! except ValueError: pass if not module: module = None if not function: function = None # * else: # offset try: offset = HexInput.integer(label) # # ordinal except ValueError: if label.startswith('#'): function = label try: HexInput.integer(function[1:]) # module? # function? except ValueError: raise ValueError("Ambiguous label: %s" % label) # module? # function? else: raise ValueError("Ambiguous label: %s" % label) # Convert function ordinal strings into integers. if function and function.startswith('#'): try: function = HexInput.integer(function[1:]) except ValueError: pass # Convert null offsets to None. if not offset: offset = None return (module, function, offset) def split_label_fuzzy(self, label): """ Splits a label entered as user input. It's more flexible in it's syntax parsing than the L{split_label_strict} method, as it allows the exclamation mark (B{C{!}}) to be omitted. The ambiguity is resolved by searching the modules in the snapshot to guess if a label refers to a module or a function. It also tries to rebuild labels when they contain hardcoded addresses. @warning: This method only parses the label, it doesn't make sure the label actually points to a valid memory location. @type label: str @param label: Label to split. @rtype: tuple( str or None, str or int or None, int or None ) @return: Tuple containing the C{module} name, the C{function} name or ordinal, and the C{offset} value. If the label doesn't specify a module, then C{module} is C{None}. If the label doesn't specify a function, then C{function} is C{None}. If the label doesn't specify an offset, then C{offset} is C{0}. @raise ValueError: The label is malformed. """ module = function = None offset = 0 # Special case: None if not label: label = compat.b("0x0") else: # Remove all blanks. label = label.replace(compat.b(' '), compat.b('')) label = label.replace(compat.b('\t'), compat.b('')) label = label.replace(compat.b('\r'), compat.b('')) label = label.replace(compat.b('\n'), compat.b('')) # Special case: empty label. if not label: label = compat.b("0x0") # If an exclamation sign is present, we know we can parse it strictly. if compat.b('!') in label: return self.split_label_strict(label) ## # Try to parse it strictly, on error do it the fuzzy way. ## try: ## return self.split_label(label) ## except ValueError: ## pass # * + offset if compat.b('+') in label: try: prefix, offset = label.split(compat.b('+')) except ValueError: raise ValueError("Malformed label: %s" % label) try: offset = HexInput.integer(offset) except ValueError: raise ValueError("Malformed label: %s" % label) label = prefix # This parses both filenames and base addresses. modobj = self.get_module_by_name(label) if modobj: # module # module + offset module = modobj.get_name() else: # TODO # If 0xAAAAAAAA + 0xBBBBBBBB is given, # A is interpreted as a module base address, # and B as an offset. # If that fails, it'd be good to add A+B and try to # use the nearest loaded module. # offset # base address + offset (when no module has that base address) try: address = HexInput.integer(label) if offset: # If 0xAAAAAAAA + 0xBBBBBBBB is given, # A is interpreted as a module base address, # and B as an offset. # If that fails, we get here, meaning no module was found # at A. Then add up A+B and work with that as a hardcoded # address. offset = address + offset else: # If the label is a hardcoded address, we get here. offset = address # If only a hardcoded address is given, # rebuild the label using get_label_at_address. # Then parse it again, but this time strictly, # both because there is no need for fuzzy syntax and # to prevent an infinite recursion if there's a bug here. try: new_label = self.get_label_at_address(offset) module, function, offset = \ self.split_label_strict(new_label) except ValueError: pass # function # function + offset except ValueError: function = label # Convert function ordinal strings into integers. if function and function.startswith(compat.b('#')): try: function = HexInput.integer(function[1:]) except ValueError: pass # Convert null offsets to None. if not offset: offset = None return (module, function, offset) @classmethod def split_label(cls, label): """ Splits a label into it's C{module}, C{function} and C{offset} components, as used in L{parse_label}. When called as a static method, the strict syntax mode is used:: winappdbg.Process.split_label( "kernel32!CreateFileA" ) When called as an instance method, the fuzzy syntax mode is used:: aProcessInstance.split_label( "CreateFileA" ) @see: L{split_label_strict}, L{split_label_fuzzy} @type label: str @param label: Label to split. @rtype: tuple( str or None, str or int or None, int or None ) @return: Tuple containing the C{module} name, the C{function} name or ordinal, and the C{offset} value. If the label doesn't specify a module, then C{module} is C{None}. If the label doesn't specify a function, then C{function} is C{None}. If the label doesn't specify an offset, then C{offset} is C{0}. @raise ValueError: The label is malformed. """ # XXX # Docstring indentation was removed so epydoc doesn't complain # when parsing the docs for __use_fuzzy_mode(). # This function is overwritten by __init__ # so here is the static implementation only. return cls.split_label_strict(label) # The split_label method is replaced with this function by __init__. def __use_fuzzy_mode(self, label): "@see: L{split_label}" return self.split_label_fuzzy(label) ## __use_fuzzy_mode.__doc__ = split_label.__doc__ def sanitize_label(self, label): """ Converts a label taken from user input into a well-formed label. @type label: str @param label: Label taken from user input. @rtype: str @return: Sanitized label. """ (module, function, offset) = self.split_label_fuzzy(label) label = self.parse_label(module, function, offset) return label def resolve_label(self, label): """ Resolve the memory address of the given label. @note: If multiple modules with the same name are loaded, the label may be resolved at any of them. For a more precise way to resolve functions use the base address to get the L{Module} object (see L{Process.get_module}) and then call L{Module.resolve}. If no module name is specified in the label, the function may be resolved in any loaded module. If you want to resolve all functions with that name in all processes, call L{Process.iter_modules} to iterate through all loaded modules, and then try to resolve the function in each one of them using L{Module.resolve}. @type label: str @param label: Label to resolve. @rtype: int @return: Memory address pointed to by the label. @raise ValueError: The label is malformed or impossible to resolve. @raise RuntimeError: Cannot resolve the module or function. """ # Split the label into module, function and offset components. module, function, offset = self.split_label_fuzzy(label) # Resolve the components into a memory address. address = self.resolve_label_components(module, function, offset) # Return the memory address. return address def resolve_label_components(self, module = None, function = None, offset = None): """ Resolve the memory address of the given module, function and/or offset. @note: If multiple modules with the same name are loaded, the label may be resolved at any of them. For a more precise way to resolve functions use the base address to get the L{Module} object (see L{Process.get_module}) and then call L{Module.resolve}. If no module name is specified in the label, the function may be resolved in any loaded module. If you want to resolve all functions with that name in all processes, call L{Process.iter_modules} to iterate through all loaded modules, and then try to resolve the function in each one of them using L{Module.resolve}. @type module: None or str @param module: (Optional) Module name. @type function: None, str or int @param function: (Optional) Function name or ordinal. @type offset: None or int @param offset: (Optional) Offset value. If C{function} is specified, offset from the function. If C{function} is C{None}, offset from the module. @rtype: int @return: Memory address pointed to by the label. @raise ValueError: The label is malformed or impossible to resolve. @raise RuntimeError: Cannot resolve the module or function. """ # Default address if no module or function are given. # An offset may be added later. address = 0 # Resolve the module. # If the module is not found, check for the special symbol "main". if module: modobj = self.get_module_by_name(module) if not modobj: if module == "main": modobj = self.get_main_module() else: raise RuntimeError("Module %r not found" % module) # Resolve the exported function or debugging symbol. # If all else fails, check for the special symbol "start". if function: address = modobj.resolve(function) if address is None: address = modobj.resolve_symbol(function) if address is None: if function == "start": address = modobj.get_entry_point() if address is None: msg = "Symbol %r not found in module %s" raise RuntimeError(msg % (function, module)) # No function, use the base address. else: address = modobj.get_base() # Resolve the function in any module. # If all else fails, check for the special symbols "main" and "start". elif function: for modobj in self.iter_modules(): address = modobj.resolve(function) if address is not None: break if address is None: if function == "start": modobj = self.get_main_module() address = modobj.get_entry_point() elif function == "main": modobj = self.get_main_module() address = modobj.get_base() else: msg = "Function %r not found in any module" % function raise RuntimeError(msg) # Return the address plus the offset. if offset: address = address + offset return address def get_label_at_address(self, address, offset = None): """ Creates a label from the given memory address. @warning: This method uses the name of the nearest currently loaded module. If that module is unloaded later, the label becomes impossible to resolve. @type address: int @param address: Memory address. @type offset: None or int @param offset: (Optional) Offset value. @rtype: str @return: Label pointing to the given address. """ if offset: address = address + offset modobj = self.get_module_at_address(address) if modobj: label = modobj.get_label_at_address(address) else: label = self.parse_label(None, None, address) return label #------------------------------------------------------------------------------ # The memory addresses of system breakpoints are be cached, since they're # all in system libraries it's not likely they'll ever change their address # during the lifetime of the process... I don't suppose a program could # happily unload ntdll.dll and survive. def __get_system_breakpoint(self, label): try: return self.__system_breakpoints[label] except KeyError: try: address = self.resolve_label(label) except Exception: return None self.__system_breakpoints[label] = address return address # It's in kernel32 in Windows Server 2003, in ntdll since Windows Vista. # It can only be resolved if we have the debug symbols. def get_break_on_error_ptr(self): """ @rtype: int @return: If present, returns the address of the C{g_dwLastErrorToBreakOn} global variable for this process. If not, returns C{None}. """ address = self.__get_system_breakpoint("ntdll!g_dwLastErrorToBreakOn") if not address: address = self.__get_system_breakpoint( "kernel32!g_dwLastErrorToBreakOn") # cheat a little :) self.__system_breakpoints["ntdll!g_dwLastErrorToBreakOn"] = address return address def is_system_defined_breakpoint(self, address): """ @type address: int @param address: Memory address. @rtype: bool @return: C{True} if the given address points to a system defined breakpoint. System defined breakpoints are hardcoded into system libraries. """ if address: module = self.get_module_at_address(address) if module: return module.match_name("ntdll") or \ module.match_name("kernel32") return False # FIXME # In Wine, the system breakpoint seems to be somewhere in kernel32. def get_system_breakpoint(self): """ @rtype: int or None @return: Memory address of the system breakpoint within the process address space. Returns C{None} on error. """ return self.__get_system_breakpoint("ntdll!DbgBreakPoint") # I don't know when this breakpoint is actually used... def get_user_breakpoint(self): """ @rtype: int or None @return: Memory address of the user breakpoint within the process address space. Returns C{None} on error. """ return self.__get_system_breakpoint("ntdll!DbgUserBreakPoint") # On some platforms, this breakpoint can only be resolved # when the debugging symbols for ntdll.dll are loaded. def get_breakin_breakpoint(self): """ @rtype: int or None @return: Memory address of the remote breakin breakpoint within the process address space. Returns C{None} on error. """ return self.__get_system_breakpoint("ntdll!DbgUiRemoteBreakin") # Equivalent of ntdll!DbgBreakPoint in Wow64. def get_wow64_system_breakpoint(self): """ @rtype: int or None @return: Memory address of the Wow64 system breakpoint within the process address space. Returns C{None} on error. """ return self.__get_system_breakpoint("ntdll32!DbgBreakPoint") # Equivalent of ntdll!DbgUserBreakPoint in Wow64. def get_wow64_user_breakpoint(self): """ @rtype: int or None @return: Memory address of the Wow64 user breakpoint within the process address space. Returns C{None} on error. """ return self.__get_system_breakpoint("ntdll32!DbgUserBreakPoint") # Equivalent of ntdll!DbgUiRemoteBreakin in Wow64. def get_wow64_breakin_breakpoint(self): """ @rtype: int or None @return: Memory address of the Wow64 remote breakin breakpoint within the process address space. Returns C{None} on error. """ return self.__get_system_breakpoint("ntdll32!DbgUiRemoteBreakin") #------------------------------------------------------------------------------ def load_symbols(self): """ Loads the debugging symbols for all modules in this snapshot. Automatically called by L{get_symbols}. """ for aModule in self.iter_modules(): aModule.load_symbols() def unload_symbols(self): """ Unloads the debugging symbols for all modules in this snapshot. """ for aModule in self.iter_modules(): aModule.unload_symbols() def get_symbols(self): """ Returns the debugging symbols for all modules in this snapshot. The symbols are automatically loaded when needed. @rtype: list of tuple( str, int, int ) @return: List of symbols. Each symbol is represented by a tuple that contains: - Symbol name - Symbol memory address - Symbol size in bytes """ symbols = list() for aModule in self.iter_modules(): for symbol in aModule.iter_symbols(): symbols.append(symbol) return symbols def iter_symbols(self): """ Returns an iterator for the debugging symbols in all modules in this snapshot, in no particular order. The symbols are automatically loaded when needed. @rtype: iterator of tuple( str, int, int ) @return: Iterator of symbols. Each symbol is represented by a tuple that contains: - Symbol name - Symbol memory address - Symbol size in bytes """ for aModule in self.iter_modules(): for symbol in aModule.iter_symbols(): yield symbol def resolve_symbol(self, symbol, bCaseSensitive = False): """ Resolves a debugging symbol's address. @type symbol: str @param symbol: Name of the symbol to resolve. @type bCaseSensitive: bool @param bCaseSensitive: C{True} for case sensitive matches, C{False} for case insensitive. @rtype: int or None @return: Memory address of symbol. C{None} if not found. """ if bCaseSensitive: for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if symbol == SymbolName: return SymbolAddress else: symbol = symbol.lower() for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if symbol == SymbolName.lower(): return SymbolAddress def get_symbol_at_address(self, address): """ Tries to find the closest matching symbol for the given address. @type address: int @param address: Memory address to query. @rtype: None or tuple( str, int, int ) @return: Returns a tuple consisting of: - Name - Address - Size (in bytes) Returns C{None} if no symbol could be matched. """ # Any module may have symbols pointing anywhere in memory, so there's # no easy way to optimize this. I guess we're stuck with brute force. found = None for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols(): if SymbolAddress > address: continue if SymbolAddress == address: found = (SymbolName, SymbolAddress, SymbolSize) break if SymbolAddress < address: if found and (address - found[1]) < (address - SymbolAddress): continue else: found = (SymbolName, SymbolAddress, SymbolSize) return found #------------------------------------------------------------------------------ # XXX _notify_* methods should not trigger a scan def _add_module(self, aModule): """ Private method to add a module object to the snapshot. @type aModule: L{Module} @param aModule: Module object. """ ## if not isinstance(aModule, Module): ## if hasattr(aModule, '__class__'): ## typename = aModule.__class__.__name__ ## else: ## typename = str(type(aModule)) ## msg = "Expected Module, got %s instead" % typename ## raise TypeError(msg) lpBaseOfDll = aModule.get_base() ## if lpBaseOfDll in self.__moduleDict: ## msg = "Module already exists: %d" % lpBaseOfDll ## raise KeyError(msg) aModule.set_process(self) self.__moduleDict[lpBaseOfDll] = aModule def _del_module(self, lpBaseOfDll): """ Private method to remove a module object from the snapshot. @type lpBaseOfDll: int @param lpBaseOfDll: Module base address. """ try: aModule = self.__moduleDict[lpBaseOfDll] del self.__moduleDict[lpBaseOfDll] except KeyError: aModule = None msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll) warnings.warn(msg, RuntimeWarning) if aModule: aModule.clear() # remove circular references def __add_loaded_module(self, event): """ Private method to automatically add new module objects from debug events. @type event: L{Event} @param event: Event object. """ lpBaseOfDll = event.get_module_base() hFile = event.get_file_handle() ## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan if lpBaseOfDll not in self.__moduleDict: fileName = event.get_filename() if not fileName: fileName = None if hasattr(event, 'get_start_address'): EntryPoint = event.get_start_address() else: EntryPoint = None aModule = Module(lpBaseOfDll, hFile, fileName = fileName, EntryPoint = EntryPoint, process = self) self._add_module(aModule) else: aModule = self.get_module(lpBaseOfDll) if not aModule.hFile and hFile not in (None, 0, win32.INVALID_HANDLE_VALUE): aModule.hFile = hFile if not aModule.process: aModule.process = self if aModule.EntryPoint is None and \ hasattr(event, 'get_start_address'): aModule.EntryPoint = event.get_start_address() if not aModule.fileName: fileName = event.get_filename() if fileName: aModule.fileName = fileName def _notify_create_process(self, event): """ Notify the load of the main module. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ self.__add_loaded_module(event) return True def _notify_load_dll(self, event): """ Notify the load of a new module. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{LoadDLLEvent} @param event: Load DLL event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ self.__add_loaded_module(event) return True def _notify_unload_dll(self, event): """ Notify the release of a loaded module. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{UnloadDLLEvent} @param event: Unload DLL event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ lpBaseOfDll = event.get_module_base() ## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan if lpBaseOfDll in self.__moduleDict: self._del_module(lpBaseOfDll) return True
70,615
Python
34.010411
81
0.54783
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Breakpoints. @group Breakpoints: Breakpoint, CodeBreakpoint, PageBreakpoint, HardwareBreakpoint, BufferWatch, Hook, ApiHook @group Warnings: BreakpointWarning, BreakpointCallbackWarning """ __revision__ = "$Id$" __all__ = [ # Base class for breakpoints 'Breakpoint', # Breakpoint implementations 'CodeBreakpoint', 'PageBreakpoint', 'HardwareBreakpoint', # Hooks and watches 'Hook', 'ApiHook', 'BufferWatch', # Warnings 'BreakpointWarning', 'BreakpointCallbackWarning', ] from winappdbg import win32 from winappdbg import compat import sys from winappdbg.process import Process, Thread from winappdbg.util import DebugRegister, MemoryAddresses from winappdbg.textio import HexDump import ctypes import warnings import traceback #============================================================================== class BreakpointWarning (UserWarning): """ This warning is issued when a non-fatal error occurs that's related to breakpoints. """ class BreakpointCallbackWarning (RuntimeWarning): """ This warning is issued when an uncaught exception was raised by a breakpoint's user-defined callback. """ #============================================================================== class Breakpoint (object): """ Base class for breakpoints. Here's the breakpoints state machine. @see: L{CodeBreakpoint}, L{PageBreakpoint}, L{HardwareBreakpoint} @group Breakpoint states: DISABLED, ENABLED, ONESHOT, RUNNING @group State machine: hit, disable, enable, one_shot, running, is_disabled, is_enabled, is_one_shot, is_running, get_state, get_state_name @group Information: get_address, get_size, get_span, is_here @group Conditional breakpoints: is_conditional, is_unconditional, get_condition, set_condition, eval_condition @group Automatic breakpoints: is_automatic, is_interactive, get_action, set_action, run_action @cvar DISABLED: I{Disabled} S{->} Enabled, OneShot @cvar ENABLED: I{Enabled} S{->} I{Running}, Disabled @cvar ONESHOT: I{OneShot} S{->} I{Disabled} @cvar RUNNING: I{Running} S{->} I{Enabled}, Disabled @type DISABLED: int @type ENABLED: int @type ONESHOT: int @type RUNNING: int @type stateNames: dict E{lb} int S{->} str E{rb} @cvar stateNames: User-friendly names for each breakpoint state. @type typeName: str @cvar typeName: User friendly breakpoint type string. """ # I don't think transitions Enabled <-> OneShot should be allowed... plus # it would require special handling to avoid setting the same bp twice DISABLED = 0 ENABLED = 1 ONESHOT = 2 RUNNING = 3 typeName = 'breakpoint' stateNames = { DISABLED : 'disabled', ENABLED : 'enabled', ONESHOT : 'one shot', RUNNING : 'running', } def __init__(self, address, size = 1, condition = True, action = None): """ Breakpoint object. @type address: int @param address: Memory address for breakpoint. @type size: int @param size: Size of breakpoint in bytes (defaults to 1). @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object. """ self.__address = address self.__size = size self.__state = self.DISABLED self.set_condition(condition) self.set_action(action) def __repr__(self): if self.is_disabled(): state = 'Disabled' else: state = 'Active (%s)' % self.get_state_name() if self.is_conditional(): condition = 'conditional' else: condition = 'unconditional' name = self.typeName size = self.get_size() if size == 1: address = HexDump.address( self.get_address() ) else: begin = self.get_address() end = begin + size begin = HexDump.address(begin) end = HexDump.address(end) address = "range %s-%s" % (begin, end) msg = "<%s %s %s at remote address %s>" msg = msg % (state, condition, name, address) return msg #------------------------------------------------------------------------------ def is_disabled(self): """ @rtype: bool @return: C{True} if the breakpoint is in L{DISABLED} state. """ return self.get_state() == self.DISABLED def is_enabled(self): """ @rtype: bool @return: C{True} if the breakpoint is in L{ENABLED} state. """ return self.get_state() == self.ENABLED def is_one_shot(self): """ @rtype: bool @return: C{True} if the breakpoint is in L{ONESHOT} state. """ return self.get_state() == self.ONESHOT def is_running(self): """ @rtype: bool @return: C{True} if the breakpoint is in L{RUNNING} state. """ return self.get_state() == self.RUNNING def is_here(self, address): """ @rtype: bool @return: C{True} if the address is within the range of the breakpoint. """ begin = self.get_address() end = begin + self.get_size() return begin <= address < end def get_address(self): """ @rtype: int @return: The target memory address for the breakpoint. """ return self.__address def get_size(self): """ @rtype: int @return: The size in bytes of the breakpoint. """ return self.__size def get_span(self): """ @rtype: tuple( int, int ) @return: Starting and ending address of the memory range covered by the breakpoint. """ address = self.get_address() size = self.get_size() return ( address, address + size ) def get_state(self): """ @rtype: int @return: The current state of the breakpoint (L{DISABLED}, L{ENABLED}, L{ONESHOT}, L{RUNNING}). """ return self.__state def get_state_name(self): """ @rtype: str @return: The name of the current state of the breakpoint. """ return self.stateNames[ self.get_state() ] #------------------------------------------------------------------------------ def is_conditional(self): """ @see: L{__init__} @rtype: bool @return: C{True} if the breakpoint has a condition callback defined. """ # Do not evaluate as boolean! Test for identity with True instead. return self.__condition is not True def is_unconditional(self): """ @rtype: bool @return: C{True} if the breakpoint doesn't have a condition callback defined. """ # Do not evaluate as boolean! Test for identity with True instead. return self.__condition is True def get_condition(self): """ @rtype: bool, function @return: Returns the condition callback for conditional breakpoints. Returns C{True} for unconditional breakpoints. """ return self.__condition def set_condition(self, condition = True): """ Sets a new condition callback for the breakpoint. @see: L{__init__} @type condition: function @param condition: (Optional) Condition callback function. """ if condition is None: self.__condition = True else: self.__condition = condition def eval_condition(self, event): """ Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise. """ condition = self.get_condition() if condition is True: # shortcut for unconditional breakpoints return True if callable(condition): try: return bool( condition(event) ) except Exception: e = sys.exc_info()[1] msg = ("Breakpoint condition callback %r" " raised an exception: %s") msg = msg % (condition, traceback.format_exc(e)) warnings.warn(msg, BreakpointCallbackWarning) return False return bool( condition ) # force evaluation now #------------------------------------------------------------------------------ def is_automatic(self): """ @rtype: bool @return: C{True} if the breakpoint has an action callback defined. """ return self.__action is not None def is_interactive(self): """ @rtype: bool @return: C{True} if the breakpoint doesn't have an action callback defined. """ return self.__action is None def get_action(self): """ @rtype: bool, function @return: Returns the action callback for automatic breakpoints. Returns C{None} for interactive breakpoints. """ return self.__action def set_action(self, action = None): """ Sets a new action callback for the breakpoint. @type action: function @param action: (Optional) Action callback function. """ self.__action = action def run_action(self, event): """ Executes the breakpoint action callback, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. """ action = self.get_action() if action is not None: try: return bool( action(event) ) except Exception: e = sys.exc_info()[1] msg = ("Breakpoint action callback %r" " raised an exception: %s") msg = msg % (action, traceback.format_exc(e)) warnings.warn(msg, BreakpointCallbackWarning) return False return True #------------------------------------------------------------------------------ def __bad_transition(self, state): """ Raises an C{AssertionError} exception for an invalid state transition. @see: L{stateNames} @type state: int @param state: Intended breakpoint state. @raise Exception: Always. """ statemsg = "" oldState = self.stateNames[ self.get_state() ] newState = self.stateNames[ state ] msg = "Invalid state transition (%s -> %s)" \ " for breakpoint at address %s" msg = msg % (oldState, newState, HexDump.address(self.get_address())) raise AssertionError(msg) def disable(self, aProcess, aThread): """ Transition to L{DISABLED} state. - When hit: OneShot S{->} Disabled - Forced by user: Enabled, OneShot, Running S{->} Disabled - Transition from running state may require special handling by the breakpoint implementation class. @type aProcess: L{Process} @param aProcess: Process object. @type aThread: L{Thread} @param aThread: Thread object. """ ## if self.__state not in (self.ENABLED, self.ONESHOT, self.RUNNING): ## self.__bad_transition(self.DISABLED) self.__state = self.DISABLED def enable(self, aProcess, aThread): """ Transition to L{ENABLED} state. - When hit: Running S{->} Enabled - Forced by user: Disabled, Running S{->} Enabled - Transition from running state may require special handling by the breakpoint implementation class. @type aProcess: L{Process} @param aProcess: Process object. @type aThread: L{Thread} @param aThread: Thread object. """ ## if self.__state not in (self.DISABLED, self.RUNNING): ## self.__bad_transition(self.ENABLED) self.__state = self.ENABLED def one_shot(self, aProcess, aThread): """ Transition to L{ONESHOT} state. - Forced by user: Disabled S{->} OneShot @type aProcess: L{Process} @param aProcess: Process object. @type aThread: L{Thread} @param aThread: Thread object. """ ## if self.__state != self.DISABLED: ## self.__bad_transition(self.ONESHOT) self.__state = self.ONESHOT def running(self, aProcess, aThread): """ Transition to L{RUNNING} state. - When hit: Enabled S{->} Running @type aProcess: L{Process} @param aProcess: Process object. @type aThread: L{Thread} @param aThread: Thread object. """ if self.__state != self.ENABLED: self.__bad_transition(self.RUNNING) self.__state = self.RUNNING def hit(self, event): """ Notify a breakpoint that it's been hit. This triggers the corresponding state transition and sets the C{breakpoint} property of the given L{Event} object. @see: L{disable}, L{enable}, L{one_shot}, L{running} @type event: L{Event} @param event: Debug event to handle (depends on the breakpoint type). @raise AssertionError: Disabled breakpoints can't be hit. """ aProcess = event.get_process() aThread = event.get_thread() state = self.get_state() event.breakpoint = self if state == self.ENABLED: self.running(aProcess, aThread) elif state == self.RUNNING: self.enable(aProcess, aThread) elif state == self.ONESHOT: self.disable(aProcess, aThread) elif state == self.DISABLED: # this should not happen msg = "Hit a disabled breakpoint at address %s" msg = msg % HexDump.address( self.get_address() ) warnings.warn(msg, BreakpointWarning) #============================================================================== # XXX TODO # Check if the user is trying to set a code breakpoint on a memory mapped file, # so we don't end up writing the int3 instruction in the file by accident. class CodeBreakpoint (Breakpoint): """ Code execution breakpoints (using an int3 opcode). @see: L{Debug.break_at} @type bpInstruction: str @cvar bpInstruction: Breakpoint instruction for the current processor. """ typeName = 'code breakpoint' if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64): bpInstruction = '\xCC' # int 3 def __init__(self, address, condition = True, action = None): """ Code breakpoint object. @see: L{Breakpoint.__init__} @type address: int @param address: Memory address for breakpoint. @type condition: function @param condition: (Optional) Condition callback function. @type action: function @param action: (Optional) Action callback function. """ if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64): msg = "Code breakpoints not supported for %s" % win32.arch raise NotImplementedError(msg) Breakpoint.__init__(self, address, len(self.bpInstruction), condition, action) self.__previousValue = self.bpInstruction def __set_bp(self, aProcess): """ Writes a breakpoint instruction at the target address. @type aProcess: L{Process} @param aProcess: Process object. """ address = self.get_address() self.__previousValue = aProcess.read(address, len(self.bpInstruction)) if self.__previousValue == self.bpInstruction: msg = "Possible overlapping code breakpoints at %s" msg = msg % HexDump.address(address) warnings.warn(msg, BreakpointWarning) aProcess.write(address, self.bpInstruction) def __clear_bp(self, aProcess): """ Restores the original byte at the target address. @type aProcess: L{Process} @param aProcess: Process object. """ address = self.get_address() currentValue = aProcess.read(address, len(self.bpInstruction)) if currentValue == self.bpInstruction: # Only restore the previous value if the int3 is still there. aProcess.write(self.get_address(), self.__previousValue) else: self.__previousValue = currentValue msg = "Overwritten code breakpoint at %s" msg = msg % HexDump.address(address) warnings.warn(msg, BreakpointWarning) def disable(self, aProcess, aThread): if not self.is_disabled() and not self.is_running(): self.__clear_bp(aProcess) super(CodeBreakpoint, self).disable(aProcess, aThread) def enable(self, aProcess, aThread): if not self.is_enabled() and not self.is_one_shot(): self.__set_bp(aProcess) super(CodeBreakpoint, self).enable(aProcess, aThread) def one_shot(self, aProcess, aThread): if not self.is_enabled() and not self.is_one_shot(): self.__set_bp(aProcess) super(CodeBreakpoint, self).one_shot(aProcess, aThread) # FIXME race condition here (however unlikely) # If another thread runs on over the target address while # the breakpoint is in RUNNING state, we'll miss it. There # is a solution to this but it's somewhat complicated, so # I'm leaving it for another version of the debugger. :( def running(self, aProcess, aThread): if self.is_enabled(): self.__clear_bp(aProcess) aThread.set_tf() super(CodeBreakpoint, self).running(aProcess, aThread) #============================================================================== # TODO: # * If the original page was already a guard page, the exception should be # passed to the debugee instead of being handled by the debugger. # * If the original page was already a guard page, it should NOT be converted # to a no-access page when disabling the breakpoint. # * If the page permissions were modified after the breakpoint was enabled, # no change should be done on them when disabling the breakpoint. For this # we need to remember the original page permissions instead of blindly # setting and clearing the guard page bit on them. # * Some pages seem to be "magic" and resist all attempts at changing their # protect bits (for example the pages where the PEB and TEB reside). Maybe # a more descriptive error message could be shown in this case. class PageBreakpoint (Breakpoint): """ Page access breakpoint (using guard pages). @see: L{Debug.watch_buffer} @group Information: get_size_in_pages """ typeName = 'page breakpoint' #------------------------------------------------------------------------------ def __init__(self, address, pages = 1, condition = True, action = None): """ Page breakpoint object. @see: L{Breakpoint.__init__} @type address: int @param address: Memory address for breakpoint. @type pages: int @param address: Size of breakpoint in pages. @type condition: function @param condition: (Optional) Condition callback function. @type action: function @param action: (Optional) Action callback function. """ Breakpoint.__init__(self, address, pages * MemoryAddresses.pageSize, condition, action) ## if (address & 0x00000FFF) != 0: floordiv_align = long(address) // long(MemoryAddresses.pageSize) truediv_align = float(address) / float(MemoryAddresses.pageSize) if floordiv_align != truediv_align: msg = "Address of page breakpoint " \ "must be aligned to a page size boundary " \ "(value %s received)" % HexDump.address(address) raise ValueError(msg) def get_size_in_pages(self): """ @rtype: int @return: The size in pages of the breakpoint. """ # The size is always a multiple of the page size. return self.get_size() // MemoryAddresses.pageSize def __set_bp(self, aProcess): """ Sets the target pages as guard pages. @type aProcess: L{Process} @param aProcess: Process object. """ lpAddress = self.get_address() dwSize = self.get_size() flNewProtect = aProcess.mquery(lpAddress).Protect flNewProtect = flNewProtect | win32.PAGE_GUARD aProcess.mprotect(lpAddress, dwSize, flNewProtect) def __clear_bp(self, aProcess): """ Restores the original permissions of the target pages. @type aProcess: L{Process} @param aProcess: Process object. """ lpAddress = self.get_address() flNewProtect = aProcess.mquery(lpAddress).Protect flNewProtect = flNewProtect & (0xFFFFFFFF ^ win32.PAGE_GUARD) # DWORD aProcess.mprotect(lpAddress, self.get_size(), flNewProtect) def disable(self, aProcess, aThread): if not self.is_disabled(): self.__clear_bp(aProcess) super(PageBreakpoint, self).disable(aProcess, aThread) def enable(self, aProcess, aThread): if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64): msg = "Only one-shot page breakpoints are supported for %s" raise NotImplementedError(msg % win32.arch) if not self.is_enabled() and not self.is_one_shot(): self.__set_bp(aProcess) super(PageBreakpoint, self).enable(aProcess, aThread) def one_shot(self, aProcess, aThread): if not self.is_enabled() and not self.is_one_shot(): self.__set_bp(aProcess) super(PageBreakpoint, self).one_shot(aProcess, aThread) def running(self, aProcess, aThread): aThread.set_tf() super(PageBreakpoint, self).running(aProcess, aThread) #============================================================================== class HardwareBreakpoint (Breakpoint): """ Hardware breakpoint (using debug registers). @see: L{Debug.watch_variable} @group Information: get_slot, get_trigger, get_watch @group Trigger flags: BREAK_ON_EXECUTION, BREAK_ON_WRITE, BREAK_ON_ACCESS @group Watch size flags: WATCH_BYTE, WATCH_WORD, WATCH_DWORD, WATCH_QWORD @type BREAK_ON_EXECUTION: int @cvar BREAK_ON_EXECUTION: Break on execution. @type BREAK_ON_WRITE: int @cvar BREAK_ON_WRITE: Break on write. @type BREAK_ON_ACCESS: int @cvar BREAK_ON_ACCESS: Break on read or write. @type WATCH_BYTE: int @cvar WATCH_BYTE: Watch a byte. @type WATCH_WORD: int @cvar WATCH_WORD: Watch a word (2 bytes). @type WATCH_DWORD: int @cvar WATCH_DWORD: Watch a double word (4 bytes). @type WATCH_QWORD: int @cvar WATCH_QWORD: Watch one quad word (8 bytes). @type validTriggers: tuple @cvar validTriggers: Valid trigger flag values. @type validWatchSizes: tuple @cvar validWatchSizes: Valid watch flag values. """ typeName = 'hardware breakpoint' BREAK_ON_EXECUTION = DebugRegister.BREAK_ON_EXECUTION BREAK_ON_WRITE = DebugRegister.BREAK_ON_WRITE BREAK_ON_ACCESS = DebugRegister.BREAK_ON_ACCESS WATCH_BYTE = DebugRegister.WATCH_BYTE WATCH_WORD = DebugRegister.WATCH_WORD WATCH_DWORD = DebugRegister.WATCH_DWORD WATCH_QWORD = DebugRegister.WATCH_QWORD validTriggers = ( BREAK_ON_EXECUTION, BREAK_ON_WRITE, BREAK_ON_ACCESS, ) validWatchSizes = ( WATCH_BYTE, WATCH_WORD, WATCH_DWORD, WATCH_QWORD, ) def __init__(self, address, triggerFlag = BREAK_ON_ACCESS, sizeFlag = WATCH_DWORD, condition = True, action = None): """ Hardware breakpoint object. @see: L{Breakpoint.__init__} @type address: int @param address: Memory address for breakpoint. @type triggerFlag: int @param triggerFlag: Trigger of breakpoint. Must be one of the following: - L{BREAK_ON_EXECUTION} Break on code execution. - L{BREAK_ON_WRITE} Break on memory read or write. - L{BREAK_ON_ACCESS} Break on memory write. @type sizeFlag: int @param sizeFlag: Size of breakpoint. Must be one of the following: - L{WATCH_BYTE} One (1) byte in size. - L{WATCH_WORD} Two (2) bytes in size. - L{WATCH_DWORD} Four (4) bytes in size. - L{WATCH_QWORD} Eight (8) bytes in size. @type condition: function @param condition: (Optional) Condition callback function. @type action: function @param action: (Optional) Action callback function. """ if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64): msg = "Hardware breakpoints not supported for %s" % win32.arch raise NotImplementedError(msg) if sizeFlag == self.WATCH_BYTE: size = 1 elif sizeFlag == self.WATCH_WORD: size = 2 elif sizeFlag == self.WATCH_DWORD: size = 4 elif sizeFlag == self.WATCH_QWORD: size = 8 else: msg = "Invalid size flag for hardware breakpoint (%s)" msg = msg % repr(sizeFlag) raise ValueError(msg) if triggerFlag not in self.validTriggers: msg = "Invalid trigger flag for hardware breakpoint (%s)" msg = msg % repr(triggerFlag) raise ValueError(msg) Breakpoint.__init__(self, address, size, condition, action) self.__trigger = triggerFlag self.__watch = sizeFlag self.__slot = None def __clear_bp(self, aThread): """ Clears this breakpoint from the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """ if self.__slot is not None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) DebugRegister.clear_bp(ctx, self.__slot) aThread.set_context(ctx) self.__slot = None finally: aThread.resume() def __set_bp(self, aThread): """ Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """ if self.__slot is None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) self.__slot = DebugRegister.find_slot(ctx) if self.__slot is None: msg = "No available hardware breakpoint slots for thread ID %d" msg = msg % aThread.get_tid() raise RuntimeError(msg) DebugRegister.set_bp(ctx, self.__slot, self.get_address(), self.__trigger, self.__watch) aThread.set_context(ctx) finally: aThread.resume() def get_slot(self): """ @rtype: int @return: The debug register number used by this breakpoint, or C{None} if the breakpoint is not active. """ return self.__slot def get_trigger(self): """ @see: L{validTriggers} @rtype: int @return: The breakpoint trigger flag. """ return self.__trigger def get_watch(self): """ @see: L{validWatchSizes} @rtype: int @return: The breakpoint watch flag. """ return self.__watch def disable(self, aProcess, aThread): if not self.is_disabled(): self.__clear_bp(aThread) super(HardwareBreakpoint, self).disable(aProcess, aThread) def enable(self, aProcess, aThread): if not self.is_enabled() and not self.is_one_shot(): self.__set_bp(aThread) super(HardwareBreakpoint, self).enable(aProcess, aThread) def one_shot(self, aProcess, aThread): if not self.is_enabled() and not self.is_one_shot(): self.__set_bp(aThread) super(HardwareBreakpoint, self).one_shot(aProcess, aThread) def running(self, aProcess, aThread): self.__clear_bp(aThread) super(HardwareBreakpoint, self).running(aProcess, aThread) aThread.set_tf() #============================================================================== # XXX FIXME # # The implementation of function hooks is very simple. A breakpoint is set at # the entry point. Each time it's hit the "pre" callback is executed. If a # "post" callback was defined, a one-shot breakpoint is set at the return # address - and when that breakpoint hits, the "post" callback is executed. # # Functions hooks, as they are implemented now, don't work correctly for # recursive functions. The problem is we don't know when to remove the # breakpoint at the return address. Also there could be more than one return # address. # # One possible solution would involve a dictionary of lists, where the key # would be the thread ID and the value a stack of return addresses. But we # still don't know what to do if the "wrong" return address is hit for some # reason (maybe check the stack pointer?). Or if both a code and a hardware # breakpoint are hit simultaneously. # # For now, the workaround for the user is to set only the "pre" callback for # functions that are known to be recursive. # # If an exception is thrown by a hooked function and caught by one of it's # parent functions, the "post" callback won't be called and weird stuff may # happen. A possible solution is to put a breakpoint in the system call that # unwinds the stack, to detect this case and remove the "post" breakpoint. # # Hooks may also behave oddly if the return address is overwritten by a buffer # overflow bug (this is similar to the exception problem). But it's probably a # minor issue since when you're fuzzing a function for overflows you're usually # not interested in the return value anyway. # TODO: an API to modify the hooked function's arguments class Hook (object): """ Factory class to produce hook objects. Used by L{Debug.hook_function} and L{Debug.stalk_function}. When you try to instance this class, one of the architecture specific implementations is returned instead. Instances act as an action callback for code breakpoints set at the beginning of a function. It automatically retrieves the parameters from the stack, sets a breakpoint at the return address and retrieves the return value from the function call. @see: L{_Hook_i386}, L{_Hook_amd64} @type useHardwareBreakpoints: bool @cvar useHardwareBreakpoints: C{True} to try to use hardware breakpoints, C{False} otherwise. """ # This is a factory class that returns # the architecture specific implementation. def __new__(cls, *argv, **argd): try: arch = argd['arch'] del argd['arch'] except KeyError: try: arch = argv[4] argv = argv[:4] + argv[5:] except IndexError: raise TypeError("Missing 'arch' argument!") if arch is None: arch = win32.arch if arch == win32.ARCH_I386: return _Hook_i386(*argv, **argd) if arch == win32.ARCH_AMD64: return _Hook_amd64(*argv, **argd) return object.__new__(cls, *argv, **argd) # XXX FIXME # # Hardware breakpoints don't work correctly (or al all) in old VirtualBox # versions (3.0 and below). # # Maybe there should be a way to autodetect the buggy VirtualBox versions # and tell Hook objects not to use hardware breakpoints? # # For now the workaround is to manually set this variable to True when # WinAppDbg is installed on a physical machine. # useHardwareBreakpoints = False def __init__(self, preCB = None, postCB = None, paramCount = None, signature = None, arch = None): """ @type preCB: function @param preCB: (Optional) Callback triggered on function entry. The signature for the callback should be something like this:: def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags): # return address ra = params[0] # function arguments start from here... szFilename = event.get_process().peek_string(lpFilename) # (...) Note that all pointer types are treated like void pointers, so your callback won't get the string or structure pointed to by it, but the remote memory address instead. This is so to prevent the ctypes library from being "too helpful" and trying to dereference the pointer. To get the actual data being pointed to, use one of the L{Process.read} methods. @type postCB: function @param postCB: (Optional) Callback triggered on function exit. The signature for the callback should be something like this:: def post_LoadLibraryEx(event, return_value): # (...) @type paramCount: int @param paramCount: (Optional) Number of parameters for the C{preCB} callback, not counting the return address. Parameters are read from the stack and assumed to be DWORDs in 32 bits and QWORDs in 64. This is a faster way to pull stack parameters in 32 bits, but in 64 bits (or with some odd APIs in 32 bits) it won't be useful, since not all arguments to the hooked function will be of the same size. For a more reliable and cross-platform way of hooking use the C{signature} argument instead. @type signature: tuple @param signature: (Optional) Tuple of C{ctypes} data types that constitute the hooked function signature. When the function is called, this will be used to parse the arguments from the stack. Overrides the C{paramCount} argument. @type arch: str @param arch: (Optional) Target architecture. Defaults to the current architecture. See: L{win32.arch} """ self.__preCB = preCB self.__postCB = postCB self.__paramStack = dict() # tid -> list of tuple( arg, arg, arg... ) self._paramCount = paramCount if win32.arch != win32.ARCH_I386: self.useHardwareBreakpoints = False if win32.bits == 64 and paramCount and not signature: signature = (win32.QWORD,) * paramCount if signature: self._signature = self._calc_signature(signature) else: self._signature = None def _cast_signature_pointers_to_void(self, signature): c_void_p = ctypes.c_void_p c_char_p = ctypes.c_char_p c_wchar_p = ctypes.c_wchar_p _Pointer = ctypes._Pointer cast = ctypes.cast for i in compat.xrange(len(signature)): t = signature[i] if t is not c_void_p and (issubclass(t, _Pointer) \ or t in [c_char_p, c_wchar_p]): signature[i] = cast(t, c_void_p) def _calc_signature(self, signature): raise NotImplementedError( "Hook signatures are not supported for architecture: %s" \ % win32.arch) def _get_return_address(self, aProcess, aThread): return None def _get_function_arguments(self, aProcess, aThread): if self._signature or self._paramCount: raise NotImplementedError( "Hook signatures are not supported for architecture: %s" \ % win32.arch) return () def _get_return_value(self, aThread): return None # By using break_at() to set a process-wide breakpoint on the function's # return address, we might hit a race condition when more than one thread # is being debugged. # # Hardware breakpoints should be used instead. But since a thread can run # out of those, we need to fall back to this method when needed. def __call__(self, event): """ Handles the breakpoint event on entry of the function. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. @raise WindowsError: An error occured. """ debug = event.debug dwProcessId = event.get_pid() dwThreadId = event.get_tid() aProcess = event.get_process() aThread = event.get_thread() # Get the return address and function arguments. ra = self._get_return_address(aProcess, aThread) params = self._get_function_arguments(aProcess, aThread) # Keep the function arguments for later use. self.__push_params(dwThreadId, params) # If we need to hook the return from the function... bHookedReturn = False if ra is not None and self.__postCB is not None: # Try to set a one shot hardware breakpoint at the return address. useHardwareBreakpoints = self.useHardwareBreakpoints if useHardwareBreakpoints: try: debug.define_hardware_breakpoint( dwThreadId, ra, event.debug.BP_BREAK_ON_EXECUTION, event.debug.BP_WATCH_BYTE, True, self.__postCallAction_hwbp ) debug.enable_one_shot_hardware_breakpoint(dwThreadId, ra) bHookedReturn = True except Exception: e = sys.exc_info()[1] useHardwareBreakpoints = False msg = ("Failed to set hardware breakpoint" " at address %s for thread ID %d") msg = msg % (HexDump.address(ra), dwThreadId) warnings.warn(msg, BreakpointWarning) # If not possible, set a code breakpoint instead. if not useHardwareBreakpoints: try: debug.break_at(dwProcessId, ra, self.__postCallAction_codebp) bHookedReturn = True except Exception: e = sys.exc_info()[1] msg = ("Failed to set code breakpoint" " at address %s for process ID %d") msg = msg % (HexDump.address(ra), dwProcessId) warnings.warn(msg, BreakpointWarning) # Call the "pre" callback. try: self.__callHandler(self.__preCB, event, ra, *params) # If no "post" callback is defined, forget the function arguments. finally: if not bHookedReturn: self.__pop_params(dwThreadId) def __postCallAction_hwbp(self, event): """ Handles hardware breakpoint events on return from the function. @type event: L{ExceptionEvent} @param event: Single step event. """ # Remove the one shot hardware breakpoint # at the return address location in the stack. tid = event.get_tid() address = event.breakpoint.get_address() event.debug.erase_hardware_breakpoint(tid, address) # Call the "post" callback. try: self.__postCallAction(event) # Forget the parameters. finally: self.__pop_params(tid) def __postCallAction_codebp(self, event): """ Handles code breakpoint events on return from the function. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. """ # If the breakpoint was accidentally hit by another thread, # pass it to the debugger instead of calling the "post" callback. # # XXX FIXME: # I suppose this check will fail under some weird conditions... # tid = event.get_tid() if tid not in self.__paramStack: return True # Remove the code breakpoint at the return address. pid = event.get_pid() address = event.breakpoint.get_address() event.debug.dont_break_at(pid, address) # Call the "post" callback. try: self.__postCallAction(event) # Forget the parameters. finally: self.__pop_params(tid) def __postCallAction(self, event): """ Calls the "post" callback. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. """ aThread = event.get_thread() retval = self._get_return_value(aThread) self.__callHandler(self.__postCB, event, retval) def __callHandler(self, callback, event, *params): """ Calls a "pre" or "post" handler, if set. @type callback: function @param callback: Callback function to call. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. @type params: tuple @param params: Parameters for the callback function. """ if callback is not None: event.hook = self callback(event, *params) def __push_params(self, tid, params): """ Remembers the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. @type params: tuple( arg, arg, arg... ) @param params: Tuple of arguments. """ stack = self.__paramStack.get( tid, [] ) stack.append(params) self.__paramStack[tid] = stack def __pop_params(self, tid): """ Forgets the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. """ stack = self.__paramStack[tid] stack.pop() if not stack: del self.__paramStack[tid] def get_params(self, tid): """ Returns the parameters found in the stack when the hooked function was last called by this thread. @type tid: int @param tid: Thread global ID. @rtype: tuple( arg, arg, arg... ) @return: Tuple of arguments. """ try: params = self.get_params_stack(tid)[-1] except IndexError: msg = "Hooked function called from thread %d already returned" raise IndexError(msg % tid) return params def get_params_stack(self, tid): """ Returns the parameters found in the stack each time the hooked function was called by this thread and hasn't returned yet. @type tid: int @param tid: Thread global ID. @rtype: list of tuple( arg, arg, arg... ) @return: List of argument tuples. """ try: stack = self.__paramStack[tid] except KeyError: msg = "Hooked function was not called from thread %d" raise KeyError(msg % tid) return stack def hook(self, debug, pid, address): """ Installs the function hook at a given process and address. @see: L{unhook} @warning: Do not call from an function hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. @type address: int @param address: Function address. """ return debug.break_at(pid, address, self) def unhook(self, debug, pid, address): """ Removes the function hook at a given process and address. @see: L{hook} @warning: Do not call from an function hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. @type address: int @param address: Function address. """ return debug.dont_break_at(pid, address) class _Hook_i386 (Hook): """ Implementation details for L{Hook} on the L{win32.ARCH_I386} architecture. """ # We don't want to inherit the parent class __new__ method. __new__ = object.__new__ def _calc_signature(self, signature): self._cast_signature_pointers_to_void(signature) class Arguments (ctypes.Structure): _fields_ = [ ("arg_%s" % i, signature[i]) \ for i in compat.xrange(len(signature) - 1, -1, -1) ] return Arguments def _get_return_address(self, aProcess, aThread): return aProcess.read_pointer( aThread.get_sp() ) def _get_function_arguments(self, aProcess, aThread): if self._signature: params = aThread.read_stack_structure(self._signature, offset = win32.sizeof(win32.LPVOID)) elif self._paramCount: params = aThread.read_stack_dwords(self._paramCount, offset = win32.sizeof(win32.LPVOID)) else: params = () return params def _get_return_value(self, aThread): ctx = aThread.get_context(win32.CONTEXT_INTEGER) return ctx['Eax'] class _Hook_amd64 (Hook): """ Implementation details for L{Hook} on the L{win32.ARCH_AMD64} architecture. """ # We don't want to inherit the parent class __new__ method. __new__ = object.__new__ # Make a list of floating point types. __float_types = ( ctypes.c_double, ctypes.c_float, ) # Long doubles are not supported in old versions of ctypes! try: __float_types += (ctypes.c_longdouble,) except AttributeError: pass def _calc_signature(self, signature): self._cast_signature_pointers_to_void(signature) float_types = self.__float_types c_sizeof = ctypes.sizeof reg_size = c_sizeof(ctypes.c_size_t) reg_int_sig = [] reg_float_sig = [] stack_sig = [] for i in compat.xrange(len(signature)): arg = signature[i] name = "arg_%d" % i stack_sig.insert( 0, (name, arg) ) if i < 4: if type(arg) in float_types: reg_float_sig.append( (name, arg) ) elif c_sizeof(arg) <= reg_size: reg_int_sig.append( (name, arg) ) else: msg = ("Hook signatures don't support structures" " within the first 4 arguments of a function" " for the %s architecture") % win32.arch raise NotImplementedError(msg) if reg_int_sig: class RegisterArguments (ctypes.Structure): _fields_ = reg_int_sig else: RegisterArguments = None if reg_float_sig: class FloatArguments (ctypes.Structure): _fields_ = reg_float_sig else: FloatArguments = None if stack_sig: class StackArguments (ctypes.Structure): _fields_ = stack_sig else: StackArguments = None return (len(signature), RegisterArguments, FloatArguments, StackArguments) def _get_return_address(self, aProcess, aThread): return aProcess.read_pointer( aThread.get_sp() ) def _get_function_arguments(self, aProcess, aThread): if self._signature: (args_count, RegisterArguments, FloatArguments, StackArguments) = self._signature arguments = {} if StackArguments: address = aThread.get_sp() + win32.sizeof(win32.LPVOID) stack_struct = aProcess.read_structure(address, StackArguments) stack_args = dict( [ (name, stack_struct.__getattribute__(name)) for (name, type) in stack_struct._fields_ ] ) arguments.update(stack_args) flags = 0 if RegisterArguments: flags = flags | win32.CONTEXT_INTEGER if FloatArguments: flags = flags | win32.CONTEXT_MMX_REGISTERS if flags: ctx = aThread.get_context(flags) if RegisterArguments: buffer = (win32.QWORD * 4)(ctx['Rcx'], ctx['Rdx'], ctx['R8'], ctx['R9']) reg_args = self._get_arguments_from_buffer(buffer, RegisterArguments) arguments.update(reg_args) if FloatArguments: buffer = (win32.M128A * 4)(ctx['XMM0'], ctx['XMM1'], ctx['XMM2'], ctx['XMM3']) float_args = self._get_arguments_from_buffer(buffer, FloatArguments) arguments.update(float_args) params = tuple( [ arguments["arg_%d" % i] for i in compat.xrange(args_count) ] ) else: params = () return params def _get_arguments_from_buffer(self, buffer, structure): b_ptr = ctypes.pointer(buffer) v_ptr = ctypes.cast(b_ptr, ctypes.c_void_p) s_ptr = ctypes.cast(v_ptr, ctypes.POINTER(structure)) struct = s_ptr.contents return dict( [ (name, struct.__getattribute__(name)) for (name, type) in struct._fields_ ] ) def _get_return_value(self, aThread): ctx = aThread.get_context(win32.CONTEXT_INTEGER) return ctx['Rax'] #------------------------------------------------------------------------------ # This class acts as a factory of Hook objects, one per target process. # Said objects are deleted by the unhook() method. class ApiHook (object): """ Used by L{EventHandler}. This class acts as an action callback for code breakpoints set at the beginning of a function. It automatically retrieves the parameters from the stack, sets a breakpoint at the return address and retrieves the return value from the function call. @see: L{EventHandler.apiHooks} @type modName: str @ivar modName: Module name. @type procName: str @ivar procName: Procedure name. """ def __init__(self, eventHandler, modName, procName, paramCount = None, signature = None): """ @type eventHandler: L{EventHandler} @param eventHandler: Event handler instance. This is where the hook callbacks are to be defined (see below). @type modName: str @param modName: Module name. @type procName: str @param procName: Procedure name. The pre and post callbacks will be deduced from it. For example, if the procedure is "LoadLibraryEx" the callback routines will be "pre_LoadLibraryEx" and "post_LoadLibraryEx". The signature for the callbacks should be something like this:: def pre_LoadLibraryEx(self, event, ra, lpFilename, hFile, dwFlags): # return address ra = params[0] # function arguments start from here... szFilename = event.get_process().peek_string(lpFilename) # (...) def post_LoadLibraryEx(self, event, return_value): # (...) Note that all pointer types are treated like void pointers, so your callback won't get the string or structure pointed to by it, but the remote memory address instead. This is so to prevent the ctypes library from being "too helpful" and trying to dereference the pointer. To get the actual data being pointed to, use one of the L{Process.read} methods. @type paramCount: int @param paramCount: (Optional) Number of parameters for the C{preCB} callback, not counting the return address. Parameters are read from the stack and assumed to be DWORDs in 32 bits and QWORDs in 64. This is a faster way to pull stack parameters in 32 bits, but in 64 bits (or with some odd APIs in 32 bits) it won't be useful, since not all arguments to the hooked function will be of the same size. For a more reliable and cross-platform way of hooking use the C{signature} argument instead. @type signature: tuple @param signature: (Optional) Tuple of C{ctypes} data types that constitute the hooked function signature. When the function is called, this will be used to parse the arguments from the stack. Overrides the C{paramCount} argument. """ self.__modName = modName self.__procName = procName self.__paramCount = paramCount self.__signature = signature self.__preCB = getattr(eventHandler, 'pre_%s' % procName, None) self.__postCB = getattr(eventHandler, 'post_%s' % procName, None) self.__hook = dict() def __call__(self, event): """ Handles the breakpoint event on entry of the function. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. @raise WindowsError: An error occured. """ pid = event.get_pid() try: hook = self.__hook[pid] except KeyError: hook = Hook(self.__preCB, self.__postCB, self.__paramCount, self.__signature, event.get_process().get_arch() ) self.__hook[pid] = hook return hook(event) @property def modName(self): return self.__modName @property def procName(self): return self.__procName def hook(self, debug, pid): """ Installs the API hook on a given process and module. @warning: Do not call from an API hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. """ label = "%s!%s" % (self.__modName, self.__procName) try: hook = self.__hook[pid] except KeyError: try: aProcess = debug.system.get_process(pid) except KeyError: aProcess = Process(pid) hook = Hook(self.__preCB, self.__postCB, self.__paramCount, self.__signature, aProcess.get_arch() ) self.__hook[pid] = hook hook.hook(debug, pid, label) def unhook(self, debug, pid): """ Removes the API hook from the given process and module. @warning: Do not call from an API hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. """ try: hook = self.__hook[pid] except KeyError: return label = "%s!%s" % (self.__modName, self.__procName) hook.unhook(debug, pid, label) del self.__hook[pid] #============================================================================== class BufferWatch (object): """ Returned by L{Debug.watch_buffer}. This object uniquely references a buffer being watched, even if there are multiple watches set on the exact memory region. @type pid: int @ivar pid: Process ID. @type start: int @ivar start: Memory address of the start of the buffer. @type end: int @ivar end: Memory address of the end of the buffer. @type action: callable @ivar action: Action callback. @type oneshot: bool @ivar oneshot: C{True} for one shot breakpoints, C{False} otherwise. """ def __init__(self, pid, start, end, action = None, oneshot = False): self.__pid = pid self.__start = start self.__end = end self.__action = action self.__oneshot = oneshot @property def pid(self): return self.__pid @property def start(self): return self.__start @property def end(self): return self.__end @property def action(self): return self.__action @property def oneshot(self): return self.__oneshot def match(self, address): """ Determine if the given memory address lies within the watched buffer. @rtype: bool @return: C{True} if the given memory address lies within the watched buffer, C{False} otherwise. """ return self.__start <= address < self.__end #============================================================================== class _BufferWatchCondition (object): """ Used by L{Debug.watch_buffer}. This class acts as a condition callback for page breakpoints. It emulates page breakpoints that can overlap and/or take up less than a page's size. """ def __init__(self): self.__ranges = list() # list of BufferWatch in definition order def add(self, bw): """ Adds a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. """ self.__ranges.append(bw) def remove(self, bw): """ Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed. """ try: self.__ranges.remove(bw) except KeyError: if not bw.oneshot: raise def remove_last_match(self, address, size): """ Removes the last buffer from the watch object to match the given address and size. @type address: int @param address: Memory address of buffer to stop watching. @type size: int @param size: Size in bytes of buffer to stop watching. @rtype: int @return: Number of matching elements found. Only the last one to be added is actually deleted upon calling this method. This counter allows you to know if there are more matching elements and how many. """ count = 0 start = address end = address + size - 1 matched = None for item in self.__ranges: if item.match(start) and item.match(end): matched = item count += 1 self.__ranges.remove(matched) return count def count(self): """ @rtype: int @return: Number of buffers being watched. """ return len(self.__ranges) def __call__(self, event): """ Breakpoint condition callback. This method will also call the action callbacks for each buffer being watched. @type event: L{ExceptionEvent} @param event: Guard page exception event. @rtype: bool @return: C{True} if the address being accessed belongs to at least one of the buffers that was being watched and had no action callback. """ address = event.get_exception_information(1) bCondition = False for bw in self.__ranges: bMatched = bw.match(address) try: action = bw.action if bMatched and action is not None: try: action(event) except Exception: e = sys.exc_info()[1] msg = ("Breakpoint action callback %r" " raised an exception: %s") msg = msg % (action, traceback.format_exc(e)) warnings.warn(msg, BreakpointCallbackWarning) else: bCondition = bCondition or bMatched finally: if bMatched and bw.oneshot: event.debug.dont_watch_buffer(bw) return bCondition #============================================================================== class _BreakpointContainer (object): """ Encapsulates the capability to contain Breakpoint objects. @group Breakpoints: break_at, watch_variable, watch_buffer, hook_function, dont_break_at, dont_watch_variable, dont_watch_buffer, dont_hook_function, unhook_function, break_on_error, dont_break_on_error @group Stalking: stalk_at, stalk_variable, stalk_buffer, stalk_function, dont_stalk_at, dont_stalk_variable, dont_stalk_buffer, dont_stalk_function @group Tracing: is_tracing, get_traced_tids, start_tracing, stop_tracing, start_tracing_process, stop_tracing_process, start_tracing_all, stop_tracing_all @group Symbols: resolve_label, resolve_exported_function @group Advanced breakpoint use: define_code_breakpoint, define_page_breakpoint, define_hardware_breakpoint, has_code_breakpoint, has_page_breakpoint, has_hardware_breakpoint, get_code_breakpoint, get_page_breakpoint, get_hardware_breakpoint, erase_code_breakpoint, erase_page_breakpoint, erase_hardware_breakpoint, enable_code_breakpoint, enable_page_breakpoint, enable_hardware_breakpoint, enable_one_shot_code_breakpoint, enable_one_shot_page_breakpoint, enable_one_shot_hardware_breakpoint, disable_code_breakpoint, disable_page_breakpoint, disable_hardware_breakpoint @group Listing breakpoints: get_all_breakpoints, get_all_code_breakpoints, get_all_page_breakpoints, get_all_hardware_breakpoints, get_process_breakpoints, get_process_code_breakpoints, get_process_page_breakpoints, get_process_hardware_breakpoints, get_thread_hardware_breakpoints, get_all_deferred_code_breakpoints, get_process_deferred_code_breakpoints @group Batch operations on breakpoints: enable_all_breakpoints, enable_one_shot_all_breakpoints, disable_all_breakpoints, erase_all_breakpoints, enable_process_breakpoints, enable_one_shot_process_breakpoints, disable_process_breakpoints, erase_process_breakpoints @group Breakpoint types: BP_TYPE_ANY, BP_TYPE_CODE, BP_TYPE_PAGE, BP_TYPE_HARDWARE @group Breakpoint states: BP_STATE_DISABLED, BP_STATE_ENABLED, BP_STATE_ONESHOT, BP_STATE_RUNNING @group Memory breakpoint trigger flags: BP_BREAK_ON_EXECUTION, BP_BREAK_ON_WRITE, BP_BREAK_ON_ACCESS @group Memory breakpoint size flags: BP_WATCH_BYTE, BP_WATCH_WORD, BP_WATCH_DWORD, BP_WATCH_QWORD @type BP_TYPE_ANY: int @cvar BP_TYPE_ANY: To get all breakpoints @type BP_TYPE_CODE: int @cvar BP_TYPE_CODE: To get code breakpoints only @type BP_TYPE_PAGE: int @cvar BP_TYPE_PAGE: To get page breakpoints only @type BP_TYPE_HARDWARE: int @cvar BP_TYPE_HARDWARE: To get hardware breakpoints only @type BP_STATE_DISABLED: int @cvar BP_STATE_DISABLED: Breakpoint is disabled. @type BP_STATE_ENABLED: int @cvar BP_STATE_ENABLED: Breakpoint is enabled. @type BP_STATE_ONESHOT: int @cvar BP_STATE_ONESHOT: Breakpoint is enabled for one shot. @type BP_STATE_RUNNING: int @cvar BP_STATE_RUNNING: Breakpoint is running (recently hit). @type BP_BREAK_ON_EXECUTION: int @cvar BP_BREAK_ON_EXECUTION: Break on code execution. @type BP_BREAK_ON_WRITE: int @cvar BP_BREAK_ON_WRITE: Break on memory write. @type BP_BREAK_ON_ACCESS: int @cvar BP_BREAK_ON_ACCESS: Break on memory read or write. """ # Breakpoint types BP_TYPE_ANY = 0 # to get all breakpoints BP_TYPE_CODE = 1 BP_TYPE_PAGE = 2 BP_TYPE_HARDWARE = 3 # Breakpoint states BP_STATE_DISABLED = Breakpoint.DISABLED BP_STATE_ENABLED = Breakpoint.ENABLED BP_STATE_ONESHOT = Breakpoint.ONESHOT BP_STATE_RUNNING = Breakpoint.RUNNING # Memory breakpoint trigger flags BP_BREAK_ON_EXECUTION = HardwareBreakpoint.BREAK_ON_EXECUTION BP_BREAK_ON_WRITE = HardwareBreakpoint.BREAK_ON_WRITE BP_BREAK_ON_ACCESS = HardwareBreakpoint.BREAK_ON_ACCESS # Memory breakpoint size flags BP_WATCH_BYTE = HardwareBreakpoint.WATCH_BYTE BP_WATCH_WORD = HardwareBreakpoint.WATCH_WORD BP_WATCH_QWORD = HardwareBreakpoint.WATCH_QWORD BP_WATCH_DWORD = HardwareBreakpoint.WATCH_DWORD def __init__(self): self.__codeBP = dict() # (pid, address) -> CodeBreakpoint self.__pageBP = dict() # (pid, address) -> PageBreakpoint self.__hardwareBP = dict() # tid -> [ HardwareBreakpoint ] self.__runningBP = dict() # tid -> set( Breakpoint ) self.__tracing = set() # set( tid ) self.__deferredBP = dict() # pid -> label -> (action, oneshot) #------------------------------------------------------------------------------ # This operates on the dictionary of running breakpoints. # Since the bps are meant to stay alive no cleanup is done here. def __get_running_bp_set(self, tid): "Auxiliary method." return self.__runningBP.get(tid, ()) def __add_running_bp(self, tid, bp): "Auxiliary method." if tid not in self.__runningBP: self.__runningBP[tid] = set() self.__runningBP[tid].add(bp) def __del_running_bp(self, tid, bp): "Auxiliary method." self.__runningBP[tid].remove(bp) if not self.__runningBP[tid]: del self.__runningBP[tid] def __del_running_bp_from_all_threads(self, bp): "Auxiliary method." for (tid, bpset) in compat.iteritems(self.__runningBP): if bp in bpset: bpset.remove(bp) self.system.get_thread(tid).clear_tf() #------------------------------------------------------------------------------ # This is the cleanup code. Mostly called on response to exit/unload debug # events. If possible it shouldn't raise exceptions on runtime errors. # The main goal here is to avoid memory or handle leaks. def __cleanup_breakpoint(self, event, bp): "Auxiliary method." try: process = event.get_process() thread = event.get_thread() bp.disable(process, thread) # clear the debug regs / trap flag except Exception: pass bp.set_condition(True) # break possible circular reference bp.set_action(None) # break possible circular reference def __cleanup_thread(self, event): """ Auxiliary method for L{_notify_exit_thread} and L{_notify_exit_process}. """ tid = event.get_tid() # Cleanup running breakpoints try: for bp in self.__runningBP[tid]: self.__cleanup_breakpoint(event, bp) del self.__runningBP[tid] except KeyError: pass # Cleanup hardware breakpoints try: for bp in self.__hardwareBP[tid]: self.__cleanup_breakpoint(event, bp) del self.__hardwareBP[tid] except KeyError: pass # Cleanup set of threads being traced if tid in self.__tracing: self.__tracing.remove(tid) def __cleanup_process(self, event): """ Auxiliary method for L{_notify_exit_process}. """ pid = event.get_pid() process = event.get_process() # Cleanup code breakpoints for (bp_pid, bp_address) in compat.keys(self.__codeBP): if bp_pid == pid: bp = self.__codeBP[ (bp_pid, bp_address) ] self.__cleanup_breakpoint(event, bp) del self.__codeBP[ (bp_pid, bp_address) ] # Cleanup page breakpoints for (bp_pid, bp_address) in compat.keys(self.__pageBP): if bp_pid == pid: bp = self.__pageBP[ (bp_pid, bp_address) ] self.__cleanup_breakpoint(event, bp) del self.__pageBP[ (bp_pid, bp_address) ] # Cleanup deferred code breakpoints try: del self.__deferredBP[pid] except KeyError: pass def __cleanup_module(self, event): """ Auxiliary method for L{_notify_unload_dll}. """ pid = event.get_pid() process = event.get_process() module = event.get_module() # Cleanup thread breakpoints on this module for tid in process.iter_thread_ids(): thread = process.get_thread(tid) # Running breakpoints if tid in self.__runningBP: bplist = list(self.__runningBP[tid]) for bp in bplist: bp_address = bp.get_address() if process.get_module_at_address(bp_address) == module: self.__cleanup_breakpoint(event, bp) self.__runningBP[tid].remove(bp) # Hardware breakpoints if tid in self.__hardwareBP: bplist = list(self.__hardwareBP[tid]) for bp in bplist: bp_address = bp.get_address() if process.get_module_at_address(bp_address) == module: self.__cleanup_breakpoint(event, bp) self.__hardwareBP[tid].remove(bp) # Cleanup code breakpoints on this module for (bp_pid, bp_address) in compat.keys(self.__codeBP): if bp_pid == pid: if process.get_module_at_address(bp_address) == module: bp = self.__codeBP[ (bp_pid, bp_address) ] self.__cleanup_breakpoint(event, bp) del self.__codeBP[ (bp_pid, bp_address) ] # Cleanup page breakpoints on this module for (bp_pid, bp_address) in compat.keys(self.__pageBP): if bp_pid == pid: if process.get_module_at_address(bp_address) == module: bp = self.__pageBP[ (bp_pid, bp_address) ] self.__cleanup_breakpoint(event, bp) del self.__pageBP[ (bp_pid, bp_address) ] #------------------------------------------------------------------------------ # Defining breakpoints. # Code breakpoints. def define_code_breakpoint(self, dwProcessId, address, condition = True, action = None): """ Creates a disabled code breakpoint at the given address. @see: L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint}, L{erase_code_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of the code instruction to break at. @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @rtype: L{CodeBreakpoint} @return: The code breakpoint object. """ process = self.system.get_process(dwProcessId) bp = CodeBreakpoint(address, condition, action) key = (dwProcessId, bp.get_address()) if key in self.__codeBP: msg = "Already exists (PID %d) : %r" raise KeyError(msg % (dwProcessId, self.__codeBP[key])) self.__codeBP[key] = bp return bp # Page breakpoints. def define_page_breakpoint(self, dwProcessId, address, pages = 1, condition = True, action = None): """ Creates a disabled page breakpoint at the given address. @see: L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint}, L{erase_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of the first page to watch. @type pages: int @param pages: Number of pages to watch. @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @rtype: L{PageBreakpoint} @return: The page breakpoint object. """ process = self.system.get_process(dwProcessId) bp = PageBreakpoint(address, pages, condition, action) begin = bp.get_address() end = begin + bp.get_size() address = begin pageSize = MemoryAddresses.pageSize while address < end: key = (dwProcessId, address) if key in self.__pageBP: msg = "Already exists (PID %d) : %r" msg = msg % (dwProcessId, self.__pageBP[key]) raise KeyError(msg) address = address + pageSize address = begin while address < end: key = (dwProcessId, address) self.__pageBP[key] = bp address = address + pageSize return bp # Hardware breakpoints. def define_hardware_breakpoint(self, dwThreadId, address, triggerFlag = BP_BREAK_ON_ACCESS, sizeFlag = BP_WATCH_DWORD, condition = True, action = None): """ Creates a disabled hardware breakpoint at the given address. @see: L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint}, L{erase_hardware_breakpoint} @note: Hardware breakpoints do not seem to work properly on VirtualBox. See U{http://www.virtualbox.org/ticket/477}. @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address to watch. @type triggerFlag: int @param triggerFlag: Trigger of breakpoint. Must be one of the following: - L{BP_BREAK_ON_EXECUTION} Break on code execution. - L{BP_BREAK_ON_WRITE} Break on memory read or write. - L{BP_BREAK_ON_ACCESS} Break on memory write. @type sizeFlag: int @param sizeFlag: Size of breakpoint. Must be one of the following: - L{BP_WATCH_BYTE} One (1) byte in size. - L{BP_WATCH_WORD} Two (2) bytes in size. - L{BP_WATCH_DWORD} Four (4) bytes in size. - L{BP_WATCH_QWORD} Eight (8) bytes in size. @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @rtype: L{HardwareBreakpoint} @return: The hardware breakpoint object. """ thread = self.system.get_thread(dwThreadId) bp = HardwareBreakpoint(address, triggerFlag, sizeFlag, condition, action) begin = bp.get_address() end = begin + bp.get_size() if dwThreadId in self.__hardwareBP: bpSet = self.__hardwareBP[dwThreadId] for oldbp in bpSet: old_begin = oldbp.get_address() old_end = old_begin + oldbp.get_size() if MemoryAddresses.do_ranges_intersect(begin, end, old_begin, old_end): msg = "Already exists (TID %d) : %r" % (dwThreadId, oldbp) raise KeyError(msg) else: bpSet = set() self.__hardwareBP[dwThreadId] = bpSet bpSet.add(bp) return bp #------------------------------------------------------------------------------ # Checking breakpoint definitions. def has_code_breakpoint(self, dwProcessId, address): """ Checks if a code breakpoint is defined at the given address. @see: L{define_code_breakpoint}, L{get_code_breakpoint}, L{erase_code_breakpoint}, L{enable_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. @rtype: bool @return: C{True} if the breakpoint is defined, C{False} otherwise. """ return (dwProcessId, address) in self.__codeBP def has_page_breakpoint(self, dwProcessId, address): """ Checks if a page breakpoint is defined at the given address. @see: L{define_page_breakpoint}, L{get_page_breakpoint}, L{erase_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. @rtype: bool @return: C{True} if the breakpoint is defined, C{False} otherwise. """ return (dwProcessId, address) in self.__pageBP def has_hardware_breakpoint(self, dwThreadId, address): """ Checks if a hardware breakpoint is defined at the given address. @see: L{define_hardware_breakpoint}, L{get_hardware_breakpoint}, L{erase_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. @rtype: bool @return: C{True} if the breakpoint is defined, C{False} otherwise. """ if dwThreadId in self.__hardwareBP: bpSet = self.__hardwareBP[dwThreadId] for bp in bpSet: if bp.get_address() == address: return True return False #------------------------------------------------------------------------------ # Getting breakpoints. def get_code_breakpoint(self, dwProcessId, address): """ Returns the internally used breakpoint object, for the code breakpoint defined at the given address. @warning: It's usually best to call the L{Debug} methods instead of accessing the breakpoint objects directly. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{enable_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint}, L{erase_code_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address where the breakpoint is defined. @rtype: L{CodeBreakpoint} @return: The code breakpoint object. """ key = (dwProcessId, address) if key not in self.__codeBP: msg = "No breakpoint at process %d, address %s" address = HexDump.address(address) raise KeyError(msg % (dwProcessId, address)) return self.__codeBP[key] def get_page_breakpoint(self, dwProcessId, address): """ Returns the internally used breakpoint object, for the page breakpoint defined at the given address. @warning: It's usually best to call the L{Debug} methods instead of accessing the breakpoint objects directly. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint}, L{erase_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address where the breakpoint is defined. @rtype: L{PageBreakpoint} @return: The page breakpoint object. """ key = (dwProcessId, address) if key not in self.__pageBP: msg = "No breakpoint at process %d, address %s" address = HexDump.addresS(address) raise KeyError(msg % (dwProcessId, address)) return self.__pageBP[key] def get_hardware_breakpoint(self, dwThreadId, address): """ Returns the internally used breakpoint object, for the code breakpoint defined at the given address. @warning: It's usually best to call the L{Debug} methods instead of accessing the breakpoint objects directly. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_code_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint}, L{erase_hardware_breakpoint} @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address where the breakpoint is defined. @rtype: L{HardwareBreakpoint} @return: The hardware breakpoint object. """ if dwThreadId not in self.__hardwareBP: msg = "No hardware breakpoints set for thread %d" raise KeyError(msg % dwThreadId) for bp in self.__hardwareBP[dwThreadId]: if bp.is_here(address): return bp msg = "No hardware breakpoint at thread %d, address %s" raise KeyError(msg % (dwThreadId, HexDump.address(address))) #------------------------------------------------------------------------------ # Enabling and disabling breakpoints. def enable_code_breakpoint(self, dwProcessId, address): """ Enables the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint} L{erase_code_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(p, None) # XXX HACK thread is not used def enable_page_breakpoint(self, dwProcessId, address): """ Enables the page breakpoint at the given address. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint} L{erase_page_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ p = self.system.get_process(dwProcessId) bp = self.get_page_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(p, None) # XXX HACK thread is not used def enable_hardware_breakpoint(self, dwThreadId, address): """ Enables the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} L{erase_hardware_breakpoint}, @note: Do not set hardware breakpoints while processing the system breakpoint event. @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """ t = self.system.get_thread(dwThreadId) bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(None, t) # XXX HACK process is not used def enable_one_shot_code_breakpoint(self, dwProcessId, address): """ Enables the code breakpoint at the given address for only one shot. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint}, L{disable_code_breakpoint} L{erase_code_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.one_shot(p, None) # XXX HACK thread is not used def enable_one_shot_page_breakpoint(self, dwProcessId, address): """ Enables the page breakpoint at the given address for only one shot. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint}, L{disable_page_breakpoint} L{erase_page_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ p = self.system.get_process(dwProcessId) bp = self.get_page_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.one_shot(p, None) # XXX HACK thread is not used def enable_one_shot_hardware_breakpoint(self, dwThreadId, address): """ Enables the hardware breakpoint at the given address for only one shot. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{disable_hardware_breakpoint} L{erase_hardware_breakpoint}, @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """ t = self.system.get_thread(dwThreadId) bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.one_shot(None, t) # XXX HACK process is not used def disable_code_breakpoint(self, dwProcessId, address): """ Disables the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint} L{enable_one_shot_code_breakpoint}, L{erase_code_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.disable(p, None) # XXX HACK thread is not used def disable_page_breakpoint(self, dwProcessId, address): """ Disables the page breakpoint at the given address. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint} L{enable_one_shot_page_breakpoint}, L{erase_page_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ p = self.system.get_process(dwProcessId) bp = self.get_page_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.disable(p, None) # XXX HACK thread is not used def disable_hardware_breakpoint(self, dwThreadId, address): """ Disables the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint} L{enable_one_shot_hardware_breakpoint}, L{erase_hardware_breakpoint}, @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """ t = self.system.get_thread(dwThreadId) p = t.get_process() bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp(dwThreadId, bp) bp.disable(p, t) #------------------------------------------------------------------------------ # Undefining (erasing) breakpoints. def erase_code_breakpoint(self, dwProcessId, address): """ Erases the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ bp = self.get_code_breakpoint(dwProcessId, address) if not bp.is_disabled(): self.disable_code_breakpoint(dwProcessId, address) del self.__codeBP[ (dwProcessId, address) ] def erase_page_breakpoint(self, dwProcessId, address): """ Erases the page breakpoint at the given address. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """ bp = self.get_page_breakpoint(dwProcessId, address) begin = bp.get_address() end = begin + bp.get_size() if not bp.is_disabled(): self.disable_page_breakpoint(dwProcessId, address) address = begin pageSize = MemoryAddresses.pageSize while address < end: del self.__pageBP[ (dwProcessId, address) ] address = address + pageSize def erase_hardware_breakpoint(self, dwThreadId, address): """ Erases the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """ bp = self.get_hardware_breakpoint(dwThreadId, address) if not bp.is_disabled(): self.disable_hardware_breakpoint(dwThreadId, address) bpSet = self.__hardwareBP[dwThreadId] bpSet.remove(bp) if not bpSet: del self.__hardwareBP[dwThreadId] #------------------------------------------------------------------------------ # Listing breakpoints. def get_all_breakpoints(self): """ Returns all breakpoint objects as a list of tuples. Each tuple contains: - Process global ID to which the breakpoint applies. - Thread global ID to which the breakpoint applies, or C{None}. - The L{Breakpoint} object itself. @note: If you're only interested in a specific breakpoint type, or in breakpoints for a specific process or thread, it's probably faster to call one of the following methods: - L{get_all_code_breakpoints} - L{get_all_page_breakpoints} - L{get_all_hardware_breakpoints} - L{get_process_code_breakpoints} - L{get_process_page_breakpoints} - L{get_process_hardware_breakpoints} - L{get_thread_hardware_breakpoints} @rtype: list of tuple( pid, tid, bp ) @return: List of all breakpoints. """ bplist = list() # Get the code breakpoints. for (pid, bp) in self.get_all_code_breakpoints(): bplist.append( (pid, None, bp) ) # Get the page breakpoints. for (pid, bp) in self.get_all_page_breakpoints(): bplist.append( (pid, None, bp) ) # Get the hardware breakpoints. for (tid, bp) in self.get_all_hardware_breakpoints(): pid = self.system.get_thread(tid).get_pid() bplist.append( (pid, tid, bp) ) # Return the list of breakpoints. return bplist def get_all_code_breakpoints(self): """ @rtype: list of tuple( int, L{CodeBreakpoint} ) @return: All code breakpoints as a list of tuples (pid, bp). """ return [ (pid, bp) for ((pid, address), bp) in compat.iteritems(self.__codeBP) ] def get_all_page_breakpoints(self): """ @rtype: list of tuple( int, L{PageBreakpoint} ) @return: All page breakpoints as a list of tuples (pid, bp). """ ## return list( set( [ (pid, bp) for ((pid, address), bp) in compat.iteritems(self.__pageBP) ] ) ) result = set() for ((pid, address), bp) in compat.iteritems(self.__pageBP): result.add( (pid, bp) ) return list(result) def get_all_hardware_breakpoints(self): """ @rtype: list of tuple( int, L{HardwareBreakpoint} ) @return: All hardware breakpoints as a list of tuples (tid, bp). """ result = list() for (tid, bplist) in compat.iteritems(self.__hardwareBP): for bp in bplist: result.append( (tid, bp) ) return result def get_process_breakpoints(self, dwProcessId): """ Returns all breakpoint objects for the given process as a list of tuples. Each tuple contains: - Process global ID to which the breakpoint applies. - Thread global ID to which the breakpoint applies, or C{None}. - The L{Breakpoint} object itself. @note: If you're only interested in a specific breakpoint type, or in breakpoints for a specific process or thread, it's probably faster to call one of the following methods: - L{get_all_code_breakpoints} - L{get_all_page_breakpoints} - L{get_all_hardware_breakpoints} - L{get_process_code_breakpoints} - L{get_process_page_breakpoints} - L{get_process_hardware_breakpoints} - L{get_thread_hardware_breakpoints} @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: list of tuple( pid, tid, bp ) @return: List of all breakpoints for the given process. """ bplist = list() # Get the code breakpoints. for bp in self.get_process_code_breakpoints(dwProcessId): bplist.append( (dwProcessId, None, bp) ) # Get the page breakpoints. for bp in self.get_process_page_breakpoints(dwProcessId): bplist.append( (dwProcessId, None, bp) ) # Get the hardware breakpoints. for (tid, bp) in self.get_process_hardware_breakpoints(dwProcessId): pid = self.system.get_thread(tid).get_pid() bplist.append( (dwProcessId, tid, bp) ) # Return the list of breakpoints. return bplist def get_process_code_breakpoints(self, dwProcessId): """ @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: list of L{CodeBreakpoint} @return: All code breakpoints for the given process. """ return [ bp for ((pid, address), bp) in compat.iteritems(self.__codeBP) \ if pid == dwProcessId ] def get_process_page_breakpoints(self, dwProcessId): """ @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: list of L{PageBreakpoint} @return: All page breakpoints for the given process. """ return [ bp for ((pid, address), bp) in compat.iteritems(self.__pageBP) \ if pid == dwProcessId ] def get_thread_hardware_breakpoints(self, dwThreadId): """ @see: L{get_process_hardware_breakpoints} @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: list of L{HardwareBreakpoint} @return: All hardware breakpoints for the given thread. """ result = list() for (tid, bplist) in compat.iteritems(self.__hardwareBP): if tid == dwThreadId: for bp in bplist: result.append(bp) return result def get_process_hardware_breakpoints(self, dwProcessId): """ @see: L{get_thread_hardware_breakpoints} @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: list of tuple( int, L{HardwareBreakpoint} ) @return: All hardware breakpoints for each thread in the given process as a list of tuples (tid, bp). """ result = list() aProcess = self.system.get_process(dwProcessId) for dwThreadId in aProcess.iter_thread_ids(): if dwThreadId in self.__hardwareBP: bplist = self.__hardwareBP[dwThreadId] for bp in bplist: result.append( (dwThreadId, bp) ) return result ## def get_all_hooks(self): ## """ ## @see: L{get_process_hooks} ## ## @rtype: list of tuple( int, int, L{Hook} ) ## @return: All defined hooks as a list of tuples (pid, address, hook). ## """ ## return [ (pid, address, hook) \ ## for ((pid, address), hook) in self.__hook_objects ] ## ## def get_process_hooks(self, dwProcessId): ## """ ## @see: L{get_all_hooks} ## ## @type dwProcessId: int ## @param dwProcessId: Process global ID. ## ## @rtype: list of tuple( int, int, L{Hook} ) ## @return: All hooks for the given process as a list of tuples ## (pid, address, hook). ## """ ## return [ (pid, address, hook) \ ## for ((pid, address), hook) in self.__hook_objects \ ## if pid == dwProcessId ] #------------------------------------------------------------------------------ # Batch operations on all breakpoints. def enable_all_breakpoints(self): """ Enables all disabled breakpoints in all processes. @see: enable_code_breakpoint, enable_page_breakpoint, enable_hardware_breakpoint """ # disable code breakpoints for (pid, bp) in self.get_all_code_breakpoints(): if bp.is_disabled(): self.enable_code_breakpoint(pid, bp.get_address()) # disable page breakpoints for (pid, bp) in self.get_all_page_breakpoints(): if bp.is_disabled(): self.enable_page_breakpoint(pid, bp.get_address()) # disable hardware breakpoints for (tid, bp) in self.get_all_hardware_breakpoints(): if bp.is_disabled(): self.enable_hardware_breakpoint(tid, bp.get_address()) def enable_one_shot_all_breakpoints(self): """ Enables for one shot all disabled breakpoints in all processes. @see: enable_one_shot_code_breakpoint, enable_one_shot_page_breakpoint, enable_one_shot_hardware_breakpoint """ # disable code breakpoints for one shot for (pid, bp) in self.get_all_code_breakpoints(): if bp.is_disabled(): self.enable_one_shot_code_breakpoint(pid, bp.get_address()) # disable page breakpoints for one shot for (pid, bp) in self.get_all_page_breakpoints(): if bp.is_disabled(): self.enable_one_shot_page_breakpoint(pid, bp.get_address()) # disable hardware breakpoints for one shot for (tid, bp) in self.get_all_hardware_breakpoints(): if bp.is_disabled(): self.enable_one_shot_hardware_breakpoint(tid, bp.get_address()) def disable_all_breakpoints(self): """ Disables all breakpoints in all processes. @see: disable_code_breakpoint, disable_page_breakpoint, disable_hardware_breakpoint """ # disable code breakpoints for (pid, bp) in self.get_all_code_breakpoints(): self.disable_code_breakpoint(pid, bp.get_address()) # disable page breakpoints for (pid, bp) in self.get_all_page_breakpoints(): self.disable_page_breakpoint(pid, bp.get_address()) # disable hardware breakpoints for (tid, bp) in self.get_all_hardware_breakpoints(): self.disable_hardware_breakpoint(tid, bp.get_address()) def erase_all_breakpoints(self): """ Erases all breakpoints in all processes. @see: erase_code_breakpoint, erase_page_breakpoint, erase_hardware_breakpoint """ # This should be faster but let's not trust the GC so much :P # self.disable_all_breakpoints() # self.__codeBP = dict() # self.__pageBP = dict() # self.__hardwareBP = dict() # self.__runningBP = dict() # self.__hook_objects = dict() ## # erase hooks ## for (pid, address, hook) in self.get_all_hooks(): ## self.dont_hook_function(pid, address) # erase code breakpoints for (pid, bp) in self.get_all_code_breakpoints(): self.erase_code_breakpoint(pid, bp.get_address()) # erase page breakpoints for (pid, bp) in self.get_all_page_breakpoints(): self.erase_page_breakpoint(pid, bp.get_address()) # erase hardware breakpoints for (tid, bp) in self.get_all_hardware_breakpoints(): self.erase_hardware_breakpoint(tid, bp.get_address()) #------------------------------------------------------------------------------ # Batch operations on breakpoints per process. def enable_process_breakpoints(self, dwProcessId): """ Enables all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """ # enable code breakpoints for bp in self.get_process_code_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_code_breakpoint(dwProcessId, bp.get_address()) # enable page breakpoints for bp in self.get_process_page_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_page_breakpoint(dwProcessId, bp.get_address()) # enable hardware breakpoints if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): if bp.is_disabled(): self.enable_hardware_breakpoint(dwThreadId, bp.get_address()) def enable_one_shot_process_breakpoints(self, dwProcessId): """ Enables for one shot all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """ # enable code breakpoints for one shot for bp in self.get_process_code_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_one_shot_code_breakpoint(dwProcessId, bp.get_address()) # enable page breakpoints for one shot for bp in self.get_process_page_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_one_shot_page_breakpoint(dwProcessId, bp.get_address()) # enable hardware breakpoints for one shot if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): if bp.is_disabled(): self.enable_one_shot_hardware_breakpoint(dwThreadId, bp.get_address()) def disable_process_breakpoints(self, dwProcessId): """ Disables all breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """ # disable code breakpoints for bp in self.get_process_code_breakpoints(dwProcessId): self.disable_code_breakpoint(dwProcessId, bp.get_address()) # disable page breakpoints for bp in self.get_process_page_breakpoints(dwProcessId): self.disable_page_breakpoint(dwProcessId, bp.get_address()) # disable hardware breakpoints if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): self.disable_hardware_breakpoint(dwThreadId, bp.get_address()) def erase_process_breakpoints(self, dwProcessId): """ Erases all breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """ # disable breakpoints first # if an error occurs, no breakpoint is erased self.disable_process_breakpoints(dwProcessId) ## # erase hooks ## for address, hook in self.get_process_hooks(dwProcessId): ## self.dont_hook_function(dwProcessId, address) # erase code breakpoints for bp in self.get_process_code_breakpoints(dwProcessId): self.erase_code_breakpoint(dwProcessId, bp.get_address()) # erase page breakpoints for bp in self.get_process_page_breakpoints(dwProcessId): self.erase_page_breakpoint(dwProcessId, bp.get_address()) # erase hardware breakpoints if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): self.erase_hardware_breakpoint(dwThreadId, bp.get_address()) #------------------------------------------------------------------------------ # Internal handlers of debug events. def _notify_guard_page(self, event): """ Notify breakpoints of a guard page exception event. @type event: L{ExceptionEvent} @param event: Guard page exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ address = event.get_fault_address() pid = event.get_pid() bCallHandler = True # Align address to page boundary. mask = ~(MemoryAddresses.pageSize - 1) address = address & mask # Do we have an active page breakpoint there? key = (pid, address) if key in self.__pageBP: bp = self.__pageBP[key] if bp.is_enabled() or bp.is_one_shot(): # Breakpoint is ours. event.continueStatus = win32.DBG_CONTINUE ## event.continueStatus = win32.DBG_EXCEPTION_HANDLED # Hit the breakpoint. bp.hit(event) # Remember breakpoints in RUNNING state. if bp.is_running(): tid = event.get_tid() self.__add_running_bp(tid, bp) # Evaluate the breakpoint condition. bCondition = bp.eval_condition(event) # If the breakpoint is automatic, run the action. # If not, notify the user. if bCondition and bp.is_automatic(): bp.run_action(event) bCallHandler = False else: bCallHandler = bCondition # If we don't have a breakpoint here pass the exception to the debugee. # This is a normally occurring exception so we shouldn't swallow it. else: event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED return bCallHandler def _notify_breakpoint(self, event): """ Notify breakpoints of a breakpoint exception event. @type event: L{ExceptionEvent} @param event: Breakpoint exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ address = event.get_exception_address() pid = event.get_pid() bCallHandler = True # Do we have an active code breakpoint there? key = (pid, address) if key in self.__codeBP: bp = self.__codeBP[key] if not bp.is_disabled(): # Change the program counter (PC) to the exception address. # This accounts for the change in PC caused by # executing the breakpoint instruction, no matter # the size of it. aThread = event.get_thread() aThread.set_pc(address) # Swallow the exception. event.continueStatus = win32.DBG_CONTINUE # Hit the breakpoint. bp.hit(event) # Remember breakpoints in RUNNING state. if bp.is_running(): tid = event.get_tid() self.__add_running_bp(tid, bp) # Evaluate the breakpoint condition. bCondition = bp.eval_condition(event) # If the breakpoint is automatic, run the action. # If not, notify the user. if bCondition and bp.is_automatic(): bCallHandler = bp.run_action(event) else: bCallHandler = bCondition # Handle the system breakpoint. # TODO: examine the stack trace to figure out if it's really a # system breakpoint or an antidebug trick. The caller should be # inside ntdll if it's legit. elif event.get_process().is_system_defined_breakpoint(address): event.continueStatus = win32.DBG_CONTINUE # In hostile mode, if we don't have a breakpoint here pass the # exception to the debugee. In normal mode assume all breakpoint # exceptions are to be handled by the debugger. else: if self.in_hostile_mode(): event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED else: event.continueStatus = win32.DBG_CONTINUE return bCallHandler def _notify_single_step(self, event): """ Notify breakpoints of a single step exception event. @type event: L{ExceptionEvent} @param event: Single step exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ pid = event.get_pid() tid = event.get_tid() aThread = event.get_thread() aProcess = event.get_process() bCallHandler = True bIsOurs = False # In hostile mode set the default to pass the exception to the debugee. # If we later determine the exception is ours, hide it instead. old_continueStatus = event.continueStatus try: if self.in_hostile_mode(): event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED # Single step support is implemented on x86/x64 architectures only. if self.system.arch not in (win32.ARCH_I386, win32.ARCH_AMD64): return bCallHandler # In hostile mode, read the last executed bytes to try to detect # some antidebug tricks. Skip this check in normal mode because # it'd slow things down. # # FIXME: weird opcode encodings may bypass this check! # # bFakeSingleStep: Ice Breakpoint undocumented instruction. # bHideTrapFlag: Don't let pushf instructions get the real value of # the trap flag. # bNextIsPopFlags: Don't let popf instructions clear the trap flag. # bFakeSingleStep = False bLastIsPushFlags = False bNextIsPopFlags = False if self.in_hostile_mode(): pc = aThread.get_pc() c = aProcess.read_char(pc - 1) if c == 0xF1: # int1 bFakeSingleStep = True elif c == 0x9C: # pushf bLastIsPushFlags = True c = aProcess.peek_char(pc) if c == 0x66: # the only valid prefix for popf c = aProcess.peek_char(pc + 1) if c == 0x9D: # popf if bLastIsPushFlags: bLastIsPushFlags = False # they cancel each other out else: bNextIsPopFlags = True # When the thread is in tracing mode, # don't pass the exception to the debugee # and set the trap flag again. if self.is_tracing(tid): bIsOurs = True if not bFakeSingleStep: event.continueStatus = win32.DBG_CONTINUE aThread.set_tf() # Don't let the debugee read or write the trap flag. # This code works in 32 and 64 bits thanks to the endianness. if bLastIsPushFlags or bNextIsPopFlags: sp = aThread.get_sp() flags = aProcess.read_dword(sp) if bLastIsPushFlags: flags &= ~Thread.Flags.Trap else: # if bNextIsPopFlags: flags |= Thread.Flags.Trap aProcess.write_dword(sp, flags) # Handle breakpoints in RUNNING state. running = self.__get_running_bp_set(tid) if running: bIsOurs = True if not bFakeSingleStep: event.continueStatus = win32.DBG_CONTINUE bCallHandler = False while running: try: running.pop().hit(event) except Exception: e = sys.exc_info()[1] warnings.warn(str(e), BreakpointWarning) # Handle hardware breakpoints. if tid in self.__hardwareBP: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) Dr6 = ctx['Dr6'] ctx['Dr6'] = Dr6 & DebugRegister.clearHitMask aThread.set_context(ctx) bFoundBreakpoint = False bCondition = False hwbpList = [ bp for bp in self.__hardwareBP[tid] ] for bp in hwbpList: if not bp in self.__hardwareBP[tid]: continue # it was removed by a user-defined callback slot = bp.get_slot() if (slot is not None) and \ (Dr6 & DebugRegister.hitMask[slot]): if not bFoundBreakpoint: #set before actions are called if not bFakeSingleStep: event.continueStatus = win32.DBG_CONTINUE bFoundBreakpoint = True bIsOurs = True bp.hit(event) if bp.is_running(): self.__add_running_bp(tid, bp) bThisCondition = bp.eval_condition(event) if bThisCondition and bp.is_automatic(): bp.run_action(event) bThisCondition = False bCondition = bCondition or bThisCondition if bFoundBreakpoint: bCallHandler = bCondition # Always call the user-defined handler # when the thread is in tracing mode. if self.is_tracing(tid): bCallHandler = True # If we're not in hostile mode, by default we assume all single # step exceptions are caused by the debugger. if not bIsOurs and not self.in_hostile_mode(): aThread.clear_tf() # If the user hit Control-C while we were inside the try block, # set the default continueStatus back. except: event.continueStatus = old_continueStatus raise return bCallHandler def _notify_load_dll(self, event): """ Notify the loading of a DLL. @type event: L{LoadDLLEvent} @param event: Load DLL event. @rtype: bool @return: C{True} to call the user-defined handler, C{False} otherwise. """ self.__set_deferred_breakpoints(event) return True def _notify_unload_dll(self, event): """ Notify the unloading of a DLL. @type event: L{UnloadDLLEvent} @param event: Unload DLL event. @rtype: bool @return: C{True} to call the user-defined handler, C{False} otherwise. """ self.__cleanup_module(event) return True def _notify_exit_thread(self, event): """ Notify the termination of a thread. @type event: L{ExitThreadEvent} @param event: Exit thread event. @rtype: bool @return: C{True} to call the user-defined handler, C{False} otherwise. """ self.__cleanup_thread(event) return True def _notify_exit_process(self, event): """ Notify the termination of a process. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handler, C{False} otherwise. """ self.__cleanup_process(event) self.__cleanup_thread(event) return True #------------------------------------------------------------------------------ # This is the high level breakpoint interface. Here we don't have to care # about defining or enabling breakpoints, and many errors are ignored # (like for example setting the same breakpoint twice, here the second # breakpoint replaces the first, much like in WinDBG). It should be easier # and more intuitive, if less detailed. It also allows the use of deferred # breakpoints. #------------------------------------------------------------------------------ # Code breakpoints def __set_break(self, pid, address, action, oneshot): """ Used by L{break_at} and L{stalk_at}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type action: function @param action: (Optional) Action callback function. See L{define_code_breakpoint} for more details. @type oneshot: bool @param oneshot: C{True} for one-shot breakpoints, C{False} otherwise. @rtype: L{Breakpoint} @return: Returns the new L{Breakpoint} object, or C{None} if the label couldn't be resolved and the breakpoint was deferred. Deferred breakpoints are set when the DLL they point to is loaded. """ if type(address) not in (int, long): label = address try: address = self.system.get_process(pid).resolve_label(address) if not address: raise Exception() except Exception: try: deferred = self.__deferredBP[pid] except KeyError: deferred = dict() self.__deferredBP[pid] = deferred if label in deferred: msg = "Redefined deferred code breakpoint at %s in process ID %d" msg = msg % (label, pid) warnings.warn(msg, BreakpointWarning) deferred[label] = (action, oneshot) return None if self.has_code_breakpoint(pid, address): bp = self.get_code_breakpoint(pid, address) if bp.get_action() != action: # can't use "is not", fails for bound methods bp.set_action(action) msg = "Redefined code breakpoint at %s in process ID %d" msg = msg % (label, pid) warnings.warn(msg, BreakpointWarning) else: self.define_code_breakpoint(pid, address, True, action) bp = self.get_code_breakpoint(pid, address) if oneshot: if not bp.is_one_shot(): self.enable_one_shot_code_breakpoint(pid, address) else: if not bp.is_enabled(): self.enable_code_breakpoint(pid, address) return bp def __clear_break(self, pid, address): """ Used by L{dont_break_at} and L{dont_stalk_at}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. """ if type(address) not in (int, long): unknown = True label = address try: deferred = self.__deferredBP[pid] del deferred[label] unknown = False except KeyError: ## traceback.print_last() # XXX DEBUG pass aProcess = self.system.get_process(pid) try: address = aProcess.resolve_label(label) if not address: raise Exception() except Exception: ## traceback.print_last() # XXX DEBUG if unknown: msg = ("Can't clear unknown code breakpoint" " at %s in process ID %d") msg = msg % (label, pid) warnings.warn(msg, BreakpointWarning) return if self.has_code_breakpoint(pid, address): self.erase_code_breakpoint(pid, address) def __set_deferred_breakpoints(self, event): """ Used internally. Sets all deferred breakpoints for a DLL when it's loaded. @type event: L{LoadDLLEvent} @param event: Load DLL event. """ pid = event.get_pid() try: deferred = self.__deferredBP[pid] except KeyError: return aProcess = event.get_process() for (label, (action, oneshot)) in deferred.items(): try: address = aProcess.resolve_label(label) except Exception: continue del deferred[label] try: self.__set_break(pid, address, action, oneshot) except Exception: msg = "Can't set deferred breakpoint %s at process ID %d" msg = msg % (label, pid) warnings.warn(msg, BreakpointWarning) def get_all_deferred_code_breakpoints(self): """ Returns a list of deferred code breakpoints. @rtype: tuple of (int, str, callable, bool) @return: Tuple containing the following elements: - Process ID where to set the breakpoint. - Label pointing to the address where to set the breakpoint. - Action callback for the breakpoint. - C{True} of the breakpoint is one-shot, C{False} otherwise. """ result = [] for pid, deferred in compat.iteritems(self.__deferredBP): for (label, (action, oneshot)) in compat.iteritems(deferred): result.add( (pid, label, action, oneshot) ) return result def get_process_deferred_code_breakpoints(self, dwProcessId): """ Returns a list of deferred code breakpoints. @type dwProcessId: int @param dwProcessId: Process ID. @rtype: tuple of (int, str, callable, bool) @return: Tuple containing the following elements: - Label pointing to the address where to set the breakpoint. - Action callback for the breakpoint. - C{True} of the breakpoint is one-shot, C{False} otherwise. """ return [ (label, action, oneshot) for (label, (action, oneshot)) in compat.iteritems(self.__deferredBP.get(dwProcessId, {})) ] def stalk_at(self, pid, address, action = None): """ Sets a one shot code breakpoint at the given process and address. If instead of an address you pass a label, the breakpoint may be deferred until the DLL it points to is loaded. @see: L{break_at}, L{dont_stalk_at} @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type action: function @param action: (Optional) Action callback function. See L{define_code_breakpoint} for more details. @rtype: bool @return: C{True} if the breakpoint was set immediately, or C{False} if it was deferred. """ bp = self.__set_break(pid, address, action, oneshot = True) return bp is not None def break_at(self, pid, address, action = None): """ Sets a code breakpoint at the given process and address. If instead of an address you pass a label, the breakpoint may be deferred until the DLL it points to is loaded. @see: L{stalk_at}, L{dont_break_at} @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type action: function @param action: (Optional) Action callback function. See L{define_code_breakpoint} for more details. @rtype: bool @return: C{True} if the breakpoint was set immediately, or C{False} if it was deferred. """ bp = self.__set_break(pid, address, action, oneshot = False) return bp is not None def dont_break_at(self, pid, address): """ Clears a code breakpoint set by L{break_at}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. """ self.__clear_break(pid, address) def dont_stalk_at(self, pid, address): """ Clears a code breakpoint set by L{stalk_at}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. """ self.__clear_break(pid, address) #------------------------------------------------------------------------------ # Function hooks def hook_function(self, pid, address, preCB = None, postCB = None, paramCount = None, signature = None): """ Sets a function hook at the given address. If instead of an address you pass a label, the hook may be deferred until the DLL it points to is loaded. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type preCB: function @param preCB: (Optional) Callback triggered on function entry. The signature for the callback should be something like this:: def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags): # return address ra = params[0] # function arguments start from here... szFilename = event.get_process().peek_string(lpFilename) # (...) Note that all pointer types are treated like void pointers, so your callback won't get the string or structure pointed to by it, but the remote memory address instead. This is so to prevent the ctypes library from being "too helpful" and trying to dereference the pointer. To get the actual data being pointed to, use one of the L{Process.read} methods. @type postCB: function @param postCB: (Optional) Callback triggered on function exit. The signature for the callback should be something like this:: def post_LoadLibraryEx(event, return_value): # (...) @type paramCount: int @param paramCount: (Optional) Number of parameters for the C{preCB} callback, not counting the return address. Parameters are read from the stack and assumed to be DWORDs in 32 bits and QWORDs in 64. This is a faster way to pull stack parameters in 32 bits, but in 64 bits (or with some odd APIs in 32 bits) it won't be useful, since not all arguments to the hooked function will be of the same size. For a more reliable and cross-platform way of hooking use the C{signature} argument instead. @type signature: tuple @param signature: (Optional) Tuple of C{ctypes} data types that constitute the hooked function signature. When the function is called, this will be used to parse the arguments from the stack. Overrides the C{paramCount} argument. @rtype: bool @return: C{True} if the hook was set immediately, or C{False} if it was deferred. """ try: aProcess = self.system.get_process(pid) except KeyError: aProcess = Process(pid) arch = aProcess.get_arch() hookObj = Hook(preCB, postCB, paramCount, signature, arch) bp = self.break_at(pid, address, hookObj) return bp is not None def stalk_function(self, pid, address, preCB = None, postCB = None, paramCount = None, signature = None): """ Sets a one-shot function hook at the given address. If instead of an address you pass a label, the hook may be deferred until the DLL it points to is loaded. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type preCB: function @param preCB: (Optional) Callback triggered on function entry. The signature for the callback should be something like this:: def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags): # return address ra = params[0] # function arguments start from here... szFilename = event.get_process().peek_string(lpFilename) # (...) Note that all pointer types are treated like void pointers, so your callback won't get the string or structure pointed to by it, but the remote memory address instead. This is so to prevent the ctypes library from being "too helpful" and trying to dereference the pointer. To get the actual data being pointed to, use one of the L{Process.read} methods. @type postCB: function @param postCB: (Optional) Callback triggered on function exit. The signature for the callback should be something like this:: def post_LoadLibraryEx(event, return_value): # (...) @type paramCount: int @param paramCount: (Optional) Number of parameters for the C{preCB} callback, not counting the return address. Parameters are read from the stack and assumed to be DWORDs in 32 bits and QWORDs in 64. This is a faster way to pull stack parameters in 32 bits, but in 64 bits (or with some odd APIs in 32 bits) it won't be useful, since not all arguments to the hooked function will be of the same size. For a more reliable and cross-platform way of hooking use the C{signature} argument instead. @type signature: tuple @param signature: (Optional) Tuple of C{ctypes} data types that constitute the hooked function signature. When the function is called, this will be used to parse the arguments from the stack. Overrides the C{paramCount} argument. @rtype: bool @return: C{True} if the breakpoint was set immediately, or C{False} if it was deferred. """ try: aProcess = self.system.get_process(pid) except KeyError: aProcess = Process(pid) arch = aProcess.get_arch() hookObj = Hook(preCB, postCB, paramCount, signature, arch) bp = self.stalk_at(pid, address, hookObj) return bp is not None def dont_hook_function(self, pid, address): """ Removes a function hook set by L{hook_function}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. """ self.dont_break_at(pid, address) # alias unhook_function = dont_hook_function def dont_stalk_function(self, pid, address): """ Removes a function hook set by L{stalk_function}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. """ self.dont_stalk_at(pid, address) #------------------------------------------------------------------------------ # Variable watches def __set_variable_watch(self, tid, address, size, action): """ Used by L{watch_variable} and L{stalk_variable}. @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to watch. @type size: int @param size: Size of variable to watch. The only supported sizes are: byte (1), word (2), dword (4) and qword (8). @type action: function @param action: (Optional) Action callback function. See L{define_hardware_breakpoint} for more details. @rtype: L{HardwareBreakpoint} @return: Hardware breakpoint at the requested address. """ # TODO # We should merge the breakpoints instead of overwriting them. # We'll have the same problem as watch_buffer and we'll need to change # the API again. if size == 1: sizeFlag = self.BP_WATCH_BYTE elif size == 2: sizeFlag = self.BP_WATCH_WORD elif size == 4: sizeFlag = self.BP_WATCH_DWORD elif size == 8: sizeFlag = self.BP_WATCH_QWORD else: raise ValueError("Bad size for variable watch: %r" % size) if self.has_hardware_breakpoint(tid, address): warnings.warn( "Hardware breakpoint in thread %d at address %s was overwritten!" \ % (tid, HexDump.address(address, self.system.get_thread(tid).get_bits())), BreakpointWarning) bp = self.get_hardware_breakpoint(tid, address) if bp.get_trigger() != self.BP_BREAK_ON_ACCESS or \ bp.get_watch() != sizeFlag: self.erase_hardware_breakpoint(tid, address) self.define_hardware_breakpoint(tid, address, self.BP_BREAK_ON_ACCESS, sizeFlag, True, action) bp = self.get_hardware_breakpoint(tid, address) else: self.define_hardware_breakpoint(tid, address, self.BP_BREAK_ON_ACCESS, sizeFlag, True, action) bp = self.get_hardware_breakpoint(tid, address) return bp def __clear_variable_watch(self, tid, address): """ Used by L{dont_watch_variable} and L{dont_stalk_variable}. @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to stop watching. """ if self.has_hardware_breakpoint(tid, address): self.erase_hardware_breakpoint(tid, address) def watch_variable(self, tid, address, size, action = None): """ Sets a hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to watch. @type size: int @param size: Size of variable to watch. The only supported sizes are: byte (1), word (2), dword (4) and qword (8). @type action: function @param action: (Optional) Action callback function. See L{define_hardware_breakpoint} for more details. """ bp = self.__set_variable_watch(tid, address, size, action) if not bp.is_enabled(): self.enable_hardware_breakpoint(tid, address) def stalk_variable(self, tid, address, size, action = None): """ Sets a one-shot hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to watch. @type size: int @param size: Size of variable to watch. The only supported sizes are: byte (1), word (2), dword (4) and qword (8). @type action: function @param action: (Optional) Action callback function. See L{define_hardware_breakpoint} for more details. """ bp = self.__set_variable_watch(tid, address, size, action) if not bp.is_one_shot(): self.enable_one_shot_hardware_breakpoint(tid, address) def dont_watch_variable(self, tid, address): """ Clears a hardware breakpoint set by L{watch_variable}. @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to stop watching. """ self.__clear_variable_watch(tid, address) def dont_stalk_variable(self, tid, address): """ Clears a hardware breakpoint set by L{stalk_variable}. @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to stop watching. """ self.__clear_variable_watch(tid, address) #------------------------------------------------------------------------------ # Buffer watches def __set_buffer_watch(self, pid, address, size, action, bOneShot): """ Used by L{watch_buffer} and L{stalk_buffer}. @type pid: int @param pid: Process global ID. @type address: int @param address: Memory address of buffer to watch. @type size: int @param size: Size in bytes of buffer to watch. @type action: function @param action: (Optional) Action callback function. See L{define_page_breakpoint} for more details. @type bOneShot: bool @param bOneShot: C{True} to set a one-shot breakpoint, C{False} to set a normal breakpoint. """ # Check the size isn't zero or negative. if size < 1: raise ValueError("Bad size for buffer watch: %r" % size) # Create the buffer watch identifier. bw = BufferWatch(pid, address, address + size, action, bOneShot) # Get the base address and size in pages required for this buffer. base = MemoryAddresses.align_address_to_page_start(address) limit = MemoryAddresses.align_address_to_page_end(address + size) pages = MemoryAddresses.get_buffer_size_in_pages(address, size) try: # For each page: # + if a page breakpoint exists reuse it # + if it doesn't exist define it bset = set() # all breakpoints used nset = set() # newly defined breakpoints cset = set() # condition objects page_addr = base pageSize = MemoryAddresses.pageSize while page_addr < limit: # If a breakpoints exists, reuse it. if self.has_page_breakpoint(pid, page_addr): bp = self.get_page_breakpoint(pid, page_addr) if bp not in bset: condition = bp.get_condition() if not condition in cset: if not isinstance(condition,_BufferWatchCondition): # this shouldn't happen unless you tinkered # with it or defined your own page breakpoints # manually. msg = "Can't watch buffer at page %s" msg = msg % HexDump.address(page_addr) raise RuntimeError(msg) cset.add(condition) bset.add(bp) # If it doesn't, define it. else: condition = _BufferWatchCondition() bp = self.define_page_breakpoint(pid, page_addr, 1, condition = condition) bset.add(bp) nset.add(bp) cset.add(condition) # Next page. page_addr = page_addr + pageSize # For each breakpoint, enable it if needed. aProcess = self.system.get_process(pid) for bp in bset: if bp.is_disabled() or bp.is_one_shot(): bp.enable(aProcess, None) # On error... except: # Erase the newly defined breakpoints. for bp in nset: try: self.erase_page_breakpoint(pid, bp.get_address()) except: pass # Pass the exception to the caller raise # For each condition object, add the new buffer. for condition in cset: condition.add(bw) def __clear_buffer_watch_old_method(self, pid, address, size): """ Used by L{dont_watch_buffer} and L{dont_stalk_buffer}. @warn: Deprecated since WinAppDbg 1.5. @type pid: int @param pid: Process global ID. @type address: int @param address: Memory address of buffer to stop watching. @type size: int @param size: Size in bytes of buffer to stop watching. """ warnings.warn("Deprecated since WinAppDbg 1.5", DeprecationWarning) # Check the size isn't zero or negative. if size < 1: raise ValueError("Bad size for buffer watch: %r" % size) # Get the base address and size in pages required for this buffer. base = MemoryAddresses.align_address_to_page_start(address) limit = MemoryAddresses.align_address_to_page_end(address + size) pages = MemoryAddresses.get_buffer_size_in_pages(address, size) # For each page, get the breakpoint and it's condition object. # For each condition, remove the buffer. # For each breakpoint, if no buffers are on watch, erase it. cset = set() # condition objects page_addr = base pageSize = MemoryAddresses.pageSize while page_addr < limit: if self.has_page_breakpoint(pid, page_addr): bp = self.get_page_breakpoint(pid, page_addr) condition = bp.get_condition() if condition not in cset: if not isinstance(condition, _BufferWatchCondition): # this shouldn't happen unless you tinkered with it # or defined your own page breakpoints manually. continue cset.add(condition) condition.remove_last_match(address, size) if condition.count() == 0: try: self.erase_page_breakpoint(pid, bp.get_address()) except WindowsError: pass page_addr = page_addr + pageSize def __clear_buffer_watch(self, bw): """ Used by L{dont_watch_buffer} and L{dont_stalk_buffer}. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. """ # Get the PID and the start and end addresses of the buffer. pid = bw.pid start = bw.start end = bw.end # Get the base address and size in pages required for the buffer. base = MemoryAddresses.align_address_to_page_start(start) limit = MemoryAddresses.align_address_to_page_end(end) pages = MemoryAddresses.get_buffer_size_in_pages(start, end - start) # For each page, get the breakpoint and it's condition object. # For each condition, remove the buffer. # For each breakpoint, if no buffers are on watch, erase it. cset = set() # condition objects page_addr = base pageSize = MemoryAddresses.pageSize while page_addr < limit: if self.has_page_breakpoint(pid, page_addr): bp = self.get_page_breakpoint(pid, page_addr) condition = bp.get_condition() if condition not in cset: if not isinstance(condition, _BufferWatchCondition): # this shouldn't happen unless you tinkered with it # or defined your own page breakpoints manually. continue cset.add(condition) condition.remove(bw) if condition.count() == 0: try: self.erase_page_breakpoint(pid, bp.get_address()) except WindowsError: msg = "Cannot remove page breakpoint at address %s" msg = msg % HexDump.address( bp.get_address() ) warnings.warn(msg, BreakpointWarning) page_addr = page_addr + pageSize def watch_buffer(self, pid, address, size, action = None): """ Sets a page breakpoint and notifies when the given buffer is accessed. @see: L{dont_watch_variable} @type pid: int @param pid: Process global ID. @type address: int @param address: Memory address of buffer to watch. @type size: int @param size: Size in bytes of buffer to watch. @type action: function @param action: (Optional) Action callback function. See L{define_page_breakpoint} for more details. @rtype: L{BufferWatch} @return: Buffer watch identifier. """ self.__set_buffer_watch(pid, address, size, action, False) def stalk_buffer(self, pid, address, size, action = None): """ Sets a one-shot page breakpoint and notifies when the given buffer is accessed. @see: L{dont_watch_variable} @type pid: int @param pid: Process global ID. @type address: int @param address: Memory address of buffer to watch. @type size: int @param size: Size in bytes of buffer to watch. @type action: function @param action: (Optional) Action callback function. See L{define_page_breakpoint} for more details. @rtype: L{BufferWatch} @return: Buffer watch identifier. """ self.__set_buffer_watch(pid, address, size, action, True) def dont_watch_buffer(self, bw, *argv, **argd): """ Clears a page breakpoint set by L{watch_buffer}. @type bw: L{BufferWatch} @param bw: Buffer watch identifier returned by L{watch_buffer}. """ # The sane way to do it. if not (argv or argd): self.__clear_buffer_watch(bw) # Backwards compatibility with WinAppDbg 1.4. else: argv = list(argv) argv.insert(0, bw) if 'pid' in argd: argv.insert(0, argd.pop('pid')) if 'address' in argd: argv.insert(1, argd.pop('address')) if 'size' in argd: argv.insert(2, argd.pop('size')) if argd: raise TypeError("Wrong arguments for dont_watch_buffer()") try: pid, address, size = argv except ValueError: raise TypeError("Wrong arguments for dont_watch_buffer()") self.__clear_buffer_watch_old_method(pid, address, size) def dont_stalk_buffer(self, bw, *argv, **argd): """ Clears a page breakpoint set by L{stalk_buffer}. @type bw: L{BufferWatch} @param bw: Buffer watch identifier returned by L{stalk_buffer}. """ self.dont_watch_buffer(bw, *argv, **argd) #------------------------------------------------------------------------------ # Tracing # XXX TODO # Add "action" parameter to tracing mode def __start_tracing(self, thread): """ @type thread: L{Thread} @param thread: Thread to start tracing. """ tid = thread.get_tid() if not tid in self.__tracing: thread.set_tf() self.__tracing.add(tid) def __stop_tracing(self, thread): """ @type thread: L{Thread} @param thread: Thread to stop tracing. """ tid = thread.get_tid() if tid in self.__tracing: self.__tracing.remove(tid) if thread.is_alive(): thread.clear_tf() def is_tracing(self, tid): """ @type tid: int @param tid: Thread global ID. @rtype: bool @return: C{True} if the thread is being traced, C{False} otherwise. """ return tid in self.__tracing def get_traced_tids(self): """ Retrieves the list of global IDs of all threads being traced. @rtype: list( int... ) @return: List of thread global IDs. """ tids = list(self.__tracing) tids.sort() return tids def start_tracing(self, tid): """ Start tracing mode in the given thread. @type tid: int @param tid: Global ID of thread to start tracing. """ if not self.is_tracing(tid): thread = self.system.get_thread(tid) self.__start_tracing(thread) def stop_tracing(self, tid): """ Stop tracing mode in the given thread. @type tid: int @param tid: Global ID of thread to stop tracing. """ if self.is_tracing(tid): thread = self.system.get_thread(tid) self.__stop_tracing(thread) def start_tracing_process(self, pid): """ Start tracing mode for all threads in the given process. @type pid: int @param pid: Global ID of process to start tracing. """ for thread in self.system.get_process(pid).iter_threads(): self.__start_tracing(thread) def stop_tracing_process(self, pid): """ Stop tracing mode for all threads in the given process. @type pid: int @param pid: Global ID of process to stop tracing. """ for thread in self.system.get_process(pid).iter_threads(): self.__stop_tracing(thread) def start_tracing_all(self): """ Start tracing mode for all threads in all debugees. """ for pid in self.get_debugee_pids(): self.start_tracing_process(pid) def stop_tracing_all(self): """ Stop tracing mode for all threads in all debugees. """ for pid in self.get_debugee_pids(): self.stop_tracing_process(pid) #------------------------------------------------------------------------------ # Break on LastError values (only available since Windows Server 2003) def break_on_error(self, pid, errorCode): """ Sets or clears the system breakpoint for a given Win32 error code. Use L{Process.is_system_defined_breakpoint} to tell if a breakpoint exception was caused by a system breakpoint or by the application itself (for example because of a failed assertion in the code). @note: This functionality is only available since Windows Server 2003. In 2003 it only breaks on error values set externally to the kernel32.dll library, but this was fixed in Windows Vista. @warn: This method will fail if the debug symbols for ntdll (kernel32 in Windows 2003) are not present. For more information see: L{System.fix_symbol_store_path}. @see: U{http://www.nynaeve.net/?p=147} @type pid: int @param pid: Process ID. @type errorCode: int @param errorCode: Win32 error code to stop on. Set to C{0} or C{ERROR_SUCCESS} to clear the breakpoint instead. @raise NotImplementedError: The functionality is not supported in this system. @raise WindowsError: An error occurred while processing this request. """ aProcess = self.system.get_process(pid) address = aProcess.get_break_on_error_ptr() if not address: raise NotImplementedError( "The functionality is not supported in this system.") aProcess.write_dword(address, errorCode) def dont_break_on_error(self, pid): """ Alias to L{break_on_error}C{(pid, ERROR_SUCCESS)}. @type pid: int @param pid: Process ID. @raise NotImplementedError: The functionality is not supported in this system. @raise WindowsError: An error occurred while processing this request. """ self.break_on_error(pid, 0) #------------------------------------------------------------------------------ # Simplified symbol resolving, useful for hooking functions def resolve_exported_function(self, pid, modName, procName): """ Resolves the exported DLL function for the given process. @type pid: int @param pid: Process global ID. @type modName: str @param modName: Name of the module that exports the function. @type procName: str @param procName: Name of the exported function to resolve. @rtype: int, None @return: On success, the address of the exported function. On failure, returns C{None}. """ aProcess = self.system.get_process(pid) aModule = aProcess.get_module_by_name(modName) if not aModule: aProcess.scan_modules() aModule = aProcess.get_module_by_name(modName) if aModule: address = aModule.resolve(procName) return address return None def resolve_label(self, pid, label): """ Resolves a label for the given process. @type pid: int @param pid: Process global ID. @type label: str @param label: Label to resolve. @rtype: int @return: Memory address pointed to by the label. @raise ValueError: The label is malformed or impossible to resolve. @raise RuntimeError: Cannot resolve the module or function. """ return self.get_process(pid).resolve_label(label)
168,168
Python
33.868132
105
0.561563
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/event.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Event handling module. @see: U{http://apps.sourceforge.net/trac/winappdbg/wiki/Debugging} @group Debugging: EventHandler, EventSift @group Debug events: EventFactory, EventDispatcher, Event, NoEvent, CreateProcessEvent, CreateThreadEvent, ExitProcessEvent, ExitThreadEvent, LoadDLLEvent, UnloadDLLEvent, OutputDebugStringEvent, RIPEvent, ExceptionEvent @group Warnings: EventCallbackWarning """ __revision__ = "$Id$" __all__ = [ # Factory of Event objects and all of it's subclasses. # Users should not need to instance Event objects directly. 'EventFactory', # Event dispatcher used internally by the Debug class. 'EventDispatcher', # Base classes for user-defined event handlers. 'EventHandler', 'EventSift', # Warning for uncaught exceptions on event callbacks. 'EventCallbackWarning', # Dummy event object that can be used as a placeholder. # It's never returned by the EventFactory. 'NoEvent', # Base class for event objects. 'Event', # Event objects. 'CreateProcessEvent', 'CreateThreadEvent', 'ExitProcessEvent', 'ExitThreadEvent', 'LoadDLLEvent', 'UnloadDLLEvent', 'OutputDebugStringEvent', 'RIPEvent', 'ExceptionEvent' ] from winappdbg import win32 from winappdbg import compat from winappdbg.win32 import FileHandle, ProcessHandle, ThreadHandle from winappdbg.breakpoint import ApiHook from winappdbg.module import Module from winappdbg.thread import Thread from winappdbg.process import Process from winappdbg.textio import HexDump from winappdbg.util import StaticClass, PathOperations import sys import ctypes import warnings import traceback #============================================================================== class EventCallbackWarning (RuntimeWarning): """ This warning is issued when an uncaught exception was raised by a user-defined event handler. """ #============================================================================== class Event (object): """ Event object. @type eventMethod: str @cvar eventMethod: Method name to call when using L{EventHandler} subclasses. Used internally. @type eventName: str @cvar eventName: User-friendly name of the event. @type eventDescription: str @cvar eventDescription: User-friendly description of the event. @type debug: L{Debug} @ivar debug: Debug object that received the event. @type raw: L{DEBUG_EVENT} @ivar raw: Raw DEBUG_EVENT structure as used by the Win32 API. @type continueStatus: int @ivar continueStatus: Continue status to pass to L{win32.ContinueDebugEvent}. """ eventMethod = 'unknown_event' eventName = 'Unknown event' eventDescription = 'A debug event of an unknown type has occured.' def __init__(self, debug, raw): """ @type debug: L{Debug} @param debug: Debug object that received the event. @type raw: L{DEBUG_EVENT} @param raw: Raw DEBUG_EVENT structure as used by the Win32 API. """ self.debug = debug self.raw = raw self.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED ## @property ## def debug(self): ## """ ## @rtype debug: L{Debug} ## @return debug: ## Debug object that received the event. ## """ ## return self.__debug() def get_event_name(self): """ @rtype: str @return: User-friendly name of the event. """ return self.eventName def get_event_description(self): """ @rtype: str @return: User-friendly description of the event. """ return self.eventDescription def get_event_code(self): """ @rtype: int @return: Debug event code as defined in the Win32 API. """ return self.raw.dwDebugEventCode ## # Compatibility with version 1.0 ## # XXX to be removed in version 1.4 ## def get_code(self): ## """ ## Alias of L{get_event_code} for backwards compatibility ## with WinAppDbg version 1.0. ## Will be phased out in the next version. ## ## @rtype: int ## @return: Debug event code as defined in the Win32 API. ## """ ## return self.get_event_code() def get_pid(self): """ @see: L{get_process} @rtype: int @return: Process global ID where the event occured. """ return self.raw.dwProcessId def get_tid(self): """ @see: L{get_thread} @rtype: int @return: Thread global ID where the event occured. """ return self.raw.dwThreadId def get_process(self): """ @see: L{get_pid} @rtype: L{Process} @return: Process where the event occured. """ pid = self.get_pid() system = self.debug.system if system.has_process(pid): process = system.get_process(pid) else: # XXX HACK # The process object was missing for some reason, so make a new one. process = Process(pid) system._add_process(process) ## process.scan_threads() # not needed process.scan_modules() return process def get_thread(self): """ @see: L{get_tid} @rtype: L{Thread} @return: Thread where the event occured. """ tid = self.get_tid() process = self.get_process() if process.has_thread(tid): thread = process.get_thread(tid) else: # XXX HACK # The thread object was missing for some reason, so make a new one. thread = Thread(tid) process._add_thread(thread) return thread #============================================================================== class NoEvent (Event): """ No event. Dummy L{Event} object that can be used as a placeholder when no debug event has occured yet. It's never returned by the L{EventFactory}. """ eventMethod = 'no_event' eventName = 'No event' eventDescription = 'No debug event has occured.' def __init__(self, debug, raw = None): Event.__init__(self, debug, raw) def __len__(self): """ Always returns C{0}, so when evaluating the object as a boolean it's always C{False}. This prevents L{Debug.cont} from trying to continue a dummy event. """ return 0 def get_event_code(self): return -1 def get_pid(self): return -1 def get_tid(self): return -1 def get_process(self): return Process(self.get_pid()) def get_thread(self): return Thread(self.get_tid()) #============================================================================== class ExceptionEvent (Event): """ Exception event. @type exceptionName: dict( int S{->} str ) @cvar exceptionName: Mapping of exception constants to their names. @type exceptionDescription: dict( int S{->} str ) @cvar exceptionDescription: Mapping of exception constants to user-friendly strings. @type breakpoint: L{Breakpoint} @ivar breakpoint: If the exception was caused by one of our breakpoints, this member contains a reference to the breakpoint object. Otherwise it's not defined. It should only be used from the condition or action callback routines, instead of the event handler. @type hook: L{Hook} @ivar hook: If the exception was caused by a function hook, this member contains a reference to the hook object. Otherwise it's not defined. It should only be used from the hook callback routines, instead of the event handler. """ eventName = 'Exception event' eventDescription = 'An exception was raised by the debugee.' __exceptionMethod = { win32.EXCEPTION_ACCESS_VIOLATION : 'access_violation', win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED : 'array_bounds_exceeded', win32.EXCEPTION_BREAKPOINT : 'breakpoint', win32.EXCEPTION_DATATYPE_MISALIGNMENT : 'datatype_misalignment', win32.EXCEPTION_FLT_DENORMAL_OPERAND : 'float_denormal_operand', win32.EXCEPTION_FLT_DIVIDE_BY_ZERO : 'float_divide_by_zero', win32.EXCEPTION_FLT_INEXACT_RESULT : 'float_inexact_result', win32.EXCEPTION_FLT_INVALID_OPERATION : 'float_invalid_operation', win32.EXCEPTION_FLT_OVERFLOW : 'float_overflow', win32.EXCEPTION_FLT_STACK_CHECK : 'float_stack_check', win32.EXCEPTION_FLT_UNDERFLOW : 'float_underflow', win32.EXCEPTION_ILLEGAL_INSTRUCTION : 'illegal_instruction', win32.EXCEPTION_IN_PAGE_ERROR : 'in_page_error', win32.EXCEPTION_INT_DIVIDE_BY_ZERO : 'integer_divide_by_zero', win32.EXCEPTION_INT_OVERFLOW : 'integer_overflow', win32.EXCEPTION_INVALID_DISPOSITION : 'invalid_disposition', win32.EXCEPTION_NONCONTINUABLE_EXCEPTION : 'noncontinuable_exception', win32.EXCEPTION_PRIV_INSTRUCTION : 'privileged_instruction', win32.EXCEPTION_SINGLE_STEP : 'single_step', win32.EXCEPTION_STACK_OVERFLOW : 'stack_overflow', win32.EXCEPTION_GUARD_PAGE : 'guard_page', win32.EXCEPTION_INVALID_HANDLE : 'invalid_handle', win32.EXCEPTION_POSSIBLE_DEADLOCK : 'possible_deadlock', win32.EXCEPTION_WX86_BREAKPOINT : 'wow64_breakpoint', win32.CONTROL_C_EXIT : 'control_c_exit', win32.DBG_CONTROL_C : 'debug_control_c', win32.MS_VC_EXCEPTION : 'ms_vc_exception', } __exceptionName = { win32.EXCEPTION_ACCESS_VIOLATION : 'EXCEPTION_ACCESS_VIOLATION', win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED : 'EXCEPTION_ARRAY_BOUNDS_EXCEEDED', win32.EXCEPTION_BREAKPOINT : 'EXCEPTION_BREAKPOINT', win32.EXCEPTION_DATATYPE_MISALIGNMENT : 'EXCEPTION_DATATYPE_MISALIGNMENT', win32.EXCEPTION_FLT_DENORMAL_OPERAND : 'EXCEPTION_FLT_DENORMAL_OPERAND', win32.EXCEPTION_FLT_DIVIDE_BY_ZERO : 'EXCEPTION_FLT_DIVIDE_BY_ZERO', win32.EXCEPTION_FLT_INEXACT_RESULT : 'EXCEPTION_FLT_INEXACT_RESULT', win32.EXCEPTION_FLT_INVALID_OPERATION : 'EXCEPTION_FLT_INVALID_OPERATION', win32.EXCEPTION_FLT_OVERFLOW : 'EXCEPTION_FLT_OVERFLOW', win32.EXCEPTION_FLT_STACK_CHECK : 'EXCEPTION_FLT_STACK_CHECK', win32.EXCEPTION_FLT_UNDERFLOW : 'EXCEPTION_FLT_UNDERFLOW', win32.EXCEPTION_ILLEGAL_INSTRUCTION : 'EXCEPTION_ILLEGAL_INSTRUCTION', win32.EXCEPTION_IN_PAGE_ERROR : 'EXCEPTION_IN_PAGE_ERROR', win32.EXCEPTION_INT_DIVIDE_BY_ZERO : 'EXCEPTION_INT_DIVIDE_BY_ZERO', win32.EXCEPTION_INT_OVERFLOW : 'EXCEPTION_INT_OVERFLOW', win32.EXCEPTION_INVALID_DISPOSITION : 'EXCEPTION_INVALID_DISPOSITION', win32.EXCEPTION_NONCONTINUABLE_EXCEPTION : 'EXCEPTION_NONCONTINUABLE_EXCEPTION', win32.EXCEPTION_PRIV_INSTRUCTION : 'EXCEPTION_PRIV_INSTRUCTION', win32.EXCEPTION_SINGLE_STEP : 'EXCEPTION_SINGLE_STEP', win32.EXCEPTION_STACK_OVERFLOW : 'EXCEPTION_STACK_OVERFLOW', win32.EXCEPTION_GUARD_PAGE : 'EXCEPTION_GUARD_PAGE', win32.EXCEPTION_INVALID_HANDLE : 'EXCEPTION_INVALID_HANDLE', win32.EXCEPTION_POSSIBLE_DEADLOCK : 'EXCEPTION_POSSIBLE_DEADLOCK', win32.EXCEPTION_WX86_BREAKPOINT : 'EXCEPTION_WX86_BREAKPOINT', win32.CONTROL_C_EXIT : 'CONTROL_C_EXIT', win32.DBG_CONTROL_C : 'DBG_CONTROL_C', win32.MS_VC_EXCEPTION : 'MS_VC_EXCEPTION', } __exceptionDescription = { win32.EXCEPTION_ACCESS_VIOLATION : 'Access violation', win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED : 'Array bounds exceeded', win32.EXCEPTION_BREAKPOINT : 'Breakpoint', win32.EXCEPTION_DATATYPE_MISALIGNMENT : 'Datatype misalignment', win32.EXCEPTION_FLT_DENORMAL_OPERAND : 'Float denormal operand', win32.EXCEPTION_FLT_DIVIDE_BY_ZERO : 'Float divide by zero', win32.EXCEPTION_FLT_INEXACT_RESULT : 'Float inexact result', win32.EXCEPTION_FLT_INVALID_OPERATION : 'Float invalid operation', win32.EXCEPTION_FLT_OVERFLOW : 'Float overflow', win32.EXCEPTION_FLT_STACK_CHECK : 'Float stack check', win32.EXCEPTION_FLT_UNDERFLOW : 'Float underflow', win32.EXCEPTION_ILLEGAL_INSTRUCTION : 'Illegal instruction', win32.EXCEPTION_IN_PAGE_ERROR : 'In-page error', win32.EXCEPTION_INT_DIVIDE_BY_ZERO : 'Integer divide by zero', win32.EXCEPTION_INT_OVERFLOW : 'Integer overflow', win32.EXCEPTION_INVALID_DISPOSITION : 'Invalid disposition', win32.EXCEPTION_NONCONTINUABLE_EXCEPTION : 'Noncontinuable exception', win32.EXCEPTION_PRIV_INSTRUCTION : 'Privileged instruction', win32.EXCEPTION_SINGLE_STEP : 'Single step event', win32.EXCEPTION_STACK_OVERFLOW : 'Stack limits overflow', win32.EXCEPTION_GUARD_PAGE : 'Guard page hit', win32.EXCEPTION_INVALID_HANDLE : 'Invalid handle', win32.EXCEPTION_POSSIBLE_DEADLOCK : 'Possible deadlock', win32.EXCEPTION_WX86_BREAKPOINT : 'WOW64 breakpoint', win32.CONTROL_C_EXIT : 'Control-C exit', win32.DBG_CONTROL_C : 'Debug Control-C', win32.MS_VC_EXCEPTION : 'Microsoft Visual C++ exception', } @property def eventMethod(self): return self.__exceptionMethod.get( self.get_exception_code(), 'unknown_exception') def get_exception_name(self): """ @rtype: str @return: Name of the exception as defined by the Win32 API. """ code = self.get_exception_code() unk = HexDump.integer(code) return self.__exceptionName.get(code, unk) def get_exception_description(self): """ @rtype: str @return: User-friendly name of the exception. """ code = self.get_exception_code() description = self.__exceptionDescription.get(code, None) if description is None: try: description = 'Exception code %s (%s)' description = description % (HexDump.integer(code), ctypes.FormatError(code)) except OverflowError: description = 'Exception code %s' % HexDump.integer(code) return description def is_first_chance(self): """ @rtype: bool @return: C{True} for first chance exceptions, C{False} for last chance. """ return self.raw.u.Exception.dwFirstChance != 0 def is_last_chance(self): """ @rtype: bool @return: The opposite of L{is_first_chance}. """ return not self.is_first_chance() def is_noncontinuable(self): """ @see: U{http://msdn.microsoft.com/en-us/library/aa363082(VS.85).aspx} @rtype: bool @return: C{True} if the exception is noncontinuable, C{False} otherwise. Attempting to continue a noncontinuable exception results in an EXCEPTION_NONCONTINUABLE_EXCEPTION exception to be raised. """ return bool( self.raw.u.Exception.ExceptionRecord.ExceptionFlags & \ win32.EXCEPTION_NONCONTINUABLE ) def is_continuable(self): """ @rtype: bool @return: The opposite of L{is_noncontinuable}. """ return not self.is_noncontinuable() def is_user_defined_exception(self): """ Determines if this is an user-defined exception. User-defined exceptions may contain any exception code that is not system reserved. Often the exception code is also a valid Win32 error code, but that's up to the debugged application. @rtype: bool @return: C{True} if the exception is user-defined, C{False} otherwise. """ return self.get_exception_code() & 0x10000000 == 0 def is_system_defined_exception(self): """ @rtype: bool @return: The opposite of L{is_user_defined_exception}. """ return not self.is_user_defined_exception() def get_exception_code(self): """ @rtype: int @return: Exception code as defined by the Win32 API. """ return self.raw.u.Exception.ExceptionRecord.ExceptionCode def get_exception_address(self): """ @rtype: int @return: Memory address where the exception occured. """ address = self.raw.u.Exception.ExceptionRecord.ExceptionAddress if address is None: address = 0 return address def get_exception_information(self, index): """ @type index: int @param index: Index into the exception information block. @rtype: int @return: Exception information DWORD. """ if index < 0 or index > win32.EXCEPTION_MAXIMUM_PARAMETERS: raise IndexError("Array index out of range: %s" % repr(index)) info = self.raw.u.Exception.ExceptionRecord.ExceptionInformation value = info[index] if value is None: value = 0 return value def get_exception_information_as_list(self): """ @rtype: list( int ) @return: Exception information block. """ info = self.raw.u.Exception.ExceptionRecord.ExceptionInformation data = list() for index in compat.xrange(0, win32.EXCEPTION_MAXIMUM_PARAMETERS): value = info[index] if value is None: value = 0 data.append(value) return data def get_fault_type(self): """ @rtype: int @return: Access violation type. Should be one of the following constants: - L{win32.EXCEPTION_READ_FAULT} - L{win32.EXCEPTION_WRITE_FAULT} - L{win32.EXCEPTION_EXECUTE_FAULT} @note: This method is only meaningful for access violation exceptions, in-page memory error exceptions and guard page exceptions. @raise NotImplementedError: Wrong kind of exception. """ if self.get_exception_code() not in (win32.EXCEPTION_ACCESS_VIOLATION, win32.EXCEPTION_IN_PAGE_ERROR, win32.EXCEPTION_GUARD_PAGE): msg = "This method is not meaningful for %s." raise NotImplementedError(msg % self.get_exception_name()) return self.get_exception_information(0) def get_fault_address(self): """ @rtype: int @return: Access violation memory address. @note: This method is only meaningful for access violation exceptions, in-page memory error exceptions and guard page exceptions. @raise NotImplementedError: Wrong kind of exception. """ if self.get_exception_code() not in (win32.EXCEPTION_ACCESS_VIOLATION, win32.EXCEPTION_IN_PAGE_ERROR, win32.EXCEPTION_GUARD_PAGE): msg = "This method is not meaningful for %s." raise NotImplementedError(msg % self.get_exception_name()) return self.get_exception_information(1) def get_ntstatus_code(self): """ @rtype: int @return: NTSTATUS status code that caused the exception. @note: This method is only meaningful for in-page memory error exceptions. @raise NotImplementedError: Not an in-page memory error. """ if self.get_exception_code() != win32.EXCEPTION_IN_PAGE_ERROR: msg = "This method is only meaningful "\ "for in-page memory error exceptions." raise NotImplementedError(msg) return self.get_exception_information(2) def is_nested(self): """ @rtype: bool @return: Returns C{True} if there are additional exception records associated with this exception. This would mean the exception is nested, that is, it was triggered while trying to handle at least one previous exception. """ return bool(self.raw.u.Exception.ExceptionRecord.ExceptionRecord) def get_raw_exception_record_list(self): """ Traverses the exception record linked list and builds a Python list. Nested exception records are received for nested exceptions. This happens when an exception is raised in the debugee while trying to handle a previous exception. @rtype: list( L{win32.EXCEPTION_RECORD} ) @return: List of raw exception record structures as used by the Win32 API. There is always at least one exception record, so the list is never empty. All other methods of this class read from the first exception record only, that is, the most recent exception. """ # The first EXCEPTION_RECORD is contained in EXCEPTION_DEBUG_INFO. # The remaining EXCEPTION_RECORD structures are linked by pointers. nested = list() record = self.raw.u.Exception while True: record = record.ExceptionRecord if not record: break nested.append(record) return nested def get_nested_exceptions(self): """ Traverses the exception record linked list and builds a Python list. Nested exception records are received for nested exceptions. This happens when an exception is raised in the debugee while trying to handle a previous exception. @rtype: list( L{ExceptionEvent} ) @return: List of ExceptionEvent objects representing each exception record found in this event. There is always at least one exception record, so the list is never empty. All other methods of this class read from the first exception record only, that is, the most recent exception. """ # The list always begins with ourselves. # Just put a reference to "self" as the first element, # and start looping from the second exception record. nested = [ self ] raw = self.raw dwDebugEventCode = raw.dwDebugEventCode dwProcessId = raw.dwProcessId dwThreadId = raw.dwThreadId dwFirstChance = raw.u.Exception.dwFirstChance record = raw.u.Exception.ExceptionRecord while True: record = record.ExceptionRecord if not record: break raw = win32.DEBUG_EVENT() raw.dwDebugEventCode = dwDebugEventCode raw.dwProcessId = dwProcessId raw.dwThreadId = dwThreadId raw.u.Exception.ExceptionRecord = record raw.u.Exception.dwFirstChance = dwFirstChance event = EventFactory.get(self.debug, raw) nested.append(event) return nested #============================================================================== class CreateThreadEvent (Event): """ Thread creation event. """ eventMethod = 'create_thread' eventName = 'Thread creation event' eventDescription = 'A new thread has started.' def get_thread_handle(self): """ @rtype: L{ThreadHandle} @return: Thread handle received from the system. Returns C{None} if the handle is not available. """ # The handle doesn't need to be closed. # See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx hThread = self.raw.u.CreateThread.hThread if hThread in (0, win32.NULL, win32.INVALID_HANDLE_VALUE): hThread = None else: hThread = ThreadHandle(hThread, False, win32.THREAD_ALL_ACCESS) return hThread def get_teb(self): """ @rtype: int @return: Pointer to the TEB. """ return self.raw.u.CreateThread.lpThreadLocalBase def get_start_address(self): """ @rtype: int @return: Pointer to the first instruction to execute in this thread. Returns C{NULL} when the debugger attached to a process and the thread already existed. See U{http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx} """ return self.raw.u.CreateThread.lpStartAddress #============================================================================== class CreateProcessEvent (Event): """ Process creation event. """ eventMethod = 'create_process' eventName = 'Process creation event' eventDescription = 'A new process has started.' def get_file_handle(self): """ @rtype: L{FileHandle} or None @return: File handle to the main module, received from the system. Returns C{None} if the handle is not available. """ # This handle DOES need to be closed. # Therefore we must cache it so it doesn't # get closed after the first call. try: hFile = self.__hFile except AttributeError: hFile = self.raw.u.CreateProcessInfo.hFile if hFile in (0, win32.NULL, win32.INVALID_HANDLE_VALUE): hFile = None else: hFile = FileHandle(hFile, True) self.__hFile = hFile return hFile def get_process_handle(self): """ @rtype: L{ProcessHandle} @return: Process handle received from the system. Returns C{None} if the handle is not available. """ # The handle doesn't need to be closed. # See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx hProcess = self.raw.u.CreateProcessInfo.hProcess if hProcess in (0, win32.NULL, win32.INVALID_HANDLE_VALUE): hProcess = None else: hProcess = ProcessHandle(hProcess, False, win32.PROCESS_ALL_ACCESS) return hProcess def get_thread_handle(self): """ @rtype: L{ThreadHandle} @return: Thread handle received from the system. Returns C{None} if the handle is not available. """ # The handle doesn't need to be closed. # See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx hThread = self.raw.u.CreateProcessInfo.hThread if hThread in (0, win32.NULL, win32.INVALID_HANDLE_VALUE): hThread = None else: hThread = ThreadHandle(hThread, False, win32.THREAD_ALL_ACCESS) return hThread def get_start_address(self): """ @rtype: int @return: Pointer to the first instruction to execute in this process. Returns C{NULL} when the debugger attaches to a process. See U{http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx} """ return self.raw.u.CreateProcessInfo.lpStartAddress def get_image_base(self): """ @rtype: int @return: Base address of the main module. @warn: This value is taken from the PE file and may be incorrect because of ASLR! """ # TODO try to calculate the real value when ASLR is active. return self.raw.u.CreateProcessInfo.lpBaseOfImage def get_teb(self): """ @rtype: int @return: Pointer to the TEB. """ return self.raw.u.CreateProcessInfo.lpThreadLocalBase def get_debug_info(self): """ @rtype: str @return: Debugging information. """ raw = self.raw.u.CreateProcessInfo ptr = raw.lpBaseOfImage + raw.dwDebugInfoFileOffset size = raw.nDebugInfoSize data = self.get_process().peek(ptr, size) if len(data) == size: return data return None def get_filename(self): """ @rtype: str, None @return: This method does it's best to retrieve the filename to the main module of the process. However, sometimes that's not possible, and C{None} is returned instead. """ # Try to get the filename from the file handle. szFilename = None hFile = self.get_file_handle() if hFile: szFilename = hFile.get_filename() if not szFilename: # Try to get it from CREATE_PROCESS_DEBUG_INFO.lpImageName # It's NULL or *NULL most of the times, see MSDN: # http://msdn.microsoft.com/en-us/library/ms679286(VS.85).aspx aProcess = self.get_process() lpRemoteFilenamePtr = self.raw.u.CreateProcessInfo.lpImageName if lpRemoteFilenamePtr: lpFilename = aProcess.peek_uint(lpRemoteFilenamePtr) fUnicode = bool( self.raw.u.CreateProcessInfo.fUnicode ) szFilename = aProcess.peek_string(lpFilename, fUnicode) # XXX TODO # Sometimes the filename is relative (ntdll.dll, kernel32.dll). # It could be converted to an absolute pathname (SearchPath). # Try to get it from Process.get_image_name(). if not szFilename: szFilename = aProcess.get_image_name() # Return the filename, or None on error. return szFilename def get_module_base(self): """ @rtype: int @return: Base address of the main module. """ return self.get_image_base() def get_module(self): """ @rtype: L{Module} @return: Main module of the process. """ return self.get_process().get_module( self.get_module_base() ) #============================================================================== class ExitThreadEvent (Event): """ Thread termination event. """ eventMethod = 'exit_thread' eventName = 'Thread termination event' eventDescription = 'A thread has finished executing.' def get_exit_code(self): """ @rtype: int @return: Exit code of the thread. """ return self.raw.u.ExitThread.dwExitCode #============================================================================== class ExitProcessEvent (Event): """ Process termination event. """ eventMethod = 'exit_process' eventName = 'Process termination event' eventDescription = 'A process has finished executing.' def get_exit_code(self): """ @rtype: int @return: Exit code of the process. """ return self.raw.u.ExitProcess.dwExitCode def get_filename(self): """ @rtype: None or str @return: Filename of the main module. C{None} if the filename is unknown. """ return self.get_module().get_filename() def get_image_base(self): """ @rtype: int @return: Base address of the main module. """ return self.get_module_base() def get_module_base(self): """ @rtype: int @return: Base address of the main module. """ return self.get_module().get_base() def get_module(self): """ @rtype: L{Module} @return: Main module of the process. """ return self.get_process().get_main_module() #============================================================================== class LoadDLLEvent (Event): """ Module load event. """ eventMethod = 'load_dll' eventName = 'Module load event' eventDescription = 'A new DLL library was loaded by the debugee.' def get_module_base(self): """ @rtype: int @return: Base address for the newly loaded DLL. """ return self.raw.u.LoadDll.lpBaseOfDll def get_module(self): """ @rtype: L{Module} @return: Module object for the newly loaded DLL. """ lpBaseOfDll = self.get_module_base() aProcess = self.get_process() if aProcess.has_module(lpBaseOfDll): aModule = aProcess.get_module(lpBaseOfDll) else: # XXX HACK # For some reason the module object is missing, so make a new one. aModule = Module(lpBaseOfDll, hFile = self.get_file_handle(), fileName = self.get_filename(), process = aProcess) aProcess._add_module(aModule) return aModule def get_file_handle(self): """ @rtype: L{FileHandle} or None @return: File handle to the newly loaded DLL received from the system. Returns C{None} if the handle is not available. """ # This handle DOES need to be closed. # Therefore we must cache it so it doesn't # get closed after the first call. try: hFile = self.__hFile except AttributeError: hFile = self.raw.u.LoadDll.hFile if hFile in (0, win32.NULL, win32.INVALID_HANDLE_VALUE): hFile = None else: hFile = FileHandle(hFile, True) self.__hFile = hFile return hFile def get_filename(self): """ @rtype: str, None @return: This method does it's best to retrieve the filename to the newly loaded module. However, sometimes that's not possible, and C{None} is returned instead. """ szFilename = None # Try to get it from LOAD_DLL_DEBUG_INFO.lpImageName # It's NULL or *NULL most of the times, see MSDN: # http://msdn.microsoft.com/en-us/library/ms679286(VS.85).aspx aProcess = self.get_process() lpRemoteFilenamePtr = self.raw.u.LoadDll.lpImageName if lpRemoteFilenamePtr: lpFilename = aProcess.peek_uint(lpRemoteFilenamePtr) fUnicode = bool( self.raw.u.LoadDll.fUnicode ) szFilename = aProcess.peek_string(lpFilename, fUnicode) if not szFilename: szFilename = None # Try to get the filename from the file handle. if not szFilename: hFile = self.get_file_handle() if hFile: szFilename = hFile.get_filename() # Return the filename, or None on error. return szFilename #============================================================================== class UnloadDLLEvent (Event): """ Module unload event. """ eventMethod = 'unload_dll' eventName = 'Module unload event' eventDescription = 'A DLL library was unloaded by the debugee.' def get_module_base(self): """ @rtype: int @return: Base address for the recently unloaded DLL. """ return self.raw.u.UnloadDll.lpBaseOfDll def get_module(self): """ @rtype: L{Module} @return: Module object for the recently unloaded DLL. """ lpBaseOfDll = self.get_module_base() aProcess = self.get_process() if aProcess.has_module(lpBaseOfDll): aModule = aProcess.get_module(lpBaseOfDll) else: aModule = Module(lpBaseOfDll, process = aProcess) aProcess._add_module(aModule) return aModule def get_file_handle(self): """ @rtype: None or L{FileHandle} @return: File handle to the recently unloaded DLL. Returns C{None} if the handle is not available. """ hFile = self.get_module().hFile if hFile in (0, win32.NULL, win32.INVALID_HANDLE_VALUE): hFile = None return hFile def get_filename(self): """ @rtype: None or str @return: Filename of the recently unloaded DLL. C{None} if the filename is unknown. """ return self.get_module().get_filename() #============================================================================== class OutputDebugStringEvent (Event): """ Debug string output event. """ eventMethod = 'output_string' eventName = 'Debug string output event' eventDescription = 'The debugee sent a message to the debugger.' def get_debug_string(self): """ @rtype: str, compat.unicode @return: String sent by the debugee. It may be ANSI or Unicode and may end with a null character. """ return self.get_process().peek_string( self.raw.u.DebugString.lpDebugStringData, bool( self.raw.u.DebugString.fUnicode ), self.raw.u.DebugString.nDebugStringLength) #============================================================================== class RIPEvent (Event): """ RIP event. """ eventMethod = 'rip' eventName = 'RIP event' eventDescription = 'An error has occured and the process ' \ 'can no longer be debugged.' def get_rip_error(self): """ @rtype: int @return: RIP error code as defined by the Win32 API. """ return self.raw.u.RipInfo.dwError def get_rip_type(self): """ @rtype: int @return: RIP type code as defined by the Win32 API. May be C{0} or one of the following: - L{win32.SLE_ERROR} - L{win32.SLE_MINORERROR} - L{win32.SLE_WARNING} """ return self.raw.u.RipInfo.dwType #============================================================================== class EventFactory (StaticClass): """ Factory of L{Event} objects. @type baseEvent: L{Event} @cvar baseEvent: Base class for Event objects. It's used for unknown event codes. @type eventClasses: dict( int S{->} L{Event} ) @cvar eventClasses: Dictionary that maps event codes to L{Event} subclasses. """ baseEvent = Event eventClasses = { win32.EXCEPTION_DEBUG_EVENT : ExceptionEvent, # 1 win32.CREATE_THREAD_DEBUG_EVENT : CreateThreadEvent, # 2 win32.CREATE_PROCESS_DEBUG_EVENT : CreateProcessEvent, # 3 win32.EXIT_THREAD_DEBUG_EVENT : ExitThreadEvent, # 4 win32.EXIT_PROCESS_DEBUG_EVENT : ExitProcessEvent, # 5 win32.LOAD_DLL_DEBUG_EVENT : LoadDLLEvent, # 6 win32.UNLOAD_DLL_DEBUG_EVENT : UnloadDLLEvent, # 7 win32.OUTPUT_DEBUG_STRING_EVENT : OutputDebugStringEvent, # 8 win32.RIP_EVENT : RIPEvent, # 9 } @classmethod def get(cls, debug, raw): """ @type debug: L{Debug} @param debug: Debug object that received the event. @type raw: L{DEBUG_EVENT} @param raw: Raw DEBUG_EVENT structure as used by the Win32 API. @rtype: L{Event} @returns: An Event object or one of it's subclasses, depending on the event type. """ eventClass = cls.eventClasses.get(raw.dwDebugEventCode, cls.baseEvent) return eventClass(debug, raw) #============================================================================== class EventHandler (object): """ Base class for debug event handlers. Your program should subclass it to implement it's own event handling. The constructor can be overriden as long as you call the superclass constructor. The special method L{__call__} B{MUST NOT} be overriden. The signature for event handlers is the following:: def event_handler(self, event): Where B{event} is an L{Event} object. Each event handler is named after the event they handle. This is the list of all valid event handler names: - I{event} Receives an L{Event} object or an object of any of it's subclasses, and handles any event for which no handler was defined. - I{unknown_event} Receives an L{Event} object or an object of any of it's subclasses, and handles any event unknown to the debugging engine. (This is not likely to happen unless the Win32 debugging API is changed in future versions of Windows). - I{exception} Receives an L{ExceptionEvent} object and handles any exception for which no handler was defined. See above for exception handlers. - I{unknown_exception} Receives an L{ExceptionEvent} object and handles any exception unknown to the debugging engine. This usually happens for C++ exceptions, which are not standardized and may change from one compiler to the next. Currently we have partial support for C++ exceptions thrown by Microsoft compilers. Also see: U{RaiseException() <http://msdn.microsoft.com/en-us/library/ms680552(VS.85).aspx>} - I{create_thread} Receives a L{CreateThreadEvent} object. - I{create_process} Receives a L{CreateProcessEvent} object. - I{exit_thread} Receives a L{ExitThreadEvent} object. - I{exit_process} Receives a L{ExitProcessEvent} object. - I{load_dll} Receives a L{LoadDLLEvent} object. - I{unload_dll} Receives an L{UnloadDLLEvent} object. - I{output_string} Receives an L{OutputDebugStringEvent} object. - I{rip} Receives a L{RIPEvent} object. This is the list of all valid exception handler names (they all receive an L{ExceptionEvent} object): - I{access_violation} - I{array_bounds_exceeded} - I{breakpoint} - I{control_c_exit} - I{datatype_misalignment} - I{debug_control_c} - I{float_denormal_operand} - I{float_divide_by_zero} - I{float_inexact_result} - I{float_invalid_operation} - I{float_overflow} - I{float_stack_check} - I{float_underflow} - I{guard_page} - I{illegal_instruction} - I{in_page_error} - I{integer_divide_by_zero} - I{integer_overflow} - I{invalid_disposition} - I{invalid_handle} - I{ms_vc_exception} - I{noncontinuable_exception} - I{possible_deadlock} - I{privileged_instruction} - I{single_step} - I{stack_overflow} - I{wow64_breakpoint} @type apiHooks: dict( str S{->} list( tuple( str, int ) ) ) @cvar apiHooks: Dictionary that maps module names to lists of tuples of ( procedure name, parameter count ). All procedures listed here will be hooked for calls from the debugee. When this happens, the corresponding event handler can be notified both when the procedure is entered and when it's left by the debugee. For example, let's hook the LoadLibraryEx() API call. This would be the declaration of apiHooks:: from winappdbg import EventHandler from winappdbg.win32 import * # (...) class MyEventHandler (EventHandler): apiHook = { "kernel32.dll" : ( # Procedure name Signature ( "LoadLibraryEx", (PVOID, HANDLE, DWORD) ), # (more procedures can go here...) ), # (more libraries can go here...) } # (your method definitions go here...) Note that all pointer types are treated like void pointers, so your callback won't get the string or structure pointed to by it, but the remote memory address instead. This is so to prevent the ctypes library from being "too helpful" and trying to dereference the pointer. To get the actual data being pointed to, use one of the L{Process.read} methods. Now, to intercept calls to LoadLibraryEx define a method like this in your event handler class:: def pre_LoadLibraryEx(self, event, ra, lpFilename, hFile, dwFlags): szFilename = event.get_process().peek_string(lpFilename) # (...) Note that the first parameter is always the L{Event} object, and the second parameter is the return address. The third parameter and above are the values passed to the hooked function. Finally, to intercept returns from calls to LoadLibraryEx define a method like this:: def post_LoadLibraryEx(self, event, retval): # (...) The first parameter is the L{Event} object and the second is the return value from the hooked function. """ #------------------------------------------------------------------------------ # Default (empty) API hooks dictionary. apiHooks = {} def __init__(self): """ Class constructor. Don't forget to call it when subclassing! Forgetting to call the superclass constructor is a common mistake when you're new to Python. :) Example:: class MyEventHandler (EventHandler): # Override the constructor to use an extra argument. def __init__(self, myArgument): # Do something with the argument, like keeping it # as an instance variable. self.myVariable = myArgument # Call the superclass constructor. super(MyEventHandler, self).__init__() # The rest of your code below... """ # TODO # All this does is set up the hooks. # This code should be moved to the EventDispatcher class. # Then the hooks can be set up at set_event_handler() instead, making # this class even simpler. The downside here is deciding where to store # the ApiHook objects. # Convert the tuples into instances of the ApiHook class. # A new dictionary must be instanced, otherwise we could also be # affecting all other instances of the EventHandler. apiHooks = dict() for lib, hooks in compat.iteritems(self.apiHooks): hook_objs = [] for proc, args in hooks: if type(args) in (int, long): h = ApiHook(self, lib, proc, paramCount = args) else: h = ApiHook(self, lib, proc, signature = args) hook_objs.append(h) apiHooks[lib] = hook_objs self.__apiHooks = apiHooks def __get_hooks_for_dll(self, event): """ Get the requested API hooks for the current DLL. Used by L{__hook_dll} and L{__unhook_dll}. """ result = [] if self.__apiHooks: path = event.get_module().get_filename() if path: lib_name = PathOperations.pathname_to_filename(path).lower() for hook_lib, hook_api_list in compat.iteritems(self.__apiHooks): if hook_lib == lib_name: result.extend(hook_api_list) return result def __hook_dll(self, event): """ Hook the requested API calls (in self.apiHooks). This method is called automatically whenever a DLL is loaded. """ debug = event.debug pid = event.get_pid() for hook_api_stub in self.__get_hooks_for_dll(event): hook_api_stub.hook(debug, pid) def __unhook_dll(self, event): """ Unhook the requested API calls (in self.apiHooks). This method is called automatically whenever a DLL is unloaded. """ debug = event.debug pid = event.get_pid() for hook_api_stub in self.__get_hooks_for_dll(event): hook_api_stub.unhook(debug, pid) def __call__(self, event): """ Dispatch debug events. @warn: B{Don't override this method!} @type event: L{Event} @param event: Event object. """ try: code = event.get_event_code() if code == win32.LOAD_DLL_DEBUG_EVENT: self.__hook_dll(event) elif code == win32.UNLOAD_DLL_DEBUG_EVENT: self.__unhook_dll(event) finally: method = EventDispatcher.get_handler_method(self, event) if method is not None: return method(event) #============================================================================== # TODO # * Make it more generic by adding a few more callbacks. # That way it will be possible to make a thread sifter too. # * This interface feels too much like an antipattern. # When apiHooks is deprecated this will have to be reviewed. class EventSift(EventHandler): """ Event handler that allows you to use customized event handlers for each process you're attached to. This makes coding the event handlers much easier, because each instance will only "know" about one process. So you can code your event handler as if only one process was being debugged, but your debugger can attach to multiple processes. Example:: from winappdbg import Debug, EventHandler, EventSift # This class was written assuming only one process is attached. # If you used it directly it would break when attaching to another # process, or when a child process is spawned. class MyEventHandler (EventHandler): def create_process(self, event): self.first = True self.name = event.get_process().get_filename() print "Attached to %s" % self.name def breakpoint(self, event): if self.first: self.first = False print "First breakpoint reached at %s" % self.name def exit_process(self, event): print "Detached from %s" % self.name # Now when debugging we use the EventSift to be able to work with # multiple processes while keeping our code simple. :) if __name__ == "__main__": handler = EventSift(MyEventHandler) #handler = MyEventHandler() # try uncommenting this line... with Debug(handler) as debug: debug.execl("calc.exe") debug.execl("notepad.exe") debug.execl("charmap.exe") debug.loop() Subclasses of C{EventSift} can prevent specific event types from being forwarded by simply defining a method for it. That means your subclass can handle some event types globally while letting other types be handled on per-process basis. To forward events manually you can call C{self.event(event)}. Example:: class MySift (EventSift): # Don't forward this event. def debug_control_c(self, event): pass # Handle this event globally without forwarding it. def output_string(self, event): print "Debug string: %s" % event.get_debug_string() # Handle this event globally and then forward it. def create_process(self, event): print "New process created, PID: %d" % event.get_pid() return self.event(event) # All other events will be forwarded. Note that overriding the C{event} method would cause no events to be forwarded at all. To prevent this, call the superclass implementation. Example:: def we_want_to_forward_this_event(event): "Use whatever logic you want here..." # (...return True or False...) class MySift (EventSift): def event(self, event): # If the event matches some custom criteria... if we_want_to_forward_this_event(event): # Forward it. return super(MySift, self).event(event) # Otherwise, don't. @type cls: class @ivar cls: Event handler class. There will be one instance of this class per debugged process in the L{forward} dictionary. @type argv: list @ivar argv: Positional arguments to pass to the constructor of L{cls}. @type argd: list @ivar argd: Keyword arguments to pass to the constructor of L{cls}. @type forward: dict @ivar forward: Dictionary that maps each debugged process ID to an instance of L{cls}. """ def __init__(self, cls, *argv, **argd): """ Maintains an instance of your event handler for each process being debugged, and forwards the events of each process to each corresponding instance. @warn: If you subclass L{EventSift} and reimplement this method, don't forget to call the superclass constructor! @see: L{event} @type cls: class @param cls: Event handler class. This must be the class itself, not an instance! All additional arguments passed to the constructor of the event forwarder will be passed on to the constructor of this class as well. """ self.cls = cls self.argv = argv self.argd = argd self.forward = dict() super(EventSift, self).__init__() # XXX HORRIBLE HACK # This makes apiHooks work in the inner handlers. def __call__(self, event): try: eventCode = event.get_event_code() if eventCode in (win32.LOAD_DLL_DEBUG_EVENT, win32.LOAD_DLL_DEBUG_EVENT): pid = event.get_pid() handler = self.forward.get(pid, None) if handler is None: handler = self.cls(*self.argv, **self.argd) self.forward[pid] = handler if isinstance(handler, EventHandler): if eventCode == win32.LOAD_DLL_DEBUG_EVENT: handler.__EventHandler_hook_dll(event) else: handler.__EventHandler_unhook_dll(event) finally: return super(EventSift, self).__call__(event) def event(self, event): """ Forwards events to the corresponding instance of your event handler for this process. If you subclass L{EventSift} and reimplement this method, no event will be forwarded at all unless you call the superclass implementation. If your filtering is based on the event type, there's a much easier way to do it: just implement a handler for it. """ eventCode = event.get_event_code() pid = event.get_pid() handler = self.forward.get(pid, None) if handler is None: handler = self.cls(*self.argv, **self.argd) if eventCode != win32.EXIT_PROCESS_DEBUG_EVENT: self.forward[pid] = handler elif eventCode == win32.EXIT_PROCESS_DEBUG_EVENT: del self.forward[pid] return handler(event) #============================================================================== class EventDispatcher (object): """ Implements debug event dispatching capabilities. @group Debugging events: get_event_handler, set_event_handler, get_handler_method """ # Maps event code constants to the names of the pre-notify routines. # These routines are called BEFORE the user-defined handlers. # Unknown codes are ignored. __preEventNotifyCallbackName = { win32.CREATE_THREAD_DEBUG_EVENT : '_notify_create_thread', win32.CREATE_PROCESS_DEBUG_EVENT : '_notify_create_process', win32.LOAD_DLL_DEBUG_EVENT : '_notify_load_dll', } # Maps event code constants to the names of the post-notify routines. # These routines are called AFTER the user-defined handlers. # Unknown codes are ignored. __postEventNotifyCallbackName = { win32.EXIT_THREAD_DEBUG_EVENT : '_notify_exit_thread', win32.EXIT_PROCESS_DEBUG_EVENT : '_notify_exit_process', win32.UNLOAD_DLL_DEBUG_EVENT : '_notify_unload_dll', win32.RIP_EVENT : '_notify_rip', } # Maps exception code constants to the names of the pre-notify routines. # These routines are called BEFORE the user-defined handlers. # Unknown codes are ignored. __preExceptionNotifyCallbackName = { win32.EXCEPTION_BREAKPOINT : '_notify_breakpoint', win32.EXCEPTION_WX86_BREAKPOINT : '_notify_breakpoint', win32.EXCEPTION_SINGLE_STEP : '_notify_single_step', win32.EXCEPTION_GUARD_PAGE : '_notify_guard_page', win32.DBG_CONTROL_C : '_notify_debug_control_c', win32.MS_VC_EXCEPTION : '_notify_ms_vc_exception', } # Maps exception code constants to the names of the post-notify routines. # These routines are called AFTER the user-defined handlers. # Unknown codes are ignored. __postExceptionNotifyCallbackName = { } def __init__(self, eventHandler = None): """ Event dispatcher. @type eventHandler: L{EventHandler} @param eventHandler: (Optional) User-defined event handler. @raise TypeError: The event handler is of an incorrect type. @note: The L{eventHandler} parameter may be any callable Python object (for example a function, or an instance method). However you'll probably find it more convenient to use an instance of a subclass of L{EventHandler} here. """ self.set_event_handler(eventHandler) def get_event_handler(self): """ Get the event handler. @see: L{set_event_handler} @rtype: L{EventHandler} @return: Current event handler object, or C{None}. """ return self.__eventHandler def set_event_handler(self, eventHandler): """ Set the event handler. @warn: This is normally not needed. Use with care! @type eventHandler: L{EventHandler} @param eventHandler: New event handler object, or C{None}. @rtype: L{EventHandler} @return: Previous event handler object, or C{None}. @raise TypeError: The event handler is of an incorrect type. @note: The L{eventHandler} parameter may be any callable Python object (for example a function, or an instance method). However you'll probably find it more convenient to use an instance of a subclass of L{EventHandler} here. """ if eventHandler is not None and not callable(eventHandler): raise TypeError("Event handler must be a callable object") try: wrong_type = issubclass(eventHandler, EventHandler) except TypeError: wrong_type = False if wrong_type: classname = str(eventHandler) msg = "Event handler must be an instance of class %s" msg += "rather than the %s class itself. (Missing parens?)" msg = msg % (classname, classname) raise TypeError(msg) try: previous = self.__eventHandler except AttributeError: previous = None self.__eventHandler = eventHandler return previous @staticmethod def get_handler_method(eventHandler, event, fallback=None): """ Retrieves the appropriate callback method from an L{EventHandler} instance for the given L{Event} object. @type eventHandler: L{EventHandler} @param eventHandler: Event handler object whose methods we are examining. @type event: L{Event} @param event: Debugging event to be handled. @type fallback: callable @param fallback: (Optional) If no suitable method is found in the L{EventHandler} instance, return this value. @rtype: callable @return: Bound method that will handle the debugging event. Returns C{None} if no such method is defined. """ eventCode = event.get_event_code() method = getattr(eventHandler, 'event', fallback) if eventCode == win32.EXCEPTION_DEBUG_EVENT: method = getattr(eventHandler, 'exception', method) method = getattr(eventHandler, event.eventMethod, method) return method def dispatch(self, event): """ Sends event notifications to the L{Debug} object and the L{EventHandler} object provided by the user. The L{Debug} object will forward the notifications to it's contained snapshot objects (L{System}, L{Process}, L{Thread} and L{Module}) when appropriate. @warning: This method is called automatically from L{Debug.dispatch}. @see: L{Debug.cont}, L{Debug.loop}, L{Debug.wait} @type event: L{Event} @param event: Event object passed to L{Debug.dispatch}. @raise WindowsError: Raises an exception on error. """ returnValue = None bCallHandler = True pre_handler = None post_handler = None eventCode = event.get_event_code() # Get the pre and post notification methods for exceptions. # If not found, the following steps take care of that. if eventCode == win32.EXCEPTION_DEBUG_EVENT: exceptionCode = event.get_exception_code() pre_name = self.__preExceptionNotifyCallbackName.get( exceptionCode, None) post_name = self.__postExceptionNotifyCallbackName.get( exceptionCode, None) if pre_name is not None: pre_handler = getattr(self, pre_name, None) if post_name is not None: post_handler = getattr(self, post_name, None) # Get the pre notification method for all other events. # This includes the exception event if no notify method was found # for this exception code. if pre_handler is None: pre_name = self.__preEventNotifyCallbackName.get(eventCode, None) if pre_name is not None: pre_handler = getattr(self, pre_name, pre_handler) # Get the post notification method for all other events. # This includes the exception event if no notify method was found # for this exception code. if post_handler is None: post_name = self.__postEventNotifyCallbackName.get(eventCode, None) if post_name is not None: post_handler = getattr(self, post_name, post_handler) # Call the pre-notify method only if it was defined. # If an exception is raised don't call the other methods. if pre_handler is not None: bCallHandler = pre_handler(event) # Call the user-defined event handler only if the pre-notify # method was not defined, or was and it returned True. try: if bCallHandler and self.__eventHandler is not None: try: returnValue = self.__eventHandler(event) except Exception: e = sys.exc_info()[1] msg = ("Event handler pre-callback %r" " raised an exception: %s") msg = msg % (self.__eventHandler, traceback.format_exc(e)) warnings.warn(msg, EventCallbackWarning) returnValue = None # Call the post-notify method if defined, even if an exception is # raised by the user-defined event handler. finally: if post_handler is not None: post_handler(event) # Return the value from the call to the user-defined event handler. # If not defined return None. return returnValue
67,241
Python
34.958289
89
0.583186
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Process instrumentation. @group Instrumentation: Process """ from __future__ import with_statement # FIXME # I've been told the host process for the latest versions of VMWare # can't be instrumented, because they try to stop code injection into the VMs. # The solution appears to be to run the debugger from a user account that # belongs to the VMware group. I haven't confirmed this yet. __revision__ = "$Id$" __all__ = ['Process'] import sys from winappdbg import win32 from winappdbg import compat from winappdbg.textio import HexDump, HexInput from winappdbg.util import Regenerator, PathOperations, MemoryAddresses from winappdbg.module import Module, _ModuleContainer from winappdbg.thread import Thread, _ThreadContainer from winappdbg.window import Window from winappdbg.search import Search, \ Pattern, BytePattern, TextPattern, RegExpPattern, HexPattern from winappdbg.disasm import Disassembler import re import os import os.path import ctypes import struct import warnings import traceback # delayed import System = None #============================================================================== # TODO # * Remote GetLastError() # * The memory operation methods do not take into account that code breakpoints # change the memory. This object should talk to BreakpointContainer to # retrieve the original memory contents where code breakpoints are enabled. # * A memory cache could be implemented here. class Process (_ThreadContainer, _ModuleContainer): """ Interface to a process. Contains threads and modules snapshots. @group Properties: get_pid, is_alive, is_debugged, is_wow64, get_arch, get_bits, get_filename, get_exit_code, get_start_time, get_exit_time, get_running_time, get_services, get_dep_policy, get_peb, get_peb_address, get_entry_point, get_main_module, get_image_base, get_image_name, get_command_line, get_environment, get_command_line_block, get_environment_block, get_environment_variables, get_handle, open_handle, close_handle @group Instrumentation: kill, wait, suspend, resume, inject_code, inject_dll, clean_exit @group Disassembly: disassemble, disassemble_around, disassemble_around_pc, disassemble_string, disassemble_instruction, disassemble_current @group Debugging: flush_instruction_cache, debug_break, peek_pointers_in_data @group Memory mapping: take_memory_snapshot, generate_memory_snapshot, iter_memory_snapshot, restore_memory_snapshot, get_memory_map, get_mapped_filenames, generate_memory_map, iter_memory_map, is_pointer, is_address_valid, is_address_free, is_address_reserved, is_address_commited, is_address_guard, is_address_readable, is_address_writeable, is_address_copy_on_write, is_address_executable, is_address_executable_and_writeable, is_buffer, is_buffer_readable, is_buffer_writeable, is_buffer_executable, is_buffer_executable_and_writeable, is_buffer_copy_on_write @group Memory allocation: malloc, free, mprotect, mquery @group Memory read: read, read_char, read_int, read_uint, read_float, read_double, read_dword, read_qword, read_pointer, read_string, read_structure, peek, peek_char, peek_int, peek_uint, peek_float, peek_double, peek_dword, peek_qword, peek_pointer, peek_string @group Memory write: write, write_char, write_int, write_uint, write_float, write_double, write_dword, write_qword, write_pointer, poke, poke_char, poke_int, poke_uint, poke_float, poke_double, poke_dword, poke_qword, poke_pointer @group Memory search: search, search_bytes, search_hexa, search_text, search_regexp, strings @group Processes snapshot: scan, clear, __contains__, __iter__, __len__ @group Deprecated: get_environment_data, parse_environment_data @type dwProcessId: int @ivar dwProcessId: Global process ID. Use L{get_pid} instead. @type hProcess: L{ProcessHandle} @ivar hProcess: Handle to the process. Use L{get_handle} instead. @type fileName: str @ivar fileName: Filename of the main module. Use L{get_filename} instead. """ def __init__(self, dwProcessId, hProcess = None, fileName = None): """ @type dwProcessId: int @param dwProcessId: Global process ID. @type hProcess: L{ProcessHandle} @param hProcess: Handle to the process. @type fileName: str @param fileName: (Optional) Filename of the main module. """ _ThreadContainer.__init__(self) _ModuleContainer.__init__(self) self.dwProcessId = dwProcessId self.hProcess = hProcess self.fileName = fileName def get_pid(self): """ @rtype: int @return: Process global ID. """ return self.dwProcessId def get_filename(self): """ @rtype: str @return: Filename of the main module of the process. """ if not self.fileName: self.fileName = self.get_image_name() return self.fileName def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): """ Opens a new handle to the process. The new handle is stored in the L{hProcess} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.PROCESS_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx} @raise WindowsError: It's not possible to open a handle to the process with the requested access rights. This tipically happens because the target process is a system process and the debugger is not runnning with administrative rights. """ hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId) try: self.close_handle() except Exception: warnings.warn( "Failed to close process handle: %s" % traceback.format_exc()) self.hProcess = hProcess def close_handle(self): """ Closes the handle to the process. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. So unless you've been tinkering with it, setting L{hProcess} to C{None} should be enough. """ try: if hasattr(self.hProcess, 'close'): self.hProcess.close() elif self.hProcess not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hProcess) finally: self.hProcess = None def get_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): """ Returns a handle to the process with I{at least} the access rights requested. @note: If a handle was previously opened and has the required access rights, it's reused. If not, a new handle is opened with the combination of the old and new access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.PROCESS_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx} @rtype: L{ProcessHandle} @return: Handle to the process. @raise WindowsError: It's not possible to open a handle to the process with the requested access rights. This tipically happens because the target process is a system process and the debugger is not runnning with administrative rights. """ if self.hProcess in (None, win32.INVALID_HANDLE_VALUE): self.open_handle(dwDesiredAccess) else: dwAccess = self.hProcess.dwAccess if (dwAccess | dwDesiredAccess) != dwAccess: self.open_handle(dwAccess | dwDesiredAccess) return self.hProcess #------------------------------------------------------------------------------ # Not really sure if it's a good idea... ## def __eq__(self, aProcess): ## """ ## Compare two Process objects. The comparison is made using the IDs. ## ## @warning: ## If you have two Process instances with different handles the ## equality operator still returns C{True}, so be careful! ## ## @type aProcess: L{Process} ## @param aProcess: Another Process object. ## ## @rtype: bool ## @return: C{True} if the two process IDs are equal, ## C{False} otherwise. ## """ ## return isinstance(aProcess, Process) and \ ## self.get_pid() == aProcess.get_pid() def __contains__(self, anObject): """ The same as: C{self.has_thread(anObject) or self.has_module(anObject)} @type anObject: L{Thread}, L{Module} or int @param anObject: Object to look for. Can be a Thread, Module, thread global ID or module base address. @rtype: bool @return: C{True} if the requested object was found in the snapshot. """ return _ThreadContainer.__contains__(self, anObject) or \ _ModuleContainer.__contains__(self, anObject) def __len__(self): """ @see: L{get_thread_count}, L{get_module_count} @rtype: int @return: Count of L{Thread} and L{Module} objects in this snapshot. """ return _ThreadContainer.__len__(self) + \ _ModuleContainer.__len__(self) class __ThreadsAndModulesIterator (object): """ Iterator object for L{Process} objects. Iterates through L{Thread} objects first, L{Module} objects next. """ def __init__(self, container): """ @type container: L{Process} @param container: L{Thread} and L{Module} container. """ self.__container = container self.__iterator = None self.__state = 0 def __iter__(self): 'x.__iter__() <==> iter(x)' return self def next(self): 'x.next() -> the next value, or raise StopIteration' if self.__state == 0: self.__iterator = self.__container.iter_threads() self.__state = 1 if self.__state == 1: try: return self.__iterator.next() except StopIteration: self.__iterator = self.__container.iter_modules() self.__state = 2 if self.__state == 2: try: return self.__iterator.next() except StopIteration: self.__iterator = None self.__state = 3 raise StopIteration def __iter__(self): """ @see: L{iter_threads}, L{iter_modules} @rtype: iterator @return: Iterator of L{Thread} and L{Module} objects in this snapshot. All threads are iterated first, then all modules. """ return self.__ThreadsAndModulesIterator(self) #------------------------------------------------------------------------------ def wait(self, dwTimeout = None): """ Waits for the process to finish executing. @raise WindowsError: On error an exception is raised. """ self.get_handle(win32.SYNCHRONIZE).wait(dwTimeout) def kill(self, dwExitCode = 0): """ Terminates the execution of the process. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_TERMINATE) win32.TerminateProcess(hProcess, dwExitCode) def suspend(self): """ Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised. """ self.scan_threads() # force refresh the snapshot suspended = list() try: for aThread in self.iter_threads(): aThread.suspend() suspended.append(aThread) except Exception: for aThread in suspended: try: aThread.resume() except Exception: pass raise def resume(self): """ Resumes execution on all threads of the process. @raise WindowsError: On error an exception is raised. """ if self.get_thread_count() == 0: self.scan_threads() # only refresh the snapshot if empty resumed = list() try: for aThread in self.iter_threads(): aThread.resume() resumed.append(aThread) except Exception: for aThread in resumed: try: aThread.suspend() except Exception: pass raise def is_debugged(self): """ Tries to determine if the process is being debugged by another process. It may detect other debuggers besides WinAppDbg. @rtype: bool @return: C{True} if the process has a debugger attached. @warning: May return inaccurate results when some anti-debug techniques are used by the target process. @note: To know if a process currently being debugged by a L{Debug} object, call L{Debug.is_debugee} instead. """ # FIXME the MSDN docs don't say what access rights are needed here! hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.CheckRemoteDebuggerPresent(hProcess) def is_alive(self): """ @rtype: bool @return: C{True} if the process is currently running. """ try: self.wait(0) except WindowsError: e = sys.exc_info()[1] return e.winerror == win32.WAIT_TIMEOUT return False def get_exit_code(self): """ @rtype: int @return: Process exit code, or C{STILL_ACTIVE} if it's still alive. @warning: If a process returns C{STILL_ACTIVE} as it's exit code, you may not be able to determine if it's active or not with this method. Use L{is_alive} to check if the process is still active. Alternatively you can call L{get_handle} to get the handle object and then L{ProcessHandle.wait} on it to wait until the process finishes running. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION return win32.GetExitCodeProcess( self.get_handle(dwAccess) ) #------------------------------------------------------------------------------ def scan(self): """ Populates the snapshot of threads and modules. """ self.scan_threads() self.scan_modules() def clear(self): """ Clears the snapshot of threads and modules. """ try: try: self.clear_threads() finally: self.clear_modules() finally: self.close_handle() #------------------------------------------------------------------------------ # Regular expression to find hexadecimal values of any size. __hexa_parameter = re.compile('0x[0-9A-Fa-f]+') def __fixup_labels(self, disasm): """ Private method used when disassembling from process memory. It has no return value because the list is modified in place. On return all raw memory addresses are replaced by labels when possible. @type disasm: list of tuple(int, int, str, str) @param disasm: Output of one of the dissassembly functions. """ for index in compat.xrange(len(disasm)): (address, size, text, dump) = disasm[index] m = self.__hexa_parameter.search(text) while m: s, e = m.span() value = text[s:e] try: label = self.get_label_at_address( int(value, 0x10) ) except Exception: label = None if label: text = text[:s] + label + text[e:] e = s + len(value) m = self.__hexa_parameter.search(text, e) disasm[index] = (address, size, text, dump) def disassemble_string(self, lpAddress, code): """ Disassemble instructions from a block of binary code. @type lpAddress: int @param lpAddress: Memory address where the code was read from. @type code: str @param code: Binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise NotImplementedError: No compatible disassembler was found for the current platform. """ try: disasm = self.__disasm except AttributeError: disasm = self.__disasm = Disassembler( self.get_arch() ) return disasm.decode(lpAddress, code) def disassemble(self, lpAddress, dwSize): """ Disassemble instructions from the address space of the process. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @type dwSize: int @param dwSize: Size of binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ data = self.read(lpAddress, dwSize) disasm = self.disassemble_string(lpAddress, data) self.__fixup_labels(disasm) return disasm # FIXME # This algorithm really bad, I've got to write a better one :P def disassemble_around(self, lpAddress, dwSize = 64): """ Disassemble around the given address. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @type dwSize: int @param dwSize: Delta offset. Code will be read from lpAddress - dwSize to lpAddress + dwSize. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ dwDelta = int(float(dwSize) / 2.0) addr_1 = lpAddress - dwDelta addr_2 = lpAddress size_1 = dwDelta size_2 = dwSize - dwDelta data = self.read(addr_1, dwSize) data_1 = data[:size_1] data_2 = data[size_1:] disasm_1 = self.disassemble_string(addr_1, data_1) disasm_2 = self.disassemble_string(addr_2, data_2) disasm = disasm_1 + disasm_2 self.__fixup_labels(disasm) return disasm def disassemble_around_pc(self, dwThreadId, dwSize = 64): """ Disassemble around the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @type dwSize: int @param dwSize: Delta offset. Code will be read from pc - dwSize to pc + dwSize. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aThread = self.get_thread(dwThreadId) return self.disassemble_around(aThread.get_pc(), dwSize) def disassemble_instruction(self, lpAddress): """ Disassemble the instruction at the given memory address. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ return self.disassemble(lpAddress, 15)[0] def disassemble_current(self, dwThreadId): """ Disassemble the instruction at the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aThread = self.get_thread(dwThreadId) return self.disassemble_instruction(aThread.get_pc()) #------------------------------------------------------------------------------ def flush_instruction_cache(self): """ Flush the instruction cache. This is required if the process memory is modified and one or more threads are executing nearby the modified memory region. @see: U{http://blogs.msdn.com/oldnewthing/archive/2003/12/08/55954.aspx#55958} @raise WindowsError: Raises exception on error. """ # FIXME # No idea what access rights are required here! # Maybe PROCESS_VM_OPERATION ??? # In any case we're only calling this from the debugger, # so it should be fine (we already have PROCESS_ALL_ACCESS). win32.FlushInstructionCache( self.get_handle() ) def debug_break(self): """ Triggers the system breakpoint in the process. @raise WindowsError: On error an exception is raised. """ # The exception is raised by a new thread. # When continuing the exception, the thread dies by itself. # This thread is hidden from the debugger. win32.DebugBreakProcess( self.get_handle() ) def is_wow64(self): """ Determines if the process is running under WOW64. @rtype: bool @return: C{True} if the process is running under WOW64. That is, a 32-bit application running in a 64-bit Windows. C{False} if the process is either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows. @raise WindowsError: On error an exception is raised. @see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} """ try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) try: wow64 = win32.IsWow64Process(hProcess) except AttributeError: wow64 = False self.__wow64 = wow64 return wow64 def get_arch(self): """ @rtype: str @return: The architecture in which this process believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the architecture returned by this method will be L{win32.ARCH_I386}, but the value of L{System.arch} will be L{win32.ARCH_AMD64}. """ # Are we in a 32 bit machine? if win32.bits == 32 and not win32.wow64: return win32.arch # Is the process outside of WOW64? if not self.is_wow64(): return win32.arch # In WOW64, "amd64" becomes "i386". if win32.arch == win32.ARCH_AMD64: return win32.ARCH_I386 # We don't know the translation for other architectures. raise NotImplementedError() def get_bits(self): """ @rtype: str @return: The number of bits in which this process believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the number of bits returned by this method will be C{32}, but the value of L{System.arch} will be C{64}. """ # Are we in a 32 bit machine? if win32.bits == 32 and not win32.wow64: # All processes are 32 bits. return 32 # Is the process inside WOW64? if self.is_wow64(): # The process is 32 bits. return 32 # The process is 64 bits. return 64 # TODO: get_os, to test compatibility run # See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms683224(v=vs.85).aspx #------------------------------------------------------------------------------ def get_start_time(self): """ Determines when has this process started running. @rtype: win32.SYSTEMTIME @return: Process start time. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) CreationTime = win32.GetProcessTimes(hProcess)[0] return win32.FileTimeToSystemTime(CreationTime) def get_exit_time(self): """ Determines when has this process finished running. If the process is still alive, the current time is returned instead. @rtype: win32.SYSTEMTIME @return: Process exit time. """ if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) ExitTime = win32.GetProcessTimes(hProcess)[1] return win32.FileTimeToSystemTime(ExitTime) def get_running_time(self): """ Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) (CreationTime, ExitTime, _, _) = win32.GetProcessTimes(hProcess) if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32) ExitTime = ExitTime.dwLowDateTime + ( ExitTime.dwHighDateTime << 32) RunningTime = ExitTime - CreationTime return RunningTime / 10000 # 100 nanoseconds steps => milliseconds #------------------------------------------------------------------------------ def __load_System_class(self): global System # delayed import if System is None: from system import System def get_services(self): """ Retrieves the list of system services that are currently running in this process. @see: L{System.get_services} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors. """ self.__load_System_class() pid = self.get_pid() return [d for d in System.get_active_services() if d.ProcessId == pid] #------------------------------------------------------------------------------ def get_dep_policy(self): """ Retrieves the DEP (Data Execution Prevention) policy for this process. @note: This method is only available in Windows XP SP3 and above, and only for 32 bit processes. It will fail in any other circumstance. @see: U{http://msdn.microsoft.com/en-us/library/bb736297(v=vs.85).aspx} @rtype: tuple(int, int) @return: The first member of the tuple is the DEP flags. It can be a combination of the following values: - 0: DEP is disabled for this process. - 1: DEP is enabled for this process. (C{PROCESS_DEP_ENABLE}) - 2: DEP-ATL thunk emulation is disabled for this process. (C{PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION}) The second member of the tuple is the permanent flag. If C{TRUE} the DEP settings cannot be changed in runtime for this process. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) try: return win32.kernel32.GetProcessDEPPolicy(hProcess) except AttributeError: msg = "This method is only available in Windows XP SP3 and above." raise NotImplementedError(msg) #------------------------------------------------------------------------------ def get_peb(self): """ Returns a copy of the PEB. To dereference pointers in it call L{Process.read_structure}. @rtype: L{win32.PEB} @return: PEB structure. @raise WindowsError: An exception is raised on error. """ self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) return self.read_structure(self.get_peb_address(), win32.PEB) def get_peb_address(self): """ Returns a remote pointer to the PEB. @rtype: int @return: Remote pointer to the L{win32.PEB} structure. Returns C{None} on error. """ try: return self._peb_ptr except AttributeError: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) pbi = win32.NtQueryInformationProcess(hProcess, win32.ProcessBasicInformation) address = pbi.PebBaseAddress self._peb_ptr = address return address def get_entry_point(self): """ Alias to C{process.get_main_module().get_entry_point()}. @rtype: int @return: Address of the entry point of the main module. """ return self.get_main_module().get_entry_point() def get_main_module(self): """ @rtype: L{Module} @return: Module object for the process main module. """ return self.get_module(self.get_image_base()) def get_image_base(self): """ @rtype: int @return: Image base address for the process main module. """ return self.get_peb().ImageBaseAddress def get_image_name(self): """ @rtype: int @return: Filename of the process main module. This method does it's best to retrieve the filename. However sometimes this is not possible, so C{None} may be returned instead. """ # Method 1: Module.fileName # It's cached if the filename was already found by the other methods, # if it came with the corresponding debug event, or it was found by the # toolhelp API. mainModule = None try: mainModule = self.get_main_module() name = mainModule.fileName if not name: name = None except (KeyError, AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 2: QueryFullProcessImageName() # Not implemented until Windows Vista. if not name: try: hProcess = self.get_handle( win32.PROCESS_QUERY_LIMITED_INFORMATION) name = win32.QueryFullProcessImageName(hProcess) except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 3: GetProcessImageFileName() # # Not implemented until Windows XP. # For more info see: # https://voidnish.wordpress.com/2005/06/20/getprocessimagefilenamequerydosdevice-trivia/ if not name: try: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) name = win32.GetProcessImageFileName(hProcess) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG if not name: name = None # Method 4: GetModuleFileNameEx() # Not implemented until Windows 2000. # # May be spoofed by malware, since this information resides # in usermode space (see http://www.ragestorm.net/blogs/?p=163). if not name: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) try: name = win32.GetModuleFileNameEx(hProcess) except WindowsError: ## traceback.print_exc() # XXX DEBUG name = win32.GetModuleFileNameEx( hProcess, self.get_image_base()) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG if not name: name = None # Method 5: PEB.ProcessParameters->ImagePathName # # May fail since it's using an undocumented internal structure. # # May be spoofed by malware, since this information resides # in usermode space (see http://www.ragestorm.net/blogs/?p=163). if not name: try: peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.ImagePathName name = self.peek_string(s.Buffer, dwMaxSize=s.MaximumLength, fUnicode=True) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 6: Module.get_filename() # It tries to get the filename from the file handle. # # There are currently some problems due to the strange way the API # works - it returns the pathname without the drive letter, and I # couldn't figure out a way to fix it. if not name and mainModule is not None: try: name = mainModule.get_filename() if not name: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Remember the filename. if name and mainModule is not None: mainModule.fileName = name # Return the image filename, or None on error. return name def get_command_line_block(self): """ Retrieves the command line block memory address and size. @rtype: tuple(int, int) @return: Tuple with the memory address of the command line block and it's maximum size in Unicode characters. @raise WindowsError: On error an exception is raised. """ peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.CommandLine return (s.Buffer, s.MaximumLength) def get_environment_block(self): """ Retrieves the environment block memory address for the process. @note: The size is always enough to contain the environment data, but it may not be an exact size. It's best to read the memory and scan for two null wide chars to find the actual size. @rtype: tuple(int, int) @return: Tuple with the memory address of the environment block and it's size. @raise WindowsError: On error an exception is raised. """ peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) Environment = pp.Environment try: EnvironmentSize = pp.EnvironmentSize except AttributeError: mbi = self.mquery(Environment) EnvironmentSize = mbi.RegionSize + mbi.BaseAddress - Environment return (Environment, EnvironmentSize) def get_command_line(self): """ Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised. """ (Buffer, MaximumLength) = self.get_command_line_block() CommandLine = self.peek_string(Buffer, dwMaxSize=MaximumLength, fUnicode=True) gst = win32.GuessStringType if gst.t_default == gst.t_ansi: CommandLine = CommandLine.encode('cp1252') return CommandLine def get_environment_variables(self): """ Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Note: the first bytes are garbage and must be skipped. Then the first # two environment entries are the current drive and directory as key # and value pairs, followed by the ExitCode variable (it's what batch # files know as "errorlevel"). After that, the real environment vars # are there in alphabetical order. In theory that's where it stops, # but I've always seen one more "variable" tucked at the end which # may be another environment block but in ANSI. I haven't examined it # yet, I'm just skipping it because if it's parsed as Unicode it just # renders garbage. # Read the environment block contents. data = self.peek( *self.get_environment_block() ) # Put them into a Unicode buffer. tmp = ctypes.create_string_buffer(data) buffer = ctypes.create_unicode_buffer(len(data)) ctypes.memmove(buffer, tmp, len(data)) del tmp # Skip until the first Unicode null char is found. pos = 0 while buffer[pos] != u'\0': pos += 1 pos += 1 # Loop for each environment variable... environment = [] while buffer[pos] != u'\0': # Until we find a null char... env_name_pos = pos env_name = u'' found_name = False while buffer[pos] != u'\0': # Get the current char. char = buffer[pos] # Is it an equal sign? if char == u'=': # Skip leading equal signs. if env_name_pos == pos: env_name_pos += 1 pos += 1 continue # Otherwise we found the separator equal sign. pos += 1 found_name = True break # Add the char to the variable name. env_name += char # Next char. pos += 1 # If the name was not parsed properly, stop. if not found_name: break # Read the variable value until we find a null char. env_value = u'' while buffer[pos] != u'\0': env_value += buffer[pos] pos += 1 # Skip the null char. pos += 1 # Add to the list of environment variables found. environment.append( (env_name, env_value) ) # Remove the last entry, it's garbage. if environment: environment.pop() # Return the environment variables. return environment def get_environment_data(self, fUnicode = None): """ Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: list of str @return: Environment keys and values separated by a (C{=}) character, as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Issue a deprecation warning. warnings.warn( "Process.get_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Get the environment variables. block = [ key + u'=' + value for (key, value) \ in self.get_environment_variables() ] # Convert the data to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: block = [x.encode('cp1252') for x in block] # Return the environment data. return block @staticmethod def parse_environment_data(block): """ Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. """ # Issue a deprecation warning. warnings.warn( "Process.parse_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Create an empty environment dictionary. environment = dict() # End here if the environment block is empty. if not block: return environment # Prepare the tokens (ANSI or Unicode). gst = win32.GuessStringType if type(block[0]) == gst.t_ansi: equals = '=' terminator = '\0' else: equals = u'=' terminator = u'\0' # Split the blocks into key/value pairs. for chunk in block: sep = chunk.find(equals, 1) if sep < 0: ## raise Exception() continue # corrupted environment block? key, value = chunk[:sep], chunk[sep+1:] # For duplicated keys, append the value. # Values are separated using null terminators. if key not in environment: environment[key] = value else: environment[key] += terminator + value # Return the environment dictionary. return environment def get_environment(self, fUnicode = None): """ Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_variables())} @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. @raise WindowsError: On error an exception is raised. """ # Get the environment variables. variables = self.get_environment_variables() # Convert the strings to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: variables = [ ( key.encode('cp1252'), value.encode('cp1252') ) \ for (key, value) in variables ] # Add the variables to a dictionary, concatenating duplicates. environment = dict() for key, value in variables: if key in environment: environment[key] = environment[key] + u'\0' + value else: environment[key] = value # Return the dictionary. return environment #------------------------------------------------------------------------------ def search(self, pattern, minAddr = None, maxAddr = None): """ Search for the given pattern within the process memory. @type pattern: str, compat.unicode or L{Pattern} @param pattern: Pattern to search for. It may be a byte string, a Unicode string, or an instance of L{Pattern}. The following L{Pattern} subclasses are provided by WinAppDbg: - L{BytePattern} - L{TextPattern} - L{RegExpPattern} - L{HexPattern} You can also write your own subclass of L{Pattern} for customized searches. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ if isinstance(pattern, str): return self.search_bytes(pattern, minAddr, maxAddr) if isinstance(pattern, compat.unicode): return self.search_bytes(pattern.encode("utf-16le"), minAddr, maxAddr) if isinstance(pattern, Pattern): return Search.search_process(self, pattern, minAddr, maxAddr) raise TypeError("Unknown pattern type: %r" % type(pattern)) def search_bytes(self, bytes, minAddr = None, maxAddr = None): """ Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of int @return: An iterator of memory addresses where the pattern was found. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None): """ Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The text that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1): """ Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages) def search_hexa(self, hexa, minAddr = None, maxAddr = None): """ Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The bytes that match the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data def strings(self, minSize = 4, maxSize = 1024): """ Extract ASCII strings from the process memory. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to search for. @rtype: iterator of tuple(int, int, str) @return: Iterator of strings extracted from the process memory. Each tuple contains the following: - The memory address where the string was found. - The size of the string. - The string. """ return Search.extract_ascii_strings(self, minSize = minSize, maxSize = maxSize) #------------------------------------------------------------------------------ def __read_c_type(self, address, format, c_type): size = ctypes.sizeof(c_type) packed = self.read(address, size) if len(packed) != size: raise ctypes.WinError() return struct.unpack(format, packed)[0] def __write_c_type(self, address, format, unpacked): packed = struct.pack('@L', unpacked) self.write(address, packed) # XXX TODO # + Maybe change page permissions before trying to read? def read(self, lpBaseAddress, nSize): """ Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not self.is_buffer(lpBaseAddress, nSize): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) data = win32.ReadProcessMemory(hProcess, lpBaseAddress, nSize) if len(data) != nSize: raise ctypes.WinError() return data def write(self, lpBaseAddress, lpBuffer): """ Writes to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type lpBuffer: str @param lpBuffer: Bytes to write. @raise WindowsError: On error an exception is raised. """ r = self.poke(lpBaseAddress, lpBuffer) if r != len(lpBuffer): raise ctypes.WinError() def read_char(self, lpBaseAddress): """ Reads a single character to the memory of the process. @see: L{peek_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @rtype: int @return: Character value read from the process memory. @raise WindowsError: On error an exception is raised. """ return ord( self.read(lpBaseAddress, 1) ) def write_char(self, lpBaseAddress, char): """ Writes a single character to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type char: int @param char: Character to write. @raise WindowsError: On error an exception is raised. """ self.write(lpBaseAddress, chr(char)) def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int) def write_int(self, lpBaseAddress, unpackedValue): """ Writes a signed integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@l', unpackedValue) def read_uint(self, lpBaseAddress): """ Reads an unsigned integer from the memory of the process. @see: L{peek_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@L', ctypes.c_uint) def write_uint(self, lpBaseAddress, unpackedValue): """ Writes an unsigned integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@L', unpackedValue) def read_float(self, lpBaseAddress): """ Reads a float from the memory of the process. @see: L{peek_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Floating point value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@f', ctypes.c_float) def write_float(self, lpBaseAddress, unpackedValue): """ Writes a float to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Floating point value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@f', unpackedValue) def read_double(self, lpBaseAddress): """ Reads a double from the memory of the process. @see: L{peek_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Floating point value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@d', ctypes.c_double) def write_double(self, lpBaseAddress, unpackedValue): """ Writes a double to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Floating point value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@d', unpackedValue) def read_pointer(self, lpBaseAddress): """ Reads a pointer value from the memory of the process. @see: L{peek_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Pointer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@P', ctypes.c_void_p) def write_pointer(self, lpBaseAddress, unpackedValue): """ Writes a pointer value to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@P', unpackedValue) def read_dword(self, lpBaseAddress): """ Reads a DWORD from the memory of the process. @see: L{peek_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '=L', win32.DWORD) def write_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '=L', unpackedValue) def read_qword(self, lpBaseAddress): """ Reads a QWORD from the memory of the process. @see: L{peek_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '=Q', win32.QWORD) def write_qword(self, lpBaseAddress, unpackedValue): """ Writes a QWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '=Q', unpackedValue) def read_structure(self, lpBaseAddress, stype): """ Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return: Structure instance filled in with data read from the process memory. @raise WindowsError: On error an exception is raised. """ if type(lpBaseAddress) not in (type(0), type(long(0))): lpBaseAddress = ctypes.cast(lpBaseAddress, ctypes.c_void_p) data = self.read(lpBaseAddress, ctypes.sizeof(stype)) buff = ctypes.create_string_buffer(data) ptr = ctypes.cast(ctypes.pointer(buff), ctypes.POINTER(stype)) return ptr.contents # XXX TODO ## def write_structure(self, lpBaseAddress, sStructure): ## """ ## Writes a ctypes structure into the memory of the process. ## ## @note: Page permissions may be changed temporarily while writing. ## ## @see: L{write} ## ## @type lpBaseAddress: int ## @param lpBaseAddress: Memory address to begin writing. ## ## @type sStructure: ctypes.Structure or a subclass' instance. ## @param sStructure: Structure definition. ## ## @rtype: int ## @return: Structure instance filled in with data ## read from the process memory. ## ## @raise WindowsError: On error an exception is raised. ## """ ## size = ctypes.sizeof(sStructure) ## data = ctypes.create_string_buffer("", size = size) ## win32.CopyMemory(ctypes.byref(data), ctypes.byref(sStructure), size) ## self.write(lpBaseAddress, data.raw) def read_string(self, lpBaseAddress, nChars, fUnicode = False): """ Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember that Unicode strings have two byte characters. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @rtype: str, compat.unicode @return: String read from the process memory space. @raise WindowsError: On error an exception is raised. """ if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString #------------------------------------------------------------------------------ # FIXME this won't work properly with a different endianness! def __peek_c_type(self, address, format, c_type): size = ctypes.sizeof(c_type) packed = self.peek(address, size) if len(packed) < size: packed = '\0' * (size - len(packed)) + packed elif len(packed) > size: packed = packed[:size] return struct.unpack(format, packed)[0] def __poke_c_type(self, address, format, unpacked): packed = struct.pack('@L', unpacked) return self.poke(address, packed) def peek(self, lpBaseAddress, nSize): """ Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Returns an empty string on error. """ # XXX TODO # + Maybe change page permissions before trying to read? # + Maybe use mquery instead of get_memory_map? # (less syscalls if we break out of the loop earlier) data = '' if nSize > 0: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) for mbi in self.get_memory_map(lpBaseAddress, lpBaseAddress + nSize): if not mbi.is_readable(): nSize = mbi.BaseAddress - lpBaseAddress break if nSize > 0: data = win32.ReadProcessMemory( hProcess, lpBaseAddress, nSize) except WindowsError: e = sys.exc_info()[1] msg = "Error reading process %d address %s: %s" msg %= (self.get_pid(), HexDump.address(lpBaseAddress), e.strerror) warnings.warn(msg) return data def poke(self, lpBaseAddress, lpBuffer): """ Writes to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type lpBuffer: str @param lpBuffer: Bytes to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ assert isinstance(lpBuffer, compat.bytes) hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_QUERY_INFORMATION ) mbi = self.mquery(lpBaseAddress) if not mbi.has_content(): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) if mbi.is_image() or mbi.is_mapped(): prot = win32.PAGE_WRITECOPY elif mbi.is_writeable(): prot = None elif mbi.is_executable(): prot = win32.PAGE_EXECUTE_READWRITE else: prot = win32.PAGE_READWRITE if prot is not None: try: self.mprotect(lpBaseAddress, len(lpBuffer), prot) except Exception: prot = None msg = ("Failed to adjust page permissions" " for process %s at address %s: %s") msg = msg % (self.get_pid(), HexDump.address(lpBaseAddress, self.get_bits()), traceback.format_exc()) warnings.warn(msg, RuntimeWarning) try: r = win32.WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer) finally: if prot is not None: self.mprotect(lpBaseAddress, len(lpBuffer), mbi.Protect) return r def peek_char(self, lpBaseAddress): """ Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error. """ char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0 def poke_char(self, lpBaseAddress, char): """ Writes a single character to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type char: str @param char: Character to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.poke(lpBaseAddress, chr(char)) def peek_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{read_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@l', ctypes.c_int) def poke_int(self, lpBaseAddress, unpackedValue): """ Writes a signed integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@l', unpackedValue) def peek_uint(self, lpBaseAddress): """ Reads an unsigned integer from the memory of the process. @see: L{read_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@L', ctypes.c_uint) def poke_uint(self, lpBaseAddress, unpackedValue): """ Writes an unsigned integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@L', unpackedValue) def peek_float(self, lpBaseAddress): """ Reads a float from the memory of the process. @see: L{read_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@f', ctypes.c_float) def poke_float(self, lpBaseAddress, unpackedValue): """ Writes a float to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@f', unpackedValue) def peek_double(self, lpBaseAddress): """ Reads a double from the memory of the process. @see: L{read_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@d', ctypes.c_double) def poke_double(self, lpBaseAddress, unpackedValue): """ Writes a double to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@d', unpackedValue) def peek_dword(self, lpBaseAddress): """ Reads a DWORD from the memory of the process. @see: L{read_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '=L', win32.DWORD) def poke_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=L', unpackedValue) def peek_qword(self, lpBaseAddress): """ Reads a QWORD from the memory of the process. @see: L{read_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '=Q', win32.QWORD) def poke_qword(self, lpBaseAddress, unpackedValue): """ Writes a QWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=Q', unpackedValue) def peek_pointer(self, lpBaseAddress): """ Reads a pointer value from the memory of the process. @see: L{read_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Pointer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@P', ctypes.c_void_p) def poke_pointer(self, lpBaseAddress, unpackedValue): """ Writes a pointer value to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@P', unpackedValue) def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000): """ Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @type dwMaxSize: int @param dwMaxSize: Maximum allowed string length to read, in bytes. @rtype: str, compat.unicode @return: String read from the process memory space. It B{doesn't} include the terminating null character. Returns an empty string on failure. """ # Validate the parameters. if not lpBaseAddress or dwMaxSize == 0: if fUnicode: return u'' return '' if not dwMaxSize: dwMaxSize = 0x1000 # Read the string. szString = self.peek(lpBaseAddress, dwMaxSize) # If the string is Unicode... if fUnicode: # Decode the string. szString = compat.unicode(szString, 'U16', 'replace') ## try: ## szString = compat.unicode(szString, 'U16') ## except UnicodeDecodeError: ## szString = struct.unpack('H' * (len(szString) / 2), szString) ## szString = [ unichr(c) for c in szString ] ## szString = u''.join(szString) # Truncate the string when the first null char is found. szString = szString[ : szString.find(u'\0') ] # If the string is ANSI... else: # Truncate the string when the first null char is found. szString = szString[ : szString.find('\0') ] # Return the decoded string. return szString # TODO # try to avoid reading the same page twice by caching it def peek_pointers_in_data(self, data, peekSize = 16, peekStep = 1): """ Tries to guess which values in the given data are valid pointers, and reads some data from them. @see: L{peek} @type data: str @param data: Binary data to find pointers in. @type peekSize: int @param peekSize: Number of bytes to read from each pointer found. @type peekStep: int @param peekStep: Expected data alignment. Tipically you specify 1 when data alignment is unknown, or 4 when you expect data to be DWORD aligned. Any other value may be specified. @rtype: dict( str S{->} str ) @return: Dictionary mapping stack offsets to the data they point to. """ result = dict() ptrSize = win32.sizeof(win32.LPVOID) if ptrSize == 4: ptrFmt = '<L' else: ptrFmt = '<Q' if len(data) > 0: for i in compat.xrange(0, len(data), peekStep): packed = data[i:i+ptrSize] if len(packed) == ptrSize: address = struct.unpack(ptrFmt, packed)[0] ## if not address & (~0xFFFF): continue peek_data = self.peek(address, peekSize) if peek_data: result[i] = peek_data return result #------------------------------------------------------------------------------ def malloc(self, dwSize, lpAddress = None): """ Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. @rtype: int @return: Address of the newly allocated memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize) def mprotect(self, lpAddress, dwSize, flNewProtect): """ Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewProtect: int @param flNewProtect: New protect flags. @rtype: int @return: Old protect flags. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect) def mquery(self, lpAddress): """ Query memory information from the address space of the process. Returns a L{win32.MemoryBasicInformation} object. @see: U{http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to query. @rtype: L{win32.MemoryBasicInformation} @return: Memory region information. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.VirtualQueryEx(hProcess, lpAddress) def free(self, lpAddress): """ Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress) #------------------------------------------------------------------------------ def is_pointer(self, address): """ Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code or data pointer. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.has_content() def is_address_valid(self, address): """ Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return True def is_address_free(self, address): """ Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_free() def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_reserved() def is_address_commited(self, address): """ Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_commited() def is_address_guard(self, address): """ Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard() def is_address_readable(self, address): """ Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and readable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_readable() def is_address_writeable(self, address): """ Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and writeable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_writeable() def is_address_copy_on_write(self, address): """ Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, copy-on-write page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_copy_on_write() def is_address_executable(self, address): """ Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable() def is_address_executable_and_writeable(self, address): """ Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, writeable and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable_and_writeable() def is_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is a valid code or data buffer, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.has_content(): return False size = size - mbi.RegionSize return True def is_buffer_readable(self, address, size): """ Determines if the given memory area is readable. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is readable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_readable(): return False size = size - mbi.RegionSize return True def is_buffer_writeable(self, address, size): """ Determines if the given memory area is writeable. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is writeable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_writeable(): return False size = size - mbi.RegionSize return True def is_buffer_copy_on_write(self, address, size): """ Determines if the given memory area is marked as copy-on-write. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is marked as copy-on-write, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_copy_on_write(): return False size = size - mbi.RegionSize return True def is_buffer_executable(self, address, size): """ Determines if the given memory area is executable. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is executable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_executable(): return False size = size - mbi.RegionSize return True def is_buffer_executable_and_writeable(self, address, size): """ Determines if the given memory area is writeable and executable. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is writeable and executable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_executable(): return False size = size - mbi.RegionSize return True def get_memory_map(self, minAddr = None, maxAddr = None): """ Produces a memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: list( L{win32.MemoryBasicInformation} ) @return: List of memory region information objects. """ return list(self.iter_memory_map(minAddr, maxAddr)) def generate_memory_map(self, minAddr = None, maxAddr = None): """ Returns a L{Regenerator} that can iterate indefinitely over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: L{Regenerator} of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """ return Regenerator(self.iter_memory_map, minAddr, maxAddr) def iter_memory_map(self, minAddr = None, maxAddr = None): """ Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """ minAddr, maxAddr = MemoryAddresses.align_address_range(minAddr,maxAddr) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr: try: mbi = self.mquery(currentAddr) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: break raise yield mbi prevAddr = currentAddr currentAddr = mbi.BaseAddress + mbi.RegionSize def get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @return: Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not memoryMap: memoryMap = self.get_memory_map() mappedFilenames = dict() for mbi in memoryMap: if mbi.Type not in (win32.MEM_IMAGE, win32.MEM_MAPPED): continue baseAddress = mbi.BaseAddress fileName = "" try: fileName = win32.GetMappedFileName(hProcess, baseAddress) fileName = PathOperations.native_to_win32_pathname(fileName) except WindowsError: #e = sys.exc_info()[1] #try: # msg = "Can't get mapped file name at address %s in process " \ # "%d, reason: %s" % (HexDump.address(baseAddress), # self.get_pid(), # e.strerror) # warnings.warn(msg, Warning) #except Exception: pass mappedFilenames[baseAddress] = fileName return mappedFilenames def generate_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns a L{Regenerator} that allows you to iterate through the memory contents of a process indefinitely. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can be iterated more than once. Each time it's iterated the memory contents of the process will be fetched again. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: L{Regenerator} of L{win32.MemoryBasicInformation} @return: Generator that when iterated returns memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ return Regenerator(self.iter_memory_snapshot, minAddr, maxAddr) def iter_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can only iterated once. To be able to iterate indefinitely call the L{generate_memory_snapshot} method instead. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: Iterator of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ # One may feel tempted to include calls to self.suspend() and # self.resume() here, but that wouldn't work on a dead process. # It also wouldn't be needed when debugging since the process is # already suspended when the debug event arrives. So it's up to # the user to suspend the process if needed. # Get the memory map. memory = self.get_memory_map(minAddr, maxAddr) # Abort if the map couldn't be retrieved. if not memory: return # Get the mapped filenames. # Don't fail on access denied errors. try: filenames = self.get_mapped_filenames(memory) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise filenames = dict() # Trim the first memory information block if needed. if minAddr is not None: minAddr = MemoryAddresses.align_address_to_page_start(minAddr) mbi = memory[0] if mbi.BaseAddress < minAddr: mbi.RegionSize = mbi.BaseAddress + mbi.RegionSize - minAddr mbi.BaseAddress = minAddr # Trim the last memory information block if needed. if maxAddr is not None: if maxAddr != MemoryAddresses.align_address_to_page_start(maxAddr): maxAddr = MemoryAddresses.align_address_to_page_end(maxAddr) mbi = memory[-1] if mbi.BaseAddress + mbi.RegionSize > maxAddr: mbi.RegionSize = maxAddr - mbi.BaseAddress # Read the contents of each block and yield it. while memory: mbi = memory.pop(0) # so the garbage collector can take it mbi.filename = filenames.get(mbi.BaseAddress, None) if mbi.has_content(): mbi.content = self.read(mbi.BaseAddress, mbi.RegionSize) else: mbi.content = None yield mbi def take_memory_snapshot(self, minAddr = None, maxAddr = None): """ Takes a snapshot of the memory contents of the process. It's best if the process is suspended (if alive) when taking the snapshot. Execution can be resumed afterwards. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.take_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @warning: If the target process has a very big memory footprint, the resulting snapshot will be equally big. This may result in a severe performance penalty. @see: L{generate_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: list( L{win32.MemoryBasicInformation} ) @return: List of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ return list( self.iter_memory_snapshot(minAddr, maxAddr) ) def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False): """ Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). @type snapshot: list( L{win32.MemoryBasicInformation} ) @param snapshot: Memory snapshot returned by L{take_memory_snapshot}. Snapshots returned by L{generate_memory_snapshot} don't work here. @type bSkipMappedFiles: bool @param bSkipMappedFiles: C{True} to avoid restoring the contents of memory mapped files, C{False} otherwise. Use with care! Setting this to C{False} can cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don't change, so trying to restore their contents is usually a waste of time. @type bSkipOnError: bool @param bSkipOnError: C{True} to issue a warning when an error occurs during the restoration of the snapshot, C{False} to stop and raise an exception instead. Use with care! Setting this to C{True} will cause the debugger to falsely believe the memory snapshot has been correctly restored. @raise WindowsError: An error occured while restoring the snapshot. @raise RuntimeError: An error occured while restoring the snapshot. @raise TypeError: A snapshot of the wrong type was passed. """ if not snapshot or not isinstance(snapshot, list) \ or not isinstance(snapshot[0], win32.MemoryBasicInformation): raise TypeError( "Only snapshots returned by " \ "take_memory_snapshot() can be used here." ) # Get the process handle. hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_SUSPEND_RESUME | win32.PROCESS_QUERY_INFORMATION ) # Freeze the process. self.suspend() try: # For each memory region in the snapshot... for old_mbi in snapshot: # If the region matches, restore it directly. new_mbi = self.mquery(old_mbi.BaseAddress) if new_mbi.BaseAddress == old_mbi.BaseAddress and \ new_mbi.RegionSize == old_mbi.RegionSize: self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles) # If the region doesn't match, restore it page by page. else: # We need a copy so we don't corrupt the snapshot. old_mbi = win32.MemoryBasicInformation(old_mbi) # Get the overlapping range of pages. old_start = old_mbi.BaseAddress old_end = old_start + old_mbi.RegionSize new_start = new_mbi.BaseAddress new_end = new_start + new_mbi.RegionSize if old_start > new_start: start = old_start else: start = new_start if old_end < new_end: end = old_end else: end = new_end # Restore each page in the overlapping range. step = MemoryAddresses.pageSize old_mbi.RegionSize = step new_mbi.RegionSize = step address = start while address < end: old_mbi.BaseAddress = address new_mbi.BaseAddress = address self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError) address = address + step # Resume execution. finally: self.resume() def __restore_mbi(self, hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError): """ Used internally by L{restore_memory_snapshot}. """ ## print "Restoring %s-%s" % ( ## HexDump.address(old_mbi.BaseAddress, self.get_bits()), ## HexDump.address(old_mbi.BaseAddress + old_mbi.RegionSize, ## self.get_bits())) try: # Restore the region state. if new_mbi.State != old_mbi.State: if new_mbi.is_free(): if old_mbi.is_reserved(): # Free -> Reserved address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RESERVE, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect else: # elif old_mbi.is_commited(): # Free -> Commited address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RESERVE | \ win32.MEM_COMMIT, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect elif new_mbi.is_reserved(): if old_mbi.is_commited(): # Reserved -> Commited address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_COMMIT, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect else: # elif old_mbi.is_free(): # Reserved -> Free win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RELEASE) else: # elif new_mbi.is_commited(): if old_mbi.is_reserved(): # Commited -> Reserved win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_DECOMMIT) else: # elif old_mbi.is_free(): # Commited -> Free win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_DECOMMIT | win32.MEM_RELEASE) new_mbi.State = old_mbi.State # Restore the region permissions. if old_mbi.is_commited() and old_mbi.Protect != new_mbi.Protect: win32.VirtualProtectEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, old_mbi.Protect) new_mbi.Protect = old_mbi.Protect # Restore the region data. # Ignore write errors when the region belongs to a mapped file. if old_mbi.has_content(): if old_mbi.Type != 0: if not bSkipMappedFiles: self.poke(old_mbi.BaseAddress, old_mbi.content) else: self.write(old_mbi.BaseAddress, old_mbi.content) new_mbi.content = old_mbi.content # On error, skip this region or raise an exception. except Exception: if not bSkipOnError: raise msg = "Error restoring region at address %s: %s" msg = msg % ( HexDump(old_mbi.BaseAddress, self.get_bits()), traceback.format_exc()) warnings.warn(msg, RuntimeWarning) #------------------------------------------------------------------------------ def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run in a new thread. @type lpParameter: int @param lpParameter: (Optional) Parameter to be pushed in the stack. @rtype: tuple( L{Thread}, int ) @return: The injected Thread object and the memory address where the code was written. @raise WindowsError: An exception is raised on error. """ # Uncomment for debugging... ## payload = '\xCC' + payload # Allocate the memory for the shellcode. lpStartAddress = self.malloc(len(payload)) # Catch exceptions so we can free the memory on error. try: # Write the shellcode to our memory location. self.write(lpStartAddress, payload) # Start a new thread for the shellcode to run. aThread = self.start_thread(lpStartAddress, lpParameter, bSuspended = False) # Remember the shellcode address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code, or have your shellcode clean up # after itself (recommended). aThread.pInjectedMemory = lpStartAddress # Free the memory on error. except Exception: self.free(lpStartAddress) raise # Return the Thread object and the shellcode address. return aThread, lpStartAddress # TODO # The shellcode should check for errors, otherwise it just crashes # when the DLL can't be loaded or the procedure can't be found. # On error the shellcode should execute an int3 instruction. def inject_dll(self, dllname, procname = None, lpParameter = 0, bWait = True, dwTimeout = None): """ Injects a DLL into the process memory. @warning: Setting C{bWait} to C{True} when the process is frozen by a debug event will cause a deadlock in your debugger. @warning: This involves allocating memory in the target process. This is how the freeing of this memory is handled: - If the C{bWait} flag is set to C{True} the memory will be freed automatically before returning from this method. - If the C{bWait} flag is set to C{False}, the memory address is set as the L{Thread.pInjectedMemory} property of the returned thread object. - L{Debug} objects free L{Thread.pInjectedMemory} automatically both when it detaches from a process and when the injected thread finishes its execution. - The {Thread.kill} method also frees L{Thread.pInjectedMemory} automatically, even if you're not attached to the process. You could still be leaking memory if not careful. For example, if you inject a dll into a process you're not attached to, you don't wait for the thread's completion and you don't kill it either, the memory would be leaked. @see: L{inject_code} @type dllname: str @param dllname: Name of the DLL module to load. @type procname: str @param procname: (Optional) Procedure to call when the DLL is loaded. @type lpParameter: int @param lpParameter: (Optional) Parameter to the C{procname} procedure. @type bWait: bool @param bWait: C{True} to wait for the process to finish. C{False} to return immediately. @type dwTimeout: int @param dwTimeout: (Optional) Timeout value in milliseconds. Ignored if C{bWait} is C{False}. @rtype: L{Thread} @return: Newly created thread object. If C{bWait} is set to C{True} the thread will be dead, otherwise it will be alive. @raise NotImplementedError: The target platform is not supported. Currently calling a procedure in the library is only supported in the I{i386} architecture. @raise WindowsError: An exception is raised on error. """ # Resolve kernel32.dll aModule = self.get_module_by_name(compat.b('kernel32.dll')) if aModule is None: self.scan_modules() aModule = self.get_module_by_name(compat.b('kernel32.dll')) if aModule is None: raise RuntimeError( "Cannot resolve kernel32.dll in the remote process") # Old method, using shellcode. if procname: if self.get_arch() != win32.ARCH_I386: raise NotImplementedError() dllname = compat.b(dllname) # Resolve kernel32.dll!LoadLibraryA pllib = aModule.resolve(compat.b('LoadLibraryA')) if not pllib: raise RuntimeError( "Cannot resolve kernel32.dll!LoadLibraryA" " in the remote process") # Resolve kernel32.dll!GetProcAddress pgpad = aModule.resolve(compat.b('GetProcAddress')) if not pgpad: raise RuntimeError( "Cannot resolve kernel32.dll!GetProcAddress" " in the remote process") # Resolve kernel32.dll!VirtualFree pvf = aModule.resolve(compat.b('VirtualFree')) if not pvf: raise RuntimeError( "Cannot resolve kernel32.dll!VirtualFree" " in the remote process") # Shellcode follows... code = compat.b('') # push dllname code += compat.b('\xe8') + struct.pack('<L', len(dllname) + 1) + dllname + compat.b('\0') # mov eax, LoadLibraryA code += compat.b('\xb8') + struct.pack('<L', pllib) # call eax code += compat.b('\xff\xd0') if procname: # push procname code += compat.b('\xe8') + struct.pack('<L', len(procname) + 1) code += procname + compat.b('\0') # push eax code += compat.b('\x50') # mov eax, GetProcAddress code += compat.b('\xb8') + struct.pack('<L', pgpad) # call eax code += compat.b('\xff\xd0') # mov ebp, esp ; preserve stack pointer code += compat.b('\x8b\xec') # push lpParameter code += compat.b('\x68') + struct.pack('<L', lpParameter) # call eax code += compat.b('\xff\xd0') # mov esp, ebp ; restore stack pointer code += compat.b('\x8b\xe5') # pop edx ; our own return address code += compat.b('\x5a') # push MEM_RELEASE ; dwFreeType code += compat.b('\x68') + struct.pack('<L', win32.MEM_RELEASE) # push 0x1000 ; dwSize, shellcode max size 4096 bytes code += compat.b('\x68') + struct.pack('<L', 0x1000) # call $+5 code += compat.b('\xe8\x00\x00\x00\x00') # and dword ptr [esp], 0xFFFFF000 ; align to page boundary code += compat.b('\x81\x24\x24\x00\xf0\xff\xff') # mov eax, VirtualFree code += compat.b('\xb8') + struct.pack('<L', pvf) # push edx ; our own return address code += compat.b('\x52') # jmp eax ; VirtualFree will return to our own return address code += compat.b('\xff\xe0') # Inject the shellcode. # There's no need to free the memory, # because the shellcode will free it itself. aThread, lpStartAddress = self.inject_code(code, lpParameter) # New method, not using shellcode. else: # Resolve kernel32.dll!LoadLibrary (A/W) if type(dllname) == type(u''): pllibname = compat.b('LoadLibraryW') bufferlen = (len(dllname) + 1) * 2 dllname = win32.ctypes.create_unicode_buffer(dllname).raw[:bufferlen + 1] else: pllibname = compat.b('LoadLibraryA') dllname = compat.b(dllname) + compat.b('\x00') bufferlen = len(dllname) pllib = aModule.resolve(pllibname) if not pllib: msg = "Cannot resolve kernel32.dll!%s in the remote process" raise RuntimeError(msg % pllibname) # Copy the library name into the process memory space. pbuffer = self.malloc(bufferlen) try: self.write(pbuffer, dllname) # Create a new thread to load the library. try: aThread = self.start_thread(pllib, pbuffer) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_NOT_ENOUGH_MEMORY: raise # This specific error is caused by trying to spawn a new # thread in a process belonging to a different Terminal # Services session (for example a service). raise NotImplementedError( "Target process belongs to a different" " Terminal Services session, cannot inject!" ) # Remember the buffer address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code. aThread.pInjectedMemory = pbuffer # Free the memory on error. except Exception: self.free(pbuffer) raise # Wait for the thread to finish. if bWait: aThread.wait(dwTimeout) self.free(aThread.pInjectedMemory) del aThread.pInjectedMemory # Return the thread object. return aThread def clean_exit(self, dwExitCode = 0, bWait = False, dwTimeout = None): """ Injects a new thread to call ExitProcess(). Optionally waits for the injected thread to finish. @warning: Setting C{bWait} to C{True} when the process is frozen by a debug event will cause a deadlock in your debugger. @type dwExitCode: int @param dwExitCode: Process exit code. @type bWait: bool @param bWait: C{True} to wait for the process to finish. C{False} to return immediately. @type dwTimeout: int @param dwTimeout: (Optional) Timeout value in milliseconds. Ignored if C{bWait} is C{False}. @raise WindowsError: An exception is raised on error. """ if not dwExitCode: dwExitCode = 0 pExitProcess = self.resolve_label('kernel32!ExitProcess') aThread = self.start_thread(pExitProcess, dwExitCode) if bWait: aThread.wait(dwTimeout) #------------------------------------------------------------------------------ def _notify_create_process(self, event): """ Notify the creation of a new process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ # Do not use super() here. bCallHandler = _ThreadContainer._notify_create_process(self, event) bCallHandler = bCallHandler and \ _ModuleContainer._notify_create_process(self, event) return bCallHandler #============================================================================== class _ProcessContainer (object): """ Encapsulates the capability to contain Process objects. @group Instrumentation: start_process, argv_to_cmdline, cmdline_to_argv, get_explorer_pid @group Processes snapshot: scan, scan_processes, scan_processes_fast, get_process, get_process_count, get_process_ids, has_process, iter_processes, iter_process_ids, find_processes_by_filename, get_pid_from_tid, get_windows, scan_process_filenames, clear, clear_processes, clear_dead_processes, clear_unattached_processes, close_process_handles, close_process_and_thread_handles @group Threads snapshots: scan_processes_and_threads, get_thread, get_thread_count, get_thread_ids, has_thread @group Modules snapshots: scan_modules, find_modules_by_address, find_modules_by_base, find_modules_by_name, get_module_count """ def __init__(self): self.__processDict = dict() def __initialize_snapshot(self): """ Private method to automatically initialize the snapshot when you try to use it without calling any of the scan_* methods first. You don't need to call this yourself. """ if not self.__processDict: try: self.scan_processes() # remote desktop api (relative fn) except Exception: self.scan_processes_fast() # psapi (no filenames) self.scan_process_filenames() # get the pathnames when possible def __contains__(self, anObject): """ @type anObject: L{Process}, L{Thread}, int @param anObject: - C{int}: Global ID of the process to look for. - C{int}: Global ID of the thread to look for. - C{Process}: Process object to look for. - C{Thread}: Thread object to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Process} or L{Thread} object with the same ID. """ if isinstance(anObject, Process): anObject = anObject.dwProcessId if self.has_process(anObject): return True for aProcess in self.iter_processes(): if anObject in aProcess: return True return False def __iter__(self): """ @see: L{iter_processes} @rtype: dictionary-valueiterator @return: Iterator of L{Process} objects in this snapshot. """ return self.iter_processes() def __len__(self): """ @see: L{get_process_count} @rtype: int @return: Count of L{Process} objects in this snapshot. """ return self.get_process_count() def has_process(self, dwProcessId): """ @type dwProcessId: int @param dwProcessId: Global ID of the process to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Process} object with the given global ID. """ self.__initialize_snapshot() return dwProcessId in self.__processDict def get_process(self, dwProcessId): """ @type dwProcessId: int @param dwProcessId: Global ID of the process to look for. @rtype: L{Process} @return: Process object with the given global ID. """ self.__initialize_snapshot() if dwProcessId not in self.__processDict: msg = "Unknown process ID %d" % dwProcessId raise KeyError(msg) return self.__processDict[dwProcessId] def iter_process_ids(self): """ @see: L{iter_processes} @rtype: dictionary-keyiterator @return: Iterator of global process IDs in this snapshot. """ self.__initialize_snapshot() return compat.iterkeys(self.__processDict) def iter_processes(self): """ @see: L{iter_process_ids} @rtype: dictionary-valueiterator @return: Iterator of L{Process} objects in this snapshot. """ self.__initialize_snapshot() return compat.itervalues(self.__processDict) def get_process_ids(self): """ @see: L{iter_process_ids} @rtype: list( int ) @return: List of global process IDs in this snapshot. """ self.__initialize_snapshot() return compat.keys(self.__processDict) def get_process_count(self): """ @rtype: int @return: Count of L{Process} objects in this snapshot. """ self.__initialize_snapshot() return len(self.__processDict) #------------------------------------------------------------------------------ # XXX TODO # Support for string searches on the window captions. def get_windows(self): """ @rtype: list of L{Window} @return: Returns a list of windows handled by all processes in this snapshot. """ window_list = list() for process in self.iter_processes(): window_list.extend( process.get_windows() ) return window_list def get_pid_from_tid(self, dwThreadId): """ Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist. """ try: # No good, because in XP and below it tries to get the PID # through the toolhelp API, and that's slow. We don't want # to scan for threads over and over for each call. ## dwProcessId = Thread(dwThreadId).get_pid() # This API only exists in Windows 2003, Vista and above. try: hThread = win32.OpenThread( win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise hThread = win32.OpenThread( win32.THREAD_QUERY_INFORMATION, False, dwThreadId) try: return win32.GetProcessIdOfThread(hThread) finally: hThread.close() # If all else fails, go through all processes in the snapshot # looking for the one that owns the thread we're looking for. # If the snapshot was empty the iteration should trigger an # automatic scan. Otherwise, it'll look for the thread in what # could possibly be an outdated snapshot. except Exception: for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # The thread wasn't found, so let's refresh the snapshot and retry. # Normally this shouldn't happen since this function is only useful # for the debugger, so the thread should already exist in the snapshot. self.scan_processes_and_threads() for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # No luck! It appears to be the thread doesn't exist after all. msg = "Unknown thread ID %d" % dwThreadId raise KeyError(msg) #------------------------------------------------------------------------------ @staticmethod def argv_to_cmdline(argv): """ Convert a list of arguments to a single command line string. @type argv: list( str ) @param argv: List of argument strings. The first element is the program to execute. @rtype: str @return: Command line string. """ cmdline = list() for token in argv: if not token: token = '""' else: if '"' in token: token = token.replace('"', '\\"') if ' ' in token or \ '\t' in token or \ '\n' in token or \ '\r' in token: token = '"%s"' % token cmdline.append(token) return ' '.join(cmdline) @staticmethod def cmdline_to_argv(lpCmdLine): """ Convert a single command line string to a list of arguments. @type lpCmdLine: str @param lpCmdLine: Command line string. The first token is the program to execute. @rtype: list( str ) @return: List of argument strings. """ if not lpCmdLine: return [] return win32.CommandLineToArgv(lpCmdLine) def start_process(self, lpCmdLine, **kwargs): """ Starts a new process for instrumenting (or debugging). @type lpCmdLine: str @param lpCmdLine: Command line to execute. Can't be an empty string. @type bConsole: bool @keyword bConsole: True to inherit the console of the debugger. Defaults to C{False}. @type bDebug: bool @keyword bDebug: C{True} to attach to the new process. To debug a process it's best to use the L{Debug} class instead. Defaults to C{False}. @type bFollow: bool @keyword bFollow: C{True} to automatically attach to the child processes of the newly created process. Ignored unless C{bDebug} is C{True}. Defaults to C{False}. @type bInheritHandles: bool @keyword bInheritHandles: C{True} if the new process should inherit it's parent process' handles. Defaults to C{False}. @type bSuspended: bool @keyword bSuspended: C{True} to suspend the main thread before any code is executed in the debugee. Defaults to C{False}. @type dwParentProcessId: int or None @keyword dwParentProcessId: C{None} if the debugger process should be the parent process (default), or a process ID to forcefully set as the debugee's parent (only available for Windows Vista and above). @type iTrustLevel: int @keyword iTrustLevel: Trust level. Must be one of the following values: - 0: B{No trust}. May not access certain resources, such as cryptographic keys and credentials. Only available since Windows XP and 2003, desktop editions. - 1: B{Normal trust}. Run with the same privileges as a normal user, that is, one that doesn't have the I{Administrator} or I{Power User} user rights. Only available since Windows XP and 2003, desktop editions. - 2: B{Full trust}. Run with the exact same privileges as the current user. This is the default value. @type bAllowElevation: bool @keyword bAllowElevation: C{True} to allow the child process to keep UAC elevation, if the debugger itself is running elevated. C{False} to ensure the child process doesn't run with elevation. Defaults to C{True}. This flag is only meaningful on Windows Vista and above, and if the debugger itself is running with elevation. It can be used to make sure the child processes don't run elevated as well. This flag DOES NOT force an elevation prompt when the debugger is not running with elevation. Note that running the debugger with elevation (or the Python interpreter at all for that matter) is not normally required. You should only need to if the target program requires elevation to work properly (for example if you try to debug an installer). @rtype: L{Process} @return: Process object. """ # Get the flags. bConsole = kwargs.pop('bConsole', False) bDebug = kwargs.pop('bDebug', False) bFollow = kwargs.pop('bFollow', False) bSuspended = kwargs.pop('bSuspended', False) bInheritHandles = kwargs.pop('bInheritHandles', False) dwParentProcessId = kwargs.pop('dwParentProcessId', None) iTrustLevel = kwargs.pop('iTrustLevel', 2) bAllowElevation = kwargs.pop('bAllowElevation', True) if kwargs: raise TypeError("Unknown keyword arguments: %s" % compat.keys(kwargs)) if not lpCmdLine: raise ValueError("Missing command line to execute!") # Sanitize the trust level flag. if iTrustLevel is None: iTrustLevel = 2 # The UAC elevation flag is only meaningful if we're running elevated. try: bAllowElevation = bAllowElevation or not self.is_admin() except AttributeError: bAllowElevation = True warnings.warn( "UAC elevation is only available in Windows Vista and above", RuntimeWarning) # Calculate the process creation flags. dwCreationFlags = 0 dwCreationFlags |= win32.CREATE_DEFAULT_ERROR_MODE dwCreationFlags |= win32.CREATE_BREAKAWAY_FROM_JOB ##dwCreationFlags |= win32.CREATE_UNICODE_ENVIRONMENT if not bConsole: dwCreationFlags |= win32.DETACHED_PROCESS #dwCreationFlags |= win32.CREATE_NO_WINDOW # weird stuff happens if bSuspended: dwCreationFlags |= win32.CREATE_SUSPENDED if bDebug: dwCreationFlags |= win32.DEBUG_PROCESS if not bFollow: dwCreationFlags |= win32.DEBUG_ONLY_THIS_PROCESS # Change the parent process if requested. # May fail on old versions of Windows. lpStartupInfo = None if dwParentProcessId is not None: myPID = win32.GetCurrentProcessId() if dwParentProcessId != myPID: if self.has_process(dwParentProcessId): ParentProcess = self.get_process(dwParentProcessId) else: ParentProcess = Process(dwParentProcessId) ParentProcessHandle = ParentProcess.get_handle( win32.PROCESS_CREATE_PROCESS) AttributeListData = ( ( win32.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, ParentProcessHandle._as_parameter_ ), ) AttributeList = win32.ProcThreadAttributeList(AttributeListData) StartupInfoEx = win32.STARTUPINFOEX() StartupInfo = StartupInfoEx.StartupInfo StartupInfo.cb = win32.sizeof(win32.STARTUPINFOEX) StartupInfo.lpReserved = 0 StartupInfo.lpDesktop = 0 StartupInfo.lpTitle = 0 StartupInfo.dwFlags = 0 StartupInfo.cbReserved2 = 0 StartupInfo.lpReserved2 = 0 StartupInfoEx.lpAttributeList = AttributeList.value lpStartupInfo = StartupInfoEx dwCreationFlags |= win32.EXTENDED_STARTUPINFO_PRESENT pi = None try: # Create the process the easy way. if iTrustLevel >= 2 and bAllowElevation: pi = win32.CreateProcess(None, lpCmdLine, bInheritHandles = bInheritHandles, dwCreationFlags = dwCreationFlags, lpStartupInfo = lpStartupInfo) # Create the process the hard way... else: # If we allow elevation, use the current process token. # If not, get the token from the current shell process. hToken = None try: if not bAllowElevation: if bFollow: msg = ( "Child processes can't be autofollowed" " when dropping UAC elevation.") raise NotImplementedError(msg) if bConsole: msg = ( "Child processes can't inherit the debugger's" " console when dropping UAC elevation.") raise NotImplementedError(msg) if bInheritHandles: msg = ( "Child processes can't inherit the debugger's" " handles when dropping UAC elevation.") raise NotImplementedError(msg) try: hWnd = self.get_shell_window() except WindowsError: hWnd = self.get_desktop_window() shell = hWnd.get_process() try: hShell = shell.get_handle( win32.PROCESS_QUERY_INFORMATION) with win32.OpenProcessToken(hShell) as hShellToken: hToken = win32.DuplicateTokenEx(hShellToken) finally: shell.close_handle() # Lower trust level if requested. if iTrustLevel < 2: if iTrustLevel > 0: dwLevelId = win32.SAFER_LEVELID_NORMALUSER else: dwLevelId = win32.SAFER_LEVELID_UNTRUSTED with win32.SaferCreateLevel(dwLevelId = dwLevelId) as hSafer: hSaferToken = win32.SaferComputeTokenFromLevel( hSafer, hToken)[0] try: if hToken is not None: hToken.close() except: hSaferToken.close() raise hToken = hSaferToken # If we have a computed token, call CreateProcessAsUser(). if bAllowElevation: pi = win32.CreateProcessAsUser( hToken = hToken, lpCommandLine = lpCmdLine, bInheritHandles = bInheritHandles, dwCreationFlags = dwCreationFlags, lpStartupInfo = lpStartupInfo) # If we have a primary token call CreateProcessWithToken(). # The problem is, there are many flags CreateProcess() and # CreateProcessAsUser() accept but CreateProcessWithToken() # and CreateProcessWithLogonW() don't, so we need to work # around them. else: # Remove the debug flags. dwCreationFlags &= ~win32.DEBUG_PROCESS dwCreationFlags &= ~win32.DEBUG_ONLY_THIS_PROCESS # Remove the console flags. dwCreationFlags &= ~win32.DETACHED_PROCESS # The process will be created suspended. dwCreationFlags |= win32.CREATE_SUSPENDED # Create the process using the new primary token. pi = win32.CreateProcessWithToken( hToken = hToken, dwLogonFlags = win32.LOGON_WITH_PROFILE, lpCommandLine = lpCmdLine, dwCreationFlags = dwCreationFlags, lpStartupInfo = lpStartupInfo) # Attach as a debugger, if requested. if bDebug: win32.DebugActiveProcess(pi.dwProcessId) # Resume execution, if requested. if not bSuspended: win32.ResumeThread(pi.hThread) # Close the token when we're done with it. finally: if hToken is not None: hToken.close() # Wrap the new process and thread in Process and Thread objects, # and add them to the corresponding snapshots. aProcess = Process(pi.dwProcessId, pi.hProcess) aThread = Thread (pi.dwThreadId, pi.hThread) aProcess._add_thread(aThread) self._add_process(aProcess) # Clean up on error. except: if pi is not None: try: win32.TerminateProcess(pi.hProcess) except WindowsError: pass pi.hThread.close() pi.hProcess.close() raise # Return the new Process object. return aProcess def get_explorer_pid(self): """ Tries to find the process ID for "explorer.exe". @rtype: int or None @return: Returns the process ID, or C{None} on error. """ try: exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS) except Exception: exp = None if not exp: exp = os.getenv('SystemRoot') if exp: exp = os.path.join(exp, 'explorer.exe') exp_list = self.find_processes_by_filename(exp) if exp_list: return exp_list[0][0].get_pid() return None #------------------------------------------------------------------------------ # XXX this methods musn't end up calling __initialize_snapshot by accident! def scan(self): """ Populates the snapshot with running processes and threads, and loaded modules. Tipically this is the first method called after instantiating a L{System} object, as it makes a best effort approach to gathering information on running processes. @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to. """ has_threads = True try: try: # Try using the Toolhelp API # to scan for processes and threads. self.scan_processes_and_threads() except Exception: # On error, try using the PSAPI to scan for process IDs only. self.scan_processes_fast() # Now try using the Toolhelp again to get the threads. for aProcess in self.__processDict.values(): if aProcess._get_thread_ids(): try: aProcess.scan_threads() except WindowsError: has_threads = False finally: # Try using the Remote Desktop API to scan for processes only. # This will update the filenames when it's not possible # to obtain them from the Toolhelp API. self.scan_processes() # When finished scanning for processes, try modules too. has_modules = self.scan_modules() # Try updating the process filenames when possible. has_full_names = self.scan_process_filenames() # Return the completion status. return has_threads and has_modules and has_full_names def scan_processes_and_threads(self): """ Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # The main module filename may be spoofed by malware, # since this information resides in usermode space. # See: http://www.ragestorm.net/blogs/?p=163 our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) found_tids = set() # Ignore our own process if it's in the snapshot for some reason if our_pid in dead_pids: dead_pids.remove(our_pid) # Take a snapshot of all processes and threads dwFlags = win32.TH32CS_SNAPPROCESS | win32.TH32CS_SNAPTHREAD with win32.CreateToolhelp32Snapshot(dwFlags) as hSnapshot: # Add all the processes (excluding our own) pe = win32.Process32First(hSnapshot) while pe is not None: dwProcessId = pe.th32ProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId not in self.__processDict: aProcess = Process(dwProcessId, fileName=pe.szExeFile) self._add_process(aProcess) elif pe.szExeFile: aProcess = self.get_process(dwProcessId) if not aProcess.fileName: aProcess.fileName = pe.szExeFile pe = win32.Process32Next(hSnapshot) # Add all the threads te = win32.Thread32First(hSnapshot) while te is not None: dwProcessId = te.th32OwnerProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId in self.__processDict: aProcess = self.get_process(dwProcessId) else: aProcess = Process(dwProcessId) self._add_process(aProcess) dwThreadId = te.th32ThreadID found_tids.add(dwThreadId) if not aProcess._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = aProcess) aProcess._add_thread(aThread) te = win32.Thread32Next(hSnapshot) # Remove dead processes for pid in dead_pids: self._del_process(pid) # Remove dead threads for aProcess in compat.itervalues(self.__processDict): dead_tids = set( aProcess._get_thread_ids() ) dead_tids.difference_update(found_tids) for tid in dead_tids: aProcess._del_thread(tid) def scan_modules(self): """ Populates the snapshot with loaded modules. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_processes_and_threads} @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to. """ complete = True for aProcess in compat.itervalues(self.__processDict): try: aProcess.scan_modules() except WindowsError: complete = False return complete def scan_processes(self): """ Populates the snapshot with running processes. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Remote Desktop API instead of the Toolhelp API. It might give slightly different results, especially if the current process does not have full privileges. @note: This method will only retrieve process filenames. To get the process pathnames instead, B{after} this method call L{scan_process_filenames}. @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # Get the previous list of PIDs. # We'll be removing live PIDs from it as we find them. our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own PID. if our_pid in dead_pids: dead_pids.remove(our_pid) # Get the list of processes from the Remote Desktop API. pProcessInfo = None try: pProcessInfo, dwCount = win32.WTSEnumerateProcesses( win32.WTS_CURRENT_SERVER_HANDLE) # For each process found... for index in compat.xrange(dwCount): sProcessInfo = pProcessInfo[index] ## # Ignore processes belonging to other sessions. ## if sProcessInfo.SessionId != win32.WTS_CURRENT_SESSION: ## continue # Ignore our own PID. pid = sProcessInfo.ProcessId if pid == our_pid: continue # Remove the PID from the dead PIDs list. if pid in dead_pids: dead_pids.remove(pid) # Get the "process name". # Empirically, this seems to be the filename without the path. # (The MSDN docs aren't very clear about this API call). fileName = sProcessInfo.pProcessName # If the process is new, add a new Process object. if pid not in self.__processDict: aProcess = Process(pid, fileName = fileName) self._add_process(aProcess) # If the process was already in the snapshot, and the # filename is missing, update the Process object. elif fileName: aProcess = self.__processDict.get(pid) if not aProcess.fileName: aProcess.fileName = fileName # Free the memory allocated by the Remote Desktop API. finally: if pProcessInfo is not None: try: win32.WTSFreeMemory(pProcessInfo) except WindowsError: pass # At this point the only remaining PIDs from the old list are dead. # Remove them from the snapshot. for pid in dead_pids: self._del_process(pid) def scan_processes_fast(self): """ Populates the snapshot with running processes. Only the PID is retrieved for each process. Dead processes are removed. Threads and modules of living processes are ignored. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the PSAPI. It may be faster for scanning, but some information may be missing, outdated or slower to obtain. This could be a good tradeoff under some circumstances. """ # Get the new and old list of pids new_pids = set( win32.EnumProcesses() ) old_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own pid our_pid = win32.GetCurrentProcessId() if our_pid in new_pids: new_pids.remove(our_pid) if our_pid in old_pids: old_pids.remove(our_pid) # Add newly found pids for pid in new_pids.difference(old_pids): self._add_process( Process(pid) ) # Remove missing pids for pid in old_pids.difference(new_pids): self._del_process(pid) def scan_process_filenames(self): """ Update the filename for each process in the snapshot when possible. @note: Tipically you don't need to call this method. It's called automatically by L{scan} to get the full pathname for each process when possible, since some scan methods only get filenames without the path component. If unsure, use L{scan} instead. @see: L{scan}, L{Process.get_filename} @rtype: bool @return: C{True} if all the pathnames were retrieved, C{False} if the debugger doesn't have permission to scan some processes. In either case, all processes the debugger has access to have a full pathname instead of just a filename. """ complete = True for aProcess in self.__processDict.values(): try: new_name = None old_name = aProcess.fileName try: aProcess.fileName = None new_name = aProcess.get_filename() finally: if not new_name: aProcess.fileName = old_name complete = False except Exception: complete = False return complete #------------------------------------------------------------------------------ def clear_dead_processes(self): """ Removes Process objects from the snapshot referring to processes no longer running. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_alive(): self._del_process(aProcess) def clear_unattached_processes(self): """ Removes Process objects from the snapshot referring to processes not being debugged. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_being_debugged(): self._del_process(aProcess) def close_process_handles(self): """ Closes all open handles to processes in this snapshot. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass def close_process_and_thread_handles(self): """ Closes all open handles to processes and threads in this snapshot. """ for aProcess in self.iter_processes(): aProcess.close_thread_handles() try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass def clear_processes(self): """ Removes all L{Process}, L{Thread} and L{Module} objects in this snapshot. """ #self.close_process_and_thread_handles() for aProcess in self.iter_processes(): aProcess.clear() self.__processDict = dict() def clear(self): """ Clears this snapshot. @see: L{clear_processes} """ self.clear_processes() #------------------------------------------------------------------------------ # Docs for these methods are taken from the _ThreadContainer class. def has_thread(self, dwThreadId): dwProcessId = self.get_pid_from_tid(dwThreadId) if dwProcessId is None: return False return self.has_process(dwProcessId) def get_thread(self, dwThreadId): dwProcessId = self.get_pid_from_tid(dwThreadId) if dwProcessId is None: msg = "Unknown thread ID %d" % dwThreadId raise KeyError(msg) return self.get_process(dwProcessId).get_thread(dwThreadId) def get_thread_ids(self): ids = list() for aProcess in self.iter_processes(): ids += aProcess.get_thread_ids() return ids def get_thread_count(self): count = 0 for aProcess in self.iter_processes(): count += aProcess.get_thread_count() return count has_thread.__doc__ = _ThreadContainer.has_thread.__doc__ get_thread.__doc__ = _ThreadContainer.get_thread.__doc__ get_thread_ids.__doc__ = _ThreadContainer.get_thread_ids.__doc__ get_thread_count.__doc__ = _ThreadContainer.get_thread_count.__doc__ #------------------------------------------------------------------------------ # Docs for these methods are taken from the _ModuleContainer class. def get_module_count(self): count = 0 for aProcess in self.iter_processes(): count += aProcess.get_module_count() return count get_module_count.__doc__ = _ModuleContainer.get_module_count.__doc__ #------------------------------------------------------------------------------ def find_modules_by_base(self, lpBaseOfDll): """ @rtype: list( L{Module}... ) @return: List of Module objects with the given base address. """ found = list() for aProcess in self.iter_processes(): if aProcess.has_module(lpBaseOfDll): aModule = aProcess.get_module(lpBaseOfDll) found.append( (aProcess, aModule) ) return found def find_modules_by_name(self, fileName): """ @rtype: list( L{Module}... ) @return: List of Module objects found. """ found = list() for aProcess in self.iter_processes(): aModule = aProcess.get_module_by_name(fileName) if aModule is not None: found.append( (aProcess, aModule) ) return found def find_modules_by_address(self, address): """ @rtype: list( L{Module}... ) @return: List of Module objects that best match the given address. """ found = list() for aProcess in self.iter_processes(): aModule = aProcess.get_module_at_address(address) if aModule is not None: found.append( (aProcess, aModule) ) return found def __find_processes_by_filename(self, filename): """ Internally used by L{find_processes_by_filename}. """ found = list() filename = filename.lower() if PathOperations.path_is_absolute(filename): for aProcess in self.iter_processes(): imagename = aProcess.get_filename() if imagename and imagename.lower() == filename: found.append( (aProcess, imagename) ) else: for aProcess in self.iter_processes(): imagename = aProcess.get_filename() if imagename: imagename = PathOperations.pathname_to_filename(imagename) if imagename.lower() == filename: found.append( (aProcess, imagename) ) return found def find_processes_by_filename(self, fileName): """ @type fileName: str @param fileName: Filename to search for. If it's a full pathname, the match must be exact. If it's a base filename only, the file part is matched, regardless of the directory where it's located. @note: If the process is not found and the file extension is not given, this method will search again assuming a default extension (.exe). @rtype: list of tuple( L{Process}, str ) @return: List of processes matching the given main module filename. Each tuple contains a Process object and it's filename. """ found = self.__find_processes_by_filename(fileName) if not found: fn, ext = PathOperations.split_extension(fileName) if not ext: fileName = '%s.exe' % fn found = self.__find_processes_by_filename(fileName) return found #------------------------------------------------------------------------------ # XXX _notify_* methods should not trigger a scan def _add_process(self, aProcess): """ Private method to add a process object to the snapshot. @type aProcess: L{Process} @param aProcess: Process object. """ ## if not isinstance(aProcess, Process): ## if hasattr(aProcess, '__class__'): ## typename = aProcess.__class__.__name__ ## else: ## typename = str(type(aProcess)) ## msg = "Expected Process, got %s instead" % typename ## raise TypeError(msg) dwProcessId = aProcess.dwProcessId ## if dwProcessId in self.__processDict: ## msg = "Process already exists: %d" % dwProcessId ## raise KeyError(msg) self.__processDict[dwProcessId] = aProcess def _del_process(self, dwProcessId): """ Private method to remove a process object from the snapshot. @type dwProcessId: int @param dwProcessId: Global process ID. """ try: aProcess = self.__processDict[dwProcessId] del self.__processDict[dwProcessId] except KeyError: aProcess = None msg = "Unknown process ID %d" % dwProcessId warnings.warn(msg, RuntimeWarning) if aProcess: aProcess.clear() # remove circular references # Notify the creation of a new process. def _notify_create_process(self, event): """ Notify the creation of a new process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ dwProcessId = event.get_pid() dwThreadId = event.get_tid() hProcess = event.get_process_handle() ## if not self.has_process(dwProcessId): # XXX this would trigger a scan if dwProcessId not in self.__processDict: aProcess = Process(dwProcessId, hProcess) self._add_process(aProcess) aProcess.fileName = event.get_filename() else: aProcess = self.get_process(dwProcessId) #if hProcess != win32.INVALID_HANDLE_VALUE: # aProcess.hProcess = hProcess # may have more privileges if not aProcess.fileName: fileName = event.get_filename() if fileName: aProcess.fileName = fileName return aProcess._notify_create_process(event) # pass it to the process def _notify_exit_process(self, event): """ Notify the termination of a process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ dwProcessId = event.get_pid() ## if self.has_process(dwProcessId): # XXX this would trigger a scan if dwProcessId in self.__processDict: self._del_process(dwProcessId) return True
183,635
Python
35.566308
101
0.561952
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/search.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Process memory finder # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Process memory search. @group Memory search: Search, Pattern, BytePattern, TextPattern, RegExpPattern, HexPattern """ __revision__ = "$Id$" __all__ = [ 'Search', 'Pattern', 'BytePattern', 'TextPattern', 'RegExpPattern', 'HexPattern', ] from winappdbg.textio import HexInput from winappdbg.util import StaticClass, MemoryAddresses from winappdbg import win32 import warnings try: # http://pypi.python.org/pypi/regex import regex as re except ImportError: import re #============================================================================== class Pattern (object): """ Base class for search patterns. The following L{Pattern} subclasses are provided by WinAppDbg: - L{BytePattern} - L{TextPattern} - L{RegExpPattern} - L{HexPattern} @see: L{Search.search_process} """ def __init__(self, pattern): """ Class constructor. The only mandatory argument should be the pattern string. This method B{MUST} be reimplemented by subclasses of L{Pattern}. """ raise NotImplementedError() def __len__(self): """ Returns the maximum expected length of the strings matched by this pattern. Exact behavior is implementation dependent. Ideally it should be an exact value, but in some cases it's not possible to calculate so an upper limit should be returned instead. If that's not possible either an exception must be raised. This value will be used to calculate the required buffer size when doing buffered searches. This method B{MUST} be reimplemented by subclasses of L{Pattern}. """ raise NotImplementedError() def read(self, process, address, size): """ Reads the requested number of bytes from the process memory at the given address. Subclasses of L{Pattern} tipically don't need to reimplement this method. """ return process.read(address, size) def find(self, buffer, pos = None): """ Searches for the pattern in the given buffer, optionally starting at the given position within the buffer. This method B{MUST} be reimplemented by subclasses of L{Pattern}. @type buffer: str @param buffer: Buffer to search on. @type pos: int @param pos: (Optional) Position within the buffer to start searching from. @rtype: tuple( int, int ) @return: Tuple containing the following: - Position within the buffer where a match is found, or C{-1} if no match was found. - Length of the matched data if a match is found, or undefined if no match was found. """ raise NotImplementedError() def found(self, address, size, data): """ This method gets called when a match is found. This allows subclasses of L{Pattern} to filter out unwanted results, or modify the results before giving them to the caller of L{Search.search_process}. If the return value is C{None} the result is skipped. Subclasses of L{Pattern} don't need to reimplement this method unless filtering is needed. @type address: int @param address: The memory address where the pattern was found. @type size: int @param size: The size of the data that matches the pattern. @type data: str @param data: The data that matches the pattern. @rtype: tuple( int, int, str ) @return: Tuple containing the following: * The memory address where the pattern was found. * The size of the data that matches the pattern. * The data that matches the pattern. """ return (address, size, data) #------------------------------------------------------------------------------ class BytePattern (Pattern): """ Fixed byte pattern. @type pattern: str @ivar pattern: Byte string to search for. @type length: int @ivar length: Length of the byte pattern. """ def __init__(self, pattern): """ @type pattern: str @param pattern: Byte string to search for. """ self.pattern = str(pattern) self.length = len(pattern) def __len__(self): """ Returns the exact length of the pattern. @see: L{Pattern.__len__} """ return self.length def find(self, buffer, pos = None): return buffer.find(self.pattern, pos), self.length #------------------------------------------------------------------------------ # FIXME: case insensitive compat.unicode searches are probably buggy! class TextPattern (BytePattern): """ Text pattern. @type isUnicode: bool @ivar isUnicode: C{True} if the text to search for is a compat.unicode string, C{False} otherwise. @type encoding: str @ivar encoding: Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @ivar caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. """ def __init__(self, text, encoding = "utf-16le", caseSensitive = False): """ @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. """ self.isUnicode = isinstance(text, compat.unicode) self.encoding = encoding self.caseSensitive = caseSensitive if not self.caseSensitive: pattern = text.lower() if self.isUnicode: pattern = text.encode(encoding) super(TextPattern, self).__init__(pattern) def read(self, process, address, size): data = super(TextPattern, self).read(address, size) if not self.caseSensitive: if self.isUnicode: try: encoding = self.encoding text = data.decode(encoding, "replace") text = text.lower() new_data = text.encode(encoding, "replace") if len(data) == len(new_data): data = new_data else: data = data.lower() except Exception: data = data.lower() else: data = data.lower() return data def found(self, address, size, data): if self.isUnicode: try: data = compat.unicode(data, self.encoding) except Exception: ## traceback.print_exc() # XXX DEBUG return None return (address, size, data) #------------------------------------------------------------------------------ class RegExpPattern (Pattern): """ Regular expression pattern. @type pattern: str @ivar pattern: Regular expression in text form. @type flags: int @ivar flags: Regular expression flags. @type regexp: re.compile @ivar regexp: Regular expression in compiled form. @type maxLength: int @ivar maxLength: Maximum expected length of the strings matched by this regular expression. This value will be used to calculate the required buffer size when doing buffered searches. Ideally it should be an exact value, but in some cases it's not possible to calculate so an upper limit should be given instead. If that's not possible either, C{None} should be used. That will cause an exception to be raised if this pattern is used in a buffered search. """ def __init__(self, regexp, flags = 0, maxLength = None): """ @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type maxLength: int @param maxLength: Maximum expected length of the strings matched by this regular expression. This value will be used to calculate the required buffer size when doing buffered searches. Ideally it should be an exact value, but in some cases it's not possible to calculate so an upper limit should be given instead. If that's not possible either, C{None} should be used. That will cause an exception to be raised if this pattern is used in a buffered search. """ self.pattern = regexp self.flags = flags self.regexp = re.compile(regexp, flags) self.maxLength = maxLength def __len__(self): """ Returns the maximum expected length of the strings matched by this pattern. This value is taken from the C{maxLength} argument of the constructor if this class. Ideally it should be an exact value, but in some cases it's not possible to calculate so an upper limit should be returned instead. If that's not possible either an exception must be raised. This value will be used to calculate the required buffer size when doing buffered searches. """ if self.maxLength is None: raise NotImplementedError() return self.maxLength def find(self, buffer, pos = None): if not pos: # make sure pos is an int pos = 0 match = self.regexp.search(buffer, pos) if match: start, end = match.span() return start, end - start return -1, 0 #------------------------------------------------------------------------------ class HexPattern (RegExpPattern): """ Hexadecimal pattern. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type pattern: str @ivar pattern: Hexadecimal pattern. """ def __new__(cls, pattern): """ If the pattern is completely static (no wildcards are present) a L{BytePattern} is created instead. That's because searching for a fixed byte pattern is faster than searching for a regular expression. """ if '?' not in pattern: return BytePattern( HexInput.hexadecimal(pattern) ) return object.__new__(cls, pattern) def __init__(self, hexa): """ Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. """ maxLength = len([x for x in hexa if x in "?0123456789ABCDEFabcdef"]) / 2 super(HexPattern, self).__init__(HexInput.pattern(hexa), maxLength = maxLength) #============================================================================== class Search (StaticClass): """ Static class to group the search functionality. Do not instance this class! Use its static methods instead. """ # TODO: aligned searches # TODO: method to coalesce search results # TODO: search memory dumps # TODO: search non-ascii C strings @staticmethod def search_process(process, pattern, minAddr = None, maxAddr = None, bufferPages = None, overlapping = False): """ Search for the given pattern within the process memory. @type process: L{Process} @param process: Process to search. @type pattern: L{Pattern} @param pattern: Pattern to search for. It must be an instance of a subclass of L{Pattern}. The following L{Pattern} subclasses are provided by WinAppDbg: - L{BytePattern} - L{TextPattern} - L{RegExpPattern} - L{HexPattern} You can also write your own subclass of L{Pattern} for customized searches. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @type overlapping: bool @param overlapping: C{True} to allow overlapping results, C{False} otherwise. Overlapping results yield the maximum possible number of results. For example, if searching for "AAAA" within "AAAAAAAA" at address C{0x10000}, when overlapping is turned off the following matches are yielded:: (0x10000, 4, "AAAA") (0x10004, 4, "AAAA") If overlapping is turned on, the following matches are yielded:: (0x10000, 4, "AAAA") (0x10001, 4, "AAAA") (0x10002, 4, "AAAA") (0x10003, 4, "AAAA") (0x10004, 4, "AAAA") As you can see, the middle results are overlapping the last two. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ # Do some namespace lookups of symbols we'll be using frequently. MEM_COMMIT = win32.MEM_COMMIT PAGE_GUARD = win32.PAGE_GUARD page = MemoryAddresses.pageSize read = pattern.read find = pattern.find # Calculate the address range. if minAddr is None: minAddr = 0 if maxAddr is None: maxAddr = win32.LPVOID(-1).value # XXX HACK # Calculate the buffer size from the number of pages. if bufferPages is None: try: size = MemoryAddresses.\ align_address_to_page_end(len(pattern)) + page except NotImplementedError: size = None elif bufferPages > 0: size = page * (bufferPages + 1) else: size = None # Get the memory map of the process. memory_map = process.iter_memory_map(minAddr, maxAddr) # Perform search with buffering enabled. if size: # Loop through all memory blocks containing data. buffer = "" # buffer to hold the memory data prev_addr = 0 # previous memory block address last = 0 # position of the last match delta = 0 # delta of last read address and start of buffer for mbi in memory_map: # Skip blocks with no data to search on. if not mbi.has_content(): continue # Get the address and size of this block. address = mbi.BaseAddress # current address to search on block_size = mbi.RegionSize # total size of the block if address >= maxAddr: break end = address + block_size # end address of the block # If the block is contiguous to the previous block, # coalesce the new data in the buffer. if delta and address == prev_addr: buffer += read(process, address, page) # If not, clear the buffer and read new data. else: buffer = read(process, address, min(size, block_size)) last = 0 delta = 0 # Search for the pattern in this block. while 1: # Yield each match of the pattern in the buffer. pos, length = find(buffer, last) while pos >= last: match_addr = address + pos - delta if minAddr <= match_addr < maxAddr: result = pattern.found( match_addr, length, buffer [ pos : pos + length ] ) if result is not None: yield result if overlapping: last = pos + 1 else: last = pos + length pos, length = find(buffer, last) # Advance to the next page. address = address + page block_size = block_size - page prev_addr = address # Fix the position of the last match. last = last - page if last < 0: last = 0 # Remove the first page in the buffer. buffer = buffer[ page : ] delta = page # If we haven't reached the end of the block yet, # read the next page in the block and keep seaching. if address < end: buffer = buffer + read(process, address, page) # Otherwise, we're done searching this block. else: break # Perform search with buffering disabled. else: # Loop through all memory blocks containing data. for mbi in memory_map: # Skip blocks with no data to search on. if not mbi.has_content(): continue # Get the address and size of this block. address = mbi.BaseAddress block_size = mbi.RegionSize if address >= maxAddr: break; # Read the whole memory region. buffer = process.read(address, block_size) # Search for the pattern in this region. pos, length = find(buffer) last = 0 while pos >= last: match_addr = address + pos if minAddr <= match_addr < maxAddr: result = pattern.found( match_addr, length, buffer [ pos : pos + length ] ) if result is not None: yield result if overlapping: last = pos + 1 else: last = pos + length pos, length = find(buffer, last) @classmethod def extract_ascii_strings(cls, process, minSize = 4, maxSize = 1024): """ Extract ASCII strings from the process memory. @type process: L{Process} @param process: Process to search. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to search for. @rtype: iterator of tuple(int, int, str) @return: Iterator of strings extracted from the process memory. Each tuple contains the following: - The memory address where the string was found. - The size of the string. - The string. """ regexp = r"[\s\w\!\@\#\$\%%\^\&\*\(\)\{\}\[\]\~\`\'\"\:\;\.\,\\\/\-\+\=\_\<\>]{%d,%d}\0" % (minSize, maxSize) pattern = RegExpPattern(regexp, 0, maxSize) return cls.search_process(process, pattern, overlapping = False)
23,798
Python
34.734234
117
0.555803
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/sql.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ SQL database storage support. @group Crash reporting: CrashDAO """ __revision__ = "$Id$" __all__ = ['CrashDAO'] import sqlite3 import datetime import warnings from sqlalchemy import create_engine, Column, ForeignKey, Sequence from sqlalchemy.engine.url import URL from sqlalchemy.ext.compiler import compiles from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.interfaces import PoolListener from sqlalchemy.orm import sessionmaker, deferred from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from sqlalchemy.types import Integer, BigInteger, Boolean, DateTime, String, \ LargeBinary, Enum, VARCHAR from sqlalchemy.sql.expression import asc, desc from crash import Crash, Marshaller, pickle, HIGHEST_PROTOCOL from textio import CrashDump import win32 #------------------------------------------------------------------------------ try: from decorator import decorator except ImportError: import functools def decorator(w): """ The C{decorator} module was not found. You can install it from: U{http://pypi.python.org/pypi/decorator/} """ def d(fn): @functools.wraps(fn) def x(*argv, **argd): return w(fn, *argv, **argd) return x return d #------------------------------------------------------------------------------ @compiles(String, 'mysql') @compiles(VARCHAR, 'mysql') 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) #------------------------------------------------------------------------------ class _SQLitePatch (PoolListener): """ Used internally by L{BaseDAO}. After connecting to an SQLite database, ensure that the foreign keys support is enabled. If not, abort the connection. @see: U{http://sqlite.org/foreignkeys.html} """ 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() #------------------------------------------------------------------------------ class BaseDTO (object): """ Customized declarative base for SQLAlchemy. """ __table_args__ = { # Don't use MyISAM in MySQL. It doesn't support ON DELETE CASCADE. 'mysql_engine': 'InnoDB', # Don't use BlitzDB in Drizzle. It doesn't support foreign keys. 'drizzle_engine': 'InnoDB', # Collate to UTF-8. 'mysql_charset': 'utf8', } BaseDTO = declarative_base(cls = BaseDTO) #------------------------------------------------------------------------------ # TODO: if using mssql, check it's at least SQL Server 2005 # (LIMIT and OFFSET support is required). # TODO: if using mysql, check it's at least MySQL 5.0.3 # (nested transactions are required). # TODO: maybe in mysql check the tables are not myisam? # TODO: maybe create the database if it doesn't exist? # TODO: maybe add a method to compact the database? # http://stackoverflow.com/questions/1875885 # http://www.sqlite.org/lang_vacuum.html # http://dev.mysql.com/doc/refman/5.1/en/optimize-table.html # http://msdn.microsoft.com/en-us/library/ms174459(v=sql.90).aspx class BaseDAO (object): """ Data Access Object base class. @type _url: sqlalchemy.url.URL @ivar _url: Database connection URL. @type _dialect: str @ivar _dialect: SQL dialect currently being used. @type _driver: str @ivar _driver: Name of the database driver currently being used. To get the actual Python module use L{_url}.get_driver() instead. @type _session: sqlalchemy.orm.Session @ivar _session: Database session object. @type _new_session: class @cvar _new_session: Custom configured Session class used to create the L{_session} instance variable. @type _echo: bool @cvar _echo: Set to C{True} to print all SQL queries to standard output. """ _echo = False _new_session = sessionmaker(autoflush = True, autocommit = True, expire_on_commit = True, weak_identity_map = True) def __init__(self, url, creator = None): """ Connect to the database using the given connection URL. The current implementation uses SQLAlchemy and so it will support whatever database said module supports. @type url: str @param url: URL that specifies the database to connect to. Some examples: - Opening an SQLite file: C{dao = CrashDAO("sqlite:///C:\\some\\path\\database.sqlite")} - Connecting to a locally installed SQL Express database: C{dao = CrashDAO("mssql://.\\SQLEXPRESS/Crashes?trusted_connection=yes")} - Connecting to a MySQL database running locally, using the C{oursql} library, authenticating as the "winappdbg" user with no password: C{dao = CrashDAO("mysql+oursql://winappdbg@localhost/Crashes")} - Connecting to a Postgres database running locally, authenticating with user and password: C{dao = CrashDAO("postgresql://winappdbg:winappdbg@localhost/Crashes")} For more information see the C{SQLAlchemy} documentation online: U{http://docs.sqlalchemy.org/en/latest/core/engines.html} Note that in all dialects except for SQLite the database must already exist. The tables schema, however, is created automatically when connecting for the first time. To create the database in MSSQL, you can use the U{SQLCMD<http://msdn.microsoft.com/en-us/library/ms180944.aspx>} command:: sqlcmd -Q "CREATE DATABASE Crashes" In MySQL you can use something like the following:: mysql -u root -e "CREATE DATABASE Crashes;" And in Postgres:: createdb Crashes -h localhost -U winappdbg -p winappdbg -O winappdbg Some small changes to the schema may be tolerated (for example, increasing the maximum length of string columns, or adding new columns with default values). Of course, it's best to test it first before making changes in a live database. This all depends very much on the SQLAlchemy version you're using, but it's best to use the latest version always. @type creator: callable @param creator: (Optional) Callback function that creates the SQL database connection. Normally it's not necessary to use this argument. However in some odd cases you may need to customize the database connection. """ # Parse the connection URL. parsed_url = URL(url) schema = parsed_url.drivername if '+' in schema: dialect, driver = schema.split('+') else: dialect, driver = schema, 'base' dialect = dialect.strip().lower() driver = driver.strip() # Prepare the database engine arguments. arguments = {'echo' : self._echo} if dialect == 'sqlite': arguments['module'] = sqlite3.dbapi2 arguments['listeners'] = [_SQLitePatch()] if creator is not None: arguments['creator'] = creator # Load the database engine. engine = create_engine(url, **arguments) # Create a new session. session = self._new_session(bind = engine) # Create the required tables if they don't exist. BaseDTO.metadata.create_all(engine) # TODO: create a dialect specific index on the "signature" column. # Set the instance properties. self._url = parsed_url self._driver = driver self._dialect = dialect self._session = session 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 #------------------------------------------------------------------------------ @decorator 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) #============================================================================== # Generates all possible memory access flags. def _gen_valid_access_flags(): f = [] for a1 in ("---", "R--", "RW-", "RC-", "--X", "R-X", "RWX", "RCX", "???"): for a2 in ("G", "-"): for a3 in ("N", "-"): for a4 in ("W", "-"): f.append("%s %s%s%s" % (a1, a2, a3, a4)) return tuple(f) _valid_access_flags = _gen_valid_access_flags() # Enumerated types for the memory table. n_MEM_ACCESS_ENUM = {"name" : "MEM_ACCESS_ENUM"} n_MEM_ALLOC_ACCESS_ENUM = {"name" : "MEM_ALLOC_ACCESS_ENUM"} MEM_ACCESS_ENUM = Enum(*_valid_access_flags, **n_MEM_ACCESS_ENUM) MEM_ALLOC_ACCESS_ENUM = Enum(*_valid_access_flags, **n_MEM_ALLOC_ACCESS_ENUM) MEM_STATE_ENUM = Enum("Reserved", "Commited", "Free", "Unknown", name = "MEM_STATE_ENUM") MEM_TYPE_ENUM = Enum("Image", "Mapped", "Private", "Unknown", name = "MEM_TYPE_ENUM") # Cleanup the namespace. del _gen_valid_access_flags del _valid_access_flags del n_MEM_ACCESS_ENUM del n_MEM_ALLOC_ACCESS_ENUM #------------------------------------------------------------------------------ class MemoryDTO (BaseDTO): """ Database mapping for memory dumps. """ # Declare the table mapping. __tablename__ = 'memory' id = Column(Integer, Sequence(__tablename__ + '_seq'), primary_key = True, autoincrement = True) crash_id = Column(Integer, ForeignKey('crashes.id', ondelete = 'CASCADE', onupdate = 'CASCADE'), nullable = False) address = Column(BigInteger, nullable = False, index = True) size = Column(BigInteger, nullable = False) state = Column(MEM_STATE_ENUM, nullable = False) access = Column(MEM_ACCESS_ENUM) type = Column(MEM_TYPE_ENUM) alloc_base = Column(BigInteger) alloc_access = Column(MEM_ALLOC_ACCESS_ENUM) filename = Column(String) content = deferred(Column(LargeBinary)) def __init__(self, crash_id, mbi): """ Process a L{win32.MemoryBasicInformation} object for database storage. """ # Crash ID. self.crash_id = crash_id # Address. self.address = mbi.BaseAddress # Size. self.size = mbi.RegionSize # State (free or allocated). if mbi.State == win32.MEM_RESERVE: self.state = "Reserved" elif mbi.State == win32.MEM_COMMIT: self.state = "Commited" elif mbi.State == win32.MEM_FREE: self.state = "Free" else: self.state = "Unknown" # Page protection bits (R/W/X/G). if mbi.State != win32.MEM_COMMIT: self.access = None else: self.access = self._to_access(mbi.Protect) # Type (file mapping, executable image, or private memory). if mbi.Type == win32.MEM_IMAGE: self.type = "Image" elif mbi.Type == win32.MEM_MAPPED: self.type = "Mapped" elif mbi.Type == win32.MEM_PRIVATE: self.type = "Private" elif mbi.Type == 0: self.type = None else: self.type = "Unknown" # Allocation info. self.alloc_base = mbi.AllocationBase if not mbi.AllocationProtect: self.alloc_access = None else: self.alloc_access = self._to_access(mbi.AllocationProtect) # Filename (for memory mappings). try: self.filename = mbi.filename except AttributeError: self.filename = None # Memory contents. try: self.content = mbi.content except AttributeError: self.content = None def _to_access(self, protect): if protect & win32.PAGE_NOACCESS: access = "--- " elif protect & win32.PAGE_READONLY: access = "R-- " elif protect & win32.PAGE_READWRITE: access = "RW- " elif protect & win32.PAGE_WRITECOPY: access = "RC- " elif protect & win32.PAGE_EXECUTE: access = "--X " elif protect & win32.PAGE_EXECUTE_READ: access = "R-X " elif protect & win32.PAGE_EXECUTE_READWRITE: access = "RWX " elif protect & win32.PAGE_EXECUTE_WRITECOPY: access = "RCX " else: access = "??? " if protect & win32.PAGE_GUARD: access += "G" else: access += "-" if protect & win32.PAGE_NOCACHE: access += "N" else: access += "-" if protect & win32.PAGE_WRITECOMBINE: access += "W" else: access += "-" return access def toMBI(self, getMemoryDump = False): """ Returns a L{win32.MemoryBasicInformation} object using the data retrieved from the database. @type getMemoryDump: bool @param getMemoryDump: (Optional) If C{True} retrieve the memory dump. Defaults to C{False} since this may be a costly operation. @rtype: L{win32.MemoryBasicInformation} @return: Memory block information. """ mbi = win32.MemoryBasicInformation() mbi.BaseAddress = self.address mbi.RegionSize = self.size mbi.State = self._parse_state(self.state) mbi.Protect = self._parse_access(self.access) mbi.Type = self._parse_type(self.type) if self.alloc_base is not None: mbi.AllocationBase = self.alloc_base else: mbi.AllocationBase = mbi.BaseAddress if self.alloc_access is not None: mbi.AllocationProtect = self._parse_access(self.alloc_access) else: mbi.AllocationProtect = mbi.Protect if self.filename is not None: mbi.filename = self.filename if getMemoryDump and self.content is not None: mbi.content = self.content return mbi @staticmethod def _parse_state(state): if state: if state == "Reserved": return win32.MEM_RESERVE if state == "Commited": return win32.MEM_COMMIT if state == "Free": return win32.MEM_FREE return 0 @staticmethod def _parse_type(type): if type: if type == "Image": return win32.MEM_IMAGE if type == "Mapped": return win32.MEM_MAPPED if type == "Private": return win32.MEM_PRIVATE return -1 return 0 @staticmethod def _parse_access(access): if not access: return 0 perm = access[:3] if perm == "R--": protect = win32.PAGE_READONLY elif perm == "RW-": protect = win32.PAGE_READWRITE elif perm == "RC-": protect = win32.PAGE_WRITECOPY elif perm == "--X": protect = win32.PAGE_EXECUTE elif perm == "R-X": protect = win32.PAGE_EXECUTE_READ elif perm == "RWX": protect = win32.PAGE_EXECUTE_READWRITE elif perm == "RCX": protect = win32.PAGE_EXECUTE_WRITECOPY else: protect = win32.PAGE_NOACCESS if access[5] == "G": protect = protect | win32.PAGE_GUARD if access[6] == "N": protect = protect | win32.PAGE_NOCACHE if access[7] == "W": protect = protect | win32.PAGE_WRITECOMBINE return protect #------------------------------------------------------------------------------ class CrashDTO (BaseDTO): """ Database mapping for crash dumps. """ # Table name. __tablename__ = "crashes" # Primary key. id = Column(Integer, Sequence(__tablename__ + '_seq'), primary_key = True, autoincrement = True) # Timestamp. timestamp = Column(DateTime, nullable = False, index = True) # Exploitability test. exploitable = Column(Integer, nullable = False) exploitability_rule = Column(String(32), nullable = False) exploitability_rating = Column(String(32), nullable = False) exploitability_desc = Column(String, nullable = False) # Platform description. os = Column(String(32), nullable = False) arch = Column(String(16), nullable = False) bits = Column(Integer, nullable = False) # Integer(4) is deprecated :( # Event description. event = Column(String, nullable = False) pid = Column(Integer, nullable = False) tid = Column(Integer, nullable = False) pc = Column(BigInteger, nullable = False) sp = Column(BigInteger, nullable = False) fp = Column(BigInteger, nullable = False) pc_label = Column(String, nullable = False) # Exception description. exception = Column(String(64)) exception_text = Column(String(64)) exception_address = Column(BigInteger) exception_label = Column(String) first_chance = Column(Boolean) fault_type = Column(Integer) fault_address = Column(BigInteger) fault_label = Column(String) fault_disasm = Column(String) stack_trace = Column(String) # Environment description. command_line = Column(String) environment = Column(String) # Debug strings. debug_string = Column(String) # Notes. notes = Column(String) # Heuristic signature. signature = Column(String, nullable = False) # Pickled Crash object, minus the memory dump. data = deferred(Column(LargeBinary, nullable = False)) def __init__(self, crash): """ @type crash: Crash @param crash: L{Crash} object to store into the database. """ # Timestamp and signature. self.timestamp = datetime.datetime.fromtimestamp( crash.timeStamp ) self.signature = pickle.dumps(crash.signature, protocol = 0) # Marshalled Crash object, minus the memory dump. # This code is *not* thread safe! memoryMap = crash.memoryMap try: crash.memoryMap = None self.data = buffer( Marshaller.dumps(crash) ) finally: crash.memoryMap = memoryMap # Exploitability test. self.exploitability_rating, \ self.exploitability_rule, \ self.exploitability_desc = crash.isExploitable() # Exploitability test as an integer result (for sorting). self.exploitable = [ "Not an exception", "Not exploitable", "Not likely exploitable", "Unknown", "Probably exploitable", "Exploitable", ].index(self.exploitability_rating) # Platform description. self.os = crash.os self.arch = crash.arch self.bits = crash.bits # Event description. self.event = crash.eventName self.pid = crash.pid self.tid = crash.tid self.pc = crash.pc self.sp = crash.sp self.fp = crash.fp self.pc_label = crash.labelPC # Exception description. self.exception = crash.exceptionName self.exception_text = crash.exceptionDescription self.exception_address = crash.exceptionAddress self.exception_label = crash.exceptionLabel self.first_chance = crash.firstChance self.fault_type = crash.faultType self.fault_address = crash.faultAddress self.fault_label = crash.faultLabel self.fault_disasm = CrashDump.dump_code( crash.faultDisasm, crash.pc ) self.stack_trace = CrashDump.dump_stack_trace_with_labels( crash.stackTracePretty ) # Command line. self.command_line = crash.commandLine # Environment. if crash.environment: envList = crash.environment.items() envList.sort() environment = '' for envKey, envVal in envList: # Must concatenate here instead of using a substitution, # so strings can be automatically promoted to Unicode. environment += envKey + '=' + envVal + '\n' if environment: self.environment = environment # Debug string. self.debug_string = crash.debugString # Notes. self.notes = crash.notesReport() def toCrash(self, getMemoryDump = False): """ Returns a L{Crash} object using the data retrieved from the database. @type getMemoryDump: bool @param getMemoryDump: If C{True} retrieve the memory dump. Defaults to C{False} since this may be a costly operation. @rtype: L{Crash} @return: Crash object. """ crash = Marshaller.loads(str(self.data)) if not isinstance(crash, Crash): raise TypeError( "Expected Crash instance, got %s instead" % type(crash)) crash._rowid = self.id if not crash.memoryMap: memory = getattr(self, "memory", []) if memory: crash.memoryMap = [dto.toMBI(getMemoryDump) for dto in memory] return crash #============================================================================== # TODO: add a method to modify already stored crash dumps. class CrashDAO (BaseDAO): """ Data Access Object to read, write and search for L{Crash} objects in a database. """ @Transactional 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 # Store the Crash object into the crashes table. def __add_crash(self, crash): session = self._session r_crash = None try: # Fill out a new row for the crashes table. r_crash = CrashDTO(crash) session.add(r_crash) # Flush and get the new row ID. session.flush() crash_id = r_crash.id finally: try: # Make the ORM forget the CrashDTO object. if r_crash is not None: session.expire(r_crash) finally: # Delete the last reference to the CrashDTO # object, so the Python garbage collector claims it. del r_crash # Return the row ID. return crash_id # Store the memory dump into the memory table. def __add_memory(self, crash_id, memoryMap): session = self._session if memoryMap: for mbi in memoryMap: r_mem = MemoryDTO(crash_id, mbi) session.add(r_mem) session.flush() @Transactional def find(self, signature = None, order = 0, since = None, until = None, offset = None, limit = None): """ Retrieve all crash dumps in the database, optionally filtering them by signature and timestamp, and/or sorting them by timestamp. Results can be paged to avoid consuming too much memory if the database is large. @see: L{find_by_example} @type signature: object @param signature: (Optional) Return only through crashes matching this signature. See L{Crash.signature} for more details. @type order: int @param order: (Optional) Sort by timestamp. If C{== 0}, results are not sorted. If C{> 0}, results are sorted from older to newer. If C{< 0}, results are sorted from newer to older. @type since: datetime @param since: (Optional) Return only the crashes after and including this date and time. @type until: datetime @param until: (Optional) Return only the crashes before this date and time, not including it. @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 Crash objects. """ # Validate the parameters. if since and until and since > until: warnings.warn("CrashDAO.find() got the 'since' and 'until'" " arguments reversed, corrected automatically.") since, until = until, since if limit is not None and not limit: warnings.warn("CrashDAO.find() was set a limit of 0 results," " returning without executing a query.") return [] # Build the SQL query. query = self._session.query(CrashDTO) if signature is not None: sig_pickled = pickle.dumps(signature, protocol = 0) query = query.filter(CrashDTO.signature == sig_pickled) if since: query = query.filter(CrashDTO.timestamp >= since) if until: query = query.filter(CrashDTO.timestamp < until) if order: if order > 0: query = query.order_by(asc(CrashDTO.timestamp)) else: query = query.order_by(desc(CrashDTO.timestamp)) else: # Default ordering is by row ID, to get consistent results. # Also some database engines require ordering when using offsets. query = query.order_by(asc(CrashDTO.id)) 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 [] @Transactional 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 [] @Transactional 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() @Transactional 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
34,997
Python
34.209255
88
0.57022
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/registry.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Registry access. @group Instrumentation: Registry, RegistryKey """ from __future__ import with_statement __revision__ = "$Id$" __all__ = ['Registry'] import sys from winappdbg import win32 from winappdbg import compat import collections import warnings #============================================================================== class _RegistryContainer (object): """ Base class for L{Registry} and L{RegistryKey}. """ # Dummy object to detect empty arguments. class __EmptyArgument: pass __emptyArgument = __EmptyArgument() def __init__(self): self.__default = None def has_key(self, name): return name in self def get(self, name, default=__emptyArgument): try: return self[name] except KeyError: if default is RegistryKey.__emptyArgument: return self.__default return default def setdefault(self, default): self.__default = default def __iter__(self): return compat.iterkeys(self) #============================================================================== class RegistryKey (_RegistryContainer): """ Exposes a single Windows Registry key as a dictionary-like object. @see: L{Registry} @type path: str @ivar path: Registry key path. @type handle: L{win32.RegistryKeyHandle} @ivar handle: Registry key handle. """ def __init__(self, path, handle): """ @type path: str @param path: Registry key path. @type handle: L{win32.RegistryKeyHandle} @param handle: Registry key handle. """ super(RegistryKey, self).__init__() if path.endswith('\\'): path = path[:-1] self._path = path self._handle = handle @property def path(self): return self._path @property def handle(self): #if not self._handle: # msg = "This Registry key handle has already been closed." # raise RuntimeError(msg) return self._handle #def close(self): # """ # Close the Registry key handle, freeing its resources. It cannot be # used again after calling this method. # # @note: This method will be called automatically by the garbage # collector, and upon exiting a "with" block. # # @raise RuntimeError: This Registry key handle has already been closed. # """ # self.handle.close() # #def __enter__(self): # """ # Compatibility with the "C{with}" Python statement. # """ # return self # #def __exit__(self, type, value, traceback): # """ # Compatibility with the "C{with}" Python statement. # """ # try: # self.close() # except Exception: # pass def __contains__(self, name): try: win32.RegQueryValueEx(self.handle, name, False) return True except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_FILE_NOT_FOUND: return False raise def __getitem__(self, name): try: return win32.RegQueryValueEx(self.handle, name)[0] except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_FILE_NOT_FOUND: raise KeyError(name) raise def __setitem__(self, name, value): win32.RegSetValueEx(self.handle, name, value) def __delitem__(self, name): win32.RegDeleteValue(self.handle, name) def iterkeys(self): handle = self.handle index = 0 while 1: resp = win32.RegEnumValue(handle, index, False) if resp is None: break yield resp[0] index += 1 def itervalues(self): handle = self.handle index = 0 while 1: resp = win32.RegEnumValue(handle, index) if resp is None: break yield resp[2] index += 1 def iteritems(self): handle = self.handle index = 0 while 1: resp = win32.RegEnumValue(handle, index) if resp is None: break yield resp[0], resp[2] index += 1 def keys(self): # return list(self.iterkeys()) # that can't be optimized by psyco handle = self.handle keys = list() index = 0 while 1: resp = win32.RegEnumValue(handle, index, False) if resp is None: break keys.append(resp[0]) index += 1 return keys def values(self): # return list(self.itervalues()) # that can't be optimized by psyco handle = self.handle values = list() index = 0 while 1: resp = win32.RegEnumValue(handle, index) if resp is None: break values.append(resp[2]) index += 1 return values def items(self): # return list(self.iteritems()) # that can't be optimized by psyco handle = self.handle items = list() index = 0 while 1: resp = win32.RegEnumValue(handle, index) if resp is None: break items.append( (resp[0], resp[2]) ) index += 1 return items def get_value_type(self, name): """ Retrieves the low-level data type for the given value. @type name: str @param name: Registry value name. @rtype: int @return: One of the following constants: - L{win32.REG_NONE} (0) - L{win32.REG_SZ} (1) - L{win32.REG_EXPAND_SZ} (2) - L{win32.REG_BINARY} (3) - L{win32.REG_DWORD} (4) - L{win32.REG_DWORD_BIG_ENDIAN} (5) - L{win32.REG_LINK} (6) - L{win32.REG_MULTI_SZ} (7) - L{win32.REG_RESOURCE_LIST} (8) - L{win32.REG_FULL_RESOURCE_DESCRIPTOR} (9) - L{win32.REG_RESOURCE_REQUIREMENTS_LIST} (10) - L{win32.REG_QWORD} (11) @raise KeyError: The specified value could not be found. """ try: return win32.RegQueryValueEx(self.handle, name)[1] except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_FILE_NOT_FOUND: raise KeyError(name) raise def clear(self): handle = self.handle while 1: resp = win32.RegEnumValue(handle, 0, False) if resp is None: break win32.RegDeleteValue(handle, resp[0]) def __str__(self): default = self[''] return str(default) def __unicode__(self): default = self[u''] return compat.unicode(default) def __repr__(self): return '<Registry key: "%s">' % self._path 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 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 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) def flush(self): """ Flushes changes immediately to disk. This method is normally not needed, as the Registry writes changes to disk by itself. This mechanism is provided to ensure the write happens immediately, as opposed to whenever the OS wants to. @warn: Calling this method too often may degrade performance. """ win32.RegFlushKey(self.handle) #============================================================================== # TODO: possibly cache the RegistryKey objects # to avoid opening and closing handles many times on code sequences like this: # # r = Registry() # r['HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Run']['Example 1'] = 'example1.exe' # r['HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Run']['Example 2'] = 'example2.exe' # r['HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Run']['Example 3'] = 'example3.exe' # TODO: support for access flags? # TODO: should be possible to disable the safety checks (see __delitem__) # TODO: workaround for an API bug described by a user in MSDN # # http://msdn.microsoft.com/en-us/library/windows/desktop/aa379776(v=vs.85).aspx # # Apparently RegDeleteTree won't work remotely from Win7 to WinXP, and the only # solution is to recursively call RegDeleteKey. class Registry (_RegistryContainer): """ Exposes the Windows Registry as a Python container. @type machine: str or None @ivar machine: For a remote Registry, the machine name. For a local Registry, the value is C{None}. """ _hives_by_name = { # Short names 'HKCR' : win32.HKEY_CLASSES_ROOT, 'HKCU' : win32.HKEY_CURRENT_USER, 'HKLM' : win32.HKEY_LOCAL_MACHINE, 'HKU' : win32.HKEY_USERS, 'HKPD' : win32.HKEY_PERFORMANCE_DATA, 'HKCC' : win32.HKEY_CURRENT_CONFIG, # Long names 'HKEY_CLASSES_ROOT' : win32.HKEY_CLASSES_ROOT, 'HKEY_CURRENT_USER' : win32.HKEY_CURRENT_USER, 'HKEY_LOCAL_MACHINE' : win32.HKEY_LOCAL_MACHINE, 'HKEY_USERS' : win32.HKEY_USERS, 'HKEY_PERFORMANCE_DATA' : win32.HKEY_PERFORMANCE_DATA, 'HKEY_CURRENT_CONFIG' : win32.HKEY_CURRENT_CONFIG, } _hives_by_value = { win32.HKEY_CLASSES_ROOT : 'HKEY_CLASSES_ROOT', win32.HKEY_CURRENT_USER : 'HKEY_CURRENT_USER', win32.HKEY_LOCAL_MACHINE : 'HKEY_LOCAL_MACHINE', win32.HKEY_USERS : 'HKEY_USERS', win32.HKEY_PERFORMANCE_DATA : 'HKEY_PERFORMANCE_DATA', win32.HKEY_CURRENT_CONFIG : 'HKEY_CURRENT_CONFIG', } _hives = sorted(compat.itervalues(_hives_by_value)) def __init__(self, machine = None): """ Opens a local or remote registry. @type machine: str @param machine: Optional machine name. If C{None} it opens the local registry. """ self._machine = machine self._remote_hives = {} @property def machine(self): return self._machine 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 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 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 def _sanitize_path(self, path): """ Sanitizes the given Registry path. @type path: str @param path: Registry path. @rtype: str @return: Registry path. """ return self._join_path( *self._split_path(path) ) 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 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 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def __repr__(self): if self._machine: return '<Remote Registry at "%s">' % self._machine return '<Local Registry>' def __contains__(self, path): hive, subpath = self._parse_path(path) try: with win32.RegOpenKey(hive, subpath): return True except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_FILE_NOT_FOUND: return False raise def __getitem__(self, path): path = self._sanitize_path(path) hive, subpath = self._parse_path(path) try: handle = win32.RegOpenKey(hive, subpath) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_FILE_NOT_FOUND: raise KeyError(path) raise return RegistryKey(path, handle) def __setitem__(self, path, value): do_copy = isinstance(value, RegistryKey) if not do_copy and not isinstance(value, str) \ and not isinstance(value, compat.unicode): if isinstance(value, object): t = value.__class__.__name__ else: t = type(value) raise TypeError("Expected string or RegistryKey, got %s" % t) hive, subpath = self._parse_path(path) with win32.RegCreateKey(hive, subpath) as handle: if do_copy: win32.RegCopyTree(value.handle, None, handle) else: win32.RegSetValueEx(handle, None, value) # XXX FIXME currently not working! # It's probably best to call RegDeleteKey recursively, even if slower. def __delitem__(self, path): hive, subpath = self._parse_path(path) if not subpath: raise TypeError( "Are you SURE you want to wipe out an entire hive?!" " Call win32.RegDeleteTree() directly if you must...") try: win32.RegDeleteTree(hive, subpath) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_FILE_NOT_FOUND: raise KeyError(path) raise def create(self, path): """ Creates a new Registry key. @type path: str @param path: Registry key path. @rtype: L{RegistryKey} @return: The newly created Registry key. """ path = self._sanitize_path(path) hive, subpath = self._parse_path(path) handle = win32.RegCreateKey(hive, subpath) return RegistryKey(path, handle) def subkeys(self, path): """ Returns a list of subkeys for the given Registry key. @type path: str @param path: Registry key path. @rtype: list(str) @return: List of subkey names. """ result = list() hive, subpath = self._parse_path(path) with win32.RegOpenKey(hive, subpath) as handle: index = 0 while 1: name = win32.RegEnumKey(handle, index) if name is None: break result.append(name) index += 1 return result def iterate(self, path): """ Returns a recursive iterator on the specified key and its subkeys. @type path: str @param path: Registry key path. @rtype: iterator @return: Recursive iterator that returns Registry key paths. @raise KeyError: The specified path does not exist. """ if path.endswith('\\'): path = path[:-1] if not self.has_key(path): raise KeyError(path) stack = collections.deque() stack.appendleft(path) return self.__iterate(stack) def iterkeys(self): """ Returns an iterator that crawls the entire Windows Registry. """ stack = collections.deque(self._hives) stack.reverse() return self.__iterate(stack) def __iterate(self, stack): while stack: path = stack.popleft() yield path try: subkeys = self.subkeys(path) except WindowsError: continue prefix = path + '\\' subkeys = [prefix + name for name in subkeys] stack.extendleft(subkeys)
21,569
Python
29.991379
95
0.557652
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/debug.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Debugging. @group Debugging: Debug @group Warnings: MixedBitsWarning """ __revision__ = "$Id$" __all__ = [ 'Debug', 'MixedBitsWarning' ] import sys from winappdbg import win32 from winappdbg.system import System from winappdbg.process import Process from winappdbg.thread import Thread from winappdbg.module import Module from winappdbg.window import Window from winappdbg.breakpoint import _BreakpointContainer, CodeBreakpoint from winappdbg.event import Event, EventHandler, EventDispatcher, EventFactory from winappdbg.interactive import ConsoleDebugger import warnings ##import traceback #============================================================================== # If you set this warning to be considered as an error, you can stop the # debugger from attaching to 64-bit processes from a 32-bit Python VM and # visceversa. class MixedBitsWarning (RuntimeWarning): """ This warning is issued when mixing 32 and 64 bit processes. """ #============================================================================== # TODO # * Add memory read and write operations, similar to those in the Process # class, but hiding the presence of the code breakpoints. # * Add a method to get the memory map of a process, but hiding the presence # of the page breakpoints. # * Maybe the previous two features should be implemented at the Process class # instead, but how to communicate with the Debug object without creating # circular references? Perhaps the "overrides" could be set using private # members (so users won't see them), but then there's the problem of the # users being able to access the snapshot (i.e. clear it), which is why it's # not such a great idea to use the snapshot to store data that really belongs # to the Debug class. class Debug (EventDispatcher, _BreakpointContainer): """ The main debugger class. @group Debugging: interactive, attach, detach, detach_from_all, execv, execl, kill, kill_all, get_debugee_count, get_debugee_pids, is_debugee, is_debugee_attached, is_debugee_started, in_hostile_mode, add_existing_session @group Debugging loop: loop, stop, next, wait, dispatch, cont @undocumented: force_garbage_collection @type system: L{System} @ivar system: A System snapshot that is automatically updated for processes being debugged. Processes not being debugged in this snapshot may be outdated. """ # Automatically set to True the first time a Debug object is instanced. _debug_static_init = False def __init__(self, eventHandler = None, bKillOnExit = False, bHostileCode = False): """ Debugger object. @type eventHandler: L{EventHandler} @param eventHandler: (Optional, recommended) Custom event handler object. @type bKillOnExit: bool @param bKillOnExit: (Optional) Kill on exit mode. If C{True} debugged processes are killed when the debugger is stopped. If C{False} when the debugger stops it detaches from all debugged processes and leaves them running (default). @type bHostileCode: bool @param bHostileCode: (Optional) Hostile code mode. Set to C{True} to take some basic precautions against anti-debug tricks. Disabled by default. @warn: When hostile mode is enabled, some things may not work as expected! This is because the anti-anti debug tricks may disrupt the behavior of the Win32 debugging APIs or WinAppDbg itself. @note: The L{eventHandler} parameter may be any callable Python object (for example a function, or an instance method). However you'll probably find it more convenient to use an instance of a subclass of L{EventHandler} here. @raise WindowsError: Raises an exception on error. """ EventDispatcher.__init__(self, eventHandler) _BreakpointContainer.__init__(self) self.system = System() self.lastEvent = None self.__firstDebugee = True self.__bKillOnExit = bKillOnExit self.__bHostileCode = bHostileCode self.__breakOnEP = set() # set of pids self.__attachedDebugees = set() # set of pids self.__startedDebugees = set() # set of pids if not self._debug_static_init: self._debug_static_init = True # Request debug privileges for the current process. # Only do this once, and only after instancing a Debug object, # so passive debuggers don't get detected because of this. self.system.request_debug_privileges(bIgnoreExceptions = False) # Try to fix the symbol store path if it wasn't set. # But don't enable symbol downloading by default, since it may # degrade performance severely. self.system.fix_symbol_store_path(remote = False, force = False) ## # It's hard not to create circular references, ## # and if we have a destructor, we can end up leaking everything. ## # It's best to code the debugging loop properly to always ## # stop the debugger before going out of scope. ## def __del__(self): ## self.stop() def __enter__(self): """ Compatibility with the "C{with}" Python statement. """ return self def __exit__(self, type, value, traceback): """ Compatibility with the "C{with}" Python statement. """ self.stop() def __len__(self): """ @rtype: int @return: Number of processes being debugged. """ return self.get_debugee_count() # TODO: maybe custom __bool__ to break out of loop() ? # it already does work (because of __len__) but it'd be # useful to do it from the event handler anyway #------------------------------------------------------------------------------ def __setSystemKillOnExitMode(self): # Make sure the default system behavior on detaching from processes # versus killing them matches our preferences. This only affects the # scenario where the Python VM dies unexpectedly without running all # the finally clauses, or the user failed to either instance the Debug # object inside a with block or call the stop() method before quitting. if self.__firstDebugee: try: System.set_kill_on_exit_mode(self.__bKillOnExit) self.__firstDebugee = False except Exception: pass 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 def execv(self, argv, **kwargs): """ Starts a new process for debugging. This method uses a list of arguments. To use a command line string instead, use L{execl}. @see: L{attach}, L{detach} @type argv: list( str... ) @param argv: List of command line arguments to pass to the debugee. The first element must be the debugee executable filename. @type bBreakOnEntryPoint: bool @keyword bBreakOnEntryPoint: C{True} to automatically set a breakpoint at the program entry point. @type bConsole: bool @keyword bConsole: True to inherit the console of the debugger. Defaults to C{False}. @type bFollow: bool @keyword bFollow: C{True} to automatically attach to child processes. Defaults to C{False}. @type bInheritHandles: bool @keyword bInheritHandles: C{True} if the new process should inherit it's parent process' handles. Defaults to C{False}. @type bSuspended: bool @keyword bSuspended: C{True} to suspend the main thread before any code is executed in the debugee. Defaults to C{False}. @keyword dwParentProcessId: C{None} or C{0} if the debugger process should be the parent process (default), or a process ID to forcefully set as the debugee's parent (only available for Windows Vista and above). In hostile mode, the default is not the debugger process but the process ID for "explorer.exe". @type iTrustLevel: int or None @keyword iTrustLevel: Trust level. Must be one of the following values: - 0: B{No trust}. May not access certain resources, such as cryptographic keys and credentials. Only available since Windows XP and 2003, desktop editions. This is the default in hostile mode. - 1: B{Normal trust}. Run with the same privileges as a normal user, that is, one that doesn't have the I{Administrator} or I{Power User} user rights. Only available since Windows XP and 2003, desktop editions. - 2: B{Full trust}. Run with the exact same privileges as the current user. This is the default in normal mode. @type bAllowElevation: bool @keyword bAllowElevation: C{True} to allow the child process to keep UAC elevation, if the debugger itself is running elevated. C{False} to ensure the child process doesn't run with elevation. Defaults to C{True}. This flag is only meaningful on Windows Vista and above, and if the debugger itself is running with elevation. It can be used to make sure the child processes don't run elevated as well. This flag DOES NOT force an elevation prompt when the debugger is not running with elevation. Note that running the debugger with elevation (or the Python interpreter at all for that matter) is not normally required. You should only need to if the target program requires elevation to work properly (for example if you try to debug an installer). @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. """ if type(argv) in (str, compat.unicode): raise TypeError("Debug.execv expects a list, not a string") lpCmdLine = self.system.argv_to_cmdline(argv) return self.execl(lpCmdLine, **kwargs) def execl(self, lpCmdLine, **kwargs): """ Starts a new process for debugging. This method uses a command line string. To use a list of arguments instead, use L{execv}. @see: L{attach}, L{detach} @type lpCmdLine: str @param lpCmdLine: Command line string to execute. The first token must be the debugee executable filename. Tokens with spaces must be enclosed in double quotes. Tokens including double quote characters must be escaped with a backslash. @type bBreakOnEntryPoint: bool @keyword bBreakOnEntryPoint: C{True} to automatically set a breakpoint at the program entry point. Defaults to C{False}. @type bConsole: bool @keyword bConsole: True to inherit the console of the debugger. Defaults to C{False}. @type bFollow: bool @keyword bFollow: C{True} to automatically attach to child processes. Defaults to C{False}. @type bInheritHandles: bool @keyword bInheritHandles: C{True} if the new process should inherit it's parent process' handles. Defaults to C{False}. @type bSuspended: bool @keyword bSuspended: C{True} to suspend the main thread before any code is executed in the debugee. Defaults to C{False}. @type dwParentProcessId: int or None @keyword dwParentProcessId: C{None} or C{0} if the debugger process should be the parent process (default), or a process ID to forcefully set as the debugee's parent (only available for Windows Vista and above). In hostile mode, the default is not the debugger process but the process ID for "explorer.exe". @type iTrustLevel: int @keyword iTrustLevel: Trust level. Must be one of the following values: - 0: B{No trust}. May not access certain resources, such as cryptographic keys and credentials. Only available since Windows XP and 2003, desktop editions. This is the default in hostile mode. - 1: B{Normal trust}. Run with the same privileges as a normal user, that is, one that doesn't have the I{Administrator} or I{Power User} user rights. Only available since Windows XP and 2003, desktop editions. - 2: B{Full trust}. Run with the exact same privileges as the current user. This is the default in normal mode. @type bAllowElevation: bool @keyword bAllowElevation: C{True} to allow the child process to keep UAC elevation, if the debugger itself is running elevated. C{False} to ensure the child process doesn't run with elevation. Defaults to C{True} in normal mode and C{False} in hostile mode. This flag is only meaningful on Windows Vista and above, and if the debugger itself is running with elevation. It can be used to make sure the child processes don't run elevated as well. This flag DOES NOT force an elevation prompt when the debugger is not running with elevation. Note that running the debugger with elevation (or the Python interpreter at all for that matter) is not normally required. You should only need to if the target program requires elevation to work properly (for example if you try to debug an installer). @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. """ if type(lpCmdLine) not in (str, compat.unicode): warnings.warn("Debug.execl expects a string") # Set the "debug" flag to True. kwargs['bDebug'] = True # Pop the "break on entry point" flag. bBreakOnEntryPoint = kwargs.pop('bBreakOnEntryPoint', False) # Set the default trust level if requested. if 'iTrustLevel' not in kwargs: if self.__bHostileCode: kwargs['iTrustLevel'] = 0 else: kwargs['iTrustLevel'] = 2 # Set the default UAC elevation flag if requested. if 'bAllowElevation' not in kwargs: kwargs['bAllowElevation'] = not self.__bHostileCode # In hostile mode the default parent process is explorer.exe. # Only supported for Windows Vista and above. if self.__bHostileCode and not kwargs.get('dwParentProcessId', None): try: vista_and_above = self.__vista_and_above except AttributeError: osi = win32.OSVERSIONINFOEXW() osi.dwMajorVersion = 6 osi.dwMinorVersion = 0 osi.dwPlatformId = win32.VER_PLATFORM_WIN32_NT mask = 0 mask = win32.VerSetConditionMask(mask, win32.VER_MAJORVERSION, win32.VER_GREATER_EQUAL) mask = win32.VerSetConditionMask(mask, win32.VER_MAJORVERSION, win32.VER_GREATER_EQUAL) mask = win32.VerSetConditionMask(mask, win32.VER_PLATFORMID, win32.VER_EQUAL) vista_and_above = win32.VerifyVersionInfoW(osi, win32.VER_MAJORVERSION | \ win32.VER_MINORVERSION | \ win32.VER_PLATFORMID, mask) self.__vista_and_above = vista_and_above if vista_and_above: dwParentProcessId = self.system.get_explorer_pid() if dwParentProcessId: kwargs['dwParentProcessId'] = dwParentProcessId else: msg = ("Failed to find \"explorer.exe\"!" " Using the debugger as parent process.") warnings.warn(msg, RuntimeWarning) # Start the new process. aProcess = None try: aProcess = self.system.start_process(lpCmdLine, **kwargs) dwProcessId = aProcess.get_pid() # Match the system kill-on-exit flag to our own. self.__setSystemKillOnExitMode() # 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) # Add the new PID to the set of debugees. self.__startedDebugees.add(dwProcessId) # Add the new PID to the set of "break on EP" debugees if needed. if bBreakOnEntryPoint: self.__breakOnEP.add(dwProcessId) # Return the Process object. return aProcess # On error kill the new process and raise an exception. except: if aProcess is not None: try: try: self.__startedDebugees.remove(aProcess.get_pid()) except KeyError: pass finally: try: try: self.__breakOnEP.remove(aProcess.get_pid()) except KeyError: pass finally: try: aProcess.kill() except Exception: pass raise def add_existing_session(self, dwProcessId, bStarted = False): """ Use this method only when for some reason the debugger's been attached to the target outside of WinAppDbg (for example when integrating with other tools). You don't normally need to call this method. Most users should call L{attach}, L{execv} or L{execl} instead. @type dwProcessId: int @param dwProcessId: Global process ID. @type bStarted: bool @param bStarted: C{True} if the process was started by the debugger, or C{False} if the process was attached to instead. @raise WindowsError: The target process does not exist, is not attached to the debugger anymore. """ # Register the process object with the snapshot. if not self.system.has_process(dwProcessId): aProcess = Process(dwProcessId) self.system._add_process(aProcess) else: aProcess = self.system.get_process(dwProcessId) # Test for debug privileges on the target process. # Raises WindowsException on error. aProcess.get_handle() # Register the process ID with the debugger. if bStarted: self.__attachedDebugees.add(dwProcessId) else: self.__startedDebugees.add(dwProcessId) # Match the system kill-on-exit flag to our own. self.__setSystemKillOnExitMode() # 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() 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) 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) 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) 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() 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) #------------------------------------------------------------------------------ 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 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) 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 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) 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() def loop(self): """ Simple debugging loop. This debugging loop is meant to be useful for most simple scripts. It iterates as long as there is at least one debugee, or an exception is raised. Multiple calls are allowed. This is a trivial example script:: import sys debug = Debug() try: debug.execv( sys.argv [ 1 : ] ) debug.loop() finally: debug.stop() @see: L{next}, L{stop} U{http://msdn.microsoft.com/en-us/library/ms681675(VS.85).aspx} @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. """ while self: self.next() def get_debugee_count(self): """ @rtype: int @return: Number of processes being debugged. """ return len(self.__attachedDebugees) + len(self.__startedDebugees) def get_debugee_pids(self): """ @rtype: list( int... ) @return: Global IDs of processes being debugged. """ return list(self.__attachedDebugees) + list(self.__startedDebugees) def is_debugee(self, dwProcessId): """ Determine if the debugger is debugging the given process. @see: L{is_debugee_attached}, L{is_debugee_started} @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: bool @return: C{True} if the given process is being debugged by this L{Debug} instance. """ return self.is_debugee_attached(dwProcessId) or \ self.is_debugee_started(dwProcessId) def is_debugee_started(self, dwProcessId): """ Determine if the given process was started by the debugger. @see: L{is_debugee}, L{is_debugee_attached} @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: bool @return: C{True} if the given process was started for debugging by this L{Debug} instance. """ return dwProcessId in self.__startedDebugees def is_debugee_attached(self, dwProcessId): """ Determine if the debugger is attached to the given process. @see: L{is_debugee}, L{is_debugee_started} @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: bool @return: C{True} if the given process is attached to this L{Debug} instance. """ return dwProcessId in self.__attachedDebugees def in_hostile_mode(self): """ Determine if we're in hostile mode (anti-anti-debug). @rtype: bool @return: C{True} if this C{Debug} instance was started in hostile mode, C{False} otherwise. """ return self.__bHostileCode #------------------------------------------------------------------------------ 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('') #------------------------------------------------------------------------------ @staticmethod 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) #------------------------------------------------------------------------------ def _notify_create_process(self, event): """ Notify the creation of a new process. @warning: This method is meant to be used internally by the debugger. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ dwProcessId = event.get_pid() if dwProcessId not in self.__attachedDebugees: if dwProcessId not in self.__startedDebugees: self.__startedDebugees.add(dwProcessId) retval = self.system._notify_create_process(event) # Set a breakpoint on the program's entry point if requested. # Try not to use the Event object's entry point value, as in some cases # it may be wrong. See: http://pferrie.host22.com/misc/lowlevel3.htm if dwProcessId in self.__breakOnEP: try: lpEntryPoint = event.get_process().get_entry_point() except Exception: lpEntryPoint = event.get_start_address() # It'd be best to use a hardware breakpoint instead, at least in # hostile mode. But since the main thread's context gets smashed # by the loader, I haven't found a way to make it work yet. self.break_at(dwProcessId, lpEntryPoint) # Defeat isDebuggerPresent by patching PEB->BeingDebugged. # When we do this, some debugging APIs cease to work as expected. # For example, the system breakpoint isn't hit when we attach. # For that reason we need to define a code breakpoint at the # code location where a new thread is spawned by the debugging # APIs, ntdll!DbgUiRemoteBreakin. if self.__bHostileCode: aProcess = event.get_process() try: hProcess = aProcess.get_handle(win32.PROCESS_QUERY_INFORMATION) pbi = win32.NtQueryInformationProcess( hProcess, win32.ProcessBasicInformation) ptr = pbi.PebBaseAddress + 2 if aProcess.peek(ptr, 1) == '\x01': aProcess.poke(ptr, '\x00') except WindowsError: e = sys.exc_info()[1] warnings.warn( "Cannot patch PEB->BeingDebugged, reason: %s" % e.strerror) return retval def _notify_create_thread(self, event): """ Notify the creation of a new thread. @warning: This method is meant to be used internally by the debugger. @type event: L{CreateThreadEvent} @param event: Create thread event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ return event.get_process()._notify_create_thread(event) 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 def _notify_exit_process(self, event): """ Notify the termination of a process. @warning: This method is meant to be used internally by the debugger. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ bCallHandler1 = _BreakpointContainer._notify_exit_process(self, event) bCallHandler2 = self.system._notify_exit_process(event) try: self.detach( event.get_pid() ) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_INVALID_PARAMETER: warnings.warn( "Failed to detach from dead process, reason: %s" % str(e), RuntimeWarning) except Exception: e = sys.exc_info()[1] warnings.warn( "Failed to detach from dead process, reason: %s" % str(e), RuntimeWarning) return bCallHandler1 and bCallHandler2 def _notify_exit_thread(self, event): """ Notify the termination of a thread. @warning: This method is meant to be used internally by the debugger. @type event: L{ExitThreadEvent} @param event: Exit thread event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ bCallHandler1 = _BreakpointContainer._notify_exit_thread(self, event) bCallHandler2 = event.get_process()._notify_exit_thread(event) return bCallHandler1 and bCallHandler2 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 def _notify_rip(self, event): """ Notify of a RIP event. @warning: This method is meant to be used internally by the debugger. @type event: L{RIPEvent} @param event: RIP event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ event.debug.detach( event.get_pid() ) return True 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 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
58,709
Python
37.024611
93
0.580337
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/__init__.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Windows application debugging engine for Python. by Mario Vilas (mvilas at gmail.com) Project: U{http://sourceforge.net/projects/winappdbg/} Web: U{http://winappdbg.sourceforge.net/} Blog: U{http://breakingcode.wordpress.com} @group Debugging: Debug, EventHandler, EventSift, DebugLog @group Instrumentation: System, Process, Thread, Module, Window, Registry @group Disassemblers: Disassembler, BeaEngine, DistormEngine, PyDasmEngine @group Crash reporting: Crash, CrashDump, CrashDAO, CrashDictionary @group Memory search: Search, Pattern, BytePattern, TextPattern, RegExpPattern, HexPattern @group Debug events: Event, NoEvent, CreateProcessEvent, CreateThreadEvent, ExitProcessEvent, ExitThreadEvent, LoadDLLEvent, UnloadDLLEvent, OutputDebugStringEvent, RIPEvent, ExceptionEvent @group Win32 API wrappers: win32, Handle, ProcessHandle, ThreadHandle, FileHandle @group Helpers: HexInput, HexOutput, HexDump, Color, Table, Logger, PathOperations, MemoryAddresses, CustomAddressIterator, DataAddressIterator, ImageAddressIterator, MappedAddressIterator, ExecutableAddressIterator, ReadableAddressIterator, WriteableAddressIterator, ExecutableAndWriteableAddressIterator, DebugRegister, Regenerator @group Warnings: MixedBitsWarning, BreakpointWarning, BreakpointCallbackWarning, EventCallbackWarning, DebugSymbolsWarning, CrashWarning @group Deprecated classes: CrashContainer, CrashTable, CrashTableMSSQL, VolatileCrashContainer, DummyCrashContainer @type version_number: float @var version_number: This WinAppDbg major and minor version, as a floating point number. Use this for compatibility checking. @type version: str @var version: This WinAppDbg release version, as a printable string. Use this to show to the user. @undocumented: plugins """ __revision__ = "$Id$" # List of all public symbols __all__ = [ # Library version 'version', 'version_number', # from breakpoint import * ## 'Breakpoint', ## 'CodeBreakpoint', ## 'PageBreakpoint', ## 'HardwareBreakpoint', ## 'Hook', ## 'ApiHook', ## 'BufferWatch', 'BreakpointWarning', 'BreakpointCallbackWarning', # from crash import * 'Crash', 'CrashWarning', 'CrashDictionary', 'CrashContainer', 'CrashTable', 'CrashTableMSSQL', 'VolatileCrashContainer', 'DummyCrashContainer', # from debug import * 'Debug', 'MixedBitsWarning', # from disasm import * 'Disassembler', 'BeaEngine', 'DistormEngine', 'PyDasmEngine', # from event import * 'EventHandler', 'EventSift', ## 'EventFactory', ## 'EventDispatcher', 'EventCallbackWarning', 'Event', ## 'NoEvent', 'CreateProcessEvent', 'CreateThreadEvent', 'ExitProcessEvent', 'ExitThreadEvent', 'LoadDLLEvent', 'UnloadDLLEvent', 'OutputDebugStringEvent', 'RIPEvent', 'ExceptionEvent', # from interactive import * ## 'ConsoleDebugger', # from module import * 'Module', 'DebugSymbolsWarning', # from process import * 'Process', # from system import * 'System', # from search import * 'Search', 'Pattern', 'BytePattern', 'TextPattern', 'RegExpPattern', 'HexPattern', # from registry import * 'Registry', # from textio import * 'HexDump', 'HexInput', 'HexOutput', 'Color', 'Table', 'CrashDump', 'DebugLog', 'Logger', # from thread import * 'Thread', # from util import * 'PathOperations', 'MemoryAddresses', 'CustomAddressIterator', 'DataAddressIterator', 'ImageAddressIterator', 'MappedAddressIterator', 'ExecutableAddressIterator', 'ReadableAddressIterator', 'WriteableAddressIterator', 'ExecutableAndWriteableAddressIterator', 'DebugRegister', # from window import * 'Window', # import win32 'win32', # from win32 import Handle, ProcessHandle, ThreadHandle, FileHandle 'Handle', 'ProcessHandle', 'ThreadHandle', 'FileHandle', ] # Import all public symbols from winappdbg.breakpoint import * from winappdbg.crash import * from winappdbg.debug import * from winappdbg.disasm import * from winappdbg.event import * from winappdbg.interactive import * from winappdbg.module import * from winappdbg.process import * from winappdbg.registry import * from winappdbg.system import * from winappdbg.search import * from winappdbg.textio import * from winappdbg.thread import * from winappdbg.util import * from winappdbg.window import * import winappdbg.win32 from winappdbg.win32 import Handle, ProcessHandle, ThreadHandle, FileHandle try: from sql import * __all__.append('CrashDAO') except ImportError: import warnings warnings.warn("No SQL database support present (missing dependencies?)", ImportWarning) # Library version version_number = 1.5 version = "Version %s" % version_number
7,917
Python
28.992424
83
0.600733
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Thread instrumentation. @group Instrumentation: Thread """ from __future__ import with_statement __revision__ = "$Id$" __all__ = ['Thread'] from winappdbg import win32 from winappdbg import compat from winappdbg.textio import HexDump from winappdbg.util import DebugRegister from winappdbg.window import Window import sys import struct import warnings # delayed imports Process = None #============================================================================== # TODO # + fetch special registers (MMX, XMM, 3DNow!, etc) class Thread (object): """ Interface to a thread in another process. @group Properties: get_tid, get_pid, get_process, set_process, get_exit_code, is_alive, get_name, set_name, get_windows, get_teb, get_teb_address, is_wow64, get_arch, get_bits, get_handle, open_handle, close_handle @group Instrumentation: suspend, resume, kill, wait @group Debugging: get_seh_chain_pointer, set_seh_chain_pointer, get_seh_chain, get_wait_chain, is_hidden @group Disassembly: disassemble, disassemble_around, disassemble_around_pc, disassemble_string, disassemble_instruction, disassemble_current @group Stack: get_stack_frame, get_stack_frame_range, get_stack_range, get_stack_trace, get_stack_trace_with_labels, read_stack_data, read_stack_dwords, read_stack_qwords, peek_stack_data, peek_stack_dwords, peek_stack_qwords, read_stack_structure, read_stack_frame @group Registers: get_context, get_register, get_flags, get_flag_value, get_pc, get_sp, get_fp, get_cf, get_df, get_sf, get_tf, get_zf, set_context, set_register, set_flags, set_flag_value, set_pc, set_sp, set_fp, set_cf, set_df, set_sf, set_tf, set_zf, clear_cf, clear_df, clear_sf, clear_tf, clear_zf, Flags @group Threads snapshot: clear @group Miscellaneous: read_code_bytes, peek_code_bytes, peek_pointers_in_data, peek_pointers_in_registers, get_linear_address, get_label_at_pc @type dwThreadId: int @ivar dwThreadId: Global thread ID. Use L{get_tid} instead. @type hThread: L{ThreadHandle} @ivar hThread: Handle to the thread. Use L{get_handle} instead. @type process: L{Process} @ivar process: Parent process object. Use L{get_process} instead. @type pInjectedMemory: int @ivar pInjectedMemory: If the thread was created by L{Process.inject_code}, this member contains a pointer to the memory buffer for the injected code. Otherwise it's C{None}. The L{kill} method uses this member to free the buffer when the injected thread is killed. """ def __init__(self, dwThreadId, hThread = None, process = None): """ @type dwThreadId: int @param dwThreadId: Global thread ID. @type hThread: L{ThreadHandle} @param hThread: (Optional) Handle to the thread. @type process: L{Process} @param process: (Optional) Parent Process object. """ self.dwProcessId = None self.dwThreadId = dwThreadId self.hThread = hThread self.pInjectedMemory = None self.set_name(None) self.set_process(process) # Not really sure if it's a good idea... ## def __eq__(self, aThread): ## """ ## Compare two Thread objects. The comparison is made using the IDs. ## ## @warning: ## If you have two Thread instances with different handles the ## equality operator still returns C{True}, so be careful! ## ## @type aThread: L{Thread} ## @param aThread: Another Thread object. ## ## @rtype: bool ## @return: C{True} if the two thread IDs are equal, ## C{False} otherwise. ## """ ## return isinstance(aThread, Thread) and \ ## self.get_tid() == aThread.get_tid() def __load_Process_class(self): global Process # delayed import if Process is None: from winappdbg.process import Process def get_process(self): """ @rtype: L{Process} @return: Parent Process object. Returns C{None} if unknown. """ if self.__process is not None: return self.__process self.__load_Process_class() self.__process = Process(self.get_pid()) return self.__process def set_process(self, process = None): """ Manually set the parent Process object. Use with care! @type process: L{Process} @param process: (Optional) Process object. Use C{None} for no process. """ if process is None: self.dwProcessId = None self.__process = None else: self.__load_Process_class() if not isinstance(process, Process): msg = "Parent process must be a Process instance, " msg += "got %s instead" % type(process) raise TypeError(msg) self.dwProcessId = process.get_pid() self.__process = process process = property(get_process, set_process, doc="") def get_pid(self): """ @rtype: int @return: Parent process global ID. @raise WindowsError: An error occured when calling a Win32 API function. @raise RuntimeError: The parent process ID can't be found. """ if self.dwProcessId is None: if self.__process is not None: # Infinite loop if self.__process is None self.dwProcessId = self.get_process().get_pid() else: try: # I wish this had been implemented before Vista... # XXX TODO find the real ntdll call under this api hThread = self.get_handle( win32.THREAD_QUERY_LIMITED_INFORMATION) self.dwProcessId = win32.GetProcessIdOfThread(hThread) except AttributeError: # This method is really bad :P self.dwProcessId = self.__get_pid_by_scanning() return self.dwProcessId def __get_pid_by_scanning(self): 'Internally used by get_pid().' dwProcessId = None dwThreadId = self.get_tid() with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot: te = win32.Thread32First(hSnapshot) while te is not None: if te.th32ThreadID == dwThreadId: dwProcessId = te.th32OwnerProcessID break te = win32.Thread32Next(hSnapshot) if dwProcessId is None: msg = "Cannot find thread ID %d in any process" % dwThreadId raise RuntimeError(msg) return dwProcessId def get_tid(self): """ @rtype: int @return: Thread global ID. """ return self.dwThreadId def get_name(self): """ @rtype: str @return: Thread name, or C{None} if the thread is nameless. """ return self.name def set_name(self, name = None): """ Sets the thread's name. @type name: str @param name: Thread name, or C{None} if the thread is nameless. """ self.name = name #------------------------------------------------------------------------------ def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS): """ Opens a new handle to the thread, closing the previous one. The new handle is stored in the L{hThread} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.THREAD_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx} @raise WindowsError: It's not possible to open a handle to the thread with the requested access rights. This tipically happens because the target thread belongs to system process and the debugger is not runnning with administrative rights. """ hThread = win32.OpenThread(dwDesiredAccess, win32.FALSE, self.dwThreadId) # In case hThread was set to an actual handle value instead of a Handle # object. This shouldn't happen unless the user tinkered with it. if not hasattr(self.hThread, '__del__'): self.close_handle() self.hThread = hThread def close_handle(self): """ Closes the handle to the thread. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. """ try: if hasattr(self.hThread, 'close'): self.hThread.close() elif self.hThread not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hThread) finally: self.hThread = None def get_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS): """ Returns a handle to the thread with I{at least} the access rights requested. @note: If a handle was previously opened and has the required access rights, it's reused. If not, a new handle is opened with the combination of the old and new access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx} @rtype: ThreadHandle @return: Handle to the thread. @raise WindowsError: It's not possible to open a handle to the thread with the requested access rights. This tipically happens because the target thread belongs to system process and the debugger is not runnning with administrative rights. """ if self.hThread in (None, win32.INVALID_HANDLE_VALUE): self.open_handle(dwDesiredAccess) else: dwAccess = self.hThread.dwAccess if (dwAccess | dwDesiredAccess) != dwAccess: self.open_handle(dwAccess | dwDesiredAccess) return self.hThread def clear(self): """ Clears the resources held by this object. """ try: self.set_process(None) finally: self.close_handle() #------------------------------------------------------------------------------ def wait(self, dwTimeout = None): """ Waits for the thread to finish executing. @type dwTimeout: int @param dwTimeout: (Optional) Timeout value in milliseconds. Use C{INFINITE} or C{None} for no timeout. """ self.get_handle(win32.SYNCHRONIZE).wait(dwTimeout) def kill(self, dwExitCode = 0): """ Terminates the thread execution. @note: If the C{lpInjectedMemory} member contains a valid pointer, the memory is freed. @type dwExitCode: int @param dwExitCode: (Optional) Thread exit code. """ hThread = self.get_handle(win32.THREAD_TERMINATE) win32.TerminateThread(hThread, dwExitCode) # Ugliest hack ever, won't work if many pieces of code are injected. # Seriously, what was I thinking? :( if self.pInjectedMemory is not None: try: self.get_process().free(self.pInjectedMemory) self.pInjectedMemory = None except Exception: ## raise # XXX DEBUG pass # XXX TODO # suspend() and resume() should have a counter of how many times a thread # was suspended, so on debugger exit they could (optionally!) be restored def suspend(self): """ Suspends the thread execution. @rtype: int @return: Suspend count. If zero, the thread is running. """ hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME) if self.is_wow64(): # FIXME this will be horribly slow on XP 64 # since it'll try to resolve a missing API every time try: return win32.Wow64SuspendThread(hThread) except AttributeError: pass return win32.SuspendThread(hThread) def resume(self): """ Resumes the thread execution. @rtype: int @return: Suspend count. If zero, the thread is running. """ hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME) return win32.ResumeThread(hThread) def is_alive(self): """ @rtype: bool @return: C{True} if the thread if currently running. @raise WindowsError: The debugger doesn't have enough privileges to perform this action. """ try: self.wait(0) except WindowsError: e = sys.exc_info()[1] error = e.winerror if error == win32.ERROR_ACCESS_DENIED: raise return error == win32.WAIT_TIMEOUT return True def get_exit_code(self): """ @rtype: int @return: Thread exit code, or C{STILL_ACTIVE} if it's still alive. """ if win32.THREAD_ALL_ACCESS == win32.THREAD_ALL_ACCESS_VISTA: dwAccess = win32.THREAD_QUERY_LIMITED_INFORMATION else: dwAccess = win32.THREAD_QUERY_INFORMATION return win32.GetExitCodeThread( self.get_handle(dwAccess) ) #------------------------------------------------------------------------------ # XXX TODO # Support for string searches on the window captions. def get_windows(self): """ @rtype: list of L{Window} @return: Returns a list of windows handled by this thread. """ try: process = self.get_process() except Exception: process = None return [ Window( hWnd, process, self ) \ for hWnd in win32.EnumThreadWindows( self.get_tid() ) ] #------------------------------------------------------------------------------ # TODO # A registers cache could be implemented here. def get_context(self, ContextFlags = None, bSuspend = False): """ Retrieves the execution context (i.e. the registers values) for this thread. @type ContextFlags: int @param ContextFlags: Optional, specify which registers to retrieve. Defaults to C{win32.CONTEXT_ALL} which retrieves all registes for the current platform. @type bSuspend: bool @param bSuspend: C{True} to automatically suspend the thread before getting its context, C{False} otherwise. Defaults to C{False} because suspending the thread during some debug events (like thread creation or destruction) may lead to strange errors. Note that WinAppDbg 1.4 used to suspend the thread automatically always. This behavior was changed in version 1.5. @rtype: dict( str S{->} int ) @return: Dictionary mapping register names to their values. @see: L{set_context} """ # Some words on the "strange errors" that lead to the bSuspend # parameter. Peter Van Eeckhoutte and I were working on a fix # for some bugs he found in the 1.5 betas when we stumbled upon # what seemed to be a deadlock in the debug API that caused the # GetThreadContext() call never to return. Since removing the # call to SuspendThread() solved the problem, and a few Google # searches showed a handful of problems related to these two # APIs and Wow64 environments, I decided to break compatibility. # # Here are some pages about the weird behavior of SuspendThread: # http://zachsaw.blogspot.com.es/2010/11/wow64-bug-getthreadcontext-may-return.html # http://stackoverflow.com/questions/3444190/windows-suspendthread-doesnt-getthreadcontext-fails # Get the thread handle. dwAccess = win32.THREAD_GET_CONTEXT if bSuspend: dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME hThread = self.get_handle(dwAccess) # Suspend the thread if requested. if bSuspend: try: self.suspend() except WindowsError: # Threads can't be suspended when the exit process event # arrives, but you can still get the context. bSuspend = False # If an exception is raised, make sure the thread execution is resumed. try: if win32.bits == self.get_bits(): # 64 bit debugger attached to 64 bit process, or # 32 bit debugger attached to 32 bit process. ctx = win32.GetThreadContext(hThread, ContextFlags = ContextFlags) else: if self.is_wow64(): # 64 bit debugger attached to 32 bit process. if ContextFlags is not None: ContextFlags &= ~win32.ContextArchMask ContextFlags |= win32.WOW64_CONTEXT_i386 ctx = win32.Wow64GetThreadContext(hThread, ContextFlags) else: # 32 bit debugger attached to 64 bit process. # XXX only i386/AMD64 is supported in this particular case if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64): raise NotImplementedError() if ContextFlags is not None: ContextFlags &= ~win32.ContextArchMask ContextFlags |= win32.context_amd64.CONTEXT_AMD64 ctx = win32.context_amd64.GetThreadContext(hThread, ContextFlags = ContextFlags) finally: # Resume the thread if we suspended it. if bSuspend: self.resume() # Return the context. return ctx def set_context(self, context, bSuspend = False): """ Sets the values of the registers. @see: L{get_context} @type context: dict( str S{->} int ) @param context: Dictionary mapping register names to their values. @type bSuspend: bool @param bSuspend: C{True} to automatically suspend the thread before setting its context, C{False} otherwise. Defaults to C{False} because suspending the thread during some debug events (like thread creation or destruction) may lead to strange errors. Note that WinAppDbg 1.4 used to suspend the thread automatically always. This behavior was changed in version 1.5. """ # Get the thread handle. dwAccess = win32.THREAD_SET_CONTEXT if bSuspend: dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME hThread = self.get_handle(dwAccess) # Suspend the thread if requested. if bSuspend: self.suspend() # No fix for the exit process event bug. # Setting the context of a dead thread is pointless anyway. # Set the thread context. try: if win32.bits == 64 and self.is_wow64(): win32.Wow64SetThreadContext(hThread, context) else: win32.SetThreadContext(hThread, context) # Resume the thread if we suspended it. finally: if bSuspend: self.resume() def get_register(self, register): """ @type register: str @param register: Register name. @rtype: int @return: Value of the requested register. """ 'Returns the value of a specific register.' context = self.get_context() return context[register] def set_register(self, register, value): """ Sets the value of a specific register. @type register: str @param register: Register name. @rtype: int @return: Register value. """ context = self.get_context() context[register] = value self.set_context(context) #------------------------------------------------------------------------------ # TODO: a metaclass would do a better job instead of checking the platform # during module import, also would support mixing 32 and 64 bits if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64): def get_pc(self): """ @rtype: int @return: Value of the program counter register. """ context = self.get_context(win32.CONTEXT_CONTROL) return context.pc def set_pc(self, pc): """ Sets the value of the program counter register. @type pc: int @param pc: Value of the program counter register. """ context = self.get_context(win32.CONTEXT_CONTROL) context.pc = pc self.set_context(context) def get_sp(self): """ @rtype: int @return: Value of the stack pointer register. """ context = self.get_context(win32.CONTEXT_CONTROL) return context.sp def set_sp(self, sp): """ Sets the value of the stack pointer register. @type sp: int @param sp: Value of the stack pointer register. """ context = self.get_context(win32.CONTEXT_CONTROL) context.sp = sp self.set_context(context) def get_fp(self): """ @rtype: int @return: Value of the frame pointer register. """ flags = win32.CONTEXT_CONTROL | win32.CONTEXT_INTEGER context = self.get_context(flags) return context.fp def set_fp(self, fp): """ Sets the value of the frame pointer register. @type fp: int @param fp: Value of the frame pointer register. """ flags = win32.CONTEXT_CONTROL | win32.CONTEXT_INTEGER context = self.get_context(flags) context.fp = fp self.set_context(context) #------------------------------------------------------------------------------ if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64): class Flags (object): 'Commonly used processor flags' Overflow = 0x800 Direction = 0x400 Interrupts = 0x200 Trap = 0x100 Sign = 0x80 Zero = 0x40 # 0x20 ??? Auxiliary = 0x10 # 0x8 ??? Parity = 0x4 # 0x2 ??? Carry = 0x1 def get_flags(self, FlagMask = 0xFFFFFFFF): """ @type FlagMask: int @param FlagMask: (Optional) Bitwise-AND mask. @rtype: int @return: Flags register contents, optionally masking out some bits. """ context = self.get_context(win32.CONTEXT_CONTROL) return context['EFlags'] & FlagMask def set_flags(self, eflags, FlagMask = 0xFFFFFFFF): """ Sets the flags register, optionally masking some bits. @type eflags: int @param eflags: Flags register contents. @type FlagMask: int @param FlagMask: (Optional) Bitwise-AND mask. """ context = self.get_context(win32.CONTEXT_CONTROL) context['EFlags'] = (context['EFlags'] & FlagMask) | eflags self.set_context(context) def get_flag_value(self, FlagBit): """ @type FlagBit: int @param FlagBit: One of the L{Flags}. @rtype: bool @return: Boolean value of the requested flag. """ return bool( self.get_flags(FlagBit) ) def set_flag_value(self, FlagBit, FlagValue): """ Sets a single flag, leaving the others intact. @type FlagBit: int @param FlagBit: One of the L{Flags}. @type FlagValue: bool @param FlagValue: Boolean value of the flag. """ if FlagValue: eflags = FlagBit else: eflags = 0 FlagMask = 0xFFFFFFFF ^ FlagBit self.set_flags(eflags, FlagMask) def get_zf(self): """ @rtype: bool @return: Boolean value of the Zero flag. """ return self.get_flag_value(self.Flags.Zero) def get_cf(self): """ @rtype: bool @return: Boolean value of the Carry flag. """ return self.get_flag_value(self.Flags.Carry) def get_sf(self): """ @rtype: bool @return: Boolean value of the Sign flag. """ return self.get_flag_value(self.Flags.Sign) def get_df(self): """ @rtype: bool @return: Boolean value of the Direction flag. """ return self.get_flag_value(self.Flags.Direction) def get_tf(self): """ @rtype: bool @return: Boolean value of the Trap flag. """ return self.get_flag_value(self.Flags.Trap) def clear_zf(self): 'Clears the Zero flag.' self.set_flag_value(self.Flags.Zero, False) def clear_cf(self): 'Clears the Carry flag.' self.set_flag_value(self.Flags.Carry, False) def clear_sf(self): 'Clears the Sign flag.' self.set_flag_value(self.Flags.Sign, False) def clear_df(self): 'Clears the Direction flag.' self.set_flag_value(self.Flags.Direction, False) def clear_tf(self): 'Clears the Trap flag.' self.set_flag_value(self.Flags.Trap, False) def set_zf(self): 'Sets the Zero flag.' self.set_flag_value(self.Flags.Zero, True) def set_cf(self): 'Sets the Carry flag.' self.set_flag_value(self.Flags.Carry, True) def set_sf(self): 'Sets the Sign flag.' self.set_flag_value(self.Flags.Sign, True) def set_df(self): 'Sets the Direction flag.' self.set_flag_value(self.Flags.Direction, True) def set_tf(self): 'Sets the Trap flag.' self.set_flag_value(self.Flags.Trap, True) #------------------------------------------------------------------------------ def is_wow64(self): """ Determines if the thread is running under WOW64. @rtype: bool @return: C{True} if the thread is running under WOW64. That is, it belongs to a 32-bit application running in a 64-bit Windows. C{False} if the thread belongs to either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows. @raise WindowsError: On error an exception is raised. @see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} """ try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: wow64 = self.get_process().is_wow64() self.__wow64 = wow64 return wow64 def get_arch(self): """ @rtype: str @return: The architecture in which this thread believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the architecture returned by this method will be L{win32.ARCH_I386}, but the value of L{System.arch} will be L{win32.ARCH_AMD64}. """ if win32.bits == 32 and not win32.wow64: return win32.arch return self.get_process().get_arch() def get_bits(self): """ @rtype: str @return: The number of bits in which this thread believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the number of bits returned by this method will be C{32}, but the value of L{System.arch} will be C{64}. """ if win32.bits == 32 and not win32.wow64: return 32 return self.get_process().get_bits() def is_hidden(self): """ Determines if the thread has been hidden from debuggers. Some binary packers hide their own threads to thwart debugging. @rtype: bool @return: C{True} if the thread is hidden from debuggers. This means the thread's execution won't be stopped for debug events, and thus said events won't be sent to the debugger. """ return win32.NtQueryInformationThread( self.get_handle(), # XXX what permissions do I need? win32.ThreadHideFromDebugger) def get_teb(self): """ Returns a copy of the TEB. To dereference pointers in it call L{Process.read_structure}. @rtype: L{TEB} @return: TEB structure. @raise WindowsError: An exception is raised on error. """ return self.get_process().read_structure( self.get_teb_address(), win32.TEB ) def get_teb_address(self): """ Returns a remote pointer to the TEB. @rtype: int @return: Remote pointer to the L{TEB} structure. @raise WindowsError: An exception is raised on error. """ try: return self._teb_ptr except AttributeError: try: hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION) tbi = win32.NtQueryInformationThread( hThread, win32.ThreadBasicInformation) address = tbi.TebBaseAddress except WindowsError: address = self.get_linear_address('SegFs', 0) # fs:[0] if not address: raise self._teb_ptr = address return address def get_linear_address(self, segment, address): """ Translates segment-relative addresses to linear addresses. Linear addresses can be used to access a process memory, calling L{Process.read} and L{Process.write}. @type segment: str @param segment: Segment register name. @type address: int @param address: Segment relative memory address. @rtype: int @return: Linear memory address. @raise ValueError: Address is too large for selector. @raise WindowsError: The current architecture does not support selectors. Selectors only exist in x86-based systems. """ hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION) selector = self.get_register(segment) ldt = win32.GetThreadSelectorEntry(hThread, selector) BaseLow = ldt.BaseLow BaseMid = ldt.HighWord.Bytes.BaseMid << 16 BaseHi = ldt.HighWord.Bytes.BaseHi << 24 Base = BaseLow | BaseMid | BaseHi LimitLow = ldt.LimitLow LimitHi = ldt.HighWord.Bits.LimitHi << 16 Limit = LimitLow | LimitHi if address > Limit: msg = "Address %s too large for segment %s (selector %d)" msg = msg % (HexDump.address(address, self.get_bits()), segment, selector) raise ValueError(msg) return Base + address def get_label_at_pc(self): """ @rtype: str @return: Label that points to the instruction currently being executed. """ return self.get_process().get_label_at_address( self.get_pc() ) def get_seh_chain_pointer(self): """ Get the pointer to the first structured exception handler block. @rtype: int @return: Remote pointer to the first block of the structured exception handlers linked list. If the list is empty, the returned value is C{0xFFFFFFFF}. @raise NotImplementedError: This method is only supported in 32 bits versions of Windows. """ if win32.arch != win32.ARCH_I386: raise NotImplementedError( "SEH chain parsing is only supported in 32-bit Windows.") process = self.get_process() address = self.get_linear_address( 'SegFs', 0 ) return process.read_pointer( address ) def set_seh_chain_pointer(self, value): """ Change the pointer to the first structured exception handler block. @type value: int @param value: Value of the remote pointer to the first block of the structured exception handlers linked list. To disable SEH set the value C{0xFFFFFFFF}. @raise NotImplementedError: This method is only supported in 32 bits versions of Windows. """ if win32.arch != win32.ARCH_I386: raise NotImplementedError( "SEH chain parsing is only supported in 32-bit Windows.") process = self.get_process() address = self.get_linear_address( 'SegFs', 0 ) process.write_pointer( address, value ) def get_seh_chain(self): """ @rtype: list of tuple( int, int ) @return: List of structured exception handlers. Each SEH is represented as a tuple of two addresses: - Address of this SEH block - Address of the SEH callback function Do not confuse this with the contents of the SEH block itself, where the first member is a pointer to the B{next} block instead. @raise NotImplementedError: This method is only supported in 32 bits versions of Windows. """ seh_chain = list() try: process = self.get_process() seh = self.get_seh_chain_pointer() while seh != 0xFFFFFFFF: seh_func = process.read_pointer( seh + 4 ) seh_chain.append( (seh, seh_func) ) seh = process.read_pointer( seh ) except WindowsError: seh_chain.append( (seh, None) ) return seh_chain def get_wait_chain(self): """ @rtype: tuple of ( list of L{win32.WaitChainNodeInfo} structures, bool) @return: Wait chain for the thread. The boolean indicates if there's a cycle in the chain (a deadlock). @raise AttributeError: This method is only suppported in Windows Vista and above. @see: U{http://msdn.microsoft.com/en-us/library/ms681622%28VS.85%29.aspx} """ with win32.OpenThreadWaitChainSession() as hWct: return win32.GetThreadWaitChain(hWct, ThreadId = self.get_tid()) def get_stack_range(self): """ @rtype: tuple( int, int ) @return: Stack beginning and end pointers, in memory addresses order. That is, the first pointer is the stack top, and the second pointer is the stack bottom, since the stack grows towards lower memory addresses. @raise WindowsError: Raises an exception on error. """ # TODO use teb.DeallocationStack too (max. possible stack size) teb = self.get_teb() tib = teb.NtTib return ( tib.StackLimit, tib.StackBase ) # top, bottom def __get_stack_trace(self, depth = 16, bUseLabels = True, bMakePretty = True): """ Tries to get a stack trace for the current function using the debug helper API (dbghelp.dll). @type depth: int @param depth: Maximum depth of stack trace. @type bUseLabels: bool @param bUseLabels: C{True} to use labels, C{False} to use addresses. @type bMakePretty: bool @param bMakePretty: C{True} for user readable labels, C{False} for labels that can be passed to L{Process.resolve_label}. "Pretty" labels look better when producing output for the user to read, while pure labels are more useful programatically. @rtype: tuple of tuple( int, int, str ) @return: Stack trace of the thread as a tuple of ( return address, frame pointer address, module filename ) when C{bUseLabels} is C{True}, or a tuple of ( return address, frame pointer label ) when C{bUseLabels} is C{False}. @raise WindowsError: Raises an exception on error. """ aProcess = self.get_process() arch = aProcess.get_arch() bits = aProcess.get_bits() if arch == win32.ARCH_I386: MachineType = win32.IMAGE_FILE_MACHINE_I386 elif arch == win32.ARCH_AMD64: MachineType = win32.IMAGE_FILE_MACHINE_AMD64 elif arch == win32.ARCH_IA64: MachineType = win32.IMAGE_FILE_MACHINE_IA64 else: msg = "Stack walking is not available for this architecture: %s" raise NotImplementedError(msg % arch) hProcess = aProcess.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) hThread = self.get_handle( win32.THREAD_GET_CONTEXT | win32.THREAD_QUERY_INFORMATION ) StackFrame = win32.STACKFRAME64() StackFrame.AddrPC = win32.ADDRESS64( self.get_pc() ) StackFrame.AddrFrame = win32.ADDRESS64( self.get_fp() ) StackFrame.AddrStack = win32.ADDRESS64( self.get_sp() ) trace = list() while win32.StackWalk64(MachineType, hProcess, hThread, StackFrame): if depth <= 0: break fp = StackFrame.AddrFrame.Offset ra = aProcess.peek_pointer(fp + 4) if ra == 0: break lib = aProcess.get_module_at_address(ra) if lib is None: lib = "" else: if lib.fileName: lib = lib.fileName else: lib = "%s" % HexDump.address(lib.lpBaseOfDll, bits) if bUseLabels: label = aProcess.get_label_at_address(ra) if bMakePretty: label = '%s (%s)' % (HexDump.address(ra, bits), label) trace.append( (fp, label) ) else: trace.append( (fp, ra, lib) ) fp = aProcess.peek_pointer(fp) return tuple(trace) def __get_stack_trace_manually(self, depth = 16, bUseLabels = True, bMakePretty = True): """ Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue. @type depth: int @param depth: Maximum depth of stack trace. @type bUseLabels: bool @param bUseLabels: C{True} to use labels, C{False} to use addresses. @type bMakePretty: bool @param bMakePretty: C{True} for user readable labels, C{False} for labels that can be passed to L{Process.resolve_label}. "Pretty" labels look better when producing output for the user to read, while pure labels are more useful programatically. @rtype: tuple of tuple( int, int, str ) @return: Stack trace of the thread as a tuple of ( return address, frame pointer address, module filename ) when C{bUseLabels} is C{True}, or a tuple of ( return address, frame pointer label ) when C{bUseLabels} is C{False}. @raise WindowsError: Raises an exception on error. """ aProcess = self.get_process() st, sb = self.get_stack_range() # top, bottom fp = self.get_fp() trace = list() if aProcess.get_module_count() == 0: aProcess.scan_modules() bits = aProcess.get_bits() while depth > 0: if fp == 0: break if not st <= fp < sb: break ra = aProcess.peek_pointer(fp + 4) if ra == 0: break lib = aProcess.get_module_at_address(ra) if lib is None: lib = "" else: if lib.fileName: lib = lib.fileName else: lib = "%s" % HexDump.address(lib.lpBaseOfDll, bits) if bUseLabels: label = aProcess.get_label_at_address(ra) if bMakePretty: label = '%s (%s)' % (HexDump.address(ra, bits), label) trace.append( (fp, label) ) else: trace.append( (fp, ra, lib) ) fp = aProcess.peek_pointer(fp) return tuple(trace) def get_stack_trace(self, depth = 16): """ Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue. @type depth: int @param depth: Maximum depth of stack trace. @rtype: tuple of tuple( int, int, str ) @return: Stack trace of the thread as a tuple of ( return address, frame pointer address, module filename ). @raise WindowsError: Raises an exception on error. """ try: trace = self.__get_stack_trace(depth, False) except Exception: import traceback traceback.print_exc() trace = () if not trace: trace = self.__get_stack_trace_manually(depth, False) return trace def get_stack_trace_with_labels(self, depth = 16, bMakePretty = True): """ Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue. @type depth: int @param depth: Maximum depth of stack trace. @type bMakePretty: bool @param bMakePretty: C{True} for user readable labels, C{False} for labels that can be passed to L{Process.resolve_label}. "Pretty" labels look better when producing output for the user to read, while pure labels are more useful programatically. @rtype: tuple of tuple( int, int, str ) @return: Stack trace of the thread as a tuple of ( return address, frame pointer label ). @raise WindowsError: Raises an exception on error. """ try: trace = self.__get_stack_trace(depth, True, bMakePretty) except Exception: trace = () if not trace: trace = self.__get_stack_trace_manually(depth, True, bMakePretty) return trace def get_stack_frame_range(self): """ Returns the starting and ending addresses of the stack frame. Only works for functions with standard prologue and epilogue. @rtype: tuple( int, int ) @return: Stack frame range. May not be accurate, depending on the compiler used. @raise RuntimeError: The stack frame is invalid, or the function doesn't have a standard prologue and epilogue. @raise WindowsError: An error occured when getting the thread context. """ st, sb = self.get_stack_range() # top, bottom sp = self.get_sp() fp = self.get_fp() size = fp - sp if not st <= sp < sb: raise RuntimeError('Stack pointer lies outside the stack') if not st <= fp < sb: raise RuntimeError('Frame pointer lies outside the stack') if sp > fp: raise RuntimeError('No valid stack frame found') return (sp, fp) def get_stack_frame(self, max_size = None): """ Reads the contents of the current stack frame. Only works for functions with standard prologue and epilogue. @type max_size: int @param max_size: (Optional) Maximum amount of bytes to read. @rtype: str @return: Stack frame data. May not be accurate, depending on the compiler used. May return an empty string. @raise RuntimeError: The stack frame is invalid, or the function doesn't have a standard prologue and epilogue. @raise WindowsError: An error occured when getting the thread context or reading data from the process memory. """ sp, fp = self.get_stack_frame_range() size = fp - sp if max_size and size > max_size: size = max_size return self.get_process().peek(sp, size) def read_stack_data(self, size = 128, offset = 0): """ Reads the contents of the top of the stack. @type size: int @param size: Number of bytes to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: str @return: Stack data. @raise WindowsError: Could not read the requested data. """ aProcess = self.get_process() return aProcess.read(self.get_sp() + offset, size) def peek_stack_data(self, size = 128, offset = 0): """ Tries to read the contents of the top of the stack. @type size: int @param size: Number of bytes to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: str @return: Stack data. Returned data may be less than the requested size. """ aProcess = self.get_process() return aProcess.peek(self.get_sp() + offset, size) def read_stack_dwords(self, count, offset = 0): """ Reads DWORDs from the top of the stack. @type count: int @param count: Number of DWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: tuple( int... ) @return: Tuple of integers read from the stack. @raise WindowsError: Could not read the requested data. """ if count > 0: stackData = self.read_stack_data(count * 4, offset) return struct.unpack('<'+('L'*count), stackData) return () def peek_stack_dwords(self, count, offset = 0): """ Tries to read DWORDs from the top of the stack. @type count: int @param count: Number of DWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: tuple( int... ) @return: Tuple of integers read from the stack. May be less than the requested number of DWORDs. """ stackData = self.peek_stack_data(count * 4, offset) if len(stackData) & 3: stackData = stackData[:-len(stackData) & 3] if not stackData: return () return struct.unpack('<'+('L'*count), stackData) def read_stack_qwords(self, count, offset = 0): """ Reads QWORDs from the top of the stack. @type count: int @param count: Number of QWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: tuple( int... ) @return: Tuple of integers read from the stack. @raise WindowsError: Could not read the requested data. """ stackData = self.read_stack_data(count * 8, offset) return struct.unpack('<'+('Q'*count), stackData) def peek_stack_qwords(self, count, offset = 0): """ Tries to read QWORDs from the top of the stack. @type count: int @param count: Number of QWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: tuple( int... ) @return: Tuple of integers read from the stack. May be less than the requested number of QWORDs. """ stackData = self.peek_stack_data(count * 8, offset) if len(stackData) & 7: stackData = stackData[:-len(stackData) & 7] if not stackData: return () return struct.unpack('<'+('Q'*count), stackData) def read_stack_structure(self, structure, offset = 0): """ Reads the given structure at the top of the stack. @type structure: ctypes.Structure @param structure: Structure of the data to read from the stack. @type offset: int @param offset: Offset from the stack pointer to begin reading. The stack pointer is the same returned by the L{get_sp} method. @rtype: tuple @return: Tuple of elements read from the stack. The type of each element matches the types in the stack frame structure. """ aProcess = self.get_process() stackData = aProcess.read_structure(self.get_sp() + offset, structure) return tuple([ stackData.__getattribute__(name) for (name, type) in stackData._fields_ ]) def read_stack_frame(self, structure, offset = 0): """ Reads the stack frame of the thread. @type structure: ctypes.Structure @param structure: Structure of the stack frame. @type offset: int @param offset: Offset from the frame pointer to begin reading. The frame pointer is the same returned by the L{get_fp} method. @rtype: tuple @return: Tuple of elements read from the stack frame. The type of each element matches the types in the stack frame structure. """ aProcess = self.get_process() stackData = aProcess.read_structure(self.get_fp() + offset, structure) return tuple([ stackData.__getattribute__(name) for (name, type) in stackData._fields_ ]) def read_code_bytes(self, size = 128, offset = 0): """ Tries to read some bytes of the code currently being executed. @type size: int @param size: Number of bytes to read. @type offset: int @param offset: Offset from the program counter to begin reading. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: Could not read the requested data. """ return self.get_process().read(self.get_pc() + offset, size) def peek_code_bytes(self, size = 128, offset = 0): """ Tries to read some bytes of the code currently being executed. @type size: int @param size: Number of bytes to read. @type offset: int @param offset: Offset from the program counter to begin reading. @rtype: str @return: Bytes read from the process memory. May be less than the requested number of bytes. """ return self.get_process().peek(self.get_pc() + offset, size) def peek_pointers_in_registers(self, peekSize = 16, context = None): """ Tries to guess which values in the registers are valid pointers, and reads some data from them. @type peekSize: int @param peekSize: Number of bytes to read from each pointer found. @type context: dict( str S{->} int ) @param context: (Optional) Dictionary mapping register names to their values. If not given, the current thread context will be used. @rtype: dict( str S{->} str ) @return: Dictionary mapping register names to the data they point to. """ peekable_registers = ( 'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp' ) if not context: context = self.get_context(win32.CONTEXT_CONTROL | \ win32.CONTEXT_INTEGER) aProcess = self.get_process() data = dict() for (reg_name, reg_value) in compat.iteritems(context): if reg_name not in peekable_registers: continue ## if reg_name == 'Ebp': ## stack_begin, stack_end = self.get_stack_range() ## print hex(stack_end), hex(reg_value), hex(stack_begin) ## if stack_begin and stack_end and stack_end < stack_begin and \ ## stack_begin <= reg_value <= stack_end: ## continue reg_data = aProcess.peek(reg_value, peekSize) if reg_data: data[reg_name] = reg_data return data # TODO # try to avoid reading the same page twice by caching it def peek_pointers_in_data(self, data, peekSize = 16, peekStep = 1): """ Tries to guess which values in the given data are valid pointers, and reads some data from them. @type data: str @param data: Binary data to find pointers in. @type peekSize: int @param peekSize: Number of bytes to read from each pointer found. @type peekStep: int @param peekStep: Expected data alignment. Tipically you specify 1 when data alignment is unknown, or 4 when you expect data to be DWORD aligned. Any other value may be specified. @rtype: dict( str S{->} str ) @return: Dictionary mapping stack offsets to the data they point to. """ aProcess = self.get_process() return aProcess.peek_pointers_in_data(data, peekSize, peekStep) #------------------------------------------------------------------------------ # TODO # The disassemble_around and disassemble_around_pc methods # should take as parameter instruction counts rather than sizes def disassemble_string(self, lpAddress, code): """ Disassemble instructions from a block of binary code. @type lpAddress: int @param lpAddress: Memory address where the code was read from. @type code: str @param code: Binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aProcess = self.get_process() return aProcess.disassemble_string(lpAddress, code) def disassemble(self, lpAddress, dwSize): """ Disassemble instructions from the address space of the process. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @type dwSize: int @param dwSize: Size of binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aProcess = self.get_process() return aProcess.disassemble(lpAddress, dwSize) def disassemble_around(self, lpAddress, dwSize = 64): """ Disassemble around the given address. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @type dwSize: int @param dwSize: Delta offset. Code will be read from lpAddress - dwSize to lpAddress + dwSize. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aProcess = self.get_process() return aProcess.disassemble_around(lpAddress, dwSize) def disassemble_around_pc(self, dwSize = 64): """ Disassemble around the program counter of the given thread. @type dwSize: int @param dwSize: Delta offset. Code will be read from pc - dwSize to pc + dwSize. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aProcess = self.get_process() return aProcess.disassemble_around(self.get_pc(), dwSize) def disassemble_instruction(self, lpAddress): """ Disassemble the instruction at the given memory address. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aProcess = self.get_process() return aProcess.disassemble(lpAddress, 15)[0] def disassemble_current(self): """ Disassemble the instruction at the program counter of the given thread. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ return self.disassemble_instruction( self.get_pc() ) #============================================================================== class _ThreadContainer (object): """ Encapsulates the capability to contain Thread objects. @group Instrumentation: start_thread @group Threads snapshot: scan_threads, get_thread, get_thread_count, get_thread_ids, has_thread, iter_threads, iter_thread_ids, find_threads_by_name, get_windows, clear_threads, clear_dead_threads, close_thread_handles """ def __init__(self): self.__threadDict = dict() def __initialize_snapshot(self): """ Private method to automatically initialize the snapshot when you try to use it without calling any of the scan_* methods first. You don't need to call this yourself. """ if not self.__threadDict: self.scan_threads() def __contains__(self, anObject): """ @type anObject: L{Thread}, int @param anObject: - C{int}: Global ID of the thread to look for. - C{Thread}: Thread object to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Thread} object with the same ID. """ if isinstance(anObject, Thread): anObject = anObject.dwThreadId return self.has_thread(anObject) def __iter__(self): """ @see: L{iter_threads} @rtype: dictionary-valueiterator @return: Iterator of L{Thread} objects in this snapshot. """ return self.iter_threads() def __len__(self): """ @see: L{get_thread_count} @rtype: int @return: Count of L{Thread} objects in this snapshot. """ return self.get_thread_count() def has_thread(self, dwThreadId): """ @type dwThreadId: int @param dwThreadId: Global ID of the thread to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Thread} object with the given global ID. """ self.__initialize_snapshot() return dwThreadId in self.__threadDict def get_thread(self, dwThreadId): """ @type dwThreadId: int @param dwThreadId: Global ID of the thread to look for. @rtype: L{Thread} @return: Thread object with the given global ID. """ self.__initialize_snapshot() if dwThreadId not in self.__threadDict: msg = "Unknown thread ID: %d" % dwThreadId raise KeyError(msg) return self.__threadDict[dwThreadId] def iter_thread_ids(self): """ @see: L{iter_threads} @rtype: dictionary-keyiterator @return: Iterator of global thread IDs in this snapshot. """ self.__initialize_snapshot() return compat.iterkeys(self.__threadDict) def iter_threads(self): """ @see: L{iter_thread_ids} @rtype: dictionary-valueiterator @return: Iterator of L{Thread} objects in this snapshot. """ self.__initialize_snapshot() return compat.itervalues(self.__threadDict) def get_thread_ids(self): """ @rtype: list( int ) @return: List of global thread IDs in this snapshot. """ self.__initialize_snapshot() return compat.keys(self.__threadDict) def get_thread_count(self): """ @rtype: int @return: Count of L{Thread} objects in this snapshot. """ self.__initialize_snapshot() return len(self.__threadDict) #------------------------------------------------------------------------------ def find_threads_by_name(self, name, bExactMatch = True): """ Find threads by name, using different search methods. @type name: str, None @param name: Name to look for. Use C{None} to find nameless threads. @type bExactMatch: bool @param bExactMatch: C{True} if the name must be B{exactly} as given, C{False} if the name can be loosely matched. This parameter is ignored when C{name} is C{None}. @rtype: list( L{Thread} ) @return: All threads matching the given name. """ found_threads = list() # Find threads with no name. if name is None: for aThread in self.iter_threads(): if aThread.get_name() is None: found_threads.append(aThread) # Find threads matching the given name exactly. elif bExactMatch: for aThread in self.iter_threads(): if aThread.get_name() == name: found_threads.append(aThread) # Find threads whose names match the given substring. else: for aThread in self.iter_threads(): t_name = aThread.get_name() if t_name is not None and name in t_name: found_threads.append(aThread) return found_threads #------------------------------------------------------------------------------ # XXX TODO # Support for string searches on the window captions. def get_windows(self): """ @rtype: list of L{Window} @return: Returns a list of windows handled by this process. """ window_list = list() for thread in self.iter_threads(): window_list.extend( thread.get_windows() ) return window_list #------------------------------------------------------------------------------ def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False): """ Remotely creates a new thread in the process. @type lpStartAddress: int @param lpStartAddress: Start address for the new thread. @type lpParameter: int @param lpParameter: Optional argument for the new thread. @type bSuspended: bool @param bSuspended: C{True} if the new thread should be suspended. In that case use L{Thread.resume} to start execution. """ if bSuspended: dwCreationFlags = win32.CREATE_SUSPENDED else: dwCreationFlags = 0 hProcess = self.get_handle( win32.PROCESS_CREATE_THREAD | win32.PROCESS_QUERY_INFORMATION | win32.PROCESS_VM_OPERATION | win32.PROCESS_VM_WRITE | win32.PROCESS_VM_READ ) hThread, dwThreadId = win32.CreateRemoteThread( hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags) aThread = Thread(dwThreadId, hThread, self) self._add_thread(aThread) return aThread #------------------------------------------------------------------------------ # TODO # maybe put all the toolhelp code into their own set of classes? # # XXX this method musn't end up calling __initialize_snapshot by accident! def scan_threads(self): """ Populates the snapshot with running threads. """ # Ignore special process IDs. # PID 0: System Idle Process. Also has a special meaning to the # toolhelp APIs (current process). # PID 4: System Integrity Group. See this forum post for more info: # http://tinyurl.com/ycza8jo # (points to social.technet.microsoft.com) # Only on XP and above # PID 8: System (?) only in Windows 2000 and below AFAIK. # It's probably the same as PID 4 in XP and above. dwProcessId = self.get_pid() if dwProcessId in (0, 4, 8): return ## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan dead_tids = self._get_thread_ids() dwProcessId = self.get_pid() hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD, dwProcessId) try: te = win32.Thread32First(hSnapshot) while te is not None: if te.th32OwnerProcessID == dwProcessId: dwThreadId = te.th32ThreadID if dwThreadId in dead_tids: dead_tids.remove(dwThreadId) ## if not self.has_thread(dwThreadId): # XXX triggers a scan if not self._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = self) self._add_thread(aThread) te = win32.Thread32Next(hSnapshot) finally: win32.CloseHandle(hSnapshot) for tid in dead_tids: self._del_thread(tid) def clear_dead_threads(self): """ Remove Thread objects from the snapshot referring to threads no longer running. """ for tid in self.get_thread_ids(): aThread = self.get_thread(tid) if not aThread.is_alive(): self._del_thread(aThread) def clear_threads(self): """ Clears the threads snapshot. """ for aThread in compat.itervalues(self.__threadDict): aThread.clear() self.__threadDict = dict() def close_thread_handles(self): """ Closes all open handles to threads in the snapshot. """ for aThread in self.iter_threads(): try: aThread.close_handle() except Exception: try: e = sys.exc_info()[1] msg = "Cannot close thread handle %s, reason: %s" msg %= (aThread.hThread.value, str(e)) warnings.warn(msg) except Exception: pass #------------------------------------------------------------------------------ # XXX _notify_* methods should not trigger a scan def _add_thread(self, aThread): """ Private method to add a thread object to the snapshot. @type aThread: L{Thread} @param aThread: Thread object. """ ## if not isinstance(aThread, Thread): ## if hasattr(aThread, '__class__'): ## typename = aThread.__class__.__name__ ## else: ## typename = str(type(aThread)) ## msg = "Expected Thread, got %s instead" % typename ## raise TypeError(msg) dwThreadId = aThread.dwThreadId ## if dwThreadId in self.__threadDict: ## msg = "Already have a Thread object with ID %d" % dwThreadId ## raise KeyError(msg) aThread.set_process(self) self.__threadDict[dwThreadId] = aThread def _del_thread(self, dwThreadId): """ Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID. """ try: aThread = self.__threadDict[dwThreadId] del self.__threadDict[dwThreadId] except KeyError: aThread = None msg = "Unknown thread ID %d" % dwThreadId warnings.warn(msg, RuntimeWarning) if aThread: aThread.clear() # remove circular references def _has_thread_id(self, dwThreadId): """ Private method to test for a thread in the snapshot without triggering an automatic scan. """ return dwThreadId in self.__threadDict def _get_thread_ids(self): """ Private method to get the list of thread IDs currently in the snapshot without triggering an automatic scan. """ return compat.keys(self.__threadDict) def __add_created_thread(self, event): """ Private method to automatically add new thread objects from debug events. @type event: L{Event} @param event: Event object. """ dwThreadId = event.get_tid() hThread = event.get_thread_handle() ## if not self.has_thread(dwThreadId): # XXX this would trigger a scan if not self._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, hThread, self) teb_ptr = event.get_teb() # remember the TEB pointer if teb_ptr: aThread._teb_ptr = teb_ptr self._add_thread(aThread) #else: # aThread = self.get_thread(dwThreadId) # if hThread != win32.INVALID_HANDLE_VALUE: # aThread.hThread = hThread # may have more privileges def _notify_create_process(self, event): """ Notify the creation of the main thread of this process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ self.__add_created_thread(event) return True def _notify_create_thread(self, event): """ Notify the creation of a new thread in this process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateThreadEvent} @param event: Create thread event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ self.__add_created_thread(event) return True def _notify_exit_thread(self, event): """ Notify the termination of a thread. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{ExitThreadEvent} @param event: Exit thread event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ dwThreadId = event.get_tid() ## if self.has_thread(dwThreadId): # XXX this would trigger a scan if self._has_thread_id(dwThreadId): self._del_thread(dwThreadId) return True
75,478
Python
34.469455
104
0.564019
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Acknowledgements: # Nicolas Economou, for his command line debugger on which this is inspired. # http://tinyurl.com/nicolaseconomou # Copyright (c) 2009-2014, Mario Vilas # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice,this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Interactive debugging console. @group Debugging: ConsoleDebugger @group Exceptions: CmdError """ from __future__ import with_statement __revision__ = "$Id$" __all__ = [ 'ConsoleDebugger', 'CmdError' ] # TODO document this module with docstrings. # TODO command to set a last error breakpoint. # TODO command to show available plugins. from winappdbg import win32 from winappdbg import compat from winappdbg.system import System from winappdbg.util import PathOperations from winappdbg.event import EventHandler, NoEvent from winappdbg.textio import HexInput, HexOutput, HexDump, CrashDump, DebugLog import os import sys import code import time import warnings import traceback # too many variables named "cmd" to have a module by the same name :P from cmd import Cmd # lazy imports readline = None #============================================================================== class DummyEvent (NoEvent): "Dummy event object used internally by L{ConsoleDebugger}." def get_pid(self): return self._pid def get_tid(self): return self._tid def get_process(self): return self._process def get_thread(self): return self._thread #============================================================================== class CmdError (Exception): """ Exception raised when a command parsing error occurs. Used internally by L{ConsoleDebugger}. """ #============================================================================== class ConsoleDebugger (Cmd, EventHandler): """ Interactive console debugger. @see: L{Debug.interactive} """ #------------------------------------------------------------------------------ # Class variables # Exception to raise when an error occurs executing a command. command_error_exception = CmdError # Milliseconds to wait for debug events in the main loop. dwMilliseconds = 100 # History file name. history_file = '.winappdbg_history' # Confirm before quitting? confirm_quit = True # Valid plugin name characters. valid_plugin_name_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXY' \ 'abcdefghijklmnopqrstuvwxy' \ '012345678' \ '_' # Names of the registers. segment_names = ('cs', 'ds', 'es', 'fs', 'gs') register_alias_64_to_32 = { 'eax':'Rax', 'ebx':'Rbx', 'ecx':'Rcx', 'edx':'Rdx', 'eip':'Rip', 'ebp':'Rbp', 'esp':'Rsp', 'esi':'Rsi', 'edi':'Rdi' } register_alias_64_to_16 = { 'ax':'Rax', 'bx':'Rbx', 'cx':'Rcx', 'dx':'Rdx' } register_alias_64_to_8_low = { 'al':'Rax', 'bl':'Rbx', 'cl':'Rcx', 'dl':'Rdx' } register_alias_64_to_8_high = { 'ah':'Rax', 'bh':'Rbx', 'ch':'Rcx', 'dh':'Rdx' } register_alias_32_to_16 = { 'ax':'Eax', 'bx':'Ebx', 'cx':'Ecx', 'dx':'Edx' } register_alias_32_to_8_low = { 'al':'Eax', 'bl':'Ebx', 'cl':'Ecx', 'dl':'Edx' } register_alias_32_to_8_high = { 'ah':'Eax', 'bh':'Ebx', 'ch':'Ecx', 'dh':'Edx' } register_aliases_full_32 = list(segment_names) register_aliases_full_32.extend(compat.iterkeys(register_alias_32_to_16)) register_aliases_full_32.extend(compat.iterkeys(register_alias_32_to_8_low)) register_aliases_full_32.extend(compat.iterkeys(register_alias_32_to_8_high)) register_aliases_full_32 = tuple(register_aliases_full_32) register_aliases_full_64 = list(segment_names) register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_32)) register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_16)) register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_8_low)) register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_8_high)) register_aliases_full_64 = tuple(register_aliases_full_64) # Names of the control flow instructions. 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 #------------------------------------------------------------------------------ # Instance variables def __init__(self): """ Interactive console debugger. @see: L{Debug.interactive} """ Cmd.__init__(self) EventHandler.__init__(self) # Quit the debugger when True. self.debuggerExit = False # Full path to the history file. self.history_file_full_path = None # Last executed command. self.__lastcmd = "" #------------------------------------------------------------------------------ # Debugger # Use this Debug object. def start_using_debugger(self, debug): # Clear the previous Debug object. self.stop_using_debugger() # Keep the Debug object. self.debug = debug # Set ourselves as the event handler for the debugger. self.prevHandler = debug.set_event_handler(self) # Stop using the Debug object given by start_using_debugger(). # Circular references must be removed, or the destructors never get called. def stop_using_debugger(self): if hasattr(self, 'debug'): debug = self.debug debug.set_event_handler(self.prevHandler) del self.prevHandler del self.debug return debug return None # Destroy the Debug object. def destroy_debugger(self, autodetach=True): debug = self.stop_using_debugger() if debug is not None: if not autodetach: debug.kill_all(bIgnoreExceptions=True) debug.lastEvent = None debug.stop() del debug @property def lastEvent(self): return self.debug.lastEvent def set_fake_last_event(self, process): if self.lastEvent is None: self.debug.lastEvent = DummyEvent(self.debug) self.debug.lastEvent._process = process self.debug.lastEvent._thread = process.get_thread( process.get_thread_ids()[0]) self.debug.lastEvent._pid = process.get_pid() self.debug.lastEvent._tid = self.lastEvent._thread.get_tid() #------------------------------------------------------------------------------ # Input # TODO # * try to guess breakpoints when insufficient data is given # * child Cmd instances will have to be used for other prompts, for example # when assembling or editing memory - it may also be a good idea to think # if it's possible to make the main Cmd instance also a child, instead of # the debugger itself - probably the same goes for the EventHandler, maybe # it can be used as a contained object rather than a parent class. # Join a token list into an argument string. def join_tokens(self, token_list): return self.debug.system.argv_to_cmdline(token_list) # Split an argument string into a token list. def split_tokens(self, arg, min_count=0, max_count=None): token_list = self.debug.system.cmdline_to_argv(arg) if len(token_list) < min_count: raise CmdError("missing parameters.") if max_count and len(token_list) > max_count: raise CmdError("too many parameters.") return token_list # Token is a thread ID or name. def input_thread(self, token): targets = self.input_thread_list([token]) if len(targets) == 0: raise CmdError("missing thread name or ID") if len(targets) > 1: msg = "more than one thread with that name:\n" for tid in targets: msg += "\t%d\n" % tid msg = msg[:-len("\n")] raise CmdError(msg) return targets[0] # Token list is a list of thread IDs or names. def input_thread_list(self, token_list): targets = set() system = self.debug.system for token in token_list: try: tid = self.input_integer(token) if not system.has_thread(tid): raise CmdError("thread not found (%d)" % tid) targets.add(tid) except ValueError: found = set() for process in system.iter_processes(): found.update(system.find_threads_by_name(token)) if not found: raise CmdError("thread not found (%s)" % token) for thread in found: targets.add(thread.get_tid()) targets = list(targets) targets.sort() return targets # Token is a process ID or name. def input_process(self, token): targets = self.input_process_list([token]) if len(targets) == 0: raise CmdError("missing process name or ID") if len(targets) > 1: msg = "more than one process with that name:\n" for pid in targets: msg += "\t%d\n" % pid msg = msg[:-len("\n")] raise CmdError(msg) return targets[0] # Token list is a list of process IDs or names. def input_process_list(self, token_list): targets = set() system = self.debug.system for token in token_list: try: pid = self.input_integer(token) if not system.has_process(pid): raise CmdError("process not found (%d)" % pid) targets.add(pid) except ValueError: found = system.find_processes_by_filename(token) if not found: raise CmdError("process not found (%s)" % token) for (process, _) in found: targets.add(process.get_pid()) targets = list(targets) targets.sort() return targets # Token is a command line to execute. def input_command_line(self, command_line): argv = self.debug.system.cmdline_to_argv(command_line) if not argv: raise CmdError("missing command line to execute") fname = argv[0] if not os.path.exists(fname): try: fname, _ = win32.SearchPath(None, fname, '.exe') except WindowsError: raise CmdError("file not found: %s" % fname) argv[0] = fname command_line = self.debug.system.argv_to_cmdline(argv) return command_line # Token is an integer. # Only hexadecimal format is supported. def input_hexadecimal_integer(self, token): return int(token, 0x10) # Token is an integer. # It can be in any supported format. def input_integer(self, token): return HexInput.integer(token) # # input_integer = input_hexadecimal_integer # Token is an address. # The address can be a integer, a label or a register. def input_address(self, token, pid=None, tid=None): address = None if self.is_register(token): if tid is None: if self.lastEvent is None or pid != self.lastEvent.get_pid(): msg = "can't resolve register (%s) for unknown thread" raise CmdError(msg % token) tid = self.lastEvent.get_tid() address = self.input_register(token, tid) if address is None: try: address = self.input_hexadecimal_integer(token) except ValueError: if pid is None: if self.lastEvent is None: raise CmdError("no current process set") process = self.lastEvent.get_process() elif self.lastEvent is not None and pid == self.lastEvent.get_pid(): process = self.lastEvent.get_process() else: try: process = self.debug.system.get_process(pid) except KeyError: raise CmdError("process not found (%d)" % pid) try: address = process.resolve_label(token) except Exception: raise CmdError("unknown address (%s)" % token) return address # Token is an address range, or a single address. # The addresses can be integers, labels or registers. def input_address_range(self, token_list, pid=None, tid=None): if len(token_list) == 2: token_1, token_2 = token_list address = self.input_address(token_1, pid, tid) try: size = self.input_integer(token_2) except ValueError: raise CmdError("bad address range: %s %s" % (token_1, token_2)) elif len(token_list) == 1: token = token_list[0] if '-' in token: try: token_1, token_2 = token.split('-') except Exception: raise CmdError("bad address range: %s" % token) address = self.input_address(token_1, pid, tid) size = self.input_address(token_2, pid, tid) - address else: address = self.input_address(token, pid, tid) size = None return address, size # XXX TODO # Support non-integer registers here. def is_register(self, token): if win32.arch == 'i386': if token in self.register_aliases_full_32: return True token = token.title() for (name, typ) in win32.CONTEXT._fields_: if name == token: return win32.sizeof(typ) == win32.sizeof(win32.DWORD) elif win32.arch == 'amd64': if token in self.register_aliases_full_64: return True token = token.title() for (name, typ) in win32.CONTEXT._fields_: if name == token: return win32.sizeof(typ) == win32.sizeof(win32.DWORD64) return False # The token is a register name. # Returns None if no register name is matched. def input_register(self, token, tid=None): if tid is None: if self.lastEvent is None: raise CmdError("no current process set") thread = self.lastEvent.get_thread() else: thread = self.debug.system.get_thread(tid) ctx = thread.get_context() token = token.lower() title = token.title() if title in ctx: return ctx.get(title) # eax -> Eax if ctx.arch == 'i386': if token in self.segment_names: return ctx.get('Seg%s' % title) # cs -> SegCs if token in self.register_alias_32_to_16: return ctx.get(self.register_alias_32_to_16[token]) & 0xFFFF if token in self.register_alias_32_to_8_low: return ctx.get(self.register_alias_32_to_8_low[token]) & 0xFF if token in self.register_alias_32_to_8_high: return (ctx.get(self.register_alias_32_to_8_high[token]) & 0xFF00) >> 8 elif ctx.arch == 'amd64': if token in self.segment_names: return ctx.get('Seg%s' % title) # cs -> SegCs if token in self.register_alias_64_to_32: return ctx.get(self.register_alias_64_to_32[token]) & 0xFFFFFFFF if token in self.register_alias_64_to_16: return ctx.get(self.register_alias_64_to_16[token]) & 0xFFFF if token in self.register_alias_64_to_8_low: return ctx.get(self.register_alias_64_to_8_low[token]) & 0xFF if token in self.register_alias_64_to_8_high: return (ctx.get(self.register_alias_64_to_8_high[token]) & 0xFF00) >> 8 return None # Token list contains an address or address range. # The prefix is also parsed looking for process and thread IDs. def input_full_address_range(self, token_list): pid, tid = self.get_process_and_thread_ids_from_prefix() address, size = self.input_address_range(token_list, pid, tid) return pid, tid, address, size # Token list contains a breakpoint. def input_breakpoint(self, token_list): pid, tid, address, size = self.input_full_address_range(token_list) if not self.debug.is_debugee(pid): raise CmdError("target process is not being debugged") return pid, tid, address, size # Token list contains a memory address, and optional size and process. # Sets the results as the default for the next display command. def input_display(self, token_list, default_size=64): pid, tid, address, size = self.input_full_address_range(token_list) if not size: size = default_size next_address = HexOutput.integer(address + size) self.default_display_target = next_address return pid, tid, address, size #------------------------------------------------------------------------------ # Output # Tell the user a module was loaded. def print_module_load(self, event): mod = event.get_module() base = mod.get_base() name = mod.get_filename() if not name: name = '' msg = "Loaded module (%s) %s" msg = msg % (HexDump.address(base), name) print(msg) # Tell the user a module was unloaded. def print_module_unload(self, event): mod = event.get_module() base = mod.get_base() name = mod.get_filename() if not name: name = '' msg = "Unloaded module (%s) %s" msg = msg % (HexDump.address(base), name) print(msg) # Tell the user a process was started. def print_process_start(self, event): pid = event.get_pid() start = event.get_start_address() if start: start = HexOutput.address(start) print("Started process %d at %s" % (pid, start)) else: print("Attached to process %d" % pid) # Tell the user a thread was started. def print_thread_start(self, event): tid = event.get_tid() start = event.get_start_address() if start: with warnings.catch_warnings(): warnings.simplefilter("ignore") start = event.get_process().get_label_at_address(start) print("Started thread %d at %s" % (tid, start)) else: print("Attached to thread %d" % tid) # Tell the user a process has finished. def print_process_end(self, event): pid = event.get_pid() code = event.get_exit_code() print("Process %d terminated, exit code %d" % (pid, code)) # Tell the user a thread has finished. def print_thread_end(self, event): tid = event.get_tid() code = event.get_exit_code() print("Thread %d terminated, exit code %d" % (tid, code)) # Print(debug strings. def print_debug_string(self, event): tid = event.get_tid() string = event.get_debug_string() print("Thread %d says: %r" % (tid, string)) # Inform the user of any other debugging event. def print_event(self, event): code = HexDump.integer(event.get_event_code()) name = event.get_event_name() desc = event.get_event_description() if code in desc: print('') print("%s: %s" % (name, desc)) else: print('') print("%s (%s): %s" % (name, code, desc)) self.print_event_location(event) # Stop on exceptions and prompt for commands. def print_exception(self, event): address = HexDump.address(event.get_exception_address()) code = HexDump.integer(event.get_exception_code()) desc = event.get_exception_description() if event.is_first_chance(): chance = 'first' else: chance = 'second' if code in desc: msg = "%s at address %s (%s chance)" % (desc, address, chance) else: msg = "%s (%s) at address %s (%s chance)" % (desc, code, address, chance) print('') print(msg) self.print_event_location(event) # Show the current location in the code. def print_event_location(self, event): process = event.get_process() thread = event.get_thread() self.print_current_location(process, thread) # Show the current location in the code. def print_breakpoint_location(self, event): process = event.get_process() thread = event.get_thread() pc = event.get_exception_address() self.print_current_location(process, thread, pc) # Show the current location in any process and thread. def print_current_location(self, process=None, thread=None, pc=None): if not process: if self.lastEvent is None: raise CmdError("no current process set") process = self.lastEvent.get_process() if not thread: if self.lastEvent is None: raise CmdError("no current process set") thread = self.lastEvent.get_thread() thread.suspend() try: if pc is None: pc = thread.get_pc() ctx = thread.get_context() finally: thread.resume() label = process.get_label_at_address(pc) try: disasm = process.disassemble(pc, 15) except WindowsError: disasm = None except NotImplementedError: disasm = None print('') print(CrashDump.dump_registers(ctx),) print("%s:" % label) if disasm: print(CrashDump.dump_code_line(disasm[0], pc, bShowDump=True)) else: try: data = process.peek(pc, 15) except Exception: data = None if data: print('%s: %s' % (HexDump.address(pc), HexDump.hexblock_byte(data))) else: print('%s: ???' % HexDump.address(pc)) # Display memory contents using a given method. def print_memory_display(self, arg, method): if not arg: arg = self.default_display_target token_list = self.split_tokens(arg, 1, 2) pid, tid, address, size = self.input_display(token_list) label = self.get_process(pid).get_label_at_address(address) data = self.read_memory(address, size, pid) if data: print("%s:" % label) print(method(data, address),) #------------------------------------------------------------------------------ # Debugging # Get the process ID from the prefix or the last event. def get_process_id_from_prefix(self): if self.cmdprefix: pid = self.input_process(self.cmdprefix) else: if self.lastEvent is None: raise CmdError("no current process set") pid = self.lastEvent.get_pid() return pid # Get the thread ID from the prefix or the last event. def get_thread_id_from_prefix(self): if self.cmdprefix: tid = self.input_thread(self.cmdprefix) else: if self.lastEvent is None: raise CmdError("no current process set") tid = self.lastEvent.get_tid() return tid # Get the process from the prefix or the last event. def get_process_from_prefix(self): pid = self.get_process_id_from_prefix() return self.get_process(pid) # Get the thread from the prefix or the last event. def get_thread_from_prefix(self): tid = self.get_thread_id_from_prefix() return self.get_thread(tid) # Get the process and thread IDs from the prefix or the last event. def get_process_and_thread_ids_from_prefix(self): if self.cmdprefix: try: pid = self.input_process(self.cmdprefix) tid = None except CmdError: try: tid = self.input_thread(self.cmdprefix) pid = self.debug.system.get_thread(tid).get_pid() except CmdError: msg = "unknown process or thread (%s)" % self.cmdprefix raise CmdError(msg) else: if self.lastEvent is None: raise CmdError("no current process set") pid = self.lastEvent.get_pid() tid = self.lastEvent.get_tid() return pid, tid # Get the process and thread from the prefix or the last event. def get_process_and_thread_from_prefix(self): pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(pid) thread = self.get_thread(tid) return process, thread # Get the process object. def get_process(self, pid=None): if pid is None: if self.lastEvent is None: raise CmdError("no current process set") process = self.lastEvent.get_process() elif self.lastEvent is not None and pid == self.lastEvent.get_pid(): process = self.lastEvent.get_process() else: try: process = self.debug.system.get_process(pid) except KeyError: raise CmdError("process not found (%d)" % pid) return process # Get the thread object. def get_thread(self, tid=None): if tid is None: if self.lastEvent is None: raise CmdError("no current process set") thread = self.lastEvent.get_thread() elif self.lastEvent is not None and tid == self.lastEvent.get_tid(): thread = self.lastEvent.get_thread() else: try: thread = self.debug.system.get_thread(tid) except KeyError: raise CmdError("thread not found (%d)" % tid) return thread # Read the process memory. def read_memory(self, address, size, pid=None): process = self.get_process(pid) try: data = process.peek(address, size) except WindowsError: orig_address = HexOutput.integer(address) next_address = HexOutput.integer(address + size) msg = "error reading process %d, from %s to %s (%d bytes)" msg = msg % (pid, orig_address, next_address, size) raise CmdError(msg) return data # Write the process memory. def write_memory(self, address, data, pid=None): process = self.get_process(pid) try: process.write(address, data) except WindowsError: size = len(data) orig_address = HexOutput.integer(address) next_address = HexOutput.integer(address + size) msg = "error reading process %d, from %s to %s (%d bytes)" msg = msg % (pid, orig_address, next_address, size) raise CmdError(msg) # Change a register value. def change_register(self, register, value, tid=None): # Get the thread. if tid is None: if self.lastEvent is None: raise CmdError("no current process set") thread = self.lastEvent.get_thread() else: try: thread = self.debug.system.get_thread(tid) except KeyError: raise CmdError("thread not found (%d)" % tid) # Convert the value to integer type. try: value = self.input_integer(value) except ValueError: pid = thread.get_pid() value = self.input_address(value, pid, tid) # Suspend the thread. # The finally clause ensures the thread is resumed before returning. thread.suspend() try: # Get the current context. ctx = thread.get_context() # Register name matching is case insensitive. register = register.lower() # Integer 32 bits registers. if register in self.register_names: register = register.title() # eax -> Eax # Segment (16 bit) registers. if register in self.segment_names: register = 'Seg%s' % register.title() # cs -> SegCs value = value & 0x0000FFFF # Integer 16 bits registers. if register in self.register_alias_16: register = self.register_alias_16[register] previous = ctx.get(register) & 0xFFFF0000 value = (value & 0x0000FFFF) | previous # Integer 8 bits registers (low part). if register in self.register_alias_8_low: register = self.register_alias_8_low[register] previous = ctx.get(register) % 0xFFFFFF00 value = (value & 0x000000FF) | previous # Integer 8 bits registers (high part). if register in self.register_alias_8_high: register = self.register_alias_8_high[register] previous = ctx.get(register) % 0xFFFF00FF value = ((value & 0x000000FF) << 8) | previous # Set the new context. ctx.__setitem__(register, value) thread.set_context(ctx) # Resume the thread. finally: thread.resume() # Very crude way to find data within the process memory. # TODO: Perhaps pfind.py can be integrated here instead. def find_in_memory(self, query, process): for mbi in process.get_memory_map(): if mbi.State != win32.MEM_COMMIT or mbi.Protect & win32.PAGE_GUARD: continue address = mbi.BaseAddress size = mbi.RegionSize try: data = process.read(address, size) except WindowsError: msg = "*** Warning: read error at address %s" msg = msg % HexDump.address(address) print(msg) width = min(len(query), 16) p = data.find(query) while p >= 0: q = p + len(query) d = data[ p: min(q, p + width) ] h = HexDump.hexline(d, width=width) a = HexDump.address(address + p) print("%s: %s" % (a, h)) p = data.find(query, q) # Kill a process. def kill_process(self, pid): process = self.debug.system.get_process(pid) try: process.kill() if self.debug.is_debugee(pid): self.debug.detach(pid) print("Killed process (%d)" % pid) except Exception: print("Error trying to kill process (%d)" % pid) # Kill a thread. def kill_thread(self, tid): thread = self.debug.system.get_thread(tid) try: thread.kill() process = thread.get_process() pid = process.get_pid() if self.debug.is_debugee(pid) and not process.is_alive(): self.debug.detach(pid) print("Killed thread (%d)" % tid) except Exception: print("Error trying to kill thread (%d)" % tid) #------------------------------------------------------------------------------ # Command prompt input # Prompt the user for commands. def prompt_user(self): while not self.debuggerExit: try: self.cmdloop() break except CmdError: e = sys.exc_info()[1] print("*** Error: %s" % str(e)) except Exception: traceback.print_exc() # # self.debuggerExit = True # Prompt the user for a YES/NO kind of question. def ask_user(self, msg, prompt="Are you sure? (y/N): "): print(msg) answer = raw_input(prompt) answer = answer.strip()[:1].lower() return answer == 'y' # Autocomplete the given command when not ambiguous. # Convert it to lowercase (so commands are seen as case insensitive). def autocomplete(self, cmd): cmd = cmd.lower() completed = self.completenames(cmd) if len(completed) == 1: cmd = completed[0] return cmd # Get the help text for the given list of command methods. # Note it's NOT a list of commands, but a list of actual method names. # Each line of text is stripped and all lines are sorted. # Repeated text lines are removed. # Returns a single, possibly multiline, string. def get_help(self, commands): msg = set() for name in commands: if name != 'do_help': try: doc = getattr(self, name).__doc__.split('\n') except Exception: return ("No help available when Python" " is run with the -OO switch.") for x in doc: x = x.strip() if x: msg.add(' %s' % x) msg = list(msg) msg.sort() msg = '\n'.join(msg) return msg # Parse the prefix and remove it from the command line. def split_prefix(self, line): prefix = None if line.startswith('~'): pos = line.find(' ') if pos == 1: pos = line.find(' ', pos + 1) if not pos < 0: prefix = line[ 1: pos ].strip() line = line[ pos: ].strip() return prefix, line #------------------------------------------------------------------------------ # Cmd() hacks # Header for help page. doc_header = 'Available commands (type help * or help <command>)' # # # Read and write directly to stdin and stdout. # # # This prevents the use of raw_input and print. # # use_rawinput = False @property def prompt(self): if self.lastEvent: pid = self.lastEvent.get_pid() tid = self.lastEvent.get_tid() if self.debug.is_debugee(pid): # # return '~%d(%d)> ' % (tid, pid) return '%d:%d> ' % (pid, tid) return '> ' # Return a sorted list of method names. # Only returns the methods that implement commands. def get_names(self): names = Cmd.get_names(self) names = [ x for x in set(names) if x.startswith('do_') ] names.sort() return names # Automatically autocomplete commands, even if Tab wasn't pressed. # The prefix is removed from the line and stored in self.cmdprefix. # Also implement the commands that consist of a symbol character. def parseline(self, line): self.cmdprefix, line = self.split_prefix(line) line = line.strip() if line: if line[0] == '.': line = 'plugin ' + line[1:] elif line[0] == '#': line = 'python ' + line[1:] cmd, arg, line = Cmd.parseline(self, line) if cmd: cmd = self.autocomplete(cmd) return cmd, arg, line # # # Don't repeat the last executed command. # # def emptyline(self): # # pass # Reset the defaults for some commands. def preloop(self): self.default_disasm_target = 'eip' self.default_display_target = 'eip' self.last_display_command = self.do_db # Put the prefix back in the command line. def get_lastcmd(self): return self.__lastcmd def set_lastcmd(self, lastcmd): if self.cmdprefix: lastcmd = '~%s %s' % (self.cmdprefix, lastcmd) self.__lastcmd = lastcmd lastcmd = property(get_lastcmd, set_lastcmd) # Quit the command prompt if the debuggerExit flag is on. def postcmd(self, stop, line): return stop or self.debuggerExit #------------------------------------------------------------------------------ # Commands # Each command contains a docstring with it's help text. # The help text consist of independent text lines, # where each line shows a command and it's parameters. # Each command method has the help message for itself and all it's aliases. # Only the docstring for the "help" command is shown as-is. # NOTE: Command methods MUST be all lowercase! # Extended help command. def do_help(self, arg): """ ? - show the list of available commands ? * - show help for all commands ? <command> [command...] - show help for the given command(s) help - show the list of available commands help * - show help for all commands help <command> [command...] - show help for the given command(s) """ if not arg: Cmd.do_help(self, arg) elif arg in ('?', 'help'): # An easter egg :) print(" Help! I need somebody...") print(" Help! Not just anybody...") print(" Help! You know, I need someone...") print(" Heeelp!") else: if arg == '*': commands = self.get_names() commands = [ x for x in commands if x.startswith('do_') ] else: commands = set() for x in arg.split(' '): x = x.strip() if x: for n in self.completenames(x): commands.add('do_%s' % n) commands = list(commands) commands.sort() print(self.get_help(commands)) def do_shell(self, arg): """ ! - spawn a system shell shell - spawn a system shell ! <command> [arguments...] - execute a single shell command shell <command> [arguments...] - execute a single shell command """ if self.cmdprefix: raise CmdError("prefix not allowed") # Try to use the environment to locate cmd.exe. # If not found, it's usually OK to just use the filename, # since cmd.exe is one of those "magic" programs that # can be automatically found by CreateProcess. shell = os.getenv('ComSpec', 'cmd.exe') # When given a command, run it and return. # When no command is given, spawn a shell. if arg: arg = '%s /c %s' % (shell, arg) else: arg = shell process = self.debug.system.start_process(arg, bConsole=True) process.wait() # This hack fixes a bug in Python, the interpreter console is closing the # stdin pipe when calling the exit() function (Ctrl+Z seems to work fine). class _PythonExit(object): def __repr__(self): return "Use exit() or Ctrl-Z plus Return to exit" def __call__(self): raise SystemExit() _python_exit = _PythonExit() # Spawns a Python shell with some handy local variables and the winappdbg # module already imported. Also the console banner is improved. def _spawn_python_shell(self, arg): import winappdbg banner = ('Python %s on %s\nType "help", "copyright", ' '"credits" or "license" for more information.\n') platform = winappdbg.version.lower() platform = 'WinAppDbg %s' % platform banner = banner % (sys.version, platform) local = {} local.update(__builtins__) local.update({ '__name__': '__console__', '__doc__': None, 'exit': self._python_exit, 'self': self, 'arg': arg, 'winappdbg': winappdbg, }) try: code.interact(banner=banner, local=local) except SystemExit: # We need to catch it so it doesn't kill our program. pass def do_python(self, arg): """ # - spawn a python interpreter python - spawn a python interpreter # <statement> - execute a single python statement python <statement> - execute a single python statement """ if self.cmdprefix: raise CmdError("prefix not allowed") # When given a Python statement, execute it directly. if arg: try: compat.exec_(arg, globals(), locals()) except Exception: traceback.print_exc() # When no statement is given, spawn a Python interpreter. else: try: self._spawn_python_shell(arg) except Exception: e = sys.exc_info()[1] raise CmdError( "unhandled exception when running Python console: %s" % e) def do_quit(self, arg): """ quit - close the debugging session q - close the debugging session """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.confirm_quit: count = self.debug.get_debugee_count() if count > 0: if count == 1: msg = "There's a program still running." else: msg = "There are %s programs still running." % count if not self.ask_user(msg): return False self.debuggerExit = True return True do_q = do_quit def do_attach(self, arg): """ attach <target> [target...] - attach to the given process(es) """ if self.cmdprefix: raise CmdError("prefix not allowed") targets = self.input_process_list(self.split_tokens(arg, 1)) if not targets: print("Error: missing parameters") else: debug = self.debug for pid in targets: try: debug.attach(pid) print("Attached to process (%d)" % pid) except Exception: print("Error: can't attach to process (%d)" % pid) def do_detach(self, arg): """ [~process] detach - detach from the current process detach - detach from the current process detach <target> [target...] - detach from the given process(es) """ debug = self.debug token_list = self.split_tokens(arg) if self.cmdprefix: token_list.insert(0, self.cmdprefix) targets = self.input_process_list(token_list) if not targets: if self.lastEvent is None: raise CmdError("no current process set") targets = [ self.lastEvent.get_pid() ] for pid in targets: try: debug.detach(pid) print("Detached from process (%d)" % pid) except Exception: print("Error: can't detach from process (%d)" % pid) def do_windowed(self, arg): """ windowed <target> [arguments...] - run a windowed program for debugging """ if self.cmdprefix: raise CmdError("prefix not allowed") cmdline = self.input_command_line(arg) try: process = self.debug.execl(arg, bConsole=False, bFollow=self.options.follow) print("Spawned process (%d)" % process.get_pid()) except Exception: raise CmdError("can't execute") self.set_fake_last_event(process) def do_console(self, arg): """ console <target> [arguments...] - run a console program for debugging """ if self.cmdprefix: raise CmdError("prefix not allowed") cmdline = self.input_command_line(arg) try: process = self.debug.execl(arg, bConsole=True, bFollow=self.options.follow) print("Spawned process (%d)" % process.get_pid()) except Exception: raise CmdError("can't execute") self.set_fake_last_event(process) def do_continue(self, arg): """ continue - continue execution g - continue execution go - continue execution """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.debug.get_debugee_count() > 0: return True do_g = do_continue do_go = do_continue def do_gh(self, arg): """ gh - go with exception handled """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.lastEvent: self.lastEvent.continueStatus = win32.DBG_EXCEPTION_HANDLED return self.do_go(arg) def do_gn(self, arg): """ gn - go with exception not handled """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.lastEvent: self.lastEvent.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED return self.do_go(arg) def do_refresh(self, arg): """ refresh - refresh the list of running processes and threads [~process] refresh - refresh the list of running threads """ if arg: raise CmdError("too many arguments") if self.cmdprefix: process = self.get_process_from_prefix() process.scan() else: self.debug.system.scan() def do_processlist(self, arg): """ pl - show the processes being debugged processlist - show the processes being debugged """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") system = self.debug.system pid_list = self.debug.get_debugee_pids() if pid_list: print("Process ID File name") for pid in pid_list: if pid == 0: filename = "System Idle Process" elif pid == 4: filename = "System" else: filename = system.get_process(pid).get_filename() filename = PathOperations.pathname_to_filename(filename) print("%-12d %s" % (pid, filename)) do_pl = do_processlist def do_threadlist(self, arg): """ tl - show the threads being debugged threadlist - show the threads being debugged """ if arg: raise CmdError("too many arguments") if self.cmdprefix: process = self.get_process_from_prefix() for thread in process.iter_threads(): tid = thread.get_tid() name = thread.get_name() print("%-12d %s" % (tid, name)) else: system = self.debug.system pid_list = self.debug.get_debugee_pids() if pid_list: print("Thread ID Thread name") for pid in pid_list: process = system.get_process(pid) for thread in process.iter_threads(): tid = thread.get_tid() name = thread.get_name() print("%-12d %s" % (tid, name)) do_tl = do_threadlist def do_kill(self, arg): """ [~process] kill - kill a process [~thread] kill - kill a thread kill - kill the current process kill * - kill all debugged processes kill <processes and/or threads...> - kill the given processes and threads """ if arg: if arg == '*': target_pids = self.debug.get_debugee_pids() target_tids = list() else: target_pids = set() target_tids = set() if self.cmdprefix: pid, tid = self.get_process_and_thread_ids_from_prefix() if tid is None: target_tids.add(tid) else: target_pids.add(pid) for token in self.split_tokens(arg): try: pid = self.input_process(token) target_pids.add(pid) except CmdError: try: tid = self.input_process(token) target_pids.add(pid) except CmdError: msg = "unknown process or thread (%s)" % token raise CmdError(msg) target_pids = list(target_pids) target_tids = list(target_tids) target_pids.sort() target_tids.sort() msg = "You are about to kill %d processes and %d threads." msg = msg % (len(target_pids), len(target_tids)) if self.ask_user(msg): for pid in target_pids: self.kill_process(pid) for tid in target_tids: self.kill_thread(tid) else: if self.cmdprefix: pid, tid = self.get_process_and_thread_ids_from_prefix() if tid is None: if self.lastEvent is not None and pid == self.lastEvent.get_pid(): msg = "You are about to kill the current process." else: msg = "You are about to kill process %d." % pid if self.ask_user(msg): self.kill_process(pid) else: if self.lastEvent is not None and tid == self.lastEvent.get_tid(): msg = "You are about to kill the current thread." else: msg = "You are about to kill thread %d." % tid if self.ask_user(msg): self.kill_thread(tid) else: if self.lastEvent is None: raise CmdError("no current process set") pid = self.lastEvent.get_pid() if self.ask_user("You are about to kill the current process."): self.kill_process(pid) # TODO: create hidden threads using undocumented API calls. def do_modload(self, arg): """ [~process] modload <filename.dll> - load a DLL module """ filename = self.split_tokens(arg, 1, 1)[0] process = self.get_process_from_prefix() try: process.inject_dll(filename, bWait=False) except RuntimeError: print("Can't inject module: %r" % filename) # TODO: modunload def do_stack(self, arg): """ [~thread] k - show the stack trace [~thread] stack - show the stack trace """ if arg: # XXX TODO add depth parameter raise CmdError("too many arguments") pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(pid) thread = process.get_thread(tid) try: stack_trace = thread.get_stack_trace_with_labels() if stack_trace: print(CrashDump.dump_stack_trace_with_labels(stack_trace),) else: print("No stack trace available for thread (%d)" % tid) except WindowsError: print("Can't get stack trace for thread (%d)" % tid) do_k = do_stack def do_break(self, arg): """ break - force a debug break in all debugees break <process> [process...] - force a debug break """ debug = self.debug system = debug.system targets = self.input_process_list(self.split_tokens(arg)) if not targets: targets = debug.get_debugee_pids() targets.sort() if self.lastEvent: current = self.lastEvent.get_pid() else: current = None for pid in targets: if pid != current and debug.is_debugee(pid): process = system.get_process(pid) try: process.debug_break() except WindowsError: print("Can't force a debug break on process (%d)") def do_step(self, arg): """ p - step on the current assembly instruction next - step on the current assembly instruction step - step on the current assembly instruction """ if self.cmdprefix: raise CmdError("prefix not allowed") if self.lastEvent is None: raise CmdError("no current process set") if arg: # XXX this check is to be removed raise CmdError("too many arguments") pid = self.lastEvent.get_pid() thread = self.lastEvent.get_thread() pc = thread.get_pc() code = thread.disassemble(pc, 16)[0] size = code[1] opcode = code[2].lower() if ' ' in opcode: opcode = opcode[: opcode.find(' ') ] if opcode in self.jump_instructions or opcode in ('int', 'ret', 'retn'): return self.do_trace(arg) address = pc + size # # print(hex(pc), hex(address), size # XXX DEBUG self.debug.stalk_at(pid, address) return True do_p = do_step do_next = do_step def do_trace(self, arg): """ t - trace at the current assembly instruction trace - trace at the current assembly instruction """ if arg: # XXX this check is to be removed raise CmdError("too many arguments") if self.lastEvent is None: raise CmdError("no current thread set") self.lastEvent.get_thread().set_tf() return True do_t = do_trace def do_bp(self, arg): """ [~process] bp <address> - set a code breakpoint """ pid = self.get_process_id_from_prefix() if not self.debug.is_debugee(pid): raise CmdError("target process is not being debugged") process = self.get_process(pid) token_list = self.split_tokens(arg, 1, 1) try: address = self.input_address(token_list[0], pid) deferred = False except Exception: address = token_list[0] deferred = True if not address: address = token_list[0] deferred = True self.debug.break_at(pid, address) if deferred: print("Deferred breakpoint set at %s" % address) else: print("Breakpoint set at %s" % address) def do_ba(self, arg): """ [~thread] ba <a|w|e> <1|2|4|8> <address> - set hardware breakpoint """ debug = self.debug thread = self.get_thread_from_prefix() pid = thread.get_pid() tid = thread.get_tid() if not debug.is_debugee(pid): raise CmdError("target thread is not being debugged") token_list = self.split_tokens(arg, 3, 3) access = token_list[0].lower() size = token_list[1] address = token_list[2] if access == 'a': access = debug.BP_BREAK_ON_ACCESS elif access == 'w': access = debug.BP_BREAK_ON_WRITE elif access == 'e': access = debug.BP_BREAK_ON_EXECUTION else: raise CmdError("bad access type: %s" % token_list[0]) if size == '1': size = debug.BP_WATCH_BYTE elif size == '2': size = debug.BP_WATCH_WORD elif size == '4': size = debug.BP_WATCH_DWORD elif size == '8': size = debug.BP_WATCH_QWORD else: raise CmdError("bad breakpoint size: %s" % size) thread = self.get_thread_from_prefix() tid = thread.get_tid() pid = thread.get_pid() if not debug.is_debugee(pid): raise CmdError("target process is not being debugged") address = self.input_address(address, pid) if debug.has_hardware_breakpoint(tid, address): debug.erase_hardware_breakpoint(tid, address) debug.define_hardware_breakpoint(tid, address, access, size) debug.enable_hardware_breakpoint(tid, address) def do_bm(self, arg): """ [~process] bm <address-address> - set memory breakpoint """ pid = self.get_process_id_from_prefix() if not self.debug.is_debugee(pid): raise CmdError("target process is not being debugged") process = self.get_process(pid) token_list = self.split_tokens(arg, 1, 2) address, size = self.input_address_range(token_list[0], pid) self.debug.watch_buffer(pid, address, size) def do_bl(self, arg): """ bl - list the breakpoints for the current process bl * - list the breakpoints for all processes [~process] bl - list the breakpoints for the given process bl <process> [process...] - list the breakpoints for each given process """ debug = self.debug if arg == '*': if self.cmdprefix: raise CmdError("prefix not supported") breakpoints = debug.get_debugee_pids() else: targets = self.input_process_list(self.split_tokens(arg)) if self.cmdprefix: targets.insert(0, self.input_process(self.cmdprefix)) if not targets: if self.lastEvent is None: raise CmdError("no current process is set") targets = [ self.lastEvent.get_pid() ] for pid in targets: bplist = debug.get_process_code_breakpoints(pid) printed_process_banner = False if bplist: if not printed_process_banner: print("Process %d:" % pid) printed_process_banner = True for bp in bplist: address = repr(bp)[1:-1].replace('remote address ', '') print(" %s" % address) dbplist = debug.get_process_deferred_code_breakpoints(pid) if dbplist: if not printed_process_banner: print("Process %d:" % pid) printed_process_banner = True for (label, action, oneshot) in dbplist: if oneshot: address = " Deferred unconditional one-shot" \ " code breakpoint at %s" else: address = " Deferred unconditional" \ " code breakpoint at %s" address = address % label print(" %s" % address) bplist = debug.get_process_page_breakpoints(pid) if bplist: if not printed_process_banner: print("Process %d:" % pid) printed_process_banner = True for bp in bplist: address = repr(bp)[1:-1].replace('remote address ', '') print(" %s" % address) for tid in debug.system.get_process(pid).iter_thread_ids(): bplist = debug.get_thread_hardware_breakpoints(tid) if bplist: print("Thread %d:" % tid) for bp in bplist: address = repr(bp)[1:-1].replace('remote address ', '') print(" %s" % address) def do_bo(self, arg): """ [~process] bo <address> - make a code breakpoint one-shot [~thread] bo <address> - make a hardware breakpoint one-shot [~process] bo <address-address> - make a memory breakpoint one-shot [~process] bo <address> <size> - make a memory breakpoint one-shot """ token_list = self.split_tokens(arg, 1, 2) pid, tid, address, size = self.input_breakpoint(token_list) debug = self.debug found = False if size is None: if tid is not None: if debug.has_hardware_breakpoint(tid, address): debug.enable_one_shot_hardware_breakpoint(tid, address) found = True if pid is not None: if debug.has_code_breakpoint(pid, address): debug.enable_one_shot_code_breakpoint(pid, address) found = True else: if debug.has_page_breakpoint(pid, address): debug.enable_one_shot_page_breakpoint(pid, address) found = True if not found: print("Error: breakpoint not found.") def do_be(self, arg): """ [~process] be <address> - enable a code breakpoint [~thread] be <address> - enable a hardware breakpoint [~process] be <address-address> - enable a memory breakpoint [~process] be <address> <size> - enable a memory breakpoint """ token_list = self.split_tokens(arg, 1, 2) pid, tid, address, size = self.input_breakpoint(token_list) debug = self.debug found = False if size is None: if tid is not None: if debug.has_hardware_breakpoint(tid, address): debug.enable_hardware_breakpoint(tid, address) found = True if pid is not None: if debug.has_code_breakpoint(pid, address): debug.enable_code_breakpoint(pid, address) found = True else: if debug.has_page_breakpoint(pid, address): debug.enable_page_breakpoint(pid, address) found = True if not found: print("Error: breakpoint not found.") def do_bd(self, arg): """ [~process] bd <address> - disable a code breakpoint [~thread] bd <address> - disable a hardware breakpoint [~process] bd <address-address> - disable a memory breakpoint [~process] bd <address> <size> - disable a memory breakpoint """ token_list = self.split_tokens(arg, 1, 2) pid, tid, address, size = self.input_breakpoint(token_list) debug = self.debug found = False if size is None: if tid is not None: if debug.has_hardware_breakpoint(tid, address): debug.disable_hardware_breakpoint(tid, address) found = True if pid is not None: if debug.has_code_breakpoint(pid, address): debug.disable_code_breakpoint(pid, address) found = True else: if debug.has_page_breakpoint(pid, address): debug.disable_page_breakpoint(pid, address) found = True if not found: print("Error: breakpoint not found.") def do_bc(self, arg): """ [~process] bc <address> - clear a code breakpoint [~thread] bc <address> - clear a hardware breakpoint [~process] bc <address-address> - clear a memory breakpoint [~process] bc <address> <size> - clear a memory breakpoint """ token_list = self.split_tokens(arg, 1, 2) pid, tid, address, size = self.input_breakpoint(token_list) debug = self.debug found = False if size is None: if tid is not None: if debug.has_hardware_breakpoint(tid, address): debug.dont_watch_variable(tid, address) found = True if pid is not None: if debug.has_code_breakpoint(pid, address): debug.dont_break_at(pid, address) found = True else: if debug.has_page_breakpoint(pid, address): debug.dont_watch_buffer(pid, address, size) found = True if not found: print("Error: breakpoint not found.") def do_disassemble(self, arg): """ [~thread] u [register] - show code disassembly [~process] u [address] - show code disassembly [~thread] disassemble [register] - show code disassembly [~process] disassemble [address] - show code disassembly """ if not arg: arg = self.default_disasm_target token_list = self.split_tokens(arg, 1, 1) pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(pid) address = self.input_address(token_list[0], pid, tid) try: code = process.disassemble(address, 15 * 8)[:8] except Exception: msg = "can't disassemble address %s" msg = msg % HexDump.address(address) raise CmdError(msg) if code: label = process.get_label_at_address(address) last_code = code[-1] next_address = last_code[0] + last_code[1] next_address = HexOutput.integer(next_address) self.default_disasm_target = next_address print("%s:" % label) # # print(CrashDump.dump_code(code)) for line in code: print(CrashDump.dump_code_line(line, bShowDump=False)) do_u = do_disassemble def do_search(self, arg): """ [~process] s [address-address] <search string> [~process] search [address-address] <search string> """ token_list = self.split_tokens(arg, 1, 3) pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(pid) if len(token_list) == 1: pattern = token_list[0] minAddr = None maxAddr = None else: pattern = token_list[-1] addr, size = self.input_address_range(token_list[:-1], pid, tid) minAddr = addr maxAddr = addr + size iter = process.search_bytes(pattern) if process.get_bits() == 32: addr_width = 8 else: addr_width = 16 # TODO: need a prettier output here! for addr in iter: print(HexDump.address(addr, addr_width)) do_s = do_search def do_searchhex(self, arg): """ [~process] sh [address-address] <hexadecimal pattern> [~process] searchhex [address-address] <hexadecimal pattern> """ token_list = self.split_tokens(arg, 1, 3) pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(pid) if len(token_list) == 1: pattern = token_list[0] minAddr = None maxAddr = None else: pattern = token_list[-1] addr, size = self.input_address_range(token_list[:-1], pid, tid) minAddr = addr maxAddr = addr + size iter = process.search_hexa(pattern) if process.get_bits() == 32: addr_width = 8 else: addr_width = 16 for addr, bytes in iter: print(HexDump.hexblock(bytes, addr, addr_width),) do_sh = do_searchhex # # def do_strings(self, arg): # # """ # # [~process] strings - extract ASCII strings from memory # # """ # # if arg: # # raise CmdError("too many arguments") # # pid, tid = self.get_process_and_thread_ids_from_prefix() # # process = self.get_process(pid) # # for addr, size, data in process.strings(): # # print("%s: %r" % (HexDump.address(addr), data) def do_d(self, arg): """ [~thread] d <register> - show memory contents [~thread] d <register-register> - show memory contents [~thread] d <register> <size> - show memory contents [~process] d <address> - show memory contents [~process] d <address-address> - show memory contents [~process] d <address> <size> - show memory contents """ return self.last_display_command(arg) def do_db(self, arg): """ [~thread] db <register> - show memory contents as bytes [~thread] db <register-register> - show memory contents as bytes [~thread] db <register> <size> - show memory contents as bytes [~process] db <address> - show memory contents as bytes [~process] db <address-address> - show memory contents as bytes [~process] db <address> <size> - show memory contents as bytes """ self.print_memory_display(arg, HexDump.hexblock) self.last_display_command = self.do_db def do_dw(self, arg): """ [~thread] dw <register> - show memory contents as words [~thread] dw <register-register> - show memory contents as words [~thread] dw <register> <size> - show memory contents as words [~process] dw <address> - show memory contents as words [~process] dw <address-address> - show memory contents as words [~process] dw <address> <size> - show memory contents as words """ self.print_memory_display(arg, HexDump.hexblock_word) self.last_display_command = self.do_dw def do_dd(self, arg): """ [~thread] dd <register> - show memory contents as dwords [~thread] dd <register-register> - show memory contents as dwords [~thread] dd <register> <size> - show memory contents as dwords [~process] dd <address> - show memory contents as dwords [~process] dd <address-address> - show memory contents as dwords [~process] dd <address> <size> - show memory contents as dwords """ self.print_memory_display(arg, HexDump.hexblock_dword) self.last_display_command = self.do_dd def do_dq(self, arg): """ [~thread] dq <register> - show memory contents as qwords [~thread] dq <register-register> - show memory contents as qwords [~thread] dq <register> <size> - show memory contents as qwords [~process] dq <address> - show memory contents as qwords [~process] dq <address-address> - show memory contents as qwords [~process] dq <address> <size> - show memory contents as qwords """ self.print_memory_display(arg, HexDump.hexblock_qword) self.last_display_command = self.do_dq # XXX TODO # Change the way the default is used with ds and du def do_ds(self, arg): """ [~thread] ds <register> - show memory contents as ANSI string [~process] ds <address> - show memory contents as ANSI string """ if not arg: arg = self.default_display_target token_list = self.split_tokens(arg, 1, 1) pid, tid, address, size = self.input_display(token_list, 256) process = self.get_process(pid) data = process.peek_string(address, False, size) if data: print(repr(data)) self.last_display_command = self.do_ds def do_du(self, arg): """ [~thread] du <register> - show memory contents as Unicode string [~process] du <address> - show memory contents as Unicode string """ if not arg: arg = self.default_display_target token_list = self.split_tokens(arg, 1, 2) pid, tid, address, size = self.input_display(token_list, 256) process = self.get_process(pid) data = process.peek_string(address, True, size) if data: print(repr(data)) self.last_display_command = self.do_du def do_register(self, arg): """ [~thread] r - print(the value of all registers [~thread] r <register> - print(the value of a register [~thread] r <register>=<value> - change the value of a register [~thread] register - print(the value of all registers [~thread] register <register> - print(the value of a register [~thread] register <register>=<value> - change the value of a register """ arg = arg.strip() if not arg: self.print_current_location() else: equ = arg.find('=') if equ >= 0: register = arg[:equ].strip() value = arg[equ + 1:].strip() if not value: value = '0' self.change_register(register, value) else: value = self.input_register(arg) if value is None: raise CmdError("unknown register: %s" % arg) try: label = None thread = self.get_thread_from_prefix() process = thread.get_process() module = process.get_module_at_address(value) if module: label = module.get_label_at_address(value) except RuntimeError: label = None reg = arg.upper() val = HexDump.address(value) if label: print("%s: %s (%s)" % (reg, val, label)) else: print("%s: %s" % (reg, val)) do_r = do_register def do_eb(self, arg): """ [~process] eb <address> <data> - write the data to the specified address """ # TODO # data parameter should be optional, use a child Cmd here pid = self.get_process_id_from_prefix() token_list = self.split_tokens(arg, 2) address = self.input_address(token_list[0], pid) data = HexInput.hexadecimal(' '.join(token_list[1:])) self.write_memory(address, data, pid) # XXX TODO # add ew, ed and eq here def do_find(self, arg): """ [~process] f <string> - find the string in the process memory [~process] find <string> - find the string in the process memory """ if not arg: raise CmdError("missing parameter: string") process = self.get_process_from_prefix() self.find_in_memory(arg, process) do_f = do_find def do_memory(self, arg): """ [~process] m - show the process memory map [~process] memory - show the process memory map """ if arg: # TODO: take min and max addresses raise CmdError("too many arguments") process = self.get_process_from_prefix() try: memoryMap = process.get_memory_map() mappedFilenames = process.get_mapped_filenames() print('') print(CrashDump.dump_memory_map(memoryMap, mappedFilenames)) except WindowsError: msg = "can't get memory information for process (%d)" raise CmdError(msg % process.get_pid()) do_m = do_memory #------------------------------------------------------------------------------ # Event handling # TODO # * add configurable stop/don't stop behavior on events and exceptions # Stop for all events, unless stated otherwise. def event(self, event): self.print_event(event) self.prompt_user() # Stop for all exceptions, unless stated otherwise. def exception(self, event): self.print_exception(event) self.prompt_user() # Stop for breakpoint exceptions. def breakpoint(self, event): if hasattr(event, 'breakpoint') and event.breakpoint: self.print_breakpoint_location(event) else: self.print_exception(event) self.prompt_user() # Stop for WOW64 breakpoint exceptions. def wow64_breakpoint(self, event): self.print_exception(event) self.prompt_user() # Stop for single step exceptions. def single_step(self, event): if event.debug.is_tracing(event.get_tid()): self.print_breakpoint_location(event) else: self.print_exception(event) self.prompt_user() # Don't stop for C++ exceptions. def ms_vc_exception(self, event): self.print_exception(event) event.continueStatus = win32.DBG_CONTINUE # Don't stop for process start. def create_process(self, event): self.print_process_start(event) self.print_thread_start(event) self.print_module_load(event) # Don't stop for process exit. def exit_process(self, event): self.print_process_end(event) # Don't stop for thread creation. def create_thread(self, event): self.print_thread_start(event) # Don't stop for thread exit. def exit_thread(self, event): self.print_thread_end(event) # Don't stop for DLL load. def load_dll(self, event): self.print_module_load(event) # Don't stop for DLL unload. def unload_dll(self, event): self.print_module_unload(event) # Don't stop for debug strings. def output_string(self, event): self.print_debug_string(event) #------------------------------------------------------------------------------ # History file def load_history(self): global readline if readline is None: try: import readline except ImportError: return if self.history_file_full_path is None: folder = os.environ.get('USERPROFILE', '') if not folder: folder = os.environ.get('HOME', '') if not folder: folder = os.path.split(sys.argv[0])[1] if not folder: folder = os.path.curdir self.history_file_full_path = os.path.join(folder, self.history_file) try: if os.path.exists(self.history_file_full_path): readline.read_history_file(self.history_file_full_path) except IOError: e = sys.exc_info()[1] warnings.warn("Cannot load history file, reason: %s" % str(e)) def save_history(self): if self.history_file_full_path is not None: global readline if readline is None: try: import readline except ImportError: return try: readline.write_history_file(self.history_file_full_path) except IOError: e = sys.exc_info()[1] warnings.warn("Cannot save history file, reason: %s" % str(e)) #------------------------------------------------------------------------------ # Main loop # Debugging loop. def loop(self): self.debuggerExit = False debug = self.debug # Stop on the initial event, if any. if self.lastEvent is not None: self.cmdqueue.append('r') self.prompt_user() # Loop until the debugger is told to quit. while not self.debuggerExit: try: # If for some reason the last event wasn't continued, # continue it here. This won't be done more than once # for a given Event instance, though. try: debug.cont() # On error, show the command prompt. except Exception: traceback.print_exc() self.prompt_user() # While debugees are attached, handle debug events. # Some debug events may cause the command prompt to be shown. if self.debug.get_debugee_count() > 0: try: # Get the next debug event. debug.wait() # Dispatch the debug event. try: debug.dispatch() # Continue the debug event. finally: debug.cont() # On error, show the command prompt. except Exception: traceback.print_exc() self.prompt_user() # While no debugees are attached, show the command prompt. else: self.prompt_user() # When the user presses Ctrl-C send a debug break to all debugees. except KeyboardInterrupt: success = False try: print("*** User requested debug break") system = debug.system for pid in debug.get_debugee_pids(): try: system.get_process(pid).debug_break() success = True except: traceback.print_exc() except: traceback.print_exc() if not success: raise # This should never happen!
83,555
Python
36.251895
87
0.53968